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
|
---|---|---|---|---|---|---|---|---|---|
922a68de8e960172c5d9433696acb63ed3f97a0a
|
source/syscalls/syscallsStubs.cpp
|
source/syscalls/syscallsStubs.cpp
|
/**
* \file
* \brief Stub system calls for newlib's libc
*
* \author Copyright (C) 2014 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 <sys/stat.h>
#include <sys/times.h>
#include <cerrno>
#include <cstdint>
extern "C"
{
/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Stub _close_r() implementation
*
* \return -1
*/
__attribute__ ((weak))
int _close_r(_reent*, int)
{
errno = EBADF;
return -1;
}
/**
* \brief Stub _execve_r() implementation
*
* \return -1
*/
__attribute__ ((weak))
int _execve_r(_reent*, const char*, char* const [], char* const [])
{
errno = ENOMEM;
return -1;
}
/**
* \brief Stub _exit() implementation
*/
__attribute__ ((weak))
void _exit(int)
{
while (1);
}
/**
* \brief Stub _fork_r() implementation
*
* \return -1
*/
__attribute__ ((weak))
pid_t _fork_r(_reent*)
{
errno = EAGAIN;
return -1;
}
/**
* \brief Stub _fstat_r() implementation
*
* \return -1
*/
__attribute__ ((weak))
int _fstat_r(_reent*, int, struct stat*)
{
errno = EBADF;
return -1;
}
/**
* \brief Stub _getpid_r() implementation
*
* \return 1.
*/
__attribute__ ((weak))
pid_t _getpid_r(_reent*)
{
return 1;
}
/**
* \brief Stub _isatty_r() implementation
*
* \return 0
*/
__attribute__ ((weak))
int _isatty_r(_reent*, int)
{
errno = EBADF;
return 0;
}
/**
* \brief Stub _kill_r() implementation
*
* \return -1
*/
__attribute__ ((weak))
int _kill_r(_reent*, pid_t, int)
{
errno = EINVAL;
return -1;
}
/**
* \brief Stub _link_r() implementation
*
* \return -1
*/
__attribute__ ((weak))
int _link_r(_reent*, const char*, const char*)
{
errno = EMLINK;
return -1;
}
/**
* \brief Stub _lseek_r() implementation
*
* \return -1
*/
__attribute__ ((weak))
off_t _lseek_r(_reent*, int, off_t, int)
{
errno = EBADF;
return -1;
}
/**
* \brief Stub _open_r() implementation
*
* \return -1
*/
__attribute__ ((weak))
int _open_r(_reent*, const char*, int, int)
{
errno = EMFILE;
return -1;
}
/**
* \brief Stub _read_r() implementation
*
* \return -1
*/
__attribute__ ((weak))
ssize_t _read_r(_reent*, int, void*, size_t)
{
errno = EBADF;
return -1;
}
/**
* \brief Stub _sbrk_r() implementation
*
* \return -1
*/
__attribute__ ((weak))
caddr_t _sbrk_r(_reent*, intptr_t)
{
errno = ENOMEM;
return reinterpret_cast<caddr_t>(-1);
}
/**
* \brief Stub _stat_r() implementation
*
* \return -1
*/
__attribute__ ((weak))
int _stat_r(_reent*, const char*, struct stat*)
{
errno = ENOENT;
return -1;
}
/**
* \brief Stub _times_r() implementation
*
* \return -1
*/
__attribute__ ((weak))
clock_t _times_r(_reent*, tms*)
{
return -1;
}
/**
* \brief Stub _unlink_r() implementation
*
* \return -1
*/
__attribute__ ((weak))
int _unlink_r(_reent*, const char*)
{
errno = ENOENT;
return -1;
}
/**
* \brief Stub _wait_r() implementation
*
* \return -1
*/
__attribute__ ((weak))
pid_t _wait_r(_reent*, int*)
{
errno = ECHILD;
return -1;
}
/**
* \brief Stub _write_r() implementation
*
* \return -1
*/
__attribute__ ((weak))
ssize_t _write_r(_reent*, int, const void*, size_t)
{
errno = EBADF;
return -1;
}
} // extern "C"
|
/**
* \file
* \brief Stub system calls for newlib's libc
*
* \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 <sys/stat.h>
#include <sys/times.h>
#include <cerrno>
#include <cstdint>
extern "C"
{
/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Stub _close_r() implementation
*
* \return -1
*/
__attribute__ ((weak))
int _close_r(_reent*, int)
{
errno = EBADF;
return -1;
}
/**
* \brief Stub _execve_r() implementation
*
* \return -1
*/
__attribute__ ((weak))
int _execve_r(_reent*, const char*, char* const [], char* const [])
{
errno = ENOMEM;
return -1;
}
/**
* \brief Stub _exit() implementation
*/
__attribute__ ((weak))
void _exit(int)
{
while (1);
}
/**
* \brief Stub _fork_r() implementation
*
* \return -1
*/
__attribute__ ((weak))
pid_t _fork_r(_reent*)
{
errno = EAGAIN;
return -1;
}
/**
* \brief Stub _fstat_r() implementation
*
* \return -1
*/
__attribute__ ((weak))
int _fstat_r(_reent*, int, struct stat*)
{
errno = EBADF;
return -1;
}
/**
* \brief Stub _getpid_r() implementation
*
* \return 1.
*/
__attribute__ ((weak))
pid_t _getpid_r(_reent*)
{
return 1;
}
/**
* \brief Stub _isatty_r() implementation
*
* \return 0
*/
__attribute__ ((weak))
int _isatty_r(_reent*, int)
{
errno = EBADF;
return 0;
}
/**
* \brief Stub _kill_r() implementation
*
* \return -1
*/
__attribute__ ((weak))
int _kill_r(_reent*, pid_t, int)
{
errno = EINVAL;
return -1;
}
/**
* \brief Stub _link_r() implementation
*
* \return -1
*/
__attribute__ ((weak))
int _link_r(_reent*, const char*, const char*)
{
errno = EMLINK;
return -1;
}
/**
* \brief Stub _lseek_r() implementation
*
* \return -1
*/
__attribute__ ((weak))
off_t _lseek_r(_reent*, int, off_t, int)
{
errno = EBADF;
return -1;
}
/**
* \brief Stub _open_r() implementation
*
* \return -1
*/
__attribute__ ((weak))
int _open_r(_reent*, const char*, int, int)
{
errno = EMFILE;
return -1;
}
/**
* \brief Stub _read_r() implementation
*
* \return -1
*/
__attribute__ ((weak))
ssize_t _read_r(_reent*, int, void*, size_t)
{
errno = EBADF;
return -1;
}
/**
* \brief Stub _sbrk_r() implementation
*
* \return -1
*/
__attribute__ ((weak))
void* _sbrk_r(_reent*, intptr_t)
{
errno = ENOMEM;
return reinterpret_cast<caddr_t>(-1);
}
/**
* \brief Stub _stat_r() implementation
*
* \return -1
*/
__attribute__ ((weak))
int _stat_r(_reent*, const char*, struct stat*)
{
errno = ENOENT;
return -1;
}
/**
* \brief Stub _times_r() implementation
*
* \return -1
*/
__attribute__ ((weak))
clock_t _times_r(_reent*, tms*)
{
return -1;
}
/**
* \brief Stub _unlink_r() implementation
*
* \return -1
*/
__attribute__ ((weak))
int _unlink_r(_reent*, const char*)
{
errno = ENOENT;
return -1;
}
/**
* \brief Stub _wait_r() implementation
*
* \return -1
*/
__attribute__ ((weak))
pid_t _wait_r(_reent*, int*)
{
errno = ECHILD;
return -1;
}
/**
* \brief Stub _write_r() implementation
*
* \return -1
*/
__attribute__ ((weak))
ssize_t _write_r(_reent*, int, const void*, size_t)
{
errno = EBADF;
return -1;
}
} // extern "C"
|
Fix weak stub of _sbrk_r()
|
Fix weak stub of _sbrk_r()
When LTO is enabled a "warning: '_sbrk_r' violates the C++ One
Definition Rule [-Wodr]" is generated, because the weak stub returns
"caddr_t", while the real implementation - "void*". Use "void*" in both
places, which is also consistent with the type used internally by
newlib.
|
C++
|
mpl-2.0
|
DISTORTEC/distortos,CezaryGapinski/distortos,jasmin-j/distortos,jasmin-j/distortos,CezaryGapinski/distortos,CezaryGapinski/distortos,CezaryGapinski/distortos,DISTORTEC/distortos,jasmin-j/distortos,CezaryGapinski/distortos,jasmin-j/distortos,DISTORTEC/distortos,jasmin-j/distortos,DISTORTEC/distortos
|
73dc9b7c2f52165983d3bb645eebc610df0d0afd
|
libraries/types/AbiSerializer.cpp
|
libraries/types/AbiSerializer.cpp
|
#include <eos/types/AbiSerializer.hpp>
#include <fc/io/raw.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/depth_first_search.hpp>
using namespace boost;
namespace eos { namespace types {
using boost::algorithm::ends_with;
using std::vector;
using std::string;
struct cycle_detector : public dfs_visitor<>
{
cycle_detector( bool& has_cycle)
: _has_cycle(has_cycle) { }
template <class Edge, class Graph>
void back_edge(Edge, Graph&) {
_has_cycle = true;
}
protected:
bool& _has_cycle;
};
template <typename T>
inline fc::variant variantFromStream(fc::datastream<const char*>& stream) {
T temp;
fc::raw::unpack( stream, temp );
return fc::variant(temp);
}
template <typename T>
auto packUnpack() {
return std::make_pair<AbiSerializer::unpack_function, AbiSerializer::pack_function>(
[]( fc::datastream<const char*>& stream, bool is_array) -> fc::variant {
if( is_array )
return variantFromStream<vector<T>>(stream);
return variantFromStream<T>(stream);
},
[]( const fc::variant& var, fc::datastream<char*>& ds, bool is_array ){
if( is_array )
fc::raw::pack( ds, var.as<vector<T>>() );
else
fc::raw::pack( ds, var.as<T>());
}
);
}
AbiSerializer::AbiSerializer( const Abi& abi ) {
configureBuiltInTypes();
setAbi(abi);
}
void AbiSerializer::configureBuiltInTypes() {
//PublicKey.hpp
built_in_types.emplace("PublicKey", packUnpack<PublicKey>());
//Asset.hpp
built_in_types.emplace("Asset", packUnpack<Asset>());
built_in_types.emplace("Price", packUnpack<Price>());
//native.hpp
built_in_types.emplace("String", packUnpack<String>());
built_in_types.emplace("Time", packUnpack<Time>());
built_in_types.emplace("Signature", packUnpack<Signature>());
built_in_types.emplace("Checksum", packUnpack<Checksum>());
built_in_types.emplace("FieldName", packUnpack<FieldName>());
built_in_types.emplace("FixedString32", packUnpack<FixedString32>());
built_in_types.emplace("FixedString16", packUnpack<FixedString16>());
built_in_types.emplace("TypeName", packUnpack<TypeName>());
built_in_types.emplace("Bytes", packUnpack<Bytes>());
built_in_types.emplace("UInt8", packUnpack<UInt8>());
built_in_types.emplace("UInt16", packUnpack<UInt16>());
built_in_types.emplace("UInt32", packUnpack<UInt32>());
built_in_types.emplace("UInt64", packUnpack<UInt64>());
built_in_types.emplace("UInt128", packUnpack<UInt128>());
built_in_types.emplace("UInt256", packUnpack<UInt256>());
built_in_types.emplace("Int8", packUnpack<int8_t>());
built_in_types.emplace("Int16", packUnpack<int16_t>());
built_in_types.emplace("Int32", packUnpack<int32_t>());
built_in_types.emplace("Int64", packUnpack<int64_t>());
//built_in_types.emplace("Int128", packUnpack<Int128>());
//built_in_types.emplace("Int256", packUnpack<Int256>());
//built_in_types.emplace("uint128_t", packUnpack<uint128_t>());
built_in_types.emplace("Name", packUnpack<Name>());
built_in_types.emplace("Field", packUnpack<Field>());
built_in_types.emplace("Struct", packUnpack<Struct>());
built_in_types.emplace("Fields", packUnpack<Fields>());
//generated.hpp
built_in_types.emplace("AccountName", packUnpack<AccountName>());
built_in_types.emplace("PermissionName", packUnpack<PermissionName>());
built_in_types.emplace("FuncName", packUnpack<FuncName>());
built_in_types.emplace("MessageName", packUnpack<MessageName>());
//built_in_types.emplace("TypeName", packUnpack<TypeName>());
built_in_types.emplace("AccountPermission", packUnpack<AccountPermission>());
built_in_types.emplace("Message", packUnpack<Message>());
built_in_types.emplace("AccountPermissionWeight", packUnpack<AccountPermissionWeight>());
built_in_types.emplace("Transaction", packUnpack<Transaction>());
built_in_types.emplace("SignedTransaction", packUnpack<SignedTransaction>());
built_in_types.emplace("KeyPermissionWeight", packUnpack<KeyPermissionWeight>());
built_in_types.emplace("Authority", packUnpack<Authority>());
built_in_types.emplace("BlockchainConfiguration", packUnpack<BlockchainConfiguration>());
built_in_types.emplace("TypeDef", packUnpack<TypeDef>());
built_in_types.emplace("Action", packUnpack<Action>());
built_in_types.emplace("Table", packUnpack<Table>());
built_in_types.emplace("Abi", packUnpack<Abi>());
}
bool AbiSerializer::hasCycle( const vector<pair<string,string>>& sedges )const {
auto addVertex = [](vector<string>& vertexs, const string& name) -> int {
auto itr = find(vertexs.begin(), vertexs.end(), name);
if(itr == vertexs.end()) {
vertexs.push_back(name);
return (int)vertexs.size()-1;
}
return (int)distance(vertexs.begin(), itr);
};
typedef adjacency_list <vecS, vecS, directedS> Graph;
typedef pair<int,int> Edge;
vector<string> vertexs;
vector<Edge> edges;
for( const auto& se : sedges ) {
edges.push_back( Edge{
addVertex(vertexs, se.first),
addVertex(vertexs, se.second)
});
}
Graph g(vertexs.size());
for( const auto& edge : edges )
add_edge(edge.first, edge.second, g);
bool has_cycle = false;
cycle_detector vis(has_cycle);
boost::depth_first_search(g, visitor(vis));
return has_cycle;
}
void AbiSerializer::setAbi( const Abi& abi ) {
typedefs.clear();
structs.clear();
actions.clear();
tables.clear();
vector<pair<string,string>> type_edges;
for( const auto& td : abi.types )
{
FC_ASSERT( isType(td.type), "invalid type", ("type",td.type));
typedefs[td.newTypeName] = td.type;
std::cout << "type_edges (" << td.type << "," << td.newTypeName << ")\n";
type_edges.push_back({td.type, td.newTypeName});
}
FC_ASSERT( !hasCycle(type_edges) );
vector<pair<string,string>> struct_edges;
for( const auto& st : abi.structs ) {
structs[st.name] = st;
std::cout << "type_edges (" << st.name << "," << st.base << ")\n";
if(st.base != TypeName())
struct_edges.push_back({st.name, resolveType(st.base)});
}
FC_ASSERT( !hasCycle(struct_edges) );
for( const auto& a : abi.actions )
actions[a.action] = a.type;
for( const auto& t : abi.tables )
tables[t.table] = t.type;
/**
* The ABI vector may contain duplicates which would make it
* an invalid ABI
*/
FC_ASSERT( typedefs.size() == abi.types.size() );
FC_ASSERT( structs.size() == abi.structs.size() );
FC_ASSERT( actions.size() == abi.actions.size() );
FC_ASSERT( tables.size() == abi.tables.size() );
}
bool AbiSerializer::isArray( const TypeName& type )const {
return ends_with(string(type), "[]");
}
TypeName AbiSerializer::arrayType( const TypeName& type )const {
if( !isArray(type) ) return type;
return TypeName(string(type).substr(0, type.size()-2));
}
bool AbiSerializer::isType( const TypeName& rtype )const {
auto type = arrayType(rtype);
if( built_in_types.find(type) != built_in_types.end() ) return true;
if( typedefs.find(type) != typedefs.end() ) return isType( typedefs.find(type)->second );
if( structs.find(type) != structs.end() ) return true;
return false;
}
const Struct& AbiSerializer::getStruct( const TypeName& type )const {
auto itr = structs.find( resolveType(type) );
FC_ASSERT( itr != structs.end(), "Unknown struct ${type}", ("type",type) );
return itr->second;
}
void AbiSerializer::validate()const {
for( const auto& t : typedefs ) { try {
FC_ASSERT( isType( t.second ), "", ("type",t.second) );
} FC_CAPTURE_AND_RETHROW( (t) ) }
for( const auto& s : structs ) { try {
if( s.second.base != TypeName() )
getStruct( s.second.base ); //FC_ASSERT( isType( s.second.base ) );
for( const auto& field : s.second.fields ) { try {
FC_ASSERT( isType( field.type ) );
} FC_CAPTURE_AND_RETHROW( (field) ) }
} FC_CAPTURE_AND_RETHROW( (s) ) }
for( const auto& a : actions ) { try {
FC_ASSERT( isType( a.second ), "", ("type",a.second) );
} FC_CAPTURE_AND_RETHROW( (a) ) }
for( const auto& t : tables ) { try {
FC_ASSERT( isType( t.second ), "", ("type",t.second) );
} FC_CAPTURE_AND_RETHROW( (t) ) }
}
TypeName AbiSerializer::resolveType( const TypeName& type )const {
auto itr = typedefs.find(type);
if( itr != typedefs.end() )
return resolveType(itr->second);
return type;
}
void AbiSerializer::binaryToVariant(const TypeName& type, fc::datastream<const char*>& stream, fc::mutable_variant_object& obj )const {
const auto& st = getStruct( type );
if( st.base != TypeName() ) {
binaryToVariant( resolveType(st.base), stream, obj );
}
for( const auto& field : st.fields ) {
obj( field.name, binaryToVariant( resolveType(field.type), stream ) );
}
}
fc::variant AbiSerializer::binaryToVariant(const TypeName& type, fc::datastream<const char*>& stream )const
{
TypeName rtype = resolveType( type );
auto btype = built_in_types.find( arrayType(rtype) );
if( btype != built_in_types.end() ) {
return btype->second.first(stream, isArray(rtype));
}
fc::mutable_variant_object mvo;
binaryToVariant( rtype, stream, mvo );
return fc::variant( std::move(mvo) );
}
fc::variant AbiSerializer::binaryToVariant(const TypeName& type, const Bytes& binary)const{
fc::datastream<const char*> ds( binary.data(), binary.size() );
return binaryToVariant( type, ds );
}
void AbiSerializer::variantToBinary(const TypeName& type, const fc::variant& var, fc::datastream<char*>& ds )const
{ try {
auto rtype = resolveType(type);
auto btype = built_in_types.find(arrayType(rtype));
if( btype != built_in_types.end() ) {
btype->second.second(var, ds, isArray(rtype));
} else {
const auto& st = getStruct( rtype );
const auto& vo = var.get_object();
if( st.base != TypeName() ) {
variantToBinary( resolveType( st.base ), var, ds );
}
for( const auto& field : st.fields ) {
if( vo.contains( String(field.name).c_str() ) ) {
variantToBinary( field.type, vo[field.name], ds );
}
else {
/// TODO: default construct field and write it out
FC_ASSERT( !"missing field in variant object", "Missing '${f}' in variant object", ("f",field.name) );
}
}
}
} FC_CAPTURE_AND_RETHROW( (type)(var) ) }
Bytes AbiSerializer::variantToBinary(const TypeName& type, const fc::variant& var)const {
if( !isType(type) ) {
return var.as<Bytes>();
}
Bytes temp( 1024*1024 );
fc::datastream<char*> ds(temp.data(), temp.size() );
variantToBinary( type, var, ds );
temp.resize(ds.tellp());
return temp;
}
TypeName AbiSerializer::getActionType( Name action )const {
auto itr = actions.find(action);
if( itr != actions.end() ) return itr->second;
return TypeName();
}
TypeName AbiSerializer::getTableType( Name action )const {
auto itr = tables.find(action);
if( itr != tables.end() ) return itr->second;
return TypeName();
}
} }
|
#include <eos/types/AbiSerializer.hpp>
#include <fc/io/raw.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/depth_first_search.hpp>
using namespace boost;
namespace eos { namespace types {
using boost::algorithm::ends_with;
using std::vector;
using std::string;
struct cycle_detector : public dfs_visitor<>
{
cycle_detector( bool& has_cycle)
: _has_cycle(has_cycle) { }
template <class Edge, class Graph>
void back_edge(Edge, Graph&) {
_has_cycle = true;
}
protected:
bool& _has_cycle;
};
template <typename T>
inline fc::variant variantFromStream(fc::datastream<const char*>& stream) {
T temp;
fc::raw::unpack( stream, temp );
return fc::variant(temp);
}
template <typename T>
auto packUnpack() {
return std::make_pair<AbiSerializer::unpack_function, AbiSerializer::pack_function>(
[]( fc::datastream<const char*>& stream, bool is_array) -> fc::variant {
if( is_array )
return variantFromStream<vector<T>>(stream);
return variantFromStream<T>(stream);
},
[]( const fc::variant& var, fc::datastream<char*>& ds, bool is_array ){
if( is_array )
fc::raw::pack( ds, var.as<vector<T>>() );
else
fc::raw::pack( ds, var.as<T>());
}
);
}
AbiSerializer::AbiSerializer( const Abi& abi ) {
configureBuiltInTypes();
setAbi(abi);
}
void AbiSerializer::configureBuiltInTypes() {
//PublicKey.hpp
built_in_types.emplace("PublicKey", packUnpack<PublicKey>());
//Asset.hpp
built_in_types.emplace("Asset", packUnpack<Asset>());
built_in_types.emplace("Price", packUnpack<Price>());
//native.hpp
built_in_types.emplace("String", packUnpack<String>());
built_in_types.emplace("Time", packUnpack<Time>());
built_in_types.emplace("Signature", packUnpack<Signature>());
built_in_types.emplace("Checksum", packUnpack<Checksum>());
built_in_types.emplace("FieldName", packUnpack<FieldName>());
built_in_types.emplace("FixedString32", packUnpack<FixedString32>());
built_in_types.emplace("FixedString16", packUnpack<FixedString16>());
built_in_types.emplace("TypeName", packUnpack<TypeName>());
built_in_types.emplace("Bytes", packUnpack<Bytes>());
built_in_types.emplace("UInt8", packUnpack<UInt8>());
built_in_types.emplace("UInt16", packUnpack<UInt16>());
built_in_types.emplace("UInt32", packUnpack<UInt32>());
built_in_types.emplace("UInt64", packUnpack<UInt64>());
built_in_types.emplace("UInt128", packUnpack<UInt128>());
built_in_types.emplace("UInt256", packUnpack<UInt256>());
built_in_types.emplace("Int8", packUnpack<int8_t>());
built_in_types.emplace("Int16", packUnpack<int16_t>());
built_in_types.emplace("Int32", packUnpack<int32_t>());
built_in_types.emplace("Int64", packUnpack<int64_t>());
//built_in_types.emplace("Int128", packUnpack<Int128>());
//built_in_types.emplace("Int256", packUnpack<Int256>());
//built_in_types.emplace("uint128_t", packUnpack<uint128_t>());
built_in_types.emplace("Name", packUnpack<Name>());
built_in_types.emplace("Field", packUnpack<Field>());
built_in_types.emplace("Struct", packUnpack<Struct>());
built_in_types.emplace("Fields", packUnpack<Fields>());
//generated.hpp
built_in_types.emplace("AccountName", packUnpack<AccountName>());
built_in_types.emplace("PermissionName", packUnpack<PermissionName>());
built_in_types.emplace("FuncName", packUnpack<FuncName>());
built_in_types.emplace("MessageName", packUnpack<MessageName>());
//built_in_types.emplace("TypeName", packUnpack<TypeName>());
built_in_types.emplace("AccountPermission", packUnpack<AccountPermission>());
built_in_types.emplace("Message", packUnpack<Message>());
built_in_types.emplace("AccountPermissionWeight", packUnpack<AccountPermissionWeight>());
built_in_types.emplace("Transaction", packUnpack<Transaction>());
built_in_types.emplace("SignedTransaction", packUnpack<SignedTransaction>());
built_in_types.emplace("KeyPermissionWeight", packUnpack<KeyPermissionWeight>());
built_in_types.emplace("Authority", packUnpack<Authority>());
built_in_types.emplace("BlockchainConfiguration", packUnpack<BlockchainConfiguration>());
built_in_types.emplace("TypeDef", packUnpack<TypeDef>());
built_in_types.emplace("Action", packUnpack<Action>());
built_in_types.emplace("Table", packUnpack<Table>());
built_in_types.emplace("Abi", packUnpack<Abi>());
}
bool AbiSerializer::hasCycle( const vector<pair<string,string>>& sedges )const {
auto addVertex = [](vector<string>& vertexs, const string& name) -> int {
auto itr = find(vertexs.begin(), vertexs.end(), name);
if(itr == vertexs.end()) {
vertexs.push_back(name);
return (int)vertexs.size()-1;
}
return (int)distance(vertexs.begin(), itr);
};
typedef adjacency_list <vecS, vecS, directedS> Graph;
typedef pair<int,int> Edge;
vector<string> vertexs;
vector<Edge> edges;
for( const auto& se : sedges ) {
edges.push_back( Edge{
addVertex(vertexs, se.first),
addVertex(vertexs, se.second)
});
}
Graph g(vertexs.size());
for( const auto& edge : edges )
add_edge(edge.first, edge.second, g);
bool has_cycle = false;
cycle_detector vis(has_cycle);
boost::depth_first_search(g, visitor(vis));
return has_cycle;
}
void AbiSerializer::setAbi( const Abi& abi ) {
typedefs.clear();
structs.clear();
actions.clear();
tables.clear();
vector<pair<string,string>> type_edges;
for( const auto& td : abi.types )
{
FC_ASSERT( isType(td.type), "invalid type", ("type",td.type));
typedefs[td.newTypeName] = td.type;
type_edges.push_back({td.type, td.newTypeName});
}
FC_ASSERT( !hasCycle(type_edges) );
vector<pair<string,string>> struct_edges;
for( const auto& st : abi.structs ) {
structs[st.name] = st;
if(st.base != TypeName())
struct_edges.push_back({st.name, resolveType(st.base)});
}
FC_ASSERT( !hasCycle(struct_edges) );
for( const auto& a : abi.actions )
actions[a.action] = a.type;
for( const auto& t : abi.tables )
tables[t.table] = t.type;
/**
* The ABI vector may contain duplicates which would make it
* an invalid ABI
*/
FC_ASSERT( typedefs.size() == abi.types.size() );
FC_ASSERT( structs.size() == abi.structs.size() );
FC_ASSERT( actions.size() == abi.actions.size() );
FC_ASSERT( tables.size() == abi.tables.size() );
}
bool AbiSerializer::isArray( const TypeName& type )const {
return ends_with(string(type), "[]");
}
TypeName AbiSerializer::arrayType( const TypeName& type )const {
if( !isArray(type) ) return type;
return TypeName(string(type).substr(0, type.size()-2));
}
bool AbiSerializer::isType( const TypeName& rtype )const {
auto type = arrayType(rtype);
if( built_in_types.find(type) != built_in_types.end() ) return true;
if( typedefs.find(type) != typedefs.end() ) return isType( typedefs.find(type)->second );
if( structs.find(type) != structs.end() ) return true;
return false;
}
const Struct& AbiSerializer::getStruct( const TypeName& type )const {
auto itr = structs.find( resolveType(type) );
FC_ASSERT( itr != structs.end(), "Unknown struct ${type}", ("type",type) );
return itr->second;
}
void AbiSerializer::validate()const {
for( const auto& t : typedefs ) { try {
FC_ASSERT( isType( t.second ), "", ("type",t.second) );
} FC_CAPTURE_AND_RETHROW( (t) ) }
for( const auto& s : structs ) { try {
if( s.second.base != TypeName() )
getStruct( s.second.base ); //FC_ASSERT( isType( s.second.base ) );
for( const auto& field : s.second.fields ) { try {
FC_ASSERT( isType( field.type ) );
} FC_CAPTURE_AND_RETHROW( (field) ) }
} FC_CAPTURE_AND_RETHROW( (s) ) }
for( const auto& a : actions ) { try {
FC_ASSERT( isType( a.second ), "", ("type",a.second) );
} FC_CAPTURE_AND_RETHROW( (a) ) }
for( const auto& t : tables ) { try {
FC_ASSERT( isType( t.second ), "", ("type",t.second) );
} FC_CAPTURE_AND_RETHROW( (t) ) }
}
TypeName AbiSerializer::resolveType( const TypeName& type )const {
auto itr = typedefs.find(type);
if( itr != typedefs.end() )
return resolveType(itr->second);
return type;
}
void AbiSerializer::binaryToVariant(const TypeName& type, fc::datastream<const char*>& stream, fc::mutable_variant_object& obj )const {
const auto& st = getStruct( type );
if( st.base != TypeName() ) {
binaryToVariant( resolveType(st.base), stream, obj );
}
for( const auto& field : st.fields ) {
obj( field.name, binaryToVariant( resolveType(field.type), stream ) );
}
}
fc::variant AbiSerializer::binaryToVariant(const TypeName& type, fc::datastream<const char*>& stream )const
{
TypeName rtype = resolveType( type );
auto btype = built_in_types.find( arrayType(rtype) );
if( btype != built_in_types.end() ) {
return btype->second.first(stream, isArray(rtype));
}
fc::mutable_variant_object mvo;
binaryToVariant( rtype, stream, mvo );
return fc::variant( std::move(mvo) );
}
fc::variant AbiSerializer::binaryToVariant(const TypeName& type, const Bytes& binary)const{
fc::datastream<const char*> ds( binary.data(), binary.size() );
return binaryToVariant( type, ds );
}
void AbiSerializer::variantToBinary(const TypeName& type, const fc::variant& var, fc::datastream<char*>& ds )const
{ try {
auto rtype = resolveType(type);
auto btype = built_in_types.find(arrayType(rtype));
if( btype != built_in_types.end() ) {
btype->second.second(var, ds, isArray(rtype));
} else {
const auto& st = getStruct( rtype );
const auto& vo = var.get_object();
if( st.base != TypeName() ) {
variantToBinary( resolveType( st.base ), var, ds );
}
for( const auto& field : st.fields ) {
if( vo.contains( String(field.name).c_str() ) ) {
variantToBinary( field.type, vo[field.name], ds );
}
else {
/// TODO: default construct field and write it out
FC_ASSERT( !"missing field in variant object", "Missing '${f}' in variant object", ("f",field.name) );
}
}
}
} FC_CAPTURE_AND_RETHROW( (type)(var) ) }
Bytes AbiSerializer::variantToBinary(const TypeName& type, const fc::variant& var)const {
if( !isType(type) ) {
return var.as<Bytes>();
}
Bytes temp( 1024*1024 );
fc::datastream<char*> ds(temp.data(), temp.size() );
variantToBinary( type, var, ds );
temp.resize(ds.tellp());
return temp;
}
TypeName AbiSerializer::getActionType( Name action )const {
auto itr = actions.find(action);
if( itr != actions.end() ) return itr->second;
return TypeName();
}
TypeName AbiSerializer::getTableType( Name action )const {
auto itr = tables.find(action);
if( itr != tables.end() ) return itr->second;
return TypeName();
}
} }
|
remove log
|
remove log
|
C++
|
mit
|
EOSIO/eos,EOSIO/eos,EOSIO/eos,EOSIO/eos,EOSIO/eos
|
0eb36a2509b048d26a1dfc28bd93edeb39b6281b
|
src/environment.hh
|
src/environment.hh
|
/*
Freebox QtCreator plugin for QML application development.
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 see
http://www.gnu.org/licenses/lgpl-2.1.html.
Copyright (c) 2014, Freebox SAS, See AUTHORS for details.
*/
#ifndef ENVIRONMENT_HH_
# define ENVIRONMENT_HH_
#include <projectexplorer/environmentaspect.h>
namespace Freebox {
class EnvironmentAspect : public ProjectExplorer::EnvironmentAspect
{
Q_OBJECT
public:
EnvironmentAspect(ProjectExplorer::RunConfiguration *rc);
EnvironmentAspect *create(ProjectExplorer::RunConfiguration *parent) const;
QList<int> possibleBaseEnvironments() const;
QString baseEnvironmentDisplayName(int base) const override;
Utils::Environment baseEnvironment() const override;
private:
enum BaseEnvironmentBase {
SystemEnvironmentBase = 0
};
};
} // namespace Freebox
#endif // !ENVIRONMENT_HH_
|
/*
Freebox QtCreator plugin for QML application development.
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 see
http://www.gnu.org/licenses/lgpl-2.1.html.
Copyright (c) 2014, Freebox SAS, See AUTHORS for details.
*/
#ifndef ENVIRONMENT_HH_
# define ENVIRONMENT_HH_
#include <projectexplorer/environmentaspect.h>
namespace Freebox {
class EnvironmentAspect : public ProjectExplorer::EnvironmentAspect
{
Q_OBJECT
public:
EnvironmentAspect(ProjectExplorer::RunConfiguration *rc);
EnvironmentAspect *create(ProjectExplorer::RunConfiguration *parent) const override;
QList<int> possibleBaseEnvironments() const override;
QString baseEnvironmentDisplayName(int base) const override;
Utils::Environment baseEnvironment() const override;
private:
enum BaseEnvironmentBase {
SystemEnvironmentBase = 0
};
};
} // namespace Freebox
#endif // !ENVIRONMENT_HH_
|
add missing overrides
|
add missing overrides
|
C++
|
lgpl-2.1
|
fbx/freebox-qtcreator-plugin,fbx/freebox-qtcreator-plugin
|
d965ad66dbf391aae420fb96c7570a9d9cb9bf98
|
libs/obs/src/carmen_log_tools.cpp
|
libs/obs/src/carmen_log_tools.cpp
|
/* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| https://www.mrpt.org/ |
| |
| Copyright (c) 2005-2021, Individual contributors, see AUTHORS file |
| See: https://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See: https://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include "obs-precomp.h" // Precompiled headers
//
#include <mrpt/containers/yaml.h>
#include <mrpt/math/TPose2D.h>
#include <mrpt/obs/CObservation2DRangeScan.h>
#include <mrpt/obs/CObservationOdometry.h>
#include <mrpt/obs/carmen_log_tools.h>
#include <mrpt/system/string_utils.h>
using namespace mrpt;
using namespace mrpt::obs;
using namespace mrpt::poses;
using namespace mrpt::system;
using namespace std;
// Read the declaration in the .h file for documentation.
bool mrpt::obs::carmen_log_parse_line(
std::istream& in_stream,
std::vector<mrpt::obs::CObservation::Ptr>& out_observations,
const mrpt::system::TTimeStamp& time_start_log)
{
/** global parameters loaded in previous calls. */
static mrpt::containers::yaml global_log_params;
out_observations.clear(); // empty output container
// Try to get line:
string line;
while (line.empty())
{
if (!in_stream) return false; // End of file
std::getline(in_stream, line);
line = trim(line);
};
// Now we have a line: analyze it:
if (strStartsI(line, "ROBOTLASER"))
{
// ROBOTLASER message
// ---------------------------
std::istringstream S; // Read from the string as if it was a stream
S.str(line);
CObservation2DRangeScan::Ptr obsLaser_ptr =
std::make_shared<CObservation2DRangeScan>();
CObservation2DRangeScan* obsLaser =
obsLaser_ptr.get(); // Faster access
// Parse:
int laser_type; // SICK_LMS = 0, SICK_PLS = 1, HOKUYO_URG = 2,
// SIMULATED_LASER = 3,
double start_angle, angular_resolution, accuracy;
int remission_mode; // OFF = 0, DIRECT = 1, NORMALIZED = 2
if (!(S >> obsLaser->sensorLabel >> laser_type >> start_angle >>
obsLaser->aperture >> angular_resolution >> obsLaser->maxRange >>
accuracy >> remission_mode))
THROW_EXCEPTION_FMT(
"Error parsing line from CARMEN log (params):\n'%s'\n",
line.c_str());
size_t nRanges;
S >> nRanges;
obsLaser->resizeScan(nRanges);
for (size_t i = 0; i < nRanges; i++)
{
float range;
if (!(S >> range))
THROW_EXCEPTION_FMT(
"Error parsing line from CARMEN log (ranges):\n'%s'\n",
line.c_str());
obsLaser->setScanRange(i, range);
// Valid value?
obsLaser->setScanRangeValidity(
i, (range >= obsLaser->maxRange || range <= 0));
}
size_t remmision_count;
if (!(S >> remmision_count))
THROW_EXCEPTION_FMT(
"Error parsing line from CARMEN log (remmision_count):\n'%s'\n",
line.c_str());
vector<double> remission;
remission.resize(remmision_count);
for (size_t i = 0; i < remmision_count; i++)
{
if (!(S >> remission[i]))
THROW_EXCEPTION_FMT(
"Error parsing line from CARMEN log (remmision "
"vals):\n'%s'\n",
line.c_str());
}
mrpt::math::TPose2D globalLaserPose;
mrpt::math::TPose2D globalRobotPose;
if (!(S >> globalLaserPose.x >> globalLaserPose.y >>
globalLaserPose.phi >> globalRobotPose.x >> globalRobotPose.y >>
globalRobotPose.phi))
THROW_EXCEPTION_FMT(
"Error parsing line from CARMEN log (poses):\n'%s'\n",
line.c_str());
// Compute pose of laser on the robot:
obsLaser->sensorPose =
CPose3D(CPose2D(globalLaserPose) - CPose2D(globalRobotPose));
double tv, rv, fw_dist, side_dist, turn_axis;
S >> tv >> rv >> fw_dist >> side_dist >> turn_axis;
double timestamp;
string robotName;
S >> timestamp >> robotName;
const mrpt::system::TTimeStamp obs_time = time_start_log +
std::chrono::microseconds(static_cast<uint64_t>(1e-6 * timestamp));
obsLaser->timestamp = obs_time;
// Create odometry observation:
{
CObservationOdometry::Ptr obsOdo_ptr =
std::make_shared<CObservationOdometry>();
obsOdo_ptr->timestamp = obs_time;
obsOdo_ptr->odometry = CPose2D(globalRobotPose);
obsOdo_ptr->sensorLabel = "ODOMETRY";
out_observations.push_back(obsOdo_ptr);
}
// Send out laser observation:
out_observations.push_back(obsLaser_ptr);
} // end ROBOTLASER
else if (strStartsI(line, "FLASER") || strStartsI(line, "RLASER"))
{
// [F,R]LASER message
// FLASER num_readings [range_readings] x y theta odom_x odom_y
// odom_theta
// ---------------------------
std::istringstream S; // Read from the string as if it was a stream
S.str(line);
CObservation2DRangeScan::Ptr obsLaser_ptr =
std::make_shared<CObservation2DRangeScan>();
CObservation2DRangeScan* obsLaser =
obsLaser_ptr.get(); // Faster access
// Parse:
size_t nRanges;
if (!(S >> obsLaser->sensorLabel >> nRanges))
THROW_EXCEPTION_FMT(
"Error parsing line from CARMEN log (params):\n'%s'\n",
line.c_str());
// Params:
{
double maxRange = 81.0;
double resolutionDeg = 0.5;
using namespace std::string_literals;
if (line[0] == 'F')
{ // front:
maxRange = global_log_params.getOrDefault<double>(
"robot_front_laser_max", 81.0);
resolutionDeg = global_log_params.getOrDefault<double>(
"laser_front_laser_resolution", 0.5);
}
else if (line[0] == 'R')
{ // rear:
maxRange = global_log_params.getOrDefault<double>(
"robot_rear_laser_max", 81.0);
resolutionDeg = global_log_params.getOrDefault<double>(
"laser_rear_laser_resolution", 0.5);
}
obsLaser->maxRange = d2f(maxRange);
obsLaser->aperture = d2f(DEG2RAD(resolutionDeg) * nRanges);
}
obsLaser->resizeScan(nRanges);
for (size_t i = 0; i < nRanges; i++)
{
float range;
if (!(S >> range))
THROW_EXCEPTION_FMT(
"Error parsing line from CARMEN log (ranges):\n'%s'\n",
line.c_str());
obsLaser->setScanRange(i, range);
// Valid value?
obsLaser->setScanRangeValidity(
i, !(range >= obsLaser->maxRange || range <= 0));
}
mrpt::math::TPose2D globalLaserPose;
mrpt::math::TPose2D globalRobotPose;
if (!(S >> globalLaserPose.x >> globalLaserPose.y >>
globalLaserPose.phi >> globalRobotPose.x >> globalRobotPose.y >>
globalRobotPose.phi))
THROW_EXCEPTION_FMT(
"Error parsing line from CARMEN log (poses):\n'%s'\n",
line.c_str());
// Compute pose of laser on the robot:
obsLaser->sensorPose =
CPose3D(CPose2D(globalLaserPose) - CPose2D(globalRobotPose));
double timestamp;
string robotName;
S >> timestamp >> robotName;
const mrpt::system::TTimeStamp obs_time = time_start_log +
std::chrono::microseconds(static_cast<uint64_t>(1e-6 * timestamp));
obsLaser->timestamp = obs_time;
// Create odometry observation:
{
CObservationOdometry::Ptr obsOdo_ptr =
std::make_shared<CObservationOdometry>();
obsOdo_ptr->timestamp = obs_time;
obsOdo_ptr->odometry = CPose2D(globalRobotPose);
obsOdo_ptr->sensorLabel = "ODOMETRY";
out_observations.push_back(obsOdo_ptr);
}
// Send out laser observation:
out_observations.push_back(obsLaser_ptr);
} // end RAWLASER
else if (strStartsI(line, "PARAM "))
{
// PARAM message
// ---------------------------
std::istringstream S; // Read from the string as if it was a stream
S.str(line);
string key, val;
S >> key; // This is "PARAM"
if (!(S >> key >> val))
THROW_EXCEPTION_FMT(
"Error parsing line from CARMEN log (PARAM):\n'%s'\n",
line.c_str());
if (!key.empty() && !val.empty())
global_log_params[lowerCase(key)] = val;
} // end RAWLASER
return true; // OK
}
|
/* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| https://www.mrpt.org/ |
| |
| Copyright (c) 2005-2021, Individual contributors, see AUTHORS file |
| See: https://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See: https://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include "obs-precomp.h" // Precompiled headers
//
#include <mrpt/containers/yaml.h>
#include <mrpt/math/TPose2D.h>
#include <mrpt/obs/CObservation2DRangeScan.h>
#include <mrpt/obs/CObservationOdometry.h>
#include <mrpt/obs/carmen_log_tools.h>
#include <mrpt/system/string_utils.h>
using namespace mrpt;
using namespace mrpt::obs;
using namespace mrpt::poses;
using namespace mrpt::system;
using namespace std;
// Read the declaration in the .h file for documentation.
bool mrpt::obs::carmen_log_parse_line(
std::istream& in_stream,
std::vector<mrpt::obs::CObservation::Ptr>& out_observations,
const mrpt::system::TTimeStamp& time_start_log)
{
/** global parameters loaded in previous calls. */
static mrpt::containers::yaml global_log_params;
out_observations.clear(); // empty output container
// Try to get line:
string line;
while (line.empty())
{
if (!in_stream) return false; // End of file
std::getline(in_stream, line);
line = trim(line);
};
// Now we have a line: analyze it:
if (strStartsI(line, "ROBOTLASER"))
{
// ROBOTLASER message
// ---------------------------
std::istringstream S; // Read from the string as if it was a stream
S.str(line);
CObservation2DRangeScan::Ptr obsLaser_ptr =
std::make_shared<CObservation2DRangeScan>();
CObservation2DRangeScan* obsLaser =
obsLaser_ptr.get(); // Faster access
// Parse:
int laser_type; // SICK_LMS = 0, SICK_PLS = 1, HOKUYO_URG = 2,
// SIMULATED_LASER = 3,
double start_angle, angular_resolution, accuracy;
int remission_mode; // OFF = 0, DIRECT = 1, NORMALIZED = 2
if (!(S >> obsLaser->sensorLabel >> laser_type >> start_angle >>
obsLaser->aperture >> angular_resolution >> obsLaser->maxRange >>
accuracy >> remission_mode))
THROW_EXCEPTION_FMT(
"Error parsing line from CARMEN log (params):\n'%s'\n",
line.c_str());
size_t nRanges;
S >> nRanges;
obsLaser->resizeScan(nRanges);
for (size_t i = 0; i < nRanges; i++)
{
float range;
if (!(S >> range))
THROW_EXCEPTION_FMT(
"Error parsing line from CARMEN log (ranges):\n'%s'\n",
line.c_str());
obsLaser->setScanRange(i, range);
// Valid value?
obsLaser->setScanRangeValidity(
i, !(range >= obsLaser->maxRange || range <= 0));
}
size_t remmision_count;
if (!(S >> remmision_count))
THROW_EXCEPTION_FMT(
"Error parsing line from CARMEN log (remmision_count):\n'%s'\n",
line.c_str());
vector<double> remission;
remission.resize(remmision_count);
for (size_t i = 0; i < remmision_count; i++)
{
if (!(S >> remission[i]))
THROW_EXCEPTION_FMT(
"Error parsing line from CARMEN log (remmision "
"vals):\n'%s'\n",
line.c_str());
}
mrpt::math::TPose2D globalLaserPose;
mrpt::math::TPose2D globalRobotPose;
if (!(S >> globalLaserPose.x >> globalLaserPose.y >>
globalLaserPose.phi >> globalRobotPose.x >> globalRobotPose.y >>
globalRobotPose.phi))
THROW_EXCEPTION_FMT(
"Error parsing line from CARMEN log (poses):\n'%s'\n",
line.c_str());
// Compute pose of laser on the robot:
obsLaser->sensorPose =
CPose3D(CPose2D(globalLaserPose) - CPose2D(globalRobotPose));
double tv, rv, fw_dist, side_dist, turn_axis;
S >> tv >> rv >> fw_dist >> side_dist >> turn_axis;
double timestamp;
string robotName;
S >> timestamp >> robotName;
const mrpt::system::TTimeStamp obs_time = time_start_log +
std::chrono::microseconds(static_cast<uint64_t>(1e-6 * timestamp));
obsLaser->timestamp = obs_time;
// Create odometry observation:
{
CObservationOdometry::Ptr obsOdo_ptr =
std::make_shared<CObservationOdometry>();
obsOdo_ptr->timestamp = obs_time;
obsOdo_ptr->odometry = CPose2D(globalRobotPose);
obsOdo_ptr->sensorLabel = "ODOMETRY";
out_observations.push_back(obsOdo_ptr);
}
// Send out laser observation:
out_observations.push_back(obsLaser_ptr);
} // end ROBOTLASER
else if (strStartsI(line, "FLASER") || strStartsI(line, "RLASER"))
{
// [F,R]LASER message
// FLASER num_readings [range_readings] x y theta odom_x odom_y
// odom_theta
// ---------------------------
std::istringstream S; // Read from the string as if it was a stream
S.str(line);
CObservation2DRangeScan::Ptr obsLaser_ptr =
std::make_shared<CObservation2DRangeScan>();
CObservation2DRangeScan* obsLaser =
obsLaser_ptr.get(); // Faster access
// Parse:
size_t nRanges;
if (!(S >> obsLaser->sensorLabel >> nRanges))
THROW_EXCEPTION_FMT(
"Error parsing line from CARMEN log (params):\n'%s'\n",
line.c_str());
// Params:
{
double maxRange = 81.0;
double resolutionDeg = 0.5;
using namespace std::string_literals;
if (line[0] == 'F')
{ // front:
maxRange = global_log_params.getOrDefault<double>(
"robot_front_laser_max", 81.0);
resolutionDeg = global_log_params.getOrDefault<double>(
"laser_front_laser_resolution", 0.5);
}
else if (line[0] == 'R')
{ // rear:
maxRange = global_log_params.getOrDefault<double>(
"robot_rear_laser_max", 81.0);
resolutionDeg = global_log_params.getOrDefault<double>(
"laser_rear_laser_resolution", 0.5);
}
obsLaser->maxRange = d2f(maxRange);
obsLaser->aperture = d2f(DEG2RAD(resolutionDeg) * nRanges);
}
obsLaser->resizeScan(nRanges);
for (size_t i = 0; i < nRanges; i++)
{
float range;
if (!(S >> range))
THROW_EXCEPTION_FMT(
"Error parsing line from CARMEN log (ranges):\n'%s'\n",
line.c_str());
obsLaser->setScanRange(i, range);
// Valid value?
obsLaser->setScanRangeValidity(
i, !(range >= obsLaser->maxRange || range <= 0));
}
mrpt::math::TPose2D globalLaserPose;
mrpt::math::TPose2D globalRobotPose;
if (!(S >> globalLaserPose.x >> globalLaserPose.y >>
globalLaserPose.phi >> globalRobotPose.x >> globalRobotPose.y >>
globalRobotPose.phi))
THROW_EXCEPTION_FMT(
"Error parsing line from CARMEN log (poses):\n'%s'\n",
line.c_str());
// Compute pose of laser on the robot:
obsLaser->sensorPose =
CPose3D(CPose2D(globalLaserPose) - CPose2D(globalRobotPose));
double timestamp;
string robotName;
S >> timestamp >> robotName;
const mrpt::system::TTimeStamp obs_time = time_start_log +
std::chrono::microseconds(static_cast<uint64_t>(1e-6 * timestamp));
obsLaser->timestamp = obs_time;
// Create odometry observation:
{
CObservationOdometry::Ptr obsOdo_ptr =
std::make_shared<CObservationOdometry>();
obsOdo_ptr->timestamp = obs_time;
obsOdo_ptr->odometry = CPose2D(globalRobotPose);
obsOdo_ptr->sensorLabel = "ODOMETRY";
out_observations.push_back(obsOdo_ptr);
}
// Send out laser observation:
out_observations.push_back(obsLaser_ptr);
} // end RAWLASER
else if (strStartsI(line, "PARAM "))
{
// PARAM message
// ---------------------------
std::istringstream S; // Read from the string as if it was a stream
S.str(line);
string key, val;
S >> key; // This is "PARAM"
if (!(S >> key >> val))
THROW_EXCEPTION_FMT(
"Error parsing line from CARMEN log (PARAM):\n'%s'\n",
line.c_str());
if (!key.empty() && !val.empty())
global_log_params[lowerCase(key)] = val;
} // end RAWLASER
return true; // OK
}
|
fix one more bug parsing carmen logs
|
fix one more bug parsing carmen logs
|
C++
|
bsd-3-clause
|
MRPT/mrpt,MRPT/mrpt,MRPT/mrpt,MRPT/mrpt,MRPT/mrpt
|
a6eab69aeeeab775d57b6813c177dda9a0e437ed
|
tests/unit/geom/Geometry/touchesTest.cpp
|
tests/unit/geom/Geometry/touchesTest.cpp
|
//
// Test Suite for Geometry's touches() functions
// tut
#include <tut.hpp>
// geos
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/Geometry.h>
#include <geos/io/WKTReader.h>
#include <geos/io/WKBReader.h>
// std
#include <sstream>
#include <memory>
namespace tut {
//
// Test Group
//
struct test_touches_data
{
typedef std::auto_ptr<geos::geom::Geometry> GeomAutoPtr;
typedef geos::geom::GeometryFactory GeometryFactory;
geos::geom::GeometryFactory::unique_ptr factory;
geos::io::WKTReader reader;
geos::io::WKBReader breader;
test_touches_data()
: factory(GeometryFactory::create())
, reader(factory.get())
, breader(*factory.get())
{}
};
typedef test_group<test_touches_data> group;
typedef group::object object;
group test_touches_data("geos::geom::Geometry::touches");
//
// Test Cases
//
// 1 - Point/Point do not touch
template<>
template<>
void object::test<1>()
{
GeomAutoPtr g1(reader.read(
"POINT (0 0)"
));
GeomAutoPtr g2(reader.read(
"POINT (0 0)"
));
ensure(!g1->touches(g2.get()));
ensure(!g2->touches(g1.get()));
}
// 2 - Line/Point do not touch if point is not on boundary
template<>
template<>
void object::test<2>()
{
GeomAutoPtr g1(reader.read(
"LINESTRING(0 0, 1 1, 0 2)"
));
GeomAutoPtr g2(reader.read(
"POINT (1 1)"
));
ensure(!g1->touches(g2.get()));
ensure(!g2->touches(g1.get()));
}
// 3 - Line/Point touch
template<>
template<>
void object::test<3>()
{
GeomAutoPtr g1(reader.read(
"LINESTRING(0 0, 1 1, 0 2)"
));
GeomAutoPtr g2(reader.read(
"POINT (0 2)"
));
ensure(g1->touches(g2.get()));
ensure(g2->touches(g1.get()));
}
// 4 - Line/Point touch (FP coordinates)
template<>
template<>
void object::test<4>()
{
GeomAutoPtr g1(reader.read(
"LINESTRING (-612844.96290006 279079.117329031,-257704.820935236 574364.179187424)"
));
GeomAutoPtr g2(reader.read(
"POINT (-257704.820935236 574364.179187424)"
));
ensure(g1->touches(g2.get()));
ensure(g2->touches(g1.get()));
}
template<>
template<>
void object::test<5>()
{
// Two T-like segments, A (horizontal), B (vertical)
// A: LINESTRING(-3511.75501903694 4257.47493284327,-877.546556856658 4257.47493284327)
// B: LINESTRING(-2119.81532027122 4257.47493284327,-2119.81532027122 2326.7198668134)
std::stringstream wkbA("01020000000200000010efda91826fabc0a8e5329579a1b040008633595f6c8bc0a8e5329579a1b040");
std::stringstream wkbB("0102000000020000005999a871a18fa0c0a8e5329579a1b0405999a871a18fa0c0180a6292702da240");
GeomAutoPtr a(breader.readHEX(wkbA));
GeomAutoPtr b(breader.readHEX(wkbB));
ensure(a->touches(b.get()));
ensure(!a->disjoint(b.get()));
ensure(a->intersects(b.get()));
}
template<>
template<>
void object::test<6>()
{
// Two Y-like segments, A (V-part), B (|-part)
// A: LINESTRING(-428.533750803201 4467.01424233489,1098.10978977856 4137.73818456235,1621.95806350759 5544.64497686319)
// B: LINESTRING(1098.10978977856 4137.73818456235,1921.2999342099 2177.04893146225)
std::stringstream wkbA("010200000003000000603f483e8ac87ac092ba62a50373b1405851bb6c70289140b6d9a9f9bc29b04060a2990ed55799401226341da5a8b540");
std::stringstream wkbB("0102000000020000005851bb6c70289140b6d9a9f9bc29b040d019f42133059e40406c8b0d1902a140");
GeomAutoPtr a(breader.readHEX(wkbA));
GeomAutoPtr b(breader.readHEX(wkbB));
ensure(a->touches(b.get()));
ensure(!a->disjoint(b.get()));
ensure(a->intersects(b.get()));
}
template<>
template<>
void object::test<7>()
{
// Two T-like two segments rotated ~55 degrees counter-clockwise; A (horizontal), B (vertical)
// A: LINESTRING(3343.17382004585 2521.2920827699,4959.61992183829 5125.56635787996)
// B: LINESTRING(4151.39687094207 3823.42922032493,6112.08612404217 2461.42370862944)
std::stringstream wkbA("01020000000200000098e8f0fe581eaa40ea70df8b95b2a3408c9532b39e5fb340417cd4fc9005b440");
std::stringstream wkbB("010200000002000000ec8455996537b040b834c4c2dbdead4086a8390c16e0b740f86456f0d83aa340");
GeomAutoPtr a(breader.readHEX(wkbA));
GeomAutoPtr b(breader.readHEX(wkbB));
// almost-touching (float-point robustness issue likely)
ensure(!a->touches(b.get()));
ensure(!a->disjoint(b.get()));
ensure(a->intersects(b.get()));
}
} // namespace tut
|
//
// Test Suite for Geometry's touches() functions
// tut
#include <tut.hpp>
// geos
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/Geometry.h>
#include <geos/io/WKTReader.h>
#include <geos/io/WKBReader.h>
// std
#include <sstream>
#include <memory>
namespace tut {
//
// Test Group
//
struct test_touches_data
{
typedef std::auto_ptr<geos::geom::Geometry> GeomAutoPtr;
typedef geos::geom::GeometryFactory GeometryFactory;
geos::geom::GeometryFactory::unique_ptr factory;
geos::io::WKTReader reader;
geos::io::WKBReader breader;
test_touches_data()
: factory(GeometryFactory::create())
, reader(factory.get())
, breader(*factory.get())
{}
};
typedef test_group<test_touches_data> group;
typedef group::object object;
group test_touches_data("geos::geom::Geometry::touches");
//
// Test Cases
//
// 1 - Point/Point do not touch
template<>
template<>
void object::test<1>()
{
GeomAutoPtr g1(reader.read(
"POINT (0 0)"
));
GeomAutoPtr g2(reader.read(
"POINT (0 0)"
));
ensure(!g1->touches(g2.get()));
ensure(!g2->touches(g1.get()));
}
// 2 - Line/Point do not touch if point is not on boundary
template<>
template<>
void object::test<2>()
{
GeomAutoPtr g1(reader.read(
"LINESTRING(0 0, 1 1, 0 2)"
));
GeomAutoPtr g2(reader.read(
"POINT (1 1)"
));
ensure(!g1->touches(g2.get()));
ensure(!g2->touches(g1.get()));
}
// 3 - Line/Point touch
template<>
template<>
void object::test<3>()
{
GeomAutoPtr g1(reader.read(
"LINESTRING(0 0, 1 1, 0 2)"
));
GeomAutoPtr g2(reader.read(
"POINT (0 2)"
));
ensure(g1->touches(g2.get()));
ensure(g2->touches(g1.get()));
}
// 4 - Line/Point touch (FP coordinates)
template<>
template<>
void object::test<4>()
{
GeomAutoPtr g1(reader.read(
"LINESTRING (-612844.96290006 279079.117329031,-257704.820935236 574364.179187424)"
));
GeomAutoPtr g2(reader.read(
"POINT (-257704.820935236 574364.179187424)"
));
ensure(g1->touches(g2.get()));
ensure(g2->touches(g1.get()));
}
template<>
template<>
void object::test<5>()
{
// Two T-like segments, A (horizontal), B (vertical)
// A: LINESTRING(-3511.75501903694 4257.47493284327,-877.546556856658 4257.47493284327)
// B: LINESTRING(-2119.81532027122 4257.47493284327,-2119.81532027122 2326.7198668134)
std::stringstream wkbA("01020000000200000010efda91826fabc0a8e5329579a1b040008633595f6c8bc0a8e5329579a1b040");
std::stringstream wkbB("0102000000020000005999a871a18fa0c0a8e5329579a1b0405999a871a18fa0c0180a6292702da240");
GeomAutoPtr a(breader.readHEX(wkbA));
GeomAutoPtr b(breader.readHEX(wkbB));
ensure(a->touches(b.get()));
ensure(!a->disjoint(b.get()));
ensure(a->intersects(b.get()));
}
template<>
template<>
void object::test<6>()
{
// Two Y-like segments, A (V-part), B (|-part)
// A: LINESTRING(-428.533750803201 4467.01424233489,1098.10978977856 4137.73818456235,1621.95806350759 5544.64497686319)
// B: LINESTRING(1098.10978977856 4137.73818456235,1921.2999342099 2177.04893146225)
std::stringstream wkbA("010200000003000000603f483e8ac87ac092ba62a50373b1405851bb6c70289140b6d9a9f9bc29b04060a2990ed55799401226341da5a8b540");
std::stringstream wkbB("0102000000020000005851bb6c70289140b6d9a9f9bc29b040d019f42133059e40406c8b0d1902a140");
GeomAutoPtr a(breader.readHEX(wkbA));
GeomAutoPtr b(breader.readHEX(wkbB));
ensure(a->touches(b.get()));
ensure(!a->disjoint(b.get()));
ensure(a->intersects(b.get()));
}
template<>
template<>
void object::test<7>()
{
// Two T-like two segments rotated ~55 degrees counter-clockwise; A (horizontal), B (vertical)
// A: LINESTRING(3343.17382004585 2521.2920827699,4959.61992183829 5125.56635787996)
// B: LINESTRING(4151.39687094207 3823.42922032493,6112.08612404217 2461.42370862944)
std::stringstream wkbA("01020000000200000098e8f0fe581eaa40ea70df8b95b2a3408c9532b39e5fb340417cd4fc9005b440");
std::stringstream wkbB("010200000002000000ec8455996537b040b834c4c2dbdead4086a8390c16e0b740f86456f0d83aa340");
GeomAutoPtr a(breader.readHEX(wkbA));
GeomAutoPtr b(breader.readHEX(wkbB));
// segments do not just touch, but intersect (float-point robustness issue likely)
ensure(!a->touches(b.get()));
ensure(!a->disjoint(b.get()));
ensure(a->intersects(b.get()));
}
} // namespace tut
|
Adjust test comment
|
Adjust test comment
git-svn-id: 6c2b1bd10c324c49ea9d9e6e31006a80e70507cb@4376 5242fede-7e19-0410-aef8-94bd7d2200fb
|
C++
|
lgpl-2.1
|
libgeos/libgeos,libgeos/libgeos,strk/libgeos,mwtoews/libgeos,mwtoews/libgeos,libgeos/libgeos,strk/libgeos,mwtoews/libgeos,mwtoews/libgeos,libgeos/libgeos,mwtoews/libgeos,mwtoews/libgeos,mwtoews/libgeos,strk/libgeos,libgeos/libgeos,strk/libgeos,strk/libgeos
|
dc50d6bfb89f7341c93de216fc19aa12da0059b7
|
include/alpaka/mem/buf/Traits.hpp
|
include/alpaka/mem/buf/Traits.hpp
|
/* Copyright 2019 Alexander Matthes, Benjamin Worpitz
*
* This file is part of Alpaka.
*
* 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/.
*/
#pragma once
#include <alpaka/mem/view/Traits.hpp>
#include <alpaka/core/Common.hpp>
namespace alpaka
{
//-----------------------------------------------------------------------------
//! The memory specifics.
namespace mem
{
//-----------------------------------------------------------------------------
//! The buffer specifics.
namespace buf
{
//-----------------------------------------------------------------------------
//! The buffer traits.
namespace traits
{
//#############################################################################
//! The memory buffer type trait.
template<
typename TDev,
typename TElem,
typename TDim,
typename TIdx,
typename TSfinae = void>
struct BufType;
//#############################################################################
//! The memory allocator trait.
template<
typename TElem,
typename TDim,
typename TIdx,
typename TDev,
typename TSfinae = void>
struct Alloc;
//#############################################################################
//! The memory mapping trait.
template<
typename TBuf,
typename TDev,
typename TSfinae = void>
struct Map;
//#############################################################################
//! The memory unmapping trait.
template<
typename TBuf,
typename TDev,
typename TSfinae = void>
struct Unmap;
//#############################################################################
//! The memory pinning trait.
template<
typename TBuf,
typename TSfinae = void>
struct Pin;
//#############################################################################
//! The memory unpinning trait.
template<
typename TBuf,
typename TSfinae = void>
struct Unpin;
//#############################################################################
//! The memory pin state trait.
template<
typename TBuf,
typename TSfinae = void>
struct IsPinned;
//#############################################################################
//! The memory prepareForAsyncCopy trait.
template<
typename TBuf,
typename TSfinae = void>
struct PrepareForAsyncCopy;
}
//#############################################################################
//! The memory buffer type trait alias template to remove the ::type.
template<
typename TDev,
typename TElem,
typename TDim,
typename TIdx>
using Buf = typename traits::BufType<
alpaka::dev::Dev<TDev>, TElem, TDim, TIdx>::type;
//-----------------------------------------------------------------------------
//! Allocates memory on the given device.
//!
//! \tparam TElem The element type of the returned buffer.
//! \tparam TExtent The extent of the buffer.
//! \tparam TDev The type of device the buffer is allocated on.
//! \param dev The device to allocate the buffer on.
//! \param extent The extent of the buffer.
//! \return The newly allocated buffer.
template<
typename TElem,
typename TIdx,
typename TExtent,
typename TDev>
ALPAKA_FN_HOST auto alloc(
TDev const & dev,
TExtent const & extent = TExtent())
{
return
traits::Alloc<
TElem,
dim::Dim<TExtent>,
TIdx,
TDev>
::alloc(
dev,
extent);
}
//-----------------------------------------------------------------------------
//! Maps the buffer into the memory of the given device.
//!
//! \tparam TBuf The buffer type.
//! \tparam TDev The device type.
//! \param buf The buffer to map into the device memory.
//! \param dev The device to map the buffer into.
template<
typename TBuf,
typename TDev>
ALPAKA_FN_HOST auto map(
TBuf & buf,
TDev const & dev)
-> void
{
return
traits::Map<
TBuf,
TDev>
::map(
buf,
dev);
}
//-----------------------------------------------------------------------------
//! Unmaps the buffer from the memory of the given device.
//!
//! \tparam TBuf The buffer type.
//! \tparam TDev The device type.
//! \param buf The buffer to unmap from the device memory.
//! \param dev The device to unmap the buffer from.
template<
typename TBuf,
typename TDev>
ALPAKA_FN_HOST auto unmap(
TBuf & buf,
TDev const & dev)
-> void
{
return
traits::Unmap<
TBuf,
TDev>
::unmap(
buf,
dev);
}
//-----------------------------------------------------------------------------
//! Pins the buffer.
//!
//! \tparam TBuf The buffer type.
//! \param buf The buffer to pin in the device memory.
template<
typename TBuf>
ALPAKA_FN_HOST auto pin(
TBuf & buf)
-> void
{
return
traits::Pin<
TBuf>
::pin(
buf);
}
//-----------------------------------------------------------------------------
//! Unpins the buffer.
//!
//! \tparam TBuf The buffer type.
//! \param buf The buffer to unpin from the device memory.
template<
typename TBuf>
ALPAKA_FN_HOST auto unpin(
TBuf & buf)
-> void
{
return
traits::Unpin<
TBuf>
::unpin(
buf);
}
//-----------------------------------------------------------------------------
//! The pin state of the buffer.
//!
//! \tparam TBuf The buffer type.
//! \param buf The buffer to get the pin state of.
template<
typename TBuf>
ALPAKA_FN_HOST auto isPinned(
TBuf const & buf)
-> bool
{
return
traits::IsPinned<
TBuf>
::isPinned(
buf);
}
//-----------------------------------------------------------------------------
//! Prepares the buffer for non-blocking copy operations, e.g. pinning if
//! non-blocking copy between a cpu and a cuda device is wanted
//!
//! \tparam TBuf The buffer type.
//! \param buf The buffer to prepare in the device memory.
template<
typename TBuf>
ALPAKA_FN_HOST auto prepareForAsyncCopy(
TBuf & buf)
-> void
{
return
traits::PrepareForAsyncCopy<
TBuf>
::prepareForAsyncCopy(
buf);
}
}
}
}
|
/* Copyright 2019 Alexander Matthes, Benjamin Worpitz
*
* This file is part of Alpaka.
*
* 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/.
*/
#pragma once
#include <alpaka/mem/view/Traits.hpp>
#include <alpaka/core/Common.hpp>
namespace alpaka
{
//-----------------------------------------------------------------------------
//! The memory specifics.
namespace mem
{
//-----------------------------------------------------------------------------
//! The buffer specifics.
namespace buf
{
//-----------------------------------------------------------------------------
//! The buffer traits.
namespace traits
{
//#############################################################################
//! The memory buffer type trait.
template<
typename TDev,
typename TElem,
typename TDim,
typename TIdx,
typename TSfinae = void>
struct BufType;
//#############################################################################
//! The memory allocator trait.
template<
typename TElem,
typename TDim,
typename TIdx,
typename TDev,
typename TSfinae = void>
struct Alloc;
//#############################################################################
//! The memory mapping trait.
template<
typename TBuf,
typename TDev,
typename TSfinae = void>
struct Map;
//#############################################################################
//! The memory unmapping trait.
template<
typename TBuf,
typename TDev,
typename TSfinae = void>
struct Unmap;
//#############################################################################
//! The memory pinning trait.
template<
typename TBuf,
typename TSfinae = void>
struct Pin;
//#############################################################################
//! The memory unpinning trait.
template<
typename TBuf,
typename TSfinae = void>
struct Unpin;
//#############################################################################
//! The memory pin state trait.
template<
typename TBuf,
typename TSfinae = void>
struct IsPinned;
//#############################################################################
//! The memory prepareForAsyncCopy trait.
template<
typename TBuf,
typename TSfinae = void>
struct PrepareForAsyncCopy;
}
//#############################################################################
//! The memory buffer type trait alias template to remove the ::type.
template<
typename TDev,
typename TElem,
typename TDim,
typename TIdx>
using Buf = typename traits::BufType<
alpaka::dev::Dev<TDev>, TElem, TDim, TIdx>::type;
//-----------------------------------------------------------------------------
//! Allocates memory on the given device.
//!
//! \tparam TElem The element type of the returned buffer.
//! \tparam TIdx The linear index type of the buffer.
//! \tparam TExtent The extent type of the buffer.
//! \tparam TDev The type of device the buffer is allocated on.
//! \param dev The device to allocate the buffer on.
//! \param extent The extent of the buffer.
//! \return The newly allocated buffer.
template<
typename TElem,
typename TIdx,
typename TExtent,
typename TDev>
ALPAKA_FN_HOST auto alloc(
TDev const & dev,
TExtent const & extent = TExtent())
{
return
traits::Alloc<
TElem,
dim::Dim<TExtent>,
TIdx,
TDev>
::alloc(
dev,
extent);
}
//-----------------------------------------------------------------------------
//! Maps the buffer into the memory of the given device.
//!
//! \tparam TBuf The buffer type.
//! \tparam TDev The device type.
//! \param buf The buffer to map into the device memory.
//! \param dev The device to map the buffer into.
template<
typename TBuf,
typename TDev>
ALPAKA_FN_HOST auto map(
TBuf & buf,
TDev const & dev)
-> void
{
return
traits::Map<
TBuf,
TDev>
::map(
buf,
dev);
}
//-----------------------------------------------------------------------------
//! Unmaps the buffer from the memory of the given device.
//!
//! \tparam TBuf The buffer type.
//! \tparam TDev The device type.
//! \param buf The buffer to unmap from the device memory.
//! \param dev The device to unmap the buffer from.
template<
typename TBuf,
typename TDev>
ALPAKA_FN_HOST auto unmap(
TBuf & buf,
TDev const & dev)
-> void
{
return
traits::Unmap<
TBuf,
TDev>
::unmap(
buf,
dev);
}
//-----------------------------------------------------------------------------
//! Pins the buffer.
//!
//! \tparam TBuf The buffer type.
//! \param buf The buffer to pin in the device memory.
template<
typename TBuf>
ALPAKA_FN_HOST auto pin(
TBuf & buf)
-> void
{
return
traits::Pin<
TBuf>
::pin(
buf);
}
//-----------------------------------------------------------------------------
//! Unpins the buffer.
//!
//! \tparam TBuf The buffer type.
//! \param buf The buffer to unpin from the device memory.
template<
typename TBuf>
ALPAKA_FN_HOST auto unpin(
TBuf & buf)
-> void
{
return
traits::Unpin<
TBuf>
::unpin(
buf);
}
//-----------------------------------------------------------------------------
//! The pin state of the buffer.
//!
//! \tparam TBuf The buffer type.
//! \param buf The buffer to get the pin state of.
template<
typename TBuf>
ALPAKA_FN_HOST auto isPinned(
TBuf const & buf)
-> bool
{
return
traits::IsPinned<
TBuf>
::isPinned(
buf);
}
//-----------------------------------------------------------------------------
//! Prepares the buffer for non-blocking copy operations, e.g. pinning if
//! non-blocking copy between a cpu and a cuda device is wanted
//!
//! \tparam TBuf The buffer type.
//! \param buf The buffer to prepare in the device memory.
template<
typename TBuf>
ALPAKA_FN_HOST auto prepareForAsyncCopy(
TBuf & buf)
-> void
{
return
traits::PrepareForAsyncCopy<
TBuf>
::prepareForAsyncCopy(
buf);
}
}
}
}
|
Add missing doxygen for TIdx parameter of mem::buf::alloc
|
Add missing doxygen for TIdx parameter of mem::buf::alloc
|
C++
|
mpl-2.0
|
BenjaminW3/alpaka,BenjaminW3/alpaka
|
8463ba6b5917886700e2382a90de321b11891954
|
include/commonpp/core/Options.hpp
|
include/commonpp/core/Options.hpp
|
/*
* File: include/commonpp/core/Options.hpp
* Part of commonpp.
*
* Distributed under the 2-clause BSD licence (See LICENCE.TXT file at the
* project root).
*
* Copyright (c) 2016 Thomas Sanchez. All rights reserved.
*
*/
#pragma once
#include <iosfwd>
#include <type_traits>
#include <commonpp/core/Utils.hpp>
#include <commonpp/core/config.hpp>
// clang-format off
#if BOOST_CLANG == 1 && BOOST_MAJOR == 1 && BOOST_MAJOR <= 55
# if defined(BOOST_PP_VARIADICS)
# if !BOOST_PP_VARIADICS
# warning BOOST_PP_VARIADICS cannot be defined as 0, redefining it to 1a
# undef BOOST_PP_VARIADICS
# define BOOST_PP_VARIADICS 1
# endif
# else
# define BOOST_PP_VARIADICS 1
# endif
#endif
// clang-format on
#include <boost/preprocessor/seq/elem.hpp>
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/stringize.hpp>
#include <boost/preprocessor/variadic/to_seq.hpp>
namespace commonpp
{
template <typename Enum, Enum... initial_value>
struct Options
{
using Underlying = typename std::underlying_type<Enum>::type;
static_assert(std::is_unsigned<Underlying>::value, "Enum must be unsigned");
constexpr Options() = default;
template <typename... E>
BOOST_CXX14_CONSTEXPR Options(E... v) noexcept
{
flag_ = set(initial_value..., v...);
}
Options& operator&=(Enum f) noexcept
{
flag_ |= enum_to_number(f);
return *this;
}
Options& operator+=(Enum f) noexcept
{
flag_ |= enum_to_number(f);
return *this;
}
Options& operator-=(Enum f) noexcept
{
flag_ = flag_ & ~enum_to_number(f);
return *this;
}
bool operator&(Enum f) const noexcept
{
return (flag_ & enum_to_number(f)) != 0;
}
bool operator[](Enum f) const noexcept
{
return (flag_ & enum_to_number(f)) != 0;
}
template <Enum... e>
bool operator==(const Options<Enum, e...>& rhs) const noexcept
{
return flag() == rhs.flag();
}
bool empty() const noexcept
{
return flag_ == 0;
}
Underlying flag() const noexcept
{
return flag_;
}
void unsafe_set_flag(Underlying u) noexcept
{
flag_ = u;
}
void reset() noexcept
{
flag_ = 0;
}
private:
static constexpr Underlying set() noexcept
{
return 0;
}
static constexpr Underlying set(Enum value) noexcept
{
return enum_to_number(value);
}
template <typename Head, typename... Tail>
static constexpr Underlying set(Head value, Tail... tail) noexcept
{
return set(value) | set(tail...);
}
Underlying flag_ = set(initial_value...);
};
#define COMMONPP_PRINT_OPTION_IF(R, Opts, Elem) \
do \
{ \
os << "Flag: " << BOOST_PP_STRINGIZE(Elem) << ": " \
<< ((Opts & Elem) ? "Enabled" : "Disabled") << ", "; \
} while (0);
#define COMMONPP_DECLARE_OPTIONS_OSTREAM_OP(Options) \
std::ostream& operator<<(std::ostream& os, const Options& opt)
#define COMMONPP_GENERATE_OPTIONS_OSTREAM_OP(Options, ...) \
COMMONPP_DECLARE_OPTIONS_OSTREAM_OP(Options) \
{ \
os << BOOST_PP_STRINGIZE(Options) << ": ["; \
BOOST_PP_SEQ_FOR_EACH(COMMONPP_PRINT_OPTION_IF, opt, \
BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)) \
os << "]"; \
return os; \
}
} // namespace commonpp
|
/*
* File: include/commonpp/core/Options.hpp
* Part of commonpp.
*
* Distributed under the 2-clause BSD licence (See LICENCE.TXT file at the
* project root).
*
* Copyright (c) 2016 Thomas Sanchez. All rights reserved.
*
*/
#pragma once
#include <iosfwd>
#include <type_traits>
#include <commonpp/core/Utils.hpp>
#include <commonpp/core/config.hpp>
// clang-format off
#if BOOST_CLANG == 1 && BOOST_MAJOR == 1 && BOOST_MAJOR <= 55
# if defined(BOOST_PP_VARIADICS)
# if !BOOST_PP_VARIADICS
# warning BOOST_PP_VARIADICS cannot be defined as 0, redefining it to 1a
# undef BOOST_PP_VARIADICS
# define BOOST_PP_VARIADICS 1
# endif
# else
# define BOOST_PP_VARIADICS 1
# endif
#endif
// clang-format on
#include <boost/preprocessor/seq/elem.hpp>
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/stringize.hpp>
#include <boost/preprocessor/variadic/to_seq.hpp>
namespace commonpp
{
template <typename Enum, Enum... initial_value>
struct Options
{
using Underlying = typename std::underlying_type<Enum>::type;
static_assert(std::is_unsigned<Underlying>::value, "Enum must be unsigned");
constexpr Options() = default;
template <typename... E>
BOOST_CXX14_CONSTEXPR Options(E... v) noexcept
{
flag_ = set(initial_value..., v...);
}
Options& operator&=(Enum f) noexcept
{
flag_ &= enum_to_number(f);
return *this;
}
Options& operator|=(Enum f) noexcept
{
flag_ |= enum_to_number(f);
return *this;
}
Options& operator+=(Enum f) noexcept
{
flag_ |= enum_to_number(f);
return *this;
}
Options& operator-=(Enum f) noexcept
{
flag_ = flag_ & ~enum_to_number(f);
return *this;
}
Options operator&(const Options& rhs) const noexcept
{
Options o;
o.flag_ = flag_ & rhs.flag_;
return o;
}
Options operator|(const Options& rhs) const noexcept
{
Options o;
o.flag_ = flag_ | rhs.flag_;
return o;
}
bool operator&(Enum f) const noexcept
{
return (flag_ & enum_to_number(f)) != 0;
}
bool operator[](Enum f) const noexcept
{
return (flag_ & enum_to_number(f)) != 0;
}
template <Enum... e>
bool operator==(const Options<Enum, e...>& rhs) const noexcept
{
return flag() == rhs.flag();
}
template <Enum... e>
bool operator!=(const Options<Enum, e...>& rhs) const noexcept
{
return flag() != rhs.flag();
}
bool empty() const noexcept
{
return flag_ == 0;
}
Underlying flag() const noexcept
{
return flag_;
}
void unsafe_set_flag(Underlying u) noexcept
{
flag_ = u;
}
void reset() noexcept
{
flag_ = 0;
}
private:
static constexpr Underlying set() noexcept
{
return 0;
}
static constexpr Underlying set(Enum value) noexcept
{
return enum_to_number(value);
}
template <typename Head, typename... Tail>
static constexpr Underlying set(Head value, Tail... tail) noexcept
{
return set(value) | set(tail...);
}
Underlying flag_ = set(initial_value...);
};
#define COMMONPP_PRINT_OPTION_IF(R, Opts, Elem) \
do \
{ \
os << "Flag: " << BOOST_PP_STRINGIZE(Elem) << ": " \
<< ((Opts & Elem) ? "Enabled" : "Disabled") << ", "; \
} while (0);
#define COMMONPP_DECLARE_OPTIONS_OSTREAM_OP(Options) \
std::ostream& operator<<(std::ostream& os, const Options& opt)
#define COMMONPP_GENERATE_OPTIONS_OSTREAM_OP(Options, ...) \
COMMONPP_DECLARE_OPTIONS_OSTREAM_OP(Options) \
{ \
os << BOOST_PP_STRINGIZE(Options) << ": ["; \
BOOST_PP_SEQ_FOR_EACH(COMMONPP_PRINT_OPTION_IF, opt, \
BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)) \
os << "]"; \
return os; \
}
} // namespace commonpp
|
add some useful member functions in Options
|
core: add some useful member functions in Options
|
C++
|
bsd-2-clause
|
daedric/commonpp,daedric/commonpp
|
5c3fb11e2df67bfe5e301c3d5acaa3adeeaac591
|
include/huffman/wx_huff_naive.hpp
|
include/huffman/wx_huff_naive.hpp
|
/*******************************************************************************
* include/huffman/wx_huff_naive.hpp
*
* Copyright (C) 2017 Florian Kurpicz <[email protected]>
*
* All rights reserved. Published under the BSD-2 license in the LICENSE file.
******************************************************************************/
#pragma once
#include <cstring>
#include "huff_bit_vectors.hpp"
#include "huff_codes.hpp"
#include "util/wavelet_structure.hpp"
template <typename AlphabetType, bool is_tree>
class wx_huff_naive;
template <typename AlphabetType>
class wx_huff_naive<AlphabetType, true> {
public:
static constexpr bool is_parallel = false;
static constexpr bool is_tree = true;
static constexpr uint8_t word_width = sizeof(AlphabetType);
static constexpr bool is_huffman_shaped = true;
static wavelet_structure compute(AlphabetType const* const text,
const uint64_t size, const uint64_t /*levels*/) {
canonical_huff_codes<AlphabetType, is_tree> codes(text, size);
if(size == 0) {
return wavelet_structure_tree_huffman<AlphabetType>(std::move(codes));
}
const uint64_t levels = codes.levels();
auto _bv = huff_bit_vectors(levels, codes.level_sizes());
auto& bv = _bv.raw_data();
std::vector<AlphabetType> local_text(size);
for(size_t i = 0; i < size; i++) {
local_text[i] = text[i];
}
for (uint64_t level = 0; level < levels; ++level) {
uint32_t cur_pos = 0;
for (; cur_pos + 64 <= local_text.size(); cur_pos += 64) {
uint64_t word = 0ULL;
for (uint32_t i = 0; i < 64; ++i) {
word <<= 1;
word |= codes.encode_symbol(local_text[cur_pos + i])[level];
}
bv[level][cur_pos >> 6] = word;
}
if (local_text.size() & 63ULL) {
uint64_t word = 0ULL;
for (uint32_t i = 0; i < local_text.size() - cur_pos; ++i) {
word <<= 1;
word |= codes.encode_symbol(local_text[cur_pos + i])[level];
}
word <<= (64 - (local_text.size() & 63ULL));
bv[level][local_text.size() >> 6] = word;
}
std::vector<std::vector<AlphabetType>> buckets(1ULL << (level + 1));
for (uint64_t i = 0; i < local_text.size(); ++i) {
const AlphabetType cur_symbol = local_text[i];
if (codes.code_length(cur_symbol) > level + 1) {
buckets[codes.encode_symbol(cur_symbol).prefix(level + 1)]
.emplace_back(cur_symbol);
}
}
for (uint64_t i = 1; i < buckets.size(); ++i) {
std::move(buckets[i].begin(), buckets[i].end(),
std::back_inserter(buckets[0]));
}
local_text.swap(buckets[0]);
}
return wavelet_structure_tree_huffman<AlphabetType>(std::move(_bv), std::move(codes));
}
}; // class wt_huff_naive
template <typename AlphabetType>
class wx_huff_naive<AlphabetType, false> {
public:
static constexpr bool is_parallel = false;
static constexpr bool is_tree = false;
static constexpr uint8_t word_width = sizeof(AlphabetType);
static constexpr bool is_huffman_shaped = true;
static wavelet_structure compute(AlphabetType const* const text,
const uint64_t size, const uint64_t /*levels*/) {
canonical_huff_codes<AlphabetType, is_tree> codes(text, size);
if(size == 0) {
return wavelet_structure_matrix_huffman<AlphabetType>(std::move(codes));
}
const uint64_t levels = codes.levels();
auto _bv = huff_bit_vectors(levels, codes.level_sizes());
auto& bv = _bv.raw_data();
auto _zeros = std::vector<size_t>(levels, 0);
std::vector<AlphabetType> local_text(size);
for(size_t i = 0; i < size; i++) {
local_text[i] = text[i];
}
// Construct each level top-down
for (uint64_t level = 0; level < levels; ++level) {
// Insert the level-th MSB in the bit vector of the level (in text order)
uint32_t cur_pos = 0;
for (; cur_pos + 64 <= local_text.size(); cur_pos += 64) {
uint64_t word = 0ULL;
for (uint32_t i = 0; i < 64; ++i) {
word <<= 1;
word |= codes.encode_symbol(local_text[cur_pos + i])[level];
}
bv[level][cur_pos >> 6] = word;
}
if (local_text.size() & 63ULL) {
uint64_t word = 0ULL;
for (uint32_t i = 0; i < local_text.size() - cur_pos; ++i) {
word <<= 1;
word |= codes.encode_symbol(local_text[cur_pos + i])[level];
}
word <<= (64 - (local_text.size() & 63ULL));
bv[level][local_text.size() >> 6] = word;
}
std::vector<AlphabetType> text0;
std::vector<AlphabetType> text1;
// Scan the text and separate characters that inserted 0s and 1s
for (const auto symbol : local_text) {
const code_pair cp = codes.encode_symbol(symbol);
if (cp.code_length > level + 1) {
if (cp[level]) {
text1.emplace_back(symbol);
} else {
text0.emplace_back(symbol);
}
}
}
_zeros[level] = text0.size();
std::move(text1.begin(), text1.end(), std::back_inserter(text0));
local_text.swap(text0);
}
return wavelet_structure_matrix_huffman<AlphabetType>(std::move(_bv), std::move(_zeros), std::move(codes));
}
}; // class wx_huff_naive<MATRIX>
/******************************************************************************/
|
/*******************************************************************************
* include/huffman/wx_huff_naive.hpp
*
* Copyright (C) 2017 Florian Kurpicz <[email protected]>
*
* All rights reserved. Published under the BSD-2 license in the LICENSE file.
******************************************************************************/
#pragma once
#include <cstring>
#include "huff_bit_vectors.hpp"
#include "huff_codes.hpp"
#include "util/wavelet_structure.hpp"
template <typename AlphabetType, bool is_tree>
class wx_huff_naive;
template <typename AlphabetType>
class wx_huff_naive<AlphabetType, true> {
public:
static constexpr bool is_parallel = false;
static constexpr bool is_tree = true;
static constexpr uint8_t word_width = sizeof(AlphabetType);
static constexpr bool is_huffman_shaped = true;
static wavelet_structure compute(AlphabetType const* const text,
const uint64_t size, const uint64_t /*levels*/) {
canonical_huff_codes<AlphabetType, is_tree> codes(text, size);
if(size == 0) {
return wavelet_structure_tree_huffman<AlphabetType>(std::move(codes));
}
const uint64_t levels = codes.levels();
auto _bv = huff_bit_vectors(levels, codes.level_sizes());
auto& bv = _bv.raw_data();
std::vector<AlphabetType> local_text(size);
for(size_t i = 0; i < size; i++) {
local_text[i] = text[i];
}
for (uint64_t level = 0; level < levels; ++level) {
uint32_t cur_pos = 0;
for (; cur_pos + 64 <= local_text.size(); cur_pos += 64) {
uint64_t word = 0ULL;
for (uint32_t i = 0; i < 64; ++i) {
word <<= 1;
word |= codes.encode_symbol(local_text[cur_pos + i])[level];
}
bv[level][cur_pos >> 6] = word;
}
if (local_text.size() & 63ULL) {
uint64_t word = 0ULL;
for (uint32_t i = 0; i < local_text.size() - cur_pos; ++i) {
word <<= 1;
word |= codes.encode_symbol(local_text[cur_pos + i])[level];
}
word <<= (64 - (local_text.size() & 63ULL));
bv[level][local_text.size() >> 6] = word;
}
std::vector<std::vector<AlphabetType>> buckets(1ULL << (level + 1));
for (uint64_t i = 0; i < local_text.size(); ++i) {
const AlphabetType cur_symbol = local_text[i];
if (codes.code_length(cur_symbol) > level + 1) {
buckets[codes.encode_symbol(cur_symbol).prefix(level + 1)]
.emplace_back(cur_symbol);
}
}
for (uint64_t i = 1; i < buckets.size(); ++i) {
std::move(buckets[i].begin(), buckets[i].end(),
std::back_inserter(buckets[0]));
}
local_text.swap(buckets[0]);
}
return wavelet_structure_tree_huffman<AlphabetType>(
std::move(_bv), std::move(codes));
}
}; // class wt_huff_naive
template <typename AlphabetType>
class wx_huff_naive<AlphabetType, false> {
public:
static constexpr bool is_parallel = false;
static constexpr bool is_tree = false;
static constexpr uint8_t word_width = sizeof(AlphabetType);
static constexpr bool is_huffman_shaped = true;
static wavelet_structure compute(AlphabetType const* const text,
const uint64_t size, const uint64_t /*levels*/) {
canonical_huff_codes<AlphabetType, is_tree> codes(text, size);
if(size == 0) {
return wavelet_structure_matrix_huffman<AlphabetType>(std::move(codes));
}
const uint64_t levels = codes.levels();
auto _bv = huff_bit_vectors(levels, codes.level_sizes());
auto& bv = _bv.raw_data();
auto _zeros = std::vector<size_t>(levels, 0);
std::vector<AlphabetType> local_text(size);
for(size_t i = 0; i < size; i++) { local_text[i] = text[i]; }
// Construct each level top-down
for (uint64_t level = 0; level < levels; ++level) {
std::vector<AlphabetType> text0;
std::vector<AlphabetType> text1;
// Insert the level-th MSB in the bit vector of the level (in text order)
uint32_t cur_pos = 0;
for (; cur_pos + 64 <= local_text.size(); cur_pos += 64) {
uint64_t word = 0ULL;
for (uint32_t i = 0; i < 64; ++i) {
const code_pair cp = codes.encode_symbol(local_text[cur_pos + i]);
word <<= 1;
word |= cp[level];
if (cp.code_length > level + 1) {
if (cp[level]) { text1.emplace_back(local_text[cur_pos + i]); }
else { text0.emplace_back(local_text[cur_pos + i]); }
}
}
_zeros[level] += __builtin_popcountll(~word);
bv[level][cur_pos >> 6] = word;
}
if (local_text.size() & 63ULL) {
uint64_t word = 0ULL;
for (uint32_t i = 0; i < local_text.size() - cur_pos; ++i) {
const code_pair cp = codes.encode_symbol(local_text[cur_pos + i]);
word <<= 1;
word |= cp[level];
if (cp.code_length > level + 1) {
if (cp[level]) { text1.emplace_back(local_text[cur_pos + i]); }
else { text0.emplace_back(local_text[cur_pos + i]); }
}
}
word <<= (64 - (local_text.size() & 63ULL));
bv[level][local_text.size() >> 6] = word;
_zeros[level] +=
(local_text.size() & 63ULL) - __builtin_popcountll(word);
}
std::move(text1.begin(), text1.end(), std::back_inserter(text0));
local_text = std::move(text0);
}
return wavelet_structure_matrix_huffman<AlphabetType>(
std::move(_bv), std::move(_zeros), std::move(codes));
}
}; // class wx_huff_naive<MATRIX>
/******************************************************************************/
|
Fix counting of zeros on last level huff_naive WM
|
Fix counting of zeros on last level huff_naive WM
|
C++
|
bsd-2-clause
|
kurpicz/pwm,kurpicz/pwm,kurpicz/pwm
|
e55b20addaa95c9fea29dea8e7cfd40ca4c167fe
|
include/internal/iutest_debug.hpp
|
include/internal/iutest_debug.hpp
|
//======================================================================
//-----------------------------------------------------------------------
/**
* @file iutest_debug.hpp
* @brief iris unit test debug 用定義 ファイル
*
* @author t.shirayanagi
* @par copyright
* Copyright (C) 2011-2019, Takazumi Shirayanagi\n
* This software is released under the new BSD License,
* see LICENSE
*/
//-----------------------------------------------------------------------
//======================================================================
#ifndef INCG_IRIS_IUTEST_DEBUG_HPP_A63366D4_2112_4269_9BAF_BD30A5F2C7F2_
#define INCG_IRIS_IUTEST_DEBUG_HPP_A63366D4_2112_4269_9BAF_BD30A5F2C7F2_
#if defined(_IUTEST_DEBUG)
// iutest 自体のデバッグ用定義
#if defined(_MSC_VER) && !defined(IUTEST_OS_WINDOWS_MOBILE)
# include <crtdbg.h>
# include <xlocnum>
# include <xtree>
# include <streambuf>
# ifndef _DEBUG_NEW_
# define _DEBUG_NEW_ new ( _NORMAL_BLOCK , __FILE__, __LINE__)
# pragma push_macro("new")
# define new _DEBUG_NEW_
# endif
#endif
#endif
namespace iutest {
namespace detail
{
//======================================================================
// function
static void IUTEST_ATTRIBUTE_UNUSED_ iuDebugInitialize()
{
#ifdef _IUTEST_DEBUG
# if defined(_MSC_VER) && !defined(IUTEST_OS_WINDOWS_MOBILE)
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
# endif
#endif
}
static void IUTEST_ATTRIBUTE_UNUSED_ iuDebugBreakAlloc(long n)
{
#ifdef _IUTEST_DEBUG
# if defined(_MSC_VER) && !defined(IUTEST_OS_WINDOWS_MOBILE)
_CrtSetBreakAlloc(n);
# endif
#endif
(void)n;
}
#if defined(_MSC_VER) && IUTEST_HAS_MINIDUMP
/**
* @brief minidump 作成クラス
*/
class MiniDump
{
private:
MiniDump();
~MiniDump();
bool Dump(HANDLE hFile, EXCEPTION_POINTERS* ep);
public:
/**
* @brief minidump 作成
*/
static bool Create(const char* filepath, EXCEPTION_POINTERS* ep);
private:
HMODULE m_hModule;
FARPROC m_pfnMiniDumpWriteDump;
};
#endif
} // end of namespace detail
} // end of namespace iutest
#if !IUTEST_HAS_LIB
# include "../impl/iutest_debug.ipp"
#endif
#endif // INCG_IRIS_IUTEST_DEBUG_HPP_A63366D4_2112_4269_9BAF_BD30A5F2C7F2_
|
//======================================================================
//-----------------------------------------------------------------------
/**
* @file iutest_debug.hpp
* @brief iris unit test debug 用定義 ファイル
*
* @author t.shirayanagi
* @par copyright
* Copyright (C) 2011-2020, Takazumi Shirayanagi\n
* This software is released under the new BSD License,
* see LICENSE
*/
//-----------------------------------------------------------------------
//======================================================================
#ifndef INCG_IRIS_IUTEST_DEBUG_HPP_A63366D4_2112_4269_9BAF_BD30A5F2C7F2_
#define INCG_IRIS_IUTEST_DEBUG_HPP_A63366D4_2112_4269_9BAF_BD30A5F2C7F2_
#if defined(_IUTEST_DEBUG)
// iutest 自体のデバッグ用定義
#if defined(_MSC_VER) && !defined(IUTEST_OS_WINDOWS_MOBILE)
# include <crtdbg.h>
# include <xlocnum>
# include <xtree>
# include <streambuf> // NOLINT
# ifndef _DEBUG_NEW_
# define _DEBUG_NEW_ new ( _NORMAL_BLOCK , __FILE__, __LINE__)
# pragma push_macro("new")
# define new _DEBUG_NEW_
# endif
#endif
#endif
namespace iutest {
namespace detail
{
//======================================================================
// function
static void IUTEST_ATTRIBUTE_UNUSED_ iuDebugInitialize()
{
#ifdef _IUTEST_DEBUG
# if defined(_MSC_VER) && !defined(IUTEST_OS_WINDOWS_MOBILE)
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
# endif
#endif
}
static void IUTEST_ATTRIBUTE_UNUSED_ iuDebugBreakAlloc(long n)
{
#ifdef _IUTEST_DEBUG
# if defined(_MSC_VER) && !defined(IUTEST_OS_WINDOWS_MOBILE)
_CrtSetBreakAlloc(n);
# endif
#endif
(void)n;
}
#if defined(_MSC_VER) && IUTEST_HAS_MINIDUMP
/**
* @brief minidump 作成クラス
*/
class MiniDump
{
private:
MiniDump();
~MiniDump();
bool Dump(HANDLE hFile, EXCEPTION_POINTERS* ep);
public:
/**
* @brief minidump 作成
*/
static bool Create(const char* filepath, EXCEPTION_POINTERS* ep);
private:
HMODULE m_hModule;
FARPROC m_pfnMiniDumpWriteDump;
};
#endif
} // end of namespace detail
} // end of namespace iutest
#if !IUTEST_HAS_LIB
# include "../impl/iutest_debug.ipp"
#endif
#endif // INCG_IRIS_IUTEST_DEBUG_HPP_A63366D4_2112_4269_9BAF_BD30A5F2C7F2_
|
fix cpplint
|
fix cpplint
|
C++
|
bsd-3-clause
|
srz-zumix/iutest,srz-zumix/iutest,srz-zumix/iutest,srz-zumix/iutest,srz-zumix/iutest
|
00de7f872950e38e284c3a35ef89bd3a925350ff
|
Filters/Core/Testing/Cxx/TestDelaunay2DFindTriangle.cxx
|
Filters/Core/Testing/Cxx/TestDelaunay2DFindTriangle.cxx
|
/*=========================================================================
Program: Visualization Toolkit
Module: TestDelaunay2D_FindTriangle.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkDelaunay2D.h"
#include "vtkCellArray.h"
int TestDelaunay2DFindTriangle( int vtkNotUsed(argc), char* vtkNotUsed(argv)[] )
{
vtkPoints *newPts = vtkPoints::New();
newPts->InsertNextPoint(0.650665, -0.325333, 0);
newPts->InsertNextPoint(-0.325333, 0.650665, 0);
newPts->InsertNextPoint(-0.325333, -0.325333, 0);
newPts->InsertNextPoint(0.283966, 0.0265961, 0);
newPts->InsertNextPoint(0.373199, -0.0478668, 0);
newPts->InsertNextPoint(-0.325333, 0.535065, 0);
vtkCellArray* cells = vtkCellArray::New();
vtkIdType pts[2];
pts[0] = 3;
pts[1] = 4;
cells->InsertNextCell(2, pts);
pts[0] = 5;
pts[1] = 3;
cells->InsertNextCell(2, pts);
pts[0] = 5;
pts[1] = 1;
cells->InsertNextCell(2, pts);
pts[0] = 1;
pts[1] = 4;
cells->InsertNextCell(2, pts);
pts[0] = 4;
pts[1] = 0;
cells->InsertNextCell(2, pts);
pts[0] = 0;
pts[1] = 2;
cells->InsertNextCell(2, pts);
pts[0] = 2;
pts[1] = 5;
cells->InsertNextCell(2, pts);
vtkPolyData *poly = vtkPolyData::New();
poly->SetPoints(newPts);
poly->SetLines(cells);
newPts->Delete();
cells->Delete();
vtkDelaunay2D *del2D = vtkDelaunay2D::New();
del2D->SetInputData(poly);
del2D->SetSourceData(poly);
del2D->SetTolerance(0.0);
del2D->SetAlpha(0.0);
del2D->SetOffset(10);
del2D->BoundingTriangulationOff();
poly->Delete();
del2D->Update();
vtkPolyData *out = del2D->GetOutput();
vtkIdType numFaces = out->GetNumberOfCells();
if (numFaces!=5)
{
del2D->Delete();
return EXIT_FAILURE;
}
int expected[5][3] = {{4,2,0},{4,3,2},{5,3,1},{4,1,3},{5,3,2}};
int face[3] = {0,0,0};
for (int i=0; i<numFaces; ++i)
{
vtkCell* cell = out->GetCell(i);
face[0] = cell->GetPointId(0);
face[1] = cell->GetPointId(1);
face[2] = cell->GetPointId(2);
if (face[0]!=expected[i][0] || face[1]!=expected[i][1] || face[2]!=expected[i][2])
{
del2D->Delete();
return EXIT_FAILURE;
}
}
del2D->Delete();
return EXIT_SUCCESS;
}
|
/*=========================================================================
Program: Visualization Toolkit
Module: TestDelaunay2D_FindTriangle.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkDelaunay2D.h"
#include "vtkCellArray.h"
int TestDelaunay2DFindTriangle( int vtkNotUsed(argc), char* vtkNotUsed(argv)[] )
{
vtkPoints *newPts = vtkPoints::New();
newPts->InsertNextPoint(0.650665, -0.325333, 0);
newPts->InsertNextPoint(-0.325333, 0.650665, 0);
newPts->InsertNextPoint(-0.325333, -0.325333, 0);
newPts->InsertNextPoint(0.283966, 0.0265961, 0);
newPts->InsertNextPoint(0.373199, -0.0478668, 0);
newPts->InsertNextPoint(-0.325333, 0.535065, 0);
vtkCellArray* cells = vtkCellArray::New();
vtkIdType pts[2];
pts[0] = 3;
pts[1] = 4;
cells->InsertNextCell(2, pts);
pts[0] = 5;
pts[1] = 3;
cells->InsertNextCell(2, pts);
pts[0] = 5;
pts[1] = 1;
cells->InsertNextCell(2, pts);
pts[0] = 1;
pts[1] = 4;
cells->InsertNextCell(2, pts);
pts[0] = 4;
pts[1] = 0;
cells->InsertNextCell(2, pts);
pts[0] = 0;
pts[1] = 2;
cells->InsertNextCell(2, pts);
pts[0] = 2;
pts[1] = 5;
cells->InsertNextCell(2, pts);
vtkPolyData *poly = vtkPolyData::New();
poly->SetPoints(newPts);
poly->SetLines(cells);
newPts->Delete();
cells->Delete();
vtkDelaunay2D *del2D = vtkDelaunay2D::New();
del2D->SetInputData(poly);
del2D->SetSourceData(poly);
del2D->SetTolerance(0.0);
del2D->SetAlpha(0.0);
del2D->SetOffset(10);
del2D->BoundingTriangulationOff();
poly->Delete();
del2D->Update();
vtkPolyData *out = del2D->GetOutput();
vtkIdType numFaces = out->GetNumberOfCells();
if (numFaces!=5)
{
del2D->Delete();
return EXIT_FAILURE;
}
int expected[5][3] = {{4,2,0},{4,3,2},{5,3,1},{4,1,3},{5,3,2}};
int face[3] = {0,0,0};
for (int i=0; i<numFaces; ++i)
{
vtkCell* cell = out->GetCell(i);
face[0] = cell->GetPointId(0);
face[1] = cell->GetPointId(1);
face[2] = cell->GetPointId(2);
if (face[0]!=expected[i][0] || face[1]!=expected[i][1] || face[2]!=expected[i][2])
{
del2D->Delete();
return EXIT_FAILURE;
}
}
del2D->Delete();
return EXIT_SUCCESS;
}
|
Add newline at end of file to silence warning.
|
Add newline at end of file to silence warning.
|
C++
|
bsd-3-clause
|
keithroe/vtkoptix,SimVascular/VTK,keithroe/vtkoptix,sumedhasingla/VTK,keithroe/vtkoptix,sumedhasingla/VTK,SimVascular/VTK,sumedhasingla/VTK,sumedhasingla/VTK,keithroe/vtkoptix,SimVascular/VTK,keithroe/vtkoptix,keithroe/vtkoptix,sumedhasingla/VTK,SimVascular/VTK,SimVascular/VTK,sumedhasingla/VTK,SimVascular/VTK,sumedhasingla/VTK,sumedhasingla/VTK,SimVascular/VTK,SimVascular/VTK,keithroe/vtkoptix,keithroe/vtkoptix
|
bed299b54c4b93858973ffd48a969f5ba5733f8c
|
dfa.cpp
|
dfa.cpp
|
#include "dfa.h"
#include <vector>
#include <utility>
#include <memory>
#include <queue>
#include <numeric>
#include <algorithm>
DFA::DFA(const NFA& nfa)
{
using state_closure_pair = std::pair<State*, eps_closure_type>;
states.push_back(std::make_unique<State>());
auto q0 = nfa.eps_closure(nfa.start_state());
auto d0 = states.back().get();
auto p0 = make_pair(d0, q0);
head = d0;
std::vector<state_closure_pair> dfa;
dfa.push_back(p0);
std::queue<state_closure_pair> work_list;
work_list.push(p0);
while (!work_list.empty())
{
auto p = work_list.front();
auto d = p.first;
auto q = p.second;
// if the set that corresponds to the DFA state contains the accepting
// state of the NFA then the DFA state is an accepting state
if (q[nfa.accepting_state()]) tails.push_back(d);
work_list.pop();
for (auto c : nfa.alphabet())
{
auto states_count = nfa.states_count();
// iterate through each state from q and see if it has
// transition through character c.
// if it has, then compute the epsilon closure to the state
// that results from the transition.
auto delta = [&nfa, states_count](eps_closure_type closure, char c)
{
std::vector<int> states;
for (int i = 0; i < states_count; ++i)
{
if (!closure[i]) continue;
auto next_state = nfa.transition(i, c);
if (next_state != -1)
{
states.push_back(next_state);
}
}
return states;
};
// return a vector of epsilon closures for the given states
auto epsilon_closures = [&nfa](std::vector<int> states)
{
std::vector<eps_closure_type> closures;
for (auto state : states)
{
closures.push_back(nfa.eps_closure(state));
}
return closures;
};
// calculate the union of a set of closures
auto closures_union = [states_count]
(std::vector<eps_closure_type> closures)
{
return std::accumulate(
closures.begin(), closures.end(),
eps_closure_type(states_count),
[](eps_closure_type closure1, eps_closure_type closure2)
{
eps_closure_type result(closure1.size());
for (std::size_t i = 0; i < result.size(); ++i)
{
result[i] = closure1[i] | closure2[i];
}
return result;
});
};
// returns true if two boolean vectors have the same size
// and are equal element-wise
auto cmp_bool_vector = [](std::vector<bool> v1, std::vector<bool> v2)
{
if (v1.size() != v2.size()) return false;
for (std::size_t i = 0; i < v1.size(); ++i)
{
if (v1[i] != v2[i]) return false;
}
return true;
};
auto t = closures_union(epsilon_closures(delta(q, c)));
// continue if all elements in t are false
if (std::all_of(t.begin(), t.end(), [](bool b) { return !b; }))
{
continue;
}
auto dd = std::find_if(dfa.begin(), dfa.end(),
[&t, cmp_bool_vector](state_closure_pair p)
{ return cmp_bool_vector(p.second, t); });
if (dd == dfa.end())
{
states.push_back(std::make_unique<State>());
auto new_state = states.back().get();
dfa.push_back(make_pair(new_state, t));
work_list.push(make_pair(new_state, t));
d->add_transition(new_state, c);
}
else
{
d->add_transition(dd->first, c);
}
}
}
for (std::size_t i = 0; i < states.size(); ++i)
{
states[i]->state_number = i;
}
}
|
#include "dfa.h"
#include <vector>
#include <utility>
#include <memory>
#include <queue>
#include <numeric>
#include <algorithm>
DFA::DFA(const NFA& nfa)
{
using state_closure_pair = std::pair<State*, eps_closure_type>;
states.push_back(std::make_unique<State>());
auto q0 = nfa.eps_closure(nfa.start_state());
auto d0 = states.back().get();
auto p0 = make_pair(d0, q0);
head = d0;
std::vector<state_closure_pair> dfa;
dfa.push_back(p0);
std::queue<state_closure_pair> work_list;
work_list.push(p0);
while (!work_list.empty())
{
auto p = work_list.front();
auto d = p.first;
auto q = p.second;
// if the set that corresponds to the DFA state contains the accepting
// state of the NFA then the DFA state is an accepting state
if (q[nfa.accepting_state()]) tails.push_back(d);
work_list.pop();
for (auto c : nfa.alphabet())
{
auto states_count = nfa.states_count();
// iterate through each state from q and see if it has
// transition through character c.
// if it has, then compute the epsilon closure to the state
// that results from the transition.
auto delta = [&nfa, states_count](eps_closure_type closure, char c)
{
std::vector<int> states;
for (int i = 0; i < states_count; ++i)
{
if (!closure[i]) continue;
auto next_state = nfa.transition(i, c);
if (next_state != -1)
{
states.push_back(next_state);
}
}
return states;
};
// return a vector of epsilon closures for the given states
auto epsilon_closures = [&nfa](std::vector<int> states)
{
std::vector<eps_closure_type> closures;
for (auto state : states)
{
closures.push_back(nfa.eps_closure(state));
}
return closures;
};
// calculate the union of a set of closures
auto closures_union = [states_count]
(std::vector<eps_closure_type> closures)
{
return std::accumulate(
closures.begin(), closures.end(),
eps_closure_type(states_count),
[](eps_closure_type closure1, eps_closure_type closure2)
{
eps_closure_type result(closure1.size());
for (std::size_t i = 0; i < result.size(); ++i)
{
result[i] = closure1[i] | closure2[i];
}
return result;
});
};
auto t = closures_union(epsilon_closures(delta(q, c)));
// continue if all elements in t are false
if (std::all_of(t.begin(), t.end(), [](bool b) { return !b; }))
{
continue;
}
auto dd = std::find_if(dfa.begin(), dfa.end(),
[&t](state_closure_pair p)
{ return p.second == t; });
if (dd == dfa.end())
{
states.push_back(std::make_unique<State>());
auto new_state = states.back().get();
dfa.push_back(make_pair(new_state, t));
work_list.push(make_pair(new_state, t));
d->add_transition(new_state, c);
}
else
{
d->add_transition(dd->first, c);
}
}
}
for (std::size_t i = 0; i < states.size(); ++i)
{
states[i]->state_number = i;
}
}
|
Use overloaded == operator to compare vectors
|
Use overloaded == operator to compare vectors
|
C++
|
mit
|
ghallak/lexical-analyzer
|
bc48a024e1237735e10c8ce1239cd8e08e2f1c56
|
dht.cpp
|
dht.cpp
|
#include <boost/foreach.hpp>
#include <event.h>
#include "libcage/src/cage.hpp"
#include "ipc.h"
extern "C" {
#include "safe_assert.h"
}
#ifndef MAX
#define MAX(a,b) a>b ? a : b
#endif
static int sock;
static void
dht_on_joined(bool res) {
int len;
struct ipc_message msg = {};
msg.type = JOINED;
msg.joined.result = res;
len = send(sock, &msg, sizeof(msg), 0);
safe_assert_io(len, sizeof(msg), size_t);
}
class dht_get_callback
{
public:
void *m_user_data;
unsigned int m_app_id;
void operator() (bool result, libcage::dht::value_set_ptr vset) {
struct ipc_message msg = {};
ssize_t len;
char *buf;
libcage::dht::value_set::const_iterator it;
msg.type = RESULT;
msg.result.user_data = this->m_user_data;
msg.result.length = (vset && result) ? vset->size() : 0;
len = send(sock, &msg, sizeof(msg), 0);
safe_assert_io(len, sizeof(msg), size_t);
if (msg.result.length == 0)
return;
BOOST_FOREACH(const libcage::dht::value_t &val, *vset) {
size_t length;
buf = val.value.get();
length = val.len;
safe_assert(val.len > 0);
len = send(sock, &length, sizeof(length), 0);
safe_assert_io(len, sizeof(length), size_t);
len = send(sock, buf, val.len, 0);
safe_assert_io(len, val.len, int);
}
}
};
static size_t
construct_lookup_key(unsigned int app_id, char *key, size_t keylen,
unsigned int **buf)
{
size_t len;
len = sizeof(app_id) + keylen;
safe_assert(len > sizeof(app_id) && len > keylen);
*buf = (unsigned int *) safe_malloc(len);
(*buf)[0] = htonl(app_id);
memcpy(&((*buf)[1]), key, keylen);
return len;
}
static void
dht_get(libcage::cage *cage, unsigned int app_id, char *key, size_t keylen,
void *user_data)
{
size_t len;
unsigned int *buf;
dht_get_callback on_get_finished;
len = construct_lookup_key(app_id, key, keylen, &buf);
on_get_finished.m_user_data = user_data;
cage->get(buf, len, on_get_finished);
free(buf);
}
static void
dht_put(libcage::cage *cage, unsigned int app_id, char *key, size_t keylen,
char *value, int valuelen, int unsigned ttl)
{
int len;
unsigned int *buf;
len = construct_lookup_key(app_id, key, keylen, &buf);
cage->put(buf, len, value, valuelen, ttl);
free(buf);
}
static void
dht_send_node_list(std::list<libcage::cageaddr> const nodes) {
unsigned int max_host_len = MAX(INET6_ADDRSTRLEN, INET_ADDRSTRLEN);
char host[max_host_len];
std::list<libcage::cageaddr>::const_iterator it;
struct ipc_message msg = {};
unsigned short port;
libcage::in6_ptr in6;
libcage::in_ptr in4;
const char *res;
size_t length;
int len;
msg.type = NODE_LIST;
msg.node_list.length = nodes.size();
len = send(sock, &msg, sizeof(msg), 0);
safe_assert_io(len, sizeof(msg), size_t);
for (it = nodes.begin(); it != nodes.end(); it++) {
if (it->domain == PF_INET6) {
in6 = boost::get<libcage::in6_ptr>(it->saddr);
res = inet_ntop(it->domain, &(*in6), host, sizeof(host));
port = ntohs(in6->sin6_port);
}
else if (it->domain == PF_INET) {
in4 = boost::get<libcage::in_ptr>(it->saddr);
res = inet_ntop(it->domain, &(*in4), host, sizeof(host));
port = ntohs(in4->sin_port);
}
else
safe_assert(0==1 && "unknown addr domain");
safe_assert(res != NULL);
len = send(sock, &port, sizeof(port), 0);
safe_assert_io(len, sizeof(port), size_t);
length = strlen(host)+1;
len = send(sock, &length, sizeof(length), 0);
safe_assert_io(len, sizeof(length), size_t);
len = send(sock, host, length, 0);
safe_assert_io(len, sizeof(length), size_t);
}
}
static void
dht_on_ipc(int fd, short ev_type, void *user_data)
{
libcage::cage *cage = (libcage::cage *) user_data;
std::list<libcage::cageaddr> nodes;
struct ipc_message msg = {};
std::string str;
ssize_t len;
char *key;
char *host;
char *value;
char *id;
len = recv(fd, &msg, sizeof(msg), MSG_WAITALL);
safe_assert_io(len, sizeof(msg), size_t);
switch(msg.type) {
case JOIN:
// TODO: timer that retries to join every 60 sec if not connected.
host = (char *) safe_malloc(msg.join.hostlen);
len = recv(fd, host, msg.join.hostlen, MSG_WAITALL);
safe_assert_io(len, msg.join.hostlen, size_t);
cage->join(host, msg.join.port, dht_on_joined);
free(host);
break;
case GET:
key = (char *) safe_malloc(msg.get.keylen);
len = recv(fd, key, msg.get.keylen, MSG_WAITALL);
safe_assert_io(len, msg.get.keylen, size_t);
dht_get(cage, msg.get.app_id, key, msg.get.keylen, msg.get.user_data);
free(key);
break;
case PUT:
key = (char *) safe_malloc(msg.put.keylen);
value = (char *) safe_malloc(msg.put.valuelen);
len = recv(fd, key, msg.put.keylen, MSG_WAITALL);
safe_assert_io(len, msg.put.keylen, size_t);
len = recv(fd, value, msg.put.valuelen, MSG_WAITALL);
safe_assert_io(len, msg.put.valuelen, size_t);
dht_put(cage, msg.put.app_id,
key, msg.put.keylen,
value, msg.put.valuelen,
msg.put.ttl);
free(key);
free(value);
break;
case NODE_LIST:
nodes = cage->get_table();
dht_send_node_list(nodes);
// TODO: free nodes?
break;
case GET_NODE_ID:
id = (char *) cage->get_id_str().c_str();
msg.type = GET_NODE_ID;
msg.node_id.length = strlen(id)+1;
len = send(sock, &msg, sizeof(msg), 0);
safe_assert_io(len, sizeof(msg), size_t);
len = send(sock, id, msg.node_id.length, 0);
safe_assert_io(len, sizeof(msg.node_id.length), size_t);
break;
case SET_NODE_ID:
id = (char *) safe_malloc(msg.node_id.length);
len = recv(sock, id, msg.node_id.length, MSG_WAITALL);
safe_assert_io(len, sizeof(msg.node_id.length), size_t);
str = std::string(id, len);
cage->set_id_str(str);
free(id);
break;
case QUIT:
event_loopbreak();
break;
default:
safe_assert("should not be reached" && (1!=1));
break;
}
}
extern "C" int
dht_run(int socket, int port) {
sock = socket;
event_init();
/* setup dht */
libcage::cage *cage = new libcage::cage();
cage->set_global();
cage->open(AF_INET6, port);
/* setup ipc */
struct event ev = {};
event_set(&ev, sock, EV_READ | EV_PERSIST, dht_on_ipc, cage);
event_add(&ev, NULL);
event_dispatch();
return 0;
}
|
#include <boost/foreach.hpp>
#include <event.h>
#include "libcage/src/cage.hpp"
#include "ipc.h"
extern "C" {
#include "safe_assert.h"
}
#ifndef MAX
#define MAX(a,b) a>b ? a : b
#endif
static int sock;
static void
dht_on_joined(bool res) {
int len;
struct ipc_message msg = {};
msg.type = JOINED;
msg.joined.result = res;
len = send(sock, &msg, sizeof(msg), 0);
safe_assert_io(len, sizeof(msg), size_t);
}
class dht_get_callback
{
public:
dht_get_callback(void *user_data) : m_user_data(user_data) {}
void operator() (bool result, libcage::dht::value_set_ptr vset) {
struct ipc_message msg = {};
ssize_t len;
char *buf;
libcage::dht::value_set::const_iterator it;
msg.type = RESULT;
msg.result.user_data = this->m_user_data;
msg.result.length = (vset && result) ? vset->size() : 0;
len = send(sock, &msg, sizeof(msg), 0);
safe_assert_io(len, sizeof(msg), size_t);
if (msg.result.length == 0)
return;
BOOST_FOREACH(const libcage::dht::value_t &val, *vset) {
size_t length;
buf = val.value.get();
length = val.len;
safe_assert(val.len > 0);
len = send(sock, &length, sizeof(length), 0);
safe_assert_io(len, sizeof(length), size_t);
len = send(sock, buf, val.len, 0);
safe_assert_io(len, val.len, int);
}
}
protected:
void *m_user_data;
};
static size_t
construct_lookup_key(unsigned int app_id, char *key, size_t keylen,
unsigned int **buf)
{
size_t len;
len = sizeof(app_id) + keylen;
safe_assert(len > sizeof(app_id) && len > keylen);
*buf = (unsigned int *) safe_malloc(len);
(*buf)[0] = htonl(app_id);
memcpy(&((*buf)[1]), key, keylen);
return len;
}
static void
dht_get(libcage::cage *cage, unsigned int app_id, char *key, size_t keylen,
void *user_data)
{
size_t len;
unsigned int *buf;
dht_get_callback on_get_finished(user_data);
len = construct_lookup_key(app_id, key, keylen, &buf);
cage->get(buf, len, on_get_finished);
free(buf);
}
static void
dht_put(libcage::cage *cage, unsigned int app_id, char *key, size_t keylen,
char *value, int valuelen, int unsigned ttl)
{
int len;
unsigned int *buf;
len = construct_lookup_key(app_id, key, keylen, &buf);
cage->put(buf, len, value, valuelen, ttl);
free(buf);
}
static void
dht_send_node_list(std::list<libcage::cageaddr> const nodes) {
unsigned int max_host_len = MAX(INET6_ADDRSTRLEN, INET_ADDRSTRLEN);
char host[max_host_len];
std::list<libcage::cageaddr>::const_iterator it;
struct ipc_message msg = {};
unsigned short port;
libcage::in6_ptr in6;
libcage::in_ptr in4;
const char *res;
size_t length;
int len;
msg.type = NODE_LIST;
msg.node_list.length = nodes.size();
len = send(sock, &msg, sizeof(msg), 0);
safe_assert_io(len, sizeof(msg), size_t);
for (it = nodes.begin(); it != nodes.end(); it++) {
if (it->domain == PF_INET6) {
in6 = boost::get<libcage::in6_ptr>(it->saddr);
res = inet_ntop(it->domain, &(*in6), host, sizeof(host));
port = ntohs(in6->sin6_port);
}
else if (it->domain == PF_INET) {
in4 = boost::get<libcage::in_ptr>(it->saddr);
res = inet_ntop(it->domain, &(*in4), host, sizeof(host));
port = ntohs(in4->sin_port);
}
else
safe_assert(0==1 && "unknown addr domain");
safe_assert(res != NULL);
len = send(sock, &port, sizeof(port), 0);
safe_assert_io(len, sizeof(port), size_t);
length = strlen(host)+1;
len = send(sock, &length, sizeof(length), 0);
safe_assert_io(len, sizeof(length), size_t);
len = send(sock, host, length, 0);
safe_assert_io(len, sizeof(length), size_t);
}
}
static void
dht_on_ipc(int fd, short ev_type, void *user_data)
{
libcage::cage *cage = (libcage::cage *) user_data;
std::list<libcage::cageaddr> nodes;
struct ipc_message msg = {};
std::string str;
ssize_t len;
char *key;
char *host;
char *value;
char *id;
len = recv(fd, &msg, sizeof(msg), MSG_WAITALL);
safe_assert_io(len, sizeof(msg), size_t);
switch(msg.type) {
case JOIN:
// TODO: timer that retries to join every 60 sec if not connected.
host = (char *) safe_malloc(msg.join.hostlen);
len = recv(fd, host, msg.join.hostlen, MSG_WAITALL);
safe_assert_io(len, msg.join.hostlen, size_t);
cage->join(host, msg.join.port, dht_on_joined);
free(host);
break;
case GET:
key = (char *) safe_malloc(msg.get.keylen);
len = recv(fd, key, msg.get.keylen, MSG_WAITALL);
safe_assert_io(len, msg.get.keylen, size_t);
dht_get(cage, msg.get.app_id, key, msg.get.keylen, msg.get.user_data);
free(key);
break;
case PUT:
key = (char *) safe_malloc(msg.put.keylen);
value = (char *) safe_malloc(msg.put.valuelen);
len = recv(fd, key, msg.put.keylen, MSG_WAITALL);
safe_assert_io(len, msg.put.keylen, size_t);
len = recv(fd, value, msg.put.valuelen, MSG_WAITALL);
safe_assert_io(len, msg.put.valuelen, size_t);
dht_put(cage, msg.put.app_id,
key, msg.put.keylen,
value, msg.put.valuelen,
msg.put.ttl);
free(key);
free(value);
break;
case NODE_LIST:
nodes = cage->get_table();
dht_send_node_list(nodes);
// TODO: free nodes?
break;
case GET_NODE_ID:
id = (char *) cage->get_id_str().c_str();
msg.type = GET_NODE_ID;
msg.node_id.length = strlen(id)+1;
len = send(sock, &msg, sizeof(msg), 0);
safe_assert_io(len, sizeof(msg), size_t);
len = send(sock, id, msg.node_id.length, 0);
safe_assert_io(len, sizeof(msg.node_id.length), size_t);
break;
case SET_NODE_ID:
id = (char *) safe_malloc(msg.node_id.length);
len = recv(sock, id, msg.node_id.length, MSG_WAITALL);
safe_assert_io(len, sizeof(msg.node_id.length), size_t);
str = std::string(id, len);
cage->set_id_str(str);
free(id);
break;
case QUIT:
event_loopbreak();
break;
default:
safe_assert("should not be reached" && (1!=1));
break;
}
}
extern "C" int
dht_run(int socket, int port) {
sock = socket;
event_init();
/* setup dht */
libcage::cage *cage = new libcage::cage();
cage->set_global();
cage->open(AF_INET6, port);
/* setup ipc */
struct event ev = {};
event_set(&ev, sock, EV_READ | EV_PERSIST, dht_on_ipc, cage);
event_add(&ev, NULL);
event_dispatch();
return 0;
}
|
Introduce constructor for dht_get_callback
|
Introduce constructor for dht_get_callback
|
C++
|
bsd-3-clause
|
manuels/lunadht,manuels/lunadht,manuels/lunadht
|
5a6e8c2435c40c5e5a677383a32de4668f14450f
|
loader/src/etl_image.cpp
|
loader/src/etl_image.cpp
|
#include "etl_image.hpp"
using namespace std;
using namespace nervana;
void image::params::dump(ostream & ostr)
{
ostr << "Angle: " << setw(3) << angle << " ";
ostr << "Flip: " << flip << " ";
ostr << "Lighting: ";
for_each (lighting.begin(), lighting.end(), [&ostr](float &l) {ostr << l << " ";});
ostr << "Photometric: ";
for_each (photometric.begin(), photometric.end(), [&ostr](float &p) {ostr << p << " ";});
ostr << "\n" << "Crop Box: " << cropbox << "\n";
}
/* Extract */
image::extractor::extractor(shared_ptr<const image::config> cfg)
{
if (!(cfg->channels == 1 || cfg->channels == 3))
{
std::stringstream ss;
ss << "Unsupported number of channels in image: " << cfg->channels;
throw std::runtime_error(ss.str());
} else {
_pixel_type = cfg->channels == 1 ? CV_8UC1 : CV_8UC3;
_color_mode = cfg->channels == 1 ? CV_LOAD_IMAGE_GRAYSCALE : CV_LOAD_IMAGE_COLOR;
}
}
shared_ptr<image::decoded> image::extractor::extract(const char* inbuf, int insize)
{
cv::Mat output_img;
// It is bad to cast away const, but opencv does not support a const Mat
// The Mat is only used for imdecode on the next line so it is OK here
cv::Mat input_img(1, insize, _pixel_type, const_cast<char*>(inbuf));
cv::imdecode(input_img, _color_mode, &output_img);
auto rc = make_shared<image::decoded>();
rc->add(output_img); // don't need to check return for single image
return rc;
}
/* Transform:
image::config will be a supplied bunch of params used by this provider.
on each record, the transformer will use the config along with the supplied
record to fill a transform_params structure which will have
Spatial distortion params:
randomly sampled crop box (based on params->center, params->aspect_ratio, params->scale_pct, record size)
randomly determined flip (based on params->flip)
randomly sampled rotation angle (based on params->angle)
Photometric distortion params:
randomly sampled contrast, brightness, saturation, lighting values (based on params->cbs, lighting bounds)
*/
image::transformer::transformer(shared_ptr<const image::config>) :
_CPCA{{0.39731118, 0.70119634, -0.59200296},
{-0.81698062, -0.02354167, -0.5761844},
{0.41795513, -0.71257945, -0.56351045}},
CPCA(3, 3, CV_32FC1, (float*)_CPCA),
CSTD(3, 1, CV_32FC1, {19.72083305, 37.09388853, 121.78006099}),
GSCL(3, 1, CV_32FC1, {0.114, 0.587, 0.299})
{
}
shared_ptr<image::decoded> image::transformer::transform(
shared_ptr<image::params> img_xform,
shared_ptr<image::decoded> img)
{
vector<cv::Mat> finalImageList;
for(int i=0; i<img->get_image_count(); i++) {
cv::Mat rotatedImage;
rotate(img->get_image(i), rotatedImage, img_xform->angle);
cv::Mat croppedImage = rotatedImage(img_xform->cropbox);
cv::Mat resizedImage;
image::resize(croppedImage, resizedImage, img_xform->output_size);
cbsjitter(resizedImage, img_xform->photometric);
lighting(resizedImage, img_xform->lighting, img_xform->color_noise_std);
cv::Mat *finalImage = &resizedImage;
cv::Mat flippedImage;
if (img_xform->flip) {
cv::flip(resizedImage, flippedImage, 1);
finalImage = &flippedImage;
}
finalImageList.push_back(*finalImage);
}
auto rc = make_shared<image::decoded>();
if(rc->add(finalImageList) == false) {
rc = nullptr;
}
return rc;
}
void image::transformer::rotate(const cv::Mat& input, cv::Mat& output, int angle)
{
if (angle == 0) {
output = input;
} else {
cv::Point2i pt(input.cols / 2, input.rows / 2);
cv::Mat rot = cv::getRotationMatrix2D(pt, angle, 1.0);
cv::warpAffine(input, output, rot, input.size());
}
}
void image::resize(const cv::Mat& input, cv::Mat& output, const cv::Size2i& size)
{
if (size == input.size()) {
output = input;
} else {
int inter = input.size().area() < size.area() ? CV_INTER_CUBIC : CV_INTER_AREA;
cv::resize(input, output, size, 0, 0, inter);
}
}
/*
Implements colorspace noise perturbation as described in:
Krizhevsky et. al., "ImageNet Classification with Deep Convolutional Neural Networks"
Constructs a random coloring pixel that is uniformly added to every pixel of the image.
lighting is filled with normally distributed values prior to calling this function.
*/
void image::transformer::lighting(cv::Mat& inout, vector<float> lighting, float color_noise_std)
{
// Skip transformations if given deterministic settings
if (lighting.size() > 0) {
cv::Mat alphas(3, 1, CV_32FC1, lighting.data());
alphas = (CPCA * CSTD.mul(alphas)); // this is the random coloring pixel
auto pixel = alphas.reshape(3, 1).at<cv::Scalar_<float>>(0, 0);
inout = (inout + pixel) / (1.0 + color_noise_std);
}
}
/*
Implements contrast, brightness, and saturation jittering using the following definitions:
Contrast: Add some multiple of the grayscale mean of the image.
Brightness: Magnify the intensity of each pixel by photometric[1]
Saturation: Add some multiple of the pixel's grayscale value to itself.
photometric is filled with uniformly distributed values prior to calling this function
*/
// adjusts contrast, brightness, and saturation according
// to values in photometric[0], photometric[1], photometric[2], respectively
void image::transformer::cbsjitter(cv::Mat& inout, const vector<float>& photometric)
{
// Skip transformations if given deterministic settings
if (photometric.size() > 0) {
/****************************
* BRIGHTNESS & SATURATION *
*****************************/
cv::Mat satmtx = photometric[1] * (photometric[2] * cv::Mat::eye(3, 3, CV_32FC1) +
(1 - photometric[2]) * cv::Mat::ones(3, 1, CV_32FC1) * GSCL.t());
cv::transform(inout, inout, satmtx);
/*************
* CONTRAST *
**************/
cv::Mat gray_mean;
cv::cvtColor(cv::Mat(1, 1, CV_32FC3, cv::mean(inout)), gray_mean, CV_BGR2GRAY);
inout = photometric[0] * inout + (1 - photometric[0]) * gray_mean.at<cv::Scalar_<float>>(0, 0);
}
}
shared_ptr<image::params>
image::param_factory::make_params(shared_ptr<const decoded> input)
{
auto imgstgs = shared_ptr<image::params>(new image::params());
imgstgs->output_size = cv::Size2i(_cfg->width, _cfg->height);
imgstgs->angle = _cfg->angle(_dre);
imgstgs->flip = _cfg->flip(_dre);
cv::Size2f in_size = input->get_image_size();
float scale = _cfg->scale(_dre);
float aspect_ratio = _cfg->aspect_ratio(_dre);
scale_cropbox(in_size, imgstgs->cropbox, aspect_ratio, scale);
float c_off_x = _cfg->crop_offset(_dre);
float c_off_y = _cfg->crop_offset(_dre);
shift_cropbox(in_size, imgstgs->cropbox, c_off_x, c_off_y);
if (_cfg->lighting.stddev() != 0) {
for( int i=0; i<3; i++ ) {
imgstgs->lighting.push_back(_cfg->lighting(_dre));
}
imgstgs->color_noise_std = _cfg->lighting.stddev();
}
if (_cfg->photometric.a()!=_cfg->photometric.b()) {
for( int i=0; i<3; i++ ) {
imgstgs->photometric.push_back(_cfg->photometric(_dre));
}
}
return imgstgs;
}
void image::shift_cropbox(const cv::Size2f &in_size, cv::Rect &crop_box, float xoff, float yoff)
{
crop_box.x = (in_size.width - crop_box.width) * xoff;
crop_box.y = (in_size.height - crop_box.height) * yoff;
}
void image::param_factory::scale_cropbox(
const cv::Size2f &in_size,
cv::Rect &crop_box,
float tgt_aspect_ratio,
float tgt_scale )
{
float out_a_r = static_cast<float>(_cfg->width) / _cfg->height;
float in_a_r = in_size.width / in_size.height;
float crop_a_r = out_a_r * tgt_aspect_ratio;
if (_cfg->do_area_scale) {
// Area scaling -- use pctge of original area subject to aspect ratio constraints
float max_scale = in_a_r > crop_a_r ? crop_a_r / in_a_r : in_a_r / crop_a_r;
float tgt_area = std::min(tgt_scale, max_scale) * in_size.area();
crop_box.height = sqrt(tgt_area / crop_a_r);
crop_box.width = crop_box.height * crop_a_r;
} else {
// Linear scaling -- make the long crop box side the scale pct of the short orig side
float short_side = std::min(in_size.width, in_size.height);
if (crop_a_r < 1) { // long side is height
crop_box.height = tgt_scale * short_side;
crop_box.width = crop_box.height * crop_a_r;
} else {
crop_box.width = tgt_scale * short_side;
crop_box.height = crop_box.width / crop_a_r;
}
}
}
shared_ptr<image::decoded> multicrop::transformer::transform(
shared_ptr<image::params> unused,
shared_ptr<image::decoded> input)
{
cv::Size2i in_size = input->get_image_size();
int short_side_in = std::min(in_size.width, in_size.height);
vector<cv::Rect> cropboxes;
// Get the positional crop boxes
for (const float &s: _cfg->scales) {
cv::Size2i boxdim(short_side_in * s, short_side_in * s);
cv::Size2i border = in_size - boxdim;
for (cv::Point2f &offset: _cfg->offsets) {
cv::Point2i corner(border);
corner.x *= offset.x;
corner.y *= offset.y;
cropboxes.push_back(cv::Rect(corner, boxdim));
}
}
auto out_imgs = make_shared<image::decoded>();
add_resized_crops(input->get_image(0), out_imgs, cropboxes);
if (_cfg->flip) {
cv::Mat input_img;
cv::flip(input->get_image(0), input_img, 1);
add_resized_crops(input_img, out_imgs, cropboxes);
}
return out_imgs;
}
void multicrop::transformer::add_resized_crops(
const cv::Mat& input,
shared_ptr<image::decoded> &out_img,
vector<cv::Rect> &cropboxes)
{
for (auto cropbox: cropboxes) {
cv::Mat img_out;
image::resize(input(cropbox), img_out, _cfg->output_size);
out_img->add(img_out);
}
}
image::loader::loader(shared_ptr<const image::config> cfg)
{
_channel_major = cfg->channel_major;
}
void image::loader::load(char* outbuf, int outsize, shared_ptr<image::decoded> input)
{
// for (int i=0; i<input->get_image_size(); i++ )
auto img = input->get_image(0);
int all_pixels = img.channels() * img.total();
if (all_pixels > outsize) {
throw std::runtime_error("Load failed - buffer too small");
}
if (_channel_major) {
this->split(img, outbuf);
} else {
memcpy(outbuf, img.data, all_pixels);
}
}
void image::loader::split(cv::Mat& img, char* buf)
{
int pix_per_channel = img.total();
int num_channels = img.channels();
if (num_channels == 1) {
memcpy(buf, img.data, pix_per_channel);
} else {
// Split into separate channels
cv::Size2i size = img.size();
cv::Mat b(size, CV_8U, buf);
cv::Mat g(size, CV_8U, buf + pix_per_channel);
cv::Mat r(size, CV_8U, buf + 2 * pix_per_channel);
cv::Mat channels[3] = {b, g, r};
cv::split(img, channels);
}
}
|
#include "etl_image.hpp"
using namespace std;
using namespace nervana;
void image::params::dump(ostream & ostr)
{
ostr << "Angle: " << setw(3) << angle << " ";
ostr << "Flip: " << flip << " ";
ostr << "Lighting: ";
for_each (lighting.begin(), lighting.end(), [&ostr](float &l) {ostr << l << " ";});
ostr << "Photometric: ";
for_each (photometric.begin(), photometric.end(), [&ostr](float &p) {ostr << p << " ";});
ostr << "\n" << "Crop Box: " << cropbox << "\n";
}
/* Extract */
image::extractor::extractor(shared_ptr<const image::config> cfg)
{
if (!(cfg->channels == 1 || cfg->channels == 3))
{
std::stringstream ss;
ss << "Unsupported number of channels in image: " << cfg->channels;
throw std::runtime_error(ss.str());
} else {
_pixel_type = cfg->channels == 1 ? CV_8UC1 : CV_8UC3;
_color_mode = cfg->channels == 1 ? CV_LOAD_IMAGE_GRAYSCALE : CV_LOAD_IMAGE_COLOR;
}
}
shared_ptr<image::decoded> image::extractor::extract(const char* inbuf, int insize)
{
cv::Mat output_img;
// It is bad to cast away const, but opencv does not support a const Mat
// The Mat is only used for imdecode on the next line so it is OK here
cv::Mat input_img(1, insize, _pixel_type, const_cast<char*>(inbuf));
cv::imdecode(input_img, _color_mode, &output_img);
auto rc = make_shared<image::decoded>();
rc->add(output_img); // don't need to check return for single image
return rc;
}
/* Transform:
image::config will be a supplied bunch of params used by this provider.
on each record, the transformer will use the config along with the supplied
record to fill a transform_params structure which will have
Spatial distortion params:
randomly sampled crop box (based on params->center, params->aspect_ratio, params->scale_pct, record size)
randomly determined flip (based on params->flip)
randomly sampled rotation angle (based on params->angle)
Photometric distortion params:
randomly sampled contrast, brightness, saturation, lighting values (based on params->cbs, lighting bounds)
*/
image::transformer::transformer(shared_ptr<const image::config>) :
_CPCA{{0.39731118, 0.70119634, -0.59200296},
{-0.81698062, -0.02354167, -0.5761844},
{0.41795513, -0.71257945, -0.56351045}},
CPCA(3, 3, CV_32FC1, (float*)_CPCA),
CSTD(3, 1, CV_32FC1, {19.72083305, 37.09388853, 121.78006099}),
GSCL(3, 1, CV_32FC1, {0.114, 0.587, 0.299})
{
}
shared_ptr<image::decoded> image::transformer::transform(
shared_ptr<image::params> img_xform,
shared_ptr<image::decoded> img)
{
vector<cv::Mat> finalImageList;
for(int i=0; i<img->get_image_count(); i++) {
cv::Mat rotatedImage;
rotate(img->get_image(i), rotatedImage, img_xform->angle);
cv::Mat croppedImage = rotatedImage(img_xform->cropbox);
cv::Mat resizedImage;
image::resize(croppedImage, resizedImage, img_xform->output_size);
cbsjitter(resizedImage, img_xform->photometric);
lighting(resizedImage, img_xform->lighting, img_xform->color_noise_std);
cv::Mat *finalImage = &resizedImage;
cv::Mat flippedImage;
if (img_xform->flip) {
cv::flip(resizedImage, flippedImage, 1);
finalImage = &flippedImage;
}
finalImageList.push_back(*finalImage);
}
auto rc = make_shared<image::decoded>();
if(rc->add(finalImageList) == false) {
rc = nullptr;
}
return rc;
}
void image::transformer::rotate(const cv::Mat& input, cv::Mat& output, int angle)
{
if (angle == 0) {
output = input;
} else {
cv::Point2i pt(input.cols / 2, input.rows / 2);
cv::Mat rot = cv::getRotationMatrix2D(pt, angle, 1.0);
cv::warpAffine(input, output, rot, input.size());
}
}
void image::resize(const cv::Mat& input, cv::Mat& output, const cv::Size2i& size)
{
if (size == input.size()) {
output = input;
} else {
int inter = input.size().area() < size.area() ? CV_INTER_CUBIC : CV_INTER_AREA;
cv::resize(input, output, size, 0, 0, inter);
}
}
/*
Implements colorspace noise perturbation as described in:
Krizhevsky et. al., "ImageNet Classification with Deep Convolutional Neural Networks"
Constructs a random coloring pixel that is uniformly added to every pixel of the image.
lighting is filled with normally distributed values prior to calling this function.
*/
void image::transformer::lighting(cv::Mat& inout, vector<float> lighting, float color_noise_std)
{
// Skip transformations if given deterministic settings
if (lighting.size() > 0) {
cv::Mat alphas(3, 1, CV_32FC1, lighting.data());
alphas = (CPCA * CSTD.mul(alphas)); // this is the random coloring pixel
auto pixel = alphas.reshape(3, 1).at<cv::Scalar_<float>>(0, 0);
inout = (inout + pixel) / (1.0 + color_noise_std);
}
}
/*
Implements contrast, brightness, and saturation jittering using the following definitions:
Contrast: Add some multiple of the grayscale mean of the image.
Brightness: Magnify the intensity of each pixel by photometric[1]
Saturation: Add some multiple of the pixel's grayscale value to itself.
photometric is filled with uniformly distributed values prior to calling this function
*/
// adjusts contrast, brightness, and saturation according
// to values in photometric[0], photometric[1], photometric[2], respectively
void image::transformer::cbsjitter(cv::Mat& inout, const vector<float>& photometric)
{
// Skip transformations if given deterministic settings
if (photometric.size() > 0) {
/****************************
* BRIGHTNESS & SATURATION *
*****************************/
cv::Mat satmtx = photometric[1] * (photometric[2] * cv::Mat::eye(3, 3, CV_32FC1) +
(1 - photometric[2]) * cv::Mat::ones(3, 1, CV_32FC1) * GSCL.t());
cv::transform(inout, inout, satmtx);
/*************
* CONTRAST *
**************/
cv::Mat gray_mean;
cv::cvtColor(cv::Mat(1, 1, CV_32FC3, cv::mean(inout)), gray_mean, CV_BGR2GRAY);
inout = photometric[0] * inout + (1 - photometric[0]) * gray_mean.at<cv::Scalar_<float>>(0, 0);
}
}
shared_ptr<image::params>
image::param_factory::make_params(shared_ptr<const decoded> input)
{
auto imgstgs = shared_ptr<image::params>(new image::params());
imgstgs->output_size = cv::Size2i(_cfg->width, _cfg->height);
imgstgs->angle = _cfg->angle(_dre);
imgstgs->flip = _cfg->flip(_dre);
cv::Size2f in_size = input->get_image_size();
float scale = _cfg->scale(_dre);
float aspect_ratio = _cfg->aspect_ratio(_dre);
scale_cropbox(in_size, imgstgs->cropbox, aspect_ratio, scale);
float c_off_x = _cfg->crop_offset(_dre);
float c_off_y = _cfg->crop_offset(_dre);
shift_cropbox(in_size, imgstgs->cropbox, c_off_x, c_off_y);
if (_cfg->lighting.stddev() != 0) {
for( int i=0; i<3; i++ ) {
imgstgs->lighting.push_back(_cfg->lighting(_dre));
}
imgstgs->color_noise_std = _cfg->lighting.stddev();
}
if (_cfg->photometric.a()!=_cfg->photometric.b()) {
for( int i=0; i<3; i++ ) {
imgstgs->photometric.push_back(_cfg->photometric(_dre));
}
}
return imgstgs;
}
void image::shift_cropbox(const cv::Size2f &in_size, cv::Rect &crop_box, float xoff, float yoff)
{
crop_box.x = (in_size.width - crop_box.width) * xoff;
crop_box.y = (in_size.height - crop_box.height) * yoff;
}
void image::param_factory::scale_cropbox(
const cv::Size2f &in_size,
cv::Rect &crop_box,
float tgt_aspect_ratio,
float tgt_scale )
{
float out_a_r = static_cast<float>(_cfg->width) / _cfg->height;
float in_a_r = in_size.width / in_size.height;
float crop_a_r = out_a_r * tgt_aspect_ratio;
if (_cfg->do_area_scale) {
// Area scaling -- use pctge of original area subject to aspect ratio constraints
float max_scale = in_a_r > crop_a_r ? crop_a_r / in_a_r : in_a_r / crop_a_r;
float tgt_area = std::min(tgt_scale, max_scale) * in_size.area();
crop_box.height = sqrt(tgt_area / crop_a_r);
crop_box.width = crop_box.height * crop_a_r;
} else {
// Linear scaling -- make the long crop box side the scale pct of the short orig side
float short_side = std::min(in_size.width, in_size.height);
if (crop_a_r < 1) { // long side is height
crop_box.height = tgt_scale * short_side;
crop_box.width = crop_box.height * crop_a_r;
} else {
crop_box.width = tgt_scale * short_side;
crop_box.height = crop_box.width / crop_a_r;
}
}
}
shared_ptr<image::decoded> multicrop::transformer::transform(
shared_ptr<image::params> unused,
shared_ptr<image::decoded> input)
{
cv::Size2i in_size = input->get_image_size();
int short_side_in = std::min(in_size.width, in_size.height);
vector<cv::Rect> cropboxes;
// Get the positional crop boxes
for (const float &s: _cfg->scales) {
cv::Size2i boxdim(short_side_in * s, short_side_in * s);
cv::Size2i border = in_size - boxdim;
for (cv::Point2f &offset: _cfg->offsets) {
cv::Point2i corner(border);
corner.x *= offset.x;
corner.y *= offset.y;
cropboxes.push_back(cv::Rect(corner, boxdim));
}
}
auto out_imgs = make_shared<image::decoded>();
add_resized_crops(input->get_image(0), out_imgs, cropboxes);
if (_cfg->flip) {
cv::Mat input_img;
cv::flip(input->get_image(0), input_img, 1);
add_resized_crops(input_img, out_imgs, cropboxes);
}
return out_imgs;
}
void multicrop::transformer::add_resized_crops(
const cv::Mat& input,
shared_ptr<image::decoded> &out_img,
vector<cv::Rect> &cropboxes)
{
for (auto cropbox: cropboxes) {
cv::Mat img_out;
image::resize(input(cropbox), img_out, _cfg->output_size);
out_img->add(img_out);
}
}
image::loader::loader(shared_ptr<const image::config> cfg)
{
_channel_major = cfg->channel_major;
}
void image::loader::load(char* outbuf, int outsize, shared_ptr<image::decoded> input)
{
if(input->get_size() > outsize) {
throw std::runtime_error("Load failed insize > outsize");
}
auto img = input->get_image(0);
int image_size = img.channels() * img.total();
for (int i=0; i < input->get_image_count(); i++) {
auto outbuf_i = outbuf + (i * image_size);
if (_channel_major) {
this->split(img, outbuf_i);
} else {
memcpy(outbuf_i, img.data, image_size);
}
}
}
void image::loader::split(cv::Mat& img, char* buf)
{
// split `img` into individual channels so that buf is in c
int pix_per_channel = img.total();
int num_channels = img.channels();
if (num_channels == 1) {
memcpy(buf, img.data, pix_per_channel);
} else {
// Split into separate channels
cv::Size2i size = img.size();
cv::Mat b(size, CV_8U, buf);
cv::Mat g(size, CV_8U, buf + pix_per_channel);
cv::Mat r(size, CV_8U, buf + 2 * pix_per_channel);
cv::Mat channels[3] = {b, g, r};
cv::split(img, channels);
}
}
|
add support in image::loader for multiple images
|
add support in image::loader for multiple images
|
C++
|
apache-2.0
|
NervanaSystems/aeon,NervanaSystems/aeon,NervanaSystems/aeon,NervanaSystems/aeon
|
c8eefebef629e0c5a87e2230fbd255cca98cc8b6
|
stoc/source/bootstrap/services.cxx
|
stoc/source/bootstrap/services.cxx
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_stoc.hxx"
#include "bootstrapservices.hxx"
#include "cppuhelper/factory.hxx"
#include "cppuhelper/implementationentry.hxx"
#include "sal/types.h"
#include "uno/environment.h"
#include "uno/lbnames.h"
#include <stdio.h>
using namespace com::sun::star;
using namespace com::sun::star::uno;
using namespace cppu;
using namespace osl;
extern rtl_StandardModuleCount g_moduleCount;
using namespace stoc_bootstrap;
static struct ImplementationEntry g_entries[] =
{
//servicemanager
{
OServiceManager_CreateInstance, smgr_getImplementationName,
smgr_getSupportedServiceNames, createSingleComponentFactory,
&g_moduleCount.modCnt , 0
},
{
ORegistryServiceManager_CreateInstance, regsmgr_getImplementationName,
regsmgr_getSupportedServiceNames, createSingleComponentFactory,
&g_moduleCount.modCnt , 0
},
{
OServiceManagerWrapper_CreateInstance, smgr_wrapper_getImplementationName,
smgr_wrapper_getSupportedServiceNames, createSingleComponentFactory,
&g_moduleCount.modCnt , 0
},
//security
{
ac_create, ac_getImplementationName,
ac_getSupportedServiceNames, createSingleComponentFactory,
&g_moduleCount.modCnt, 0
},
{
filepolicy_create, filepolicy_getImplementationName,
filepolicy_getSupportedServiceNames, createSingleComponentFactory,
&g_moduleCount.modCnt, 0
},
//simpleregistry
{
SimpleRegistry_CreateInstance, simreg_getImplementationName,
simreg_getSupportedServiceNames, createSingleComponentFactory,
&g_moduleCount.modCnt , 0
},
//defaultregistry
{
NestedRegistry_CreateInstance, defreg_getImplementationName,
defreg_getSupportedServiceNames, createSingleComponentFactory,
&g_moduleCount.modCnt , 0
},
//implementationregistry
{
ImplementationRegistration_CreateInstance, impreg_getImplementationName,
impreg_getSupportedServiceNames, createSingleComponentFactory,
&g_moduleCount.modCnt , 0
},
//loader
{
DllComponentLoader_CreateInstance, loader_getImplementationName,
loader_getSupportedServiceNames, createSingleComponentFactory,
&g_moduleCount.modCnt , 0
},
//registry_tdprovider
{
ProviderImpl_create, rdbtdp_getImplementationName,
rdbtdp_getSupportedServiceNames, createSingleComponentFactory,
&g_moduleCount.modCnt , 0
},
//tdmanager
{
ManagerImpl_create, tdmgr_getImplementationName,
tdmgr_getSupportedServiceNames, createSingleComponentFactory,
&g_moduleCount.modCnt , 0
},
//end
{ 0, 0, 0, 0, 0, 0 }
};
extern "C"
{
sal_Bool SAL_CALL component_canUnload( TimeValue *pTime )
{
return g_moduleCount.canUnload( &g_moduleCount , pTime );
}
//==================================================================================================
SAL_DLLPUBLIC_EXPORT void * SAL_CALL component_getFactory(
const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey )
{
return component_getFactoryHelper( pImplName, pServiceManager, pRegistryKey , g_entries );
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_stoc.hxx"
#include "bootstrapservices.hxx"
#include "cppuhelper/factory.hxx"
#include "cppuhelper/implementationentry.hxx"
#include "sal/types.h"
#include "uno/environment.h"
#include "uno/lbnames.h"
#include <stdio.h>
using namespace com::sun::star;
using namespace com::sun::star::uno;
using namespace cppu;
using namespace osl;
extern rtl_StandardModuleCount g_moduleCount;
using namespace stoc_bootstrap;
static struct ImplementationEntry g_entries[] =
{
//servicemanager
{
OServiceManager_CreateInstance, smgr_getImplementationName,
smgr_getSupportedServiceNames, createSingleComponentFactory,
&g_moduleCount.modCnt , 0
},
{
ORegistryServiceManager_CreateInstance, regsmgr_getImplementationName,
regsmgr_getSupportedServiceNames, createSingleComponentFactory,
&g_moduleCount.modCnt , 0
},
{
OServiceManagerWrapper_CreateInstance, smgr_wrapper_getImplementationName,
smgr_wrapper_getSupportedServiceNames, createSingleComponentFactory,
&g_moduleCount.modCnt , 0
},
//security
{
ac_create, ac_getImplementationName,
ac_getSupportedServiceNames, createSingleComponentFactory,
&g_moduleCount.modCnt, 0
},
{
filepolicy_create, filepolicy_getImplementationName,
filepolicy_getSupportedServiceNames, createSingleComponentFactory,
&g_moduleCount.modCnt, 0
},
//simpleregistry
{
SimpleRegistry_CreateInstance, simreg_getImplementationName,
simreg_getSupportedServiceNames, createSingleComponentFactory,
&g_moduleCount.modCnt , 0
},
//defaultregistry
{
NestedRegistry_CreateInstance, defreg_getImplementationName,
defreg_getSupportedServiceNames, createSingleComponentFactory,
&g_moduleCount.modCnt , 0
},
//implementationregistry
{
ImplementationRegistration_CreateInstance, impreg_getImplementationName,
impreg_getSupportedServiceNames, createSingleComponentFactory,
&g_moduleCount.modCnt , 0
},
//loader
{
DllComponentLoader_CreateInstance, loader_getImplementationName,
loader_getSupportedServiceNames, createSingleComponentFactory,
&g_moduleCount.modCnt , 0
},
//registry_tdprovider
{
ProviderImpl_create, rdbtdp_getImplementationName,
rdbtdp_getSupportedServiceNames, createSingleComponentFactory,
&g_moduleCount.modCnt , 0
},
//tdmanager
{
ManagerImpl_create, tdmgr_getImplementationName,
tdmgr_getSupportedServiceNames, createSingleComponentFactory,
&g_moduleCount.modCnt , 0
},
//end
{ 0, 0, 0, 0, 0, 0 }
};
extern "C"
{
#ifndef IOS
sal_Bool SAL_CALL component_canUnload( TimeValue *pTime )
{
return g_moduleCount.canUnload( &g_moduleCount , pTime );
}
#endif
#ifdef IOS
#define component_getFactory bootstrap_component_getFactory
#endif
//==================================================================================================
SAL_DLLPUBLIC_EXPORT void * SAL_CALL component_getFactory(
const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey )
{
return component_getFactoryHelper( pImplName, pServiceManager, pRegistryKey , g_entries );
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
Use prefixed getFactory and no canUnload on iOS
|
Use prefixed getFactory and no canUnload on iOS
|
C++
|
mpl-2.0
|
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
|
066158e5c1384b23067c79a7144e25e3eecbc0da
|
src/AssimpWorker/model/Folder.cpp
|
src/AssimpWorker/model/Folder.cpp
|
/*
* This file is part of ATLAS. It is subject to the license terms in
* the LICENSE file found in the top-level directory of this distribution.
* (Also avialable at http://www.apache.org/licenses/LICENSE-2.0.txt)
* You may not use this file except in compliance with the License.
*/
#include <atlas/model/Folder.hpp>
#include <boost/bind.hpp>
#include <boost/mem_fn.hpp>
namespace ATLAS {
namespace Model {
Folder::Folder(BlobHolder& blobHolder, const std::string& type) :
blobHolder(blobHolder),
type(type)
{
return;
}
// If this were pure C++11, we'd use =default; in the header,
// but silly MSVC wants the default move constructor spelled out.
Folder::Folder(Folder&& folder) :
blobHolder(folder.blobHolder),
name(std::move(folder.name)),
type(std::move(folder.type)),
blobs(std::move(folder.blobs)),
attributes(std::move(folder.attributes)),
childFolders(std::move(folder.childFolders))
{
}
Folder& Folder::operator=(Folder&& other) {
if (type != other.type) {
// must not assign different types of folders.
throw std::exception();
}
blobHolder = other.blobHolder;
name = std::move(other.name);
blobs = std::move(other.blobs);
attributes = std::move(other.attributes);
childFolders = std::move(other.childFolders);
return *this;
}
Folder::~Folder(){
return;
}
const std::string& Folder::getName() const{
return name;
}
void Folder::setName(const std::string& newName){
name = newName;
}
const std::string& Folder::getType() const{
return type;
}
Folder& Folder::appendChild(const std::string& type){
Folder newFolder(blobHolder, type);
childFolders.push_back(std::move(newFolder));
return childFolders.back();
}
const std::vector<Folder>& Folder::getChildren() const{
return childFolders;
}
void Folder::removeAttribute(std::string key){
attributes.erase(key);
}
std::vector<Folder>& Folder::getChildren(){
return childFolders;
}
Blob* Folder::getBlobByType(const std::string& type){
for (auto type_and_hash : blobs){
if (type_and_hash.first == type) {
return &(blobHolder.getBlob(type_and_hash.second));
}
}
return NULL;
}
void Folder::addBlob(const std::string& type, Blob& blob){
std::string hash = blob.getHash();
if (!blobHolder.hasBlob(hash)){
blobHolder.addBlob(blob);
}
blobs.erase(type); // Re-adding a blob should overwrite it
blobs.insert(std::pair<std::string, std::string>(type,hash));
}
bool Folder::hasChildren() const{
return !childFolders.empty();
}
void Folder::addAttribute(const std::string& key, const std::string& value) {
attributes.insert(std::pair<std::string, std::string>(key, value));
}
std::string Folder::getAttribute(const std::string& key) {
auto valueIterator = attributes.find(key);
if (valueIterator != attributes.end()) {
return valueIterator->second;
}
else {
return "ATTRIBUTE_NOT_FOUND";
}
}
std::map<std::string, std::string>& Folder::getAttributes(){
return attributes;
}
const std::map<std::string, std::string>& Folder::getAttributes() const{
return attributes;
}
Folder::iterator Folder::begin() {
return blobs.begin();
}
Folder::iterator Folder::end() {
return blobs.end();
}
Folder::const_iterator Folder::begin() const{
return blobs.begin();
}
Folder::const_iterator Folder::end() const{
return blobs.end();
}
}
}
|
/*
* This file is part of ATLAS. It is subject to the license terms in
* the LICENSE file found in the top-level directory of this distribution.
* (Also avialable at http://www.apache.org/licenses/LICENSE-2.0.txt)
* You may not use this file except in compliance with the License.
*/
#include <atlas/model/Folder.hpp>
#include <boost/bind.hpp>
#include <boost/mem_fn.hpp>
namespace ATLAS {
namespace Model {
Folder::Folder(BlobHolder& blobHolder, const std::string& type) :
blobHolder(blobHolder),
type(type)
{
return;
}
// If this were pure C++11, we'd use =default; in the header,
// but silly MSVC wants the default move constructor spelled out.
Folder::Folder(Folder&& folder) :
blobHolder(folder.blobHolder),
name(std::move(folder.name)),
type(std::move(folder.type)),
blobs(std::move(folder.blobs)),
attributes(std::move(folder.attributes)),
childFolders(std::move(folder.childFolders))
{
}
Folder& Folder::operator=(Folder&& other) {
if (type != other.type) {
// must not assign different types of folders.
throw std::exception();
}
blobHolder = other.blobHolder;
name = std::move(other.name);
blobs = std::move(other.blobs);
attributes = std::move(other.attributes);
childFolders = std::move(other.childFolders);
return *this;
}
Folder::~Folder(){
return;
}
const std::string& Folder::getName() const{
return name;
}
void Folder::setName(const std::string& newName){
name = newName;
}
const std::string& Folder::getType() const{
return type;
}
Folder& Folder::appendChild(const std::string& type){
Folder newFolder(blobHolder, type);
childFolders.push_back(std::move(newFolder));
return childFolders.back();
}
const std::vector<Folder>& Folder::getChildren() const{
return childFolders;
}
void Folder::removeAttribute(std::string key){
attributes.erase(key);
}
std::vector<Folder>& Folder::getChildren(){
return childFolders;
}
Blob* Folder::getBlobByType(const std::string& type){
for (auto type_and_hash : blobs){
if (type_and_hash.first == type) {
return &(blobHolder.getBlob(type_and_hash.second));
}
}
return NULL;
}
void Folder::addBlob(const std::string& type, Blob& blob){
std::string hash = blob.getHash();
if (!blobHolder.hasBlob(hash)){
blobHolder.addBlob(blob);
} else {
blob.cleanup();
}
blobs.erase(type); // Re-adding a blob should overwrite it
blobs.insert(std::pair<std::string, std::string>(type,hash));
}
bool Folder::hasChildren() const{
return !childFolders.empty();
}
void Folder::addAttribute(const std::string& key, const std::string& value) {
attributes.insert(std::pair<std::string, std::string>(key, value));
}
std::string Folder::getAttribute(const std::string& key) {
auto valueIterator = attributes.find(key);
if (valueIterator != attributes.end()) {
return valueIterator->second;
}
else {
return "ATTRIBUTE_NOT_FOUND";
}
}
std::map<std::string, std::string>& Folder::getAttributes(){
return attributes;
}
const std::map<std::string, std::string>& Folder::getAttributes() const{
return attributes;
}
Folder::iterator Folder::begin() {
return blobs.begin();
}
Folder::iterator Folder::end() {
return blobs.end();
}
Folder::const_iterator Folder::begin() const{
return blobs.begin();
}
Folder::const_iterator Folder::end() const{
return blobs.end();
}
}
}
|
Fix memory leak: clean-up blobs that do not end up within the blobholder
|
Fix memory leak: clean-up blobs that do not end up within the blobholder
|
C++
|
apache-2.0
|
dfki-asr/atlas-worker,dfki-asr/atlas-worker
|
f134dc096006b055bf0d4835e6dd6788dce912c6
|
src/BatchEncoderWorkerContext.cpp
|
src/BatchEncoderWorkerContext.cpp
|
// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "StdAfx.h"
#include "BatchEncoder.h"
#include "BatchEncoderWorkerContext.h"
void CBatchEncoderWorkerContext::Init()
{
this->timer.Start();
pDlg->m_Progress.SetPos(0);
}
void CBatchEncoderWorkerContext::Next(int nItemId)
{
this->nProcessedFiles++;
this->nErrors = (this->nProcessedFiles - 1) - this->nDoneWithoutError;
if (this->nThreadCount == 1)
{
CString szText;
szText.Format(_T("Processing item %d of %d (%d Done, %d %s)"),
this->nProcessedFiles,
this->nTotalFiles,
this->nDoneWithoutError,
this->nErrors,
((this->nErrors == 0) || (this->nErrors > 1)) ? _T("Errors") : _T("Error"));
pDlg->m_StatusBar.SetText(szText, 1, 0);
this->nLastItemId = nItemId;
pDlg->m_LstInputItems.EnsureVisible(nItemId, FALSE);
}
}
void CBatchEncoderWorkerContext::Done()
{
this->timer.Stop();
this->nErrors = this->nProcessedFiles - this->nDoneWithoutError;
CString szText;
szText.Format(_T("Converted %d of %d (%d Done, %d %s) in %s"),
this->nProcessedFiles,
this->nTotalFiles,
this->nDoneWithoutError,
this->nErrors,
((this->nErrors == 0) || (this->nErrors > 1)) ? _T("Errors") : _T("Error"),
::FormatTime(this->timer.ElapsedTime(), 3));
pDlg->m_StatusBar.SetText(szText, 1, 0);
pDlg->FinishConvert();
}
bool CBatchEncoderWorkerContext::Callback(int nItemId, int nProgress, bool bFinished, bool bError)
{
if (bError == true)
{
if (pDlg->pWorkerContext->pConfig->m_Options.bStopOnErrors == true)
{
pDlg->m_Progress.SetPos(0);
this->bRunning = false;
}
return this->bRunning;
}
if (bFinished == false)
{
CString szProgress;
szProgress.Format(_T("%d%%\0"), nProgress);
pDlg->m_LstInputItems.SetItemText(nItemId, ITEM_COLUMN_STATUS, szProgress); // Status
pDlg->pWorkerContext->nProgess[nItemId] = nProgress;
static volatile bool bSafeCheck = false;
if (bSafeCheck == false)
{
bSafeCheck = true;
if (nItemId > this->nLastItemId)
{
this->nLastItemId = nItemId;
pDlg->m_LstInputItems.EnsureVisible(nItemId, FALSE);
}
int nTotalProgress = 0;
int nItems = pDlg->pWorkerContext->pConfig->m_Items.GetSize();
for (int i = 0; i < nItems; i++)
{
if (pDlg->pWorkerContext->pConfig->m_Items.GetData(i).bChecked == TRUE)
nTotalProgress += pDlg->pWorkerContext->nProgess[i];
}
int nPos = nTotalProgress / pDlg->pWorkerContext->nTotalFiles;
if (pDlg->m_Progress.GetPos() != nPos)
{
pDlg->m_Progress.SetPos(nPos);
}
bSafeCheck = false;
}
}
return this->bRunning;
}
void CBatchEncoderWorkerContext::Status(int nItemId, CString szTime, CString szStatus)
{
pDlg->m_LstInputItems.SetItemText(nItemId, ITEM_COLUMN_TIME, szTime); // Time
pDlg->m_LstInputItems.SetItemText(nItemId, ITEM_COLUMN_STATUS, szStatus); // Status
};
|
// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "StdAfx.h"
#include "BatchEncoder.h"
#include "utilities\Utilities.h"
#include "BatchEncoderWorkerContext.h"
void CBatchEncoderWorkerContext::Init()
{
this->timer.Start();
pDlg->m_Progress.SetPos(0);
}
void CBatchEncoderWorkerContext::Next(int nItemId)
{
this->nProcessedFiles++;
this->nErrors = (this->nProcessedFiles - 1) - this->nDoneWithoutError;
if (this->nThreadCount == 1)
{
CString szText;
szText.Format(_T("Processing item %d of %d (%d Done, %d %s)"),
this->nProcessedFiles,
this->nTotalFiles,
this->nDoneWithoutError,
this->nErrors,
((this->nErrors == 0) || (this->nErrors > 1)) ? _T("Errors") : _T("Error"));
pDlg->m_StatusBar.SetText(szText, 1, 0);
this->nLastItemId = nItemId;
pDlg->m_LstInputItems.EnsureVisible(nItemId, FALSE);
}
}
void CBatchEncoderWorkerContext::Done()
{
this->timer.Stop();
this->nErrors = this->nProcessedFiles - this->nDoneWithoutError;
CString szText;
szText.Format(_T("Converted %d of %d (%d Done, %d %s) in %s"),
this->nProcessedFiles,
this->nTotalFiles,
this->nDoneWithoutError,
this->nErrors,
((this->nErrors == 0) || (this->nErrors > 1)) ? _T("Errors") : _T("Error"),
::FormatTime(this->timer.ElapsedTime(), 3));
pDlg->m_StatusBar.SetText(szText, 1, 0);
pDlg->FinishConvert();
}
bool CBatchEncoderWorkerContext::Callback(int nItemId, int nProgress, bool bFinished, bool bError)
{
if (bError == true)
{
if (pDlg->pWorkerContext->pConfig->m_Options.bStopOnErrors == true)
{
pDlg->m_Progress.SetPos(0);
this->bRunning = false;
}
return this->bRunning;
}
if (bFinished == false)
{
CString szProgress;
szProgress.Format(_T("%d%%\0"), nProgress);
pDlg->m_LstInputItems.SetItemText(nItemId, ITEM_COLUMN_STATUS, szProgress); // Status
pDlg->pWorkerContext->nProgess[nItemId] = nProgress;
static volatile bool bSafeCheck = false;
if (bSafeCheck == false)
{
bSafeCheck = true;
if (nItemId > this->nLastItemId)
{
this->nLastItemId = nItemId;
pDlg->m_LstInputItems.EnsureVisible(nItemId, FALSE);
}
int nTotalProgress = 0;
int nItems = pDlg->pWorkerContext->pConfig->m_Items.GetSize();
for (int i = 0; i < nItems; i++)
{
if (pDlg->pWorkerContext->pConfig->m_Items.GetData(i).bChecked == TRUE)
nTotalProgress += pDlg->pWorkerContext->nProgess[i];
}
int nPos = nTotalProgress / pDlg->pWorkerContext->nTotalFiles;
if (pDlg->m_Progress.GetPos() != nPos)
{
pDlg->m_Progress.SetPos(nPos);
}
bSafeCheck = false;
}
}
return this->bRunning;
}
void CBatchEncoderWorkerContext::Status(int nItemId, CString szTime, CString szStatus)
{
pDlg->m_LstInputItems.SetItemText(nItemId, ITEM_COLUMN_TIME, szTime); // Time
pDlg->m_LstInputItems.SetItemText(nItemId, ITEM_COLUMN_STATUS, szStatus); // Status
};
|
Update BatchEncoderWorkerContext.cpp
|
Update BatchEncoderWorkerContext.cpp
|
C++
|
mit
|
wieslawsoltes/BatchEncoder,wieslawsoltes/BatchEncoder,wieslawsoltes/BatchEncoder,wieslawsoltes/BatchEncoder
|
dea5f1db77d0c5bd04d9706bccf2f29594adc4e0
|
basics/session.hpp
|
basics/session.hpp
|
#ifndef SESSION_HPP_
#define SESSION_HPP_
#include <iostream>
class Session {
public:
static Session* GetNewSession() {
if (session) {
Session * tmp = session;
session = NULL;
delete tmp;
}
session = new Session();
return session;
}
static Session* GetSession() {
if (!session) {
session = new Session();
}
return session;
}
~Session() {
if (session) {
delete session;
session = NULL;
}
}
bool gpu;
unsigned device;
private:
Session():gpu(false), device(0) {}
static Session* session;
};
Session* Session::session = NULL;
#endif // SESSION_HPP_
|
#ifndef SESSION_HPP_
#define SESSION_HPP_
#include <iostream>
class Session {
public:
static Session* GetNewSession() {
if (session) {
Session * tmp = session;
session = NULL;
delete tmp;
}
session = new Session();
return session;
}
static Session* GetSession() {
if (!session) {
session = new Session();
}
return session;
}
~Session() {
if (session) {
delete session;
session = NULL;
}
}
bool gpu;
unsigned device;
size_t batch_size;
private:
Session():gpu(false), device(0), batch_size(1) {}
static Session* session;
};
Session* Session::session = NULL;
#endif // SESSION_HPP_
|
add batch-size to session
|
add batch-size to session
|
C++
|
mit
|
stormmax/Teaism,stormmax/Teaism,stormmax/Teaism,stormmax/Teaism
|
906d52117f5dedeac3b74a4b23cf97f6462bcfcc
|
src/qtquick/PeruseConfig.cpp
|
src/qtquick/PeruseConfig.cpp
|
/*
* Copyright (C) 2016 Dan Leinir Turthra Jensen <[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) version 3, or any
* later version accepted by the membership of KDE e.V. (or its
* successor approved by the membership of KDE e.V.), which shall
* act as a proxy defined in Section 6 of version 3 of the license.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "PeruseConfig.h"
#include <KFileMetaData/UserMetaData>
#include <KConfig>
#include <KConfigGroup>
#include <QTimer>
#include <QFile>
class PeruseConfig::Private
{
public:
Private()
: config("peruserc")
{};
KConfig config;
};
PeruseConfig::PeruseConfig(QObject* parent)
: QObject(parent)
, d(new Private)
{
QStringList locations = d->config.group("general").readEntry("book locations", QStringList());
if(locations.count() < 1)
{
locations = QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation);
locations << QStandardPaths::standardLocations(QStandardPaths::DownloadLocation);
locations << QString("%1/comics").arg(QStandardPaths::standardLocations(QStandardPaths::GenericDataLocation).first());
d->config.group("general").writeEntry("book locations", locations);
d->config.sync();
}
}
PeruseConfig::~PeruseConfig()
{
delete d;
}
void PeruseConfig::bookOpened(QString path)
{
QStringList recent = recentlyOpened();
int i = recent.indexOf(path);
if(i == 0)
{
// This is already first, don't do work we don't need to, because that's just silly
return;
}
else
{
recent.removeAll(path);
recent.prepend(path);
}
d->config.group("general").writeEntry("recently opened", recent);
d->config.sync();
emit recentlyOpenedChanged();
}
QStringList PeruseConfig::recentlyOpened() const
{
QStringList recent = d->config.group("general").readEntry("recently opened", QStringList());
QStringList actualRecent;
while(recent.count() > 0) {
QString current = recent.takeFirst();
if(QFile::exists(current)) {
actualRecent.append(current);
}
}
return actualRecent;
}
void PeruseConfig::addBookLocation(const QString& location)
{
if(location.startsWith("file://"))
{
#ifdef Q_OS_WIN
QString newLocation = location.mid(8);
#else
QString newLocation = location.mid(7);
#endif
QStringList locations = bookLocations();
// First, get rid of all the entries which start with the newly added location, because that's silly
QStringList newLocations;
bool alreadyInThere = false;
Q_FOREACH(QString entry, locations) {
if(!entry.startsWith(newLocation))
{
newLocations.append(entry);
}
if(newLocation.startsWith(entry))
{
alreadyInThere = true;
}
}
if(alreadyInThere)
{
// Don't be silly, don't add a new location if it's already covered by something more high level...
emit showMessage("Attempted to add a new location to the list of search folders which is a sub-folder to something already in the list.");
return;
}
newLocations.append(newLocation);
d->config.group("general").writeEntry("book locations", newLocations);
d->config.sync();
emit bookLocationsChanged();
}
}
void PeruseConfig::removeBookLocation(const QString& location)
{
QStringList locations = bookLocations();
locations.removeAll(location);
d->config.group("general").writeEntry("book locations", locations);
d->config.sync();
QTimer::singleShot(100, this, SIGNAL(bookLocationsChanged()));
}
QStringList PeruseConfig::bookLocations() const
{
QStringList locations = d->config.group("general").readEntry("book locations", QStringList());
return locations;
}
QString PeruseConfig::newstuffLocation() const
{
QString knsrc = QStandardPaths::locate(QStandardPaths::GenericConfigLocation, "peruse.knsrc");
if(qEnvironmentVariableIsSet("APPDIR"))
{
// Because appimage install happens into /app/usr...
knsrc = knsrc.prepend("/usr").prepend(qgetenv("APPDIR"));
}
return knsrc;
}
QString PeruseConfig::homeDir() const
{
return QStandardPaths::standardLocations(QStandardPaths::HomeLocation).first();
}
void PeruseConfig::setFilesystemProperty(QString fileName, QString propertyName, QString value)
{
KFileMetaData::UserMetaData data(fileName);
if (propertyName == "rating") {
data.setRating(value.toInt());
} else if (propertyName == "tags") {
data.setTags(value.split(","));
} else if (propertyName == "comment") {
data.setUserComment(value);
} else {
data.setAttribute(QString("peruse.").append(propertyName), value);
}
}
QString PeruseConfig::getFilesystemProperty(QString fileName, QString propertyName)
{
QString value;
KFileMetaData::UserMetaData data(fileName);
if (propertyName == "rating") {
value = QString::number(data.rating());
} else if (propertyName == "tags") {
value = data.tags().join(",");
} else if (propertyName == "comment") {
value = data.userComment();
} else {
value = data.attribute(QString("peruse.").append(propertyName));
}
return value;
}
|
/*
* Copyright (C) 2016 Dan Leinir Turthra Jensen <[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) version 3, or any
* later version accepted by the membership of KDE e.V. (or its
* successor approved by the membership of KDE e.V.), which shall
* act as a proxy defined in Section 6 of version 3 of the license.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "PeruseConfig.h"
#include <KFileMetaData/UserMetaData>
#include <KConfig>
#include <KConfigGroup>
#include <KNSCore/Engine>
#include <QTimer>
#include <QFile>
class PeruseConfig::Private
{
public:
Private()
: config("peruserc")
{};
KConfig config;
};
PeruseConfig::PeruseConfig(QObject* parent)
: QObject(parent)
, d(new Private)
{
QStringList locations = d->config.group("general").readEntry("book locations", QStringList());
if(locations.count() < 1)
{
locations = QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation);
locations << QStandardPaths::standardLocations(QStandardPaths::DownloadLocation);
locations << QString("%1/comics").arg(QStandardPaths::standardLocations(QStandardPaths::GenericDataLocation).first());
d->config.group("general").writeEntry("book locations", locations);
d->config.sync();
}
}
PeruseConfig::~PeruseConfig()
{
delete d;
}
void PeruseConfig::bookOpened(QString path)
{
QStringList recent = recentlyOpened();
int i = recent.indexOf(path);
if(i == 0)
{
// This is already first, don't do work we don't need to, because that's just silly
return;
}
else
{
recent.removeAll(path);
recent.prepend(path);
}
d->config.group("general").writeEntry("recently opened", recent);
d->config.sync();
emit recentlyOpenedChanged();
}
QStringList PeruseConfig::recentlyOpened() const
{
QStringList recent = d->config.group("general").readEntry("recently opened", QStringList());
QStringList actualRecent;
while(recent.count() > 0) {
QString current = recent.takeFirst();
if(QFile::exists(current)) {
actualRecent.append(current);
}
}
return actualRecent;
}
void PeruseConfig::addBookLocation(const QString& location)
{
if(location.startsWith("file://"))
{
#ifdef Q_OS_WIN
QString newLocation = location.mid(8);
#else
QString newLocation = location.mid(7);
#endif
QStringList locations = bookLocations();
// First, get rid of all the entries which start with the newly added location, because that's silly
QStringList newLocations;
bool alreadyInThere = false;
Q_FOREACH(QString entry, locations) {
if(!entry.startsWith(newLocation))
{
newLocations.append(entry);
}
if(newLocation.startsWith(entry))
{
alreadyInThere = true;
}
}
if(alreadyInThere)
{
// Don't be silly, don't add a new location if it's already covered by something more high level...
emit showMessage("Attempted to add a new location to the list of search folders which is a sub-folder to something already in the list.");
return;
}
newLocations.append(newLocation);
d->config.group("general").writeEntry("book locations", newLocations);
d->config.sync();
emit bookLocationsChanged();
}
}
void PeruseConfig::removeBookLocation(const QString& location)
{
QStringList locations = bookLocations();
locations.removeAll(location);
d->config.group("general").writeEntry("book locations", locations);
d->config.sync();
QTimer::singleShot(100, this, SIGNAL(bookLocationsChanged()));
}
QStringList PeruseConfig::bookLocations() const
{
QStringList locations = d->config.group("general").readEntry("book locations", QStringList());
return locations;
}
QString PeruseConfig::newstuffLocation() const
{
const QStringList locations = KNSCore::Engine::configSearchLocations();
QString knsrc;
for (const QString& location : locations) {
knsrc = QString::fromLocal8Bit("%1/peruse.knsrc").arg(location);
if (QFile().exists()) {
break;
}
}
if(qEnvironmentVariableIsSet("APPDIR"))
{
// Because appimage install happens into /app/usr...
knsrc = knsrc.prepend("/usr").prepend(qgetenv("APPDIR"));
}
return knsrc;
}
QString PeruseConfig::homeDir() const
{
return QStandardPaths::standardLocations(QStandardPaths::HomeLocation).first();
}
void PeruseConfig::setFilesystemProperty(QString fileName, QString propertyName, QString value)
{
KFileMetaData::UserMetaData data(fileName);
if (propertyName == "rating") {
data.setRating(value.toInt());
} else if (propertyName == "tags") {
data.setTags(value.split(","));
} else if (propertyName == "comment") {
data.setUserComment(value);
} else {
data.setAttribute(QString("peruse.").append(propertyName), value);
}
}
QString PeruseConfig::getFilesystemProperty(QString fileName, QString propertyName)
{
QString value;
KFileMetaData::UserMetaData data(fileName);
if (propertyName == "rating") {
value = QString::number(data.rating());
} else if (propertyName == "tags") {
value = data.tags().join(",");
} else if (propertyName == "comment") {
value = data.userComment();
} else {
value = data.attribute(QString("peruse.").append(propertyName));
}
return value;
}
|
Use the new KNSCore config location bits
|
Use the new KNSCore config location bits
|
C++
|
lgpl-2.1
|
KDE/peruse,KDE/peruse,KDE/peruse
|
2a7addcfa6059ea8d75bd15f7da359bd80811112
|
src/Interface/Application/Note.cc
|
src/Interface/Application/Note.cc
|
/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2015 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <iostream>
#include <stdexcept>
#include <Interface/qt_include.h>
#include <Core/Logging/Log.h>
#include <Interface/Application/Note.h>
#include <Interface/Application/HasNotes.h>
#include <Interface/Application/NoteEditor.h>
#include <Interface/Application/MainWindowCollaborators.h>
using namespace SCIRun::Gui;
using namespace SCIRun::Core::Logging;
HasNotes::HasNotes(const std::string& name, bool positionAdjustable) :
noteEditor_(QString::fromStdString(name), positionAdjustable, 0),
destroyed_(false)
{
noteEditor_.setStyleSheet(scirunStylesheet());
}
HasNotes::~HasNotes()
{
destroy();
}
void HasNotes::destroy()
{
if (!destroyed_)
{
destroyed_ = true;
}
}
void HasNotes::connectNoteEditorToAction(QAction* action)
{
QObject::connect(action, SIGNAL(triggered()), ¬eEditor_, SLOT(show()));
QObject::connect(action, SIGNAL(triggered()), ¬eEditor_, SLOT(raise()));
}
void HasNotes::connectUpdateNote(QObject* obj)
{
QObject::connect(¬eEditor_, SIGNAL(noteChanged(const Note&)), obj, SLOT(updateNote(const Note&)));
QObject::connect(¬eEditor_, SIGNAL(noteChanged(const Note&)), obj, SIGNAL(noteChanged()));
}
void HasNotes::setCurrentNote(const Note& note, bool updateEditor)
{
currentNote_ = note;
if (updateEditor)
{
noteEditor_.setNoteHtml(note.html_);
noteEditor_.setNoteFontSize(note.fontSize_);
}
}
void HasNotes::setDefaultNoteFontSize(int size)
{
noteEditor_.setDefaultNoteFontSize(size);
}
NoteDisplayHelper::NoteDisplayHelper(NoteDisplayStrategyPtr display) :
networkObjectWithNote_(nullptr), scene_(nullptr), note_(nullptr),
notePosition_(NotePosition::Default),
defaultNotePosition_(NotePosition::Top), //TODO
displayStrategy_(display),
destroyed_(false)
{
}
NoteDisplayHelper::~NoteDisplayHelper()
{
destroy();
}
void NoteDisplayHelper::destroy()
{
if (!destroyed_)
{
if (note_ && scene_)
{
scene_->removeItem(note_);
}
delete note_;
destroyed_ = true;
}
}
void NoteDisplayHelper::updateNoteImpl(const Note& note)
{
if (!note_)
{
setNoteGraphicsContext();
if (!scene_)
logWarning("Scene not set, network notes will not be displayed.");
#ifdef QT5_BUILD
note_ = new QGraphicsTextItem("");
#else
note_ = new QGraphicsTextItem("", nullptr, scene_);
#endif
note_->setDefaultTextColor(Qt::white);
}
note_->setHtml(note.html_);
notePosition_ = note.position_;
updateNotePosition();
note_->setZValue(networkObjectWithNote_->zValue() - 1);
}
void NoteDisplayHelper::clearNoteCursor()
{
if (note_)
{
auto cur = note_->textCursor();
cur.clearSelection();
note_->setTextCursor(cur);
}
}
QPointF NoteDisplayHelper::relativeNotePosition()
{
if (note_ && networkObjectWithNote_)
{
auto position = notePosition_ == NotePosition::Default ? defaultNotePosition_ : notePosition_;
note_->setVisible(!(NotePosition::Tooltip == position || NotePosition::None == position));
networkObjectWithNote_->setToolTip("");
return displayStrategy_->relativeNotePosition(networkObjectWithNote_, note_, position);
}
return QPointF();
}
void NoteDisplayHelper::setDefaultNotePositionImpl(NotePosition position)
{
defaultNotePosition_ = position;
updateNotePosition();
}
void NoteDisplayHelper::setDefaultNoteSizeImpl(int size)
{
defaultNoteFontSize_ = size;
}
void NoteDisplayHelper::updateNotePosition()
{
if (note_ && networkObjectWithNote_)
{
auto position = positioner_->currentPosition() + relativeNotePosition();
note_->setPos(position);
}
}
Note NoteDisplayHelper::currentNote() const
{
if (note_)
return Note(note_->toHtml(), note_->toPlainText(), note_->font().pointSizeF(), notePosition_);
return Note();
}
|
/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2015 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <iostream>
#include <stdexcept>
#include <Interface/qt_include.h>
#include <Core/Logging/Log.h>
#include <Interface/Application/Note.h>
#include <Interface/Application/HasNotes.h>
#include <Interface/Application/NoteEditor.h>
#include <Interface/Application/MainWindowCollaborators.h>
using namespace SCIRun::Gui;
using namespace SCIRun::Core::Logging;
HasNotes::HasNotes(const std::string& name, bool positionAdjustable) :
noteEditor_(QString::fromStdString(name), positionAdjustable, 0),
destroyed_(false)
{
noteEditor_.setStyleSheet(scirunStylesheet());
}
HasNotes::~HasNotes()
{
destroy();
}
void HasNotes::destroy()
{
if (!destroyed_)
{
destroyed_ = true;
}
}
void HasNotes::connectNoteEditorToAction(QAction* action)
{
QObject::connect(action, SIGNAL(triggered()), ¬eEditor_, SLOT(show()));
QObject::connect(action, SIGNAL(triggered()), ¬eEditor_, SLOT(raise()));
}
void HasNotes::connectUpdateNote(QObject* obj)
{
QObject::connect(¬eEditor_, SIGNAL(noteChanged(const Note&)), obj, SLOT(updateNote(const Note&)));
QObject::connect(¬eEditor_, SIGNAL(noteChanged(const Note&)), obj, SIGNAL(noteChanged()));
}
void HasNotes::setCurrentNote(const Note& note, bool updateEditor)
{
currentNote_ = note;
if (updateEditor)
{
noteEditor_.setNoteHtml(note.html_);
noteEditor_.setNoteFontSize(note.fontSize_);
}
}
void HasNotes::setDefaultNoteFontSize(int size)
{
noteEditor_.setDefaultNoteFontSize(size);
}
NoteDisplayHelper::NoteDisplayHelper(NoteDisplayStrategyPtr display) :
networkObjectWithNote_(nullptr), scene_(nullptr), note_(nullptr),
notePosition_(NotePosition::Default),
defaultNotePosition_(NotePosition::Top), //TODO
displayStrategy_(display),
destroyed_(false)
{
}
NoteDisplayHelper::~NoteDisplayHelper()
{
destroy();
}
void NoteDisplayHelper::destroy()
{
if (!destroyed_)
{
if (note_ && scene_)
{
scene_->removeItem(note_);
}
delete note_;
destroyed_ = true;
}
}
void NoteDisplayHelper::updateNoteImpl(const Note& note)
{
if (!note_)
{
setNoteGraphicsContext();
if (!scene_)
logWarning("Scene not set, network notes will not be displayed.");
#ifdef QT5_BUILD
note_ = new QGraphicsTextItem("");
scene_->addItem(note_);
#else
note_ = new QGraphicsTextItem("", nullptr, scene_);
#endif
note_->setDefaultTextColor(Qt::white);
}
note_->setHtml(note.html_);
notePosition_ = note.position_;
updateNotePosition();
note_->setZValue(networkObjectWithNote_->zValue() - 1);
}
void NoteDisplayHelper::clearNoteCursor()
{
if (note_)
{
auto cur = note_->textCursor();
cur.clearSelection();
note_->setTextCursor(cur);
}
}
QPointF NoteDisplayHelper::relativeNotePosition()
{
if (note_ && networkObjectWithNote_)
{
auto position = notePosition_ == NotePosition::Default ? defaultNotePosition_ : notePosition_;
note_->setVisible(!(NotePosition::Tooltip == position || NotePosition::None == position));
networkObjectWithNote_->setToolTip("");
return displayStrategy_->relativeNotePosition(networkObjectWithNote_, note_, position);
}
return QPointF();
}
void NoteDisplayHelper::setDefaultNotePositionImpl(NotePosition position)
{
defaultNotePosition_ = position;
updateNotePosition();
}
void NoteDisplayHelper::setDefaultNoteSizeImpl(int size)
{
defaultNoteFontSize_ = size;
}
void NoteDisplayHelper::updateNotePosition()
{
if (note_ && networkObjectWithNote_)
{
auto position = positioner_->currentPosition() + relativeNotePosition();
note_->setPos(position);
}
}
Note NoteDisplayHelper::currentNote() const
{
if (note_)
return Note(note_->toHtml(), note_->toPlainText(), note_->font().pointSizeF(), notePosition_);
return Note();
}
|
Fix notes in Qt5
|
Fix notes in Qt5
|
C++
|
mit
|
jessdtate/SCIRun,moritzdannhauer/SCIRunGUIPrototype,jessdtate/SCIRun,moritzdannhauer/SCIRunGUIPrototype,jessdtate/SCIRun,moritzdannhauer/SCIRunGUIPrototype,moritzdannhauer/SCIRunGUIPrototype,jessdtate/SCIRun,moritzdannhauer/SCIRunGUIPrototype,jessdtate/SCIRun,jessdtate/SCIRun,jessdtate/SCIRun,moritzdannhauer/SCIRunGUIPrototype,moritzdannhauer/SCIRunGUIPrototype,jessdtate/SCIRun
|
b7888ccd27f86aa601fc95c04ac4c0512ec88f93
|
src/realm/util/terminate.cpp
|
src/realm/util/terminate.cpp
|
/*************************************************************************
*
* Copyright 2016 Realm 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 <realm/util/terminate.hpp>
#include <iostream>
#include <sstream>
#include <realm/util/features.h>
#include <realm/util/thread.hpp>
#if REALM_PLATFORM_APPLE
#if REALM_APPLE_OS_LOG
#include <os/log.h>
#else
#include <asl.h>
#endif
#include <dlfcn.h>
#include <execinfo.h>
#include <CoreFoundation/CoreFoundation.h>
#endif
#if REALM_ANDROID
#include <android/log.h>
#endif
// extern "C" and noinline so that a readable message shows up in the stack trace
// of the crash
// prototype here to silence warning
extern "C" REALM_NORETURN REALM_NOINLINE void please_report_this_error_to_help_at_realm_dot_io();
// LCOV_EXCL_START
extern "C" REALM_NORETURN REALM_NOINLINE void please_report_this_error_to_help_at_realm_dot_io()
{
std::abort();
}
// LCOV_EXCL_STOP
namespace {
#if REALM_PLATFORM_APPLE
void nslog(const char* message) noexcept
{
// Standard error goes nowhere for applications managed by launchd,
// so log to ASL/unified logging system logs as well.
fputs(message, stderr);
#if REALM_APPLE_OS_LOG
// The unified logging system considers dynamic strings to be private in
// order to protect users. This means we must specify "%{public}s" to get
// the message here. See `man os_log` for more details.
os_log_error(OS_LOG_DEFAULT, "%{public}s", message);
#else
asl_log(nullptr, nullptr, ASL_LEVEL_ERR, "%s", message);
#endif
// Log the message to Crashlytics if it's loaded into the process
void* addr = dlsym(RTLD_DEFAULT, "CLSLog");
if (addr) {
CFStringRef str =
CFStringCreateWithCStringNoCopy(kCFAllocatorDefault, message, kCFStringEncodingUTF8, kCFAllocatorNull);
auto fn = reinterpret_cast<void (*)(CFStringRef, ...)>(reinterpret_cast<size_t>(addr));
fn(CFSTR("%@"), str);
CFRelease(str);
}
}
void (*termination_notification_callback)(const char*) noexcept = nslog;
#elif REALM_ANDROID
void android_log(const char* message) noexcept
{
__android_log_write(ANDROID_LOG_ERROR, "REALM", message);
}
void (*termination_notification_callback)(const char*) noexcept = android_log;
#else
void (*termination_notification_callback)(const char*) noexcept = nullptr;
#endif
} // unnamed namespace
namespace realm {
namespace util {
// LCOV_EXCL_START
REALM_NORETURN static void terminate_internal(std::stringstream& ss) noexcept
{
#if REALM_PLATFORM_APPLE
void* callstack[128];
int frames = backtrace(callstack, 128);
char** strs = backtrace_symbols(callstack, frames);
for (int i = 0; i < frames; ++i) {
ss << strs[i] << '\n';
}
free(strs);
#endif
ss << "IMPORTANT: if you see this error, please send this log to [email protected].";
#ifdef REALM_DEBUG
std::cerr << ss.rdbuf() << '\n';
std::string thread_name;
if (Thread::get_name(thread_name))
std::cerr << "Thread name: " << thread_name << "\n";
#endif
if (termination_notification_callback) {
termination_notification_callback(ss.str().c_str());
}
please_report_this_error_to_help_at_realm_dot_io();
}
REALM_NORETURN void terminate(const char* message, const char* file, long line) noexcept
{
std::stringstream ss;
ss << file << ":" << line << ": " REALM_VER_CHUNK " " << message << '\n';
terminate_internal(ss);
}
REALM_NORETURN void terminate(const char* message, const char* file, long line,
std::initializer_list<Printable>&& values) noexcept
{
std::stringstream ss;
ss << file << ':' << line << ": " REALM_VER_CHUNK " " << message;
Printable::print_all(ss, values, false);
ss << '\n';
terminate_internal(ss);
}
REALM_NORETURN void terminate_with_info(const char* message, const char* file, long line,
const char* interesting_names,
std::initializer_list<Printable>&& values) noexcept
{
std::stringstream ss;
ss << file << ':' << line << ": " REALM_VER_CHUNK " " << message << " with " << interesting_names << " = ";
Printable::print_all(ss, values, true);
ss << '\n';
terminate_internal(ss);
}
// LCOV_EXCL_STOP
} // namespace util
} // namespace realm
|
/*************************************************************************
*
* Copyright 2016 Realm 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 <realm/util/terminate.hpp>
#include <iostream>
#include <sstream>
#include <realm/util/features.h>
#include <realm/util/thread.hpp>
#if REALM_PLATFORM_APPLE
#if REALM_APPLE_OS_LOG
#include <os/log.h>
#else
#include <asl.h>
#endif
#include <dlfcn.h>
#include <execinfo.h>
#include <CoreFoundation/CoreFoundation.h>
#endif
#if REALM_ANDROID
#include <android/log.h>
#endif
// extern "C" and noinline so that a readable message shows up in the stack trace
// of the crash
// prototype here to silence warning
extern "C" REALM_NORETURN REALM_NOINLINE void please_report_this_error_to_help_at_realm_dot_io();
// LCOV_EXCL_START
extern "C" REALM_NORETURN REALM_NOINLINE void please_report_this_error_to_help_at_realm_dot_io()
{
std::abort();
}
// LCOV_EXCL_STOP
namespace {
#if REALM_PLATFORM_APPLE
void nslog(const char* message) noexcept
{
// Standard error goes nowhere for applications managed by launchd,
// so log to ASL/unified logging system logs as well.
fputs(message, stderr);
#if REALM_APPLE_OS_LOG
// The unified logging system considers dynamic strings to be private in
// order to protect users. This means we must specify "%{public}s" to get
// the message here. See `man os_log` for more details.
os_log_error(OS_LOG_DEFAULT, "%{public}s", message);
#else
asl_log(nullptr, nullptr, ASL_LEVEL_ERR, "%s", message);
#endif
// Log the message to Crashlytics if it's loaded into the process
void* addr = dlsym(RTLD_DEFAULT, "CLSLog");
if (addr) {
CFStringRef str =
CFStringCreateWithCStringNoCopy(kCFAllocatorDefault, message, kCFStringEncodingUTF8, kCFAllocatorNull);
auto fn = reinterpret_cast<void (*)(CFStringRef, ...)>(reinterpret_cast<size_t>(addr));
fn(CFSTR("%@"), str);
CFRelease(str);
}
}
void (*termination_notification_callback)(const char*) noexcept = nslog;
#elif REALM_ANDROID
void android_log(const char* message) noexcept
{
__android_log_write(ANDROID_LOG_ERROR, "REALM", message);
}
void (*termination_notification_callback)(const char*) noexcept = android_log;
#else
void (*termination_notification_callback)(const char*) noexcept = nullptr;
#endif
} // unnamed namespace
namespace realm {
namespace util {
// LCOV_EXCL_START
REALM_NORETURN static void terminate_internal(std::stringstream& ss) noexcept
{
#if REALM_PLATFORM_APPLE
void* callstack[128];
int frames = backtrace(callstack, 128);
char** strs = backtrace_symbols(callstack, frames);
for (int i = 0; i < frames; ++i) {
ss << strs[i] << '\n';
}
free(strs);
#endif
ss << "IMPORTANT: if you see this error, please send this log and info about which version you are using and other relevant reproduction info to [email protected].";
#ifdef REALM_DEBUG
std::cerr << ss.rdbuf() << '\n';
std::string thread_name;
if (Thread::get_name(thread_name))
std::cerr << "Thread name: " << thread_name << "\n";
#endif
if (termination_notification_callback) {
termination_notification_callback(ss.str().c_str());
}
please_report_this_error_to_help_at_realm_dot_io();
}
REALM_NORETURN void terminate(const char* message, const char* file, long line) noexcept
{
std::stringstream ss;
ss << file << ":" << line << ": " REALM_VER_CHUNK " " << message << '\n';
terminate_internal(ss);
}
REALM_NORETURN void terminate(const char* message, const char* file, long line,
std::initializer_list<Printable>&& values) noexcept
{
std::stringstream ss;
ss << file << ':' << line << ": " REALM_VER_CHUNK " " << message;
Printable::print_all(ss, values, false);
ss << '\n';
terminate_internal(ss);
}
REALM_NORETURN void terminate_with_info(const char* message, const char* file, long line,
const char* interesting_names,
std::initializer_list<Printable>&& values) noexcept
{
std::stringstream ss;
ss << file << ':' << line << ": " REALM_VER_CHUNK " " << message << " with " << interesting_names << " = ";
Printable::print_all(ss, values, true);
ss << '\n';
terminate_internal(ss);
}
// LCOV_EXCL_STOP
} // namespace util
} // namespace realm
|
Update terminate.cpp
|
Update terminate.cpp
|
C++
|
apache-2.0
|
realm/realm-core,realm/realm-core,realm/realm-core,realm/realm-core,realm/realm-core,realm/realm-core,realm/realm-core
|
8dea059b1cad5e94da604f9ba91d14468172f106
|
chrome/browser/ui/views/ash/balloon_collection_impl_ash.cc
|
chrome/browser/ui/views/ash/balloon_collection_impl_ash.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/ui/views/ash/balloon_collection_impl_ash.h"
#include "ash/ash_switches.h"
#include "ash/shell.h"
#include "ash/system/status_area_widget.h"
#include "base/command_line.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/notifications/balloon.h"
#include "chrome/browser/notifications/desktop_notification_service.h"
#include "chrome/browser/notifications/desktop_notification_service_factory.h"
#include "chrome/browser/notifications/notification.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/chrome_pages.h"
#include "chrome/browser/ui/views/ash/balloon_view_ash.h"
#include "chrome/browser/ui/views/notifications/balloon_view_host.h"
#include "chrome/browser/ui/views/notifications/balloon_view_views.h"
namespace {
bool IsAshNotifyEnabled() {
return !CommandLine::ForCurrentProcess()->HasSwitch(
ash::switches::kAshNotifyDisabled);
}
} // namespace
BalloonCollectionImplAsh::BalloonCollectionImplAsh() {
if (IsAshNotifyEnabled()) {
ash::Shell::GetInstance()->status_area_widget()->
web_notification_tray()->SetDelegate(this);
}
}
BalloonCollectionImplAsh::~BalloonCollectionImplAsh() {
}
bool BalloonCollectionImplAsh::HasSpace() const {
if (!IsAshNotifyEnabled())
return BalloonCollectionImpl::HasSpace();
return true; // Overflow is handled by ash::WebNotificationTray.
}
void BalloonCollectionImplAsh::Add(const Notification& notification,
Profile* profile) {
if (IsAshNotifyEnabled()) {
if (notification.is_html())
return; // HTML notifications are not supported in Ash.
if (notification.title().empty() && notification.body().empty())
return; // Empty notification, don't show.
}
return BalloonCollectionImpl::Add(notification, profile);
}
void BalloonCollectionImplAsh::DisableExtension(
const std::string& notifcation_id) {
Balloon* balloon = base().FindBalloonById(notifcation_id);
const extensions::Extension* extension = GetBalloonExtension(balloon);
if (!extension)
return;
balloon->profile()->GetExtensionService()->DisableExtension(
extension->id(), extensions::Extension::DISABLE_USER_ACTION);
}
void BalloonCollectionImplAsh::DisableNotificationsFromSource(
const std::string& notifcation_id) {
Balloon* balloon = base().FindBalloonById(notifcation_id);
if (!balloon)
return;
DesktopNotificationService* service =
DesktopNotificationServiceFactory::GetForProfile(balloon->profile());
service->DenyPermission(balloon->notification().origin_url());
}
void BalloonCollectionImplAsh::NotificationRemoved(
const std::string& notifcation_id) {
RemoveById(notifcation_id);
}
void BalloonCollectionImplAsh::ShowSettings(const std::string& notifcation_id) {
Balloon* balloon = base().FindBalloonById(notifcation_id);
Profile* profile =
balloon ? balloon->profile() : ProfileManager::GetDefaultProfile();
Browser* browser = browser::FindOrCreateTabbedBrowser(profile);
if (GetBalloonExtension(balloon))
chrome::ShowExtensions(browser);
else
chrome::ShowContentSettings(browser, CONTENT_SETTINGS_TYPE_NOTIFICATIONS);
}
void BalloonCollectionImplAsh::OnClicked(const std::string& notifcation_id) {
Balloon* balloon = base().FindBalloonById(notifcation_id);
if (!balloon)
return;
balloon->OnClick();
}
bool BalloonCollectionImplAsh::AddWebUIMessageCallback(
const Notification& notification,
const std::string& message,
const chromeos::BalloonViewHost::MessageCallback& callback) {
#if defined(OS_CHROMEOS)
Balloon* balloon = base().FindBalloon(notification);
if (!balloon)
return false;
BalloonHost* balloon_host = balloon->balloon_view()->GetHost();
if (!balloon_host)
return false;
chromeos::BalloonViewHost* balloon_view_host =
static_cast<chromeos::BalloonViewHost*>(balloon_host);
return balloon_view_host->AddWebUIMessageCallback(message, callback);
#else
return false;
#endif
}
void BalloonCollectionImplAsh::AddSystemNotification(
const Notification& notification,
Profile* profile,
bool sticky) {
system_notifications_.insert(notification.notification_id());
// Add balloons to the front of the stack. This ensures that system
// notifications will always be displayed. NOTE: This has the side effect
// that system notifications are displayed in inverse order, with the most
// recent notification always at the front of the list.
AddImpl(notification, profile, true /* add to front*/);
}
bool BalloonCollectionImplAsh::UpdateNotification(
const Notification& notification) {
Balloon* balloon = base().FindBalloon(notification);
if (!balloon)
return false;
balloon->Update(notification);
return true;
}
bool BalloonCollectionImplAsh::UpdateAndShowNotification(
const Notification& notification) {
return UpdateNotification(notification);
}
Balloon* BalloonCollectionImplAsh::MakeBalloon(
const Notification& notification, Profile* profile) {
Balloon* balloon = new Balloon(notification, profile, this);
if (!IsAshNotifyEnabled()) {
::BalloonViewImpl* balloon_view = new ::BalloonViewImpl(this);
if (system_notifications_.find(notification.notification_id()) !=
system_notifications_.end())
balloon_view->set_enable_web_ui(true);
balloon->set_view(balloon_view);
gfx::Size size(layout().min_balloon_width(), layout().min_balloon_height());
balloon->set_content_size(size);
} else {
BalloonViewAsh* balloon_view = new BalloonViewAsh(this);
balloon->set_view(balloon_view);
}
return balloon;
}
const extensions::Extension* BalloonCollectionImplAsh::GetBalloonExtension(
Balloon* balloon) {
if (!balloon)
return NULL;
ExtensionService* extension_service =
balloon->profile()->GetExtensionService();
const GURL& origin = balloon->notification().origin_url();
return extension_service->extensions()->GetExtensionOrAppByURL(
ExtensionURLInfo(origin));
}
// For now, only use BalloonCollectionImplAsh on ChromeOS, until
// system_notifications_ is replaced with status area notifications.
#if defined(OS_CHROMEOS)
// static
BalloonCollection* BalloonCollection::Create() {
return new BalloonCollectionImplAsh();
}
#endif
|
// 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/ui/views/ash/balloon_collection_impl_ash.h"
#include "ash/ash_switches.h"
#include "ash/shell.h"
#include "ash/system/status_area_widget.h"
#include "base/command_line.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/notifications/balloon.h"
#include "chrome/browser/notifications/desktop_notification_service.h"
#include "chrome/browser/notifications/desktop_notification_service_factory.h"
#include "chrome/browser/notifications/notification.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/chrome_pages.h"
#include "chrome/browser/ui/views/ash/balloon_view_ash.h"
#include "chrome/browser/ui/views/notifications/balloon_view_host.h"
#include "chrome/browser/ui/views/notifications/balloon_view_views.h"
namespace {
bool IsAshNotifyEnabled() {
return !CommandLine::ForCurrentProcess()->HasSwitch(
ash::switches::kAshNotifyDisabled);
}
} // namespace
BalloonCollectionImplAsh::BalloonCollectionImplAsh() {
if (IsAshNotifyEnabled()) {
ash::Shell::GetInstance()->status_area_widget()->
web_notification_tray()->SetDelegate(this);
}
}
BalloonCollectionImplAsh::~BalloonCollectionImplAsh() {
}
bool BalloonCollectionImplAsh::HasSpace() const {
if (!IsAshNotifyEnabled())
return BalloonCollectionImpl::HasSpace();
return true; // Overflow is handled by ash::WebNotificationTray.
}
void BalloonCollectionImplAsh::Add(const Notification& notification,
Profile* profile) {
if (IsAshNotifyEnabled()) {
if (notification.is_html())
return; // HTML notifications are not supported in Ash.
if (notification.title().empty() && notification.body().empty())
return; // Empty notification, don't show.
}
return BalloonCollectionImpl::Add(notification, profile);
}
void BalloonCollectionImplAsh::DisableExtension(
const std::string& notifcation_id) {
Balloon* balloon = base().FindBalloonById(notifcation_id);
const extensions::Extension* extension = GetBalloonExtension(balloon);
if (!extension)
return;
balloon->profile()->GetExtensionService()->DisableExtension(
extension->id(), extensions::Extension::DISABLE_USER_ACTION);
}
void BalloonCollectionImplAsh::DisableNotificationsFromSource(
const std::string& notifcation_id) {
Balloon* balloon = base().FindBalloonById(notifcation_id);
if (!balloon)
return;
DesktopNotificationService* service =
DesktopNotificationServiceFactory::GetForProfile(balloon->profile());
service->DenyPermission(balloon->notification().origin_url());
}
void BalloonCollectionImplAsh::NotificationRemoved(
const std::string& notifcation_id) {
RemoveById(notifcation_id);
}
void BalloonCollectionImplAsh::ShowSettings(const std::string& notifcation_id) {
Balloon* balloon = base().FindBalloonById(notifcation_id);
Profile* profile =
balloon ? balloon->profile() : ProfileManager::GetDefaultProfile();
Browser* browser = browser::FindOrCreateTabbedBrowser(profile);
if (GetBalloonExtension(balloon))
chrome::ShowExtensions(browser);
else
chrome::ShowContentSettings(browser, CONTENT_SETTINGS_TYPE_NOTIFICATIONS);
}
void BalloonCollectionImplAsh::OnClicked(const std::string& notifcation_id) {
Balloon* balloon = base().FindBalloonById(notifcation_id);
if (!balloon)
return;
balloon->OnClick();
RemoveById(notifcation_id);
}
bool BalloonCollectionImplAsh::AddWebUIMessageCallback(
const Notification& notification,
const std::string& message,
const chromeos::BalloonViewHost::MessageCallback& callback) {
#if defined(OS_CHROMEOS)
Balloon* balloon = base().FindBalloon(notification);
if (!balloon)
return false;
BalloonHost* balloon_host = balloon->balloon_view()->GetHost();
if (!balloon_host)
return false;
chromeos::BalloonViewHost* balloon_view_host =
static_cast<chromeos::BalloonViewHost*>(balloon_host);
return balloon_view_host->AddWebUIMessageCallback(message, callback);
#else
return false;
#endif
}
void BalloonCollectionImplAsh::AddSystemNotification(
const Notification& notification,
Profile* profile,
bool sticky) {
system_notifications_.insert(notification.notification_id());
// Add balloons to the front of the stack. This ensures that system
// notifications will always be displayed. NOTE: This has the side effect
// that system notifications are displayed in inverse order, with the most
// recent notification always at the front of the list.
AddImpl(notification, profile, true /* add to front*/);
}
bool BalloonCollectionImplAsh::UpdateNotification(
const Notification& notification) {
Balloon* balloon = base().FindBalloon(notification);
if (!balloon)
return false;
balloon->Update(notification);
return true;
}
bool BalloonCollectionImplAsh::UpdateAndShowNotification(
const Notification& notification) {
return UpdateNotification(notification);
}
Balloon* BalloonCollectionImplAsh::MakeBalloon(
const Notification& notification, Profile* profile) {
Balloon* balloon = new Balloon(notification, profile, this);
if (!IsAshNotifyEnabled()) {
::BalloonViewImpl* balloon_view = new ::BalloonViewImpl(this);
if (system_notifications_.find(notification.notification_id()) !=
system_notifications_.end())
balloon_view->set_enable_web_ui(true);
balloon->set_view(balloon_view);
gfx::Size size(layout().min_balloon_width(), layout().min_balloon_height());
balloon->set_content_size(size);
} else {
BalloonViewAsh* balloon_view = new BalloonViewAsh(this);
balloon->set_view(balloon_view);
}
return balloon;
}
const extensions::Extension* BalloonCollectionImplAsh::GetBalloonExtension(
Balloon* balloon) {
if (!balloon)
return NULL;
ExtensionService* extension_service =
balloon->profile()->GetExtensionService();
const GURL& origin = balloon->notification().origin_url();
return extension_service->extensions()->GetExtensionOrAppByURL(
ExtensionURLInfo(origin));
}
// For now, only use BalloonCollectionImplAsh on ChromeOS, until
// system_notifications_ is replaced with status area notifications.
#if defined(OS_CHROMEOS)
// static
BalloonCollection* BalloonCollection::Create() {
return new BalloonCollectionImplAsh();
}
#endif
|
Remove notifications when clicked on
|
Ash: Remove notifications when clicked on
BUG=144546
TEST=Ensure that clicking on a notification still invokes any associated action. Notification should be removed regardless of whether it is a popup or in the tray.
Review URL: https://chromiumcodereview.appspot.com/10870051
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@153257 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
nacl-webkit/chrome_deps,ondra-novak/chromium.src,ltilve/chromium,mogoweb/chromium-crosswalk,dednal/chromium.src,markYoungH/chromium.src,jaruba/chromium.src,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,ltilve/chromium,M4sse/chromium.src,zcbenz/cefode-chromium,hgl888/chromium-crosswalk-efl,patrickm/chromium.src,pozdnyakov/chromium-crosswalk,M4sse/chromium.src,Jonekee/chromium.src,patrickm/chromium.src,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,littlstar/chromium.src,M4sse/chromium.src,timopulkkinen/BubbleFish,timopulkkinen/BubbleFish,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,littlstar/chromium.src,jaruba/chromium.src,junmin-zhu/chromium-rivertrail,dednal/chromium.src,ChromiumWebApps/chromium,Just-D/chromium-1,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,axinging/chromium-crosswalk,M4sse/chromium.src,junmin-zhu/chromium-rivertrail,mogoweb/chromium-crosswalk,zcbenz/cefode-chromium,zcbenz/cefode-chromium,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,littlstar/chromium.src,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,nacl-webkit/chrome_deps,Chilledheart/chromium,mogoweb/chromium-crosswalk,anirudhSK/chromium,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,hujiajie/pa-chromium,hgl888/chromium-crosswalk,timopulkkinen/BubbleFish,dushu1203/chromium.src,axinging/chromium-crosswalk,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hujiajie/pa-chromium,timopulkkinen/BubbleFish,littlstar/chromium.src,timopulkkinen/BubbleFish,Fireblend/chromium-crosswalk,timopulkkinen/BubbleFish,Jonekee/chromium.src,ltilve/chromium,hujiajie/pa-chromium,junmin-zhu/chromium-rivertrail,markYoungH/chromium.src,dednal/chromium.src,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,zcbenz/cefode-chromium,hgl888/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,ltilve/chromium,nacl-webkit/chrome_deps,ltilve/chromium,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,markYoungH/chromium.src,jaruba/chromium.src,krieger-od/nwjs_chromium.src,Just-D/chromium-1,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,jaruba/chromium.src,ChromiumWebApps/chromium,ChromiumWebApps/chromium,patrickm/chromium.src,krieger-od/nwjs_chromium.src,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hujiajie/pa-chromium,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,zcbenz/cefode-chromium,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,junmin-zhu/chromium-rivertrail,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,mogoweb/chromium-crosswalk,fujunwei/chromium-crosswalk,zcbenz/cefode-chromium,littlstar/chromium.src,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,timopulkkinen/BubbleFish,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,Fireblend/chromium-crosswalk,M4sse/chromium.src,hujiajie/pa-chromium,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,Pluto-tv/chromium-crosswalk,littlstar/chromium.src,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,dednal/chromium.src,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,bright-sparks/chromium-spacewalk,anirudhSK/chromium,ltilve/chromium,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,bright-sparks/chromium-spacewalk,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,mogoweb/chromium-crosswalk,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,markYoungH/chromium.src,littlstar/chromium.src,hujiajie/pa-chromium,markYoungH/chromium.src,dednal/chromium.src,Chilledheart/chromium,Just-D/chromium-1,zcbenz/cefode-chromium,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,axinging/chromium-crosswalk,axinging/chromium-crosswalk,M4sse/chromium.src,Chilledheart/chromium,anirudhSK/chromium,nacl-webkit/chrome_deps,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,zcbenz/cefode-chromium,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,timopulkkinen/BubbleFish,Chilledheart/chromium,jaruba/chromium.src,hujiajie/pa-chromium,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,zcbenz/cefode-chromium,Jonekee/chromium.src,hgl888/chromium-crosswalk,mogoweb/chromium-crosswalk,Just-D/chromium-1,dednal/chromium.src,dushu1203/chromium.src,ondra-novak/chromium.src,timopulkkinen/BubbleFish,anirudhSK/chromium,M4sse/chromium.src,nacl-webkit/chrome_deps,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,Jonekee/chromium.src,anirudhSK/chromium,ondra-novak/chromium.src,anirudhSK/chromium,fujunwei/chromium-crosswalk,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,axinging/chromium-crosswalk,patrickm/chromium.src,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,timopulkkinen/BubbleFish,krieger-od/nwjs_chromium.src,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,nacl-webkit/chrome_deps,ondra-novak/chromium.src,nacl-webkit/chrome_deps,M4sse/chromium.src,Jonekee/chromium.src,littlstar/chromium.src,dushu1203/chromium.src,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,dednal/chromium.src,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,dushu1203/chromium.src,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,junmin-zhu/chromium-rivertrail,patrickm/chromium.src,krieger-od/nwjs_chromium.src,junmin-zhu/chromium-rivertrail,ltilve/chromium,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,dushu1203/chromium.src,axinging/chromium-crosswalk,junmin-zhu/chromium-rivertrail,junmin-zhu/chromium-rivertrail,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk,patrickm/chromium.src,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,jaruba/chromium.src,M4sse/chromium.src,dednal/chromium.src,axinging/chromium-crosswalk,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,Just-D/chromium-1,nacl-webkit/chrome_deps,Fireblend/chromium-crosswalk,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,hujiajie/pa-chromium,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,junmin-zhu/chromium-rivertrail,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,jaruba/chromium.src,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,zcbenz/cefode-chromium,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,ondra-novak/chromium.src,dushu1203/chromium.src,dednal/chromium.src,axinging/chromium-crosswalk,markYoungH/chromium.src,markYoungH/chromium.src,hujiajie/pa-chromium,chuan9/chromium-crosswalk,timopulkkinen/BubbleFish,M4sse/chromium.src,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,Jonekee/chromium.src,patrickm/chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl
|
d8074674c0abd64b1ca5016f54cc4957f0fe0c2a
|
chrome/browser/views/tab_contents/tab_contents_drag_win.cc
|
chrome/browser/views/tab_contents/tab_contents_drag_win.cc
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/views/tab_contents/tab_contents_drag_win.h"
#include <windows.h>
#include <string>
#include "base/file_path.h"
#include "base/message_loop.h"
#include "base/task.h"
#include "base/thread.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/bookmarks/bookmark_drag_data.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/download/download_util.h"
#include "chrome/browser/download/drag_download_file.h"
#include "chrome/browser/download/drag_download_util.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/web_drag_source_win.h"
#include "chrome/browser/tab_contents/web_drag_utils_win.h"
#include "chrome/browser/tab_contents/web_drop_target_win.h"
#include "chrome/browser/views/tab_contents/tab_contents_view_win.h"
#include "chrome/common/url_constants.h"
#include "net/base/net_util.h"
#include "views/drag_utils.h"
#include "webkit/glue/webdropdata.h"
using WebKit::WebDragOperationsMask;
using WebKit::WebDragOperationCopy;
using WebKit::WebDragOperationLink;
using WebKit::WebDragOperationMove;
namespace {
HHOOK msg_hook = NULL;
DWORD drag_out_thread_id = 0;
bool mouse_up_received = false;
LRESULT CALLBACK MsgFilterProc(int code, WPARAM wparam, LPARAM lparam) {
if (code == base::MessagePumpForUI::kMessageFilterCode &&
!mouse_up_received) {
MSG* msg = reinterpret_cast<MSG*>(lparam);
// We do not care about WM_SYSKEYDOWN and WM_SYSKEYUP because when ALT key
// is pressed down on drag-and-drop, it means to create a link.
if (msg->message == WM_MOUSEMOVE || msg->message == WM_LBUTTONUP ||
msg->message == WM_KEYDOWN || msg->message == WM_KEYUP) {
// Forward the message from the UI thread to the drag-and-drop thread.
PostThreadMessage(drag_out_thread_id,
msg->message,
msg->wParam,
msg->lParam);
// If the left button is up, we do not need to forward the message any
// more.
if (msg->message == WM_LBUTTONUP || !(GetKeyState(VK_LBUTTON) & 0x8000))
mouse_up_received = true;
return TRUE;
}
}
return CallNextHookEx(msg_hook, code, wparam, lparam);
}
} // namespace
class DragDropThread : public base::Thread {
public:
explicit DragDropThread(TabContentsDragWin* drag_handler)
: base::Thread("Chrome_DragDropThread"),
drag_handler_(drag_handler) {
}
virtual ~DragDropThread() {
Thread::Stop();
}
protected:
// base::Thread implementations:
virtual void Init() {
int ole_result = OleInitialize(NULL);
DCHECK(ole_result == S_OK);
}
virtual void CleanUp() {
OleUninitialize();
}
private:
// Hold a reference count to TabContentsDragWin to make sure that it is always
// alive in the thread lifetime.
scoped_refptr<TabContentsDragWin> drag_handler_;
DISALLOW_COPY_AND_ASSIGN(DragDropThread);
};
TabContentsDragWin::TabContentsDragWin(TabContentsViewWin* view)
: drag_drop_thread_id_(0),
view_(view),
drag_ended_(false),
old_drop_target_suspended_state_(false) {
}
TabContentsDragWin::~TabContentsDragWin() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(!drag_drop_thread_.get());
}
void TabContentsDragWin::StartDragging(const WebDropData& drop_data,
WebDragOperationsMask ops,
const SkBitmap& image,
const gfx::Point& image_offset) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
drag_source_ = new WebDragSource(view_->GetNativeView(),
view_->tab_contents());
const GURL& page_url = view_->tab_contents()->GetURL();
const std::string& page_encoding = view_->tab_contents()->encoding();
// If it is not drag-out, do the drag-and-drop in the current UI thread.
if (drop_data.download_metadata.empty()) {
DoDragging(drop_data, ops, page_url, page_encoding, image, image_offset);
EndDragging(false);
return;
}
// We do not want to drag and drop the download to itself.
old_drop_target_suspended_state_ = view_->drop_target()->suspended();
view_->drop_target()->set_suspended(true);
// Start a background thread to do the drag-and-drop.
DCHECK(!drag_drop_thread_.get());
drag_drop_thread_.reset(new DragDropThread(this));
base::Thread::Options options;
options.message_loop_type = MessageLoop::TYPE_UI;
if (drag_drop_thread_->StartWithOptions(options)) {
drag_drop_thread_->message_loop()->PostTask(
FROM_HERE,
NewRunnableMethod(this,
&TabContentsDragWin::StartBackgroundDragging,
drop_data,
ops,
page_url,
page_encoding,
image,
image_offset));
}
// Install a hook procedure to monitor the messages so that we can forward
// the appropriate ones to the background thread.
drag_out_thread_id = drag_drop_thread_->thread_id();
mouse_up_received = false;
DCHECK(!msg_hook);
msg_hook = SetWindowsHookEx(WH_MSGFILTER,
MsgFilterProc,
NULL,
GetCurrentThreadId());
// Attach the input state of the background thread to the UI thread so that
// SetCursor can work from the background thread.
AttachThreadInput(drag_out_thread_id, GetCurrentThreadId(), TRUE);
}
void TabContentsDragWin::StartBackgroundDragging(
const WebDropData& drop_data,
WebDragOperationsMask ops,
const GURL& page_url,
const std::string& page_encoding,
const SkBitmap& image,
const gfx::Point& image_offset) {
drag_drop_thread_id_ = PlatformThread::CurrentId();
DoDragging(drop_data, ops, page_url, page_encoding, image, image_offset);
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
NewRunnableMethod(this, &TabContentsDragWin::EndDragging, true));
}
void TabContentsDragWin::PrepareDragForDownload(
const WebDropData& drop_data,
OSExchangeData* data,
const GURL& page_url,
const std::string& page_encoding) {
// Parse the download metadata.
string16 mime_type;
FilePath file_name;
GURL download_url;
if (!drag_download_util::ParseDownloadMetadata(drop_data.download_metadata,
&mime_type,
&file_name,
&download_url))
return;
// Generate the download filename.
std::string content_disposition =
"attachment; filename=" + UTF16ToUTF8(file_name.value());
FilePath generated_file_name;
download_util::GenerateFileName(download_url,
content_disposition,
std::string(),
UTF16ToUTF8(mime_type),
&generated_file_name);
// Provide the data as file (CF_HDROP). A temporary download file with the
// Zone.Identifier ADS (Alternate Data Stream) attached will be created.
linked_ptr<net::FileStream> empty_file_stream;
scoped_refptr<DragDownloadFile> download_file =
new DragDownloadFile(generated_file_name,
empty_file_stream,
download_url,
page_url,
page_encoding,
view_->tab_contents());
OSExchangeData::DownloadFileInfo file_download(FilePath(),
download_file.get());
data->SetDownloadFileInfo(file_download);
// Enable asynchronous operation.
OSExchangeDataProviderWin::GetIAsyncOperation(*data)->SetAsyncMode(TRUE);
}
void TabContentsDragWin::PrepareDragForFileContents(
const WebDropData& drop_data, OSExchangeData* data) {
// Images without ALT text will only have a file extension so we need to
// synthesize one from the provided extension and URL.
FilePath file_name(drop_data.file_description_filename);
file_name = file_name.BaseName().RemoveExtension();
if (file_name.value().empty()) {
// Retrieve the name from the URL.
file_name = net::GetSuggestedFilename(drop_data.url, "", "", FilePath());
if (file_name.value().size() + drop_data.file_extension.size() + 1 >
MAX_PATH) {
file_name = FilePath(file_name.value().substr(
0, MAX_PATH - drop_data.file_extension.size() - 2));
}
}
file_name = file_name.ReplaceExtension(drop_data.file_extension);
data->SetFileContents(file_name.value(), drop_data.file_contents);
}
void TabContentsDragWin::PrepareDragForUrl(const WebDropData& drop_data,
OSExchangeData* data) {
if (drop_data.url.SchemeIs(chrome::kJavaScriptScheme)) {
// We don't want to allow javascript URLs to be dragged to the desktop,
// but we do want to allow them to be added to the bookmarks bar
// (bookmarklets). So we create a fake bookmark entry (BookmarkDragData
// object) which explorer.exe cannot handle, and write the entry to data.
BookmarkDragData::Element bm_elt;
bm_elt.is_url = true;
bm_elt.url = drop_data.url;
bm_elt.title = drop_data.url_title;
BookmarkDragData bm_drag_data;
bm_drag_data.elements.push_back(bm_elt);
// Pass in NULL as the profile so that the bookmark always adds the url
// rather than trying to move an existing url.
bm_drag_data.Write(NULL, data);
} else {
data->SetURL(drop_data.url, drop_data.url_title);
}
}
void TabContentsDragWin::DoDragging(const WebDropData& drop_data,
WebDragOperationsMask ops,
const GURL& page_url,
const std::string& page_encoding,
const SkBitmap& image,
const gfx::Point& image_offset) {
OSExchangeData data;
if (!drop_data.download_metadata.empty()) {
PrepareDragForDownload(drop_data, &data, page_url, page_encoding);
// Set the observer.
OSExchangeDataProviderWin::GetDataObjectImpl(data)->set_observer(this);
} else {
// We set the file contents before the URL because the URL also sets file
// contents (to a .URL shortcut). We want to prefer file content data over
// a shortcut so we add it first.
if (!drop_data.file_contents.empty())
PrepareDragForFileContents(drop_data, &data);
if (!drop_data.text_html.empty())
data.SetHtml(drop_data.text_html, drop_data.html_base_url);
if (drop_data.url.is_valid())
PrepareDragForUrl(drop_data, &data);
if (!drop_data.plain_text.empty())
data.SetString(drop_data.plain_text);
}
// Set drag image.
if (!image.isNull()) {
drag_utils::SetDragImageOnDataObject(
image, gfx::Size(image.width(), image.height()), image_offset, &data);
}
// We need to enable recursive tasks on the message loop so we can get
// updates while in the system DoDragDrop loop.
bool old_state = MessageLoop::current()->NestableTasksAllowed();
MessageLoop::current()->SetNestableTasksAllowed(true);
DWORD effect;
DoDragDrop(OSExchangeDataProviderWin::GetIDataObject(data), drag_source_,
web_drag_utils_win::WebDragOpMaskToWinDragOpMask(ops), &effect);
MessageLoop::current()->SetNestableTasksAllowed(old_state);
// This works because WebDragSource::OnDragSourceDrop uses PostTask to
// dispatch the actual event.
drag_source_->set_effect(effect);
}
void TabContentsDragWin::EndDragging(bool restore_suspended_state) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (drag_ended_)
return;
drag_ended_ = true;
if (restore_suspended_state)
view_->drop_target()->set_suspended(old_drop_target_suspended_state_);
if (msg_hook) {
AttachThreadInput(drag_out_thread_id, GetCurrentThreadId(), FALSE);
UnhookWindowsHookEx(msg_hook);
msg_hook = NULL;
}
view_->EndDragging();
}
void TabContentsDragWin::CancelDrag() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
drag_source_->CancelDrag();
}
void TabContentsDragWin::CloseThread() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
drag_drop_thread_.reset();
}
void TabContentsDragWin::OnWaitForData() {
DCHECK(drag_drop_thread_id_ == PlatformThread::CurrentId());
// When the left button is release and we start to wait for the data, end
// the dragging before DoDragDrop returns. This makes the page leave the drag
// mode so that it can start to process the normal input events.
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
NewRunnableMethod(this, &TabContentsDragWin::EndDragging, true));
}
void TabContentsDragWin::OnDataObjectDisposed() {
DCHECK(drag_drop_thread_id_ == PlatformThread::CurrentId());
// The drag-and-drop thread is only closed after OLE is done with
// DataObjectImpl.
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
NewRunnableMethod(this, &TabContentsDragWin::CloseThread));
}
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/views/tab_contents/tab_contents_drag_win.h"
#include <windows.h>
#include <string>
#include "base/file_path.h"
#include "base/message_loop.h"
#include "base/task.h"
#include "base/thread.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/bookmarks/bookmark_drag_data.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/download/download_util.h"
#include "chrome/browser/download/drag_download_file.h"
#include "chrome/browser/download/drag_download_util.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/web_drag_source_win.h"
#include "chrome/browser/tab_contents/web_drag_utils_win.h"
#include "chrome/browser/tab_contents/web_drop_target_win.h"
#include "chrome/browser/views/tab_contents/tab_contents_view_win.h"
#include "chrome/common/url_constants.h"
#include "net/base/net_util.h"
#include "views/drag_utils.h"
#include "webkit/glue/webdropdata.h"
using WebKit::WebDragOperationsMask;
using WebKit::WebDragOperationCopy;
using WebKit::WebDragOperationLink;
using WebKit::WebDragOperationMove;
namespace {
HHOOK msg_hook = NULL;
DWORD drag_out_thread_id = 0;
bool mouse_up_received = false;
LRESULT CALLBACK MsgFilterProc(int code, WPARAM wparam, LPARAM lparam) {
if (code == base::MessagePumpForUI::kMessageFilterCode &&
!mouse_up_received) {
MSG* msg = reinterpret_cast<MSG*>(lparam);
// We do not care about WM_SYSKEYDOWN and WM_SYSKEYUP because when ALT key
// is pressed down on drag-and-drop, it means to create a link.
if (msg->message == WM_MOUSEMOVE || msg->message == WM_LBUTTONUP ||
msg->message == WM_KEYDOWN || msg->message == WM_KEYUP) {
// Forward the message from the UI thread to the drag-and-drop thread.
PostThreadMessage(drag_out_thread_id,
msg->message,
msg->wParam,
msg->lParam);
// If the left button is up, we do not need to forward the message any
// more.
if (msg->message == WM_LBUTTONUP || !(GetKeyState(VK_LBUTTON) & 0x8000))
mouse_up_received = true;
return TRUE;
}
}
return CallNextHookEx(msg_hook, code, wparam, lparam);
}
} // namespace
class DragDropThread : public base::Thread {
public:
explicit DragDropThread(TabContentsDragWin* drag_handler)
: base::Thread("Chrome_DragDropThread"),
drag_handler_(drag_handler) {
}
virtual ~DragDropThread() {
Thread::Stop();
}
protected:
// base::Thread implementations:
virtual void Init() {
int ole_result = OleInitialize(NULL);
DCHECK(ole_result == S_OK);
}
virtual void CleanUp() {
OleUninitialize();
}
private:
// Hold a reference count to TabContentsDragWin to make sure that it is always
// alive in the thread lifetime.
scoped_refptr<TabContentsDragWin> drag_handler_;
DISALLOW_COPY_AND_ASSIGN(DragDropThread);
};
TabContentsDragWin::TabContentsDragWin(TabContentsViewWin* view)
: drag_drop_thread_id_(0),
view_(view),
drag_ended_(false),
old_drop_target_suspended_state_(false) {
}
TabContentsDragWin::~TabContentsDragWin() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(!drag_drop_thread_.get());
}
void TabContentsDragWin::StartDragging(const WebDropData& drop_data,
WebDragOperationsMask ops,
const SkBitmap& image,
const gfx::Point& image_offset) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
drag_source_ = new WebDragSource(view_->GetNativeView(),
view_->tab_contents());
const GURL& page_url = view_->tab_contents()->GetURL();
const std::string& page_encoding = view_->tab_contents()->encoding();
// If it is not drag-out, do the drag-and-drop in the current UI thread.
if (drop_data.download_metadata.empty()) {
DoDragging(drop_data, ops, page_url, page_encoding, image, image_offset);
EndDragging(false);
return;
}
// We do not want to drag and drop the download to itself.
old_drop_target_suspended_state_ = view_->drop_target()->suspended();
view_->drop_target()->set_suspended(true);
// Start a background thread to do the drag-and-drop.
DCHECK(!drag_drop_thread_.get());
drag_drop_thread_.reset(new DragDropThread(this));
base::Thread::Options options;
options.message_loop_type = MessageLoop::TYPE_UI;
if (drag_drop_thread_->StartWithOptions(options)) {
drag_drop_thread_->message_loop()->PostTask(
FROM_HERE,
NewRunnableMethod(this,
&TabContentsDragWin::StartBackgroundDragging,
drop_data,
ops,
page_url,
page_encoding,
image,
image_offset));
}
// Install a hook procedure to monitor the messages so that we can forward
// the appropriate ones to the background thread.
drag_out_thread_id = drag_drop_thread_->thread_id();
mouse_up_received = false;
DCHECK(!msg_hook);
msg_hook = SetWindowsHookEx(WH_MSGFILTER,
MsgFilterProc,
NULL,
GetCurrentThreadId());
// Attach the input state of the background thread to the UI thread so that
// SetCursor can work from the background thread.
AttachThreadInput(drag_out_thread_id, GetCurrentThreadId(), TRUE);
}
void TabContentsDragWin::StartBackgroundDragging(
const WebDropData& drop_data,
WebDragOperationsMask ops,
const GURL& page_url,
const std::string& page_encoding,
const SkBitmap& image,
const gfx::Point& image_offset) {
drag_drop_thread_id_ = PlatformThread::CurrentId();
DoDragging(drop_data, ops, page_url, page_encoding, image, image_offset);
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
NewRunnableMethod(this, &TabContentsDragWin::EndDragging, true));
}
void TabContentsDragWin::PrepareDragForDownload(
const WebDropData& drop_data,
OSExchangeData* data,
const GURL& page_url,
const std::string& page_encoding) {
// Parse the download metadata.
string16 mime_type;
FilePath file_name;
GURL download_url;
if (!drag_download_util::ParseDownloadMetadata(drop_data.download_metadata,
&mime_type,
&file_name,
&download_url))
return;
// Generate the download filename.
std::string content_disposition =
"attachment; filename=" + UTF16ToUTF8(file_name.value());
FilePath generated_file_name;
download_util::GenerateFileName(download_url,
content_disposition,
std::string(),
UTF16ToUTF8(mime_type),
&generated_file_name);
// Provide the data as file (CF_HDROP). A temporary download file with the
// Zone.Identifier ADS (Alternate Data Stream) attached will be created.
linked_ptr<net::FileStream> empty_file_stream;
scoped_refptr<DragDownloadFile> download_file =
new DragDownloadFile(generated_file_name,
empty_file_stream,
download_url,
page_url,
page_encoding,
view_->tab_contents());
OSExchangeData::DownloadFileInfo file_download(FilePath(),
download_file.get());
data->SetDownloadFileInfo(file_download);
// Enable asynchronous operation.
OSExchangeDataProviderWin::GetIAsyncOperation(*data)->SetAsyncMode(TRUE);
}
void TabContentsDragWin::PrepareDragForFileContents(
const WebDropData& drop_data, OSExchangeData* data) {
// Images without ALT text will only have a file extension so we need to
// synthesize one from the provided extension and URL.
FilePath file_name(drop_data.file_description_filename);
file_name = file_name.BaseName().RemoveExtension();
if (file_name.value().empty()) {
// Retrieve the name from the URL.
file_name = net::GetSuggestedFilename(drop_data.url, "", "", FilePath());
if (file_name.value().size() + drop_data.file_extension.size() + 1 >
MAX_PATH) {
file_name = FilePath(file_name.value().substr(
0, MAX_PATH - drop_data.file_extension.size() - 2));
}
}
file_name = file_name.ReplaceExtension(drop_data.file_extension);
data->SetFileContents(file_name.value(), drop_data.file_contents);
}
void TabContentsDragWin::PrepareDragForUrl(const WebDropData& drop_data,
OSExchangeData* data) {
if (drop_data.url.SchemeIs(chrome::kJavaScriptScheme)) {
// We don't want to allow javascript URLs to be dragged to the desktop,
// but we do want to allow them to be added to the bookmarks bar
// (bookmarklets). So we create a fake bookmark entry (BookmarkDragData
// object) which explorer.exe cannot handle, and write the entry to data.
BookmarkDragData::Element bm_elt;
bm_elt.is_url = true;
bm_elt.url = drop_data.url;
bm_elt.title = drop_data.url_title;
BookmarkDragData bm_drag_data;
bm_drag_data.elements.push_back(bm_elt);
// Pass in NULL as the profile so that the bookmark always adds the url
// rather than trying to move an existing url.
bm_drag_data.Write(NULL, data);
} else {
data->SetURL(drop_data.url, drop_data.url_title);
}
}
void TabContentsDragWin::DoDragging(const WebDropData& drop_data,
WebDragOperationsMask ops,
const GURL& page_url,
const std::string& page_encoding,
const SkBitmap& image,
const gfx::Point& image_offset) {
OSExchangeData data;
if (!drop_data.download_metadata.empty()) {
PrepareDragForDownload(drop_data, &data, page_url, page_encoding);
// Set the observer.
OSExchangeDataProviderWin::GetDataObjectImpl(data)->set_observer(this);
} else {
// We set the file contents before the URL because the URL also sets file
// contents (to a .URL shortcut). We want to prefer file content data over
// a shortcut so we add it first.
if (!drop_data.file_contents.empty())
PrepareDragForFileContents(drop_data, &data);
if (!drop_data.text_html.empty())
data.SetHtml(drop_data.text_html, drop_data.html_base_url);
// We set the text contents before the URL because the URL also sets text
// content.
if (!drop_data.plain_text.empty())
data.SetString(drop_data.plain_text);
if (drop_data.url.is_valid())
PrepareDragForUrl(drop_data, &data);
}
// Set drag image.
if (!image.isNull()) {
drag_utils::SetDragImageOnDataObject(
image, gfx::Size(image.width(), image.height()), image_offset, &data);
}
// We need to enable recursive tasks on the message loop so we can get
// updates while in the system DoDragDrop loop.
bool old_state = MessageLoop::current()->NestableTasksAllowed();
MessageLoop::current()->SetNestableTasksAllowed(true);
DWORD effect;
DoDragDrop(OSExchangeDataProviderWin::GetIDataObject(data), drag_source_,
web_drag_utils_win::WebDragOpMaskToWinDragOpMask(ops), &effect);
MessageLoop::current()->SetNestableTasksAllowed(old_state);
// This works because WebDragSource::OnDragSourceDrop uses PostTask to
// dispatch the actual event.
drag_source_->set_effect(effect);
}
void TabContentsDragWin::EndDragging(bool restore_suspended_state) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (drag_ended_)
return;
drag_ended_ = true;
if (restore_suspended_state)
view_->drop_target()->set_suspended(old_drop_target_suspended_state_);
if (msg_hook) {
AttachThreadInput(drag_out_thread_id, GetCurrentThreadId(), FALSE);
UnhookWindowsHookEx(msg_hook);
msg_hook = NULL;
}
view_->EndDragging();
}
void TabContentsDragWin::CancelDrag() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
drag_source_->CancelDrag();
}
void TabContentsDragWin::CloseThread() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
drag_drop_thread_.reset();
}
void TabContentsDragWin::OnWaitForData() {
DCHECK(drag_drop_thread_id_ == PlatformThread::CurrentId());
// When the left button is release and we start to wait for the data, end
// the dragging before DoDragDrop returns. This makes the page leave the drag
// mode so that it can start to process the normal input events.
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
NewRunnableMethod(this, &TabContentsDragWin::EndDragging, true));
}
void TabContentsDragWin::OnDataObjectDisposed() {
DCHECK(drag_drop_thread_id_ == PlatformThread::CurrentId());
// The drag-and-drop thread is only closed after OLE is done with
// DataObjectImpl.
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
NewRunnableMethod(this, &TabContentsDragWin::CloseThread));
}
|
Fix drag data population on Windows so URL data doesn't take precedence over text.
|
Fix drag data population on Windows so URL data doesn't take precedence over text.
BUG=59229
TEST=Manual test using test case attached to bug 59229.
Review URL: http://codereview.chromium.org/3818005
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@62803 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
yitian134/chromium,yitian134/chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,ropik/chromium,ropik/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,adobe/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,ropik/chromium,yitian134/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,ropik/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,gavinp/chromium,yitian134/chromium,yitian134/chromium,gavinp/chromium,ropik/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,adobe/chromium
|
aed9ac164252be8f97561bb0d145775388a4b6d5
|
main/src/hadd.cxx
|
main/src/hadd.cxx
|
/*
This program will add histograms (see note) and Trees from a list of root files and write them
to a target root file. The target file is newly created and must not be
identical to one of the source files.
Syntax:
hadd targetfile source1 source2 ...
or
hadd -f targetfile source1 source2 ...
(targetfile is overwritten if it exists)
When the -f option is specified, one can also specify the compression
level of the target file. By default the compression level is 1, but
if "-f0" is specified, the target file will not be compressed.
if "-f6" is specified, the compression level 6 will be used.
For example assume 3 files f1, f2, f3 containing histograms hn and Trees Tn
f1 with h1 h2 h3 T1
f2 with h1 h4 T1 T2
f3 with h5
the result of
hadd -f x.root f1.root f2.root f3.root
will be a file x.root with h1 h2 h3 h4 h5 T1 T2
where h1 will be the sum of the 2 histograms in f1 and f2
T1 will be the merge of the Trees in f1 and f2
The files may contain sub-directories.
if the source files contains histograms and Trees, one can skip
the Trees with
hadd -T targetfile source1 source2 ...
Wildcarding and indirect files are also supported
hadd result.root myfil*.root
will merge all files in myfil*.root
hadd result.root file1.root @list.txt file2. root myfil*.root
will merge file1. root, file2. root, all files in myfil*.root
and all files in the indirect text file list.txt ("@" as the first
character of the file indicates an indirect file. An indirect file
is a text file containing a list of other files, including other
indirect files, one line per file).
If the sources and and target compression levels are identical (default),
the program uses the TChain::Merge function with option "fast", ie
the merge will be done without unzipping or unstreaming the baskets
(i.e. direct copy of the raw byte on disk). The "fast" mode is typically
5 times faster than the mode unzipping and unstreaming the baskets.
NOTE1: By default histograms are added. However hadd does not support the case where
histograms have their bit TH1::kIsAverage set.
NOTE2: hadd returns a status code: 0 if OK, -1 otherwise
Authors: Rene Brun, Dirk Geppert, Sven A. Schmidt, [email protected]
: rewritten from scratch by Rene Brun (30 November 2005)
to support files with nested directories.
Toby Burnett implemented the possibility to use indirect files.
*/
#include "RConfig.h"
#include <string>
#include "TFile.h"
#include "THashList.h"
#include "TKey.h"
#include "TObjString.h"
#include "Riostream.h"
#include "TClass.h"
#include "TSystem.h"
#include <stdlib.h>
#include "TFileMerger.h"
//___________________________________________________________________________
int main( int argc, char **argv )
{
if ( argc < 3 || "-h" == std::string(argv[1]) || "--help" == std::string(argv[1]) ) {
std::cout << "Usage: " << argv[0] << " [-f[0-9]] [-k] [-T] [-O] [-n maxopenedfiles] [-v verbosity] targetfile source1 [source2 source3 ...]" << std::endl;
std::cout << "This program will add histograms from a list of root files and write them" << std::endl;
std::cout << "to a target root file. The target file is newly created and must not " << std::endl;
std::cout << "exist, or if -f (\"force\") is given, must not be one of the source files." << std::endl;
std::cout << "Supply at least two source files for this to make sense... ;-)" << std::endl;
std::cout << "If the option -k is used, hadd will not exit on corrupt or non-existant input files but skip the offending files instead." << std::endl;
std::cout << "If the option -T is used, Trees are not merged" <<std::endl;
std::cout << "If the option -O is used, when merging TTree, the basket size is re-optimized" <<std::endl;
std::cout << "If the option -v is used, explicitly set the verbosity level; 0 request no output, 99 is the default" <<std::endl;
std::cout << "If the option -n is used, hadd will open at most 'maxopenedfiles' at once, use 0 to request to use the system maximum." << std::endl;
std::cout << "When -the -f option is specified, one can also specify the compression" <<std::endl;
std::cout << "level of the target file. By default the compression level is 1, but" <<std::endl;
std::cout << "if \"-f0\" is specified, the target file will not be compressed." <<std::endl;
std::cout << "if \"-f6\" is specified, the compression level 6 will be used. See TFile::SetCompressionSettings for the support range of value." <<std::endl;
std::cout << "if Target and source files have different compression settings"<<std::endl;
std::cout << " a slower method is used"<<std::endl;
return 1;
}
Bool_t force = kFALSE;
Bool_t skip_errors = kFALSE;
Bool_t reoptimize = kFALSE;
Bool_t noTrees = kFALSE;
Int_t maxopenedfiles = 0;
Int_t verbosity = 99;
int outputPlace = 0;
int ffirst = 2;
Int_t newcomp = 1;
for( int a = 1; a < argc; ++a ) {
if ( strcmp(argv[a],"-T") == 0 ) {
noTrees = kTRUE;
++ffirst;
} else if ( strcmp(argv[a],"-f") == 0 ) {
force = kTRUE;
++ffirst;
} else if ( strcmp(argv[a],"-k") == 0 ) {
skip_errors = kTRUE;
++ffirst;
} else if ( strcmp(argv[a],"-O") == 0 ) {
reoptimize = kTRUE;
++ffirst;
} else if ( strcmp(argv[a],"-n") == 0 ) {
if (a+1 >= argc) {
std::cerr << "Error: no maximum number of opened was provided after -n.\n";
} else {
Long_t request = strtol(argv[a+1], 0, 10);
if (request < kMaxLong && request >= 0) {
maxopenedfiles = (Int_t)request;
++a;
++ffirst;
} else {
std::cerr << "Error: could not parse the max number of opened file passed after -n: " << argv[a+1] << ". We will use the system maximum.\n";
}
}
++ffirst;
} else if ( strcmp(argv[a],"-v") == 0 ) {
if (a+1 >= argc) {
std::cerr << "Error: no verbosity level was provided after -v.\n";
} else {
Long_t request = strtol(argv[a+1], 0, 10);
if (request < kMaxLong && request >= 0) {
verbosity = (Int_t)request;
++a;
++ffirst;
} else {
std::cerr << "Error: could not parse the verbosity level passed after -v: " << argv[a+1] << ". We will use the default value (99).\n";
}
}
++ffirst;
} else if ( argv[a][0] == '-' ) {
char ft[6];
for ( int alg = 0; alg <= 2; ++alg ) {
for( int j=0; j<=9; ++j ) {
const int comp = (alg*100)+j;
snprintf(ft,6,"-f%d",comp);
if (!strcmp(argv[a],ft)) {
force = kTRUE;
newcomp = comp;
++ffirst;
break;
}
}
}
if (!force) {
// Bad argument
std::cerr << "Error: option " << argv[a] << " is not a supported option.\n";
++ffirst;
}
} else if (!outputPlace) {
outputPlace = a;
}
}
gSystem->Load("libTreePlayer");
const char *targetname = 0;
if (outputPlace) {
targetname = argv[outputPlace];
} else {
targetname = argv[ffirst-1];
}
if (verbosity > 1) {
std::cout << "hadd Target file: " << targetname << std::endl;
}
TFileMerger merger(kFALSE,kFALSE);
merger.SetMsgPrefix("hadd");
merger.SetPrintLevel(verbosity - 1);
if (maxopenedfiles > 0) {
merger.SetMaxOpenedFiles(maxopenedfiles);
}
if (!merger.OutputFile(targetname,force,newcomp) ) {
std::cerr << "hadd error opening target file (does " << argv[ffirst-1] << " exist?)." << std::endl;
std::cerr << "Pass \"-f\" argument to force re-creation of output file." << std::endl;
exit(1);
}
for ( int i = ffirst; i < argc; i++ ) {
if (argv[i] && argv[i][0]=='@') {
std::ifstream indirect_file(argv[i]+1);
if( ! indirect_file.is_open() ) {
std::cerr<< "hadd could not open indirect file " << (argv[i]+1) << std::endl;
return 1;
}
while( indirect_file ){
std::string line;
if( std::getline(indirect_file, line) && line.length() && !merger.AddFile(line.c_str()) ) {
return 1;
}
}
} else if( ! merger.AddFile(argv[i]) ) {
if ( skip_errors ) {
std::cerr << "hadd skipping file with error: " << argv[i] << std::endl;
} else {
std::cerr << "hadd exiting due to error in " << argv[i] << std::endl;
return 1;
}
}
}
if (reoptimize) {
merger.SetFastMethod(kFALSE);
} else {
if (merger.HasCompressionChange()) {
// Don't warn if the user any request re-optimization.
std::cout <<"hadd Sources and Target have different compression levels"<<std::endl;
std::cout <<"hadd merging will be slower"<<std::endl;
}
}
merger.SetNotrees(noTrees);
Bool_t status = merger.Merge();
if (status) {
if (verbosity == 1) {
std::cout << "hadd merged " << merger.GetMergeList()->GetEntries() << " input files in " << targetname << ".\n";
}
return 0;
} else {
if (verbosity == 1) {
std::cout << "hadd failure during the merge of " << merger.GetMergeList()->GetEntries() << " input files in " << targetname << ".\n";
}
return 1;
}
}
|
/*
This program will add histograms (see note) and Trees from a list of root files and write them
to a target root file. The target file is newly created and must not be
identical to one of the source files.
Syntax:
hadd targetfile source1 source2 ...
or
hadd -f targetfile source1 source2 ...
(targetfile is overwritten if it exists)
When the -f option is specified, one can also specify the compression
level of the target file. By default the compression level is 1, but
if "-f0" is specified, the target file will not be compressed.
if "-f6" is specified, the compression level 6 will be used.
For example assume 3 files f1, f2, f3 containing histograms hn and Trees Tn
f1 with h1 h2 h3 T1
f2 with h1 h4 T1 T2
f3 with h5
the result of
hadd -f x.root f1.root f2.root f3.root
will be a file x.root with h1 h2 h3 h4 h5 T1 T2
where h1 will be the sum of the 2 histograms in f1 and f2
T1 will be the merge of the Trees in f1 and f2
The files may contain sub-directories.
if the source files contains histograms and Trees, one can skip
the Trees with
hadd -T targetfile source1 source2 ...
Wildcarding and indirect files are also supported
hadd result.root myfil*.root
will merge all files in myfil*.root
hadd result.root file1.root @list.txt file2. root myfil*.root
will merge file1. root, file2. root, all files in myfil*.root
and all files in the indirect text file list.txt ("@" as the first
character of the file indicates an indirect file. An indirect file
is a text file containing a list of other files, including other
indirect files, one line per file).
If the sources and and target compression levels are identical (default),
the program uses the TChain::Merge function with option "fast", ie
the merge will be done without unzipping or unstreaming the baskets
(i.e. direct copy of the raw byte on disk). The "fast" mode is typically
5 times faster than the mode unzipping and unstreaming the baskets.
NOTE1: By default histograms are added. However hadd does not support the case where
histograms have their bit TH1::kIsAverage set.
NOTE2: hadd returns a status code: 0 if OK, -1 otherwise
Authors: Rene Brun, Dirk Geppert, Sven A. Schmidt, [email protected]
: rewritten from scratch by Rene Brun (30 November 2005)
to support files with nested directories.
Toby Burnett implemented the possibility to use indirect files.
*/
#include "RConfig.h"
#include <string>
#include "TFile.h"
#include "THashList.h"
#include "TKey.h"
#include "TObjString.h"
#include "Riostream.h"
#include "TClass.h"
#include "TSystem.h"
#include <stdlib.h>
#include "TFileMerger.h"
//___________________________________________________________________________
int main( int argc, char **argv )
{
if ( argc < 3 || "-h" == std::string(argv[1]) || "--help" == std::string(argv[1]) ) {
std::cout << "Usage: " << argv[0] << " [-f[0-9]] [-k] [-T] [-O] [-n maxopenedfiles] [-v [verbosity]] targetfile source1 [source2 source3 ...]" << std::endl;
std::cout << "This program will add histograms from a list of root files and write them" << std::endl;
std::cout << "to a target root file. The target file is newly created and must not " << std::endl;
std::cout << "exist, or if -f (\"force\") is given, must not be one of the source files." << std::endl;
std::cout << "Supply at least two source files for this to make sense... ;-)" << std::endl;
std::cout << "If the option -k is used, hadd will not exit on corrupt or non-existant input files but skip the offending files instead." << std::endl;
std::cout << "If the option -T is used, Trees are not merged" <<std::endl;
std::cout << "If the option -O is used, when merging TTree, the basket size is re-optimized" <<std::endl;
std::cout << "If the option -v is used, explicitly set the verbosity level; 0 request no output, 99 is the default" <<std::endl;
std::cout << "If the option -n is used, hadd will open at most 'maxopenedfiles' at once, use 0 to request to use the system maximum." << std::endl;
std::cout << "When -the -f option is specified, one can also specify the compression" <<std::endl;
std::cout << "level of the target file. By default the compression level is 1, but" <<std::endl;
std::cout << "if \"-f0\" is specified, the target file will not be compressed." <<std::endl;
std::cout << "if \"-f6\" is specified, the compression level 6 will be used. See TFile::SetCompressionSettings for the support range of value." <<std::endl;
std::cout << "if Target and source files have different compression settings"<<std::endl;
std::cout << " a slower method is used"<<std::endl;
return 1;
}
Bool_t force = kFALSE;
Bool_t skip_errors = kFALSE;
Bool_t reoptimize = kFALSE;
Bool_t noTrees = kFALSE;
Int_t maxopenedfiles = 0;
Int_t verbosity = 99;
int outputPlace = 0;
int ffirst = 2;
Int_t newcomp = 1;
for( int a = 1; a < argc; ++a ) {
if ( strcmp(argv[a],"-T") == 0 ) {
noTrees = kTRUE;
++ffirst;
} else if ( strcmp(argv[a],"-f") == 0 ) {
force = kTRUE;
++ffirst;
} else if ( strcmp(argv[a],"-k") == 0 ) {
skip_errors = kTRUE;
++ffirst;
} else if ( strcmp(argv[a],"-O") == 0 ) {
reoptimize = kTRUE;
++ffirst;
} else if ( strcmp(argv[a],"-n") == 0 ) {
if (a+1 >= argc) {
std::cerr << "Error: no maximum number of opened was provided after -n.\n";
} else {
Long_t request = strtol(argv[a+1], 0, 10);
if (request < kMaxLong && request >= 0) {
maxopenedfiles = (Int_t)request;
++a;
++ffirst;
} else {
std::cerr << "Error: could not parse the max number of opened file passed after -n: " << argv[a+1] << ". We will use the system maximum.\n";
}
}
++ffirst;
} else if ( strcmp(argv[a],"-v") == 0 ) {
if (a+1 == argc || argv[a+1][0] == '-') {
// Verbosity level was not specified use the default:
verbosity = 99;
// if (a+1 >= argc) {
// std::cerr << "Error: no verbosity level was provided after -v.\n";
} else {
Long_t request = -1;
for (char *c = argv[a+1]; *c != '\0'; ++c) {
if (!isdigit(*c)) {
// Verbosity level was not specified use the default:
request = 99;
break;
}
}
if (request == 1) {
request = strtol(argv[a+1], 0, 10);
if (request < kMaxLong && request >= 0) {
verbosity = (Int_t)request;
++a;
++ffirst;
std::cerr << "Error: from " << argv[a+1] << " guess verbosity level : " << verbosity << "\n";
} else {
std::cerr << "Error: could not parse the verbosity level passed after -v: " << argv[a+1] << ". We will use the default value (99).\n";
}
}
}
++ffirst;
} else if ( argv[a][0] == '-' ) {
char ft[6];
for ( int alg = 0; alg <= 2; ++alg ) {
for( int j=0; j<=9; ++j ) {
const int comp = (alg*100)+j;
snprintf(ft,6,"-f%d",comp);
if (!strcmp(argv[a],ft)) {
force = kTRUE;
newcomp = comp;
++ffirst;
break;
}
}
}
if (!force) {
// Bad argument
std::cerr << "Error: option " << argv[a] << " is not a supported option.\n";
++ffirst;
}
} else if (!outputPlace) {
outputPlace = a;
}
}
gSystem->Load("libTreePlayer");
const char *targetname = 0;
if (outputPlace) {
targetname = argv[outputPlace];
} else {
targetname = argv[ffirst-1];
}
if (verbosity > 1) {
std::cout << "hadd Target file: " << targetname << std::endl;
}
TFileMerger merger(kFALSE,kFALSE);
merger.SetMsgPrefix("hadd");
merger.SetPrintLevel(verbosity - 1);
if (maxopenedfiles > 0) {
merger.SetMaxOpenedFiles(maxopenedfiles);
}
if (!merger.OutputFile(targetname,force,newcomp) ) {
std::cerr << "hadd error opening target file (does " << argv[ffirst-1] << " exist?)." << std::endl;
if (!force) std::cerr << "Pass \"-f\" argument to force re-creation of output file." << std::endl;
exit(1);
}
for ( int i = ffirst; i < argc; i++ ) {
if (argv[i] && argv[i][0]=='@') {
std::ifstream indirect_file(argv[i]+1);
if( ! indirect_file.is_open() ) {
std::cerr<< "hadd could not open indirect file " << (argv[i]+1) << std::endl;
return 1;
}
while( indirect_file ){
std::string line;
if( std::getline(indirect_file, line) && line.length() && !merger.AddFile(line.c_str()) ) {
return 1;
}
}
} else if( ! merger.AddFile(argv[i]) ) {
if ( skip_errors ) {
std::cerr << "hadd skipping file with error: " << argv[i] << std::endl;
} else {
std::cerr << "hadd exiting due to error in " << argv[i] << std::endl;
return 1;
}
}
}
if (reoptimize) {
merger.SetFastMethod(kFALSE);
} else {
if (merger.HasCompressionChange()) {
// Don't warn if the user any request re-optimization.
std::cout <<"hadd Sources and Target have different compression levels"<<std::endl;
std::cout <<"hadd merging will be slower"<<std::endl;
}
}
merger.SetNotrees(noTrees);
Bool_t status = merger.Merge();
if (status) {
if (verbosity == 1) {
std::cout << "hadd merged " << merger.GetMergeList()->GetEntries() << " input files in " << targetname << ".\n";
}
return 0;
} else {
if (verbosity == 1) {
std::cout << "hadd failure during the merge of " << merger.GetMergeList()->GetEntries() << " input files in " << targetname << ".\n";
}
return 1;
}
}
|
Make the verbosity level optional after -v
|
Make the verbosity level optional after -v
|
C++
|
lgpl-2.1
|
krafczyk/root,olifre/root,Y--/root,satyarth934/root,omazapa/root,georgtroska/root,beniz/root,abhinavmoudgil95/root,root-mirror/root,agarciamontoro/root,evgeny-boger/root,gbitzes/root,lgiommi/root,mkret2/root,davidlt/root,buuck/root,davidlt/root,satyarth934/root,jrtomps/root,krafczyk/root,gganis/root,gganis/root,root-mirror/root,CristinaCristescu/root,abhinavmoudgil95/root,Y--/root,veprbl/root,gganis/root,georgtroska/root,omazapa/root,simonpf/root,lgiommi/root,evgeny-boger/root,vukasinmilosevic/root,arch1tect0r/root,davidlt/root,CristinaCristescu/root,sbinet/cxx-root,Duraznos/root,georgtroska/root,dfunke/root,pspe/root,veprbl/root,krafczyk/root,Duraznos/root,agarciamontoro/root,perovic/root,zzxuanyuan/root,abhinavmoudgil95/root,evgeny-boger/root,lgiommi/root,beniz/root,omazapa/root,Y--/root,abhinavmoudgil95/root,davidlt/root,BerserkerTroll/root,CristinaCristescu/root,pspe/root,buuck/root,davidlt/root,davidlt/root,buuck/root,krafczyk/root,mhuwiler/rootauto,beniz/root,karies/root,evgeny-boger/root,sbinet/cxx-root,krafczyk/root,buuck/root,vukasinmilosevic/root,krafczyk/root,zzxuanyuan/root,sbinet/cxx-root,buuck/root,esakellari/root,vukasinmilosevic/root,zzxuanyuan/root,simonpf/root,gganis/root,arch1tect0r/root,buuck/root,simonpf/root,dfunke/root,zzxuanyuan/root,sirinath/root,Y--/root,BerserkerTroll/root,zzxuanyuan/root,abhinavmoudgil95/root,CristinaCristescu/root,root-mirror/root,karies/root,omazapa/root,agarciamontoro/root,omazapa/root,mkret2/root,dfunke/root,mhuwiler/rootauto,arch1tect0r/root,simonpf/root,agarciamontoro/root,beniz/root,thomaskeck/root,BerserkerTroll/root,sirinath/root,sbinet/cxx-root,CristinaCristescu/root,gganis/root,mattkretz/root,gbitzes/root,root-mirror/root,CristinaCristescu/root,mattkretz/root,olifre/root,esakellari/root,beniz/root,Y--/root,buuck/root,CristinaCristescu/root,beniz/root,CristinaCristescu/root,sirinath/root,dfunke/root,root-mirror/root,dfunke/root,sawenzel/root,zzxuanyuan/root-compressor-dummy,mkret2/root,dfunke/root,simonpf/root,nilqed/root,abhinavmoudgil95/root,sirinath/root,Y--/root,gganis/root,karies/root,sbinet/cxx-root,evgeny-boger/root,bbockelm/root,lgiommi/root,olifre/root,mhuwiler/rootauto,nilqed/root,dfunke/root,karies/root,nilqed/root,mattkretz/root,Duraznos/root,nilqed/root,krafczyk/root,perovic/root,sbinet/cxx-root,zzxuanyuan/root-compressor-dummy,sawenzel/root,beniz/root,veprbl/root,dfunke/root,olifre/root,agarciamontoro/root,Duraznos/root,mhuwiler/rootauto,satyarth934/root,satyarth934/root,BerserkerTroll/root,jrtomps/root,mhuwiler/rootauto,arch1tect0r/root,agarciamontoro/root,jrtomps/root,veprbl/root,satyarth934/root,root-mirror/root,thomaskeck/root,davidlt/root,krafczyk/root,BerserkerTroll/root,gganis/root,pspe/root,dfunke/root,esakellari/root,olifre/root,georgtroska/root,Y--/root,bbockelm/root,esakellari/root,zzxuanyuan/root-compressor-dummy,esakellari/root,perovic/root,pspe/root,simonpf/root,sawenzel/root,sawenzel/root,perovic/root,Duraznos/root,gbitzes/root,georgtroska/root,karies/root,arch1tect0r/root,nilqed/root,georgtroska/root,lgiommi/root,abhinavmoudgil95/root,agarciamontoro/root,esakellari/root,sbinet/cxx-root,karies/root,abhinavmoudgil95/root,mattkretz/root,olifre/root,esakellari/root,perovic/root,sirinath/root,evgeny-boger/root,bbockelm/root,vukasinmilosevic/root,Duraznos/root,agarciamontoro/root,BerserkerTroll/root,Y--/root,bbockelm/root,omazapa/root,sawenzel/root,sawenzel/root,mattkretz/root,olifre/root,beniz/root,bbockelm/root,pspe/root,buuck/root,zzxuanyuan/root-compressor-dummy,nilqed/root,perovic/root,veprbl/root,jrtomps/root,davidlt/root,agarciamontoro/root,karies/root,simonpf/root,sirinath/root,root-mirror/root,sirinath/root,karies/root,Duraznos/root,mkret2/root,georgtroska/root,sbinet/cxx-root,evgeny-boger/root,zzxuanyuan/root,mkret2/root,jrtomps/root,bbockelm/root,krafczyk/root,jrtomps/root,olifre/root,zzxuanyuan/root-compressor-dummy,evgeny-boger/root,gbitzes/root,georgtroska/root,arch1tect0r/root,simonpf/root,dfunke/root,gbitzes/root,sawenzel/root,sirinath/root,thomaskeck/root,BerserkerTroll/root,zzxuanyuan/root,vukasinmilosevic/root,thomaskeck/root,sawenzel/root,arch1tect0r/root,esakellari/root,perovic/root,bbockelm/root,zzxuanyuan/root,pspe/root,pspe/root,sirinath/root,zzxuanyuan/root-compressor-dummy,gganis/root,jrtomps/root,jrtomps/root,veprbl/root,dfunke/root,agarciamontoro/root,lgiommi/root,mkret2/root,CristinaCristescu/root,perovic/root,lgiommi/root,nilqed/root,sirinath/root,mkret2/root,omazapa/root,bbockelm/root,pspe/root,bbockelm/root,BerserkerTroll/root,gbitzes/root,olifre/root,BerserkerTroll/root,mattkretz/root,lgiommi/root,arch1tect0r/root,zzxuanyuan/root-compressor-dummy,zzxuanyuan/root,root-mirror/root,omazapa/root,evgeny-boger/root,mkret2/root,perovic/root,zzxuanyuan/root-compressor-dummy,georgtroska/root,thomaskeck/root,root-mirror/root,lgiommi/root,zzxuanyuan/root-compressor-dummy,nilqed/root,beniz/root,lgiommi/root,vukasinmilosevic/root,BerserkerTroll/root,veprbl/root,mhuwiler/rootauto,satyarth934/root,krafczyk/root,vukasinmilosevic/root,mhuwiler/rootauto,krafczyk/root,nilqed/root,Duraznos/root,zzxuanyuan/root-compressor-dummy,mkret2/root,jrtomps/root,zzxuanyuan/root,Duraznos/root,sbinet/cxx-root,root-mirror/root,perovic/root,Duraznos/root,davidlt/root,pspe/root,mkret2/root,Y--/root,jrtomps/root,thomaskeck/root,simonpf/root,satyarth934/root,evgeny-boger/root,sbinet/cxx-root,georgtroska/root,gganis/root,root-mirror/root,sirinath/root,Duraznos/root,buuck/root,BerserkerTroll/root,simonpf/root,satyarth934/root,CristinaCristescu/root,arch1tect0r/root,nilqed/root,gbitzes/root,mattkretz/root,mattkretz/root,Y--/root,mattkretz/root,beniz/root,zzxuanyuan/root,mattkretz/root,esakellari/root,sawenzel/root,olifre/root,gganis/root,agarciamontoro/root,thomaskeck/root,karies/root,pspe/root,gbitzes/root,buuck/root,lgiommi/root,CristinaCristescu/root,mhuwiler/rootauto,abhinavmoudgil95/root,mhuwiler/rootauto,bbockelm/root,veprbl/root,sawenzel/root,omazapa/root,olifre/root,mhuwiler/rootauto,vukasinmilosevic/root,thomaskeck/root,bbockelm/root,arch1tect0r/root,sbinet/cxx-root,veprbl/root,vukasinmilosevic/root,gganis/root,simonpf/root,mkret2/root,thomaskeck/root,gbitzes/root,davidlt/root,karies/root,gbitzes/root,georgtroska/root,vukasinmilosevic/root,jrtomps/root,perovic/root,Y--/root,zzxuanyuan/root-compressor-dummy,sawenzel/root,esakellari/root,evgeny-boger/root,mhuwiler/rootauto,karies/root,abhinavmoudgil95/root,omazapa/root,veprbl/root,mattkretz/root,gbitzes/root,thomaskeck/root,buuck/root,arch1tect0r/root,vukasinmilosevic/root,omazapa/root,satyarth934/root,zzxuanyuan/root,satyarth934/root,abhinavmoudgil95/root,veprbl/root,nilqed/root,davidlt/root,satyarth934/root,pspe/root,beniz/root,esakellari/root
|
eb780ae5d46bfba2909d0cdf4b51f636944f7689
|
main/src/hadd.cxx
|
main/src/hadd.cxx
|
/*
This program will add histograms from a list of root files and write them
to a target root file. The target file is newly created and must not be
identical to one of the source files.
Syntax:
hadd targetfile source1 source2 ...
if the source files contains histograms and Trees, one can skip
the Trees with
hadd -T targetfile source1 source2 ...
Authors: Rene Brun, Dirk Geppert, Sven A. Schmidt, [email protected]
*/
#include "RConfig.h"
#include <string>
#include "TChain.h"
#include "TFile.h"
#include "TH1.h"
#include "TKey.h"
#include "Riostream.h"
TList *FileList;
TFile *Target, *Source;
Bool_t noTrees;
void MergeRootfile( TDirectory *target, TList *sourcelist );
int main( int argc, char **argv ) {
if ( argc < 4 || "-h" == string(argv[1]) || "--help" == string(argv[1]) ) {
cout << "Usage: " << argv[0] << " [-f] [-T] targetfile source1 source2 [source3 ...]" << endl;
cout << "This program will add histograms from a list of root files and write them" << endl;
cout << "to a target root file. The target file is newly created and must not " << endl;
cout << "exist, or if -f (\"force\") is given, must not be one of the source files." << endl;
cout << "Supply at least two source files for this to make sense... ;-)" << endl;
cout << "If the first argument is -T, Trees are not merged" <<endl;
return 1;
}
FileList = new TList();
Bool_t force = (!strcmp(argv[1],"-f") || !strcmp(argv[2],"-f"));
noTrees = (!strcmp(argv[1],"-T") || !strcmp(argv[2],"-T"));
int ffirst = 2;
if (force) ffirst++;
if (noTrees) ffirst++;
cout << "Target file: " << argv[ffirst-1] << endl;
Target = TFile::Open( argv[ffirst-1], (force?"RECREATE":"CREATE") );
if (!Target || Target->IsZombie()) {
cerr << "Error opening target file (does " << argv[ffirst-1] << " exist?)." << endl;
cerr << "Pass \"-f\" argument to force re-creation of output file." << endl;
exit(1);
}
// by default hadd can merge Trees in a file that can go up to 100 Gbytes
Long64_t maxsize = 100000000; //100GB
maxsize *= 100; //to bypass some compiler limitations with big constants
TTree::SetMaxTreeSize(maxsize);
for ( int i = ffirst; i < argc; i++ ) {
cout << "Source file " << i-ffirst+1 << ": " << argv[i] << endl;
Source = TFile::Open( argv[i] );
FileList->Add(Source);
}
MergeRootfile( Target, FileList );
//must delete Target to avoid a problem with dictionaries in~ TROOT
delete Target;
return 0;
}
void MergeRootfile( TDirectory *target, TList *sourcelist ) {
// cout << "Target path: " << target->GetPath() << endl;
TString path( (char*)strstr( target->GetPath(), ":" ) );
path.Remove( 0, 2 );
TFile *first_source = (TFile*)sourcelist->First();
first_source->cd( path );
TDirectory *current_sourcedir = gDirectory;
// loop over all keys in this directory
TChain *globChain = 0;
TIter nextkey( current_sourcedir->GetListOfKeys() );
TKey *key, *oldkey=0;
//gain time, do not add the objects in the list in memory
TH1::AddDirectory(kFALSE);
while ( (key = (TKey*)nextkey())) {
//keep only the highest cycle number for each key
if (oldkey && !strcmp(oldkey->GetName(),key->GetName())) continue;
// read object from first source file
first_source->cd( path );
TObject *obj = key->ReadObj();
if ( obj->IsA()->InheritsFrom( TH1::Class() ) ) {
// descendant of TH1 -> merge it
// cout << "Merging histogram " << obj->GetName() << endl;
TH1 *h1 = (TH1*)obj;
TList listH;
// loop over all source files and add the content of the
// correspondant histogram to the one pointed to by "h1"
TFile *nextsource = (TFile*)sourcelist->After( first_source );
while ( nextsource ) {
// make sure we are at the correct directory level by cd'ing to path
nextsource->cd( path );
TKey *key2 = (TKey*)gDirectory->GetListOfKeys()->FindObject(h1->GetName());
if (key2) {
listH.Add(key2->ReadObj());
h1->Merge(&listH);
listH.Delete();
}
nextsource = (TFile*)sourcelist->After( nextsource );
}
}
else if ( obj->IsA()->InheritsFrom( "TTree" ) ) {
// loop over all source files create a chain of Trees "globChain"
if (!noTrees) {
TString obj_name;
if (path.Length()) {
obj_name = path + "/" + obj->GetName();
} else {
obj_name = obj->GetName();
}
globChain = new TChain(obj_name);
globChain->Add(first_source->GetName());
TFile *nextsource = (TFile*)sourcelist->After( first_source );
// const char* file_name = nextsource->GetName();
// cout << "file name " << file_name << endl;
while ( nextsource ) {
globChain->Add(nextsource->GetName());
nextsource = (TFile*)sourcelist->After( nextsource );
}
}
} else if ( obj->IsA()->InheritsFrom( "TDirectory" ) ) {
// it's a subdirectory
cout << "Found subdirectory " << obj->GetName() << endl;
// create a new subdir of same name and title in the target file
target->cd();
TDirectory *newdir = target->mkdir( obj->GetName(), obj->GetTitle() );
// newdir is now the starting point of another round of merging
// newdir still knows its depth within the target file via
// GetPath(), so we can still figure out where we are in the recursion
MergeRootfile( newdir, sourcelist );
} else {
// object is of no type that we know or can handle
cout << "Unknown object type, name: "
<< obj->GetName() << " title: " << obj->GetTitle() << endl;
}
// now write the merged histogram (which is "in" obj) to the target file
// note that this will just store obj in the current directory level,
// which is not persistent until the complete directory itself is stored
// by "target->Write()" below
if ( obj ) {
target->cd();
//!!if the object is a tree, it is stored in globChain...
if(obj->IsA()->InheritsFrom( "TTree" )) {
if (!noTrees) {
globChain->Merge(target->GetFile(),0,"keep");
delete globChain;
}
} else {
obj->Write( key->GetName() );
}
}
oldkey = key;
} // while ( ( TKey *key = (TKey*)nextkey() ) )
// save modifications to target file
target->SaveSelf(kTRUE);
}
|
/*
This program will add histograms from a list of root files and write them
to a target root file. The target file is newly created and must not be
identical to one of the source files.
Syntax:
hadd targetfile source1 source2 ...
or
hadd -f targetfile source1 source2 ...
(targetfile is overwritten if it exists)
For example assume 3 files f1, f2, f3 containing histograms hn and Trees Tn
f1 with h1 h2 h3 T1
f2 with h1 h4 T1 T2
f3 with h5
the result of
hadd -f x.root f1.root f2.root f3.root
will be a file x.root with
x with h1 h2 h3 h4 h5 T1 T2
where h1 will be the sum of the 2 histograms in f1 and f2
T1 will be the merge of the Trees in f1 and f2
if the source files contains histograms and Trees, one can skip
the Trees with
hadd -T targetfile source1 source2 ...
Authors: Rene Brun, Dirk Geppert, Sven A. Schmidt, [email protected]
*/
#include "RConfig.h"
#include <string>
#include "TChain.h"
#include "TFile.h"
#include "TH1.h"
#include "TKey.h"
#include "TObjString.h"
#include "Riostream.h"
TList *FileList;
TFile *Target, *Source;
Bool_t noTrees;
void MergeRootfile( TDirectory *target, TList *sourcelist );
int main( int argc, char **argv ) {
if ( argc < 4 || "-h" == string(argv[1]) || "--help" == string(argv[1]) ) {
cout << "Usage: " << argv[0] << " [-f] [-T] targetfile source1 source2 [source3 ...]" << endl;
cout << "This program will add histograms from a list of root files and write them" << endl;
cout << "to a target root file. The target file is newly created and must not " << endl;
cout << "exist, or if -f (\"force\") is given, must not be one of the source files." << endl;
cout << "Supply at least two source files for this to make sense... ;-)" << endl;
cout << "If the first argument is -T, Trees are not merged" <<endl;
return 1;
}
FileList = new TList();
Bool_t force = (!strcmp(argv[1],"-f") || !strcmp(argv[2],"-f"));
noTrees = (!strcmp(argv[1],"-T") || !strcmp(argv[2],"-T"));
int ffirst = 2;
if (force) ffirst++;
if (noTrees) ffirst++;
cout << "Target file: " << argv[ffirst-1] << endl;
Target = TFile::Open( argv[ffirst-1], (force?"RECREATE":"CREATE") );
if (!Target || Target->IsZombie()) {
cerr << "Error opening target file (does " << argv[ffirst-1] << " exist?)." << endl;
cerr << "Pass \"-f\" argument to force re-creation of output file." << endl;
exit(1);
}
// by default hadd can merge Trees in a file that can go up to 100 Gbytes
Long64_t maxsize = 100000000; //100GB
maxsize *= 100; //to bypass some compiler limitations with big constants
TTree::SetMaxTreeSize(maxsize);
for ( int i = ffirst; i < argc; i++ ) {
cout << "Source file " << i-ffirst+1 << ": " << argv[i] << endl;
Source = TFile::Open( argv[i] );
FileList->Add(Source);
}
MergeRootfile( Target, FileList );
//must delete Target to avoid a problem with dictionaries in~ TROOT
delete Target;
return 0;
}
void MergeRootfile( TDirectory *target, TList *sourcelist ) {
// cout << "Target path: " << target->GetPath() << endl;
TString path( (char*)strstr( target->GetPath(), ":" ) );
path.Remove( 0, 2 );
TFile *first_source = (TFile*)sourcelist->First();
THashList allNames;
while(first_source) {
first_source->cd( path );
TDirectory *current_sourcedir = gDirectory;
// loop over all keys in this directory
TChain *globChain = 0;
TIter nextkey( current_sourcedir->GetListOfKeys() );
TKey *key, *oldkey=0;
//gain time, do not add the objects in the list in memory
TH1::AddDirectory(kFALSE);
while ( (key = (TKey*)nextkey())) {
//keep only the highest cycle number for each key
if (oldkey && !strcmp(oldkey->GetName(),key->GetName())) continue;
if (allNames.FindObject(key->GetName())) continue;
allNames.Add(new TObjString(key->GetName()));
// read object from first source file
first_source->cd( path );
TObject *obj = key->ReadObj();
if ( obj->IsA()->InheritsFrom( TH1::Class() ) ) {
// descendant of TH1 -> merge it
//cout << "Merging histogram " << obj->GetName() << endl;
TH1 *h1 = (TH1*)obj;
TList listH;
// loop over all source files and add the content of the
// correspondant histogram to the one pointed to by "h1"
TFile *nextsource = (TFile*)sourcelist->After( first_source );
while ( nextsource ) {
// make sure we are at the correct directory level by cd'ing to path
nextsource->cd( path );
TKey *key2 = (TKey*)gDirectory->GetListOfKeys()->FindObject(h1->GetName());
if (key2) {
listH.Add(key2->ReadObj());
h1->Merge(&listH);
listH.Delete();
}
nextsource = (TFile*)sourcelist->After( nextsource );
}
}
else if ( obj->IsA()->InheritsFrom( "TTree" ) ) {
// loop over all source files create a chain of Trees "globChain"
if (!noTrees) {
TString obj_name;
if (path.Length()) {
obj_name = path + "/" + obj->GetName();
} else {
obj_name = obj->GetName();
}
globChain = new TChain(obj_name);
globChain->Add(first_source->GetName());
TFile *nextsource = (TFile*)sourcelist->After( first_source );
// const char* file_name = nextsource->GetName();
// cout << "file name " << file_name << endl;
while ( nextsource ) {
//do not add to the list a file that does not contain this Tree
TFile *curf = TFile::Open(nextsource->GetName());
if (curf && curf->FindObject(obj_name)) {
globChain->Add(nextsource->GetName());
}
delete curf;
nextsource = (TFile*)sourcelist->After( nextsource );
}
}
} else if ( obj->IsA()->InheritsFrom( "TDirectory" ) ) {
// it's a subdirectory
cout << "Found subdirectory " << obj->GetName() << endl;
// create a new subdir of same name and title in the target file
target->cd();
TDirectory *newdir = target->mkdir( obj->GetName(), obj->GetTitle() );
// newdir is now the starting point of another round of merging
// newdir still knows its depth within the target file via
// GetPath(), so we can still figure out where we are in the recursion
MergeRootfile( newdir, sourcelist );
} else {
// object is of no type that we know or can handle
cout << "Unknown object type, name: "
<< obj->GetName() << " title: " << obj->GetTitle() << endl;
}
// now write the merged histogram (which is "in" obj) to the target file
// note that this will just store obj in the current directory level,
// which is not persistent until the complete directory itself is stored
// by "target->Write()" below
if ( obj ) {
target->cd();
//!!if the object is a tree, it is stored in globChain...
if(obj->IsA()->InheritsFrom( "TTree" )) {
if (!noTrees) {
globChain->Merge(target->GetFile(),0,"keep");
delete globChain;
}
} else {
obj->Write( key->GetName() );
}
}
oldkey = key;
} // while ( ( TKey *key = (TKey*)nextkey() ) )
sourcelist->Remove(first_source);
first_source = (TFile*)sourcelist->First();
}
// save modifications to target file
target->SaveSelf(kTRUE);
}
|
Extend functionality of hadd. The new version can store in the result file histograms or Trees that are not found in the first file but are present in any other file. For example assume 3 files f1, f2, f3 containing histograms hn and Trees Tn f1 with h1 h2 h3 T1 f2 with h1 h4 T1 T2 f3 with h5 the result of hadd -f x.root f1.root f2.root f3.root will be a file x.root with x with h1 h2 h3 h4 h5 T1 T2 where h1 will be the sum of the 2 histograms in f1 and f2 T1 will be the merge of the Trees in f1 and f2
|
Extend functionality of hadd. The new version can store in the result file
histograms or Trees that are not found in the first file but are present
in any other file.
For example assume 3 files f1, f2, f3 containing histograms hn and Trees Tn
f1 with h1 h2 h3 T1
f2 with h1 h4 T1 T2
f3 with h5
the result of
hadd -f x.root f1.root f2.root f3.root
will be a file x.root with
x with h1 h2 h3 h4 h5 T1 T2
where h1 will be the sum of the 2 histograms in f1 and f2
T1 will be the merge of the Trees in f1 and f2
git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@13169 27541ba8-7e3a-0410-8455-c3a389f83636
|
C++
|
lgpl-2.1
|
mkret2/root,sirinath/root,jrtomps/root,tc3t/qoot,root-mirror/root,karies/root,satyarth934/root,gganis/root,BerserkerTroll/root,jrtomps/root,krafczyk/root,zzxuanyuan/root-compressor-dummy,Dr15Jones/root,zzxuanyuan/root,omazapa/root,sbinet/cxx-root,krafczyk/root,agarciamontoro/root,beniz/root,Y--/root,olifre/root,pspe/root,beniz/root,olifre/root,thomaskeck/root,esakellari/my_root_for_test,tc3t/qoot,smarinac/root,abhinavmoudgil95/root,mhuwiler/rootauto,Dr15Jones/root,sawenzel/root,vukasinmilosevic/root,zzxuanyuan/root-compressor-dummy,olifre/root,sirinath/root,BerserkerTroll/root,agarciamontoro/root,sbinet/cxx-root,arch1tect0r/root,dfunke/root,bbockelm/root,CristinaCristescu/root,olifre/root,Dr15Jones/root,CristinaCristescu/root,arch1tect0r/root,mhuwiler/rootauto,pspe/root,dfunke/root,strykejern/TTreeReader,0x0all/ROOT,buuck/root,esakellari/root,mkret2/root,nilqed/root,esakellari/my_root_for_test,thomaskeck/root,lgiommi/root,kirbyherm/root-r-tools,root-mirror/root,gganis/root,nilqed/root,mkret2/root,satyarth934/root,evgeny-boger/root,omazapa/root-old,satyarth934/root,omazapa/root,0x0all/ROOT,cxx-hep/root-cern,cxx-hep/root-cern,CristinaCristescu/root,esakellari/my_root_for_test,nilqed/root,perovic/root,Y--/root,sirinath/root,gganis/root,smarinac/root,satyarth934/root,tc3t/qoot,krafczyk/root,veprbl/root,gganis/root,lgiommi/root,bbockelm/root,0x0all/ROOT,evgeny-boger/root,omazapa/root,esakellari/root,nilqed/root,mkret2/root,beniz/root,beniz/root,veprbl/root,Y--/root,omazapa/root,davidlt/root,omazapa/root-old,esakellari/root,cxx-hep/root-cern,esakellari/my_root_for_test,buuck/root,bbockelm/root,satyarth934/root,simonpf/root,satyarth934/root,Duraznos/root,esakellari/my_root_for_test,zzxuanyuan/root-compressor-dummy,veprbl/root,sawenzel/root,zzxuanyuan/root,agarciamontoro/root,karies/root,veprbl/root,Duraznos/root,krafczyk/root,vukasinmilosevic/root,perovic/root,buuck/root,mattkretz/root,esakellari/my_root_for_test,davidlt/root,BerserkerTroll/root,abhinavmoudgil95/root,zzxuanyuan/root,Y--/root,georgtroska/root,pspe/root,mkret2/root,perovic/root,mkret2/root,Duraznos/root,buuck/root,olifre/root,dfunke/root,gbitzes/root,arch1tect0r/root,perovic/root,simonpf/root,mattkretz/root,olifre/root,karies/root,veprbl/root,zzxuanyuan/root,mkret2/root,BerserkerTroll/root,kirbyherm/root-r-tools,pspe/root,abhinavmoudgil95/root,perovic/root,zzxuanyuan/root,lgiommi/root,agarciamontoro/root,esakellari/my_root_for_test,karies/root,smarinac/root,abhinavmoudgil95/root,Duraznos/root,root-mirror/root,CristinaCristescu/root,nilqed/root,ffurano/root5,mhuwiler/rootauto,davidlt/root,sbinet/cxx-root,abhinavmoudgil95/root,thomaskeck/root,nilqed/root,abhinavmoudgil95/root,sirinath/root,gbitzes/root,sawenzel/root,CristinaCristescu/root,gbitzes/root,veprbl/root,olifre/root,davidlt/root,dfunke/root,sawenzel/root,zzxuanyuan/root-compressor-dummy,satyarth934/root,nilqed/root,buuck/root,BerserkerTroll/root,sbinet/cxx-root,Duraznos/root,strykejern/TTreeReader,kirbyherm/root-r-tools,lgiommi/root,bbockelm/root,arch1tect0r/root,georgtroska/root,vukasinmilosevic/root,buuck/root,perovic/root,krafczyk/root,jrtomps/root,pspe/root,root-mirror/root,smarinac/root,zzxuanyuan/root-compressor-dummy,zzxuanyuan/root-compressor-dummy,nilqed/root,sbinet/cxx-root,root-mirror/root,BerserkerTroll/root,mattkretz/root,satyarth934/root,arch1tect0r/root,abhinavmoudgil95/root,lgiommi/root,Duraznos/root,beniz/root,beniz/root,Dr15Jones/root,zzxuanyuan/root,lgiommi/root,dfunke/root,mattkretz/root,BerserkerTroll/root,omazapa/root,karies/root,gbitzes/root,0x0all/ROOT,sbinet/cxx-root,georgtroska/root,BerserkerTroll/root,omazapa/root-old,zzxuanyuan/root-compressor-dummy,cxx-hep/root-cern,cxx-hep/root-cern,omazapa/root,gbitzes/root,bbockelm/root,pspe/root,buuck/root,Duraznos/root,0x0all/ROOT,simonpf/root,gbitzes/root,jrtomps/root,gganis/root,georgtroska/root,vukasinmilosevic/root,omazapa/root,simonpf/root,omazapa/root-old,nilqed/root,sirinath/root,Dr15Jones/root,thomaskeck/root,buuck/root,Y--/root,perovic/root,zzxuanyuan/root-compressor-dummy,krafczyk/root,root-mirror/root,perovic/root,arch1tect0r/root,agarciamontoro/root,agarciamontoro/root,mhuwiler/rootauto,Y--/root,evgeny-boger/root,simonpf/root,perovic/root,thomaskeck/root,kirbyherm/root-r-tools,agarciamontoro/root,simonpf/root,agarciamontoro/root,sirinath/root,tc3t/qoot,veprbl/root,alexschlueter/cern-root,strykejern/TTreeReader,evgeny-boger/root,vukasinmilosevic/root,sawenzel/root,lgiommi/root,zzxuanyuan/root,mhuwiler/rootauto,Duraznos/root,karies/root,root-mirror/root,sirinath/root,evgeny-boger/root,0x0all/ROOT,dfunke/root,vukasinmilosevic/root,evgeny-boger/root,sawenzel/root,abhinavmoudgil95/root,tc3t/qoot,evgeny-boger/root,bbockelm/root,perovic/root,cxx-hep/root-cern,zzxuanyuan/root,buuck/root,krafczyk/root,mhuwiler/rootauto,BerserkerTroll/root,cxx-hep/root-cern,sirinath/root,georgtroska/root,gganis/root,zzxuanyuan/root,veprbl/root,mhuwiler/rootauto,thomaskeck/root,agarciamontoro/root,pspe/root,kirbyherm/root-r-tools,veprbl/root,krafczyk/root,lgiommi/root,Y--/root,sirinath/root,strykejern/TTreeReader,evgeny-boger/root,mattkretz/root,krafczyk/root,krafczyk/root,georgtroska/root,Y--/root,bbockelm/root,alexschlueter/cern-root,mkret2/root,sirinath/root,omazapa/root-old,evgeny-boger/root,Dr15Jones/root,simonpf/root,tc3t/qoot,bbockelm/root,gbitzes/root,pspe/root,smarinac/root,ffurano/root5,root-mirror/root,vukasinmilosevic/root,veprbl/root,bbockelm/root,tc3t/qoot,BerserkerTroll/root,lgiommi/root,abhinavmoudgil95/root,0x0all/ROOT,georgtroska/root,dfunke/root,davidlt/root,zzxuanyuan/root,jrtomps/root,mhuwiler/rootauto,esakellari/root,CristinaCristescu/root,agarciamontoro/root,olifre/root,satyarth934/root,esakellari/root,dfunke/root,cxx-hep/root-cern,davidlt/root,georgtroska/root,ffurano/root5,omazapa/root,beniz/root,omazapa/root-old,nilqed/root,0x0all/ROOT,ffurano/root5,smarinac/root,nilqed/root,esakellari/root,jrtomps/root,CristinaCristescu/root,jrtomps/root,sawenzel/root,evgeny-boger/root,gbitzes/root,thomaskeck/root,karies/root,dfunke/root,gganis/root,Duraznos/root,ffurano/root5,mhuwiler/rootauto,Dr15Jones/root,buuck/root,davidlt/root,mattkretz/root,kirbyherm/root-r-tools,bbockelm/root,Duraznos/root,mhuwiler/rootauto,strykejern/TTreeReader,sbinet/cxx-root,jrtomps/root,alexschlueter/cern-root,pspe/root,ffurano/root5,karies/root,strykejern/TTreeReader,omazapa/root,mattkretz/root,omazapa/root,gbitzes/root,davidlt/root,gganis/root,krafczyk/root,CristinaCristescu/root,arch1tect0r/root,esakellari/root,beniz/root,mattkretz/root,dfunke/root,CristinaCristescu/root,sbinet/cxx-root,sbinet/cxx-root,vukasinmilosevic/root,sawenzel/root,esakellari/my_root_for_test,BerserkerTroll/root,vukasinmilosevic/root,simonpf/root,pspe/root,agarciamontoro/root,buuck/root,ffurano/root5,simonpf/root,gbitzes/root,0x0all/ROOT,arch1tect0r/root,alexschlueter/cern-root,zzxuanyuan/root-compressor-dummy,CristinaCristescu/root,omazapa/root-old,tc3t/qoot,Y--/root,root-mirror/root,omazapa/root-old,zzxuanyuan/root,abhinavmoudgil95/root,root-mirror/root,tc3t/qoot,zzxuanyuan/root-compressor-dummy,esakellari/root,Y--/root,satyarth934/root,omazapa/root,Duraznos/root,simonpf/root,georgtroska/root,thomaskeck/root,olifre/root,arch1tect0r/root,root-mirror/root,esakellari/my_root_for_test,omazapa/root-old,strykejern/TTreeReader,esakellari/root,davidlt/root,tc3t/qoot,thomaskeck/root,abhinavmoudgil95/root,sawenzel/root,evgeny-boger/root,alexschlueter/cern-root,georgtroska/root,smarinac/root,bbockelm/root,gganis/root,smarinac/root,davidlt/root,smarinac/root,kirbyherm/root-r-tools,beniz/root,beniz/root,mattkretz/root,davidlt/root,simonpf/root,sawenzel/root,esakellari/root,sbinet/cxx-root,jrtomps/root,gganis/root,omazapa/root-old,jrtomps/root,gganis/root,vukasinmilosevic/root,sirinath/root,beniz/root,arch1tect0r/root,mkret2/root,mhuwiler/rootauto,mkret2/root,zzxuanyuan/root,thomaskeck/root,jrtomps/root,lgiommi/root,alexschlueter/cern-root,pspe/root,zzxuanyuan/root-compressor-dummy,vukasinmilosevic/root,satyarth934/root,CristinaCristescu/root,Y--/root,veprbl/root,gbitzes/root,karies/root,mattkretz/root,esakellari/root,smarinac/root,mattkretz/root,esakellari/my_root_for_test,perovic/root,alexschlueter/cern-root,arch1tect0r/root,sawenzel/root,karies/root,georgtroska/root,karies/root,lgiommi/root,mkret2/root,dfunke/root,olifre/root,omazapa/root-old,olifre/root,sbinet/cxx-root
|
14a4677c66504a79b499a0f08985d28788c7d7e7
|
envcontext_processor.cpp
|
envcontext_processor.cpp
|
#include "stdafx.h"
#include "envcontext_processor.h"
#include "EnVistasGeometryPlugin.h"
#include <Maplayer.h>
#include "SHP3D.h"
#include <cstring>
#include <thread>
using std::string;
using std::thread;
static const string shp3dRegisterName("vip_core_shpviewer");
#ifdef _DEBUG
static const string shp3dPath("E:/Vault/envision_source/x64/Debug/shp3d.dll");
#else
static const string shp3dPath("E:/Vault/envision_source/x64/Release/shp3d.dll");
#endif
static shared_ptr<VI_VizPlugin3D> LoadSHP3DDLL(const VI_Path& path) {
if (!gPluginMgr->LoadPlugin(path)) {
return shared_ptr<VI_VizPlugin3D>();
}
auto plugin = gPluginMgr->GetPluginInstance(shp3dRegisterName);
auto shp3dPlugin = dynamic_cast<SHP3D*>(plugin);
if (!shp3dPlugin) {
return shared_ptr<VI_VizPlugin3D>();
}
return shared_ptr<VI_VizPlugin3D>(shp3dPlugin);
}
SHP3DProcessor::SHP3DProcessor(const EnvContext* context, VI_Scene& scene) :
_envContext(context), _scene(scene), _lastActiveField(-1)
{
_dataPlugin.reset(new EnVistasGeometryPlugin(context->pMapLayer));
VI_Path path(shp3dPath);
assert(path.Exists());
_vizPlugin = LoadSHP3DDLL(path);
thread task(*this);
task.detach();
}
void SHP3DProcessor::operator()() {
while (true) {
if (_envContext->pMapLayer->m_activeField != _lastActiveField) {
_lastActiveField = _envContext->pMapLayer->m_activeField;
const int irrelevant = 0;
_vizPlugin->SetData(_dataPlugin.get(), irrelevant);
_scene.RemoveAllObjects();
_vizPlugin->SetScene(_scene);
}
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
}
|
#include "stdafx.h"
#include "envcontext_processor.h"
#include "EnVistasGeometryPlugin.h"
#include <Maplayer.h>
#include "SHP3D.h"
#include <cstring>
#include <thread>
#include "SHP3DVizPlugin.h"
using std::string;
using std::thread;
static const string shp3dRegisterName("vip_core_shpviewer");
#ifdef _DEBUG
static const string shp3dPath("E:/Vault/envision_source/x64/Debug/shp3d.dll");
#else
static const string shp3dPath("E:/Vault/envision_source/x64/Release/shp3d.dll");
#endif
static shared_ptr<VI_VizPlugin3D> LoadSHP3DDLL(const VI_Path& path) {
if (!gPluginMgr->LoadPlugin(path)) {
return shared_ptr<VI_VizPlugin3D>();
}
auto plugin = gPluginMgr->GetPluginInstance(shp3dRegisterName);
auto shp3dPlugin = dynamic_cast<SHP3D*>(plugin);
if (!shp3dPlugin) {
return shared_ptr<VI_VizPlugin3D>();
}
return shared_ptr<VI_VizPlugin3D>(shp3dPlugin);
}
SHP3DProcessor::SHP3DProcessor(const EnvContext* context, VI_Scene& scene) :
_envContext(context), _scene(scene), _lastActiveField(-1)
{
_dataPlugin.reset(new EnVistasGeometryPlugin(context->pMapLayer));
VI_Path path(shp3dPath);
assert(path.Exists());
_vizPlugin = LoadSHP3DDLL(path);
thread task(*this);
task.detach();
}
void SHP3DProcessor::operator()() {
while (true) {
if (_envContext->pMapLayer->m_activeField != _lastActiveField) {
_lastActiveField = _envContext->pMapLayer->m_activeField;
const int irrelevant = 0;
_vizPlugin->SetData(_dataPlugin.get(), irrelevant);
_scene.RemoveAllObjects();
_vizPlugin->SetScene(_scene);
}
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
}
|
include new vizplugin header after vistas reorganization.
|
include new vizplugin header after vistas reorganization.
|
C++
|
apache-2.0
|
ratanasv/EnVistas
|
43387c81de38e3cdcafa703b53191b9d1a8b77d5
|
test/gtx/gtx_fast_trigonometry.cpp
|
test/gtx/gtx_fast_trigonometry.cpp
|
///////////////////////////////////////////////////////////////////////////////////////////////////
// OpenGL Mathematics Copyright (c) 2005 - 2014 G-Truc Creation (www.g-truc.net)
///////////////////////////////////////////////////////////////////////////////////////////////////
// Created : 2013-10-25
// Updated : 2013-10-25
// Licence : This source is under MIT licence
// File : test/gtx/fast_trigonometry.cpp
///////////////////////////////////////////////////////////////////////////////////////////////////
#include <glm/gtc/type_precision.hpp>
#include <glm/gtx/fast_trigonometry.hpp>
#include <ctime>
#include <cstdio>
namespace fastCos{
int perf()
{
const float begin = -glm::pi<float>();
const float end = glm::pi<float>();
float result = 0.f;
const std::clock_t timestamp1 = std::clock();
for(float i=begin; i<end; i = nextafterf(i, end))
result = glm::fastCos(i);
const std::clock_t timestamp2 = std::clock();
for(float i=begin; i<end; i = nextafterf(i, end))
result = glm::cos(i);
const std::clock_t timestamp3 = std::clock();
const std::clock_t time_fastCos = timestamp2 - timestamp1;
const std::clock_t time_cos = timestamp3 - timestamp2;
std::printf("fastCos Time %d clocks\n", static_cast<unsigned int>(time_fastCos));
std::printf("cos Time %d clocks\n", static_cast<unsigned int>(time_cos));
return time_fastCos < time_cos ? 0 : 1;
}
}
namespace fastSin{
int perf()
{
const float begin = -glm::pi<float>();
const float end = glm::pi<float>();
float result = 0.f;
const std::clock_t timestamp1 = std::clock();
for (float i = begin; i<end; i = nextafterf(i, end))
result = glm::fastSin(i);
const std::clock_t timestamp2 = std::clock();
for (float i = begin; i<end; i = nextafterf(i, end))
result = glm::sin(i);
const std::clock_t timestamp3 = std::clock();
const std::clock_t time_fast = timestamp2 - timestamp1;
const std::clock_t time_default = timestamp3 - timestamp2;
std::printf("fastSin Time %d clocks\n", static_cast<unsigned int>(time_fast));
std::printf("sin Time %d clocks\n", static_cast<unsigned int>(time_default));
return time_fast < time_default ? 0 : 1;
}
}
namespace fastTan{
int perf()
{
const float begin = -glm::pi<float>();
const float end = glm::pi<float>();
float result = 0.f;
const std::clock_t timestamp1 = std::clock();
for (float i = begin; i<end; i = nextafterf(i, end))
result = glm::fastTan(i);
const std::clock_t timestamp2 = std::clock();
for (float i = begin; i<end; i = nextafterf(i, end))
result = glm::tan(i);
const std::clock_t timestamp3 = std::clock();
const std::clock_t time_fast = timestamp2 - timestamp1;
const std::clock_t time_default = timestamp3 - timestamp2;
std::printf("fastTan Time %d clocks\n", static_cast<unsigned int>(time_fast));
std::printf("tan Time %d clocks\n", static_cast<unsigned int>(time_default));
return time_fast < time_default ? 0 : 1;
}
}
int main()
{
int Error(0);
Error += ::fastCos::perf();
Error += ::fastSin::perf();
Error += ::fastTan::perf();
return Error;
}
|
///////////////////////////////////////////////////////////////////////////////////////////////////
// OpenGL Mathematics Copyright (c) 2005 - 2014 G-Truc Creation (www.g-truc.net)
///////////////////////////////////////////////////////////////////////////////////////////////////
// Created : 2013-10-25
// Updated : 2013-10-25
// Licence : This source is under MIT licence
// File : test/gtx/fast_trigonometry.cpp
///////////////////////////////////////////////////////////////////////////////////////////////////
#include <glm/gtc/type_precision.hpp>
#include <glm/gtx/fast_trigonometry.hpp>
#include <ctime>
#include <cstdio>
namespace fastCos{
int perf()
{
const float begin = -glm::pi<float>();
const float end = glm::pi<float>();
float result = 0.f;
const std::clock_t timestamp1 = std::clock();
for(float i=begin; i<end; i = nextafterf(i, end))
result = glm::fastCos(i);
const std::clock_t timestamp2 = std::clock();
for(float i=begin; i<end; i = nextafterf(i, end))
result = glm::cos(i);
const std::clock_t timestamp3 = std::clock();
const std::clock_t time_fastCos = timestamp2 - timestamp1;
const std::clock_t time_cos = timestamp3 - timestamp2;
std::printf("fastCos Time %d clocks\n", static_cast<unsigned int>(time_fastCos));
std::printf("cos Time %d clocks\n", static_cast<unsigned int>(time_cos));
return time_fastCos < time_cos ? 0 : 1;
}
}
namespace fastSin{
int perf()
{
const float begin = -glm::pi<float>();
const float end = glm::pi<float>();
float result = 0.f;
const std::clock_t timestamp1 = std::clock();
for (float i = begin; i<end; i = nextafterf(i, end))
result = glm::fastSin(i);
const std::clock_t timestamp2 = std::clock();
for (float i = begin; i<end; i = nextafterf(i, end))
result = glm::sin(i);
const std::clock_t timestamp3 = std::clock();
const std::clock_t time_fast = timestamp2 - timestamp1;
const std::clock_t time_default = timestamp3 - timestamp2;
std::printf("fastSin Time %d clocks\n", static_cast<unsigned int>(time_fast));
std::printf("sin Time %d clocks\n", static_cast<unsigned int>(time_default));
return time_fast < time_default ? 0 : 1;
}
}
namespace fastTan{
int perf()
{
const float begin = -glm::pi<float>();
const float end = glm::pi<float>();
float result = 0.f;
const std::clock_t timestamp1 = std::clock();
for (float i = begin; i<end; i = nextafterf(i, end))
result = glm::fastTan(i);
const std::clock_t timestamp2 = std::clock();
for (float i = begin; i<end; i = nextafterf(i, end))
result = glm::tan(i);
const std::clock_t timestamp3 = std::clock();
const std::clock_t time_fast = timestamp2 - timestamp1;
const std::clock_t time_default = timestamp3 - timestamp2;
std::printf("fastTan Time %d clocks\n", static_cast<unsigned int>(time_fast));
std::printf("tan Time %d clocks\n", static_cast<unsigned int>(time_default));
return time_fast < time_default ? 0 : 1;
}
}
namespace fastAcos{
int perf()
{
const float begin = -glm::pi<float>();
const float end = glm::pi<float>();
float result = 0.f;
const std::clock_t timestamp1 = std::clock();
for (float i = begin; i<end; i = nextafterf(i, end))
result = glm::fastAcos(i);
const std::clock_t timestamp2 = std::clock();
for (float i = begin; i<end; i = nextafterf(i, end))
result = glm::acos(i);
const std::clock_t timestamp3 = std::clock();
const std::clock_t time_fast = timestamp2 - timestamp1;
const std::clock_t time_default = timestamp3 - timestamp2;
std::printf("fastAcos Time %d clocks\n", static_cast<unsigned int>(time_fast));
std::printf("acos Time %d clocks\n", static_cast<unsigned int>(time_default));
return time_fast < time_default ? 0 : 1;
}
}
int main()
{
int Error(0);
Error += ::fastCos::perf();
Error += ::fastSin::perf();
Error += ::fastTan::perf();
Error += ::fastAcos::perf();
return Error;
}
|
test perf fastAcos
|
test perf fastAcos
|
C++
|
mit
|
hrehfeld/glm,hrehfeld/glm
|
8f69a98eb31ddfae2a79b9f107c837b4bb8fbbe5
|
test/integration-test/UserTest.cpp
|
test/integration-test/UserTest.cpp
|
#include "AuthenticatedClient.h"
#include <gmock/gmock.h>
#include <memory>
using namespace Instagram;
using namespace testing;
TEST(UserTest, findsUserById)
{
ClientPtr client = CreateClient("d7b1086490044ada88da482a87b073f3");
UserPtr user = client->findUserById("1479058533");
EXPECT_THAT(user->getId(), StrEq("1479058533"));
EXPECT_THAT(user->getUsername(), StrEq("coconut_beard"));
EXPECT_THAT(user->getFullName(), StrEq("CB"));
EXPECT_THAT(user->getProfilePicture(), StrEq("http://photos-c.ak.instagram.com/hphotos-ak-xaf1/10654924_727813450634146_619431088_a.jpg"));
EXPECT_THAT(user->getBio(), StrEq("I'm bearded."));
EXPECT_THAT(user->getWebsite(), StrEq("http://en.wikipedia.org/wiki/Beard"));
EXPECT_THAT(user->getMediaCount(), 2);
EXPECT_THAT(user->getFollowsCount(), 20);
EXPECT_THAT(user->getFollowedByCount(), 10);
}
TEST(FeedTest, getsFeed)
{
AuthenticatedClientPtr client = CreateAuthenticatedClient("1479058533.d7b1086.6abab8dee8e140afa8ee6b8b7f7318c5");
Feed feed = client->getFeed(10);
ASSERT_THAT(feed, SizeIs(10));
}
|
#include "AuthenticatedClient.h"
#include <gmock/gmock.h>
#include <memory>
using namespace Instagram;
using namespace testing;
TEST(UserTest, findsUserById)
{
ClientPtr client = CreateClient("d7b1086490044ada88da482a87b073f3");
UserPtr user = client->findUserById("1479058533");
EXPECT_THAT(user->getId(), StrEq("1479058533"));
EXPECT_THAT(user->getUsername(), StrEq("coconut_beard"));
EXPECT_THAT(user->getFullName(), StrEq("CB"));
EXPECT_THAT(user->getProfilePicture(), StrEq("http://photos-c.ak.instagram.com/hphotos-ak-xaf1/10654924_727813450634146_619431088_a.jpg"));
EXPECT_THAT(user->getBio(), StrEq("I'm bearded."));
EXPECT_THAT(user->getWebsite(), StrEq("http://en.wikipedia.org/wiki/Beard"));
EXPECT_THAT(user->getMediaCount(), 2);
EXPECT_THAT(user->getFollowsCount(), 20);
EXPECT_THAT(user->getFollowedByCount(), 10);
}
TEST(FeedTest, getsFeed)
{
AuthenticatedClientPtr client = CreateAuthenticatedClient("1479058533.d7b1086.6abab8dee8e140afa8ee6b8b7f7318c5");
Feed feed = client->getFeed(10);
for (MediaPtr media : feed)
{
const std::string id = media->getId();
media->getImages()->getStandardResolution()->download(id + ".jpg");
}
}
|
Call MediaData::download in integration test
|
Call MediaData::download in integration test
|
C++
|
mit
|
gumb0/cpp-instagram,gumb0/cpp-instagram
|
b6eab3de31d29be9ef7e2cae31ee11ec4f5e576e
|
xchainer/check_backward_test.cc
|
xchainer/check_backward_test.cc
|
#include "xchainer/numerical_gradient.h"
#include <algorithm>
#include <memory>
#include <tuple>
#include <unordered_map>
#include <vector>
#include <gtest/gtest-spi.h>
#include <gtest/gtest.h>
#include <gsl/gsl>
#include <nonstd/optional.hpp>
#include "xchainer/array.h"
#include "xchainer/check_backward.h"
#include "xchainer/context.h"
#include "xchainer/indexable_array.h"
#include "xchainer/indexer.h"
#include "xchainer/native/native_backend.h"
#include "xchainer/op_node.h"
#include "xchainer/shape.h"
#include "xchainer/testing/array.h"
#include "xchainer/testing/device_session.h"
namespace xchainer {
namespace {
using Arrays = std::vector<Array>;
using Fprop = std::function<std::vector<Array>(const std::vector<Array>&)>;
Arrays ForwardWithIncorrectBackward(const Arrays& inputs) {
const Array& in = inputs[0];
Array out = EmptyLike(in);
auto backward_function = [](const Array& gout, const std::vector<GraphId>&) { return gout * gout; };
internal::SetUpOpNodes("incorrect_unary", {in}, out, {backward_function});
VisitDtype(in.dtype(), [&](auto pt) {
using T = typename decltype(pt)::type;
IndexableArray<const T> in_iarray{in};
IndexableArray<T> out_iarray{out};
Indexer indexer{out.shape()};
for (int64_t i = 0; i < indexer.total_size(); ++i) {
indexer.Set(i);
out_iarray[indexer] = in_iarray[indexer];
}
});
return {out};
}
class CheckBackwardTest : public ::testing::TestWithParam<bool> {
protected:
void SetUp() override {
device_session_.emplace(DeviceId{native::NativeBackend::kDefaultName, 0});
requires_grad_ = GetParam();
}
void TearDown() override { device_session_.reset(); }
protected:
template <typename Data>
void CheckCheckBackward(
bool expect_correct,
const Fprop& fprop,
const Shape& shape,
Data input_data,
Data grad_output_data,
Data eps_data,
double atol,
double rtol,
const GraphId& graph_id) {
Arrays inputs{testing::BuildArray(shape, input_data)};
if (requires_grad_) {
inputs[0].RequireGrad(graph_id);
}
Arrays grad_outputs{testing::BuildArray(shape, grad_output_data)};
Arrays eps{testing::BuildArray(shape, eps_data)};
bool is_none_of_grad_required =
std::none_of(inputs.begin(), inputs.end(), [graph_id](const Array& input) { return input.IsGradRequired(graph_id); });
if (expect_correct || is_none_of_grad_required) {
// We cannot expect any failures in case none of the input std::vector<Array> require gradients
EXPECT_NO_THROW(CheckBackwardComputation(fprop, inputs, grad_outputs, eps, atol, rtol, graph_id));
} else {
// Catch the gtest failure expected to be generated by CheckBackwardComputation but without failing this test
EXPECT_THROW(CheckBackwardComputation(fprop, inputs, grad_outputs, eps, atol, rtol, graph_id), GradientCheckError);
}
}
private:
nonstd::optional<testing::DeviceSession> device_session_;
bool requires_grad_{};
};
class CheckDoubleBackwardTest : public ::testing::Test {
protected:
void SetUp() override { device_session_.emplace(DeviceId{native::NativeBackend::kDefaultName, 0}); }
void TearDown() override { device_session_.reset(); }
protected:
template <typename Data>
void CheckCheckDoubleBackward(
const Fprop& fprop,
const Shape& shape,
Data input_data,
Data grad_output_data,
Data grad_grad_input_data,
Data eps_input_data,
Data eps_grad_output_data,
double atol,
double rtol,
const GraphId& graph_id) {
Arrays inputs{testing::BuildArray(shape, input_data)};
Arrays grad_outputs{testing::BuildArray(shape, grad_output_data)};
Arrays grad_grad_inputs{testing::BuildArray(shape, grad_grad_input_data)};
Arrays eps{testing::BuildArray(shape, eps_input_data), testing::BuildArray(shape, eps_grad_output_data)};
for (auto& input : inputs) {
input.RequireGrad(graph_id);
}
for (auto& grad_output : grad_outputs) {
grad_output.RequireGrad(graph_id);
}
// A failure occurs if backward computation and numerical gradients have differences
CheckDoubleBackwardComputation(fprop, inputs, grad_outputs, grad_grad_inputs, eps, atol, rtol, graph_id);
}
private:
nonstd::optional<testing::DeviceSession> device_session_;
};
TEST_P(CheckBackwardTest, CorrectBackward) {
using Data = std::array<float, 3>;
Data input_data{1.f, 2.f, 1.f};
Data grad_output_data{0.f, -2.f, 1.f};
Data eps_data{1e-3f, 1e-3f, 1e-3f};
Fprop fprop = [](const Arrays& inputs) -> Arrays { return {inputs[0] * inputs[0]}; };
CheckCheckBackward(true, fprop, {1, 3}, input_data, grad_output_data, eps_data, 1e-5, 1e-4, "graph_1");
}
TEST_P(CheckBackwardTest, IncorrectBackward) {
using Data = std::array<float, 3>;
Data input_data{-2.f, 3.f, 1.f};
Data grad_output_data{0.f, -2.f, 1.f};
Data eps_data{1e-3f, 1e-3f, 1e-3f};
CheckCheckBackward(false, &ForwardWithIncorrectBackward, {1, 3}, input_data, grad_output_data, eps_data, 1e-5, 1e-4, "graph_1");
}
TEST_F(CheckDoubleBackwardTest, CorrectBackward) {
using Data = std::array<float, 3>;
Data input_data{1.f, 2.f, 3.f};
Data grad_output_data{1.f, 1.f, 1.f};
Data grad_grad_input_data{1.f, 1.f, 1.f};
Data eps_input_data{1e-3f, 1e-3f, 1e-3f};
Data eps_grad_output_data{1e-3f, 1e-3f, 1e-3f};
Fprop fprop = [](const Arrays& inputs) -> Arrays { return {inputs[0] * inputs[0]}; };
CheckCheckDoubleBackward(
fprop, {1, 3}, input_data, grad_output_data, grad_grad_input_data, eps_input_data, eps_grad_output_data, 1e-4, 1e-3, "graph_1");
}
INSTANTIATE_TEST_CASE_P(ForEachSingleSetRequiresGrad, CheckBackwardTest, ::testing::Bool());
} // namespace
} // namespace xchainer
|
#include "xchainer/numerical_gradient.h"
#include <algorithm>
#include <memory>
#include <tuple>
#include <unordered_map>
#include <vector>
#include <gtest/gtest-spi.h>
#include <gtest/gtest.h>
#include <gsl/gsl>
#include <nonstd/optional.hpp>
#include "xchainer/array.h"
#include "xchainer/check_backward.h"
#include "xchainer/context.h"
#include "xchainer/indexable_array.h"
#include "xchainer/indexer.h"
#include "xchainer/native/native_backend.h"
#include "xchainer/op_node.h"
#include "xchainer/shape.h"
#include "xchainer/testing/array.h"
#include "xchainer/testing/device_session.h"
namespace xchainer {
namespace {
using Arrays = std::vector<Array>;
using Fprop = std::function<std::vector<Array>(const std::vector<Array>&)>;
Arrays ForwardWithIncorrectBackward(const Arrays& inputs) {
const Array& in = inputs[0];
Array out = EmptyLike(in);
auto backward_function = [](const Array& gout, const std::vector<GraphId>&) { return gout * gout; };
internal::SetUpOpNodes("incorrect_unary", {in}, out, {backward_function});
VisitDtype(in.dtype(), [&](auto pt) {
using T = typename decltype(pt)::type;
IndexableArray<const T> in_iarray{in};
IndexableArray<T> out_iarray{out};
Indexer indexer{out.shape()};
for (int64_t i = 0; i < indexer.total_size(); ++i) {
indexer.Set(i);
out_iarray[indexer] = in_iarray[indexer];
}
});
return {out};
}
Arrays ForwardWithIncorrectDoubleBackpropOption(const Arrays& inputs) {
const Array& a = inputs[0];
Array out = a.AsConstant() * a.AsConstant();
auto backward_function = [a](const Array& gout, const std::vector<GraphId>&) {
return 2 * gout * a; // a must be a.AsConstant(graph_ids_to_stop_gradient) correctly
};
internal::SetUpOpNodes("incorrect_square", {a}, out, {backward_function});
return {out};
}
class CheckBackwardTest : public ::testing::TestWithParam<bool> {
protected:
void SetUp() override {
device_session_.emplace(DeviceId{native::NativeBackend::kDefaultName, 0});
requires_grad_ = GetParam();
}
void TearDown() override { device_session_.reset(); }
protected:
template <typename Data>
void CheckCheckBackward(
bool expect_correct,
const Fprop& fprop,
const Shape& shape,
Data input_data,
Data grad_output_data,
Data eps_data,
double atol,
double rtol,
const GraphId& graph_id) {
Arrays inputs{testing::BuildArray(shape, input_data)};
if (requires_grad_) {
inputs[0].RequireGrad(graph_id);
}
Arrays grad_outputs{testing::BuildArray(shape, grad_output_data)};
Arrays eps{testing::BuildArray(shape, eps_data)};
bool is_none_of_grad_required =
std::none_of(inputs.begin(), inputs.end(), [graph_id](const Array& input) { return input.IsGradRequired(graph_id); });
if (expect_correct || is_none_of_grad_required) {
// We cannot expect any failures in case none of the input std::vector<Array> require gradients
EXPECT_NO_THROW(CheckBackward(fprop, inputs, grad_outputs, eps, atol, rtol, graph_id));
} else {
// Catch the gtest failure expected to be generated by CheckBackward but without failing this test
EXPECT_THROW(CheckBackward(fprop, inputs, grad_outputs, eps, atol, rtol, graph_id), GradientCheckError);
}
}
private:
nonstd::optional<testing::DeviceSession> device_session_;
bool requires_grad_{};
};
class CheckDoubleBackwardTest : public ::testing::Test {
protected:
void SetUp() override { device_session_.emplace(DeviceId{native::NativeBackend::kDefaultName, 0}); }
void TearDown() override { device_session_.reset(); }
protected:
template <typename Data>
void CheckCheckDoubleBackward(
const Fprop& fprop,
const Shape& shape,
Data input_data,
Data grad_output_data,
Data grad_grad_input_data,
Data eps_input_data,
Data eps_grad_output_data,
double atol,
double rtol,
const GraphId& graph_id) {
Arrays inputs{testing::BuildArray(shape, input_data)};
Arrays grad_outputs{testing::BuildArray(shape, grad_output_data)};
Arrays grad_grad_inputs{testing::BuildArray(shape, grad_grad_input_data)};
Arrays eps{testing::BuildArray(shape, eps_input_data), testing::BuildArray(shape, eps_grad_output_data)};
for (auto& input : inputs) {
input.RequireGrad(graph_id);
}
for (auto& grad_output : grad_outputs) {
grad_output.RequireGrad(graph_id);
}
// A failure occurs if backward computation and numerical gradients have differences
CheckDoubleBackwardComputation(fprop, inputs, grad_outputs, grad_grad_inputs, eps, atol, rtol, graph_id);
}
private:
nonstd::optional<testing::DeviceSession> device_session_;
};
TEST_P(CheckBackwardTest, CorrectBackward) {
using Data = std::array<float, 3>;
Data input_data{1.f, 2.f, 1.f};
Data grad_output_data{0.f, -2.f, 1.f};
Data eps_data{1e-3f, 1e-3f, 1e-3f};
Fprop fprop = [](const Arrays& inputs) -> Arrays { return {inputs[0] * inputs[0]}; };
CheckCheckBackward(true, fprop, {1, 3}, input_data, grad_output_data, eps_data, 1e-5, 1e-4, "graph_1");
}
TEST_P(CheckBackwardTest, CorrectBackwardWithNonDoubleDifferentiableFunction) {
using Data = std::array<float, 3>;
Data input_data{1.f, 2.f, 1.f};
Data grad_output_data{0.f, -2.f, 1.f};
Data eps_data{1e-3f, 1e-3f, 1e-3f};
Fprop fprop = [](const Arrays& inputs) -> Arrays { return {-inputs[0]}; };
CheckCheckBackward(true, fprop, {1, 3}, input_data, grad_output_data, eps_data, 1e-5, 1e-4, "graph_1");
}
TEST_P(CheckBackwardTest, IncorrectBackward) {
using Data = std::array<float, 3>;
Data input_data{-2.f, 3.f, 1.f};
Data grad_output_data{0.f, -2.f, 1.f};
Data eps_data{1e-3f, 1e-3f, 1e-3f};
CheckCheckBackward(false, &ForwardWithIncorrectBackward, {1, 3}, input_data, grad_output_data, eps_data, 1e-5, 1e-4, "graph_1");
}
TEST_P(CheckBackwardTest, IncorrectDoubleBackpropOption) {
using Data = std::array<float, 3>;
Data input_data{-2.f, 3.f, 1.f};
Data grad_output_data{0.f, -2.f, 1.f};
Data eps_data{1e-3f, 1e-3f, 1e-3f};
CheckCheckBackward(
false, &ForwardWithIncorrectDoubleBackpropOption, {1, 3}, input_data, grad_output_data, eps_data, 1e-4, 1e-3, "graph_1");
}
TEST_F(CheckDoubleBackwardTest, CorrectBackward) {
using Data = std::array<float, 3>;
Data input_data{1.f, 2.f, 3.f};
Data grad_output_data{1.f, 1.f, 1.f};
Data grad_grad_input_data{1.f, 1.f, 1.f};
Data eps_input_data{1e-3f, 1e-3f, 1e-3f};
Data eps_grad_output_data{1e-3f, 1e-3f, 1e-3f};
Fprop fprop = [](const Arrays& inputs) -> Arrays { return {inputs[0] * inputs[0]}; };
CheckCheckDoubleBackward(
fprop, {1, 3}, input_data, grad_output_data, grad_grad_input_data, eps_input_data, eps_grad_output_data, 1e-4, 1e-3, "graph_1");
}
INSTANTIATE_TEST_CASE_P(ForEachSingleSetRequiresGrad, CheckBackwardTest, ::testing::Bool());
} // namespace
} // namespace xchainer
|
Add tests for CheckDoubleBackpropOption
|
Add tests for CheckDoubleBackpropOption
|
C++
|
mit
|
ktnyt/chainer,hvy/chainer,jnishi/chainer,okuta/chainer,wkentaro/chainer,jnishi/chainer,chainer/chainer,pfnet/chainer,keisuke-umezawa/chainer,jnishi/chainer,keisuke-umezawa/chainer,wkentaro/chainer,okuta/chainer,wkentaro/chainer,niboshi/chainer,okuta/chainer,hvy/chainer,okuta/chainer,wkentaro/chainer,ktnyt/chainer,niboshi/chainer,hvy/chainer,keisuke-umezawa/chainer,jnishi/chainer,tkerola/chainer,keisuke-umezawa/chainer,ktnyt/chainer,niboshi/chainer,niboshi/chainer,chainer/chainer,hvy/chainer,chainer/chainer,chainer/chainer,ktnyt/chainer
|
a740e35eb0fc96b28246932ec6be39f008ac1077
|
xchainer/check_backward_test.cc
|
xchainer/check_backward_test.cc
|
#include "xchainer/gradient_check.h"
#include <algorithm>
#include <memory>
#include <vector>
#include <gtest/gtest-spi.h>
#include <gtest/gtest.h>
#include <gsl/gsl>
#include "xchainer/array.h"
#include "xchainer/check_backward.h"
#include "xchainer/op_node.h"
#include "xchainer/shape.h"
namespace xchainer {
namespace {
using Arrays = std::vector<Array>;
using Fprop = std::function<std::vector<Array>(const std::vector<Array>&)>;
Arrays IncorrectBackwardUnaryFunc(const Arrays& inputs) {
const Array& lhs = inputs[0];
Array out = Array::EmptyLike(lhs);
out.set_requires_grad(lhs.requires_grad());
if (out.requires_grad()) {
std::shared_ptr<ArrayNode> lhs_node = lhs.mutable_node();
std::shared_ptr<ArrayNode> out_node = out.RenewNode();
int64_t out_rank = lhs_node->rank();
auto next_nodes = std::vector<std::shared_ptr<ArrayNode>>{lhs_node};
std::function<Array(const Array&)> empty_func;
auto lhs_func = lhs.requires_grad() ? [](const Array& gout) { return gout * gout; } : empty_func;
auto backward_functions = std::vector<std::function<Array(const Array&)>>{lhs_func};
std::shared_ptr<OpNode> op_node = std::make_shared<OpNode>("incorrect_unary", out_rank, next_nodes, backward_functions);
out_node->set_next_node(op_node);
out_node->set_rank(out_rank + 1);
}
VisitDtype(lhs.dtype(), [&](auto pt) {
using T = typename decltype(pt)::type;
int64_t total_size = lhs.total_size();
auto* ldata = static_cast<const T*>(lhs.data().get());
auto* odata = static_cast<T*>(out.data().get());
for (int64_t i = 0; i < total_size; i++) {
odata[i] = ldata[i];
}
});
return {out};
}
Arrays IncorrectBackwardBinaryFunc(const Arrays& inputs) {
const Array& lhs = inputs[0];
const Array& rhs = inputs[1];
CheckEqual(lhs.dtype(), rhs.dtype());
CheckEqual(lhs.shape(), rhs.shape());
Array out = Array::EmptyLike(lhs);
out.set_requires_grad(lhs.requires_grad() || rhs.requires_grad());
if (out.requires_grad()) {
std::shared_ptr<ArrayNode> lhs_node = lhs.mutable_node();
std::shared_ptr<ArrayNode> rhs_node = rhs.mutable_node();
std::shared_ptr<ArrayNode> out_node = out.RenewNode();
int64_t out_rank = std::max(lhs_node->rank(), rhs_node->rank());
auto next_nodes = std::vector<std::shared_ptr<ArrayNode>>{lhs_node, rhs_node};
std::function<Array(const Array&)> empty_func;
auto lhs_func = lhs.requires_grad() ? [rhs](const Array& gout) { return gout + rhs; } : empty_func;
auto rhs_func = rhs.requires_grad() ? [lhs](const Array& gout) { return gout + lhs; } : empty_func;
auto backward_functions = std::vector<std::function<Array(const Array&)>>{lhs_func, rhs_func};
std::shared_ptr<OpNode> op_node = std::make_shared<OpNode>("incorrect_binary", out_rank, next_nodes, backward_functions);
out_node->set_next_node(op_node);
out_node->set_rank(out_rank + 1);
}
VisitDtype(lhs.dtype(), [&](auto pt) {
using T = typename decltype(pt)::type;
int64_t total_size = lhs.total_size();
auto* ldata = static_cast<const T*>(lhs.data().get());
auto* rdata = static_cast<const T*>(rhs.data().get());
auto* odata = static_cast<T*>(out.data().get());
for (int64_t i = 0; i < total_size; i++) {
odata[i] = ldata[i] * rdata[i];
}
});
return {out};
}
class CheckBackwardBaseTest : public ::testing::Test {
protected:
template <typename T>
Array MakeArray(const Shape& shape, const T* data) const {
int64_t size = shape.total_size();
auto a = std::make_unique<T[]>(size);
std::copy(data, data + size, a.get());
return Array::FromBuffer(shape, TypeToDtype<T>, std::move(a));
}
protected:
void CheckBaseBackwardComputation(bool expect_correct, const Fprop fprop, const Arrays& inputs, const Arrays& grad_outputs,
const Arrays& eps, double atol, double rtol) {
if (!expect_correct && std::any_of(inputs.begin(), inputs.end(), [](const Array& input) { return input.requires_grad(); })) {
// Catch the gtest failure expected to be generated by CheckBackwardComputation but without failing this test
EXPECT_NONFATAL_FAILURE(CheckBackwardComputation(fprop, inputs, grad_outputs, eps, atol, rtol), "Backward check failure");
} else {
// We cannot expect any failures in case none of the input std::vector<Array> require gradients
CheckBackwardComputation(fprop, inputs, grad_outputs, eps, atol, rtol);
}
}
};
class CheckBackwardUnaryTest : public CheckBackwardBaseTest, public ::testing::WithParamInterface<bool> {
protected:
void SetUp() override { requires_grad = GetParam(); }
template <typename T>
void CheckBackwardComputation(bool expect_correct, const Fprop fprop, const Shape& shape, const T* input_data,
const T* grad_output_data, const T* eps_data, double atol, double rtol) {
Arrays inputs{MakeArray(shape, input_data)};
Arrays grad_outputs{MakeArray(shape, grad_output_data)};
Arrays eps{MakeArray(shape, eps_data)};
inputs[0].set_requires_grad(requires_grad); // parameterized by test
CheckBaseBackwardComputation(expect_correct, fprop, inputs, grad_outputs, eps, atol, rtol);
}
private:
bool requires_grad;
};
class CheckBackwardBinaryTest : public CheckBackwardBaseTest, public ::testing::WithParamInterface<::testing::tuple<bool, bool>> {
protected:
void SetUp() override { requires_grads = {::testing::get<0>(GetParam()), ::testing::get<1>(GetParam())}; }
template <typename T>
void CheckBackwardComputation(bool expect_correct, const Fprop fprop, const Shape& shape, const T* input_data1, const T* input_data2,
const T* grad_output_data, const T* eps_data1, const T* eps_data2, double atol, double rtol) {
Arrays inputs{MakeArray(shape, input_data1), MakeArray(shape, input_data2)};
Arrays grad_outputs{MakeArray(shape, grad_output_data)};
Arrays eps{MakeArray(shape, eps_data1), MakeArray(shape, eps_data2)};
inputs[0].set_requires_grad(requires_grads[0]); // parameterized by test
inputs[1].set_requires_grad(requires_grads[1]);
CheckBaseBackwardComputation(expect_correct, fprop, inputs, grad_outputs, eps, atol, rtol);
}
private:
std::vector<bool> requires_grads;
};
TEST_P(CheckBackwardUnaryTest, CorrectBackward) {
float input_data[]{1.f, 2.f, 3.f};
float grad_output_data[]{0.f, -2.f, 3.f};
float eps_data[]{1.f, 2.f, 3.f};
const Fprop fprop = [](const Arrays& inputs) -> Arrays { return {inputs[0]}; };
CheckBackwardComputation(true, fprop, {1, 3}, input_data, grad_output_data, eps_data, 1e-5, 1e-4);
}
TEST_P(CheckBackwardUnaryTest, IncorrectBackward) {
float input_data[]{-2.f, 3.f, 1.f};
float grad_output_data[]{0.f, -2.f, 1.f};
float eps_data[]{1.f, 2.f, 3.f};
CheckBackwardComputation(false, &IncorrectBackwardUnaryFunc, {1, 3}, input_data, grad_output_data, eps_data, 1e-5, 1e-4);
}
TEST_P(CheckBackwardBinaryTest, CorrectBackward) {
float input_data1[]{1.f, 2.f, 3.f};
float input_data2[]{0.f, 1.f, 2.f};
float eps_data1[]{1.f, 2.f, 3.f};
float eps_data2[]{3.f, -2.f, 3.f};
float grad_output_data[]{1.f, -2.f, 3.f};
const Fprop fprop = [](const Arrays& inputs) -> Arrays { return {inputs[0] * inputs[1]}; };
CheckBackwardComputation(true, fprop, {1, 3}, input_data1, input_data2, grad_output_data, eps_data1, eps_data2, 1e-5, 1e-4);
}
TEST_P(CheckBackwardBinaryTest, IncorrectBackward) {
float input_data1[]{3.f, -2.f, 1.f};
float input_data2[]{0.f, 1.4f, 2.f};
float eps_data1[]{1.f, 2.f, 3.8f};
float eps_data2[]{3.f, -2.f, -3.f};
float grad_output_data[]{4.f, -2.f, 3.f};
CheckBackwardComputation(false, &IncorrectBackwardBinaryFunc, {1, 3}, input_data1, input_data2, grad_output_data, eps_data1, eps_data2,
1e-5, 1e-4);
}
INSTANTIATE_TEST_CASE_P(ForEachSingleSetRequiresGrad, CheckBackwardUnaryTest, ::testing::Bool());
INSTANTIATE_TEST_CASE_P(ForEachCombinedSetRequiresGrad, CheckBackwardBinaryTest, ::testing::Combine(::testing::Bool(), ::testing::Bool()));
} // namespace
} // namespace xchainer
|
#include "xchainer/gradient_check.h"
#include <algorithm>
#include <memory>
#include <tuple>
#include <vector>
#include <gtest/gtest-spi.h>
#include <gtest/gtest.h>
#include <gsl/gsl>
#include "xchainer/array.h"
#include "xchainer/check_backward.h"
#include "xchainer/op_node.h"
#include "xchainer/shape.h"
namespace xchainer {
namespace {
using Arrays = std::vector<Array>;
using Fprop = std::function<std::vector<Array>(const std::vector<Array>&)>;
Arrays IncorrectBackwardUnaryFunc(const Arrays& inputs) {
const Array& lhs = inputs[0];
Array out = Array::EmptyLike(lhs);
out.set_requires_grad(lhs.requires_grad());
if (out.requires_grad()) {
std::shared_ptr<ArrayNode> lhs_node = lhs.mutable_node();
std::shared_ptr<ArrayNode> out_node = out.RenewNode();
int64_t out_rank = lhs_node->rank();
auto next_nodes = std::vector<std::shared_ptr<ArrayNode>>{lhs_node};
std::function<Array(const Array&)> empty_func;
auto lhs_func = lhs.requires_grad() ? [](const Array& gout) { return gout * gout; } : empty_func;
auto backward_functions = std::vector<std::function<Array(const Array&)>>{lhs_func};
std::shared_ptr<OpNode> op_node = std::make_shared<OpNode>("incorrect_unary", out_rank, next_nodes, backward_functions);
out_node->set_next_node(op_node);
out_node->set_rank(out_rank + 1);
}
VisitDtype(lhs.dtype(), [&](auto pt) {
using T = typename decltype(pt)::type;
int64_t total_size = lhs.total_size();
auto* ldata = static_cast<const T*>(lhs.data().get());
auto* odata = static_cast<T*>(out.data().get());
for (int64_t i = 0; i < total_size; i++) {
odata[i] = ldata[i];
}
});
return {out};
}
Arrays IncorrectBackwardBinaryFunc(const Arrays& inputs) {
const Array& lhs = inputs[0];
const Array& rhs = inputs[1];
CheckEqual(lhs.dtype(), rhs.dtype());
CheckEqual(lhs.shape(), rhs.shape());
Array out = Array::EmptyLike(lhs);
out.set_requires_grad(lhs.requires_grad() || rhs.requires_grad());
if (out.requires_grad()) {
std::shared_ptr<ArrayNode> lhs_node = lhs.mutable_node();
std::shared_ptr<ArrayNode> rhs_node = rhs.mutable_node();
std::shared_ptr<ArrayNode> out_node = out.RenewNode();
int64_t out_rank = std::max(lhs_node->rank(), rhs_node->rank());
auto next_nodes = std::vector<std::shared_ptr<ArrayNode>>{lhs_node, rhs_node};
std::function<Array(const Array&)> empty_func;
auto lhs_func = lhs.requires_grad() ? [rhs](const Array& gout) { return gout + rhs; } : empty_func;
auto rhs_func = rhs.requires_grad() ? [lhs](const Array& gout) { return gout + lhs; } : empty_func;
auto backward_functions = std::vector<std::function<Array(const Array&)>>{lhs_func, rhs_func};
std::shared_ptr<OpNode> op_node = std::make_shared<OpNode>("incorrect_binary", out_rank, next_nodes, backward_functions);
out_node->set_next_node(op_node);
out_node->set_rank(out_rank + 1);
}
VisitDtype(lhs.dtype(), [&](auto pt) {
using T = typename decltype(pt)::type;
int64_t total_size = lhs.total_size();
auto* ldata = static_cast<const T*>(lhs.data().get());
auto* rdata = static_cast<const T*>(rhs.data().get());
auto* odata = static_cast<T*>(out.data().get());
for (int64_t i = 0; i < total_size; i++) {
odata[i] = ldata[i] * rdata[i];
}
});
return {out};
}
class CheckBackwardBaseTest : public ::testing::Test {
protected:
template <typename T>
Array MakeArray(const Shape& shape, const T* data) const {
int64_t size = shape.total_size();
auto a = std::make_unique<T[]>(size);
std::copy(data, data + size, a.get());
return Array::FromBuffer(shape, TypeToDtype<T>, std::move(a));
}
protected:
void CheckBaseBackwardComputation(bool expect_correct, const Fprop fprop, const Arrays& inputs, const Arrays& grad_outputs,
const Arrays& eps, double atol, double rtol) {
if (!expect_correct && std::any_of(inputs.begin(), inputs.end(), [](const Array& input) { return input.requires_grad(); })) {
// Catch the gtest failure expected to be generated by CheckBackwardComputation but without failing this test
EXPECT_NONFATAL_FAILURE(CheckBackwardComputation(fprop, inputs, grad_outputs, eps, atol, rtol), "Backward check failure");
} else {
// We cannot expect any failures in case none of the input std::vector<Array> require gradients
CheckBackwardComputation(fprop, inputs, grad_outputs, eps, atol, rtol);
}
}
};
class CheckBackwardUnaryTest : public CheckBackwardBaseTest, public ::testing::WithParamInterface<bool> {
protected:
void SetUp() override { requires_grad = GetParam(); }
template <typename T>
void CheckBackwardComputation(bool expect_correct, const Fprop fprop, const Shape& shape, const T* input_data,
const T* grad_output_data, const T* eps_data, double atol, double rtol) {
Arrays inputs{MakeArray(shape, input_data)};
Arrays grad_outputs{MakeArray(shape, grad_output_data)};
Arrays eps{MakeArray(shape, eps_data)};
inputs[0].set_requires_grad(requires_grad); // parameterized by test
CheckBaseBackwardComputation(expect_correct, fprop, inputs, grad_outputs, eps, atol, rtol);
}
private:
bool requires_grad;
};
class CheckBackwardBinaryTest : public CheckBackwardBaseTest, public ::testing::WithParamInterface<std::tuple<bool, bool>> {
protected:
void SetUp() override { requires_grads = {std::get<0>(GetParam()), std::get<1>(GetParam())}; }
template <typename T>
void CheckBackwardComputation(bool expect_correct, const Fprop fprop, const Shape& shape, const T* input_data1, const T* input_data2,
const T* grad_output_data, const T* eps_data1, const T* eps_data2, double atol, double rtol) {
Arrays inputs{MakeArray(shape, input_data1), MakeArray(shape, input_data2)};
Arrays grad_outputs{MakeArray(shape, grad_output_data)};
Arrays eps{MakeArray(shape, eps_data1), MakeArray(shape, eps_data2)};
inputs[0].set_requires_grad(requires_grads[0]); // parameterized by test
inputs[1].set_requires_grad(requires_grads[1]);
CheckBaseBackwardComputation(expect_correct, fprop, inputs, grad_outputs, eps, atol, rtol);
}
private:
std::vector<bool> requires_grads;
};
TEST_P(CheckBackwardUnaryTest, CorrectBackward) {
float input_data[]{1.f, 2.f, 3.f};
float grad_output_data[]{0.f, -2.f, 3.f};
float eps_data[]{1.f, 2.f, 3.f};
const Fprop fprop = [](const Arrays& inputs) -> Arrays { return {inputs[0]}; };
CheckBackwardComputation(true, fprop, {1, 3}, input_data, grad_output_data, eps_data, 1e-5, 1e-4);
}
TEST_P(CheckBackwardUnaryTest, IncorrectBackward) {
float input_data[]{-2.f, 3.f, 1.f};
float grad_output_data[]{0.f, -2.f, 1.f};
float eps_data[]{1.f, 2.f, 3.f};
CheckBackwardComputation(false, &IncorrectBackwardUnaryFunc, {1, 3}, input_data, grad_output_data, eps_data, 1e-5, 1e-4);
}
TEST_P(CheckBackwardBinaryTest, CorrectBackward) {
float input_data1[]{1.f, 2.f, 3.f};
float input_data2[]{0.f, 1.f, 2.f};
float eps_data1[]{1.f, 2.f, 3.f};
float eps_data2[]{3.f, -2.f, 3.f};
float grad_output_data[]{1.f, -2.f, 3.f};
const Fprop fprop = [](const Arrays& inputs) -> Arrays { return {inputs[0] * inputs[1]}; };
CheckBackwardComputation(true, fprop, {1, 3}, input_data1, input_data2, grad_output_data, eps_data1, eps_data2, 1e-5, 1e-4);
}
TEST_P(CheckBackwardBinaryTest, IncorrectBackward) {
float input_data1[]{3.f, -2.f, 1.f};
float input_data2[]{0.f, 1.4f, 2.f};
float eps_data1[]{1.f, 2.f, 3.8f};
float eps_data2[]{3.f, -2.f, -3.f};
float grad_output_data[]{4.f, -2.f, 3.f};
CheckBackwardComputation(false, &IncorrectBackwardBinaryFunc, {1, 3}, input_data1, input_data2, grad_output_data, eps_data1, eps_data2,
1e-5, 1e-4);
}
INSTANTIATE_TEST_CASE_P(ForEachSingleSetRequiresGrad, CheckBackwardUnaryTest, ::testing::Bool());
INSTANTIATE_TEST_CASE_P(ForEachCombinedSetRequiresGrad, CheckBackwardBinaryTest, ::testing::Combine(::testing::Bool(), ::testing::Bool()));
} // namespace
} // namespace xchainer
|
Change testing::tuple to std::tuple
|
Change testing::tuple to std::tuple
|
C++
|
mit
|
wkentaro/chainer,wkentaro/chainer,jnishi/chainer,hvy/chainer,niboshi/chainer,okuta/chainer,ktnyt/chainer,okuta/chainer,ktnyt/chainer,hvy/chainer,pfnet/chainer,chainer/chainer,jnishi/chainer,keisuke-umezawa/chainer,hvy/chainer,ktnyt/chainer,keisuke-umezawa/chainer,wkentaro/chainer,keisuke-umezawa/chainer,niboshi/chainer,chainer/chainer,chainer/chainer,niboshi/chainer,wkentaro/chainer,hvy/chainer,okuta/chainer,jnishi/chainer,jnishi/chainer,chainer/chainer,niboshi/chainer,okuta/chainer,tkerola/chainer,keisuke-umezawa/chainer,ktnyt/chainer
|
b9e6762c3f862788da2dd9b6f5529105d64f6277
|
test/test_dont_print_log_value.cpp
|
test/test_dont_print_log_value.cpp
|
// (C) Copyright Marek Kurdej 2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
// File : $RCSfile$
//
// Version : $Revision$
//
// Description : BOOST_TEST_DONT_PRINT_LOG_VALUE unit test
// *****************************************************************************
// Boost.Test
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
// STL
#include <vector>
struct MyClass
{
bool operator==(MyClass const&) const
{
return true;
}
bool operator!=(MyClass const&) const
{
return false;
}
};
typedef ::std::vector<MyClass> MyClassVec;
BOOST_TEST_DONT_PRINT_LOG_VALUE(MyClass)
BOOST_AUTO_TEST_CASE(single_object)
{
MyClass actual, expected;
BOOST_CHECK_EQUAL(actual, expected);
}
BOOST_AUTO_TEST_CASE(collection_of_objects)
{
MyClassVec actual, expected;
BOOST_CHECK_EQUAL_COLLECTIONS(actual.begin(), actual.end(), expected.begin(), expected.end());
}
|
// (C) Copyright Marek Kurdej 2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
//! @file
//! BOOST_TEST_DONT_PRINT_LOG_VALUE unit test
// *****************************************************************************
#define BOOST_TEST_MAIN
#include <boost/test/included/unit_test.hpp>
#include <boost/test/data/test_case.hpp>
#include <boost/test/data/monomorphic.hpp>
#include <vector>
struct dummy_class
{
dummy_class(int i = 0) : i_(i){}
bool operator==(dummy_class const&) const
{
return true;
}
bool operator!=(dummy_class const&) const
{
return false;
}
int i_;
};
typedef ::std::vector<dummy_class> vector_dummy_class;
BOOST_TEST_DONT_PRINT_LOG_VALUE(dummy_class)
BOOST_AUTO_TEST_CASE(single_object)
{
dummy_class actual, expected;
BOOST_CHECK_EQUAL(actual, expected);
}
BOOST_AUTO_TEST_CASE(collection_of_objects)
{
vector_dummy_class actual, expected;
BOOST_CHECK_EQUAL_COLLECTIONS(actual.begin(), actual.end(), expected.begin(), expected.end());
}
// this one tests for contexts
vector_dummy_class generate_vector()
{
vector_dummy_class out;
out.push_back(3);
out.push_back(1);
out.push_back(7);
return out;
}
vector_dummy_class v = generate_vector();
BOOST_DATA_TEST_CASE( test_data_case, boost::unit_test::data::make(v), var1)
{
BOOST_CHECK(true);
}
|
test case for the BOOST_TEST_DONT_PRINT_LOG_VALUE for contexts
|
test case for the BOOST_TEST_DONT_PRINT_LOG_VALUE for contexts
|
C++
|
mit
|
nihildeb/hme,nihildeb/hme,nihildeb/hme,nihildeb/hme,nihildeb/hme,nihildeb/hme
|
c03e0c83670b1a7334a7165990c5a3744d77e692
|
src/mex_wrapper.cc
|
src/mex_wrapper.cc
|
#include <vector>
#include <string>
#include <set>
#include <math.h>
#include <matrix.h>
#include <mex.h>
#include "mex_helper.h"
#include "emd_flow.h"
#include "emd_flow_network_factory.h"
using namespace std;
void output_function(const char* s) {
mexPrintf(s);
mexEvalString("drawnow;");
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
if (nrhs < 3) {
mexErrMsgTxt("At least three input argument required (amplitudes, sparsity,"
" EMD budget.");
}
if (nrhs > 4) {
mexErrMsgTxt("Too many input arguments, at most four: amplitudes, sparsity,"
" EMD budget and the options struct.");
}
if (nlhs > 5) {
mexErrMsgTxt("Too many output arguments.");
}
vector<vector<double> > a;
if (!get_double_matrix(prhs[0], &a)) {
mexErrMsgTxt("Amplitudes need to be a two-dimensional double array.");
}
int s = 0;
if (!get_double_as_int(prhs[1], &s)) {
mexErrMsgTxt("Sparsity has to be a double scalar.");
}
int emd_bound_low = 0;
int emd_bound_high = 0;
if (!get_double_as_int(prhs[2], &emd_bound_low)) {
if (!get_double_interval_as_ints(prhs[2], &emd_bound_low,
&emd_bound_high)) {
mexErrMsgTxt("EMD budget has to be a double scalar or a double "
"interval.");
}
} else {
emd_bound_high = emd_bound_low;
}
// optional parameters
bool verbose = false;
double lambda_low = 0.5;
double lambda_high = 1.0;
int num_iter = 10;
vector<double> emd_costs;
if (nrhs == 4) {
set<string> known_options;
known_options.insert("verbose");
known_options.insert("lambda_low");
known_options.insert("lambda_high");
known_options.insert("num_iterations");
vector<string> options;
if (!get_fields(prhs[3], &options)) {
mexErrMsgTxt("Cannot get fields from options argument.");
}
for (size_t ii = 0; ii < options.size(); ++ii) {
if (known_options.find(options[ii]) == known_options.end()) {
const size_t tmp_size = 1000;
char tmp[tmp_size];
snprintf(tmp, tmp_size, "Unknown option \"%s\"\n", options[ii].c_str());
mexErrMsgTxt(tmp);
}
}
if (has_field(prhs[3], "verbose")
&& !get_bool_field(prhs[3], "verbose", &verbose)) {
mexErrMsgTxt("verbose flag has to be a boolean scalar.");
}
if (has_field(prhs[3], "lambda_low")
&& !get_double_field(prhs[3], "lambda_low", &lambda_low)) {
mexErrMsgTxt("lambda_low field has to be a double scalar.");
}
if (has_field(prhs[3], "lambda_high")
&& !get_double_field(prhs[3], "lambda_high", &lambda_high)) {
mexErrMsgTxt("lambda_high field has to be a double scalar.");
}
if (has_field(prhs[3], "num_iterations")
&& !get_double_field_as_int(prhs[3], "num_iterations", &num_iter)) {
mexErrMsgTxt("num_iterations field has to be a double scalar.");
}
}
emd_flow_args args(a);
args.s = s;
args.emd_bound_low = emd_bound_low;
args.emd_bound_high = emd_bound_high;
args.lambda_low = lambda_low;
args.lambda_high = lambda_high;
args.num_search_iterations = num_iter;
args.outdegree_vertical_distance = -1;
args.emd_costs = emd_costs;
args.alg_type = EMDFlowNetworkFactory::kShortestAugmentingPath;
args.output_function = output_function;
args.verbose = verbose;
emd_flow_result result;
emd_flow(args, &result);
if (nlhs >= 1) {
set_double_matrix(&(plhs[0]), *(result.support));
}
if (nlhs >= 2) {
set_double(&(plhs[1]), result.emd_cost);
}
if (nlhs >= 3) {
set_double(&(plhs[2]), result.amp_sum);
}
if (nlhs >= 4) {
set_double(&(plhs[3]), result.final_lambda_low);
}
if (nlhs >= 5) {
set_double(&(plhs[4]), result.final_lambda_high);
}
/*
mexPrintf("r = %d, c = %d, k = %d, EMD budget = %d\n", r, c, k, emd_budget);
for (int ii = 0; ii < r; ++ii) {
for (int jj = 0; jj < c; ++jj) {
mexPrintf("%lf ", a[ii][jj]);
}
mexPrintf("\n");
}
*/
}
|
#include <vector>
#include <string>
#include <set>
#include <math.h>
#include <matrix.h>
#include <mex.h>
#include "mex_helper.h"
#include "emd_flow.h"
#include "emd_flow_network_factory.h"
using namespace std;
void output_function(const char* s) {
mexPrintf(s);
mexEvalString("drawnow;");
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
if (nrhs < 3) {
mexErrMsgTxt("At least three input argument required (amplitudes, sparsity,"
" EMD budget.");
}
if (nrhs > 4) {
mexErrMsgTxt("Too many input arguments, at most four: amplitudes, sparsity,"
" EMD budget and the options struct.");
}
if (nlhs > 5) {
mexErrMsgTxt("Too many output arguments.");
}
vector<vector<double> > a;
if (!get_double_matrix(prhs[0], &a)) {
mexErrMsgTxt("Amplitudes need to be a two-dimensional double array.");
}
int s = 0;
if (!get_double_as_int(prhs[1], &s)) {
mexErrMsgTxt("Sparsity has to be a double scalar.");
}
int emd_bound_low = 0;
int emd_bound_high = 0;
if (!get_double_as_int(prhs[2], &emd_bound_low)) {
if (!get_double_interval_as_ints(prhs[2], &emd_bound_low,
&emd_bound_high)) {
mexErrMsgTxt("EMD budget has to be a double scalar or a double "
"interval.");
}
} else {
emd_bound_high = emd_bound_low;
}
// optional parameters
bool verbose = false;
double lambda_low = 0.5;
double lambda_high = 1.0;
int num_iter = 10;
int outdegree_vertical_distance = -1;
vector<double> emd_costs;
if (nrhs == 4) {
set<string> known_options;
known_options.insert("verbose");
known_options.insert("lambda_low");
known_options.insert("lambda_high");
known_options.insert("num_iterations");
known_options.insert("outdegree_vertical_distance");
vector<string> options;
if (!get_fields(prhs[3], &options)) {
mexErrMsgTxt("Cannot get fields from options argument.");
}
for (size_t ii = 0; ii < options.size(); ++ii) {
if (known_options.find(options[ii]) == known_options.end()) {
const size_t tmp_size = 1000;
char tmp[tmp_size];
snprintf(tmp, tmp_size, "Unknown option \"%s\"\n", options[ii].c_str());
mexErrMsgTxt(tmp);
}
}
if (has_field(prhs[3], "verbose")
&& !get_bool_field(prhs[3], "verbose", &verbose)) {
mexErrMsgTxt("verbose flag has to be a boolean scalar.");
}
if (has_field(prhs[3], "lambda_low")
&& !get_double_field(prhs[3], "lambda_low", &lambda_low)) {
mexErrMsgTxt("lambda_low field has to be a double scalar.");
}
if (has_field(prhs[3], "lambda_high")
&& !get_double_field(prhs[3], "lambda_high", &lambda_high)) {
mexErrMsgTxt("lambda_high field has to be a double scalar.");
}
if (has_field(prhs[3], "num_iterations")
&& !get_double_field_as_int(prhs[3], "num_iterations", &num_iter)) {
mexErrMsgTxt("num_iterations field has to be a double scalar.");
}
if (has_field(prhs[3], "outdegree_vertical_distance")
&& !get_double_field_as_int(prhs[3], "outdegree_vertical_distance",
&outdegree_vertical_distance)) {
mexErrMsgTxt("outdegree_vertical_distance field has to be a double "
"scalar.");
}
}
emd_flow_args args(a);
args.s = s;
args.emd_bound_low = emd_bound_low;
args.emd_bound_high = emd_bound_high;
args.lambda_low = lambda_low;
args.lambda_high = lambda_high;
args.num_search_iterations = num_iter;
args.outdegree_vertical_distance = outdegree_vertical_distance;
args.emd_costs = emd_costs;
args.alg_type = EMDFlowNetworkFactory::kShortestAugmentingPath;
args.output_function = output_function;
args.verbose = verbose;
emd_flow_result result;
emd_flow(args, &result);
if (nlhs >= 1) {
set_double_matrix(&(plhs[0]), *(result.support));
}
if (nlhs >= 2) {
set_double(&(plhs[1]), result.emd_cost);
}
if (nlhs >= 3) {
set_double(&(plhs[2]), result.amp_sum);
}
if (nlhs >= 4) {
set_double(&(plhs[3]), result.final_lambda_low);
}
if (nlhs >= 5) {
set_double(&(plhs[4]), result.final_lambda_high);
}
/*
mexPrintf("r = %d, c = %d, k = %d, EMD budget = %d\n", r, c, k, emd_budget);
for (int ii = 0; ii < r; ++ii) {
for (int jj = 0; jj < c; ++jj) {
mexPrintf("%lf ", a[ii][jj]);
}
mexPrintf("\n");
}
*/
}
|
add outdegree_vertical_distance option to mex wrapper
|
add outdegree_vertical_distance option to mex wrapper
|
C++
|
mit
|
ludwigschmidt/emd_flow,samvrit/emd_flow,ludwigschmidt/emd_flow
|
cbbbfdcbaf5ff53eb4da8f0dbe8ca82dc94a6ca8
|
src/models/api.cpp
|
src/models/api.cpp
|
#include "source.h"
#include "site.h"
#include "functions.h"
Api::Api(QString name, QMap<QString, QString> data)
: m_name(name), m_data(data)
{
QString sr = m_name;
if (m_data.contains("Urls/"+sr+"/Tags"))
m_data["Urls/Tags"] = m_data["Urls/"+sr+"/Tags"];
if (m_data.contains("Urls/"+sr+"/Home"))
m_data["Urls/Home"] = m_data["Urls/"+sr+"/Home"];
if (m_data.contains("Urls/"+sr+"/Pools"))
m_data["Urls/Pools"] = m_data["Urls/"+sr+"/Pools"];
if (m_data.contains("Urls/"+sr+"/Login"))
m_data["Urls/Login"] = m_data["Urls/"+sr+"/Login"];
if (m_data.contains("Urls/"+sr+"/Limit"))
m_data["Urls/Limit"] = m_data["Urls/"+sr+"/Limit"];
if (m_data.contains("Urls/"+sr+"/Image"))
m_data["Urls/Image"] = m_data["Urls/"+sr+"/Image"];
if (m_data.contains("Urls/"+sr+"/Sample"))
m_data["Urls/Sample"] = m_data["Urls/"+sr+"/Sample"];
if (m_data.contains("Urls/"+sr+"/Preview"))
m_data["Urls/Preview"] = m_data["Urls/"+sr+"/Preview"];
if (m_data.contains("Urls/"+sr+"/MaxPage"))
m_data["Urls/MaxPage"] = m_data["Urls/"+sr+"/MaxPage"];
if (m_data.contains("Urls/"+sr+"/AltPagePrev"))
m_data["Urls/AltPagePrev"] = m_data["Urls/"+sr+"/AltPagePrev"];
if (m_data.contains("Urls/"+sr+"/AltPageNext"))
m_data["Urls/AltPageNext"] = m_data["Urls/"+sr+"/AltPageNext"];
}
QString Api::getName() const { return m_name; }
bool Api::contains(QString key) const { return m_data.contains(key); }
QString Api::value(QString key) const { return m_data.value(key); }
|
#include "source.h"
#include "site.h"
#include "functions.h"
Api::Api(QString name, QMap<QString, QString> data)
: m_name(name), m_data(data)
{
QString sr = m_name;
if (m_data.contains("Urls/"+sr+"/Tags"))
m_data["Urls/Tags"] = m_data["Urls/"+sr+"/Tags"];
if (m_data.contains("Urls/"+sr+"/Home"))
m_data["Urls/Home"] = m_data["Urls/"+sr+"/Home"];
if (m_data.contains("Urls/"+sr+"/Pools"))
m_data["Urls/Pools"] = m_data["Urls/"+sr+"/Pools"];
if (m_data.contains("Urls/"+sr+"/Login"))
m_data["Urls/Login"] = m_data["Urls/"+sr+"/Login"];
if (m_data.contains("Urls/"+sr+"/Limit"))
m_data["Urls/Limit"] = m_data["Urls/"+sr+"/Limit"];
if (m_data.contains("Urls/"+sr+"/MaxPage"))
m_data["Urls/MaxPage"] = m_data["Urls/"+sr+"/MaxPage"];
if (m_data.contains("Urls/"+sr+"/AltPagePrev"))
m_data["Urls/AltPagePrev"] = m_data["Urls/"+sr+"/AltPagePrev"];
if (m_data.contains("Urls/"+sr+"/AltPageNext"))
m_data["Urls/AltPageNext"] = m_data["Urls/"+sr+"/AltPageNext"];
}
QString Api::getName() const { return m_name; }
bool Api::contains(QString key) const { return m_data.contains(key); }
QString Api::value(QString key) const { return m_data.value(key); }
|
Fix coverage for Api class
|
Fix coverage for Api class
|
C++
|
apache-2.0
|
YoukaiCat/imgbrd-grabber,Bionus/imgbrd-grabber,Bionus/imgbrd-grabber,Bionus/imgbrd-grabber,Bionus/imgbrd-grabber,Bionus/imgbrd-grabber,YoukaiCat/imgbrd-grabber,Bionus/imgbrd-grabber
|
1e2b1c9fc4b76f8803b85a713b808292eb3e8bf1
|
src/condor_c++_util/stat_info.cpp
|
src/condor_c++_util/stat_info.cpp
|
/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "condor_constants.h"
#include "condor_debug.h"
#include "stat_info.h"
#include "condor_string.h"
#include "status_string.h"
#include "condor_config.h"
#include "stat_wrapper.h"
#include "perm.h"
#include "my_username.h"
#include "my_popen.h"
#include "directory.h"
StatInfo::StatInfo( const char *path )
{
char *s, *last = NULL;
fullpath = strnewp( path );
dirpath = strnewp( path );
// Since we've got our own copy of the full path now sitting
// in dirpath, we can find the last directory delimiter, make
// a copy of whatever is beyond it as the filename, and put a
// NULL in the first character after the delim character so
// that the dirpath always contains the directory delim.
for( s = dirpath; s && *s != '\0'; s++ ) {
if( *s == '\\' || *s == '/' ) {
last = s;
}
}
if( last != NULL && last[1] ) {
filename = strnewp( &last[1] );
last[1] = '\0';
} else {
filename = NULL;
}
stat_file( fullpath );
}
StatInfo::StatInfo( const char *param_dirpath,
const char *param_filename )
{
this->filename = strnewp( param_filename );
this->dirpath = make_dirpath( param_dirpath );
fullpath = dircat( param_dirpath, param_filename );
stat_file( fullpath );
}
StatInfo::StatInfo( int fd )
{
filename = NULL;
fullpath = NULL;
dirpath = NULL;
stat_file( fd );
}
#ifdef WIN32
StatInfo::StatInfo( const char* dirpath, const char* filename,
time_t time_access, time_t time_create,
time_t time_modify, filesize_t fsize,
bool is_dir, bool is_symlink )
{
this->dirpath = strnewp( dirpath );
this->filename = strnewp( filename );
fullpath = dircat( dirpath, filename );
si_error = SIGood;
si_errno = 0;
access_time = time_access;
modify_time = time_modify;
create_time = time_create;
mode_set = false;
file_size = fsize;
m_isDirectory = is_dir;
m_isSymlink = is_symlink;
}
#endif /* WIN32 */
StatInfo::~StatInfo( void )
{
if ( filename ) delete [] filename;
if ( dirpath ) delete [] dirpath;
if ( fullpath ) delete [] fullpath;
}
/*
UNIX note:
We want to stat the given file. We may be operating as root, but
root == nobody across most NFS file systems, so we may have to do it
as condor. If we succeed, we proceed, if the file has already been
removed we handle it. If we cannot do it as either root or condor,
we report an error.
*/
void
StatInfo::stat_file( const char *path )
{
// Initialize
init( );
// Ok, run stat
StatWrapper statbuf;
int status = statbuf.Stat( path, StatWrapper::STATOP_STAT );
# if (! defined WIN32)
if ( !status ) {
// Only lstat if it's a directory - or -
// the "only lstat() if dir" flag isn't set
const StatStructType *sb = statbuf.GetBuf( StatWrapper::STATOP_STAT );
status = statbuf.Stat( StatWrapper::STATOP_LSTAT );
}
# endif
// How'd it go?
if ( status ) {
si_errno = statbuf.GetErrno( );
# if (! defined WIN32 )
if ( EACCES == si_errno ) {
// permission denied, try as condor
priv_state priv = set_condor_priv();
status = statbuf.Retry( );
set_priv( priv );
if( status < 0 ) {
si_errno = statbuf.GetErrno( );
}
}
# endif
}
// If we've failed, just bail out
if ( status ) {
if (( ENOENT == si_errno ) || (EBADF == si_errno) ) {
si_error = SINoFile;
} else {
dprintf( D_FULLDEBUG,
"StatInfo::%s(%s) failed, errno: %d = %s\n",
statbuf.GetStatFn(),path,si_errno,strerror(si_errno) );
}
return;
}
init( &statbuf );
}
void
StatInfo::stat_file( int fd )
{
// Initialize
init( );
// Ok, run stat
StatWrapper statbuf;
int status = statbuf.Stat( fd );
// How'd it go?
if ( status ) {
si_errno = statbuf.GetErrno( );
# if (! defined WIN32 )
if ( EACCES == si_errno ) {
// permission denied, try as condor
priv_state priv = set_condor_priv();
status = statbuf.Retry( );
set_priv( priv );
if( status < 0 ) {
si_errno = statbuf.GetErrno( );
}
}
# endif
}
// If we've failed, just bail out
if ( status ) {
if (( ENOENT == si_errno ) || (EBADF == si_errno) ) {
si_error = SINoFile;
} else {
dprintf( D_FULLDEBUG,
"StatInfo::%s(fd=%d) failed, errno: %d = %s\n",
statbuf.GetStatFn(), fd, si_errno, strerror(si_errno) );
}
return;
}
init( &statbuf );
}
void
StatInfo::init( StatWrapper *statbuf )
{
// Initialize
if ( NULL == statbuf )
{
si_error = SIFailure;
access_time = 0;
modify_time = 0;
create_time = 0;
m_isDirectory = false;
m_isExecutable = false;
m_isSymlink = false;
mode_set = false;
}
else
{
// the do_stat succeeded
const StatStructType *sb;
const StatStructType *lsb;
sb = statbuf->GetBuf( StatWrapper::STATOP_STAT );
if ( !sb ) {
sb = statbuf->GetBuf( StatWrapper::STATOP_FSTAT );
}
if ( !sb ) {
sb = statbuf->GetBuf( StatWrapper::STATOP_LAST );
}
ASSERT(sb);
lsb = statbuf->GetBuf( StatWrapper::STATOP_LSTAT );
si_error = SIGood;
access_time = sb->st_atime;
create_time = sb->st_ctime;
modify_time = sb->st_mtime;
file_size = sb->st_size;
file_mode = sb->st_mode;
mode_set = true;
# if (! defined WIN32)
m_isDirectory = S_ISDIR(sb->st_mode);
// On Unix, if any execute bit is set (user, group, other), we
// consider it to be executable.
m_isExecutable = ((sb->st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) != 0 );
m_isSymlink = lsb && S_ISLNK(lsb->st_mode);
owner = sb->st_uid;
group = sb->st_gid;
# else
m_isDirectory = ((_S_IFDIR & sb->st_mode) != 0);
m_isExecutable = ((_S_IEXEC & sb->st_mode) != 0);
# endif
}
}
char*
StatInfo::make_dirpath( const char* dir )
{
if(!dir) {
return NULL;
}
char* rval;
int dirlen = strlen(dir);
if( dir[dirlen - 1] == DIR_DELIM_CHAR ) {
// We've already got the delim, just return a copy of what
// we were passed in:
rval = new char[dirlen + 1];
sprintf( rval, "%s", dir );
} else {
// We need to include the delim character.
rval = new char[dirlen + 2];
sprintf( rval, "%s%c", dir, DIR_DELIM_CHAR );
}
return rval;
}
mode_t
StatInfo::GetMode( void )
{
if( ! mode_set ) {
stat_file( fullpath );
}
return file_mode;
}
|
/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "condor_constants.h"
#include "condor_debug.h"
#include "stat_info.h"
#include "condor_string.h"
#include "status_string.h"
#include "condor_config.h"
#include "stat_wrapper.h"
#include "perm.h"
#include "my_username.h"
#include "my_popen.h"
#include "directory.h"
StatInfo::StatInfo( const char *path )
{
char *s, *last = NULL;
fullpath = strnewp( path );
dirpath = strnewp( path );
// Since we've got our own copy of the full path now sitting
// in dirpath, we can find the last directory delimiter, make
// a copy of whatever is beyond it as the filename, and put a
// NULL in the first character after the delim character so
// that the dirpath always contains the directory delim.
for( s = dirpath; s && *s != '\0'; s++ ) {
if( *s == '\\' || *s == '/' ) {
last = s;
}
}
if( last != NULL && last[1] ) {
filename = strnewp( &last[1] );
last[1] = '\0';
} else {
filename = NULL;
}
stat_file( fullpath );
}
StatInfo::StatInfo( const char *param_dirpath,
const char *param_filename )
{
this->filename = strnewp( param_filename );
this->dirpath = make_dirpath( param_dirpath );
fullpath = dircat( param_dirpath, param_filename );
stat_file( fullpath );
}
StatInfo::StatInfo( int fd )
{
filename = NULL;
fullpath = NULL;
dirpath = NULL;
stat_file( fd );
}
#ifdef WIN32
StatInfo::StatInfo( const char* dirpath, const char* filename,
time_t time_access, time_t time_create,
time_t time_modify, filesize_t fsize,
bool is_dir, bool is_symlink )
{
this->dirpath = strnewp( dirpath );
this->filename = strnewp( filename );
fullpath = dircat( dirpath, filename );
si_error = SIGood;
si_errno = 0;
access_time = time_access;
modify_time = time_modify;
create_time = time_create;
mode_set = false;
file_size = fsize;
m_isDirectory = is_dir;
m_isSymlink = is_symlink;
}
#endif /* WIN32 */
StatInfo::~StatInfo( void )
{
if ( filename ) delete [] filename;
if ( dirpath ) delete [] dirpath;
if ( fullpath ) delete [] fullpath;
}
/*
UNIX note:
We want to stat the given file. We may be operating as root, but
root == nobody across most NFS file systems, so we may have to do it
as condor. If we succeed, we proceed, if the file has already been
removed we handle it. If we cannot do it as either root or condor,
we report an error.
*/
void
StatInfo::stat_file( const char *path )
{
// Initialize
init( );
// Ok, run stat
StatWrapper statbuf;
int status = statbuf.Stat( path, StatWrapper::STATOP_STAT );
# if (! defined WIN32)
if ( !status ) {
// Only lstat if it's a directory - or -
// the "only lstat() if dir" flag isn't set
const StatStructType *sb = statbuf.GetBuf( StatWrapper::STATOP_STAT );
status = statbuf.Stat( StatWrapper::STATOP_LSTAT );
}
# endif
// How'd it go?
if ( status ) {
si_errno = statbuf.GetErrno( );
# if (! defined WIN32 )
if ( EACCES == si_errno ) {
// permission denied, try as condor
priv_state priv = set_condor_priv();
status = statbuf.Retry( );
set_priv( priv );
if( status < 0 ) {
si_errno = statbuf.GetErrno( );
}
}
# endif
}
// If we've failed, just bail out
if ( status ) {
if (( ENOENT == si_errno ) || (EBADF == si_errno) ) {
si_error = SINoFile;
} else {
dprintf( D_FULLDEBUG,
"StatInfo::%s(%s) failed, errno: %d = %s\n",
statbuf.GetStatFn(),path,si_errno,strerror(si_errno) );
}
return;
}
init( &statbuf );
}
void
StatInfo::stat_file( int fd )
{
// Initialize
init( );
// Ok, run stat
StatWrapper statbuf;
int status = statbuf.Stat( fd );
// How'd it go?
if ( status ) {
si_errno = statbuf.GetErrno( );
# if (! defined WIN32 )
if ( EACCES == si_errno ) {
// permission denied, try as condor
priv_state priv = set_condor_priv();
status = statbuf.Retry( );
set_priv( priv );
if( status < 0 ) {
si_errno = statbuf.GetErrno( );
}
}
# endif
}
// If we've failed, just bail out
if ( status ) {
if (( ENOENT == si_errno ) || (EBADF == si_errno) ) {
si_error = SINoFile;
} else {
dprintf( D_FULLDEBUG,
"StatInfo::%s(fd=%d) failed, errno: %d = %s\n",
statbuf.GetStatFn(), fd, si_errno, strerror(si_errno) );
}
return;
}
init( &statbuf );
}
void
StatInfo::init( StatWrapper *statbuf )
{
// Initialize
if ( NULL == statbuf )
{
si_error = SIFailure;
access_time = 0;
modify_time = 0;
create_time = 0;
file_size = 0;
m_isDirectory = false;
m_isExecutable = false;
m_isSymlink = false;
mode_set = false;
}
else
{
// the do_stat succeeded
const StatStructType *sb;
const StatStructType *lsb;
sb = statbuf->GetBuf( StatWrapper::STATOP_STAT );
if ( !sb ) {
sb = statbuf->GetBuf( StatWrapper::STATOP_FSTAT );
}
if ( !sb ) {
sb = statbuf->GetBuf( StatWrapper::STATOP_LAST );
}
ASSERT(sb);
lsb = statbuf->GetBuf( StatWrapper::STATOP_LSTAT );
si_error = SIGood;
access_time = sb->st_atime;
create_time = sb->st_ctime;
modify_time = sb->st_mtime;
file_size = sb->st_size;
file_mode = sb->st_mode;
mode_set = true;
# if (! defined WIN32)
m_isDirectory = S_ISDIR(sb->st_mode);
// On Unix, if any execute bit is set (user, group, other), we
// consider it to be executable.
m_isExecutable = ((sb->st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) != 0 );
m_isSymlink = lsb && S_ISLNK(lsb->st_mode);
owner = sb->st_uid;
group = sb->st_gid;
# else
m_isDirectory = ((_S_IFDIR & sb->st_mode) != 0);
m_isExecutable = ((_S_IEXEC & sb->st_mode) != 0);
# endif
}
}
char*
StatInfo::make_dirpath( const char* dir )
{
if(!dir) {
return NULL;
}
char* rval;
int dirlen = strlen(dir);
if( dir[dirlen - 1] == DIR_DELIM_CHAR ) {
// We've already got the delim, just return a copy of what
// we were passed in:
rval = new char[dirlen + 1];
sprintf( rval, "%s", dir );
} else {
// We need to include the delim character.
rval = new char[dirlen + 2];
sprintf( rval, "%s%c", dir, DIR_DELIM_CHAR );
}
return rval;
}
mode_t
StatInfo::GetMode( void )
{
if( ! mode_set ) {
stat_file( fullpath );
}
return file_mode;
}
|
Set file size to be intialized to 0 in stat_info.cpp to avoid returning an uninitialized value. #1621
|
Set file size to be intialized to 0 in stat_info.cpp to avoid returning an uninitialized value. #1621
|
C++
|
apache-2.0
|
djw8605/condor,zhangzhehust/htcondor,djw8605/htcondor,djw8605/htcondor,zhangzhehust/htcondor,mambelli/osg-bosco-marco,mambelli/osg-bosco-marco,bbockelm/condor-network-accounting,djw8605/htcondor,clalancette/condor-dcloud,clalancette/condor-dcloud,neurodebian/htcondor,htcondor/htcondor,djw8605/condor,djw8605/htcondor,mambelli/osg-bosco-marco,bbockelm/condor-network-accounting,zhangzhehust/htcondor,djw8605/htcondor,clalancette/condor-dcloud,bbockelm/condor-network-accounting,neurodebian/htcondor,zhangzhehust/htcondor,neurodebian/htcondor,djw8605/condor,zhangzhehust/htcondor,htcondor/htcondor,neurodebian/htcondor,djw8605/htcondor,djw8605/condor,mambelli/osg-bosco-marco,zhangzhehust/htcondor,bbockelm/condor-network-accounting,mambelli/osg-bosco-marco,bbockelm/condor-network-accounting,mambelli/osg-bosco-marco,neurodebian/htcondor,clalancette/condor-dcloud,neurodebian/htcondor,clalancette/condor-dcloud,clalancette/condor-dcloud,djw8605/htcondor,djw8605/condor,mambelli/osg-bosco-marco,neurodebian/htcondor,bbockelm/condor-network-accounting,djw8605/condor,htcondor/htcondor,bbockelm/condor-network-accounting,zhangzhehust/htcondor,djw8605/htcondor,zhangzhehust/htcondor,djw8605/condor,htcondor/htcondor,neurodebian/htcondor,djw8605/htcondor,clalancette/condor-dcloud,bbockelm/condor-network-accounting,htcondor/htcondor,neurodebian/htcondor,zhangzhehust/htcondor,djw8605/condor,mambelli/osg-bosco-marco,htcondor/htcondor,htcondor/htcondor,htcondor/htcondor
|
e7f01cc9754c572b4ccef324cea5758b2ca0eb8d
|
src/core/kext/util/FlagStatus.cpp
|
src/core/kext/util/FlagStatus.cpp
|
#include "FlagStatus.hpp"
namespace org_pqrs_KeyRemap4MacBook {
FlagStatus::Item FlagStatus::item_[FlagStatus::MAXNUM];
void
FlagStatus::Item::initialize(const ModifierFlag& f)
{
flag_ = f;
count_ = 0;
temporary_count_ = 0;
lock_count_ = 0;
original_lock_count_ = 0;
}
void
FlagStatus::Item::set(void)
{
temporary_count_ = 0;
}
void
FlagStatus::Item::set(const KeyCode& key, const Flags& flags)
{
temporary_count_ = 0;
// ------------------------------------------------------------
// At some keyboard, when we press CapsLock key, the down & up event are thrown at a time.
// So, we treat the capslock key exceptionally.
if (flag_ == ModifierFlag::CAPSLOCK) {
if (flags.isOn(flag_)) {
if (! original_lock_count_) {
original_lock_count_ = 1;
lock_count_ = 0; // clear remapped lock_count_ when original changed.
}
} else {
if (original_lock_count_) {
original_lock_count_ = 0;
lock_count_ = 0; // clear remapped lock_count_ when original changed.
}
}
return;
}
// ------------------------------------------------------------
if (key != flag_.getKeyCode()) return;
if (flags.isOn(flag_)) {
increase();
} else {
decrease();
}
}
void
FlagStatus::Item::reset(void)
{
count_ = 0;
temporary_count_ = 0;
/*
preserve lock_count, original_lock_count.
FlagStatus::reset is called when NumHeldDownKeys == 0,
so we need remember the status of CapsLock, NumLock, ...
*/
}
void
FlagStatus::Item::increase(void)
{
if (flag_ == ModifierFlag::CAPSLOCK) {
lock_count_ = ! lock_count_;
} else {
++count_;
}
}
void
FlagStatus::Item::decrease(void)
{
if (flag_ == ModifierFlag::CAPSLOCK) {
// do nothing (toggle at Item::increase).
} else {
--count_;
}
}
// ----------------------------------------------------------------------
bool
FlagStatus::initialize(void)
{
#define PUSH_ITEM(FLAG) { \
if (i >= MAXNUM) return false; \
item_[i].initialize(FLAG); \
i++; \
}
int i = 0;
PUSH_ITEM(ModifierFlag::CAPSLOCK);
PUSH_ITEM(ModifierFlag::SHIFT_L);
PUSH_ITEM(ModifierFlag::SHIFT_R);
PUSH_ITEM(ModifierFlag::CONTROL_L);
PUSH_ITEM(ModifierFlag::CONTROL_R);
PUSH_ITEM(ModifierFlag::OPTION_L);
PUSH_ITEM(ModifierFlag::OPTION_R);
PUSH_ITEM(ModifierFlag::COMMAND_L);
PUSH_ITEM(ModifierFlag::COMMAND_R);
PUSH_ITEM(ModifierFlag::FN);
PUSH_ITEM(ModifierFlag::NONE);
#undef PUSH_ITEM
return true;
}
void
FlagStatus::set(void)
{
for (int i = 0; item_[i].flag_ != ModifierFlag::NONE; ++i) {
item_[i].set();
}
}
void
FlagStatus::set(const KeyCode& key, const Flags& flags)
{
for (int i = 0; item_[i].flag_ != ModifierFlag::NONE; ++i) {
item_[i].set(key, flags);
}
}
void
FlagStatus::reset(void)
{
for (int i = 0; item_[i].flag_ != ModifierFlag::NONE; ++i) {
item_[i].reset();
}
}
Flags
FlagStatus::makeFlags(void)
{
Flags flags;
for (int i = 0; item_[i].flag_ != ModifierFlag::NONE; ++i) {
flags.add(item_[i].makeFlag());
}
return flags;
}
const ModifierFlag&
FlagStatus::getFlag(int index)
{
for (int i = 0; item_[i].flag_ != ModifierFlag::NONE; ++i) {
if (i == index) {
return item_[i].flag_;
}
}
return ModifierFlag::NONE;
}
// ------------------------------------------------------------
#define FOREACH_TO_FLAGS(METHOD) { \
for (int i = 0; item_[i].flag_ != ModifierFlag::NONE; ++i) { \
if (flags.isOn(item_[i].flag_)) { \
item_[i].METHOD(); \
} \
} \
}
void FlagStatus::increase(const Flags& flags) { FOREACH_TO_FLAGS(increase); }
void FlagStatus::decrease(const Flags& flags) { FOREACH_TO_FLAGS(decrease); }
void FlagStatus::temporary_increase(const Flags& flags) { FOREACH_TO_FLAGS(temporary_increase); }
void FlagStatus::temporary_decrease(const Flags& flags) { FOREACH_TO_FLAGS(temporary_decrease); }
void FlagStatus::lock_increase(const Flags& flags) { FOREACH_TO_FLAGS(lock_increase); }
void FlagStatus::lock_decrease(const Flags& flags) { FOREACH_TO_FLAGS(lock_decrease); }
#undef FOREACH_TO_FLAGS
}
|
#include "FlagStatus.hpp"
namespace org_pqrs_KeyRemap4MacBook {
FlagStatus::Item FlagStatus::item_[FlagStatus::MAXNUM];
void
FlagStatus::Item::initialize(const ModifierFlag& f)
{
flag_ = f;
count_ = 0;
temporary_count_ = 0;
lock_count_ = 0;
original_lock_count_ = 0;
}
void
FlagStatus::Item::set(void)
{
temporary_count_ = 0;
}
void
FlagStatus::Item::set(const KeyCode& key, const Flags& flags)
{
temporary_count_ = 0;
// ------------------------------------------------------------
// At some keyboard, when we press CapsLock key, the down & up event are thrown at a time.
// So, we treat the capslock key exceptionally.
if (flag_ == ModifierFlag::CAPSLOCK) {
if (flags.isOn(flag_)) {
if (! original_lock_count_) {
original_lock_count_ = 1;
lock_count_ = 0; // clear remapped lock_count_ when original changed.
}
} else {
if (original_lock_count_) {
original_lock_count_ = 0;
lock_count_ = 0; // clear remapped lock_count_ when original changed.
}
}
return;
}
// ------------------------------------------------------------
if (key != flag_.getKeyCode()) return;
if (flags.isOn(flag_)) {
increase();
} else {
decrease();
}
}
void
FlagStatus::Item::reset(void)
{
count_ = 0;
temporary_count_ = 0;
/*
preserve lock_count, original_lock_count.
FlagStatus::reset is called when NumHeldDownKeys == 0,
so we need remember the status of CapsLock, NumLock, ...
*/
}
void
FlagStatus::Item::increase(void)
{
if (flag_ == ModifierFlag::CAPSLOCK) {
lock_count_ = ! lock_count_;
} else {
++count_;
}
}
void
FlagStatus::Item::decrease(void)
{
if (flag_ == ModifierFlag::CAPSLOCK) {
// do nothing (toggle at Item::increase).
} else {
--count_;
}
}
// ----------------------------------------------------------------------
bool
FlagStatus::initialize(void)
{
#define PUSH_ITEM(FLAG) { \
if (i >= MAXNUM) return false; \
item_[i].initialize(FLAG); \
i++; \
}
int i = 0;
PUSH_ITEM(ModifierFlag::CAPSLOCK);
PUSH_ITEM(ModifierFlag::SHIFT_L);
PUSH_ITEM(ModifierFlag::SHIFT_R);
PUSH_ITEM(ModifierFlag::CONTROL_L);
PUSH_ITEM(ModifierFlag::CONTROL_R);
PUSH_ITEM(ModifierFlag::OPTION_L);
PUSH_ITEM(ModifierFlag::OPTION_R);
PUSH_ITEM(ModifierFlag::COMMAND_L);
PUSH_ITEM(ModifierFlag::COMMAND_R);
PUSH_ITEM(ModifierFlag::FN);
PUSH_ITEM(ModifierFlag::NONE);
#undef PUSH_ITEM
return true;
}
void
FlagStatus::set(void)
{
for (int i = 0; item_[i].flag_ != ModifierFlag::NONE; ++i) {
item_[i].set();
}
}
void
FlagStatus::set(const KeyCode& key, const Flags& flags)
{
for (int i = 0; item_[i].flag_ != ModifierFlag::NONE; ++i) {
item_[i].set(key, flags);
}
}
void
FlagStatus::reset(void)
{
for (int i = 0; item_[i].flag_ != ModifierFlag::NONE; ++i) {
item_[i].reset();
}
}
Flags
FlagStatus::makeFlags(void)
{
Flags flags;
for (int i = 0; item_[i].flag_ != ModifierFlag::NONE; ++i) {
flags.add(item_[i].makeFlag());
}
return flags;
}
const ModifierFlag&
FlagStatus::getFlag(int index)
{
for (int i = 0; item_[i].flag_ != ModifierFlag::NONE; ++i) {
if (i == index) {
return item_[i].flag_;
}
}
return ModifierFlag::NONE;
}
// ------------------------------------------------------------
#define FOREACH_TO_FLAGS(METHOD) { \
for (int i = 0; item_[i].flag_ != ModifierFlag::NONE; ++i) { \
if (flags.isOn(item_[i].flag_)) { \
item_[i].METHOD(); \
} \
} \
}
void FlagStatus::increase(const Flags& flags) { FOREACH_TO_FLAGS(increase); }
void FlagStatus::decrease(const Flags& flags) { FOREACH_TO_FLAGS(decrease); }
void FlagStatus::temporary_increase(const Flags& flags) { FOREACH_TO_FLAGS(temporary_increase); }
void FlagStatus::temporary_decrease(const Flags& flags) { FOREACH_TO_FLAGS(temporary_decrease); }
void FlagStatus::lock_increase(const Flags& flags) { FOREACH_TO_FLAGS(lock_increase); }
void FlagStatus::lock_decrease(const Flags& flags) { FOREACH_TO_FLAGS(lock_decrease); }
#undef FOREACH_TO_FLAGS
}
|
apply uncrustify
|
apply uncrustify
|
C++
|
unlicense
|
muramasa64/Karabiner,muramasa64/Karabiner,miaotaizi/Karabiner,e-gaulue/Karabiner,miaotaizi/Karabiner,wataash/Karabiner,chzyer-dev/Karabiner,muramasa64/Karabiner,miaotaizi/Karabiner,e-gaulue/Karabiner,e-gaulue/Karabiner,wataash/Karabiner,muramasa64/Karabiner,runarbu/Karabiner,tekezo/Karabiner,wataash/Karabiner,runarbu/Karabiner,astachurski/Karabiner,tekezo/Karabiner,e-gaulue/Karabiner,chzyer-dev/Karabiner,runarbu/Karabiner,runarbu/Karabiner,tekezo/Karabiner,miaotaizi/Karabiner,astachurski/Karabiner,wataash/Karabiner,astachurski/Karabiner,tekezo/Karabiner,astachurski/Karabiner,chzyer-dev/Karabiner,chzyer-dev/Karabiner
|
b9fd8e40736b69c6ad1d8ed4bd066e4b84474424
|
examples/hello-world.cxx
|
examples/hello-world.cxx
|
/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2014
Raffaello D. Di Napoli
This file is part of Application-Building Components (henceforth referred to as ABC).
ABC 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.
ABC 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 ABC. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/
/** DOC:0101 Hello World example
This is a basic usage example of ABC; all it does is display the canonical “Hello World” text, then
it terminates. See the source code for line-by-line comments.
*/
// This should always be the first file included in any C++ source using Abc.
#include <abc.hxx>
// This needs to be included in the .cxx file that defines the application class for the program –
// see below.
#include <abc/app.hxx>
// This provides abc::io::text::stdout() and stdin(), which allow basic text interactivity for the
// program.
#include <abc/io/text/file.hxx>
// ABC does not use “using” directives in its sources or header files; if you want such convenience,
// you have to write it yourself in your own source files.
using namespace abc;
////////////////////////////////////////////////////////////////////////////////////////////////////
// example_app
/** This is a basic application class. The ABC_APP_CLASS() statement (below) indicates that this
class shall be instantiated as soon as the program is started, and its main() method should be
invoked immediately afterwards; see [DOC:1063 Application startup and abc::app].
*/
class example_app :
public app {
public:
/** This method is invoked when the program starts; returning from this method causes the end of
the program.
vsArgs
This vector contains all the arguments that were provided to the program via command line.
return
The return value of this method will be available to the parent process as this program’s
return value, accessible in a shell/command prompt as $? (Linux/POSIX) or %ERRORLEVEL%
(Win32).
*/
virtual int main(mvector<istr const> const & vsArgs) {
ABC_TRACE_FN((this, vsArgs));
// Write “Hello World” into the stdout text writer object.
io::text::stdout()->write_line(SL("Hello World"));
// Make this program return 0 to the parent process.
return 0;
}
};
ABC_APP_CLASS(example_app)
|
/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2014
Raffaello D. Di Napoli
This file is part of Application-Building Components (henceforth referred to as ABC).
ABC 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.
ABC 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 ABC. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/
/** DOC:0101 Hello World example
This is a basic usage example of ABC; all it does is display the canonical “Hello World” text, then
it terminates. See the source code for line-by-line comments.
*/
// This should always be the first file included in any C++ source using ABC.
#include <abc.hxx>
// This needs to be included in the .cxx file that defines the application class for the program –
// see below.
#include <abc/app.hxx>
// This provides abc::io::text::stdout() and stdin(), which allow basic text interactivity for the
// program.
#include <abc/io/text/file.hxx>
// ABC does not use “using” directives in its sources or header files; if you want such convenience,
// you have to write it yourself in your own source files.
using namespace abc;
////////////////////////////////////////////////////////////////////////////////////////////////////
// example_app
/** This is a basic application class. The ABC_APP_CLASS() statement (below) indicates that this
class shall be instantiated as soon as the program is started, and its main() method should be
invoked immediately afterwards; see [DOC:1063 Application startup and abc::app].
*/
class example_app :
public app {
public:
/** This method is invoked when the program starts; returning from this method causes the end of
the program.
vsArgs
This vector contains all the arguments that were provided to the program via command line.
return
The return value of this method will be available to the parent process as this program’s
return value, accessible in a shell/command prompt as $? (Linux/POSIX) or %ERRORLEVEL%
(Win32).
*/
virtual int main(mvector<istr const> const & vsArgs) {
// This should be the first line of every function/method; it allows to inspect the values of
// the method’s arguments when an exception is raised during the execution of the method.
ABC_TRACE_FN((this, vsArgs));
// Write “Hello World” into the stdout text writer object.
io::text::stdout()->write_line(SL("Hello World"));
// Make this program return 0 to the parent process.
return 0;
}
};
ABC_APP_CLASS(example_app)
|
Improve code documentation
|
Improve code documentation
|
C++
|
lgpl-2.1
|
raffaellod/lofty,raffaellod/lofty
|
50e454278188d16807f2e2539354ef1e8d07cabc
|
examples/json_classes.hh
|
examples/json_classes.hh
|
// Copyright (c) 2014-2015 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/
#ifndef PEGTL_EXAMPLES_JSON_CLASSES_HH
#define PEGTL_EXAMPLES_JSON_CLASSES_HH
#include <map>
#include <string>
#include <vector>
#include <memory>
#include <iostream>
namespace examples
{
enum class json_type
{
ARRAY,
BOOLEAN,
NULL_,
NUMBER,
OBJECT,
STRING
};
class json_base
{
public:
const json_type type;
virtual void stream( std::ostream & ) const = 0;
protected:
explicit
json_base( const json_type type )
: type( type )
{ }
~json_base()
{ }
};
inline std::ostream & operator<< ( std::ostream & o, const json_base & j )
{
j.stream( o );
return o;
}
inline std::ostream & operator<< ( std::ostream & o, const std::shared_ptr< json_base > & j )
{
return j ? ( o << * j ) : ( o << "NULL" );
}
struct array_json
: public json_base
{
array_json()
: json_base( json_type::ARRAY )
{ }
std::vector< std::shared_ptr< json_base > > data;
virtual void stream( std::ostream & o ) const override
{
o << '[';
if ( ! data.empty() ) {
auto iter = data.begin();
o << * iter;
while ( ++iter != data.end() ) {
o << ',' << * iter;
}
}
o << ']';
}
};
struct boolean_json
: public json_base
{
explicit
boolean_json( const bool data)
: json_base( json_type::BOOLEAN ),
data( data )
{ }
bool data;
virtual void stream( std::ostream & o ) const override
{
o << ( data ? "true" : "false" );
}
};
struct null_json
: public json_base
{
null_json()
: json_base( json_type::NULL_ )
{ }
virtual void stream( std::ostream & o ) const override
{
o << "null";
}
};
struct number_json
: public json_base
{
explicit
number_json( const long double data )
: json_base( json_type::NUMBER ),
data( data )
{ }
long double data;
virtual void stream( std::ostream & o ) const override
{
o << data;
}
};
inline std::string json_escape( const std::string & data )
{
std::string r = "\"";
static const char * h = "0123456789abcdef";
for ( auto c : data ) {
if ( ( c < 32 ) || ( c == 127 ) ) {
r += "\\u00";
r += h[ ( c & 0xf0 ) >> 4 ];
r += h[ c & 0x0f ];
continue;
}
switch ( c ) {
case '\b':
r += "\\b";
break;
case '\f':
r += "\\f";
break;
case '\n':
r += "\\n";
break;
case '\r':
r += "\\r";
break;
case '\t':
r += "\\t";
break;
case '\\':
r += "\\\\";
break;
case '\"':
r += "\\\"";
break;
default:
r += c; // Assume valid UTF-8.
break;
}
}
r += '"';
return r;
}
struct string_json
: public json_base
{
explicit
string_json( const std::string & data )
: json_base( json_type::STRING ),
data( data )
{ }
std::string data;
virtual void stream( std::ostream & o ) const override
{
o << json_escape( data );
}
};
struct object_json
: public json_base
{
object_json()
: json_base( json_type::OBJECT )
{ }
std::map< std::string, std::shared_ptr< json_base > > data;
virtual void stream( std::ostream & o ) const override
{
o << '{';
if ( ! data.empty() ) {
auto iter = data.begin();
o << json_escape( iter->first ) << ':' << iter->second;
while ( ++iter != data.end() ) {
o << ',' << json_escape( iter->first ) << ':' << iter->second;
}
}
o << '}';
}
};
} // examples
#endif
|
// Copyright (c) 2014-2015 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/
#ifndef PEGTL_EXAMPLES_JSON_CLASSES_HH
#define PEGTL_EXAMPLES_JSON_CLASSES_HH
#include <map>
#include <string>
#include <vector>
#include <memory>
#include <iostream>
namespace examples
{
enum class json_type
{
ARRAY,
BOOLEAN,
NULL_,
NUMBER,
OBJECT,
STRING
};
class json_base
{
public:
const json_type type;
virtual void stream( std::ostream & ) const = 0;
protected:
explicit
json_base( const json_type type )
: type( type )
{ }
~json_base()
{ }
};
inline std::ostream & operator<< ( std::ostream & o, const json_base & j )
{
j.stream( o );
return o;
}
inline std::ostream & operator<< ( std::ostream & o, const std::shared_ptr< json_base > & j )
{
return j ? ( o << * j ) : ( o << "NULL" );
}
struct array_json
: public json_base
{
array_json()
: json_base( json_type::ARRAY )
{ }
std::vector< std::shared_ptr< json_base > > data;
virtual void stream( std::ostream & o ) const override
{
o << '[';
if ( ! data.empty() ) {
auto iter = data.begin();
o << * iter;
while ( ++iter != data.end() ) {
o << ',' << * iter;
}
}
o << ']';
}
};
struct boolean_json
: public json_base
{
explicit
boolean_json( const bool data)
: json_base( json_type::BOOLEAN ),
data( data )
{ }
bool data;
virtual void stream( std::ostream & o ) const override
{
o << ( data ? "true" : "false" );
}
};
struct null_json
: public json_base
{
null_json()
: json_base( json_type::NULL_ )
{ }
virtual void stream( std::ostream & o ) const override
{
o << "null";
}
};
struct number_json
: public json_base
{
explicit
number_json( const long double data )
: json_base( json_type::NUMBER ),
data( data )
{ }
long double data;
virtual void stream( std::ostream & o ) const override
{
o << data;
}
};
inline std::string json_escape( const std::string & data )
{
std::string r = "\"";
r.reserve( data.size() + 4 );
static const char * h = "0123456789abcdef";
const unsigned char * d = reinterpret_cast< const unsigned char * >( data.data() );
for ( size_t i = 0; i < data.size(); ++i ) {
const auto c = d[ i ];
if ( ( c < 32 ) || ( c == 127 ) ) {
r += "\\u00";
r += h[ ( c & 0xf0 ) >> 4 ];
r += h[ c & 0x0f ];
continue;
}
switch ( c ) {
case '\b':
r += "\\b";
break;
case '\f':
r += "\\f";
break;
case '\n':
r += "\\n";
break;
case '\r':
r += "\\r";
break;
case '\t':
r += "\\t";
break;
case '\\':
r += "\\\\";
break;
case '\"':
r += "\\\"";
break;
default:
r += c; // Assume valid UTF-8.
break;
}
}
r += '"';
return r;
}
struct string_json
: public json_base
{
explicit
string_json( const std::string & data )
: json_base( json_type::STRING ),
data( data )
{ }
std::string data;
virtual void stream( std::ostream & o ) const override
{
o << json_escape( data );
}
};
struct object_json
: public json_base
{
object_json()
: json_base( json_type::OBJECT )
{ }
std::map< std::string, std::shared_ptr< json_base > > data;
virtual void stream( std::ostream & o ) const override
{
o << '{';
if ( ! data.empty() ) {
auto iter = data.begin();
o << json_escape( iter->first ) << ':' << iter->second;
while ( ++iter != data.end() ) {
o << ',' << json_escape( iter->first ) << ':' << iter->second;
}
}
o << '}';
}
};
} // examples
#endif
|
Fix JSON string escape.
|
Fix JSON string escape.
|
C++
|
mit
|
ColinH/PEGTL,nlyan/PEGTL,ColinH/PEGTL,kneth/PEGTL,kneth/PEGTL
|
c54aed8aaaa063c68a9979b1598b50d1e475aa67
|
sash/libedit_backend.hpp
|
sash/libedit_backend.hpp
|
/******************************************************************************
* ____ ______ ____ __ __ *
* /\ _`\ /\ _ \ /\ _`\ /\ \/\ \ *
* \ \,\L\_\\ \ \L\ \\ \,\L\_\\ \ \_\ \ *
* \/_\__ \ \ \ __ \\/_\__ \ \ \ _ \ *
* /\ \L\ \\ \ \/\ \ /\ \L\ \\ \ \ \ \ *
* \ `\____\\ \_\ \_\\ `\____\\ \_\ \_\ *
* \/_____/ \/_/\/_/ \/_____/ \/_/\/_/ *
* *
* *
* Copyright (c) 2014 *
* Matthias Vallentin <vallentin (at) icir.org> *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the 3-clause BSD License. *
* See accompanying file LICENSE. *
\******************************************************************************/
#ifndef SASH_BACKEND_HPP
#define SASH_BACKEND_HPP
#include <string>
#include <cassert>
#include <histedit.h>
#include "sash/color.hpp"
namespace sash {
/// The default backend wraps command line editing functionality
/// as provided by `libedit`.
template<class Completer>
class libedit_backend
{
public:
/// A (smart) pointer to the completion context
using completer_pointer = std::shared_ptr<Completer>;
using completer_type = Completer;
libedit_backend(const char* shell_name,
std::string history_filename = "",
int history_size = 1000,
bool unique_history = true,
std::string completion_key = "\t",
char const* editrc = nullptr)
: history_filename_{std::move(history_filename)},
completer_{std::make_shared<Completer>()},
eof_{false}
{
el_ = ::el_init(shell_name, stdin, stdout, stderr);
assert(el_ != nullptr);
// Make ourselves available in callbacks.
set(EL_CLIENTDATA, this);
// Keyboard defaults.
set(EL_EDITOR, "vi");
set(EL_BIND, "^r", "em-inc-search-prev", NULL);
set(EL_BIND, "^w", "ed-delete-prev-word", NULL);
// Setup completion.
using completion_handler = unsigned char (*)(EditLine*, int);
completion_handler ch_callback = [](EditLine* el, int) -> unsigned char
{
libedit_backend* self = nullptr;
::el_get(el, EL_CLIENTDATA, &self);
assert(self != nullptr);
assert(self->el_ == el);
std::string line;
self->get_cursor_line(line);
std::string completed_line;
if (self->completer_->complete(completed_line, line) != completed)
return CC_REFRESH_BEEP;
self->insert(completed_line);
return CC_REDISPLAY;
};
set(EL_ADDFN, "sash-complete", "SASH complete", ch_callback);
set(EL_BIND, completion_key.c_str(), "sash-complete", NULL);
// FIXME: this is a fix for folks that have "bind -v" in their .editrc.
// Most of these also have "bind ^I rl_complete" in there to re-enable tab
// completion, which "bind -v" somehow disabled. A better solution to
// handle this problem would be desirable.
set(EL_ADDFN, "rl_complete", "default complete", ch_callback);
// Let all character reads go through our custom handler so that we can
// figure out when we receive EOF.
using char_read_handler = int (*)(EditLine*, char*);
char_read_handler cr_callback = [](EditLine* el, char* result) -> int
{
libedit_backend* self = nullptr;
::el_get(el, EL_CLIENTDATA, &self);
assert(self != nullptr);
assert(self->el_ == el);
FILE* input_file_handle = nullptr;
::el_get(el, EL_GETFP, 0, &input_file_handle);
auto empty_line = [el]() -> bool
{
auto info = ::el_line(el);
return info->buffer == info->cursor && info->buffer == info->lastchar;
};
for (;;)
{
errno = 0;
char ch = ::fgetc(input_file_handle);
if (ch == '\x04' && empty_line())
{
errno = 0;
ch = EOF;
}
if (ch == EOF)
{
if (errno == EINTR)
{
continue;
}
else
{
self->eof_ = true;
return 0;
}
}
else
{
*result = ch;
return 1;
}
}
};
set(EL_GETCFN, cr_callback);
// Setup for our prompt.
using prompt_function = char* (*)(EditLine* el);
prompt_function pf = [](EditLine* el) -> char*
{
libedit_backend* self;
::el_get(el, EL_CLIENTDATA, &self);
assert(self);
return const_cast<char*>(self->prompt_.c_str());
};
set(EL_PROMPT, pf);
// Setup for our history.
hist_ = ::history_init();
assert(hist_ != nullptr);
set(EL_HIST, ::history, hist_);
minitrue(H_SETSIZE, history_size);
minitrue(H_SETUNIQUE, unique_history ? 1 : 0);
history_load();
// Source the editrc config.
source(editrc);
}
~libedit_backend()
{
history_save();
::history_end(hist_);
::el_end(el_);
}
/// Parses an editrc.
/// @param editrc The configuration file in *editrc* format. If `nullptr`,
/// looks in `$PWD/.editrc` and then `$HOME/.editrc`.
/// @returns `true` on successful parsing.
bool source(char const* editrc = nullptr)
{
return ::el_source(el_, editrc) != -1;
}
/// Resets the TTY and the parser.
void reset()
{
::el_reset(el_);
}
/// Writes the history to file.
void history_save()
{
if (! history_filename_.empty())
minitrue(H_SAVE, history_filename_.c_str());
}
/// Reads the history from file.
void history_load()
{
if (! history_filename_.empty())
minitrue(H_LOAD, history_filename_.c_str());
}
/// Appends @p str to the current element of the history, or
/// behave like {@link enter_history} if there is no current element.
void history_add(std::string const& str)
{
minitrue(H_ADD, str.c_str());
history_save();
}
/// Appends @p str to the last new element of the history.
void history_append(std::string const& str)
{
minitrue(H_APPEND, str.c_str());
}
/// Adds @p str as a new element to the history.
void history_enter(std::string const& str)
{
minitrue(H_ENTER, str.c_str());
}
/// Sets a (colored) string as prompt for the shell.
void set_prompt(std::string str, color::type strcolor = color::none)
{
prompt_.clear();
add_to_prompt(std::move(str), strcolor);
}
/// Appends a (colored) string to the prompt.
void add_to_prompt(std::string str, color::type strcolor = color::none)
{
if (str.empty())
return;
if (strcolor != color::none)
{
prompt_ += strcolor;
prompt_ += std::move(str);
prompt_ += color::reset;
}
else
{
prompt_ += std::move(str);
}
}
/// Returns the current prompt.
std::string const& prompt() const
{
return prompt_;
}
/// Checks whether we've reached the end of file.
bool eof() const
{
return eof_;
}
/// Reads a character.
bool read_char(char& c)
{
return ! eof() && get(&c) == 1;
}
/// Reads a line.
bool read_line(std::string& line)
{
if (eof())
return false;
line.clear();
raii_set guard{el_, EL_PREP_TERM};
int n;
auto str = ::el_gets(el_, &n);
if (n == -1 || eof())
return false;
if (str != nullptr)
{
while (n > 0 && (str[n - 1] == '\n' || str[n - 1] == '\r'))
--n;
line.assign(str, n);
}
return true;
}
void get_current_line(std::string& line)
{
auto info = ::el_line(el_);
line.assign(
info->buffer,
static_cast<std::string::size_type>(info->lastchar - info->buffer));
}
void get_cursor_line(std::string& line)
{
auto info = ::el_line(el_);
line.assign(
info->buffer,
static_cast<std::string::size_type>(info->cursor - info->buffer));
}
/// Returns the current cursor position.
size_t cursor()
{
auto info = ::el_line(el_);
return info->cursor - info->buffer;
}
/// Resizes the shell.
void resize()
{
::el_resize(el_);
}
/// Rings a bell.
void beep()
{
::el_beep(el_);
}
void push(char const* str)
{
::el_push(el_, str);
}
void insert(std::string const& str)
{
::el_insertstr(el_, str.c_str());
}
completer_pointer get_completer()
{
return completer_;
}
private:
// The Ministry of Truth. Its purpose is to
// rewrite history over and over again...
template<typename... Ts>
void minitrue(int flag, Ts... args)
{
::history(hist_, &hist_event_, flag, args...);
}
template<typename... Ts>
void get(int flag, Ts... args)
{
::el_get(el_, flag, args...);
}
template<typename... Ts>
void set(int flag, Ts... args)
{
::el_set(el_, flag, args...);
}
// RAII enabling of editline settings.
struct raii_set
{
raii_set(EditLine* el, int flag)
: el{el}, flag{flag}
{
::el_set(el, flag, 1);
}
~raii_set()
{
assert(el);
::el_set(el, flag, 0);
}
EditLine* el;
int flag;
};
EditLine* el_;
History* hist_;
HistEvent hist_event_;
std::string history_filename_;
std::string prompt_;
std::string comp_key_;
completer_pointer completer_;
bool eof_;
};
} // namespace sash
#endif // SASH_BACKEND_HPP
|
/******************************************************************************
* ____ ______ ____ __ __ *
* /\ _`\ /\ _ \ /\ _`\ /\ \/\ \ *
* \ \,\L\_\\ \ \L\ \\ \,\L\_\\ \ \_\ \ *
* \/_\__ \ \ \ __ \\/_\__ \ \ \ _ \ *
* /\ \L\ \\ \ \/\ \ /\ \L\ \\ \ \ \ \ *
* \ `\____\\ \_\ \_\\ `\____\\ \_\ \_\ *
* \/_____/ \/_/\/_/ \/_____/ \/_/\/_/ *
* *
* *
* Copyright (c) 2014 *
* Matthias Vallentin <vallentin (at) icir.org> *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the 3-clause BSD License. *
* See accompanying file LICENSE. *
\******************************************************************************/
#ifndef SASH_BACKEND_HPP
#define SASH_BACKEND_HPP
#include <string>
#include <cassert>
#include <histedit.h>
#include "sash/color.hpp"
namespace sash {
/// The default backend wraps command line editing functionality
/// as provided by `libedit`.
template<class Completer>
class libedit_backend
{
public:
/// A (smart) pointer to the completion context
using completer_pointer = std::shared_ptr<Completer>;
using completer_type = Completer;
libedit_backend(const char* shell_name,
std::string history_filename = "",
int history_size = 1000,
bool unique_history = true,
std::string completion_key = "\t",
char const* editrc = nullptr)
: history_filename_{std::move(history_filename)},
completer_{std::make_shared<Completer>()},
eof_{false}
{
el_ = ::el_init(shell_name, stdin, stdout, stderr);
assert(el_ != nullptr);
// Make ourselves available in callbacks.
set(EL_CLIENTDATA, this);
// Keyboard defaults.
set(EL_EDITOR, "emacs");
// Setup completion.
using completion_handler = unsigned char (*)(EditLine*, int);
completion_handler ch_callback = [](EditLine* el, int) -> unsigned char
{
libedit_backend* self = nullptr;
::el_get(el, EL_CLIENTDATA, &self);
assert(self != nullptr);
assert(self->el_ == el);
std::string line;
self->get_cursor_line(line);
std::string completed_line;
if (self->completer_->complete(completed_line, line) != completed)
return CC_REFRESH_BEEP;
self->insert(completed_line);
return CC_REDISPLAY;
};
set(EL_ADDFN, "sash-complete", "SASH complete", ch_callback);
set(EL_BIND, completion_key.c_str(), "sash-complete", NULL);
// FIXME: this is a fix for folks that have "bind -v" in their .editrc.
// Most of these also have "bind ^I rl_complete" in there to re-enable tab
// completion, which "bind -v" somehow disabled. A better solution to
// handle this problem would be desirable.
set(EL_ADDFN, "rl_complete", "default complete", ch_callback);
// Let all character reads go through our custom handler so that we can
// figure out when we receive EOF.
using char_read_handler = int (*)(EditLine*, char*);
char_read_handler cr_callback = [](EditLine* el, char* result) -> int
{
libedit_backend* self = nullptr;
::el_get(el, EL_CLIENTDATA, &self);
assert(self != nullptr);
assert(self->el_ == el);
FILE* input_file_handle = nullptr;
::el_get(el, EL_GETFP, 0, &input_file_handle);
auto empty_line = [el]() -> bool
{
auto info = ::el_line(el);
return info->buffer == info->cursor && info->buffer == info->lastchar;
};
for (;;)
{
errno = 0;
char ch = ::fgetc(input_file_handle);
if (ch == '\x04' && empty_line())
{
errno = 0;
ch = EOF;
}
if (ch == EOF)
{
if (errno == EINTR)
{
continue;
}
else
{
self->eof_ = true;
return 0;
}
}
else
{
*result = ch;
return 1;
}
}
};
set(EL_GETCFN, cr_callback);
// Setup for our prompt.
using prompt_function = char* (*)(EditLine* el);
prompt_function pf = [](EditLine* el) -> char*
{
libedit_backend* self;
::el_get(el, EL_CLIENTDATA, &self);
assert(self);
return const_cast<char*>(self->prompt_.c_str());
};
set(EL_PROMPT, pf);
// Setup for our history.
hist_ = ::history_init();
assert(hist_ != nullptr);
set(EL_HIST, ::history, hist_);
minitrue(H_SETSIZE, history_size);
minitrue(H_SETUNIQUE, unique_history ? 1 : 0);
history_load();
// Source the editrc config.
source(editrc);
}
~libedit_backend()
{
history_save();
::history_end(hist_);
::el_end(el_);
}
/// Parses an editrc.
/// @param editrc The configuration file in *editrc* format. If `nullptr`,
/// looks in `$PWD/.editrc` and then `$HOME/.editrc`.
/// @returns `true` on successful parsing.
bool source(char const* editrc = nullptr)
{
return ::el_source(el_, editrc) != -1;
}
/// Resets the TTY and the parser.
void reset()
{
::el_reset(el_);
}
/// Writes the history to file.
void history_save()
{
if (! history_filename_.empty())
minitrue(H_SAVE, history_filename_.c_str());
}
/// Reads the history from file.
void history_load()
{
if (! history_filename_.empty())
minitrue(H_LOAD, history_filename_.c_str());
}
/// Appends @p str to the current element of the history, or
/// behave like {@link enter_history} if there is no current element.
void history_add(std::string const& str)
{
minitrue(H_ADD, str.c_str());
history_save();
}
/// Appends @p str to the last new element of the history.
void history_append(std::string const& str)
{
minitrue(H_APPEND, str.c_str());
}
/// Adds @p str as a new element to the history.
void history_enter(std::string const& str)
{
minitrue(H_ENTER, str.c_str());
}
/// Sets a (colored) string as prompt for the shell.
void set_prompt(std::string str, color::type strcolor = color::none)
{
prompt_.clear();
add_to_prompt(std::move(str), strcolor);
}
/// Appends a (colored) string to the prompt.
void add_to_prompt(std::string str, color::type strcolor = color::none)
{
if (str.empty())
return;
if (strcolor != color::none)
{
prompt_ += strcolor;
prompt_ += std::move(str);
prompt_ += color::reset;
}
else
{
prompt_ += std::move(str);
}
}
/// Returns the current prompt.
std::string const& prompt() const
{
return prompt_;
}
/// Checks whether we've reached the end of file.
bool eof() const
{
return eof_;
}
/// Reads a character.
bool read_char(char& c)
{
return ! eof() && get(&c) == 1;
}
/// Reads a line.
bool read_line(std::string& line)
{
if (eof())
return false;
line.clear();
raii_set guard{el_, EL_PREP_TERM};
int n;
auto str = ::el_gets(el_, &n);
if (n == -1 || eof())
return false;
if (str != nullptr)
{
while (n > 0 && (str[n - 1] == '\n' || str[n - 1] == '\r'))
--n;
line.assign(str, n);
}
return true;
}
void get_current_line(std::string& line)
{
auto info = ::el_line(el_);
line.assign(
info->buffer,
static_cast<std::string::size_type>(info->lastchar - info->buffer));
}
void get_cursor_line(std::string& line)
{
auto info = ::el_line(el_);
line.assign(
info->buffer,
static_cast<std::string::size_type>(info->cursor - info->buffer));
}
/// Returns the current cursor position.
size_t cursor()
{
auto info = ::el_line(el_);
return info->cursor - info->buffer;
}
/// Resizes the shell.
void resize()
{
::el_resize(el_);
}
/// Rings a bell.
void beep()
{
::el_beep(el_);
}
void push(char const* str)
{
::el_push(el_, str);
}
void insert(std::string const& str)
{
::el_insertstr(el_, str.c_str());
}
completer_pointer get_completer()
{
return completer_;
}
private:
// The Ministry of Truth. Its purpose is to
// rewrite history over and over again...
template<typename... Ts>
void minitrue(int flag, Ts... args)
{
::history(hist_, &hist_event_, flag, args...);
}
template<typename... Ts>
void get(int flag, Ts... args)
{
::el_get(el_, flag, args...);
}
template<typename... Ts>
void set(int flag, Ts... args)
{
::el_set(el_, flag, args...);
}
// RAII enabling of editline settings.
struct raii_set
{
raii_set(EditLine* el, int flag)
: el{el}, flag{flag}
{
::el_set(el, flag, 1);
}
~raii_set()
{
assert(el);
::el_set(el, flag, 0);
}
EditLine* el;
int flag;
};
EditLine* el_;
History* hist_;
HistEvent hist_event_;
std::string history_filename_;
std::string prompt_;
std::string comp_key_;
completer_pointer completer_;
bool eof_;
};
} // namespace sash
#endif // SASH_BACKEND_HPP
|
Fix VI-Mode when scrolling trough history
|
Fix VI-Mode when scrolling trough history
|
C++
|
bsd-3-clause
|
Neverlord/sash
|
b2191d0467eaee992eff48646c40a01d1e405597
|
rmidevice/rmidevice.cpp
|
rmidevice/rmidevice.cpp
|
/*
* Copyright (C) 2014 Andrew Duggan
* Copyright (C) 2014 Synaptics 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 <stdio.h>
#include <time.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include "rmidevice.h"
#define RMI_DEVICE_PDT_ENTRY_SIZE 6
#define RMI_DEVICE_PAGE_SELECT_REGISTER 0xFF
#define RMI_DEVICE_MAX_PAGE 0xFF
#define RMI_DEVICE_PAGE_SIZE 0x100
#define RMI_DEVICE_PAGE_SCAN_START 0x00e9
#define RMI_DEVICE_PAGE_SCAN_END 0x0005
#define RMI_DEVICE_F01_BASIC_QUERY_LEN 11
#define RMI_DEVICE_F01_QRY5_YEAR_MASK 0x1f
#define RMI_DEVICE_F01_QRY6_MONTH_MASK 0x0f
#define RMI_DEVICE_F01_QRY7_DAY_MASK 0x1f
#define RMI_DEVICE_F01_QRY1_HAS_LTS (1 << 2)
#define RMI_DEVICE_F01_QRY1_HAS_SENSOR_ID (1 << 3)
#define RMI_DEVICE_F01_QRY1_HAS_CHARGER_INP (1 << 4)
#define RMI_DEVICE_F01_QRY1_HAS_ADJ_DOZE (1 << 5)
#define RMI_DEVICE_F01_QRY1_HAS_ADJ_DOZE_HOFF (1 << 6)
#define RMI_DEVICE_F01_QRY1_HAS_PROPS_2 (1 << 7)
#define RMI_DEVICE_F01_LTS_RESERVED_SIZE 19
#define RMI_DEVICE_F01_QRY42_DS4_QUERIES (1 << 0)
#define RMI_DEVICE_F01_QRY42_MULTI_PHYS (1 << 1)
#define RMI_DEVICE_F01_QRY43_01_PACKAGE_ID (1 << 0)
#define RMI_DEVICE_F01_QRY43_01_BUILD_ID (1 << 1)
#define PACKAGE_ID_BYTES 4
#define BUILD_ID_BYTES 3
#define RMI_F01_CMD_DEVICE_RESET 1
#define RMI_F01_DEFAULT_RESET_DELAY_MS 100
int RMIDevice::SetRMIPage(unsigned char page)
{
int rc;
if (m_page == page)
return 0;
m_page = page;
rc = Write(RMI_DEVICE_PAGE_SELECT_REGISTER, &page, 1);
if (rc < 0) {
m_page = -1;
return rc;
}
return 0;
}
int RMIDevice::QueryBasicProperties()
{
int rc;
unsigned char basicQuery[RMI_DEVICE_F01_BASIC_QUERY_LEN];
unsigned short queryAddr;
unsigned char infoBuf[4];
unsigned short prodInfoAddr;
RMIFunction f01;
SetRMIPage(0x00);
if (GetFunction(f01, 1)) {
queryAddr = f01.GetQueryBase();
rc = Read(queryAddr, basicQuery, RMI_DEVICE_F01_BASIC_QUERY_LEN);
if (rc < 0) {
fprintf(stderr, "Failed to read the basic query: %s\n", strerror(errno));
return rc;
}
m_manufacturerID = basicQuery[0];
m_hasLTS = basicQuery[1] & RMI_DEVICE_F01_QRY1_HAS_LTS;
m_hasSensorID = basicQuery[1] & RMI_DEVICE_F01_QRY1_HAS_SENSOR_ID;
m_hasAdjustableDoze = basicQuery[1] & RMI_DEVICE_F01_QRY1_HAS_ADJ_DOZE;
m_hasAdjustableDozeHoldoff = basicQuery[1] & RMI_DEVICE_F01_QRY1_HAS_ADJ_DOZE_HOFF;
m_hasQuery42 = basicQuery[1] & RMI_DEVICE_F01_QRY1_HAS_PROPS_2;
m_firmwareVersionMajor = basicQuery[2];
m_firmwareVersionMinor = basicQuery[3];
snprintf(m_dom, sizeof(m_dom), "20%02d/%02d/%02d",
basicQuery[5] & RMI_DEVICE_F01_QRY5_YEAR_MASK,
basicQuery[6] & RMI_DEVICE_F01_QRY6_MONTH_MASK,
basicQuery[7] & RMI_DEVICE_F01_QRY7_DAY_MASK);
queryAddr += 11;
rc = Read(queryAddr, m_productID, RMI_PRODUCT_ID_LENGTH);
if (rc < 0) {
fprintf(stderr, "Failed to read the product id: %s\n", strerror(errno));
return rc;
}
m_productID[RMI_PRODUCT_ID_LENGTH] = '\0';
prodInfoAddr = queryAddr + 6;
queryAddr += 10;
if (m_hasLTS)
++queryAddr;
if (m_hasSensorID) {
rc = Read(queryAddr++, &m_sensorID, 1);
if (rc < 0) {
fprintf(stderr, "Failed to read sensor id: %s\n", strerror(errno));
return rc;
}
}
if (m_hasLTS)
queryAddr += RMI_DEVICE_F01_LTS_RESERVED_SIZE;
if (m_hasQuery42) {
rc = Read(queryAddr++, infoBuf, 1);
if (rc < 0) {
fprintf(stderr, "Failed to read query 42: %s\n", strerror(errno));
return rc;
}
m_hasDS4Queries = infoBuf[0] & RMI_DEVICE_F01_QRY42_DS4_QUERIES;
m_hasMultiPhysical = infoBuf[0] & RMI_DEVICE_F01_QRY42_MULTI_PHYS;
}
if (m_hasDS4Queries) {
rc = Read(queryAddr++, &m_ds4QueryLength, 1);
if (rc < 0) {
fprintf(stderr, "Failed to read DS4 query length: %s\n", strerror(errno));
return rc;
}
}
for (int i = 1; i <= m_ds4QueryLength; ++i) {
unsigned char val;
rc = Read(queryAddr++, &val, 1);
if (rc < 0) {
fprintf(stderr, "Failed to read F01 Query43.%02d: %s\n", i, strerror(errno));
continue;
}
switch(i) {
case 1:
m_hasPackageIDQuery = val & RMI_DEVICE_F01_QRY43_01_PACKAGE_ID;
m_hasBuildIDQuery = val & RMI_DEVICE_F01_QRY43_01_BUILD_ID;
break;
case 2:
case 3:
default:
break;
}
}
if (m_hasPackageIDQuery) {
rc = Read(prodInfoAddr++, infoBuf, PACKAGE_ID_BYTES);
if (rc > 0) {
unsigned short *val = (unsigned short *)infoBuf;
m_packageID = *val;
val = (unsigned short *)(infoBuf + 2);
m_packageRev = *val;
}
}
if (m_hasBuildIDQuery) {
rc = Read(prodInfoAddr, infoBuf, BUILD_ID_BYTES);
if (rc > 0) {
unsigned short *val = (unsigned short *)infoBuf;
m_buildID = *val;
m_buildID += infoBuf[2] * 65536;
}
}
}
return 0;
}
void RMIDevice::PrintProperties()
{
fprintf(stdout, "manufacturerID:\t\t%d\n", m_manufacturerID);
fprintf(stdout, "Has LTS?:\t\t%d\n", m_hasLTS);
fprintf(stdout, "Has Sensor ID?:\t\t%d\n", m_hasSensorID);
fprintf(stdout, "Has Adjustable Doze?:\t%d\n", m_hasAdjustableDoze);
fprintf(stdout, "Has Query 42?:\t\t%d\n", m_hasQuery42);
fprintf(stdout, "Date of Manufacturer:\t%s\n", m_dom);
fprintf(stdout, "Product ID:\t\t%s\n", m_productID);
fprintf(stdout, "Firmware Version:\t%d.%d\n", m_firmwareVersionMajor, m_firmwareVersionMinor);
fprintf(stdout, "Package ID:\t\t%d\n", m_packageID);
fprintf(stdout, "Package Rev:\t\t%d\n", m_packageRev);
fprintf(stdout, "Build ID:\t\t%ld\n", m_buildID);
fprintf(stdout, "Sensor ID:\t\t%d\n", m_sensorID);
fprintf(stdout, "Has DS4 Queries?:\t%d\n", m_hasDS4Queries);
fprintf(stdout, "Has Multi Phys?:\t%d\n", m_hasMultiPhysical);
fprintf(stdout, "\n");
}
int RMIDevice::Reset()
{
int rc;
RMIFunction f01;
const unsigned char deviceReset = RMI_F01_CMD_DEVICE_RESET;
if (!GetFunction(f01, 1))
return -1;
fprintf(stdout, "Resetting...\n");
rc = Write(f01.GetCommandBase(), &deviceReset, 1);
if (rc < 0)
return rc;
rc = Sleep(RMI_F01_DEFAULT_RESET_DELAY_MS);
if (rc < 0)
return -1;
fprintf(stdout, "Reset completed.\n");
return 0;
}
bool RMIDevice::GetFunction(RMIFunction &func, int functionNumber)
{
std::vector<RMIFunction>::iterator funcIter;
for (funcIter = m_functionList.begin(); funcIter != m_functionList.end(); ++funcIter) {
if (funcIter->GetFunctionNumber() == functionNumber) {
func = *funcIter;
return true;
}
}
return false;
}
void RMIDevice::PrintFunctions()
{
std::vector<RMIFunction>::iterator funcIter;
for (funcIter = m_functionList.begin(); funcIter != m_functionList.end(); ++funcIter)
fprintf(stdout, "0x%02x (%d) (%d) (0x%x): 0x%02x 0x%02x 0x%02x 0x%02x\n",
funcIter->GetFunctionNumber(), funcIter->GetFunctionVersion(),
funcIter->GetInterruptSourceCount(),
funcIter->GetInterruptMask(),
funcIter->GetDataBase(),
funcIter->GetControlBase(), funcIter->GetCommandBase(),
funcIter->GetQueryBase());
}
int RMIDevice::ScanPDT(int endFunc, int endPage)
{
int rc;
unsigned int page;
unsigned int maxPage;
unsigned int addr;
unsigned char entry[RMI_DEVICE_PDT_ENTRY_SIZE];
unsigned int interruptCount = 0;
maxPage = (unsigned int)((endPage < 0) ? RMI_DEVICE_MAX_PAGE : endPage);
m_functionList.clear();
for (page = 0; page < maxPage; ++page) {
unsigned int page_start = RMI_DEVICE_PAGE_SIZE * page;
unsigned int pdt_start = page_start + RMI_DEVICE_PAGE_SCAN_START;
unsigned int pdt_end = page_start + RMI_DEVICE_PAGE_SCAN_END;
bool found = false;
SetRMIPage(page);
for (addr = pdt_start; addr >= pdt_end; addr -= RMI_DEVICE_PDT_ENTRY_SIZE) {
rc = Read(addr, entry, RMI_DEVICE_PDT_ENTRY_SIZE);
if (rc < 0) {
fprintf(stderr, "Failed to read PDT entry at address (0x%04x)\n", addr);
return rc;
}
RMIFunction func(entry, page_start, interruptCount);
if (func.GetFunctionNumber() == 0)
break;
m_functionList.push_back(func);
interruptCount += func.GetInterruptSourceCount();
found = true;
if (func.GetFunctionNumber() == endFunc)
return 0;
}
if (!found && (endPage < 0))
break;
}
m_numInterruptRegs = (interruptCount + 7) / 8;
return 0;
}
bool RMIDevice::InBootloader()
{
RMIFunction f01;
if (GetFunction(f01, 0x01)) {
int rc;
unsigned char status;
rc = Read(f01.GetDataBase(), &status, 1);
if (rc < 0)
return true;
return !!(status & 0x40);
}
return true;
}
long long diff_time(struct timespec *start, struct timespec *end)
{
long long diff;
diff = (end->tv_sec - start->tv_sec) * 1000 * 1000;
diff += (end->tv_nsec - start->tv_nsec) / 1000;
return diff;
}
int Sleep(int ms)
{
struct timespec ts;
struct timespec rem;
ts.tv_sec = ms / 1000;
ts.tv_nsec = (ms % 1000) * 1000 * 1000;
for (;;) {
if (nanosleep(&ts, &rem) == 0) {
break;
} else {
if (errno == EINTR) {
ts = rem;
continue;
}
return -1;
}
}
return 0;
}
void print_buffer(const unsigned char *buf, unsigned int len)
{
for (unsigned int i = 0; i < len; ++i) {
fprintf(stdout, "0x%02X ", buf[i]);
if (i % 8 == 7)
fprintf(stdout, "\n");
}
fprintf(stdout, "\n");
}
|
/*
* Copyright (C) 2014 Andrew Duggan
* Copyright (C) 2014 Synaptics 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 <stdio.h>
#include <time.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include "rmidevice.h"
#define RMI_DEVICE_PDT_ENTRY_SIZE 6
#define RMI_DEVICE_PAGE_SELECT_REGISTER 0xFF
#define RMI_DEVICE_MAX_PAGE 0xFF
#define RMI_DEVICE_PAGE_SIZE 0x100
#define RMI_DEVICE_PAGE_SCAN_START 0x00e9
#define RMI_DEVICE_PAGE_SCAN_END 0x0005
#define RMI_DEVICE_F01_BASIC_QUERY_LEN 11
#define RMI_DEVICE_F01_QRY5_YEAR_MASK 0x1f
#define RMI_DEVICE_F01_QRY6_MONTH_MASK 0x0f
#define RMI_DEVICE_F01_QRY7_DAY_MASK 0x1f
#define RMI_DEVICE_F01_QRY1_HAS_LTS (1 << 2)
#define RMI_DEVICE_F01_QRY1_HAS_SENSOR_ID (1 << 3)
#define RMI_DEVICE_F01_QRY1_HAS_CHARGER_INP (1 << 4)
#define RMI_DEVICE_F01_QRY1_HAS_ADJ_DOZE (1 << 5)
#define RMI_DEVICE_F01_QRY1_HAS_ADJ_DOZE_HOFF (1 << 6)
#define RMI_DEVICE_F01_QRY1_HAS_PROPS_2 (1 << 7)
#define RMI_DEVICE_F01_LTS_RESERVED_SIZE 19
#define RMI_DEVICE_F01_QRY42_DS4_QUERIES (1 << 0)
#define RMI_DEVICE_F01_QRY42_MULTI_PHYS (1 << 1)
#define RMI_DEVICE_F01_QRY43_01_PACKAGE_ID (1 << 0)
#define RMI_DEVICE_F01_QRY43_01_BUILD_ID (1 << 1)
#define PACKAGE_ID_BYTES 4
#define BUILD_ID_BYTES 3
#define RMI_F01_CMD_DEVICE_RESET 1
#define RMI_F01_DEFAULT_RESET_DELAY_MS 100
int RMIDevice::SetRMIPage(unsigned char page)
{
int rc;
if (m_page == page)
return 0;
m_page = page;
rc = Write(RMI_DEVICE_PAGE_SELECT_REGISTER, &page, 1);
if (rc < 0 || rc < 1) {
m_page = -1;
return rc;
}
return 0;
}
int RMIDevice::QueryBasicProperties()
{
int rc;
unsigned char basicQuery[RMI_DEVICE_F01_BASIC_QUERY_LEN];
unsigned short queryAddr;
unsigned char infoBuf[4];
unsigned short prodInfoAddr;
RMIFunction f01;
SetRMIPage(0x00);
if (GetFunction(f01, 1)) {
queryAddr = f01.GetQueryBase();
rc = Read(queryAddr, basicQuery, RMI_DEVICE_F01_BASIC_QUERY_LEN);
if (rc < 0 || rc < RMI_DEVICE_F01_BASIC_QUERY_LEN) {
fprintf(stderr, "Failed to read the basic query: %s\n", strerror(errno));
return rc;
}
m_manufacturerID = basicQuery[0];
m_hasLTS = basicQuery[1] & RMI_DEVICE_F01_QRY1_HAS_LTS;
m_hasSensorID = basicQuery[1] & RMI_DEVICE_F01_QRY1_HAS_SENSOR_ID;
m_hasAdjustableDoze = basicQuery[1] & RMI_DEVICE_F01_QRY1_HAS_ADJ_DOZE;
m_hasAdjustableDozeHoldoff = basicQuery[1] & RMI_DEVICE_F01_QRY1_HAS_ADJ_DOZE_HOFF;
m_hasQuery42 = basicQuery[1] & RMI_DEVICE_F01_QRY1_HAS_PROPS_2;
m_firmwareVersionMajor = basicQuery[2];
m_firmwareVersionMinor = basicQuery[3];
snprintf(m_dom, sizeof(m_dom), "20%02d/%02d/%02d",
basicQuery[5] & RMI_DEVICE_F01_QRY5_YEAR_MASK,
basicQuery[6] & RMI_DEVICE_F01_QRY6_MONTH_MASK,
basicQuery[7] & RMI_DEVICE_F01_QRY7_DAY_MASK);
queryAddr += 11;
rc = Read(queryAddr, m_productID, RMI_PRODUCT_ID_LENGTH);
if (rc < 0 || rc < RMI_PRODUCT_ID_LENGTH) {
fprintf(stderr, "Failed to read the product id: %s\n", strerror(errno));
return rc;
}
m_productID[RMI_PRODUCT_ID_LENGTH] = '\0';
prodInfoAddr = queryAddr + 6;
queryAddr += 10;
if (m_hasLTS)
++queryAddr;
if (m_hasSensorID) {
rc = Read(queryAddr++, &m_sensorID, 1);
if (rc < 0 || rc < 1) {
fprintf(stderr, "Failed to read sensor id: %s\n", strerror(errno));
return rc;
}
}
if (m_hasLTS)
queryAddr += RMI_DEVICE_F01_LTS_RESERVED_SIZE;
if (m_hasQuery42) {
rc = Read(queryAddr++, infoBuf, 1);
if (rc < 0 || rc < 1) {
fprintf(stderr, "Failed to read query 42: %s\n", strerror(errno));
return rc;
}
m_hasDS4Queries = infoBuf[0] & RMI_DEVICE_F01_QRY42_DS4_QUERIES;
m_hasMultiPhysical = infoBuf[0] & RMI_DEVICE_F01_QRY42_MULTI_PHYS;
}
if (m_hasDS4Queries) {
rc = Read(queryAddr++, &m_ds4QueryLength, 1);
if (rc < 0 || rc < 1) {
fprintf(stderr, "Failed to read DS4 query length: %s\n", strerror(errno));
return rc;
}
}
for (int i = 1; i <= m_ds4QueryLength; ++i) {
unsigned char val;
rc = Read(queryAddr++, &val, 1);
if (rc < 0 || rc < 1) {
fprintf(stderr, "Failed to read F01 Query43.%02d: %s\n", i, strerror(errno));
continue;
}
switch(i) {
case 1:
m_hasPackageIDQuery = val & RMI_DEVICE_F01_QRY43_01_PACKAGE_ID;
m_hasBuildIDQuery = val & RMI_DEVICE_F01_QRY43_01_BUILD_ID;
break;
case 2:
case 3:
default:
break;
}
}
if (m_hasPackageIDQuery) {
rc = Read(prodInfoAddr++, infoBuf, PACKAGE_ID_BYTES);
if (rc >= PACKAGE_ID_BYTES) {
unsigned short *val = (unsigned short *)infoBuf;
m_packageID = *val;
val = (unsigned short *)(infoBuf + 2);
m_packageRev = *val;
}
}
if (m_hasBuildIDQuery) {
rc = Read(prodInfoAddr, infoBuf, BUILD_ID_BYTES);
if (rc >= BUILD_ID_BYTES) {
unsigned short *val = (unsigned short *)infoBuf;
m_buildID = *val;
m_buildID += infoBuf[2] * 65536;
}
}
}
return 0;
}
void RMIDevice::PrintProperties()
{
fprintf(stdout, "manufacturerID:\t\t%d\n", m_manufacturerID);
fprintf(stdout, "Has LTS?:\t\t%d\n", m_hasLTS);
fprintf(stdout, "Has Sensor ID?:\t\t%d\n", m_hasSensorID);
fprintf(stdout, "Has Adjustable Doze?:\t%d\n", m_hasAdjustableDoze);
fprintf(stdout, "Has Query 42?:\t\t%d\n", m_hasQuery42);
fprintf(stdout, "Date of Manufacturer:\t%s\n", m_dom);
fprintf(stdout, "Product ID:\t\t%s\n", m_productID);
fprintf(stdout, "Firmware Version:\t%d.%d\n", m_firmwareVersionMajor, m_firmwareVersionMinor);
fprintf(stdout, "Package ID:\t\t%d\n", m_packageID);
fprintf(stdout, "Package Rev:\t\t%d\n", m_packageRev);
fprintf(stdout, "Build ID:\t\t%ld\n", m_buildID);
fprintf(stdout, "Sensor ID:\t\t%d\n", m_sensorID);
fprintf(stdout, "Has DS4 Queries?:\t%d\n", m_hasDS4Queries);
fprintf(stdout, "Has Multi Phys?:\t%d\n", m_hasMultiPhysical);
fprintf(stdout, "\n");
}
int RMIDevice::Reset()
{
int rc;
RMIFunction f01;
const unsigned char deviceReset = RMI_F01_CMD_DEVICE_RESET;
if (!GetFunction(f01, 1))
return -1;
fprintf(stdout, "Resetting...\n");
rc = Write(f01.GetCommandBase(), &deviceReset, 1);
if (rc < 0 || rc < 1)
return rc;
rc = Sleep(RMI_F01_DEFAULT_RESET_DELAY_MS);
if (rc < 0)
return -1;
fprintf(stdout, "Reset completed.\n");
return 0;
}
bool RMIDevice::GetFunction(RMIFunction &func, int functionNumber)
{
std::vector<RMIFunction>::iterator funcIter;
for (funcIter = m_functionList.begin(); funcIter != m_functionList.end(); ++funcIter) {
if (funcIter->GetFunctionNumber() == functionNumber) {
func = *funcIter;
return true;
}
}
return false;
}
void RMIDevice::PrintFunctions()
{
std::vector<RMIFunction>::iterator funcIter;
for (funcIter = m_functionList.begin(); funcIter != m_functionList.end(); ++funcIter)
fprintf(stdout, "0x%02x (%d) (%d) (0x%x): 0x%02x 0x%02x 0x%02x 0x%02x\n",
funcIter->GetFunctionNumber(), funcIter->GetFunctionVersion(),
funcIter->GetInterruptSourceCount(),
funcIter->GetInterruptMask(),
funcIter->GetDataBase(),
funcIter->GetControlBase(), funcIter->GetCommandBase(),
funcIter->GetQueryBase());
}
int RMIDevice::ScanPDT(int endFunc, int endPage)
{
int rc;
unsigned int page;
unsigned int maxPage;
unsigned int addr;
unsigned char entry[RMI_DEVICE_PDT_ENTRY_SIZE];
unsigned int interruptCount = 0;
maxPage = (unsigned int)((endPage < 0) ? RMI_DEVICE_MAX_PAGE : endPage);
m_functionList.clear();
for (page = 0; page < maxPage; ++page) {
unsigned int page_start = RMI_DEVICE_PAGE_SIZE * page;
unsigned int pdt_start = page_start + RMI_DEVICE_PAGE_SCAN_START;
unsigned int pdt_end = page_start + RMI_DEVICE_PAGE_SCAN_END;
bool found = false;
SetRMIPage(page);
for (addr = pdt_start; addr >= pdt_end; addr -= RMI_DEVICE_PDT_ENTRY_SIZE) {
rc = Read(addr, entry, RMI_DEVICE_PDT_ENTRY_SIZE);
if (rc < 0 || rc < RMI_DEVICE_PDT_ENTRY_SIZE) {
fprintf(stderr, "Failed to read PDT entry at address (0x%04x)\n", addr);
return rc;
}
RMIFunction func(entry, page_start, interruptCount);
if (func.GetFunctionNumber() == 0)
break;
m_functionList.push_back(func);
interruptCount += func.GetInterruptSourceCount();
found = true;
if (func.GetFunctionNumber() == endFunc)
return 0;
}
if (!found && (endPage < 0))
break;
}
m_numInterruptRegs = (interruptCount + 7) / 8;
return 0;
}
bool RMIDevice::InBootloader()
{
RMIFunction f01;
if (GetFunction(f01, 0x01)) {
int rc;
unsigned char status;
rc = Read(f01.GetDataBase(), &status, 1);
if (rc < 0 || rc < 1)
return true;
return !!(status & 0x40);
}
return true;
}
long long diff_time(struct timespec *start, struct timespec *end)
{
long long diff;
diff = (end->tv_sec - start->tv_sec) * 1000 * 1000;
diff += (end->tv_nsec - start->tv_nsec) / 1000;
return diff;
}
int Sleep(int ms)
{
struct timespec ts;
struct timespec rem;
ts.tv_sec = ms / 1000;
ts.tv_nsec = (ms % 1000) * 1000 * 1000;
for (;;) {
if (nanosleep(&ts, &rem) == 0) {
break;
} else {
if (errno == EINTR) {
ts = rem;
continue;
}
return -1;
}
}
return 0;
}
void print_buffer(const unsigned char *buf, unsigned int len)
{
for (unsigned int i = 0; i < len; ++i) {
fprintf(stdout, "0x%02X ", buf[i]);
if (i % 8 == 7)
fprintf(stdout, "\n");
}
fprintf(stdout, "\n");
}
|
Check return value of Read(), Write()
|
rmidevice: Check return value of Read(), Write()
Addresses security concern:
All users of Read and Write fail to check for return value being equal
to desired write size (only look for <0, not a size >= 0 but less than
expected). This can lead to all kinds of corruption or overflows.
|
C++
|
apache-2.0
|
aduggan/rmi4utils,aduggan/rmi4utils
|
12d072a4a933a33350fb73dbb6fe99c7e8aab98c
|
src/prioritydb.cpp
|
src/prioritydb.cpp
|
#include "prioritydb.h"
#include <functional>
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
#include <sqlite3.h>
class PriorityDB::Impl {
public:
Impl(const unsigned long long& max_size, const std::string& path)
: max_size_{max_size}, table_path_{path}, table_name_{"prism_data"} {
if (max_size_ == 0LL) {
throw PriorityDBException{"Must specify a nonzero max_size"};
}
if (!check_table_()) {
create_table_();
}
}
void Insert(const unsigned long long& priority, const std::string& hash,
const unsigned long long& size, const bool& on_disk);
void Delete(const std::string& hash);
void Update(const std::string& hash, const bool& on_disk);
std::string GetHighestHash(bool& on_disk);
std::string GetLowestMemoryHash();
std::string GetLowestDiskHash();
bool Full();
private:
typedef std::map<std::string, std::string> Record;
std::unique_ptr<sqlite3, std::function<int(sqlite3*)>> open_db_();
bool check_table_();
void create_table_();
std::vector<Record> execute_(const std::string& sql);
static int callback_(void* response_ptr, int num_values, char** values, char** names);
std::string table_path_;
std::string table_name_;
unsigned long long max_size_;
};
void PriorityDB::Impl::Insert(const unsigned long long& priority, const std::string& hash,
const unsigned long long& size, const bool& on_disk) {
if (hash.empty()) {
return;
}
std::stringstream stream;
stream << "INSERT INTO "
<< table_name_
<< "(priority, hash, size, on_disk)"
<< "VALUES"
<< "("
<< priority << ","
<< "'" << hash << "',"
<< size << ","
<< on_disk
<< ");";
execute_(stream.str());
}
void PriorityDB::Impl::Delete(const std::string& hash) {
if (hash.empty()) {
return;
}
std::stringstream stream;
stream << "DELETE FROM "
<< table_name_
<< " WHERE hash='"
<< hash
<< "';";
execute_(stream.str());
}
void PriorityDB::Impl::Update(const std::string& hash, const bool& on_disk) {
if (hash.empty()) {
return;
}
std::stringstream stream;
stream << "UPDATE "
<< table_name_
<< " SET on_disk="
<< on_disk
<< " WHERE hash='"
<< hash
<< "';";
execute_(stream.str());
}
std::string PriorityDB::Impl::GetHighestHash(bool& on_disk) {
std::stringstream stream;
stream << "SELECT hash, on_disk FROM "
<< table_name_
<< " ORDER BY priority DESC, on_disk ASC LIMIT 1;";
auto response = execute_(stream.str());
std::string hash;
if (!response.empty()) {
auto record = response[0];
if (!record.empty()) {
hash = record["hash"];
on_disk = std::stoi(record["on_disk"]);
}
}
return hash;
}
std::string PriorityDB::Impl::GetLowestMemoryHash() {
std::stringstream stream;
stream << "SELECT hash FROM "
<< table_name_
<< " WHERE on_disk="
<< false
<< " ORDER BY priority ASC LIMIT 1;";
auto response = execute_(stream.str());
std::string hash;
if (!response.empty()) {
auto record = response[0];
if (!record.empty()) {
hash = record["hash"];
}
}
return hash;
}
std::string PriorityDB::Impl::GetLowestDiskHash() {
std::stringstream stream;
stream << "SELECT hash FROM "
<< table_name_
<< " WHERE on_disk="
<< true
<< " ORDER BY priority ASC LIMIT 1;";
auto response = execute_(stream.str());
std::string hash;
if (!response.empty()) {
auto record = response[0];
if (!record.empty()) {
hash = record["hash"];
}
}
return hash;
}
bool PriorityDB::Impl::Full() {
std::stringstream stream;
stream << "SELECT SUM(size) FROM "
<< table_name_
<< " WHERE on_disk="
<< true
<< ";";
auto response = execute_(stream.str());
unsigned long long total = 0;
if (!response.empty()) {
auto record = response[0];
if (!record.empty()) {
total = std::stoi(record["SUM(size)"]);
}
}
return total > max_size_;
}
std::unique_ptr<sqlite3, std::function<int(sqlite3*)>> PriorityDB::Impl::open_db_() {
sqlite3* sqlite_db;
if (sqlite3_open(table_path_.data(), &sqlite_db) != SQLITE_OK) {
throw PriorityDBException{sqlite3_errmsg(sqlite_db)};
}
return std::unique_ptr<sqlite3, std::function<int(sqlite3*)>>(sqlite_db, sqlite3_close);
}
bool PriorityDB::Impl::check_table_() {
std::stringstream stream;
stream << "SELECT name FROM sqlite_master WHERE type='table' AND name='"
<< table_name_
<< "';";
auto response = execute_(stream.str());
return !response.empty();
}
void PriorityDB::Impl::create_table_() {
std::stringstream stream;
stream << "CREATE TABLE "
<< table_name_
<< "("
<< "id INTEGER PRIMARY KEY AUTOINCREMENT,"
<< "priority UNSIGNED BIGINT NOT NULL,"
<< "hash TEXT NOT NULL,"
<< "size UNSIGNED BIGINT NOT NULL,"
<< "on_disk BOOL NOT NULL"
<< ");";
execute_(stream.str());
}
std::vector<PriorityDB::Impl::Record> PriorityDB::Impl::execute_(const std::string& sql) {
std::vector<Record> response;
auto db = open_db_();
char* error;
int rc = sqlite3_exec(db.get(), sql.data(), &PriorityDB::Impl::callback_, &response, &error);
if (rc != SQLITE_OK) {
auto error_string = std::string{error};
sqlite3_free(error);
throw PriorityDBException{error_string};
}
return response;
}
int PriorityDB::Impl::callback_(void* response_ptr, int num_values, char** values, char** names) {
auto response = (std::vector<Record>*) response_ptr;
auto record = Record();
for (int i = 0; i < num_values; ++i) {
if (values[i]) {
record[names[i]] = values[i];
}
}
response->push_back(record);
return 0;
}
// Bridge
PriorityDB::PriorityDB(const unsigned long long& max_size, const std::string& path)
: pimpl_{ new Impl{max_size, path} } {}
PriorityDB::~PriorityDB() {}
void PriorityDB::Insert(const unsigned long long& priority, const std::string& hash,
const unsigned long long& size, const bool& on_disk) {
pimpl_->Insert(priority, hash, size, on_disk);
}
void PriorityDB::Delete(const std::string& hash) {
pimpl_->Delete(hash);
}
void PriorityDB::Update(const std::string& hash, const bool& on_disk) {
pimpl_->Update(hash, on_disk);
}
std::string PriorityDB::GetHighestHash(bool& on_disk) {
return pimpl_->GetHighestHash(on_disk);
}
std::string PriorityDB::GetLowestMemoryHash() {
return pimpl_->GetLowestMemoryHash();
}
std::string PriorityDB::GetLowestDiskHash() {
return pimpl_->GetLowestDiskHash();
}
bool PriorityDB::Full() {
return pimpl_->Full();
}
|
#include "prioritydb.h"
#include <functional>
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
#include <sqlite3.h>
class PriorityDB::Impl {
public:
Impl(const unsigned long long& max_size, const std::string& path)
: max_size_{max_size}, table_path_{path}, table_name_{"prism_data"} {
if (max_size_ == 0LL) {
throw PriorityDBException{"Must specify a nonzero max_size"};
}
if (!check_table_()) {
create_table_();
}
delete_memory_messages_();
}
void Insert(const unsigned long long& priority, const std::string& hash,
const unsigned long long& size, const bool& on_disk);
void Delete(const std::string& hash);
void Update(const std::string& hash, const bool& on_disk);
std::string GetHighestHash(bool& on_disk);
std::string GetLowestMemoryHash();
std::string GetLowestDiskHash();
bool Full();
private:
typedef std::map<std::string, std::string> Record;
std::unique_ptr<sqlite3, std::function<int(sqlite3*)>> open_db_();
bool check_table_();
void create_table_();
void delete_memory_messages_();
std::vector<Record> execute_(const std::string& sql);
static int callback_(void* response_ptr, int num_values, char** values, char** names);
std::string table_path_;
std::string table_name_;
unsigned long long max_size_;
};
void PriorityDB::Impl::Insert(const unsigned long long& priority, const std::string& hash,
const unsigned long long& size, const bool& on_disk) {
if (hash.empty()) {
return;
}
std::stringstream stream;
stream << "INSERT INTO "
<< table_name_
<< "(priority, hash, size, on_disk)"
<< "VALUES"
<< "("
<< priority << ","
<< "'" << hash << "',"
<< size << ","
<< on_disk
<< ");";
execute_(stream.str());
}
void PriorityDB::Impl::Delete(const std::string& hash) {
if (hash.empty()) {
return;
}
std::stringstream stream;
stream << "DELETE FROM "
<< table_name_
<< " WHERE hash='"
<< hash
<< "';";
execute_(stream.str());
}
void PriorityDB::Impl::Update(const std::string& hash, const bool& on_disk) {
if (hash.empty()) {
return;
}
std::stringstream stream;
stream << "UPDATE "
<< table_name_
<< " SET on_disk="
<< on_disk
<< " WHERE hash='"
<< hash
<< "';";
execute_(stream.str());
}
std::string PriorityDB::Impl::GetHighestHash(bool& on_disk) {
std::stringstream stream;
stream << "SELECT hash, on_disk FROM "
<< table_name_
<< " ORDER BY priority DESC, on_disk ASC LIMIT 1;";
auto response = execute_(stream.str());
std::string hash;
if (!response.empty()) {
auto record = response[0];
if (!record.empty()) {
hash = record["hash"];
on_disk = std::stoi(record["on_disk"]);
}
}
return hash;
}
std::string PriorityDB::Impl::GetLowestMemoryHash() {
std::stringstream stream;
stream << "SELECT hash FROM "
<< table_name_
<< " WHERE on_disk="
<< false
<< " ORDER BY priority ASC LIMIT 1;";
auto response = execute_(stream.str());
std::string hash;
if (!response.empty()) {
auto record = response[0];
if (!record.empty()) {
hash = record["hash"];
}
}
return hash;
}
std::string PriorityDB::Impl::GetLowestDiskHash() {
std::stringstream stream;
stream << "SELECT hash FROM "
<< table_name_
<< " WHERE on_disk="
<< true
<< " ORDER BY priority ASC LIMIT 1;";
auto response = execute_(stream.str());
std::string hash;
if (!response.empty()) {
auto record = response[0];
if (!record.empty()) {
hash = record["hash"];
}
}
return hash;
}
bool PriorityDB::Impl::Full() {
std::stringstream stream;
stream << "SELECT SUM(size) FROM "
<< table_name_
<< " WHERE on_disk="
<< true
<< ";";
auto response = execute_(stream.str());
unsigned long long total = 0;
if (!response.empty()) {
auto record = response[0];
if (!record.empty()) {
total = std::stoi(record["SUM(size)"]);
}
}
return total > max_size_;
}
std::unique_ptr<sqlite3, std::function<int(sqlite3*)>> PriorityDB::Impl::open_db_() {
sqlite3* sqlite_db;
if (sqlite3_open(table_path_.data(), &sqlite_db) != SQLITE_OK) {
throw PriorityDBException{sqlite3_errmsg(sqlite_db)};
}
return std::unique_ptr<sqlite3, std::function<int(sqlite3*)>>(sqlite_db, sqlite3_close);
}
bool PriorityDB::Impl::check_table_() {
std::stringstream stream;
stream << "SELECT name FROM sqlite_master WHERE type='table' AND name='"
<< table_name_
<< "';";
auto response = execute_(stream.str());
return !response.empty();
}
void PriorityDB::Impl::create_table_() {
std::stringstream stream;
stream << "CREATE TABLE "
<< table_name_
<< "("
<< "id INTEGER PRIMARY KEY AUTOINCREMENT,"
<< "priority UNSIGNED BIGINT NOT NULL,"
<< "hash TEXT NOT NULL,"
<< "size UNSIGNED BIGINT NOT NULL,"
<< "on_disk BOOL NOT NULL"
<< ");";
execute_(stream.str());
}
void PriorityDB::Impl::delete_memory_messages_() {
std::stringstream stream;
stream << "DELETE FROM "
<< table_name_
<< " WHERE on_disk='"
<< false
<< "';";
execute_(stream.str());
}
std::vector<PriorityDB::Impl::Record> PriorityDB::Impl::execute_(const std::string& sql) {
std::vector<Record> response;
auto db = open_db_();
char* error;
int rc = sqlite3_exec(db.get(), sql.data(), &PriorityDB::Impl::callback_, &response, &error);
if (rc != SQLITE_OK) {
auto error_string = std::string{error};
sqlite3_free(error);
throw PriorityDBException{error_string};
}
return response;
}
int PriorityDB::Impl::callback_(void* response_ptr, int num_values, char** values, char** names) {
auto response = (std::vector<Record>*) response_ptr;
auto record = Record();
for (int i = 0; i < num_values; ++i) {
if (values[i]) {
record[names[i]] = values[i];
}
}
response->push_back(record);
return 0;
}
// Bridge
PriorityDB::PriorityDB(const unsigned long long& max_size, const std::string& path)
: pimpl_{ new Impl{max_size, path} } {}
PriorityDB::~PriorityDB() {}
void PriorityDB::Insert(const unsigned long long& priority, const std::string& hash,
const unsigned long long& size, const bool& on_disk) {
pimpl_->Insert(priority, hash, size, on_disk);
}
void PriorityDB::Delete(const std::string& hash) {
pimpl_->Delete(hash);
}
void PriorityDB::Update(const std::string& hash, const bool& on_disk) {
pimpl_->Update(hash, on_disk);
}
std::string PriorityDB::GetHighestHash(bool& on_disk) {
return pimpl_->GetHighestHash(on_disk);
}
std::string PriorityDB::GetLowestMemoryHash() {
return pimpl_->GetLowestMemoryHash();
}
std::string PriorityDB::GetLowestDiskHash() {
return pimpl_->GetLowestDiskHash();
}
bool PriorityDB::Full() {
return pimpl_->Full();
}
|
Clear out in-memory messages in the db in case of a dirty exit
|
Clear out in-memory messages in the db in case of a dirty exit
|
C++
|
mit
|
prismskylabs/PriorityBuffer
|
da22738ba1dbb33db3f6eb0f5fbc01d759f12ef6
|
formats/ico.cpp
|
formats/ico.cpp
|
#include "ico.h"
#include <algorithm>
#include <iostream>
#include <vector>
#include "../lib/zopflipng/lodepng/lodepng.h"
#include "bmp.h"
#include "png.h"
using std::cout;
using std::cerr;
using std::endl;
using std::vector;
const uint8_t Ico::header_magic[] = { 0x00, 0x00, 0x01, 0x00 };
namespace
{
struct IconDirEntry
{
uint8_t bWidth; // Width, in pixels, of the image
uint8_t bHeight; // Height, in pixels, of the image
uint8_t bColorCount; // Number of colors in image (0 if >=8bpp)
uint8_t bReserved; // Reserved ( must be 0)
uint16_t wPlanes; // Color Planes
uint16_t wBitCount; // Bits per pixel
uint32_t dwBytesInRes; // How many bytes in this resource?
uint32_t dwImageOffset; // Where in the file is this image?
};
} // namespace
size_t Ico::Leanify(size_t size_leanified /*= 0*/)
{
// number of images inside ico file
uint16_t num_of_img = *(uint16_t *)(fp_ + 4);
// size too small
if (6 + num_of_img * sizeof(IconDirEntry) >= size_)
{
return Format::Leanify(size_leanified);
}
// sort the entries by offset just in case it's not sorted before
IconDirEntry *entry_addr = reinterpret_cast<IconDirEntry *>(fp_ + 6);
vector<IconDirEntry> entries(entry_addr, entry_addr + num_of_img);
std::sort(entries.begin(), entries.end(), [] (const IconDirEntry& a, const IconDirEntry& b)
{
return a.dwImageOffset < b.dwImageOffset;
});
// check overlaps
for (size_t i = 1; i < entries.size(); i++)
{
if (entries[i - 1].dwImageOffset + entries[i - 1].dwBytesInRes > entries[i].dwImageOffset)
{
cerr << "Error: Found overlapping icon entries!" << endl;
return Format::Leanify(size_leanified);
}
}
// is file size enough?
if (entries.back().dwImageOffset + entries.back().dwBytesInRes > size_)
{
return Format::Leanify(size_leanified);
}
for (size_t i = 0; i < entries.size(); i++)
{
uint32_t old_offset = entries[i].dwImageOffset;
// write new offset
if (i != 0)
{
entries[i].dwImageOffset = entries[i - 1].dwImageOffset + entries[i - 1].dwBytesInRes;
}
else
{
entries[i].dwImageOffset = 6 + num_of_img * sizeof(IconDirEntry);
}
// Leanify PNG
if (memcmp(fp_ + old_offset, Png::header_magic, sizeof(Png::header_magic)) == 0)
{
entries[i].dwBytesInRes = Png(fp_ + old_offset, entries[i].dwBytesInRes).Leanify(size_leanified + old_offset - entries[i].dwImageOffset);
continue;
}
// Convert 256x256 BMP to PNG if possible
if (entries[i].bWidth == 0 && entries[i].bHeight == 0)
{
auto dib = reinterpret_cast<Bmp::BITMAPINFOHEADER*>(fp_ + old_offset);
if (dib->biSize >= 40 &&
dib->biWidth == 256 && dib->biHeight == 512 && // DIB in ICO always has double height
dib->biPlanes == 1 &&
dib->biBitCount == 32 && // only support RGBA for now
dib->biCompression == 0 && // BI_RGB aka no compression
dib->biSize + std::max(dib->biSizeImage, 256 * 256 * 4U) <= entries[i].dwBytesInRes &&
(dib->biSizeImage == 0 || dib->biSizeImage >= 256 * 256 * 4U) &&
dib->biClrUsed == 0)
{
if (is_verbose)
{
cout << "Converting 256x256 BMP to PNG..." << endl;
}
// BMP stores ARGB in little endian, so it's actually BGRA, convert it to normal RGBA
// It also stores the pixels upside down for some reason, so reverse it.
uint8_t *bmp_row = fp_ + old_offset + dib->biSize + 256 * 256 * 4;
vector<uint8_t> raw(256 * 256 * 4), png;
// TODO: detect 0RGB and convert it to RGBA using mask
for (size_t j = 0; j < 256; j++)
{
bmp_row -= 256 * 4;
for (size_t k = 0; k < 256; k++)
{
raw[(j * 256 + k) * 4 + 0] = bmp_row[k * 4 + 2];
raw[(j * 256 + k) * 4 + 1] = bmp_row[k * 4 + 1];
raw[(j * 256 + k) * 4 + 2] = bmp_row[k * 4 + 0];
raw[(j * 256 + k) * 4 + 3] = bmp_row[k * 4 + 3];
}
}
if (lodepng::encode(png, raw, 256, 256) == 0)
{
// Optimize the new PNG
size_t png_size = Png(png).Leanify();
if (png_size < entries[i].dwBytesInRes)
{
entries[i].dwBytesInRes = png_size;
memcpy(fp_ + entries[i].dwImageOffset - size_leanified, png.data(), png_size);
continue;
}
}
}
}
memmove(fp_ + entries[i].dwImageOffset - size_leanified, fp_ + old_offset, entries[i].dwBytesInRes);
}
fp_ -= size_leanified;
// write new entries
memcpy(fp_ + 6, entries.data(), entries.size() * sizeof(IconDirEntry));
// offset + size of last img
size_ = entries.back().dwImageOffset + entries.back().dwBytesInRes;
return size_;
}
|
#include "ico.h"
#include <algorithm>
#include <iostream>
#include <vector>
#include "../lib/zopflipng/lodepng/lodepng.h"
#include "bmp.h"
#include "png.h"
using std::cout;
using std::cerr;
using std::endl;
using std::vector;
const uint8_t Ico::header_magic[] = { 0x00, 0x00, 0x01, 0x00 };
namespace
{
struct IconDirEntry
{
uint8_t bWidth; // Width, in pixels, of the image
uint8_t bHeight; // Height, in pixels, of the image
uint8_t bColorCount; // Number of colors in image (0 if >=8bpp)
uint8_t bReserved; // Reserved ( must be 0)
uint16_t wPlanes; // Color Planes
uint16_t wBitCount; // Bits per pixel
uint32_t dwBytesInRes; // How many bytes in this resource?
uint32_t dwImageOffset; // Where in the file is this image?
};
} // namespace
size_t Ico::Leanify(size_t size_leanified /*= 0*/)
{
// number of images inside ico file
const uint16_t num_of_img = *(uint16_t *)(fp_ + 4);
// size too small
if (6 + num_of_img * sizeof(IconDirEntry) >= size_)
{
return Format::Leanify(size_leanified);
}
// sort the entries by offset just in case it's not sorted before
IconDirEntry *entry_addr = reinterpret_cast<IconDirEntry *>(fp_ + 6);
vector<IconDirEntry> entries(entry_addr, entry_addr + num_of_img);
std::sort(entries.begin(), entries.end(), [] (const IconDirEntry& a, const IconDirEntry& b)
{
return a.dwImageOffset < b.dwImageOffset;
});
// check overlaps
for (size_t i = 1; i < entries.size(); i++)
{
if (entries[i - 1].dwImageOffset + entries[i - 1].dwBytesInRes > entries[i].dwImageOffset)
{
cerr << "Error: Found overlapping icon entries!" << endl;
return Format::Leanify(size_leanified);
}
}
// is file size enough?
if (entries.back().dwImageOffset + entries.back().dwBytesInRes > size_)
{
return Format::Leanify(size_leanified);
}
for (size_t i = 0; i < entries.size(); i++)
{
uint32_t old_offset = entries[i].dwImageOffset;
// write new offset
if (i != 0)
{
entries[i].dwImageOffset = entries[i - 1].dwImageOffset + entries[i - 1].dwBytesInRes;
}
else
{
entries[i].dwImageOffset = 6 + num_of_img * sizeof(IconDirEntry);
}
// Leanify PNG
if (memcmp(fp_ + old_offset, Png::header_magic, sizeof(Png::header_magic)) == 0)
{
entries[i].dwBytesInRes = Png(fp_ + old_offset, entries[i].dwBytesInRes).Leanify(size_leanified + old_offset - entries[i].dwImageOffset);
continue;
}
// Convert 256x256 BMP to PNG if possible
if (entries[i].bWidth == 0 && entries[i].bHeight == 0)
{
auto dib = reinterpret_cast<Bmp::BITMAPINFOHEADER*>(fp_ + old_offset);
if (dib->biSize >= 40 &&
dib->biWidth == 256 && dib->biHeight == 512 && // DIB in ICO always has double height
dib->biPlanes == 1 &&
dib->biBitCount == 32 && // only support RGBA for now
dib->biCompression == 0 && // BI_RGB aka no compression
dib->biSize + std::max(dib->biSizeImage, 256 * 256 * 4U) <= entries[i].dwBytesInRes &&
(dib->biSizeImage == 0 || dib->biSizeImage >= 256 * 256 * 4U) &&
dib->biClrUsed == 0)
{
if (is_verbose)
{
cout << "Converting 256x256 BMP to PNG..." << endl;
}
// BMP stores ARGB in little endian, so it's actually BGRA, convert it to normal RGBA
// It also stores the pixels upside down for some reason, so reverse it.
uint8_t *bmp_row = fp_ + old_offset + dib->biSize + 256 * 256 * 4;
vector<uint8_t> raw(256 * 256 * 4), png;
// TODO: detect 0RGB and convert it to RGBA using mask
for (size_t j = 0; j < 256; j++)
{
bmp_row -= 256 * 4;
for (size_t k = 0; k < 256; k++)
{
raw[(j * 256 + k) * 4 + 0] = bmp_row[k * 4 + 2];
raw[(j * 256 + k) * 4 + 1] = bmp_row[k * 4 + 1];
raw[(j * 256 + k) * 4 + 2] = bmp_row[k * 4 + 0];
raw[(j * 256 + k) * 4 + 3] = bmp_row[k * 4 + 3];
}
}
if (lodepng::encode(png, raw, 256, 256) == 0)
{
// Optimize the new PNG
size_t png_size = Png(png).Leanify();
if (png_size < entries[i].dwBytesInRes)
{
entries[i].dwBytesInRes = png_size;
memcpy(fp_ + entries[i].dwImageOffset - size_leanified, png.data(), png_size);
continue;
}
}
}
}
memmove(fp_ + entries[i].dwImageOffset - size_leanified, fp_ + old_offset, entries[i].dwBytesInRes);
}
fp_ -= size_leanified;
// write headers if moved
if (size_leanified)
{
memcpy(fp_, header_magic, sizeof(header_magic));
*(uint16_t *)(fp_ + 4) = num_of_img;
}
// write new entries
memcpy(fp_ + 6, entries.data(), entries.size() * sizeof(IconDirEntry));
// offset + size of last img
size_ = entries.back().dwImageOffset + entries.back().dwBytesInRes;
return size_;
}
|
fix header if moved
|
ICO: fix header if moved
|
C++
|
mit
|
JayXon/Leanify,yyjdelete/Leanify,JayXon/Leanify,yyjdelete/Leanify
|
4303278424261091dde0121212f14f67a6add16a
|
modules/notes.cpp
|
modules/notes.cpp
|
/*
* Copyright (C) 2004-2011 See the AUTHORS file for details.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*/
#include "Chan.h"
#include "HTTPSock.h"
#include "Server.h"
#include "Template.h"
#include "User.h"
#include "znc.h"
#include "WebModules.h"
#include <sstream>
using std::stringstream;
class CNotesMod : public CModule {
void ListCommand(const CString &sLine) {
ListNotes();
}
void AddNoteCommand(const CString &sLine) {
CString sKey(sLine.Token(1));
CString sValue(sLine.Token(2, true));
if (!GetNV(sKey).empty()) {
PutModule("That note already exists. Use MOD <key> <note> to overwrite.");
} else if (AddNote(sKey, sValue)) {
PutModule("Added note [" + sKey + "]");
} else {
PutModule("Unable to add note [" + sKey + "]");
}
}
void ModCommand(const CString &sLine) {
CString sKey(sLine.Token(1));
CString sValue(sLine.Token(2, true));
if (AddNote(sKey, sValue)) {
PutModule("Set note for [" + sKey + "]");
} else {
PutModule("Unable to add note [" + sKey + "]");
}
}
void GetCommand(const CString &sLine) {
CString sNote = GetNV(sLine.Token(1, true));
if (sNote.empty()) {
PutModule("This note doesn't exist.");
} else {
PutModule(sNote);
}
}
void DelCommand(const CString &sLine) {
CString sKey(sLine.Token(1));
if (DelNote(sKey)) {
PutModule("Deleted note [" + sKey + "]");
} else {
PutModule("Unable to delete note [" + sKey + "]");
}
}
public:
MODCONSTRUCTOR(CNotesMod) {
AddHelpCommand();
AddCommand("List", static_cast<CModCommand::ModCmdFunc>(&CNotesMod::ListCommand));
AddCommand("Add", static_cast<CModCommand::ModCmdFunc>(&CNotesMod::AddNoteCommand),
"<key> <note>");
AddCommand("Del", static_cast<CModCommand::ModCmdFunc>(&CNotesMod::DelCommand),
"<key>", "Delete a note");
AddCommand("Mod", static_cast<CModCommand::ModCmdFunc>(&CNotesMod::ModCommand),
"<key> <note>", "Modify a note");
AddCommand("Get", static_cast<CModCommand::ModCmdFunc>(&CNotesMod::GetCommand),
"<key>");
}
virtual ~CNotesMod() {}
virtual bool OnLoad(const CString& sArgStr, CString& sMessage) {
return true;
}
virtual CString GetWebMenuTitle() { return "Notes"; }
virtual void OnClientLogin() {
ListNotes(true);
}
virtual EModRet OnUserRaw(CString& sLine) {
if (sLine.Left(1) != "#") {
return CONTINUE;
}
CString sKey;
bool bOverwrite = false;
if (sLine == "#?") {
ListNotes(true);
return HALT;
} else if (sLine.Left(2) == "#-") {
sKey = sLine.Token(0).LeftChomp_n(2);
if (DelNote(sKey)) {
PutModNotice("Deleted note [" + sKey + "]");
} else {
PutModNotice("Unable to delete note [" + sKey + "]");
}
return HALT;
} else if (sLine.Left(2) == "#+") {
sKey = sLine.Token(0).LeftChomp_n(2);
bOverwrite = true;
} else if (sLine.Left(1) == "#") {
sKey = sLine.Token(0).LeftChomp_n(1);
}
CString sValue(sLine.Token(1, true));
if (!sKey.empty()) {
if (!bOverwrite && FindNV(sKey) != EndNV()) {
PutModNotice("That note already exists. Use /#+<key> <note> to overwrite.");
} else if (AddNote(sKey, sValue)) {
if (!bOverwrite) {
PutModNotice("Added note [" + sKey + "]");
} else {
PutModNotice("Set note for [" + sKey + "]");
}
} else {
PutModNotice("Unable to add note [" + sKey + "]");
}
}
return HALT;
}
bool DelNote(const CString& sKey) {
return DelNV(sKey);
}
bool AddNote(const CString& sKey, const CString& sNote) {
if (sKey.empty()) {
return false;
}
return SetNV(sKey, sNote);
}
void ListNotes(bool bNotice = false) {
CClient* pClient = GetClient();
if (pClient) {
CTable Table;
Table.AddColumn("Key");
Table.AddColumn("Note");
for (MCString::iterator it = BeginNV(); it != EndNV(); ++it) {
Table.AddRow();
Table.SetCell("Key", it->first);
Table.SetCell("Note", it->second);
}
if (Table.size()) {
unsigned int idx = 0;
CString sLine;
while (Table.GetLine(idx++, sLine)) {
if (bNotice) {
pClient->PutModNotice(GetModName(), sLine);
} else {
pClient->PutModule(GetModName(), sLine);
}
}
} else {
if (bNotice) {
PutModNotice("You have no entries.");
} else {
PutModule("You have no entries.");
}
}
}
}
virtual bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) {
if (sPageName == "index") {
for (MCString::iterator it = BeginNV(); it != EndNV(); ++it) {
CTemplate& Row = Tmpl.AddRow("NotesLoop");
Row["Key"] = it->first;
Row["Note"] = it->second;
}
return true;
} else if (sPageName == "delnote") {
DelNote(WebSock.GetParam("key", false));
WebSock.Redirect("/mods/notes/");
return true;
} else if (sPageName == "addnote") {
AddNote(WebSock.GetParam("key"), WebSock.GetParam("note"));
WebSock.Redirect("/mods/notes/");
return true;
}
return false;
}
};
MODULEDEFS(CNotesMod, "Keep and replay notes")
|
/*
* Copyright (C) 2004-2011 See the AUTHORS file for details.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*/
#include "Chan.h"
#include "HTTPSock.h"
#include "Server.h"
#include "Template.h"
#include "User.h"
#include "znc.h"
#include "WebModules.h"
#include <sstream>
using std::stringstream;
class CNotesMod : public CModule {
bool bShowNotesOnLogin;
void ListCommand(const CString &sLine) {
ListNotes();
}
void AddNoteCommand(const CString &sLine) {
CString sKey(sLine.Token(1));
CString sValue(sLine.Token(2, true));
if (!GetNV(sKey).empty()) {
PutModule("That note already exists. Use MOD <key> <note> to overwrite.");
} else if (AddNote(sKey, sValue)) {
PutModule("Added note [" + sKey + "]");
} else {
PutModule("Unable to add note [" + sKey + "]");
}
}
void ModCommand(const CString &sLine) {
CString sKey(sLine.Token(1));
CString sValue(sLine.Token(2, true));
if (AddNote(sKey, sValue)) {
PutModule("Set note for [" + sKey + "]");
} else {
PutModule("Unable to add note [" + sKey + "]");
}
}
void GetCommand(const CString &sLine) {
CString sNote = GetNV(sLine.Token(1, true));
if (sNote.empty()) {
PutModule("This note doesn't exist.");
} else {
PutModule(sNote);
}
}
void DelCommand(const CString &sLine) {
CString sKey(sLine.Token(1));
if (DelNote(sKey)) {
PutModule("Deleted note [" + sKey + "]");
} else {
PutModule("Unable to delete note [" + sKey + "]");
}
}
public:
MODCONSTRUCTOR(CNotesMod) {
AddHelpCommand();
AddCommand("List", static_cast<CModCommand::ModCmdFunc>(&CNotesMod::ListCommand));
AddCommand("Add", static_cast<CModCommand::ModCmdFunc>(&CNotesMod::AddNoteCommand),
"<key> <note>");
AddCommand("Del", static_cast<CModCommand::ModCmdFunc>(&CNotesMod::DelCommand),
"<key>", "Delete a note");
AddCommand("Mod", static_cast<CModCommand::ModCmdFunc>(&CNotesMod::ModCommand),
"<key> <note>", "Modify a note");
AddCommand("Get", static_cast<CModCommand::ModCmdFunc>(&CNotesMod::GetCommand),
"<key>");
}
virtual ~CNotesMod() {}
virtual bool OnLoad(const CString& sArgs, CString& sMessage) {
bShowNotesOnLogin = !sArgs.Equals("-disableNotesOnLogin");
return true;
}
virtual CString GetWebMenuTitle() { return "Notes"; }
virtual void OnClientLogin() {
if (bShowNotesOnLogin) {
ListNotes(true);
}
}
virtual EModRet OnUserRaw(CString& sLine) {
if (sLine.Left(1) != "#") {
return CONTINUE;
}
CString sKey;
bool bOverwrite = false;
if (sLine == "#?") {
ListNotes(true);
return HALT;
} else if (sLine.Left(2) == "#-") {
sKey = sLine.Token(0).LeftChomp_n(2);
if (DelNote(sKey)) {
PutModNotice("Deleted note [" + sKey + "]");
} else {
PutModNotice("Unable to delete note [" + sKey + "]");
}
return HALT;
} else if (sLine.Left(2) == "#+") {
sKey = sLine.Token(0).LeftChomp_n(2);
bOverwrite = true;
} else if (sLine.Left(1) == "#") {
sKey = sLine.Token(0).LeftChomp_n(1);
}
CString sValue(sLine.Token(1, true));
if (!sKey.empty()) {
if (!bOverwrite && FindNV(sKey) != EndNV()) {
PutModNotice("That note already exists. Use /#+<key> <note> to overwrite.");
} else if (AddNote(sKey, sValue)) {
if (!bOverwrite) {
PutModNotice("Added note [" + sKey + "]");
} else {
PutModNotice("Set note for [" + sKey + "]");
}
} else {
PutModNotice("Unable to add note [" + sKey + "]");
}
}
return HALT;
}
bool DelNote(const CString& sKey) {
return DelNV(sKey);
}
bool AddNote(const CString& sKey, const CString& sNote) {
if (sKey.empty()) {
return false;
}
return SetNV(sKey, sNote);
}
void ListNotes(bool bNotice = false) {
CClient* pClient = GetClient();
if (pClient) {
CTable Table;
Table.AddColumn("Key");
Table.AddColumn("Note");
for (MCString::iterator it = BeginNV(); it != EndNV(); ++it) {
Table.AddRow();
Table.SetCell("Key", it->first);
Table.SetCell("Note", it->second);
}
if (Table.size()) {
unsigned int idx = 0;
CString sLine;
while (Table.GetLine(idx++, sLine)) {
if (bNotice) {
pClient->PutModNotice(GetModName(), sLine);
} else {
pClient->PutModule(GetModName(), sLine);
}
}
} else {
if (bNotice) {
PutModNotice("You have no entries.");
} else {
PutModule("You have no entries.");
}
}
}
}
virtual bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) {
if (sPageName == "index") {
for (MCString::iterator it = BeginNV(); it != EndNV(); ++it) {
CTemplate& Row = Tmpl.AddRow("NotesLoop");
Row["Key"] = it->first;
Row["Note"] = it->second;
}
return true;
} else if (sPageName == "delnote") {
DelNote(WebSock.GetParam("key", false));
WebSock.Redirect("/mods/notes/");
return true;
} else if (sPageName == "addnote") {
AddNote(WebSock.GetParam("key"), WebSock.GetParam("note"));
WebSock.Redirect("/mods/notes/");
return true;
}
return false;
}
};
MODULEDEFS(CNotesMod, "Keep and replay notes")
|
Add a option to the notes module so that you can prevent it from sending you notes when you connect
|
Add a option to the notes module so that you can prevent it from sending you notes when you connect
|
C++
|
apache-2.0
|
psychon/znc,badloop/znc,TuffLuck/znc,Adam-/znc,Adam-/znc,ollie27/znc,jantman/znc,Hasimir/znc,badloop/znc,markusj/znc,Kriechi/znc,BtbN/znc,jpnurmi/znc,Mikaela/znc,anthonyryan1/znc,Mkaysi/znc,psychon/znc,Zarthus/znc,DarthGandalf/znc,anthonyryan1/znc,trisk/znc,withinsoft/znc,znc/znc,reedloden/znc,reedloden/znc,Mikaela/znc,Adam-/znc,Kriechi/znc,Mkaysi/znc,Mikaela/znc,Kriechi/nobnc,YourBNC/znc,elyscape/znc,znc/znc,jantman/znc,Hasimir/znc,ollie27/znc,znc/znc,KielBNC/znc,Mkaysi/znc,markusj/znc,KielBNC/znc,jpnurmi/znc,Zarthus/znc,kashike/znc,Zarthus/znc,Phansa/znc,wolfy1339/znc,BtbN/znc,evilnet/znc,BtbN/znc,aarondunlap/znc,aarondunlap/znc,TingPing/znc,badloop/znc,markusj/znc,reedloden/znc,KiNgMaR/znc,KielBNC/znc,KiNgMaR/znc,Hasimir/znc,anthonyryan1/znc,aarondunlap/znc,TuffLuck/znc,reedloden/znc,DarthGandalf/znc,Adam-/znc,Mikaela/znc,trisk/znc,Hasimir/znc,evilnet/znc,wolfy1339/znc,kashike/znc,aarondunlap/znc,elyscape/znc,Kriechi/znc,jpnurmi/znc,jreese/znc,reedloden/znc,Adam-/znc,dgw/znc,YourBNC/znc,KiNgMaR/znc,Zarthus/znc,evilnet/znc,Mkaysi/znc,trisk/znc,jreese/znc,ollie27/znc,jantman/znc,kashike/znc,wolfy1339/znc,Adam-/znc,psychon/znc,Mkaysi/znc,aarondunlap/znc,TuffLuck/znc,kashike/znc,badloop/znc,TingPing/znc,dgw/znc,wolfy1339/znc,psychon/znc,KiNgMaR/znc,znc/znc,ollie27/znc,trisk/znc,ollie27/znc,wolfy1339/znc,evilnet/znc,Adam-/znc,Phansa/znc,badloop/znc,KiNgMaR/znc,YourBNC/znc,dgw/znc,elyscape/znc,jpnurmi/znc,Hasimir/znc,Kriechi/nobnc,Zarthus/znc,TingPing/znc,GLolol/znc,TingPing/znc,trisk/znc,KielBNC/znc,markusj/znc,TuffLuck/znc,dgw/znc,jreese/znc,jreese/znc,kashike/znc,aarondunlap/znc,badloop/znc,GLolol/znc,Kriechi/znc,Mikaela/znc,Kriechi/nobnc,aarondunlap/znc,KiNgMaR/znc,anthonyryan1/znc,YourBNC/znc,jreese/znc,psychon/znc,Kriechi/znc,withinsoft/znc,Mkaysi/znc,dgw/znc,markusj/znc,evilnet/znc,Phansa/znc,Zarthus/znc,KielBNC/znc,evilnet/znc,withinsoft/znc,Kriechi/znc,KielBNC/znc,jantman/znc,TingPing/znc,YourBNC/znc,DarthGandalf/znc,elyscape/znc,BtbN/znc,Phansa/znc,badloop/znc,GLolol/znc,withinsoft/znc,TuffLuck/znc,withinsoft/znc,GLolol/znc,kashike/znc,YourBNC/znc,elyscape/znc,DarthGandalf/znc,Mikaela/znc,jantman/znc,jreese/znc,TuffLuck/znc,anthonyryan1/znc,elyscape/znc,GLolol/znc,BtbN/znc,jpnurmi/znc,jantman/znc,jpnurmi/znc,Hasimir/znc,TingPing/znc,anthonyryan1/znc,psychon/znc,Phansa/znc,anthonyryan1/znc,Mikaela/znc,DarthGandalf/znc,Hasimir/znc,Mkaysi/znc,reedloden/znc,DarthGandalf/znc,znc/znc,jpnurmi/znc,withinsoft/znc,wolfy1339/znc,BtbN/znc,trisk/znc,markusj/znc,Phansa/znc,TuffLuck/znc,dgw/znc,GLolol/znc,ollie27/znc,znc/znc
|
2c68ab3cded74c9e584d05bbadd9a6f912ae2bb5
|
net-rcf/include/RCFClientImpl.hpp
|
net-rcf/include/RCFClientImpl.hpp
|
/* Copyright(C)
* For free
* All right reserved
*
*/
/**
* @file RCFClientImpl.h
* @brief RCF客户端通信框架实现类
* @author highway-9, [email protected]
* @version 1.1.0
* @date 2016-01-04
*/
#ifndef _RCFCLIENTIMPL_H
#define _RCFCLIENTIMPL_H
#include <RCF/RCF.hpp>
#include <iostream>
#include <boost/shared_ptr.hpp>
/**
* @brief RCF客户端通信框架实现类
*
* @tparam T 类类型
*/
template<typename T>
class RCFClientImpl
{
public:
/**
* @brief RCFClientImpl 构造函数
*/
RCFClientImpl()
: m_rcfInit(NULL),
m_rcfClient(NULL),
m_ip(127.0.0.1),
m_port(50001)
{
// Do nothing
}
/**
* @brief ~RCFClientImpl 析构函数
*/
~RCFClientImpl()
{
stop();
deinit();
}
/**
* @brief init 初始化RCF客户端
*
* @param ip 服务器ip地址
* @param port 服务器端口号,默认为50001
*/
void init(const std::string& ip, unsigned int port = 50001)
{
m_ip = ip;
m_port = port;
}
/**
* @brief start 开启客户端服务
*
* @return 成功返回true,否则返回false
*/
bool start()
{
try
{
if (m_rcfInit == NULL)
{
m_rcfInit = boost::make_shared<RCF::RcfInitDeinit>();
}
if (m_rcfClient == NULL)
{
m_rcfClient = boost::make_shared<RcfClient<T> >(RCF::TcpEndPoint(m_ip, m_port));
}
}
catch (const RCF::Exception& e)
{
std::cout << "Error: " << e.getErrorString() << std::endl;
return false;
}
return true;
}
/**
* @brief stop 停止客户端服务
*
* @return 成功返回true,否则返回false
*/
bool stop()
{
return true;
}
/**
* @brief deinit 反初始化,释放一些资源
*/
void deinit()
{
// Do nothing
}
private:
typedef boost::shared_ptr<RCF::RcfInitDeinit> RcfInitDeinitPtr;
RcfInitDeinitPtr m_rcfInit; ///< RCF客户端服务初始化对象
typedef boost::shared_ptr<RcfClient<T> > RcfClientPtr;
RcfClientPtr m_rcfClient; ///< RCF客户端对象
std::string m_ip; ///< 服务器ip地址
unsigned int m_port; ///< 服务器端口号
};
#endif
|
/* Copyright(C)
* For free
* All right reserved
*
*/
/**
* @file RCFClientImpl.h
* @brief RCF客户端通信框架实现类
* @author highway-9, [email protected]
* @version 1.1.0
* @date 2016-01-04
*/
#ifndef _RCFCLIENTIMPL_H
#define _RCFCLIENTIMPL_H
#include <RCF/RCF.hpp>
#include <iostream>
#include <boost/shared_ptr.hpp>
/**
* @brief RCF客户端通信框架实现类
*
* @tparam I_RCFMessageHandler 类类型
*/
template<typename I_RCFMessageHandler>
class RCFClientImpl
{
public:
/**
* @brief RCFClientImpl 构造函数
*/
RCFClientImpl()
: m_rcfInit(NULL),
m_rcfClient(NULL),
m_ip(127.0.0.1),
m_port(50001)
{
// Do nothing
}
/**
* @brief ~RCFClientImpl 析构函数
*/
~RCFClientImpl()
{
stop();
deinit();
}
/**
* @brief init 初始化RCF客户端
*
* @param ip 服务器ip地址
* @param port 服务器端口号,默认为50001
*/
void init(const std::string& ip, unsigned int port = 50001)
{
m_ip = ip;
m_port = port;
}
/**
* @brief start 开启客户端服务
*
* @return 成功返回true,否则返回false
*/
bool start()
{
try
{
if (m_rcfInit == NULL)
{
m_rcfInit = boost::make_shared<RCF::RcfInitDeinit>();
}
if (m_rcfClient == NULL)
{
m_rcfClient = boost::make_shared<RcfClient<I_RCFMessageHandler> >(RCF::TcpEndPoint(m_ip, m_port));
}
}
catch (const RCF::Exception& e)
{
std::cout << "Error: " << e.getErrorString() << std::endl;
return false;
}
return true;
}
/**
* @brief stop 停止客户端服务
*
* @return 成功返回true,否则返回false
*/
bool stop()
{
return true;
}
/**
* @brief deinit 反初始化,释放一些资源
*/
void deinit()
{
// Do nothing
}
private:
typedef boost::shared_ptr<RCF::RcfInitDeinit> RcfInitDeinitPtr;
RcfInitDeinitPtr m_rcfInit; ///< RCF客户端服务初始化对象
typedef boost::shared_ptr<RcfClient<I_RCFMessageHandler> > RcfClientPtr;
RcfClientPtr m_rcfClient; ///< RCF客户端对象
std::string m_ip; ///< 服务器ip地址
unsigned int m_port; ///< 服务器端口号
};
#endif
|
Update net-rcf
|
Update net-rcf
|
C++
|
mit
|
chxuan/easyrpc,chxuan/easyrpc,chxuan/easyrpc,chxuan/easyrpc
|
b2e8c08ded3d3f18171b6bf8abef1375d8d90ef4
|
net/spdy/spdy_session_unittest.cc
|
net/spdy/spdy_session_unittest.cc
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/spdy/spdy_io_buffer.h"
#include "googleurl/src/gurl.h"
#include "net/base/mock_host_resolver.h"
#include "net/base/ssl_config_service_defaults.h"
#include "net/base/test_completion_callback.h"
#include "net/http/http_network_session.h"
#include "net/http/http_response_info.h"
#include "net/proxy/proxy_service.h"
#include "net/socket/socket_test_util.h"
#include "net/spdy/spdy_http_stream.h"
#include "net/spdy/spdy_session.h"
#include "net/spdy/spdy_session_pool.h"
#include "net/spdy/spdy_stream.h"
#include "net/spdy/spdy_test_util.h"
#include "testing/platform_test.h"
namespace net {
// TODO(cbentzel): Expose compression setter/getter in public SpdySession
// interface rather than going through all these contortions.
class SpdySessionTest : public PlatformTest {
public:
static void TurnOffCompression() {
spdy::SpdyFramer::set_enable_compression_default(false);
}
};
namespace {
// Helper to manage the lifetimes of the dependencies for a
// SpdyNetworkTransaction.
class SessionDependencies {
public:
// Default set of dependencies -- "null" proxy service.
SessionDependencies()
: host_resolver(new MockHostResolver),
proxy_service(ProxyService::CreateNull()),
ssl_config_service(new SSLConfigServiceDefaults),
spdy_session_pool(new SpdySessionPool()) {
}
scoped_refptr<MockHostResolverBase> host_resolver;
scoped_refptr<ProxyService> proxy_service;
scoped_refptr<SSLConfigService> ssl_config_service;
MockClientSocketFactory socket_factory;
scoped_refptr<SpdySessionPool> spdy_session_pool;
};
HttpNetworkSession* CreateSession(SessionDependencies* session_deps) {
return new HttpNetworkSession(session_deps->host_resolver,
session_deps->proxy_service,
&session_deps->socket_factory,
session_deps->ssl_config_service,
session_deps->spdy_session_pool,
NULL,
NULL,
NULL);
}
// Test the SpdyIOBuffer class.
TEST_F(SpdySessionTest, SpdyIOBuffer) {
std::priority_queue<SpdyIOBuffer> queue_;
const size_t kQueueSize = 100;
// Insert 100 items; pri 100 to 1.
for (size_t index = 0; index < kQueueSize; ++index) {
SpdyIOBuffer buffer(new IOBuffer(), 0, kQueueSize - index, NULL);
queue_.push(buffer);
}
// Insert several priority 0 items last.
const size_t kNumDuplicates = 12;
IOBufferWithSize* buffers[kNumDuplicates];
for (size_t index = 0; index < kNumDuplicates; ++index) {
buffers[index] = new IOBufferWithSize(index+1);
queue_.push(SpdyIOBuffer(buffers[index], buffers[index]->size(), 0, NULL));
}
EXPECT_EQ(kQueueSize + kNumDuplicates, queue_.size());
// Verify the P0 items come out in FIFO order.
for (size_t index = 0; index < kNumDuplicates; ++index) {
SpdyIOBuffer buffer = queue_.top();
EXPECT_EQ(0, buffer.priority());
EXPECT_EQ(index + 1, buffer.size());
queue_.pop();
}
int priority = 1;
while (queue_.size()) {
SpdyIOBuffer buffer = queue_.top();
EXPECT_EQ(priority++, buffer.priority());
queue_.pop();
}
}
static const unsigned char kGoAway[] = {
0x80, 0x01, 0x00, 0x07, // header
0x00, 0x00, 0x00, 0x04, // flags, len
0x00, 0x00, 0x00, 0x00, // last-accepted-stream-id
};
TEST_F(SpdySessionTest, GoAway) {
SessionDependencies session_deps;
session_deps.host_resolver->set_synchronous_mode(true);
MockConnect connect_data(false, OK);
MockRead reads[] = {
MockRead(false, reinterpret_cast<const char*>(kGoAway),
arraysize(kGoAway)),
MockRead(false, 0, 0) // EOF
};
StaticSocketDataProvider data(reads, arraysize(reads), NULL, 0);
data.set_connect_data(connect_data);
session_deps.socket_factory.AddSocketDataProvider(&data);
SSLSocketDataProvider ssl(false, OK);
session_deps.socket_factory.AddSSLSocketDataProvider(&ssl);
scoped_refptr<HttpNetworkSession> http_session(CreateSession(&session_deps));
const std::string kTestHost("www.foo.com");
const int kTestPort = 80;
HostPortPair test_host_port_pair;
test_host_port_pair.host = kTestHost;
test_host_port_pair.port = kTestPort;
scoped_refptr<SpdySessionPool> spdy_session_pool(
http_session->spdy_session_pool());
EXPECT_FALSE(spdy_session_pool->HasSession(test_host_port_pair));
scoped_refptr<SpdySession> session =
spdy_session_pool->Get(
test_host_port_pair, http_session.get(), BoundNetLog());
EXPECT_TRUE(spdy_session_pool->HasSession(test_host_port_pair));
scoped_refptr<TCPSocketParams> tcp_params =
new TCPSocketParams(kTestHost, kTestPort, MEDIUM, GURL(), false);
int rv = session->Connect(kTestHost, tcp_params, MEDIUM);
ASSERT_EQ(OK, rv);
// Flush the SpdySession::OnReadComplete() task.
MessageLoop::current()->RunAllPending();
EXPECT_FALSE(spdy_session_pool->HasSession(test_host_port_pair));
scoped_refptr<SpdySession> session2 =
spdy_session_pool->Get(
test_host_port_pair, http_session.get(), BoundNetLog());
// Delete the first session.
session = NULL;
// Delete the second session.
spdy_session_pool->Remove(session2);
session2 = NULL;
}
// kPush is a server-issued SYN_STREAM with stream id 2, and
// associated stream id 1. It also includes 3 headers of path,
// status, and HTTP version.
static const uint8 kPush[] = {
0x80, 0x01, 0x00, 0x01, // SYN_STREAM for SPDY v1.
0x00, 0x00, 0x00, 0x3b, // No flags 59 bytes after this 8 byte header.
0x00, 0x00, 0x00, 0x02, // Stream ID of 2
0x00, 0x00, 0x00, 0x01, // Associate Stream ID of 1
0x00, 0x00, 0x00, 0x03, // Priority 0, 3 name/value pairs in block below.
0x00, 0x04, 'p', 'a', 't', 'h',
0x00, 0x07, '/', 'f', 'o', 'o', '.', 'j', 's',
0x00, 0x06, 's', 't', 'a', 't', 'u', 's',
0x00, 0x03, '2', '0', '0',
0x00, 0x07, 'v', 'e', 'r', 's', 'i', 'o', 'n',
0x00, 0x08, 'H', 'T', 'T', 'P', '/', '1', '.', '1',
};
} // namespace
TEST_F(SpdySessionTest, GetActivePushStream) {
SpdySessionTest::TurnOffCompression();
SessionDependencies session_deps;
session_deps.host_resolver->set_synchronous_mode(true);
MockConnect connect_data(false, OK);
MockRead reads[] = {
MockRead(false, reinterpret_cast<const char*>(kPush),
arraysize(kPush)),
MockRead(true, ERR_IO_PENDING, 0) // EOF
};
StaticSocketDataProvider data(reads, arraysize(reads), NULL, 0);
data.set_connect_data(connect_data);
session_deps.socket_factory.AddSocketDataProvider(&data);
SSLSocketDataProvider ssl(false, OK);
session_deps.socket_factory.AddSSLSocketDataProvider(&ssl);
scoped_refptr<HttpNetworkSession> http_session(CreateSession(&session_deps));
const std::string kTestHost("www.foo.com");
const int kTestPort = 80;
HostPortPair test_host_port_pair;
test_host_port_pair.host = kTestHost;
test_host_port_pair.port = kTestPort;
scoped_refptr<SpdySessionPool> spdy_session_pool(
http_session->spdy_session_pool());
EXPECT_FALSE(spdy_session_pool->HasSession(test_host_port_pair));
scoped_refptr<SpdySession> session =
spdy_session_pool->Get(
test_host_port_pair, http_session.get(), BoundNetLog());
EXPECT_TRUE(spdy_session_pool->HasSession(test_host_port_pair));
// No push streams should exist in the beginning.
std::string test_push_path = "/foo.js";
scoped_refptr<SpdyStream> first_stream = session->GetActivePushStream(
test_push_path);
EXPECT_EQ(static_cast<SpdyStream*>(NULL), first_stream.get());
// Read in the data which contains a server-issued SYN_STREAM.
scoped_refptr<TCPSocketParams> tcp_params =
new TCPSocketParams(test_host_port_pair, MEDIUM, GURL(), false);
int rv = session->Connect(kTestHost, tcp_params, MEDIUM);
ASSERT_EQ(OK, rv);
MessageLoop::current()->RunAllPending();
// An unpushed path should not work.
scoped_refptr<SpdyStream> unpushed_stream = session->GetActivePushStream(
"/unpushed_path");
EXPECT_EQ(static_cast<SpdyStream*>(NULL), unpushed_stream.get());
// The pushed path should be found.
scoped_refptr<SpdyStream> second_stream = session->GetActivePushStream(
test_push_path);
ASSERT_NE(static_cast<SpdyStream*>(NULL), second_stream.get());
EXPECT_EQ(test_push_path, second_stream->path());
EXPECT_EQ(2U, second_stream->stream_id());
EXPECT_EQ(0, second_stream->priority());
// Clean up
second_stream = NULL;
session = NULL;
spdy_session_pool->CloseAllSessions();
// RunAllPending needs to be called here because the
// ClientSocketPoolBase posts a task to clean up and destroy the
// underlying socket.
MessageLoop::current()->RunAllPending();
}
} // namespace net
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/spdy/spdy_io_buffer.h"
#include "googleurl/src/gurl.h"
#include "net/base/mock_host_resolver.h"
#include "net/base/ssl_config_service_defaults.h"
#include "net/base/test_completion_callback.h"
#include "net/http/http_network_session.h"
#include "net/http/http_response_info.h"
#include "net/proxy/proxy_service.h"
#include "net/socket/socket_test_util.h"
#include "net/spdy/spdy_http_stream.h"
#include "net/spdy/spdy_session.h"
#include "net/spdy/spdy_session_pool.h"
#include "net/spdy/spdy_stream.h"
#include "net/spdy/spdy_test_util.h"
#include "testing/platform_test.h"
namespace net {
// TODO(cbentzel): Expose compression setter/getter in public SpdySession
// interface rather than going through all these contortions.
class SpdySessionTest : public PlatformTest {
public:
static void TurnOffCompression() {
spdy::SpdyFramer::set_enable_compression_default(false);
}
};
namespace {
// Helper to manage the lifetimes of the dependencies for a
// SpdyNetworkTransaction.
class SessionDependencies {
public:
// Default set of dependencies -- "null" proxy service.
SessionDependencies()
: host_resolver(new MockHostResolver),
proxy_service(ProxyService::CreateNull()),
ssl_config_service(new SSLConfigServiceDefaults),
spdy_session_pool(new SpdySessionPool()) {
}
scoped_refptr<MockHostResolverBase> host_resolver;
scoped_refptr<ProxyService> proxy_service;
scoped_refptr<SSLConfigService> ssl_config_service;
MockClientSocketFactory socket_factory;
scoped_refptr<SpdySessionPool> spdy_session_pool;
};
HttpNetworkSession* CreateSession(SessionDependencies* session_deps) {
return new HttpNetworkSession(session_deps->host_resolver,
session_deps->proxy_service,
&session_deps->socket_factory,
session_deps->ssl_config_service,
session_deps->spdy_session_pool,
NULL,
NULL,
NULL);
}
// Test the SpdyIOBuffer class.
TEST_F(SpdySessionTest, SpdyIOBuffer) {
std::priority_queue<SpdyIOBuffer> queue_;
const size_t kQueueSize = 100;
// Insert 100 items; pri 100 to 1.
for (size_t index = 0; index < kQueueSize; ++index) {
SpdyIOBuffer buffer(new IOBuffer(), 0, kQueueSize - index, NULL);
queue_.push(buffer);
}
// Insert several priority 0 items last.
const size_t kNumDuplicates = 12;
IOBufferWithSize* buffers[kNumDuplicates];
for (size_t index = 0; index < kNumDuplicates; ++index) {
buffers[index] = new IOBufferWithSize(index+1);
queue_.push(SpdyIOBuffer(buffers[index], buffers[index]->size(), 0, NULL));
}
EXPECT_EQ(kQueueSize + kNumDuplicates, queue_.size());
// Verify the P0 items come out in FIFO order.
for (size_t index = 0; index < kNumDuplicates; ++index) {
SpdyIOBuffer buffer = queue_.top();
EXPECT_EQ(0, buffer.priority());
EXPECT_EQ(index + 1, buffer.size());
queue_.pop();
}
int priority = 1;
while (queue_.size()) {
SpdyIOBuffer buffer = queue_.top();
EXPECT_EQ(priority++, buffer.priority());
queue_.pop();
}
}
TEST_F(SpdySessionTest, GoAway) {
SessionDependencies session_deps;
session_deps.host_resolver->set_synchronous_mode(true);
MockConnect connect_data(false, OK);
scoped_ptr<spdy::SpdyFrame> goaway(ConstructSpdyGoAway());
MockRead reads[] = {
CreateMockRead(*goaway),
MockRead(false, 0, 0) // EOF
};
StaticSocketDataProvider data(reads, arraysize(reads), NULL, 0);
data.set_connect_data(connect_data);
session_deps.socket_factory.AddSocketDataProvider(&data);
SSLSocketDataProvider ssl(false, OK);
session_deps.socket_factory.AddSSLSocketDataProvider(&ssl);
scoped_refptr<HttpNetworkSession> http_session(CreateSession(&session_deps));
const std::string kTestHost("www.foo.com");
const int kTestPort = 80;
HostPortPair test_host_port_pair;
test_host_port_pair.host = kTestHost;
test_host_port_pair.port = kTestPort;
scoped_refptr<SpdySessionPool> spdy_session_pool(
http_session->spdy_session_pool());
EXPECT_FALSE(spdy_session_pool->HasSession(test_host_port_pair));
scoped_refptr<SpdySession> session =
spdy_session_pool->Get(
test_host_port_pair, http_session.get(), BoundNetLog());
EXPECT_TRUE(spdy_session_pool->HasSession(test_host_port_pair));
scoped_refptr<TCPSocketParams> tcp_params =
new TCPSocketParams(kTestHost, kTestPort, MEDIUM, GURL(), false);
int rv = session->Connect(kTestHost, tcp_params, MEDIUM);
ASSERT_EQ(OK, rv);
// Flush the SpdySession::OnReadComplete() task.
MessageLoop::current()->RunAllPending();
EXPECT_FALSE(spdy_session_pool->HasSession(test_host_port_pair));
scoped_refptr<SpdySession> session2 =
spdy_session_pool->Get(
test_host_port_pair, http_session.get(), BoundNetLog());
// Delete the first session.
session = NULL;
// Delete the second session.
spdy_session_pool->Remove(session2);
session2 = NULL;
}
} // namespace
TEST_F(SpdySessionTest, GetActivePushStream) {
spdy::SpdyFramer framer;
SpdySessionTest::TurnOffCompression();
SessionDependencies session_deps;
session_deps.host_resolver->set_synchronous_mode(true);
MockConnect connect_data(false, OK);
spdy::SpdyHeaderBlock headers;
headers["path"] = "/foo.js";
headers["status"] = "200";
headers["version"] = "HTTP/1.1";
scoped_ptr<spdy::SpdyFrame> push_syn(framer.CreateSynStream(
2, 1, 0, spdy::CONTROL_FLAG_NONE, false, &headers));
MockRead reads[] = {
CreateMockRead(*push_syn),
MockRead(true, ERR_IO_PENDING, 0) // EOF
};
StaticSocketDataProvider data(reads, arraysize(reads), NULL, 0);
data.set_connect_data(connect_data);
session_deps.socket_factory.AddSocketDataProvider(&data);
SSLSocketDataProvider ssl(false, OK);
session_deps.socket_factory.AddSSLSocketDataProvider(&ssl);
scoped_refptr<HttpNetworkSession> http_session(CreateSession(&session_deps));
const std::string kTestHost("www.foo.com");
const int kTestPort = 80;
HostPortPair test_host_port_pair;
test_host_port_pair.host = kTestHost;
test_host_port_pair.port = kTestPort;
scoped_refptr<SpdySessionPool> spdy_session_pool(
http_session->spdy_session_pool());
EXPECT_FALSE(spdy_session_pool->HasSession(test_host_port_pair));
scoped_refptr<SpdySession> session =
spdy_session_pool->Get(
test_host_port_pair, http_session.get(), BoundNetLog());
EXPECT_TRUE(spdy_session_pool->HasSession(test_host_port_pair));
// No push streams should exist in the beginning.
std::string test_push_path = "/foo.js";
scoped_refptr<SpdyStream> first_stream = session->GetActivePushStream(
test_push_path);
EXPECT_EQ(static_cast<SpdyStream*>(NULL), first_stream.get());
// Read in the data which contains a server-issued SYN_STREAM.
scoped_refptr<TCPSocketParams> tcp_params =
new TCPSocketParams(test_host_port_pair, MEDIUM, GURL(), false);
int rv = session->Connect(kTestHost, tcp_params, MEDIUM);
ASSERT_EQ(OK, rv);
MessageLoop::current()->RunAllPending();
// An unpushed path should not work.
scoped_refptr<SpdyStream> unpushed_stream = session->GetActivePushStream(
"/unpushed_path");
EXPECT_EQ(static_cast<SpdyStream*>(NULL), unpushed_stream.get());
// The pushed path should be found.
scoped_refptr<SpdyStream> second_stream = session->GetActivePushStream(
test_push_path);
ASSERT_NE(static_cast<SpdyStream*>(NULL), second_stream.get());
EXPECT_EQ(test_push_path, second_stream->path());
EXPECT_EQ(2U, second_stream->stream_id());
EXPECT_EQ(0, second_stream->priority());
// Clean up
second_stream = NULL;
session = NULL;
spdy_session_pool->CloseAllSessions();
// RunAllPending needs to be called here because the
// ClientSocketPoolBase posts a task to clean up and destroy the
// underlying socket.
MessageLoop::current()->RunAllPending();
}
} // namespace net
|
Remove hex frames from spdy_session_unittest.cc
|
Remove hex frames from spdy_session_unittest.cc
BUG=None
TEST=net_unittests pass
Review URL: http://codereview.chromium.org/2896004
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@52118 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
ropik/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,yitian134/chromium,adobe/chromium,ropik/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,adobe/chromium,yitian134/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,gavinp/chromium,ropik/chromium,adobe/chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,adobe/chromium,gavinp/chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,ropik/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,ropik/chromium,yitian134/chromium
|
7e4eb476e67b2e29c96a80e228c81b623ce3befc
|
media/webrtc/webrtcmediaengine.cc
|
media/webrtc/webrtcmediaengine.cc
|
/*
* libjingle
* Copyright 2014 Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
#if defined(LIBPEERCONNECTION_LIB) || defined(LIBPEERCONNECTION_IMPLEMENTATION)
#include "talk/media/webrtc/webrtcmediaengine.h"
#include "talk/media/webrtc/webrtcvideoengine.h"
#include "talk/media/webrtc/webrtcvideoengine2.h"
#include "talk/media/webrtc/webrtcvoiceengine.h"
#include "webrtc/system_wrappers/interface/field_trial.h"
namespace cricket {
class WebRtcMediaEngine
: public CompositeMediaEngine<WebRtcVoiceEngine, WebRtcVideoEngine> {
public:
WebRtcMediaEngine() {}
WebRtcMediaEngine(webrtc::AudioDeviceModule* adm,
webrtc::AudioDeviceModule* adm_sc,
WebRtcVideoEncoderFactory* encoder_factory,
WebRtcVideoDecoderFactory* decoder_factory) {
voice_.SetAudioDeviceModule(adm, adm_sc);
video_.SetExternalEncoderFactory(encoder_factory);
video_.SetExternalDecoderFactory(decoder_factory);
}
};
class WebRtcMediaEngine2
: public CompositeMediaEngine<WebRtcVoiceEngine, WebRtcVideoEngine2> {
public:
WebRtcMediaEngine2(webrtc::AudioDeviceModule* adm,
webrtc::AudioDeviceModule* adm_sc,
WebRtcVideoEncoderFactory* encoder_factory,
WebRtcVideoDecoderFactory* decoder_factory) {
voice_.SetAudioDeviceModule(adm, adm_sc);
video_.SetExternalDecoderFactory(decoder_factory);
video_.SetExternalEncoderFactory(encoder_factory);
}
};
} // namespace cricket
WRME_EXPORT
cricket::MediaEngineInterface* CreateWebRtcMediaEngine(
webrtc::AudioDeviceModule* adm,
webrtc::AudioDeviceModule* adm_sc,
cricket::WebRtcVideoEncoderFactory* encoder_factory,
cricket::WebRtcVideoDecoderFactory* decoder_factory) {
return new cricket::WebRtcMediaEngine2(adm, adm_sc, encoder_factory,
decoder_factory);
}
WRME_EXPORT
void DestroyWebRtcMediaEngine(cricket::MediaEngineInterface* media_engine) {
delete media_engine;
}
namespace cricket {
// Used by ChannelManager when no media engine is passed in to it
// explicitly (acts as a default).
MediaEngineInterface* WebRtcMediaEngineFactory::Create() {
return new cricket::WebRtcMediaEngine();
}
// Used by PeerConnectionFactory to create a media engine passed into
// ChannelManager.
MediaEngineInterface* WebRtcMediaEngineFactory::Create(
webrtc::AudioDeviceModule* adm,
webrtc::AudioDeviceModule* adm_sc,
WebRtcVideoEncoderFactory* encoder_factory,
WebRtcVideoDecoderFactory* decoder_factory) {
return CreateWebRtcMediaEngine(adm, adm_sc, encoder_factory, decoder_factory);
}
} // namespace cricket
#endif // defined(LIBPEERCONNECTION_LIB) ||
// defined(LIBPEERCONNECTION_IMPLEMENTATION)
|
/*
* libjingle
* Copyright 2014 Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
#if defined(LIBPEERCONNECTION_LIB) || defined(LIBPEERCONNECTION_IMPLEMENTATION)
#include "talk/media/webrtc/webrtcmediaengine.h"
#include "talk/media/webrtc/webrtcvideoengine.h"
#include "talk/media/webrtc/webrtcvideoengine2.h"
#include "talk/media/webrtc/webrtcvoiceengine.h"
#include "webrtc/system_wrappers/interface/field_trial.h"
namespace cricket {
class WebRtcMediaEngine
: public CompositeMediaEngine<WebRtcVoiceEngine, WebRtcVideoEngine> {
public:
WebRtcMediaEngine() {}
WebRtcMediaEngine(webrtc::AudioDeviceModule* adm,
webrtc::AudioDeviceModule* adm_sc,
WebRtcVideoEncoderFactory* encoder_factory,
WebRtcVideoDecoderFactory* decoder_factory) {
voice_.SetAudioDeviceModule(adm, adm_sc);
video_.SetExternalEncoderFactory(encoder_factory);
video_.SetExternalDecoderFactory(decoder_factory);
}
};
class WebRtcMediaEngine2
: public CompositeMediaEngine<WebRtcVoiceEngine, WebRtcVideoEngine2> {
public:
WebRtcMediaEngine2(webrtc::AudioDeviceModule* adm,
webrtc::AudioDeviceModule* adm_sc,
WebRtcVideoEncoderFactory* encoder_factory,
WebRtcVideoDecoderFactory* decoder_factory) {
voice_.SetAudioDeviceModule(adm, adm_sc);
video_.SetExternalDecoderFactory(decoder_factory);
video_.SetExternalEncoderFactory(encoder_factory);
}
};
} // namespace cricket
WRME_EXPORT
cricket::MediaEngineInterface* CreateWebRtcMediaEngine(
webrtc::AudioDeviceModule* adm,
webrtc::AudioDeviceModule* adm_sc,
cricket::WebRtcVideoEncoderFactory* encoder_factory,
cricket::WebRtcVideoDecoderFactory* decoder_factory) {
if (webrtc::field_trial::FindFullName("WebRTC-NewVideoAPI") == "Disabled") {
return new cricket::WebRtcMediaEngine(adm, adm_sc, encoder_factory,
decoder_factory);
}
return new cricket::WebRtcMediaEngine2(adm, adm_sc, encoder_factory,
decoder_factory);
}
WRME_EXPORT
void DestroyWebRtcMediaEngine(cricket::MediaEngineInterface* media_engine) {
delete media_engine;
}
namespace cricket {
// Used by ChannelManager when no media engine is passed in to it
// explicitly (acts as a default).
MediaEngineInterface* WebRtcMediaEngineFactory::Create() {
return new cricket::WebRtcMediaEngine();
}
// Used by PeerConnectionFactory to create a media engine passed into
// ChannelManager.
MediaEngineInterface* WebRtcMediaEngineFactory::Create(
webrtc::AudioDeviceModule* adm,
webrtc::AudioDeviceModule* adm_sc,
WebRtcVideoEncoderFactory* encoder_factory,
WebRtcVideoDecoderFactory* decoder_factory) {
return CreateWebRtcMediaEngine(adm, adm_sc, encoder_factory, decoder_factory);
}
} // namespace cricket
#endif // defined(LIBPEERCONNECTION_LIB) ||
// defined(LIBPEERCONNECTION_IMPLEMENTATION)
|
Add field-trial flag to disable WebRtcVideoEngine2.
|
Add field-trial flag to disable WebRtcVideoEngine2.
BUG=chromium:475164
[email protected]
Review URL: https://webrtc-codereview.appspot.com/45059004
Cr-Original-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#8957}
Cr-Mirrored-From: https://chromium.googlesource.com/external/webrtc
Cr-Mirrored-Commit: 15cf019a0071c7b67af047ae826d6bb5fb8ca89e
|
C++
|
bsd-3-clause
|
sippet/talk,sippet/talk,sippet/talk,sippet/talk,sippet/talk
|
ca468021d9d5f0fbba4ace5de03840a1497776aa
|
src/search/SearchHandler.cpp
|
src/search/SearchHandler.cpp
|
/* SearchHandler.cpp
*
* Kubo Ryosuke
*/
#include "search/SearchHandler.hpp"
#include "search/Searcher.hpp"
#include "logger/Logger.hpp"
#include <iomanip>
namespace sunfish {
void LoggingSearchHandler::onStart(const Searcher&) {
}
void LoggingSearchHandler::onUpdatePV(const Searcher& searcher, const PV& pv, float elapsed, int depth, Score score) {
if (pv.size() == 0) {
LOG(warning) << "PV is empty.";
return;
}
auto& info = searcher.getInfo();
auto timeMilliSeconds = static_cast<uint32_t>(elapsed * 1e3);
auto realDepth = depth / Searcher::Depth1Ply;
OUT(info) << std::setw(2) << realDepth << ": "
<< std::setw(10) << info.nodes << ": "
<< std::setw(7) << timeMilliSeconds
<< pv.toString() << ": "
<< score;
}
void LoggingSearchHandler::onFailLow(const Searcher& searcher, const PV& pv, float elapsed, int depth, Score score) {
onUpdatePV(searcher, pv, elapsed, depth, score);
OUT(info) << "fail-low";
}
void LoggingSearchHandler::onFailHigh(const Searcher& searcher, const PV& pv, float elapsed, int depth, Score score) {
onUpdatePV(searcher, pv, elapsed, depth, score);
OUT(info) << "fail-high";
}
} // namespace sunfish
|
/* SearchHandler.cpp
*
* Kubo Ryosuke
*/
#include "search/SearchHandler.hpp"
#include "search/Searcher.hpp"
#include "logger/Logger.hpp"
#include <iomanip>
namespace sunfish {
void LoggingSearchHandler::onStart(const Searcher&) {
}
void LoggingSearchHandler::onUpdatePV(const Searcher& searcher, const PV& pv, float elapsed, int depth, Score score) {
if (pv.size() == 0) {
LOG(warning) << "PV is empty.";
return;
}
auto& info = searcher.getInfo();
auto timeMilliSeconds = static_cast<uint32_t>(elapsed * 1e3);
auto realDepth = depth / Searcher::Depth1Ply;
OUT(info) << std::setw(2) << realDepth << ": "
<< std::setw(10) << info.nodes << ": "
<< std::setw(7) << timeMilliSeconds << ' '
<< pv.toString() << ": "
<< score;
}
void LoggingSearchHandler::onFailLow(const Searcher& searcher, const PV& pv, float elapsed, int depth, Score score) {
onUpdatePV(searcher, pv, elapsed, depth, score);
OUT(info) << "fail-low";
}
void LoggingSearchHandler::onFailHigh(const Searcher& searcher, const PV& pv, float elapsed, int depth, Score score) {
onUpdatePV(searcher, pv, elapsed, depth, score);
OUT(info) << "fail-high";
}
} // namespace sunfish
|
Fix LoggingSearchHandler
|
Fix LoggingSearchHandler
|
C++
|
mit
|
sunfish-shogi/sunfish4,sunfish-shogi/sunfish4,sunfish-shogi/sunfish4,sunfish-shogi/sunfish4
|
3650d5ddd64e077695cf23533592e8d145fe5720
|
src/datasource_cache.cpp
|
src/datasource_cache.cpp
|
/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id: datasource_cache.cpp 23 2005-03-22 22:16:34Z pavlenko $
// mapnik
#include <mapnik/datasource_cache.hpp>
#include <mapnik/config_error.hpp>
// boost
#include <boost/version.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/algorithm/string.hpp>
// ltdl
#include <ltdl.h>
// stl
#include <algorithm>
#include <stdexcept>
namespace mapnik
{
using namespace std;
using namespace boost;
bool is_input_plugin (std::string const& filename)
{
return boost::algorithm::ends_with(filename,std::string(".input"));
}
datasource_cache::datasource_cache()
{
if (lt_dlinit()) throw std::runtime_error("lt_dlinit() failed");
}
datasource_cache::~datasource_cache()
{
lt_dlexit();
}
std::map<string,boost::shared_ptr<PluginInfo> > datasource_cache::plugins_;
bool datasource_cache::registered_=false;
datasource_ptr datasource_cache::create(const parameters& params)
{
boost::optional<std::string> type = params.get<std::string>("type");
if ( ! type)
{
throw config_error(string("Could not create datasource. Required ") +
"parameter 'type' is missing");
}
datasource_ptr ds;
map<string,boost::shared_ptr<PluginInfo> >::iterator itr=plugins_.find(*type);
if ( itr == plugins_.end() )
{
throw config_error(string("Could not create datasource. No plugin ") +
"found for type '" + * type + "'");
}
if ( ! itr->second->handle())
{
throw std::runtime_error(string("Cannot load library: ") +
lt_dlerror());
}
create_ds* create_datasource =
(create_ds*) lt_dlsym(itr->second->handle(), "create");
if ( ! create_datasource)
{
throw std::runtime_error(string("Cannot load symbols: ") +
lt_dlerror());
}
#ifdef MAPNIK_DEBUG
std::clog << "size = " << params.size() << "\n";
parameters::const_iterator i = params.begin();
for (;i!=params.end();++i)
{
std::clog << i->first << "=" << i->second << "\n";
}
#endif
ds=datasource_ptr(create_datasource(params), datasource_deleter());
#ifdef MAPNIK_DEBUG
std::clog<<"datasource="<<ds<<" type="<<type<<std::endl;
#endif
return ds;
}
bool datasource_cache::insert(const std::string& type,const lt_dlhandle module)
{
return plugins_.insert(make_pair(type,boost::shared_ptr<PluginInfo>
(new PluginInfo(type,module)))).second;
}
std::vector<std::string> datasource_cache::plugin_names ()
{
std::vector<std::string> names;
std::map<std::string,boost::shared_ptr<PluginInfo> >::const_iterator itr;
for (itr = plugins_.begin();itr!=plugins_.end();++itr)
{
names.push_back(itr->first);
}
return names;
}
void datasource_cache::register_datasources(const std::string& str)
{
#ifdef MAPNIK_THREADSAFE
mutex::scoped_lock lock(mapnik::singleton<mapnik::datasource_cache,
mapnik::CreateStatic>::mutex_);
#endif
filesystem::path path(str);
filesystem::directory_iterator end_itr;
if (exists(path) && is_directory(path))
{
for (filesystem::directory_iterator itr(path);itr!=end_itr;++itr )
{
#if BOOST_VERSION < 103400
if (!is_directory( *itr ) && is_input_plugin(itr->leaf()))
#else
if (!is_directory( *itr ) && is_input_plugin(itr->path().leaf()))
#endif
{
try
{
lt_dlhandle module=lt_dlopen(itr->string().c_str());
if (module)
{
datasource_name* ds_name =
(datasource_name*) lt_dlsym(module, "datasource_name");
if (ds_name && insert(ds_name(),module))
{
#ifdef MAPNIK_DEBUG
std::clog << "registered datasource : " << ds_name() << std::endl;
#endif
registered_=true;
}
}
else
{
std::clog << "plugin" << ds_name() << ": " << lt_dlerror() << "\n" << std::endl;
}
}
catch (...) {}
}
}
}
}
}
|
/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id: datasource_cache.cpp 23 2005-03-22 22:16:34Z pavlenko $
// mapnik
#include <mapnik/datasource_cache.hpp>
#include <mapnik/config_error.hpp>
// boost
#include <boost/version.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/algorithm/string.hpp>
// ltdl
#include <ltdl.h>
// stl
#include <algorithm>
#include <stdexcept>
namespace mapnik
{
using namespace std;
using namespace boost;
bool is_input_plugin (std::string const& filename)
{
return boost::algorithm::ends_with(filename,std::string(".input"));
}
datasource_cache::datasource_cache()
{
if (lt_dlinit()) throw std::runtime_error("lt_dlinit() failed");
}
datasource_cache::~datasource_cache()
{
lt_dlexit();
}
std::map<string,boost::shared_ptr<PluginInfo> > datasource_cache::plugins_;
bool datasource_cache::registered_=false;
datasource_ptr datasource_cache::create(const parameters& params)
{
boost::optional<std::string> type = params.get<std::string>("type");
if ( ! type)
{
throw config_error(string("Could not create datasource. Required ") +
"parameter 'type' is missing");
}
datasource_ptr ds;
map<string,boost::shared_ptr<PluginInfo> >::iterator itr=plugins_.find(*type);
if ( itr == plugins_.end() )
{
throw config_error(string("Could not create datasource. No plugin ") +
"found for type '" + * type + "'");
}
if ( ! itr->second->handle())
{
throw std::runtime_error(string("Cannot load library: ") +
lt_dlerror());
}
create_ds* create_datasource =
(create_ds*) lt_dlsym(itr->second->handle(), "create");
if ( ! create_datasource)
{
throw std::runtime_error(string("Cannot load symbols: ") +
lt_dlerror());
}
#ifdef MAPNIK_DEBUG
std::clog << "size = " << params.size() << "\n";
parameters::const_iterator i = params.begin();
for (;i!=params.end();++i)
{
std::clog << i->first << "=" << i->second << "\n";
}
#endif
ds=datasource_ptr(create_datasource(params), datasource_deleter());
#ifdef MAPNIK_DEBUG
std::clog<<"datasource="<<ds<<" type="<<type<<std::endl;
#endif
return ds;
}
bool datasource_cache::insert(const std::string& type,const lt_dlhandle module)
{
return plugins_.insert(make_pair(type,boost::shared_ptr<PluginInfo>
(new PluginInfo(type,module)))).second;
}
std::vector<std::string> datasource_cache::plugin_names ()
{
std::vector<std::string> names;
std::map<std::string,boost::shared_ptr<PluginInfo> >::const_iterator itr;
for (itr = plugins_.begin();itr!=plugins_.end();++itr)
{
names.push_back(itr->first);
}
return names;
}
void datasource_cache::register_datasources(const std::string& str)
{
#ifdef MAPNIK_THREADSAFE
mutex::scoped_lock lock(mapnik::singleton<mapnik::datasource_cache,
mapnik::CreateStatic>::mutex_);
#endif
filesystem::path path(str);
filesystem::directory_iterator end_itr;
if (exists(path) && is_directory(path))
{
for (filesystem::directory_iterator itr(path);itr!=end_itr;++itr )
{
#if BOOST_VERSION < 103400
if (!is_directory( *itr ) && is_input_plugin(itr->leaf()))
#else
if (!is_directory( *itr ) && is_input_plugin(itr->path().leaf()))
#endif
{
try
{
lt_dlhandle module=lt_dlopen(itr->string().c_str());
if (module)
{
datasource_name* ds_name =
(datasource_name*) lt_dlsym(module, "datasource_name");
if (ds_name && insert(ds_name(),module))
{
#ifdef MAPNIK_DEBUG
std::clog << "registered datasource : " << ds_name() << std::endl;
#endif
registered_=true;
}
}
else
{
std::clog << "plugin" << itr->string().c_str() << ": " << lt_dlerror() << "\n" << std::endl;
}
}
catch (...) {}
}
}
}
}
}
|
fix scope issue in previous commit
|
fix scope issue in previous commit
git-svn-id: 5adfda8227e14e59fd47d5bd9925a30df16fed74@1182 d397654b-2ff0-0310-9e29-ba003691a0f9
|
C++
|
lgpl-2.1
|
craigds/mapnik2,craigds/mapnik2,makinacorpus/mapnik2,makinacorpus/mapnik2,makinacorpus/mapnik2,craigds/mapnik2,makinacorpus/mapnik2,craigds/mapnik2
|
f49ec8023fbe7f42bf94eb6970f89331f79fb822
|
max-points-on-a-line.cpp
|
max-points-on-a-line.cpp
|
class Solution {
public:
int maxPoints(vector<Point> &points) {
int maxCount = 0;
for(int i = 0; i != points.size(); ++i){
for(int j = 0; j < i; ++j){
int count = 0;
for(int k = 0; k != points.size(); ++k){
if(k != i && k !=j){
if(points[i].x == points[j].x){
if(points[k].x == points[i].x) count ++;
}
else if(points[i].y == points[j].y){
if(points[k].y == points[i].y) count ++;
}
else{
if((points[k].y-points[i].y)/(points[j].y-points[i].y)-(points[k].x-points[i].x)/(points[j].x-points[i].x) == 0) count ++;
}
}
}
if(count > maxCount) maxCount = count;
}
}
return maxCount;
}
};
|
class Solution {
public:
int maxPoints(vector<Point> &points) {
int maxCount = 0;
if(points.size() == 0) return maxCount;
for(int i = 0; i != points.size(); ++i){
int count = 0, n = 0;
unordered_map<double, int> umap;
for(int j = 0; j != points.size(); ++j){
int dx = points[j].x - points[i].x;
int dy = points[j].y - points[i].y;
double slope = std::numeric_limits<double>::infinity();
if(dx == 0 && dy == 0){n ++; continue;}
else if(dx != 0) slope = ((double)dy)/dx;
int tmp = 0;
if(umap.find(slope) != umap.end()) tmp = umap[slope];
umap[slope] = tmp + 1;
if(count < tmp + 1) count = tmp + 1;
}
if(maxCount < count + n) maxCount = count + n;
}
return maxCount;
}
};
|
add a O(n^2*lgn) solution, accepted
|
add a O(n^2*lgn) solution, accepted
|
C++
|
mit
|
mengjiaowang/leetcode
|
c6cd57b9ed176597f0aac08ee6d21438187695e8
|
tests/openssl_async_echo_server.cc
|
tests/openssl_async_echo_server.cc
|
//
// openssl_async_echo_server.cc
//
// clang++ -std=c++11 openssl_async_echo_server.cc -lcrypto -lssl -o openssl_async_echo_server
//
// * example of non-blocking TLS
// * probably leaks
// * tested with boringssl
//
#include <netdb.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/poll.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstdio>
#include <cstdarg>
#include <cstring>
#include <cerrno>
#include <csignal>
#include <vector>
#include <map>
#include <algorithm>
#include <openssl/crypto.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
static int listen_port = 8443;
static int listen_backlog = 128;
static const char* ssl_cert_file = "ssl/cert.pem";
static const char* ssl_key_file = "ssl/key.pem";
enum ssl_state
{
ssl_none,
ssl_handshake_read,
ssl_handshake_write,
ssl_app_read,
ssl_app_write
};
static const char* state_names[] =
{
"ssl_none",
"ssl_handshake_read",
"ssl_handshake_write",
"ssl_app_read",
"ssl_app_write"
};
struct ssl_connection
{
ssl_connection(int conn_fd, SSL *ssl, BIO *sbio)
: conn_fd(conn_fd), ssl(ssl), sbio(sbio), state(ssl_none) {}
ssl_connection(const ssl_connection &o)
: conn_fd(o.conn_fd), ssl(o.ssl), sbio(o.sbio), state(o.state) {}
int conn_fd;
SSL *ssl;
BIO *sbio;
ssl_state state;
};
void log_prefix(const char* prefix, const char* fmt, va_list args)
{
std::vector<char> buf(256);
int len = vsnprintf(buf.data(), buf.capacity(), fmt, args);
if (len >= (int)buf.capacity()) {
buf.resize(len + 1);
vsnprintf(buf.data(), buf.capacity(), fmt, args);
}
fprintf(stderr, "%s: %s\n", prefix, buf.data());
}
void log_fatal_exit(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
log_prefix("fatal", fmt, args);
va_end(args);
exit(9);
}
void log_error(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
log_prefix("error", fmt, args);
va_end(args);
}
void log_debug(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
log_prefix("debug", fmt, args);
va_end(args);
}
static EVP_PKEY *load_key(BIO *bio_err, const char *file)
{
BIO *bio_key = BIO_new(BIO_s_file());
if (bio_key == NULL) return NULL;
if (BIO_read_filename(bio_key, file) <= 0) {
BIO_free(bio_key);
return NULL;
}
EVP_PKEY *key = PEM_read_bio_PrivateKey(bio_key, NULL, NULL, NULL);
BIO_free(bio_key);
return key;
}
static X509 *load_cert(BIO *bio_err, const char *file)
{
BIO *bio_cert = BIO_new(BIO_s_file());
if (bio_cert == NULL) return NULL;
if (BIO_read_filename(bio_cert, file) <= 0) {
BIO_free(bio_cert);
return NULL;
}
X509 *cert = PEM_read_bio_X509_AUX(bio_cert, NULL, NULL, NULL);
BIO_free(bio_cert);
return cert;
}
void update_state(struct pollfd &pfd, ssl_connection &ssl_conn, int events, ssl_state new_state)
{
log_debug("conn_fd=%d %s -> %s",
pfd.fd, state_names[ssl_conn.state], state_names[new_state]);
ssl_conn.state = new_state;
pfd.events = events;
}
void update_state(struct pollfd &pfd, ssl_connection &ssl_conn, int ssl_err)
{
switch (ssl_err) {
case SSL_ERROR_WANT_READ:
update_state(pfd, ssl_conn, POLLIN, ssl_handshake_read);
break;
case SSL_ERROR_WANT_WRITE:
update_state(pfd, ssl_conn, POLLOUT, ssl_handshake_write);
break;
default:
break;
}
}
int main(int argc, char **argv)
{
BIO *bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
SSL_CTX *ctx = SSL_CTX_new(TLSv1_server_method());
X509 *cert = load_cert(bio_err, ssl_cert_file);
if (cert) {
log_debug("loaded cert: %s", ssl_cert_file);
} else {
BIO_print_errors(bio_err);
log_fatal_exit("error loading certificate: %s", ssl_cert_file);
}
if (SSL_CTX_use_certificate(ctx, cert) <= 0) {
BIO_print_errors(bio_err);
log_fatal_exit("error using certificate");
}
EVP_PKEY *key = load_key(bio_err, ssl_key_file);
if (key) {
log_debug("loaded key: %s", ssl_key_file);
} else {
BIO_print_errors(bio_err);
log_fatal_exit("error loading private key: %s", ssl_key_file);
}
if (SSL_CTX_use_PrivateKey(ctx, key) <= 0) {
BIO_print_errors(bio_err);
log_fatal_exit("error using private key");
}
sockaddr_in saddr;
memset(&saddr, 0, sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_port = htons(listen_port);
saddr.sin_addr.s_addr = INADDR_ANY;
int listen_fd = socket(AF_INET, SOCK_STREAM, 0);
if (listen_fd < 0) {
log_fatal_exit("socket failed: %s", strerror(errno));
}
int reuse = 1;
if (setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, (void *)&reuse, sizeof(reuse)) < 0) {
log_fatal_exit("setsockopt(SOL_SOCKET, SO_REUSEADDR) failed: %s", strerror(errno));
}
if (fcntl(listen_fd, F_SETFD, FD_CLOEXEC) < 0) {
log_fatal_exit("fcntl(F_SETFD, FD_CLOEXEC) failed: %s", strerror(errno));
}
if (fcntl(listen_fd, F_SETFL, O_NONBLOCK) < 0) {
log_fatal_exit("fcntl(F_SETFL, O_NONBLOCK) failed: %s", strerror(errno));
}
socklen_t addr_size = sizeof(sockaddr_in);
if (bind(listen_fd, (struct sockaddr *) &saddr, addr_size) < 0) {
log_fatal_exit("bind failed: %s", strerror(errno));
}
if (listen(listen_fd, (int)listen_backlog) < 0) {
log_fatal_exit("listen failed: %s", strerror(errno));
}
char saddr_name[32];
inet_ntop(saddr.sin_family, (void*)&saddr.sin_addr, saddr_name, sizeof(saddr_name));
log_debug("listening on: %s:%d", saddr_name, ntohs(saddr.sin_port));
char buf[16384];
int buf_len = 0;
std::vector<struct pollfd> poll_vec;
std::map<int,ssl_connection> ssl_connection_map;
poll_vec.push_back({listen_fd, POLLIN, 0});
while (true) {
retry:
int ret = poll(&poll_vec[0], (int)poll_vec.size(), -1);
if (ret < 0 && (errno != EAGAIN || errno != EINTR))
{
log_error("poll failed: %s", strerror(errno));
exit(9);
}
for (size_t i = 0; i < poll_vec.size(); i++)
{
if (poll_vec[i].fd == listen_fd && poll_vec[i].revents & POLLIN)
{
sockaddr_in paddr;
char paddr_name[32];
int conn_fd = accept(listen_fd, (struct sockaddr *) &paddr, &addr_size);
inet_ntop(paddr.sin_family, (void*)&paddr.sin_addr, paddr_name, sizeof(paddr_name));
log_debug("accepted connection from: %s:%d fd=%d",
paddr_name, ntohs(paddr.sin_port), conn_fd);
SSL *ssl = SSL_new(ctx);
SSL_set_fd(ssl, conn_fd);
SSL_set_accept_state(ssl);
auto si = ssl_connection_map.insert(std::pair<int,ssl_connection>
(conn_fd, ssl_connection(conn_fd, ssl, NULL /*sbio */)));
ssl_connection &ssl_conn = si.first->second;
poll_vec.push_back({conn_fd, POLLIN, 0});
size_t ni = poll_vec.size() - 1;
int ret = SSL_do_handshake(ssl_conn.ssl);
if (ret < 0) {
int ssl_err = SSL_get_error(ssl_conn.ssl, ret);
update_state(poll_vec[ni], ssl_conn, ssl_err);
}
continue;
}
int conn_fd = poll_vec[i].fd;
auto si = ssl_connection_map.find(conn_fd);
if (si == ssl_connection_map.end()) continue;
ssl_connection &ssl_conn = si->second;
if ((poll_vec[i].revents & POLLHUP) || (poll_vec[i].revents & POLLERR))
{
log_debug("connection closed");
SSL_free(ssl_conn.ssl);
close(ssl_conn.conn_fd);
auto pi = std::find_if(poll_vec.begin(), poll_vec.end(), [conn_fd] (const struct pollfd &pfd){
return pfd.fd == conn_fd;
});
if (pi != poll_vec.end()) {
poll_vec.erase(pi);
}
}
else if (ssl_conn.state == ssl_handshake_read && poll_vec[i].revents & POLLIN)
{
int ret = SSL_do_handshake(ssl_conn.ssl);
if (ret < 0) {
int ssl_err = SSL_get_error(ssl_conn.ssl, ret);
update_state(poll_vec[i], ssl_conn, ssl_err);
} else {
update_state(poll_vec[i], ssl_conn, POLLIN, ssl_app_read);
}
}
else if (ssl_conn.state == ssl_handshake_write && poll_vec[i].revents & POLLOUT)
{
int ret = SSL_do_handshake(ssl_conn.ssl);
if (ret < 0) {
int ssl_err = SSL_get_error(ssl_conn.ssl, ret);
update_state(poll_vec[i], ssl_conn, ssl_err);
} else {
update_state(poll_vec[i], ssl_conn, POLLIN, ssl_app_read);
}
}
else if (ssl_conn.state == ssl_app_read && poll_vec[i].revents & POLLIN)
{
int ret = SSL_read(ssl_conn.ssl, buf, sizeof(buf) - 1);
if (ret < 0) {
int ssl_err = SSL_get_error(ssl_conn.ssl, ret);
update_state(poll_vec[i], ssl_conn, ssl_err);
} else {
buf_len = ret;
buf[buf_len] = '\0';
printf("received: %s", buf);
update_state(poll_vec[i], ssl_conn, POLLOUT, ssl_app_write);
}
}
else if (ssl_conn.state == ssl_app_write && poll_vec[i].revents & POLLOUT)
{
int ret = SSL_write(ssl_conn.ssl, buf, buf_len);
if (ret < 0) {
int ssl_err = SSL_get_error(ssl_conn.ssl, ret);
update_state(poll_vec[i], ssl_conn, ssl_err);
} else {
printf("sent: %s", buf);
update_state(poll_vec[i], ssl_conn, POLLIN, ssl_app_read);
}
}
}
}
return 0;
}
|
//
// openssl_async_echo_server.cc
//
// clang++ -std=c++11 openssl_async_echo_server.cc -lcrypto -lssl -o openssl_async_echo_server
//
// * example of non-blocking TLS
// * probably leaks
// * tested with boringssl
//
#include <netdb.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/poll.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstdio>
#include <cstdarg>
#include <cstring>
#include <cerrno>
#include <csignal>
#include <vector>
#include <map>
#include <algorithm>
#include <openssl/crypto.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
static int listen_port = 8443;
static int listen_backlog = 128;
static const char* ssl_cert_file = "ssl/cert.pem";
static const char* ssl_key_file = "ssl/key.pem";
enum ssl_state
{
ssl_none,
ssl_handshake_read,
ssl_handshake_write,
ssl_app_read,
ssl_app_write
};
static const char* state_names[] =
{
"ssl_none",
"ssl_handshake_read",
"ssl_handshake_write",
"ssl_app_read",
"ssl_app_write"
};
struct ssl_connection
{
ssl_connection(int conn_fd, SSL *ssl, BIO *sbio)
: conn_fd(conn_fd), ssl(ssl), sbio(sbio), state(ssl_none) {}
ssl_connection(const ssl_connection &o)
: conn_fd(o.conn_fd), ssl(o.ssl), sbio(o.sbio), state(o.state) {}
int conn_fd;
SSL *ssl;
BIO *sbio;
ssl_state state;
};
void log_prefix(const char* prefix, const char* fmt, va_list args)
{
std::vector<char> buf(256);
int len = vsnprintf(buf.data(), buf.capacity(), fmt, args);
if (len >= (int)buf.capacity()) {
buf.resize(len + 1);
vsnprintf(buf.data(), buf.capacity(), fmt, args);
}
fprintf(stderr, "%s: %s\n", prefix, buf.data());
}
void log_fatal_exit(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
log_prefix("fatal", fmt, args);
va_end(args);
exit(9);
}
void log_error(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
log_prefix("error", fmt, args);
va_end(args);
}
void log_debug(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
log_prefix("debug", fmt, args);
va_end(args);
}
static EVP_PKEY *load_key(BIO *bio_err, const char *file)
{
BIO *bio_key = BIO_new(BIO_s_file());
if (bio_key == NULL) return NULL;
if (BIO_read_filename(bio_key, file) <= 0) {
BIO_free(bio_key);
return NULL;
}
EVP_PKEY *key = PEM_read_bio_PrivateKey(bio_key, NULL, NULL, NULL);
BIO_free(bio_key);
return key;
}
static X509 *load_cert(BIO *bio_err, const char *file)
{
BIO *bio_cert = BIO_new(BIO_s_file());
if (bio_cert == NULL) return NULL;
if (BIO_read_filename(bio_cert, file) <= 0) {
BIO_free(bio_cert);
return NULL;
}
X509 *cert = PEM_read_bio_X509_AUX(bio_cert, NULL, NULL, NULL);
BIO_free(bio_cert);
return cert;
}
void update_state(struct pollfd &pfd, ssl_connection &ssl_conn, int events, ssl_state new_state)
{
log_debug("conn_fd=%d %s -> %s",
pfd.fd, state_names[ssl_conn.state], state_names[new_state]);
ssl_conn.state = new_state;
pfd.events = events;
}
void update_state(struct pollfd &pfd, ssl_connection &ssl_conn, int ssl_err)
{
switch (ssl_err) {
case SSL_ERROR_WANT_READ:
update_state(pfd, ssl_conn, POLLIN, ssl_handshake_read);
break;
case SSL_ERROR_WANT_WRITE:
update_state(pfd, ssl_conn, POLLOUT, ssl_handshake_write);
break;
default:
break;
}
}
int main(int argc, char **argv)
{
BIO *bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
SSL_CTX *ctx = SSL_CTX_new(TLSv1_server_method());
X509 *cert = load_cert(bio_err, ssl_cert_file);
if (cert) {
log_debug("loaded cert: %s", ssl_cert_file);
} else {
BIO_print_errors(bio_err);
log_fatal_exit("error loading certificate: %s", ssl_cert_file);
}
if (SSL_CTX_use_certificate(ctx, cert) <= 0) {
BIO_print_errors(bio_err);
log_fatal_exit("error using certificate");
}
EVP_PKEY *key = load_key(bio_err, ssl_key_file);
if (key) {
log_debug("loaded key: %s", ssl_key_file);
} else {
BIO_print_errors(bio_err);
log_fatal_exit("error loading private key: %s", ssl_key_file);
}
if (SSL_CTX_use_PrivateKey(ctx, key) <= 0) {
BIO_print_errors(bio_err);
log_fatal_exit("error using private key");
}
sockaddr_in saddr;
memset(&saddr, 0, sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_port = htons(listen_port);
saddr.sin_addr.s_addr = INADDR_ANY;
int listen_fd = socket(AF_INET, SOCK_STREAM, 0);
if (listen_fd < 0) {
log_fatal_exit("socket failed: %s", strerror(errno));
}
int reuse = 1;
if (setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, (void *)&reuse, sizeof(reuse)) < 0) {
log_fatal_exit("setsockopt(SOL_SOCKET, SO_REUSEADDR) failed: %s", strerror(errno));
}
if (fcntl(listen_fd, F_SETFD, FD_CLOEXEC) < 0) {
log_fatal_exit("fcntl(F_SETFD, FD_CLOEXEC) failed: %s", strerror(errno));
}
if (fcntl(listen_fd, F_SETFL, O_NONBLOCK) < 0) {
log_fatal_exit("fcntl(F_SETFL, O_NONBLOCK) failed: %s", strerror(errno));
}
socklen_t addr_size = sizeof(sockaddr_in);
if (bind(listen_fd, (struct sockaddr *) &saddr, addr_size) < 0) {
log_fatal_exit("bind failed: %s", strerror(errno));
}
if (listen(listen_fd, (int)listen_backlog) < 0) {
log_fatal_exit("listen failed: %s", strerror(errno));
}
char saddr_name[32];
inet_ntop(saddr.sin_family, (void*)&saddr.sin_addr, saddr_name, sizeof(saddr_name));
log_debug("listening on: %s:%d", saddr_name, ntohs(saddr.sin_port));
char buf[16384];
int buf_len = 0;
std::vector<struct pollfd> poll_vec;
std::map<int,ssl_connection> ssl_connection_map;
poll_vec.push_back({listen_fd, POLLIN, 0});
while (true) {
int ret = poll(&poll_vec[0], (int)poll_vec.size(), -1);
if (ret < 0 && (errno != EAGAIN || errno != EINTR))
{
log_error("poll failed: %s", strerror(errno));
exit(9);
}
for (size_t i = 0; i < poll_vec.size(); i++)
{
if (poll_vec[i].fd == listen_fd && poll_vec[i].revents & POLLIN)
{
sockaddr_in paddr;
char paddr_name[32];
int conn_fd = accept(listen_fd, (struct sockaddr *) &paddr, &addr_size);
inet_ntop(paddr.sin_family, (void*)&paddr.sin_addr, paddr_name, sizeof(paddr_name));
log_debug("accepted connection from: %s:%d fd=%d",
paddr_name, ntohs(paddr.sin_port), conn_fd);
SSL *ssl = SSL_new(ctx);
SSL_set_fd(ssl, conn_fd);
SSL_set_accept_state(ssl);
auto si = ssl_connection_map.insert(std::pair<int,ssl_connection>
(conn_fd, ssl_connection(conn_fd, ssl, NULL /*sbio */)));
ssl_connection &ssl_conn = si.first->second;
poll_vec.push_back({conn_fd, POLLIN, 0});
size_t ni = poll_vec.size() - 1;
int ret = SSL_do_handshake(ssl_conn.ssl);
if (ret < 0) {
int ssl_err = SSL_get_error(ssl_conn.ssl, ret);
update_state(poll_vec[ni], ssl_conn, ssl_err);
}
continue;
}
int conn_fd = poll_vec[i].fd;
auto si = ssl_connection_map.find(conn_fd);
if (si == ssl_connection_map.end()) continue;
ssl_connection &ssl_conn = si->second;
if ((poll_vec[i].revents & POLLHUP) || (poll_vec[i].revents & POLLERR))
{
log_debug("connection closed");
SSL_free(ssl_conn.ssl);
close(ssl_conn.conn_fd);
auto pi = std::find_if(poll_vec.begin(), poll_vec.end(), [conn_fd] (const struct pollfd &pfd){
return pfd.fd == conn_fd;
});
if (pi != poll_vec.end()) {
poll_vec.erase(pi);
}
}
else if (ssl_conn.state == ssl_handshake_read && poll_vec[i].revents & POLLIN)
{
int ret = SSL_do_handshake(ssl_conn.ssl);
if (ret < 0) {
int ssl_err = SSL_get_error(ssl_conn.ssl, ret);
update_state(poll_vec[i], ssl_conn, ssl_err);
} else {
update_state(poll_vec[i], ssl_conn, POLLIN, ssl_app_read);
}
}
else if (ssl_conn.state == ssl_handshake_write && poll_vec[i].revents & POLLOUT)
{
int ret = SSL_do_handshake(ssl_conn.ssl);
if (ret < 0) {
int ssl_err = SSL_get_error(ssl_conn.ssl, ret);
update_state(poll_vec[i], ssl_conn, ssl_err);
} else {
update_state(poll_vec[i], ssl_conn, POLLIN, ssl_app_read);
}
}
else if (ssl_conn.state == ssl_app_read && poll_vec[i].revents & POLLIN)
{
int ret = SSL_read(ssl_conn.ssl, buf, sizeof(buf) - 1);
if (ret < 0) {
int ssl_err = SSL_get_error(ssl_conn.ssl, ret);
update_state(poll_vec[i], ssl_conn, ssl_err);
} else {
buf_len = ret;
buf[buf_len] = '\0';
printf("received: %s", buf);
update_state(poll_vec[i], ssl_conn, POLLOUT, ssl_app_write);
}
}
else if (ssl_conn.state == ssl_app_write && poll_vec[i].revents & POLLOUT)
{
int ret = SSL_write(ssl_conn.ssl, buf, buf_len);
if (ret < 0) {
int ssl_err = SSL_get_error(ssl_conn.ssl, ret);
update_state(poll_vec[i], ssl_conn, ssl_err);
} else {
printf("sent: %s", buf);
update_state(poll_vec[i], ssl_conn, POLLIN, ssl_app_read);
}
}
}
}
return 0;
}
|
remove unused label
|
remove unused label
|
C++
|
isc
|
metaparadigm/latypus,metaparadigm/latypus,metaparadigm/latypus,metaparadigm/latypus
|
3369910b5a9884e687cf1e46a87be6c65c31812d
|
q3/qs/src/ui/theme.cpp
|
q3/qs/src/ui/theme.cpp
|
/*
* $Id$
*
* Copyright(C) 1998-2004 Satoshi Nakamura
* All rights reserved.
*
*/
#ifndef _WIN32_WCE
#include <qstheme.h>
#include <uxtheme.h>
using namespace qs;
/****************************************************************************
*
* ThemeImpl
*
*/
struct qs::ThemeImpl
{
HINSTANCE hInstUxTheme_;
HTHEME hTheme_;
};
/****************************************************************************
*
* Theme
*
*/
qs::Theme::Theme(HWND hwnd,
const WCHAR* pwszClasses) :
pImpl_(0)
{
pImpl_ = new ThemeImpl();
pImpl_->hInstUxTheme_ = 0;
pImpl_->hTheme_ = 0;
pImpl_->hInstUxTheme_ = ::LoadLibrary(L"uxtheme.dll");
if (pImpl_->hInstUxTheme_) {
typedef BOOL (WINAPI *PFN_ISTHEMEACTIVE)();
PFN_ISTHEMEACTIVE pfnIsThemeActive = reinterpret_cast<PFN_ISTHEMEACTIVE>(
::GetProcAddress(pImpl_->hInstUxTheme_, "IsThemeActive"));
if ((*pfnIsThemeActive)()) {
typedef HTHEME (WINAPI *PFN_OPENTHEMEDATA)(HWND, LPCWSTR);
PFN_OPENTHEMEDATA pfnOpenThemeData = reinterpret_cast<PFN_OPENTHEMEDATA>(
::GetProcAddress(pImpl_->hInstUxTheme_, "OpenThemeData"));
pImpl_->hTheme_ = (*pfnOpenThemeData)(hwnd, pwszClasses);
}
}
}
qs::Theme::~Theme()
{
if (pImpl_->hInstUxTheme_) {
if (pImpl_->hTheme_) {
typedef HRESULT (WINAPI *PFN_CLOSETHEMEDATA)(HTHEME);
PFN_CLOSETHEMEDATA pfnCloseThemeData = reinterpret_cast<PFN_CLOSETHEMEDATA>(
::GetProcAddress(pImpl_->hInstUxTheme_, "CloseThemeData"));
(*pfnCloseThemeData)(pImpl_->hTheme_);
}
::FreeLibrary(pImpl_->hInstUxTheme_);
}
delete pImpl_;
}
bool qs::Theme::isActive() const
{
return pImpl_->hTheme_ != 0;
}
bool qs::Theme::drawBackground(HDC hdc,
int nPartId,
int nStateId,
const RECT& rect,
const RECT* pRectClip)
{
if (!pImpl_->hTheme_)
return false;
typedef HRESULT (WINAPI *PFN_DRAWTHEMEBACKGROUND)(HTHEME, HDC, int, int, const RECT*, const RECT*);
PFN_DRAWTHEMEBACKGROUND pfnDrawThemeBackground = reinterpret_cast<PFN_DRAWTHEMEBACKGROUND>(
::GetProcAddress(pImpl_->hInstUxTheme_, "DrawThemeBackground"));
return (*pfnDrawThemeBackground)(pImpl_->hTheme_, hdc, nPartId, nStateId, &rect, pRectClip) == S_OK;
}
bool qs::Theme::drawEdge(HDC hdc,
int nPartId,
int nStateId,
const RECT& rect,
UINT nEdge,
UINT nFlags,
RECT* pRect)
{
if (!pImpl_->hTheme_)
return false;
typedef HRESULT (WINAPI *PFN_DRAWTHEMEEDGE)(HTHEME, HDC, int, int, const RECT*, UINT, UINT, RECT*);
PFN_DRAWTHEMEEDGE pfnDrawThemeEdge = reinterpret_cast<PFN_DRAWTHEMEEDGE>(
::GetProcAddress(pImpl_->hInstUxTheme_, "DrawThemeEdge"));
return (*pfnDrawThemeEdge)(pImpl_->hTheme_, hdc, nPartId, nStateId, &rect, nEdge, nFlags, pRect) == S_OK;
}
int qs::Theme::getSysSize(int nId)
{
if (!pImpl_->hTheme_)
return ::GetSystemMetrics(nId);
typedef int (WINAPI *PFN_GETTHEMESYSSIZE)(HTHEME, int);
PFN_GETTHEMESYSSIZE pfnGetThemeSysSize = reinterpret_cast<PFN_GETTHEMESYSSIZE>(
::GetProcAddress(pImpl_->hInstUxTheme_, "GetThemeSysSize"));
return (*pfnGetThemeSysSize)(pImpl_->hTheme_, nId) == S_OK;
}
#endif // _WIN32_WCE
|
/*
* $Id$
*
* Copyright(C) 1998-2004 Satoshi Nakamura
* All rights reserved.
*
*/
#ifndef _WIN32_WCE
#include <qstheme.h>
#include <tchar.h>
#include <uxtheme.h>
using namespace qs;
/****************************************************************************
*
* ThemeImpl
*
*/
struct qs::ThemeImpl
{
HINSTANCE hInstUxTheme_;
HTHEME hTheme_;
};
/****************************************************************************
*
* Theme
*
*/
qs::Theme::Theme(HWND hwnd,
const WCHAR* pwszClasses) :
pImpl_(0)
{
pImpl_ = new ThemeImpl();
pImpl_->hInstUxTheme_ = 0;
pImpl_->hTheme_ = 0;
pImpl_->hInstUxTheme_ = ::LoadLibrary(_T("uxtheme.dll"));
if (pImpl_->hInstUxTheme_) {
typedef BOOL (WINAPI *PFN_ISTHEMEACTIVE)();
PFN_ISTHEMEACTIVE pfnIsThemeActive = reinterpret_cast<PFN_ISTHEMEACTIVE>(
::GetProcAddress(pImpl_->hInstUxTheme_, "IsThemeActive"));
if ((*pfnIsThemeActive)()) {
typedef HTHEME (WINAPI *PFN_OPENTHEMEDATA)(HWND, LPCWSTR);
PFN_OPENTHEMEDATA pfnOpenThemeData = reinterpret_cast<PFN_OPENTHEMEDATA>(
::GetProcAddress(pImpl_->hInstUxTheme_, "OpenThemeData"));
pImpl_->hTheme_ = (*pfnOpenThemeData)(hwnd, pwszClasses);
}
}
}
qs::Theme::~Theme()
{
if (pImpl_->hInstUxTheme_) {
if (pImpl_->hTheme_) {
typedef HRESULT (WINAPI *PFN_CLOSETHEMEDATA)(HTHEME);
PFN_CLOSETHEMEDATA pfnCloseThemeData = reinterpret_cast<PFN_CLOSETHEMEDATA>(
::GetProcAddress(pImpl_->hInstUxTheme_, "CloseThemeData"));
(*pfnCloseThemeData)(pImpl_->hTheme_);
}
::FreeLibrary(pImpl_->hInstUxTheme_);
}
delete pImpl_;
}
bool qs::Theme::isActive() const
{
return pImpl_->hTheme_ != 0;
}
bool qs::Theme::drawBackground(HDC hdc,
int nPartId,
int nStateId,
const RECT& rect,
const RECT* pRectClip)
{
if (!pImpl_->hTheme_)
return false;
typedef HRESULT (WINAPI *PFN_DRAWTHEMEBACKGROUND)(HTHEME, HDC, int, int, const RECT*, const RECT*);
PFN_DRAWTHEMEBACKGROUND pfnDrawThemeBackground = reinterpret_cast<PFN_DRAWTHEMEBACKGROUND>(
::GetProcAddress(pImpl_->hInstUxTheme_, "DrawThemeBackground"));
return (*pfnDrawThemeBackground)(pImpl_->hTheme_, hdc, nPartId, nStateId, &rect, pRectClip) == S_OK;
}
bool qs::Theme::drawEdge(HDC hdc,
int nPartId,
int nStateId,
const RECT& rect,
UINT nEdge,
UINT nFlags,
RECT* pRect)
{
if (!pImpl_->hTheme_)
return false;
typedef HRESULT (WINAPI *PFN_DRAWTHEMEEDGE)(HTHEME, HDC, int, int, const RECT*, UINT, UINT, RECT*);
PFN_DRAWTHEMEEDGE pfnDrawThemeEdge = reinterpret_cast<PFN_DRAWTHEMEEDGE>(
::GetProcAddress(pImpl_->hInstUxTheme_, "DrawThemeEdge"));
return (*pfnDrawThemeEdge)(pImpl_->hTheme_, hdc, nPartId, nStateId, &rect, nEdge, nFlags, pRect) == S_OK;
}
int qs::Theme::getSysSize(int nId)
{
if (!pImpl_->hTheme_)
return ::GetSystemMetrics(nId);
typedef int (WINAPI *PFN_GETTHEMESYSSIZE)(HTHEME, int);
PFN_GETTHEMESYSSIZE pfnGetThemeSysSize = reinterpret_cast<PFN_GETTHEMESYSSIZE>(
::GetProcAddress(pImpl_->hInstUxTheme_, "GetThemeSysSize"));
return (*pfnGetThemeSysSize)(pImpl_->hTheme_, nId) == S_OK;
}
#endif // _WIN32_WCE
|
Fix for ANSI version.
|
Fix for ANSI version.
git-svn-id: 12ae5aeef08fd453d75833463da4cc20df82a94e@816 8af8166b-12a6-a448-a533-9086ace3f9f6
|
C++
|
mit
|
snakamura/q3,snakamura/q3,snakamura/q3,snakamura/q3,snakamura/q3,snakamura/q3,snakamura/q3,snakamura/q3,snakamura/q3
|
b34655ae0527dd112024e8ec9729e3fefa12f901
|
modules/map/hdmap/adapter/xml_parser/signals_xml_parser.cc
|
modules/map/hdmap/adapter/xml_parser/signals_xml_parser.cc
|
/* Copyright 2017 The Apollo Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
#include "modules/map/hdmap/adapter/xml_parser/signals_xml_parser.h"
#include <iomanip>
#include <string>
#include <vector>
#include "modules/map/hdmap/adapter/xml_parser/util_xml_parser.h"
namespace apollo {
namespace hdmap {
namespace adapter {
Status SignalsXmlParser::ParseTrafficLights(
const tinyxml2::XMLElement& xml_node,
std::vector<TrafficLightInternal>* traffic_lights) {
CHECK_NOTNULL(traffic_lights);
auto signal_node = xml_node.FirstChildElement("signal");
while (signal_node) {
std::string object_type;
std::string object_id;
int checker =
UtilXmlParser::QueryStringAttribute(*signal_node, "type", &object_type);
checker +=
UtilXmlParser::QueryStringAttribute(*signal_node, "id", &object_id);
if (checker != tinyxml2::XML_SUCCESS) {
std::string err_msg = "Error parse signal type.";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
if (object_type == "trafficLight") {
PbSignal traffic_light;
traffic_light.mutable_id()->set_id(object_id);
std::string layout_type;
int checker = UtilXmlParser::QueryStringAttribute(
*signal_node, "layoutType", &layout_type);
if (checker != tinyxml2::XML_SUCCESS) {
std::string err_msg = "Error parse signal layout type.";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
PbSignalType signal_layout_type;
ToPbSignalType(layout_type, &signal_layout_type);
traffic_light.set_type(signal_layout_type);
PbPolygon* polygon = traffic_light.mutable_boundary();
auto outline_node = signal_node->FirstChildElement("outline");
if (outline_node == nullptr) {
std::string err_msg = "Error parse signal outline";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
RETURN_IF_ERROR(UtilXmlParser::ParseOutline(*outline_node, polygon));
auto sub_node = signal_node->FirstChildElement("subSignal");
if (sub_node == nullptr) {
std::string err_msg = "Error parse sub signal.";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
while (sub_node) {
std::string sub_signal_id;
std::string sub_signal_xml_type;
checker = UtilXmlParser::QueryStringAttribute(*sub_node, "type",
&sub_signal_xml_type);
checker += UtilXmlParser::QueryStringAttribute(*sub_node, "id",
&sub_signal_id);
if (checker != tinyxml2::XML_SUCCESS) {
std::string err_msg = "Error parse sub signal layout type.";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
PbSubSignal* sub_signal = traffic_light.add_subsignal();
PbSubSignalType sub_signal_type;
ToPbSubSignalType(sub_signal_xml_type, &sub_signal_type);
sub_signal->mutable_id()->set_id(sub_signal_id);
sub_signal->set_type(sub_signal_type);
PbPoint3D* pt = sub_signal->mutable_location();
RETURN_IF_ERROR(UtilXmlParser::ParsePoint(*sub_node, pt));
sub_node = sub_node->NextSiblingElement("subSignal");
}
TrafficLightInternal trafficlight_internal;
trafficlight_internal.id = object_id;
trafficlight_internal.traffic_light = traffic_light;
sub_node = signal_node->FirstChildElement("stopline");
if (sub_node) {
sub_node = sub_node->FirstChildElement("objectReference");
while (sub_node) {
std::string stop_line_id;
int checker = UtilXmlParser::QueryStringAttribute(*sub_node, "id",
&stop_line_id);
CHECK(checker == tinyxml2::XML_SUCCESS);
trafficlight_internal.stop_line_ids.insert(stop_line_id);
sub_node = sub_node->NextSiblingElement("objectReference");
}
}
traffic_lights->emplace_back(trafficlight_internal);
}
signal_node = signal_node->NextSiblingElement("signal");
}
return Status::OK();
}
Status SignalsXmlParser::ToPbSignalType(const std::string& xml_type,
PbSignalType* signal_type) {
CHECK_NOTNULL(signal_type);
std::string upper_str = UtilXmlParser::ToUpper(xml_type);
if (upper_str == "UNKNOWN") {
*signal_type = hdmap::Signal::UNKNOWN;
} else if (upper_str == "MIX2HORIZONTAL") {
*signal_type = hdmap::Signal::MIX_2_HORIZONTAL;
} else if (upper_str == "MIX2VERTICAL") {
*signal_type = hdmap::Signal::MIX_2_VERTICAL;
} else if (upper_str == "MIX3HORIZONTAL") {
*signal_type = hdmap::Signal::MIX_3_HORIZONTAL;
} else if (upper_str == "MIX3VERTICAL") {
*signal_type = hdmap::Signal::MIX_3_VERTICAL;
} else if (upper_str == "SINGLE") {
*signal_type = hdmap::Signal::SINGLE;
} else {
std::string err_msg = "Error or unsupport signal layout type";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
return Status::OK();
}
Status SignalsXmlParser::ToPbSubSignalType(const std::string& xml_type,
PbSubSignalType* sub_signal_type) {
CHECK_NOTNULL(sub_signal_type);
std::string upper_str = UtilXmlParser::ToUpper(xml_type);
if (upper_str == "UNKNOWN") {
*sub_signal_type = hdmap::Subsignal::UNKNOWN;
} else if (upper_str == "CIRCLE") {
*sub_signal_type = hdmap::Subsignal::CIRCLE;
} else if (upper_str == "ARROWLEFT") {
*sub_signal_type = hdmap::Subsignal::ARROW_LEFT;
} else if (upper_str == "ARROWFORWARD") {
*sub_signal_type = hdmap::Subsignal::ARROW_FORWARD;
} else if (upper_str == "ARROWRIGHT") {
*sub_signal_type = hdmap::Subsignal::ARROW_RIGHT;
} else if (upper_str == "ARROWLEFTANDFORWARD") {
*sub_signal_type = hdmap::Subsignal::ARROW_LEFT_AND_FORWARD;
} else if (upper_str == "ARROWRIGHTANDFORWARD") {
*sub_signal_type = hdmap::Subsignal::ARROW_RIGHT_AND_FORWARD;
} else if (upper_str == "ARROWUTURN") {
*sub_signal_type = hdmap::Subsignal::ARROW_U_TURN;
} else {
std::string err_msg = "Error or unsupport sub signal type";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
return Status::OK();
}
Status SignalsXmlParser::ParseStopSigns(
const tinyxml2::XMLElement& xml_node,
std::vector<StopSignInternal>* stop_signs) {
CHECK_NOTNULL(stop_signs);
auto signal_node = xml_node.FirstChildElement("signal");
while (signal_node) {
std::string object_type;
std::string object_id;
int checker =
UtilXmlParser::QueryStringAttribute(*signal_node, "type", &object_type);
checker +=
UtilXmlParser::QueryStringAttribute(*signal_node, "id", &object_id);
if (checker != tinyxml2::XML_SUCCESS) {
std::string err_msg = "Error parse signal type.";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
if (object_type == "stopSign") {
PbStopSign stop_sign;
stop_sign.mutable_id()->set_id(object_id);
StopSignInternal stop_sign_internal;
stop_sign_internal.stop_sign = stop_sign;
auto sub_node = signal_node->FirstChildElement("stopline");
if (sub_node) {
sub_node = sub_node->FirstChildElement("objectReference");
while (sub_node) {
std::string stop_line_id;
UtilXmlParser::QueryStringAttribute(*sub_node, "id", &stop_line_id);
CHECK(checker == tinyxml2::XML_SUCCESS);
stop_sign_internal.stop_line_ids.insert(stop_line_id);
sub_node = sub_node->NextSiblingElement("objectReference");
}
}
stop_signs->emplace_back(stop_sign_internal);
}
signal_node = signal_node->NextSiblingElement("signal");
}
return Status::OK();
}
Status SignalsXmlParser::ParseYieldSigns(
const tinyxml2::XMLElement& xml_node,
std::vector<YieldSignInternal>* yield_signs) {
CHECK_NOTNULL(yield_signs);
auto signal_node = xml_node.FirstChildElement("signal");
while (signal_node) {
std::string object_type;
std::string object_id;
int checker =
UtilXmlParser::QueryStringAttribute(*signal_node, "type", &object_type);
checker +=
UtilXmlParser::QueryStringAttribute(*signal_node, "id", &object_id);
if (checker != tinyxml2::XML_SUCCESS) {
std::string err_msg = "Error parse signal type.";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
if (object_type == "yieldSign") {
PbYieldSign yield_sign;
yield_sign.mutable_id()->set_id(object_id);
YieldSignInternal yield_sign_internal;
yield_sign_internal.id = object_id;
yield_sign_internal.yield_sign = yield_sign;
auto sub_node = signal_node->FirstChildElement("stopline");
if (sub_node) {
sub_node = sub_node->FirstChildElement("objectReference");
while (sub_node) {
std::string stop_line_id;
int checker = UtilXmlParser::QueryStringAttribute(*sub_node, "id",
&stop_line_id);
CHECK(checker == tinyxml2::XML_SUCCESS);
yield_sign_internal.stop_line_ids.insert(stop_line_id);
sub_node = sub_node->NextSiblingElement("objectReference");
}
}
yield_signs->emplace_back(yield_sign_internal);
}
signal_node = signal_node->NextSiblingElement("signal");
}
return Status::OK();
}
} // namespace adapter
} // namespace hdmap
} // namespace apollo
|
/* Copyright 2017 The Apollo Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
#include "modules/map/hdmap/adapter/xml_parser/signals_xml_parser.h"
#include <iomanip>
#include <string>
#include <vector>
#include "modules/map/hdmap/adapter/xml_parser/util_xml_parser.h"
namespace apollo {
namespace hdmap {
namespace adapter {
Status SignalsXmlParser::ParseTrafficLights(
const tinyxml2::XMLElement& xml_node,
std::vector<TrafficLightInternal>* traffic_lights) {
CHECK_NOTNULL(traffic_lights);
auto signal_node = xml_node.FirstChildElement("signal");
while (signal_node) {
std::string object_type;
std::string object_id;
int checker =
UtilXmlParser::QueryStringAttribute(*signal_node, "type", &object_type);
checker +=
UtilXmlParser::QueryStringAttribute(*signal_node, "id", &object_id);
if (checker != tinyxml2::XML_SUCCESS) {
std::string err_msg = "Error parse signal type.";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
if (object_type == "trafficLight") {
PbSignal traffic_light;
traffic_light.mutable_id()->set_id(object_id);
std::string layout_type;
int checker = UtilXmlParser::QueryStringAttribute(
*signal_node, "layoutType", &layout_type);
if (checker != tinyxml2::XML_SUCCESS) {
std::string err_msg = "Error parse signal layout type.";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
PbSignalType signal_layout_type;
ToPbSignalType(layout_type, &signal_layout_type);
traffic_light.set_type(signal_layout_type);
PbPolygon* polygon = traffic_light.mutable_boundary();
auto outline_node = signal_node->FirstChildElement("outline");
if (outline_node == nullptr) {
std::string err_msg = "Error parse signal outline";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
RETURN_IF_ERROR(UtilXmlParser::ParseOutline(*outline_node, polygon));
auto sub_node = signal_node->FirstChildElement("subSignal");
if (sub_node == nullptr) {
std::string err_msg = "Error parse sub signal.";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
while (sub_node) {
std::string sub_signal_id;
std::string sub_signal_xml_type;
checker = UtilXmlParser::QueryStringAttribute(*sub_node, "type",
&sub_signal_xml_type);
checker += UtilXmlParser::QueryStringAttribute(*sub_node, "id",
&sub_signal_id);
if (checker != tinyxml2::XML_SUCCESS) {
std::string err_msg = "Error parse sub signal layout type.";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
PbSubSignal* sub_signal = traffic_light.add_subsignal();
PbSubSignalType sub_signal_type;
ToPbSubSignalType(sub_signal_xml_type, &sub_signal_type);
sub_signal->mutable_id()->set_id(sub_signal_id);
sub_signal->set_type(sub_signal_type);
PbPoint3D* pt = sub_signal->mutable_location();
RETURN_IF_ERROR(UtilXmlParser::ParsePoint(*sub_node, pt));
sub_node = sub_node->NextSiblingElement("subSignal");
}
TrafficLightInternal trafficlight_internal;
trafficlight_internal.id = object_id;
trafficlight_internal.traffic_light = traffic_light;
sub_node = signal_node->FirstChildElement("stopline");
if (sub_node) {
sub_node = sub_node->FirstChildElement("objectReference");
while (sub_node) {
std::string stop_line_id;
int checker = UtilXmlParser::QueryStringAttribute(*sub_node, "id",
&stop_line_id);
CHECK(checker == tinyxml2::XML_SUCCESS);
trafficlight_internal.stop_line_ids.insert(stop_line_id);
sub_node = sub_node->NextSiblingElement("objectReference");
}
}
traffic_lights->emplace_back(trafficlight_internal);
}
signal_node = signal_node->NextSiblingElement("signal");
}
return Status::OK();
}
Status SignalsXmlParser::ToPbSignalType(const std::string& xml_type,
PbSignalType* signal_type) {
CHECK_NOTNULL(signal_type);
std::string upper_str = UtilXmlParser::ToUpper(xml_type);
if (upper_str == "UNKNOWN") {
*signal_type = hdmap::Signal::UNKNOWN;
} else if (upper_str == "MIX2HORIZONTAL") {
*signal_type = hdmap::Signal::MIX_2_HORIZONTAL;
} else if (upper_str == "MIX2VERTICAL") {
*signal_type = hdmap::Signal::MIX_2_VERTICAL;
} else if (upper_str == "MIX3HORIZONTAL") {
*signal_type = hdmap::Signal::MIX_3_HORIZONTAL;
} else if (upper_str == "MIX3VERTICAL") {
*signal_type = hdmap::Signal::MIX_3_VERTICAL;
} else if (upper_str == "SINGLE") {
*signal_type = hdmap::Signal::SINGLE;
} else {
std::string err_msg = "Error or unsupport signal layout type";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
return Status::OK();
}
Status SignalsXmlParser::ToPbSubSignalType(const std::string& xml_type,
PbSubSignalType* sub_signal_type) {
CHECK_NOTNULL(sub_signal_type);
std::string upper_str = UtilXmlParser::ToUpper(xml_type);
if (upper_str == "UNKNOWN") {
*sub_signal_type = hdmap::Subsignal::UNKNOWN;
} else if (upper_str == "CIRCLE") {
*sub_signal_type = hdmap::Subsignal::CIRCLE;
} else if (upper_str == "ARROWLEFT") {
*sub_signal_type = hdmap::Subsignal::ARROW_LEFT;
} else if (upper_str == "ARROWFORWARD") {
*sub_signal_type = hdmap::Subsignal::ARROW_FORWARD;
} else if (upper_str == "ARROWRIGHT") {
*sub_signal_type = hdmap::Subsignal::ARROW_RIGHT;
} else if (upper_str == "ARROWLEFTANDFORWARD") {
*sub_signal_type = hdmap::Subsignal::ARROW_LEFT_AND_FORWARD;
} else if (upper_str == "ARROWRIGHTANDFORWARD") {
*sub_signal_type = hdmap::Subsignal::ARROW_RIGHT_AND_FORWARD;
} else if (upper_str == "ARROWUTURN") {
*sub_signal_type = hdmap::Subsignal::ARROW_U_TURN;
} else {
std::string err_msg = "Error or unsupport sub signal type";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
return Status::OK();
}
Status SignalsXmlParser::ParseStopSigns(
const tinyxml2::XMLElement& xml_node,
std::vector<StopSignInternal>* stop_signs) {
CHECK_NOTNULL(stop_signs);
auto signal_node = xml_node.FirstChildElement("signal");
while (signal_node) {
std::string object_type;
std::string object_id;
int checker =
UtilXmlParser::QueryStringAttribute(*signal_node, "type", &object_type);
checker +=
UtilXmlParser::QueryStringAttribute(*signal_node, "id", &object_id);
if (checker != tinyxml2::XML_SUCCESS) {
std::string err_msg = "Error parse signal type.";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
if (object_type == "stopSign") {
PbStopSign stop_sign;
stop_sign.mutable_id()->set_id(object_id);
StopSignInternal stop_sign_internal;
stop_sign_internal.stop_sign = stop_sign;
auto sub_node = signal_node->FirstChildElement("stopline");
if (sub_node) {
sub_node = sub_node->FirstChildElement("objectReference");
while (sub_node) {
std::string stop_line_id;
int checker = UtilXmlParser::QueryStringAttribute(*sub_node, "id", &stop_line_id);
CHECK(checker == tinyxml2::XML_SUCCESS);
stop_sign_internal.stop_line_ids.insert(stop_line_id);
sub_node = sub_node->NextSiblingElement("objectReference");
}
}
stop_signs->emplace_back(stop_sign_internal);
}
signal_node = signal_node->NextSiblingElement("signal");
}
return Status::OK();
}
Status SignalsXmlParser::ParseYieldSigns(
const tinyxml2::XMLElement& xml_node,
std::vector<YieldSignInternal>* yield_signs) {
CHECK_NOTNULL(yield_signs);
auto signal_node = xml_node.FirstChildElement("signal");
while (signal_node) {
std::string object_type;
std::string object_id;
int checker =
UtilXmlParser::QueryStringAttribute(*signal_node, "type", &object_type);
checker +=
UtilXmlParser::QueryStringAttribute(*signal_node, "id", &object_id);
if (checker != tinyxml2::XML_SUCCESS) {
std::string err_msg = "Error parse signal type.";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
if (object_type == "yieldSign") {
PbYieldSign yield_sign;
yield_sign.mutable_id()->set_id(object_id);
YieldSignInternal yield_sign_internal;
yield_sign_internal.id = object_id;
yield_sign_internal.yield_sign = yield_sign;
auto sub_node = signal_node->FirstChildElement("stopline");
if (sub_node) {
sub_node = sub_node->FirstChildElement("objectReference");
while (sub_node) {
std::string stop_line_id;
int checker = UtilXmlParser::QueryStringAttribute(*sub_node, "id",
&stop_line_id);
CHECK(checker == tinyxml2::XML_SUCCESS);
yield_sign_internal.stop_line_ids.insert(stop_line_id);
sub_node = sub_node->NextSiblingElement("objectReference");
}
}
yield_signs->emplace_back(yield_sign_internal);
}
signal_node = signal_node->NextSiblingElement("signal");
}
return Status::OK();
}
} // namespace adapter
} // namespace hdmap
} // namespace apollo
|
Fix bug in xml parser (#3090)
|
Fix bug in xml parser (#3090)
Signed-off-by: Yu Ding <[email protected]>
|
C++
|
apache-2.0
|
startcode/apollo,startcode/apollo,startcode/apollo,startcode/apollo,startcode/apollo,startcode/apollo
|
134af6b6d2639033b32e23cecc651f26466e584c
|
src/gpu/vk/GrVkUniformHandler.cpp
|
src/gpu/vk/GrVkUniformHandler.cpp
|
/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrVkUniformHandler.h"
#include "glsl/GrGLSLProgramBuilder.h"
// To determine whether a current offset is aligned, we can just 'and' the lowest bits with the
// alignment mask. A value of 0 means aligned, any other value is how many bytes past alignment we
// are. This works since all alignments are powers of 2. The mask is always (alignment - 1).
// This alignment mask will give correct alignments for using the std430 block layout. If you want
// the std140 alignment, you can use this, but then make sure if you have an array type it is
// aligned to 16 bytes (i.e. has mask of 0xF).
uint32_t grsltype_to_alignment_mask(GrSLType type) {
SkASSERT(GrSLTypeIsFloatType(type));
static const uint32_t kAlignments[kGrSLTypeCount] = {
0x0, // kVoid_GrSLType, should never return this
0x3, // kFloat_GrSLType
0x7, // kVec2f_GrSLType
0xF, // kVec3f_GrSLType
0xF, // kVec4f_GrSLType
0x7, // kMat22f_GrSLType
0xF, // kMat33f_GrSLType
0xF, // kMat44f_GrSLType
0x0, // Sampler2D_GrSLType, should never return this
0x0, // SamplerExternal_GrSLType, should never return this
};
GR_STATIC_ASSERT(0 == kVoid_GrSLType);
GR_STATIC_ASSERT(1 == kFloat_GrSLType);
GR_STATIC_ASSERT(2 == kVec2f_GrSLType);
GR_STATIC_ASSERT(3 == kVec3f_GrSLType);
GR_STATIC_ASSERT(4 == kVec4f_GrSLType);
GR_STATIC_ASSERT(5 == kMat22f_GrSLType);
GR_STATIC_ASSERT(6 == kMat33f_GrSLType);
GR_STATIC_ASSERT(7 == kMat44f_GrSLType);
GR_STATIC_ASSERT(8 == kSampler2D_GrSLType);
GR_STATIC_ASSERT(9 == kSamplerExternal_GrSLType);
GR_STATIC_ASSERT(SK_ARRAY_COUNT(kAlignments) == kGrSLTypeCount);
return kAlignments[type];
}
/** Returns the size in bytes taken up in vulkanbuffers for floating point GrSLTypes.
For non floating point type returns 0 */
static inline uint32_t grsltype_to_vk_size(GrSLType type) {
SkASSERT(GrSLTypeIsFloatType(type));
SkASSERT(kMat22f_GrSLType != type); // TODO: handle mat2 differences between std140 and std430.
static const uint32_t kSizes[] = {
0, // kVoid_GrSLType
sizeof(float), // kFloat_GrSLType
2 * sizeof(float), // kVec2f_GrSLType
3 * sizeof(float), // kVec3f_GrSLType
4 * sizeof(float), // kVec4f_GrSLType
8 * sizeof(float), // kMat22f_GrSLType. TODO: this will be 4 * szof(float) on std430.
12 * sizeof(float), // kMat33f_GrSLType
16 * sizeof(float), // kMat44f_GrSLType
0, // kSampler2D_GrSLType
0, // kSamplerExternal_GrSLType
0, // kSampler2DRect_GrSLType
0, // kBool_GrSLType
0, // kInt_GrSLType
0, // kUint_GrSLType
};
return kSizes[type];
GR_STATIC_ASSERT(0 == kVoid_GrSLType);
GR_STATIC_ASSERT(1 == kFloat_GrSLType);
GR_STATIC_ASSERT(2 == kVec2f_GrSLType);
GR_STATIC_ASSERT(3 == kVec3f_GrSLType);
GR_STATIC_ASSERT(4 == kVec4f_GrSLType);
GR_STATIC_ASSERT(5 == kMat22f_GrSLType);
GR_STATIC_ASSERT(6 == kMat33f_GrSLType);
GR_STATIC_ASSERT(7 == kMat44f_GrSLType);
GR_STATIC_ASSERT(8 == kSampler2D_GrSLType);
GR_STATIC_ASSERT(9 == kSamplerExternal_GrSLType);
GR_STATIC_ASSERT(10 == kSampler2DRect_GrSLType);
GR_STATIC_ASSERT(11 == kBool_GrSLType);
GR_STATIC_ASSERT(12 == kInt_GrSLType);
GR_STATIC_ASSERT(13 == kUint_GrSLType);
GR_STATIC_ASSERT(SK_ARRAY_COUNT(kSizes) == kGrSLTypeCount);
}
// Given the current offset into the ubo, calculate the offset for the uniform we're trying to add
// taking into consideration all alignment requirements. The uniformOffset is set to the offset for
// the new uniform, and currentOffset is updated to be the offset to the end of the new uniform.
void get_ubo_aligned_offset(uint32_t* uniformOffset,
uint32_t* currentOffset,
GrSLType type,
int arrayCount) {
uint32_t alignmentMask = grsltype_to_alignment_mask(type);
// We want to use the std140 layout here, so we must make arrays align to 16 bytes.
SkASSERT(type != kMat22f_GrSLType); // TODO: support mat2.
if (arrayCount) {
alignmentMask = 0xF;
}
uint32_t offsetDiff = *currentOffset & alignmentMask;
if (offsetDiff != 0) {
offsetDiff = alignmentMask - offsetDiff + 1;
}
*uniformOffset = *currentOffset + offsetDiff;
SkASSERT(sizeof(float) == 4);
if (arrayCount) {
uint32_t elementSize = SkTMax<uint32_t>(16, grsltype_to_vk_size(type));
SkASSERT(0 == (elementSize & 0xF));
*currentOffset = *uniformOffset + elementSize * arrayCount;
} else {
*currentOffset = *uniformOffset + grsltype_to_vk_size(type);
}
}
GrGLSLUniformHandler::UniformHandle GrVkUniformHandler::internalAddUniformArray(
uint32_t visibility,
GrSLType type,
GrSLPrecision precision,
const char* name,
bool mangleName,
int arrayCount,
const char** outName) {
SkASSERT(name && strlen(name));
SkDEBUGCODE(static const uint32_t kVisibilityMask = kVertex_GrShaderFlag|kFragment_GrShaderFlag);
SkASSERT(0 == (~kVisibilityMask & visibility));
SkASSERT(0 != visibility);
SkASSERT(kDefault_GrSLPrecision == precision || GrSLTypeIsFloatType(type));
UniformInfo& uni = fUniforms.push_back();
uni.fVariable.setType(type);
// TODO this is a bit hacky, lets think of a better way. Basically we need to be able to use
// the uniform view matrix name in the GP, and the GP is immutable so it has to tell the PB
// exactly what name it wants to use for the uniform view matrix. If we prefix anythings, then
// the names will mismatch. I think the correct solution is to have all GPs which need the
// uniform view matrix, they should upload the view matrix in their setData along with regular
// uniforms.
char prefix = 'u';
if ('u' == name[0]) {
prefix = '\0';
}
fProgramBuilder->nameVariable(uni.fVariable.accessName(), prefix, name, mangleName);
uni.fVariable.setArrayCount(arrayCount);
// For now asserting the the visibility is either only vertex or only fragment
SkASSERT(kVertex_GrShaderFlag == visibility || kFragment_GrShaderFlag == visibility);
uni.fVisibility = visibility;
uni.fVariable.setPrecision(precision);
if (GrSLTypeIsFloatType(type)) {
// When outputing the GLSL, only the outer uniform block will get the Uniform modifier. Thus
// we set the modifier to none for all uniforms declared inside the block.
uni.fVariable.setTypeModifier(GrGLSLShaderVar::kNone_TypeModifier);
uint32_t* currentOffset = kVertex_GrShaderFlag == visibility ? &fCurrentVertexUBOOffset
: &fCurrentFragmentUBOOffset;
get_ubo_aligned_offset(&uni.fUBOffset, currentOffset, type, arrayCount);
uni.fSetNumber = kUniformBufferDescSet;
uni.fBinding = kVertex_GrShaderFlag == visibility ? kVertexBinding : kFragBinding;
if (outName) {
*outName = uni.fVariable.c_str();
}
} else {
SkASSERT(type == kSampler2D_GrSLType);
uni.fVariable.setTypeModifier(GrGLSLShaderVar::kUniform_TypeModifier);
uni.fSetNumber = kSamplerDescSet;
uni.fBinding = fCurrentSamplerBinding++;
uni.fUBOffset = 0; // This value will be ignored, but initializing to avoid any errors.
SkString layoutQualifier;
layoutQualifier.appendf("set=%d, binding=%d", uni.fSetNumber, uni.fBinding);
uni.fVariable.setLayoutQualifier(layoutQualifier.c_str());
}
return GrGLSLUniformHandler::UniformHandle(fUniforms.count() - 1);
}
void GrVkUniformHandler::appendUniformDecls(GrShaderFlags visibility, SkString* out) const {
SkTArray<UniformInfo*> uniformBufferUniform;
// Used to collect all the variables that will be place inside the uniform buffer
SkString uniformsString;
SkASSERT(kVertex_GrShaderFlag == visibility || kFragment_GrShaderFlag == visibility);
uint32_t uniformBinding = (visibility == kVertex_GrShaderFlag) ? kVertexBinding : kFragBinding;
for (int i = 0; i < fUniforms.count(); ++i) {
const UniformInfo& localUniform = fUniforms[i];
if (visibility == localUniform.fVisibility) {
if (GrSLTypeIsFloatType(localUniform.fVariable.getType())) {
SkASSERT(uniformBinding == localUniform.fBinding);
SkASSERT(kUniformBufferDescSet == localUniform.fSetNumber);
localUniform.fVariable.appendDecl(fProgramBuilder->glslCaps(), &uniformsString);
uniformsString.append(";\n");
} else {
SkASSERT(localUniform.fVariable.getType() == kSampler2D_GrSLType);
SkASSERT(kSamplerDescSet == localUniform.fSetNumber);
localUniform.fVariable.appendDecl(fProgramBuilder->glslCaps(), out);
out->append(";\n");
}
}
}
if (!uniformsString.isEmpty()) {
const char* stage = (visibility == kVertex_GrShaderFlag) ? "vertex" : "fragment";
out->appendf("layout (set=%d, binding=%d) uniform %sUniformBuffer\n{\n",
kUniformBufferDescSet, uniformBinding, stage);
out->appendf("%s\n};\n", uniformsString.c_str());
}
}
|
/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrVkUniformHandler.h"
#include "glsl/GrGLSLProgramBuilder.h"
// To determine whether a current offset is aligned, we can just 'and' the lowest bits with the
// alignment mask. A value of 0 means aligned, any other value is how many bytes past alignment we
// are. This works since all alignments are powers of 2. The mask is always (alignment - 1).
// This alignment mask will give correct alignments for using the std430 block layout. If you want
// the std140 alignment, you can use this, but then make sure if you have an array type it is
// aligned to 16 bytes (i.e. has mask of 0xF).
uint32_t grsltype_to_alignment_mask(GrSLType type) {
SkASSERT(GrSLTypeIsFloatType(type));
static const uint32_t kAlignmentMask[] = {
0x0, // kVoid_GrSLType, should never return this
0x3, // kFloat_GrSLType
0x7, // kVec2f_GrSLType
0xF, // kVec3f_GrSLType
0xF, // kVec4f_GrSLType
0x7, // kMat22f_GrSLType
0xF, // kMat33f_GrSLType
0xF, // kMat44f_GrSLType
0x0, // Sampler2D_GrSLType, should never return this
0x0, // SamplerExternal_GrSLType, should never return this
0x0, // Sampler2DRect_GrSLType, should never return this
0x0, // SamplerBuffer_GrSLType, should never return this
0x0, // kBool_GrSLType
0x7, // kInt_GrSLType
0x7, // kUint_GrSLType
};
GR_STATIC_ASSERT(0 == kVoid_GrSLType);
GR_STATIC_ASSERT(1 == kFloat_GrSLType);
GR_STATIC_ASSERT(2 == kVec2f_GrSLType);
GR_STATIC_ASSERT(3 == kVec3f_GrSLType);
GR_STATIC_ASSERT(4 == kVec4f_GrSLType);
GR_STATIC_ASSERT(5 == kMat22f_GrSLType);
GR_STATIC_ASSERT(6 == kMat33f_GrSLType);
GR_STATIC_ASSERT(7 == kMat44f_GrSLType);
GR_STATIC_ASSERT(8 == kSampler2D_GrSLType);
GR_STATIC_ASSERT(9 == kSamplerExternal_GrSLType);
GR_STATIC_ASSERT(10 == kSampler2DRect_GrSLType);
GR_STATIC_ASSERT(11 == kSamplerBuffer_GrSLType);
GR_STATIC_ASSERT(12 == kBool_GrSLType);
GR_STATIC_ASSERT(13 == kInt_GrSLType);
GR_STATIC_ASSERT(14 == kUint_GrSLType);
GR_STATIC_ASSERT(SK_ARRAY_COUNT(kAlignmentMask) == kGrSLTypeCount);
return kAlignmentMask[type];
}
/** Returns the size in bytes taken up in vulkanbuffers for floating point GrSLTypes.
For non floating point type returns 0 */
static inline uint32_t grsltype_to_vk_size(GrSLType type) {
SkASSERT(GrSLTypeIsFloatType(type));
SkASSERT(kMat22f_GrSLType != type); // TODO: handle mat2 differences between std140 and std430.
static const uint32_t kSizes[] = {
0, // kVoid_GrSLType
sizeof(float), // kFloat_GrSLType
2 * sizeof(float), // kVec2f_GrSLType
3 * sizeof(float), // kVec3f_GrSLType
4 * sizeof(float), // kVec4f_GrSLType
8 * sizeof(float), // kMat22f_GrSLType. TODO: this will be 4 * szof(float) on std430.
12 * sizeof(float), // kMat33f_GrSLType
16 * sizeof(float), // kMat44f_GrSLType
0, // kSampler2D_GrSLType
0, // kSamplerExternal_GrSLType
0, // kSampler2DRect_GrSLType
0, // kSamplerBuffer_GrSLType
1, // kBool_GrSLType
4, // kInt_GrSLType
4 // kUint_GrSLType
};
return kSizes[type];
GR_STATIC_ASSERT(0 == kVoid_GrSLType);
GR_STATIC_ASSERT(1 == kFloat_GrSLType);
GR_STATIC_ASSERT(2 == kVec2f_GrSLType);
GR_STATIC_ASSERT(3 == kVec3f_GrSLType);
GR_STATIC_ASSERT(4 == kVec4f_GrSLType);
GR_STATIC_ASSERT(5 == kMat22f_GrSLType);
GR_STATIC_ASSERT(6 == kMat33f_GrSLType);
GR_STATIC_ASSERT(7 == kMat44f_GrSLType);
GR_STATIC_ASSERT(8 == kSampler2D_GrSLType);
GR_STATIC_ASSERT(9 == kSamplerExternal_GrSLType);
GR_STATIC_ASSERT(10 == kSampler2DRect_GrSLType);
GR_STATIC_ASSERT(11 == kSamplerBuffer_GrSLType);
GR_STATIC_ASSERT(12 == kBool_GrSLType);
GR_STATIC_ASSERT(13 == kInt_GrSLType);
GR_STATIC_ASSERT(14 == kUint_GrSLType);
GR_STATIC_ASSERT(SK_ARRAY_COUNT(kSizes) == kGrSLTypeCount);
}
// Given the current offset into the ubo, calculate the offset for the uniform we're trying to add
// taking into consideration all alignment requirements. The uniformOffset is set to the offset for
// the new uniform, and currentOffset is updated to be the offset to the end of the new uniform.
void get_ubo_aligned_offset(uint32_t* uniformOffset,
uint32_t* currentOffset,
GrSLType type,
int arrayCount) {
uint32_t alignmentMask = grsltype_to_alignment_mask(type);
// We want to use the std140 layout here, so we must make arrays align to 16 bytes.
SkASSERT(type != kMat22f_GrSLType); // TODO: support mat2.
if (arrayCount) {
alignmentMask = 0xF;
}
uint32_t offsetDiff = *currentOffset & alignmentMask;
if (offsetDiff != 0) {
offsetDiff = alignmentMask - offsetDiff + 1;
}
*uniformOffset = *currentOffset + offsetDiff;
SkASSERT(sizeof(float) == 4);
if (arrayCount) {
uint32_t elementSize = SkTMax<uint32_t>(16, grsltype_to_vk_size(type));
SkASSERT(0 == (elementSize & 0xF));
*currentOffset = *uniformOffset + elementSize * arrayCount;
} else {
*currentOffset = *uniformOffset + grsltype_to_vk_size(type);
}
}
GrGLSLUniformHandler::UniformHandle GrVkUniformHandler::internalAddUniformArray(
uint32_t visibility,
GrSLType type,
GrSLPrecision precision,
const char* name,
bool mangleName,
int arrayCount,
const char** outName) {
SkASSERT(name && strlen(name));
SkDEBUGCODE(static const uint32_t kVisibilityMask = kVertex_GrShaderFlag|kFragment_GrShaderFlag);
SkASSERT(0 == (~kVisibilityMask & visibility));
SkASSERT(0 != visibility);
SkASSERT(kDefault_GrSLPrecision == precision || GrSLTypeIsFloatType(type));
UniformInfo& uni = fUniforms.push_back();
uni.fVariable.setType(type);
// TODO this is a bit hacky, lets think of a better way. Basically we need to be able to use
// the uniform view matrix name in the GP, and the GP is immutable so it has to tell the PB
// exactly what name it wants to use for the uniform view matrix. If we prefix anythings, then
// the names will mismatch. I think the correct solution is to have all GPs which need the
// uniform view matrix, they should upload the view matrix in their setData along with regular
// uniforms.
char prefix = 'u';
if ('u' == name[0]) {
prefix = '\0';
}
fProgramBuilder->nameVariable(uni.fVariable.accessName(), prefix, name, mangleName);
uni.fVariable.setArrayCount(arrayCount);
// For now asserting the the visibility is either only vertex or only fragment
SkASSERT(kVertex_GrShaderFlag == visibility || kFragment_GrShaderFlag == visibility);
uni.fVisibility = visibility;
uni.fVariable.setPrecision(precision);
if (GrSLTypeIsFloatType(type)) {
// When outputing the GLSL, only the outer uniform block will get the Uniform modifier. Thus
// we set the modifier to none for all uniforms declared inside the block.
uni.fVariable.setTypeModifier(GrGLSLShaderVar::kNone_TypeModifier);
uint32_t* currentOffset = kVertex_GrShaderFlag == visibility ? &fCurrentVertexUBOOffset
: &fCurrentFragmentUBOOffset;
get_ubo_aligned_offset(&uni.fUBOffset, currentOffset, type, arrayCount);
uni.fSetNumber = kUniformBufferDescSet;
uni.fBinding = kVertex_GrShaderFlag == visibility ? kVertexBinding : kFragBinding;
if (outName) {
*outName = uni.fVariable.c_str();
}
} else {
SkASSERT(type == kSampler2D_GrSLType);
uni.fVariable.setTypeModifier(GrGLSLShaderVar::kUniform_TypeModifier);
uni.fSetNumber = kSamplerDescSet;
uni.fBinding = fCurrentSamplerBinding++;
uni.fUBOffset = 0; // This value will be ignored, but initializing to avoid any errors.
SkString layoutQualifier;
layoutQualifier.appendf("set=%d, binding=%d", uni.fSetNumber, uni.fBinding);
uni.fVariable.setLayoutQualifier(layoutQualifier.c_str());
}
return GrGLSLUniformHandler::UniformHandle(fUniforms.count() - 1);
}
void GrVkUniformHandler::appendUniformDecls(GrShaderFlags visibility, SkString* out) const {
SkTArray<UniformInfo*> uniformBufferUniform;
// Used to collect all the variables that will be place inside the uniform buffer
SkString uniformsString;
SkASSERT(kVertex_GrShaderFlag == visibility || kFragment_GrShaderFlag == visibility);
uint32_t uniformBinding = (visibility == kVertex_GrShaderFlag) ? kVertexBinding : kFragBinding;
for (int i = 0; i < fUniforms.count(); ++i) {
const UniformInfo& localUniform = fUniforms[i];
if (visibility == localUniform.fVisibility) {
if (GrSLTypeIsFloatType(localUniform.fVariable.getType())) {
SkASSERT(uniformBinding == localUniform.fBinding);
SkASSERT(kUniformBufferDescSet == localUniform.fSetNumber);
localUniform.fVariable.appendDecl(fProgramBuilder->glslCaps(), &uniformsString);
uniformsString.append(";\n");
} else {
SkASSERT(localUniform.fVariable.getType() == kSampler2D_GrSLType);
SkASSERT(kSamplerDescSet == localUniform.fSetNumber);
localUniform.fVariable.appendDecl(fProgramBuilder->glslCaps(), out);
out->append(";\n");
}
}
}
if (!uniformsString.isEmpty()) {
const char* stage = (visibility == kVertex_GrShaderFlag) ? "vertex" : "fragment";
out->appendf("layout (set=%d, binding=%d) uniform %sUniformBuffer\n{\n",
kUniformBufferDescSet, uniformBinding, stage);
out->appendf("%s\n};\n", uniformsString.c_str());
}
}
|
Fix Vk build breakage due to new GrSLType
|
Fix Vk build breakage due to new GrSLType
[email protected]
GOLD_TRYBOT_URL= https://gold.skia.org/search2?unt=true&query=source_type%3Dgm&master=false&issue=1881033002
Review URL: https://codereview.chromium.org/1881033002
|
C++
|
bsd-3-clause
|
aosp-mirror/platform_external_skia,HalCanary/skia-hc,rubenvb/skia,Hikari-no-Tenshi/android_external_skia,tmpvar/skia.cc,Hikari-no-Tenshi/android_external_skia,rubenvb/skia,tmpvar/skia.cc,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,HalCanary/skia-hc,rubenvb/skia,google/skia,HalCanary/skia-hc,rubenvb/skia,tmpvar/skia.cc,aosp-mirror/platform_external_skia,google/skia,google/skia,tmpvar/skia.cc,HalCanary/skia-hc,aosp-mirror/platform_external_skia,rubenvb/skia,Hikari-no-Tenshi/android_external_skia,tmpvar/skia.cc,HalCanary/skia-hc,HalCanary/skia-hc,Hikari-no-Tenshi/android_external_skia,HalCanary/skia-hc,google/skia,aosp-mirror/platform_external_skia,rubenvb/skia,rubenvb/skia,Hikari-no-Tenshi/android_external_skia,aosp-mirror/platform_external_skia,rubenvb/skia,HalCanary/skia-hc,google/skia,tmpvar/skia.cc,google/skia,rubenvb/skia,HalCanary/skia-hc,tmpvar/skia.cc,Hikari-no-Tenshi/android_external_skia,tmpvar/skia.cc,google/skia,aosp-mirror/platform_external_skia,tmpvar/skia.cc,HalCanary/skia-hc,Hikari-no-Tenshi/android_external_skia,google/skia,google/skia,Hikari-no-Tenshi/android_external_skia,rubenvb/skia,google/skia,aosp-mirror/platform_external_skia
|
8113d2ce2b342d815ba8e5a6396619386067fd12
|
src/http/HttpOutputCompressor.cpp
|
src/http/HttpOutputCompressor.cpp
|
#include <xzero/http/HttpOutputCompressor.h>
#include <xzero/http/HttpOutputFilter.h>
#include <xzero/http/HttpOutput.h>
#include <xzero/http/HttpRequest.h>
#include <xzero/http/HttpResponse.h>
#include <xzero/Tokenizer.h>
#include <xzero/Buffer.h>
#include <algorithm>
#include <system_error>
#include <stdexcept>
#include <cstdlib>
#include <xzero/sysconfig.h>
#if defined(HAVE_ZLIB_H)
#include <zlib.h>
#endif
#if defined(HAVE_BZLIB_H)
#include <bzlib.h>
#endif
namespace xzero {
// {{{ HttpOutputCompressor::ZlibFilter
#if defined(HAVE_ZLIB_H)
class HttpOutputCompressor::ZlibFilter : public HttpOutputFilter {
public:
explicit ZlibFilter(int flags, int level);
~ZlibFilter();
void filter(const BufferRef& input, Buffer* output) override;
private:
z_stream z_;
};
HttpOutputCompressor::ZlibFilter::ZlibFilter(int flags, int level) {
z_.zalloc = Z_NULL;
z_.zfree = Z_NULL;
z_.opaque = Z_NULL;
int rv = deflateInit2(&z_,
level, // compression level
Z_DEFLATED, // method
flags, // window bits (15=gzip compression,
// 16=simple header, -15=raw deflate)
level, // memory level (1..9)
Z_FILTERED); // strategy
if (rv != Z_OK)
throw std::runtime_error("deflateInit2 failed.");
}
HttpOutputCompressor::ZlibFilter::~ZlibFilter() {
deflateEnd(&z_);
}
void HttpOutputCompressor::ZlibFilter::filter(const BufferRef& input,
Buffer* output) {
z_.total_out = 0;
z_.next_in = (Bytef*)input.cbegin();
z_.avail_in = input.size();
output->reserve(output->size() + input.size() * 1.1 + 12 + 18);
z_.next_out = (Bytef*)output->end();
z_.avail_out = output->capacity() - output->size();
do {
if (output->size() > output->capacity() / 2) {
output->reserve(output->capacity() + Buffer::CHUNK_SIZE);
z_.avail_out = output->capacity() - output->size();
}
const int rv = deflate(&z_, Z_SYNC_FLUSH); // or: Z_FINISH with Z_NO_FLUSH for non-last
if (rv != Z_OK) { // or: STREAM_END for last
switch (rv) {
case Z_NEED_DICT:
throw std::runtime_error("zlib dictionary needed.");
case Z_ERRNO:
throw std::system_error(errno, std::system_category());
case Z_STREAM_ERROR:
throw std::runtime_error("Invalid Zlib compression level.");
case Z_DATA_ERROR:
throw std::runtime_error("Invalid or incomplete deflate data.");
case Z_MEM_ERROR:
throw std::runtime_error("Zlib out of memory.");
case Z_BUF_ERROR:
throw std::runtime_error("Zlib buffer error.");
case Z_VERSION_ERROR:
throw std::runtime_error("Zlib version mismatch.");
default:
throw std::runtime_error("Unknown Zlib deflate() error.");
}
}
} while (z_.avail_out == 0);
assert(z_.avail_in == 0);
output->resize(z_.total_out);
}
#endif
// }}}
// {{{ HttpOutputCompressor::DeflateFilter
#if defined(HAVE_ZLIB_H)
class HttpOutputCompressor::DeflateFilter : public ZlibFilter {
public:
explicit DeflateFilter(int level) : ZlibFilter(-15 + 16, level) {}
};
#endif
// }}}
// {{{ HttpOutputCompressor::GzipFilter
#if defined(HAVE_ZLIB_H)
class HttpOutputCompressor::GzipFilter : public ZlibFilter {
public:
explicit GzipFilter(int level) : ZlibFilter(15 + 16, level) {}
};
#endif
// }}}
// {{{ HttpOutputCompressor
HttpOutputCompressor::HttpOutputCompressor()
: contentTypes_(), // no types
level_(9), // best compression
minSize_(256), // 256 byte
maxSize_(128 * 1024 * 1024) { // 128 MB
addMimeType("text/plain");
addMimeType("text/html");
addMimeType("text/css");
addMimeType("application/xml");
addMimeType("application/xhtml+xml");
}
HttpOutputCompressor::~HttpOutputCompressor() {
}
void HttpOutputCompressor::setMinSize(size_t value) {
minSize_ = value;
}
void HttpOutputCompressor::setMaxSize(size_t value) {
maxSize_ = value;
}
void HttpOutputCompressor::addMimeType(const std::string& value) {
contentTypes_[value] = 0;
}
bool HttpOutputCompressor::containsMimeType(const std::string& value) const {
return contentTypes_.find(value) != contentTypes_.end();
}
template<typename Encoder>
bool tryEncode(const std::string& encoding,
int level,
const std::vector<BufferRef>& accepts,
HttpRequest* request,
HttpResponse* response) {
if (std::find(accepts.begin(), accepts.end(), encoding) == accepts.end())
return false;
// response might change according to Accept-Encoding
response->appendHeader("Vary", "Accept-Encoding", ",");
// removing content-length implicitely enables chunked encoding
response->resetContentLength();
response->addHeader("Content-Encoding", encoding);
response->output()->addFilter(std::make_shared<Encoder>(level));
return true;
}
void HttpOutputCompressor::inject(HttpRequest* request,
HttpResponse* response) {
// TODO: ensure postProcess() gets invoked right before response commit
}
void HttpOutputCompressor::postProcess(HttpRequest* request,
HttpResponse* response) {
if (response->headers().contains("Content-Encoding"))
return; // do not double-encode content
bool chunked = !response->hasContentLength();
long long size = chunked ? 0 : response->contentLength();
if (!chunked && (size < minSize_ || size > maxSize_))
return;
if (!containsMimeType(response->headers().get("Content-Type")))
return;
const std::string& acceptEncoding = request->headers().get("Accept-Encoding");
BufferRef r(acceptEncoding);
if (!r.empty()) {
const auto items = Tokenizer<BufferRef, BufferRef>::tokenize(r, ", ");
// if (tryEncode<Bzip2Filter>("bzip2", level_, items, request, response))
// return;
if (tryEncode<GzipFilter>("gzip", level_, items, request, response))
return;
if (tryEncode<DeflateFilter>("deflate", level_, items, request, response))
return;
}
}
// }}}
} // namespace xzero
|
#include <xzero/http/HttpOutputCompressor.h>
#include <xzero/http/HttpOutputFilter.h>
#include <xzero/http/HttpOutput.h>
#include <xzero/http/HttpRequest.h>
#include <xzero/http/HttpResponse.h>
#include <xzero/Tokenizer.h>
#include <xzero/Buffer.h>
#include <algorithm>
#include <system_error>
#include <stdexcept>
#include <cstdlib>
#include <xzero/sysconfig.h>
#if defined(HAVE_ZLIB_H)
#include <zlib.h>
#endif
#if defined(HAVE_BZLIB_H)
#include <bzlib.h>
#endif
namespace xzero {
// {{{ HttpOutputCompressor::ZlibFilter
#if defined(HAVE_ZLIB_H)
class HttpOutputCompressor::ZlibFilter : public HttpOutputFilter {
public:
explicit ZlibFilter(int flags, int level);
~ZlibFilter();
void filter(const BufferRef& input, Buffer* output) override;
private:
z_stream z_;
};
HttpOutputCompressor::ZlibFilter::ZlibFilter(int flags, int level) {
z_.zalloc = Z_NULL;
z_.zfree = Z_NULL;
z_.opaque = Z_NULL;
int rv = deflateInit2(&z_,
level, // compression level
Z_DEFLATED, // method
flags, // window bits (15=gzip compression,
// 16=simple header, -15=raw deflate)
level, // memory level (1..9)
Z_FILTERED); // strategy
if (rv != Z_OK)
throw std::runtime_error("deflateInit2 failed.");
}
HttpOutputCompressor::ZlibFilter::~ZlibFilter() {
deflateEnd(&z_);
}
void HttpOutputCompressor::ZlibFilter::filter(const BufferRef& input,
Buffer* output) {
z_.total_out = 0;
z_.next_in = (Bytef*)input.cbegin();
z_.avail_in = input.size();
output->reserve(output->size() + input.size() * 1.1 + 12 + 18);
z_.next_out = (Bytef*)output->end();
z_.avail_out = output->capacity() - output->size();
do {
if (output->size() > output->capacity() / 2) {
output->reserve(output->capacity() + Buffer::CHUNK_SIZE);
z_.avail_out = output->capacity() - output->size();
}
const int rv = deflate(&z_, Z_SYNC_FLUSH); // or: Z_FINISH with Z_NO_FLUSH for non-last
if (rv != Z_OK) { // or: STREAM_END for last
switch (rv) {
case Z_NEED_DICT:
throw std::runtime_error("zlib dictionary needed.");
case Z_ERRNO:
throw std::system_error(errno, std::system_category());
case Z_STREAM_ERROR:
throw std::runtime_error("Invalid Zlib compression level.");
case Z_DATA_ERROR:
throw std::runtime_error("Invalid or incomplete deflate data.");
case Z_MEM_ERROR:
throw std::runtime_error("Zlib out of memory.");
case Z_BUF_ERROR:
throw std::runtime_error("Zlib buffer error.");
case Z_VERSION_ERROR:
throw std::runtime_error("Zlib version mismatch.");
default:
throw std::runtime_error("Unknown Zlib deflate() error.");
}
}
} while (z_.avail_out == 0);
assert(z_.avail_in == 0);
output->resize(z_.total_out);
}
#endif
// }}}
// {{{ HttpOutputCompressor::DeflateFilter
#if defined(HAVE_ZLIB_H)
class HttpOutputCompressor::DeflateFilter : public ZlibFilter {
public:
explicit DeflateFilter(int level) : ZlibFilter(-15 + 16, level) {}
};
#endif
// }}}
// {{{ HttpOutputCompressor::GzipFilter
#if defined(HAVE_ZLIB_H)
class HttpOutputCompressor::GzipFilter : public ZlibFilter {
public:
explicit GzipFilter(int level) : ZlibFilter(15 + 16, level) {}
};
#endif
// }}}
// {{{ HttpOutputCompressor
HttpOutputCompressor::HttpOutputCompressor()
: contentTypes_(), // no types
level_(9), // best compression
minSize_(256), // 256 byte
maxSize_(128 * 1024 * 1024) { // 128 MB
addMimeType("text/plain");
addMimeType("text/html");
addMimeType("text/css");
addMimeType("application/xml");
addMimeType("application/xhtml+xml");
addMimeType("application/javascript");
}
HttpOutputCompressor::~HttpOutputCompressor() {
}
void HttpOutputCompressor::setMinSize(size_t value) {
minSize_ = value;
}
void HttpOutputCompressor::setMaxSize(size_t value) {
maxSize_ = value;
}
void HttpOutputCompressor::addMimeType(const std::string& value) {
contentTypes_[value] = 0;
}
bool HttpOutputCompressor::containsMimeType(const std::string& value) const {
return contentTypes_.find(value) != contentTypes_.end();
}
template<typename Encoder>
bool tryEncode(const std::string& encoding,
int level,
const std::vector<BufferRef>& accepts,
HttpRequest* request,
HttpResponse* response) {
if (std::find(accepts.begin(), accepts.end(), encoding) == accepts.end())
return false;
// response might change according to Accept-Encoding
response->appendHeader("Vary", "Accept-Encoding", ",");
// removing content-length implicitely enables chunked encoding
response->resetContentLength();
response->addHeader("Content-Encoding", encoding);
response->output()->addFilter(std::make_shared<Encoder>(level));
return true;
}
void HttpOutputCompressor::inject(HttpRequest* request,
HttpResponse* response) {
// TODO: ensure postProcess() gets invoked right before response commit
}
void HttpOutputCompressor::postProcess(HttpRequest* request,
HttpResponse* response) {
if (response->headers().contains("Content-Encoding"))
return; // do not double-encode content
bool chunked = !response->hasContentLength();
long long size = chunked ? 0 : response->contentLength();
if (!chunked && (size < minSize_ || size > maxSize_))
return;
if (!containsMimeType(response->headers().get("Content-Type")))
return;
const std::string& acceptEncoding = request->headers().get("Accept-Encoding");
BufferRef r(acceptEncoding);
if (!r.empty()) {
const auto items = Tokenizer<BufferRef, BufferRef>::tokenize(r, ", ");
// if (tryEncode<Bzip2Filter>("bzip2", level_, items, request, response))
// return;
if (tryEncode<GzipFilter>("gzip", level_, items, request, response))
return;
if (tryEncode<DeflateFilter>("deflate", level_, items, request, response))
return;
}
}
// }}}
} // namespace xzero
|
add application/javascript to mimetype-list to be compressed by default
|
HttpOutputCompressor: add application/javascript to mimetype-list to be compressed by default
|
C++
|
agpl-3.0
|
eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql
|
b543ac2a167f019262c052c1b838593b44a35c58
|
tests/src/device_usbspeed_test.cpp
|
tests/src/device_usbspeed_test.cpp
|
#define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
// std
#include <atomic>
#include <iostream>
// Include depthai library
#include <depthai/depthai.hpp>
void makeInfo(dai::Pipeline& p) {
auto info = p.create<dai::node::SystemLogger>();
auto xo = p.create<dai::node::XLinkOut>();
xo->setStreamName("sysinfo");
info->out.link(xo->input);
}
void verifyInfo(dai::Device& d) {
auto infoQ = d.getOutputQueue("sysinfo");
if(infoQ->isClosed()) throw std::runtime_error("queue is not open");
}
TEST_CASE("usb2Mode == true") {
dai::Pipeline p;
makeInfo(p);
dai::Device d(p, true);
verifyInfo(d);
}
TEST_CASE("UsbSpeed::HIGH") {
dai::Pipeline p;
makeInfo(p);
dai::Device d(p, dai::UsbSpeed::HIGH);
verifyInfo(d);
}
TEST_CASE("UsbSpeed::SUPER") {
dai::Pipeline p;
makeInfo(p);
dai::Device d(p, dai::UsbSpeed::SUPER);
verifyInfo(d);
}
TEST_CASE("UsbSpeed::SUPER_PLUS") {
dai::Pipeline p;
makeInfo(p);
dai::Device d(p, dai::UsbSpeed::SUPER_PLUS);
verifyInfo(d);
}
|
#define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
// std
#include <atomic>
#include <chrono>
#include <iostream>
// Include depthai library
#include <depthai/depthai.hpp>
void makeInfo(dai::Pipeline& p) {
auto xo = p.create<dai::node::XLinkOut>();
xo->setStreamName("sysinfo");
auto info = p.create<dai::node::SystemLogger>();
info->out.link(xo->input);
}
void verifyInfo(dai::Device& d) {
auto infoQ = d.getOutputQueue("sysinfo", 1, false);
bool timeout = false;
auto infoFrame = infoQ->get<dai::SystemInformation>(std::chrono::seconds(1), timeout);
if(timeout || (infoFrame == nullptr)) throw std::runtime_error("no valid frame arrived at host");
if((infoFrame->leonCssCpuUsage.average < 0.0f) || (infoFrame->leonCssCpuUsage.average > 1.0f))
throw std::runtime_error("invalid leonCssCpuUsage.average " + std::to_string(infoFrame->leonCssCpuUsage.average));
}
TEST_CASE("usb2Mode == true") {
dai::Pipeline p;
makeInfo(p);
dai::Device d(p, true);
verifyInfo(d);
}
TEST_CASE("UsbSpeed::HIGH") {
dai::Pipeline p;
makeInfo(p);
dai::Device d(p, dai::UsbSpeed::HIGH);
verifyInfo(d);
}
TEST_CASE("UsbSpeed::SUPER") {
dai::Pipeline p;
makeInfo(p);
dai::Device d(p, dai::UsbSpeed::SUPER);
verifyInfo(d);
}
TEST_CASE("UsbSpeed::SUPER_PLUS") {
dai::Pipeline p;
makeInfo(p);
dai::Device d(p, dai::UsbSpeed::SUPER_PLUS);
verifyInfo(d);
}
|
strengthen test for device construct+q+frame
|
strengthen test for device construct+q+frame
|
C++
|
mit
|
luxonis/depthai-core,luxonis/depthai-core,luxonis/depthai-core
|
212ec72a6cb7324d2335d0ee45d1f9f5c7511e8f
|
src/image_annotator/mainwindow.cc
|
src/image_annotator/mainwindow.cc
|
#include <algorithm>
#include <QFileDialog>
#include <QMessageBox>
#include "fish_annotator/common/species_dialog.h"
#include "fish_annotator/image_annotator/mainwindow.h"
#include "ui_mainwindow.h"
namespace fish_annotator { namespace image_annotator {
namespace fs = boost::filesystem;
namespace { //anonymous
static const std::vector<std::string> kDirExtensions = {
".jpg", ".png", ".bmp", ".tif", ".jpeg",
".JPG", ".PNG", ".BMP", ".TIF", ".JPEG"};
} // anonymous namespace
MainWindow::MainWindow(QWidget *parent)
: annotations_(new ImageAnnotationList)
, scene_(new QGraphicsScene)
, ui_(new Ui::MainWindow)
, species_controls_(new SpeciesControls(this))
, image_files_() {
ui_->setupUi(this);
#ifdef _WIN32
setWindowIcon(QIcon(":/icons/FishAnnotator.ico"));
#endif
ui_->next->setIcon(QIcon(":/icons/image_controls/next.svg"));
ui_->prev->setIcon(QIcon(":/icons/image_controls/prev.svg"));
ui_->sideBarLayout->addWidget(species_controls_.get());
QObject::connect(species_controls_.get(),
SIGNAL(individualAdded(std::string, std::string)),
this, SLOT(addIndividual(std::string, std::string)));
fs::path current_path(QDir::currentPath().toStdString());
fs::path default_species = current_path / fs::path("default.species");
if(fs::exists(default_species)) {
species_controls_->loadSpeciesFile(
QString(default_species.string().c_str()));
}
}
void MainWindow::on_next_clicked() {
int next_val = ui_->imageSlider->value() + 1;
if(next_val <= ui_->imageSlider->maximum()) {
ui_->imageSlider->setValue(next_val);
}
}
void MainWindow::on_prev_clicked() {
int prev_val = ui_->imageSlider->value() - 1;
if(prev_val >= ui_->imageSlider->minimum()) {
ui_->imageSlider->setValue(prev_val);
}
}
void MainWindow::on_loadImageDir_triggered() {
QString image_dir = QFileDialog::getExistingDirectory(this,
"Select an image directory.");
if(!image_dir.isEmpty()) {
onLoadDirectorySuccess(image_dir);
}
}
void MainWindow::on_saveAnnotations_triggered() {
if(image_files_.size() > 0) {
annotations_->write(image_files_);
}
}
void MainWindow::on_imageSlider_valueChanged() {
scene_->clear();
ui_->idSelection->clear();
#ifdef _WIN32
QString filename(image_files_[ui_->imageSlider->value()].string().c_str());
#else
QString filename(image_files_[ui_->imageSlider->value()].c_str());
#endif
QImage current(filename);
if(!current.isNull()) {
scene_->addPixmap(QPixmap::fromImage(current));
scene_->setSceneRect(current.rect());
ui_->imageWindow->setScene(scene_.get());
ui_->imageWindow->fitInView(scene_->sceneRect(), Qt::KeepAspectRatio);
ui_->imageWindow->show();
ui_->fileNameValue->setText(filename);
fs::path img_path(filename.toStdString());
auto annotations =
annotations_->getImageAnnotations(img_path.filename());
for(auto annotation : annotations) {
if(ui_->showAnnotations->isChecked()) {
auto region = new AnnotatedRegion<ImageAnnotation>(
annotation->id_, annotation, current.rect());
scene_->addItem(region);
}
ui_->idSelection->addItem(QString::number(annotation->id_));
}
species_controls_->resetCounts();
auto counts = annotations_->getCounts(filename.toStdString());
for(auto it = counts.begin(); it != counts.end(); it++) {
species_controls_->setCount(it->second, it->first);
}
updateTypeMenus();
}
else {
QMessageBox err;
err.critical(0, "Error", std::string(
std::string("Error loading image ")
+ filename.toStdString()
+ std::string(".")).c_str());
}
}
void MainWindow::on_showAnnotations_stateChanged() {
on_imageSlider_valueChanged();
}
void MainWindow::on_idSelection_currentIndexChanged(const QString &id) {
updateTypeMenus();
}
void MainWindow::on_typeMenu_activated(const QString &text) {
auto ann = currentAnnotation();
if(ann != nullptr) {
ann->species_ = text.toStdString();
updateTypeMenus();
}
}
void MainWindow::on_subTypeMenu_activated(const QString &text) {
auto ann = currentAnnotation();
if(ann != nullptr) {
ann->subspecies_ = text.toStdString();
updateTypeMenus();
}
}
void MainWindow::on_removeAnnotation_clicked() {
if(image_files_.size() > 0 && ui_->imageSlider->isEnabled()) {
auto current_image = image_files_[ui_->imageSlider->value()];
int id = ui_->idSelection->currentText().toInt();
annotations_->remove(current_image, id);
on_imageSlider_valueChanged();
}
}
void MainWindow::addIndividual(std::string species, std::string subspecies) {
if(image_files_.size() > 0 && ui_->imageSlider->isEnabled()) {
auto current_image = image_files_[ui_->imageSlider->value()];
uint64_t id = annotations_->nextId(current_image);
auto annotation = std::make_shared<ImageAnnotation>(
current_image.filename().string(), species, subspecies, id,
Rect(0, 0, 0, 0));
annotations_->insert(annotation);
on_imageSlider_valueChanged();
}
}
void MainWindow::onLoadDirectorySuccess(const QString &image_dir) {
image_files_.clear();
fs::directory_iterator dir_it(image_dir.toStdString());
fs::directory_iterator dir_end;
for(; dir_it != dir_end; ++dir_it) {
fs::path ext(dir_it->path().extension());
for(auto &ok_ext : kDirExtensions) {
if(ext == ok_ext) {
image_files_.push_back(dir_it->path());
}
}
}
std::sort(image_files_.begin(), image_files_.end());
if(image_files_.size() > 0) {
ui_->idLabel->setEnabled(true);
ui_->speciesLabel->setEnabled(true);
ui_->subspeciesLabel->setEnabled(true);
ui_->idSelection->setEnabled(true);
ui_->typeMenu->setEnabled(true);
ui_->subTypeMenu->setEnabled(true);
ui_->removeAnnotation->setEnabled(true);
ui_->showAnnotations->setEnabled(true);
ui_->setMetadata->setEnabled(true);
ui_->next->setEnabled(true);
ui_->prev->setEnabled(true);
ui_->saveAnnotations->setEnabled(true);
ui_->imageSlider->setEnabled(true);
ui_->imageSlider->setMinimum(0);
ui_->imageSlider->setMaximum(static_cast<int>(image_files_.size() - 1));
ui_->imageSlider->setSingleStep(1);
ui_->imageSlider->setValue(0);
annotations_->read(image_files_);
species_controls_->loadFromVector(annotations_->getAllSpecies());
on_imageSlider_valueChanged();
}
else {
QMessageBox err;
err.critical(0, "Error", "No images found in this directory.");
}
}
void MainWindow::updateTypeMenus() {
auto ann = currentAnnotation();
if(ann != nullptr) {
ui_->typeMenu->clear();
ui_->subTypeMenu->clear();
auto species = species_controls_->getSpecies();
for(auto &s : species) {
ui_->typeMenu->addItem(s.getName().c_str());
if(s.getName() == ann->species_) {
ui_->typeMenu->setCurrentText(s.getName().c_str());
auto subspecies = s.getSubspecies();
for(auto &sub : subspecies) {
ui_->subTypeMenu->addItem(sub.c_str());
if(sub == ann->subspecies_) {
ui_->subTypeMenu->setCurrentText(sub.c_str());
}
}
}
}
}
}
std::shared_ptr<ImageAnnotation> MainWindow::currentAnnotation() {
if(image_files_.size() > 0 && ui_->imageSlider->isEnabled()) {
auto id = ui_->idSelection->currentText();
auto current_image = image_files_[ui_->imageSlider->value()];
auto annotations =
annotations_->getImageAnnotations(current_image);
for(auto annotation : annotations) {
if(annotation->id_ == id.toInt()) {
return annotation;
}
}
}
return nullptr;
}
#include "../../include/fish_annotator/image_annotator/moc_mainwindow.cpp"
}} // namespace fish_annotator::image_annotator
|
#include <algorithm>
#include <QFileDialog>
#include <QMessageBox>
#include "fish_annotator/common/species_dialog.h"
#include "fish_annotator/image_annotator/mainwindow.h"
#include "ui_mainwindow.h"
namespace fish_annotator { namespace image_annotator {
namespace fs = boost::filesystem;
namespace { //anonymous
static const std::vector<std::string> kDirExtensions = {
".jpg", ".png", ".bmp", ".tif", ".jpeg",
".JPG", ".PNG", ".BMP", ".TIF", ".JPEG"};
} // anonymous namespace
MainWindow::MainWindow(QWidget *parent)
: annotations_(new ImageAnnotationList)
, scene_(new QGraphicsScene)
, ui_(new Ui::MainWindow)
, species_controls_(new SpeciesControls(this))
, image_files_() {
ui_->setupUi(this);
#ifdef _WIN32
setWindowIcon(QIcon(":/icons/FishAnnotator.ico"));
#endif
ui_->next->setIcon(QIcon(":/icons/image_controls/next.svg"));
ui_->prev->setIcon(QIcon(":/icons/image_controls/prev.svg"));
ui_->sideBarLayout->addWidget(species_controls_.get());
QObject::connect(species_controls_.get(),
SIGNAL(individualAdded(std::string, std::string)),
this, SLOT(addIndividual(std::string, std::string)));
fs::path current_path(QDir::currentPath().toStdString());
fs::path default_species = current_path / fs::path("default.species");
if(fs::exists(default_species)) {
species_controls_->loadSpeciesFile(
QString(default_species.string().c_str()));
}
}
void MainWindow::on_next_clicked() {
int next_val = ui_->imageSlider->value() + 1;
if(next_val <= ui_->imageSlider->maximum()) {
ui_->imageSlider->setValue(next_val);
}
}
void MainWindow::on_prev_clicked() {
int prev_val = ui_->imageSlider->value() - 1;
if(prev_val >= ui_->imageSlider->minimum()) {
ui_->imageSlider->setValue(prev_val);
}
}
void MainWindow::on_loadImageDir_triggered() {
QString image_dir = QFileDialog::getExistingDirectory(this,
"Select an image directory.");
if(!image_dir.isEmpty()) {
onLoadDirectorySuccess(image_dir);
}
}
void MainWindow::on_saveAnnotations_triggered() {
if(image_files_.size() > 0) {
annotations_->write(image_files_);
}
}
void MainWindow::on_imageSlider_valueChanged() {
scene_->clear();
ui_->idSelection->clear();
std::string filename = image_files_[ui_->imageSlider->value()].string();
QImage current(filename.c_str());
if(!current.isNull()) {
scene_->addPixmap(QPixmap::fromImage(current));
scene_->setSceneRect(current.rect());
ui_->imageWindow->setScene(scene_.get());
ui_->imageWindow->fitInView(scene_->sceneRect(), Qt::KeepAspectRatio);
ui_->imageWindow->show();
ui_->fileNameValue->setText(filename.c_str());
fs::path img_path(filename);
auto annotations =
annotations_->getImageAnnotations(img_path.filename());
for(auto annotation : annotations) {
if(ui_->showAnnotations->isChecked()) {
auto region = new AnnotatedRegion<ImageAnnotation>(
annotation->id_, annotation, current.rect());
scene_->addItem(region);
}
ui_->idSelection->addItem(QString::number(annotation->id_));
}
species_controls_->resetCounts();
auto counts = annotations_->getCounts(img_path.filename().string());
for(const auto &species : species_controls_->getSpecies()) {
auto it = counts.find(species.getName());
if(it != counts.end()) {
species_controls_->setCount(it->second, it->first);
}
else {
species_controls_->setCount(0, species.getName());
}
}
updateTypeMenus();
}
else {
QMessageBox err;
err.critical(0, "Error", std::string(
std::string("Error loading image ")
+ filename
+ std::string(".")).c_str());
}
}
void MainWindow::on_showAnnotations_stateChanged() {
on_imageSlider_valueChanged();
}
void MainWindow::on_idSelection_currentIndexChanged(const QString &id) {
updateTypeMenus();
}
void MainWindow::on_typeMenu_activated(const QString &text) {
auto ann = currentAnnotation();
if(ann != nullptr) {
ann->species_ = text.toStdString();
updateTypeMenus();
}
}
void MainWindow::on_subTypeMenu_activated(const QString &text) {
auto ann = currentAnnotation();
if(ann != nullptr) {
ann->subspecies_ = text.toStdString();
updateTypeMenus();
}
}
void MainWindow::on_removeAnnotation_clicked() {
if(image_files_.size() > 0 && ui_->imageSlider->isEnabled()) {
auto current_image = image_files_[ui_->imageSlider->value()];
int id = ui_->idSelection->currentText().toInt();
annotations_->remove(current_image, id);
on_imageSlider_valueChanged();
}
}
void MainWindow::addIndividual(std::string species, std::string subspecies) {
if(image_files_.size() > 0 && ui_->imageSlider->isEnabled()) {
auto current_image = image_files_[ui_->imageSlider->value()];
uint64_t id = annotations_->nextId(current_image);
auto annotation = std::make_shared<ImageAnnotation>(
current_image.filename().string(), species, subspecies, id,
Rect(0, 0, 0, 0));
annotations_->insert(annotation);
on_imageSlider_valueChanged();
ui_->idSelection->setCurrentText(QString::number(id));
}
}
void MainWindow::onLoadDirectorySuccess(const QString &image_dir) {
image_files_.clear();
fs::directory_iterator dir_it(image_dir.toStdString());
fs::directory_iterator dir_end;
for(; dir_it != dir_end; ++dir_it) {
fs::path ext(dir_it->path().extension());
for(auto &ok_ext : kDirExtensions) {
if(ext == ok_ext) {
image_files_.push_back(dir_it->path());
}
}
}
std::sort(image_files_.begin(), image_files_.end());
if(image_files_.size() > 0) {
ui_->idLabel->setEnabled(true);
ui_->speciesLabel->setEnabled(true);
ui_->subspeciesLabel->setEnabled(true);
ui_->idSelection->setEnabled(true);
ui_->typeMenu->setEnabled(true);
ui_->subTypeMenu->setEnabled(true);
ui_->removeAnnotation->setEnabled(true);
ui_->showAnnotations->setEnabled(true);
ui_->setMetadata->setEnabled(true);
ui_->next->setEnabled(true);
ui_->prev->setEnabled(true);
ui_->saveAnnotations->setEnabled(true);
ui_->imageSlider->setEnabled(true);
ui_->imageSlider->setMinimum(0);
ui_->imageSlider->setMaximum(static_cast<int>(image_files_.size() - 1));
ui_->imageSlider->setSingleStep(1);
ui_->imageSlider->setValue(0);
annotations_->read(image_files_);
species_controls_->loadFromVector(annotations_->getAllSpecies());
on_imageSlider_valueChanged();
}
else {
QMessageBox err;
err.critical(0, "Error", "No images found in this directory.");
}
}
void MainWindow::updateTypeMenus() {
auto ann = currentAnnotation();
if(ann != nullptr) {
ui_->typeMenu->clear();
ui_->subTypeMenu->clear();
auto species = species_controls_->getSpecies();
for(auto &s : species) {
ui_->typeMenu->addItem(s.getName().c_str());
if(s.getName() == ann->species_) {
ui_->typeMenu->setCurrentText(s.getName().c_str());
auto subspecies = s.getSubspecies();
for(auto &sub : subspecies) {
ui_->subTypeMenu->addItem(sub.c_str());
if(sub == ann->subspecies_) {
ui_->subTypeMenu->setCurrentText(sub.c_str());
}
}
}
}
}
}
std::shared_ptr<ImageAnnotation> MainWindow::currentAnnotation() {
if(image_files_.size() > 0 && ui_->imageSlider->isEnabled()) {
auto id = ui_->idSelection->currentText();
auto current_image = image_files_[ui_->imageSlider->value()];
auto annotations =
annotations_->getImageAnnotations(current_image);
for(auto annotation : annotations) {
if(annotation->id_ == id.toInt()) {
return annotation;
}
}
}
return nullptr;
}
#include "../../include/fish_annotator/image_annotator/moc_mainwindow.cpp"
}} // namespace fish_annotator::image_annotator
|
Fix issue with updating counts, set current ID to latest added
|
Fix issue with updating counts, set current ID to latest added
|
C++
|
mit
|
BGWoodward/FishDetector
|
f0f3dedb2e5941942765575a0eca610bad295ea5
|
src/rpcz/worker.cc
|
src/rpcz/worker.cc
|
// Copyright 2011 Google Inc. All Rights Reserved.
// Copyright 2015 Jin Qing.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: [email protected] <Nadav Samet>
// Jin Qing (http://blog.csdn.net/jq0123)
#include <rpcz/worker.hpp>
#include <zmq.hpp>
#include <rpcz/callback.hpp> // for closure
#include <rpcz/connection_info_zmq.hpp> // for read_connection_info()
#include <rpcz/internal_commands.hpp> // for kReady
#include <rpcz/logging.hpp> // for CHECK_EQ()
#include <rpcz/request_handler.hpp>
#include <rpcz/rpc_controller.hpp> // for rpc_controller
#include <rpcz/zmq_utils.hpp> // for send_empty_message()
namespace rpcz {
worker::worker(const std::string& frontend_endpoint,
zmq::context_t& context)
: frontend_endpoint_(frontend_endpoint),
context_(context) {
}
worker::~worker() {
}
void worker::operator()() {
zmq::socket_t socket(context_, ZMQ_DEALER);
socket.connect(frontend_endpoint_.c_str());
send_empty_message(&socket, ZMQ_SNDMORE);
send_char(&socket, c2b::kWorkerReady);
bool should_continue = true;
do {
message_iterator iter(socket);
CHECK_EQ(0, iter.next().size());
char command(interpret_message<char>(iter.next()));
using namespace b2w; // broker to worker command
switch (command) {
case kWorkerQuit:
should_continue = false;
break;
case kRunClosure:
interpret_message<closure*>(iter.next())->run();
break;
case kHandleData:
handle_data(socket);
break;
case kHandleTimeout:
handle_timeout(iter);
break;
default:
CHECK(false);
break;
} // switch
} while (should_continue);
send_empty_message(&socket, ZMQ_SNDMORE);
send_char(&socket, c2b::kWorkerDone);
}
void worker::handle_data(zmq::socket_t& socket) {
connection_info info;
read_connection_info(&socket, &info);
// XXXX
// XXX
//request_handler* handler =
// interpret_message<request_handler*>(iter.next());
//assert(handler);
//handler->handle_request(iter);
// XXX
//rpc_controller* ctrl =
// interpret_message<rpc_controller*>(iter.next());
//BOOST_ASSERT(ctrl);
//ctrl->handle_response(iter);
//delete ctrl;
}
void worker::handle_timeout(message_iterator& iter) {
uint64 event_id = interpret_message<uint64>(iter.next());
// XXXX
//remote_response_map::iterator response_iter = remote_response_map_.find(event_id);
//if (response_iter == remote_response_map_.end()) {
// return;
//}
//rpc_controller* ctrl = response_iter->second;
//BOOST_ASSERT(ctrl);
//ctrl->set_timeout_expired(); XXX ->timeout()
//remote_response_map_.erase(response_iter);
}
} // namespace rpcz
|
// Copyright 2011 Google Inc. All Rights Reserved.
// Copyright 2015 Jin Qing.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: [email protected] <Nadav Samet>
// Jin Qing (http://blog.csdn.net/jq0123)
#include <rpcz/worker.hpp>
#include <zmq.hpp>
#include <rpcz/callback.hpp> // for closure
#include <rpcz/connection_info_zmq.hpp> // for read_connection_info()
#include <rpcz/internal_commands.hpp> // for kReady
#include <rpcz/logging.hpp> // for CHECK_EQ()
#include <rpcz/request_handler.hpp>
#include <rpcz/rpc_controller.hpp> // for rpc_controller
#include <rpcz/zmq_utils.hpp> // for send_empty_message()
namespace rpcz {
worker::worker(const std::string& frontend_endpoint,
zmq::context_t& context)
: frontend_endpoint_(frontend_endpoint),
context_(context) {
}
worker::~worker() {
}
void worker::operator()() {
zmq::socket_t socket(context_, ZMQ_DEALER);
socket.connect(frontend_endpoint_.c_str());
send_empty_message(&socket, ZMQ_SNDMORE);
send_char(&socket, c2b::kWorkerReady);
bool should_continue = true;
do {
message_iterator iter(socket);
CHECK_EQ(0, iter.next().size());
char command(interpret_message<char>(iter.next()));
using namespace b2w; // broker to worker command
switch (command) {
case kWorkerQuit:
should_continue = false;
break;
case kRunClosure:
interpret_message<closure*>(iter.next())->run();
break;
case kHandleData:
handle_data(socket);
break;
case kHandleTimeout:
handle_timeout(iter);
break;
default:
CHECK(false);
break;
} // switch
} while (should_continue);
send_empty_message(&socket, ZMQ_SNDMORE);
send_char(&socket, c2b::kWorkerDone);
}
void worker::handle_data(zmq::socket_t& socket) {
connection_info info;
read_connection_info(&socket, &info);
message_iterator iter(socket);
if (!iter.has_more()) return;
const zmq::message_t& msg = iter.next();
rpc_header rpc_hdr;
if (!rpc_hdr.ParseFromArray(msg.data(), msg.size())) {
// Handle bad rpc.
DLOG(INFO) << "Received bad header.";
// XXXX rep.reply_error(error_code::INVALID_HEADER, "Invalid rpc_header.");
return;
}
if (!iter.has_more()) return;
// XXXX
// XXX
//request_handler* handler =
// interpret_message<request_handler*>(iter.next());
//assert(handler);
//handler->handle_request(iter);
// XXX
//rpc_controller* ctrl =
// interpret_message<rpc_controller*>(iter.next());
//BOOST_ASSERT(ctrl);
//ctrl->handle_response(iter);
//delete ctrl;
}
void worker::handle_timeout(message_iterator& iter) {
uint64 event_id = interpret_message<uint64>(iter.next());
// XXXX
//remote_response_map::iterator response_iter = remote_response_map_.find(event_id);
//if (response_iter == remote_response_map_.end()) {
// return;
//}
//rpc_controller* ctrl = response_iter->second;
//BOOST_ASSERT(ctrl);
//ctrl->set_timeout_expired(); XXX ->timeout()
//remote_response_map_.erase(response_iter);
}
} // namespace rpcz
|
read rpc header
|
read rpc header
|
C++
|
apache-2.0
|
jinq0123/rpcz,malexzx/rpcz,malexzx/rpcz,malexzx/rpcz,jinq0123/rpcz
|
938cedbc62c2e77f815908c329f12152dac10265
|
src/run_tagger.cpp
|
src/run_tagger.cpp
|
// This file is part of MorphoDiTa.
//
// Copyright 2013 by Institute of Formal and Applied Linguistics, Faculty of
// Mathematics and Physics, Charles University in Prague, Czech Republic.
//
// MorphoDiTa is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of
// the License, or (at your option) any later version.
//
// MorphoDiTa 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 MorphoDiTa. If not, see <http://www.gnu.org/licenses/>.
#include <cstring>
#include <ctime>
#include <memory>
#include "tagger/tagger.h"
#include "utils/input.h"
using namespace ufal::morphodita;
static void tag_vertical(const tagger& tagger);
static void tag_untokenized(const tagger& tagger);
int main(int argc, char* argv[]) {
bool use_vertical = false;
int argi = 1;
if (argi < argc && strcmp(argv[argi], "-v") == 0) argi++, use_vertical = true;
if (argi + 1 < argc) runtime_errorf("Usage: %s [-v] tagger_file", argv[0]);
eprintf("Loading tagger: ");
unique_ptr<tagger> tagger(tagger::load(argv[argi]));
if (!tagger) runtime_errorf("Cannot load tagger from file '%s'!", argv[argi]);
eprintf("done\n");
eprintf("Tagging: ");
clock_t now = clock();
if (use_vertical) tag_vertical(*tagger);
else tag_untokenized(*tagger);
eprintf("done, in %.3f seconds.\n", (clock() - now) / double(CLOCKS_PER_SEC));
return 0;
}
void tag_vertical(const tagger& tagger) {
string line;
vector<string> words;
vector<string_piece> forms;
vector<tagged_lemma> tags;
for (bool not_eof = true; not_eof; ) {
// Read sentence
words.clear();
forms.clear();
while ((not_eof = getline(stdin, line)) && !line.empty()) {
words.emplace_back(line);
forms.emplace_back(words.back());
}
// Tag
if (!forms.empty()) {
tagger.tag(forms, tags);
for (auto& tag : tags)
printf("%s\t%s\n", tag.lemma.c_str(), tag.tag.c_str());
putchar('\n');
}
}
}
static void encode_entities_and_print(const char* text, size_t length);
void tag_untokenized(const tagger& tagger) {
string line, text;
vector<string_piece> forms;
vector<tagged_lemma> tags;
unique_ptr<tokenizer> tokenizer(tagger.new_tokenizer());
for (bool not_eof = true; not_eof; ) {
// Read block of text
text.clear();
while ((not_eof = getline(stdin, line)) && !line.empty()) {
text += line;
text += '\n';
}
if (not_eof) text += '\n';
// Tokenize and tag
const char* unprinted = text.c_str();
tokenizer->set_text(unprinted);
while (tokenizer->next_sentence(&forms, nullptr)) {
tagger.tag(forms, tags);
for (unsigned i = 0; i < forms.size(); i++) {
if (unprinted < forms[i].str) encode_entities_and_print(unprinted, forms[i].str - unprinted);
fputs("<form lemma=\"", stdout);
encode_entities_and_print(tags[i].lemma.c_str(), tags[i].lemma.size());
fputs("\" tag=\"", stdout);
encode_entities_and_print(tags[i].tag.c_str(), tags[i].tag.size());
fputs("\">", stdout);
encode_entities_and_print(forms[i].str, forms[i].len);
fputs("</form>", stdout);
unprinted = forms[i].str + forms[i].len;
}
}
if (unprinted < text.c_str() + text.size()) encode_entities_and_print(unprinted, text.c_str() + text.size() - unprinted);
}
}
void encode_entities_and_print(const char* text, size_t length) {
const char* to_print = text;
while (length) {
while (length && *text != '<' && *text != '>' && *text != '&' && *text != '"')
text++, length--;
if (length) {
if (to_print < text) fwrite(to_print, 1, text - to_print, stdout);
fputs(*text == '<' ? "<" : *text == '>' ? ">" : *text == '&' ? "&" : """, stdout);
text++, length--;
to_print = text;
}
}
if (to_print < text) fwrite(to_print, 1, text - to_print, stdout);
}
|
// This file is part of MorphoDiTa.
//
// Copyright 2013 by Institute of Formal and Applied Linguistics, Faculty of
// Mathematics and Physics, Charles University in Prague, Czech Republic.
//
// MorphoDiTa is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of
// the License, or (at your option) any later version.
//
// MorphoDiTa 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 MorphoDiTa. If not, see <http://www.gnu.org/licenses/>.
#include <cstring>
#include <ctime>
#include <memory>
#include "tagger/tagger.h"
#include "utils/input.h"
using namespace ufal::morphodita;
static void tag_vertical(const tagger& tagger);
static void tag_untokenized(const tagger& tagger);
int main(int argc, char* argv[]) {
bool use_vertical = false;
int argi = 1;
if (argi < argc && strcmp(argv[argi], "-v") == 0) argi++, use_vertical = true;
if (argi >= argc) runtime_errorf("Usage: %s [-v] tagger_file", argv[0]);
eprintf("Loading tagger: ");
unique_ptr<tagger> tagger(tagger::load(argv[argi]));
if (!tagger) runtime_errorf("Cannot load tagger from file '%s'!", argv[argi]);
eprintf("done\n");
eprintf("Tagging: ");
clock_t now = clock();
if (use_vertical) tag_vertical(*tagger);
else tag_untokenized(*tagger);
eprintf("done, in %.3f seconds.\n", (clock() - now) / double(CLOCKS_PER_SEC));
return 0;
}
void tag_vertical(const tagger& tagger) {
string line;
vector<string> words;
vector<string_piece> forms;
vector<tagged_lemma> tags;
for (bool not_eof = true; not_eof; ) {
// Read sentence
words.clear();
forms.clear();
while ((not_eof = getline(stdin, line)) && !line.empty()) {
words.emplace_back(line);
forms.emplace_back(words.back());
}
// Tag
if (!forms.empty()) {
tagger.tag(forms, tags);
for (auto& tag : tags)
printf("%s\t%s\n", tag.lemma.c_str(), tag.tag.c_str());
putchar('\n');
}
}
}
static void encode_entities_and_print(const char* text, size_t length);
void tag_untokenized(const tagger& tagger) {
string line, text;
vector<string_piece> forms;
vector<tagged_lemma> tags;
unique_ptr<tokenizer> tokenizer(tagger.new_tokenizer());
for (bool not_eof = true; not_eof; ) {
// Read block of text
text.clear();
while ((not_eof = getline(stdin, line)) && !line.empty()) {
text += line;
text += '\n';
}
if (not_eof) text += '\n';
// Tokenize and tag
const char* unprinted = text.c_str();
tokenizer->set_text(unprinted);
while (tokenizer->next_sentence(&forms, nullptr)) {
tagger.tag(forms, tags);
for (unsigned i = 0; i < forms.size(); i++) {
if (unprinted < forms[i].str) encode_entities_and_print(unprinted, forms[i].str - unprinted);
fputs("<form lemma=\"", stdout);
encode_entities_and_print(tags[i].lemma.c_str(), tags[i].lemma.size());
fputs("\" tag=\"", stdout);
encode_entities_and_print(tags[i].tag.c_str(), tags[i].tag.size());
fputs("\">", stdout);
encode_entities_and_print(forms[i].str, forms[i].len);
fputs("</form>", stdout);
unprinted = forms[i].str + forms[i].len;
}
}
if (unprinted < text.c_str() + text.size()) encode_entities_and_print(unprinted, text.c_str() + text.size() - unprinted);
}
}
void encode_entities_and_print(const char* text, size_t length) {
const char* to_print = text;
while (length) {
while (length && *text != '<' && *text != '>' && *text != '&' && *text != '"')
text++, length--;
if (length) {
if (to_print < text) fwrite(to_print, 1, text - to_print, stdout);
fputs(*text == '<' ? "<" : *text == '>' ? ">" : *text == '&' ? "&" : """, stdout);
text++, length--;
to_print = text;
}
}
if (to_print < text) fwrite(to_print, 1, text - to_print, stdout);
}
|
Fix wrong argument count check.
|
Fix wrong argument count check.
|
C++
|
mpl-2.0
|
ufal/morphodita,ufal/morphodita,ufal/morphodita,ufal/morphodita,ufal/morphodita,ufal/morphodita,ufal/morphodita,ufal/morphodita
|
2c0460a5c9d15739d36ea800ed4d9614a299f7da
|
AlembicImporterPlugin/AlembicImporter.cpp
|
AlembicImporterPlugin/AlembicImporter.cpp
|
#include "pch.h"
#include "AlembicImporter.h"
#include "aiContext.h"
#include "aiObject.h"
#include "Schema/aiSchema.h"
#include "Schema/aiXForm.h"
#include "Schema/aiPolyMesh.h"
#include "Schema/aiCamera.h"
#include "aiLogger.h"
#ifdef aiWindows
#include <windows.h>
# define aiBreak() DebugBreak()
#else // aiWindows
# define aiBreak() __builtin_trap()
#endif // aiWindows
#ifdef aiDebug
void aiDebugLogImpl(const char* fmt, ...)
{
va_list vl;
va_start(vl, fmt);
#ifdef aiWindows
char buf[2048];
vsprintf(buf, fmt, vl);
::OutputDebugStringA(buf);
#else // aiWindows
vprintf(fmt, vl);
#endif // aiWindows
va_end(vl);
}
#endif // aiDebug
aiCLinkage aiExport void aiEnableFileLog(bool on, const char *path)
{
aiLogger::Enable(on, path);
}
aiCLinkage aiExport void aiCleanup()
{
#ifdef aiWithTBB
#else
aiThreadPool::releaseInstance();
#endif
}
aiCLinkage aiExport aiContext* aiCreateContext(int uid)
{
auto ctx = aiContext::create(uid);
return ctx;
}
aiCLinkage aiExport void aiDestroyContext(aiContext* ctx)
{
aiContext::destroy(ctx);
}
aiCLinkage aiExport bool aiLoad(aiContext* ctx, const char *path)
{
return ctx->load(path);
}
aiCLinkage aiExport float aiGetStartTime(aiContext* ctx)
{
return ctx->getStartTime();
}
aiCLinkage aiExport float aiGetEndTime(aiContext* ctx)
{
return ctx->getEndTime();
}
aiCLinkage aiExport aiObject* aiGetTopObject(aiContext* ctx)
{
return ctx->getTopObject();
}
aiCLinkage aiExport void aiDestroyObject(aiContext* ctx, aiObject* obj)
{
ctx->destroyObject(obj);
}
aiCLinkage aiExport void aiUpdateSamples(aiContext* ctx, float time, bool useThreads)
{
ctx->updateSamples(time, useThreads);
}
aiCLinkage aiExport void aiSetTimeRangeToKeepSamples(aiContext* ctx, float time, float range)
{
ctx->setTimeRangeToKeepSamples(time, range);
}
aiCLinkage aiExport void aiErasePastSamples(aiContext* ctx, float time, float range)
{
ctx->erasePastSamples(time, range);
}
aiCLinkage aiExport void aiUpdateSamplesBegin(aiContext* ctx, float time)
{
ctx->updateSamplesBegin(time);
}
aiCLinkage aiExport void aiUpdateSamplesEnd(aiContext* ctx)
{
ctx->updateSamplesEnd();
}
aiCLinkage aiExport void aiEnumerateChild(aiObject *obj, aiNodeEnumerator e, void *userData)
{
size_t n = obj->getNumChildren();
for (size_t i = 0; i < n; ++i)
{
try
{
aiObject *child = obj->getChild(i);
e(child, userData);
}
catch (Alembic::Util::Exception e)
{
aiDebugLog("exception: %s\n", e.what());
}
}
}
aiCLinkage aiExport const char* aiGetNameS(aiObject* obj)
{
return obj->getName();
}
aiCLinkage aiExport const char* aiGetFullNameS(aiObject* obj)
{
return obj->getFullName();
}
aiCLinkage aiExport void aiSchemaSetSampleCallback(aiSchemaBase* schema, aiSampleCallback cb, void* arg)
{
schema->setSampleCallback(cb, arg);
}
aiCLinkage aiExport void aiSchemaSetConfigCallback(aiSchemaBase* schema, aiConfigCallback cb, void* arg)
{
schema->setConfigCallback(cb, arg);
}
aiCLinkage aiExport const aiSampleBase* aiSchemaUpdateSample(aiSchemaBase* schema, float time)
{
return schema->updateSample(time);
}
aiCLinkage aiExport const aiSampleBase* aiSchemaGetSample(aiSchemaBase* schema, float time)
{
return schema->findSample(time);
}
aiCLinkage aiExport float aiSampleGetTime(aiSampleBase* sample)
{
return sample->getTime();
}
aiCLinkage aiExport bool aiHasXForm(aiObject* obj)
{
return obj->hasXForm();
}
aiCLinkage aiExport aiXForm* aiGetXForm(aiObject* obj)
{
return &(obj->getXForm());
}
aiCLinkage aiExport void aiXFormGetData(aiXFormSample* sample, aiXFormData *outData)
{
sample->getData(*outData);
}
aiCLinkage aiExport bool aiHasPolyMesh(aiObject* obj)
{
return obj->hasPolyMesh();
}
aiCLinkage aiExport aiPolyMesh* aiGetPolyMesh(aiObject* obj)
{
return &(obj->getPolyMesh());
}
aiCLinkage aiExport void aiPolyMeshGetSummary(aiPolyMesh* schema, aiMeshSummary* summary)
{
schema->getSummary(*summary);
}
aiCLinkage aiExport void aiPolyMeshGetSampleSummary(aiPolyMeshSample* sample, aiMeshSampleSummary* summary, bool forceRefresh)
{
sample->getSummary(forceRefresh, *summary);
}
aiCLinkage aiExport int aiPolyMeshGetVertexBufferLength(aiPolyMeshSample* sample, int splitIndex)
{
return sample->getVertexBufferLength(splitIndex);
}
aiCLinkage aiExport void aiPolyMeshFillVertexBuffer(aiPolyMeshSample* sample, int splitIndex, aiMeshSampleData* data)
{
sample->fillVertexBuffer(splitIndex, *data);
}
aiCLinkage aiExport int aiPolyMeshPrepareSubmeshes(aiPolyMeshSample* sample, const aiFacesets* facesets)
{
return sample->prepareSubmeshes(*facesets);
}
aiCLinkage aiExport int aiPolyMeshGetSplitSubmeshCount(aiPolyMeshSample* sample, int splitIndex)
{
return sample->getSplitSubmeshCount(splitIndex);
}
aiCLinkage aiExport bool aiPolyMeshGetNextSubmesh(aiPolyMeshSample* sample, aiSubmeshSummary* summary)
{
return sample->getNextSubmesh(*summary);
}
aiCLinkage aiExport void aiPolyMeshFillSubmeshIndices(aiPolyMeshSample* sample, const aiSubmeshSummary* summary, aiSubmeshData* data)
{
sample->fillSubmeshIndices(*summary, *data);
}
aiCLinkage aiExport bool aiHasCamera(aiObject* obj)
{
return obj->hasCamera();
}
aiCLinkage aiExport aiCamera* aiGetCamera(aiObject* obj)
{
return &(obj->getCamera());
}
aiCLinkage aiExport void aiCameraGetData(aiCameraSample* sample, aiCameraData *outData)
{
sample->getData(*outData);
}
|
#include "pch.h"
#include "AlembicImporter.h"
#include "aiContext.h"
#include "aiObject.h"
#include "Schema/aiSchema.h"
#include "Schema/aiXForm.h"
#include "Schema/aiPolyMesh.h"
#include "Schema/aiCamera.h"
#include "aiLogger.h"
#ifdef aiWindows
#include <windows.h>
# define aiBreak() DebugBreak()
#else // aiWindows
# define aiBreak() __builtin_trap()
#endif // aiWindows
#ifdef aiDebug
void aiDebugLogImpl(const char* fmt, ...)
{
va_list vl;
va_start(vl, fmt);
#ifdef aiWindows
char buf[2048];
vsprintf(buf, fmt, vl);
::OutputDebugStringA(buf);
#else // aiWindows
vprintf(fmt, vl);
#endif // aiWindows
va_end(vl);
}
#endif // aiDebug
aiCLinkage aiExport void aiEnableFileLog(bool on, const char *path)
{
aiLogger::Enable(on, path);
}
aiCLinkage aiExport void aiCleanup()
{
#ifdef aiWithTBB
#else
aiThreadPool::releaseInstance();
#endif
}
aiCLinkage aiExport aiContext* aiCreateContext(int uid)
{
auto ctx = aiContext::create(uid);
return ctx;
}
aiCLinkage aiExport void aiDestroyContext(aiContext* ctx)
{
aiContext::destroy(ctx);
}
aiCLinkage aiExport bool aiLoad(aiContext* ctx, const char *path)
{
return ctx->load(path);
}
aiCLinkage aiExport void aiSetConfig(aiContext* ctx, const aiConfig* conf)
{
ctx->setConfig(*conf);
}
aiCLinkage aiExport float aiGetStartTime(aiContext* ctx)
{
return ctx->getStartTime();
}
aiCLinkage aiExport float aiGetEndTime(aiContext* ctx)
{
return ctx->getEndTime();
}
aiCLinkage aiExport aiObject* aiGetTopObject(aiContext* ctx)
{
return ctx->getTopObject();
}
aiCLinkage aiExport void aiDestroyObject(aiContext* ctx, aiObject* obj)
{
ctx->destroyObject(obj);
}
aiCLinkage aiExport void aiUpdateSamples(aiContext* ctx, float time, bool useThreads)
{
ctx->updateSamples(time, useThreads);
}
aiCLinkage aiExport void aiSetTimeRangeToKeepSamples(aiContext* ctx, float time, float range)
{
ctx->setTimeRangeToKeepSamples(time, range);
}
aiCLinkage aiExport void aiErasePastSamples(aiContext* ctx, float time, float range)
{
ctx->erasePastSamples(time, range);
}
aiCLinkage aiExport void aiUpdateSamplesBegin(aiContext* ctx, float time)
{
ctx->updateSamplesBegin(time);
}
aiCLinkage aiExport void aiUpdateSamplesEnd(aiContext* ctx)
{
ctx->updateSamplesEnd();
}
aiCLinkage aiExport void aiEnumerateChild(aiObject *obj, aiNodeEnumerator e, void *userData)
{
size_t n = obj->getNumChildren();
for (size_t i = 0; i < n; ++i)
{
try
{
aiObject *child = obj->getChild(i);
e(child, userData);
}
catch (Alembic::Util::Exception e)
{
aiDebugLog("exception: %s\n", e.what());
}
}
}
aiCLinkage aiExport const char* aiGetNameS(aiObject* obj)
{
return obj->getName();
}
aiCLinkage aiExport const char* aiGetFullNameS(aiObject* obj)
{
return obj->getFullName();
}
aiCLinkage aiExport void aiSchemaSetSampleCallback(aiSchemaBase* schema, aiSampleCallback cb, void* arg)
{
schema->setSampleCallback(cb, arg);
}
aiCLinkage aiExport void aiSchemaSetConfigCallback(aiSchemaBase* schema, aiConfigCallback cb, void* arg)
{
schema->setConfigCallback(cb, arg);
}
aiCLinkage aiExport const aiSampleBase* aiSchemaUpdateSample(aiSchemaBase* schema, float time)
{
return schema->updateSample(time);
}
aiCLinkage aiExport const aiSampleBase* aiSchemaGetSample(aiSchemaBase* schema, float time)
{
return schema->findSample(time);
}
aiCLinkage aiExport float aiSampleGetTime(aiSampleBase* sample)
{
return sample->getTime();
}
aiCLinkage aiExport bool aiHasXForm(aiObject* obj)
{
return obj->hasXForm();
}
aiCLinkage aiExport aiXForm* aiGetXForm(aiObject* obj)
{
return &(obj->getXForm());
}
aiCLinkage aiExport void aiXFormGetData(aiXFormSample* sample, aiXFormData *outData)
{
sample->getData(*outData);
}
aiCLinkage aiExport bool aiHasPolyMesh(aiObject* obj)
{
return obj->hasPolyMesh();
}
aiCLinkage aiExport aiPolyMesh* aiGetPolyMesh(aiObject* obj)
{
return &(obj->getPolyMesh());
}
aiCLinkage aiExport void aiPolyMeshGetSummary(aiPolyMesh* schema, aiMeshSummary* summary)
{
schema->getSummary(*summary);
}
aiCLinkage aiExport void aiPolyMeshGetSampleSummary(aiPolyMeshSample* sample, aiMeshSampleSummary* summary, bool forceRefresh)
{
sample->getSummary(forceRefresh, *summary);
}
aiCLinkage aiExport int aiPolyMeshGetVertexBufferLength(aiPolyMeshSample* sample, int splitIndex)
{
return sample->getVertexBufferLength(splitIndex);
}
aiCLinkage aiExport void aiPolyMeshFillVertexBuffer(aiPolyMeshSample* sample, int splitIndex, aiMeshSampleData* data)
{
sample->fillVertexBuffer(splitIndex, *data);
}
aiCLinkage aiExport int aiPolyMeshPrepareSubmeshes(aiPolyMeshSample* sample, const aiFacesets* facesets)
{
return sample->prepareSubmeshes(*facesets);
}
aiCLinkage aiExport int aiPolyMeshGetSplitSubmeshCount(aiPolyMeshSample* sample, int splitIndex)
{
return sample->getSplitSubmeshCount(splitIndex);
}
aiCLinkage aiExport bool aiPolyMeshGetNextSubmesh(aiPolyMeshSample* sample, aiSubmeshSummary* summary)
{
return sample->getNextSubmesh(*summary);
}
aiCLinkage aiExport void aiPolyMeshFillSubmeshIndices(aiPolyMeshSample* sample, const aiSubmeshSummary* summary, aiSubmeshData* data)
{
sample->fillSubmeshIndices(*summary, *data);
}
aiCLinkage aiExport bool aiHasCamera(aiObject* obj)
{
return obj->hasCamera();
}
aiCLinkage aiExport aiCamera* aiGetCamera(aiObject* obj)
{
return &(obj->getCamera());
}
aiCLinkage aiExport void aiCameraGetData(aiCameraSample* sample, aiCameraData *outData)
{
sample->getData(*outData);
}
|
add missing 'aiSetConfig' function
|
add missing 'aiSetConfig' function
|
C++
|
mit
|
unity3d-jp/AlembicImporter,unity3d-jp/AlembicImporter,unity3d-jp/AlembicImporter
|
b9c254a6d47cee43040617dfd45e47ac43701bdd
|
src/serializer.cpp
|
src/serializer.cpp
|
/* This file is part of qjson
*
* Copyright (C) 2009 Till Adam <[email protected]>
*
* 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 "serializer.h"
#include <QDataStream>
#include <QStringList>
#include <QVariant>
using namespace QJson;
class Serializer::SerializerPrivate {
};
Serializer::Serializer() : d( new SerializerPrivate ) {
}
Serializer::~Serializer() {
delete d;
}
void Serializer::serialize( const QVariant& v, QIODevice* io, bool* ok )
{
Q_ASSERT( io );
if (!io->isOpen()) {
if (!io->open(QIODevice::WriteOnly)) {
if ( ok != 0 )
*ok = false;
qCritical ("Error opening device");
return;
}
}
if (!io->isWritable()) {
if (ok != 0)
*ok = false;
qCritical ("Device is not readable");
io->close();
return;
}
const QByteArray str = serialize( v );
if ( !str.isNull() ) {
QDataStream stream( io );
stream << str;
} else {
if ( ok )
*ok = false;
}
}
namespace {
QString sanitizeString( QString str )
{
str.replace( QLatin1String( "\\" ), QLatin1String( "\\\\" ) );
str.replace( QLatin1String( "\"" ), QLatin1String( "\\\"" ) );
str.replace( QLatin1String( "\b" ), QLatin1String( "\\b" ) );
str.replace( QLatin1String( "\f" ), QLatin1String( "\\f" ) );
str.replace( QLatin1String( "\n" ), QLatin1String( "\\n" ) );
str.replace( QLatin1String( "\r" ), QLatin1String( "\\r" ) );
str.replace( QLatin1String( "\t" ), QLatin1String( "\\t" ) );
return QString( QLatin1String( "\"%1\"" ) ).arg( str );
}
}
static QByteArray join( const QList<QByteArray>& list, const QByteArray& sep ) {
QByteArray res;
Q_FOREACH( const QByteArray& i, list ) {
if ( !res.isEmpty() )
res += sep;
res += i;
}
return res;
}
QByteArray Serializer::serialize( const QVariant &v )
{
QByteArray str;
bool error = false;
if ( v.isNull() || ! v.isValid() ) { // invalid or null?
str = "null";
} else if ( v.type() == QVariant::List ) { // variant is a list?
const QVariantList list = v.toList();
QList<QByteArray> values;
Q_FOREACH( const QVariant& v, list )
{
QByteArray serializedValue = serialize( v );
if ( serializedValue.isNull() ) {
error = true;
break;
}
values << serializedValue;
}
str = "[ " + join( values, ", " ) + " ]";
} else if ( v.type() == QVariant::Map ) { // variant is a map?
const QVariantMap vmap = v.toMap();
QMapIterator<QString, QVariant> it( vmap );
str = "{ ";
QList<QByteArray> pairs;
while ( it.hasNext() ) {
it.next();
QByteArray serializedValue = serialize( it.value() );
if ( serializedValue.isNull() ) {
error = true;
break;
}
pairs << sanitizeString( it.key() ).toUtf8() + " : " + serializedValue;
}
str += join( pairs, ", " );
str += " }";
} else if (( v.type() == QVariant::String ) || ( v.type() == QVariant::ByteArray )) { // a string or a byte array?
str = sanitizeString( v.toString() ).toUtf8();
} else if ( v.type() == QVariant::Double ) { // a double?
str = QByteArray::number( v.toDouble() );
if( ! str.contains( "." ) && ! str.contains( "e" ) ) {
str += ".0";
}
} else if ( v.type() == QVariant::Bool ) { // boolean value?
str = ( v.toBool() ? "true" : "false" );
} else if ( v.canConvert<qlonglong>() ) { // any signed number?
str = QByteArray::number( v.value<qlonglong>() );
} else if ( v.canConvert<qulonglong>() ) { // large unsigned number?
str = QByteArray::number( v.value<qulonglong>() );
} else {
error = true;
}
if ( !error )
return str;
else
return QByteArray();
}
|
/* This file is part of qjson
*
* Copyright (C) 2009 Till Adam <[email protected]>
*
* 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 "serializer.h"
#include <QDataStream>
#include <QStringList>
#include <QVariant>
using namespace QJson;
class Serializer::SerializerPrivate {
};
Serializer::Serializer() : d( new SerializerPrivate ) {
}
Serializer::~Serializer() {
delete d;
}
void Serializer::serialize( const QVariant& v, QIODevice* io, bool* ok )
{
Q_ASSERT( io );
if (!io->isOpen()) {
if (!io->open(QIODevice::WriteOnly)) {
if ( ok != 0 )
*ok = false;
qCritical ("Error opening device");
return;
}
}
if (!io->isWritable()) {
if (ok != 0)
*ok = false;
qCritical ("Device is not readable");
io->close();
return;
}
const QByteArray str = serialize( v );
if ( !str.isNull() ) {
QDataStream stream( io );
stream << str;
} else {
if ( ok )
*ok = false;
}
}
static QString sanitizeString( QString str )
{
str.replace( QLatin1String( "\\" ), QLatin1String( "\\\\" ) );
str.replace( QLatin1String( "\"" ), QLatin1String( "\\\"" ) );
str.replace( QLatin1String( "\b" ), QLatin1String( "\\b" ) );
str.replace( QLatin1String( "\f" ), QLatin1String( "\\f" ) );
str.replace( QLatin1String( "\n" ), QLatin1String( "\\n" ) );
str.replace( QLatin1String( "\r" ), QLatin1String( "\\r" ) );
str.replace( QLatin1String( "\t" ), QLatin1String( "\\t" ) );
return QString( QLatin1String( "\"%1\"" ) ).arg( str );
}
static QByteArray join( const QList<QByteArray>& list, const QByteArray& sep ) {
QByteArray res;
Q_FOREACH( const QByteArray& i, list ) {
if ( !res.isEmpty() )
res += sep;
res += i;
}
return res;
}
QByteArray Serializer::serialize( const QVariant &v )
{
QByteArray str;
bool error = false;
if ( v.isNull() || ! v.isValid() ) { // invalid or null?
str = "null";
} else if ( v.type() == QVariant::List ) { // variant is a list?
const QVariantList list = v.toList();
QList<QByteArray> values;
Q_FOREACH( const QVariant& v, list )
{
QByteArray serializedValue = serialize( v );
if ( serializedValue.isNull() ) {
error = true;
break;
}
values << serializedValue;
}
str = "[ " + join( values, ", " ) + " ]";
} else if ( v.type() == QVariant::Map ) { // variant is a map?
const QVariantMap vmap = v.toMap();
QMapIterator<QString, QVariant> it( vmap );
str = "{ ";
QList<QByteArray> pairs;
while ( it.hasNext() ) {
it.next();
QByteArray serializedValue = serialize( it.value() );
if ( serializedValue.isNull() ) {
error = true;
break;
}
pairs << sanitizeString( it.key() ).toUtf8() + " : " + serializedValue;
}
str += join( pairs, ", " );
str += " }";
} else if (( v.type() == QVariant::String ) || ( v.type() == QVariant::ByteArray )) { // a string or a byte array?
str = sanitizeString( v.toString() ).toUtf8();
} else if ( v.type() == QVariant::Double ) { // a double?
str = QByteArray::number( v.toDouble() );
if( ! str.contains( "." ) && ! str.contains( "e" ) ) {
str += ".0";
}
} else if ( v.type() == QVariant::Bool ) { // boolean value?
str = ( v.toBool() ? "true" : "false" );
} else if ( v.canConvert<qlonglong>() ) { // any signed number?
str = QByteArray::number( v.value<qlonglong>() );
} else if ( v.canConvert<qulonglong>() ) { // large unsigned number?
str = QByteArray::number( v.value<qulonglong>() );
} else {
error = true;
}
if ( !error )
return str;
else
return QByteArray();
}
|
make it static
|
make it static
git-svn-id: ec8dad496322030ce832d387f43d3d061c430ff7@1008734 283d02a7-25f6-0310-bc7c-ecb5cbfe19da
|
C++
|
lgpl-2.1
|
drizt/qjson,drizt/qjson,cbranch/qjson-qmakefriendly,gentlefn/qjson,coolshou/qjson,gentlefn/qjson,coolshou/qjson,qlands/qjson,seem-sky/qjson,cbranch/qjson-qmakefriendly,flavio/qjson,seem-sky/qjson,flavio/qjson,qlands/qjson
|
d67babe256d8115ee524d2621df8904f36332936
|
src/graph/list_graph.hpp
|
src/graph/list_graph.hpp
|
#pragma once
#include <algorithm>
#include <map>
#include <set>
#include "graphi.hpp"
template <bool Dir, typename V, typename E>
class ListGraph : public GraphI<V, E> {
public:
ListGraph() : vertex_num_(0), vertices_(), edges_() {}
virtual ~ListGraph() = default;
virtual int add_vertex(const Vertex<V> &vertex) override {
if (vertex.idx() >= vertex_num_) {
vertex_num_ = vertex.idx() + 1;
}
if (vertices_.count(vertex.idx()) != 0) {
return -1;
}
vertices_[vertex.idx()] = vertex;
edges_[vertex.idx()] = std::set<int>();
return 0;
}
virtual int set_vertex(const Vertex<V> &vertex) override {
if (vertex.idx() >= vertex_num_) {
vertex_num_ = vertex.idx() + 1;
}
vertices_[vertex.idx()] = vertex;
return 0;
}
void rm_vertex(const Vertex<V> &vertex) override {
if (vertices_.count(vertex.idx()) > 0) {
vertices_.erase(vertex.idx());
}
for (auto v : edges_[vertex.idx()]) {
rm_edge(Edge<E>(v, vertex.idx()));
}
}
virtual const std::set<int> &adjacent_vertices(int idx) const override {
return edges_.at(idx);
}
virtual const Vertex<V> &vertex(int idx) const override {
return vertices_.at(idx);
}
virtual int vertex_num() const override { return vertex_num_; };
virtual int add_edge(const Edge<E> &edge) override {
if (std::max(edge.idx1(), edge.idx2()) >= vertex_num_) {
return -1;
}
edges_[edge.idx1()].insert(edge.idx2());
if (!Dir) {
edges_[edge.idx2()].insert(edge.idx1());
}
return 0;
}
virtual int rm_edge(const Edge<E> &edge) override {
if (std::max(edge.idx1(), edge.idx2()) >= vertex_num_) {
return -1;
}
if (edges_.count(edge.idx1()) == 0) {
return -1;
}
edges_[edge.idx1()].erase(edge.idx2());
if (!Dir) {
edges_[edge.idx2()].erase(edge.idx1());
}
return 0;
}
private:
int vertex_num_;
std::map<int, Vertex<V>> vertices_;
std::map<int, std::set<int>> edges_;
};
|
#pragma once
#include <algorithm>
#include <map>
#include <set>
#include "graphi.hpp"
template <bool Dir, typename V, typename E>
class ListGraph : public GraphI<V, E> {
public:
ListGraph() : vertex_num_(0), vertices_(), neighbours_(), edges_() {}
virtual ~ListGraph() = default;
virtual int add_vertex(const Vertex<V> &vertex) override {
if (vertex.idx() >= vertex_num_) {
vertex_num_ = vertex.idx() + 1;
}
if (vertices_.count(vertex.idx()) != 0) {
return -1;
}
vertices_[vertex.idx()] = vertex;
neighbours_[vertex.idx()] = std::set<int>();
return 0;
}
virtual int set_vertex(const Vertex<V> &vertex) override {
if (vertex.idx() >= vertex_num_) {
vertex_num_ = vertex.idx() + 1;
}
vertices_[vertex.idx()] = vertex;
return 0;
}
void rm_vertex(const Vertex<V> &vertex) override {
if (vertices_.count(vertex.idx()) > 0) {
vertices_.erase(vertex.idx());
}
for (auto v : neighbours_[vertex.idx()]) {
rm_edge(Edge<E>(v, vertex.idx()));
}
}
virtual const std::set<int> &adjacent_vertices(int idx) const override {
return neighbours_.at(idx);
}
virtual const Vertex<V> &vertex(int idx) const override {
return vertices_.at(idx);
}
virtual int vertex_num() const override { return vertex_num_; };
virtual int add_edge(const Edge<E> &edge) override {
if (std::max(edge.idx1(), edge.idx2()) >= vertex_num_) {
return -1;
}
neighbours_[edge.idx1()].insert(edge.idx2());
if (!Dir) {
neighbours_[edge.idx2()].insert(edge.idx1());
}
if (Dir) {
edges_[edge.idx1()][edge.idx2()] = edge;
}
// store undirected edge as min_idx->max_idx
else {
std::pair<int, int> p = std::minmax(edge.idx1(), edge.idx2());
edges_[p.first][p.second] = edge;
}
return 0;
}
virtual int rm_edge(const Edge<E> &edge) override {
if (std::max(edge.idx1(), edge.idx2()) >= vertex_num_) {
return -1;
}
if (neighbours_.count(edge.idx1()) == 0) {
return -1;
}
neighbours_[edge.idx1()].erase(edge.idx2());
if (!Dir) {
neighbours_[edge.idx2()].erase(edge.idx1());
}
if (Dir) {
edges_[edge.idx1()].erase(edge.idx2());
if (edges_[edge.idx1()].size() == 0) {
edges_.erase(edge.idx1());
}
}
else {
std::pair<int, int> p = std::minmax(edge.idx1(), edge.idx2());
edges_[p.first].erase(p.second);
if (edges_[p.first].size() == 0) {
edges_.erase(p.first);
}
}
return 0;
}
private:
int vertex_num_;
std::map<int, Vertex<V>> vertices_;
std::map<int, std::set<int>> neighbours_;
std::map<int, std::map<int, Edge<E>>> edges_;
};
|
Store edges in graph
|
Store edges in graph
|
C++
|
mit
|
sfod/simple-graph
|
c46fbc7fc9b89f4c043e25c5814a915ff5fa2030
|
pano.cpp
|
pano.cpp
|
/*
* Pano engine
*
* Copyright (C)2016 Laurentiu Badea
*
* This file may be redistributed under the terms of the MIT license.
* A copy of this license has been included with this distribution in the file LICENSE.
*/
#include "pano.h"
Pano::Pano(Motor& horiz_motor, Motor& vert_motor, Camera& camera, int motors_pin)
:horiz_motor(horiz_motor),
vert_motor(vert_motor),
camera(camera),
motors_pin(motors_pin)
{
pinMode(motors_pin, OUTPUT);
motorsEnable(false);
setFOV(360,180);
}
void Pano::setFOV(int horiz_angle, int vert_angle){
if (horiz_angle && vert_angle && horiz_angle <= 360 && vert_angle <= 180){
horiz_fov = horiz_angle;
vert_fov = vert_angle;
}
}
void Pano::setShutter(unsigned speed, unsigned pre_delay, unsigned post_wait, bool long_pulse){
shutter_delay = speed;
pre_shutter_delay = pre_delay;
post_shutter_delay = post_wait;
shutter_long_pulse = long_pulse;
}
void Pano::setShots(unsigned shots){
shots_per_position = shots;
}
void Pano::setMode(unsigned mode){
}
unsigned Pano::getHorizShots(void){
return horiz_count;
}
unsigned Pano::getVertShots(void){
return vert_count;
}
int Pano::getCurRow(void){
return position / horiz_count;
}
int Pano::getCurCol(void){
return position % horiz_count;
}
/*
* Calculate time left to complete pano.
*/
unsigned Pano::getTimeLeft(void){
int photos = getHorizShots() * getVertShots() - position + 1;
int seconds = photos * shots_per_position * (pre_shutter_delay + shutter_delay + post_shutter_delay) / 1000 +
// time needed to move the platform
// each photo requires a horizontal move (except last one in each row)
(photos - photos/horiz_count) * camera.getHorizFOV() * horiz_gear_ratio * 60 / DYNAMIC_RPM(HORIZ_MOTOR_RPM, camera.getHorizFOV()) / 360 +
// row-to-row movement
photos / horiz_count * camera.getVertFOV() * vert_gear_ratio * 60 / DYNAMIC_RPM(VERT_MOTOR_RPM, camera.getVertFOV()) / 360 +
// row return horizontal movement
photos / horiz_count * horiz_fov * 60 / HORIZ_MOTOR_RPM / 360;
return seconds;
}
/*
* Helper to calculate grid fit with overlap
* @param total_size: entire grid size (1-360 degrees)
* @param overlap: min required overlap in percent (1-99)
* @param block_size: ref to initial (max) block size (will be updated)
* @param count: ref to image count (will be updated)
*/
void Pano::gridFit(int total_size, int overlap, float& block_size, int& count){
if (block_size <= total_size){
/*
* For 360 pano, we need to cover entire circle plus overlap.
* For smaller panos, we cover the requested size only.
*/
if (total_size != 360){
total_size = ceil(total_size - block_size * overlap/100);
}
block_size = block_size * (100-overlap) / 100;
count = ceil(total_size / block_size);
block_size = float(total_size) / count;
} else {
count = 1;
}
}
/*
* Calculate shot-to-shot horizontal/vertical head movement,
* taking overlap into account
* Must be called every time focal distance or panorama dimensions change.
*/
void Pano::computeGrid(void){
horiz_move = camera.getHorizFOV();
gridFit(horiz_fov, MIN_OVERLAP, horiz_move, horiz_count);
vert_move = camera.getVertFOV();
gridFit(vert_fov, MIN_OVERLAP, vert_move, vert_count);
}
void Pano::start(void){
computeGrid();
motorsEnable(true);
horiz_motor.setRPM(HORIZ_MOTOR_RPM);
vert_motor.setRPM(VERT_MOTOR_RPM);
// set start position
setMotorsHomePosition();
position = 0;
}
void Pano::shutter(void){
delay(pre_shutter_delay);
for (unsigned i=shots_per_position; i; i--){
camera.shutter(shutter_delay, shutter_long_pulse);
delay(post_shutter_delay);
}
}
/*
* Move to grid position by photo index (0-number of photos)
*/
bool Pano::moveTo(int new_position){
int new_row = new_position / horiz_count;
int new_col = new_position % horiz_count;
return moveTo(new_row, new_col);
}
/*
* Move to specified grid position
* @param new_row: requested row position [0 - vert_count)
* @param new_col: requested col position [0 - horiz_count)
*/
bool Pano::moveTo(int new_row, int new_col){
int cur_row = getCurRow();
int cur_col = getCurCol();
if (cur_row >= vert_count ||
new_row >= vert_count ||
new_col >= horiz_count ||
new_col < 0 ||
new_row < 0){
// beyond last/first row or column, cannot move there.
return false;
}
if (cur_col != new_col){
// horizontal adjustment needed
// figure out shortest path around the circle
// good idea if on batteries, bad idea when power cable in use
float move = (new_col-cur_col) * horiz_move;
if (abs(move) > 180){
if (move < 0){
move = 360 + move;
} else {
move = move - 360;
}
}
moveMotorsAdaptive(move, 0);
}
if (cur_row != new_row){
// vertical adjustment needed
moveMotorsAdaptive(0, -(new_row-cur_row)*vert_move);
}
position = new_row * horiz_count + new_col;
return true;
}
bool Pano::next(void){
return moveTo(position+1);
}
bool Pano::prev(void){
return (position > 0) ? moveTo(position-1) : false;
}
void Pano::end(void){
// move to home position
moveTo(0, 0);
}
/*
* Execute a full pano run.
*/
void Pano::run(void){
start();
do {
shutter();
} while(next());
end();
}
/*
* Remember current position as "home"
* (start tracking platform movement to be able to return to it)
*/
void Pano::setMotorsHomePosition(void){
horiz_home_offset = 0;
vert_home_offset = 0;
}
/*
* Move head requested number of degrees at an adaptive speed
*/
void Pano::moveMotorsAdaptive(float h, float v){
if (h){
horiz_motor.setRPM(DYNAMIC_HORIZ_RPM(h));
}
if (v){
vert_motor.setRPM(DYNAMIC_VERT_RPM(v));
}
moveMotors(h, v);
}
/*
* Move head requested number of degrees, fixed predefined speed
*/
void Pano::moveMotors(float h, float v){
if (h){
horiz_motor.rotate(h * horiz_gear_ratio);
horiz_home_offset += h;
}
if (v){
vert_motor.rotate(v * vert_gear_ratio);
vert_home_offset += v;
}
Serial.print("horiz_home_offset ");
Serial.println(horiz_home_offset);
}
/*
* Move head back to home position
*/
void Pano::moveMotorsHome(void){
moveMotorsAdaptive(-horiz_home_offset, -vert_home_offset);
}
void Pano::motorsEnable(bool on){
digitalWrite(motors_pin, (on) ? HIGH : LOW);
delay(1);
}
|
/*
* Pano engine
*
* Copyright (C)2016 Laurentiu Badea
*
* This file may be redistributed under the terms of the MIT license.
* A copy of this license has been included with this distribution in the file LICENSE.
*/
#include "pano.h"
Pano::Pano(Motor& horiz_motor, Motor& vert_motor, Camera& camera, int motors_pin)
:horiz_motor(horiz_motor),
vert_motor(vert_motor),
camera(camera),
motors_pin(motors_pin)
{
pinMode(motors_pin, OUTPUT);
motorsEnable(false);
setFOV(360,180);
}
void Pano::setFOV(int horiz_angle, int vert_angle){
if (horiz_angle && vert_angle && horiz_angle <= 360 && vert_angle <= 180){
horiz_fov = horiz_angle;
vert_fov = vert_angle;
}
}
void Pano::setShutter(unsigned speed, unsigned pre_delay, unsigned post_wait, bool long_pulse){
shutter_delay = speed;
pre_shutter_delay = pre_delay;
post_shutter_delay = post_wait;
shutter_long_pulse = long_pulse;
}
void Pano::setShots(unsigned shots){
shots_per_position = shots;
}
void Pano::setMode(unsigned mode){
}
unsigned Pano::getHorizShots(void){
return horiz_count;
}
unsigned Pano::getVertShots(void){
return vert_count;
}
int Pano::getCurRow(void){
return position / horiz_count;
}
int Pano::getCurCol(void){
return position % horiz_count;
}
/*
* Calculate time left to complete pano.
*/
unsigned Pano::getTimeLeft(void){
int photos = getHorizShots() * getVertShots() - position + 1;
int seconds = photos * shots_per_position * (pre_shutter_delay + shutter_delay + post_shutter_delay) / 1000 +
// time needed to move the platform
// each photo requires a horizontal move (except last one in each row)
(photos - photos/horiz_count) * camera.getHorizFOV() * horiz_gear_ratio * 60 / DYNAMIC_RPM(HORIZ_MOTOR_RPM, camera.getHorizFOV()) / 360 +
// row-to-row movement
photos / horiz_count * camera.getVertFOV() * vert_gear_ratio * 60 / DYNAMIC_RPM(VERT_MOTOR_RPM, camera.getVertFOV()) / 360 +
// row return horizontal movement
photos / horiz_count * horiz_fov * 60 / HORIZ_MOTOR_RPM / 360;
return seconds;
}
/*
* Helper to calculate grid fit with overlap
* @param total_size: entire grid size (1-360 degrees)
* @param overlap: min required overlap in percent (1-99)
* @param block_size: ref to initial (max) block size (will be updated)
* @param count: ref to image count (will be updated)
*/
void Pano::gridFit(int total_size, int overlap, float& block_size, int& count){
if (block_size <= total_size){
/*
* For 360 pano, we need to cover entire circle plus overlap.
* For smaller panos, we cover the requested size only.
*/
if (total_size != 360){
total_size = ceil(total_size - block_size * overlap/100);
}
block_size = block_size * (100-overlap) / 100;
count = ceil(total_size / block_size);
block_size = float(total_size) / count;
} else {
count = 1;
}
}
/*
* Calculate shot-to-shot horizontal/vertical head movement,
* taking overlap into account
* Must be called every time focal distance or panorama dimensions change.
*/
void Pano::computeGrid(void){
horiz_move = camera.getHorizFOV();
gridFit(horiz_fov, MIN_OVERLAP, horiz_move, horiz_count);
vert_move = camera.getVertFOV();
gridFit(vert_fov, MIN_OVERLAP, vert_move, vert_count);
}
void Pano::start(void){
computeGrid();
motorsEnable(true);
horiz_motor.setRPM(HORIZ_MOTOR_RPM);
vert_motor.setRPM(VERT_MOTOR_RPM);
// set start position
setMotorsHomePosition();
position = 0;
}
void Pano::shutter(void){
delay(pre_shutter_delay);
for (unsigned i=shots_per_position; i; i--){
camera.shutter(shutter_delay, shutter_long_pulse);
delay(post_shutter_delay);
}
}
/*
* Move to grid position by photo index (0-number of photos)
*/
bool Pano::moveTo(int new_position){
int new_row = new_position / horiz_count;
int new_col = new_position % horiz_count;
return moveTo(new_row, new_col);
}
/*
* Move to specified grid position
* @param new_row: requested row position [0 - vert_count)
* @param new_col: requested col position [0 - horiz_count)
*/
bool Pano::moveTo(int new_row, int new_col){
int cur_row = getCurRow();
int cur_col = getCurCol();
if (cur_row >= vert_count ||
new_row >= vert_count ||
new_col >= horiz_count ||
new_col < 0 ||
new_row < 0){
// beyond last/first row or column, cannot move there.
return false;
}
if (cur_col != new_col){
// horizontal adjustment needed
// figure out shortest path around the circle
// good idea if on batteries, bad idea when power cable in use
float move = (new_col-cur_col) * horiz_move;
if (abs(move) > 180){
if (move < 0){
move = 360 + move;
} else {
move = move - 360;
}
}
moveMotorsAdaptive(move, 0);
}
if (cur_row != new_row){
// vertical adjustment needed
moveMotorsAdaptive(0, -(new_row-cur_row)*vert_move);
}
position = new_row * horiz_count + new_col;
return true;
}
bool Pano::next(void){
return moveTo(position+1);
}
bool Pano::prev(void){
return (position > 0) ? moveTo(position-1) : false;
}
void Pano::end(void){
// move to home position
moveTo(0, 0);
}
/*
* Execute a full pano run.
*/
void Pano::run(void){
start();
do {
shutter();
} while(next());
end();
}
/*
* Remember current position as "home"
* (start tracking platform movement to be able to return to it)
*/
void Pano::setMotorsHomePosition(void){
horiz_home_offset = 0;
vert_home_offset = 0;
}
/*
* Move head requested number of degrees at an adaptive speed
*/
void Pano::moveMotorsAdaptive(float h, float v){
if (h){
horiz_motor.setRPM(DYNAMIC_HORIZ_RPM(h));
}
if (v){
vert_motor.setRPM(DYNAMIC_VERT_RPM(v));
}
moveMotors(h, v);
}
/*
* Move head requested number of degrees, fixed predefined speed
*/
void Pano::moveMotors(float h, float v){
if (h){
horiz_motor.rotate(h * horiz_gear_ratio);
horiz_home_offset += h;
}
if (v){
vert_motor.rotate(v * vert_gear_ratio);
vert_home_offset += v;
}
}
/*
* Move head back to home position
*/
void Pano::moveMotorsHome(void){
moveMotorsAdaptive(-horiz_home_offset, -vert_home_offset);
}
void Pano::motorsEnable(bool on){
digitalWrite(motors_pin, (on) ? HIGH : LOW);
delay(1);
}
|
Remove logging statement.
|
Remove logging statement.
|
C++
|
mit
|
laurb9/pano-controller,laurb9/pano-controller,laurb9/gigapanplus,laurb9/gigapanplus
|
7b2f938954180e8945f776d3e202f6a2bda1aaf9
|
third_party/subzero/src/IceRNG.cpp
|
third_party/subzero/src/IceRNG.cpp
|
//===- subzero/src/IceRNG.cpp - PRNG implementation -----------------------===//
//
// The Subzero Code Generator
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief Implements the random number generator.
///
//===----------------------------------------------------------------------===//
#include "IceRNG.h"
#include <climits>
#include <ctime>
namespace Ice {
namespace {
constexpr unsigned MAX = 2147483647;
} // end of anonymous namespace
// TODO(wala,stichnot): Switch to RNG implementation from LLVM or C++11.
//
// TODO(wala,stichnot): Make it possible to replay the RNG sequence in a
// subsequent run, for reproducing a bug. Print the seed in a comment in the
// asm output. Embed the seed in the binary via metadata that an attacker can't
// introspect.
RandomNumberGenerator::RandomNumberGenerator(uint64_t Seed, llvm::StringRef)
: State(Seed) {}
RandomNumberGenerator::RandomNumberGenerator(
uint64_t Seed, RandomizationPassesEnum RandomizationPassID, uint64_t Salt) {
constexpr unsigned NumBitsGlobalSeed = CHAR_BIT * sizeof(State);
constexpr unsigned NumBitsPassID = 4;
constexpr unsigned NumBitsSalt = 12;
static_assert(RPE_num < (1 << NumBitsPassID), "NumBitsPassID too small");
State =
Seed ^
((uint64_t)RandomizationPassID << (NumBitsGlobalSeed - NumBitsPassID)) ^
(Salt << (NumBitsGlobalSeed - NumBitsPassID - NumBitsSalt));
}
uint64_t RandomNumberGenerator::next(uint64_t Max) {
// Lewis, Goodman, and Miller (1969)
State = (16807 * State) % MAX;
return State % Max;
}
bool RandomNumberGeneratorWrapper::getTrueWithProbability(float Probability) {
return RNG.next(MAX) < Probability * MAX;
}
} // end of namespace Ice
|
//===- subzero/src/IceRNG.cpp - PRNG implementation -----------------------===//
//
// The Subzero Code Generator
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief Implements the random number generator.
///
//===----------------------------------------------------------------------===//
#include "IceRNG.h"
#include <climits>
#include <ctime>
namespace Ice {
namespace {
constexpr unsigned MAX = 2147483647;
} // end of anonymous namespace
// TODO(wala,stichnot): Switch to RNG implementation from LLVM or C++11.
//
// TODO(wala,stichnot): Make it possible to replay the RNG sequence in a
// subsequent run, for reproducing a bug. Print the seed in a comment in the
// asm output. Embed the seed in the binary via metadata that an attacker can't
// introspect.
RandomNumberGenerator::RandomNumberGenerator(uint64_t Seed, llvm::StringRef)
: State(Seed) {}
RandomNumberGenerator::RandomNumberGenerator(
uint64_t Seed, RandomizationPassesEnum RandomizationPassID, uint64_t Salt) {
constexpr unsigned NumBitsGlobalSeed = CHAR_BIT * sizeof(State);
constexpr unsigned NumBitsPassID = 4;
constexpr unsigned NumBitsSalt = 12;
static_assert(RPE_num < (1 << NumBitsPassID), "NumBitsPassID too small");
State =
Seed ^
((uint64_t)RandomizationPassID << (NumBitsGlobalSeed - NumBitsPassID)) ^
(Salt << (NumBitsGlobalSeed - NumBitsPassID - NumBitsSalt));
}
uint64_t RandomNumberGenerator::next(uint64_t Max) {
// Lewis, Goodman, and Miller (1969)
State = (16807 * State) % MAX;
return State % Max;
}
bool RandomNumberGeneratorWrapper::getTrueWithProbability(float Probability) {
return static_cast<float>(RNG.next(MAX)) < Probability * static_cast<float>(MAX);
}
} // end of namespace Ice
|
Fix implicit inexact conversion
|
Fix implicit inexact conversion
Clang 10's -Wimplicit-int-float-conversion complains that
MAX = 2147483647 cannot be exactly represented as a float.
Use an explicit conversion to suppress the warning locally. Note that
this value's usage to produce a random boolean doesn't critically depend
on exact conversion.
Bug: b/152777669
Change-Id: I1136ca16dcb842b97f4a76a6ed3e1c3333e814f8
Reviewed-on: https://swiftshader-review.googlesource.com/c/SwiftShader/+/51488
Tested-by: Nicolas Capens <[email protected]>
Commit-Queue: Nicolas Capens <[email protected]>
Kokoro-Result: kokoro <[email protected]>
Reviewed-by: Antonio Maiorano <[email protected]>
|
C++
|
apache-2.0
|
bkaradzic/SwiftShader,google/swiftshader,google/swiftshader,google/swiftshader,bkaradzic/SwiftShader,bkaradzic/SwiftShader,bkaradzic/SwiftShader,bkaradzic/SwiftShader
|
022f3224d3da885c6cf25b845d0dc0477b633cee
|
tools/memory_watcher/call_stack.cc
|
tools/memory_watcher/call_stack.cc
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "tools/memory_watcher/call_stack.h"
#include <shlwapi.h>
#include <tlhelp32.h>
#include "base/string_number_conversions.h"
#include "tools/memory_watcher/memory_hook.h"
// Typedefs for explicit dynamic linking with functions exported from
// dbghelp.dll.
typedef BOOL (__stdcall *t_StackWalk64)(DWORD, HANDLE, HANDLE,
LPSTACKFRAME64, PVOID,
PREAD_PROCESS_MEMORY_ROUTINE64,
PFUNCTION_TABLE_ACCESS_ROUTINE64,
PGET_MODULE_BASE_ROUTINE64,
PTRANSLATE_ADDRESS_ROUTINE64);
typedef PVOID (__stdcall *t_SymFunctionTableAccess64)(HANDLE, DWORD64);
typedef DWORD64 (__stdcall *t_SymGetModuleBase64)(HANDLE, DWORD64);
typedef BOOL (__stdcall *t_SymCleanup)(HANDLE);
typedef BOOL (__stdcall *t_SymGetSymFromAddr64)(HANDLE, DWORD64,
PDWORD64, PIMAGEHLP_SYMBOL64);
typedef BOOL (__stdcall *t_SymGetLineFromAddr64)(HANDLE, DWORD64, PDWORD,
PIMAGEHLP_LINE64);
typedef BOOL (__stdcall *t_SymInitialize)(HANDLE, PCTSTR, BOOL);
typedef DWORD (__stdcall *t_SymGetOptions)(void);
typedef DWORD (__stdcall *t_SymSetOptions)(DWORD);
typedef BOOL (__stdcall *t_SymGetSearchPath)(HANDLE, PTSTR, DWORD);
typedef DWORD64 (__stdcall *t_SymLoadModule64)(HANDLE, HANDLE, PCSTR,
PCSTR, DWORD64, DWORD);
typedef BOOL (__stdcall *t_SymGetModuleInfo64)(HANDLE, DWORD64,
PIMAGEHLP_MODULE64);
// static
base:Lock CallStack::dbghelp_lock_;
// static
bool CallStack::dbghelp_loaded_ = false;
// static
DWORD CallStack::active_thread_id_ = 0;
static t_StackWalk64 pStackWalk64 = NULL;
static t_SymCleanup pSymCleanup = NULL;
static t_SymGetSymFromAddr64 pSymGetSymFromAddr64 = NULL;
static t_SymFunctionTableAccess64 pSymFunctionTableAccess64 = NULL;
static t_SymGetModuleBase64 pSymGetModuleBase64 = NULL;
static t_SymGetLineFromAddr64 pSymGetLineFromAddr64 = NULL;
static t_SymInitialize pSymInitialize = NULL;
static t_SymGetOptions pSymGetOptions = NULL;
static t_SymSetOptions pSymSetOptions = NULL;
static t_SymGetModuleInfo64 pSymGetModuleInfo64 = NULL;
static t_SymGetSearchPath pSymGetSearchPath = NULL;
static t_SymLoadModule64 pSymLoadModule64 = NULL;
#define LOADPROC(module, name) do { \
p##name = reinterpret_cast<t_##name>(GetProcAddress(module, #name)); \
if (p##name == NULL) return false; \
} while (0)
// This code has to be VERY careful to not induce any allocations, as memory
// watching code may cause recursion, which may obscure the stack for the truly
// offensive issue. We use this function to break into a debugger, and it
// is guaranteed to not do any allocations (in fact, not do anything).
static void UltraSafeDebugBreak() {
_asm int(3);
}
// static
bool CallStack::LoadDbgHelp() {
if (!dbghelp_loaded_) {
base::AutoLock Lock(dbghelp_lock_);
// Re-check if we've loaded successfully now that we have the lock.
if (dbghelp_loaded_)
return true;
// Load dbghelp.dll, and obtain pointers to the exported functions that we
// will be using.
HMODULE dbghelp_module = LoadLibrary(L"dbghelp.dll");
if (dbghelp_module) {
LOADPROC(dbghelp_module, StackWalk64);
LOADPROC(dbghelp_module, SymFunctionTableAccess64);
LOADPROC(dbghelp_module, SymGetModuleBase64);
LOADPROC(dbghelp_module, SymCleanup);
LOADPROC(dbghelp_module, SymGetSymFromAddr64);
LOADPROC(dbghelp_module, SymGetLineFromAddr64);
LOADPROC(dbghelp_module, SymInitialize);
LOADPROC(dbghelp_module, SymGetOptions);
LOADPROC(dbghelp_module, SymSetOptions);
LOADPROC(dbghelp_module, SymGetModuleInfo64);
LOADPROC(dbghelp_module, SymGetSearchPath);
LOADPROC(dbghelp_module, SymLoadModule64);
dbghelp_loaded_ = true;
} else {
UltraSafeDebugBreak();
return false;
}
}
return dbghelp_loaded_;
}
// Load the symbols for generating stack traces.
static bool LoadSymbols(HANDLE process_handle) {
static bool symbols_loaded = false;
if (symbols_loaded) return true;
BOOL ok;
// Initialize the symbol engine.
ok = pSymInitialize(process_handle, /* hProcess */
NULL, /* UserSearchPath */
FALSE); /* fInvadeProcess */
if (!ok) return false;
DWORD options = pSymGetOptions();
options |= SYMOPT_LOAD_LINES;
options |= SYMOPT_FAIL_CRITICAL_ERRORS;
options |= SYMOPT_UNDNAME;
options = pSymSetOptions(options);
const DWORD kMaxSearchPath = 1024;
TCHAR buf[kMaxSearchPath] = {0};
ok = pSymGetSearchPath(process_handle, buf, kMaxSearchPath);
if (!ok)
return false;
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE,
GetCurrentProcessId());
if (snapshot == INVALID_HANDLE_VALUE)
return false;
MODULEENTRY32W module;
module.dwSize = sizeof(module); // Set the size of the structure.
BOOL cont = Module32FirstW(snapshot, &module);
while (cont) {
DWORD64 base;
// NOTE the SymLoadModule64 function has the peculiarity of accepting a
// both unicode and ASCII strings even though the parameter is PSTR.
base = pSymLoadModule64(process_handle,
0,
reinterpret_cast<PSTR>(module.szExePath),
reinterpret_cast<PSTR>(module.szModule),
reinterpret_cast<DWORD64>(module.modBaseAddr),
module.modBaseSize);
if (base == 0) {
int err = GetLastError();
if (err != ERROR_MOD_NOT_FOUND && err != ERROR_INVALID_HANDLE)
return false;
}
cont = Module32NextW(snapshot, &module);
}
CloseHandle(snapshot);
symbols_loaded = true;
return true;
}
CallStack::SymbolCache* CallStack::symbol_cache_;
bool CallStack::Initialize() {
// We need to delay load the symbol cache until after
// the MemoryHook heap is alive.
symbol_cache_ = new SymbolCache();
return LoadDbgHelp();
}
CallStack::CallStack() {
static LONG callstack_id = 0;
frame_count_ = 0;
hash_ = 0;
id_ = InterlockedIncrement(&callstack_id);
valid_ = false;
if (!dbghelp_loaded_) {
UltraSafeDebugBreak(); // Initialize should have been called.
return;
}
GetStackTrace();
}
bool CallStack::IsEqual(const CallStack &target) {
if (frame_count_ != target.frame_count_)
return false; // They can't be equal if the sizes are different.
// Walk the frames array until we
// either find a mismatch, or until we reach the end of the call stacks.
for (int index = 0; index < frame_count_; index++) {
if (frames_[index] != target.frames_[index])
return false; // Found a mismatch. They are not equal.
}
// Reached the end of the call stacks. They are equal.
return true;
}
void CallStack::AddFrame(DWORD_PTR pc) {
DCHECK(frame_count_ < kMaxTraceFrames);
frames_[frame_count_++] = pc;
// Create a unique id for this CallStack.
pc = pc + (frame_count_ * 13); // Alter the PC based on position in stack.
hash_ = ~hash_ + (pc << 15);
hash_ = hash_ ^ (pc >> 12);
hash_ = hash_ + (pc << 2);
hash_ = hash_ ^ (pc >> 4);
hash_ = hash_ * 2057;
hash_ = hash_ ^ (pc >> 16);
}
bool CallStack::LockedRecursionDetected() const {
if (!active_thread_id_) return false;
DWORD thread_id = GetCurrentThreadId();
// TODO(jar): Perchance we should use atomic access to member.
return thread_id == active_thread_id_;
}
bool CallStack::GetStackTrace() {
if (LockedRecursionDetected())
return false;
// Initialize the context record.
CONTEXT context;
memset(&context, 0, sizeof(context));
context.ContextFlags = CONTEXT_FULL;
__asm call x
__asm x: pop eax
__asm mov context.Eip, eax
__asm mov context.Ebp, ebp
__asm mov context.Esp, esp
STACKFRAME64 frame;
memset(&frame, 0, sizeof(frame));
#ifdef _M_IX86
DWORD image_type = IMAGE_FILE_MACHINE_I386;
frame.AddrPC.Offset = context.Eip;
frame.AddrPC.Mode = AddrModeFlat;
frame.AddrFrame.Offset = context.Ebp;
frame.AddrFrame.Mode = AddrModeFlat;
frame.AddrStack.Offset = context.Esp;
frame.AddrStack.Mode = AddrModeFlat;
#elif
NOT IMPLEMENTED!
#endif
HANDLE current_process = GetCurrentProcess();
HANDLE current_thread = GetCurrentThread();
// Walk the stack.
unsigned int count = 0;
{
AutoDbgHelpLock thread_monitoring_lock;
while (count < kMaxTraceFrames) {
count++;
if (!pStackWalk64(image_type,
current_process,
current_thread,
&frame,
&context,
0,
pSymFunctionTableAccess64,
pSymGetModuleBase64,
NULL))
break; // Couldn't trace back through any more frames.
if (frame.AddrFrame.Offset == 0)
continue; // End of stack.
// Push this frame's program counter onto the provided CallStack.
AddFrame((DWORD_PTR)frame.AddrPC.Offset);
}
valid_ = true;
}
return true;
}
void CallStack::ToString(PrivateAllocatorString* output) {
static const int kStackWalkMaxNameLen = MAX_SYM_NAME;
HANDLE current_process = GetCurrentProcess();
if (!LoadSymbols(current_process)) {
*output = "Error";
return;
}
base::AutoLock lock(dbghelp_lock_);
// Iterate through each frame in the call stack.
for (int32 index = 0; index < frame_count_; index++) {
PrivateAllocatorString line;
DWORD_PTR intruction_pointer = frame(index);
SymbolCache::iterator it;
it = symbol_cache_->find(intruction_pointer);
if (it != symbol_cache_->end()) {
line = it->second;
} else {
// Try to locate a symbol for this frame.
DWORD64 symbol_displacement = 0;
ULONG64 buffer[(sizeof(IMAGEHLP_SYMBOL64) +
sizeof(TCHAR)*kStackWalkMaxNameLen +
sizeof(ULONG64) - 1) / sizeof(ULONG64)];
IMAGEHLP_SYMBOL64* symbol = reinterpret_cast<IMAGEHLP_SYMBOL64*>(buffer);
memset(buffer, 0, sizeof(buffer));
symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
symbol->MaxNameLength = kStackWalkMaxNameLen;
BOOL ok = pSymGetSymFromAddr64(current_process, // hProcess
intruction_pointer, // Address
&symbol_displacement, // Displacement
symbol); // Symbol
if (ok) {
// Try to locate more source information for the symbol.
IMAGEHLP_LINE64 Line;
memset(&Line, 0, sizeof(Line));
Line.SizeOfStruct = sizeof(Line);
DWORD line_displacement;
ok = pSymGetLineFromAddr64(current_process,
intruction_pointer,
&line_displacement,
&Line);
if (ok) {
// Skip junk symbols from our internal stuff.
if (strstr(symbol->Name, "CallStack::") ||
strstr(symbol->Name, "MemoryWatcher::") ||
strstr(symbol->Name, "Perftools_") ||
strstr(symbol->Name, "MemoryHook::") ) {
// Just record a blank string.
(*symbol_cache_)[intruction_pointer] = "";
continue;
}
line += " ";
line += static_cast<char*>(Line.FileName);
line += " (";
// TODO(jar): get something like this template to work :-/
// line += IntToCustomString<PrivateAllocatorString>(Line.LineNumber);
// ...and then delete this line, which uses std::string.
line += base::IntToString(Line.LineNumber).c_str();
line += "): ";
line += symbol->Name;
line += "\n";
} else {
line += " unknown (0):";
line += symbol->Name;
line += "\n";
}
} else {
// OK - couldn't get any info. Try for the module.
IMAGEHLP_MODULE64 module_info;
module_info.SizeOfStruct = sizeof(module_info);
if (pSymGetModuleInfo64(current_process, intruction_pointer,
&module_info)) {
line += " (";
line += static_cast<char*>(module_info.ModuleName);
line += ")\n";
} else {
line += " ???\n";
}
}
}
(*symbol_cache_)[intruction_pointer] = line;
*output += line;
}
*output += "==================\n";
}
base::Lock AllocationStack::freelist_lock_;
AllocationStack* AllocationStack::freelist_ = NULL;
void* AllocationStack::operator new(size_t size) {
DCHECK(size == sizeof(AllocationStack));
{
base::AutoLock lock(freelist_lock_);
if (freelist_ != NULL) {
AllocationStack* stack = freelist_;
freelist_ = freelist_->next_;
stack->next_ = NULL;
return stack;
}
}
return MemoryHook::Alloc(size);
}
void AllocationStack::operator delete(void* ptr) {
AllocationStack *stack = reinterpret_cast<AllocationStack*>(ptr);
base::AutoLock lock(freelist_lock_);
DCHECK(stack->next_ == NULL);
stack->next_ = freelist_;
freelist_ = stack;
}
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "tools/memory_watcher/call_stack.h"
#include <shlwapi.h>
#include <tlhelp32.h>
#include "base/string_number_conversions.h"
#include "tools/memory_watcher/memory_hook.h"
// Typedefs for explicit dynamic linking with functions exported from
// dbghelp.dll.
typedef BOOL (__stdcall *t_StackWalk64)(DWORD, HANDLE, HANDLE,
LPSTACKFRAME64, PVOID,
PREAD_PROCESS_MEMORY_ROUTINE64,
PFUNCTION_TABLE_ACCESS_ROUTINE64,
PGET_MODULE_BASE_ROUTINE64,
PTRANSLATE_ADDRESS_ROUTINE64);
typedef PVOID (__stdcall *t_SymFunctionTableAccess64)(HANDLE, DWORD64);
typedef DWORD64 (__stdcall *t_SymGetModuleBase64)(HANDLE, DWORD64);
typedef BOOL (__stdcall *t_SymCleanup)(HANDLE);
typedef BOOL (__stdcall *t_SymGetSymFromAddr64)(HANDLE, DWORD64,
PDWORD64, PIMAGEHLP_SYMBOL64);
typedef BOOL (__stdcall *t_SymGetLineFromAddr64)(HANDLE, DWORD64, PDWORD,
PIMAGEHLP_LINE64);
typedef BOOL (__stdcall *t_SymInitialize)(HANDLE, PCTSTR, BOOL);
typedef DWORD (__stdcall *t_SymGetOptions)(void);
typedef DWORD (__stdcall *t_SymSetOptions)(DWORD);
typedef BOOL (__stdcall *t_SymGetSearchPath)(HANDLE, PTSTR, DWORD);
typedef DWORD64 (__stdcall *t_SymLoadModule64)(HANDLE, HANDLE, PCSTR,
PCSTR, DWORD64, DWORD);
typedef BOOL (__stdcall *t_SymGetModuleInfo64)(HANDLE, DWORD64,
PIMAGEHLP_MODULE64);
// static
base::Lock CallStack::dbghelp_lock_;
// static
bool CallStack::dbghelp_loaded_ = false;
// static
DWORD CallStack::active_thread_id_ = 0;
static t_StackWalk64 pStackWalk64 = NULL;
static t_SymCleanup pSymCleanup = NULL;
static t_SymGetSymFromAddr64 pSymGetSymFromAddr64 = NULL;
static t_SymFunctionTableAccess64 pSymFunctionTableAccess64 = NULL;
static t_SymGetModuleBase64 pSymGetModuleBase64 = NULL;
static t_SymGetLineFromAddr64 pSymGetLineFromAddr64 = NULL;
static t_SymInitialize pSymInitialize = NULL;
static t_SymGetOptions pSymGetOptions = NULL;
static t_SymSetOptions pSymSetOptions = NULL;
static t_SymGetModuleInfo64 pSymGetModuleInfo64 = NULL;
static t_SymGetSearchPath pSymGetSearchPath = NULL;
static t_SymLoadModule64 pSymLoadModule64 = NULL;
#define LOADPROC(module, name) do { \
p##name = reinterpret_cast<t_##name>(GetProcAddress(module, #name)); \
if (p##name == NULL) return false; \
} while (0)
// This code has to be VERY careful to not induce any allocations, as memory
// watching code may cause recursion, which may obscure the stack for the truly
// offensive issue. We use this function to break into a debugger, and it
// is guaranteed to not do any allocations (in fact, not do anything).
static void UltraSafeDebugBreak() {
_asm int(3);
}
// static
bool CallStack::LoadDbgHelp() {
if (!dbghelp_loaded_) {
base::AutoLock Lock(dbghelp_lock_);
// Re-check if we've loaded successfully now that we have the lock.
if (dbghelp_loaded_)
return true;
// Load dbghelp.dll, and obtain pointers to the exported functions that we
// will be using.
HMODULE dbghelp_module = LoadLibrary(L"dbghelp.dll");
if (dbghelp_module) {
LOADPROC(dbghelp_module, StackWalk64);
LOADPROC(dbghelp_module, SymFunctionTableAccess64);
LOADPROC(dbghelp_module, SymGetModuleBase64);
LOADPROC(dbghelp_module, SymCleanup);
LOADPROC(dbghelp_module, SymGetSymFromAddr64);
LOADPROC(dbghelp_module, SymGetLineFromAddr64);
LOADPROC(dbghelp_module, SymInitialize);
LOADPROC(dbghelp_module, SymGetOptions);
LOADPROC(dbghelp_module, SymSetOptions);
LOADPROC(dbghelp_module, SymGetModuleInfo64);
LOADPROC(dbghelp_module, SymGetSearchPath);
LOADPROC(dbghelp_module, SymLoadModule64);
dbghelp_loaded_ = true;
} else {
UltraSafeDebugBreak();
return false;
}
}
return dbghelp_loaded_;
}
// Load the symbols for generating stack traces.
static bool LoadSymbols(HANDLE process_handle) {
static bool symbols_loaded = false;
if (symbols_loaded) return true;
BOOL ok;
// Initialize the symbol engine.
ok = pSymInitialize(process_handle, /* hProcess */
NULL, /* UserSearchPath */
FALSE); /* fInvadeProcess */
if (!ok) return false;
DWORD options = pSymGetOptions();
options |= SYMOPT_LOAD_LINES;
options |= SYMOPT_FAIL_CRITICAL_ERRORS;
options |= SYMOPT_UNDNAME;
options = pSymSetOptions(options);
const DWORD kMaxSearchPath = 1024;
TCHAR buf[kMaxSearchPath] = {0};
ok = pSymGetSearchPath(process_handle, buf, kMaxSearchPath);
if (!ok)
return false;
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE,
GetCurrentProcessId());
if (snapshot == INVALID_HANDLE_VALUE)
return false;
MODULEENTRY32W module;
module.dwSize = sizeof(module); // Set the size of the structure.
BOOL cont = Module32FirstW(snapshot, &module);
while (cont) {
DWORD64 base;
// NOTE the SymLoadModule64 function has the peculiarity of accepting a
// both unicode and ASCII strings even though the parameter is PSTR.
base = pSymLoadModule64(process_handle,
0,
reinterpret_cast<PSTR>(module.szExePath),
reinterpret_cast<PSTR>(module.szModule),
reinterpret_cast<DWORD64>(module.modBaseAddr),
module.modBaseSize);
if (base == 0) {
int err = GetLastError();
if (err != ERROR_MOD_NOT_FOUND && err != ERROR_INVALID_HANDLE)
return false;
}
cont = Module32NextW(snapshot, &module);
}
CloseHandle(snapshot);
symbols_loaded = true;
return true;
}
CallStack::SymbolCache* CallStack::symbol_cache_;
bool CallStack::Initialize() {
// We need to delay load the symbol cache until after
// the MemoryHook heap is alive.
symbol_cache_ = new SymbolCache();
return LoadDbgHelp();
}
CallStack::CallStack() {
static LONG callstack_id = 0;
frame_count_ = 0;
hash_ = 0;
id_ = InterlockedIncrement(&callstack_id);
valid_ = false;
if (!dbghelp_loaded_) {
UltraSafeDebugBreak(); // Initialize should have been called.
return;
}
GetStackTrace();
}
bool CallStack::IsEqual(const CallStack &target) {
if (frame_count_ != target.frame_count_)
return false; // They can't be equal if the sizes are different.
// Walk the frames array until we
// either find a mismatch, or until we reach the end of the call stacks.
for (int index = 0; index < frame_count_; index++) {
if (frames_[index] != target.frames_[index])
return false; // Found a mismatch. They are not equal.
}
// Reached the end of the call stacks. They are equal.
return true;
}
void CallStack::AddFrame(DWORD_PTR pc) {
DCHECK(frame_count_ < kMaxTraceFrames);
frames_[frame_count_++] = pc;
// Create a unique id for this CallStack.
pc = pc + (frame_count_ * 13); // Alter the PC based on position in stack.
hash_ = ~hash_ + (pc << 15);
hash_ = hash_ ^ (pc >> 12);
hash_ = hash_ + (pc << 2);
hash_ = hash_ ^ (pc >> 4);
hash_ = hash_ * 2057;
hash_ = hash_ ^ (pc >> 16);
}
bool CallStack::LockedRecursionDetected() const {
if (!active_thread_id_) return false;
DWORD thread_id = GetCurrentThreadId();
// TODO(jar): Perchance we should use atomic access to member.
return thread_id == active_thread_id_;
}
bool CallStack::GetStackTrace() {
if (LockedRecursionDetected())
return false;
// Initialize the context record.
CONTEXT context;
memset(&context, 0, sizeof(context));
context.ContextFlags = CONTEXT_FULL;
__asm call x
__asm x: pop eax
__asm mov context.Eip, eax
__asm mov context.Ebp, ebp
__asm mov context.Esp, esp
STACKFRAME64 frame;
memset(&frame, 0, sizeof(frame));
#ifdef _M_IX86
DWORD image_type = IMAGE_FILE_MACHINE_I386;
frame.AddrPC.Offset = context.Eip;
frame.AddrPC.Mode = AddrModeFlat;
frame.AddrFrame.Offset = context.Ebp;
frame.AddrFrame.Mode = AddrModeFlat;
frame.AddrStack.Offset = context.Esp;
frame.AddrStack.Mode = AddrModeFlat;
#elif
NOT IMPLEMENTED!
#endif
HANDLE current_process = GetCurrentProcess();
HANDLE current_thread = GetCurrentThread();
// Walk the stack.
unsigned int count = 0;
{
AutoDbgHelpLock thread_monitoring_lock;
while (count < kMaxTraceFrames) {
count++;
if (!pStackWalk64(image_type,
current_process,
current_thread,
&frame,
&context,
0,
pSymFunctionTableAccess64,
pSymGetModuleBase64,
NULL))
break; // Couldn't trace back through any more frames.
if (frame.AddrFrame.Offset == 0)
continue; // End of stack.
// Push this frame's program counter onto the provided CallStack.
AddFrame((DWORD_PTR)frame.AddrPC.Offset);
}
valid_ = true;
}
return true;
}
void CallStack::ToString(PrivateAllocatorString* output) {
static const int kStackWalkMaxNameLen = MAX_SYM_NAME;
HANDLE current_process = GetCurrentProcess();
if (!LoadSymbols(current_process)) {
*output = "Error";
return;
}
base::AutoLock lock(dbghelp_lock_);
// Iterate through each frame in the call stack.
for (int32 index = 0; index < frame_count_; index++) {
PrivateAllocatorString line;
DWORD_PTR intruction_pointer = frame(index);
SymbolCache::iterator it;
it = symbol_cache_->find(intruction_pointer);
if (it != symbol_cache_->end()) {
line = it->second;
} else {
// Try to locate a symbol for this frame.
DWORD64 symbol_displacement = 0;
ULONG64 buffer[(sizeof(IMAGEHLP_SYMBOL64) +
sizeof(TCHAR)*kStackWalkMaxNameLen +
sizeof(ULONG64) - 1) / sizeof(ULONG64)];
IMAGEHLP_SYMBOL64* symbol = reinterpret_cast<IMAGEHLP_SYMBOL64*>(buffer);
memset(buffer, 0, sizeof(buffer));
symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
symbol->MaxNameLength = kStackWalkMaxNameLen;
BOOL ok = pSymGetSymFromAddr64(current_process, // hProcess
intruction_pointer, // Address
&symbol_displacement, // Displacement
symbol); // Symbol
if (ok) {
// Try to locate more source information for the symbol.
IMAGEHLP_LINE64 Line;
memset(&Line, 0, sizeof(Line));
Line.SizeOfStruct = sizeof(Line);
DWORD line_displacement;
ok = pSymGetLineFromAddr64(current_process,
intruction_pointer,
&line_displacement,
&Line);
if (ok) {
// Skip junk symbols from our internal stuff.
if (strstr(symbol->Name, "CallStack::") ||
strstr(symbol->Name, "MemoryWatcher::") ||
strstr(symbol->Name, "Perftools_") ||
strstr(symbol->Name, "MemoryHook::") ) {
// Just record a blank string.
(*symbol_cache_)[intruction_pointer] = "";
continue;
}
line += " ";
line += static_cast<char*>(Line.FileName);
line += " (";
// TODO(jar): get something like this template to work :-/
// line += IntToCustomString<PrivateAllocatorString>(Line.LineNumber);
// ...and then delete this line, which uses std::string.
line += base::IntToString(Line.LineNumber).c_str();
line += "): ";
line += symbol->Name;
line += "\n";
} else {
line += " unknown (0):";
line += symbol->Name;
line += "\n";
}
} else {
// OK - couldn't get any info. Try for the module.
IMAGEHLP_MODULE64 module_info;
module_info.SizeOfStruct = sizeof(module_info);
if (pSymGetModuleInfo64(current_process, intruction_pointer,
&module_info)) {
line += " (";
line += static_cast<char*>(module_info.ModuleName);
line += ")\n";
} else {
line += " ???\n";
}
}
}
(*symbol_cache_)[intruction_pointer] = line;
*output += line;
}
*output += "==================\n";
}
base::Lock AllocationStack::freelist_lock_;
AllocationStack* AllocationStack::freelist_ = NULL;
void* AllocationStack::operator new(size_t size) {
DCHECK(size == sizeof(AllocationStack));
{
base::AutoLock lock(freelist_lock_);
if (freelist_ != NULL) {
AllocationStack* stack = freelist_;
freelist_ = freelist_->next_;
stack->next_ = NULL;
return stack;
}
}
return MemoryHook::Alloc(size);
}
void AllocationStack::operator delete(void* ptr) {
AllocationStack *stack = reinterpret_cast<AllocationStack*>(ptr);
base::AutoLock lock(freelist_lock_);
DCHECK(stack->next_ == NULL);
stack->next_ = freelist_;
freelist_ = stack;
}
|
Fix typo in build fix.
|
Fix typo in build fix.
TEST=it compiles
BUG=none
Review URL: http://codereview.chromium.org/6346011
git-svn-id: http://src.chromium.org/svn/trunk/src@72112 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Former-commit-id: 0fb2d73110002a7cd70d00ecdcb19ef183bab386
|
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
|
8c529521fc83b48a58667d7619690d5ca4b58847
|
src/libaten/material/material.cpp
|
src/libaten/material/material.cpp
|
#include <atomic>
#include "material/material.h"
#include "light/light.h"
#include "material/sample_texture.h"
namespace AT_NAME
{
static const char* g_mtrlTypeNames[] = {
"emissive",
"lambert",
"ornenayar",
"specular",
"refraction",
"blinn",
"ggx",
"beckman",
"velvet",
"lambert_refraction",
"microfacet_refraction",
"disney_brdf",
"carpaint",
"toon",
"layer",
};
AT_STATICASSERT(AT_COUNTOF(g_mtrlTypeNames) == (int)aten::MaterialType::MaterialTypeMax);
const char* material::getMaterialTypeName(aten::MaterialType type)
{
AT_ASSERT(static_cast<int>(type) < AT_COUNTOF(g_mtrlTypeNames));
return g_mtrlTypeNames[type];
}
aten::MaterialType material::getMaterialTypeFromMaterialTypeName(const std::string& name)
{
std::string lowerName = name;
std::transform(lowerName.begin(), lowerName.end(), lowerName.begin(), ::tolower);
for (int i = 0; i < AT_COUNTOF(g_mtrlTypeNames); i++) {
auto mtrlName = g_mtrlTypeNames[i];
if (lowerName == mtrlName) {
return static_cast<aten::MaterialType>(i);
}
}
AT_ASSERT(false);
return aten::MaterialType::MaterialTypeMax;
}
bool material::isDefaultMaterialName(const std::string& name)
{
auto lower = name;
std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
for (const char* mtrl_name : g_mtrlTypeNames) {
if (lower == mtrl_name) {
return true;
}
}
return false;
}
bool material::isValidMaterialType(aten::MaterialType type)
{
return (0 <= type && type < aten::MaterialType::MaterialTypeMax);
}
void material::resetIdWhenAnyMaterialLeave(AT_NAME::material* mtrl)
{
mtrl->m_id = mtrl->m_listItem.currentIndex();
}
material::material(
aten::MaterialType type,
const aten::MaterialAttribute& attrib)
: m_param(type, attrib)
{
m_listItem.init(this, resetIdWhenAnyMaterialLeave);
}
material::material(
aten::MaterialType type,
const aten::MaterialAttribute& attrib,
const aten::vec3& clr,
real ior/*= 1*/,
aten::texture* albedoMap/*= nullptr*/,
aten::texture* normalMap/*= nullptr*/)
: material(type, attrib)
{
m_listItem.init(this, resetIdWhenAnyMaterialLeave);
m_param.baseColor = clr;
m_param.ior = ior;
setTextures(albedoMap, normalMap, nullptr);
}
material::material(
aten::MaterialType type,
const aten::MaterialAttribute& attrib,
aten::Values& val)
: material(type, attrib)
{
m_listItem.init(this, resetIdWhenAnyMaterialLeave);
m_param.baseColor = val.get("baseColor", m_param.baseColor);
m_param.ior = val.get("ior", m_param.ior);
auto albedoMap = (aten::texture*)val.get<void*>("albedoMap", nullptr);
auto normalMap = (aten::texture*)val.get<void*>("normalMap", nullptr);
setTextures(albedoMap, normalMap, nullptr);
}
void material::setTextures(
aten::texture* albedoMap,
aten::texture* normalMap,
aten::texture* roughnessMap)
{
m_param.albedoMap = albedoMap ? albedoMap->id() : -1;
m_param.normalMap = normalMap ? normalMap->id() : -1;
m_param.roughnessMap = roughnessMap ? roughnessMap->id() : -1;
}
material::~material()
{
m_listItem.leave();
}
NPRMaterial::NPRMaterial(
aten::MaterialType type,
const aten::vec3& e, AT_NAME::Light* light)
: material(type, MaterialAttributeNPR, e)
{
setTargetLight(light);
}
void NPRMaterial::setTargetLight(AT_NAME::Light* light)
{
m_targetLight = light;
}
const AT_NAME::Light* NPRMaterial::getTargetLight() const
{
return m_targetLight;
}
// NOTE
// Schlickによるフレネル反射率の近似.
// http://yokotakenji.me/log/math/4501/
// https://en.wikipedia.org/wiki/Schlick%27s_approximation
// NOTE
// フレネル反射率について.
// http://d.hatena.ne.jp/hanecci/20130525/p3
real schlick(
const aten::vec3& in,
const aten::vec3& normal,
real ni, real nt)
{
// NOTE
// Fschlick(v,h) ≒ R0 + (1 - R0)(1 - cosΘ)^5
// R0 = ((n1 - n2) / (n1 + n2))^2
auto r0 = (ni - nt) / (ni + nt);
r0 = r0 * r0;
auto c = dot(in, normal);
return r0 + (1 - r0) * aten::pow((1 - c), 5);
}
real computFresnel(
const aten::vec3& in,
const aten::vec3& normal,
real ni, real nt)
{
real cos_i = dot(in, normal);
bool isEnter = (cos_i > real(0));
aten::vec3 n = normal;
if (isEnter) {
// レイが出ていくので、全部反対.
auto tmp = nt;
nt = real(1);
ni = tmp;
n = -n;
}
auto eta = ni / nt;
auto sini2 = 1.f - cos_i * cos_i;
auto sint2 = eta * eta * sini2;
auto fresnel = schlick(
in,
n, ni, nt);
return fresnel;
}
AT_DEVICE_MTRL_API aten::vec3 material::sampleAlbedoMap(real u, real v) const
{
return std::move(AT_NAME::sampleTexture(m_param.albedoMap, u, v, aten::vec3(real(1))));
}
AT_DEVICE_MTRL_API void material::applyNormalMap(
const aten::vec3& orgNml,
aten::vec3& newNml,
real u, real v) const
{
AT_NAME::applyNormalMap(m_param.normalMap, orgNml, newNml, u, v);
}
}
|
#include <atomic>
#include "material/material.h"
#include "light/light.h"
#include "material/sample_texture.h"
namespace AT_NAME
{
static const char* g_mtrlTypeNames[] = {
"emissive",
"lambert",
"ornenayar",
"specular",
"refraction",
"blinn",
"ggx",
"beckman",
"velvet",
"lambert_refraction",
"microfacet_refraction",
"disney_brdf",
"carpaint",
"toon",
"layer",
};
AT_STATICASSERT(AT_COUNTOF(g_mtrlTypeNames) == (int)aten::MaterialType::MaterialTypeMax);
const char* material::getMaterialTypeName(aten::MaterialType type)
{
AT_ASSERT(static_cast<int>(type) < AT_COUNTOF(g_mtrlTypeNames));
return g_mtrlTypeNames[type];
}
aten::MaterialType material::getMaterialTypeFromMaterialTypeName(const std::string& name)
{
std::string lowerName = name;
std::transform(lowerName.begin(), lowerName.end(), lowerName.begin(), ::tolower);
for (int i = 0; i < AT_COUNTOF(g_mtrlTypeNames); i++) {
auto mtrlName = g_mtrlTypeNames[i];
if (lowerName == mtrlName) {
return static_cast<aten::MaterialType>(i);
}
}
AT_ASSERT(false);
return aten::MaterialType::MaterialTypeMax;
}
bool material::isDefaultMaterialName(const std::string& name)
{
auto lower = name;
std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
for (const char* mtrl_name : g_mtrlTypeNames) {
if (lower == mtrl_name) {
return true;
}
}
return false;
}
bool material::isValidMaterialType(aten::MaterialType type)
{
return (0 <= type && type < aten::MaterialType::MaterialTypeMax);
}
void material::resetIdWhenAnyMaterialLeave(AT_NAME::material* mtrl)
{
mtrl->m_id = mtrl->m_listItem.currentIndex();
}
material::material(
aten::MaterialType type,
const aten::MaterialAttribute& attrib)
: m_param(type, attrib)
{
m_listItem.init(this, resetIdWhenAnyMaterialLeave);
}
material::material(
aten::MaterialType type,
const aten::MaterialAttribute& attrib,
const aten::vec3& clr,
real ior/*= 1*/,
aten::texture* albedoMap/*= nullptr*/,
aten::texture* normalMap/*= nullptr*/)
: material(type, attrib)
{
m_listItem.init(this, resetIdWhenAnyMaterialLeave);
m_param.baseColor = clr;
m_param.ior = ior;
setTextures(albedoMap, normalMap, nullptr);
}
material::material(
aten::MaterialType type,
const aten::MaterialAttribute& attrib,
aten::Values& val)
: material(type, attrib)
{
m_listItem.init(this, resetIdWhenAnyMaterialLeave);
m_param.baseColor = val.get("baseColor", m_param.baseColor);
m_param.ior = val.get("ior", m_param.ior);
auto albedoMap = (aten::texture*)val.get<void*>("albedoMap", nullptr);
auto normalMap = (aten::texture*)val.get<void*>("normalMap", nullptr);
setTextures(albedoMap, normalMap, nullptr);
}
void material::setTextures(
aten::texture* albedoMap,
aten::texture* normalMap,
aten::texture* roughnessMap)
{
m_param.albedoMap = albedoMap ? albedoMap->id() : -1;
m_param.normalMap = normalMap ? normalMap->id() : -1;
m_param.roughnessMap = roughnessMap ? roughnessMap->id() : -1;
}
material::~material()
{
m_listItem.leave();
}
NPRMaterial::NPRMaterial(
aten::MaterialType type,
const aten::vec3& e, AT_NAME::Light* light)
: material(type, MaterialAttributeNPR, e)
{
setTargetLight(light);
}
void NPRMaterial::setTargetLight(AT_NAME::Light* light)
{
m_targetLight = light;
}
const AT_NAME::Light* NPRMaterial::getTargetLight() const
{
return m_targetLight;
}
// NOTE
// Schlickɂtl˗̋ߎ.
// http://yokotakenji.me/log/math/4501/
// https://en.wikipedia.org/wiki/Schlick%27s_approximation
// NOTE
// tl˗ɂ.
// http://d.hatena.ne.jp/hanecci/20130525/p3
real schlick(
const aten::vec3& in,
const aten::vec3& normal,
real ni, real nt)
{
// NOTE
// Fschlick(v,h) R0 + (1 - R0)(1 - cos)^5
// R0 = ((n1 - n2) / (n1 + n2))^2
auto r0 = (ni - nt) / (ni + nt);
r0 = r0 * r0;
auto c = dot(in, normal);
return r0 + (1 - r0) * aten::pow((1 - c), 5);
}
real computFresnel(
const aten::vec3& in,
const aten::vec3& normal,
real ni, real nt)
{
real cos_i = dot(in, normal);
bool isEnter = (cos_i > real(0));
aten::vec3 n = normal;
if (isEnter) {
// CoĂ̂ŁAS.
auto tmp = nt;
nt = real(1);
ni = tmp;
n = -n;
}
auto eta = ni / nt;
auto sini2 = 1.f - cos_i * cos_i;
auto sint2 = eta * eta * sini2;
auto fresnel = schlick(
in,
n, ni, nt);
return fresnel;
}
AT_DEVICE_MTRL_API aten::vec3 material::sampleAlbedoMap(real u, real v) const
{
return std::move(AT_NAME::sampleTexture(m_param.albedoMap, u, v, aten::vec3(real(1))));
}
AT_DEVICE_MTRL_API void material::applyNormalMap(
const aten::vec3& orgNml,
aten::vec3& newNml,
real u, real v) const
{
AT_NAME::applyNormalMap(m_param.normalMap, orgNml, newNml, u, v);
}
}
|
Fix character code
|
Fix character code
|
C++
|
mit
|
nakdai/aten,nakdai/aten
|
cb65ecb0801c3b26d3877fc7748033a45a4bf3e6
|
firmware/ros_arduino.cpp
|
firmware/ros_arduino.cpp
|
#include <string.h>
#include <ros.h>
#include <std_msgs/String.h>
#include <joystick/PwmRequests.h>
#include <uranus_dp/ThrusterForces.h>
#include "ForceToPwmLookup.h"
//incleder for IMU og trykksensor
#include "MPU6050/MPU6050.h"
#include "MS5803_14BA.h"
#include <Wire.h>
#include <ros_arduino/SensorRaw.h>
#include <geometry_msgs/Vector3.h>
#define MPU9150_I2C_ADDR 0x69
MPU6050 accelgyro(MPU9150_I2C_ADDR);
MS5803_14BA depthSensor;
ros::NodeHandle nh;
ros_arduino::SensorRaw sensor_raw_msg;
ros::Publisher pub_imu( "SensorRaw", &sensor_raw_msg);
const int SensorReadDelay = 83;
unsigned long PrevoiusSensorReadMillis = 0;
//PWM-variable:
int dbg_count = 0;
const int PwmCount = 6;
int PwmOnTime[PwmCount];
const int PwmPins[PwmCount] = { 3, 5, 6, 9, 10, 11 };
const int PwmTotalTime = 3600;
int PwmPinState[PwmCount] = { LOW, LOW, LOW, LOW, LOW, LOW };
unsigned long PreviousToggleMicros[PwmCount] = { 0, 0, 0, 0, 0, 0 };
joystick::PwmRequests pwm_status_msg;
ros::Publisher pwm_status_pub("PwmStatus", &pwm_status_msg);
std_msgs::String arduino_dbg_msg;
ros::Publisher arduino_dbg_pub("ArduinoDbg", &arduino_dbg_msg);
void pwm_update( const uranus_dp::ThrusterForces& force_input ){
PwmOnTime[0] = ForceToPwm(force_input.F1);
PwmOnTime[1] = ForceToPwm(force_input.F2);
PwmOnTime[2] = ForceToPwm(force_input.F3);
PwmOnTime[3] = ForceToPwm(force_input.F4);
PwmOnTime[4] = ForceToPwm(force_input.F5);
PwmOnTime[5] = ForceToPwm(force_input.F6);
//Send PWM-verdiene tilbake som debugoutput
pwm_status_msg.pwm1 = PwmOnTime[0];
pwm_status_msg.pwm2 = PwmOnTime[1];
pwm_status_msg.pwm3 = PwmOnTime[2];
pwm_status_msg.pwm4 = PwmOnTime[3];
pwm_status_msg.pwm5 = PwmOnTime[4];
pwm_status_msg.pwm6 = PwmOnTime[5];
dbg_count = 0;
pwm_status_pub.publish( &pwm_status_msg );
}
ros::Subscriber<uranus_dp::ThrusterForces> pwm_input_sub("controlInput", &pwm_update );
double GyroLsbSens, AccelLsbSens;
void getFsRangeAndSetLsbSensisivity() {
uint8_t GyroFsRange, AccelFsRange;
GyroFsRange = accelgyro.getFullScaleGyroRange();
/* Gyro
* FS_SEL | Full Scale Range | LSB Sensitivity
* -------+--------------------+----------------
* 0 | +/- 250 degrees/s | 131 LSB/deg/s
* 1 | +/- 500 degrees/s | 65.5 LSB/deg/s
* 2 | +/- 1000 degrees/s | 32.8 LSB/deg/s
* 3 | +/- 2000 degrees/s | 16.4 LSB/deg/s
*/
switch(GyroFsRange) {
case 0:
GyroLsbSens = 131.0;
break;
case 1:
GyroLsbSens = 65.5;
break;
case 2:
GyroLsbSens = 32.8;
break;
case 3:
GyroLsbSens = 16.4;
break;
};
AccelFsRange = accelgyro.getFullScaleAccelRange();
/*Accelerometer
* AFS_SEL | Full Scale Range | LSB Sensitivity
* --------+------------------+----------------
* 0 | +/- 2g | 16384 LSB/g
* 1 | +/- 4g | 8192 LSB/g
* 2 | +/- 8g | 4096 LSB/g
* 3 | +/- 16g | 2048 LSB/g
*/
switch(AccelFsRange) {
case 0:
AccelLsbSens = 16384.0;
break;
case 1:
AccelLsbSens = 8192.0;
break;
case 2:
AccelLsbSens = 4096.0;
break;
case 3:
AccelLsbSens = 2048.0;
break;
};
}
void setup() {
//start ROS-node
nh.initNode();
nh.advertise(pwm_status_pub);
nh.advertise(arduino_dbg_pub);
nh.advertise(pub_imu);
nh.subscribe(pwm_input_sub);
nh.spinOnce();
// Initialize the 'Wire' class for the I2C-bus.
Wire.begin();
accelgyro.initialize();
getFsRangeAndSetLsbSensisivity();
depthSensor.initialize(false);
nh.spinOnce();
String dbg_msg = String("init:\n") +
(accelgyro.testConnection() ? "MPU6050 connection successful" : "MPU6050 connection failed");
arduino_dbg_msg.data = dbg_msg.c_str();
arduino_dbg_pub.publish( &arduino_dbg_msg );
nh.spinOnce();
//sett alle motorer til 0 Newton
for(int i = 0; i < PwmCount; i++) {
PwmOnTime[i] = ForceToPwm(0);
}
}
void lesSensorer() {
int16_t ax, ay, az;
int16_t gx, gy, gz;
int16_t mx, my, mz;
accelgyro.getMotion9(&ax, &ay, &az, &gx, &gy, &gz, &mx, &my, &mz);
//Accelerometerdata enhet: [g]
sensor_raw_msg.acceleration.x = ax / AccelLsbSens;
sensor_raw_msg.acceleration.y = ay / AccelLsbSens;
sensor_raw_msg.acceleration.z = az / AccelLsbSens;
//Gyrodata: enhet [deg/s]
sensor_raw_msg.gyro.x = gx / GyroLsbSens;
sensor_raw_msg.gyro.y = gy / GyroLsbSens;
sensor_raw_msg.gyro.z = gz / GyroLsbSens;
//Kompass enhent [µT]
//TODO fin ut om 0.3 er riktig skalerinsfaktor
sensor_raw_msg.compass.x = mx * 0.3;
sensor_raw_msg.compass.y = my * 0.3;
sensor_raw_msg.compass.z = mz * 0.3;
sensor_raw_msg.temperature = ( (double)accelgyro.getTemperature() + 12412.0) / 340.0;
depthSensor.read();
sensor_raw_msg.pressure = depthSensor.getPreassure();
}
void loop(){
nh.spinOnce();
/*
//komenterte vekk IMU for å kunne bruke software-PWM uten forstyrrelser
if( millis() - PrevoiusSensorReadMillis >= SensorReadDelay ) {
PrevoiusSensorReadMillis = millis();
lesSensorer();
//nh.spinOnce();
pub_imu.publish(&sensor_raw_msg);
//nh.spinOnce();
//dbg_count++;
//nh.spinOnce();
}
*/
/*
//String dbg_msg = "pwm updated after " + String(dbg_count) + " cycles";
//String dbg_msg = "accelX = " ;//+ String(imu.read(MPU9150_ACCEL_XOUT_L, MPU9150_ACCEL_XOUT_H));
String dbg_msg = String("GyroFsRange = ") + String(GyroFsRange) +
String("\nAccelFsRange = ") + String(AccelFsRange);
arduino_dbg_msg.data = dbg_msg.c_str();
arduino_dbg_pub.publish( &arduino_dbg_msg );
nh.spinOnce();
*/
//Software-PWM
for(int i = 0; i < PwmCount; i++) {
nh.spinOnce();
unsigned long CurrentMicros = micros();
if(PwmPinState[i] == HIGH) {
if(CurrentMicros - PreviousToggleMicros[i] >= PwmOnTime[i]) {
PwmPinState[i] = LOW;
digitalWrite(PwmPins[i], PwmPinState[i]);
PreviousToggleMicros[i] = CurrentMicros;
}
} else { // (PwmPinState[i] == LOW)
if(CurrentMicros - PreviousToggleMicros[i] >= PwmTotalTime - PwmOnTime[i] ) {
PwmPinState[i] = HIGH;
digitalWrite(PwmPins[i], PwmPinState[i]);
PreviousToggleMicros[i] = CurrentMicros;
}
}
//analogWrite(pwm_pins[i], PwmOnTime[i]);
}
}
|
#include <string.h>
#include <ros.h>
#include <std_msgs/String.h>
#include <joystick/PwmRequests.h>
#include <uranus_dp/ThrusterForces.h>
#include "ForceToPwmLookup.h"
//incleder for IMU og trykksensor
#include "MPU6050/MPU6050.h"
#include "MS5803_14BA.h"
#include <Wire.h>
#include <ros_arduino/SensorRaw.h>
#include <geometry_msgs/Vector3.h>
#define MPU9150_I2C_ADDR 0x69
MPU6050 accelgyro(MPU9150_I2C_ADDR);
MS5803_14BA depthSensor;
ros::NodeHandle nh;
ros_arduino::SensorRaw sensor_raw_msg;
ros::Publisher pub_imu( "SensorRaw", &sensor_raw_msg);
const int SensorReadDelay = 83;
unsigned long PrevoiusSensorReadMillis = 0;
//PWM-variable:
int dbg_count = 0;
const int PwmCount = 6;
int PwmOnTime[PwmCount];
const int PwmPins[PwmCount] = { 3, 5, 6, 9, 10, 11 };
const int PwmTotalTime = 3600;
int PwmPinState[PwmCount] = { LOW, LOW, LOW, LOW, LOW, LOW };
unsigned long PreviousToggleMicros[PwmCount] = { 0, 0, 0, 0, 0, 0 };
joystick::PwmRequests pwm_status_msg;
ros::Publisher pwm_status_pub("PwmStatus", &pwm_status_msg);
std_msgs::String arduino_dbg_msg;
ros::Publisher arduino_dbg_pub("ArduinoDbg", &arduino_dbg_msg);
void pwm_update( const uranus_dp::ThrusterForces& force_input ){
PwmOnTime[0] = ForceToPwm(force_input.F1);
PwmOnTime[1] = ForceToPwm(force_input.F2);
PwmOnTime[2] = ForceToPwm(force_input.F3);
PwmOnTime[3] = ForceToPwm(force_input.F4);
PwmOnTime[4] = ForceToPwm(force_input.F5);
PwmOnTime[5] = ForceToPwm(force_input.F6);
//Send PWM-verdiene tilbake som debugoutput
pwm_status_msg.pwm1 = PwmOnTime[0];
pwm_status_msg.pwm2 = PwmOnTime[1];
pwm_status_msg.pwm3 = PwmOnTime[2];
pwm_status_msg.pwm4 = PwmOnTime[3];
pwm_status_msg.pwm5 = PwmOnTime[4];
pwm_status_msg.pwm6 = PwmOnTime[5];
dbg_count = 0;
pwm_status_pub.publish( &pwm_status_msg );
}
ros::Subscriber<uranus_dp::ThrusterForces> pwm_input_sub("control_inputs", &pwm_update );
double GyroLsbSens, AccelLsbSens;
void getFsRangeAndSetLsbSensisivity() {
uint8_t GyroFsRange, AccelFsRange;
GyroFsRange = accelgyro.getFullScaleGyroRange();
/* Gyro
* FS_SEL | Full Scale Range | LSB Sensitivity
* -------+--------------------+----------------
* 0 | +/- 250 degrees/s | 131 LSB/deg/s
* 1 | +/- 500 degrees/s | 65.5 LSB/deg/s
* 2 | +/- 1000 degrees/s | 32.8 LSB/deg/s
* 3 | +/- 2000 degrees/s | 16.4 LSB/deg/s
*/
switch(GyroFsRange) {
case 0:
GyroLsbSens = 131.0;
break;
case 1:
GyroLsbSens = 65.5;
break;
case 2:
GyroLsbSens = 32.8;
break;
case 3:
GyroLsbSens = 16.4;
break;
};
AccelFsRange = accelgyro.getFullScaleAccelRange();
/*Accelerometer
* AFS_SEL | Full Scale Range | LSB Sensitivity
* --------+------------------+----------------
* 0 | +/- 2g | 16384 LSB/g
* 1 | +/- 4g | 8192 LSB/g
* 2 | +/- 8g | 4096 LSB/g
* 3 | +/- 16g | 2048 LSB/g
*/
switch(AccelFsRange) {
case 0:
AccelLsbSens = 16384.0;
break;
case 1:
AccelLsbSens = 8192.0;
break;
case 2:
AccelLsbSens = 4096.0;
break;
case 3:
AccelLsbSens = 2048.0;
break;
};
}
void setup() {
//start ROS-node
nh.initNode();
nh.advertise(pwm_status_pub);
nh.advertise(arduino_dbg_pub);
nh.advertise(pub_imu);
nh.subscribe(pwm_input_sub);
nh.spinOnce();
// Initialize the 'Wire' class for the I2C-bus.
Wire.begin();
accelgyro.initialize();
getFsRangeAndSetLsbSensisivity();
depthSensor.initialize(false);
nh.spinOnce();
String dbg_msg = String("init:\n") +
(accelgyro.testConnection() ? "MPU6050 connection successful" : "MPU6050 connection failed");
arduino_dbg_msg.data = dbg_msg.c_str();
arduino_dbg_pub.publish( &arduino_dbg_msg );
nh.spinOnce();
//sett alle motorer til 0 Newton
for(int i = 0; i < PwmCount; i++) {
PwmOnTime[i] = ForceToPwm(0);
}
}
void lesSensorer() {
int16_t ax, ay, az;
int16_t gx, gy, gz;
int16_t mx, my, mz;
accelgyro.getMotion9(&ax, &ay, &az, &gx, &gy, &gz, &mx, &my, &mz);
//Accelerometerdata enhet: [g]
sensor_raw_msg.acceleration.x = ax / AccelLsbSens;
sensor_raw_msg.acceleration.y = ay / AccelLsbSens;
sensor_raw_msg.acceleration.z = az / AccelLsbSens;
//Gyrodata: enhet [deg/s]
sensor_raw_msg.gyro.x = gx / GyroLsbSens;
sensor_raw_msg.gyro.y = gy / GyroLsbSens;
sensor_raw_msg.gyro.z = gz / GyroLsbSens;
//Kompass enhent [µT]
//TODO fin ut om 0.3 er riktig skalerinsfaktor
sensor_raw_msg.compass.x = mx * 0.3;
sensor_raw_msg.compass.y = my * 0.3;
sensor_raw_msg.compass.z = mz * 0.3;
sensor_raw_msg.temperature = ( (double)accelgyro.getTemperature() + 12412.0) / 340.0;
depthSensor.read();
sensor_raw_msg.pressure = depthSensor.getPreassure();
}
void loop(){
nh.spinOnce();
/*
//komenterte vekk IMU for å kunne bruke software-PWM uten forstyrrelser
if( millis() - PrevoiusSensorReadMillis >= SensorReadDelay ) {
PrevoiusSensorReadMillis = millis();
lesSensorer();
//nh.spinOnce();
pub_imu.publish(&sensor_raw_msg);
//nh.spinOnce();
//dbg_count++;
//nh.spinOnce();
}
*/
/*
//String dbg_msg = "pwm updated after " + String(dbg_count) + " cycles";
//String dbg_msg = "accelX = " ;//+ String(imu.read(MPU9150_ACCEL_XOUT_L, MPU9150_ACCEL_XOUT_H));
String dbg_msg = String("GyroFsRange = ") + String(GyroFsRange) +
String("\nAccelFsRange = ") + String(AccelFsRange);
arduino_dbg_msg.data = dbg_msg.c_str();
arduino_dbg_pub.publish( &arduino_dbg_msg );
nh.spinOnce();
*/
//Software-PWM
for(int i = 0; i < PwmCount; i++) {
nh.spinOnce();
unsigned long CurrentMicros = micros();
if(PwmPinState[i] == HIGH) {
if(CurrentMicros - PreviousToggleMicros[i] >= PwmOnTime[i]) {
PwmPinState[i] = LOW;
digitalWrite(PwmPins[i], PwmPinState[i]);
PreviousToggleMicros[i] = CurrentMicros;
}
} else { // (PwmPinState[i] == LOW)
if(CurrentMicros - PreviousToggleMicros[i] >= PwmTotalTime - PwmOnTime[i] ) {
PwmPinState[i] = HIGH;
digitalWrite(PwmPins[i], PwmPinState[i]);
PreviousToggleMicros[i] = CurrentMicros;
}
}
//analogWrite(pwm_pins[i], PwmOnTime[i]);
}
}
|
Change control input topic name to snake_case
|
Change control input topic name to snake_case
|
C++
|
mit
|
vortexntnu/rov-control,vortexntnu/rov-control,vortexntnu/rov-control
|
94b0be96c219c7354963375389491215feba430c
|
src/libusb/AFU420PropertyImpl.cpp
|
src/libusb/AFU420PropertyImpl.cpp
|
#include "AFU420PropertyImpl.h"
#include "../logging.h"
#include "AFU420DeviceBackend.h"
namespace tcam::property
{
AFU420PropertyIntegerImpl::AFU420PropertyIntegerImpl(
const std::string& name,
tcam_value_int i,
tcam::afu420::AFU420Property id,
std::shared_ptr<tcam::property::AFU420DeviceBackend> cam)
: m_cam(cam), m_name(name), m_id(id)
{
m_default = i.default_value;
m_min = i.min;
m_max = i.max;
m_step = i.step;
m_flags = (PropertyFlags::Available | PropertyFlags::Implemented);
}
std::string_view AFU420PropertyIntegerImpl::get_display_name() const
{
return std::string_view();
}
std::string_view AFU420PropertyIntegerImpl::get_description() const
{
return std::string_view();
}
std::string_view AFU420PropertyIntegerImpl::get_category() const
{
return std::string_view();
}
std::string_view AFU420PropertyIntegerImpl::get_unit() const
{
return std::string_view();
}
tcamprop1::IntRepresentation_t AFU420PropertyIntegerImpl::get_representation() const
{
if (p_static_info)
{
return p_static_info->representation;
}
return tcamprop1::IntRepresentation_t::Linear;
}
outcome::result<int64_t> AFU420PropertyIntegerImpl::get_value() const
{
if (auto ptr = m_cam.lock())
{
return ptr->get_int(m_id);
}
else
{
SPDLOG_ERROR("Unable to lock property backend. Cannot retrieve value.");
return tcam::status::ResourceNotLockable;
}
}
outcome::result<void> AFU420PropertyIntegerImpl::set_value(int64_t new_value)
{
if (auto ptr = m_cam.lock())
{
return ptr->set_int(m_id, new_value);
}
else
{
SPDLOG_ERROR("Unable to lock property backend. Cannot retrieve value.");
return tcam::status::ResourceNotLockable;
}
}
outcome::result<void> AFU420PropertyIntegerImpl::valid_value(int64_t value)
{
if (get_min() > value || value > get_max())
{
return tcam::status::PropertyOutOfBounds;
}
return outcome::success();
}
AFU420PropertyDoubleImpl::AFU420PropertyDoubleImpl(
const std::string& name,
tcam_value_double d,
tcam::afu420::AFU420Property id,
std::shared_ptr<tcam::property::AFU420DeviceBackend> cam)
: m_cam(cam), m_name(name), m_id(id)
{
m_default = d.default_value;
m_min = d.min;
m_max = d.max;
m_step = d.step;
m_flags = (PropertyFlags::Available | PropertyFlags::Implemented);
}
std::string_view AFU420PropertyDoubleImpl::get_display_name() const
{
return std::string_view();
}
std::string_view AFU420PropertyDoubleImpl::get_description() const
{
return std::string_view();
}
std::string_view AFU420PropertyDoubleImpl::get_category() const
{
return std::string_view();
}
std::string_view AFU420PropertyDoubleImpl::get_unit() const
{
return std::string_view();
}
tcamprop1::FloatRepresentation_t AFU420PropertyDoubleImpl::get_representation() const
{
if (p_static_info)
{
return p_static_info->representation;
}
else
{
return tcamprop1::FloatRepresentation_t::Linear;
}
}
outcome::result<double> AFU420PropertyDoubleImpl::get_value() const
{
if (auto ptr = m_cam.lock())
{
auto ret = ptr->get_int(m_id);
if (ret)
{
return ret.value();
}
return ret.as_failure();
}
else
{
SPDLOG_ERROR("Unable to lock property backend. Cannot retrieve value.");
return tcam::status::ResourceNotLockable;
}
}
outcome::result<void> AFU420PropertyDoubleImpl::set_value(double new_value)
{
if (auto ptr = m_cam.lock())
{
OUTCOME_TRY(ptr->set_int(m_id, new_value));
return outcome::success();
}
else
{
SPDLOG_ERROR("Unable to lock property backend. Cannot retrieve value.");
return tcam::status::ResourceNotLockable;
}
}
outcome::result<void> AFU420PropertyDoubleImpl::valid_value(double value)
{
if (get_min() > value || value > get_max())
{
return tcam::status::PropertyOutOfBounds;
}
return outcome::success();
}
AFU420PropertyBoolImpl::AFU420PropertyBoolImpl(
const std::string& name,
bool default_value,
tcam::afu420::AFU420Property id,
std::shared_ptr<tcam::property::AFU420DeviceBackend> backend)
: m_name(name), m_cam(backend), m_default(default_value), m_id(id)
{
m_flags = (PropertyFlags::Available | PropertyFlags::Implemented);
m_value = m_default;
}
std::string_view AFU420PropertyBoolImpl::get_display_name() const
{
return std::string_view();
}
std::string_view AFU420PropertyBoolImpl::get_description() const
{
return std::string_view();
}
std::string_view AFU420PropertyBoolImpl::get_category() const
{
return std::string_view();
}
outcome::result<bool> AFU420PropertyBoolImpl::get_value() const
{
// if (m_ctrl.is_write_only)
// {
// return m_value;
// }
if (auto ptr = m_cam.lock())
{
return ptr->get_bool(m_id);
}
else
{
SPDLOG_ERROR("Unable to lock property backend. Cannot retrieve value.");
return tcam::status::ResourceNotLockable;
}
}
outcome::result<void> AFU420PropertyBoolImpl::set_value(bool new_value)
{
//unsigned short value = new_value ? 0xFFFF : 0x0;
if (auto ptr = m_cam.lock())
{
if (ptr->set_bool(m_id, new_value))
{
m_value = new_value;
return outcome::success();
}
return tcam::status::UndefinedError;
}
else
{
SPDLOG_ERROR("Unable to lock property backend. Cannot retrieve value.");
return tcam::status::ResourceNotLockable;
}
}
AFU420PropertyEnumImpl::AFU420PropertyEnumImpl(const std::string& name,
tcam::afu420::AFU420Property id,
std::map<int, std::string> entries,
std::shared_ptr<AFU420DeviceBackend> backend)
: m_entries(entries), m_cam(backend), m_name(name), m_id(id)
{
m_flags = (PropertyFlags::Available | PropertyFlags::Implemented);
// if (auto ptr = m_cam.lock())
// {
// auto ret = ptr->get_int(m_ctrl, GET_DEF);
// if (ret)
// {
// m_default = m_entries.at(ret.value());
// }
// }
// else
// {
// SPDLOG_ERROR("Unable to lock propertybackend. Cannot retrieve value.");
// }
}
std::string_view AFU420PropertyEnumImpl::get_display_name() const
{
return std::string_view();
}
std::string_view AFU420PropertyEnumImpl::get_description() const
{
return std::string_view();
}
std::string_view AFU420PropertyEnumImpl::get_category() const
{
return std::string_view();
}
outcome::result<void> AFU420PropertyEnumImpl::set_value_str(const std::string_view& new_value)
{
for (auto it = m_entries.begin(); it != m_entries.end(); ++it)
{
if (it->second == new_value)
{
return set_value(it->first);
}
}
return tcam::status::PropertyValueDoesNotExist;
}
outcome::result<void> AFU420PropertyEnumImpl::set_value(int64_t new_value)
{
if (!valid_value(new_value))
{
return tcam::status::PropertyValueDoesNotExist;
}
if (auto ptr = m_cam.lock())
{
return ptr->set_int(m_id, new_value);
}
else
{
SPDLOG_ERROR("Unable to lock property backend. Cannot write value.");
return tcam::status::ResourceNotLockable;
}
return tcam::status::Success;
}
outcome::result<std::string_view> AFU420PropertyEnumImpl::get_value() const
{
OUTCOME_TRY(auto value, get_value_int());
// TODO: additional checks if key exists
return m_entries.at(value);
}
outcome::result<int64_t> AFU420PropertyEnumImpl::get_value_int() const
{
if (auto ptr = m_cam.lock())
{
return ptr->get_int(m_id);
}
else
{
SPDLOG_ERROR("Unable to lock propertybackend. Cannot retrieve value.");
return tcam::status::ResourceNotLockable;
}
}
std::vector<std::string> AFU420PropertyEnumImpl::get_entries() const
{
std::vector<std::string> v;
for (auto it = m_entries.begin(); it != m_entries.end(); ++it) { v.push_back(it->second); }
return v;
}
bool AFU420PropertyEnumImpl::valid_value(int value)
{
auto it = m_entries.find(value);
if (it == m_entries.end())
{
return false;
}
return true;
}
} // namespace tcam::property
|
#include "AFU420PropertyImpl.h"
#include "../logging.h"
#include "AFU420DeviceBackend.h"
namespace tcam::property
{
AFU420PropertyIntegerImpl::AFU420PropertyIntegerImpl(
const std::string& name,
tcam_value_int i,
tcam::afu420::AFU420Property id,
std::shared_ptr<tcam::property::AFU420DeviceBackend> cam)
: m_cam(cam), m_name(name), m_id(id)
{
m_default = i.default_value;
m_min = i.min;
m_max = i.max;
m_step = i.step;
m_flags = (PropertyFlags::Available | PropertyFlags::Implemented);
auto static_info = tcamprop1::find_prop_static_info(m_name);
if (static_info.type == tcamprop1::prop_type::Integer && static_info.info_ptr)
{
p_static_info = static_cast<const tcamprop1::prop_static_info_integer*>(static_info.info_ptr);
}
else if (!static_info.info_ptr)
{
SPDLOG_ERROR("static information for {} do not exist!", m_name);
p_static_info = nullptr;
}
else
{
SPDLOG_ERROR("static information for {} have the wrong type!", m_name);
p_static_info = nullptr;
}
}
std::string_view AFU420PropertyIntegerImpl::get_display_name() const
{
if (p_static_info)
{
return p_static_info->display_name;
}
return std::string_view();
}
std::string_view AFU420PropertyIntegerImpl::get_description() const
{
if (p_static_info)
{
return p_static_info->description;
}
return std::string_view();
}
std::string_view AFU420PropertyIntegerImpl::get_category() const
{
if (p_static_info)
{
return p_static_info->iccategory;
}
return std::string_view();
}
std::string_view AFU420PropertyIntegerImpl::get_unit() const
{
if (p_static_info)
{
return p_static_info->unit;
}
return std::string_view();
}
tcamprop1::IntRepresentation_t AFU420PropertyIntegerImpl::get_representation() const
{
if (p_static_info)
{
return p_static_info->representation;
}
return tcamprop1::IntRepresentation_t::Linear;
}
outcome::result<int64_t> AFU420PropertyIntegerImpl::get_value() const
{
if (auto ptr = m_cam.lock())
{
return ptr->get_int(m_id);
}
else
{
SPDLOG_ERROR("Unable to lock property backend. Cannot retrieve value.");
return tcam::status::ResourceNotLockable;
}
}
outcome::result<void> AFU420PropertyIntegerImpl::set_value(int64_t new_value)
{
if (auto ptr = m_cam.lock())
{
return ptr->set_int(m_id, new_value);
}
else
{
SPDLOG_ERROR("Unable to lock property backend. Cannot retrieve value.");
return tcam::status::ResourceNotLockable;
}
}
outcome::result<void> AFU420PropertyIntegerImpl::valid_value(int64_t value)
{
if (get_min() > value || value > get_max())
{
return tcam::status::PropertyOutOfBounds;
}
return outcome::success();
}
AFU420PropertyDoubleImpl::AFU420PropertyDoubleImpl(
const std::string& name,
tcam_value_double d,
tcam::afu420::AFU420Property id,
std::shared_ptr<tcam::property::AFU420DeviceBackend> cam)
: m_cam(cam), m_name(name), m_id(id)
{
m_default = d.default_value;
m_min = d.min;
m_max = d.max;
m_step = d.step;
m_flags = (PropertyFlags::Available | PropertyFlags::Implemented);
auto static_info = tcamprop1::find_prop_static_info(m_name);
if (static_info.type == tcamprop1::prop_type::Float && static_info.info_ptr)
{
p_static_info = static_cast<const tcamprop1::prop_static_info_float*>(static_info.info_ptr);
}
else if (!static_info.info_ptr)
{
SPDLOG_ERROR("static information for {} do not exist!", m_name);
p_static_info = nullptr;
}
else
{
SPDLOG_ERROR("static information for {} have the wrong type!", m_name);
p_static_info = nullptr;
}
}
std::string_view AFU420PropertyDoubleImpl::get_display_name() const
{
if (p_static_info)
{
return p_static_info->display_name;
}
return std::string_view();
}
std::string_view AFU420PropertyDoubleImpl::get_description() const
{
if (p_static_info)
{
return p_static_info->description;
}
return std::string_view();
}
std::string_view AFU420PropertyDoubleImpl::get_category() const
{
if (p_static_info)
{
return p_static_info->iccategory;
}
return std::string_view();
}
std::string_view AFU420PropertyDoubleImpl::get_unit() const
{
if (p_static_info)
{
return p_static_info->unit;
}
return std::string_view();
}
tcamprop1::FloatRepresentation_t AFU420PropertyDoubleImpl::get_representation() const
{
if (p_static_info)
{
return p_static_info->representation;
}
else
{
return tcamprop1::FloatRepresentation_t::Linear;
}
}
outcome::result<double> AFU420PropertyDoubleImpl::get_value() const
{
if (auto ptr = m_cam.lock())
{
auto ret = ptr->get_int(m_id);
if (ret)
{
return ret.value();
}
return ret.as_failure();
}
else
{
SPDLOG_ERROR("Unable to lock property backend. Cannot retrieve value.");
return tcam::status::ResourceNotLockable;
}
}
outcome::result<void> AFU420PropertyDoubleImpl::set_value(double new_value)
{
if (auto ptr = m_cam.lock())
{
OUTCOME_TRY(ptr->set_int(m_id, new_value));
return outcome::success();
}
else
{
SPDLOG_ERROR("Unable to lock property backend. Cannot retrieve value.");
return tcam::status::ResourceNotLockable;
}
}
outcome::result<void> AFU420PropertyDoubleImpl::valid_value(double value)
{
if (get_min() > value || value > get_max())
{
return tcam::status::PropertyOutOfBounds;
}
return outcome::success();
}
AFU420PropertyBoolImpl::AFU420PropertyBoolImpl(
const std::string& name,
bool default_value,
tcam::afu420::AFU420Property id,
std::shared_ptr<tcam::property::AFU420DeviceBackend> backend)
: m_name(name), m_cam(backend), m_default(default_value), m_id(id)
{
m_flags = (PropertyFlags::Available | PropertyFlags::Implemented);
m_value = m_default;
auto static_info = tcamprop1::find_prop_static_info(m_name);
if (static_info.type == tcamprop1::prop_type::Boolean && static_info.info_ptr)
{
p_static_info = static_cast<const tcamprop1::prop_static_info_boolean*>(static_info.info_ptr);
}
else if (!static_info.info_ptr)
{
SPDLOG_ERROR("static information for {} do not exist!", m_name);
p_static_info = nullptr;
}
else
{
SPDLOG_ERROR("static information for {} have the wrong type!", m_name);
p_static_info = nullptr;
}
}
std::string_view AFU420PropertyBoolImpl::get_display_name() const
{
if (p_static_info)
{
return p_static_info->display_name;
}
return std::string_view();
}
std::string_view AFU420PropertyBoolImpl::get_description() const
{
if (p_static_info)
{
return p_static_info->description;
}
return std::string_view();
}
std::string_view AFU420PropertyBoolImpl::get_category() const
{
if (p_static_info)
{
return p_static_info->iccategory;
}
return std::string_view();
}
outcome::result<bool> AFU420PropertyBoolImpl::get_value() const
{
// if (m_ctrl.is_write_only)
// {
// return m_value;
// }
if (auto ptr = m_cam.lock())
{
return ptr->get_bool(m_id);
}
else
{
SPDLOG_ERROR("Unable to lock property backend. Cannot retrieve value.");
return tcam::status::ResourceNotLockable;
}
}
outcome::result<void> AFU420PropertyBoolImpl::set_value(bool new_value)
{
//unsigned short value = new_value ? 0xFFFF : 0x0;
if (auto ptr = m_cam.lock())
{
if (ptr->set_bool(m_id, new_value))
{
m_value = new_value;
return outcome::success();
}
return tcam::status::UndefinedError;
}
else
{
SPDLOG_ERROR("Unable to lock property backend. Cannot retrieve value.");
return tcam::status::ResourceNotLockable;
}
}
AFU420PropertyEnumImpl::AFU420PropertyEnumImpl(const std::string& name,
tcam::afu420::AFU420Property id,
std::map<int, std::string> entries,
std::shared_ptr<AFU420DeviceBackend> backend)
: m_entries(entries), m_cam(backend), m_name(name), m_id(id)
{
m_flags = (PropertyFlags::Available | PropertyFlags::Implemented);
// if (auto ptr = m_cam.lock())
// {
// auto ret = ptr->get_int(m_ctrl, GET_DEF);
// if (ret)
// {
// m_default = m_entries.at(ret.value());
// }
// }
// else
// {
// SPDLOG_ERROR("Unable to lock propertybackend. Cannot retrieve value.");
// }
auto static_info = tcamprop1::find_prop_static_info(m_name);
if (static_info.type == tcamprop1::prop_type::Enumeration && static_info.info_ptr)
{
p_static_info = static_cast<const tcamprop1::prop_static_info_enumeration*>(static_info.info_ptr);
}
else if (!static_info.info_ptr)
{
SPDLOG_ERROR("static information for {} do not exist!", m_name);
p_static_info = nullptr;
}
else
{
SPDLOG_ERROR("static information for {} have the wrong type!", m_name);
p_static_info = nullptr;
}
}
std::string_view AFU420PropertyEnumImpl::get_display_name() const
{
if (p_static_info)
{
return p_static_info->display_name;
}
return std::string_view();
}
std::string_view AFU420PropertyEnumImpl::get_description() const
{
if (p_static_info)
{
return p_static_info->description;
}
return std::string_view();
}
std::string_view AFU420PropertyEnumImpl::get_category() const
{
if (p_static_info)
{
return p_static_info->iccategory;
}
return std::string_view();
}
outcome::result<void> AFU420PropertyEnumImpl::set_value_str(const std::string_view& new_value)
{
for (auto it = m_entries.begin(); it != m_entries.end(); ++it)
{
if (it->second == new_value)
{
return set_value(it->first);
}
}
return tcam::status::PropertyValueDoesNotExist;
}
outcome::result<void> AFU420PropertyEnumImpl::set_value(int64_t new_value)
{
if (!valid_value(new_value))
{
return tcam::status::PropertyValueDoesNotExist;
}
if (auto ptr = m_cam.lock())
{
return ptr->set_int(m_id, new_value);
}
else
{
SPDLOG_ERROR("Unable to lock property backend. Cannot write value.");
return tcam::status::ResourceNotLockable;
}
return tcam::status::Success;
}
outcome::result<std::string_view> AFU420PropertyEnumImpl::get_value() const
{
OUTCOME_TRY(auto value, get_value_int());
// TODO: additional checks if key exists
return m_entries.at(value);
}
outcome::result<int64_t> AFU420PropertyEnumImpl::get_value_int() const
{
if (auto ptr = m_cam.lock())
{
return ptr->get_int(m_id);
}
else
{
SPDLOG_ERROR("Unable to lock propertybackend. Cannot retrieve value.");
return tcam::status::ResourceNotLockable;
}
}
std::vector<std::string> AFU420PropertyEnumImpl::get_entries() const
{
std::vector<std::string> v;
for (auto it = m_entries.begin(); it != m_entries.end(); ++it) { v.push_back(it->second); }
return v;
}
bool AFU420PropertyEnumImpl::valid_value(int value)
{
auto it = m_entries.find(value);
if (it == m_entries.end())
{
return false;
}
return true;
}
} // namespace tcam::property
|
Add static information to AFU420 properties
|
libusb: Add static information to AFU420 properties
|
C++
|
apache-2.0
|
TheImagingSource/tiscamera,TheImagingSource/tiscamera,TheImagingSource/tiscamera,TheImagingSource/tiscamera
|
e83260103f1208173ad6de7325dffcd400a8a8f6
|
Applications/src/compose-dofs.cc
|
Applications/src/compose-dofs.cc
|
/*
* Medical Image Registration ToolKit (MIRTK)
*
* Copyright 2008-2015 Imperial College London
* Copyright 2008-2013 Daniel Rueckert, Julia Schnabel
* Copyright 2013-2015 Andreas Schuh
*
* 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 "mirtk/Common.h"
#include "mirtk/Options.h"
#include "mirtk/IOConfig.h"
#include "mirtk/GenericImage.h"
#include "mirtk/Transformations.h"
using namespace mirtk;
// =============================================================================
// Help
// =============================================================================
// -----------------------------------------------------------------------------
// Print help screen
void PrintHelp(const char *name)
{
cout << endl;
cout << "Usage: " << name << " <T1> <T2>... <T> [-target <image>]" << endl;
cout << endl;
cout << "Description:" << endl;
cout << " Computes the composition T of the given input transformations such that" << endl;
cout << endl;
cout << " .. math::" << endl;
cout << endl;
cout << " T(x) = Tn o ... o T2 o T1(x)" << endl;
cout << endl;
cout << "Optional arguments:" << endl;
cout << " -target <image> Target image on which images will be resampled using" << endl;
cout << " the composed transformation." << endl;
PrintStandardOptions(cout);
cout << endl;
}
// =============================================================================
// Auxiliaries
// =============================================================================
// -----------------------------------------------------------------------------
/// Compose current composite transformation with any displacement field
void PushDisplacement(FluidFreeFormTransformation &t1,
Transformation *t2,
ImageAttributes &attr)
{
if (!attr) {
if (t1.NumberOfLevels() == 0) {
MultiLevelTransformation *mffd;
mffd = dynamic_cast<MultiLevelTransformation *>(t2);
if (mffd && mffd->NumberOfLevels() > 0) {
attr = mffd->GetLocalTransformation(-1)->Attributes();
} else {
// Note: As long as no local transformation was encountered before,
// no global transformation or single-level FFD has to be
// approximated by a displacement field. This error should
// thus never be encountered...
cerr << "Internal error: Specify -target image to circumvent it" << endl;
cerr << " and please consider reporting the issue" << endl;
exit(1);
}
} else {
attr = t1.GetLocalTransformation(-1)->Attributes();
}
}
GenericImage<double> disp(attr, 3);
t2->Displacement(disp);
t1.PushLocalTransformation(new LinearFreeFormTransformation3D(disp));
}
// -----------------------------------------------------------------------------
/// Compose current composite transformation with rigid/affine transformation
void PushTransformation(FluidFreeFormTransformation &t1,
HomogeneousTransformation *t2,
ImageAttributes &attr,
bool last = false)
{
if (t2->IsIdentity()) return;
if (t1.NumberOfLevels() == 0) {
HomogeneousTransformation *global = t1.GetGlobalTransformation();
global->PutMatrix(t2->GetMatrix() * global->GetMatrix());
} else {
if (last) {
AffineTransformation *post = t1.GetAffineTransformation();
post->PutMatrix(post->GetMatrix() * t2->GetMatrix());
} else {
PushDisplacement(t1, t2, attr);
}
}
}
// -----------------------------------------------------------------------------
/// Compose current composite transformation with single-level FFD
void PushTransformation(FluidFreeFormTransformation &t1,
FreeFormTransformation *t2,
ImageAttributes &attr,
bool = false)
{
t1.PushLocalTransformation(t2);
}
// -----------------------------------------------------------------------------
/// Compose current composite transformation with multi-level FFD
void PushTransformation(FluidFreeFormTransformation &t1,
MultiLevelFreeFormTransformation *t2,
ImageAttributes &attr,
bool = false)
{
if (t2->NumberOfLevels() == 0) {
PushTransformation(t1, t2->GetGlobalTransformation(), attr);
} else if (t2->NumberOfLevels() == 1) {
t2->MergeGlobalIntoLocalDisplacement();
t1.PushLocalTransformation(t2->RemoveLocalTransformation(0));
} else {
PushDisplacement(t1, t2, attr);
}
}
// -----------------------------------------------------------------------------
/// Compose current composite transformation with multi-level SV FFD
void PushTransformation(FluidFreeFormTransformation &t1,
MultiLevelStationaryVelocityTransformation *t2,
ImageAttributes &attr,
bool = false)
{
if (t2->NumberOfLevels() == 0) {
PushTransformation(t1, t2->GetGlobalTransformation(), attr);
} else if (t2->NumberOfLevels() == 1) {
t2->MergeGlobalIntoLocalDisplacement();
t1.PushLocalTransformation(t2->RemoveLocalTransformation(0));
} else {
PushDisplacement(t1, t2, attr);
}
}
// -----------------------------------------------------------------------------
/// Compose current composite transformation with another composite transformation
void PushTransformation(FluidFreeFormTransformation &t1,
FluidFreeFormTransformation *t2,
ImageAttributes &attr,
bool last = false)
{
PushTransformation(t1, t2->GetGlobalTransformation(), attr);
for (int l = 0; l < t2->NumberOfLevels(); ++l) {
PushTransformation(t1, t2->RemoveLocalTransformation(l), attr);
}
if (last) {
AffineTransformation *post = t1.GetAffineTransformation();
post->PutMatrix(post->GetMatrix() * t2->GetAffineTransformation()->GetMatrix());
} else {
PushTransformation(t1, t2->GetAffineTransformation(), attr);
}
}
// =============================================================================
// Main
// =============================================================================
// -----------------------------------------------------------------------------
int main(int argc, char **argv)
{
REQUIRES_POSARGS(3);
int N = NUM_POSARGS - 1;
ImageAttributes attr;
FluidFreeFormTransformation t;
for (ALL_OPTIONS) {
if (OPTION("-target")) {
InitializeIOLibrary();
GreyImage target(ARGUMENT);
attr = target.Attributes();
}
else HANDLE_STANDARD_OR_UNKNOWN_OPTION();
}
HomogeneousTransformation *aff;
FreeFormTransformation *ffd;
MultiLevelFreeFormTransformation *mffd;
MultiLevelStationaryVelocityTransformation *svmffd;
FluidFreeFormTransformation *fluid;
// Compose affine transformations at the end
if (verbose) {
cout << "Compose affine transformations at end..." << endl;
}
AffineTransformation *post = t.GetAffineTransformation();
for (int n = N; n >= 1; --n) {
if (verbose) {
cout << "Reading transformation " << n << ": " << POSARG(n) << endl;
}
UniquePtr<Transformation> dof(Transformation::New(POSARG(n)));
if ((aff = dynamic_cast<HomogeneousTransformation *>(dof.get()))) {
post->PutMatrix(post->GetMatrix() * aff->GetMatrix());
--N; // remove transformation from composition chain
} else {
break;
}
}
if (verbose) {
cout << "Compose affine transformations at end... done" << endl;
}
// Compose remaining transformations from the start
if (verbose) {
cout << "\nCompose remaining transformations..." << endl;
}
for (int n = 1; n <= N; ++n) {
// Read n-th transformation
if (verbose) {
cout << "Reading transformation " << n << " from " << POSARG(n) << endl;
}
UniquePtr<Transformation> dof(Transformation::New(POSARG(n)));
aff = dynamic_cast<HomogeneousTransformation *>(dof.get());
ffd = dynamic_cast<FreeFormTransformation *>(dof.get());
mffd = dynamic_cast<MultiLevelFreeFormTransformation *>(dof.get());
svmffd = dynamic_cast<MultiLevelStationaryVelocityTransformation *>(dof.get());
fluid = dynamic_cast<FluidFreeFormTransformation *>(dof.get());
// Compose current composite transformation with n-th transformation
const bool last = (n == N);
if (aff ) PushTransformation(t, aff, attr, last);
else if (mffd ) PushTransformation(t, mffd, attr, last);
else if (svmffd) PushTransformation(t, svmffd, attr, last);
else if (fluid ) PushTransformation(t, fluid, attr, last);
else if (ffd ) {
PushTransformation(t, ffd, attr, last);
dof.release();
}
else {
cerr << "Unsupported transformation file " << POSARG(n) << endl;
cerr << " Type name = " << dof->NameOfClass() << endl;
exit(1);
}
// Transform target image attributes by affine transformation such that
// attributes of consecutively approximated displacment fields overlap
// with the thus far transformed image grid
if (aff && attr) {
attr.PutAffineMatrix(aff->GetMatrix(), true);
}
}
if (verbose) {
cout << "Compose remaining transformations... done" << endl;
}
// Write composite transformation
const char *output_name = POSARG(NUM_POSARGS);
if (verbose) cout << "Writing composite transformation to " << output_name << endl;
t.Write(output_name);
if (verbose) t.Print(2);
}
|
/*
* Medical Image Registration ToolKit (MIRTK)
*
* Copyright 2008-2015 Imperial College London
* Copyright 2008-2013 Daniel Rueckert, Julia Schnabel
* Copyright 2013-2015 Andreas Schuh
*
* 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 "mirtk/Common.h"
#include "mirtk/Options.h"
#include "mirtk/IOConfig.h"
#include "mirtk/GenericImage.h"
#include "mirtk/Transformations.h"
using namespace mirtk;
// =============================================================================
// Help
// =============================================================================
// -----------------------------------------------------------------------------
// Print help screen
void PrintHelp(const char *name)
{
cout << endl;
cout << "Usage: " << name << " <T1> <T2>... <T> [-target <image>]" << endl;
cout << endl;
cout << "Description:" << endl;
cout << " Computes the composition T of the given input transformations such that" << endl;
cout << endl;
cout << " .. math::" << endl;
cout << endl;
cout << " T(x) = Tn o ... o T2 o T1(x)" << endl;
cout << endl;
cout << "Optional arguments:" << endl;
cout << " -target <image> Target image on which images will be resampled using" << endl;
cout << " the composed transformation." << endl;
cout << " -approximate Approximate the composed transformation using a single FFD. (default: off)" << endl;
PrintStandardOptions(cout);
cout << endl;
}
// =============================================================================
// Auxiliaries
// =============================================================================
// -----------------------------------------------------------------------------
/// Compose current composite transformation with any displacement field
void PushDisplacement(FluidFreeFormTransformation &t1,
Transformation *t2,
ImageAttributes &attr)
{
if (!attr) {
if (t1.NumberOfLevels() == 0) {
MultiLevelTransformation *mffd;
mffd = dynamic_cast<MultiLevelTransformation *>(t2);
if (mffd && mffd->NumberOfLevels() > 0) {
attr = mffd->GetLocalTransformation(-1)->Attributes();
} else {
// Note: As long as no local transformation was encountered before,
// no global transformation or single-level FFD has to be
// approximated by a displacement field. This error should
// thus never be encountered...
cerr << "Internal error: Specify -target image to circumvent it" << endl;
cerr << " and please consider reporting the issue" << endl;
exit(1);
}
} else {
attr = t1.GetLocalTransformation(-1)->Attributes();
}
}
GenericImage<double> disp(attr, 3);
t2->Displacement(disp);
t1.PushLocalTransformation(new LinearFreeFormTransformation3D(disp));
}
// -----------------------------------------------------------------------------
/// Compose current composite transformation with rigid/affine transformation
void PushTransformation(FluidFreeFormTransformation &t1,
HomogeneousTransformation *t2,
ImageAttributes &attr,
bool last = false)
{
if (t2->IsIdentity()) return;
if (t1.NumberOfLevels() == 0) {
HomogeneousTransformation *global = t1.GetGlobalTransformation();
global->PutMatrix(t2->GetMatrix() * global->GetMatrix());
} else {
if (last) {
AffineTransformation *post = t1.GetAffineTransformation();
post->PutMatrix(post->GetMatrix() * t2->GetMatrix());
} else {
PushDisplacement(t1, t2, attr);
}
}
}
// -----------------------------------------------------------------------------
/// Compose current composite transformation with single-level FFD
void PushTransformation(FluidFreeFormTransformation &t1,
FreeFormTransformation *t2,
ImageAttributes &attr,
bool = false)
{
t1.PushLocalTransformation(t2);
}
// -----------------------------------------------------------------------------
/// Compose current composite transformation with multi-level FFD
void PushTransformation(FluidFreeFormTransformation &t1,
MultiLevelFreeFormTransformation *t2,
ImageAttributes &attr,
bool = false)
{
if (t2->NumberOfLevels() == 0) {
PushTransformation(t1, t2->GetGlobalTransformation(), attr);
} else if (t2->NumberOfLevels() == 1) {
t2->MergeGlobalIntoLocalDisplacement();
t1.PushLocalTransformation(t2->RemoveLocalTransformation(0));
} else {
PushDisplacement(t1, t2, attr);
}
}
// -----------------------------------------------------------------------------
/// Compose current composite transformation with multi-level SV FFD
void PushTransformation(FluidFreeFormTransformation &t1,
MultiLevelStationaryVelocityTransformation *t2,
ImageAttributes &attr,
bool = false)
{
if (t2->NumberOfLevels() == 0) {
PushTransformation(t1, t2->GetGlobalTransformation(), attr);
} else if (t2->NumberOfLevels() == 1) {
t2->MergeGlobalIntoLocalDisplacement();
t1.PushLocalTransformation(t2->RemoveLocalTransformation(0));
} else {
PushDisplacement(t1, t2, attr);
}
}
// -----------------------------------------------------------------------------
/// Compose current composite transformation with another composite transformation
void PushTransformation(FluidFreeFormTransformation &t1,
FluidFreeFormTransformation *t2,
ImageAttributes &attr,
bool last = false)
{
PushTransformation(t1, t2->GetGlobalTransformation(), attr);
for (int l = 0; l < t2->NumberOfLevels(); ++l) {
PushTransformation(t1, t2->RemoveLocalTransformation(l), attr);
}
if (last) {
AffineTransformation *post = t1.GetAffineTransformation();
post->PutMatrix(post->GetMatrix() * t2->GetAffineTransformation()->GetMatrix());
} else {
PushTransformation(t1, t2->GetAffineTransformation(), attr);
}
}
// =============================================================================
// Main
// =============================================================================
// -----------------------------------------------------------------------------
int main(int argc, char **argv)
{
REQUIRES_POSARGS(3);
int N = NUM_POSARGS - 1;
ImageAttributes attr;
FluidFreeFormTransformation t;
bool approximate = false;
for (ALL_OPTIONS) {
if (OPTION("-target")) {
InitializeIOLibrary();
GreyImage target(ARGUMENT);
attr = target.Attributes();
}
else if (OPTION("-approximate")) {
approximate = true;
}
else HANDLE_STANDARD_OR_UNKNOWN_OPTION();
}
HomogeneousTransformation *aff;
FreeFormTransformation *ffd;
MultiLevelFreeFormTransformation *mffd;
MultiLevelStationaryVelocityTransformation *svmffd;
FluidFreeFormTransformation *fluid;
// Compose affine transformations at the end
if (verbose) {
cout << "Compose affine transformations at end..." << endl;
}
AffineTransformation *post = t.GetAffineTransformation();
for (int n = N; n >= 1; --n) {
if (verbose) {
cout << "Reading transformation " << n << ": " << POSARG(n) << endl;
}
UniquePtr<Transformation> dof(Transformation::New(POSARG(n)));
if ((aff = dynamic_cast<HomogeneousTransformation *>(dof.get()))) {
post->PutMatrix(post->GetMatrix() * aff->GetMatrix());
--N; // remove transformation from composition chain
} else {
break;
}
}
if (verbose) {
cout << "Compose affine transformations at end... done" << endl;
}
// Compose remaining transformations from the start
if (verbose) {
cout << "\nCompose remaining transformations..." << endl;
}
for (int n = 1; n <= N; ++n) {
// Read n-th transformation
if (verbose) {
cout << "Reading transformation " << n << " from " << POSARG(n) << endl;
}
UniquePtr<Transformation> dof(Transformation::New(POSARG(n)));
aff = dynamic_cast<HomogeneousTransformation *>(dof.get());
ffd = dynamic_cast<FreeFormTransformation *>(dof.get());
mffd = dynamic_cast<MultiLevelFreeFormTransformation *>(dof.get());
svmffd = dynamic_cast<MultiLevelStationaryVelocityTransformation *>(dof.get());
fluid = dynamic_cast<FluidFreeFormTransformation *>(dof.get());
// Compose current composite transformation with n-th transformation
const bool last = (n == N);
if (aff ) PushTransformation(t, aff, attr, last);
else if (mffd ) PushTransformation(t, mffd, attr, last);
else if (svmffd) PushTransformation(t, svmffd, attr, last);
else if (fluid ) PushTransformation(t, fluid, attr, last);
else if (ffd ) {
PushTransformation(t, ffd, attr, last);
dof.release();
}
else {
cerr << "Unsupported transformation file " << POSARG(n) << endl;
cerr << " Type name = " << dof->NameOfClass() << endl;
exit(1);
}
// Transform target image attributes by affine transformation such that
// attributes of consecutively approximated displacment fields overlap
// with the thus far transformed image grid
if (aff && attr) {
attr.PutAffineMatrix(aff->GetMatrix(), true);
}
}
if (verbose) {
cout << "Compose remaining transformations... done" << endl;
}
// Approximate the composed transformation using a single free-form deformation
if (approximate && (t.NumberOfLevels() > 0)) {
if (verbose) {
cout << "Approximate the composed transformation using a single FFD..." << endl;
}
// Use the densest control point lattice in the local transformation stack
ImageAttributes ffd_attr;
for (int i = 0; i < t.NumberOfLevels(); ++i) {
const auto &attr = t.GetLocalTransformation(i)->Attributes();
if (attr.NumberOfLatticePoints() > ffd_attr.NumberOfLatticePoints()) {
ffd_attr = attr;
}
}
// Approximate
typedef BSplineFreeFormTransformation3D OutputType;
UniquePtr<OutputType> ffd(new OutputType(ffd_attr));
double rms_error = ffd->ApproximateAsNew(&t);
if (verbose) {
cout << " RMS error = " << rms_error << endl;
}
// Set the output transformation
t.Clear();
t.PushLocalTransformation(ffd.release());
}
// Write composite transformation
const char *output_name = POSARG(NUM_POSARGS);
if (verbose) cout << "Writing composite transformation to " << output_name << endl;
t.Write(output_name);
if (verbose) t.Print(2);
}
|
Add -approximate option to compose-dofs [Applications]
|
enh: Add -approximate option to compose-dofs [Applications]
Closes #325.
|
C++
|
apache-2.0
|
schuhschuh/MIRTK,schuhschuh/MIRTK,BioMedIA/MIRTK,BioMedIA/MIRTK,stefanpsz/MIRTK,stefanpsz/MIRTK,BioMedIA/MIRTK,schuhschuh/MIRTK,BioMedIA/MIRTK,stefanpsz/MIRTK,schuhschuh/MIRTK,stefanpsz/MIRTK
|
c12a87c4d3fb36d00581cd889be47c33ad586f30
|
src/system/rocket_system.cpp
|
src/system/rocket_system.cpp
|
#include "system/rocket_system.hpp"
#include "util/time.hpp"
#include "ch.hpp"
#include "chprintf.h"
RocketSystem::RocketSystem(
Accelerometer& accel,
optional<Accelerometer *> accelH,
optional<Barometer *> bar,
optional<GPS *> gps,
Gyroscope& gyr,
optional<Magnetometer *> mag,
WorldEstimator& estimator, InputSource& inputSource,
MotorMapper& motorMapper, Communicator& communicator,
Platform& platform)
: VehicleSystem(communicator), MessageListener(communicator),
accel(accel), accelH(accelH), bar(bar), gps(gps), gyr(gyr), mag(mag),
estimator(estimator), inputSource(inputSource),
motorMapper(motorMapper), platform(platform),
imuStream(communicator, 100),
systemStream(communicator, 5),
state(RocketState::DISARMED) {
// Disarm by default. A set_arm_state_message_t message is required to enable
// the control pipeline.
setArmed(false);
}
void RocketSystem::update() {
//static int time = 0;
//if (time % 1000 == 0) {
// chprintf((BaseSequentialStream*)&SD4, "%d\r\n", RTT2MS(chibios_rt::System::getTime()));
//}
//time = (time+1) % 1000;
// Poll the gyroscope and accelerometer
AccelerometerReading accelReading = accel.readAccel();
GyroscopeReading gyrReading = gyr.readGyro();
optional<AccelerometerReading> accelHReading;
optional<BarometerReading> barReading;
optional<GPSReading> gpsReading;
optional<MagnetometerReading> magReading;
if (accelH) accelHReading = (*accelH)->readAccel();
if (bar) barReading = (*bar)->readBar();
if (gps) gpsReading = (*gps)->readGPS();
//if (mag) magReading = (*mag)->readMag();
SensorMeasurements meas {
.accel = std::experimental::make_optional(accelReading),
.accelH = accelHReading,
.bar = barReading,
.gps = gpsReading,
.gyro = std::experimental::make_optional(gyrReading),
.mag = magReading
};
// Update the world estimate
WorldEstimate estimate = estimator.update(meas);
// Poll for controller input
ControllerInput input = inputSource.read();
// Keep moving average of acceleration
static float accel = -1.0f;
accel = 0.5*accel + 0.5*accelReading.axes[0];
// Run the controllers
ActuatorSetpoint actuatorSp;
// Run state machine
switch (state) {
case RocketState::DISARMED:
state = DisarmedState(meas, estimate);
break;
case RocketState::PRE_ARM:
state = PreArmState(meas, estimate);
break;
case RocketState::ARMED:
state = ArmedState(meas, estimate);
break;
case RocketState::FLIGHT:
state = FlightState(meas, estimate);
break;
case RocketState::APOGEE:
state = ApogeeState(meas, estimate);
break;
case RocketState::DESCENT:
state = DescentState(meas, estimate);
break;
case RocketState::RECOVERY:
state = RecoveryState(meas, estimate);
break;
default:
break;
}
// Update streams
updateStreams(meas, estimate);
// Update motor outputs
motorMapper.run(isArmed(), actuatorSp);
}
bool RocketSystem::healthy() {
bool healthy = accel.healthy() && gyr.healthy();
if(accelH) {
healthy &= (*accelH)->healthy();
}
if(bar) {
healthy &= (*bar)->healthy();
}
if(gps) {
healthy &= (*gps)->healthy();
}
if(mag) {
healthy &= (*mag)->healthy();
}
return healthy;
}
void RocketSystem::on(const protocol::message::set_arm_state_message_t& m) {
setArmed(m.armed);
}
void RocketSystem::updateStreams(SensorMeasurements meas, WorldEstimate est) {
if (imuStream.ready()) {
protocol::message::imu_message_t m {
.time = ST2MS(chibios_rt::System::getTime()),
.gyro = {
(*meas.gyro).axes[0],
(*meas.gyro).axes[1],
(*meas.gyro).axes[2]
},
.accel = {
(*meas.accel).axes[0],
(*meas.accel).axes[1],
(*meas.accel).axes[2]
}
};
imuStream.publish(m);
}
if (systemStream.ready()) {
uint8_t stateNum = 0;
switch (state) {
case RocketState::DISARMED:
stateNum = 0;
break;
case RocketState::PRE_ARM:
stateNum = 1;
break;
case RocketState::ARMED:
stateNum = 2;
break;
case RocketState::FLIGHT:
stateNum = 3;
break;
case RocketState::APOGEE:
stateNum = 4;
break;
case RocketState::DESCENT:
stateNum = 6;
break;
case RocketState::RECOVERY:
stateNum = 7;
break;
default:
break;
}
protocol::message::system_message_t m {
.time = ST2MS(chibios_rt::System::getTime()),
.state = stateNum,
.motorDC = motorDC
};
systemStream.publish(m);
}
}
RocketState RocketSystem::DisarmedState(SensorMeasurements meas, WorldEstimate est) {
PulseLED(1,0,0,1); // Red 1 Hz
// Proceed directly to PRE_ARM for now.
return RocketState::PRE_ARM;
}
RocketState RocketSystem::PreArmState(SensorMeasurements meas, WorldEstimate est) {
PulseLED(1,0,0,4); // Red 4 Hz
// Calibrate
groundAltitude = est.loc.alt;
// TODO(yoos): run sensor calibration here
// Proceed to ARMED if all sensors are healthy and GS arm signal received.
if (healthy() && isArmed()) {
return RocketState::ARMED;
}
return RocketState::PRE_ARM;
}
RocketState RocketSystem::ArmedState(SensorMeasurements meas, WorldEstimate est) {
SetLED(1,0,0); // Red
static int count = 10;
count = ((*meas.accel).axes[0] > 1.1) ? (count-1) : 10;
// Revert to PRE_ARM if any sensors are unhealthy or disarm signal received
if (!(healthy() && isArmed())) {
return RocketState::PRE_ARM;
}
// Proceed to FLIGHT on 1.1g sense on X axis.
if (count == 0) {
return RocketState::FLIGHT;
}
return RocketState::ARMED;
}
RocketState RocketSystem::FlightState(SensorMeasurements meas, WorldEstimate est) {
SetLED(0,0,1); // Blue
static bool powered = true; // First time we enter, we are in powered flight.
// Check for motor cutoff. We should see negative acceleration due to drag.
static int count = 100;
if (powered) {
count = ((*meas.accel).axes[0] < 0.0) ? (count-1) : 100;
powered = (count == 0) ? false : true;
}
// Apogee occurs after motor cutoff
if (!powered && est.loc.dAlt < 2.0) {
// If falling faster than -40m/s, definitely deploy.
if (est.loc.dAlt < -40.0) {
return RocketState::APOGEE;
}
// Check for near-zero altitude change towards end of ascent (ideal case)
// and that we are not just undergoing a subsonic transition.
else if ((*meas.accel).axes[0] > -1.0) {
return RocketState::APOGEE;
}
}
return RocketState::FLIGHT;
}
RocketState RocketSystem::ApogeeState(SensorMeasurements meas, WorldEstimate est) {
PulseLED(0,0,1,2); // Blue 2 Hz
static float sTime = 0.0; // State time
// Fire drogue pyro
platform.get<DigitalPlatform>().set(unit_config::PIN_DROGUE_CH, true);
// Count continuous time under drogue
// TODO(yoos): We might still see this if partially deployed and spinning
// around..
static float drogueTime = 0.0;
if ((*meas.accel).axes[0] > 0.3) {
drogueTime += unit_config::DT;
}
else {
drogueTime = 0.0;
}
// Check for successful drogue deployment. If failure detected, deploy main.
if (sTime < 10.0) { // TODO(yoos): Is it safe to wait this long?
if (drogueTime > 1.0) { // TODO(yoos): Do we want to wait longer for ensure drogue?
return RocketState::DESCENT;
}
}
else {
platform.get<DigitalPlatform>().set(unit_config::PIN_MAIN_CH, true);
return RocketState::DESCENT;
}
sTime += unit_config::DT;
return RocketState::APOGEE;
}
RocketState RocketSystem::DescentState(SensorMeasurements meas, WorldEstimate est) {
SetLED(1,0,1); // Violet
static float sTime = 0.0; // State time
// Deploy main at 1500' (457.2m) AGL.
if (est.loc.alt < (groundAltitude + 457.2)) {
platform.get<DigitalPlatform>().set(unit_config::PIN_MAIN_CH, true);
}
// Stay for at least 1 s
static int count = 1000;
if (sTime < 1.0) {}
// Enter recovery if altitude is unchanging and rotation rate is zero
else if (est.loc.dAlt > -2.0 &&
fabs((*meas.gyro).axes[0] < 0.05) &&
fabs((*meas.gyro).axes[1] < 0.05) &&
fabs((*meas.gyro).axes[2] < 0.05)) {
count -= 1;
}
else {
count = 1000;
}
if (count == 0) {
return RocketState::RECOVERY;
}
sTime += unit_config::DT;
return RocketState::DESCENT;
}
RocketState RocketSystem::RecoveryState(SensorMeasurements meas, WorldEstimate est) {
PulseLED(1,0,1,2); // Violet 2 Hz
// Turn things off
platform.get<DigitalPlatform>().set(unit_config::PIN_MAIN_CH, false);
platform.get<DigitalPlatform>().set(unit_config::PIN_DROGUE_CH, false);
return RocketState::RECOVERY;
}
void RocketSystem::SetLED(float r, float g, float b) {
platform.get<PWMPlatform>().set(9, 0.1*r);
platform.get<PWMPlatform>().set(10, 0.1*g);
platform.get<PWMPlatform>().set(11, 0.1*b);
}
void RocketSystem::BlinkLED(float r, float g, float b, float freq) { static int count = 0;
int period = 1000 / freq;
if (count % period < period/2) {
SetLED(r,g,b);
}
else {
SetLED(0,0,0);
}
count = (count+1) % period;
}
void RocketSystem::PulseLED(float r, float g, float b, float freq) {
int period = 1000 / freq;
static int count = 0;
float dc = ((float) abs(period/2 - count)) / (period/2);
SetLED(dc*r, dc*g, dc*b);
count = (count+1) % period;
}
|
#include "system/rocket_system.hpp"
#include "util/time.hpp"
#include "ch.hpp"
#include "chprintf.h"
RocketSystem::RocketSystem(
Accelerometer& accel,
optional<Accelerometer *> accelH,
optional<Barometer *> bar,
optional<GPS *> gps,
Gyroscope& gyr,
optional<Magnetometer *> mag,
WorldEstimator& estimator, InputSource& inputSource,
MotorMapper& motorMapper, Communicator& communicator,
Platform& platform)
: VehicleSystem(communicator), MessageListener(communicator),
accel(accel), accelH(accelH), bar(bar), gps(gps), gyr(gyr), mag(mag),
estimator(estimator), inputSource(inputSource),
motorMapper(motorMapper), platform(platform),
imuStream(communicator, 10), // TODO(yoos): calculate data link budget and increase if possible
systemStream(communicator, 5),
state(RocketState::DISARMED) {
// Disarm by default. A set_arm_state_message_t message is required to enable
// the control pipeline.
setArmed(false);
}
void RocketSystem::update() {
//static int time = 0;
//if (time % 1000 == 0) {
// chprintf((BaseSequentialStream*)&SD4, "%d\r\n", RTT2MS(chibios_rt::System::getTime()));
//}
//time = (time+1) % 1000;
// Poll the gyroscope and accelerometer
AccelerometerReading accelReading = accel.readAccel();
GyroscopeReading gyrReading = gyr.readGyro();
optional<AccelerometerReading> accelHReading;
optional<BarometerReading> barReading;
optional<GPSReading> gpsReading;
optional<MagnetometerReading> magReading;
if (accelH) accelHReading = (*accelH)->readAccel();
if (bar) barReading = (*bar)->readBar();
if (gps) gpsReading = (*gps)->readGPS();
//if (mag) magReading = (*mag)->readMag();
SensorMeasurements meas {
.accel = std::experimental::make_optional(accelReading),
.accelH = accelHReading,
.bar = barReading,
.gps = gpsReading,
.gyro = std::experimental::make_optional(gyrReading),
.mag = magReading
};
// Update the world estimate
WorldEstimate estimate = estimator.update(meas);
// Poll for controller input
ControllerInput input = inputSource.read();
// Keep moving average of acceleration
static float accel = -1.0f;
accel = 0.5*accel + 0.5*accelReading.axes[0];
// Run the controllers
ActuatorSetpoint actuatorSp;
// Run state machine
switch (state) {
case RocketState::DISARMED:
state = DisarmedState(meas, estimate);
break;
case RocketState::PRE_ARM:
state = PreArmState(meas, estimate);
break;
case RocketState::ARMED:
state = ArmedState(meas, estimate);
break;
case RocketState::FLIGHT:
state = FlightState(meas, estimate);
break;
case RocketState::APOGEE:
state = ApogeeState(meas, estimate);
break;
case RocketState::DESCENT:
state = DescentState(meas, estimate);
break;
case RocketState::RECOVERY:
state = RecoveryState(meas, estimate);
break;
default:
break;
}
// Update streams
updateStreams(meas, estimate);
// Update motor outputs
motorMapper.run(isArmed(), actuatorSp);
}
bool RocketSystem::healthy() {
// TODO(yoos): Most of the health checks here are disabled due to a broken av
// bay SPI bus. Reenable on next hardware revision.
bool healthy = true;//accel.healthy() && gyr.healthy();
if(accelH) {
//healthy &= (*accelH)->healthy();
}
if(bar) {
//healthy &= (*bar)->healthy();
}
if(gps) {
healthy &= (*gps)->healthy();
}
if(mag) {
//healthy &= (*mag)->healthy();
}
return healthy;
}
void RocketSystem::on(const protocol::message::set_arm_state_message_t& m) {
setArmed(m.armed);
}
void RocketSystem::updateStreams(SensorMeasurements meas, WorldEstimate est) {
if (imuStream.ready()) {
protocol::message::imu_message_t m {
.time = ST2MS(chibios_rt::System::getTime()),
.gyro = {
(*meas.gyro).axes[0],
(*meas.gyro).axes[1],
(*meas.gyro).axes[2]
},
.accel = {
(*meas.accel).axes[0],
(*meas.accel).axes[1],
(*meas.accel).axes[2]
}
};
imuStream.publish(m);
}
if (systemStream.ready()) {
uint8_t stateNum = 0;
switch (state) {
case RocketState::DISARMED:
stateNum = 0;
break;
case RocketState::PRE_ARM:
stateNum = 1;
break;
case RocketState::ARMED:
stateNum = 2;
break;
case RocketState::FLIGHT:
stateNum = 3;
break;
case RocketState::APOGEE:
stateNum = 4;
break;
case RocketState::DESCENT:
stateNum = 6;
break;
case RocketState::RECOVERY:
stateNum = 7;
break;
default:
break;
}
protocol::message::system_message_t m {
.time = ST2MS(chibios_rt::System::getTime()),
.state = stateNum,
.motorDC = motorDC
};
systemStream.publish(m);
}
}
RocketState RocketSystem::DisarmedState(SensorMeasurements meas, WorldEstimate est) {
PulseLED(1,0,0,1); // Red 1 Hz
// Proceed directly to PRE_ARM for now.
return RocketState::PRE_ARM;
}
RocketState RocketSystem::PreArmState(SensorMeasurements meas, WorldEstimate est) {
PulseLED(1,0,0,4); // Red 4 Hz
// Calibrate
groundAltitude = est.loc.alt;
// TODO(yoos): run sensor calibration here
// Proceed to ARMED if all sensors are healthy and GS arm signal received.
if (healthy() && isArmed()) {
return RocketState::ARMED;
}
return RocketState::PRE_ARM;
}
RocketState RocketSystem::ArmedState(SensorMeasurements meas, WorldEstimate est) {
SetLED(1,0,0); // Red
static int count = 10;
count = ((*meas.accel).axes[0] > 1.1) ? (count-1) : 10;
// Revert to PRE_ARM if any sensors are unhealthy or disarm signal received
if (!(healthy() && isArmed())) {
return RocketState::PRE_ARM;
}
// Proceed to FLIGHT on 1.1g sense on X axis.
if (count == 0) {
return RocketState::FLIGHT;
}
return RocketState::ARMED;
}
RocketState RocketSystem::FlightState(SensorMeasurements meas, WorldEstimate est) {
SetLED(0,0,1); // Blue
static bool powered = true; // First time we enter, we are in powered flight.
// Check for motor cutoff. We should see negative acceleration due to drag.
static int count = 100;
if (powered) {
count = ((*meas.accel).axes[0] < 0.0) ? (count-1) : 100;
powered = (count == 0) ? false : true;
}
// Apogee occurs after motor cutoff
if (!powered && est.loc.dAlt < 2.0) {
// If falling faster than -40m/s, definitely deploy.
if (est.loc.dAlt < -40.0) {
return RocketState::APOGEE;
}
// Check for near-zero altitude change towards end of ascent (ideal case)
// and that we are not just undergoing a subsonic transition.
else if ((*meas.accel).axes[0] > -1.0) {
return RocketState::APOGEE;
}
}
return RocketState::FLIGHT;
}
RocketState RocketSystem::ApogeeState(SensorMeasurements meas, WorldEstimate est) {
PulseLED(0,0,1,2); // Blue 2 Hz
static float sTime = 0.0; // State time
// Fire drogue pyro
platform.get<DigitalPlatform>().set(unit_config::PIN_DROGUE_CH, true);
// Count continuous time under drogue
// TODO(yoos): We might still see this if partially deployed and spinning
// around..
static float drogueTime = 0.0;
if ((*meas.accel).axes[0] > 0.3) {
drogueTime += unit_config::DT;
}
else {
drogueTime = 0.0;
}
// Check for successful drogue deployment. If failure detected, deploy main.
if (sTime < 10.0) { // TODO(yoos): Is it safe to wait this long?
if (drogueTime > 1.0) { // TODO(yoos): Do we want to wait longer for ensure drogue?
return RocketState::DESCENT;
}
}
else {
platform.get<DigitalPlatform>().set(unit_config::PIN_MAIN_CH, true);
return RocketState::DESCENT;
}
sTime += unit_config::DT;
return RocketState::APOGEE;
}
RocketState RocketSystem::DescentState(SensorMeasurements meas, WorldEstimate est) {
SetLED(1,0,1); // Violet
static float sTime = 0.0; // State time
// Deploy main at 1500' (457.2m) AGL.
if (est.loc.alt < (groundAltitude + 457.2)) {
platform.get<DigitalPlatform>().set(unit_config::PIN_MAIN_CH, true);
}
// Stay for at least 1 s
static int count = 1000;
if (sTime < 1.0) {}
// Enter recovery if altitude is unchanging and rotation rate is zero
else if (est.loc.dAlt > -2.0 &&
fabs((*meas.gyro).axes[0] < 0.05) &&
fabs((*meas.gyro).axes[1] < 0.05) &&
fabs((*meas.gyro).axes[2] < 0.05)) {
count -= 1;
}
else {
count = 1000;
}
if (count == 0) {
return RocketState::RECOVERY;
}
sTime += unit_config::DT;
return RocketState::DESCENT;
}
RocketState RocketSystem::RecoveryState(SensorMeasurements meas, WorldEstimate est) {
PulseLED(1,0,1,2); // Violet 2 Hz
// Turn things off
platform.get<DigitalPlatform>().set(unit_config::PIN_MAIN_CH, false);
platform.get<DigitalPlatform>().set(unit_config::PIN_DROGUE_CH, false);
return RocketState::RECOVERY;
}
void RocketSystem::SetLED(float r, float g, float b) {
platform.get<PWMPlatform>().set(9, 0.1*r);
platform.get<PWMPlatform>().set(10, 0.1*g);
platform.get<PWMPlatform>().set(11, 0.1*b);
}
void RocketSystem::BlinkLED(float r, float g, float b, float freq) { static int count = 0;
int period = 1000 / freq;
if (count % period < period/2) {
SetLED(r,g,b);
}
else {
SetLED(0,0,0);
}
count = (count+1) % period;
}
void RocketSystem::PulseLED(float r, float g, float b, float freq) {
int period = 1000 / freq;
static int count = 0;
float dc = ((float) abs(period/2 - count)) / (period/2);
SetLED(dc*r, dc*g, dc*b);
count = (count+1) % period;
}
|
Disable most sensor health checks in rocket system.
|
Disable most sensor health checks in rocket system.
|
C++
|
mit
|
OSURoboticsClub/aerial_control,OSURoboticsClub/aerial_control,OSURoboticsClub/aerial_control
|
6d5ece012f508206059fcce420362d61dbd398e6
|
src/uri/Verify.cxx
|
src/uri/Verify.cxx
|
/*
* Copyright 2007-2020 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Verify.hxx"
#include "Chars.hxx"
#include "util/StringView.hxx"
#include <string.h>
bool
uri_segment_verify(StringView segment) noexcept
{
for (char ch : segment) {
/* XXX check for invalid escaped characters? */
if (!IsUriPchar(ch))
return false;
}
return true;
}
bool
uri_path_verify(StringView uri) noexcept
{
if (uri.empty() || uri.front() != '/')
/* path must begin with slash */
return false;
auto src = uri.begin(), end = uri.end();
const char *slash;
++src;
while (src < end) {
slash = (const char *)memchr(src, '/', end - src);
if (slash == nullptr)
slash = end;
if (!uri_segment_verify({src, slash}))
return false;
src = slash + 1;
}
return true;
}
static constexpr bool
IsEncodedNul(const char *p) noexcept
{
return p[0] == '%' && p[1] == '0' && p[2] == '0';
}
static constexpr bool
IsEncodedDot(const char *p) noexcept
{
return p[0] == '%' && p[1] == '2' &&
(p[2] == 'e' || p[2] == 'E');
}
static constexpr bool
IsEncodedSlash(const char *p) noexcept
{
return p[0] == '%' && p[1] == '2' &&
(p[2] == 'f' || p[2] == 'F');
}
bool
uri_path_verify_paranoid(const char *uri) noexcept
{
if (uri[0] == '.' &&
(uri[1] == 0 || uri[1] == '/' ||
(uri[1] == '.' && (uri[2] == 0 || uri[2] == '/')) ||
IsEncodedDot(uri + 1)))
/* no ".", "..", "./", "../" */
return false;
if (IsEncodedDot(uri))
return false;
while (*uri != 0 && *uri != '?') {
if (*uri == '%') {
if (/* don't allow an encoded NUL character */
IsEncodedNul(uri) ||
/* don't allow an encoded slash (somebody trying to
hide a hack?) */
IsEncodedSlash(uri))
return false;
++uri;
} else if (*uri == '/') {
++uri;
if (IsEncodedDot(uri))
/* encoded dot after a slash - what's this client
trying to hide? */
return false;
if (*uri == '.') {
++uri;
if (IsEncodedDot(uri))
/* encoded dot after a real dot - smells fishy */
return false;
if (*uri == 0 || *uri == '/')
return false;
if (*uri == '.')
/* disallow two dots after a slash, even if
something else follows - this is the paranoid
function after all! */
return false;
}
} else
++uri;
}
return true;
}
bool
uri_path_verify_quick(const char *uri) noexcept
{
if (*uri != '/')
/* must begin with a slash */
return false;
for (++uri; *uri != 0; ++uri)
if ((signed char)*uri <= 0x20)
return false;
return true;
}
|
/*
* Copyright 2007-2020 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Verify.hxx"
#include "Chars.hxx"
#include "util/StringView.hxx"
#include <string.h>
bool
uri_segment_verify(StringView segment) noexcept
{
for (char ch : segment) {
/* XXX check for invalid escaped characters? */
if (!IsUriPchar(ch))
return false;
}
return true;
}
bool
uri_path_verify(StringView uri) noexcept
{
if (uri.empty() || uri.front() != '/')
/* path must begin with slash */
return false;
uri.pop_front(); // strip the leading slash
do {
auto s = uri.Split('/');
if (!uri_segment_verify(s.first))
return false;
uri = s.second;
} while (!uri.empty());
return true;
}
static constexpr bool
IsEncodedNul(const char *p) noexcept
{
return p[0] == '%' && p[1] == '0' && p[2] == '0';
}
static constexpr bool
IsEncodedDot(const char *p) noexcept
{
return p[0] == '%' && p[1] == '2' &&
(p[2] == 'e' || p[2] == 'E');
}
static constexpr bool
IsEncodedSlash(const char *p) noexcept
{
return p[0] == '%' && p[1] == '2' &&
(p[2] == 'f' || p[2] == 'F');
}
bool
uri_path_verify_paranoid(const char *uri) noexcept
{
if (uri[0] == '.' &&
(uri[1] == 0 || uri[1] == '/' ||
(uri[1] == '.' && (uri[2] == 0 || uri[2] == '/')) ||
IsEncodedDot(uri + 1)))
/* no ".", "..", "./", "../" */
return false;
if (IsEncodedDot(uri))
return false;
while (*uri != 0 && *uri != '?') {
if (*uri == '%') {
if (/* don't allow an encoded NUL character */
IsEncodedNul(uri) ||
/* don't allow an encoded slash (somebody trying to
hide a hack?) */
IsEncodedSlash(uri))
return false;
++uri;
} else if (*uri == '/') {
++uri;
if (IsEncodedDot(uri))
/* encoded dot after a slash - what's this client
trying to hide? */
return false;
if (*uri == '.') {
++uri;
if (IsEncodedDot(uri))
/* encoded dot after a real dot - smells fishy */
return false;
if (*uri == 0 || *uri == '/')
return false;
if (*uri == '.')
/* disallow two dots after a slash, even if
something else follows - this is the paranoid
function after all! */
return false;
}
} else
++uri;
}
return true;
}
bool
uri_path_verify_quick(const char *uri) noexcept
{
if (*uri != '/')
/* must begin with a slash */
return false;
for (++uri; *uri != 0; ++uri)
if ((signed char)*uri <= 0x20)
return false;
return true;
}
|
use StringView::Split()
|
uri/Verify: use StringView::Split()
|
C++
|
bsd-2-clause
|
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
|
5d76027dc46998fddd6e69bea4e1e62d3ee355b0
|
src/test/scheduler_tests.cpp
|
src/test/scheduler_tests.cpp
|
// Copyright (c) 2012-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <scheduler.h>
#include <util/time.h>
#include <random.h>
#include <sync.h>
#include <boost/test/unit_test.hpp>
#include <boost/thread.hpp>
#include <atomic>
#include <condition_variable>
#include <thread>
BOOST_AUTO_TEST_SUITE(scheduler_tests)
static void microTask(CScheduler &s, boost::mutex &mutex, int &counter,
int delta,
std::chrono::system_clock::time_point rescheduleTime) {
{
boost::unique_lock<boost::mutex> lock(mutex);
counter += delta;
}
std::chrono::system_clock::time_point noTime =
std::chrono::system_clock::time_point::min();
if (rescheduleTime != noTime) {
CScheduler::Function f =
std::bind(µTask, std::ref(s), std::ref(mutex),
std::ref(counter), -delta + 1, noTime);
s.schedule(f, rescheduleTime);
}
}
BOOST_AUTO_TEST_CASE(manythreads) {
// Stress test: hundreds of microsecond-scheduled tasks,
// serviced by 10 threads.
//
// So... ten shared counters, which if all the tasks execute
// properly will sum to the number of tasks done.
// Each task adds or subtracts a random amount from one of the
// counters, and then schedules another task 0-1000
// microseconds in the future to subtract or add from
// the counter -random_amount+1, so in the end the shared
// counters should sum to the number of initial tasks performed.
CScheduler microTasks;
boost::mutex counterMutex[10];
int counter[10] = {0};
FastRandomContext rng{/* fDeterministic */ true};
// [0, 9]
auto zeroToNine = [](FastRandomContext &rc) -> int {
return rc.randrange(10);
};
// [-11, 1000]
auto randomMsec = [](FastRandomContext &rc) -> int {
return -11 + int(rc.randrange(1012));
};
// [-1000, 1000]
auto randomDelta = [](FastRandomContext &rc) -> int {
return -1000 + int(rc.randrange(2001));
};
std::chrono::system_clock::time_point start =
std::chrono::system_clock::now();
std::chrono::system_clock::time_point now = start;
std::chrono::system_clock::time_point first, last;
size_t nTasks = microTasks.getQueueInfo(first, last);
BOOST_CHECK(nTasks == 0);
for (int i = 0; i < 100; ++i) {
std::chrono::system_clock::time_point t =
now + std::chrono::microseconds(randomMsec(rng));
std::chrono::system_clock::time_point tReschedule =
now + std::chrono::microseconds(500 + randomMsec(rng));
int whichCounter = zeroToNine(rng);
CScheduler::Function f = std::bind(µTask, std::ref(microTasks),
std::ref(counterMutex[whichCounter]),
std::ref(counter[whichCounter]),
randomDelta(rng), tReschedule);
microTasks.schedule(f, t);
}
nTasks = microTasks.getQueueInfo(first, last);
BOOST_CHECK(nTasks == 100);
BOOST_CHECK(first < last);
BOOST_CHECK(last > now);
// As soon as these are created they will start running and servicing the
// queue
boost::thread_group microThreads;
for (int i = 0; i < 5; i++) {
microThreads.create_thread(
std::bind(&CScheduler::serviceQueue, µTasks));
}
UninterruptibleSleep(std::chrono::microseconds{600});
now = std::chrono::system_clock::now();
// More threads and more tasks:
for (int i = 0; i < 5; i++) {
microThreads.create_thread(
std::bind(&CScheduler::serviceQueue, µTasks));
}
for (int i = 0; i < 100; i++) {
std::chrono::system_clock::time_point t =
now + std::chrono::microseconds(randomMsec(rng));
std::chrono::system_clock::time_point tReschedule =
now + std::chrono::microseconds(500 + randomMsec(rng));
int whichCounter = zeroToNine(rng);
CScheduler::Function f = std::bind(µTask, std::ref(microTasks),
std::ref(counterMutex[whichCounter]),
std::ref(counter[whichCounter]),
randomDelta(rng), tReschedule);
microTasks.schedule(f, t);
}
// Drain the task queue then exit threads
microTasks.stop(true);
// ... wait until all the threads are done
microThreads.join_all();
int counterSum = 0;
for (int i = 0; i < 10; i++) {
BOOST_CHECK(counter[i] != 0);
counterSum += counter[i];
}
BOOST_CHECK_EQUAL(counterSum, 200);
}
BOOST_AUTO_TEST_CASE(schedule_every) {
CScheduler scheduler;
std::condition_variable cvar;
std::atomic<int> counter{15};
std::atomic<bool> keepRunning{true};
scheduler.scheduleEvery(
[&keepRunning, &cvar, &counter, &scheduler]() {
assert(counter > 0);
cvar.notify_all();
if (--counter > 0) {
return true;
}
// We reached the end of our test, make sure nothing run again for
// 100ms.
scheduler.scheduleFromNow(
[&keepRunning, &cvar]() {
keepRunning = false;
cvar.notify_all();
},
std::chrono::milliseconds{100});
// We set the counter to some magic value to check the scheduler
// empty its queue properly after 120ms.
scheduler.scheduleFromNow([&counter]() { counter = 42; },
std::chrono::milliseconds{120});
return false;
},
std::chrono::milliseconds{5});
// Start the scheduler thread.
std::thread schedulerThread(
std::bind(&CScheduler::serviceQueue, &scheduler));
Mutex mutex;
WAIT_LOCK(mutex, lock);
while (keepRunning) {
cvar.wait(lock);
BOOST_CHECK(counter >= 0);
}
BOOST_CHECK_EQUAL(counter, 0);
scheduler.stop(true);
schedulerThread.join();
BOOST_CHECK_EQUAL(counter, 42);
}
BOOST_AUTO_TEST_CASE(wait_until_past) {
std::condition_variable condvar;
Mutex mtx;
WAIT_LOCK(mtx, lock);
const auto no_wait = [&](const std::chrono::seconds &d) {
return condvar.wait_until(lock, std::chrono::system_clock::now() - d);
};
BOOST_CHECK(std::cv_status::timeout == no_wait(std::chrono::seconds{1}));
BOOST_CHECK(std::cv_status::timeout == no_wait(std::chrono::minutes{1}));
BOOST_CHECK(std::cv_status::timeout == no_wait(std::chrono::hours{1}));
BOOST_CHECK(std::cv_status::timeout == no_wait(std::chrono::hours{10}));
BOOST_CHECK(std::cv_status::timeout == no_wait(std::chrono::hours{100}));
BOOST_CHECK(std::cv_status::timeout == no_wait(std::chrono::hours{1000}));
}
BOOST_AUTO_TEST_CASE(singlethreadedscheduler_ordered) {
CScheduler scheduler;
// each queue should be well ordered with respect to itself but not other
// queues
SingleThreadedSchedulerClient queue1(&scheduler);
SingleThreadedSchedulerClient queue2(&scheduler);
// create more threads than queues
// if the queues only permit execution of one task at once then
// the extra threads should effectively be doing nothing
// if they don't we'll get out of order behaviour
boost::thread_group threads;
for (int i = 0; i < 5; ++i) {
threads.create_thread(std::bind(&CScheduler::serviceQueue, &scheduler));
}
// these are not atomic, if SinglethreadedSchedulerClient prevents
// parallel execution at the queue level no synchronization should be
// required here
int counter1 = 0;
int counter2 = 0;
// just simply count up on each queue - if execution is properly ordered
// then the callbacks should run in exactly the order in which they were
// enqueued
for (int i = 0; i < 100; ++i) {
queue1.AddToProcessQueue([i, &counter1]() {
bool expectation = i == counter1++;
assert(expectation);
});
queue2.AddToProcessQueue([i, &counter2]() {
bool expectation = i == counter2++;
assert(expectation);
});
}
// finish up
scheduler.stop(true);
threads.join_all();
BOOST_CHECK_EQUAL(counter1, 100);
BOOST_CHECK_EQUAL(counter2, 100);
}
BOOST_AUTO_TEST_CASE(mockforward) {
CScheduler scheduler;
int counter{0};
CScheduler::Function dummy = [&counter] { counter++; };
// schedule jobs for 2, 5 & 8 minutes into the future
scheduler.scheduleFromNow(dummy, std::chrono::minutes{2});
scheduler.scheduleFromNow(dummy, std::chrono::minutes{5});
scheduler.scheduleFromNow(dummy, std::chrono::minutes{8});
// check taskQueue
std::chrono::system_clock::time_point first, last;
size_t num_tasks = scheduler.getQueueInfo(first, last);
BOOST_CHECK_EQUAL(num_tasks, 3ul);
std::thread scheduler_thread([&]() { scheduler.serviceQueue(); });
// bump the scheduler forward 5 minutes
scheduler.MockForward(std::chrono::minutes{5});
// ensure scheduler has chance to process all tasks queued for before 1 ms
// from now.
scheduler.scheduleFromNow([&scheduler] { scheduler.stop(false); },
std::chrono::milliseconds{1});
scheduler_thread.join();
// check that the queue only has one job remaining
num_tasks = scheduler.getQueueInfo(first, last);
BOOST_CHECK_EQUAL(num_tasks, 1ul);
// check that the dummy function actually ran
BOOST_CHECK_EQUAL(counter, 2);
// check that the time of the remaining job has been updated
std::chrono::system_clock::time_point now =
std::chrono::system_clock::now();
int delta =
std::chrono::duration_cast<std::chrono::seconds>(first - now).count();
// should be between 2 & 3 minutes from now
BOOST_CHECK(delta > 2 * 60 && delta < 3 * 60);
}
BOOST_AUTO_TEST_SUITE_END()
|
// Copyright (c) 2012-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <scheduler.h>
#include <util/time.h>
#include <random.h>
#include <sync.h>
#include <boost/test/unit_test.hpp>
#include <boost/thread.hpp>
#include <atomic>
#include <condition_variable>
#include <mutex>
#include <thread>
BOOST_AUTO_TEST_SUITE(scheduler_tests)
static void microTask(CScheduler &s, std::mutex &mutex, int &counter, int delta,
std::chrono::system_clock::time_point rescheduleTime) {
{
std::lock_guard<std::mutex> lock(mutex);
counter += delta;
}
std::chrono::system_clock::time_point noTime =
std::chrono::system_clock::time_point::min();
if (rescheduleTime != noTime) {
CScheduler::Function f =
std::bind(µTask, std::ref(s), std::ref(mutex),
std::ref(counter), -delta + 1, noTime);
s.schedule(f, rescheduleTime);
}
}
BOOST_AUTO_TEST_CASE(manythreads) {
// Stress test: hundreds of microsecond-scheduled tasks,
// serviced by 10 threads.
//
// So... ten shared counters, which if all the tasks execute
// properly will sum to the number of tasks done.
// Each task adds or subtracts a random amount from one of the
// counters, and then schedules another task 0-1000
// microseconds in the future to subtract or add from
// the counter -random_amount+1, so in the end the shared
// counters should sum to the number of initial tasks performed.
CScheduler microTasks;
std::mutex counterMutex[10];
int counter[10] = {0};
FastRandomContext rng{/* fDeterministic */ true};
// [0, 9]
auto zeroToNine = [](FastRandomContext &rc) -> int {
return rc.randrange(10);
};
// [-11, 1000]
auto randomMsec = [](FastRandomContext &rc) -> int {
return -11 + int(rc.randrange(1012));
};
// [-1000, 1000]
auto randomDelta = [](FastRandomContext &rc) -> int {
return -1000 + int(rc.randrange(2001));
};
std::chrono::system_clock::time_point start =
std::chrono::system_clock::now();
std::chrono::system_clock::time_point now = start;
std::chrono::system_clock::time_point first, last;
size_t nTasks = microTasks.getQueueInfo(first, last);
BOOST_CHECK(nTasks == 0);
for (int i = 0; i < 100; ++i) {
std::chrono::system_clock::time_point t =
now + std::chrono::microseconds(randomMsec(rng));
std::chrono::system_clock::time_point tReschedule =
now + std::chrono::microseconds(500 + randomMsec(rng));
int whichCounter = zeroToNine(rng);
CScheduler::Function f = std::bind(µTask, std::ref(microTasks),
std::ref(counterMutex[whichCounter]),
std::ref(counter[whichCounter]),
randomDelta(rng), tReschedule);
microTasks.schedule(f, t);
}
nTasks = microTasks.getQueueInfo(first, last);
BOOST_CHECK(nTasks == 100);
BOOST_CHECK(first < last);
BOOST_CHECK(last > now);
// As soon as these are created they will start running and servicing the
// queue
boost::thread_group microThreads;
for (int i = 0; i < 5; i++) {
microThreads.create_thread(
std::bind(&CScheduler::serviceQueue, µTasks));
}
UninterruptibleSleep(std::chrono::microseconds{600});
now = std::chrono::system_clock::now();
// More threads and more tasks:
for (int i = 0; i < 5; i++) {
microThreads.create_thread(
std::bind(&CScheduler::serviceQueue, µTasks));
}
for (int i = 0; i < 100; i++) {
std::chrono::system_clock::time_point t =
now + std::chrono::microseconds(randomMsec(rng));
std::chrono::system_clock::time_point tReschedule =
now + std::chrono::microseconds(500 + randomMsec(rng));
int whichCounter = zeroToNine(rng);
CScheduler::Function f = std::bind(µTask, std::ref(microTasks),
std::ref(counterMutex[whichCounter]),
std::ref(counter[whichCounter]),
randomDelta(rng), tReschedule);
microTasks.schedule(f, t);
}
// Drain the task queue then exit threads
microTasks.stop(true);
// ... wait until all the threads are done
microThreads.join_all();
int counterSum = 0;
for (int i = 0; i < 10; i++) {
BOOST_CHECK(counter[i] != 0);
counterSum += counter[i];
}
BOOST_CHECK_EQUAL(counterSum, 200);
}
BOOST_AUTO_TEST_CASE(schedule_every) {
CScheduler scheduler;
std::condition_variable cvar;
std::atomic<int> counter{15};
std::atomic<bool> keepRunning{true};
scheduler.scheduleEvery(
[&keepRunning, &cvar, &counter, &scheduler]() {
assert(counter > 0);
cvar.notify_all();
if (--counter > 0) {
return true;
}
// We reached the end of our test, make sure nothing run again for
// 100ms.
scheduler.scheduleFromNow(
[&keepRunning, &cvar]() {
keepRunning = false;
cvar.notify_all();
},
std::chrono::milliseconds{100});
// We set the counter to some magic value to check the scheduler
// empty its queue properly after 120ms.
scheduler.scheduleFromNow([&counter]() { counter = 42; },
std::chrono::milliseconds{120});
return false;
},
std::chrono::milliseconds{5});
// Start the scheduler thread.
std::thread schedulerThread(
std::bind(&CScheduler::serviceQueue, &scheduler));
Mutex mutex;
WAIT_LOCK(mutex, lock);
while (keepRunning) {
cvar.wait(lock);
BOOST_CHECK(counter >= 0);
}
BOOST_CHECK_EQUAL(counter, 0);
scheduler.stop(true);
schedulerThread.join();
BOOST_CHECK_EQUAL(counter, 42);
}
BOOST_AUTO_TEST_CASE(wait_until_past) {
std::condition_variable condvar;
Mutex mtx;
WAIT_LOCK(mtx, lock);
const auto no_wait = [&](const std::chrono::seconds &d) {
return condvar.wait_until(lock, std::chrono::system_clock::now() - d);
};
BOOST_CHECK(std::cv_status::timeout == no_wait(std::chrono::seconds{1}));
BOOST_CHECK(std::cv_status::timeout == no_wait(std::chrono::minutes{1}));
BOOST_CHECK(std::cv_status::timeout == no_wait(std::chrono::hours{1}));
BOOST_CHECK(std::cv_status::timeout == no_wait(std::chrono::hours{10}));
BOOST_CHECK(std::cv_status::timeout == no_wait(std::chrono::hours{100}));
BOOST_CHECK(std::cv_status::timeout == no_wait(std::chrono::hours{1000}));
}
BOOST_AUTO_TEST_CASE(singlethreadedscheduler_ordered) {
CScheduler scheduler;
// each queue should be well ordered with respect to itself but not other
// queues
SingleThreadedSchedulerClient queue1(&scheduler);
SingleThreadedSchedulerClient queue2(&scheduler);
// create more threads than queues
// if the queues only permit execution of one task at once then
// the extra threads should effectively be doing nothing
// if they don't we'll get out of order behaviour
boost::thread_group threads;
for (int i = 0; i < 5; ++i) {
threads.create_thread(std::bind(&CScheduler::serviceQueue, &scheduler));
}
// these are not atomic, if SinglethreadedSchedulerClient prevents
// parallel execution at the queue level no synchronization should be
// required here
int counter1 = 0;
int counter2 = 0;
// just simply count up on each queue - if execution is properly ordered
// then the callbacks should run in exactly the order in which they were
// enqueued
for (int i = 0; i < 100; ++i) {
queue1.AddToProcessQueue([i, &counter1]() {
bool expectation = i == counter1++;
assert(expectation);
});
queue2.AddToProcessQueue([i, &counter2]() {
bool expectation = i == counter2++;
assert(expectation);
});
}
// finish up
scheduler.stop(true);
threads.join_all();
BOOST_CHECK_EQUAL(counter1, 100);
BOOST_CHECK_EQUAL(counter2, 100);
}
BOOST_AUTO_TEST_CASE(mockforward) {
CScheduler scheduler;
int counter{0};
CScheduler::Function dummy = [&counter] { counter++; };
// schedule jobs for 2, 5 & 8 minutes into the future
scheduler.scheduleFromNow(dummy, std::chrono::minutes{2});
scheduler.scheduleFromNow(dummy, std::chrono::minutes{5});
scheduler.scheduleFromNow(dummy, std::chrono::minutes{8});
// check taskQueue
std::chrono::system_clock::time_point first, last;
size_t num_tasks = scheduler.getQueueInfo(first, last);
BOOST_CHECK_EQUAL(num_tasks, 3ul);
std::thread scheduler_thread([&]() { scheduler.serviceQueue(); });
// bump the scheduler forward 5 minutes
scheduler.MockForward(std::chrono::minutes{5});
// ensure scheduler has chance to process all tasks queued for before 1 ms
// from now.
scheduler.scheduleFromNow([&scheduler] { scheduler.stop(false); },
std::chrono::milliseconds{1});
scheduler_thread.join();
// check that the queue only has one job remaining
num_tasks = scheduler.getQueueInfo(first, last);
BOOST_CHECK_EQUAL(num_tasks, 1ul);
// check that the dummy function actually ran
BOOST_CHECK_EQUAL(counter, 2);
// check that the time of the remaining job has been updated
std::chrono::system_clock::time_point now =
std::chrono::system_clock::now();
int delta =
std::chrono::duration_cast<std::chrono::seconds>(first - now).count();
// should be between 2 & 3 minutes from now
BOOST_CHECK(delta > 2 * 60 && delta < 3 * 60);
}
BOOST_AUTO_TEST_SUITE_END()
|
Replace boost::mutex with std::mutex
|
test: Replace boost::mutex with std::mutex
Summary: This is a backport of Core [[https://github.com/bitcoin/bitcoin/pull/18695 | PR18695]]
Test Plan: ninja all check-all
Reviewers: #bitcoin_abc, deadalnix
Reviewed By: #bitcoin_abc, deadalnix
Differential Revision: https://reviews.bitcoinabc.org/D8941
|
C++
|
mit
|
Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc
|
7caf92ef6c189ba32bc87dc9b9c9d7c7d5c138d7
|
glc_factory.cpp
|
glc_factory.cpp
|
/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005-2008 Laurent Ribon ([email protected])
Version 1.1.0, packaged on March, 2009.
http://glc-lib.sourceforge.net
GLC-lib is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
GLC-lib 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 GLC-lib; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
//! \file glc_factory.cpp implementation of the GLC_Factory class.
#include "glc_factory.h"
#include "io/glc_objtoworld.h"
#include "io/glc_stltoworld.h"
#include "io/glc_offtoworld.h"
#include "io/glc_3dstoworld.h"
#include "io/glc_3dxmltoworld.h"
#include "io/glc_colladatoworld.h"
#include "viewport/glc_panmover.h"
#include "viewport/glc_zoommover.h"
#include "viewport/glc_settargetmover.h"
#include "viewport/glc_trackballmover.h"
#include "viewport/glc_turntablemover.h"
#include "viewport/glc_repcrossmover.h"
#include "viewport/glc_reptrackballmover.h"
// init static member
GLC_Factory* GLC_Factory::m_pFactory= NULL;
//////////////////////////////////////////////////////////////////////
// static method
//////////////////////////////////////////////////////////////////////
// Return the unique instance of the factory
GLC_Factory* GLC_Factory::instance(const QGLContext *pContext)
{
if(m_pFactory == NULL)
{
m_pFactory= new GLC_Factory(pContext);
}
return m_pFactory;
}
//////////////////////////////////////////////////////////////////////
// Constructor destructor
//////////////////////////////////////////////////////////////////////
// Protected constructor
GLC_Factory::GLC_Factory(const QGLContext *pContext)
: m_pQGLContext(pContext)
{
}
// Destructor
GLC_Factory::~GLC_Factory()
{
m_pFactory= NULL;
}
//////////////////////////////////////////////////////////////////////
// Create functions
//////////////////////////////////////////////////////////////////////
// Create an GLC_Point
GLC_3DViewInstance GLC_Factory::createPoint(const GLC_Vector4d &coord) const
{
GLC_3DViewInstance newPoint(new GLC_Point(coord));
return newPoint;
}
// Create an GLC_Point
GLC_3DViewInstance GLC_Factory::createPoint(double x, double y, double z) const
{
GLC_3DViewInstance newPoint(new GLC_Point(x, y, z));
return newPoint;
}
// Create an GLC_Line
GLC_3DViewInstance GLC_Factory::createLine(const GLC_Point4d& point1, const GLC_Point4d& point2) const
{
GLC_3DViewInstance newPoint(new GLC_Line(point1, point2));
return newPoint;
}
// Create an GLC_Circle
GLC_3DViewInstance GLC_Factory::createCircle(double radius, double angle) const
{
GLC_3DViewInstance newCircle(new GLC_Circle(radius, angle));
return newCircle;
}
// Create an GLC_Box
GLC_3DViewInstance GLC_Factory::createBox(double lx, double ly, double lz) const
{
GLC_3DViewInstance newBox(new GLC_Box(lx, ly, lz));
return newBox;
}
// Create an GLC_Box
GLC_3DViewInstance GLC_Factory::createBox(const GLC_BoundingBox& boundingBox) const
{
const double lx= boundingBox.getUpper().X() - boundingBox.getLower().X();
const double ly= boundingBox.getUpper().Y() - boundingBox.getLower().Y();
const double lz= boundingBox.getUpper().Z() - boundingBox.getLower().Z();
GLC_Box* pBox= new GLC_Box(lx, ly, lz);
GLC_3DViewInstance newBox(pBox);
newBox.translate(boundingBox.getCenter().X(), boundingBox.getCenter().Y()
, boundingBox.getCenter().Z());
return newBox;
}
// Create an GLC_Cylinder
GLC_3DViewInstance GLC_Factory::createCylinder(double radius, double length) const
{
GLC_3DViewInstance newCylinder(new GLC_Cylinder(radius, length));
return newCylinder;
}
// Create ang GLC_Rectangle
GLC_3DViewInstance GLC_Factory::createRectangle(const GLC_Vector4d& normal, double l1, double l2)
{
GLC_3DViewInstance newRectangle(new GLC_Rectangle(normal, l1, l2));
return newRectangle;
}
// Create an GLC_World* with a QFile
GLC_World* GLC_Factory::createWorld(QFile &file, QStringList* pAttachedFileName) const
{
GLC_World* pWorld= NULL;
if (QFileInfo(file).suffix().toLower() == "obj")
{
GLC_ObjToWorld objToWorld(m_pQGLContext);
connect(&objToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));
pWorld= objToWorld.CreateWorldFromObj(file);
if (NULL != pAttachedFileName)
{
(*pAttachedFileName)= objToWorld.listOfAttachedFileName();
}
}
else if (QFileInfo(file).suffix().toLower() == "stl")
{
GLC_StlToWorld stlToWorld;
connect(&stlToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));
pWorld= stlToWorld.CreateWorldFromStl(file);
}
else if (QFileInfo(file).suffix().toLower() == "off")
{
GLC_OffToWorld offToWorld;
connect(&offToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));
pWorld= offToWorld.CreateWorldFromOff(file);
}
else if (QFileInfo(file).suffix().toLower() == "3ds")
{
GLC_3dsToWorld studioToWorld(m_pQGLContext);
connect(&studioToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));
pWorld= studioToWorld.CreateWorldFrom3ds(file);
if (NULL != pAttachedFileName)
{
(*pAttachedFileName)= studioToWorld.listOfAttachedFileName();
}
}
else if (QFileInfo(file).suffix().toLower() == "3dxml")
{
GLC_3dxmlToWorld d3dxmlToWorld(m_pQGLContext);
connect(&d3dxmlToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));
pWorld= d3dxmlToWorld.CreateWorldFrom3dxml(file, false);
}
else if (QFileInfo(file).suffix().toLower() == "dae")
{
GLC_ColladaToWorld colladaToWorld(m_pQGLContext);
connect(&colladaToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));
pWorld= colladaToWorld.CreateWorldFromCollada(file);
}
return pWorld;
}
// Create an GLC_World containing only the 3dxml structure
GLC_World* GLC_Factory::createWorldStructureFrom3dxml(QFile &file) const
{
GLC_World* pWorld= NULL;
if (QFileInfo(file).suffix().toLower() == "3dxml")
{
GLC_3dxmlToWorld d3dxmlToWorld(m_pQGLContext);
connect(&d3dxmlToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));
pWorld= d3dxmlToWorld.CreateWorldFrom3dxml(file, true);
}
return pWorld;
}
// Create 3DRep from 3dxml or 3DRep file
GLC_3DRep GLC_Factory::create3DrepFromFile(const QString& fileName) const
{
GLC_3DRep rep;
if ((QFileInfo(fileName).suffix().toLower() == "3dxml") or (QFileInfo(fileName).suffix().toLower() == "3drep"))
{
GLC_3dxmlToWorld d3dxmlToWorld(m_pQGLContext);
connect(&d3dxmlToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));
rep= d3dxmlToWorld.Create3DrepFrom3dxmlRep(fileName);
}
return rep;
}
// Create an GLC_Material
GLC_Material* GLC_Factory::createMaterial() const
{
return new GLC_Material();
}
// Create an GLC_Material
GLC_Material* GLC_Factory::createMaterial(const GLfloat *pAmbiantColor) const
{
return new GLC_Material("Material", pAmbiantColor);
}
// Create an GLC_Material
GLC_Material* GLC_Factory::createMaterial(const QColor &color) const
{
return new GLC_Material(color);
}
GLC_Material* GLC_Factory::createMaterial(GLC_Texture* pTexture) const
{
return new GLC_Material(pTexture, "TextureMaterial");
}
// create an material textured with a image file name
GLC_Material* GLC_Factory::createMaterial(const QString &textureFullFileName) const
{
GLC_Texture* pTexture= createTexture(textureFullFileName);
return createMaterial(pTexture);
}
// Create an GLC_Texture
GLC_Texture* GLC_Factory::createTexture(const QString &textureFullFileName) const
{
return new GLC_Texture(m_pQGLContext, textureFullFileName);
}
// Create the default mover controller
GLC_MoverController GLC_Factory::createDefaultMoverController(const QColor& color, GLC_Viewport* pViewport)
{
GLC_MoverController defaultController;
//////////////////////////////////////////////////////////////////////
// Pan Mover
//////////////////////////////////////////////////////////////////////
// Create Pan Mover representation
GLC_RepMover* pRepMover= new GLC_RepCrossMover(pViewport);
pRepMover->setMainColor(color);
QList<GLC_RepMover*> listOfRep;
listOfRep.append(pRepMover);
// Create the Pan Mover
GLC_Mover* pMover= new GLC_PanMover(pViewport, listOfRep);
// Add the Pan Mover to the controller
defaultController.addMover(pMover, GLC_MoverController::Pan);
//////////////////////////////////////////////////////////////////////
// Zoom Mover
//////////////////////////////////////////////////////////////////////
// Copy the pan Mover representation
pRepMover= pRepMover->clone();
listOfRep.clear();
listOfRep.append(pRepMover);
// Create the Zoom Mover
pMover= new GLC_ZoomMover(pViewport, listOfRep);
// Add the Zoom Mover to the controller
defaultController.addMover(pMover, GLC_MoverController::Zoom);
//////////////////////////////////////////////////////////////////////
// Set Target Mover
//////////////////////////////////////////////////////////////////////
// Create the Zoom Mover
pMover= new GLC_SetTargetMover(pViewport);
// Add the Zoom Mover to the controller
defaultController.addMover(pMover, GLC_MoverController::Target);
//////////////////////////////////////////////////////////////////////
// Track Ball Mover
//////////////////////////////////////////////////////////////////////
// Copy the pan Mover representation
pRepMover= pRepMover->clone();
listOfRep.clear();
listOfRep.append(pRepMover);
// Create the track ball representation
pRepMover= new GLC_RepTrackBallMover(pViewport);
pRepMover->setMainColor(color);
listOfRep.append(pRepMover);
// Create the Track Ball Mover
pMover= new GLC_TrackBallMover(pViewport, listOfRep);
// Add the Track ball Mover to the controller
defaultController.addMover(pMover, GLC_MoverController::TrackBall);
//////////////////////////////////////////////////////////////////////
// Turn Table Mover
//////////////////////////////////////////////////////////////////////
// Create the Turn Table Mover
pMover= new GLC_TurnTableMover(pViewport);
// Add the Turn Table Mover to the controller
defaultController.addMover(pMover, GLC_MoverController::TurnTable);
return defaultController;
}
|
/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005-2008 Laurent Ribon ([email protected])
Version 1.1.0, packaged on March, 2009.
http://glc-lib.sourceforge.net
GLC-lib is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
GLC-lib 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 GLC-lib; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
//! \file glc_factory.cpp implementation of the GLC_Factory class.
#include "glc_factory.h"
#include "io/glc_objtoworld.h"
#include "io/glc_stltoworld.h"
#include "io/glc_offtoworld.h"
#include "io/glc_3dstoworld.h"
#include "io/glc_3dxmltoworld.h"
#include "io/glc_colladatoworld.h"
#include "viewport/glc_panmover.h"
#include "viewport/glc_zoommover.h"
#include "viewport/glc_settargetmover.h"
#include "viewport/glc_trackballmover.h"
#include "viewport/glc_turntablemover.h"
#include "viewport/glc_repcrossmover.h"
#include "viewport/glc_reptrackballmover.h"
// init static member
GLC_Factory* GLC_Factory::m_pFactory= NULL;
//////////////////////////////////////////////////////////////////////
// static method
//////////////////////////////////////////////////////////////////////
// Return the unique instance of the factory
GLC_Factory* GLC_Factory::instance(const QGLContext *pContext)
{
if(m_pFactory == NULL)
{
m_pFactory= new GLC_Factory(pContext);
}
return m_pFactory;
}
//////////////////////////////////////////////////////////////////////
// Constructor destructor
//////////////////////////////////////////////////////////////////////
// Protected constructor
GLC_Factory::GLC_Factory(const QGLContext *pContext)
: m_pQGLContext(pContext)
{
}
// Destructor
GLC_Factory::~GLC_Factory()
{
m_pFactory= NULL;
}
//////////////////////////////////////////////////////////////////////
// Create functions
//////////////////////////////////////////////////////////////////////
// Create an GLC_Point
GLC_3DViewInstance GLC_Factory::createPoint(const GLC_Vector4d &coord) const
{
GLC_3DViewInstance newPoint(new GLC_Point(coord));
return newPoint;
}
// Create an GLC_Point
GLC_3DViewInstance GLC_Factory::createPoint(double x, double y, double z) const
{
GLC_3DViewInstance newPoint(new GLC_Point(x, y, z));
return newPoint;
}
// Create an GLC_Line
GLC_3DViewInstance GLC_Factory::createLine(const GLC_Point4d& point1, const GLC_Point4d& point2) const
{
GLC_3DViewInstance newPoint(new GLC_Line(point1, point2));
return newPoint;
}
// Create an GLC_Circle
GLC_3DViewInstance GLC_Factory::createCircle(double radius, double angle) const
{
GLC_3DViewInstance newCircle(new GLC_Circle(radius, angle));
return newCircle;
}
// Create an GLC_Box
GLC_3DViewInstance GLC_Factory::createBox(double lx, double ly, double lz) const
{
GLC_3DViewInstance newBox(new GLC_Box(lx, ly, lz));
return newBox;
}
// Create an GLC_Box
GLC_3DViewInstance GLC_Factory::createBox(const GLC_BoundingBox& boundingBox) const
{
const double lx= boundingBox.getUpper().X() - boundingBox.getLower().X();
const double ly= boundingBox.getUpper().Y() - boundingBox.getLower().Y();
const double lz= boundingBox.getUpper().Z() - boundingBox.getLower().Z();
GLC_Box* pBox= new GLC_Box(lx, ly, lz);
GLC_3DViewInstance newBox(pBox);
newBox.translate(boundingBox.getCenter().X(), boundingBox.getCenter().Y()
, boundingBox.getCenter().Z());
return newBox;
}
// Create an GLC_Cylinder
GLC_3DViewInstance GLC_Factory::createCylinder(double radius, double length) const
{
GLC_3DViewInstance newCylinder(new GLC_Cylinder(radius, length));
return newCylinder;
}
// Create ang GLC_Rectangle
GLC_3DViewInstance GLC_Factory::createRectangle(const GLC_Vector4d& normal, double l1, double l2)
{
GLC_3DViewInstance newRectangle(new GLC_Rectangle(normal, l1, l2));
return newRectangle;
}
// Create an GLC_World* with a QFile
GLC_World* GLC_Factory::createWorld(QFile &file, QStringList* pAttachedFileName) const
{
GLC_World* pWorld= NULL;
if (QFileInfo(file).suffix().toLower() == "obj")
{
GLC_ObjToWorld objToWorld(m_pQGLContext);
connect(&objToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));
pWorld= objToWorld.CreateWorldFromObj(file);
if (NULL != pAttachedFileName)
{
(*pAttachedFileName)= objToWorld.listOfAttachedFileName();
}
}
else if (QFileInfo(file).suffix().toLower() == "stl")
{
GLC_StlToWorld stlToWorld;
connect(&stlToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));
pWorld= stlToWorld.CreateWorldFromStl(file);
}
else if (QFileInfo(file).suffix().toLower() == "off")
{
GLC_OffToWorld offToWorld;
connect(&offToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));
pWorld= offToWorld.CreateWorldFromOff(file);
}
else if (QFileInfo(file).suffix().toLower() == "3ds")
{
GLC_3dsToWorld studioToWorld(m_pQGLContext);
connect(&studioToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));
pWorld= studioToWorld.CreateWorldFrom3ds(file);
if (NULL != pAttachedFileName)
{
(*pAttachedFileName)= studioToWorld.listOfAttachedFileName();
}
}
else if (QFileInfo(file).suffix().toLower() == "3dxml")
{
GLC_3dxmlToWorld d3dxmlToWorld(m_pQGLContext);
connect(&d3dxmlToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));
pWorld= d3dxmlToWorld.CreateWorldFrom3dxml(file, false);
if (NULL != pAttachedFileName)
{
(*pAttachedFileName)= d3dxmlToWorld.listOfAttachedFileName();
}
}
else if (QFileInfo(file).suffix().toLower() == "dae")
{
GLC_ColladaToWorld colladaToWorld(m_pQGLContext);
connect(&colladaToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));
pWorld= colladaToWorld.CreateWorldFromCollada(file);
if (NULL != pAttachedFileName)
{
(*pAttachedFileName)= colladaToWorld.listOfAttachedFileName();
}
}
return pWorld;
}
// Create an GLC_World containing only the 3dxml structure
GLC_World* GLC_Factory::createWorldStructureFrom3dxml(QFile &file) const
{
GLC_World* pWorld= NULL;
if (QFileInfo(file).suffix().toLower() == "3dxml")
{
GLC_3dxmlToWorld d3dxmlToWorld(m_pQGLContext);
connect(&d3dxmlToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));
pWorld= d3dxmlToWorld.CreateWorldFrom3dxml(file, true);
}
return pWorld;
}
// Create 3DRep from 3dxml or 3DRep file
GLC_3DRep GLC_Factory::create3DrepFromFile(const QString& fileName) const
{
GLC_3DRep rep;
if ((QFileInfo(fileName).suffix().toLower() == "3dxml") or (QFileInfo(fileName).suffix().toLower() == "3drep"))
{
GLC_3dxmlToWorld d3dxmlToWorld(m_pQGLContext);
connect(&d3dxmlToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));
rep= d3dxmlToWorld.Create3DrepFrom3dxmlRep(fileName);
}
return rep;
}
// Create an GLC_Material
GLC_Material* GLC_Factory::createMaterial() const
{
return new GLC_Material();
}
// Create an GLC_Material
GLC_Material* GLC_Factory::createMaterial(const GLfloat *pAmbiantColor) const
{
return new GLC_Material("Material", pAmbiantColor);
}
// Create an GLC_Material
GLC_Material* GLC_Factory::createMaterial(const QColor &color) const
{
return new GLC_Material(color);
}
GLC_Material* GLC_Factory::createMaterial(GLC_Texture* pTexture) const
{
return new GLC_Material(pTexture, "TextureMaterial");
}
// create an material textured with a image file name
GLC_Material* GLC_Factory::createMaterial(const QString &textureFullFileName) const
{
GLC_Texture* pTexture= createTexture(textureFullFileName);
return createMaterial(pTexture);
}
// Create an GLC_Texture
GLC_Texture* GLC_Factory::createTexture(const QString &textureFullFileName) const
{
return new GLC_Texture(m_pQGLContext, textureFullFileName);
}
// Create the default mover controller
GLC_MoverController GLC_Factory::createDefaultMoverController(const QColor& color, GLC_Viewport* pViewport)
{
GLC_MoverController defaultController;
//////////////////////////////////////////////////////////////////////
// Pan Mover
//////////////////////////////////////////////////////////////////////
// Create Pan Mover representation
GLC_RepMover* pRepMover= new GLC_RepCrossMover(pViewport);
pRepMover->setMainColor(color);
QList<GLC_RepMover*> listOfRep;
listOfRep.append(pRepMover);
// Create the Pan Mover
GLC_Mover* pMover= new GLC_PanMover(pViewport, listOfRep);
// Add the Pan Mover to the controller
defaultController.addMover(pMover, GLC_MoverController::Pan);
//////////////////////////////////////////////////////////////////////
// Zoom Mover
//////////////////////////////////////////////////////////////////////
// Copy the pan Mover representation
pRepMover= pRepMover->clone();
listOfRep.clear();
listOfRep.append(pRepMover);
// Create the Zoom Mover
pMover= new GLC_ZoomMover(pViewport, listOfRep);
// Add the Zoom Mover to the controller
defaultController.addMover(pMover, GLC_MoverController::Zoom);
//////////////////////////////////////////////////////////////////////
// Set Target Mover
//////////////////////////////////////////////////////////////////////
// Create the Zoom Mover
pMover= new GLC_SetTargetMover(pViewport);
// Add the Zoom Mover to the controller
defaultController.addMover(pMover, GLC_MoverController::Target);
//////////////////////////////////////////////////////////////////////
// Track Ball Mover
//////////////////////////////////////////////////////////////////////
// Copy the pan Mover representation
pRepMover= pRepMover->clone();
listOfRep.clear();
listOfRep.append(pRepMover);
// Create the track ball representation
pRepMover= new GLC_RepTrackBallMover(pViewport);
pRepMover->setMainColor(color);
listOfRep.append(pRepMover);
// Create the Track Ball Mover
pMover= new GLC_TrackBallMover(pViewport, listOfRep);
// Add the Track ball Mover to the controller
defaultController.addMover(pMover, GLC_MoverController::TrackBall);
//////////////////////////////////////////////////////////////////////
// Turn Table Mover
//////////////////////////////////////////////////////////////////////
// Create the Turn Table Mover
pMover= new GLC_TurnTableMover(pViewport);
// Add the Turn Table Mover to the controller
defaultController.addMover(pMover, GLC_MoverController::TurnTable);
return defaultController;
}
|
Add the possibility to get collada and 3dxml attached files list.
|
Add the possibility to get collada and 3dxml attached files list.
|
C++
|
lgpl-2.1
|
3drepo/GLC_lib
|
b551056330fca324dee167a5920004bc39e79659
|
trunk/src/rtmp/srs_protocol_io.hpp
|
trunk/src/rtmp/srs_protocol_io.hpp
|
/*
The MIT License (MIT)
Copyright (c) 2013-2014 winlin
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.
*/
#ifndef SRS_RTMP_PROTOCOL_IO_HPP
#define SRS_RTMP_PROTOCOL_IO_HPP
/*
#include <srs_protocol_io.hpp>
*/
#include <srs_core.hpp>
#include <sys/uio.h>
#include <srs_kernel_buffer.hpp>
/**
* the system io reader/writer architecture:
+---------------+ +--------------------+ +---------------+
| IBufferReader | | IStatistic | | IBufferWriter |
+---------------+ +--------------------+ +---------------+
| + read() | | + get_recv_bytes() | | + write() |
+------+--------+ | + get_recv_bytes() | | + writev() |
/ \ +---+--------------+-+ +-------+-------+
| / \ / \ / \
| | | |
+------+------------------+-+ +-----+----------------+--+
| IProtocolReader | | IProtocolWriter |
+---------------------------+ +-------------------------+
| + readfully() | | + set_send_timeout() |
| + set_recv_timeout() | +-------+-----------------+
+------------+--------------+ / \
/ \ |
| |
+--+-----------------------------+-+
| IProtocolReaderWriter |
+----------------------------------+
| + is_never_timeout() |
+----------------------------------+
*/
/**
* the writer for the buffer to write to whatever channel.
*/
class ISrsBufferWriter
{
public:
ISrsBufferWriter();
virtual ~ISrsBufferWriter();
// for protocol
public:
virtual int write(void* buf, size_t size, ssize_t* nwrite) = 0;
virtual int writev(const iovec *iov, int iov_size, ssize_t* nwrite) = 0;
};
/**
* get the statistic of channel.
*/
class ISrsProtocolStatistic
{
public:
ISrsProtocolStatistic();
virtual ~ISrsProtocolStatistic();
// for protocol
public:
virtual int64_t get_recv_bytes() = 0;
virtual int64_t get_send_bytes() = 0;
};
/**
* the reader for the protocol to read from whatever channel.
*/
class ISrsProtocolReader : public virtual ISrsBufferReader, public virtual ISrsProtocolStatistic
{
public:
ISrsProtocolReader();
virtual ~ISrsProtocolReader();
// for protocol
public:
virtual void set_recv_timeout(int64_t timeout_us) = 0;
virtual int64_t get_recv_timeout() = 0;
// for handshake.
public:
virtual int read_fully(void* buf, size_t size, ssize_t* nread) = 0;
};
/**
* the writer for the protocol to write to whatever channel.
*/
class ISrsProtocolWriter : public virtual ISrsBufferWriter, public virtual ISrsProtocolStatistic
{
public:
ISrsProtocolWriter();
virtual ~ISrsProtocolWriter();
// for protocol
public:
virtual void set_send_timeout(int64_t timeout_us) = 0;
virtual int64_t get_send_timeout() = 0;
};
/**
* the reader and writer.
*/
class ISrsProtocolReaderWriter : public virtual ISrsProtocolReader, public virtual ISrsProtocolWriter
{
public:
ISrsProtocolReaderWriter();
virtual ~ISrsProtocolReaderWriter();
// for protocol
public:
/**
* whether the specified timeout_us is never timeout.
*/
virtual bool is_never_timeout(int64_t timeout_us) = 0;
};
#endif
|
/*
The MIT License (MIT)
Copyright (c) 2013-2014 winlin
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.
*/
#ifndef SRS_RTMP_PROTOCOL_IO_HPP
#define SRS_RTMP_PROTOCOL_IO_HPP
/*
#include <srs_protocol_io.hpp>
*/
#include <srs_core.hpp>
#include <sys/uio.h>
#include <srs_kernel_buffer.hpp>
/**
* the system io reader/writer architecture:
+---------------+ +--------------------+ +---------------+
| IBufferReader | | IStatistic | | IBufferWriter |
+---------------+ +--------------------+ +---------------+
| + read() | | + get_recv_bytes() | | + write() |
+------+--------+ | + get_recv_bytes() | | + writev() |
/ \ +---+--------------+-+ +-------+-------+
| / \ / \ / \
| | | |
+------+------------------+-+ +-----+----------------+--+
| IProtocolReader | | IProtocolWriter |
+---------------------------+ +-------------------------+
| + readfully() | | + set_send_timeout() |
| + set_recv_timeout() | +-------+-----------------+
+------------+--------------+ / \
/ \ |
| |
+--+-----------------------------+-+
| IProtocolReaderWriter |
+----------------------------------+
| + is_never_timeout() |
+----------------------------------+
*/
/**
* the writer for the buffer to write to whatever channel.
*/
class ISrsBufferWriter
{
public:
ISrsBufferWriter();
virtual ~ISrsBufferWriter();
// for protocol
public:
/**
* write bytes over writer.
* @nwrite the actual written bytes. NULL to ignore.
*/
virtual int write(void* buf, size_t size, ssize_t* nwrite) = 0;
/**
* write iov over writer.
* @nwrite the actual written bytes. NULL to ignore.
*/
virtual int writev(const iovec *iov, int iov_size, ssize_t* nwrite) = 0;
};
/**
* get the statistic of channel.
*/
class ISrsProtocolStatistic
{
public:
ISrsProtocolStatistic();
virtual ~ISrsProtocolStatistic();
// for protocol
public:
/**
* get the total recv bytes over underlay fd.
*/
virtual int64_t get_recv_bytes() = 0;
/**
* get the total send bytes over underlay fd.
*/
virtual int64_t get_send_bytes() = 0;
};
/**
* the reader for the protocol to read from whatever channel.
*/
class ISrsProtocolReader : public virtual ISrsBufferReader, public virtual ISrsProtocolStatistic
{
public:
ISrsProtocolReader();
virtual ~ISrsProtocolReader();
// for protocol
public:
/**
* set the recv timeout in us, recv will error when timeout.
* @remark, if not set, use ST_UTIME_NO_TIMEOUT, never timeout.
*/
virtual void set_recv_timeout(int64_t timeout_us) = 0;
/**
* get the recv timeout in us.
*/
virtual int64_t get_recv_timeout() = 0;
// for handshake.
public:
/**
* read specified size bytes of data
* @param nread, the actually read size, NULL to ignore.
*/
virtual int read_fully(void* buf, size_t size, ssize_t* nread) = 0;
};
/**
* the writer for the protocol to write to whatever channel.
*/
class ISrsProtocolWriter : public virtual ISrsBufferWriter, public virtual ISrsProtocolStatistic
{
public:
ISrsProtocolWriter();
virtual ~ISrsProtocolWriter();
// for protocol
public:
/**
* set the send timeout in us, send will error when timeout.
* @remark, if not set, use ST_UTIME_NO_TIMEOUT, never timeout.
*/
virtual void set_send_timeout(int64_t timeout_us) = 0;
/**
* get the send timeout in us.
*/
virtual int64_t get_send_timeout() = 0;
};
/**
* the reader and writer.
*/
class ISrsProtocolReaderWriter : public virtual ISrsProtocolReader, public virtual ISrsProtocolWriter
{
public:
ISrsProtocolReaderWriter();
virtual ~ISrsProtocolReaderWriter();
// for protocol
public:
/**
* whether the specified timeout_us is never timeout.
*/
virtual bool is_never_timeout(int64_t timeout_us) = 0;
};
#endif
|
add comments of io interfaces.
|
add comments of io interfaces.
|
C++
|
mit
|
dymx101/simple-rtmp-server,oceanho/simple-rtmp-server,tribbiani/srs,KevinHM/simple-rtmp-server,KevinHM/simple-rtmp-server,skyfe79/srs,CallMeNP/srs,drunknbass/srs,oceanho/simple-rtmp-server,lewdon/srs,skyfe79/srs,myself659/simple-rtmp-server,JinruiWang/srs,dymx101/srs,antonioparisi/srs,JinruiWang/srs,danielfree/srs,newlightdd/srs,rudeb0t/simple-rtmp-server,wenqinruan/srs,antonioparisi/srs,tempbottle/simple-rtmp-server,rudeb0t/simple-rtmp-server,drunknbass/srs,winlinvip/srs,JinruiWang/srs,newlightdd/srs,WilliamRen/srs,avplus/srs,winlinvip/simple-rtmp-server,avplus/srs,skyfe79/srs,ossrs/srs,wenqinruan/srs,drunknbass/srs,myself659/simple-rtmp-server,rudeb0t/simple-rtmp-server,icevl/srs,Robinson10240/simple-rtmp-server,antonioparisi/srs,CallMeNP/srs,Robinson10240/simple-rtmp-server,ossrs/srs,lzpfmh/simple-rtmp-server,antonioparisi/srs,tribbiani/srs,drunknbass/srs,tribbiani/srs,winlinvip/srs,Robinson10240/simple-rtmp-server,zhiliaoniu/simple-rtmp-server,dymx101/simple-rtmp-server,tempbottle/simple-rtmp-server,chengjunjian/simple-rtmp-server,chengjunjian/simple-rtmp-server,myself659/simple-rtmp-server,zhiliaoniu/simple-rtmp-server,lewdon/srs,keyanmca/srs-May-2014,newlightdd/srs,keyanmca/srs-May-2014,lzpfmh/simple-rtmp-server,Vincent0209/simple-rtmp-server,icevl/srs,dymx101/simple-rtmp-server,avplus/srs,icevl/srs,wenqinruan/srs,chengjunjian/simple-rtmp-server,icevl/srs,wenqinruan/srs,dymx101/simple-rtmp-server,dymx101/simple-rtmp-server,danielfree/srs,nestle1998/srs,avplus/srs,antonioparisi/srs,zhiliaoniu/simple-rtmp-server,nestle1998/srs,dymx101/srs,KevinHM/simple-rtmp-server,lzpfmh/simple-rtmp-server,winlinvip/srs,chengjunjian/simple-rtmp-server,skyfe79/srs,ossrs/srs,ossrs/srs,flashbuckets/srs,keyanmca/srs-May-2014,lewdon/srs,chengjunjian/simple-rtmp-server,avplus/srs,nestle1998/srs,avplus/srs,winlinvip/srs,oceanho/simple-rtmp-server,dymx101/srs,rudeb0t/simple-rtmp-server,nestle1998/srs,keyanmca/srs-May-2014,KevinHM/simple-rtmp-server,danielfree/srs,winlinvip/srs,lzpfmh/simple-rtmp-server,wenqinruan/srs,danielfree/srs,winlinvip/srs,ossrs/srs,avplus/srs,CallMeNP/srs,danielfree/srs,myself659/simple-rtmp-server,JinruiWang/srs,newlightdd/srs,KevinHM/simple-rtmp-server,tempbottle/simple-rtmp-server,icevl/srs,nestle1998/srs,Vincent0209/simple-rtmp-server,oceanho/simple-rtmp-server,JinruiWang/srs,zhiliaoniu/simple-rtmp-server,WilliamRen/srs,Robinson10240/simple-rtmp-server,Vincent0209/simple-rtmp-server,rudeb0t/simple-rtmp-server,lzpfmh/simple-rtmp-server,dymx101/srs,myself659/simple-rtmp-server,wenqinruan/srs,ossrs/srs,oceanho/simple-rtmp-server,lewdon/srs,drunknbass/srs,WilliamRen/srs,flashbuckets/srs,flashbuckets/srs,dymx101/srs,icevl/srs,dymx101/srs,CallMeNP/srs,oceanho/simple-rtmp-server,flashbuckets/srs,Robinson10240/simple-rtmp-server,JinruiWang/srs,danielfree/srs,flashbuckets/srs,tempbottle/simple-rtmp-server,tribbiani/srs,Robinson10240/simple-rtmp-server,newlightdd/srs,WilliamRen/srs,lewdon/srs,lzpfmh/simple-rtmp-server,tempbottle/simple-rtmp-server,chengjunjian/simple-rtmp-server,keyanmca/srs-May-2014,Vincent0209/simple-rtmp-server,rudeb0t/simple-rtmp-server,zhiliaoniu/simple-rtmp-server,Vincent0209/simple-rtmp-server,tempbottle/simple-rtmp-server,newlightdd/srs,tribbiani/srs,zhiliaoniu/simple-rtmp-server,drunknbass/srs,tribbiani/srs,skyfe79/srs,Vincent0209/simple-rtmp-server,KevinHM/simple-rtmp-server,antonioparisi/srs,CallMeNP/srs,flashbuckets/srs,keyanmca/srs-May-2014,CallMeNP/srs,dymx101/simple-rtmp-server,tribbiani/srs,WilliamRen/srs,nestle1998/srs,skyfe79/srs,WilliamRen/srs,lewdon/srs,myself659/simple-rtmp-server
|
ff5a3fe3d12e8fd5e356e7726ce2048345db6203
|
src/ui/map/Waypoint2DIcon.cc
|
src/ui/map/Waypoint2DIcon.cc
|
#include "Waypoint2DIcon.h"
#include <QPainter>
#include "opmapcontrol.h"
#include "QGC.h"
Waypoint2DIcon::Waypoint2DIcon(mapcontrol::MapGraphicItem* map, mapcontrol::OPMapWidget* parent, qreal latitude, qreal longitude, qreal altitude, int listindex, QString name, QString description, int radius)
: mapcontrol::WayPointItem(internals::PointLatLng(latitude, longitude), altitude, description, map),
parent(parent),
waypoint(NULL),
radius(radius),
showAcceptanceRadius(true),
showOrbit(false),
color(Qt::red)
{
Q_UNUSED(name);
SetHeading(0);
SetNumber(listindex);
this->setFlag(QGraphicsItem::ItemIgnoresTransformations,true);
picture = QPixmap(radius+1, radius+1);
autoreachedEnabled = false; // In contrast to the use in OpenPilot, we don't
// want to let the map interfere with the actual mission logic
// wether a WP is reached depends solely on the UAV's state machine
drawIcon();
}
Waypoint2DIcon::Waypoint2DIcon(mapcontrol::MapGraphicItem* map, mapcontrol::OPMapWidget* parent, Waypoint* wp, const QColor& color, int listindex, int radius)
: mapcontrol::WayPointItem(internals::PointLatLng(wp->getLatitude(), wp->getLongitude()), wp->getAltitude(), wp->getDescription(), map),
parent(parent),
waypoint(wp),
radius(radius),
showAcceptanceRadius(true),
showOrbit(false),
color(color)
{
SetHeading(wp->getYaw());
SetNumber(listindex);
this->setFlag(QGraphicsItem::ItemIgnoresTransformations,true);
picture = QPixmap(radius+1, radius+1);
autoreachedEnabled = false; // In contrast to the use in OpenPilot, we don't
// want to let the map interfere with the actual mission logic
// wether a WP is reached depends solely on the UAV's state machine
updateWaypoint();
}
Waypoint2DIcon::~Waypoint2DIcon()
{
}
void Waypoint2DIcon::SetHeading(float heading)
{
mapcontrol::WayPointItem::SetHeading(heading);
drawIcon();
}
void Waypoint2DIcon::updateWaypoint()
{
if (waypoint) {
// Store old size
static QRectF oldSize;
SetHeading(waypoint->getYaw());
SetCoord(internals::PointLatLng(waypoint->getLatitude(), waypoint->getLongitude()));
// qDebug() << "UPDATING WP:" << waypoint->getId() << "LAT:" << waypoint->getLatitude() << "LON:" << waypoint->getLongitude();
SetDescription(waypoint->getDescription());
SetAltitude(waypoint->getAltitude());
// FIXME Add SetNumber (currently needs a separate call)
drawIcon();
QRectF newSize = boundingRect();
// qDebug() << "WIDTH" << newSize.width() << "<" << oldSize.width();
// If new size is smaller than old size, update surrounding
if ((newSize.width() <= oldSize.width()) || (newSize.height() <= oldSize.height()))
{
// If the symbol size was reduced, enforce an update of the environment
// update(oldSize);
int oldWidth = oldSize.width() + 20;
int oldHeight = oldSize.height() + 20;
map->update(this->x()-10, this->y()-10, oldWidth, oldHeight);
//// qDebug() << "UPDATING DUE TO SMALLER SIZE";
//// qDebug() << "X:" << this->x()-1 << "Y:" << this->y()-1 << "WIDTH:" << oldWidth << "HEIGHT:" << oldHeight;
}
else
{
// Symbol size stayed constant or increased, use new size for update
this->update();
}
oldSize = boundingRect();
}
}
QRectF Waypoint2DIcon::boundingRect() const
{
int loiter = 0;
int acceptance = 0;
internals::PointLatLng coord = (internals::PointLatLng)Coord();
if (waypoint && showAcceptanceRadius && (waypoint->getAction() == (int)MAV_CMD_NAV_WAYPOINT))
{
acceptance = map->metersToPixels(waypoint->getAcceptanceRadius(), coord);
}
if (waypoint && ((waypoint->getAction() == (int)MAV_CMD_NAV_LOITER_UNLIM) || (waypoint->getAction() == (int)MAV_CMD_NAV_LOITER_TIME) || (waypoint->getAction() == (int)MAV_CMD_NAV_LOITER_TURNS)))
{
loiter = map->metersToPixels(waypoint->getLoiterOrbit(), coord);
}
int width = qMax(picture.width()/2, qMax(loiter, acceptance));
int height = qMax(picture.height()/2, qMax(loiter, acceptance));
return QRectF(-width,-height,2*width,2*height);
}
void Waypoint2DIcon::drawIcon()
{
picture.fill(Qt::transparent);
QPainter painter(&picture);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setRenderHint(QPainter::HighQualityAntialiasing, true);
QFont font("Bitstream Vera Sans");
int fontSize = picture.height()*0.8f;
font.setPixelSize(fontSize);
QFontMetrics metrics = QFontMetrics(font);
int border = qMax(4, metrics.leading());
painter.setFont(font);
painter.setRenderHint(QPainter::TextAntialiasing);
QPen pen1(Qt::black);
pen1.setWidth(4);
QPen pen2(color);
pen2.setWidth(2);
painter.setBrush(Qt::NoBrush);
int penWidth = pen1.width();
// DRAW WAYPOINT
QPointF p(picture.width()/2, picture.height()/2);
QPolygonF poly(4);
// Top point
poly.replace(0, QPointF(p.x(), p.y()-picture.height()/2.0f+penWidth/2));
// Right point
poly.replace(1, QPointF(p.x()+picture.width()/2.0f-penWidth/2, p.y()));
// Bottom point
poly.replace(2, QPointF(p.x(), p.y() + picture.height()/2.0f-penWidth/2));
poly.replace(3, QPointF(p.x() - picture.width()/2.0f+penWidth/2, p.y()));
int waypointSize = qMin(picture.width(), picture.height());
float rad = (waypointSize/2.0f) * 0.7f * (1/sqrt(2.0f));
// If this is not a waypoint (only the default representation)
// or it is a waypoint, but not one where direction has no meaning
// then draw the heading indicator
if (!waypoint || (waypoint && (
(waypoint->getAction() != (int)MAV_CMD_NAV_TAKEOFF) &&
(waypoint->getAction() != (int)MAV_CMD_NAV_LAND) &&
(waypoint->getAction() != (int)MAV_CMD_NAV_LOITER_UNLIM) &&
(waypoint->getAction() != (int)MAV_CMD_NAV_LOITER_TIME) &&
(waypoint->getAction() != (int)MAV_CMD_NAV_LOITER_TURNS) &&
(waypoint->getAction() != (int)MAV_CMD_NAV_RETURN_TO_LAUNCH)
)))
{
painter.setPen(pen1);
painter.drawLine(p.x(), p.y(), p.x()+sin(Heading()/180.0f*M_PI) * rad, p.y()-cos(Heading()/180.0f*M_PI) * rad);
painter.setPen(pen2);
painter.drawLine(p.x(), p.y(), p.x()+sin(Heading()/180.0f*M_PI) * rad, p.y()-cos(Heading()/180.0f*M_PI) * rad);
}
if ((waypoint != NULL) && (waypoint->getAction() == (int)MAV_CMD_NAV_TAKEOFF))
{
// Takeoff waypoint
int width = picture.width()-penWidth;
int height = picture.height()-penWidth;
painter.setPen(pen1);
painter.drawRect(penWidth/2, penWidth/2, width, height);
painter.setPen(pen2);
painter.drawRect(penWidth/2, penWidth/2, width, height);
painter.setPen(pen1);
painter.drawRect(width*0.3, height*0.3f, width*0.6f, height*0.6f);
painter.setPen(pen2);
painter.drawRect(width*0.3, height*0.3f, width*0.6f, height*0.6f);
}
else if ((waypoint != NULL) && (waypoint->getAction() == (int)MAV_CMD_NAV_LAND))
{
// Landing waypoint
int width = (picture.width())/2-penWidth;
int height = (picture.height())/2-penWidth;
painter.setPen(pen1);
painter.drawEllipse(p, width, height);
painter.drawLine(p.x()-width/2, p.y()-height/2, 2*width, 2*height);
painter.setPen(pen2);
painter.drawEllipse(p, width, height);
painter.drawLine(p.x()-width/2, p.y()-height/2, 2*width, 2*height);
}
else if ((waypoint != NULL) && ((waypoint->getAction() == (int)MAV_CMD_NAV_LOITER_UNLIM) || (waypoint->getAction() == (int)MAV_CMD_NAV_LOITER_TIME) || (waypoint->getAction() == (int)MAV_CMD_NAV_LOITER_TURNS)))
{
// Loiter waypoint
int width = (picture.width()-penWidth)/2;
int height = (picture.height()-penWidth)/2;
painter.setPen(pen1);
painter.drawEllipse(p, width, height);
painter.drawPoint(p);
painter.setPen(pen2);
painter.drawEllipse(p, width, height);
painter.drawPoint(p);
}
else if ((waypoint != NULL) && (waypoint->getAction() == (int)MAV_CMD_NAV_RETURN_TO_LAUNCH))
{
// Return to launch waypoint
int width = picture.width()-penWidth;
int height = picture.height()-penWidth;
painter.setPen(pen1);
painter.drawRect(penWidth/2, penWidth/2, width, height);
painter.setPen(pen2);
painter.drawRect(penWidth/2, penWidth/2, width, height);
QString text("R");
painter.setPen(pen1);
QRect rect = metrics.boundingRect(0, 0, width - 2*border, height, Qt::AlignLeft | Qt::TextWordWrap, text);
painter.drawText(width/4, height/6, rect.width(), rect.height(),
Qt::AlignCenter | Qt::TextWordWrap, text);
painter.setPen(pen2);
font.setPixelSize(fontSize*0.85f);
painter.setFont(font);
painter.drawText(width/4, height/6, rect.width(), rect.height(), Qt::AlignCenter | Qt::TextWordWrap, text);
}
else
{
// Navigation waypoint
painter.setPen(pen1);
painter.drawPolygon(poly);
painter.setPen(pen2);
painter.drawPolygon(poly);
}
}
void Waypoint2DIcon::SetShowNumber(const bool &value)
{
shownumber=value;
if((numberI==0) && value)
{
numberI=new QGraphicsSimpleTextItem(this);
numberIBG=new QGraphicsRectItem(this);
numberIBG->setBrush(Qt::black);
numberIBG->setOpacity(0.5);
numberI->setZValue(3);
numberI->setPen(QPen(QGC::colorCyan));
numberI->setPos(5,-picture.height());
numberIBG->setPos(5,-picture.height());
numberI->setText(QString::number(number));
numberIBG->setRect(numberI->boundingRect().adjusted(-2,0,1,0));
}
else if (!value && numberI)
{
delete numberI;
delete numberIBG;
}
this->update();
}
void Waypoint2DIcon::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
QPen pen = painter->pen();
pen.setWidth(2);
painter->drawPixmap(-picture.width()/2,-picture.height()/2,picture);
if (this->isSelected())
{
pen.setColor(Qt::yellow);
painter->drawRect(QRectF(-picture.width()/2,-picture.height()/2,picture.width()-1,picture.height()-1));
}
QPen penBlack(Qt::black);
penBlack.setWidth(4);
pen.setColor(color);
if ((waypoint) && (waypoint->getAction() == (int)MAV_CMD_NAV_WAYPOINT) && showAcceptanceRadius)
{
QPen redPen = QPen(pen);
redPen.setColor(Qt::yellow);
redPen.setWidth(1);
painter->setPen(redPen);
const int acceptance = map->metersToPixels(waypoint->getAcceptanceRadius(), Coord());
painter->setPen(penBlack);
painter->drawEllipse(QPointF(0, 0), acceptance, acceptance);
painter->setPen(redPen);
painter->drawEllipse(QPointF(0, 0), acceptance, acceptance);
}
if ((waypoint) && ((waypoint->getAction() == (int)MAV_CMD_NAV_LOITER_UNLIM) || (waypoint->getAction() == (int)MAV_CMD_NAV_LOITER_TIME) || (waypoint->getAction() == (int)MAV_CMD_NAV_LOITER_TURNS)))
{
QPen penDash(color);
penDash.setWidth(1);
//penDash.setStyle(Qt::DotLine);
const int loiter = map->metersToPixels(waypoint->getLoiterOrbit(), Coord());
if (loiter > picture.width()/2)
{
painter->setPen(penBlack);
painter->drawEllipse(QPointF(0, 0), loiter, loiter);
painter->setPen(penDash);
painter->drawEllipse(QPointF(0, 0), loiter, loiter);
}
}
}
|
#include "Waypoint2DIcon.h"
#include <QPainter>
#include "opmapcontrol.h"
#include "QGC.h"
Waypoint2DIcon::Waypoint2DIcon(mapcontrol::MapGraphicItem* map, mapcontrol::OPMapWidget* parent, qreal latitude, qreal longitude, qreal altitude, int listindex, QString name, QString description, int radius)
: mapcontrol::WayPointItem(internals::PointLatLng(latitude, longitude), altitude, description, map),
parent(parent),
waypoint(NULL),
radius(radius),
showAcceptanceRadius(true),
showOrbit(false),
color(Qt::red)
{
Q_UNUSED(name);
SetHeading(0);
SetNumber(listindex);
this->setFlag(QGraphicsItem::ItemIgnoresTransformations,true);
picture = QPixmap(radius+1, radius+1);
autoreachedEnabled = false; // In contrast to the use in OpenPilot, we don't
// want to let the map interfere with the actual mission logic
// wether a WP is reached depends solely on the UAV's state machine
drawIcon();
}
Waypoint2DIcon::Waypoint2DIcon(mapcontrol::MapGraphicItem* map, mapcontrol::OPMapWidget* parent, Waypoint* wp, const QColor& color, int listindex, int radius)
: mapcontrol::WayPointItem(internals::PointLatLng(wp->getLatitude(), wp->getLongitude()), wp->getAltitude(), wp->getDescription(), map),
parent(parent),
waypoint(wp),
radius(radius),
showAcceptanceRadius(true),
showOrbit(false),
color(color)
{
SetHeading(wp->getYaw());
SetNumber(listindex);
this->setFlag(QGraphicsItem::ItemIgnoresTransformations,true);
picture = QPixmap(radius+1, radius+1);
autoreachedEnabled = false; // In contrast to the use in OpenPilot, we don't
// want to let the map interfere with the actual mission logic
// wether a WP is reached depends solely on the UAV's state machine
updateWaypoint();
}
Waypoint2DIcon::~Waypoint2DIcon()
{
}
void Waypoint2DIcon::SetHeading(float heading)
{
mapcontrol::WayPointItem::SetHeading(heading);
drawIcon();
}
void Waypoint2DIcon::updateWaypoint()
{
if (waypoint) {
// Store old size
static QRectF oldSize;
SetHeading(waypoint->getYaw());
SetCoord(internals::PointLatLng(waypoint->getLatitude(), waypoint->getLongitude()));
// qDebug() << "UPDATING WP:" << waypoint->getId() << "LAT:" << waypoint->getLatitude() << "LON:" << waypoint->getLongitude();
SetDescription(waypoint->getDescription());
SetAltitude(waypoint->getAltitude());
// FIXME Add SetNumber (currently needs a separate call)
drawIcon();
QRectF newSize = boundingRect();
// qDebug() << "WIDTH" << newSize.width() << "<" << oldSize.width();
// If new size is smaller than old size, update surrounding
if ((newSize.width() <= oldSize.width()) || (newSize.height() <= oldSize.height()))
{
// If the symbol size was reduced, enforce an update of the environment
// update(oldSize);
int oldWidth = oldSize.width() + 20;
int oldHeight = oldSize.height() + 20;
map->update(this->x()-10, this->y()-10, oldWidth, oldHeight);
//// qDebug() << "UPDATING DUE TO SMALLER SIZE";
//// qDebug() << "X:" << this->x()-1 << "Y:" << this->y()-1 << "WIDTH:" << oldWidth << "HEIGHT:" << oldHeight;
}
else
{
// Symbol size stayed constant or increased, use new size for update
this->update();
}
oldSize = boundingRect();
}
}
QRectF Waypoint2DIcon::boundingRect() const
{
int loiter = 0;
int acceptance = 0;
internals::PointLatLng coord = (internals::PointLatLng)Coord();
if (waypoint && showAcceptanceRadius && (waypoint->getAction() == (int)MAV_CMD_NAV_WAYPOINT))
{
acceptance = map->metersToPixels(waypoint->getAcceptanceRadius(), coord);
}
if (waypoint && ((waypoint->getAction() == (int)MAV_CMD_NAV_LOITER_UNLIM) || (waypoint->getAction() == (int)MAV_CMD_NAV_LOITER_TIME) || (waypoint->getAction() == (int)MAV_CMD_NAV_LOITER_TURNS)))
{
loiter = map->metersToPixels(waypoint->getLoiterOrbit(), coord);
}
int width = qMax(picture.width()/2, qMax(loiter, acceptance));
int height = qMax(picture.height()/2, qMax(loiter, acceptance));
return QRectF(-width,-height,2*width,2*height);
}
void Waypoint2DIcon::drawIcon()
{
picture.fill(Qt::transparent);
QPainter painter(&picture);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setRenderHint(QPainter::HighQualityAntialiasing, true);
QFont font("Bitstream Vera Sans");
int fontSize = picture.height()*0.8f;
font.setPixelSize(fontSize);
QFontMetrics metrics = QFontMetrics(font);
int border = qMax(4, metrics.leading());
painter.setFont(font);
painter.setRenderHint(QPainter::TextAntialiasing);
QPen pen1(Qt::black);
pen1.setWidth(4);
QPen pen2(color);
pen2.setWidth(2);
painter.setBrush(Qt::NoBrush);
int penWidth = pen1.width();
// DRAW WAYPOINT
QPointF p(picture.width()/2, picture.height()/2);
QPolygonF poly(4);
// Top point
poly.replace(0, QPointF(p.x(), p.y()-picture.height()/2.0f+penWidth/2));
// Right point
poly.replace(1, QPointF(p.x()+picture.width()/2.0f-penWidth/2, p.y()));
// Bottom point
poly.replace(2, QPointF(p.x(), p.y() + picture.height()/2.0f-penWidth/2));
poly.replace(3, QPointF(p.x() - picture.width()/2.0f+penWidth/2, p.y()));
int waypointSize = qMin(picture.width(), picture.height());
float rad = (waypointSize/2.0f) * 0.7f * (1/sqrt(2.0f));
// If this is not a waypoint (only the default representation)
// or it is a waypoint, but not one where direction has no meaning
// then draw the heading indicator
if (!waypoint || (waypoint && (
(waypoint->getAction() != (int)MAV_CMD_NAV_TAKEOFF) &&
(waypoint->getAction() != (int)MAV_CMD_NAV_LAND) &&
(waypoint->getAction() != (int)MAV_CMD_NAV_LOITER_UNLIM) &&
(waypoint->getAction() != (int)MAV_CMD_NAV_LOITER_TIME) &&
(waypoint->getAction() != (int)MAV_CMD_NAV_LOITER_TURNS) &&
(waypoint->getAction() != (int)MAV_CMD_NAV_RETURN_TO_LAUNCH)
)))
{
painter.setPen(pen1);
painter.drawLine(p.x(), p.y(), p.x()+sin(Heading()/180.0f*M_PI) * rad, p.y()-cos(Heading()/180.0f*M_PI) * rad);
painter.setPen(pen2);
painter.drawLine(p.x(), p.y(), p.x()+sin(Heading()/180.0f*M_PI) * rad, p.y()-cos(Heading()/180.0f*M_PI) * rad);
}
if ((waypoint != NULL) && (waypoint->getAction() == (int)MAV_CMD_NAV_TAKEOFF))
{
// Takeoff waypoint
int width = picture.width()-penWidth;
int height = picture.height()-penWidth;
painter.setPen(pen1);
painter.drawRect(penWidth/2, penWidth/2, width, height);
painter.setPen(pen2);
painter.drawRect(penWidth/2, penWidth/2, width, height);
painter.setPen(pen1);
painter.drawRect(width*0.3, height*0.3f, width*0.6f, height*0.6f);
painter.setPen(pen2);
painter.drawRect(width*0.3, height*0.3f, width*0.6f, height*0.6f);
}
else if ((waypoint != NULL) && (waypoint->getAction() == (int)MAV_CMD_NAV_LAND))
{
// Landing waypoint
int width = (picture.width())/2-penWidth;
int height = (picture.height())/2-penWidth;
painter.setPen(pen1);
painter.drawEllipse(p, width, height);
painter.drawLine(p.x()-width/2, p.y()-height/2, 2*width, 2*height);
painter.setPen(pen2);
painter.drawEllipse(p, width, height);
painter.drawLine(p.x()-width/2, p.y()-height/2, 2*width, 2*height);
}
else if ((waypoint != NULL) && ((waypoint->getAction() == (int)MAV_CMD_NAV_LOITER_UNLIM) || (waypoint->getAction() == (int)MAV_CMD_NAV_LOITER_TIME) || (waypoint->getAction() == (int)MAV_CMD_NAV_LOITER_TURNS)))
{
// Loiter waypoint
int width = (picture.width()-penWidth)/2;
int height = (picture.height()-penWidth)/2;
painter.setPen(pen1);
painter.drawEllipse(p, width, height);
painter.drawPoint(p);
painter.setPen(pen2);
painter.drawEllipse(p, width, height);
painter.drawPoint(p);
}
else if ((waypoint != NULL) && (waypoint->getAction() == (int)MAV_CMD_NAV_RETURN_TO_LAUNCH))
{
// Return to launch waypoint
int width = picture.width()-penWidth;
int height = picture.height()-penWidth;
painter.setPen(pen1);
painter.drawRect(penWidth/2, penWidth/2, width, height);
painter.setPen(pen2);
painter.drawRect(penWidth/2, penWidth/2, width, height);
QString text("R");
painter.setPen(pen1);
QRect rect = metrics.boundingRect(0, 0, width - 2*border, height, Qt::AlignLeft | Qt::TextWordWrap, text);
painter.drawText(width/4, height/6, rect.width(), rect.height(),
Qt::AlignCenter | Qt::TextWordWrap, text);
painter.setPen(pen2);
font.setPixelSize(fontSize*0.85f);
painter.setFont(font);
painter.drawText(width/4, height/6, rect.width(), rect.height(), Qt::AlignCenter | Qt::TextWordWrap, text);
}
else
{
// Navigation waypoint
painter.setPen(pen1);
painter.drawPolygon(poly);
painter.setPen(pen2);
painter.drawPolygon(poly);
}
}
void Waypoint2DIcon::SetShowNumber(const bool &value)
{
shownumber=value;
if((numberI==0) && value)
{
numberI=new QGraphicsSimpleTextItem(this);
numberIBG=new QGraphicsRectItem(this);
numberIBG->setBrush(Qt::black);
numberIBG->setOpacity(0.5);
numberI->setZValue(3);
numberI->setPen(QPen(QGC::colorCyan));
numberI->setPos(5,-picture.height());
numberIBG->setPos(5,-picture.height());
numberI->setText(QString::number(number));
numberIBG->setRect(numberI->boundingRect().adjusted(-2,0,1,0));
}
else if (!value && numberI)
{
delete numberI;
delete numberIBG;
}
this->update();
}
void Waypoint2DIcon::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
QPen pen = painter->pen();
pen.setWidth(2);
painter->drawPixmap(-picture.width()/2,-picture.height()/2,picture);
if (this->isSelected())
{
pen.setColor(Qt::yellow);
painter->drawRect(QRectF(-picture.width()/2,-picture.height()/2,picture.width()-1,picture.height()-1));
}
QPen penBlack(Qt::black);
penBlack.setWidth(4);
pen.setColor(color);
if ((waypoint) && (waypoint->getAction() == (int)MAV_CMD_NAV_WAYPOINT) && showAcceptanceRadius)
{
QPen redPen = QPen(pen);
redPen.setColor(Qt::yellow);
redPen.setWidth(1);
painter->setPen(redPen);
const int acceptance = map->metersToPixels(waypoint->getAcceptanceRadius(), Coord());
if (acceptance > 0) {
painter->setPen(penBlack);
painter->drawEllipse(QPointF(0, 0), acceptance, acceptance);
painter->setPen(redPen);
painter->drawEllipse(QPointF(0, 0), acceptance, acceptance);
}
}
if ((waypoint) && ((waypoint->getAction() == (int)MAV_CMD_NAV_LOITER_UNLIM) || (waypoint->getAction() == (int)MAV_CMD_NAV_LOITER_TIME) || (waypoint->getAction() == (int)MAV_CMD_NAV_LOITER_TURNS)))
{
QPen penDash(color);
penDash.setWidth(1);
//penDash.setStyle(Qt::DotLine);
const int loiter = map->metersToPixels(waypoint->getLoiterOrbit(), Coord());
if (loiter > picture.width()/2)
{
painter->setPen(penBlack);
painter->drawEllipse(QPointF(0, 0), loiter, loiter);
painter->setPen(penDash);
painter->drawEllipse(QPointF(0, 0), loiter, loiter);
}
}
}
|
Fix crash when acceptance in pixels == 0
|
Fix crash when acceptance in pixels == 0
|
C++
|
agpl-3.0
|
nado1688/qgroundcontrol,Hunter522/qgroundcontrol,cfelipesouza/qgroundcontrol,jy723/qgroundcontrol,CornerOfSkyline/qgroundcontrol,cfelipesouza/qgroundcontrol,catch-twenty-two/qgroundcontrol,LIKAIMO/qgroundcontrol,UAVenture/qgroundcontrol,Hunter522/qgroundcontrol,RedoXyde/PX4_qGCS,BMP-TECH/qgroundcontrol,caoxiongkun/qgroundcontrol,scott-eddy/qgroundcontrol,BMP-TECH/qgroundcontrol,josephlewis42/UDenverQGC2,lis-epfl/qgroundcontrol,cfelipesouza/qgroundcontrol,UAVenture/qgroundcontrol,TheIronBorn/qgroundcontrol,mihadyuk/qgroundcontrol,mihadyuk/qgroundcontrol,jy723/qgroundcontrol,fizzaly/qgroundcontrol,iidioter/qgroundcontrol,fizzaly/qgroundcontrol,hejunbok/qgroundcontrol,greenoaktree/qgroundcontrol,caoxiongkun/qgroundcontrol,lis-epfl/qgroundcontrol,fizzaly/qgroundcontrol,LIKAIMO/qgroundcontrol,cfelipesouza/qgroundcontrol,remspoor/qgroundcontrol,hejunbok/qgroundcontrol,dagoodma/qgroundcontrol,scott-eddy/qgroundcontrol,catch-twenty-two/qgroundcontrol,greenoaktree/qgroundcontrol,lis-epfl/qgroundcontrol,hejunbok/qgroundcontrol,iidioter/qgroundcontrol,CornerOfSkyline/qgroundcontrol,kd0aij/qgroundcontrol,CornerOfSkyline/qgroundcontrol,LIKAIMO/qgroundcontrol,remspoor/qgroundcontrol,kd0aij/qgroundcontrol,Hunter522/qgroundcontrol,josephlewis42/UDenverQGC2,caoxiongkun/qgroundcontrol,UAVenture/qgroundcontrol,dagoodma/qgroundcontrol,devbharat/qgroundcontrol,scott-eddy/qgroundcontrol,CornerOfSkyline/qgroundcontrol,greenoaktree/qgroundcontrol,ethz-asl/qgc_asl,catch-twenty-two/qgroundcontrol,nado1688/qgroundcontrol,mihadyuk/qgroundcontrol,mihadyuk/qgroundcontrol,dagoodma/qgroundcontrol,BMP-TECH/qgroundcontrol,remspoor/qgroundcontrol,remspoor/qgroundcontrol,Hunter522/qgroundcontrol,caoxiongkun/qgroundcontrol,CornerOfSkyline/qgroundcontrol,UAVenture/qgroundcontrol,ethz-asl/qgc_asl,remspoor/qgroundcontrol,RedoXyde/PX4_qGCS,UAVenture/qgroundcontrol,TheIronBorn/qgroundcontrol,catch-twenty-two/qgroundcontrol,iidioter/qgroundcontrol,kd0aij/qgroundcontrol,lis-epfl/qgroundcontrol,devbharat/qgroundcontrol,dagoodma/qgroundcontrol,LIKAIMO/qgroundcontrol,fizzaly/qgroundcontrol,TheIronBorn/qgroundcontrol,josephlewis42/UDenverQGC2,catch-twenty-two/qgroundcontrol,remspoor/qgroundcontrol,dagoodma/qgroundcontrol,catch-twenty-two/qgroundcontrol,RedoXyde/PX4_qGCS,iidioter/qgroundcontrol,devbharat/qgroundcontrol,jy723/qgroundcontrol,nado1688/qgroundcontrol,TheIronBorn/qgroundcontrol,greenoaktree/qgroundcontrol,iidioter/qgroundcontrol,scott-eddy/qgroundcontrol,kd0aij/qgroundcontrol,lis-epfl/qgroundcontrol,LIKAIMO/qgroundcontrol,CornerOfSkyline/qgroundcontrol,TheIronBorn/qgroundcontrol,devbharat/qgroundcontrol,hejunbok/qgroundcontrol,fizzaly/qgroundcontrol,kd0aij/qgroundcontrol,devbharat/qgroundcontrol,kd0aij/qgroundcontrol,caoxiongkun/qgroundcontrol,jy723/qgroundcontrol,ethz-asl/qgc_asl,greenoaktree/qgroundcontrol,mihadyuk/qgroundcontrol,LIKAIMO/qgroundcontrol,BMP-TECH/qgroundcontrol,RedoXyde/PX4_qGCS,UAVenture/qgroundcontrol,ethz-asl/qgc_asl,fizzaly/qgroundcontrol,RedoXyde/PX4_qGCS,ethz-asl/qgc_asl,scott-eddy/qgroundcontrol,BMP-TECH/qgroundcontrol,hejunbok/qgroundcontrol,nado1688/qgroundcontrol,BMP-TECH/qgroundcontrol,TheIronBorn/qgroundcontrol,iidioter/qgroundcontrol,greenoaktree/qgroundcontrol,Hunter522/qgroundcontrol,scott-eddy/qgroundcontrol,hejunbok/qgroundcontrol,josephlewis42/UDenverQGC2,nado1688/qgroundcontrol,mihadyuk/qgroundcontrol,dagoodma/qgroundcontrol,caoxiongkun/qgroundcontrol,jy723/qgroundcontrol,cfelipesouza/qgroundcontrol,cfelipesouza/qgroundcontrol,nado1688/qgroundcontrol,jy723/qgroundcontrol,devbharat/qgroundcontrol,RedoXyde/PX4_qGCS,Hunter522/qgroundcontrol
|
31db083d682adedfaf3a968650c3f4a31fc6fe00
|
C++/minimum-window-substring.cpp
|
C++/minimum-window-substring.cpp
|
// Time: O(n)
// Space: O(1)
class Solution {
public:
/**
* @param source: A string
* @param target: A string
* @return: A string denote the minimum window
* Return "" if there is no such a string
*/
string minWindow(string &source, string &target) {
if (source.empty() || source.length() < target.length()) {
return "";
}
const int ASCII_MAX = 256;
vector<int> expCnt(ASCII_MAX, 0);
vector<int> curCnt(ASCII_MAX, 0);
int cnt = 0;
int start = 0;
int min_width = numeric_limits<int>::max();
int min_start = 0;
for (const auto& c : target) {
++expCnt[c];
}
for (int i = 0; i < source.length(); ++i) {
if (expCnt[source[i]] > 0) {
++curCnt[source[i]];
if (curCnt[source[i]] <= expCnt[source[i]]) { // Counting expected elements.
++cnt;
}
}
if (cnt == target.size()) { // If window meets the requirement.
while (expCnt[source[start]] == 0 || // Adjust left bound of window.
curCnt[source[start]] > expCnt[source[start]]) {
--curCnt[source[start]];
++start;
}
if (min_width > i - start + 1) { // Update minimum window.
min_width = i - start + 1;
min_start = start;
}
}
}
if (min_width == numeric_limits<int>::max()) {
return "";
}
return source.substr(min_start, min_width);
}
};
|
// Time: O(n)
// Space: O(1)
class Solution {
public:
/**
* @param source: A string
* @param target: A string
* @return: A string denote the minimum window
* Return "" if there is no such a string
*/
string minWindow(string &source, string &target) {
if (source.empty() || source.length() < target.length()) {
return "";
}
const int ASCII_MAX = 256;
vector<int> exp_cnt(ASCII_MAX, 0);
vector<int> cur_cnt(ASCII_MAX, 0);
int cnt = 0;
int start = 0;
int min_start = 0;
int min_width = numeric_limits<int>::max();
for (const auto& c : target) {
++exp_cnt[c];
}
for (int i = 0; i < source.length(); ++i) {
if (exp_cnt[source[i]] > 0) {
++cur_cnt[source[i]];
if (cur_cnt[source[i]] <= exp_cnt[source[i]]) { // Counting expected elements.
++cnt;
}
}
if (cnt == target.size()) { // If window meets the requirement.
while (exp_cnt[source[start]] == 0 || // Adjust left bound of window.
cur_cnt[source[start]] > exp_cnt[source[start]]) {
--cur_cnt[source[start]];
++start;
}
if (min_width > i - start + 1) { // Update minimum window.
min_width = i - start + 1;
min_start = start;
}
}
}
if (min_width == numeric_limits<int>::max()) {
return "";
}
return source.substr(min_start, min_width);
}
};
|
Update minimum-window-substring.cpp
|
Update minimum-window-substring.cpp
|
C++
|
mit
|
jaredkoontz/lintcode,jaredkoontz/lintcode,jaredkoontz/lintcode,kamyu104/LintCode,kamyu104/LintCode,kamyu104/LintCode
|
7ee7dc5c30681f899f0d7157e2d90ee965c1a8df
|
src/vogltrace/vogl_trace.cpp
|
src/vogltrace/vogl_trace.cpp
|
/**************************************************************************
*
* Copyright 2013-2014 RAD Game Tools and Valve Software
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**************************************************************************/
// File: vogl_trace.cpp
#include "vogl_trace.h"
#include "vogl_command_line_params.h"
#include "vogl_colorized_console.h"
#include <signal.h>
#include <linux/unistd.h>
#include <execinfo.h>
#include "btrace.h"
//----------------------------------------------------------------------------------------------------------------------
// Has exception hooks, dlopen() interception, super low-level global init. Be super careful what you
// do in some of these funcs (particularly vogl_shared_object_constructor_func() or any of the funcs
// it calls). I've found it's possible to do shit here that will work fine in primitive apps (like
// vogltest) but kill tracing in some real apps.
//----------------------------------------------------------------------------------------------------------------------
#define VOGL_LIBGL_SO_FILENAME "libGL.so.1"
//----------------------------------------------------------------------------------------------------------------------
// globals
//----------------------------------------------------------------------------------------------------------------------
void *g_vogl_actual_libgl_module_handle = NULL;
bool g_vogl_initializing_flag = false;
//----------------------------------------------------------------------------------------------------------------------
// dlopen interceptor
//----------------------------------------------------------------------------------------------------------------------
typedef void *(*dlopen_func_ptr_t)(const char *pFile, int mode);
VOGL_API_EXPORT void *dlopen(const char *pFile, int mode)
{
static dlopen_func_ptr_t s_pActual_dlopen = (dlopen_func_ptr_t)dlsym(RTLD_NEXT, "dlopen");
if (!s_pActual_dlopen)
return NULL;
printf("(vogltrace) dlopen: %s %i\n", pFile ? pFile : "(nullptr)", mode);
// Only redirect libGL.so when it comes from the app, NOT the driver or one of its associated helpers.
// This is definitely fragile as all fuck.
if (!g_vogl_initializing_flag)
{
if (pFile && (strstr(pFile, "libGL.so") != NULL))
{
const char *calling_module = btrace_get_calling_module();
bool should_redirect = !strstr(calling_module, "fglrx");
if (should_redirect)
{
pFile = btrace_get_current_module();
printf("(vogltrace) redirecting dlopen to %s\n", pFile);
}
else
{
printf("(vogltrace) NOT redirecting dlopen to %s, this dlopen() call appears to be coming from the driver\n", pFile);
}
printf("------------\n");
}
}
// Check if this module is already loaded.
void *is_loaded = (*s_pActual_dlopen)(pFile, RTLD_NOLOAD);
// Call the real dlopen().
void *dlopen_ret = (*s_pActual_dlopen)(pFile, mode);
// Only call btrace routines after vogl has been initialized. Otherwise we get
// called before memory routines have been set up, etc. and possibly crash.
if (g_vogl_has_been_initialized)
{
// If this file hadn't been loaded before, notify btrace.
if (!is_loaded && dlopen_ret)
btrace_dlopen_notify(pFile);
}
return dlopen_ret;
}
//----------------------------------------------------------------------------------------------------------------------
// Intercept _exit() so we get a final chance to flush our trace/log files
//----------------------------------------------------------------------------------------------------------------------
typedef void (*exit_func_ptr_t)(int status);
VOGL_NORETURN VOGL_API_EXPORT void _exit(int status)
{
static exit_func_ptr_t s_pActual_exit = (exit_func_ptr_t)dlsym(RTLD_NEXT, "_exit");
vogl_deinit();
if (s_pActual_exit)
(*s_pActual_exit)(status);
raise(SIGKILL);
// to shut up compiler about this func marked as noreturn
for (;;)
;
}
//----------------------------------------------------------------------------------------------------------------------
// Intercept _exit() so we get a final chance to flush our trace/log files
//----------------------------------------------------------------------------------------------------------------------
typedef void (*Exit_func_ptr_t)(int status);
VOGL_NORETURN VOGL_API_EXPORT void _Exit(int status)
{
static Exit_func_ptr_t s_pActual_Exit = (Exit_func_ptr_t)dlsym(RTLD_NEXT, "_Exit");
vogl_deinit();
if (s_pActual_Exit)
(*s_pActual_Exit)(status);
raise(SIGKILL);
// to shut up compiler about this func marked as noreturn
for (;;)
;
}
//----------------------------------------------------------------------------------------------------------------------
// vogl_glInternalTraceCommandRAD_dummy_func
//----------------------------------------------------------------------------------------------------------------------
static void vogl_glInternalTraceCommandRAD_dummy_func(GLuint cmd, GLuint size, const GLubyte *data)
{
// Nothing to do, this is an internal command used for serialization purposes that only we understand.
VOGL_NOTE_UNUSED(cmd);
VOGL_NOTE_UNUSED(size);
VOGL_NOTE_UNUSED(data);
}
//----------------------------------------------------------------------------------------------------------------------
// vogl_get_proc_address_helper
//----------------------------------------------------------------------------------------------------------------------
static vogl_void_func_ptr_t vogl_get_proc_address_helper(const char *pName)
{
if (!strcmp(pName, "glInternalTraceCommandRAD"))
return reinterpret_cast<vogl_void_func_ptr_t>(vogl_glInternalTraceCommandRAD_dummy_func);
vogl_void_func_ptr_t pFunc = reinterpret_cast<vogl_void_func_ptr_t>(dlsym(g_vogl_actual_libgl_module_handle ? g_vogl_actual_libgl_module_handle : RTLD_NEXT, pName));
if ((!pFunc) && (g_vogl_actual_gl_entrypoints.m_glXGetProcAddress))
pFunc = reinterpret_cast<vogl_void_func_ptr_t>(g_vogl_actual_gl_entrypoints.m_glXGetProcAddress(reinterpret_cast<const GLubyte *>(pName)));
return pFunc;
}
//----------------------------------------------------------------------------------------------------------------------
// global constructor init
// Note: Be VERY careful what you do in here! It's called very early during init (long before main, during c++ init)
//----------------------------------------------------------------------------------------------------------------------
VOGL_CONSTRUCTOR_FUNCTION(vogl_shared_object_constructor_func);
static void vogl_shared_object_constructor_func()
{
g_vogl_initializing_flag = true;
printf("(vogltrace) %s\n", VOGL_METHOD_NAME);
// Initialize vogl_core.
vogl_core_init();
// can't call vogl::colorized_console::init() because its global arrays will be cleared after this func returns
vogl::console::set_tool_prefix("(vogltrace) ");
vogl_message_printf("%s built %s %s, begin initialization in %s\n", btrace_get_current_module(), __DATE__, __TIME__, getenv("_"));
// We can't use the regular cmd line parser here because this func is called before global objects are constructed.
char *pEnv_cmd_line = getenv("VOGL_CMD_LINE");
bool pause = vogl::check_for_command_line_param("-vogl_pause") || ((pEnv_cmd_line) && (strstr(pEnv_cmd_line, "-vogl_pause") != NULL));
bool long_pause = vogl::check_for_command_line_param("-vogl_long_pause") || ((pEnv_cmd_line) && (strstr(pEnv_cmd_line, "-vogl_long_pause") != NULL));
if (pause || long_pause)
{
int count = 60000;
bool debugger_connected = false;
dynamic_string cmdline = vogl::get_command_line();
vogl_message_printf("cmdline: %s\n", cmdline.c_str());
vogl_message_printf("Pausing %d ms or until debugger is attached (pid %d).\n", count, getpid());
vogl_message_printf(" Or press any key to continue.\n");
while (count >= 0)
{
vogl_sleep(200);
count -= 200;
debugger_connected = vogl_is_debugger_present();
if (debugger_connected || vogl_kbhit())
break;
}
if (debugger_connected)
vogl_message_printf(" Debugger connected...\n");
}
g_vogl_actual_gl_entrypoints.m_glXGetProcAddress = reinterpret_cast<glXGetProcAddress_func_ptr_t>(dlsym(RTLD_NEXT, "glXGetProcAddress"));
if (!g_vogl_actual_gl_entrypoints.m_glXGetProcAddress)
{
vogl_warning_printf("%s: dlsym(RTLD_NEXT, \"glXGetProcAddress\") failed, trying to manually load %s\n", VOGL_FUNCTION_NAME, VOGL_LIBGL_SO_FILENAME);
g_vogl_actual_libgl_module_handle = dlopen(VOGL_LIBGL_SO_FILENAME, RTLD_LAZY);
if (!g_vogl_actual_libgl_module_handle)
{
vogl_error_printf("%s: Failed loading %s!\n", VOGL_FUNCTION_NAME, VOGL_LIBGL_SO_FILENAME);
exit(EXIT_FAILURE);
}
g_vogl_actual_gl_entrypoints.m_glXGetProcAddress = reinterpret_cast<glXGetProcAddress_func_ptr_t>(dlsym(g_vogl_actual_libgl_module_handle, "glXGetProcAddress"));
if (!g_vogl_actual_gl_entrypoints.m_glXGetProcAddress)
{
vogl_error_printf("%s: Failed getting address of glXGetProcAddress() from %s!\n", VOGL_FUNCTION_NAME, VOGL_LIBGL_SO_FILENAME);
exit(EXIT_FAILURE);
}
vogl_message_printf("%s: Manually loaded %s\n", VOGL_FUNCTION_NAME, VOGL_LIBGL_SO_FILENAME);
}
vogl_common_lib_early_init();
vogl_init_actual_gl_entrypoints(vogl_get_proc_address_helper);
vogl_early_init();
vogl_message_printf("end initialization\n");
g_vogl_initializing_flag = false;
}
__attribute__((destructor)) static void vogl_shared_object_destructor_func()
{
vogl_deinit();
}
|
/**************************************************************************
*
* Copyright 2013-2014 RAD Game Tools and Valve Software
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**************************************************************************/
// File: vogl_trace.cpp
#include "vogl_trace.h"
#include "vogl_command_line_params.h"
#include "vogl_colorized_console.h"
#include <signal.h>
#include <linux/unistd.h>
#include <execinfo.h>
#include "btrace.h"
//----------------------------------------------------------------------------------------------------------------------
// Has exception hooks, dlopen() interception, super low-level global init. Be super careful what you
// do in some of these funcs (particularly vogl_shared_object_constructor_func() or any of the funcs
// it calls). I've found it's possible to do shit here that will work fine in primitive apps (like
// vogltest) but kill tracing in some real apps.
//----------------------------------------------------------------------------------------------------------------------
#define VOGL_LIBGL_SO_FILENAME "libGL.so.1"
//----------------------------------------------------------------------------------------------------------------------
// globals
//----------------------------------------------------------------------------------------------------------------------
void *g_vogl_actual_libgl_module_handle = NULL;
bool g_vogl_initializing_flag = false;
//----------------------------------------------------------------------------------------------------------------------
// dlopen interceptor
//----------------------------------------------------------------------------------------------------------------------
typedef void *(*dlopen_func_ptr_t)(const char *pFile, int mode);
VOGL_API_EXPORT void *dlopen(const char *pFile, int mode)
{
static dlopen_func_ptr_t s_pActual_dlopen = (dlopen_func_ptr_t)dlsym(RTLD_NEXT, "dlopen");
if (!s_pActual_dlopen)
return NULL;
printf("(vogltrace) dlopen: %s %i\n", pFile ? pFile : "(nullptr)", mode);
// Only redirect libGL.so when it comes from the app, NOT the driver or one of its associated helpers.
// This is definitely fragile as all fuck.
if (!g_vogl_initializing_flag)
{
if (pFile && (strstr(pFile, "libGL.so") != NULL))
{
const char *calling_module = btrace_get_calling_module();
bool should_redirect = !strstr(calling_module, "fglrx");
if (should_redirect)
{
pFile = btrace_get_current_module();
printf("(vogltrace) redirecting dlopen to %s\n", pFile);
}
else
{
printf("(vogltrace) NOT redirecting dlopen to %s, this dlopen() call appears to be coming from the driver\n", pFile);
}
printf("------------\n");
}
}
// Check if this module is already loaded.
void *is_loaded = (*s_pActual_dlopen)(pFile, RTLD_NOLOAD);
// Call the real dlopen().
void *dlopen_ret = (*s_pActual_dlopen)(pFile, mode);
// Only call btrace routines after vogl has been initialized. Otherwise we get
// called before memory routines have been set up, etc. and possibly crash.
if (g_vogl_has_been_initialized)
{
// If this file hadn't been loaded before, notify btrace.
if (!is_loaded && dlopen_ret)
btrace_dlopen_notify(pFile);
}
return dlopen_ret;
}
//----------------------------------------------------------------------------------------------------------------------
// Intercept _exit() so we get a final chance to flush our trace/log files
//----------------------------------------------------------------------------------------------------------------------
typedef void (*exit_func_ptr_t)(int status);
VOGL_API_EXPORT VOGL_NORETURN void _exit(int status)
{
static exit_func_ptr_t s_pActual_exit = (exit_func_ptr_t)dlsym(RTLD_NEXT, "_exit");
vogl_deinit();
if (s_pActual_exit)
(*s_pActual_exit)(status);
raise(SIGKILL);
// to shut up compiler about this func marked as noreturn
for (;;)
;
}
//----------------------------------------------------------------------------------------------------------------------
// Intercept _exit() so we get a final chance to flush our trace/log files
//----------------------------------------------------------------------------------------------------------------------
typedef void (*Exit_func_ptr_t)(int status);
VOGL_API_EXPORT VOGL_NORETURN void _Exit(int status)
{
static Exit_func_ptr_t s_pActual_Exit = (Exit_func_ptr_t)dlsym(RTLD_NEXT, "_Exit");
vogl_deinit();
if (s_pActual_Exit)
(*s_pActual_Exit)(status);
raise(SIGKILL);
// to shut up compiler about this func marked as noreturn
for (;;)
;
}
//----------------------------------------------------------------------------------------------------------------------
// vogl_glInternalTraceCommandRAD_dummy_func
//----------------------------------------------------------------------------------------------------------------------
static void vogl_glInternalTraceCommandRAD_dummy_func(GLuint cmd, GLuint size, const GLubyte *data)
{
// Nothing to do, this is an internal command used for serialization purposes that only we understand.
VOGL_NOTE_UNUSED(cmd);
VOGL_NOTE_UNUSED(size);
VOGL_NOTE_UNUSED(data);
}
//----------------------------------------------------------------------------------------------------------------------
// vogl_get_proc_address_helper
//----------------------------------------------------------------------------------------------------------------------
static vogl_void_func_ptr_t vogl_get_proc_address_helper(const char *pName)
{
if (!strcmp(pName, "glInternalTraceCommandRAD"))
return reinterpret_cast<vogl_void_func_ptr_t>(vogl_glInternalTraceCommandRAD_dummy_func);
vogl_void_func_ptr_t pFunc = reinterpret_cast<vogl_void_func_ptr_t>(dlsym(g_vogl_actual_libgl_module_handle ? g_vogl_actual_libgl_module_handle : RTLD_NEXT, pName));
if ((!pFunc) && (g_vogl_actual_gl_entrypoints.m_glXGetProcAddress))
pFunc = reinterpret_cast<vogl_void_func_ptr_t>(g_vogl_actual_gl_entrypoints.m_glXGetProcAddress(reinterpret_cast<const GLubyte *>(pName)));
return pFunc;
}
//----------------------------------------------------------------------------------------------------------------------
// global constructor init
// Note: Be VERY careful what you do in here! It's called very early during init (long before main, during c++ init)
//----------------------------------------------------------------------------------------------------------------------
VOGL_CONSTRUCTOR_FUNCTION(vogl_shared_object_constructor_func);
static void vogl_shared_object_constructor_func()
{
g_vogl_initializing_flag = true;
printf("(vogltrace) %s\n", VOGL_METHOD_NAME);
// Initialize vogl_core.
vogl_core_init();
// can't call vogl::colorized_console::init() because its global arrays will be cleared after this func returns
vogl::console::set_tool_prefix("(vogltrace) ");
vogl_message_printf("%s built %s %s, begin initialization in %s\n", btrace_get_current_module(), __DATE__, __TIME__, getenv("_"));
// We can't use the regular cmd line parser here because this func is called before global objects are constructed.
char *pEnv_cmd_line = getenv("VOGL_CMD_LINE");
bool pause = vogl::check_for_command_line_param("-vogl_pause") || ((pEnv_cmd_line) && (strstr(pEnv_cmd_line, "-vogl_pause") != NULL));
bool long_pause = vogl::check_for_command_line_param("-vogl_long_pause") || ((pEnv_cmd_line) && (strstr(pEnv_cmd_line, "-vogl_long_pause") != NULL));
if (pause || long_pause)
{
int count = 60000;
bool debugger_connected = false;
dynamic_string cmdline = vogl::get_command_line();
vogl_message_printf("cmdline: %s\n", cmdline.c_str());
vogl_message_printf("Pausing %d ms or until debugger is attached (pid %d).\n", count, getpid());
vogl_message_printf(" Or press any key to continue.\n");
while (count >= 0)
{
vogl_sleep(200);
count -= 200;
debugger_connected = vogl_is_debugger_present();
if (debugger_connected || vogl_kbhit())
break;
}
if (debugger_connected)
vogl_message_printf(" Debugger connected...\n");
}
g_vogl_actual_gl_entrypoints.m_glXGetProcAddress = reinterpret_cast<glXGetProcAddress_func_ptr_t>(dlsym(RTLD_NEXT, "glXGetProcAddress"));
if (!g_vogl_actual_gl_entrypoints.m_glXGetProcAddress)
{
vogl_warning_printf("%s: dlsym(RTLD_NEXT, \"glXGetProcAddress\") failed, trying to manually load %s\n", VOGL_FUNCTION_NAME, VOGL_LIBGL_SO_FILENAME);
g_vogl_actual_libgl_module_handle = dlopen(VOGL_LIBGL_SO_FILENAME, RTLD_LAZY);
if (!g_vogl_actual_libgl_module_handle)
{
vogl_error_printf("%s: Failed loading %s!\n", VOGL_FUNCTION_NAME, VOGL_LIBGL_SO_FILENAME);
exit(EXIT_FAILURE);
}
g_vogl_actual_gl_entrypoints.m_glXGetProcAddress = reinterpret_cast<glXGetProcAddress_func_ptr_t>(dlsym(g_vogl_actual_libgl_module_handle, "glXGetProcAddress"));
if (!g_vogl_actual_gl_entrypoints.m_glXGetProcAddress)
{
vogl_error_printf("%s: Failed getting address of glXGetProcAddress() from %s!\n", VOGL_FUNCTION_NAME, VOGL_LIBGL_SO_FILENAME);
exit(EXIT_FAILURE);
}
vogl_message_printf("%s: Manually loaded %s\n", VOGL_FUNCTION_NAME, VOGL_LIBGL_SO_FILENAME);
}
vogl_common_lib_early_init();
vogl_init_actual_gl_entrypoints(vogl_get_proc_address_helper);
vogl_early_init();
vogl_message_printf("end initialization\n");
g_vogl_initializing_flag = false;
}
__attribute__((destructor)) static void vogl_shared_object_destructor_func()
{
vogl_deinit();
}
|
Fix gcc 4.8 build.
|
Fix gcc 4.8 build.
|
C++
|
mit
|
bclemetsonblizzard/vogl,bclemetsonblizzard/vogl,ValveSoftware/vogl,ValveSoftware/vogl,ValveSoftware/vogl,bclemetsonblizzard/vogl,bclemetsonblizzard/vogl,kingtaurus/vogl,bclemetsonblizzard/vogl,kingtaurus/vogl,kingtaurus/vogl,ValveSoftware/vogl,kingtaurus/vogl
|
050d4275af57a21ed76bd3302df2180333228c30
|
unitTesting/tools/test_mailbox.cpp
|
unitTesting/tools/test_mailbox.cpp
|
/*
* Copyright 2010,
* François Bleibel,
* Olivier Stasse,
*
* CNRS/AIST
*
* This file is part of sot-core.
* sot-core is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
* sot-core is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details. You should
* have received a copy of the GNU Lesser General Public License along
* with sot-core. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <sot-core/debug.h>
#include <jrl/mal/boost.hh>
#ifndef WIN32
#include <unistd.h>
#endif
using namespace std;
namespace ml = maal::boost;
#include <dynamic-graph/factory.h>
#include <dynamic-graph/entity.h>
#include <sot-core/feature-abstract.h>
#include <dynamic-graph/plugin-loader.h>
#include <dynamic-graph/interpreter.h>
#include <sot-core/mailbox-vector.h>
#include <sstream>
using namespace dynamicgraph;
using namespace sot;
#include <boost/thread.hpp>
sot::MailboxVector mailbox("mail");
void f( void )
{
ml::Vector vect(25);
ml::Vector vect2(25);
for( int i=0;;++i )
{
std::cout << " iter " << i << std::endl;
for( int j=0;j<25;++j ) vect(j) = j+i*10;
mailbox.post( vect );
maal::boost::Vector V = mailbox.getObject( vect2, 1 );
std::cout << vect2 << std::endl;
std::cout << " getClassName " << mailbox.getClassName() << std::endl;
std::cout << " getName " << mailbox.getName() << std::endl;
std::cout << " hasBeenUpdated " << mailbox.hasBeenUpdated() << std::endl;
std::cout << std::endl;
}
}
int main( int argc,char** argv )
{
boost::thread th( f );
#ifdef WIN32
Sleep( 100 );
#else
usleep( 1000*100 );
#endif
return 0;
}
|
/*
* Copyright 2010,
* François Bleibel,
* Olivier Stasse,
*
* CNRS/AIST
*
* This file is part of sot-core.
* sot-core is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
* sot-core is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details. You should
* have received a copy of the GNU Lesser General Public License along
* with sot-core. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <sot-core/debug.h>
#include <jrl/mal/boost.hh>
#ifndef WIN32
#include <unistd.h>
#endif
using namespace std;
namespace ml = maal::boost;
#include <dynamic-graph/factory.h>
#include <dynamic-graph/entity.h>
#include <sot-core/feature-abstract.h>
#include <dynamic-graph/plugin-loader.h>
#include <dynamic-graph/interpreter.h>
#include <sot-core/mailbox-vector.h>
#include <sstream>
using namespace dynamicgraph;
using namespace sot;
#include <boost/thread.hpp>
sot::MailboxVector mailbox("mail");
void f( void )
{
ml::Vector vect(25);
ml::Vector vect2(25);
for( int i=0; i < 250 ; ++i )
{
std::cout << " iter " << i << std::endl;
for( int j=0;j<25;++j ) vect(j) = j+i*10;
mailbox.post( vect );
maal::boost::Vector V = mailbox.getObject( vect2, 1 );
std::cout << vect2 << std::endl;
std::cout << " getClassName " << mailbox.getClassName() << std::endl;
std::cout << " getName " << mailbox.getName() << std::endl;
std::cout << " hasBeenUpdated " << mailbox.hasBeenUpdated() << std::endl;
std::cout << std::endl;
}
}
int main( int argc,char** argv )
{
boost::thread th( f );
th.join();
return 0;
}
|
Fix unwanted race condition in test_mailbox
|
Fix unwanted race condition in test_mailbox
|
C++
|
bsd-2-clause
|
stack-of-tasks/sot-core,stack-of-tasks/sot-core,stack-of-tasks/sot-core
|
356aa77b75948b217ba3e6ce60467dccd891deec
|
src/web_util_http_parser.cpp
|
src/web_util_http_parser.cpp
|
#include "web_util_http_parser.h"
#include "hphp/runtime/server/http-protocol.h"
#include "hphp/runtime/ext/json/ext_json.h"
namespace HPHP {
#if HHVM_API_VERSION < 20140702L
using JIT::VMRegAnchor;
#endif
const static StaticString
s_header("Header"),
s_request("Request"),
s_query("Query"),
s_content("Content"),
s_content_parsed("Content-Parsed"),
s_parsedData("parsedData")
;
ALWAYS_INLINE void parseContentType(http_parser_ext *parser){
Array parsedData = parser->http_parser_object_data->o_get(s_parsedData, false, s_web_util_http_parser).toArray();
Array parsedData_header = parsedData[s_header].toArray();
String contentType = parsedData_header[String("Content-Type")].toString();
if(contentType == String("application/x-www-form-urlencoded")){
parser->contentType = CONTENT_TYPE_URLENCODE;
return;
}
if(contentType.find("application/json", 0, false) == 0){
parser->contentType = CONTENT_TYPE_JSONENCODE;
return;
}
if(contentType.find("multipart/form-data", 0, false) == 0){
parser->contentType = CONTENT_TYPE_MULTIPART;
return;
}
}
ALWAYS_INLINE void parseRequest(http_parser_ext *parser){
struct http_parser_url parser_url;
Array parsedData = parser->http_parser_object_data->o_get(s_parsedData, false, s_web_util_http_parser).toArray();
Array parsedData_request = parsedData[s_request].toArray();
Array parsedData_query = parsedData[s_query].toArray();
Array params;
parsedData_request.set(String("Method"), http_method_str((enum http_method)parser->method));
parsedData_request.set(String("Target"), parser->url);
parsedData_request.set(String("Protocol"), "HTTP");
parsedData_request.set(String("Protocol-Version"), String(parser->http_major)+"."+String(parser->http_minor));
parsedData.set(s_request, parsedData_request);
http_parser_parse_url(parser->url.data(),parser->url.size(), 0, &parser_url);
parsedData_query.set(String("Path"), parser->url.substr(parser_url.field_data[UF_PATH].off, parser_url.field_data[UF_PATH].len));
if(parser_url.field_data[UF_QUERY].len){
String query;
query = parser->url.substr(parser_url.field_data[UF_QUERY].off, parser_url.field_data[UF_QUERY].len);
HttpProtocol::DecodeParameters(params, query.data(), query.size());
}
parsedData_query.set(String("Param"), params);
parsedData.set(s_query, parsedData_query);
parser->http_parser_object_data->o_set(s_parsedData, parsedData, s_web_util_http_parser);
}
ALWAYS_INLINE void resetHeaderParser(http_parser_ext *parser){
if(parser->headerEnd){
Array parsedData = parser->http_parser_object_data->o_get(s_parsedData, false, s_web_util_http_parser).toArray();
Array parsedData_header = parsedData[s_header].toArray();
parsedData_header.set(parser->Header, parser->Field);
parsedData.set(s_header, parsedData_header);
parser->http_parser_object_data->o_set(s_parsedData, parsedData, s_web_util_http_parser);
parser->Header.clear();
parser->Field.clear();
parser->headerEnd = false;
}
}
ALWAYS_INLINE void parseBody(http_parser_ext *parser){
Array parsedData = parser->http_parser_object_data->o_get(s_parsedData, false, s_web_util_http_parser).toArray();
Array params;
parsedData.set(s_content, parser->Body);
switch(parser->contentType){
case CONTENT_TYPE_URLENCODE:
HttpProtocol::DecodeParameters(params, parser->Body.data(), parser->Body.size());
parsedData.set(s_content_parsed, params);
break;
case CONTENT_TYPE_JSONENCODE:
parsedData.set(s_content_parsed, HHVM_FN(json_decode)(parser->Body, true));
break;
default:
break;
}
parser->http_parser_object_data->o_set(s_parsedData, parsedData, s_web_util_http_parser);
}
static http_parser_settings parser_settings = {
(http_cb) on_message_begin, //on_message_begin
(http_data_cb) on_url, //on_url
(http_data_cb) on_status, //on_status
(http_data_cb) on_header_field, //on_header_field
(http_data_cb) on_header_value, //on_header_value
(http_cb) on_headers_complete, //on_headers_complete
(http_data_cb) on_body, //on_body
(http_cb) on_message_complete //on_message_complete
};
web_util_HttpParserData::web_util_HttpParserData(){
onParsedCallback.setNull();
parser = new http_parser_ext;
parser->headerEnd = false;
http_parser_init(parser, HTTP_REQUEST);
}
web_util_HttpParserData::~web_util_HttpParserData(){
sweep();
}
void web_util_HttpParserData::sweep() {
if(parser){
delete parser;
parser = NULL;
}
}
static int on_message_begin(http_parser_ext *parser){
return 0;
}
static int on_message_complete(http_parser_ext *parser){
auto* data = Native::data<web_util_HttpParserData>(parser->http_parser_object_data);
Array parsedData;
parseBody(parser);
parsedData = parser->http_parser_object_data->o_get(s_parsedData, false, s_web_util_http_parser).toArray();
if(!data->onParsedCallback.isNull()){
vm_call_user_func(data->onParsedCallback, make_packed_array(parsedData));
}
return 0;
}
static int on_headers_complete(http_parser_ext *parser){
resetHeaderParser(parser);
parseRequest(parser);
parseContentType(parser);
return 0;
}
static int on_status(http_parser_ext *parser, const char *buf, size_t len){
return 0;
}
static int on_url(http_parser_ext *parser, const char *buf, size_t len){
parser->url += String(buf, len, CopyString);
return 0;
}
static int on_header_field(http_parser_ext *parser, const char *buf, size_t len){
resetHeaderParser(parser);
parser->Header += String(buf, len, CopyString);
return 0;
}
static int on_header_value(http_parser_ext *parser, const char *buf, size_t len){
parser->headerEnd = true;
parser->Field += String(buf, len, CopyString);
return 0;
}
static int on_body(http_parser_ext *parser, const char *buf, size_t len){
parser->Body += String(buf, len, CopyString);
return 0;
}
static void HHVM_METHOD(WebUtil_HttpParser, feed, const String &feedData) {
VMRegAnchor _;
auto* data = Native::data<web_util_HttpParserData>(this_);
http_parser_execute(data->parser, &parser_settings, feedData.data(), feedData.size());
}
static Variant HHVM_METHOD(WebUtil_HttpParser, setOnParsedCallback, const Variant &callback) {
auto* data = Native::data<web_util_HttpParserData>(this_);
Variant oldCallback = data->onParsedCallback;
data->onParsedCallback = callback;
return oldCallback;
}
static void HHVM_METHOD(WebUtil_HttpParser, __construct) {
auto* data = Native::data<web_util_HttpParserData>(this_);
data->parser->http_parser_object_data = this_;
}
void web_utilExtension::initHttpParser() {
HHVM_ME(WebUtil_HttpParser, __construct);
HHVM_MALIAS(WebUtil\\Parser\\HttpParser, __construct, WebUtil_HttpParser, __construct);
HHVM_ME(WebUtil_HttpParser, feed);
HHVM_MALIAS(WebUtil\\Parser\\HttpParser, feed, WebUtil_HttpParser, feed);
HHVM_ME(WebUtil_HttpParser, setOnParsedCallback);
HHVM_MALIAS(WebUtil\\Parser\\HttpParser, setOnParsedCallback, WebUtil_HttpParser, setOnParsedCallback);
Native::registerNativeDataInfo<web_util_HttpParserData>(s_web_util_http_parser.get());
}
}
|
#include "web_util_http_parser.h"
#include "hphp/runtime/server/http-protocol.h"
#include "hphp/runtime/ext/json/ext_json.h"
namespace HPHP {
#if HHVM_API_VERSION < 20140702L
using JIT::VMRegAnchor;
#endif
const static StaticString
s_header("Header"),
s_request("Request"),
s_query("Query"),
s_content("Content"),
s_content_parsed("Content-Parsed"),
s_cookie("Cookie"),
s_parsedData("parsedData")
;
ALWAYS_INLINE void parseContentType(http_parser_ext *parser){
Array parsedData = parser->http_parser_object_data->o_get(s_parsedData, false, s_web_util_http_parser).toArray();
Array parsedData_header = parsedData[s_header].toArray();
String contentType = parsedData_header[String("Content-Type")].toString();
if(contentType == String("application/x-www-form-urlencoded")){
parser->contentType = CONTENT_TYPE_URLENCODE;
return;
}
if(contentType.find("application/json", 0, false) == 0){
parser->contentType = CONTENT_TYPE_JSONENCODE;
return;
}
if(contentType.find("multipart/form-data", 0, false) == 0){
parser->contentType = CONTENT_TYPE_MULTIPART;
return;
}
}
ALWAYS_INLINE void parseRequest(http_parser_ext *parser){
struct http_parser_url parser_url;
Array parsedData = parser->http_parser_object_data->o_get(s_parsedData, false, s_web_util_http_parser).toArray();
Array parsedData_request = parsedData[s_request].toArray();
Array parsedData_query = parsedData[s_query].toArray();
Array params;
parsedData_request.set(String("Method"), http_method_str((enum http_method)parser->method));
parsedData_request.set(String("Target"), parser->url);
parsedData_request.set(String("Protocol"), "HTTP");
parsedData_request.set(String("Protocol-Version"), String(parser->http_major)+"."+String(parser->http_minor));
parsedData.set(s_request, parsedData_request);
http_parser_parse_url(parser->url.data(),parser->url.size(), 0, &parser_url);
parsedData_query.set(String("Path"), parser->url.substr(parser_url.field_data[UF_PATH].off, parser_url.field_data[UF_PATH].len));
if(parser_url.field_data[UF_QUERY].len){
String query;
query = parser->url.substr(parser_url.field_data[UF_QUERY].off, parser_url.field_data[UF_QUERY].len);
HttpProtocol::DecodeParameters(params, query.data(), query.size());
}
parsedData_query.set(String("Param"), params);
parsedData.set(s_query, parsedData_query);
parser->http_parser_object_data->o_set(s_parsedData, parsedData, s_web_util_http_parser);
}
ALWAYS_INLINE void resetHeaderParser(http_parser_ext *parser){
if(parser->headerEnd){
Array parsedData = parser->http_parser_object_data->o_get(s_parsedData, false, s_web_util_http_parser).toArray();
Array parsedData_header = parsedData[s_header].toArray();
parsedData_header.set(parser->Header, parser->Field);
parsedData.set(s_header, parsedData_header);
parser->http_parser_object_data->o_set(s_parsedData, parsedData, s_web_util_http_parser);
parser->Header.clear();
parser->Field.clear();
parser->headerEnd = false;
}
}
ALWAYS_INLINE void parseCookie(http_parser_ext *parser){
int token_equal_pos = 0, token_semi_pos = 0;
int field_start = 0;
int i = 0;
const char *cookieString;
int cookieString_len;
Array parsedData = parser->http_parser_object_data->o_get(s_parsedData, false, s_web_util_http_parser).toArray();
Array parsedData_header = parsedData[s_header].toArray();
String parsedData_cookie = parsedData_header[s_cookie].toString();
Array cookie;
if(parsedData_cookie.size() == 0){
return;
}
cookieString = parsedData_cookie.c_str();
cookieString_len = parsedData_cookie.size();
while(true){
if(cookieString[i] == '='){
if(token_equal_pos <= token_semi_pos){
token_equal_pos = i;
}
}
if(cookieString[i] == ';' || i==cookieString_len-1){
token_semi_pos = i;
cookie.set(String(&cookieString[field_start], token_equal_pos - field_start, CopyString), String(&cookieString[token_equal_pos+1], token_semi_pos - token_equal_pos - 1, CopyString));
field_start = i + 2;
}
if(++i>=cookieString_len){
break;
}
}
parsedData_header.set(s_cookie, cookie);
parsedData.set(s_header, parsedData_header);
parser->http_parser_object_data->o_set(s_parsedData, parsedData, s_web_util_http_parser);
}
ALWAYS_INLINE void parseBody(http_parser_ext *parser){
Array parsedData = parser->http_parser_object_data->o_get(s_parsedData, false, s_web_util_http_parser).toArray();
Array params;
parsedData.set(s_content, parser->Body);
switch(parser->contentType){
case CONTENT_TYPE_URLENCODE:
HttpProtocol::DecodeParameters(params, parser->Body.data(), parser->Body.size());
parsedData.set(s_content_parsed, params);
break;
case CONTENT_TYPE_JSONENCODE:
parsedData.set(s_content_parsed, HHVM_FN(json_decode)(parser->Body, true));
break;
default:
break;
}
parser->http_parser_object_data->o_set(s_parsedData, parsedData, s_web_util_http_parser);
}
static http_parser_settings parser_settings = {
(http_cb) on_message_begin, //on_message_begin
(http_data_cb) on_url, //on_url
(http_data_cb) on_status, //on_status
(http_data_cb) on_header_field, //on_header_field
(http_data_cb) on_header_value, //on_header_value
(http_cb) on_headers_complete, //on_headers_complete
(http_data_cb) on_body, //on_body
(http_cb) on_message_complete //on_message_complete
};
web_util_HttpParserData::web_util_HttpParserData(){
onParsedCallback.setNull();
parser = new http_parser_ext;
parser->headerEnd = false;
http_parser_init(parser, HTTP_REQUEST);
}
web_util_HttpParserData::~web_util_HttpParserData(){
sweep();
}
void web_util_HttpParserData::sweep() {
if(parser){
delete parser;
parser = NULL;
}
}
static int on_message_begin(http_parser_ext *parser){
return 0;
}
static int on_message_complete(http_parser_ext *parser){
auto* data = Native::data<web_util_HttpParserData>(parser->http_parser_object_data);
Array parsedData;
parseBody(parser);
parsedData = parser->http_parser_object_data->o_get(s_parsedData, false, s_web_util_http_parser).toArray();
if(!data->onParsedCallback.isNull()){
vm_call_user_func(data->onParsedCallback, make_packed_array(parsedData));
}
return 0;
}
static int on_headers_complete(http_parser_ext *parser){
resetHeaderParser(parser);
parseRequest(parser);
parseContentType(parser);
parseCookie(parser);
return 0;
}
static int on_status(http_parser_ext *parser, const char *buf, size_t len){
return 0;
}
static int on_url(http_parser_ext *parser, const char *buf, size_t len){
parser->url += String(buf, len, CopyString);
return 0;
}
static int on_header_field(http_parser_ext *parser, const char *buf, size_t len){
resetHeaderParser(parser);
parser->Header += String(buf, len, CopyString);
return 0;
}
static int on_header_value(http_parser_ext *parser, const char *buf, size_t len){
parser->headerEnd = true;
parser->Field += String(buf, len, CopyString);
return 0;
}
static int on_body(http_parser_ext *parser, const char *buf, size_t len){
parser->Body += String(buf, len, CopyString);
return 0;
}
static void HHVM_METHOD(WebUtil_HttpParser, feed, const String &feedData) {
VMRegAnchor _;
auto* data = Native::data<web_util_HttpParserData>(this_);
http_parser_execute(data->parser, &parser_settings, feedData.data(), feedData.size());
}
static Variant HHVM_METHOD(WebUtil_HttpParser, setOnParsedCallback, const Variant &callback) {
auto* data = Native::data<web_util_HttpParserData>(this_);
Variant oldCallback = data->onParsedCallback;
data->onParsedCallback = callback;
return oldCallback;
}
static void HHVM_METHOD(WebUtil_HttpParser, __construct) {
auto* data = Native::data<web_util_HttpParserData>(this_);
data->parser->http_parser_object_data = this_;
}
void web_utilExtension::initHttpParser() {
HHVM_ME(WebUtil_HttpParser, __construct);
HHVM_MALIAS(WebUtil\\Parser\\HttpParser, __construct, WebUtil_HttpParser, __construct);
HHVM_ME(WebUtil_HttpParser, feed);
HHVM_MALIAS(WebUtil\\Parser\\HttpParser, feed, WebUtil_HttpParser, feed);
HHVM_ME(WebUtil_HttpParser, setOnParsedCallback);
HHVM_MALIAS(WebUtil\\Parser\\HttpParser, setOnParsedCallback, WebUtil_HttpParser, setOnParsedCallback);
Native::registerNativeDataInfo<web_util_HttpParserData>(s_web_util_http_parser.get());
}
}
|
add cookie parser
|
add cookie parser
|
C++
|
mit
|
RickySu/hhvm-ext-web-util,RickySu/hhvm-ext-web-util,RickySu/hhvm-ext-web-util
|
e64ffef727028f460f3cdcea77174cd199afd423
|
ode/src/error.cpp
|
ode/src/error.cpp
|
/*************************************************************************
* *
* Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. *
* All rights reserved. Email: [email protected] Web: www.q12.org *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of EITHER: *
* (1) 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. The text of the GNU Lesser *
* General Public License is included with this library in the *
* file LICENSE.TXT. *
* (2) The BSD-style license that is included with this library in *
* the file LICENSE-BSD.TXT. *
* *
* 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 files *
* LICENSE.TXT and LICENSE-BSD.TXT for more details. *
* *
*************************************************************************/
#include <ode/config.h>
#include <ode/error.h>
static dMessageFunction *error_function = 0;
static dMessageFunction *debug_function = 0;
static dMessageFunction *message_function = 0;
extern "C" void dSetErrorHandler (dMessageFunction *fn)
{
error_function = fn;
}
extern "C" void dSetDebugHandler (dMessageFunction *fn)
{
debug_function = fn;
}
extern "C" void dSetMessageHandler (dMessageFunction *fn)
{
message_function = fn;
}
extern "C" dMessageFunction *dGetErrorHandler()
{
return error_function;
}
extern "C" dMessageFunction *dGetDebugHandler()
{
return debug_function;
}
extern "C" dMessageFunction *dGetMessageHandler()
{
return message_function;
}
static void printMessage (int num, const char *msg1, const char *msg2,
va_list ap)
{
fflush (stderr);
fflush (stdout);
if (num) fprintf (stderr,"\n%s %d: ",msg1,num);
else fprintf (stderr,"\n%s: ",msg1);
vfprintf (stderr,msg2,ap);
fprintf (stderr,"\n");
fflush (stderr);
}
//****************************************************************************
// unix
#ifndef WIN32
extern "C" void dError (int num, const char *msg, ...)
{
va_list ap;
va_start (ap,msg);
if (error_function) error_function (num,msg,ap);
else printMessage (num,"ODE Error",msg,ap);
exit (1);
}
extern "C" void dDebug (int num, const char *msg, ...)
{
va_list ap;
va_start (ap,msg);
if (debug_function) debug_function (num,msg,ap);
else printMessage (num,"ODE INTERNAL ERROR",msg,ap);
// *((char *)0) = 0; ... commit SEGVicide
abort();
}
extern "C" void dMessage (int num, const char *msg, ...)
{
va_list ap;
va_start (ap,msg);
if (message_function) message_function (num,msg,ap);
else printMessage (num,"ODE Message",msg,ap);
}
#endif
//****************************************************************************
// windows
#ifdef WIN32
#include "windows.h"
extern "C" void dError (int num, const char *msg, ...)
{
va_list ap;
va_start (ap,msg);
if (error_function) error_function (num,msg,ap);
else {
char s[1000],title[100];
snprintf (title,sizeof(title),"ODE Error %d",num);
vsnprintf (s,sizeof(s),msg,ap);
s[sizeof(s)-1] = 0;
MessageBox(0,s,title,MB_OK | MB_ICONWARNING);
}
exit (1);
}
extern "C" void dDebug (int num, const char *msg, ...)
{
va_list ap;
va_start (ap,msg);
if (debug_function) debug_function (num,msg,ap);
else {
char s[1000],title[100];
snprintf (title,sizeof(title),"ODE INTERNAL ERROR %d",num);
vsnprintf (s,sizeof(s),msg,ap);
s[sizeof(s)-1] = 0;
MessageBox(0,s,title,MB_OK | MB_ICONSTOP);
}
abort();
}
extern "C" void dMessage (int num, const char *msg, ...)
{
va_list ap;
va_start (ap,msg);
if (message_function) message_function (num,msg,ap);
else printMessage (num,"ODE Message",msg,ap);
}
#endif
|
/*************************************************************************
* *
* Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. *
* All rights reserved. Email: [email protected] Web: www.q12.org *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of EITHER: *
* (1) 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. The text of the GNU Lesser *
* General Public License is included with this library in the *
* file LICENSE.TXT. *
* (2) The BSD-style license that is included with this library in *
* the file LICENSE-BSD.TXT. *
* *
* 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 files *
* LICENSE.TXT and LICENSE-BSD.TXT for more details. *
* *
*************************************************************************/
#include <ode/config.h>
#include <ode/error.h>
static dMessageFunction *error_function = 0;
static dMessageFunction *debug_function = 0;
static dMessageFunction *message_function = 0;
extern "C" void dSetErrorHandler (dMessageFunction *fn)
{
error_function = fn;
}
extern "C" void dSetDebugHandler (dMessageFunction *fn)
{
debug_function = fn;
}
extern "C" void dSetMessageHandler (dMessageFunction *fn)
{
message_function = fn;
}
extern "C" dMessageFunction *dGetErrorHandler()
{
return error_function;
}
extern "C" dMessageFunction *dGetDebugHandler()
{
return debug_function;
}
extern "C" dMessageFunction *dGetMessageHandler()
{
return message_function;
}
static void printMessage (int num, const char *msg1, const char *msg2,
va_list ap)
{
fflush (stderr);
fflush (stdout);
if (num) fprintf (stderr,"\n%s %d: ",msg1,num);
else fprintf (stderr,"\n%s: ",msg1);
vfprintf (stderr,msg2,ap);
fprintf (stderr,"\n");
fflush (stderr);
}
//****************************************************************************
// unix
#ifndef WIN32
extern "C" void dError (int num, const char *msg, ...)
{
va_list ap;
va_start (ap,msg);
if (error_function) error_function (num,msg,ap);
else printMessage (num,"ODE Error",msg,ap);
exit (1);
}
extern "C" void dDebug (int num, const char *msg, ...)
{
va_list ap;
va_start (ap,msg);
if (debug_function) debug_function (num,msg,ap);
else printMessage (num,"ODE INTERNAL ERROR",msg,ap);
// *((char *)0) = 0; ... commit SEGVicide
abort();
}
extern "C" void dMessage (int num, const char *msg, ...)
{
va_list ap;
va_start (ap,msg);
if (message_function) message_function (num,msg,ap);
else printMessage (num,"ODE Message",msg,ap);
}
#endif
//****************************************************************************
// windows
#ifdef WIN32
// isn't cygwin annoying!
#ifdef CYGWIN
#define _snprintf snprintf
#define _vsnprintf vsnprintf
#endif
#include "windows.h"
extern "C" void dError (int num, const char *msg, ...)
{
va_list ap;
va_start (ap,msg);
if (error_function) error_function (num,msg,ap);
else {
char s[1000],title[100];
_snprintf (title,sizeof(title),"ODE Error %d",num);
_vsnprintf (s,sizeof(s),msg,ap);
s[sizeof(s)-1] = 0;
MessageBox(0,s,title,MB_OK | MB_ICONWARNING);
}
exit (1);
}
extern "C" void dDebug (int num, const char *msg, ...)
{
va_list ap;
va_start (ap,msg);
if (debug_function) debug_function (num,msg,ap);
else {
char s[1000],title[100];
_snprintf (title,sizeof(title),"ODE INTERNAL ERROR %d",num);
_vsnprintf (s,sizeof(s),msg,ap);
s[sizeof(s)-1] = 0;
MessageBox(0,s,title,MB_OK | MB_ICONSTOP);
}
abort();
}
extern "C" void dMessage (int num, const char *msg, ...)
{
va_list ap;
va_start (ap,msg);
if (message_function) message_function (num,msg,ap);
else printMessage (num,"ODE Message",msg,ap);
}
#endif
|
Put WIN32/CYGWIN specific defines back in
|
Put WIN32/CYGWIN specific defines back in
|
C++
|
lgpl-2.1
|
forrestv/opende,forrestv/opende,forrestv/opende,forrestv/opende,forrestv/opende
|
3cb7070d7cabc8971e30243d6eb47eaf322fffad
|
C++/kth-smallest-element-in-a-sorted-matrix.cpp
|
C++/kth-smallest-element-in-a-sorted-matrix.cpp
|
// Time: O(klogk)
// Space: O(k)
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
int kth_smallest = 0;
using P = pair<int, int>;
const auto Compare = [&matrix](const P& a, const P& b) {
return matrix[a.first][a.second] > matrix[b.first][b.second];
};
priority_queue<P, vector<P>, decltype(Compare)> min_heap(Compare);
min_heap.emplace(0, 0);
for (int i = 0; i < k; ++i) {
const auto idx = min_heap.top();
min_heap.pop();
if (idx.first == 0 && idx.second + 1 < matrix[0].size()) {
min_heap.emplace(0, idx.second + 1);
}
if (idx.first + 1 < matrix.size()) {
min_heap.emplace(idx.first + 1, idx.second);
}
kth_smallest = matrix[idx.first][idx.second];
}
return kth_smallest;
}
};
|
// Time: O(k * log(min(n, m, k))), with n x m matrix
// Space: O(min(n, m, k))
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
int kth_smallest = 0;
using P = pair<int, pair<int, int>>;
priority_queue<P, vector<P>, greater<P>> q;
auto push = [&matrix, &q](int i, int j) {
if (matrix.size() > matrix[0].size()) {
if (i < matrix[0].size() && j < matrix.size()) {
q.emplace(matrix[j][i], make_pair(j, i));
}
} else {
if (i < matrix.size() && j < matrix[0].size()) {
q.emplace(matrix[i][j], make_pair(i, j));
}
}
};
push(0, 0);
while (!q.empty() && k--) {
auto tmp = q.top(); q.pop();
kth_smallest = tmp.first;
int i, j;
tie(i, j) = tmp.second;
push(i, j + 1);
if (j == 0) {
push(i + 1, 0);
}
}
return kth_smallest;
}
};
|
Update kth-smallest-element-in-a-sorted-matrix.cpp
|
Update kth-smallest-element-in-a-sorted-matrix.cpp
|
C++
|
mit
|
kamyu104/LeetCode,githubutilities/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,tudennis/LeetCode---kamyu104-11-24-2015,yiwen-luo/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,githubutilities/LeetCode,yiwen-luo/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,githubutilities/LeetCode,yiwen-luo/LeetCode,githubutilities/LeetCode,kamyu104/LeetCode,jaredkoontz/leetcode,kamyu104/LeetCode,yiwen-luo/LeetCode,kamyu104/LeetCode,jaredkoontz/leetcode,kamyu104/LeetCode,jaredkoontz/leetcode,githubutilities/LeetCode,yiwen-luo/LeetCode,jaredkoontz/leetcode,tudennis/LeetCode---kamyu104-11-24-2015,jaredkoontz/leetcode
|
c68c385b270d9632c576efff4126eff821cfbde6
|
ode/ode/src/collision_trimesh.cpp
|
ode/ode/src/collision_trimesh.cpp
|
/*************************************************************************
* *
* Open Dynamics Engine, Copyright (C) 2001-2003 Russell L. Smith. *
* All rights reserved. Email: [email protected] Web: www.q12.org *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of EITHER: *
* (1) 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. The text of the GNU Lesser *
* General Public License is included with this library in the *
* file LICENSE.TXT. *
* (2) The BSD-style license that is included with this library in *
* the file LICENSE-BSD.TXT. *
* *
* 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 files *
* LICENSE.TXT and LICENSE-BSD.TXT for more details. *
* *
*************************************************************************/
// TriMesh code by Erwin de Vries.
#include <ode/collision.h>
#include <ode/matrix.h>
#include <ode/rotation.h>
#include <ode/odemath.h>
#include "collision_util.h"
#define TRIMESH_INTERNAL
#include "collision_trimesh_internal.h"
// Trimesh data
dxTriMeshData::dxTriMeshData(){
#ifndef dTRIMESH_ENABLED
dUASSERT(g, "dTRIMESH_ENABLED is not defined. Trimesh geoms will not work");
#endif
}
dxTriMeshData::~dxTriMeshData(){
//
}
void dxTriMeshData::Build(const void* Vertices, int VertexStide, int VertexCount, const void* Indices, int IndexCount, int TriStride, bool Single){
Mesh.SetNbTriangles(IndexCount / 3);
Mesh.SetNbVertices(VertexCount);
Mesh.SetPointers((IndexedTriangle*)Indices, (Point*)Vertices);
Mesh.SetStrides(TriStride, VertexStide);
Mesh.Single = Single;
// Build tree
BuildSettings Settings;
Settings.mRules = SPLIT_BEST_AXIS;
OPCODECREATE TreeBuilder;
TreeBuilder.mIMesh = &Mesh;
TreeBuilder.mSettings = Settings;
TreeBuilder.mNoLeaf = true;
TreeBuilder.mQuantized = false;
TreeBuilder.mKeepOriginal = false;
TreeBuilder.mCanRemap = false;
BVTree.Build(TreeBuilder);
}
dTriMeshDataID dGeomTriMeshDataCreate(){
return new dxTriMeshData();
}
void dGeomTriMeshDataDestroy(dTriMeshDataID g){
delete g;
}
void dGeomTriMeshDataBuildSingle(dTriMeshDataID g, const void* Vertices, int VertexStride, int VertexCount,
const void* Indices, int IndexCount, int TriStride){
dUASSERT(g, "argument not trimesh data");
g->Build(Vertices, VertexStride, VertexCount, Indices, IndexCount, TriStride, true);
}
void dGeomTriMeshDataBuildDouble(dTriMeshDataID g, const void* Vertices, int VertexStride, int VertexCount,
const void* Indices, int IndexCount, int TriStride){
dUASSERT(g, "argument not trimesh data");
g->Build(Vertices, VertexStride, VertexCount, Indices, IndexCount, TriStride, false);
}
void dGeomTriMeshDataBuildSimple(dTriMeshDataID g, const dReal* Vertices, int VertexCount,
const int* Indices, int IndexCount){
#ifdef dSINGLE
dGeomTriMeshDataBuildSingle(g, Vertices, 4 * sizeof(dReal), VertexCount, Indices, IndexCount, 3 * sizeof(unsigned int));
#else
dGeomTriMeshDataBuildDouble(g, Vertices, 4 * sizeof(dReal), VertexCount, Indices, IndexCount, 3 * sizeof(unsigned int));
#endif
}
// Trimesh
PlanesCollider dxTriMesh::_PlanesCollider;
SphereCollider dxTriMesh::_SphereCollider;
OBBCollider dxTriMesh::_OBBCollider;
RayCollider dxTriMesh::_RayCollider;
AABBTreeCollider dxTriMesh::_AABBTreeCollider;
CollisionFaces dxTriMesh::Faces;
dxTriMesh::dxTriMesh(dSpaceID Space, dTriMeshDataID Data) : dxGeom(Space, 1){
type = dTriMeshClass;
this->Data = Data;
_RayCollider.SetDestination(&Faces);
_PlanesCollider.SetTemporalCoherence(true);
_SphereCollider.SetTemporalCoherence(true);
_OBBCollider.SetTemporalCoherence(true);
_AABBTreeCollider.SetTemporalCoherence(true);
_SphereCollider.SetPrimitiveTests(false);
}
dxTriMesh::~dxTriMesh(){
//
}
void dxTriMesh::ClearTCCache(){
SphereTCCache.setSize(0);
BoxTCCache.setSize(0);
}
int dxTriMesh::AABBTest(dxGeom* g, dReal aabb[6]){
return 1;
}
void dxTriMesh::computeAABB(){
aabb[0] = -dInfinity;
aabb[1] = dInfinity;
aabb[2] = -dInfinity;
aabb[3] = dInfinity;
aabb[4] = -dInfinity;
aabb[5] = dInfinity;
}
dGeomID dCreateTriMesh(dSpaceID space, dTriMeshDataID Data, dTriCallback* Callback, dTriArrayCallback* ArrayCallback, dTriRayCallback* RayCallback){
dxTriMesh* Geom = new dxTriMesh(space, Data);
Geom->Callback = Callback;
Geom->ArrayCallback = ArrayCallback;
Geom->RayCallback = RayCallback;
return Geom;
}
void dGeomTriMeshClearTC(dGeomID g){
dUASSERT(g && g->type == dTriMeshClass, "argument not a trimesh");
dxTriMesh* Geom = (dxTriMesh*)g;
Geom->ClearTCCache();
}
// Getting data
void dGeomTriMeshGetTriangle(dGeomID g, int Index, dVector3* v0, dVector3* v1, dVector3* v2){
dUASSERT(g && g->type == dTriMeshClass, "argument not a trimesh");
dxTriMesh* Geom = (dxTriMesh*)g;
const dVector3& Position = *(const dVector3*)dGeomGetPosition(g);
const dMatrix3& Rotation = *(const dMatrix3*)dGeomGetRotation(g);
dVector3 v[3];
FetchTriangle(Geom, Index, Rotation, Position, v);
if (v0){
(*v0)[0] = v[0][0];
(*v0)[1] = v[0][1];
(*v0)[2] = v[0][2];
(*v0)[3] = v[0][3];
}
if (v1){
(*v1)[0] = v[1][0];
(*v1)[1] = v[1][1];
(*v1)[2] = v[1][2];
(*v1)[3] = v[0][3];
}
if (v2){
(*v2)[0] = v[2][0];
(*v2)[1] = v[2][1];
(*v2)[2] = v[2][2];
(*v2)[3] = v[2][3];
}
}
void dGeomTriMeshGetPoint(dGeomID g, int Index, dReal u, dReal v, dVector3 Out){
dUASSERT(g && g->type == dTriMeshClass, "argument not a trimesh");
dxTriMesh* Geom = (dxTriMesh*)g;
const dVector3& Position = *(const dVector3*)dGeomGetPosition(g);
const dMatrix3& Rotation = *(const dMatrix3*)dGeomGetRotation(g);
dVector3 dv[3];
FetchTriangle(Geom, Index, Rotation, Position, dv);
GetPointFromBarycentric(dv, u, v, Out);
}
|
/*************************************************************************
* *
* Open Dynamics Engine, Copyright (C) 2001-2003 Russell L. Smith. *
* All rights reserved. Email: [email protected] Web: www.q12.org *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of EITHER: *
* (1) 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. The text of the GNU Lesser *
* General Public License is included with this library in the *
* file LICENSE.TXT. *
* (2) The BSD-style license that is included with this library in *
* the file LICENSE-BSD.TXT. *
* *
* 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 files *
* LICENSE.TXT and LICENSE-BSD.TXT for more details. *
* *
*************************************************************************/
// TriMesh code by Erwin de Vries.
#include <ode/collision.h>
#include <ode/matrix.h>
#include <ode/rotation.h>
#include <ode/odemath.h>
#include "collision_util.h"
#define TRIMESH_INTERNAL
#include "collision_trimesh_internal.h"
// Trimesh data
dxTriMeshData::dxTriMeshData(){
#ifndef dTRIMESH_ENABLED
dUASSERT(g, "dTRIMESH_ENABLED is not defined. Trimesh geoms will not work");
#endif
}
dxTriMeshData::~dxTriMeshData(){
//
}
void dxTriMeshData::Build(const void* Vertices, int VertexStide, int VertexCount, const void* Indices, int IndexCount, int TriStride, bool Single){
Mesh.SetNbTriangles(IndexCount / 3);
Mesh.SetNbVertices(VertexCount);
Mesh.SetPointers((IndexedTriangle*)Indices, (Point*)Vertices);
Mesh.SetStrides(TriStride, VertexStide);
Mesh.Single = Single;
// Build tree
BuildSettings Settings;
Settings.mRules = SPLIT_BEST_AXIS;
OPCODECREATE TreeBuilder;
TreeBuilder.mIMesh = &Mesh;
TreeBuilder.mSettings = Settings;
TreeBuilder.mNoLeaf = true;
TreeBuilder.mQuantized = false;
TreeBuilder.mKeepOriginal = false;
TreeBuilder.mCanRemap = false;
BVTree.Build(TreeBuilder);
}
dTriMeshDataID dGeomTriMeshDataCreate(){
return new dxTriMeshData();
}
void dGeomTriMeshDataDestroy(dTriMeshDataID g){
delete g;
}
void dGeomTriMeshDataBuildSingle(dTriMeshDataID g, const void* Vertices, int VertexStride, int VertexCount,
const void* Indices, int IndexCount, int TriStride){
dUASSERT(g, "argument not trimesh data");
g->Build(Vertices, VertexStride, VertexCount, Indices, IndexCount, TriStride, true);
}
void dGeomTriMeshDataBuildDouble(dTriMeshDataID g, const void* Vertices, int VertexStride, int VertexCount,
const void* Indices, int IndexCount, int TriStride){
dUASSERT(g, "argument not trimesh data");
g->Build(Vertices, VertexStride, VertexCount, Indices, IndexCount, TriStride, false);
}
void dGeomTriMeshDataBuildSimple(dTriMeshDataID g, const dReal* Vertices, int VertexCount,
const int* Indices, int IndexCount){
#ifdef dSINGLE
dGeomTriMeshDataBuildSingle(g, Vertices, 4 * sizeof(dReal), VertexCount, Indices, IndexCount, 3 * sizeof(unsigned int));
#else
dGeomTriMeshDataBuildDouble(g, Vertices, 4 * sizeof(dReal), VertexCount, Indices, IndexCount, 3 * sizeof(unsigned int));
#endif
}
// Trimesh
PlanesCollider dxTriMesh::_PlanesCollider;
SphereCollider dxTriMesh::_SphereCollider;
OBBCollider dxTriMesh::_OBBCollider;
RayCollider dxTriMesh::_RayCollider;
AABBTreeCollider dxTriMesh::_AABBTreeCollider;
CollisionFaces dxTriMesh::Faces;
dxTriMesh::dxTriMesh(dSpaceID Space, dTriMeshDataID Data) : dxGeom(Space, 1){
type = dTriMeshClass;
this->Data = Data;
_RayCollider.SetDestination(&Faces);
_PlanesCollider.SetTemporalCoherence(true);
_SphereCollider.SetTemporalCoherence(true);
_OBBCollider.SetTemporalCoherence(true);
_AABBTreeCollider.SetTemporalCoherence(true);
_SphereCollider.SetPrimitiveTests(false);
}
dxTriMesh::~dxTriMesh(){
//
}
void dxTriMesh::ClearTCCache(){
/* dxTriMesh::ClearTCCache uses dArray's setSize(0) to clear the caches -
but the destructor isn't called when doing this, so we would leak.
So, call the previous caches' containers' destructors by hand first. */
int i, n;
n = SphereTCCache.size();
for( i = 0; i < n; ++i ) {
SphereTCCache[i].~SphereTC();
}
SphereTCCache.setSize(0);
n = BoxTCCache.size();
for( i = 0; i < n; ++i ) {
BoxTCCache[i].~BoxTC();
}
BoxTCCache.setSize(0);
}
int dxTriMesh::AABBTest(dxGeom* g, dReal aabb[6]){
return 1;
}
void dxTriMesh::computeAABB(){
aabb[0] = -dInfinity;
aabb[1] = dInfinity;
aabb[2] = -dInfinity;
aabb[3] = dInfinity;
aabb[4] = -dInfinity;
aabb[5] = dInfinity;
}
dGeomID dCreateTriMesh(dSpaceID space, dTriMeshDataID Data, dTriCallback* Callback, dTriArrayCallback* ArrayCallback, dTriRayCallback* RayCallback){
dxTriMesh* Geom = new dxTriMesh(space, Data);
Geom->Callback = Callback;
Geom->ArrayCallback = ArrayCallback;
Geom->RayCallback = RayCallback;
return Geom;
}
void dGeomTriMeshClearTC(dGeomID g){
dUASSERT(g && g->type == dTriMeshClass, "argument not a trimesh");
dxTriMesh* Geom = (dxTriMesh*)g;
Geom->ClearTCCache();
}
// Getting data
void dGeomTriMeshGetTriangle(dGeomID g, int Index, dVector3* v0, dVector3* v1, dVector3* v2){
dUASSERT(g && g->type == dTriMeshClass, "argument not a trimesh");
dxTriMesh* Geom = (dxTriMesh*)g;
const dVector3& Position = *(const dVector3*)dGeomGetPosition(g);
const dMatrix3& Rotation = *(const dMatrix3*)dGeomGetRotation(g);
dVector3 v[3];
FetchTriangle(Geom, Index, Rotation, Position, v);
if (v0){
(*v0)[0] = v[0][0];
(*v0)[1] = v[0][1];
(*v0)[2] = v[0][2];
(*v0)[3] = v[0][3];
}
if (v1){
(*v1)[0] = v[1][0];
(*v1)[1] = v[1][1];
(*v1)[2] = v[1][2];
(*v1)[3] = v[0][3];
}
if (v2){
(*v2)[0] = v[2][0];
(*v2)[1] = v[2][1];
(*v2)[2] = v[2][2];
(*v2)[3] = v[2][3];
}
}
void dGeomTriMeshGetPoint(dGeomID g, int Index, dReal u, dReal v, dVector3 Out){
dUASSERT(g && g->type == dTriMeshClass, "argument not a trimesh");
dxTriMesh* Geom = (dxTriMesh*)g;
const dVector3& Position = *(const dVector3*)dGeomGetPosition(g);
const dMatrix3& Rotation = *(const dMatrix3*)dGeomGetRotation(g);
dVector3 dv[3];
FetchTriangle(Geom, Index, Rotation, Position, dv);
GetPointFromBarycentric(dv, u, v, Out);
}
|
apply the following fix, with a mildly descriptive comment: ------------------ Hi,
|
apply the following fix, with a mildly descriptive comment:
------------------
Hi,
TriMesh for temporal coherence uses ODE's dArray of SphereTC and BoxTC
classes. These in turn are derived from OPCODE classes, and contain
IceCore::Container that has a non-trivial destructor.
Now, dxTriMesh::ClearTCCache uses dArray's setSize(0) to clear the caches -
but the destructor isn't called. So, each ClearTCCache leaks previous
caches' containers.
A quick dirty fix is to call destructors by hand:
void dxTriMesh::ClearTCCache(){
int i, n;
n = SphereTCCache.size();
for( i = 0; i < n; ++i ) {
SphereTCCache[i].~SphereTC();
}
SphereTCCache.setSize(0);
n = BoxTCCache.size();
for( i = 0; i < n; ++i ) {
BoxTCCache[i].~BoxTC();
}
BoxTCCache.setSize(0);
}
Aras Pranckevicius aka NeARAZ
http://www.gim.ktu.lt/nesnausk/nearaz/
|
C++
|
lgpl-2.1
|
keletskiy/ode,nabijaczleweli/ODE,nabijaczleweli/ODE,keletskiy/ode,keletskiy/ode,nabijaczleweli/ODE,nabijaczleweli/ODE,nabijaczleweli/ODE,keletskiy/ode,keletskiy/ode,nabijaczleweli/ODE,keletskiy/ode
|
478b02cf8c818106f377a43d81d3cdf0148377e5
|
DSP/extensions/EffectsLib/tests/TTThru.test.cpp
|
DSP/extensions/EffectsLib/tests/TTThru.test.cpp
|
/** @file
*
* @ingroup dspEffectsLib
*
* @brief Unit tests for #TTThru
*
* @authors Timothy Place, Trond Lossius
*
* @copyright Copyright © 2011, Timothy Place @n
* License: This code is licensed under the terms of the "New BSD License" @n
* http://creativecommons.org/licenses/BSD/
*/
#include "TTThru.h"
TTErr TTThru::test(TTValue& returnedTestInfo)
{
int errorCount = 0;
int testAssertionCount = 0;
TTAudioSignalPtr input = NULL;
TTAudioSignalPtr output = NULL;
// create stereo audio signals
TTObjectBaseInstantiate(kTTSym_audiosignal, &input, 2);
TTObjectBaseInstantiate(kTTSym_audiosignal, &output, 2);
input->allocWithVectorSize(64);
output->allocWithVectorSize(64);
for (int i=0; i<64; i++)
input->mSampleVectors[0][i] = TTRandom64();
this->process(input, output);
int validSampleCount = 0;
for (int channel=0; channel<2; channel++) {
TTSampleValuePtr inSamples = input->mSampleVectors[channel];
TTSampleValuePtr outSamples = output->mSampleVectors[channel];
for (int i=0; i<64; i++) {
validSampleCount += TTTestFloatEquivalence(inSamples[i], outSamples[i]);
}
}
TTTestAssertion("input samples accurately copied to output samples",
validSampleCount == 128, // 64 * 2 channels
testAssertionCount,
errorCount);
TTTestLog("Number of bad samples: %i", 128-validSampleCount);
TTObjectBaseRelease(&input);
TTObjectBaseRelease(&output);
// Wrap up the test results to pass back to whoever called this test
return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo);
}
|
/** @file
*
* @ingroup dspEffectsLib
*
* @brief Unit tests for #TTThru
*
* @authors Timothy Place, Trond Lossius
*
* @copyright Copyright © 2011, Timothy Place @n
* License: This code is licensed under the terms of the "New BSD License" @n
* http://creativecommons.org/licenses/BSD/
*/
#include "TTThru.h"
TTErr TTThru::test(TTValue& returnedTestInfo)
{
int errorCount = 0;
int testAssertionCount = 0;
// create stereo audio signals
TTAudio input(2);
TTAudio output(2);
input.allocWithVectorSize(64);
output.allocWithVectorSize(64);
for (int i=0; i<64; i++)
input.rawSamples()[0][i] = TTRandom64();
this->process(input, output);
int validSampleCount = 0;
for (int channel=0; channel<2; channel++) {
TTSampleValuePtr inSamples = input.rawSamples()[channel];
TTSampleValuePtr outSamples = output.rawSamples()[channel];
for (int i=0; i<64; i++) {
validSampleCount += TTTestFloatEquivalence(inSamples[i], outSamples[i]);
}
}
TTTestAssertion("input samples accurately copied to output samples",
validSampleCount == 128, // 64 * 2 channels
testAssertionCount,
errorCount);
TTTestLog("Number of bad samples: %i", 128-validSampleCount);
// Wrap up the test results to pass back to whoever called this test
return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo);
}
|
refactor of TTThru test. see issue #295
|
TTEffectsLib: refactor of TTThru test. see issue #295
|
C++
|
bsd-3-clause
|
jamoma/JamomaCore,eriser/JamomaCore,jamoma/JamomaCore,eriser/JamomaCore,eriser/JamomaCore,jamoma/JamomaCore,eriser/JamomaCore,jamoma/JamomaCore,jamoma/JamomaCore,eriser/JamomaCore,eriser/JamomaCore,jamoma/JamomaCore,eriser/JamomaCore,jamoma/JamomaCore,eriser/JamomaCore
|
aa14615309a7997e0e9a2332c8d377952927c1d4
|
DungeonsOfNoudar486/SDLVersion/CSDLRenderer.cpp
|
DungeonsOfNoudar486/SDLVersion/CSDLRenderer.cpp
|
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <utility>
#include <functional>
#include <memory>
#include <algorithm>
#include <iostream>
#include <map>
#include <chrono>
#include <sg14/fixed_point>
#include <EASTL/vector.h>
#include <EASTL/array.h>
using eastl::vector;
using eastl::array;
using namespace std::chrono;
using sg14::fixed_point;
#include "RasterizerCommon.h"
#include "RaycastCommon.h"
#include "Vec2i.h"
#include "IMapElement.h"
#include "CTeam.h"
#include "CItem.h"
#include "CActor.h"
#include "CGameDelegate.h"
#include "CMap.h"
#include "IRenderer.h"
#include "IFileLoaderDelegate.h"
#include "CGame.h"
#include "NativeBitmap.h"
#include "RasterizerCommon.h"
#include "CRenderer.h"
#include <SDL/SDL.h>
#include <SDL/SDL_mixer.h>
#include <cmath>
#include "NativeBitmap.h"
#include "LoadPNG.h"
#ifdef __EMSCRIPTEN__
#include <emscripten/html5.h>
#endif
namespace odb {
bool drawZBuffer = false;
SDL_Surface *video;
#ifdef __EMSCRIPTEN__
void enterFullScreenMode() {
EmscriptenFullscreenStrategy s;
memset(&s, 0, sizeof(s));
s.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_ASPECT;
s.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_NONE;
s.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
emscripten_enter_soft_fullscreen(0, &s);
}
#endif
CRenderer::CRenderer() {
SDL_Init( SDL_INIT_EVERYTHING );
video = SDL_SetVideoMode( 640, 400, 32, 0 );
for ( int r = 0; r < 256; r += 16 ) {
for ( int g = 0; g < 256; g += 8 ) {
for ( int b = 0; b < 256; b += 8 ) {
auto pixel = 0xFF000000 + ( r << 16 ) + ( g << 8 ) + ( b );
auto paletteEntry = getPaletteEntry( pixel );
mPalette[ paletteEntry ] = pixel;
}
}
}
#ifdef __EMSCRIPTEN__
enterFullScreenMode();
#endif
}
void CRenderer::sleep(long ms) {
#ifndef __EMSCRIPTEN__
SDL_Delay(33);
#endif
}
void CRenderer::handleSystemEvents() {
SDL_Event event;
const static FixP delta{2};
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
#ifndef __EMSCRIPTEN__
exit(0);
#endif
}
if (event.type == SDL_KEYDOWN) {
switch (event.key.keysym.sym) {
case SDLK_ESCAPE:
exit(0);
mCached = false;
break;
case SDLK_SPACE:
mBufferedCommand = Knights::kUseCurrentItemInInventoryCommand;
mCached = false;
break;
case SDLK_q:
mBufferedCommand = Knights::kPickItemCommand;
mCached = false;
break;
case SDLK_a:
mBufferedCommand = Knights::kDropItemCommand;
mCached = false;
break;
case SDLK_PLUS:
mBufferedCommand = Knights::kCycleRightInventoryCommand;
mCached = false;
break;
case SDLK_MINUS:
mBufferedCommand = Knights::kCycleRightInventoryCommand;
mCached = false;
break;
case SDLK_LEFT:
mBufferedCommand = Knights::kTurnPlayerLeftCommand;
mCached = false;
break;
case SDLK_RIGHT:
mBufferedCommand = Knights::kTurnPlayerRightCommand;
mCached = false;
break;
case SDLK_UP:
mBufferedCommand = Knights::kMovePlayerForwardCommand;
mCached = false;
break;
case SDLK_DOWN:
mBufferedCommand = Knights::kMovePlayerBackwardCommand;
mCached = false;
break;
case SDLK_d:
case SDLK_s:
drawZBuffer = (event.key.keysym.sym == SDLK_a );
mCached = false;
break;
case SDLK_z:
mBufferedCommand = Knights::kStrafeLeftCommand;
mCached = false;
break;
case SDLK_x:
mBufferedCommand = Knights::kStrafeRightCommand;
mCached = false;
break;
default:
return;
}
}
}
}
void CRenderer::putRaw(int16_t x, int16_t y, uint32_t pixel) {
if ( x < 0 || x >= 256 || y < 0 || y >= 128 ) {
return;
}
mBuffer[ (320 * y ) + x ] = pixel;
}
void CRenderer::flip() {
for ( int y = 0; y < 200; ++y ) {
for ( int x = 0; x < 320; ++x ) {
SDL_Rect rect;
rect.x = 2 * x;
rect.y = 2 * y;
rect.w = 2;
rect.h = 2;
auto pixel = drawZBuffer ? static_cast<uint8_t >(mDepthBuffer[ (320 * y) + x ]) : mPalette[ mBuffer[ (320 * y ) + x ] ];
SDL_FillRect(video, &rect, SDL_MapRGB(video->format, ((pixel & 0x000000FF)), ((pixel & 0x0000FF00) >> 8),
((pixel & 0x00FF0000) >> 16)));
}
}
SDL_Flip(video);
}
void CRenderer::clear() {
SDL_FillRect(video, nullptr, 0);
}
}
|
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <utility>
#include <functional>
#include <memory>
#include <algorithm>
#include <iostream>
#include <map>
#include <chrono>
#include <sg14/fixed_point>
#include <EASTL/vector.h>
#include <EASTL/array.h>
using eastl::vector;
using eastl::array;
using namespace std::chrono;
using sg14::fixed_point;
#include "RasterizerCommon.h"
#include "RaycastCommon.h"
#include "Vec2i.h"
#include "IMapElement.h"
#include "CTeam.h"
#include "CItem.h"
#include "CActor.h"
#include "CGameDelegate.h"
#include "CMap.h"
#include "IRenderer.h"
#include "IFileLoaderDelegate.h"
#include "CGame.h"
#include "NativeBitmap.h"
#include "RasterizerCommon.h"
#include "CRenderer.h"
#include <SDL/SDL.h>
#include <SDL/SDL_mixer.h>
#include <cmath>
#include "NativeBitmap.h"
#include "LoadPNG.h"
#ifdef __EMSCRIPTEN__
#include <emscripten/html5.h>
#endif
namespace odb {
bool drawZBuffer = false;
SDL_Surface *video;
#ifdef __EMSCRIPTEN__
void enterFullScreenMode() {
EmscriptenFullscreenStrategy s;
memset(&s, 0, sizeof(s));
s.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_ASPECT;
s.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_NONE;
s.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
emscripten_enter_soft_fullscreen(0, &s);
}
#endif
CRenderer::CRenderer() {
SDL_Init( SDL_INIT_EVERYTHING );
video = SDL_SetVideoMode( 640, 400, 32, 0 );
for ( int r = 0; r < 256; r += 16 ) {
for ( int g = 0; g < 256; g += 8 ) {
for ( int b = 0; b < 256; b += 8 ) {
auto pixel = 0xFF000000 + ( r << 16 ) + ( g << 8 ) + ( b );
auto paletteEntry = getPaletteEntry( pixel );
mPalette[ paletteEntry ] = pixel;
}
}
}
#ifdef __EMSCRIPTEN__
enterFullScreenMode();
#endif
}
void CRenderer::sleep(long ms) {
#ifndef __EMSCRIPTEN__
SDL_Delay(33);
#endif
}
void CRenderer::handleSystemEvents() {
SDL_Event event;
const static FixP delta{2};
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
#ifndef __EMSCRIPTEN__
exit(0);
#endif
}
if (event.type == SDL_KEYDOWN) {
switch (event.key.keysym.sym) {
case SDLK_ESCAPE:
exit(0);
mCached = false;
break;
case SDLK_SPACE:
mBufferedCommand = Knights::kUseCurrentItemInInventoryCommand;
mCached = false;
break;
case SDLK_w:
mBufferedCommand = Knights::kPickItemCommand;
mCached = false;
break;
case SDLK_s:
mBufferedCommand = Knights::kDropItemCommand;
mCached = false;
break;
case SDLK_e:
mBufferedCommand = Knights::kCycleRightInventoryCommand;
mCached = false;
break;
case SDLK_q:
mBufferedCommand = Knights::kCycleRightInventoryCommand;
mCached = false;
break;
case SDLK_LEFT:
mBufferedCommand = Knights::kTurnPlayerLeftCommand;
mCached = false;
break;
case SDLK_RIGHT:
mBufferedCommand = Knights::kTurnPlayerRightCommand;
mCached = false;
break;
case SDLK_UP:
mBufferedCommand = Knights::kMovePlayerForwardCommand;
mCached = false;
break;
case SDLK_DOWN:
mBufferedCommand = Knights::kMovePlayerBackwardCommand;
mCached = false;
break;
case SDLK_d:
case SDLK_a:
drawZBuffer = (event.key.keysym.sym == SDLK_a );
mCached = false;
break;
case SDLK_z:
mBufferedCommand = Knights::kStrafeLeftCommand;
mCached = false;
break;
case SDLK_x:
mBufferedCommand = Knights::kStrafeRightCommand;
mCached = false;
break;
default:
return;
}
}
}
}
void CRenderer::putRaw(int16_t x, int16_t y, uint32_t pixel) {
if ( x < 0 || x >= 256 || y < 0 || y >= 128 ) {
return;
}
mBuffer[ (320 * y ) + x ] = pixel;
}
void CRenderer::flip() {
for ( int y = 0; y < 200; ++y ) {
for ( int x = 0; x < 320; ++x ) {
SDL_Rect rect;
rect.x = 2 * x;
rect.y = 2 * y;
rect.w = 2;
rect.h = 2;
auto pixel = drawZBuffer ? static_cast<uint8_t >(mDepthBuffer[ (320 * y) + x ]) : mPalette[ mBuffer[ (320 * y ) + x ] ];
SDL_FillRect(video, &rect, SDL_MapRGB(video->format, ((pixel & 0x000000FF)), ((pixel & 0x0000FF00) >> 8),
((pixel & 0x00FF0000) >> 16)));
}
}
SDL_Flip(video);
}
void CRenderer::clear() {
SDL_FillRect(video, nullptr, 0);
}
}
|
Unify controls, making SDL like the 486 version
|
Unify controls, making SDL like the 486 version
|
C++
|
bsd-2-clause
|
TheFakeMontyOnTheRun/dungeons-of-noudar,TheFakeMontyOnTheRun/dungeons-of-noudar
|
29712f67cc49a15b91e24d87ab1bd5928e0ea3b5
|
chrome/renderer/renderer_main.cc
|
chrome/renderer/renderer_main.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 "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/command_line.h"
#include "base/field_trial.h"
#include "base/histogram.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/platform_thread.h"
#include "base/process_util.h"
#include "base/scoped_nsautorelease_pool.h"
#include "base/stats_counters.h"
#include "base/string_util.h"
#include "base/system_monitor.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_counters.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/logging_chrome.h"
#include "chrome/common/main_function_params.h"
#include "chrome/renderer/renderer_main_platform_delegate.h"
#include "chrome/renderer/render_process.h"
#include "chrome/renderer/render_thread.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#if defined(OS_LINUX)
#include "chrome/app/breakpad_linux.h"
#endif
#if defined(OS_POSIX)
#include <signal.h>
static void SigUSR1Handler(int signal) { }
#endif
// This function provides some ways to test crash and assertion handling
// behavior of the renderer.
static void HandleRendererErrorTestParameters(const CommandLine& command_line) {
// This parameter causes an assertion.
if (command_line.HasSwitch(switches::kRendererAssertTest)) {
DCHECK(false);
}
// This parameter causes a null pointer crash (crash reporter trigger).
if (command_line.HasSwitch(switches::kRendererCrashTest)) {
int* bad_pointer = NULL;
*bad_pointer = 0;
}
if (command_line.HasSwitch(switches::kRendererStartupDialog)) {
#if defined(OS_WIN)
std::wstring title = l10n_util::GetString(IDS_PRODUCT_NAME);
std::wstring message = L"renderer starting with pid: ";
message += IntToWString(base::GetCurrentProcId());
title += L" renderer"; // makes attaching to process easier
::MessageBox(NULL, message.c_str(), title.c_str(),
MB_OK | MB_SETFOREGROUND);
#elif defined(OS_POSIX)
// TODO(playmobil): In the long term, overriding this flag doesn't seem
// right, either use our own flag or open a dialog we can use.
// This is just to ease debugging in the interim.
LOG(WARNING) << "Renderer ("
<< getpid()
<< ") paused waiting for debugger to attach @ pid";
// Install a signal handler so that pause can be woken.
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SigUSR1Handler;
sigaction(SIGUSR1, &sa, NULL);
pause();
#endif // defined(OS_POSIX)
}
}
// mainline routine for running as the Renderer process
int RendererMain(const MainFunctionParams& parameters) {
const CommandLine& parsed_command_line = parameters.command_line_;
base::ScopedNSAutoreleasePool* pool = parameters.autorelease_pool_;
#if defined(OS_LINUX)
// Needs to be called after we have chrome::DIR_USER_DATA.
InitCrashReporter();
#endif
// This function allows pausing execution using the --renderer-startup-dialog
// flag allowing us to attach a debugger.
// Do not move this function down since that would mean we can't easily debug
// whatever occurs before it.
HandleRendererErrorTestParameters(parsed_command_line);
RendererMainPlatformDelegate platform(parameters);
StatsScope<StatsCounterTimer>
startup_timer(chrome::Counters::renderer_main());
// The main message loop of the renderer services doesn't have IO or UI tasks,
// unless in-process-plugins is used.
MessageLoop main_message_loop(RenderProcess::InProcessPlugins() ?
MessageLoop::TYPE_UI : MessageLoop::TYPE_DEFAULT);
std::wstring app_name = chrome::kBrowserAppName;
PlatformThread::SetName(WideToASCII(app_name + L"_RendererMain").c_str());
// Initialize the SystemMonitor
base::SystemMonitor::Start();
platform.PlatformInitialize();
bool no_sandbox = parsed_command_line.HasSwitch(switches::kNoSandbox);
platform.InitSandboxTests(no_sandbox);
// Initialize histogram statistics gathering system.
// Don't create StatisticsRecorder in the single process mode.
scoped_ptr<StatisticsRecorder> statistics;
if (!StatisticsRecorder::WasStarted()) {
statistics.reset(new StatisticsRecorder());
}
// Initialize statistical testing infrastructure.
FieldTrialList field_trial;
// Ensure any field trials in browser are reflected into renderer.
if (parsed_command_line.HasSwitch(switches::kForceFieldTestNameAndValue)) {
std::string persistent(WideToASCII(parsed_command_line.GetSwitchValue(
switches::kForceFieldTestNameAndValue)));
bool ret = field_trial.StringAugmentsState(persistent);
DCHECK(ret);
}
{
RenderProcess render_process;
render_process.set_main_thread(new RenderThread());
bool run_loop = true;
if (!no_sandbox) {
run_loop = platform.EnableSandbox();
}
platform.RunSandboxTests();
startup_timer.Stop(); // End of Startup Time Measurement.
if (run_loop) {
// Load the accelerator table from the browser executable and tell the
// message loop to use it when translating messages.
if (pool) pool->Recycle();
MessageLoop::current()->Run();
}
}
platform.PlatformUninitialize();
return 0;
}
|
// 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 "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/command_line.h"
#include "base/field_trial.h"
#include "base/histogram.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/platform_thread.h"
#include "base/process_util.h"
#include "base/scoped_nsautorelease_pool.h"
#include "base/stats_counters.h"
#include "base/string_util.h"
#include "base/system_monitor.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_counters.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/logging_chrome.h"
#include "chrome/common/main_function_params.h"
#include "chrome/renderer/renderer_main_platform_delegate.h"
#include "chrome/renderer/render_process.h"
#include "chrome/renderer/render_thread.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#if defined(OS_LINUX)
#include "chrome/app/breakpad_linux.h"
#endif
#if defined(OS_POSIX)
#include <signal.h>
static void SigUSR1Handler(int signal) { }
#endif
// This function provides some ways to test crash and assertion handling
// behavior of the renderer.
static void HandleRendererErrorTestParameters(const CommandLine& command_line) {
// This parameter causes an assertion.
if (command_line.HasSwitch(switches::kRendererAssertTest)) {
DCHECK(false);
}
// This parameter causes a null pointer crash (crash reporter trigger).
if (command_line.HasSwitch(switches::kRendererCrashTest)) {
int* bad_pointer = NULL;
*bad_pointer = 0;
}
if (command_line.HasSwitch(switches::kRendererStartupDialog)) {
#if defined(OS_WIN)
std::wstring title = l10n_util::GetString(IDS_PRODUCT_NAME);
std::wstring message = L"renderer starting with pid: ";
message += IntToWString(base::GetCurrentProcId());
title += L" renderer"; // makes attaching to process easier
::MessageBox(NULL, message.c_str(), title.c_str(),
MB_OK | MB_SETFOREGROUND);
#elif defined(OS_POSIX)
// TODO(playmobil): In the long term, overriding this flag doesn't seem
// right, either use our own flag or open a dialog we can use.
// This is just to ease debugging in the interim.
LOG(WARNING) << "Renderer ("
<< getpid()
<< ") paused waiting for debugger to attach @ pid";
// Install a signal handler so that pause can be woken.
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SigUSR1Handler;
sigaction(SIGUSR1, &sa, NULL);
pause();
#endif // defined(OS_POSIX)
}
}
// mainline routine for running as the Renderer process
int RendererMain(const MainFunctionParams& parameters) {
const CommandLine& parsed_command_line = parameters.command_line_;
base::ScopedNSAutoreleasePool* pool = parameters.autorelease_pool_;
#if defined(OS_LINUX)
// Needs to be called after we have chrome::DIR_USER_DATA.
InitCrashReporter();
#endif
// This function allows pausing execution using the --renderer-startup-dialog
// flag allowing us to attach a debugger.
// Do not move this function down since that would mean we can't easily debug
// whatever occurs before it.
HandleRendererErrorTestParameters(parsed_command_line);
RendererMainPlatformDelegate platform(parameters);
StatsScope<StatsCounterTimer>
startup_timer(chrome::Counters::renderer_main());
// The main message loop of the renderer services doesn't have IO or UI tasks,
// unless in-process-plugins is used.
MessageLoop main_message_loop(RenderProcess::InProcessPlugins() ?
MessageLoop::TYPE_UI : MessageLoop::TYPE_DEFAULT);
std::wstring app_name = chrome::kBrowserAppName;
PlatformThread::SetName(WideToASCII(app_name + L"_RendererMain").c_str());
// Initialize the SystemMonitor
base::SystemMonitor::Start();
platform.PlatformInitialize();
bool no_sandbox = parsed_command_line.HasSwitch(switches::kNoSandbox);
platform.InitSandboxTests(no_sandbox);
// Initialize histogram statistics gathering system.
// Don't create StatisticsRecorder in the single process mode.
scoped_ptr<StatisticsRecorder> statistics;
if (!StatisticsRecorder::WasStarted()) {
statistics.reset(new StatisticsRecorder());
}
// Initialize statistical testing infrastructure.
FieldTrialList field_trial;
// Ensure any field trials in browser are reflected into renderer.
if (parsed_command_line.HasSwitch(switches::kForceFieldTestNameAndValue)) {
std::string persistent(WideToASCII(parsed_command_line.GetSwitchValue(
switches::kForceFieldTestNameAndValue)));
bool ret = field_trial.StringAugmentsState(persistent);
DCHECK(ret);
}
{
RenderProcess render_process;
render_process.set_main_thread(new RenderThread());
bool run_loop = true;
if (!no_sandbox) {
run_loop = platform.EnableSandbox();
}
platform.RunSandboxTests();
startup_timer.Stop(); // End of Startup Time Measurement.
if (run_loop) {
if (pool)
pool->Recycle();
MessageLoop::current()->Run();
}
}
platform.PlatformUninitialize();
return 0;
}
|
Remove a comment that doesn't make any sense.
|
Remove a comment that doesn't make any sense.
Review URL: http://codereview.chromium.org/159509
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@21850 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
ondra-novak/chromium.src,Just-D/chromium-1,hujiajie/pa-chromium,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,anirudhSK/chromium,markYoungH/chromium.src,axinging/chromium-crosswalk,hujiajie/pa-chromium,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,hujiajie/pa-chromium,ChromiumWebApps/chromium,patrickm/chromium.src,Fireblend/chromium-crosswalk,mogoweb/chromium-crosswalk,dushu1203/chromium.src,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,rogerwang/chromium,ondra-novak/chromium.src,M4sse/chromium.src,timopulkkinen/BubbleFish,chuan9/chromium-crosswalk,littlstar/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,ondra-novak/chromium.src,Just-D/chromium-1,dednal/chromium.src,nacl-webkit/chrome_deps,fujunwei/chromium-crosswalk,zcbenz/cefode-chromium,axinging/chromium-crosswalk,rogerwang/chromium,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,Chilledheart/chromium,dednal/chromium.src,zcbenz/cefode-chromium,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,fujunwei/chromium-crosswalk,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,nacl-webkit/chrome_deps,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk,keishi/chromium,hgl888/chromium-crosswalk,ltilve/chromium,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,M4sse/chromium.src,junmin-zhu/chromium-rivertrail,jaruba/chromium.src,dednal/chromium.src,keishi/chromium,anirudhSK/chromium,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,dednal/chromium.src,ChromiumWebApps/chromium,Chilledheart/chromium,pozdnyakov/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,keishi/chromium,timopulkkinen/BubbleFish,dednal/chromium.src,hujiajie/pa-chromium,ltilve/chromium,nacl-webkit/chrome_deps,markYoungH/chromium.src,markYoungH/chromium.src,robclark/chromium,littlstar/chromium.src,anirudhSK/chromium,rogerwang/chromium,rogerwang/chromium,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,hujiajie/pa-chromium,markYoungH/chromium.src,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,junmin-zhu/chromium-rivertrail,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,jaruba/chromium.src,robclark/chromium,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,axinging/chromium-crosswalk,axinging/chromium-crosswalk,dednal/chromium.src,pozdnyakov/chromium-crosswalk,Chilledheart/chromium,Chilledheart/chromium,zcbenz/cefode-chromium,ondra-novak/chromium.src,pozdnyakov/chromium-crosswalk,bright-sparks/chromium-spacewalk,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,robclark/chromium,littlstar/chromium.src,chuan9/chromium-crosswalk,junmin-zhu/chromium-rivertrail,junmin-zhu/chromium-rivertrail,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,mogoweb/chromium-crosswalk,M4sse/chromium.src,jaruba/chromium.src,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,littlstar/chromium.src,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,jaruba/chromium.src,dednal/chromium.src,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,keishi/chromium,TheTypoMaster/chromium-crosswalk,ltilve/chromium,dednal/chromium.src,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,patrickm/chromium.src,dushu1203/chromium.src,keishi/chromium,patrickm/chromium.src,PeterWangIntel/chromium-crosswalk,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,Jonekee/chromium.src,timopulkkinen/BubbleFish,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,axinging/chromium-crosswalk,pozdnyakov/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,pozdnyakov/chromium-crosswalk,ltilve/chromium,anirudhSK/chromium,jaruba/chromium.src,axinging/chromium-crosswalk,Jonekee/chromium.src,nacl-webkit/chrome_deps,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,Jonekee/chromium.src,keishi/chromium,bright-sparks/chromium-spacewalk,M4sse/chromium.src,chuan9/chromium-crosswalk,junmin-zhu/chromium-rivertrail,ltilve/chromium,krieger-od/nwjs_chromium.src,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,rogerwang/chromium,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,zcbenz/cefode-chromium,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,robclark/chromium,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,patrickm/chromium.src,timopulkkinen/BubbleFish,Jonekee/chromium.src,mogoweb/chromium-crosswalk,hujiajie/pa-chromium,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,Jonekee/chromium.src,anirudhSK/chromium,rogerwang/chromium,hujiajie/pa-chromium,pozdnyakov/chromium-crosswalk,littlstar/chromium.src,markYoungH/chromium.src,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,junmin-zhu/chromium-rivertrail,Chilledheart/chromium,littlstar/chromium.src,M4sse/chromium.src,patrickm/chromium.src,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,anirudhSK/chromium,ltilve/chromium,Chilledheart/chromium,Fireblend/chromium-crosswalk,Jonekee/chromium.src,M4sse/chromium.src,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,Just-D/chromium-1,ChromiumWebApps/chromium,junmin-zhu/chromium-rivertrail,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,hujiajie/pa-chromium,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,jaruba/chromium.src,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,junmin-zhu/chromium-rivertrail,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,keishi/chromium,fujunwei/chromium-crosswalk,ltilve/chromium,dushu1203/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk,Just-D/chromium-1,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,pozdnyakov/chromium-crosswalk,mogoweb/chromium-crosswalk,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,zcbenz/cefode-chromium,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,ltilve/chromium,Fireblend/chromium-crosswalk,nacl-webkit/chrome_deps,dushu1203/chromium.src,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,keishi/chromium,hgl888/chromium-crosswalk,markYoungH/chromium.src,mogoweb/chromium-crosswalk,timopulkkinen/BubbleFish,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,M4sse/chromium.src,fujunwei/chromium-crosswalk,patrickm/chromium.src,ondra-novak/chromium.src,robclark/chromium,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,dushu1203/chromium.src,robclark/chromium,mohamed--abdel-maksoud/chromium.src,hujiajie/pa-chromium,zcbenz/cefode-chromium,Jonekee/chromium.src,fujunwei/chromium-crosswalk,rogerwang/chromium,junmin-zhu/chromium-rivertrail,keishi/chromium,nacl-webkit/chrome_deps,littlstar/chromium.src,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,jaruba/chromium.src,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,timopulkkinen/BubbleFish,robclark/chromium,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,Chilledheart/chromium,robclark/chromium,zcbenz/cefode-chromium,hgl888/chromium-crosswalk,anirudhSK/chromium,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,robclark/chromium,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,hujiajie/pa-chromium,anirudhSK/chromium,axinging/chromium-crosswalk,dednal/chromium.src,anirudhSK/chromium,patrickm/chromium.src,bright-sparks/chromium-spacewalk,timopulkkinen/BubbleFish,zcbenz/cefode-chromium,Jonekee/chromium.src,rogerwang/chromium,markYoungH/chromium.src,zcbenz/cefode-chromium,nacl-webkit/chrome_deps,markYoungH/chromium.src,M4sse/chromium.src,robclark/chromium,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,patrickm/chromium.src,ltilve/chromium,M4sse/chromium.src,Chilledheart/chromium,dushu1203/chromium.src,rogerwang/chromium,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,hujiajie/pa-chromium,anirudhSK/chromium,crosswalk-project/chromium-crosswalk-efl,Just-D/chromium-1,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,timopulkkinen/BubbleFish,fujunwei/chromium-crosswalk,mogoweb/chromium-crosswalk,keishi/chromium,hgl888/chromium-crosswalk,rogerwang/chromium,keishi/chromium,nacl-webkit/chrome_deps,krieger-od/nwjs_chromium.src,jaruba/chromium.src,markYoungH/chromium.src,junmin-zhu/chromium-rivertrail
|
7dc965c3f88cbc75f0768ed015b02cb583751281
|
MMLoader/Inject.cpp
|
MMLoader/Inject.cpp
|
#include "StdAfx.h"
#include "Inject.h"
#include "Util.h"
// Ripped from Oblivion Script Extender
// http://obse.silverlock.org/
// The sordid thread-suspending logic in DoInjectDLL is my own dismal contribution
extern BOOL ToggleProcessThreads(DWORD dwOwnerPID, bool suspend);
Inject::Inject(void)
{
}
Inject::~Inject(void)
{
}
bool Inject::InjectDLL(DWORD processId, const char * dllPath, bool processWasLaunched)
{
bool result = false;
// wrap DLL injection in SEH, if it crashes print a message
__try {
result = DoInjectDLL(processId, dllPath, processWasLaunched);
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
_injectError = "DLL injection failed. In most cases, this is caused by an overly paranoid software firewall or antivirus package. Disabling either of these may solve the problem.";
result = false;
}
return result;
}
/*** jmp hook layout
* E9 ## ## ## ## jmp LoadLibraryA
* offset = LoadLibraryA - (base + 5)
* <string> name of function
***/
typedef unsigned int UInt32;
typedef unsigned char UInt8;
bool Inject::DoInjectDLL(DWORD processId, const char * dllPath, bool processWasLaunched)
{
bool result = false; // assume failure
HANDLE process = OpenProcess(
PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, FALSE, processId);
if(process)
{
UInt32 hookBase = (UInt32)VirtualAllocEx(process, NULL, 8192, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
if(hookBase)
{
// safe because kernel32 is loaded at the same address in all processes
// (can change across restarts)
UInt32 loadLibraryAAddr = (UInt32)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
//_MESSAGE("hookBase = %08X", hookBase);
//_MESSAGE("loadLibraryAAddr = %08X", loadLibraryAAddr);
SIZE_T bytesWritten;
WriteProcessMemory(process, (LPVOID)(hookBase + 5), dllPath, strlen(dllPath) + 1, &bytesWritten);
UInt8 hookCode[5];
hookCode[0] = 0xE9;
*((UInt32 *)&hookCode[1]) = loadLibraryAAddr - (hookBase + 5);
WriteProcessMemory(process, (LPVOID)(hookBase), hookCode, sizeof(hookCode), &bytesWritten);
// yet another race...creating this thread sometimes fails, usually when loader is "cold" and hasn't been started
// recently. not sure a retry loop will help (and may need to sleep here)
int hook_thread_attempts = 3;
HANDLE hookThread = NULL;
bool hookThreadValid = false;
while (!hookThreadValid && hook_thread_attempts > 0) {
hook_thread_attempts--;
hookThread = CreateRemoteThread(process, NULL, 0, (LPTHREAD_START_ROUTINE)hookBase, (void *)(hookBase + 5), 0, NULL);
hookThreadValid = hookThread && hookThread != INVALID_HANDLE_VALUE;
if (!hookThreadValid) {
Util::Log("Failed hook thread (%d more attempts)", hook_thread_attempts);
}
}
if (hookThreadValid)
{
ResumeThread(hookThread);
// So, if we are attaching to an existing process, all of its threads should have already been suspended by the loader.
// however, its quite possible that we suspended the threads inside a critical section and now our hook thread will deadlock.
// so what we'll do is wait for a bit on the hook thread, and if we timeout, resume all threads in the target process for a brief period,
// then resuspend them. Then resume our hook thread and try again. Do this some number of times and hopefully we'll be successful.
// Its basically a jackhammer, and it can fail (especially if our hook thread does a bunch of slow initialization stuff), but it
// usually succeeds.
DWORD waitTimeout;
int MaxHookAttempts;
if (processWasLaunched) {
waitTimeout = INFINITE;
MaxHookAttempts = 1;
}
else {
waitTimeout = 500;
MaxHookAttempts = 25;
}
int attempt = 0;
for (attempt = 0; !result && attempt < MaxHookAttempts; ++attempt) {
switch(WaitForSingleObject(hookThread, waitTimeout)) // g_options.m_threadTimeout
{
case WAIT_OBJECT_0:
Util::Log("Hook Thread complete\n");
result = true;
break;
case WAIT_ABANDONED:
_injectError = "Hook Thread WAIT_ABANDONED";
break;
case WAIT_TIMEOUT:
// Resume all threads, sleep for a bit, then suspend them all again. Then resume hook thread and retry.
Util::Log("timeout, retrying\n");
ToggleProcessThreads(processId,false);
Sleep(0);
ToggleProcessThreads(processId,true);
ResumeThread(hookThread);
break;
case WAIT_FAILED:
_injectError = "Hook Thread WAIT_FAILED";
break;
default:
_injectError = "Hook Thread Unknown wait state";
}
}
if (!result) {
_injectError = "Unable to complete hook thread after several attempts";
}
CloseHandle(hookThread);
}
else {
//http://stackoverflow.com/questions/3006229/get-a-text-from-the-error-code-returns-from-the-getlasterror-function
DWORD dwLastError = ::GetLastError();
const DWORD BufSize = 256;
TCHAR lpBuffer[BufSize] = _T("?");
if(dwLastError != 0) // Don't want to see a "operation done successfully" error ;-)
::FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, // Its a system error
NULL, // No string to be formatted needed
dwLastError, // Hey Windows: Please explain this error!
MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), // Do it in the standard language
lpBuffer, // Put the message here
BufSize-1, // Number of bytes to store the message
NULL);
_injectError = string("CreateRemoteThread failed: ") + string(lpBuffer);
}
VirtualFreeEx(process, (LPVOID)hookBase, 8192, MEM_RELEASE);
}
else
_injectError = "Process::InstallHook: couldn't allocate memory in target process";
CloseHandle(process);
}
else
_injectError = "Process::InstallHook: couldn't get process handle. You may need to run MMLoader as an adminstrator.";
return result;
}
|
#include "StdAfx.h"
#include "Inject.h"
#include "Util.h"
// Ripped from Oblivion Script Extender
// http://obse.silverlock.org/
// The sordid thread-suspending logic in DoInjectDLL is my own dismal contribution
extern BOOL ToggleProcessThreads(DWORD dwOwnerPID, bool suspend);
Inject::Inject(void)
{
}
Inject::~Inject(void)
{
}
bool Inject::InjectDLL(DWORD processId, const char * dllPath, bool processWasLaunched)
{
bool result = false;
// wrap DLL injection in SEH, if it crashes print a message
__try {
result = DoInjectDLL(processId, dllPath, processWasLaunched);
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
_injectError = "DLL injection failed. In most cases, this is caused by an overly paranoid software firewall or antivirus package. Disabling either of these may solve the problem.";
result = false;
}
return result;
}
/*** jmp hook layout
* E9 ## ## ## ## jmp LoadLibraryA
* offset = LoadLibraryA - (base + 5)
* <string> name of function
***/
typedef unsigned int UInt32;
typedef unsigned char UInt8;
bool Inject::DoInjectDLL(DWORD processId, const char * dllPath, bool processWasLaunched)
{
bool result = false; // assume failure
HANDLE process = OpenProcess(
PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, FALSE, processId);
if(process)
{
UInt32 hookBase = (UInt32)VirtualAllocEx(process, NULL, 8192, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
if(hookBase)
{
// safe because kernel32 is loaded at the same address in all processes
// (can change across restarts)
UInt32 loadLibraryAAddr = (UInt32)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
//_MESSAGE("hookBase = %08X", hookBase);
//_MESSAGE("loadLibraryAAddr = %08X", loadLibraryAAddr);
SIZE_T bytesWritten;
WriteProcessMemory(process, (LPVOID)(hookBase + 5), dllPath, strlen(dllPath) + 1, &bytesWritten);
UInt8 hookCode[5];
hookCode[0] = 0xE9;
*((UInt32 *)&hookCode[1]) = loadLibraryAAddr - (hookBase + 5);
WriteProcessMemory(process, (LPVOID)(hookBase), hookCode, sizeof(hookCode), &bytesWritten);
// yet another race...creating this thread sometimes fails, usually when loader is "cold" and hasn't been started
// recently. use the resume/suspend trick (described below) to increase the odds that it will work.
int hook_thread_attempts = 3;
HANDLE hookThread = NULL;
bool hookThreadValid = false;
while (!hookThreadValid && hook_thread_attempts > 0) {
hook_thread_attempts--;
hookThread = CreateRemoteThread(process, NULL, 0, (LPTHREAD_START_ROUTINE)hookBase, (void *)(hookBase + 5), 0, NULL);
hookThreadValid = hookThread && hookThread != INVALID_HANDLE_VALUE;
if (!hookThreadValid) {
Util::Log("Failed to create hook thread (%d more attempts)\n", hook_thread_attempts);
ToggleProcessThreads(processId, false);
Sleep(0);
ToggleProcessThreads(processId, true);
}
}
if (hookThreadValid)
{
ResumeThread(hookThread);
// So, if we are attaching to an existing process, all of its threads should have already been suspended by the loader.
// however, its quite possible that we suspended the threads inside a critical section and now our hook thread will deadlock.
// so what we'll do is wait for a bit on the hook thread, and if we timeout, resume all threads in the target process for a brief period,
// then resuspend them. Then resume our hook thread and try again. Do this some number of times and hopefully we'll be successful.
// Its basically a jackhammer, and it can fail (especially if our hook thread does a bunch of slow initialization stuff), but it
// usually succeeds.
DWORD waitTimeout;
int MaxHookAttempts;
if (processWasLaunched) {
waitTimeout = INFINITE;
MaxHookAttempts = 1;
}
else {
waitTimeout = 500;
MaxHookAttempts = 25;
}
int attempt = 0;
for (attempt = 0; !result && attempt < MaxHookAttempts; ++attempt) {
switch(WaitForSingleObject(hookThread, waitTimeout)) // g_options.m_threadTimeout
{
case WAIT_OBJECT_0:
Util::Log("Hook Thread complete\n");
result = true;
break;
case WAIT_ABANDONED:
_injectError = "Hook Thread WAIT_ABANDONED";
break;
case WAIT_TIMEOUT:
// Resume all threads, sleep for a bit, then suspend them all again. Then resume hook thread and retry.
Util::Log("timeout, retrying\n");
ToggleProcessThreads(processId,false);
Sleep(0);
ToggleProcessThreads(processId,true);
ResumeThread(hookThread);
break;
case WAIT_FAILED:
_injectError = "Hook Thread WAIT_FAILED";
break;
default:
_injectError = "Hook Thread Unknown wait state";
}
}
if (!result) {
_injectError = "Unable to complete hook thread after several attempts";
}
CloseHandle(hookThread);
}
else {
//http://stackoverflow.com/questions/3006229/get-a-text-from-the-error-code-returns-from-the-getlasterror-function
DWORD dwLastError = ::GetLastError();
const DWORD BufSize = 256;
TCHAR lpBuffer[BufSize] = _T("?");
if(dwLastError != 0) // Don't want to see a "operation done successfully" error ;-)
::FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, // Its a system error
NULL, // No string to be formatted needed
dwLastError, // Hey Windows: Please explain this error!
MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), // Do it in the standard language
lpBuffer, // Put the message here
BufSize-1, // Number of bytes to store the message
NULL);
_injectError = string("CreateRemoteThread failed: ") + string(lpBuffer);
}
VirtualFreeEx(process, (LPVOID)hookBase, 8192, MEM_RELEASE);
}
else
_injectError = "Process::InstallHook: couldn't allocate memory in target process";
CloseHandle(process);
}
else
_injectError = "Process::InstallHook: couldn't get process handle. You may need to run MMLoader as an adminstrator.";
return result;
}
|
use the resume/suspend trick to in the case where CreateRemoteThread fails
|
Fix(loader): use the resume/suspend trick to in the case where CreateRemoteThread fails
- This appeared to fix the issue on at least one occassion
|
C++
|
lgpl-2.1
|
jmquigs/ModelMod,jmquigs/ModelMod,jmquigs/ModelMod,jmquigs/ModelMod
|
b0c1bdf5d366afc47d4a94cebc00fd2912128929
|
chrome_frame/test/reliability/run_all_unittests.cc
|
chrome_frame/test/reliability/run_all_unittests.cc
|
// Copyright (c) 2006-2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome_frame/test/reliability/reliability_test_suite.h"
#include "base/command_line.h"
#include "chrome/common/chrome_paths.h"
#include "chrome_frame/test/chrome_frame_test_utils.h"
#include "chrome_frame/test_utils.h"
#include "chrome_frame/utils.h"
static const char kRegisterDllFlag[] = "register";
int main(int argc, char **argv) {
// If --register is passed, then we need to ensure that Chrome Frame is
// registered before starting up the reliability tests.
CommandLine::Init(argc, argv);
CommandLine* cmd_line = CommandLine::ForCurrentProcess();
DCHECK(cmd_line);
// We create this slightly early as it is the one who instantiates THE
// AtExitManager which some of the other stuff below relies on.
ReliabilityTestSuite test_suite(argc, argv);
SetConfigBool(kChromeFrameHeadlessMode, true);
base::ProcessHandle crash_service = chrome_frame_test::StartCrashService();
int result = -1;
if (cmd_line->HasSwitch(kRegisterDllFlag)) {
std::wstring dll_path = cmd_line->GetSwitchValueNative(kRegisterDllFlag);
// Run() must be called within the scope of the ScopedChromeFrameRegistrar
// to ensure that the correct DLL remains registered during the tests.
ScopedChromeFrameRegistrar scoped_chrome_frame_registrar(
dll_path, ScopedChromeFrameRegistrar::SYSTEM_LEVEL);
result = test_suite.Run();
} else {
result = test_suite.Run();
}
DeleteConfigValue(kChromeFrameHeadlessMode);
if (crash_service)
base::KillProcess(crash_service, 0, false);
return result;
}
|
// Copyright (c) 2006-2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome_frame/test/reliability/reliability_test_suite.h"
#include "base/command_line.h"
#include "chrome/common/chrome_paths.h"
#include "chrome_frame/test/chrome_frame_test_utils.h"
#include "chrome_frame/test_utils.h"
#include "chrome_frame/utils.h"
static const char kRegisterDllFlag[] = "register";
int main(int argc, char **argv) {
// We create this slightly early as it is the one who instantiates THE
// AtExitManager which some of the other stuff below relies on.
ReliabilityTestSuite test_suite(argc, argv);
SetConfigBool(kChromeFrameHeadlessMode, true);
base::ProcessHandle crash_service = chrome_frame_test::StartCrashService();
int result = -1;
// If --register is passed, then we need to ensure that Chrome Frame is
// registered before starting up the reliability tests.
CommandLine* cmd_line = CommandLine::ForCurrentProcess();
DCHECK(cmd_line);
if (!cmd_line) {
NOTREACHED() << "CommandLine object not initialized";
return result;
}
if (cmd_line->HasSwitch(kRegisterDllFlag)) {
std::wstring dll_path = cmd_line->GetSwitchValueNative(kRegisterDllFlag);
// Run() must be called within the scope of the ScopedChromeFrameRegistrar
// to ensure that the correct DLL remains registered during the tests.
ScopedChromeFrameRegistrar scoped_chrome_frame_registrar(
dll_path, ScopedChromeFrameRegistrar::SYSTEM_LEVEL);
result = test_suite.Run();
} else {
result = test_suite.Run();
}
DeleteConfigValue(kChromeFrameHeadlessMode);
if (crash_service)
base::KillProcess(crash_service, 0, false);
return result;
}
|
Fix a crash in the chrome frame relaibility test suite which occurs while accessing a deleted CommandLine object. The test suite on startup initializes the command line. It then initializes the gtest TestSuite class which also initializes a new instance of the CommandLine object. This ends up deleting the CommandLine instance initialized before leading to a crash when this is accessed.
|
Fix a crash in the chrome frame relaibility test suite which occurs while accessing a deleted
CommandLine object. The test suite on startup initializes the command line. It then initializes
the gtest TestSuite class which also initializes a new instance of the CommandLine object. This
ends up deleting the CommandLine instance initialized before leading to a crash when this is
accessed.
Fix is to remove the CommandLine initialization code from the test suite.
Fixes bug http://code.google.com/p/chromium/issues/detail?id=77984
BUG=77984
TEST=ChromeFrame relaibility tests should now run correctly.
TBR=amit
Review URL: http://codereview.chromium.org/6781002
git-svn-id: http://src.chromium.org/svn/trunk/src@80060 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Former-commit-id: 7b9ed4c994aa9f4b41eff988450d72ad51aadef7
|
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
|
69ac786a0ce98f14bcb1dbe4de27a7eb52d60be3
|
tests/unit/fem/test_datacollection.cpp
|
tests/unit/fem/test_datacollection.cpp
|
// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "mfem.hpp"
#include "unit_tests.hpp"
#include <stdio.h>
#ifndef _WIN32
#include <unistd.h> // rmdir
#else
#include <direct.h> // _rmdir
#define rmdir(dir) _rmdir(dir)
#endif
using namespace mfem;
TEST_CASE("Save and load from collections", "[DataCollection]")
{
SECTION("VisIt data files")
{
std::cout<<"Testing VisIt data files"<<std::endl;
//Set up a small mesh and a couple of grid function on that mesh
Mesh mesh = Mesh::MakeCartesian2D(2, 3, Element::QUADRILATERAL, 0, 2.0, 3.0);
FiniteElementCollection *fec = new LinearFECollection;
FiniteElementSpace *fespace = new FiniteElementSpace(&mesh, fec);
GridFunction *u = new GridFunction(fespace);
GridFunction *v = new GridFunction(fespace);
int N = u->Size();
for (int i = 0; i < N; ++i)
{
(*u)(i) = double(i);
(*v)(i) = double(N - i - 1);
}
int intOrder = 3;
QuadratureSpace *qspace = new QuadratureSpace(&mesh, intOrder);
QuadratureFunction *qs = new QuadratureFunction(qspace, 1);
QuadratureFunction *qv = new QuadratureFunction(qspace, 2);
int Nq = qs->Size();
for (int i = 0; i < Nq; ++i)
{
(*qs)(i) = double(i);
(*qv)(2*i+0) = double(i);
(*qv)(2*i+1) = double(Nq - i - 1);
}
SECTION("Uncompressed MFEM format")
{
std::cout<<"Testing uncompressed MFEM format"<<std::endl;
//Collect the mesh and grid functions into a DataCollection and test that they got in there
VisItDataCollection dc("base", &mesh);
dc.RegisterField("u", u);
dc.RegisterField("v", v);
dc.RegisterQField("qs",qs);
dc.RegisterQField("qv",qv);
dc.SetCycle(5);
dc.SetTime(8.0);
REQUIRE(dc.GetMesh() == &mesh);
bool has_u = dc.HasField("u");
REQUIRE(has_u);
bool has_v = dc.HasField("v");
REQUIRE(has_v);
bool has_qs = dc.HasQField("qs");
REQUIRE(has_qs);
bool has_qv = dc.HasQField("qv");
REQUIRE(has_qv);
REQUIRE(dc.GetCycle() == 5);
REQUIRE(dc.GetTime() == 8.0);
//Save the DataCollection and load it into a new DataCollection for comparison
dc.SetPadDigits(5);
dc.Save();
VisItDataCollection dc_new("base");
dc_new.SetPadDigits(5);
dc_new.Load(dc.GetCycle());
Mesh* mesh_new = dc_new.GetMesh();
GridFunction *u_new = dc_new.GetField("u");
GridFunction *v_new = dc_new.GetField("v");
QuadratureFunction *qs_new = dc_new.GetQField("qs");
QuadratureFunction *qv_new = dc_new.GetQField("qv");
REQUIRE(mesh_new);
REQUIRE(u_new);
REQUIRE(v_new);
REQUIRE(qs_new);
REQUIRE(qv_new);
//Compare some collection parameters for old and new
std::string name, name_new;
name = dc.GetCollectionName();
name_new = dc_new.GetCollectionName();
REQUIRE(name == name_new);
REQUIRE(dc.GetCycle() == dc_new.GetCycle());
REQUIRE(dc.GetTime() == dc_new.GetTime());
//Compare the new new mesh with the old mesh
//(Just a basic comparison here, a full comparison should be done in Mesh unit testing)
REQUIRE(mesh.Dimension() == mesh_new->Dimension());
REQUIRE(mesh.SpaceDimension() == mesh_new->SpaceDimension());
Vector vert, vert_diff;
mesh.GetVertices(vert);
mesh_new->GetVertices(vert_diff);
vert_diff -= vert;
REQUIRE(vert_diff.Normlinf() < 1e-10);
//Compare the old and new grid functions
//(Just a basic comparison here, a full comparison should be done in GridFunction unit testing)
Vector u_diff(*u_new), v_diff(*v_new);
u_diff -= *u;
v_diff -= *v;
REQUIRE(u_diff.Normlinf() < 1e-10);
REQUIRE(v_diff.Normlinf() < 1e-10);
//Compare the old and new quadrature functions
//(Just a basic comparison here, a full comparison should be done in GridFunction unit testing)
Vector qs_diff(*qs_new), qv_diff(*qv_new);
qs_diff -= *qs;
qv_diff -= *qv;
REQUIRE(qs_diff.Normlinf() < 1e-10);
REQUIRE(qv_diff.Normlinf() < 1e-10);
//Cleanup all the files
REQUIRE(remove("base_00005.mfem_root") == 0);
REQUIRE(remove("base_00005/mesh.00000") == 0);
REQUIRE(remove("base_00005/u.00000") == 0);
REQUIRE(remove("base_00005/v.00000") == 0);
REQUIRE(remove("base_00005/qs.00000") == 0);
REQUIRE(remove("base_00005/qv.00000") == 0);
REQUIRE(rmdir("base_00005") == 0);
}
#ifdef MFEM_USE_ZLIB
SECTION("Compressed MFEM format")
{
std::cout<<"Testing compressed MFEM format"<<std::endl;
//Collect the mesh and grid functions into a DataCollection and test that they got in there
VisItDataCollection dc("base", &mesh);
dc.RegisterField("u", u);
dc.RegisterField("v", v);
dc.RegisterQField("qs",qs);
dc.RegisterQField("qv",qv);
dc.SetCycle(5);
dc.SetTime(8.0);
REQUIRE(dc.GetMesh() == &mesh);
bool has_u = dc.HasField("u");
REQUIRE(has_u);
bool has_v = dc.HasField("v");
REQUIRE(has_v);
bool has_qs = dc.HasQField("qs");
REQUIRE(has_qs);
bool has_qv = dc.HasQField("qv");
REQUIRE(has_qv);
REQUIRE(dc.GetCycle() == 5);
REQUIRE(dc.GetTime() == 8.0);
//Save the DataCollection and load it into a new DataCollection for comparison
dc.SetPadDigits(5);
dc.SetCompression(true);
dc.Save();
VisItDataCollection dc_new("base");
dc_new.SetPadDigits(5);
dc_new.Load(dc.GetCycle());
Mesh *mesh_new = dc_new.GetMesh();
GridFunction *u_new = dc_new.GetField("u");
GridFunction *v_new = dc_new.GetField("v");
QuadratureFunction *qs_new = dc_new.GetQField("qs");
QuadratureFunction *qv_new = dc_new.GetQField("qv");
REQUIRE(mesh_new);
REQUIRE(u_new);
REQUIRE(v_new);
REQUIRE(qs_new);
REQUIRE(qv_new);
//Compare some collection parameters for old and new
std::string name, name_new;
name = dc.GetCollectionName();
name_new = dc_new.GetCollectionName();
REQUIRE(name == name_new);
REQUIRE(dc.GetCycle() == dc_new.GetCycle());
REQUIRE(dc.GetTime() == dc_new.GetTime());
//Compare the new new mesh with the old mesh
//(Just a basic comparison here, a full comparison should be done in Mesh unit testing)
REQUIRE(mesh.Dimension() == mesh_new->Dimension());
REQUIRE(mesh.SpaceDimension() == mesh_new->SpaceDimension());
Vector vert, vert_diff;
mesh.GetVertices(vert);
mesh_new->GetVertices(vert_diff);
vert_diff -= vert;
REQUIRE(vert_diff.Normlinf() < 1e-10);
//Compare the old and new grid functions
//(Just a basic comparison here, a full comparison should be done in GridFunction unit testing)
Vector u_diff(*u_new), v_diff(*v_new);
u_diff -= *u;
v_diff -= *v;
REQUIRE(u_diff.Normlinf() < 1e-10);
REQUIRE(v_diff.Normlinf() < 1e-10);
//Compare the old and new quadrature functions
//(Just a basic comparison here, a full comparison should be done in GridFunction unit testing)
Vector qs_diff(*qs_new), qv_diff(*qv_new);
qs_diff -= *qs;
qv_diff -= *qv;
REQUIRE(qs_diff.Normlinf() < 1e-10);
REQUIRE(qv_diff.Normlinf() < 1e-10);
//Cleanup all the files
REQUIRE(remove("base_00005.mfem_root") == 0);
REQUIRE(remove("base_00005/mesh.00000") == 0);
REQUIRE(remove("base_00005/u.00000") == 0);
REQUIRE(remove("base_00005/v.00000") == 0);
REQUIRE(remove("base_00005/qs.00000") == 0);
REQUIRE(remove("base_00005/qv.00000") == 0);
REQUIRE(rmdir("base_00005") == 0);
}
#endif
}
}
|
// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "mfem.hpp"
#include "unit_tests.hpp"
#include "general/tinyxml2.h"
#include <stdio.h>
#ifndef _WIN32
#include <unistd.h> // rmdir
#else
#include <direct.h> // _rmdir
#define rmdir(dir) _rmdir(dir)
#endif
using namespace mfem;
TEST_CASE("Save and load from collections", "[DataCollection]")
{
SECTION("VisIt data files")
{
std::cout<<"Testing VisIt data files"<<std::endl;
//Set up a small mesh and a couple of grid function on that mesh
Mesh mesh = Mesh::MakeCartesian2D(2, 3, Element::QUADRILATERAL, 0, 2.0, 3.0);
FiniteElementCollection *fec = new LinearFECollection;
FiniteElementSpace *fespace = new FiniteElementSpace(&mesh, fec);
GridFunction *u = new GridFunction(fespace);
GridFunction *v = new GridFunction(fespace);
int N = u->Size();
for (int i = 0; i < N; ++i)
{
(*u)(i) = double(i);
(*v)(i) = double(N - i - 1);
}
int intOrder = 3;
QuadratureSpace *qspace = new QuadratureSpace(&mesh, intOrder);
QuadratureFunction *qs = new QuadratureFunction(qspace, 1);
QuadratureFunction *qv = new QuadratureFunction(qspace, 2);
int Nq = qs->Size();
for (int i = 0; i < Nq; ++i)
{
(*qs)(i) = double(i);
(*qv)(2*i+0) = double(i);
(*qv)(2*i+1) = double(Nq - i - 1);
}
SECTION("Uncompressed MFEM format")
{
std::cout<<"Testing uncompressed MFEM format"<<std::endl;
//Collect the mesh and grid functions into a DataCollection and test that they got in there
VisItDataCollection dc("base", &mesh);
dc.RegisterField("u", u);
dc.RegisterField("v", v);
dc.RegisterQField("qs",qs);
dc.RegisterQField("qv",qv);
dc.SetCycle(5);
dc.SetTime(8.0);
REQUIRE(dc.GetMesh() == &mesh);
bool has_u = dc.HasField("u");
REQUIRE(has_u);
bool has_v = dc.HasField("v");
REQUIRE(has_v);
bool has_qs = dc.HasQField("qs");
REQUIRE(has_qs);
bool has_qv = dc.HasQField("qv");
REQUIRE(has_qv);
REQUIRE(dc.GetCycle() == 5);
REQUIRE(dc.GetTime() == 8.0);
//Save the DataCollection and load it into a new DataCollection for comparison
dc.SetPadDigits(5);
dc.Save();
VisItDataCollection dc_new("base");
dc_new.SetPadDigits(5);
dc_new.Load(dc.GetCycle());
Mesh* mesh_new = dc_new.GetMesh();
GridFunction *u_new = dc_new.GetField("u");
GridFunction *v_new = dc_new.GetField("v");
QuadratureFunction *qs_new = dc_new.GetQField("qs");
QuadratureFunction *qv_new = dc_new.GetQField("qv");
REQUIRE(mesh_new);
REQUIRE(u_new);
REQUIRE(v_new);
REQUIRE(qs_new);
REQUIRE(qv_new);
//Compare some collection parameters for old and new
std::string name, name_new;
name = dc.GetCollectionName();
name_new = dc_new.GetCollectionName();
REQUIRE(name == name_new);
REQUIRE(dc.GetCycle() == dc_new.GetCycle());
REQUIRE(dc.GetTime() == dc_new.GetTime());
//Compare the new new mesh with the old mesh
//(Just a basic comparison here, a full comparison should be done in Mesh unit testing)
REQUIRE(mesh.Dimension() == mesh_new->Dimension());
REQUIRE(mesh.SpaceDimension() == mesh_new->SpaceDimension());
Vector vert, vert_diff;
mesh.GetVertices(vert);
mesh_new->GetVertices(vert_diff);
vert_diff -= vert;
REQUIRE(vert_diff.Normlinf() < 1e-10);
//Compare the old and new grid functions
//(Just a basic comparison here, a full comparison should be done in GridFunction unit testing)
Vector u_diff(*u_new), v_diff(*v_new);
u_diff -= *u;
v_diff -= *v;
REQUIRE(u_diff.Normlinf() < 1e-10);
REQUIRE(v_diff.Normlinf() < 1e-10);
//Compare the old and new quadrature functions
//(Just a basic comparison here, a full comparison should be done in GridFunction unit testing)
Vector qs_diff(*qs_new), qv_diff(*qv_new);
qs_diff -= *qs;
qv_diff -= *qv;
REQUIRE(qs_diff.Normlinf() < 1e-10);
REQUIRE(qv_diff.Normlinf() < 1e-10);
//Cleanup all the files
REQUIRE(remove("base_00005.mfem_root") == 0);
REQUIRE(remove("base_00005/mesh.00000") == 0);
REQUIRE(remove("base_00005/u.00000") == 0);
REQUIRE(remove("base_00005/v.00000") == 0);
REQUIRE(remove("base_00005/qs.00000") == 0);
REQUIRE(remove("base_00005/qv.00000") == 0);
REQUIRE(rmdir("base_00005") == 0);
}
#ifdef MFEM_USE_ZLIB
SECTION("Compressed MFEM format")
{
std::cout<<"Testing compressed MFEM format"<<std::endl;
//Collect the mesh and grid functions into a DataCollection and test that they got in there
VisItDataCollection dc("base", &mesh);
dc.RegisterField("u", u);
dc.RegisterField("v", v);
dc.RegisterQField("qs",qs);
dc.RegisterQField("qv",qv);
dc.SetCycle(5);
dc.SetTime(8.0);
REQUIRE(dc.GetMesh() == &mesh);
bool has_u = dc.HasField("u");
REQUIRE(has_u);
bool has_v = dc.HasField("v");
REQUIRE(has_v);
bool has_qs = dc.HasQField("qs");
REQUIRE(has_qs);
bool has_qv = dc.HasQField("qv");
REQUIRE(has_qv);
REQUIRE(dc.GetCycle() == 5);
REQUIRE(dc.GetTime() == 8.0);
//Save the DataCollection and load it into a new DataCollection for comparison
dc.SetPadDigits(5);
dc.SetCompression(true);
dc.Save();
VisItDataCollection dc_new("base");
dc_new.SetPadDigits(5);
dc_new.Load(dc.GetCycle());
Mesh *mesh_new = dc_new.GetMesh();
GridFunction *u_new = dc_new.GetField("u");
GridFunction *v_new = dc_new.GetField("v");
QuadratureFunction *qs_new = dc_new.GetQField("qs");
QuadratureFunction *qv_new = dc_new.GetQField("qv");
REQUIRE(mesh_new);
REQUIRE(u_new);
REQUIRE(v_new);
REQUIRE(qs_new);
REQUIRE(qv_new);
//Compare some collection parameters for old and new
std::string name, name_new;
name = dc.GetCollectionName();
name_new = dc_new.GetCollectionName();
REQUIRE(name == name_new);
REQUIRE(dc.GetCycle() == dc_new.GetCycle());
REQUIRE(dc.GetTime() == dc_new.GetTime());
//Compare the new new mesh with the old mesh
//(Just a basic comparison here, a full comparison should be done in Mesh unit testing)
REQUIRE(mesh.Dimension() == mesh_new->Dimension());
REQUIRE(mesh.SpaceDimension() == mesh_new->SpaceDimension());
Vector vert, vert_diff;
mesh.GetVertices(vert);
mesh_new->GetVertices(vert_diff);
vert_diff -= vert;
REQUIRE(vert_diff.Normlinf() < 1e-10);
//Compare the old and new grid functions
//(Just a basic comparison here, a full comparison should be done in GridFunction unit testing)
Vector u_diff(*u_new), v_diff(*v_new);
u_diff -= *u;
v_diff -= *v;
REQUIRE(u_diff.Normlinf() < 1e-10);
REQUIRE(v_diff.Normlinf() < 1e-10);
//Compare the old and new quadrature functions
//(Just a basic comparison here, a full comparison should be done in GridFunction unit testing)
Vector qs_diff(*qs_new), qv_diff(*qv_new);
qs_diff -= *qs;
qv_diff -= *qv;
REQUIRE(qs_diff.Normlinf() < 1e-10);
REQUIRE(qv_diff.Normlinf() < 1e-10);
//Cleanup all the files
REQUIRE(remove("base_00005.mfem_root") == 0);
REQUIRE(remove("base_00005/mesh.00000") == 0);
REQUIRE(remove("base_00005/u.00000") == 0);
REQUIRE(remove("base_00005/v.00000") == 0);
REQUIRE(remove("base_00005/qs.00000") == 0);
REQUIRE(remove("base_00005/qv.00000") == 0);
REQUIRE(rmdir("base_00005") == 0);
}
#endif
}
}
void SaveDataCollection(DataCollection &dc, int cycle, double t)
{
dc.SetCycle(cycle);
dc.SetTime(t);
dc.Save();
}
TEST_CASE("ParaView restart mode", "[ParaView]")
{
Mesh mesh = Mesh::MakeCartesian2D(2, 3, Element::QUADRILATERAL);
H1_FECollection fec(1, mesh.Dimension());
FiniteElementSpace fes(&mesh, &fec);
GridFunction u(&fes);
u = 0.0;
// Write initial dataset with three timesteps: 0, 1, 2.
{
ParaViewDataCollection dc("ParaView", &mesh);
dc.RegisterField("u", &u);
SaveDataCollection(dc, 0, 0);
SaveDataCollection(dc, 1, 1);
SaveDataCollection(dc, 2, 2);
}
// Using restart mode, append to the existing dataset, overwriting timesteps
// 1 and 2 with 1 and 1.5.
{
ParaViewDataCollection dc("ParaView", &mesh);
dc.UseRestartMode(true);
dc.RegisterField("u", &u);
SaveDataCollection(dc, 1, 1.0);
SaveDataCollection(dc, 2, 1.5);
}
// Parse the resulting PVD file, and verify that the structure is correct,
// and that it contains three timesteps: 0, 1, and 1.5.
using namespace tinyxml2;
auto StringCompare = [](const char *s1, const char *s2)
{
if (s1 == NULL || s2 == NULL) { return false; }
return strcmp(s1, s2) == 0;
};
auto VerifyDataset = [StringCompare](const XMLElement *ds, double t_ref)
{
REQUIRE(ds);
REQUIRE(StringCompare(ds->Name(), "DataSet"));
const char *timestep = ds->Attribute("timestep");
REQUIRE(timestep);
double t = std::stod(timestep);
REQUIRE(t == MFEM_Approx(t_ref));
};
XMLDocument xml;
xml.LoadFile("ParaView/ParaView.pvd");
REQUIRE(xml.ErrorID() == XML_SUCCESS);
const XMLElement *vtkfile = xml.FirstChildElement();
REQUIRE(vtkfile);
REQUIRE(StringCompare(vtkfile->Name(), "VTKFile"));
const XMLElement *collection = vtkfile->FirstChildElement();
REQUIRE(collection);
REQUIRE(StringCompare(collection->Name(), "Collection"));
const XMLElement *dataset = collection->FirstChildElement();
VerifyDataset(dataset, 0.0);
dataset = dataset->NextSiblingElement();
VerifyDataset(dataset, 1.0);
dataset = dataset->NextSiblingElement();
VerifyDataset(dataset, 1.5);
REQUIRE(dataset->NextSiblingElement() == NULL);
// Clean up
for (int c=0; c<=2; ++c)
{
std::string prefix = "ParaView/Cycle00000" + std::to_string(c);
REQUIRE(remove((prefix + "/data.pvtu").c_str()) == 0);
REQUIRE(remove((prefix + "/proc000000.vtu").c_str()) == 0);
REQUIRE(rmdir(prefix.c_str()) == 0);
}
REQUIRE(remove("ParaView/ParaView.pvd") == 0);
REQUIRE(rmdir("ParaView") == 0);
}
|
Add unit test for ParaView restart mode
|
Add unit test for ParaView restart mode
|
C++
|
bsd-3-clause
|
mfem/mfem,mfem/mfem,mfem/mfem,mfem/mfem,mfem/mfem
|
a8b3dded7939b4a63d2cf04993023ddce5245ae9
|
tests/unit/fem/test_linearform_ext.cpp
|
tests/unit/fem/test_linearform_ext.cpp
|
// Copyright (c) 2010-2022, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "mfem.hpp"
#include "unit_tests.hpp"
#include <functional>
#include <ctime>
using namespace mfem;
struct LinearFormExtTest
{
enum { DLFEval, QLFEval, DLFGrad, // scalar domain
VDLFEval, VQLFEval, VDLFGrad, // vector domain
BLFEval, BNLFEval // boundary
};
const double abs_tol = 1e-14, rel_tol = 1e-14;
const char *mesh_filename;
Mesh mesh;
const int dim, vdim, ordering, gll, problem, p, q, SEED = 0x100001b3;
H1_FECollection fec;
FiniteElementSpace vfes;
const Geometry::Type geom_type;
IntegrationRules IntRulesGLL;
const IntegrationRule *irGLL, *ir;
Array<int> elem_marker;
Vector one_vec, dim_vec, vdim_vec, vdim_dim_vec;
ConstantCoefficient cst_coeff;
VectorConstantCoefficient dim_cst_coeff, vdim_cst_coeff, vdim_dim_cst_coeff;
QuadratureSpace qspace;
QuadratureFunction q_function, q_vdim_function;
QuadratureFunctionCoefficient qfc;
VectorQuadratureFunctionCoefficient qfvc;
LinearForm lf_dev, lf_std;
LinearFormIntegrator *lfi_dev, *lfi_std;
LinearFormExtTest(const char *mesh_filename,
int vdim, int ordering, bool gll, int problem, int p):
mesh_filename(mesh_filename),
mesh(Mesh::LoadFromFile(mesh_filename)),
dim(mesh.Dimension()), vdim(vdim), ordering(ordering), gll(gll),
problem(problem), p(p), q(2*p + (gll?-1:3)), fec(p, dim),
vfes(&mesh, &fec, vdim, ordering),
geom_type(vfes.GetFE(0)->GetGeomType()),
IntRulesGLL(0, Quadrature1D::GaussLobatto),
irGLL(&IntRulesGLL.Get(geom_type, q)), ir(&IntRules.Get(geom_type, q)),
elem_marker(), one_vec(1), dim_vec(dim), vdim_vec(vdim), vdim_dim_vec(vdim*dim),
cst_coeff(M_PI), dim_cst_coeff((dim_vec.Randomize(SEED), dim_vec)),
vdim_cst_coeff((vdim_vec.Randomize(SEED), vdim_vec)),
vdim_dim_cst_coeff((vdim_dim_vec.Randomize(SEED), vdim_dim_vec)),
qspace(&mesh, q),
q_function(&qspace, 1),
q_vdim_function(&qspace, vdim),
qfc((q_function.Randomize(SEED), q_function)),
qfvc((q_vdim_function.Randomize(SEED), q_vdim_function)),
lf_dev(&vfes), lf_std(&vfes), lfi_dev(nullptr), lfi_std(nullptr)
{
for (int e = 0; e < mesh.GetNE(); e++) { mesh.SetAttribute(e, e%2?1:2); }
mesh.SetAttributes();
MFEM_VERIFY(mesh.attributes.Size() == 2, "mesh attributes size error!");
elem_marker.SetSize(2);
elem_marker[0] = 0;
elem_marker[1] = 1;
if (problem == DLFEval)
{
lfi_dev = new DomainLFIntegrator(cst_coeff);
lfi_std = new DomainLFIntegrator(cst_coeff);
}
else if (problem == QLFEval)
{
lfi_dev = new QuadratureLFIntegrator(qfc,NULL);
lfi_std = new QuadratureLFIntegrator(qfc,NULL);
}
else if (problem == DLFGrad)
{
lfi_dev = new DomainLFGradIntegrator(dim_cst_coeff);
lfi_std = new DomainLFGradIntegrator(dim_cst_coeff);
}
else if (problem == VDLFEval)
{
lfi_dev = new VectorDomainLFIntegrator(vdim_cst_coeff);
lfi_std = new VectorDomainLFIntegrator(vdim_cst_coeff);
}
else if (problem == VQLFEval)
{
lfi_dev = new VectorQuadratureLFIntegrator(qfvc,NULL);
lfi_std = new VectorQuadratureLFIntegrator(qfvc,NULL);
}
else if (problem == VDLFGrad)
{
lfi_dev = new VectorDomainLFGradIntegrator(vdim_dim_cst_coeff);
lfi_std = new VectorDomainLFGradIntegrator(vdim_dim_cst_coeff);
}
else if (problem == BLFEval)
{
lfi_dev = new BoundaryLFIntegrator(cst_coeff);
lfi_std = new BoundaryLFIntegrator(cst_coeff);
}
else if (problem == BNLFEval)
{
lfi_dev = new BoundaryNormalLFIntegrator(dim_cst_coeff);
lfi_std = new BoundaryNormalLFIntegrator(dim_cst_coeff);
}
else { REQUIRE(false); }
if (problem != QLFEval && problem != VQLFEval && problem != BLFEval &&
problem != BNLFEval)
{
lfi_dev->SetIntRule(gll ? irGLL : ir);
lfi_std->SetIntRule(gll ? irGLL : ir);
}
if (problem != BLFEval && problem != BNLFEval)
{
lf_dev.AddDomainIntegrator(lfi_dev, elem_marker);
lf_std.AddDomainIntegrator(lfi_std, elem_marker);
}
else
{
lf_dev.AddBoundaryIntegrator(lfi_dev);
lf_std.AddBoundaryIntegrator(lfi_std);
}
}
void Run()
{
const bool scalar = problem == LinearFormExtTest::DLFEval ||
problem == LinearFormExtTest::QLFEval ||
problem == LinearFormExtTest::DLFGrad;
REQUIRE((!scalar || vdim == 1));
const bool grad = problem == LinearFormExtTest::DLFGrad ||
problem == LinearFormExtTest::VDLFGrad;
CAPTURE(mesh_filename, dim, p, q, ordering, vdim, scalar, grad);
const bool use_device = true;
lf_dev.Assemble(use_device);
const bool dont_use_device = false;
lf_std.Assemble(dont_use_device);
lf_std -= lf_dev;
REQUIRE(0.0 == MFEM_Approx(lf_std*lf_std, abs_tol, rel_tol));
}
};
TEST_CASE("Linear Form Extension", "[LinearFormExtension], [CUDA]")
{
const bool all = launch_all_non_regression_tests;
const auto mesh_file =
all ? GENERATE("../../data/star.mesh", "../../data/star-q3.mesh",
"../../data/fichera.mesh", "../../data/fichera-q3.mesh") :
GENERATE("../../data/star-q3.mesh", "../../data/fichera-q3.mesh");
const auto p = all ? GENERATE(1,2,3,4,5,6) : GENERATE(1,3);
SECTION("Scalar")
{
const auto gll = GENERATE(false, true);
const auto problem = GENERATE(LinearFormExtTest::DLFEval,
LinearFormExtTest::QLFEval,
LinearFormExtTest::DLFGrad,
LinearFormExtTest::BLFEval,
LinearFormExtTest::BNLFEval);
LinearFormExtTest(mesh_file, 1, Ordering::byNODES, gll, problem, p).Run();
}
SECTION("Vector")
{
const auto gll = GENERATE(false, true);
const auto vdim = all ? GENERATE(1,5,7) : GENERATE(1,5);
const auto ordering = GENERATE(Ordering::byVDIM, Ordering::byNODES);
const auto problem = GENERATE(LinearFormExtTest::VDLFEval,
LinearFormExtTest::VQLFEval,
LinearFormExtTest::VDLFGrad);
LinearFormExtTest(mesh_file, vdim, ordering, gll, problem, p).Run();
}
SECTION("SetIntPoint")
{
Mesh mesh(mesh_file);
const int dim = mesh.Dimension();
CAPTURE(mesh_file, dim, p);
H1_FECollection H1(p, dim);
FiniteElementSpace H1fes(&mesh, &H1);
FunctionCoefficient f([](const Vector& x)
{ return std::sin(M_PI*x(0)) * std::sin(M_PI*x(1)); });
GridFunction x(&H1fes);
x.ProjectCoefficient(f);
GradientGridFunctionCoefficient grad_x(&x);
InnerProductCoefficient norm2_grad_x(grad_x,grad_x);
L2_FECollection L2(p-1, dim);
FiniteElementSpace L2fes(&mesh, &L2);
LinearForm d1(&L2fes);
d1.AddDomainIntegrator(new DomainLFIntegrator(norm2_grad_x));
d1.Assemble();
LinearForm d2(&L2fes);
d2.AddDomainIntegrator(new DomainLFIntegrator(norm2_grad_x));
d2.Assemble(false);
d1 -= d2;
REQUIRE(d1.Norml2() == MFEM_Approx(0.0));
}
SECTION("L2 MapType")
{
auto map_type = GENERATE(FiniteElement::VALUE, FiniteElement::INTEGRAL);
Mesh mesh(mesh_file);
const int dim = mesh.Dimension();
CAPTURE(mesh_file, dim, p, map_type);
L2_FECollection fec(p, dim, BasisType::GaussLegendre, map_type);
FiniteElementSpace fes(&mesh, &fec);
ConstantCoefficient coeff(1.0);
LinearForm d1(&fes);
d1.AddDomainIntegrator(new DomainLFIntegrator(coeff));
d1.Assemble();
LinearForm d2(&fes);
d2.AddDomainIntegrator(new DomainLFIntegrator(coeff));
d2.Assemble(false);
CAPTURE(d1.Norml2(), d2.Norml2());
d1 -= d2;
REQUIRE(d1.Norml2() == MFEM_Approx(0.0));
}
}
|
// Copyright (c) 2010-2022, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "mfem.hpp"
#include "unit_tests.hpp"
#include <functional>
#include <ctime>
using namespace mfem;
static double f(const Vector &xvec)
{
const int dim = xvec.Size();
double val = 2*xvec[0];
if (dim >= 2)
{
val += 3*xvec[1]*xvec[0];
}
if (dim >= 3)
{
val += 0.25*xvec[2]*xvec[1];
}
return val;
}
static void fvec_dim(const Vector &xvec, Vector &v)
{
v.SetSize(xvec.Size());
for (int d = 0; d < xvec.Size(); ++d)
{
v[d] = f(xvec) / double(d + 1);
}
}
struct LinearFormExtTest
{
enum { DLFEval, QLFEval, DLFGrad, // scalar domain
VDLFEval, VQLFEval, VDLFGrad, // vector domain
BLFEval, BNLFEval // boundary
};
const double abs_tol = 1e-14, rel_tol = 1e-14;
const char *mesh_filename;
Mesh mesh;
const int dim, vdim, ordering, gll, problem, p, q, SEED = 0x100001b3;
H1_FECollection fec;
FiniteElementSpace vfes;
const Geometry::Type geom_type;
IntegrationRules IntRulesGLL;
const IntegrationRule *irGLL, *ir;
Array<int> elem_marker;
Vector vdim_vec, vdim_dim_vec;
FunctionCoefficient fn_coeff;
VectorFunctionCoefficient dim_fn_coeff;
VectorConstantCoefficient vdim_cst_coeff, vdim_dim_cst_coeff;
QuadratureSpace qspace;
QuadratureFunction q_function, q_vdim_function;
QuadratureFunctionCoefficient qfc;
VectorQuadratureFunctionCoefficient qfvc;
LinearForm lf_dev, lf_std;
LinearFormIntegrator *lfi_dev, *lfi_std;
LinearFormExtTest(const char *mesh_filename,
int vdim, int ordering, bool gll, int problem, int p):
mesh_filename(mesh_filename),
mesh(Mesh::LoadFromFile(mesh_filename)),
dim(mesh.Dimension()), vdim(vdim), ordering(ordering), gll(gll),
problem(problem), p(p), q(2*p + (gll?-1:3)), fec(p, dim),
vfes(&mesh, &fec, vdim, ordering),
geom_type(vfes.GetFE(0)->GetGeomType()),
IntRulesGLL(0, Quadrature1D::GaussLobatto),
irGLL(&IntRulesGLL.Get(geom_type, q)), ir(&IntRules.Get(geom_type, q)),
elem_marker(), vdim_vec(vdim), vdim_dim_vec(vdim*dim),
fn_coeff(f), dim_fn_coeff(dim, fvec_dim),
vdim_cst_coeff((vdim_vec.Randomize(SEED), vdim_vec)),
vdim_dim_cst_coeff((vdim_dim_vec.Randomize(SEED), vdim_dim_vec)),
qspace(&mesh, q),
q_function(&qspace, 1),
q_vdim_function(&qspace, vdim),
qfc((q_function.Randomize(SEED), q_function)),
qfvc((q_vdim_function.Randomize(SEED), q_vdim_function)),
lf_dev(&vfes), lf_std(&vfes), lfi_dev(nullptr), lfi_std(nullptr)
{
for (int e = 0; e < mesh.GetNE(); e++) { mesh.SetAttribute(e, e%2?1:2); }
mesh.SetAttributes();
MFEM_VERIFY(mesh.attributes.Size() == 2, "mesh attributes size error!");
elem_marker.SetSize(2);
elem_marker[0] = 0;
elem_marker[1] = 1;
if (problem == DLFEval)
{
lfi_dev = new DomainLFIntegrator(fn_coeff);
lfi_std = new DomainLFIntegrator(fn_coeff);
}
else if (problem == QLFEval)
{
lfi_dev = new QuadratureLFIntegrator(qfc,NULL);
lfi_std = new QuadratureLFIntegrator(qfc,NULL);
}
else if (problem == DLFGrad)
{
lfi_dev = new DomainLFGradIntegrator(dim_fn_coeff);
lfi_std = new DomainLFGradIntegrator(dim_fn_coeff);
}
else if (problem == VDLFEval)
{
lfi_dev = new VectorDomainLFIntegrator(vdim_cst_coeff);
lfi_std = new VectorDomainLFIntegrator(vdim_cst_coeff);
}
else if (problem == VQLFEval)
{
lfi_dev = new VectorQuadratureLFIntegrator(qfvc,NULL);
lfi_std = new VectorQuadratureLFIntegrator(qfvc,NULL);
}
else if (problem == VDLFGrad)
{
lfi_dev = new VectorDomainLFGradIntegrator(vdim_dim_cst_coeff);
lfi_std = new VectorDomainLFGradIntegrator(vdim_dim_cst_coeff);
}
else if (problem == BLFEval)
{
lfi_dev = new BoundaryLFIntegrator(fn_coeff);
lfi_std = new BoundaryLFIntegrator(fn_coeff);
}
else if (problem == BNLFEval)
{
lfi_dev = new BoundaryNormalLFIntegrator(dim_fn_coeff);
lfi_std = new BoundaryNormalLFIntegrator(dim_fn_coeff);
}
else { REQUIRE(false); }
if (problem != QLFEval && problem != VQLFEval && problem != BLFEval &&
problem != BNLFEval)
{
lfi_dev->SetIntRule(gll ? irGLL : ir);
lfi_std->SetIntRule(gll ? irGLL : ir);
}
if (problem != BLFEval && problem != BNLFEval)
{
lf_dev.AddDomainIntegrator(lfi_dev, elem_marker);
lf_std.AddDomainIntegrator(lfi_std, elem_marker);
}
else
{
lf_dev.AddBoundaryIntegrator(lfi_dev);
lf_std.AddBoundaryIntegrator(lfi_std);
}
}
void Run()
{
const bool scalar = problem == LinearFormExtTest::DLFEval ||
problem == LinearFormExtTest::QLFEval ||
problem == LinearFormExtTest::DLFGrad;
REQUIRE((!scalar || vdim == 1));
const bool grad = problem == LinearFormExtTest::DLFGrad ||
problem == LinearFormExtTest::VDLFGrad;
CAPTURE(mesh_filename, dim, p, q, ordering, vdim, scalar, grad);
const bool use_device = true;
lf_dev.Assemble(use_device);
const bool dont_use_device = false;
lf_std.Assemble(dont_use_device);
lf_std -= lf_dev;
REQUIRE(0.0 == MFEM_Approx(lf_std*lf_std, abs_tol, rel_tol));
}
};
TEST_CASE("Linear Form Extension", "[LinearFormExtension], [CUDA]")
{
const bool all = launch_all_non_regression_tests;
const auto mesh_file =
all ? GENERATE("../../data/star.mesh", "../../data/star-q3.mesh",
"../../data/fichera.mesh", "../../data/fichera-q3.mesh") :
GENERATE("../../data/star-q3.mesh", "../../data/fichera-q3.mesh");
const auto p = all ? GENERATE(1,2,3,4,5,6) : GENERATE(1,3);
SECTION("Scalar")
{
const auto gll = GENERATE(false, true);
const auto problem = GENERATE(LinearFormExtTest::DLFEval,
LinearFormExtTest::QLFEval,
LinearFormExtTest::DLFGrad,
LinearFormExtTest::BLFEval,
LinearFormExtTest::BNLFEval);
LinearFormExtTest(mesh_file, 1, Ordering::byNODES, gll, problem, p).Run();
}
SECTION("Vector")
{
const auto gll = GENERATE(false, true);
const auto vdim = all ? GENERATE(1,5,7) : GENERATE(1,5);
const auto ordering = GENERATE(Ordering::byVDIM, Ordering::byNODES);
const auto problem = GENERATE(LinearFormExtTest::VDLFEval,
LinearFormExtTest::VQLFEval,
LinearFormExtTest::VDLFGrad);
LinearFormExtTest(mesh_file, vdim, ordering, gll, problem, p).Run();
}
SECTION("SetIntPoint")
{
Mesh mesh(mesh_file);
const int dim = mesh.Dimension();
CAPTURE(mesh_file, dim, p);
H1_FECollection H1(p, dim);
FiniteElementSpace H1fes(&mesh, &H1);
FunctionCoefficient f([](const Vector& x)
{ return std::sin(M_PI*x(0)) * std::sin(M_PI*x(1)); });
GridFunction x(&H1fes);
x.ProjectCoefficient(f);
GradientGridFunctionCoefficient grad_x(&x);
InnerProductCoefficient norm2_grad_x(grad_x,grad_x);
L2_FECollection L2(p-1, dim);
FiniteElementSpace L2fes(&mesh, &L2);
LinearForm d1(&L2fes);
d1.AddDomainIntegrator(new DomainLFIntegrator(norm2_grad_x));
d1.Assemble();
LinearForm d2(&L2fes);
d2.AddDomainIntegrator(new DomainLFIntegrator(norm2_grad_x));
d2.Assemble(false);
d1 -= d2;
REQUIRE(d1.Norml2() == MFEM_Approx(0.0));
}
SECTION("L2 MapType")
{
auto map_type = GENERATE(FiniteElement::VALUE, FiniteElement::INTEGRAL);
Mesh mesh(mesh_file);
const int dim = mesh.Dimension();
CAPTURE(mesh_file, dim, p, map_type);
L2_FECollection fec(p, dim, BasisType::GaussLegendre, map_type);
FiniteElementSpace fes(&mesh, &fec);
ConstantCoefficient coeff(1.0);
LinearForm d1(&fes);
d1.AddDomainIntegrator(new DomainLFIntegrator(coeff));
d1.Assemble();
LinearForm d2(&fes);
d2.AddDomainIntegrator(new DomainLFIntegrator(coeff));
d2.Assemble(false);
CAPTURE(d1.Norml2(), d2.Norml2());
d1 -= d2;
REQUIRE(d1.Norml2() == MFEM_Approx(0.0));
}
}
|
Use variable coefficients in linear form extension unit tests
|
Use variable coefficients in linear form extension unit tests
|
C++
|
bsd-3-clause
|
mfem/mfem,mfem/mfem,mfem/mfem,mfem/mfem,mfem/mfem
|
d031d20cdb5197f208811a386e659ddbe19cca27
|
src/test/pegtl/verify_file.hpp
|
src/test/pegtl/verify_file.hpp
|
// Copyright (c) 2014-2020 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAO_PEGTL_SRC_TEST_PEGTL_VERIFY_FILE_HPP
#define TAO_PEGTL_SRC_TEST_PEGTL_VERIFY_FILE_HPP
#include <tao/pegtl.hpp>
#include "test.hpp"
#if defined( _MSC_VER )
#define TAO_PEGTL_TEST_FILENAME u"src/test/pegtl/file_äöü𝄞_data.txt"
#else
#define TAO_PEGTL_TEST_FILENAME "src/test/pegtl/file_äöü𝄞_data.txt"
#endif
namespace TAO_PEGTL_NAMESPACE
{
struct file_content
: seq< TAO_PEGTL_STRING( "dummy content" ), eol, discard >
{};
struct file_grammar
: seq< rep_min_max< 11, 11, file_content >, eof >
{};
template< typename Rule >
struct file_action
{};
template<>
struct file_action< eof >
{
static void apply0( bool& flag )
{
flag = true;
}
};
template< typename Rule >
struct file_control
: normal< Rule >
{};
template<>
struct file_control< eof >
: normal< eof >
{
template< typename ParseInput >
static void success( const ParseInput& /*unused*/, bool& flag )
{
flag = true;
}
};
template< typename T >
void verify_file()
{
{
try {
T in( "src/test/pegtl/no_such_file.txt" );
TAO_PEGTL_TEST_ASSERT( false ); // LCOV_EXCL_LINE
}
catch( const internal::filesystem::filesystem_error& ) {
}
}
{
T in( "src/test/pegtl/file_data.txt" );
TAO_PEGTL_TEST_ASSERT( in.source() == "src/test/pegtl/file_data.txt" );
TAO_PEGTL_TEST_ASSERT( parse< file_grammar >( in ) );
TAO_PEGTL_TEST_ASSERT( in.source() == "src/test/pegtl/file_data.txt" );
}
{
T in( TAO_PEGTL_TEST_FILENAME );
bool flag = true;
TAO_PEGTL_TEST_ASSERT( parse< file_grammar >( in, flag ) );
TAO_PEGTL_TEST_ASSERT( flag == true );
}
{
T in( TAO_PEGTL_TEST_FILENAME );
bool flag = false;
TAO_PEGTL_TEST_ASSERT( parse< file_grammar >( in, flag ) );
TAO_PEGTL_TEST_ASSERT( flag == false );
}
{
T in( TAO_PEGTL_TEST_FILENAME );
bool flag = false;
const bool result = parse< file_grammar, file_action >( in, flag );
TAO_PEGTL_TEST_ASSERT( result );
TAO_PEGTL_TEST_ASSERT( flag == true );
}
{
T in( TAO_PEGTL_TEST_FILENAME );
bool flag = false;
const bool result = parse< file_grammar, nothing, file_control >( in, flag );
TAO_PEGTL_TEST_ASSERT( result );
TAO_PEGTL_TEST_ASSERT( flag == true );
}
const char* foo = "foo";
const memory_input m( foo, foo + 3, foo );
{
T in( TAO_PEGTL_TEST_FILENAME );
TAO_PEGTL_TEST_ASSERT( parse_nested< file_grammar >( m, in ) );
}
{
T in( TAO_PEGTL_TEST_FILENAME );
bool flag = true;
TAO_PEGTL_TEST_ASSERT( parse_nested< file_grammar >( m, in, flag ) );
TAO_PEGTL_TEST_ASSERT( flag == true );
}
{
T in( TAO_PEGTL_TEST_FILENAME );
bool flag = false;
TAO_PEGTL_TEST_ASSERT( parse_nested< file_grammar >( m, in, flag ) );
TAO_PEGTL_TEST_ASSERT( flag == false );
}
{
T in( TAO_PEGTL_TEST_FILENAME );
bool flag = false;
const bool result = parse_nested< file_grammar, file_action >( m, in, flag );
TAO_PEGTL_TEST_ASSERT( result );
TAO_PEGTL_TEST_ASSERT( flag == true );
}
{
T in( TAO_PEGTL_TEST_FILENAME );
bool flag = false;
const bool result = parse_nested< file_grammar, nothing, file_control >( m, in, flag );
TAO_PEGTL_TEST_ASSERT( result );
TAO_PEGTL_TEST_ASSERT( flag == true );
}
}
} // namespace TAO_PEGTL_NAMESPACE
#endif
|
// Copyright (c) 2014-2020 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAO_PEGTL_SRC_TEST_PEGTL_VERIFY_FILE_HPP
#define TAO_PEGTL_SRC_TEST_PEGTL_VERIFY_FILE_HPP
#include <tao/pegtl.hpp>
#include "test.hpp"
#if defined( _MSC_VER )
#define TAO_PEGTL_TEST_FILENAME u"src/test/pegtl/file_äöü𝄞_data.txt"
#else
#define TAO_PEGTL_TEST_FILENAME "src/test/pegtl/file_äöü𝄞_data.txt"
#endif
namespace TAO_PEGTL_NAMESPACE
{
struct file_content
: seq< TAO_PEGTL_STRING( "dummy content" ), eol, discard >
{};
struct file_grammar
: seq< rep_min_max< 11, 11, file_content >, eof >
{};
template< typename Rule >
struct file_action
{};
template<>
struct file_action< eof >
{
static void apply0( bool& flag )
{
flag = true;
}
};
template< typename Rule >
struct file_control
: normal< Rule >
{};
template<>
struct file_control< eof >
: normal< eof >
{
template< typename ParseInput >
static void success( const ParseInput& /*unused*/, bool& flag )
{
flag = true;
}
};
template< typename T >
void verify_file()
{
{
try {
T in( "src/test/pegtl/no_such_file.txt" );
TAO_PEGTL_TEST_UNREACHABLE; // LCOV_EXCL_LINE
}
catch( const internal::filesystem::filesystem_error& ) {
}
}
{
T in( "src/test/pegtl/file_data.txt" );
TAO_PEGTL_TEST_ASSERT( in.source() == "src/test/pegtl/file_data.txt" );
TAO_PEGTL_TEST_ASSERT( parse< file_grammar >( in ) );
TAO_PEGTL_TEST_ASSERT( in.source() == "src/test/pegtl/file_data.txt" );
}
{
T in( TAO_PEGTL_TEST_FILENAME );
bool flag = true;
TAO_PEGTL_TEST_ASSERT( parse< file_grammar >( in, flag ) );
TAO_PEGTL_TEST_ASSERT( flag == true );
}
{
T in( TAO_PEGTL_TEST_FILENAME );
bool flag = false;
TAO_PEGTL_TEST_ASSERT( parse< file_grammar >( in, flag ) );
TAO_PEGTL_TEST_ASSERT( flag == false );
}
{
T in( TAO_PEGTL_TEST_FILENAME );
bool flag = false;
const bool result = parse< file_grammar, file_action >( in, flag );
TAO_PEGTL_TEST_ASSERT( result );
TAO_PEGTL_TEST_ASSERT( flag == true );
}
{
T in( TAO_PEGTL_TEST_FILENAME );
bool flag = false;
const bool result = parse< file_grammar, nothing, file_control >( in, flag );
TAO_PEGTL_TEST_ASSERT( result );
TAO_PEGTL_TEST_ASSERT( flag == true );
}
const char* foo = "foo";
const memory_input m( foo, foo + 3, foo );
{
T in( TAO_PEGTL_TEST_FILENAME );
TAO_PEGTL_TEST_ASSERT( parse_nested< file_grammar >( m, in ) );
}
{
T in( TAO_PEGTL_TEST_FILENAME );
bool flag = true;
TAO_PEGTL_TEST_ASSERT( parse_nested< file_grammar >( m, in, flag ) );
TAO_PEGTL_TEST_ASSERT( flag == true );
}
{
T in( TAO_PEGTL_TEST_FILENAME );
bool flag = false;
TAO_PEGTL_TEST_ASSERT( parse_nested< file_grammar >( m, in, flag ) );
TAO_PEGTL_TEST_ASSERT( flag == false );
}
{
T in( TAO_PEGTL_TEST_FILENAME );
bool flag = false;
const bool result = parse_nested< file_grammar, file_action >( m, in, flag );
TAO_PEGTL_TEST_ASSERT( result );
TAO_PEGTL_TEST_ASSERT( flag == true );
}
{
T in( TAO_PEGTL_TEST_FILENAME );
bool flag = false;
const bool result = parse_nested< file_grammar, nothing, file_control >( m, in, flag );
TAO_PEGTL_TEST_ASSERT( result );
TAO_PEGTL_TEST_ASSERT( flag == true );
}
}
} // namespace TAO_PEGTL_NAMESPACE
#endif
|
Revert useless change
|
Revert useless change
|
C++
|
mit
|
ColinH/PEGTL,ColinH/PEGTL
|
9cdc1cbebc72779a048b00006d3bb30f5cb0abec
|
src/test/pegtl/verify_rule.hpp
|
src/test/pegtl/verify_rule.hpp
|
// Copyright (c) 2014-2020 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAO_PEGTL_SRC_TEST_PEGTL_VERIFY_RULE_HPP
#define TAO_PEGTL_SRC_TEST_PEGTL_VERIFY_RULE_HPP
#include <cstdlib>
#include <string>
#include <tao/pegtl/eol.hpp>
#include <tao/pegtl/memory_input.hpp>
#include <tao/pegtl/rule_list.hpp>
#include <tao/pegtl/tracking_mode.hpp>
#include "result_type.hpp"
#include "verify_impl.hpp"
namespace TAO_PEGTL_NAMESPACE
{
template< typename Name, typename Rule, typename... Rules >
void verify_meta()
{
static_assert( std::is_same_v< typename Name::rule_t, Rule > );
static_assert( std::is_same_v< typename Name::subs_t, rule_list< Rules... > > );
};
template< typename Rule >
struct verify_action_impl
{
template< typename Input, typename... States >
static void apply( const Input& /*unused*/, States&&... /*unused*/ )
{}
};
template< typename Rule >
struct verify_action_impl0
{
template< typename... States >
static void apply0( States&&... /*unused*/ )
{}
};
template< typename Rule, typename Eol = eol::lf_crlf >
void verify_rule( const std::size_t line, const char* file, const std::string& data, const result_type expected, int remain = -1 )
{
if( remain < 0 ) {
remain = ( expected == result_type::success ) ? 0 : int( data.size() );
}
{
memory_input< tracking_mode::eager, Eol > in( data.data(), data.data() + data.size(), file, 0, line, 0 );
verify_impl_one< Rule, nothing >( line, file, data, in, expected, remain );
memory_input< tracking_mode::lazy, Eol > i2( data.data(), data.data() + data.size(), file );
verify_impl_one< Rule, nothing >( line, file, data, i2, expected, remain );
}
{
memory_input< tracking_mode::eager, Eol > in( data.data(), data.data() + data.size(), file, 0, line, 0 );
verify_impl_one< Rule, verify_action_impl >( line, file, data, in, expected, remain );
memory_input< tracking_mode::lazy, Eol > i2( data.data(), data.data() + data.size(), file );
verify_impl_one< Rule, verify_action_impl >( line, file, data, i2, expected, remain );
}
{
memory_input< tracking_mode::eager, Eol > in( data.data(), data.data() + data.size(), file, 0, line, 0 );
verify_impl_one< Rule, verify_action_impl0 >( line, file, data, in, expected, remain );
memory_input< tracking_mode::lazy, Eol > i2( data.data(), data.data() + data.size(), file );
verify_impl_one< Rule, verify_action_impl0 >( line, file, data, i2, expected, remain );
}
}
template< typename Rule, typename Eol = eol::lf_crlf >
void verify_only( const std::size_t line, const char* file, const std::string& data, const result_type expected, const std::size_t remain )
{
{
memory_input< tracking_mode::eager, Eol > in( data.data(), data.data() + data.size(), file, 0, line, 0 );
verify_impl_one< Rule, nothing >( line, file, data, in, expected, remain );
}
{
memory_input< tracking_mode::eager, Eol > in( data.data(), data.data() + data.size(), file, 0, line, 0 );
verify_impl_one< Rule, verify_action_impl >( line, file, data, in, expected, remain );
}
{
memory_input< tracking_mode::eager, Eol > in( data.data(), data.data() + data.size(), file, 0, line, 0 );
verify_impl_one< Rule, verify_action_impl0 >( line, file, data, in, expected, remain );
}
}
} // namespace TAO_PEGTL_NAMESPACE
#endif
|
// Copyright (c) 2014-2020 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAO_PEGTL_SRC_TEST_PEGTL_VERIFY_RULE_HPP
#define TAO_PEGTL_SRC_TEST_PEGTL_VERIFY_RULE_HPP
#include <cstdlib>
#include <string>
#include <tao/pegtl/eol.hpp>
#include <tao/pegtl/memory_input.hpp>
#include <tao/pegtl/rule_list.hpp>
#include <tao/pegtl/tracking_mode.hpp>
#include "result_type.hpp"
#include "verify_impl.hpp"
namespace TAO_PEGTL_NAMESPACE
{
template< typename Name, typename Rule, typename... Rules >
void verify_meta()
{
static_assert( std::is_same_v< typename Name::rule_t, Rule > );
static_assert( std::is_same_v< typename Name::subs_t, rule_list< Rules... > > );
}
template< typename Rule >
struct verify_action_impl
{
template< typename Input, typename... States >
static void apply( const Input& /*unused*/, States&&... /*unused*/ )
{}
};
template< typename Rule >
struct verify_action_impl0
{
template< typename... States >
static void apply0( States&&... /*unused*/ )
{}
};
template< typename Rule, typename Eol = eol::lf_crlf >
void verify_rule( const std::size_t line, const char* file, const std::string& data, const result_type expected, int remain = -1 )
{
if( remain < 0 ) {
remain = ( expected == result_type::success ) ? 0 : int( data.size() );
}
{
memory_input< tracking_mode::eager, Eol > in( data.data(), data.data() + data.size(), file, 0, line, 0 );
verify_impl_one< Rule, nothing >( line, file, data, in, expected, remain );
memory_input< tracking_mode::lazy, Eol > i2( data.data(), data.data() + data.size(), file );
verify_impl_one< Rule, nothing >( line, file, data, i2, expected, remain );
}
{
memory_input< tracking_mode::eager, Eol > in( data.data(), data.data() + data.size(), file, 0, line, 0 );
verify_impl_one< Rule, verify_action_impl >( line, file, data, in, expected, remain );
memory_input< tracking_mode::lazy, Eol > i2( data.data(), data.data() + data.size(), file );
verify_impl_one< Rule, verify_action_impl >( line, file, data, i2, expected, remain );
}
{
memory_input< tracking_mode::eager, Eol > in( data.data(), data.data() + data.size(), file, 0, line, 0 );
verify_impl_one< Rule, verify_action_impl0 >( line, file, data, in, expected, remain );
memory_input< tracking_mode::lazy, Eol > i2( data.data(), data.data() + data.size(), file );
verify_impl_one< Rule, verify_action_impl0 >( line, file, data, i2, expected, remain );
}
}
template< typename Rule, typename Eol = eol::lf_crlf >
void verify_only( const std::size_t line, const char* file, const std::string& data, const result_type expected, const std::size_t remain )
{
{
memory_input< tracking_mode::eager, Eol > in( data.data(), data.data() + data.size(), file, 0, line, 0 );
verify_impl_one< Rule, nothing >( line, file, data, in, expected, remain );
}
{
memory_input< tracking_mode::eager, Eol > in( data.data(), data.data() + data.size(), file, 0, line, 0 );
verify_impl_one< Rule, verify_action_impl >( line, file, data, in, expected, remain );
}
{
memory_input< tracking_mode::eager, Eol > in( data.data(), data.data() + data.size(), file, 0, line, 0 );
verify_impl_one< Rule, verify_action_impl0 >( line, file, data, in, expected, remain );
}
}
} // namespace TAO_PEGTL_NAMESPACE
#endif
|
Fix typo.
|
Fix typo.
|
C++
|
mit
|
ColinH/PEGTL,ColinH/PEGTL
|
35176ad47efec77e929cc7772e09a2b91d169475
|
X10_Project/Classes/Sling.cpp
|
X10_Project/Classes/Sling.cpp
|
#include "stdafx.h"
#include "Sling.h"
#include "GameManager.h"
#include "FileStuff.h"
#include <SimpleAudioEngine.h>
Sling::Sling() : m_expectLine(), m_shotAngle(Vec2(0, 0)), m_shotPower(0), m_arm(nullptr), m_character(nullptr)
{
///# ڸ ̿ ʱȭ å Ѵ. (Ŀ ٸ Լ ʱȭ ϴ..)
}
bool Sling::init()
{
if (Node::init() == false)
{
return false;
}
//set Name
setName("Sling");
//set Empey status
ChangeToEmpty();
//set some frame work variable
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
//set position of character
setPosition(SLING_POSITION);
/*Make Expect line*/
for (int i = 0; i < DOTNUM_OF_LINE; i++)
{
Sprite* dot = Sprite::create(FileStuff::SLING_LINE_DOT);
float r = -((2.f / DOTNUM_OF_LINE)*(2.f / DOTNUM_OF_LINE) * (i*1.f - DOTNUM_OF_LINE / 2.f) * (i*1.f - DOTNUM_OF_LINE / 2.f)) + 1;
dot->setOpacity(r * 100);
dot->setScale(r * 2);
dot->setVisible(false);
m_expectLine.pushBack(dot);
addChild(dot, 1.0);
}
/*Make Before line*/
for (int i = 0; i < DOTNUM_OF_LINE; i++)
{
Sprite* dot = Sprite::create(FileStuff::SLING_LINE_DOT);
float r = -((2.f / DOTNUM_OF_LINE)*(2.f / DOTNUM_OF_LINE) * (i*1.f - DOTNUM_OF_LINE / 2.f) * (i*1.f - DOTNUM_OF_LINE / 2.f)) + 1;
dot->setOpacity(r * 100 * 0.5);
dot->setScale(r * 2);
dot->setVisible(false);
m_beforeLine.pushBack(dot);
addChild(dot, 1.0);
}
m_arm = Sprite::createWithSpriteFrameName(FileStuff::CHARACTER_ARM);
m_arm->setScale(SLING_SCALE);
m_arm->setRotation(DEFAULT_ARM);
m_arm->setAnchorPoint(Point(0.5, 0.4));
m_arm->setPosition(Vec2(0, 10));
addChild(m_arm, 1);
m_character = LoadCharacter();
addChild(m_character, 2);
EventListenerMouse* _mouseListener = EventListenerMouse::create();
_mouseListener->onMouseUp = CC_CALLBACK_1(Sling::Shot, this);
_mouseListener->onMouseDown = CC_CALLBACK_1(Sling::PullStart, this);
_mouseListener->onMouseMove = CC_CALLBACK_1(Sling::Pull, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(_mouseListener, this);
return true;
}
void Sling::Reset()
{
ChangeToEmpty();
}
void Sling::ShotComplete()
{
ChangeToEmpty();
}
void Sling::LoadBullet()
{
ChangeToLoaded();
}
Point Sling::GetStartLocation()
{
return getPosition();
}
Sprite* Sling::LoadCharacter()
{
Sprite* character = Sprite::createWithSpriteFrameName(FileStuff::CHARACTER_HARDPIXEL);
character->setPosition(Vec2::ZERO);
return character;
}
void Sling::PullStart(Event* e)
{
if (m_status != STATUS::LOADED)
{
return;
}
/*Pull mouse ġ Ÿ */
EventMouse* evMouse = static_cast<EventMouse*>(e);
Point mouseLocation = evMouse->getLocationInView();
Point startLocation = GetStartLocation();
float distance = startLocation.getDistance(mouseLocation);
if (distance > CLICK_RANGE)
{
return;
}
m_character->removeFromParent();
m_character = Sprite::createWithSpriteFrameName(FileStuff::CHARACTER_SELECTED);
addChild(m_character, 2);
ChangeToPulling();
}
void Sling::Pull(Event* e)
{
if (m_status != STATUS::PULLING)
{
return;
}
EventMouse* evMouse = static_cast<EventMouse*>(e);
Point mouseLocation = evMouse->getLocationInView();
Point startLocation = GetStartLocation();
m_shotAngle = startLocation - mouseLocation;
if (m_shotAngle.getAngle() <= Vec2::ZERO.getAngle())
{
m_shotAngle = Vec2::ZERO;
return;
}
m_shotPower = startLocation.getDistance(mouseLocation);
if (m_shotPower > MAX_POWER)
{
m_shotAngle = m_shotAngle / (m_shotPower / MAX_POWER);
m_shotPower = MAX_POWER;
}
/*Set Position expect line */
for (int i = 0; i < m_expectLine.size(); i++)
{
Sprite* dot = m_expectLine.at(i);
dot->setPosition(m_shotAngle *m_shotPower/MAX_POWER * i);
}
// set rotation arm angle
m_arm->setRotation(-m_shotAngle.getAngle()*60 + 90);
}
void Sling::Shot(Event* e)
{
if (m_status != STATUS::PULLING)
{
return;
}
if (m_shotAngle.getAngle() <= Vec2::ZERO.getAngle())
{
m_shotAngle = Vec2::ZERO;
m_status = STATUS::LOADED;
for (int i = 0; i < m_expectLine.size(); i++)
{
Sprite* dot = m_expectLine.at(i);
dot->setVisible(false);
}
return;
}
//fix shot angle,power from last pointer position.
Pull(e);
/*Set Position before line */
for (int i = 0; i < m_beforeLine.size(); i++)
{
Sprite* dot = m_beforeLine.at(i);
dot->setPosition(m_shotAngle *m_shotPower / MAX_POWER * i);
dot->setVisible(true);
}
ChangeToShotted();
GameManager* gm = GameManager::GetInstance();
gm->ShotBullet(this);
m_character->removeFromParent();
m_character = Sprite::createWithSpriteFrameName(FileStuff::CHARACTER_HARDPIXEL);
addChild(m_character, 2);
}
void Sling::RemoveDots()
{
for (Sprite* dot : m_expectLine)
{
dot->removeFromParent();
}
for (Sprite* dot : m_beforeLine)
{
dot->removeFromParent();
}
}
Vec2 Sling::GetDirection()
{
return m_shotAngle;
}
float Sling::GetAngleInRadian()
{
return m_shotAngle.getAngle();
}
float Sling::GetRotationAngle()
{
return -GetAngleInRadian() / 3.14 * 180 + 90;
}
float Sling::GetSpeed()
{
return m_shotPower;
}
bool Sling::IsShotted() // --> üũ
{
if (m_status == STATUS::SHOTTED)
return true;
else
return false;
}
void Sling::ChangeToLoaded() //empty -> load
{
if (m_status != STATUS::EMPTY)
return;
m_status = STATUS::LOADED;
}
void Sling::ChangeToPulling() //loaded -> pulling
{
if (m_status != STATUS::LOADED)
return;
m_status = STATUS::PULLING;
for (Sprite* dot : m_expectLine)
{
dot->setVisible(true);
}
}
void Sling::ChangeToShotted() //pullig -> shotted
{
if (m_status != STATUS::PULLING)
return;
m_status = STATUS::SHOTTED;
for (Sprite* dot : m_expectLine)
{
dot->setVisible(false);
}
}
void Sling::ChangeToEmpty() //shotted -> empty
{
m_status = STATUS::EMPTY;
}
|
#include "stdafx.h"
#include "Sling.h"
#include "GameManager.h"
#include "FileStuff.h"
#include <SimpleAudioEngine.h>
Sling::Sling() : m_expectLine(), m_shotAngle(Vec2(0, 0)), m_shotPower(0), m_arm(nullptr), m_character(nullptr)
{
///# ڸ ̿ ʱȭ å Ѵ. (Ŀ ٸ Լ ʱȭ ϴ..)
}
bool Sling::init()
{
if (Node::init() == false)
{
return false;
}
//set Name
setName("Sling");
//set Empey status
ChangeToEmpty();
//set some frame work variable
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
//set position of character
setPosition(SLING_POSITION);
/*Make Expect line*/
for (int i = 0; i < DOTNUM_OF_LINE; i++)
{
Sprite* dot = Sprite::create(FileStuff::SLING_LINE_DOT);
float r = -((2.f / DOTNUM_OF_LINE)*(2.f / DOTNUM_OF_LINE) * (i*1.f - DOTNUM_OF_LINE / 2.f) * (i*1.f - DOTNUM_OF_LINE / 2.f)) + 1;
dot->setOpacity(r * 100);
dot->setScale(r * 2);
dot->setVisible(false);
m_expectLine.pushBack(dot);
addChild(dot, 1.0);
}
/*Make Before line*/
for (int i = 0; i < DOTNUM_OF_LINE; i++)
{
Sprite* dot = Sprite::create(FileStuff::SLING_LINE_DOT);
float r = -((2.f / DOTNUM_OF_LINE)*(2.f / DOTNUM_OF_LINE) * (i*1.f - DOTNUM_OF_LINE / 2.f) * (i*1.f - DOTNUM_OF_LINE / 2.f)) + 1;
dot->setOpacity(r * 100 * 0.5);
dot->setScale(r * 2);
dot->setVisible(false);
m_beforeLine.pushBack(dot);
addChild(dot, 1.0);
}
m_arm = Sprite::createWithSpriteFrameName(FileStuff::CHARACTER_ARM);
m_arm->setScale(SLING_SCALE);
m_arm->setRotation(DEFAULT_ARM);
m_arm->setAnchorPoint(Point(0.5, 0.4));
m_arm->setPosition(Vec2(0, 10));
addChild(m_arm, 1);
m_character = LoadCharacter();
addChild(m_character, 2);
EventListenerMouse* _mouseListener = EventListenerMouse::create();
_mouseListener->onMouseUp = CC_CALLBACK_1(Sling::Shot, this);
_mouseListener->onMouseDown = CC_CALLBACK_1(Sling::PullStart, this);
_mouseListener->onMouseMove = CC_CALLBACK_1(Sling::Pull, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(_mouseListener, this);
return true;
}
void Sling::Reset()
{
ChangeToEmpty();
}
void Sling::ShotComplete()
{
ChangeToEmpty();
}
void Sling::LoadBullet()
{
ChangeToLoaded();
}
Point Sling::GetStartLocation()
{
return getPosition();
}
Sprite* Sling::LoadCharacter()
{
Sprite* character = Sprite::createWithSpriteFrameName(FileStuff::CHARACTER_HARDPIXEL);
character->setPosition(Vec2::ZERO);
return character;
}
void Sling::PullStart(Event* e)
{
if (m_status != STATUS::LOADED)
{
return;
}
/*Pull mouse ġ Ÿ */
EventMouse* evMouse = static_cast<EventMouse*>(e);
Point mouseLocation = evMouse->getLocationInView();
Point startLocation = GetStartLocation();
float distance = startLocation.getDistance(mouseLocation);
if (distance > CLICK_RANGE)
{
return;
}
m_character->removeFromParent();
m_character = Sprite::createWithSpriteFrameName(FileStuff::CHARACTER_SELECTED);
addChild(m_character, 2);
ChangeToPulling();
}
void Sling::Pull(Event* e)
{
if (m_status != STATUS::PULLING)
{
return;
}
EventMouse* evMouse = static_cast<EventMouse*>(e);
Point mouseLocation = evMouse->getLocationInView();
Point startLocation = GetStartLocation();
m_shotAngle = mouseLocation - startLocation;
if (m_shotAngle.getAngle() <= Vec2::ZERO.getAngle())
{
m_shotAngle = Vec2::ZERO;
return;
}
m_shotPower = startLocation.getDistance(mouseLocation);
if (m_shotPower > MAX_POWER)
{
m_shotAngle = m_shotAngle / (m_shotPower / MAX_POWER);
m_shotPower = MAX_POWER;
}
/*Set Position expect line */
for (int i = 0; i < m_expectLine.size(); i++)
{
Sprite* dot = m_expectLine.at(i);
dot->setPosition(m_shotAngle *m_shotPower/MAX_POWER * i);
}
// set rotation arm angle
m_arm->setRotation(-m_shotAngle.getAngle()*60 + 90);
}
void Sling::Shot(Event* e)
{
if (m_status != STATUS::PULLING)
{
return;
}
if (m_shotAngle.getAngle() <= Vec2::ZERO.getAngle())
{
m_shotAngle = Vec2::ZERO;
m_status = STATUS::LOADED;
for (int i = 0; i < m_expectLine.size(); i++)
{
Sprite* dot = m_expectLine.at(i);
dot->setVisible(false);
}
return;
}
//fix shot angle,power from last pointer position.
Pull(e);
/*Set Position before line */
for (int i = 0; i < m_beforeLine.size(); i++)
{
Sprite* dot = m_beforeLine.at(i);
dot->setPosition(m_shotAngle *m_shotPower / MAX_POWER * i);
dot->setVisible(true);
}
ChangeToShotted();
GameManager* gm = GameManager::GetInstance();
gm->ShotBullet(this);
m_character->removeFromParent();
m_character = Sprite::createWithSpriteFrameName(FileStuff::CHARACTER_HARDPIXEL);
addChild(m_character, 2);
}
void Sling::RemoveDots()
{
for (Sprite* dot : m_expectLine)
{
dot->removeFromParent();
}
for (Sprite* dot : m_beforeLine)
{
dot->removeFromParent();
}
}
Vec2 Sling::GetDirection()
{
return m_shotAngle;
}
float Sling::GetAngleInRadian()
{
return m_shotAngle.getAngle();
}
float Sling::GetRotationAngle()
{
return -GetAngleInRadian() / 3.14 * 180 + 90;
}
float Sling::GetSpeed()
{
return m_shotPower;
}
bool Sling::IsShotted() // --> üũ
{
if (m_status == STATUS::SHOTTED)
return true;
else
return false;
}
void Sling::ChangeToLoaded() //empty -> load
{
if (m_status != STATUS::EMPTY)
return;
m_status = STATUS::LOADED;
}
void Sling::ChangeToPulling() //loaded -> pulling
{
if (m_status != STATUS::LOADED)
return;
m_status = STATUS::PULLING;
for (Sprite* dot : m_expectLine)
{
dot->setVisible(true);
}
}
void Sling::ChangeToShotted() //pullig -> shotted
{
if (m_status != STATUS::PULLING)
return;
m_status = STATUS::SHOTTED;
for (Sprite* dot : m_expectLine)
{
dot->setVisible(false);
}
}
void Sling::ChangeToEmpty() //shotted -> empty
{
m_status = STATUS::EMPTY;
}
|
change sling pull point
|
change sling pull point
|
C++
|
mit
|
kimsin3003/X10,kimsin3003/X10,kimsin3003/X10,kimsin3003/X10,kimsin3003/X10
|
cdfdca8cb43f9ba93b93253383c502900383d7ca
|
thrust/detail/device/cuda/for_each.inl
|
thrust/detail/device/cuda/for_each.inl
|
/*
* Copyright 2008-2010 NVIDIA 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.
*/
/*! \file for_each.inl
* \brief Inline file for for_each.h.
*/
#include <limits>
#include <thrust/detail/device/dereference.h>
#include <thrust/detail/device/cuda/launch_closure.h>
#include <thrust/detail/static_assert.h>
namespace thrust
{
namespace detail
{
namespace device
{
namespace cuda
{
template<typename RandomAccessIterator,
typename Size,
typename UnaryFunction>
struct for_each_n_closure
{
typedef void result_type;
RandomAccessIterator first;
Size n;
UnaryFunction f;
for_each_n_closure(RandomAccessIterator first_,
Size n_,
UnaryFunction f_)
: first(first_),
n(n_),
f(f_)
{}
// CUDA built-in variables require nvcc
#if THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC
__device__
result_type operator()(void)
{
const Size grid_size = blockDim.x * gridDim.x;
Size i = blockIdx.x * blockDim.x + threadIdx.x;
// advance iterator
first += i;
while(i < n)
{
f(thrust::detail::device::dereference(first));
i += grid_size;
first += grid_size;
}
}
#endif // THRUST_DEVICE_COMPILER_NVCC
};
template<typename InputIterator,
typename UnaryFunction>
void for_each(InputIterator first,
InputIterator last,
UnaryFunction f)
{
// we're attempting to launch a kernel, assert we're compiling with nvcc
// ========================================================================
// X Note to the user: If you've found this line due to a compiler error, X
// X you need to compile your code using nvcc, rather than g++ or cl.exe X
// ========================================================================
THRUST_STATIC_ASSERT( (depend_on_instantiation<InputIterator, THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC>::value) );
if (first >= last) return; //empty range
typedef typename thrust::iterator_traits<InputIterator>::difference_type difference_type;
difference_type n = last - first;
if ((sizeof(difference_type) > sizeof(unsigned int))
&& n > difference_type(std::numeric_limits<unsigned int>::max())) // convert to difference_type to avoid a warning
{
// n is large, must use 64-bit indices
typedef for_each_n_closure<InputIterator, difference_type, UnaryFunction> Closure;
Closure closure(first, last - first, f);
launch_closure(closure, last - first);
}
else
{
// n is small, 32-bit indices are sufficient
typedef for_each_n_closure<InputIterator, unsigned int, UnaryFunction> Closure;
Closure closure(first, static_cast<unsigned int>(n), f);
launch_closure(closure, static_cast<unsigned int>(n));
}
}
} // end namespace cuda
} // end namespace device
} // end namespace detail
} // end namespace thrust
|
/*
* Copyright 2008-2010 NVIDIA 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.
*/
/*! \file for_each.inl
* \brief Inline file for for_each.h.
*/
#include <limits>
#include <thrust/detail/config.h>
#include <thrust/detail/device/dereference.h>
#include <thrust/detail/device/cuda/launch_closure.h>
#include <thrust/detail/static_assert.h>
namespace thrust
{
namespace detail
{
namespace device
{
namespace cuda
{
template<typename RandomAccessIterator,
typename Size,
typename UnaryFunction>
struct for_each_n_closure
{
typedef void result_type;
RandomAccessIterator first;
Size n;
UnaryFunction f;
for_each_n_closure(RandomAccessIterator first_,
Size n_,
UnaryFunction f_)
: first(first_),
n(n_),
f(f_)
{}
// CUDA built-in variables require nvcc
#if THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC
__device__
result_type operator()(void)
{
const Size grid_size = blockDim.x * gridDim.x;
Size i = blockIdx.x * blockDim.x + threadIdx.x;
// advance iterator
first += i;
while(i < n)
{
f(thrust::detail::device::dereference(first));
i += grid_size;
first += grid_size;
}
}
#endif // THRUST_DEVICE_COMPILER_NVCC
};
template<typename InputIterator,
typename UnaryFunction>
void for_each(InputIterator first,
InputIterator last,
UnaryFunction f)
{
// we're attempting to launch a kernel, assert we're compiling with nvcc
// ========================================================================
// X Note to the user: If you've found this line due to a compiler error, X
// X you need to compile your code using nvcc, rather than g++ or cl.exe X
// ========================================================================
THRUST_STATIC_ASSERT( (depend_on_instantiation<InputIterator, THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC>::value) );
if (first >= last) return; //empty range
typedef typename thrust::iterator_traits<InputIterator>::difference_type difference_type;
difference_type n = last - first;
if ((sizeof(difference_type) > sizeof(unsigned int))
&& n > difference_type(std::numeric_limits<unsigned int>::max())) // convert to difference_type to avoid a warning
{
// n is large, must use 64-bit indices
typedef for_each_n_closure<InputIterator, difference_type, UnaryFunction> Closure;
Closure closure(first, last - first, f);
launch_closure(closure, last - first);
}
else
{
// n is small, 32-bit indices are sufficient
typedef for_each_n_closure<InputIterator, unsigned int, UnaryFunction> Closure;
Closure closure(first, static_cast<unsigned int>(n), f);
launch_closure(closure, static_cast<unsigned int>(n));
}
}
} // end namespace cuda
} // end namespace device
} // end namespace detail
} // end namespace thrust
|
Add #include <thrust/detail/config.h> to cuda/for_each.inl as it relies on THRUST_DEVICE_COMPILER Reported by Ryuta
|
Add #include <thrust/detail/config.h> to cuda/for_each.inl as it relies on THRUST_DEVICE_COMPILER
Reported by Ryuta
--HG--
extra : convert_revision : svn%3A83215879-3e5a-4751-8c9d-778f44bb06a5/trunk%40877
|
C++
|
apache-2.0
|
jbrownbridge/thrust,jbrownbridge/thrust,jbrownbridge/thrust,jbrownbridge/thrust
|
981fbfd51009ce247e010c284046e4fba768365e
|
src/unittest/snapshots_test.cc
|
src/unittest/snapshots_test.cc
|
#include "unittest/gtest.hpp"
#include <boost/bind.hpp>
#include <cstdlib>
#include <string>
#include <functional>
#include "server/cmd_args.hpp"
#include "serializer/log/log_serializer.hpp"
#include "serializer/translator.hpp"
#include "btree/slice.hpp"
#include "buffer_cache/transactor.hpp"
#include "buffer_cache/co_functions.hpp"
#include "concurrency/count_down_latch.hpp"
namespace unittest {
class temp_file_t {
char * filename;
public:
temp_file_t(const char * tmpl) {
size_t len = strlen(tmpl);
filename = new char[len+1];
strncpy(filename, tmpl, len);
int fd = mkstemp(filename);
guarantee_err(fd != -1, "Couldn't create a temporary file");
close(fd);
}
operator const char *() {
return filename;
}
~temp_file_t() {
unlink(filename);
delete [] filename;
}
};
struct tester_t : public thread_message_t {
thread_pool_t thread_pool;
tester_t() : thread_pool(1) { }
void run() {
thread_pool.run(this);
}
private:
static buf_t *create(transactor_t& txor) {
return txor.transaction()->allocate();
}
static void snap(transactor_t& txor) {
txor.transaction()->snapshot();
}
static buf_t *acq(transactor_t& txor, block_id_t block_id, access_t mode = rwi_read) {
thread_saver_t saver;
return co_acquire_block(saver, txor.transaction(), block_id, mode);
}
static void change_value(buf_t *buf, uint32_t value) {
buf->set_data(const_cast<void *>(buf->get_data_read()), &value, sizeof(value));
}
static uint32_t get_value(buf_t *buf) {
return *((uint32_t*) buf->get_data_read());
}
struct acquiring_coro_t {
buf_t *result;
bool signaled;
transactor_t& txor;
block_id_t block_id;
access_t mode;
acquiring_coro_t(transactor_t& txor, block_id_t block_id, access_t mode) : result(NULL), signaled(false), txor(txor), block_id(block_id), mode(mode) { }
void run() {
result = acq(txor, block_id, mode);
signaled = true;
}
};
static buf_t *acq_check_if_blocks_until_buf_released(transactor_t& acquiring_txor, buf_t *already_acquired_block, access_t acquire_mode, bool do_release, bool &blocked) {
acquiring_coro_t acq_coro(acquiring_txor, already_acquired_block->get_block_id(), acquire_mode);
coro_t::spawn(boost::bind(&acquiring_coro_t::run, &acq_coro));
coro_t::nap(500);
blocked = !acq_coro.signaled;
if (do_release) {
already_acquired_block->release();
if (blocked) {
coro_t::nap(500);
rassert(acq_coro.signaled, "Buf release must have unblocked the coroutine trying to acquire the buf. May be a bug in the test.");
}
}
return acq_coro.result;
}
void snapshot_txn_runner(cache_t *cache, count_down_latch_t *stop_latch) {
thread_saver_t saver;
transactor_t snap_txor(saver, cache, rwi_read, repli_timestamp::invalid);
snap_txor.transaction()->snapshot();
debugf("snapshot.done\n");
stop_latch->count_down();
}
void main() {
temp_file_t db_file("/tmp/rdb_unittest.XXXXXX");
{
cmd_config_t config;
config.store_dynamic_config.cache.max_dirty_size = config.store_dynamic_config.cache.max_size / 10;
// Set ridiculously high flush_* values, so that flush lock doesn't block the txn creation
config.store_dynamic_config.cache.flush_timer_ms = 1000000;
config.store_dynamic_config.cache.flush_dirty_size = 1000000000;
log_serializer_private_dynamic_config_t ser_config;
ser_config.db_filename = db_file;
log_serializer_t::create(&config.store_dynamic_config.serializer, &ser_config, &config.store_static_config.serializer);
log_serializer_t serializer(&config.store_dynamic_config.serializer, &ser_config);
std::vector<serializer_t *> serializers;
serializers.push_back(&serializer);
serializer_multiplexer_t::create(serializers, 1);
serializer_multiplexer_t multiplexer(serializers);
btree_slice_t::create(multiplexer.proxies[0], &config.store_static_config.cache);
btree_slice_t slice(multiplexer.proxies[0], &config.store_dynamic_config.cache);
cache_t *cache = slice.cache();
int init_value = 0x12345678;
int changed_value = 0x87654321;
thread_saver_t saver;
// t0:create(A), t1:snap(), t1:acq(A) blocks, t0:release(A), t1 unblocks, t1 sees the block.
{
transactor_t t0(saver, cache, rwi_write, 0, current_time());
transactor_t t1(saver, cache, rwi_read, 0, repli_timestamp::invalid);
buf_t *buf0 = create(t0);
snap(t1);
bool blocked = false;
buf_t *buf1 = acq_check_if_blocks_until_buf_released(t1, buf0, rwi_read, true, blocked);
EXPECT_TRUE(blocked);
EXPECT_TRUE(buf1 != NULL);
if (buf1)
buf1->release();
}
// t0:create(A), t0:release(A), t1:snap(), t2:acqw(A), t2:change(A), t2:release(A), t1:acq(A), t1 sees the change
{
transactor_t t0(saver, cache, rwi_write, 0, current_time());
transactor_t t1(saver, cache, rwi_read, 0, repli_timestamp::invalid);
transactor_t t2(saver, cache, rwi_write, 0, current_time());
buf_t *buf0 = create(t0);
block_id_t block_A = buf0->get_block_id();
change_value(buf0, init_value);
buf0->release();
snap(t1);
buf_t *buf2 = acq(t2, block_A, rwi_write);
change_value(buf2, changed_value);
buf2->release();
buf_t *buf1 = acq(t1, block_A, rwi_read);
EXPECT_EQ(changed_value, get_value(buf1));
buf1->release();
}
// t0:create(A), t0:release(A), t1:snap(), t1:acq(A), t2:acqw(A), t2:change(A), t2:release(A), t3:snap(), t3:acq(A), t1 doesn't see the change, t3 does see the change
{
transactor_t t0(saver, cache, rwi_write, 0, current_time());
transactor_t t1(saver, cache, rwi_read, 0, repli_timestamp::invalid);
transactor_t t2(saver, cache, rwi_write, 0, current_time());
transactor_t t3(saver, cache, rwi_read, 0, repli_timestamp::invalid);
buf_t *buf0 = create(t0);
block_id_t block_A = buf0->get_block_id();
change_value(buf0, init_value);
buf0->release();
snap(t1);
buf_t *buf1 = acq(t1, block_A, rwi_read);
bool blocked = true;
buf_t *buf2 = acq_check_if_blocks_until_buf_released(t2, buf1, rwi_write, false, blocked);
EXPECT_FALSE(blocked);
change_value(buf2, changed_value);
snap(t3);
buf_t *buf3 = acq_check_if_blocks_until_buf_released(t2, buf2, rwi_read, true, blocked);
EXPECT_TRUE(blocked);
EXPECT_EQ(init_value, get_value(buf1));
EXPECT_EQ(changed_value, get_value(buf3));
buf1->release();
buf3->release();
}
// t0:create(A,B), t0:release(A,B), t1:snap(), t1:acq(A), t2:acqw(A) doesn't block, t2:acqw(B), t1:acq(B) doesn't block
{
transactor_t t0(saver, cache, rwi_write, 0, current_time());
transactor_t t1(saver, cache, rwi_read, 0, repli_timestamp::invalid);
transactor_t t2(saver, cache, rwi_write, 0, current_time());
buf_t *buf0_A = create(t0);
buf_t *buf0_B = create(t0);
block_id_t block_A = buf0_A->get_block_id();
block_id_t block_B = buf0_B->get_block_id();
change_value(buf0_A, init_value);
change_value(buf0_B, init_value);
buf0_A->release();
buf0_B->release();
snap(t1);
buf_t *buf1_A = acq(t1, block_A, rwi_read);
bool blocked = true;
buf_t *buf2_A = acq_check_if_blocks_until_buf_released(t2, buf1_A, rwi_write, false, blocked);
EXPECT_FALSE(blocked);
buf_t *buf2_B = acq(t2, block_B, rwi_write);
buf_t *buf1_B = acq_check_if_blocks_until_buf_released(t1, buf2_B, rwi_read, false, blocked);
EXPECT_FALSE(blocked);
buf1_A->release();
buf2_A->release();
buf1_B->release();
buf2_B->release();
}
// t0:create(A,B), t0:release(A,B), t1:acqw(A), t1:acqw(B), t1:release(A), t2:snap(), t2:acq(A), t2:release(A), t2:acq(B) blocks, t1:release(B), t2 unblocks
{
transactor_t t0(saver, cache, rwi_write, 0, current_time());
transactor_t t1(saver, cache, rwi_write, 0, current_time());
transactor_t t2(saver, cache, rwi_read, 0, repli_timestamp::invalid);
buf_t *buf0_A = create(t0);
buf_t *buf0_B = create(t0);
block_id_t block_A = buf0_A->get_block_id();
block_id_t block_B = buf0_B->get_block_id();
change_value(buf0_A, init_value);
change_value(buf0_B, init_value);
buf0_A->release();
buf0_B->release();
buf_t *buf1_A = acq(t1, block_A, rwi_write);
buf_t *buf1_B = acq(t1, block_B, rwi_write);
change_value(buf1_A, changed_value);
change_value(buf1_B, changed_value);
buf1_A->release();
snap(t2);
buf_t *buf2_A = acq(t1, block_A, rwi_read);
EXPECT_EQ(changed_value, get_value(buf2_A));
buf2_A->release();
bool blocked = false;
buf_t *buf2_B = acq_check_if_blocks_until_buf_released(t2, buf1_B, rwi_read, true, blocked);
EXPECT_TRUE(blocked);
EXPECT_EQ(changed_value, get_value(buf2_B));
buf2_B->release();
}
debugf("tests finished\n");
}
debugf("thread_pool.shutdown()\n");
thread_pool.shutdown();
}
void on_thread_switch() {
coro_t::spawn(boost::bind(&tester_t::main, this));
}
};
TEST(SnapshotsTest, server_start) {
tester_t test;
test.run();
}
}
|
#include "unittest/gtest.hpp"
#include <boost/bind.hpp>
#include <cstdlib>
#include <string>
#include <functional>
#include "server/cmd_args.hpp"
#include "serializer/log/log_serializer.hpp"
#include "serializer/translator.hpp"
#include "btree/slice.hpp"
#include "buffer_cache/transactor.hpp"
#include "buffer_cache/co_functions.hpp"
#include "concurrency/count_down_latch.hpp"
namespace unittest {
class temp_file_t {
char * filename;
public:
temp_file_t(const char * tmpl) {
size_t len = strlen(tmpl);
filename = new char[len+1];
strncpy(filename, tmpl, len);
int fd = mkstemp(filename);
guarantee_err(fd != -1, "Couldn't create a temporary file");
close(fd);
}
operator const char *() {
return filename;
}
~temp_file_t() {
unlink(filename);
delete [] filename;
}
};
struct tester_t : public thread_message_t {
thread_pool_t thread_pool;
tester_t() : thread_pool(1) { }
void run() {
thread_pool.run(this);
}
private:
static buf_t *create(transactor_t& txor) {
return txor.transaction()->allocate();
}
static void snap(transactor_t& txor) {
txor.transaction()->snapshot();
}
static buf_t *acq(transactor_t& txor, block_id_t block_id, access_t mode = rwi_read) {
thread_saver_t saver;
return co_acquire_block(saver, txor.transaction(), block_id, mode);
}
static void change_value(buf_t *buf, uint32_t value) {
buf->set_data(const_cast<void *>(buf->get_data_read()), &value, sizeof(value));
}
static uint32_t get_value(buf_t *buf) {
return *((uint32_t*) buf->get_data_read());
}
struct acquiring_coro_t {
buf_t *result;
bool signaled;
transactor_t& txor;
block_id_t block_id;
access_t mode;
acquiring_coro_t(transactor_t& txor, block_id_t block_id, access_t mode) : result(NULL), signaled(false), txor(txor), block_id(block_id), mode(mode) { }
void run() {
result = acq(txor, block_id, mode);
signaled = true;
}
};
static buf_t *acq_check_if_blocks_until_buf_released(transactor_t& acquiring_txor, buf_t *already_acquired_block, access_t acquire_mode, bool do_release, bool &blocked) {
acquiring_coro_t acq_coro(acquiring_txor, already_acquired_block->get_block_id(), acquire_mode);
coro_t::spawn(boost::bind(&acquiring_coro_t::run, &acq_coro));
coro_t::nap(500);
blocked = !acq_coro.signaled;
if (do_release) {
already_acquired_block->release();
if (blocked) {
coro_t::nap(500);
rassert(acq_coro.signaled, "Buf release must have unblocked the coroutine trying to acquire the buf. May be a bug in the test.");
}
}
return acq_coro.result;
}
void snapshot_txn_runner(cache_t *cache, count_down_latch_t *stop_latch) {
thread_saver_t saver;
transactor_t snap_txor(saver, cache, rwi_read, repli_timestamp::invalid);
snap_txor.transaction()->snapshot();
debugf("snapshot.done\n");
stop_latch->count_down();
}
void main() {
temp_file_t db_file("/tmp/rdb_unittest.XXXXXX");
{
cmd_config_t config;
config.store_dynamic_config.cache.max_dirty_size = config.store_dynamic_config.cache.max_size / 10;
// Set ridiculously high flush_* values, so that flush lock doesn't block the txn creation
config.store_dynamic_config.cache.flush_timer_ms = 1000000;
config.store_dynamic_config.cache.flush_dirty_size = 1000000000;
log_serializer_private_dynamic_config_t ser_config;
ser_config.db_filename = db_file;
log_serializer_t::create(&config.store_dynamic_config.serializer, &ser_config, &config.store_static_config.serializer);
log_serializer_t serializer(&config.store_dynamic_config.serializer, &ser_config);
std::vector<serializer_t *> serializers;
serializers.push_back(&serializer);
serializer_multiplexer_t::create(serializers, 1);
serializer_multiplexer_t multiplexer(serializers);
btree_slice_t::create(multiplexer.proxies[0], &config.store_static_config.cache);
btree_slice_t slice(multiplexer.proxies[0], &config.store_dynamic_config.cache);
cache_t *cache = slice.cache();
int init_value = 0x12345678;
int changed_value = 0x87654321;
thread_saver_t saver;
// t0:create(A), t1:snap(), t1:acq(A) blocks, t0:release(A), t1 unblocks, t1 sees the block.
{
transactor_t t0(saver, cache, rwi_write, 0, current_time());
transactor_t t1(saver, cache, rwi_read, 0, repli_timestamp::invalid);
buf_t *buf0 = create(t0);
snap(t1);
bool blocked = false;
buf_t *buf1 = acq_check_if_blocks_until_buf_released(t1, buf0, rwi_read, true, blocked);
EXPECT_TRUE(blocked);
EXPECT_TRUE(buf1 != NULL);
if (buf1)
buf1->release();
}
// t0:create(A), t0:release(A), t1:snap(), t2:acqw(A), t2:change(A), t2:release(A), t1:acq(A), t1 sees the change
{
transactor_t t0(saver, cache, rwi_write, 0, current_time());
transactor_t t1(saver, cache, rwi_read, 0, repli_timestamp::invalid);
transactor_t t2(saver, cache, rwi_write, 0, current_time());
buf_t *buf0 = create(t0);
block_id_t block_A = buf0->get_block_id();
change_value(buf0, init_value);
buf0->release();
snap(t1);
buf_t *buf2 = acq(t2, block_A, rwi_write);
change_value(buf2, changed_value);
buf2->release();
buf_t *buf1 = acq(t1, block_A, rwi_read);
EXPECT_EQ(changed_value, get_value(buf1));
buf1->release();
}
// t0:create(A), t0:release(A), t1:snap(), t1:acq(A), t2:acqw(A), t2:change(A), t2:release(A), t3:snap(), t3:acq(A), t1 doesn't see the change, t3 does see the change
{
transactor_t t0(saver, cache, rwi_write, 0, current_time());
transactor_t t1(saver, cache, rwi_read, 0, repli_timestamp::invalid);
transactor_t t2(saver, cache, rwi_write, 0, current_time());
transactor_t t3(saver, cache, rwi_read, 0, repli_timestamp::invalid);
buf_t *buf0 = create(t0);
block_id_t block_A = buf0->get_block_id();
change_value(buf0, init_value);
buf0->release();
snap(t1);
buf_t *buf1 = acq(t1, block_A, rwi_read);
bool blocked = true;
buf_t *buf2 = acq_check_if_blocks_until_buf_released(t2, buf1, rwi_write, false, blocked);
EXPECT_FALSE(blocked);
change_value(buf2, changed_value);
snap(t3);
buf_t *buf3 = acq_check_if_blocks_until_buf_released(t2, buf2, rwi_read, true, blocked);
EXPECT_TRUE(blocked);
EXPECT_EQ(init_value, get_value(buf1));
EXPECT_EQ(changed_value, get_value(buf3));
buf1->release();
buf3->release();
}
// t0:create(A,B), t0:release(A,B), t1:snap(), t1:acq(A), t2:acqw(A) doesn't block, t2:acqw(B), t1:acq(B) doesn't block
{
transactor_t t0(saver, cache, rwi_write, 0, current_time());
transactor_t t1(saver, cache, rwi_read, 0, repli_timestamp::invalid);
transactor_t t2(saver, cache, rwi_write, 0, current_time());
buf_t *buf0_A = create(t0);
buf_t *buf0_B = create(t0);
block_id_t block_A = buf0_A->get_block_id();
block_id_t block_B = buf0_B->get_block_id();
change_value(buf0_A, init_value);
change_value(buf0_B, init_value);
buf0_A->release();
buf0_B->release();
snap(t1);
buf_t *buf1_A = acq(t1, block_A, rwi_read);
bool blocked = true;
buf_t *buf2_A = acq_check_if_blocks_until_buf_released(t2, buf1_A, rwi_write, false, blocked);
EXPECT_FALSE(blocked);
buf_t *buf2_B = acq(t2, block_B, rwi_write);
buf_t *buf1_B = acq_check_if_blocks_until_buf_released(t1, buf2_B, rwi_read, false, blocked);
EXPECT_FALSE(blocked);
buf1_A->release();
buf2_A->release();
buf1_B->release();
buf2_B->release();
}
// t0:create(A,B), t0:release(A,B), t1:acqw(A), t1:acqw(B), t1:release(A), t2:snap(), t2:acq(A), t2:release(A), t2:acq(B) blocks, t1:release(B), t2 unblocks
{
transactor_t t0(saver, cache, rwi_write, 0, current_time());
transactor_t t1(saver, cache, rwi_write, 0, current_time());
transactor_t t2(saver, cache, rwi_read, 0, repli_timestamp::invalid);
buf_t *buf0_A = create(t0);
buf_t *buf0_B = create(t0);
block_id_t block_A = buf0_A->get_block_id();
block_id_t block_B = buf0_B->get_block_id();
change_value(buf0_A, init_value);
change_value(buf0_B, init_value);
buf0_A->release();
buf0_B->release();
buf_t *buf1_A = acq(t1, block_A, rwi_write);
buf_t *buf1_B = acq(t1, block_B, rwi_write);
change_value(buf1_A, changed_value);
change_value(buf1_B, changed_value);
buf1_A->release();
snap(t2);
buf_t *buf2_A = acq(t1, block_A, rwi_read);
EXPECT_EQ(changed_value, get_value(buf2_A));
buf2_A->release();
bool blocked = false;
buf_t *buf2_B = acq_check_if_blocks_until_buf_released(t2, buf1_B, rwi_read, true, blocked);
EXPECT_TRUE(blocked);
EXPECT_EQ(changed_value, get_value(buf2_B));
buf2_B->release();
}
// issue 194 unit-test
// t0:create(A,B), t0:acqw(A), t0:release(A), t1:acqw(A), t2:snap(), t2:acq(A) blocks, t1:release(A), t0:acqw(B), t0:release(B), t1:acqw(B) (fails with assertion if issue 194 is not fixed)
{
transactor_t t0(saver, cache, rwi_write, 0, current_time());
transactor_t t1(saver, cache, rwi_write, 0, current_time());
transactor_t t2(saver, cache, rwi_read, 0, repli_timestamp::invalid);
buf_t *buf0_A = create(t0);
buf_t *buf0_B = create(t0);
block_id_t block_A = buf0_A->get_block_id();
block_id_t block_B = buf0_B->get_block_id();
change_value(buf0_A, init_value);
change_value(buf0_B, init_value);
buf0_A->release();
buf0_B->release();
buf0_A = acq(t0, block_A, rwi_write);
buf0_A->release();
buf_t *buf1_A = acq(t1, block_A, rwi_write);
snap(t2);
bool blocked = false;
buf_t *buf2_A = acq_check_if_blocks_until_buf_released(t2, buf1_A, rwi_read, true, blocked);
EXPECT_TRUE(blocked);
buf0_B = acq(t0, block_B, rwi_write);
buf0_B->release();
buf_t *buf1_B = acq(t1, block_B, rwi_write); // if issue 194 is not fixed, expect assertion failure here
buf2_A->release();
buf_t *buf2_B = acq_check_if_blocks_until_buf_released(t2, buf1_B, rwi_read, false, blocked);
EXPECT_FALSE(blocked);
buf1_B->release();
buf2_B->release();
}
debugf("tests finished\n");
}
debugf("thread_pool.shutdown()\n");
thread_pool.shutdown();
}
void on_thread_switch() {
coro_t::spawn(boost::bind(&tester_t::main, this));
}
};
TEST(SnapshotsTest, server_start) {
tester_t test;
test.run();
}
}
|
Add unit-test for issue 194
|
Add unit-test for issue 194
If issue 194 is present, the unit-test fails with an assertion failure.
Sorry, until it's fixed, our unit-test suite will die with an assertion,
because there's no way I can catch it.
|
C++
|
agpl-3.0
|
sontek/rethinkdb,mbroadst/rethinkdb,tempbottle/rethinkdb,tempbottle/rethinkdb,matthaywardwebdesign/rethinkdb,dparnell/rethinkdb,yaolinz/rethinkdb,robertjpayne/rethinkdb,sontek/rethinkdb,wujf/rethinkdb,jfriedly/rethinkdb,lenstr/rethinkdb,wojons/rethinkdb,ayumilong/rethinkdb,mquandalle/rethinkdb,elkingtonmcb/rethinkdb,wujf/rethinkdb,eliangidoni/rethinkdb,rrampage/rethinkdb,tempbottle/rethinkdb,nviennot/rethinkdb,yakovenkodenis/rethinkdb,RubenKelevra/rethinkdb,robertjpayne/rethinkdb,gdi2290/rethinkdb,AtnNn/rethinkdb,scripni/rethinkdb,AntouanK/rethinkdb,gavioto/rethinkdb,JackieXie168/rethinkdb,nviennot/rethinkdb,4talesa/rethinkdb,ajose01/rethinkdb,victorbriz/rethinkdb,AtnNn/rethinkdb,jfriedly/rethinkdb,ajose01/rethinkdb,dparnell/rethinkdb,mcanthony/rethinkdb,mcanthony/rethinkdb,bpradipt/rethinkdb,yaolinz/rethinkdb,RubenKelevra/rethinkdb,scripni/rethinkdb,jmptrader/rethinkdb,mquandalle/rethinkdb,sebadiaz/rethinkdb,catroot/rethinkdb,AtnNn/rethinkdb,captainpete/rethinkdb,dparnell/rethinkdb,bpradipt/rethinkdb,AntouanK/rethinkdb,bchavez/rethinkdb,lenstr/rethinkdb,bpradipt/rethinkdb,Qinusty/rethinkdb,captainpete/rethinkdb,bchavez/rethinkdb,matthaywardwebdesign/rethinkdb,yakovenkodenis/rethinkdb,alash3al/rethinkdb,AntouanK/rethinkdb,spblightadv/rethinkdb,matthaywardwebdesign/rethinkdb,wujf/rethinkdb,RubenKelevra/rethinkdb,yaolinz/rethinkdb,wkennington/rethinkdb,bpradipt/rethinkdb,4talesa/rethinkdb,marshall007/rethinkdb,wujf/rethinkdb,greyhwndz/rethinkdb,Wilbeibi/rethinkdb,marshall007/rethinkdb,mbroadst/rethinkdb,sontek/rethinkdb,JackieXie168/rethinkdb,grandquista/rethinkdb,gavioto/rethinkdb,sbusso/rethinkdb,jmptrader/rethinkdb,nviennot/rethinkdb,elkingtonmcb/rethinkdb,robertjpayne/rethinkdb,wkennington/rethinkdb,bchavez/rethinkdb,gdi2290/rethinkdb,RubenKelevra/rethinkdb,rrampage/rethinkdb,rrampage/rethinkdb,scripni/rethinkdb,4talesa/rethinkdb,matthaywardwebdesign/rethinkdb,ayumilong/rethinkdb,wojons/rethinkdb,eliangidoni/rethinkdb,eliangidoni/rethinkdb,jesseditson/rethinkdb,greyhwndz/rethinkdb,jmptrader/rethinkdb,JackieXie168/rethinkdb,grandquista/rethinkdb,niieani/rethinkdb,wkennington/rethinkdb,lenstr/rethinkdb,ayumilong/rethinkdb,wojons/rethinkdb,spblightadv/rethinkdb,sbusso/rethinkdb,mbroadst/rethinkdb,urandu/rethinkdb,KSanthanam/rethinkdb,eliangidoni/rethinkdb,gdi2290/rethinkdb,sbusso/rethinkdb,eliangidoni/rethinkdb,captainpete/rethinkdb,sbusso/rethinkdb,eliangidoni/rethinkdb,jfriedly/rethinkdb,wkennington/rethinkdb,rrampage/rethinkdb,mbroadst/rethinkdb,greyhwndz/rethinkdb,jfriedly/rethinkdb,losywee/rethinkdb,yakovenkodenis/rethinkdb,losywee/rethinkdb,urandu/rethinkdb,robertjpayne/rethinkdb,robertjpayne/rethinkdb,dparnell/rethinkdb,matthaywardwebdesign/rethinkdb,bchavez/rethinkdb,sbusso/rethinkdb,Wilbeibi/rethinkdb,robertjpayne/rethinkdb,spblightadv/rethinkdb,niieani/rethinkdb,alash3al/rethinkdb,jesseditson/rethinkdb,niieani/rethinkdb,bchavez/rethinkdb,jesseditson/rethinkdb,grandquista/rethinkdb,jmptrader/rethinkdb,jmptrader/rethinkdb,mcanthony/rethinkdb,pap/rethinkdb,yakovenkodenis/rethinkdb,JackieXie168/rethinkdb,AtnNn/rethinkdb,yakovenkodenis/rethinkdb,gavioto/rethinkdb,dparnell/rethinkdb,losywee/rethinkdb,catroot/rethinkdb,Wilbeibi/rethinkdb,ajose01/rethinkdb,spblightadv/rethinkdb,robertjpayne/rethinkdb,gavioto/rethinkdb,mquandalle/rethinkdb,bpradipt/rethinkdb,mquandalle/rethinkdb,grandquista/rethinkdb,Qinusty/rethinkdb,wujf/rethinkdb,gdi2290/rethinkdb,jesseditson/rethinkdb,Qinusty/rethinkdb,ajose01/rethinkdb,wojons/rethinkdb,ayumilong/rethinkdb,marshall007/rethinkdb,yakovenkodenis/rethinkdb,robertjpayne/rethinkdb,yaolinz/rethinkdb,RubenKelevra/rethinkdb,bchavez/rethinkdb,mcanthony/rethinkdb,AtnNn/rethinkdb,greyhwndz/rethinkdb,sbusso/rethinkdb,KSanthanam/rethinkdb,victorbriz/rethinkdb,losywee/rethinkdb,yakovenkodenis/rethinkdb,lenstr/rethinkdb,sontek/rethinkdb,4talesa/rethinkdb,AntouanK/rethinkdb,bpradipt/rethinkdb,niieani/rethinkdb,ayumilong/rethinkdb,urandu/rethinkdb,sebadiaz/rethinkdb,4talesa/rethinkdb,urandu/rethinkdb,wojons/rethinkdb,marshall007/rethinkdb,losywee/rethinkdb,AntouanK/rethinkdb,nviennot/rethinkdb,marshall007/rethinkdb,victorbriz/rethinkdb,mbroadst/rethinkdb,urandu/rethinkdb,gavioto/rethinkdb,JackieXie168/rethinkdb,4talesa/rethinkdb,lenstr/rethinkdb,nviennot/rethinkdb,Wilbeibi/rethinkdb,wojons/rethinkdb,alash3al/rethinkdb,nviennot/rethinkdb,rrampage/rethinkdb,sebadiaz/rethinkdb,pap/rethinkdb,AntouanK/rethinkdb,jmptrader/rethinkdb,nviennot/rethinkdb,AtnNn/rethinkdb,spblightadv/rethinkdb,alash3al/rethinkdb,jfriedly/rethinkdb,RubenKelevra/rethinkdb,mcanthony/rethinkdb,wujf/rethinkdb,victorbriz/rethinkdb,eliangidoni/rethinkdb,sebadiaz/rethinkdb,Qinusty/rethinkdb,KSanthanam/rethinkdb,Wilbeibi/rethinkdb,rrampage/rethinkdb,gavioto/rethinkdb,4talesa/rethinkdb,sontek/rethinkdb,jfriedly/rethinkdb,greyhwndz/rethinkdb,KSanthanam/rethinkdb,matthaywardwebdesign/rethinkdb,grandquista/rethinkdb,greyhwndz/rethinkdb,yakovenkodenis/rethinkdb,ajose01/rethinkdb,scripni/rethinkdb,catroot/rethinkdb,wojons/rethinkdb,eliangidoni/rethinkdb,elkingtonmcb/rethinkdb,ayumilong/rethinkdb,victorbriz/rethinkdb,JackieXie168/rethinkdb,greyhwndz/rethinkdb,losywee/rethinkdb,mbroadst/rethinkdb,JackieXie168/rethinkdb,AntouanK/rethinkdb,tempbottle/rethinkdb,matthaywardwebdesign/rethinkdb,greyhwndz/rethinkdb,wkennington/rethinkdb,bpradipt/rethinkdb,jesseditson/rethinkdb,ajose01/rethinkdb,bchavez/rethinkdb,niieani/rethinkdb,alash3al/rethinkdb,elkingtonmcb/rethinkdb,wkennington/rethinkdb,sontek/rethinkdb,pap/rethinkdb,jmptrader/rethinkdb,RubenKelevra/rethinkdb,RubenKelevra/rethinkdb,4talesa/rethinkdb,lenstr/rethinkdb,Qinusty/rethinkdb,bpradipt/rethinkdb,tempbottle/rethinkdb,Qinusty/rethinkdb,JackieXie168/rethinkdb,ayumilong/rethinkdb,KSanthanam/rethinkdb,bchavez/rethinkdb,gavioto/rethinkdb,jfriedly/rethinkdb,KSanthanam/rethinkdb,grandquista/rethinkdb,spblightadv/rethinkdb,matthaywardwebdesign/rethinkdb,wkennington/rethinkdb,mcanthony/rethinkdb,scripni/rethinkdb,mcanthony/rethinkdb,lenstr/rethinkdb,scripni/rethinkdb,gavioto/rethinkdb,rrampage/rethinkdb,spblightadv/rethinkdb,catroot/rethinkdb,alash3al/rethinkdb,niieani/rethinkdb,mbroadst/rethinkdb,pap/rethinkdb,pap/rethinkdb,yaolinz/rethinkdb,catroot/rethinkdb,Wilbeibi/rethinkdb,captainpete/rethinkdb,grandquista/rethinkdb,gdi2290/rethinkdb,dparnell/rethinkdb,wujf/rethinkdb,losywee/rethinkdb,grandquista/rethinkdb,alash3al/rethinkdb,bchavez/rethinkdb,jfriedly/rethinkdb,ayumilong/rethinkdb,yaolinz/rethinkdb,tempbottle/rethinkdb,captainpete/rethinkdb,rrampage/rethinkdb,eliangidoni/rethinkdb,dparnell/rethinkdb,pap/rethinkdb,niieani/rethinkdb,Qinusty/rethinkdb,dparnell/rethinkdb,sontek/rethinkdb,victorbriz/rethinkdb,robertjpayne/rethinkdb,Qinusty/rethinkdb,scripni/rethinkdb,urandu/rethinkdb,captainpete/rethinkdb,sbusso/rethinkdb,urandu/rethinkdb,bpradipt/rethinkdb,elkingtonmcb/rethinkdb,nviennot/rethinkdb,tempbottle/rethinkdb,dparnell/rethinkdb,mquandalle/rethinkdb,catroot/rethinkdb,AtnNn/rethinkdb,AntouanK/rethinkdb,victorbriz/rethinkdb,sebadiaz/rethinkdb,JackieXie168/rethinkdb,jesseditson/rethinkdb,elkingtonmcb/rethinkdb,sebadiaz/rethinkdb,sbusso/rethinkdb,captainpete/rethinkdb,Wilbeibi/rethinkdb,marshall007/rethinkdb,mbroadst/rethinkdb,wojons/rethinkdb,mquandalle/rethinkdb,jesseditson/rethinkdb,catroot/rethinkdb,lenstr/rethinkdb,losywee/rethinkdb,alash3al/rethinkdb,sebadiaz/rethinkdb,yaolinz/rethinkdb,pap/rethinkdb,mquandalle/rethinkdb,marshall007/rethinkdb,sebadiaz/rethinkdb,pap/rethinkdb,gdi2290/rethinkdb,jesseditson/rethinkdb,ajose01/rethinkdb,mbroadst/rethinkdb,scripni/rethinkdb,elkingtonmcb/rethinkdb,grandquista/rethinkdb,mcanthony/rethinkdb,niieani/rethinkdb,Qinusty/rethinkdb,sontek/rethinkdb,victorbriz/rethinkdb,marshall007/rethinkdb,catroot/rethinkdb,gdi2290/rethinkdb,urandu/rethinkdb,elkingtonmcb/rethinkdb,mquandalle/rethinkdb,spblightadv/rethinkdb,captainpete/rethinkdb,Wilbeibi/rethinkdb,yaolinz/rethinkdb,tempbottle/rethinkdb,jmptrader/rethinkdb,AtnNn/rethinkdb,KSanthanam/rethinkdb,KSanthanam/rethinkdb,ajose01/rethinkdb,wkennington/rethinkdb
|
11713b8c37b9a6eeb087161f2e8d04ba52bf40c0
|
src/unix/fcitx5/mozc_engine.cc
|
src/unix/fcitx5/mozc_engine.cc
|
/*
* Copyright (C) 2017~2017 by CSSlayer
* [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 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 COPYING. If not,
* see <http://www.gnu.org/licenses/>.
*/
#include "unix/fcitx5/mozc_engine.h"
#include <fcitx-config/iniparser.h>
#include <fcitx-utils/i18n.h>
#include <fcitx-utils/log.h>
#include <fcitx-utils/standardpath.h>
#include <fcitx/inputcontext.h>
#include <fcitx/inputcontextmanager.h>
#include <fcitx/inputmethodmanager.h>
#include <fcitx/userinterfacemanager.h>
#include <vector>
#include "base/init_mozc.h"
#include "base/process.h"
#include "unix/fcitx5/mozc_connection.h"
#include "unix/fcitx5/mozc_response_parser.h"
namespace fcitx {
const struct CompositionMode {
const char *name;
const char *icon;
const char *label;
const char *description;
mozc::commands::CompositionMode mode;
} kPropCompositionModes[] = {
{
"mozc-mode-direct",
"fcitx-mozc-direct",
"A",
N_("Direct"),
mozc::commands::DIRECT,
},
{
"mozc-mode-hiragana",
"fcitx-mozc-hiragana",
"\xe3\x81\x82", // Hiragana letter A in UTF-8.
N_("Hiragana"),
mozc::commands::HIRAGANA,
},
{
"mozc-mode-katakana_full",
"fcitx-mozc-katakana-full",
"\xe3\x82\xa2", // Katakana letter A.
N_("Full Katakana"),
mozc::commands::FULL_KATAKANA,
},
{
"mozc-mode-alpha_half",
"fcitx-mozc-alpha-half",
"A",
N_("Half ASCII"),
mozc::commands::HALF_ASCII,
},
{
"mozc-mode-alpha_full",
"fcitx-mozc-alpha-full",
"\xef\xbc\xa1", // Full width ASCII letter A.
N_("Full ASCII"),
mozc::commands::FULL_ASCII,
},
{
"mozc-mode-katakana_full",
"fcitx-mozc-katakana-full",
"\xef\xbd\xb1", // Half width Katakana letter A.
N_("Half Katakana"),
mozc::commands::HALF_KATAKANA,
},
};
const size_t kNumCompositionModes = arraysize(kPropCompositionModes);
std::string MozcModeAction::shortText(InputContext *) const {
return _("Composition Mode");
}
std::string MozcModeAction::longText(InputContext *ic) const {
auto mozc_state = engine_->mozcState(ic);
return _(kPropCompositionModes[mozc_state->GetCompositionMode()].description);
}
std::string MozcModeAction::icon(InputContext *ic) const {
auto mozc_state = engine_->mozcState(ic);
return kPropCompositionModes[mozc_state->GetCompositionMode()].icon;
}
MozcModeSubAction::MozcModeSubAction(MozcEngine *engine,
mozc::commands::CompositionMode mode)
: engine_(engine), mode_(mode) {
setShortText(kPropCompositionModes[mode].label);
setLongText(_(kPropCompositionModes[mode].description));
setIcon(kPropCompositionModes[mode].icon);
setCheckable(true);
}
bool MozcModeSubAction::isChecked(InputContext *ic) const {
auto mozc_state = engine_->mozcState(ic);
return mozc_state->GetCompositionMode() == mode_;
}
void MozcModeSubAction::activate(InputContext *ic) {
auto mozc_state = engine_->mozcState(ic);
mozc_state->SendCompositionMode(mode_);
}
// This array must correspond with the CompositionMode enum in the
// mozc/session/command.proto file.
static_assert(mozc::commands::NUM_OF_COMPOSITIONS == kNumCompositionModes,
"number of modes must match");
Instance *Init(Instance *instance) {
int argc = 1;
char argv0[] = "fcitx_mozc";
char *_argv[] = {argv0};
char **argv = _argv;
mozc::InitMozc(argv[0], &argc, &argv);
return instance;
}
MozcEngine::MozcEngine(Instance *instance)
: instance_(Init(instance)),
connection_(std::make_unique<MozcConnection>()),
factory_([this](InputContext &ic) {
return new MozcState(&ic, connection_->CreateClient(), this);
}),
modeAction_(this) {
for (auto command :
{mozc::commands::DIRECT, mozc::commands::HIRAGANA,
mozc::commands::FULL_KATAKANA, mozc::commands::FULL_ASCII,
mozc::commands::HALF_ASCII, mozc::commands::HALF_KATAKANA}) {
modeActions_.push_back(std::make_unique<MozcModeSubAction>(this, command));
}
instance_->inputContextManager().registerProperty("mozcState", &factory_);
instance_->userInterfaceManager().registerAction("mozc-mode", &modeAction_);
instance_->userInterfaceManager().registerAction("mozc-tool", &toolAction_);
toolAction_.setShortText(_("Tool"));
toolAction_.setLongText(_("Tool"));
toolAction_.setIcon("fcitx-mozc-tool");
int i = 0;
for (auto &modeAction : modeActions_) {
instance_->userInterfaceManager().registerAction(
kPropCompositionModes[i].name, modeAction.get());
modeMenu_.addAction(modeAction.get());
i++;
}
instance_->userInterfaceManager().registerAction("mozc-tool-config",
&configToolAction_);
configToolAction_.setShortText(_("Configuration Tool"));
configToolAction_.setIcon("fcitx-mozc-tool");
configToolAction_.connect<SimpleAction::Activated>([](InputContext *) {
mozc::Process::SpawnMozcProcess("mozc_tool", "--mode=config_dialog");
});
instance_->userInterfaceManager().registerAction("mozc-tool-dict",
&dictionaryToolAction_);
dictionaryToolAction_.setShortText(_("Dictionary Tool"));
dictionaryToolAction_.setIcon("fcitx-mozc-dictionary");
dictionaryToolAction_.connect<SimpleAction::Activated>([](InputContext *) {
mozc::Process::SpawnMozcProcess("mozc_tool", "--mode=dictionary_tool");
});
instance_->userInterfaceManager().registerAction("mozc-tool-add",
&addWordAction_);
addWordAction_.setShortText(_("Add Word"));
addWordAction_.connect<SimpleAction::Activated>([](InputContext *) {
mozc::Process::SpawnMozcProcess("mozc_tool", "--mode=word_register_dialog");
});
instance_->userInterfaceManager().registerAction("mozc-tool-about",
&aboutAction_);
aboutAction_.setShortText(_("About Mozc"));
aboutAction_.connect<SimpleAction::Activated>([](InputContext *) {
mozc::Process::SpawnMozcProcess("mozc_tool", "--mode=about_dialog");
});
toolMenu_.addAction(&configToolAction_);
toolMenu_.addAction(&dictionaryToolAction_);
toolMenu_.addAction(&addWordAction_);
toolMenu_.addAction(&aboutAction_);
modeAction_.setMenu(&modeMenu_);
toolAction_.setMenu(&toolMenu_);
reloadConfig();
}
MozcEngine::~MozcEngine() {}
void MozcEngine::setConfig(const RawConfig &config) {
config_.load(config, true);
safeSaveAsIni(config_, "conf/mozc.conf");
}
void MozcEngine::reloadConfig() { readAsIni(config_, "conf/mozc.conf"); }
void MozcEngine::activate(const fcitx::InputMethodEntry &,
fcitx::InputContextEvent &event) {
auto ic = event.inputContext();
auto mozc_state = mozcState(ic);
mozc_state->FocusIn();
ic->statusArea().addAction(StatusGroup::InputMethod, &modeAction_);
ic->statusArea().addAction(StatusGroup::InputMethod, &toolAction_);
}
void MozcEngine::deactivate(const fcitx::InputMethodEntry &,
fcitx::InputContextEvent &event) {
auto ic = event.inputContext();
auto mozc_state = mozcState(ic);
mozc_state->FocusOut();
}
void MozcEngine::keyEvent(const InputMethodEntry &entry, KeyEvent &event) {
auto mozc_state = mozcState(event.inputContext());
auto &group = instance_->inputMethodManager().currentGroup();
std::string layout = group.layoutFor(entry.uniqueName());
if (layout.empty()) {
layout = group.defaultLayout();
}
const bool isJP = (layout == "jp" || stringutils::startsWith(layout, "jp-"));
if (mozc_state->ProcessKeyEvent(event.rawKey().sym(), event.rawKey().code(),
event.rawKey().states(), isJP,
event.isRelease())) {
event.filterAndAccept();
}
}
void MozcEngine::reset(const InputMethodEntry &, InputContextEvent &event) {
auto mozc_state = mozcState(event.inputContext());
mozc_state->Reset();
}
void MozcEngine::save() {}
std::string MozcEngine::subMode(const fcitx::InputMethodEntry &,
fcitx::InputContext &ic) {
return modeAction_.longText(&ic);
}
MozcState *MozcEngine::mozcState(InputContext *ic) {
return ic->propertyFor(&factory_);
}
void MozcEngine::compositionModeUpdated(InputContext *ic) {
modeAction_.update(ic);
for (const auto &modeAction : modeActions_) {
modeAction->update(ic);
}
}
AddonInstance *MozcEngine::clipboardAddon() { return clipboard(); }
} // namespace fcitx
|
/*
* Copyright (C) 2017~2017 by CSSlayer
* [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 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 COPYING. If not,
* see <http://www.gnu.org/licenses/>.
*/
#include "unix/fcitx5/mozc_engine.h"
#include <fcitx-config/iniparser.h>
#include <fcitx-utils/i18n.h>
#include <fcitx-utils/log.h>
#include <fcitx-utils/standardpath.h>
#include <fcitx/inputcontext.h>
#include <fcitx/inputcontextmanager.h>
#include <fcitx/inputmethodmanager.h>
#include <fcitx/userinterfacemanager.h>
#include <vector>
#include "base/init_mozc.h"
#include "base/process.h"
#include "unix/fcitx5/mozc_connection.h"
#include "unix/fcitx5/mozc_response_parser.h"
namespace fcitx {
const struct CompositionMode {
const char *name;
const char *icon;
const char *label;
const char *description;
mozc::commands::CompositionMode mode;
} kPropCompositionModes[] = {
{
"mozc-mode-direct",
"fcitx-mozc-direct",
"A",
N_("Direct"),
mozc::commands::DIRECT,
},
{
"mozc-mode-hiragana",
"fcitx-mozc-hiragana",
"\xe3\x81\x82", // Hiragana letter A in UTF-8.
N_("Hiragana"),
mozc::commands::HIRAGANA,
},
{
"mozc-mode-katakana_full",
"fcitx-mozc-katakana-full",
"\xe3\x82\xa2", // Katakana letter A.
N_("Full Katakana"),
mozc::commands::FULL_KATAKANA,
},
{
"mozc-mode-alpha_half",
"fcitx-mozc-alpha-half",
"A",
N_("Half ASCII"),
mozc::commands::HALF_ASCII,
},
{
"mozc-mode-alpha_full",
"fcitx-mozc-alpha-full",
"\xef\xbc\xa1", // Full width ASCII letter A.
N_("Full ASCII"),
mozc::commands::FULL_ASCII,
},
{
"mozc-mode-katakana_half",
"fcitx-mozc-katakana-half",
"\xef\xbd\xb1", // Half width Katakana letter A.
N_("Half Katakana"),
mozc::commands::HALF_KATAKANA,
},
};
const size_t kNumCompositionModes = arraysize(kPropCompositionModes);
std::string MozcModeAction::shortText(InputContext *) const {
return _("Composition Mode");
}
std::string MozcModeAction::longText(InputContext *ic) const {
auto mozc_state = engine_->mozcState(ic);
return _(kPropCompositionModes[mozc_state->GetCompositionMode()].description);
}
std::string MozcModeAction::icon(InputContext *ic) const {
auto mozc_state = engine_->mozcState(ic);
return kPropCompositionModes[mozc_state->GetCompositionMode()].icon;
}
MozcModeSubAction::MozcModeSubAction(MozcEngine *engine,
mozc::commands::CompositionMode mode)
: engine_(engine), mode_(mode) {
setShortText(kPropCompositionModes[mode].label);
setLongText(_(kPropCompositionModes[mode].description));
setIcon(kPropCompositionModes[mode].icon);
setCheckable(true);
}
bool MozcModeSubAction::isChecked(InputContext *ic) const {
auto mozc_state = engine_->mozcState(ic);
return mozc_state->GetCompositionMode() == mode_;
}
void MozcModeSubAction::activate(InputContext *ic) {
auto mozc_state = engine_->mozcState(ic);
mozc_state->SendCompositionMode(mode_);
}
// This array must correspond with the CompositionMode enum in the
// mozc/session/command.proto file.
static_assert(mozc::commands::NUM_OF_COMPOSITIONS == kNumCompositionModes,
"number of modes must match");
Instance *Init(Instance *instance) {
int argc = 1;
char argv0[] = "fcitx_mozc";
char *_argv[] = {argv0};
char **argv = _argv;
mozc::InitMozc(argv[0], &argc, &argv);
return instance;
}
MozcEngine::MozcEngine(Instance *instance)
: instance_(Init(instance)),
connection_(std::make_unique<MozcConnection>()),
factory_([this](InputContext &ic) {
return new MozcState(&ic, connection_->CreateClient(), this);
}),
modeAction_(this) {
for (auto command :
{mozc::commands::DIRECT, mozc::commands::HIRAGANA,
mozc::commands::FULL_KATAKANA, mozc::commands::FULL_ASCII,
mozc::commands::HALF_ASCII, mozc::commands::HALF_KATAKANA}) {
modeActions_.push_back(std::make_unique<MozcModeSubAction>(this, command));
}
instance_->inputContextManager().registerProperty("mozcState", &factory_);
instance_->userInterfaceManager().registerAction("mozc-mode", &modeAction_);
instance_->userInterfaceManager().registerAction("mozc-tool", &toolAction_);
toolAction_.setShortText(_("Tool"));
toolAction_.setLongText(_("Tool"));
toolAction_.setIcon("fcitx-mozc-tool");
int i = 0;
for (auto &modeAction : modeActions_) {
instance_->userInterfaceManager().registerAction(
kPropCompositionModes[i].name, modeAction.get());
modeMenu_.addAction(modeAction.get());
i++;
}
instance_->userInterfaceManager().registerAction("mozc-tool-config",
&configToolAction_);
configToolAction_.setShortText(_("Configuration Tool"));
configToolAction_.setIcon("fcitx-mozc-tool");
configToolAction_.connect<SimpleAction::Activated>([](InputContext *) {
mozc::Process::SpawnMozcProcess("mozc_tool", "--mode=config_dialog");
});
instance_->userInterfaceManager().registerAction("mozc-tool-dict",
&dictionaryToolAction_);
dictionaryToolAction_.setShortText(_("Dictionary Tool"));
dictionaryToolAction_.setIcon("fcitx-mozc-dictionary");
dictionaryToolAction_.connect<SimpleAction::Activated>([](InputContext *) {
mozc::Process::SpawnMozcProcess("mozc_tool", "--mode=dictionary_tool");
});
instance_->userInterfaceManager().registerAction("mozc-tool-add",
&addWordAction_);
addWordAction_.setShortText(_("Add Word"));
addWordAction_.connect<SimpleAction::Activated>([](InputContext *) {
mozc::Process::SpawnMozcProcess("mozc_tool", "--mode=word_register_dialog");
});
instance_->userInterfaceManager().registerAction("mozc-tool-about",
&aboutAction_);
aboutAction_.setShortText(_("About Mozc"));
aboutAction_.connect<SimpleAction::Activated>([](InputContext *) {
mozc::Process::SpawnMozcProcess("mozc_tool", "--mode=about_dialog");
});
toolMenu_.addAction(&configToolAction_);
toolMenu_.addAction(&dictionaryToolAction_);
toolMenu_.addAction(&addWordAction_);
toolMenu_.addAction(&aboutAction_);
modeAction_.setMenu(&modeMenu_);
toolAction_.setMenu(&toolMenu_);
reloadConfig();
}
MozcEngine::~MozcEngine() {}
void MozcEngine::setConfig(const RawConfig &config) {
config_.load(config, true);
safeSaveAsIni(config_, "conf/mozc.conf");
}
void MozcEngine::reloadConfig() { readAsIni(config_, "conf/mozc.conf"); }
void MozcEngine::activate(const fcitx::InputMethodEntry &,
fcitx::InputContextEvent &event) {
auto ic = event.inputContext();
auto mozc_state = mozcState(ic);
mozc_state->FocusIn();
ic->statusArea().addAction(StatusGroup::InputMethod, &modeAction_);
ic->statusArea().addAction(StatusGroup::InputMethod, &toolAction_);
}
void MozcEngine::deactivate(const fcitx::InputMethodEntry &,
fcitx::InputContextEvent &event) {
auto ic = event.inputContext();
auto mozc_state = mozcState(ic);
mozc_state->FocusOut();
}
void MozcEngine::keyEvent(const InputMethodEntry &entry, KeyEvent &event) {
auto mozc_state = mozcState(event.inputContext());
auto &group = instance_->inputMethodManager().currentGroup();
std::string layout = group.layoutFor(entry.uniqueName());
if (layout.empty()) {
layout = group.defaultLayout();
}
const bool isJP = (layout == "jp" || stringutils::startsWith(layout, "jp-"));
if (mozc_state->ProcessKeyEvent(event.rawKey().sym(), event.rawKey().code(),
event.rawKey().states(), isJP,
event.isRelease())) {
event.filterAndAccept();
}
}
void MozcEngine::reset(const InputMethodEntry &, InputContextEvent &event) {
auto mozc_state = mozcState(event.inputContext());
mozc_state->Reset();
}
void MozcEngine::save() {}
std::string MozcEngine::subMode(const fcitx::InputMethodEntry &,
fcitx::InputContext &ic) {
return modeAction_.longText(&ic);
}
MozcState *MozcEngine::mozcState(InputContext *ic) {
return ic->propertyFor(&factory_);
}
void MozcEngine::compositionModeUpdated(InputContext *ic) {
modeAction_.update(ic);
for (const auto &modeAction : modeActions_) {
modeAction->update(ic);
}
}
AddonInstance *MozcEngine::clipboardAddon() { return clipboard(); }
} // namespace fcitx
|
Fix typo in katakana half action. #12
|
Fix typo in katakana half action. #12
|
C++
|
bsd-3-clause
|
fcitx/mozc,fcitx/mozc,fcitx/mozc,fcitx/mozc,fcitx/mozc
|
9cbff3779ff159ed24b6f044d67e5b6270736626
|
tools/data-collect/rs-data-collect.cpp
|
tools/data-collect/rs-data-collect.cpp
|
// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2015 Intel Corporation. All Rights Reserved.
#include <librealsense2/rs.hpp>
#include <chrono>
#include <thread>
#include <iostream>
#include <fstream>
#include <sstream>
#include "tclap/CmdLine.h"
#include <condition_variable>
#include <set>
#include <cctype>
#include <thread>
#include <array>
using namespace std;
using namespace TCLAP;
using namespace rs2;
int MAX_FRAMES_NUMBER = 10; //number of frames to capture from each stream
const unsigned int NUM_OF_STREAMS = static_cast<int>(RS2_STREAM_COUNT);
struct frame_data
{
unsigned long long frame_number;
double ts;
long long arrival_time;
rs2_timestamp_domain domain;
rs2_stream stream_type;
};
enum Config_Params { STREAM_TYPE = 0, RES_WIDTH, RES_HEIGHT, FPS, FORMAT };
int parse_number(char const *s, int base = 0)
{
char c;
stringstream ss(s);
int i;
ss >> i;
if (ss.fail() || ss.get(c))
{
throw runtime_error(string(string("Invalid numeric input - ") + s + string("\n")));
}
return i;
}
std::string to_lower(const std::string& s)
{
auto copy = s;
std::transform(copy.begin(), copy.end(), copy.begin(), ::tolower);
return copy;
}
rs2_format parse_format(const string str)
{
for (int i = RS2_FORMAT_ANY; i < RS2_FORMAT_COUNT; i++)
{
if (to_lower(rs2_format_to_string((rs2_format)i)) == str)
{
return (rs2_format)i;
}
}
throw runtime_error((string("Invalid format - ") + str + string("\n")).c_str());
}
rs2_stream parse_stream_type(const string str)
{
for (int i = RS2_STREAM_ANY; i < RS2_STREAM_COUNT; i++)
{
if (to_lower(rs2_stream_to_string((rs2_stream)i)) == str)
{
return static_cast<rs2_stream>(i);
}
}
throw runtime_error((string("Invalid stream type - ") + str + string("\n")).c_str());
}
int parse_fps(const string str)
{
return parse_number(str.c_str());
}
void parse_configuration(const vector<string> row, rs2_stream& type, int& width, int& height, rs2_format& format, int& fps)
{
// Convert string to uppercase
auto stream_type_str = row[STREAM_TYPE];
type = parse_stream_type(to_lower(stream_type_str));
width = parse_number(row[RES_WIDTH].c_str());
height = parse_number(row[RES_HEIGHT].c_str());
fps = parse_fps(row[FPS]);
format = parse_format(to_lower(row[FORMAT]));
}
void configure_stream(pipeline& pipe, std::string filename)
{
ifstream file(filename);
if (!file.is_open())
throw runtime_error("Given .csv configure file Not Found!");
string line;
while (getline(file, line))
{
// Parsing configuration requests
stringstream ss(line);
vector<string> row;
while (ss.good())
{
string substr;
getline(ss, substr, ',');
row.push_back(substr);
}
rs2_stream stream_type;
rs2_format format;
int width, height, fps;
// correctness check
parse_configuration(row, stream_type, width, height, format, fps);
pipe.enable_stream(stream_type, 0, width, height, format, fps);
}
}
void save_data_to_file(std::array<list<frame_data>, NUM_OF_STREAMS> buffer, const string& filename)
{
// Save to file
ofstream csv;
csv.open(filename);
csv << "Stream Type,F#,Timestamp,Arrival Time\n";
for (int stream_index = 0; stream_index < NUM_OF_STREAMS; stream_index++)
{
unsigned int buffer_size = buffer[stream_index].size();
for (unsigned int i = 0; i < buffer_size; i++)
{
ostringstream line;
auto data = buffer[stream_index].front();
line << rs2_stream_to_string(data.stream_type) << "," << data.frame_number << "," << data.ts << "," << data.arrival_time << "\n";
buffer[stream_index].pop_front();
csv << line.str();
}
}
csv.close();
}
int main(int argc, char** argv) try
{
log_to_file(RS2_LOG_SEVERITY_WARN);
// Parse command line arguments
CmdLine cmd("librealsense cpp-data-collect example tool", ' ');
ValueArg<int> timeout("t", "Timeout", "Max amount of time to receive frames (in seconds)", false, 10, "");
ValueArg<int> max_frames("m", "MaxFrames_Number", "Maximun number of frames data to receive", false, 100, "");
ValueArg<string> filename("f", "FullFilePath", "the file which the data will be saved to", false, "", "");
ValueArg<string> config_file("c", "ConfigurationFile", "Specify file path with the requested configuration", false, "", "");
cmd.add(timeout);
cmd.add(max_frames);
cmd.add(filename);
cmd.add(config_file);
cmd.parse(argc, argv);
std::string output_file = filename.isSet() ? filename.getValue() : "frames_data.csv";
auto max_frames_number = MAX_FRAMES_NUMBER;
if (max_frames.isSet())
max_frames_number = max_frames.getValue();
while (true)
{
pipeline pipe;
if (config_file.isSet())
{
configure_stream(pipe, config_file.getValue());
}
pipe.open();
auto dev = pipe.get_device();
std::atomic_bool need_to_reset(false);
for (auto sub : dev.query_sensors())
{
sub.set_notifications_callback([&](const notification& n)
{
if (n.get_category() == RS2_NOTIFICATION_CATEGORY_FRAMES_TIMEOUT)
{
need_to_reset = true;
}
});
}
pipe.start();
std::array<std::list<frame_data>, NUM_OF_STREAMS> buffer;
auto start_time = chrono::high_resolution_clock::now();
const auto ready = [&]()
{
if (timeout.isSet())
{
auto timeout_sec = std::chrono::seconds(timeout.getValue());
if (chrono::high_resolution_clock::now() - start_time < timeout_sec)
{
return false;
}
}
else
{
for (auto&& profile : pipe.get_active_streams())
{
if (buffer[(int)profile.stream_type()].size() < max_frames_number)
return false;
}
}
return true;
};
while (!ready())
{
auto f = pipe.wait_for_frames();
auto arrival_time = chrono::duration_cast<chrono::milliseconds>(chrono::high_resolution_clock::now() - start_time);
frame_data data;
data.frame_number = f.get_frame_number();
data.stream_type = f.get_profile().stream_type();
data.ts = f.get_timestamp();
data.domain = f.get_frame_timestamp_domain();
data.arrival_time = arrival_time.count();
buffer[(int)data.stream_type].push_back(data);
if (need_to_reset)
{
dev.hardware_reset();
need_to_reset = false;
break;
}
}
if(ready())
{
save_data_to_file(buffer, output_file);
pipe.stop();
break;
}
}
return EXIT_SUCCESS;
}
catch (const error & e)
{
cerr << "RealSense error calling " << e.get_failed_function() << "(" << e.get_failed_args() << "):\n " << e.what() << endl;
return EXIT_FAILURE;
}
catch (const exception & e)
{
cerr << e.what() << endl;
return EXIT_FAILURE;
}
|
// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2015 Intel Corporation. All Rights Reserved.
#include <librealsense2/rs.hpp>
#include <chrono>
#include <thread>
#include <iostream>
#include <fstream>
#include <sstream>
#include "tclap/CmdLine.h"
#include <condition_variable>
#include <set>
#include <cctype>
#include <thread>
#include <array>
using namespace std;
using namespace TCLAP;
using namespace rs2;
int MAX_FRAMES_NUMBER = 10; //number of frames to capture from each stream
const unsigned int NUM_OF_STREAMS = static_cast<int>(RS2_STREAM_COUNT);
struct frame_data
{
unsigned long long frame_number;
double ts;
long long arrival_time;
rs2_timestamp_domain domain;
rs2_stream stream_type;
};
enum Config_Params { STREAM_TYPE = 0, RES_WIDTH, RES_HEIGHT, FPS, FORMAT };
int parse_number(char const *s, int base = 0)
{
char c;
stringstream ss(s);
int i;
ss >> i;
if (ss.fail() || ss.get(c))
{
throw runtime_error(string(string("Invalid numeric input - ") + s + string("\n")));
}
return i;
}
std::string to_lower(const std::string& s)
{
auto copy = s;
std::transform(copy.begin(), copy.end(), copy.begin(), ::tolower);
return copy;
}
rs2_format parse_format(const string str)
{
for (int i = RS2_FORMAT_ANY; i < RS2_FORMAT_COUNT; i++)
{
if (to_lower(rs2_format_to_string((rs2_format)i)) == str)
{
return (rs2_format)i;
}
}
throw runtime_error((string("Invalid format - ") + str + string("\n")).c_str());
}
rs2_stream parse_stream_type(const string str)
{
for (int i = RS2_STREAM_ANY; i < RS2_STREAM_COUNT; i++)
{
if (to_lower(rs2_stream_to_string((rs2_stream)i)) == str)
{
return static_cast<rs2_stream>(i);
}
}
throw runtime_error((string("Invalid stream type - ") + str + string("\n")).c_str());
}
int parse_fps(const string str)
{
return parse_number(str.c_str());
}
void parse_configuration(const vector<string> row, rs2_stream& type, int& width, int& height, rs2_format& format, int& fps)
{
// Convert string to uppercase
auto stream_type_str = row[STREAM_TYPE];
type = parse_stream_type(to_lower(stream_type_str));
width = parse_number(row[RES_WIDTH].c_str());
height = parse_number(row[RES_HEIGHT].c_str());
fps = parse_fps(row[FPS]);
format = parse_format(to_lower(row[FORMAT]));
}
void configure_stream(pipeline& pipe, std::string filename)
{
ifstream file(filename);
if (!file.is_open())
throw runtime_error("Given .csv configure file Not Found!");
string line;
while (getline(file, line))
{
// Parsing configuration requests
stringstream ss(line);
vector<string> row;
while (ss.good())
{
string substr;
getline(ss, substr, ',');
row.push_back(substr);
}
rs2_stream stream_type;
rs2_format format;
int width, height, fps;
// correctness check
parse_configuration(row, stream_type, width, height, format, fps);
pipe.enable_stream(stream_type, 0, width, height, format, fps);
}
}
void save_data_to_file(std::array<list<frame_data>, NUM_OF_STREAMS> buffer, const string& filename)
{
// Save to file
ofstream csv;
csv.open(filename);
csv << "Stream Type,F#,Timestamp,Arrival Time\n";
for (int stream_index = 0; stream_index < NUM_OF_STREAMS; stream_index++)
{
unsigned int buffer_size = buffer[stream_index].size();
for (unsigned int i = 0; i < buffer_size; i++)
{
ostringstream line;
auto data = buffer[stream_index].front();
line << rs2_stream_to_string(data.stream_type) << "," << data.frame_number << "," << data.ts << "," << data.arrival_time << "\n";
buffer[stream_index].pop_front();
csv << line.str();
}
}
csv.close();
}
int main(int argc, char** argv) try
{
log_to_file(RS2_LOG_SEVERITY_WARN);
// Parse command line arguments
CmdLine cmd("librealsense cpp-data-collect example tool", ' ');
ValueArg<int> timeout("t", "Timeout", "Max amount of time to receive frames (in seconds)", false, 10, "");
ValueArg<int> max_frames("m", "MaxFrames_Number", "Maximun number of frames data to receive", false, 100, "");
ValueArg<string> filename("f", "FullFilePath", "the file which the data will be saved to", false, "", "");
ValueArg<string> config_file("c", "ConfigurationFile", "Specify file path with the requested configuration", false, "", "");
cmd.add(timeout);
cmd.add(max_frames);
cmd.add(filename);
cmd.add(config_file);
cmd.parse(argc, argv);
std::string output_file = filename.isSet() ? filename.getValue() : "frames_data.csv";
auto max_frames_number = MAX_FRAMES_NUMBER;
if (max_frames.isSet())
max_frames_number = max_frames.getValue();
bool succeed = false;
while (!succeed)
{
pipeline pipe;
if (config_file.isSet())
{
configure_stream(pipe, config_file.getValue());
}
pipe.open();
auto dev = pipe.get_device();
std::atomic_bool need_to_reset(false);
for (auto sub : dev.query_sensors())
{
sub.set_notifications_callback([&](const notification& n)
{
if (n.get_category() == RS2_NOTIFICATION_CATEGORY_FRAMES_TIMEOUT)
{
need_to_reset = true;
}
});
}
pipe.start();
std::array<std::list<frame_data>, NUM_OF_STREAMS> buffer;
auto start_time = chrono::high_resolution_clock::now();
const auto ready = [&]()
{
if (timeout.isSet())
{
auto timeout_sec = std::chrono::seconds(timeout.getValue());
if (chrono::high_resolution_clock::now() - start_time < timeout_sec)
{
return false;
}
}
else
{
for (auto&& profile : pipe.get_active_streams())
{
if (buffer[(int)profile.stream_type()].size() < max_frames_number)
return false;
}
}
return true;
};
while (!ready())
{
auto f = pipe.wait_for_frames();
auto arrival_time = chrono::duration_cast<chrono::milliseconds>(chrono::high_resolution_clock::now() - start_time);
frame_data data;
data.frame_number = f.get_frame_number();
data.stream_type = f.get_profile().stream_type();
data.ts = f.get_timestamp();
data.domain = f.get_frame_timestamp_domain();
data.arrival_time = arrival_time.count();
buffer[(int)data.stream_type].push_back(data);
if (need_to_reset)
{
dev.hardware_reset();
need_to_reset = false;
break;
}
}
if(ready())
{
save_data_to_file(buffer, output_file);
pipe.stop();
succeed = true;
}
}
return EXIT_SUCCESS;
}
catch (const error & e)
{
cerr << "RealSense error calling " << e.get_failed_function() << "(" << e.get_failed_args() << "):\n " << e.what() << endl;
return EXIT_FAILURE;
}
catch (const exception & e)
{
cerr << e.what() << endl;
return EXIT_FAILURE;
}
|
Change per CR
|
Change per CR
|
C++
|
apache-2.0
|
IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense
|
cf35ffb126c1e4f3902ec2d8a64ec1a0cde53ec3
|
vm/data_heap.cpp
|
vm/data_heap.cpp
|
#include "master.hpp"
namespace factor
{
void factor_vm::init_card_decks()
{
cards_offset = (cell)data->cards - addr_to_card(data->start);
decks_offset = (cell)data->decks - addr_to_deck(data->start);
}
data_heap::data_heap(cell young_size_,
cell aging_size_,
cell tenured_size_)
{
young_size_ = align(young_size_,deck_size);
aging_size_ = align(aging_size_,deck_size);
tenured_size_ = align(tenured_size_,deck_size);
young_size = young_size_;
aging_size = aging_size_;
tenured_size = tenured_size_;
cell total_size = young_size + 2 * aging_size + tenured_size + deck_size;
seg = new segment(total_size,false);
cell cards_size = addr_to_card(total_size);
cards = new card[cards_size];
cards_end = cards + cards_size;
memset(cards,0,cards_size);
cell decks_size = addr_to_deck(total_size);
decks = new card_deck[decks_size];
decks_end = decks + decks_size;
memset(decks,0,decks_size);
start = align(seg->start,deck_size);
tenured = new tenured_space(tenured_size,start);
aging = new aging_space(aging_size,tenured->end);
aging_semispace = new aging_space(aging_size,aging->end);
nursery = new nursery_space(young_size,aging_semispace->end);
assert(seg->end - nursery->end <= deck_size);
}
data_heap::~data_heap()
{
delete seg;
delete nursery;
delete aging;
delete aging_semispace;
delete tenured;
delete[] cards;
delete[] decks;
}
data_heap *data_heap::grow(cell requested_bytes)
{
cell new_tenured_size = (tenured_size * 2) + requested_bytes;
return new data_heap(young_size,
aging_size,
new_tenured_size);
}
template<typename Generation> void data_heap::clear_cards(Generation *gen)
{
cell first_card = addr_to_card(gen->start - start);
cell last_card = addr_to_card(gen->end - start);
memset(&cards[first_card],0,last_card - first_card);
}
template<typename Generation> void data_heap::clear_decks(Generation *gen)
{
cell first_deck = addr_to_deck(gen->start - start);
cell last_deck = addr_to_deck(gen->end - start);
memset(&decks[first_deck],0,last_deck - first_deck);
}
void data_heap::reset_generation(nursery_space *gen)
{
gen->here = gen->start;
}
void data_heap::reset_generation(aging_space *gen)
{
gen->here = gen->start;
clear_cards(gen);
clear_decks(gen);
gen->starts.clear_object_start_offsets();
}
void data_heap::reset_generation(tenured_space *gen)
{
clear_cards(gen);
clear_decks(gen);
}
bool data_heap::low_memory_p()
{
return (tenured->free_space() <= nursery->size + aging->size);
}
void data_heap::mark_all_cards()
{
memset(cards,-1,cards_end - cards);
memset(decks,-1,decks_end - decks);
}
void factor_vm::set_data_heap(data_heap *data_)
{
data = data_;
nursery = *data->nursery;
init_card_decks();
}
void factor_vm::init_data_heap(cell young_size, cell aging_size, cell tenured_size)
{
set_data_heap(new data_heap(young_size,aging_size,tenured_size));
}
/* Size of the object pointed to by an untagged pointer */
cell object::size() const
{
if(free_p()) return ((free_heap_block *)this)->size();
switch(type())
{
case ARRAY_TYPE:
return align(array_size((array*)this),data_alignment);
case BIGNUM_TYPE:
return align(array_size((bignum*)this),data_alignment);
case BYTE_ARRAY_TYPE:
return align(array_size((byte_array*)this),data_alignment);
case STRING_TYPE:
return align(string_size(string_capacity((string*)this)),data_alignment);
case TUPLE_TYPE:
{
tuple_layout *layout = (tuple_layout *)UNTAG(((tuple *)this)->layout);
return align(tuple_size(layout),data_alignment);
}
case QUOTATION_TYPE:
return align(sizeof(quotation),data_alignment);
case WORD_TYPE:
return align(sizeof(word),data_alignment);
case FLOAT_TYPE:
return align(sizeof(boxed_float),data_alignment);
case DLL_TYPE:
return align(sizeof(dll),data_alignment);
case ALIEN_TYPE:
return align(sizeof(alien),data_alignment);
case WRAPPER_TYPE:
return align(sizeof(wrapper),data_alignment);
case CALLSTACK_TYPE:
return align(callstack_size(untag_fixnum(((callstack *)this)->length)),data_alignment);
default:
critical_error("Invalid header",(cell)this);
return 0; /* can't happen */
}
}
/* The number of cells from the start of the object which should be scanned by
the GC. Some types have a binary payload at the end (string, word, DLL) which
we ignore. */
cell object::binary_payload_start() const
{
switch(type())
{
/* these objects do not refer to other objects at all */
case FLOAT_TYPE:
case BYTE_ARRAY_TYPE:
case BIGNUM_TYPE:
case CALLSTACK_TYPE:
return 0;
/* these objects have some binary data at the end */
case WORD_TYPE:
return sizeof(word) - sizeof(cell) * 3;
case ALIEN_TYPE:
return sizeof(cell) * 3;
case DLL_TYPE:
return sizeof(cell) * 2;
case QUOTATION_TYPE:
return sizeof(quotation) - sizeof(cell) * 2;
case STRING_TYPE:
return sizeof(string);
/* everything else consists entirely of pointers */
case ARRAY_TYPE:
return array_size<array>(array_capacity((array*)this));
case TUPLE_TYPE:
return tuple_size(untag<tuple_layout>(((tuple *)this)->layout));
case WRAPPER_TYPE:
return sizeof(wrapper);
default:
critical_error("Invalid header",(cell)this);
return 0; /* can't happen */
}
}
data_heap_room factor_vm::data_room()
{
data_heap_room room;
room.nursery_size = nursery.size;
room.nursery_occupied = nursery.occupied_space();
room.nursery_free = nursery.free_space();
room.aging_size = data->aging->size;
room.aging_occupied = data->aging->occupied_space();
room.aging_free = data->aging->free_space();
room.tenured_size = data->tenured->size;
room.tenured_occupied = data->tenured->occupied_space();
room.tenured_total_free = data->tenured->free_space();
room.tenured_contiguous_free = data->tenured->largest_free_block();
room.tenured_free_block_count = data->tenured->free_block_count();
room.cards = data->cards_end - data->cards;
room.decks = data->decks_end - data->decks;
room.mark_stack = data->tenured->mark_stack.capacity() * sizeof(cell);
return room;
}
void factor_vm::primitive_data_room()
{
data_heap_room room = data_room();
dpush(tag<byte_array>(byte_array_from_value(&room)));
}
struct object_accumulator {
cell type;
std::vector<cell> objects;
explicit object_accumulator(cell type_) : type(type_) {}
void operator()(object *obj)
{
if(type == TYPE_COUNT || obj->type() == type)
objects.push_back(tag_dynamic(obj));
}
};
cell factor_vm::instances(cell type)
{
object_accumulator accum(type);
each_object(accum);
cell object_count = accum.objects.size();
data_roots.push_back(data_root_range(&accum.objects[0],object_count));
array *objects = allot_array(object_count,false_object);
memcpy(objects->data(),&accum.objects[0],object_count * sizeof(cell));
data_roots.pop_back();
return tag<array>(objects);
}
void factor_vm::primitive_all_instances()
{
primitive_full_gc();
dpush(instances(TYPE_COUNT));
}
cell factor_vm::find_all_words()
{
return instances(WORD_TYPE);
}
}
|
#include "master.hpp"
namespace factor
{
void factor_vm::init_card_decks()
{
cards_offset = (cell)data->cards - addr_to_card(data->start);
decks_offset = (cell)data->decks - addr_to_deck(data->start);
}
data_heap::data_heap(cell young_size_,
cell aging_size_,
cell tenured_size_)
{
young_size_ = align(young_size_,deck_size);
aging_size_ = align(aging_size_,deck_size);
tenured_size_ = align(tenured_size_,deck_size);
young_size = young_size_;
aging_size = aging_size_;
tenured_size = tenured_size_;
cell total_size = young_size + 2 * aging_size + tenured_size + deck_size;
seg = new segment(total_size,false);
cell cards_size = addr_to_card(total_size);
cards = new card[cards_size];
cards_end = cards + cards_size;
memset(cards,0,cards_size);
cell decks_size = addr_to_deck(total_size);
decks = new card_deck[decks_size];
decks_end = decks + decks_size;
memset(decks,0,decks_size);
start = align(seg->start,deck_size);
tenured = new tenured_space(tenured_size,start);
aging = new aging_space(aging_size,tenured->end);
aging_semispace = new aging_space(aging_size,aging->end);
nursery = new nursery_space(young_size,aging_semispace->end);
assert(seg->end - nursery->end <= deck_size);
}
data_heap::~data_heap()
{
delete seg;
delete nursery;
delete aging;
delete aging_semispace;
delete tenured;
delete[] cards;
delete[] decks;
}
data_heap *data_heap::grow(cell requested_bytes)
{
cell new_tenured_size = (tenured_size * 2) + requested_bytes;
return new data_heap(young_size,
aging_size,
new_tenured_size);
}
template<typename Generation> void data_heap::clear_cards(Generation *gen)
{
cell first_card = addr_to_card(gen->start - start);
cell last_card = addr_to_card(gen->end - start);
memset(&cards[first_card],0,last_card - first_card);
}
template<typename Generation> void data_heap::clear_decks(Generation *gen)
{
cell first_deck = addr_to_deck(gen->start - start);
cell last_deck = addr_to_deck(gen->end - start);
memset(&decks[first_deck],0,last_deck - first_deck);
}
void data_heap::reset_generation(nursery_space *gen)
{
gen->here = gen->start;
}
void data_heap::reset_generation(aging_space *gen)
{
gen->here = gen->start;
clear_cards(gen);
clear_decks(gen);
gen->starts.clear_object_start_offsets();
}
void data_heap::reset_generation(tenured_space *gen)
{
clear_cards(gen);
clear_decks(gen);
}
bool data_heap::low_memory_p()
{
return (tenured->free_space() <= nursery->size + aging->size);
}
void data_heap::mark_all_cards()
{
memset(cards,-1,cards_end - cards);
memset(decks,-1,decks_end - decks);
}
void factor_vm::set_data_heap(data_heap *data_)
{
data = data_;
nursery = *data->nursery;
init_card_decks();
}
void factor_vm::init_data_heap(cell young_size, cell aging_size, cell tenured_size)
{
set_data_heap(new data_heap(young_size,aging_size,tenured_size));
}
/* Size of the object pointed to by an untagged pointer */
cell object::size() const
{
if(free_p()) return ((free_heap_block *)this)->size();
switch(type())
{
case ARRAY_TYPE:
return align(array_size((array*)this),data_alignment);
case BIGNUM_TYPE:
return align(array_size((bignum*)this),data_alignment);
case BYTE_ARRAY_TYPE:
return align(array_size((byte_array*)this),data_alignment);
case STRING_TYPE:
return align(string_size(string_capacity((string*)this)),data_alignment);
case TUPLE_TYPE:
{
tuple_layout *layout = (tuple_layout *)UNTAG(((tuple *)this)->layout);
return align(tuple_size(layout),data_alignment);
}
case QUOTATION_TYPE:
return align(sizeof(quotation),data_alignment);
case WORD_TYPE:
return align(sizeof(word),data_alignment);
case FLOAT_TYPE:
return align(sizeof(boxed_float),data_alignment);
case DLL_TYPE:
return align(sizeof(dll),data_alignment);
case ALIEN_TYPE:
return align(sizeof(alien),data_alignment);
case WRAPPER_TYPE:
return align(sizeof(wrapper),data_alignment);
case CALLSTACK_TYPE:
return align(callstack_size(untag_fixnum(((callstack *)this)->length)),data_alignment);
default:
critical_error("Invalid header",(cell)this);
return 0; /* can't happen */
}
}
/* The number of cells from the start of the object which should be scanned by
the GC. Some types have a binary payload at the end (string, word, DLL) which
we ignore. */
cell object::binary_payload_start() const
{
if(free_p()) return 0;
switch(type())
{
/* these objects do not refer to other objects at all */
case FLOAT_TYPE:
case BYTE_ARRAY_TYPE:
case BIGNUM_TYPE:
case CALLSTACK_TYPE:
return 0;
/* these objects have some binary data at the end */
case WORD_TYPE:
return sizeof(word) - sizeof(cell) * 3;
case ALIEN_TYPE:
return sizeof(cell) * 3;
case DLL_TYPE:
return sizeof(cell) * 2;
case QUOTATION_TYPE:
return sizeof(quotation) - sizeof(cell) * 2;
case STRING_TYPE:
return sizeof(string);
/* everything else consists entirely of pointers */
case ARRAY_TYPE:
return array_size<array>(array_capacity((array*)this));
case TUPLE_TYPE:
return tuple_size(untag<tuple_layout>(((tuple *)this)->layout));
case WRAPPER_TYPE:
return sizeof(wrapper);
default:
critical_error("Invalid header",(cell)this);
return 0; /* can't happen */
}
}
data_heap_room factor_vm::data_room()
{
data_heap_room room;
room.nursery_size = nursery.size;
room.nursery_occupied = nursery.occupied_space();
room.nursery_free = nursery.free_space();
room.aging_size = data->aging->size;
room.aging_occupied = data->aging->occupied_space();
room.aging_free = data->aging->free_space();
room.tenured_size = data->tenured->size;
room.tenured_occupied = data->tenured->occupied_space();
room.tenured_total_free = data->tenured->free_space();
room.tenured_contiguous_free = data->tenured->largest_free_block();
room.tenured_free_block_count = data->tenured->free_block_count();
room.cards = data->cards_end - data->cards;
room.decks = data->decks_end - data->decks;
room.mark_stack = data->tenured->mark_stack.capacity() * sizeof(cell);
return room;
}
void factor_vm::primitive_data_room()
{
data_heap_room room = data_room();
dpush(tag<byte_array>(byte_array_from_value(&room)));
}
struct object_accumulator {
cell type;
std::vector<cell> objects;
explicit object_accumulator(cell type_) : type(type_) {}
void operator()(object *obj)
{
if(type == TYPE_COUNT || obj->type() == type)
objects.push_back(tag_dynamic(obj));
}
};
cell factor_vm::instances(cell type)
{
object_accumulator accum(type);
each_object(accum);
cell object_count = accum.objects.size();
data_roots.push_back(data_root_range(&accum.objects[0],object_count));
array *objects = allot_array(object_count,false_object);
memcpy(objects->data(),&accum.objects[0],object_count * sizeof(cell));
data_roots.pop_back();
return tag<array>(objects);
}
void factor_vm::primitive_all_instances()
{
primitive_full_gc();
dpush(instances(TYPE_COUNT));
}
cell factor_vm::find_all_words()
{
return instances(WORD_TYPE);
}
}
|
fix problem in card marking if first block is free
|
vm: fix problem in card marking if first block is free
|
C++
|
bsd-2-clause
|
sarvex/factor-lang,factor/factor,slavapestov/factor,mrjbq7/factor,slavapestov/factor,AlexIljin/factor,bjourne/factor,mrjbq7/factor,slavapestov/factor,bpollack/factor,bjourne/factor,sarvex/factor-lang,bpollack/factor,bjourne/factor,sarvex/factor-lang,tgunr/factor,factor/factor,bjourne/factor,nicolas-p/factor,tgunr/factor,mrjbq7/factor,nicolas-p/factor,mrjbq7/factor,sarvex/factor-lang,bjourne/factor,factor/factor,dch/factor,dch/factor,AlexIljin/factor,sarvex/factor-lang,slavapestov/factor,nicolas-p/factor,bjourne/factor,dch/factor,bpollack/factor,AlexIljin/factor,bpollack/factor,tgunr/factor,AlexIljin/factor,nicolas-p/factor,slavapestov/factor,factor/factor,factor/factor,sarvex/factor-lang,nicolas-p/factor,tgunr/factor,AlexIljin/factor,slavapestov/factor,AlexIljin/factor,bjourne/factor,tgunr/factor,mrjbq7/factor,bpollack/factor,nicolas-p/factor,AlexIljin/factor,sarvex/factor-lang,dch/factor,slavapestov/factor,factor/factor,tgunr/factor,dch/factor,mrjbq7/factor,bpollack/factor,nicolas-p/factor,bpollack/factor,dch/factor
|
46d82c64edc316122af7417a412316e841ed64f6
|
src/zippylog/device/server.hpp
|
src/zippylog/device/server.hpp
|
// Copyright 2010 Gregory Szorc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef ZIPPYLOG_DEVICE_SERVER_HPP_
#define ZIPPYLOG_DEVICE_SERVER_HPP_
#include <zippylog/zippylog.hpp>
#include <zippylog/platform.hpp>
#include <zippylog/request_processor.hpp>
#include <zippylog/store.hpp>
#include <zippylog/store_watcher.hpp>
#include <zippylog/device/store_writer.hpp>
#include <zippylog/device/store_writer_sender.hpp>
#include <zippylog/device/streamer.hpp>
#include <vector>
#include <zmq.hpp>
namespace zippylog {
namespace device {
/// contains classes used by server device
namespace server {
/// Used to construct a server worker
class WorkerStartParams {
public:
// where to send client subscription messages
::std::string streaming_subscriptions_endpoint;
// where to send updates for existing subscriptions
::std::string streaming_updates_endpoint;
/// 0MQ endpoint for store writer's envelope PULL socket
::std::string store_writer_envelope_pull_endpoint;
/// 0MQ endpoint for store writer's envelope REP socket
::std::string store_writer_envelope_rep_endpoint;
::zippylog::RequestProcessorStartParams request_processor_params;
};
/// RequestProcessor implementation for the service device
///
/// When this request processor receives a request related to streaming, it
/// forwards it to the stream processors, via 1 of 2 sockets. The built-in
/// subscriptions sock load balances among all active streamers in the
/// server device. The subscription updates sock fans out to all instances.
/// The former is used when a message only needs to go to 1 streamer and the
/// latter when all streamers need to see it (e.g. a keepalive message since
/// the server doesn't know which streamers have which subscriptions).
class Worker : public ::zippylog::RequestProcessor {
public:
Worker(WorkerStartParams ¶ms);
~Worker();
protected:
// implement virtual functions
ResponseStatus HandleSubscribeStoreChanges(Envelope &request, ::std::vector<Envelope> &output);
ResponseStatus HandleSubscribeEnvelopes(Envelope &request, ::std::vector<Envelope> &output);
ResponseStatus HandleSubscribeKeepalive(Envelope &request, ::std::vector<Envelope> &output);
bool HandleWriteEnvelopes(const ::std::string &path, ::std::vector<Envelope> &to_write, bool synchronous);
::std::string streaming_subscriptions_endpoint;
::std::string streaming_updates_endpoint;
::zmq::socket_t *subscriptions_sock;
::zmq::socket_t *subscription_updates_sock;
::zippylog::device::StoreWriterSender * store_sender;
};
/// Create store watchers tailored for the server device
class WatcherStartParams {
public:
::zippylog::StoreWatcherStartParams params;
// 0MQ socket endpoint on which to bind a PUB socket
::std::string socket_endpoint;
};
/// Store watcher implementation for the server device
///
/// Whenever changes are seen, forwards store change events on a 0MQ PUB socket
/// whose endpoint is defined at construction time.
class Watcher : public ::zippylog::StoreWatcher {
public:
// Construct a watcher that sends events to a 0MQ PUB socket
Watcher(WatcherStartParams ¶ms);
~Watcher();
protected:
// implement the interface
void HandleAdded(::std::string path, platform::FileStat &stat);
void HandleDeleted(::std::string path);
void HandleModified(::std::string path, platform::FileStat &stat);
// sends the change to all interested parties
void SendChangeMessage(Envelope &e);
::std::string endpoint;
::zmq::socket_t * socket;
private:
Watcher(const Watcher &orig);
Watcher & operator=(const Watcher &orig);
};
} // end of server namespace
/// Holds the config for a server device
///
/// Typically this is populated by parsing a Lua file. However, it could also
/// be created manually and passed into a server's constructor.
class ServerConfig {
public:
ServerConfig();
/// the path to the store the server operates against
::std::string store_path;
/// 0MQ endpoints to bind XREP sockets to listen for client messages
::std::vector< ::std::string > listen_endpoints;
/// The number of worker threads to run
uint32 worker_threads;
/// The number of streaming threads to run
uint32 streaming_threads;
/// The default subscription expiration TTL, in milliseconds
uint32 subscription_ttl;
/// Bucket to log server's own log messages to
::std::string log_bucket;
/// Stream set to log server's own log messages to
::std::string log_stream_set;
/// How often to flush written streams, in milliseconds
int32 stream_flush_interval;
/// whether client-supplied Lua code can be executed
bool lua_execute_client_code;
/// max memory size of Lua interpreters attached to streaming
uint32 lua_streaming_max_memory;
};
/// The server is an uber device that provides server functionality
///
/// It has a couple of functions:
///
/// - ZMQ Device - it forwards 0MQ messages to and from the appropriate sockets
/// - Thread Manager - manages threads for request processing, store watching, streaming
/// - Logging coordinator - all process logging (itself using zippylog) flows through this class
///
/// SOCKET FLOWS
///
/// When a client connects to a configured listening socket, messages will
/// be handled as follows:
///
/// client -> <clients_sock> -> <workers_sock> -> worker thread
///
/// A worker thread will handle the message in one of the following:
///
/// - It will generate a response itself. It just sends the response
/// back through the workers_sock and it will make its way back to
/// the client.
/// - If a subscription keepalive, will forward the message to
/// worker_streaming_notify_sock. The broker receives messages
/// from all workers and then rebroadcasts the messages to all
/// streamers connected via streaming_streaming_notify_sock.
/// - If a subscription request, will forward the message to
/// worker_subscriptions_sock. The broker receives these messages
/// and sends to one streamer via streaming_subscriptions_sock.
/// The streamer that receives it will likely send a response via
/// streaming_sock and the broker will forward it to the
/// clients_sock.
///
/// In the streaming cases, the request response (if there is one) does not
/// come back through the workers_sock. This is perfectly fine, as that
/// socket is a XREQ socket. This preserves the event-driver architecture
/// of the server.
class ZIPPYLOG_EXPORT Server {
public:
/// Construct a server from a Lua config file
///
/// For a description of what configuration options are read, see
/// ParseConfig()
Server(const ::std::string config_file_path);
~Server();
/// Run the server synchronously
///
/// This will block until a fatal error is encountered or until the
/// Shutdown() function is called.
void Run();
/// Runs asynchronously
/// this creates a new thread, runs the server in that, then returns
void RunAsync();
/// Shut down the server
///
/// On first call, will trigger the shutdown semaphore which signals all
/// created threads to stop execution. The function call will block
/// until all threads have been joined.
///
/// On second call, is a no-op.
/// TODO need an API to force shutdown
void Shutdown();
protected:
::zmq::context_t zctx;
// fans XREQ that fans out to individual worker threads
::zmq::socket_t * workers_sock;
// binds to listen for client requests on configured interfaces
::zmq::socket_t * clients_sock;
// XREP that receives all streamed envelopes to be sent to clients
::zmq::socket_t * streaming_sock;
// PULL that receives processed client subscription requests
// messages delivered to one random streamer
::zmq::socket_t * worker_subscriptions_sock;
// PUSH that sends client subscription requests to streamers
::zmq::socket_t * streaming_subscriptions_sock;
// PULL that receives processed client streaming messages
// messages that need to be forwarded to all streamers
// we can't send directly from the workers to the streamers
// because there is potentially a many to many mapping there
// the broker binds to both endpoints and distributes messages
// properly
::zmq::socket_t * worker_streaming_notify_sock;
// PUB that sends processed client streaming messages to all streamers
::zmq::socket_t * streaming_streaming_notify_sock;
// PULL that receives logging messages from other threads
::zmq::socket_t * logger_sock;
// PUSH that sends logging messages to main logging sock
// yes, we have both a client and server in the same object. this is easier
::zmq::socket_t * log_client_sock;
/// server id
///
/// used for identification purposes in logging
::std::string id;
/// Thread running the server
///
/// Only present when server is running asynchronously via RunAsync()
::zippylog::platform::Thread * exec_thread;
/// Threads running workers/request processors
::std::vector< ::zippylog::platform::Thread * > worker_threads;
/// Threads running streamers
::std::vector< ::zippylog::platform::Thread * > streaming_threads;
/// Thread writing to the store
::zippylog::platform::Thread * store_writer_thread;
/// Thread watching the store
::zippylog::platform::Thread * store_watcher_thread;
/// The store we are bound to
::zippylog::Store * store;
bool active;
ServerConfig config;
/// Whether the internal structure is set up and ready for running
bool initialized;
/// used to construct child objects
///
/// The addresses of these variables are passed when starting the
/// threads for these objects.
::zippylog::device::server::WorkerStartParams request_processor_params;
::zippylog::device::StreamerStartParams streamer_params;
::zippylog::device::server::WatcherStartParams store_watcher_params;
::zippylog::device::StoreWriterStartParams store_writer_params;
/// 0MQ endpoints used by various internal sockets
::std::string worker_endpoint;
::std::string store_change_endpoint;
::std::string streaming_endpoint;
::std::string logger_endpoint;
::std::string worker_subscriptions_endpoint;
::std::string streaming_subscriptions_endpoint;
::std::string worker_streaming_notify_endpoint;
::std::string streaming_streaming_notify_endpoint;
::std::string store_writer_envelope_pull_endpoint;
::std::string store_writer_envelope_rep_endpoint;
static bool ParseConfig(const ::std::string path, ServerConfig &config, ::std::string &error);
/// Thread start functions
static void * StoreWatcherStart(void *data);
static void * StreamingStart(void *data);
static void * AsyncExecStart(void *data);
static void * RequestProcessorStart(void *data);
static void * StoreWriterStart(void *data);
/// Populates the *StartParams members with appropriate values
bool SynchronizeStartParams();
/// Initialize internal sockets and threads
bool Initialize();
/// Spins up a new worker thread
bool CreateWorkerThread();
/// Spins up a new thread to process streaming
bool CreateStreamingThread();
private:
// copy constructor and assignment operator are not available
Server(const Server &orig);
Server & operator=(const Server &orig);
};
}} // namespaces
#endif
|
// Copyright 2010 Gregory Szorc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef ZIPPYLOG_DEVICE_SERVER_HPP_
#define ZIPPYLOG_DEVICE_SERVER_HPP_
#include <zippylog/zippylog.hpp>
#include <zippylog/platform.hpp>
#include <zippylog/request_processor.hpp>
#include <zippylog/store.hpp>
#include <zippylog/store_watcher.hpp>
#include <zippylog/device/store_writer.hpp>
#include <zippylog/device/store_writer_sender.hpp>
#include <zippylog/device/streamer.hpp>
#include <vector>
#include <zmq.hpp>
namespace zippylog {
namespace device {
/// contains classes used by server device
namespace server {
/// Used to construct a server worker
class WorkerStartParams {
public:
// where to send client subscription messages
::std::string streaming_subscriptions_endpoint;
// where to send updates for existing subscriptions
::std::string streaming_updates_endpoint;
/// 0MQ endpoint for store writer's envelope PULL socket
::std::string store_writer_envelope_pull_endpoint;
/// 0MQ endpoint for store writer's envelope REP socket
::std::string store_writer_envelope_rep_endpoint;
::zippylog::RequestProcessorStartParams request_processor_params;
};
/// RequestProcessor implementation for the service device
///
/// When this request processor receives a request related to streaming, it
/// forwards it to the stream processors, via 1 of 2 sockets. The built-in
/// subscriptions sock load balances among all active streamers in the
/// server device. The subscription updates sock fans out to all instances.
/// The former is used when a message only needs to go to 1 streamer and the
/// latter when all streamers need to see it (e.g. a keepalive message since
/// the server doesn't know which streamers have which subscriptions).
class Worker : public ::zippylog::RequestProcessor {
public:
Worker(WorkerStartParams ¶ms);
~Worker();
protected:
// implement virtual functions
ResponseStatus HandleSubscribeStoreChanges(Envelope &request, ::std::vector<Envelope> &output);
ResponseStatus HandleSubscribeEnvelopes(Envelope &request, ::std::vector<Envelope> &output);
ResponseStatus HandleSubscribeKeepalive(Envelope &request, ::std::vector<Envelope> &output);
bool HandleWriteEnvelopes(const ::std::string &path, ::std::vector<Envelope> &to_write, bool synchronous);
::std::string streaming_subscriptions_endpoint;
::std::string streaming_updates_endpoint;
::zmq::socket_t *subscriptions_sock;
::zmq::socket_t *subscription_updates_sock;
::zippylog::device::StoreWriterSender * store_sender;
};
/// Create store watchers tailored for the server device
class WatcherStartParams {
public:
::zippylog::StoreWatcherStartParams params;
// 0MQ socket endpoint on which to bind a PUB socket
::std::string socket_endpoint;
};
/// Store watcher implementation for the server device
///
/// Whenever changes are seen, forwards store change events on a 0MQ PUB socket
/// whose endpoint is defined at construction time.
class Watcher : public ::zippylog::StoreWatcher {
public:
// Construct a watcher that sends events to a 0MQ PUB socket
Watcher(WatcherStartParams ¶ms);
~Watcher();
protected:
// implement the interface
void HandleAdded(::std::string path, platform::FileStat &stat);
void HandleDeleted(::std::string path);
void HandleModified(::std::string path, platform::FileStat &stat);
// sends the change to all interested parties
void SendChangeMessage(Envelope &e);
::std::string endpoint;
::zmq::socket_t * socket;
private:
Watcher(const Watcher &orig);
Watcher & operator=(const Watcher &orig);
};
} // end of server namespace
/// Holds the config for a server device
///
/// Typically this is populated by parsing a Lua file. However, it could also
/// be created manually and passed into a server's constructor.
class ServerConfig {
public:
ServerConfig();
/// the path to the store the server operates against
::std::string store_path;
/// 0MQ endpoints to bind XREP sockets to listen for client messages
::std::vector< ::std::string > listen_endpoints;
/// The number of worker threads to run
uint32 worker_threads;
/// The number of streaming threads to run
uint32 streaming_threads;
/// The default subscription expiration TTL, in milliseconds
uint32 subscription_ttl;
/// Bucket to log server's own log messages to
::std::string log_bucket;
/// Stream set to log server's own log messages to
::std::string log_stream_set;
/// How often to flush written streams, in milliseconds
int32 stream_flush_interval;
/// whether client-supplied Lua code can be executed
bool lua_execute_client_code;
/// max memory size of Lua interpreters attached to streaming
uint32 lua_streaming_max_memory;
};
/// The server is an uber device that provides server functionality
///
/// It has a couple of functions:
///
/// - ZMQ Device - it forwards 0MQ messages to and from the appropriate sockets
/// - Thread Manager - manages threads for request processing, store watching, streaming
/// - Logging coordinator - all process logging (itself using zippylog) flows through this class
///
/// SOCKET FLOWS
///
/// When a client connects to a configured listening socket, messages will
/// be handled as follows:
///
/// client -> <clients_sock> -> <workers_sock> -> worker thread
///
/// A worker thread will handle the message in one of the following:
///
/// - It will generate a response itself. It just sends the response
/// back through the workers_sock and it will make its way back to
/// the client.
/// - If a subscription keepalive, will forward the message to
/// worker_streaming_notify_sock. The broker receives messages
/// from all workers and then rebroadcasts the messages to all
/// streamers connected via streaming_streaming_notify_sock.
/// - If a subscription request, will forward the message to
/// worker_subscriptions_sock. The broker receives these messages
/// and sends to one streamer via streaming_subscriptions_sock.
/// The streamer that receives it will likely send a response via
/// streaming_sock and the broker will forward it to the
/// clients_sock.
///
/// In the streaming cases, the request response (if there is one) does not
/// come back through the workers_sock. This is perfectly fine, as that
/// socket is a XREQ socket. This preserves the event-driver architecture
/// of the server.
class ZIPPYLOG_EXPORT Server {
public:
/// Construct a server from a Lua config file
///
/// For a description of what configuration options are read, see
/// ParseConfig()
Server(const ::std::string config_file_path);
~Server();
/// Run the server synchronously
///
/// This will block until a fatal error is encountered or until the
/// Shutdown() function is called.
void Run();
/// Runs asynchronously
/// this creates a new thread, runs the server in that, then returns
void RunAsync();
/// Shut down the server
///
/// On first call, will trigger the shutdown semaphore which signals all
/// created threads to stop execution. The function call will block
/// until all threads have been joined.
///
/// On second call, is a no-op.
/// TODO need an API to force shutdown
void Shutdown();
protected:
static bool ParseConfig(const ::std::string path, ServerConfig &config, ::std::string &error);
/// Thread start functions
static void * StoreWatcherStart(void *data);
static void * StreamingStart(void *data);
static void * AsyncExecStart(void *data);
static void * RequestProcessorStart(void *data);
static void * StoreWriterStart(void *data);
/// Populates the *StartParams members with appropriate values
bool SynchronizeStartParams();
/// Initialize internal sockets and threads
bool Initialize();
/// Spins up a new worker thread
bool CreateWorkerThread();
/// Spins up a new thread to process streaming
bool CreateStreamingThread();
/// Holds the main server config
/// TODO factor this into individual variables and remove
ServerConfig config;
/// The store we are bound to
::zippylog::Store * store;
/// Whether we are running
bool active;
/// Whether the internal structure is set up and ready for running
bool initialized;
/// 0MQ context to use
///
/// Currently, we have our own dedicated context, but this could change
::zmq::context_t zctx;
// fans XREQ that fans out to individual worker threads
::zmq::socket_t * workers_sock;
::std::string worker_endpoint;
// binds to listen for client requests on configured interfaces
::zmq::socket_t * clients_sock;
// XREP that receives all streamed envelopes to be sent to clients
::zmq::socket_t * streaming_sock;
::std::string streaming_endpoint;
// PULL that receives processed client subscription requests
// messages delivered to one random streamer
::zmq::socket_t * worker_subscriptions_sock;
::std::string worker_subscriptions_endpoint;
// PUSH that sends client subscription requests to streamers
::zmq::socket_t * streaming_subscriptions_sock;
::std::string streaming_subscriptions_endpoint;
// PULL that receives processed client streaming messages
// messages that need to be forwarded to all streamers
// we can't send directly from the workers to the streamers
// because there is potentially a many to many mapping there
// the broker binds to both endpoints and distributes messages
// properly
::zmq::socket_t * worker_streaming_notify_sock;
::std::string worker_streaming_notify_endpoint;
// PUB that sends processed client streaming messages to all streamers
::zmq::socket_t * streaming_streaming_notify_sock;
::std::string streaming_streaming_notify_endpoint;
// PULL that receives logging messages from other threads
::zmq::socket_t * logger_sock;
::std::string logger_endpoint;
// PUSH that sends logging messages to main logging sock
// yes, we have both a client and server in the same object. this is easier
::zmq::socket_t * log_client_sock;
/// socket endpoint used to receive store changes
/// streamers connect to this directly, so we don't have
/// a local socket
::std::string store_change_endpoint;
/// socket endpoints used by store writer
::std::string store_writer_envelope_pull_endpoint;
::std::string store_writer_envelope_rep_endpoint;
/// server id
///
/// used for identification purposes in logging
::std::string id;
/// Thread running the server
///
/// Only present when server is running asynchronously via RunAsync()
::zippylog::platform::Thread * exec_thread;
/// Thread writing to the store
::zippylog::platform::Thread * store_writer_thread;
/// Thread watching the store
::zippylog::platform::Thread * store_watcher_thread;
/// Threads running workers/request processors
::std::vector< ::zippylog::platform::Thread * > worker_threads;
/// Threads running streamers
::std::vector< ::zippylog::platform::Thread * > streaming_threads;
/// used to construct child objects
///
/// The addresses of these variables are passed when starting the
/// threads for these objects.
::zippylog::device::server::WorkerStartParams request_processor_params;
::zippylog::device::StreamerStartParams streamer_params;
::zippylog::device::server::WatcherStartParams store_watcher_params;
::zippylog::device::StoreWriterStartParams store_writer_params;
private:
// copy constructor and assignment operator are not available
Server(const Server &orig);
Server & operator=(const Server &orig);
};
}} // namespaces
#endif
|
reorder member variables
|
reorder member variables
|
C++
|
apache-2.0
|
indygreg/zippylog,indygreg/zippylog,indygreg/zippylog,indygreg/zippylog
|
e3236e68753b82dbd4538078a5ddb8676d378fa8
|
src/cpp/session/modules/tex/SessionTexi2Dvi.cpp
|
src/cpp/session/modules/tex/SessionTexi2Dvi.cpp
|
/*
* SessionTexi2Dvi.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionTexi2Dvi.hpp"
#include <boost/format.hpp>
#include <core/system/ShellUtils.hpp>
#include <core/system/Process.hpp>
#include <core/system/Environment.hpp>
#include <session/SessionModuleContext.hpp>
#include "SessionPdfLatex.hpp"
#include "SessionTexUtils.hpp"
// platform specific constants
#ifdef _WIN32
const char * const kScriptEx = ".cmd";
#else
const char * const kScriptEx = ".sh";
#endif
using namespace core;
namespace session {
namespace modules {
namespace tex {
namespace texi2dvi {
namespace {
struct Texi2DviInfo
{
bool empty() const { return programFilePath.empty(); }
FilePath programFilePath;
const std::string versionInfo;
};
Texi2DviInfo texi2DviInfo()
{
// get the path to the texi2dvi binary
FilePath programFilePath = module_context::findProgram("texi2dvi");
if (programFilePath.empty())
return Texi2DviInfo();
// this is enough to return so setup the return structure
Texi2DviInfo t2dviInfo;
t2dviInfo.programFilePath = programFilePath;
// try to get version info from it
core::system::ProcessResult result;
Error error = core::system::runProgram(
string_utils::utf8ToSystem(programFilePath.absolutePath()),
core::shell_utils::ShellArgs() << "--version",
"",
core::system::ProcessOptions(),
&result);
if (error)
LOG_ERROR(error);
else if (result.exitStatus != EXIT_SUCCESS)
LOG_ERROR_MESSAGE("Error probing for texi2dvi version: "+ result.stdErr);
// return what we have
return t2dviInfo;
}
// set of environment variables to customize pdflatex invocation
// includes both the core PDFLATEX command (which maps to the location
// of the custom rstudio-pdflatex script) as well as environment
// variables required to pass options to the script
core::system::Options pdfLatexEnvVars(
const tex::pdflatex::PdfLatexOptions& options)
{
core::system::Options envVars;
// executable
FilePath pdfLatexPath;
std::string pdfLatexEnv = core::system::getenv("PDFLATEX");
if (!pdfLatexEnv.empty())
{
pdfLatexPath = FilePath(pdfLatexEnv);
}
else
{
pdfLatexPath = module_context::findProgram("pdflatex");
}
envVars.push_back(std::make_pair("RS_PDFLATEX",
string_utils::utf8ToSystem(pdfLatexPath.absolutePath())));
// options
boost::format fmt("RS_PDFLATEX_OPTION_%1%");
int n = 1;
if (options.fileLineError)
{
envVars.push_back(std::make_pair(boost::str(fmt % n++),
pdflatex::kFileLineErrorOption));
}
if (options.syncTex)
{
envVars.push_back(std::make_pair(boost::str(fmt % n++),
pdflatex::kSynctexOption));
}
// rstudio-pdflatex script
FilePath texScriptsPath = session::options().texScriptsPath();
FilePath scriptPath = texScriptsPath.complete("rstudio-pdflatex" +
std::string(kScriptEx));
std::string path = string_utils::utf8ToSystem(scriptPath.absolutePath());
envVars.push_back(std::make_pair("PDFLATEX", path));
// return envVars
return envVars;
}
core::system::Options environmentVars(
const std::string& versionInfo,
const pdflatex::PdfLatexOptions& pdfLatexOptions)
{
// start with inputs (TEXINPUTS, BIBINPUTS, BSTINPUTS)
core::system::Options envVars = utils::rTexInputsEnvVars();
// The tools::texi2dvi function sets these environment variables (on posix)
// so they are presumably there as workarounds-- it would be good to
// understand exactly why they are defined and consequently whether we also
// need to define them
#ifndef _WIN32
envVars.push_back(std::make_pair("TEXINDY", "false"));
envVars.push_back(std::make_pair("LC_COLLATE", "C"));
#endif
// env vars required to customize invocation of pdflatex
core::system::Options pdfLatexVars = pdfLatexEnvVars(pdfLatexOptions);
std::copy(pdfLatexVars.begin(),
pdfLatexVars.end(),
std::back_inserter(envVars));
return envVars;
}
shell_utils::ShellArgs shellArgs(const std::string& texVersionInfo)
{
shell_utils::ShellArgs args;
args << "--pdf";
args << "--quiet";
#ifdef _WIN32
// This emulates two behaviors found in tools::texi2dvi:
//
// (1) Detecting MikTeX and in that case passing TEXINPUTS and
// BSTINPUTS (but not BIBINPUTS) on the texi2devi command line
//
// (2) Substituting any instances of \ in the paths with /
//
if (texVersionInfo.find("MiKTeX") != std::string::npos)
{
inputs::RTexmfPaths texmfPaths = inputs::rTexmfPaths();
if (!texmfPaths.empty())
{
std::string texInputs = string_utils::utf8ToSystem(
texmfPaths.texInputsPath.absolutePath());
boost::algorithm::replace_all(texInputs, "\\", "/");
args << "-I" << texInputs;
std::string bstInputs = string_utils::utf8ToSystem(
texmfPaths.bstInputsPath.absolutePath());
boost::algorithm::replace_all(bstInputs, "\\", "/");
args << "-I" << bstInputs;
}
}
#endif
return args;
}
} // anonymous namespace
Error texToPdf(const tex::pdflatex::PdfLatexOptions& options,
const FilePath& texFilePath,
core::system::ProcessResult* pResult)
{
Texi2DviInfo t2dviInfo = texi2DviInfo();
if (t2dviInfo.empty())
return core::fileNotFoundError("texi2dvi", ERROR_LOCATION);
return utils::runTexCompile(t2dviInfo.programFilePath,
environmentVars(t2dviInfo.versionInfo, options),
shellArgs(t2dviInfo.versionInfo),
texFilePath,
pResult);
}
} // namespace texi2dvi
} // namespace tex
} // namespace modules
} // namesapce session
|
/*
* SessionTexi2Dvi.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionTexi2Dvi.hpp"
#include <boost/format.hpp>
#include <core/system/ShellUtils.hpp>
#include <core/system/Process.hpp>
#include <core/system/Environment.hpp>
#include <session/SessionModuleContext.hpp>
#include "SessionPdfLatex.hpp"
#include "SessionTexUtils.hpp"
// platform specific constants
#ifdef _WIN32
const char * const kScriptEx = ".cmd";
#else
const char * const kScriptEx = ".sh";
#endif
using namespace core;
namespace session {
namespace modules {
namespace tex {
namespace texi2dvi {
namespace {
struct Texi2DviInfo
{
bool empty() const { return programFilePath.empty(); }
FilePath programFilePath;
const std::string versionInfo;
};
Texi2DviInfo texi2DviInfo()
{
// get the path to the texi2dvi binary
FilePath programFilePath = module_context::findProgram("texi2dvi");
if (programFilePath.empty())
return Texi2DviInfo();
// this is enough to return so setup the return structure
Texi2DviInfo t2dviInfo;
t2dviInfo.programFilePath = programFilePath;
// try to get version info from it
core::system::ProcessResult result;
Error error = core::system::runProgram(
string_utils::utf8ToSystem(programFilePath.absolutePath()),
core::shell_utils::ShellArgs() << "--version",
"",
core::system::ProcessOptions(),
&result);
if (error)
LOG_ERROR(error);
else if (result.exitStatus != EXIT_SUCCESS)
LOG_ERROR_MESSAGE("Error probing for texi2dvi version: "+ result.stdErr);
// return what we have
return t2dviInfo;
}
// set of environment variables to customize pdflatex invocation
// includes both the core PDFLATEX command (which maps to the location
// of the custom rstudio-pdflatex script) as well as environment
// variables required to pass options to the script
core::system::Options pdfLatexEnvVars(
const tex::pdflatex::PdfLatexOptions& options)
{
core::system::Options envVars;
// executable
FilePath pdfLatexPath;
std::string pdfLatexEnv = core::system::getenv("PDFLATEX");
if (!pdfLatexEnv.empty())
{
pdfLatexPath = FilePath(pdfLatexEnv);
}
else
{
pdfLatexPath = module_context::findProgram("pdflatex");
}
envVars.push_back(std::make_pair("RS_PDFLATEX",
string_utils::utf8ToSystem(pdfLatexPath.absolutePath())));
// options
boost::format fmt("RS_PDFLATEX_OPTION_%1%");
int n = 1;
if (options.fileLineError)
{
envVars.push_back(std::make_pair(boost::str(fmt % n++),
pdflatex::kFileLineErrorOption));
}
if (options.syncTex)
{
envVars.push_back(std::make_pair(boost::str(fmt % n++),
pdflatex::kSynctexOption));
}
// rstudio-pdflatex script
FilePath texScriptsPath = session::options().texScriptsPath();
FilePath scriptPath = texScriptsPath.complete("rstudio-pdflatex" +
std::string(kScriptEx));
std::string path = string_utils::utf8ToSystem(scriptPath.absolutePath());
envVars.push_back(std::make_pair("PDFLATEX", path));
// return envVars
return envVars;
}
core::system::Options environmentVars(
const std::string& versionInfo,
const pdflatex::PdfLatexOptions& pdfLatexOptions)
{
// start with inputs (TEXINPUTS, BIBINPUTS, BSTINPUTS)
core::system::Options envVars = utils::rTexInputsEnvVars();
// The tools::texi2dvi function sets these environment variables (on posix)
// so they are presumably there as workarounds-- it would be good to
// understand exactly why they are defined and consequently whether we also
// need to define them
#ifndef _WIN32
envVars.push_back(std::make_pair("TEXINDY", "false"));
envVars.push_back(std::make_pair("LC_COLLATE", "C"));
#endif
// env vars required to customize invocation of pdflatex
core::system::Options pdfLatexVars = pdfLatexEnvVars(pdfLatexOptions);
std::copy(pdfLatexVars.begin(),
pdfLatexVars.end(),
std::back_inserter(envVars));
return envVars;
}
shell_utils::ShellArgs shellArgs(const std::string& texVersionInfo)
{
shell_utils::ShellArgs args;
args << "--pdf";
args << "--quiet";
#ifdef _WIN32
// This emulates two behaviors found in tools::texi2dvi:
//
// (1) Detecting MikTeX and in that case passing TEXINPUTS and
// BSTINPUTS (but not BIBINPUTS) on the texi2devi command line
//
// (2) Substituting any instances of \ in the paths with /
//
if (texVersionInfo.find("MiKTeX") != std::string::npos)
{
utils::RTexmfPaths texmfPaths = utils::rTexmfPaths();
if (!texmfPaths.empty())
{
std::string texInputs = string_utils::utf8ToSystem(
texmfPaths.texInputsPath.absolutePath());
boost::algorithm::replace_all(texInputs, "\\", "/");
args << "-I" << texInputs;
std::string bstInputs = string_utils::utf8ToSystem(
texmfPaths.bstInputsPath.absolutePath());
boost::algorithm::replace_all(bstInputs, "\\", "/");
args << "-I" << bstInputs;
}
}
#endif
return args;
}
} // anonymous namespace
Error texToPdf(const tex::pdflatex::PdfLatexOptions& options,
const FilePath& texFilePath,
core::system::ProcessResult* pResult)
{
Texi2DviInfo t2dviInfo = texi2DviInfo();
if (t2dviInfo.empty())
return core::fileNotFoundError("texi2dvi", ERROR_LOCATION);
return utils::runTexCompile(t2dviInfo.programFilePath,
environmentVars(t2dviInfo.versionInfo, options),
shellArgs(t2dviInfo.versionInfo),
texFilePath,
pResult);
}
} // namespace texi2dvi
} // namespace tex
} // namespace modules
} // namesapce session
|
fix win32 build
|
fix win32 build
|
C++
|
agpl-3.0
|
maligulzar/Rstudio-instrumented,jar1karp/rstudio,pssguy/rstudio,sfloresm/rstudio,suribes/rstudio,sfloresm/rstudio,thklaus/rstudio,JanMarvin/rstudio,sfloresm/rstudio,jzhu8803/rstudio,pssguy/rstudio,nvoron23/rstudio,Sage-Bionetworks/rstudio,nvoron23/rstudio,brsimioni/rstudio,suribes/rstudio,piersharding/rstudio,piersharding/rstudio,maligulzar/Rstudio-instrumented,suribes/rstudio,suribes/rstudio,jar1karp/rstudio,suribes/rstudio,jar1karp/rstudio,pssguy/rstudio,Sage-Bionetworks/rstudio,vbelakov/rstudio,Sage-Bionetworks/rstudio,edrogers/rstudio,edrogers/rstudio,maligulzar/Rstudio-instrumented,thklaus/rstudio,JanMarvin/rstudio,nvoron23/rstudio,jrnold/rstudio,thklaus/rstudio,jrnold/rstudio,john-r-mcpherson/rstudio,brsimioni/rstudio,piersharding/rstudio,JanMarvin/rstudio,thklaus/rstudio,nvoron23/rstudio,tbarrongh/rstudio,thklaus/rstudio,john-r-mcpherson/rstudio,jrnold/rstudio,jrnold/rstudio,jar1karp/rstudio,JanMarvin/rstudio,suribes/rstudio,edrogers/rstudio,brsimioni/rstudio,jar1karp/rstudio,piersharding/rstudio,vbelakov/rstudio,thklaus/rstudio,john-r-mcpherson/rstudio,nvoron23/rstudio,jrnold/rstudio,thklaus/rstudio,john-r-mcpherson/rstudio,john-r-mcpherson/rstudio,jrnold/rstudio,maligulzar/Rstudio-instrumented,jzhu8803/rstudio,more1/rstudio,jzhu8803/rstudio,nvoron23/rstudio,vbelakov/rstudio,JanMarvin/rstudio,jar1karp/rstudio,john-r-mcpherson/rstudio,suribes/rstudio,githubfun/rstudio,githubfun/rstudio,githubfun/rstudio,more1/rstudio,JanMarvin/rstudio,jzhu8803/rstudio,jzhu8803/rstudio,more1/rstudio,sfloresm/rstudio,Sage-Bionetworks/rstudio,tbarrongh/rstudio,edrogers/rstudio,jzhu8803/rstudio,sfloresm/rstudio,edrogers/rstudio,tbarrongh/rstudio,tbarrongh/rstudio,JanMarvin/rstudio,piersharding/rstudio,brsimioni/rstudio,pssguy/rstudio,nvoron23/rstudio,more1/rstudio,maligulzar/Rstudio-instrumented,githubfun/rstudio,pssguy/rstudio,brsimioni/rstudio,more1/rstudio,sfloresm/rstudio,vbelakov/rstudio,tbarrongh/rstudio,maligulzar/Rstudio-instrumented,maligulzar/Rstudio-instrumented,githubfun/rstudio,john-r-mcpherson/rstudio,maligulzar/Rstudio-instrumented,more1/rstudio,brsimioni/rstudio,piersharding/rstudio,JanMarvin/rstudio,sfloresm/rstudio,more1/rstudio,vbelakov/rstudio,maligulzar/Rstudio-instrumented,tbarrongh/rstudio,Sage-Bionetworks/rstudio,Sage-Bionetworks/rstudio,JanMarvin/rstudio,tbarrongh/rstudio,Sage-Bionetworks/rstudio,tbarrongh/rstudio,vbelakov/rstudio,edrogers/rstudio,jar1karp/rstudio,jar1karp/rstudio,vbelakov/rstudio,githubfun/rstudio,pssguy/rstudio,jzhu8803/rstudio,jzhu8803/rstudio,jrnold/rstudio,edrogers/rstudio,edrogers/rstudio,jar1karp/rstudio,vbelakov/rstudio,pssguy/rstudio,githubfun/rstudio,brsimioni/rstudio,john-r-mcpherson/rstudio,piersharding/rstudio,pssguy/rstudio,piersharding/rstudio,jrnold/rstudio,githubfun/rstudio,brsimioni/rstudio,piersharding/rstudio,jrnold/rstudio,sfloresm/rstudio,thklaus/rstudio,suribes/rstudio,more1/rstudio
|
a6086fc9754c28a5f72045ca96b3a3a0f00dfce6
|
lib/Target/Blackfin/AsmPrinter/BlackfinAsmPrinter.cpp
|
lib/Target/Blackfin/AsmPrinter/BlackfinAsmPrinter.cpp
|
//===-- BlackfinAsmPrinter.cpp - Blackfin LLVM assembly writer ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains a printer that converts from our internal representation
// of machine-dependent LLVM code to GAS-format BLACKFIN assembly language.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "asm-printer"
#include "Blackfin.h"
#include "BlackfinInstrInfo.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Module.h"
#include "llvm/CodeGen/AsmPrinter.h"
#include "llvm/CodeGen/DwarfWriter.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetLoweringObjectFile.h"
#include "llvm/Target/TargetRegistry.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FormattedStream.h"
using namespace llvm;
STATISTIC(EmittedInsts, "Number of machine instrs printed");
namespace {
class BlackfinAsmPrinter : public AsmPrinter {
public:
BlackfinAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
const MCAsmInfo *MAI, bool V)
: AsmPrinter(O, TM, MAI, V) {}
virtual const char *getPassName() const {
return "Blackfin Assembly Printer";
}
void printOperand(const MachineInstr *MI, int opNum);
void printMemoryOperand(const MachineInstr *MI, int opNum);
void printInstruction(const MachineInstr *MI); // autogenerated.
static const char *getRegisterName(unsigned RegNo);
bool runOnMachineFunction(MachineFunction &F);
bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
unsigned AsmVariant, const char *ExtraCode);
bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
unsigned AsmVariant, const char *ExtraCode);
};
} // end of anonymous namespace
#include "BlackfinGenAsmWriter.inc"
extern "C" void LLVMInitializeBlackfinAsmPrinter() {
RegisterAsmPrinter<BlackfinAsmPrinter> X(TheBlackfinTarget);
}
/// runOnMachineFunction - This uses the printInstruction()
/// method to print assembly for each instruction.
///
bool BlackfinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
SetupMachineFunction(MF);
EmitFunctionHeader();
// Print out code for the function.
for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
I != E; ++I) {
// Print a label for the basic block.
EmitBasicBlockStart(I);
for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
II != E; ++II) {
// Print the assembly for the instruction.
processDebugLoc(II, true);
printInstruction(II);
if (VerboseAsm)
EmitComments(*II);
O << '\n';
processDebugLoc(II, false);
++EmittedInsts;
}
}
EmitJumpTableInfo();
O << "\t.size " << *CurrentFnSym << ", .-" << *CurrentFnSym << "\n";
if (DW)
DW->EndFunction(&MF);
return false;
}
void BlackfinAsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
const MachineOperand &MO = MI->getOperand (opNum);
switch (MO.getType()) {
case MachineOperand::MO_Register:
assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
"Virtual registers should be already mapped!");
O << getRegisterName(MO.getReg());
break;
case MachineOperand::MO_Immediate:
O << MO.getImm();
break;
case MachineOperand::MO_MachineBasicBlock:
O << *MO.getMBB()->getSymbol(OutContext);
return;
case MachineOperand::MO_GlobalAddress:
O << *GetGlobalValueSymbol(MO.getGlobal());
printOffset(MO.getOffset());
break;
case MachineOperand::MO_ExternalSymbol:
O << *GetExternalSymbolSymbol(MO.getSymbolName());
break;
case MachineOperand::MO_ConstantPoolIndex:
O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << "_"
<< MO.getIndex();
break;
case MachineOperand::MO_JumpTableIndex:
O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
<< '_' << MO.getIndex();
break;
default:
llvm_unreachable("<unknown operand type>");
break;
}
}
void BlackfinAsmPrinter::printMemoryOperand(const MachineInstr *MI, int opNum) {
printOperand(MI, opNum);
if (MI->getOperand(opNum+1).isImm() && MI->getOperand(opNum+1).getImm() == 0)
return;
O << " + ";
printOperand(MI, opNum+1);
}
/// PrintAsmOperand - Print out an operand for an inline asm expression.
///
bool BlackfinAsmPrinter::PrintAsmOperand(const MachineInstr *MI,
unsigned OpNo,
unsigned AsmVariant,
const char *ExtraCode) {
if (ExtraCode && ExtraCode[0]) {
if (ExtraCode[1] != 0) return true; // Unknown modifier.
switch (ExtraCode[0]) {
default: return true; // Unknown modifier.
case 'r':
break;
}
}
printOperand(MI, OpNo);
return false;
}
bool BlackfinAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
unsigned OpNo,
unsigned AsmVariant,
const char *ExtraCode) {
if (ExtraCode && ExtraCode[0])
return true; // Unknown modifier
O << '[';
printOperand(MI, OpNo);
O << ']';
return false;
}
|
//===-- BlackfinAsmPrinter.cpp - Blackfin LLVM assembly writer ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains a printer that converts from our internal representation
// of machine-dependent LLVM code to GAS-format BLACKFIN assembly language.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "asm-printer"
#include "Blackfin.h"
#include "BlackfinInstrInfo.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Module.h"
#include "llvm/CodeGen/AsmPrinter.h"
#include "llvm/CodeGen/DwarfWriter.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetLoweringObjectFile.h"
#include "llvm/Target/TargetRegistry.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FormattedStream.h"
using namespace llvm;
namespace {
class BlackfinAsmPrinter : public AsmPrinter {
public:
BlackfinAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
const MCAsmInfo *MAI, bool V)
: AsmPrinter(O, TM, MAI, V) {}
virtual const char *getPassName() const {
return "Blackfin Assembly Printer";
}
void printOperand(const MachineInstr *MI, int opNum);
void printMemoryOperand(const MachineInstr *MI, int opNum);
void printInstruction(const MachineInstr *MI); // autogenerated.
static const char *getRegisterName(unsigned RegNo);
void EmitInstruction(const MachineInstr *MI) { printInstruction(MI); }
bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
unsigned AsmVariant, const char *ExtraCode);
bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
unsigned AsmVariant, const char *ExtraCode);
};
} // end of anonymous namespace
#include "BlackfinGenAsmWriter.inc"
extern "C" void LLVMInitializeBlackfinAsmPrinter() {
RegisterAsmPrinter<BlackfinAsmPrinter> X(TheBlackfinTarget);
}
void BlackfinAsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
const MachineOperand &MO = MI->getOperand (opNum);
switch (MO.getType()) {
case MachineOperand::MO_Register:
assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
"Virtual registers should be already mapped!");
O << getRegisterName(MO.getReg());
break;
case MachineOperand::MO_Immediate:
O << MO.getImm();
break;
case MachineOperand::MO_MachineBasicBlock:
O << *MO.getMBB()->getSymbol(OutContext);
return;
case MachineOperand::MO_GlobalAddress:
O << *GetGlobalValueSymbol(MO.getGlobal());
printOffset(MO.getOffset());
break;
case MachineOperand::MO_ExternalSymbol:
O << *GetExternalSymbolSymbol(MO.getSymbolName());
break;
case MachineOperand::MO_ConstantPoolIndex:
O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << "_"
<< MO.getIndex();
break;
case MachineOperand::MO_JumpTableIndex:
O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
<< '_' << MO.getIndex();
break;
default:
llvm_unreachable("<unknown operand type>");
break;
}
}
void BlackfinAsmPrinter::printMemoryOperand(const MachineInstr *MI, int opNum) {
printOperand(MI, opNum);
if (MI->getOperand(opNum+1).isImm() && MI->getOperand(opNum+1).getImm() == 0)
return;
O << " + ";
printOperand(MI, opNum+1);
}
/// PrintAsmOperand - Print out an operand for an inline asm expression.
///
bool BlackfinAsmPrinter::PrintAsmOperand(const MachineInstr *MI,
unsigned OpNo,
unsigned AsmVariant,
const char *ExtraCode) {
if (ExtraCode && ExtraCode[0]) {
if (ExtraCode[1] != 0) return true; // Unknown modifier.
switch (ExtraCode[0]) {
default: return true; // Unknown modifier.
case 'r':
break;
}
}
printOperand(MI, OpNo);
return false;
}
bool BlackfinAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
unsigned OpNo,
unsigned AsmVariant,
const char *ExtraCode) {
if (ExtraCode && ExtraCode[0])
return true; // Unknown modifier
O << '[';
printOperand(MI, OpNo);
O << ']';
return false;
}
|
switch blackfin to the default runOnMachineFunction
|
switch blackfin to the default runOnMachineFunction
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@94729 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
bsd-2-clause
|
chubbymaggie/asap,dslab-epfl/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,dslab-epfl/asap,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,dslab-epfl/asap,chubbymaggie/asap,chubbymaggie/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,chubbymaggie/asap,llvm-mirror/llvm,dslab-epfl/asap,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,dslab-epfl/asap,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,chubbymaggie/asap,dslab-epfl/asap
|
c4bc7164994bda989fe1f294312cd3f6b98e8da5
|
EngineCommand.C
|
EngineCommand.C
|
#include "EngineCommand.h"
#include <maya/MArgDatabase.h>
#include <maya/MArgList.h>
#include <maya/MStatus.h>
#include <HAPI/HAPI.h>
#include "SubCommand.h"
#define kHoudiniVersionFlag "-hv"
#define kHoudiniVersionFlagLong "-houdiniVersion"
#define kHoudiniEngineVersionFlag "-hev"
#define kHoudiniEngineVersionFlagLong "-houdiniEngineVersion"
#define kSaveHIPFlag "-sh"
#define kSaveHIPFlagLong "-saveHIP"
const char* EngineCommand::commandName = "houdiniEngine";
class EngineSubCommandSaveHIPFile : public SubCommand
{
public:
EngineSubCommandSaveHIPFile(const MString &hipFilePath) :
myHIPFilePath(hipFilePath)
{
}
virtual MStatus doIt()
{
HAPI_SaveHIPFile(myHIPFilePath.asChar());
return MStatus::kSuccess;
}
protected:
MString myHIPFilePath;
};
class EngineSubCommandHoudiniVersion : public SubCommand
{
public:
virtual MStatus doIt()
{
int major, minor, build;
HAPI_GetEnvInt(HAPI_ENVINT_VERSION_HOUDINI_MAJOR, &major);
HAPI_GetEnvInt(HAPI_ENVINT_VERSION_HOUDINI_MINOR, &minor);
HAPI_GetEnvInt(HAPI_ENVINT_VERSION_HOUDINI_BUILD, &build);
MString version_string;
version_string.format(
"^1s.^2s.^3s",
MString() + major,
MString() + minor,
MString() + build
);
MPxCommand::setResult(version_string);
return MStatus::kSuccess;
}
};
class EngineSubCommandHoudiniEngineVersion : public SubCommand
{
public:
virtual MStatus doIt()
{
int major, minor, api;
HAPI_GetEnvInt(HAPI_ENVINT_VERSION_HOUDINI_ENGINE_MAJOR, &major);
HAPI_GetEnvInt(HAPI_ENVINT_VERSION_HOUDINI_ENGINE_MINOR, &minor);
HAPI_GetEnvInt(HAPI_ENVINT_VERSION_HOUDINI_ENGINE_API, &api);
MString version_string;
version_string.format(
"^1s.^2s (API: ^3s)",
MString() + major,
MString() + minor,
MString() + api
);
MPxCommand::setResult(version_string);
return MStatus::kSuccess;
}
};
void* EngineCommand::creator()
{
return new EngineCommand();
}
MSyntax
EngineCommand::newSyntax()
{
MSyntax syntax;
// -license returns the Houdini version that's being used.
CHECK_MSTATUS(syntax.addFlag(kLicenseFlag, kLicenseFlagLong));
// -houdiniVersion returns the Houdini version that's being used.
CHECK_MSTATUS(syntax.addFlag(kHoudiniVersionFlag, kHoudiniVersionFlagLong));
// -houdiniVersion returns the Houdini version that's being used.
CHECK_MSTATUS(syntax.addFlag(kHoudiniEngineVersionFlag, kHoudiniEngineVersionFlagLong));
// -saveHIP saves the contents of the current Houdini scene as a hip file
// expected arguments: hip_file_name - the name of the hip file to save
CHECK_MSTATUS(syntax.addFlag(kSaveHIPFlag, kSaveHIPFlagLong, MSyntax::kString));
return syntax;
}
EngineCommand::EngineCommand() :
mySubCommand(NULL)
{
}
EngineCommand::~EngineCommand()
{
delete mySubCommand;
}
MStatus
EngineCommand::parseArgs(const MArgList &args)
{
MStatus status;
MArgDatabase argData(syntax(), args, &status);
if(!status)
{
return status;
}
if(!(
argData.isFlagSet(kHoudiniVersionFlag)
^ argData.isFlagSet(kHoudiniEngineVersionFlag)
^ argData.isFlagSet(kSaveHIPFlag)
))
{
displayError("Exactly one of these flags must be specified:\n"
kSaveHIPFlagLong "\n"
);
return MStatus::kInvalidParameter;
}
if(argData.isFlagSet(kHoudiniVersionFlag))
{
mySubCommand = new EngineSubCommandHoudiniVersion();
}
if(argData.isFlagSet(kHoudiniEngineVersionFlag))
{
mySubCommand = new EngineSubCommandHoudiniEngineVersion();
}
if(argData.isFlagSet(kSaveHIPFlag))
{
MString hipFilePath;
{
status = argData.getFlagArgument(kSaveHIPFlag, 0, hipFilePath);
if(!status)
{
displayError("Invalid argument for \"" kSaveHIPFlagLong "\".");
return status;
}
}
mySubCommand = new EngineSubCommandSaveHIPFile(hipFilePath);
}
return MStatus::kSuccess;
}
MStatus EngineCommand::doIt(const MArgList& args)
{
MStatus status;
status = parseArgs(args);
if(!status)
{
return status;
}
return mySubCommand->doIt();
}
MStatus EngineCommand::redoIt()
{
return mySubCommand->redoIt();
}
MStatus EngineCommand::undoIt()
{
return mySubCommand->undoIt();
}
bool EngineCommand::isUndoable() const
{
return mySubCommand->isUndoable();
}
|
#include "EngineCommand.h"
#include <maya/MArgDatabase.h>
#include <maya/MArgList.h>
#include <maya/MStatus.h>
#include <HAPI/HAPI.h>
#include "SubCommand.h"
#define kLicenseFlag "-lic"
#define kLicenseFlagLong "-license"
#define kHoudiniVersionFlag "-hv"
#define kHoudiniVersionFlagLong "-houdiniVersion"
#define kHoudiniEngineVersionFlag "-hev"
#define kHoudiniEngineVersionFlagLong "-houdiniEngineVersion"
#define kSaveHIPFlag "-sh"
#define kSaveHIPFlagLong "-saveHIP"
const char* EngineCommand::commandName = "houdiniEngine";
class EngineSubCommandLicense : public SubCommand
{
public:
virtual MStatus doIt()
{
int license;
HAPI_GetEnvInt(HAPI_ENVINT_LICENSE, &license);
MString version_string;
switch(license)
{
case HAPI_LICENSE_NONE:
version_string = "none";
break;
case HAPI_LICENSE_HOUDINI_ENGINE:
version_string = "Houdini-Engine";
break;
case HAPI_LICENSE_HOUDINI:
version_string = "Houdini-Escape";
break;
case HAPI_LICENSE_HOUDINI_FX:
version_string = "Houdini-Master";
break;
case HAPI_LICENSE_HOUDINI_ENGINE_INDIE:
version_string = "Houdini-Engine-Indie";
break;
case HAPI_LICENSE_HOUDINI_INDIE:
version_string = "Houdini-Indie";
break;
default:
version_string = "Unknown";
break;
}
MPxCommand::setResult(version_string);
return MStatus::kSuccess;
}
};
class EngineSubCommandSaveHIPFile : public SubCommand
{
public:
EngineSubCommandSaveHIPFile(const MString &hipFilePath) :
myHIPFilePath(hipFilePath)
{
}
virtual MStatus doIt()
{
HAPI_SaveHIPFile(myHIPFilePath.asChar());
return MStatus::kSuccess;
}
protected:
MString myHIPFilePath;
};
class EngineSubCommandHoudiniVersion : public SubCommand
{
public:
virtual MStatus doIt()
{
int major, minor, build;
HAPI_GetEnvInt(HAPI_ENVINT_VERSION_HOUDINI_MAJOR, &major);
HAPI_GetEnvInt(HAPI_ENVINT_VERSION_HOUDINI_MINOR, &minor);
HAPI_GetEnvInt(HAPI_ENVINT_VERSION_HOUDINI_BUILD, &build);
MString version_string;
version_string.format(
"^1s.^2s.^3s",
MString() + major,
MString() + minor,
MString() + build
);
MPxCommand::setResult(version_string);
return MStatus::kSuccess;
}
};
class EngineSubCommandHoudiniEngineVersion : public SubCommand
{
public:
virtual MStatus doIt()
{
int major, minor, api;
HAPI_GetEnvInt(HAPI_ENVINT_VERSION_HOUDINI_ENGINE_MAJOR, &major);
HAPI_GetEnvInt(HAPI_ENVINT_VERSION_HOUDINI_ENGINE_MINOR, &minor);
HAPI_GetEnvInt(HAPI_ENVINT_VERSION_HOUDINI_ENGINE_API, &api);
MString version_string;
version_string.format(
"^1s.^2s (API: ^3s)",
MString() + major,
MString() + minor,
MString() + api
);
MPxCommand::setResult(version_string);
return MStatus::kSuccess;
}
};
void* EngineCommand::creator()
{
return new EngineCommand();
}
MSyntax
EngineCommand::newSyntax()
{
MSyntax syntax;
// -license returns the Houdini version that's being used.
CHECK_MSTATUS(syntax.addFlag(kLicenseFlag, kLicenseFlagLong));
// -houdiniVersion returns the Houdini version that's being used.
CHECK_MSTATUS(syntax.addFlag(kHoudiniVersionFlag, kHoudiniVersionFlagLong));
// -houdiniVersion returns the Houdini version that's being used.
CHECK_MSTATUS(syntax.addFlag(kHoudiniEngineVersionFlag, kHoudiniEngineVersionFlagLong));
// -saveHIP saves the contents of the current Houdini scene as a hip file
// expected arguments: hip_file_name - the name of the hip file to save
CHECK_MSTATUS(syntax.addFlag(kSaveHIPFlag, kSaveHIPFlagLong, MSyntax::kString));
return syntax;
}
EngineCommand::EngineCommand() :
mySubCommand(NULL)
{
}
EngineCommand::~EngineCommand()
{
delete mySubCommand;
}
MStatus
EngineCommand::parseArgs(const MArgList &args)
{
MStatus status;
MArgDatabase argData(syntax(), args, &status);
if(!status)
{
return status;
}
if(!(
argData.isFlagSet(kLicenseFlag)
^ argData.isFlagSet(kHoudiniVersionFlag)
^ argData.isFlagSet(kHoudiniEngineVersionFlag)
^ argData.isFlagSet(kSaveHIPFlag)
))
{
displayError("Exactly one of these flags must be specified:\n"
kSaveHIPFlagLong "\n"
);
return MStatus::kInvalidParameter;
}
if(argData.isFlagSet(kLicenseFlag))
{
mySubCommand = new EngineSubCommandLicense();
}
if(argData.isFlagSet(kHoudiniVersionFlag))
{
mySubCommand = new EngineSubCommandHoudiniVersion();
}
if(argData.isFlagSet(kHoudiniEngineVersionFlag))
{
mySubCommand = new EngineSubCommandHoudiniEngineVersion();
}
if(argData.isFlagSet(kSaveHIPFlag))
{
MString hipFilePath;
{
status = argData.getFlagArgument(kSaveHIPFlag, 0, hipFilePath);
if(!status)
{
displayError("Invalid argument for \"" kSaveHIPFlagLong "\".");
return status;
}
}
mySubCommand = new EngineSubCommandSaveHIPFile(hipFilePath);
}
return MStatus::kSuccess;
}
MStatus EngineCommand::doIt(const MArgList& args)
{
MStatus status;
status = parseArgs(args);
if(!status)
{
return status;
}
return mySubCommand->doIt();
}
MStatus EngineCommand::redoIt()
{
return mySubCommand->redoIt();
}
MStatus EngineCommand::undoIt()
{
return mySubCommand->undoIt();
}
bool EngineCommand::isUndoable() const
{
return mySubCommand->isUndoable();
}
|
Add "houdiniEngine -license" to get the license type
|
Add "houdiniEngine -license" to get the license type
|
C++
|
mit
|
sonictk/HoudiniEngineForMaya,sonictk/HoudiniEngineForMaya,sonictk/HoudiniEngineForMaya
|
d3c15b862b88feb8aed500fa9bc91b1b02023b69
|
speed.cpp
|
speed.cpp
|
#include <cstring>
#include <set>
#include <chrono>
// --------------------------------------------------
#include "config.h"
#include "popcnt-all.cpp"
#include "function_registry.cpp"
// --------------------------------------------------
class Error final {
std::string message;
public:
Error(const std::string& msg) : message(msg) {}
public:
const char* c_str() const {
return message.c_str();
}
};
// --------------------------------------------------
class CommandLine final {
public:
bool print_help;
bool print_csv;
size_t size;
size_t iteration_count;
std::string executable;
std::set<std::string> functions;
public:
CommandLine(int argc, char* argv[], const FunctionRegistry& names);
};
// --------------------------------------------------
CommandLine::CommandLine(int argc, char* argv[], const FunctionRegistry& names)
: print_help(false)
, print_csv(false)
, size(0)
, iteration_count(0) {
int positional = 0;
for (int i=1; i < argc; i++) {
const std::string arg = argv[i];
if (arg == "--help" || arg == "-h") {
print_help = true;
return;
}
if (arg == "--csv") {
print_csv = true;
continue;
}
// positional arguments
if (positional == 0) {
int tmp = std::atoi(arg.c_str());
if (tmp <= 0) {
throw Error("Size must be greater than 0.");
}
if (tmp % 32 != 0) {
throw Error("Size must be divisible by 32.");
}
size = tmp;
} else if (positional == 1) {
int tmp = std::atoi(arg.c_str());
if (tmp <= 0) {
throw Error("Iteration count must be greater than 0.");
}
iteration_count = tmp;
} else {
if (names.has(arg)) {
functions.insert(std::move(arg));
} else {
throw Error("'" + arg + "' is not valid function name");
}
}
positional += 1;
}
if (positional < 2) {
print_help = true;
}
}
// --------------------------------------------------
class Application final {
const CommandLine& cmd;
const FunctionRegistry& names;
uint8_t* data;
uint64_t count;
double time;
struct Result {
uint64_t count;
double time;
};
public:
Application(const CommandLine& cmdline, const FunctionRegistry& names);
~Application();
int run();
private:
void print_help();
void run_procedures();
void run_procedure(const std::string& name);
template <typename FN>
Result run(const std::string& name, FN function, double reference);
};
Application::Application(const CommandLine& cmdline, const FunctionRegistry& names)
: cmd(cmdline)
, names(names)
, data(nullptr) {}
int Application::run() {
if (cmd.print_help) {
print_help();
} else {
run_procedures();
}
return 0;
}
void Application::run_procedures() {
// GCC parses alignof(), but does not implement it...
int result = posix_memalign(reinterpret_cast<void**>(&data), 64, cmd.size);
if (result) {
throw Error(std::string("posix_memalign failed: ") + strerror(result));
}
for (size_t i=0; i < cmd.size; i++) {
data[i] = i;
}
count = 0;
time = 0;
if (!cmd.functions.empty()) {
for (const auto& name: cmd.functions) {
run_procedure(name);
}
} else {
for (const auto& name: names.get_available()) {
run_procedure(name);
}
}
}
Application::~Application() {
free(data);
}
void Application::run_procedure(const std::string& name) {
#define RUN(function_name, function) \
if (name == function_name) { \
auto result = run(name, function, time); \
count += result.count; \
if (time == 0.0) { \
time = result.time; \
} \
}
RUN("lookup-8", popcnt_lookup_8bit)
RUN("lookup-64", popcnt_lookup_64bit);
RUN("bit-parallel", popcnt_parallel_64bit_naive);
RUN("bit-parallel-optimized", popcnt_parallel_64bit_optimized);
RUN("bit-parallel-mul", popcnt_parallel_64bit_mul);
RUN("bit-parallel32", popcnt_parallel_32bit_naive);
RUN("bit-parallel-optimized32", popcnt_parallel_32bit_optimized);
RUN("harley-seal", popcnt_harley_seal);
#if defined(HAVE_SSE_INSTRUCTIONS)
RUN("sse-bit-parallel", popcnt_SSE_bit_parallel);
RUN("sse-bit-parallel-original", popcnt_SSE_bit_parallel_original);
RUN("sse-bit-parallel-better", popcnt_SSE_bit_parallel_better);
RUN("sse-harley-seal", popcnt_SSE_harley_seal);
RUN("sse-lookup", popcnt_SSE_lookup);
RUN("sse-lookup-original", popcnt_SSE_lookup_original);
RUN("sse-cpu", popcnt_SSE_and_cpu);
#endif
#if defined(HAVE_AVX2_INSTRUCTIONS)
RUN("avx2-lookup", popcnt_AVX2_lookup);
RUN("avx2-lookup-original", popcnt_AVX2_lookup_original);
RUN("avx2-harley-seal", popcnt_AVX2_harley_seal);
RUN("avx2-cpu", popcnt_AVX2_and_cpu);
#endif
#if defined(HAVE_AVX512BW_INSTRUCTIONS)
RUN("avx512-harley-seal", popcnt_AVX512_harley_seal);
#endif
#if defined(HAVE_POPCNT_INSTRUCTION)
RUN("cpu", popcnt_cpu_64bit);
#endif
#if defined(HAVE_NEON_INSTRUCTIONS)
RUN("neon-vcnt", popcnt_neon_vcnt);
RUN("neon-HS", popcnt_neon_harley_seal);
#endif
#if defined(HAVE_AARCH64_ARCHITECTURE)
RUN("aarch64-cnt", popcnt_aarch64_cnt);
#endif
#define RUN_BUILTIN(function_name, function) \
{ \
auto wrapper = [](const uint8_t* data, size_t size) { \
return function(reinterpret_cast<const uint64_t*>(data), size/8); \
}; \
RUN(function_name, wrapper); \
}
RUN_BUILTIN("builtin-popcnt", builtin_popcnt);
RUN_BUILTIN("builtin-popcnt32", builtin_popcnt32);
RUN_BUILTIN("builtin-popcnt-unrolled", builtin_popcnt_unrolled);
RUN_BUILTIN("builtin-popcnt-unrolled32", builtin_popcnt_unrolled32);
#if defined(HAVE_POPCNT_INSTRUCTION)
RUN_BUILTIN("builtin-popcnt-unrolled-errata", builtin_popcnt_unrolled_errata);
RUN_BUILTIN("builtin-popcnt-unrolled-errata-manual", builtin_popcnt_unrolled_errata_manual);
RUN_BUILTIN("builtin-popcnt-movdq", builtin_popcnt_movdq);
RUN_BUILTIN("builtin-popcnt-movdq-unrolled", builtin_popcnt_movdq_unrolled);
RUN_BUILTIN("builtin-popcnt-movdq-unrolled_manual", builtin_popcnt_movdq_unrolled_manual);
#endif
}
template <typename FN>
Application::Result Application::run(const std::string& name, FN function, double reference) {
Result result;
if (cmd.print_csv) {
printf("%s, %lu, %lu, ", name.c_str(), cmd.size, cmd.iteration_count);
fflush(stdout);
} else {
const auto& dsc = names.get(name);
printf("%*s ... ", -names.get_widest_name(), dsc.name.c_str());
fflush(stdout);
}
size_t n = 0;
size_t k = cmd.iteration_count;
const auto t1 = std::chrono::high_resolution_clock::now();
while (k-- > 0) {
n += function(data, cmd.size);
}
const auto t2 = std::chrono::high_resolution_clock::now();
const std::chrono::duration<double> td = t2-t1;
if (cmd.print_csv) {
printf("%0.6f\n", td.count());
} else {
//printf("reference result = %lu, time = %0.6f s", n, td.count());
printf("time = %0.6f s", td.count());
if (reference > 0.0) {
const auto speedup = reference/td.count();
printf(" (speedup: %3.2f)", speedup);
}
putchar('\n');
}
result.count = n; // to prevent compiler from optimizing out the loop
result.time = td.count();
return result;
}
void Application::print_help() {
std::printf("usage: %s [--csv] buffer_size iteration_count [function(s)]\n", cmd.executable.c_str());
std::puts("");
std::puts("--csv - print results in CVS format:");
std::puts(" function name, buffer_size, iteration_count, time");
std::puts("");
std::puts("1. buffer_size - size of buffer in bytes");
std::puts("2. iteration_count - as the name states");
std::puts("3. one or more functions (if not given all will run):");
const int w = names.get_widest_name();
for (const auto& item: names.get_functions()) {
std::printf(" * %*s - %s\n", -w, item.name.c_str(), item.help.c_str());
}
}
int main(int argc, char* argv[]) {
try {
FunctionRegistry names;
CommandLine cmd(argc, argv, names);
Application app(cmd, names);
return app.run();
} catch (Error& e) {
puts(e.c_str());
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
#include <cstring>
#include <set>
#include <chrono>
// --------------------------------------------------
#include "config.h"
#include "popcnt-all.cpp"
#include "function_registry.cpp"
// --------------------------------------------------
class Error final {
std::string message;
public:
Error(const std::string& msg) : message(msg) {}
public:
const char* c_str() const {
return message.c_str();
}
};
// --------------------------------------------------
class CommandLine final {
public:
bool print_help;
bool print_csv;
size_t size;
size_t iteration_count;
std::string executable;
std::set<std::string> functions;
public:
CommandLine(int argc, char* argv[], const FunctionRegistry& names);
};
// --------------------------------------------------
CommandLine::CommandLine(int argc, char* argv[], const FunctionRegistry& names)
: print_help(false)
, print_csv(false)
, size(0)
, iteration_count(0) {
int positional = 0;
for (int i=1; i < argc; i++) {
const std::string arg = argv[i];
if (arg == "--help" || arg == "-h") {
print_help = true;
return;
}
if (arg == "--csv") {
print_csv = true;
continue;
}
// positional arguments
if (positional == 0) {
int tmp = std::atoi(arg.c_str());
if (tmp <= 0) {
throw Error("Size must be greater than 0.");
}
if (tmp % 32 != 0) {
throw Error("Size must be divisible by 32.");
}
size = tmp;
} else if (positional == 1) {
int tmp = std::atoi(arg.c_str());
if (tmp <= 0) {
throw Error("Iteration count must be greater than 0.");
}
iteration_count = tmp;
} else {
if (names.has(arg)) {
functions.insert(std::move(arg));
} else {
throw Error("'" + arg + "' is not valid function name");
}
}
positional += 1;
}
if (positional < 2) {
print_help = true;
}
}
// --------------------------------------------------
class Application final {
const CommandLine& cmd;
const FunctionRegistry& names;
uint8_t* data;
uint64_t count;
double time;
struct Result {
uint64_t count;
double time;
};
public:
Application(const CommandLine& cmdline, const FunctionRegistry& names);
~Application();
int run();
private:
void print_help();
void run_procedures();
void run_procedure(const std::string& name);
template <typename FN>
Result run(const std::string& name, FN function, double reference);
};
Application::Application(const CommandLine& cmdline, const FunctionRegistry& names)
: cmd(cmdline)
, names(names)
, data(nullptr) {}
int Application::run() {
if (cmd.print_help) {
print_help();
} else {
run_procedures();
}
return 0;
}
void Application::run_procedures() {
// GCC parses alignof(), but does not implement it...
int result = posix_memalign(reinterpret_cast<void**>(&data), 64, cmd.size);
if (result) {
throw Error(std::string("posix_memalign failed: ") + strerror(result));
}
for (size_t i=0; i < cmd.size; i++) {
data[i] = i;
}
count = 0;
time = 0;
if (!cmd.functions.empty()) {
for (const auto& name: cmd.functions) {
run_procedure(name);
}
} else {
for (const auto& name: names.get_available()) {
run_procedure(name);
}
}
}
Application::~Application() {
free(data);
}
void Application::run_procedure(const std::string& name) {
#define RUN(function_name, function) \
if (name == function_name) { \
auto result = run(name, function, time); \
count += result.count; \
if (time == 0.0) { \
time = result.time; \
} \
}
RUN("lookup-8", popcnt_lookup_8bit)
RUN("lookup-64", popcnt_lookup_64bit);
RUN("bit-parallel", popcnt_parallel_64bit_naive);
RUN("bit-parallel-optimized", popcnt_parallel_64bit_optimized);
RUN("bit-parallel-mul", popcnt_parallel_64bit_mul);
RUN("bit-parallel32", popcnt_parallel_32bit_naive);
RUN("bit-parallel-optimized32", popcnt_parallel_32bit_optimized);
RUN("harley-seal", popcnt_harley_seal);
#if defined(HAVE_SSE_INSTRUCTIONS)
RUN("sse-bit-parallel", popcnt_SSE_bit_parallel);
RUN("sse-bit-parallel-original", popcnt_SSE_bit_parallel_original);
RUN("sse-bit-parallel-better", popcnt_SSE_bit_parallel_better);
RUN("sse-harley-seal", popcnt_SSE_harley_seal);
RUN("sse-lookup", popcnt_SSE_lookup);
RUN("sse-lookup-original", popcnt_SSE_lookup_original);
RUN("sse-cpu", popcnt_SSE_and_cpu);
#endif
#if defined(HAVE_AVX2_INSTRUCTIONS)
RUN("avx2-lookup", popcnt_AVX2_lookup);
RUN("avx2-lookup-original", popcnt_AVX2_lookup_original);
RUN("avx2-harley-seal", popcnt_AVX2_harley_seal);
RUN("avx2-cpu", popcnt_AVX2_and_cpu);
#endif
#if defined(HAVE_AVX512BW_INSTRUCTIONS)
RUN("avx512-harley-seal", popcnt_AVX512_harley_seal);
RUN("avx512bw-shuf", popcnt_AVX512BW_lookup_original);
#endif
#if defined(HAVE_POPCNT_INSTRUCTION)
RUN("cpu", popcnt_cpu_64bit);
#endif
#if defined(HAVE_NEON_INSTRUCTIONS)
RUN("neon-vcnt", popcnt_neon_vcnt);
RUN("neon-HS", popcnt_neon_harley_seal);
#endif
#if defined(HAVE_AARCH64_ARCHITECTURE)
RUN("aarch64-cnt", popcnt_aarch64_cnt);
#endif
#define RUN_BUILTIN(function_name, function) \
{ \
auto wrapper = [](const uint8_t* data, size_t size) { \
return function(reinterpret_cast<const uint64_t*>(data), size/8); \
}; \
RUN(function_name, wrapper); \
}
RUN_BUILTIN("builtin-popcnt", builtin_popcnt);
RUN_BUILTIN("builtin-popcnt32", builtin_popcnt32);
RUN_BUILTIN("builtin-popcnt-unrolled", builtin_popcnt_unrolled);
RUN_BUILTIN("builtin-popcnt-unrolled32", builtin_popcnt_unrolled32);
#if defined(HAVE_POPCNT_INSTRUCTION)
RUN_BUILTIN("builtin-popcnt-unrolled-errata", builtin_popcnt_unrolled_errata);
RUN_BUILTIN("builtin-popcnt-unrolled-errata-manual", builtin_popcnt_unrolled_errata_manual);
RUN_BUILTIN("builtin-popcnt-movdq", builtin_popcnt_movdq);
RUN_BUILTIN("builtin-popcnt-movdq-unrolled", builtin_popcnt_movdq_unrolled);
RUN_BUILTIN("builtin-popcnt-movdq-unrolled_manual", builtin_popcnt_movdq_unrolled_manual);
#endif
}
template <typename FN>
Application::Result Application::run(const std::string& name, FN function, double reference) {
Result result;
if (cmd.print_csv) {
printf("%s, %lu, %lu, ", name.c_str(), cmd.size, cmd.iteration_count);
fflush(stdout);
} else {
const auto& dsc = names.get(name);
printf("%*s ... ", -names.get_widest_name(), dsc.name.c_str());
fflush(stdout);
}
size_t n = 0;
size_t k = cmd.iteration_count;
const auto t1 = std::chrono::high_resolution_clock::now();
while (k-- > 0) {
n += function(data, cmd.size);
}
const auto t2 = std::chrono::high_resolution_clock::now();
const std::chrono::duration<double> td = t2-t1;
if (cmd.print_csv) {
printf("%0.6f\n", td.count());
} else {
//printf("reference result = %lu, time = %0.6f s", n, td.count());
printf("time = %0.6f s", td.count());
if (reference > 0.0) {
const auto speedup = reference/td.count();
printf(" (speedup: %3.2f)", speedup);
}
putchar('\n');
}
result.count = n; // to prevent compiler from optimizing out the loop
result.time = td.count();
return result;
}
void Application::print_help() {
std::printf("usage: %s [--csv] buffer_size iteration_count [function(s)]\n", cmd.executable.c_str());
std::puts("");
std::puts("--csv - print results in CVS format:");
std::puts(" function name, buffer_size, iteration_count, time");
std::puts("");
std::puts("1. buffer_size - size of buffer in bytes");
std::puts("2. iteration_count - as the name states");
std::puts("3. one or more functions (if not given all will run):");
const int w = names.get_widest_name();
for (const auto& item: names.get_functions()) {
std::printf(" * %*s - %s\n", -w, item.name.c_str(), item.help.c_str());
}
}
int main(int argc, char* argv[]) {
try {
FunctionRegistry names;
CommandLine cmd(argc, argv, names);
Application app(cmd, names);
return app.run();
} catch (Error& e) {
puts(e.c_str());
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
enable performance testing of the new function
|
enable performance testing of the new function
|
C++
|
bsd-2-clause
|
WojciechMula/sse-popcount,WojciechMula/sse-popcount,WojciechMula/sse-popcount,WojciechMula/sse-popcount
|
d79cbb7fe5ae80969a9d3f1026510c5bab740dce
|
FTDebouncer.cpp
|
FTDebouncer.cpp
|
/*
* @Author: Ubi de Feo | Future Tailors
* @Date: 2017-07-09 16:34:07
* @Last Modified by: ubi
* @Last Modified time: 2017-07-09 16:41:17
*/
#include "FTDebouncer.h"
/* CONSTRUCTORS/DESTRUCTOR */
FTDebouncer::FTDebouncer() {
FTDebouncer(40);
}
FTDebouncer::FTDebouncer(uint16_t debounceDelay) : _debounceDelay(debounceDelay) {
_firstDebounceItem = _lastDebounceItem = nullptr;
}
FTDebouncer::~FTDebouncer() {
}
/* METHODS */
void FTDebouncer::addPin(uint8_t pinNr, uint8_t restState) {
this->addPin(pinNr, restState, PinMode::Input);
}
void FTDebouncer::addPin(uint8_t pinNr, uint8_t restState, PinMode pullUpMode) {
DebounceItem *debounceItem = new DebounceItem();
debounceItem->pinNumber = pinNr;
debounceItem->restState = restState;
if (_firstDebounceItem == nullptr) {
_firstDebounceItem = debounceItem;
} else {
_lastDebounceItem->nextItem = debounceItem;
}
_lastDebounceItem = debounceItem;
pinMode(pinNr, static_cast<uint8_t>(pullUpMode));
_debouncedItemsCount++;
}
void FTDebouncer::init() {
unsigned long currentMilliseconds = millis();
DebounceItem *debounceItem = _firstDebounceItem;
while (debounceItem != nullptr) {
debounceItem->lastTimeChecked = currentMilliseconds;
debounceItem->currentState = debounceItem->previousState = debounceItem->restState;
debounceItem->currentDebouncedState = debounceItem->previousDebouncedState = debounceItem->restState;
debounceItem = debounceItem->nextItem;
}
}
void FTDebouncer::run() {
DebounceItem *debounceItem = _firstDebounceItem;
while (debounceItem != nullptr) {
debounceItem->currentState = digitalRead(debounceItem->pinNumber);
debounceItem = debounceItem->nextItem;
}
this->debouncePins();
this->checkStateChange();
}
void FTDebouncer::debouncePins() {
unsigned long currentMilliseconds = millis();
DebounceItem *debounceItem = _firstDebounceItem;
while (debounceItem != nullptr) {
if (debounceItem->currentState != debounceItem->previousState) {
debounceItem->lastTimeChecked = currentMilliseconds;
}
if (currentMilliseconds - debounceItem->lastTimeChecked > _debounceDelay) {
if (debounceItem->previousState == debounceItem->currentState) {
debounceItem->lastTimeChecked = currentMilliseconds;
debounceItem->currentDebouncedState = debounceItem->currentState;
}
}
debounceItem->previousState = debounceItem->currentState;
debounceItem = debounceItem->nextItem;
}
}
void FTDebouncer::checkStateChange() {
DebounceItem *debounceItem = _firstDebounceItem;
while (debounceItem != nullptr) {
if (debounceItem->previousDebouncedState != debounceItem->currentDebouncedState) {
if (debounceItem->currentDebouncedState == !debounceItem->restState) {
pinActivated(debounceItem->pinNumber);
}
if (debounceItem->currentDebouncedState == debounceItem->restState) {
pinDeactivated(debounceItem->pinNumber);
}
}
debounceItem->previousDebouncedState = debounceItem->currentDebouncedState;
debounceItem = debounceItem->nextItem;
}
}
uint8_t FTDebouncer::getPinCount(){
return _debouncedItemsCount;
}
|
/*
* @Author: Ubi de Feo | Future Tailors
* @Date: 2017-07-09 16:34:07
* @Last Modified by: ubi
* @Last Modified time: 2017-07-09 16:41:17
*/
#include "FTDebouncer.h"
/* CONSTRUCTORS/DESTRUCTOR */
FTDebouncer::FTDebouncer() {
FTDebouncer(40);
}
FTDebouncer::FTDebouncer(uint16_t debounceDelay) : _debounceDelay(debounceDelay) {
_firstDebounceItem = _lastDebounceItem = nullptr;
}
FTDebouncer::~FTDebouncer() {
}
/* METHODS */
void FTDebouncer::addPin(uint8_t pinNr, uint8_t restState) {
this->addPin(pinNr, restState, PinMode::Input);
}
void FTDebouncer::addPin(uint8_t pinNr, uint8_t restState, PinMode pullUpMode) {
DebounceItem *debounceItem = new DebounceItem();
debounceItem->pinNumber = pinNr;
debounceItem->restState = restState;
if (_firstDebounceItem == nullptr) {
_firstDebounceItem = debounceItem;
} else {
_lastDebounceItem->nextItem = debounceItem;
}
_lastDebounceItem = debounceItem;
pinMode(pinNr, static_cast<uint8_t>(pullUpMode));
++_debouncedItemsCount;
}
void FTDebouncer::init() {
unsigned long currentMilliseconds = millis();
DebounceItem *debounceItem = _firstDebounceItem;
while (debounceItem != nullptr) {
debounceItem->lastTimeChecked = currentMilliseconds;
debounceItem->currentState = debounceItem->previousState = debounceItem->restState;
debounceItem->currentDebouncedState = debounceItem->previousDebouncedState = debounceItem->restState;
debounceItem = debounceItem->nextItem;
}
}
void FTDebouncer::run() {
DebounceItem *debounceItem = _firstDebounceItem;
while (debounceItem != nullptr) {
debounceItem->currentState = digitalRead(debounceItem->pinNumber);
debounceItem = debounceItem->nextItem;
}
this->debouncePins();
this->checkStateChange();
}
void FTDebouncer::debouncePins() {
unsigned long currentMilliseconds = millis();
DebounceItem *debounceItem = _firstDebounceItem;
while (debounceItem != nullptr) {
if (debounceItem->currentState != debounceItem->previousState) {
debounceItem->lastTimeChecked = currentMilliseconds;
}
if (currentMilliseconds - debounceItem->lastTimeChecked > _debounceDelay) {
if (debounceItem->previousState == debounceItem->currentState) {
debounceItem->lastTimeChecked = currentMilliseconds;
debounceItem->currentDebouncedState = debounceItem->currentState;
}
}
debounceItem->previousState = debounceItem->currentState;
debounceItem = debounceItem->nextItem;
}
}
void FTDebouncer::checkStateChange() {
DebounceItem *debounceItem = _firstDebounceItem;
while (debounceItem != nullptr) {
if (debounceItem->previousDebouncedState != debounceItem->currentDebouncedState) {
if (debounceItem->currentDebouncedState == !debounceItem->restState) {
pinActivated(debounceItem->pinNumber);
}
if (debounceItem->currentDebouncedState == debounceItem->restState) {
pinDeactivated(debounceItem->pinNumber);
}
}
debounceItem->previousDebouncedState = debounceItem->currentDebouncedState;
debounceItem = debounceItem->nextItem;
}
}
uint8_t FTDebouncer::getPinCount(){
return _debouncedItemsCount;
}
|
Use faster prefixed increment operator
|
Use faster prefixed increment operator
|
C++
|
mit
|
ubidefeo/FTDebouncer
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.