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
4d4afa25daa55b917e6e1454ebcb4b421ec03d8d
prototype2/tools/ReaderPcap.cpp
prototype2/tools/ReaderPcap.cpp
/** Copyright (C) 2016, 2017 European Spallation Source ERIC */ #include <algorithm> #include <arpa/inet.h> #include <cassert> #include <cinttypes> #include <cstring> #include <tools/ReaderPcap.h> #include <netinet/ip.h> #include <netinet/udp.h> #include <fmt/format.h> // GCOVR_EXCL_START // Protocol identifiers const int ETHERTYPE_ARP = 0x0806; #define ETHERTYPE_IPV4 0x0800 #define IPPROTO_UDP 17 // Header and data location specifications #define ETHERTYPE_OFFSET 12 #define ETHERNET_HEADER_SIZE 14 #define IP_HEADR_OFFSET 14 #define IP_HEADER_SIZE 20 #define UDP_HEADER_OFFSET 34 #define UDP_HEADER_SIZE 8 #define UDP_DATA_OFFSET 42 ReaderPcap::ReaderPcap(std::string filename) : FileName(filename) { memset(&Stats, 0, sizeof(struct stats_t)); } ReaderPcap::~ReaderPcap() { if (PcapHandle != NULL ) { pcap_close(PcapHandle); } } int ReaderPcap::open() { char errbuff[PCAP_ERRBUF_SIZE]; PcapHandle = pcap_open_offline(FileName.c_str(), errbuff); if (PcapHandle == NULL) { return -1; } return 0; } int ReaderPcap::validatePacket(struct pcap_pkthdr *header, const unsigned char *data) { Stats.PacketsTotal++; /**< total packets in pcap file */ Stats.BytesTotal += header->len; if (header->len != header->caplen) { Stats.PacketsTruncated++; return 0; } uint16_t type = ntohs(*(uint16_t *)&data[ETHERTYPE_OFFSET]); // printf("packet header len %d, type %x\n", header->len, type); if (type == ETHERTYPE_ARP) { Stats.EtherTypeArp++; } else if (type == ETHERTYPE_IPV4) { Stats.EtherTypeIpv4++; } else { Stats.EtherTypeUnknown++; } if (type != ETHERTYPE_IPV4) { // must be ipv4 return 0; } struct ip *ip = (struct ip *)&data[IP_HEADR_OFFSET]; // IPv4 header length must be 20, ip version 4, ipproto must be UDP if ((ip->ip_hl != 5) or (ip->ip_v != 4) or (ip->ip_p != IPPROTO_UDP)) { Stats.IpProtoUnknown++; return 0; } Stats.IpProtoUDP++; assert(header->len > ETHERNET_HEADER_SIZE + IP_HEADER_SIZE + UDP_HEADER_SIZE); assert(Stats.PacketsTotal == Stats.EtherTypeIpv4 + Stats.EtherTypeArp + Stats.EtherTypeUnknown); assert(Stats.EtherTypeIpv4 == Stats.IpProtoUDP + Stats.IpProtoUnknown); struct udphdr *udp = (struct udphdr *)&data[UDP_HEADER_OFFSET]; #ifndef __FAVOR_BSD // Why is __FAVOR_BSD not defined here? uint16_t UdpLen = htons(udp->len); #else uint16_t UdpLen = htons(udp->uh_ulen); #endif assert(UdpLen >= UDP_HEADER_SIZE); #if 0 printf("UDP Payload, Packet %" PRIu64 ", time: %d:%d seconds, size: %d bytes\n", Stats.PacketsTotal, (int)header->ts.tv_sec, (int)header->ts.tv_usec, (int)header->len); printf("ip src->dest: 0x%08x:%d ->0x%08x:%d\n", ntohl(*(uint32_t*)&ip->ip_src), ntohs(udp->uh_sport), ntohl(*(uint32_t*)&ip->ip_dst), ntohs(udp->uh_dport)); #endif return UdpLen; } int ReaderPcap::read(char *buffer, size_t bufferlen) { if (PcapHandle == nullptr) { return -1; } struct pcap_pkthdr *Header; const unsigned char *Data; int ret = pcap_next_ex(PcapHandle, &Header, &Data); if (ret < 0) { return -1; } int UdpDataLength; if ((UdpDataLength = validatePacket(Header, Data)) <= 0) { return UdpDataLength; } auto DataLength = std::min((size_t)(UdpDataLength - UDP_HEADER_SIZE), bufferlen); std::memcpy(buffer, &Data[UDP_DATA_OFFSET], DataLength); return DataLength; } int ReaderPcap::getStats() { if (PcapHandle == NULL) { return -1; } while (true) { int RetVal; struct pcap_pkthdr *Header; const unsigned char *Data; if ((RetVal = pcap_next_ex(PcapHandle, &Header, &Data)) < 0) { break; } validatePacket(Header, Data); } return 0; } void ReaderPcap::printPacket(unsigned char *data, size_t len) { for (unsigned int i = 0; i < len; i++) { if ((i % 16) == 0 && i != 0) { printf("\n"); } printf("%.2x ", data[i]); } printf("\n"); } void ReaderPcap::printStats() { printf("Total packets %" PRIu64 "\n", Stats.PacketsTotal); printf("Truncated packets %" PRIu64 "\n", Stats.PacketsTruncated); printf("Ethertype IPv4 %" PRIu64 "\n", Stats.EtherTypeIpv4); printf(" ipproto UDP %" PRIu64 "\n", Stats.IpProtoUDP); printf(" ipproto other %" PRIu64 "\n", Stats.IpProtoUnknown); printf("Ethertype unknown %" PRIu64 "\n", Stats.EtherTypeUnknown); printf("Ethertype ARP %" PRIu64 "\n", Stats.EtherTypeArp); printf("Total bytes %" PRIu64 "\n", Stats.BytesTotal); } // GCOVR_EXCL_STOP
/** Copyright (C) 2016, 2017 European Spallation Source ERIC */ #include <algorithm> #include <arpa/inet.h> #include <cassert> #include <cinttypes> #include <cstring> #include <tools/ReaderPcap.h> #include <netinet/ip.h> #include <netinet/udp.h> #include <fmt/format.h> // GCOVR_EXCL_START // Protocol identifiers const int ETHERTYPE_ARP = 0x0806; const int ETHERTYPE_IPV4 = 0x0800; #define IPPROTO_UDP 17 // Header and data location specifications #define ETHERTYPE_OFFSET 12 #define ETHERNET_HEADER_SIZE 14 #define IP_HEADR_OFFSET 14 #define IP_HEADER_SIZE 20 #define UDP_HEADER_OFFSET 34 #define UDP_HEADER_SIZE 8 #define UDP_DATA_OFFSET 42 ReaderPcap::ReaderPcap(std::string filename) : FileName(filename) { memset(&Stats, 0, sizeof(struct stats_t)); } ReaderPcap::~ReaderPcap() { if (PcapHandle != NULL ) { pcap_close(PcapHandle); } } int ReaderPcap::open() { char errbuff[PCAP_ERRBUF_SIZE]; PcapHandle = pcap_open_offline(FileName.c_str(), errbuff); if (PcapHandle == NULL) { return -1; } return 0; } int ReaderPcap::validatePacket(struct pcap_pkthdr *header, const unsigned char *data) { Stats.PacketsTotal++; /**< total packets in pcap file */ Stats.BytesTotal += header->len; if (header->len != header->caplen) { Stats.PacketsTruncated++; return 0; } uint16_t type = ntohs(*(uint16_t *)&data[ETHERTYPE_OFFSET]); // printf("packet header len %d, type %x\n", header->len, type); if (type == ETHERTYPE_ARP) { Stats.EtherTypeArp++; } else if (type == ETHERTYPE_IPV4) { Stats.EtherTypeIpv4++; } else { Stats.EtherTypeUnknown++; } if (type != ETHERTYPE_IPV4) { // must be ipv4 return 0; } struct ip *ip = (struct ip *)&data[IP_HEADR_OFFSET]; // IPv4 header length must be 20, ip version 4, ipproto must be UDP if ((ip->ip_hl != 5) or (ip->ip_v != 4) or (ip->ip_p != IPPROTO_UDP)) { Stats.IpProtoUnknown++; return 0; } Stats.IpProtoUDP++; assert(header->len > ETHERNET_HEADER_SIZE + IP_HEADER_SIZE + UDP_HEADER_SIZE); assert(Stats.PacketsTotal == Stats.EtherTypeIpv4 + Stats.EtherTypeArp + Stats.EtherTypeUnknown); assert(Stats.EtherTypeIpv4 == Stats.IpProtoUDP + Stats.IpProtoUnknown); struct udphdr *udp = (struct udphdr *)&data[UDP_HEADER_OFFSET]; #ifndef __FAVOR_BSD // Why is __FAVOR_BSD not defined here? uint16_t UdpLen = htons(udp->len); #else uint16_t UdpLen = htons(udp->uh_ulen); #endif assert(UdpLen >= UDP_HEADER_SIZE); #if 0 printf("UDP Payload, Packet %" PRIu64 ", time: %d:%d seconds, size: %d bytes\n", Stats.PacketsTotal, (int)header->ts.tv_sec, (int)header->ts.tv_usec, (int)header->len); printf("ip src->dest: 0x%08x:%d ->0x%08x:%d\n", ntohl(*(uint32_t*)&ip->ip_src), ntohs(udp->uh_sport), ntohl(*(uint32_t*)&ip->ip_dst), ntohs(udp->uh_dport)); #endif return UdpLen; } int ReaderPcap::read(char *buffer, size_t bufferlen) { if (PcapHandle == nullptr) { return -1; } struct pcap_pkthdr *Header; const unsigned char *Data; int ret = pcap_next_ex(PcapHandle, &Header, &Data); if (ret < 0) { return -1; } int UdpDataLength; if ((UdpDataLength = validatePacket(Header, Data)) <= 0) { return UdpDataLength; } auto DataLength = std::min((size_t)(UdpDataLength - UDP_HEADER_SIZE), bufferlen); std::memcpy(buffer, &Data[UDP_DATA_OFFSET], DataLength); return DataLength; } int ReaderPcap::getStats() { if (PcapHandle == NULL) { return -1; } while (true) { int RetVal; struct pcap_pkthdr *Header; const unsigned char *Data; if ((RetVal = pcap_next_ex(PcapHandle, &Header, &Data)) < 0) { break; } validatePacket(Header, Data); } return 0; } void ReaderPcap::printPacket(unsigned char *data, size_t len) { for (unsigned int i = 0; i < len; i++) { if ((i % 16) == 0 && i != 0) { printf("\n"); } printf("%.2x ", data[i]); } printf("\n"); } void ReaderPcap::printStats() { printf("Total packets %" PRIu64 "\n", Stats.PacketsTotal); printf("Truncated packets %" PRIu64 "\n", Stats.PacketsTruncated); printf("Ethertype IPv4 %" PRIu64 "\n", Stats.EtherTypeIpv4); printf(" ipproto UDP %" PRIu64 "\n", Stats.IpProtoUDP); printf(" ipproto other %" PRIu64 "\n", Stats.IpProtoUnknown); printf("Ethertype unknown %" PRIu64 "\n", Stats.EtherTypeUnknown); printf("Ethertype ARP %" PRIu64 "\n", Stats.EtherTypeArp); printf("Total bytes %" PRIu64 "\n", Stats.BytesTotal); } // GCOVR_EXCL_STOP
Update prototype2/tools/ReaderPcap.cpp
Update prototype2/tools/ReaderPcap.cpp Co-Authored-By: Jonas Nilsson <[email protected]>
C++
bsd-2-clause
ess-dmsc/event-formation-unit,ess-dmsc/event-formation-unit,ess-dmsc/event-formation-unit,ess-dmsc/event-formation-unit
a76b826e5d257d7b2534d1ec814946ef131c193b
src/istream_later.cxx
src/istream_later.cxx
/* * author: Max Kellermann <[email protected]> */ #include "istream_later.hxx" #include "istream_internal.hxx" #include "istream_forward.hxx" #include "event/defer_event.h" #include "util/Cast.hxx" #include <event.h> struct istream_later { struct istream output; struct istream *input; struct defer_event defer_event; }; static void later_event_callback(int fd gcc_unused, short event gcc_unused, void *ctx) { auto *later = (struct istream_later *)ctx; if (later->input == nullptr) istream_deinit_eof(&later->output); else istream_read(later->input); } static void later_schedule(struct istream_later *later) { defer_event_add(&later->defer_event); } /* * istream handler * */ static void later_input_eof(void *ctx) { auto *later = (struct istream_later *)ctx; later->input = nullptr; later_schedule(later); } static void later_input_abort(GError *error, void *ctx) { auto *later = (struct istream_later *)ctx; defer_event_deinit(&later->defer_event); later->input = nullptr; istream_deinit_abort(&later->output, error); } static constexpr struct istream_handler later_input_handler = { .data = istream_forward_data, .direct = istream_forward_direct, .eof = later_input_eof, .abort = later_input_abort, }; /* * istream implementation * */ static inline struct istream_later * istream_to_later(struct istream *istream) { return &ContainerCast2(*istream, &istream_later::output); } static void istream_later_read(struct istream *istream) { struct istream_later *later = istream_to_later(istream); later_schedule(later); } static void istream_later_close(struct istream *istream) { struct istream_later *later = istream_to_later(istream); defer_event_deinit(&later->defer_event); /* input can only be nullptr during the eof callback delay */ if (later->input != nullptr) istream_close_handler(later->input); istream_deinit(&later->output); } static constexpr struct istream_class istream_later = { .read = istream_later_read, .close = istream_later_close, }; /* * constructor * */ struct istream * istream_later_new(struct pool *pool, struct istream *input) { struct istream_later *later = istream_new_macro(pool, later); assert(input != nullptr); assert(!istream_has_handler(input)); istream_assign_handler(&later->input, input, &later_input_handler, later, 0); defer_event_init(&later->defer_event, later_event_callback, later); return &later->output; }
/* * author: Max Kellermann <[email protected]> */ #include "istream_later.hxx" #include "istream_internal.hxx" #include "istream_forward.hxx" #include "event/defer_event.h" #include "util/Cast.hxx" #include "pool.hxx" #include <event.h> struct istream_later { struct istream output; struct istream *input; struct defer_event defer_event; }; static void later_event_callback(int fd gcc_unused, short event gcc_unused, void *ctx) { auto *later = (struct istream_later *)ctx; if (later->input == nullptr) istream_deinit_eof(&later->output); else istream_read(later->input); } static void later_schedule(struct istream_later *later) { defer_event_add(&later->defer_event); } /* * istream handler * */ static void later_input_eof(void *ctx) { auto *later = (struct istream_later *)ctx; later->input = nullptr; later_schedule(later); } static void later_input_abort(GError *error, void *ctx) { auto *later = (struct istream_later *)ctx; defer_event_deinit(&later->defer_event); later->input = nullptr; istream_deinit_abort(&later->output, error); } static constexpr struct istream_handler later_input_handler = { .data = istream_forward_data, .direct = istream_forward_direct, .eof = later_input_eof, .abort = later_input_abort, }; /* * istream implementation * */ static inline struct istream_later * istream_to_later(struct istream *istream) { return &ContainerCast2(*istream, &istream_later::output); } static void istream_later_read(struct istream *istream) { struct istream_later *later = istream_to_later(istream); later_schedule(later); } static void istream_later_close(struct istream *istream) { struct istream_later *later = istream_to_later(istream); defer_event_deinit(&later->defer_event); /* input can only be nullptr during the eof callback delay */ if (later->input != nullptr) istream_close_handler(later->input); istream_deinit(&later->output); } static constexpr struct istream_class istream_later = { .read = istream_later_read, .close = istream_later_close, }; /* * constructor * */ struct istream * istream_later_new(struct pool *pool, struct istream *input) { assert(input != nullptr); assert(!istream_has_handler(input)); auto later = NewFromPool<struct istream_later>(*pool); istream_init(&later->output, &istream_later, pool); istream_assign_handler(&later->input, input, &later_input_handler, later, 0); defer_event_init(&later->defer_event, later_event_callback, later); return &later->output; }
use NewFromPool()
istream_later: use NewFromPool()
C++
bsd-2-clause
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
1be74eaee862045e2845b28e2c7a9cc9f6c9d223
src/parser/Parser.cpp
src/parser/Parser.cpp
/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs * * Authors: Hugo Beauzée-Luyssen<[email protected]> * * This program 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 program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #if HAVE_CONFIG_H # include "config.h" #endif #include "Parser.h" #include <algorithm> #include "medialibrary/IMediaLibrary.h" #include "Media.h" #include "File.h" #include "ParserService.h" namespace medialibrary { Parser::Parser( MediaLibrary* ml ) : m_ml( ml ) , m_callback( ml->getCb() ) , m_opToDo( 0 ) , m_opDone( 0 ) , m_percent( 0 ) { } Parser::~Parser() { stop(); } void Parser::addService( ServicePtr service ) { service->initialize( m_ml, this ); m_services.push_back( std::move( service ) ); } void Parser::parse( std::shared_ptr<Media> media, std::shared_ptr<File> file ) { if ( m_services.size() == 0 ) return; m_services[0]->parse( std::unique_ptr<parser::Task>( new parser::Task( media, file ) ) ); m_opToDo += m_services.size(); updateStats(); } void Parser::start() { restore(); for ( auto& s : m_services ) s->start(); } void Parser::pause() { for ( auto& s : m_services ) s->pause(); } void Parser::resume() { for ( auto& s : m_services ) s->resume(); } void Parser::stop() { for ( auto& s : m_services ) { s->signalStop(); } for ( auto& s : m_services ) { s->stop(); } } void Parser::restore() { if ( m_services.empty() == true ) return; static const std::string req = "SELECT * FROM " + policy::FileTable::Name + " WHERE parser_step != ? AND is_present = 1"; auto files = File::fetchAll<File>( m_ml, req, File::ParserStep::Completed ); for ( auto& f : files ) { auto m = f->media(); parse( m, f ); } } void Parser::updateStats() { auto percent = m_opToDo > 0 ? ( m_opDone * 100 / m_opToDo ) : 0; if ( percent != m_percent ) { LOG_ERROR( "Parser progress: ", percent, '%' ); m_percent = percent; m_callback->onParsingStatsUpdated( m_percent ); } } void Parser::done( std::unique_ptr<parser::Task> t, parser::Task::Status status ) { ++m_opDone; auto serviceIdx = ++t->currentService; if ( status == parser::Task::Status::TemporaryUnavailable || status == parser::Task::Status::Fatal || t->file->parserStep() == File::ParserStep::Completed ) { if ( serviceIdx < m_services.size() ) { // We won't process the next tasks, so we need to keep the number of "todo" operations coherent: m_opToDo -= m_services.size() - serviceIdx; } updateStats(); return; } // If some services declined to parse the file, start over again. if ( serviceIdx == m_services.size() ) { t->currentService = serviceIdx = 0; m_opToDo += m_services.size(); LOG_INFO("Running parser chain again for ", t->file->mrl()); } updateStats(); m_services[serviceIdx]->parse( std::move( t ) ); } }
/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs * * Authors: Hugo Beauzée-Luyssen<[email protected]> * * This program 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 program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #if HAVE_CONFIG_H # include "config.h" #endif #include "Parser.h" #include <algorithm> #include "medialibrary/IMediaLibrary.h" #include "Media.h" #include "File.h" #include "ParserService.h" namespace medialibrary { Parser::Parser( MediaLibrary* ml ) : m_ml( ml ) , m_callback( ml->getCb() ) , m_opToDo( 0 ) , m_opDone( 0 ) , m_percent( 0 ) { } Parser::~Parser() { stop(); } void Parser::addService( ServicePtr service ) { service->initialize( m_ml, this ); m_services.push_back( std::move( service ) ); } void Parser::parse( std::shared_ptr<Media> media, std::shared_ptr<File> file ) { if ( m_services.size() == 0 ) return; m_services[0]->parse( std::unique_ptr<parser::Task>( new parser::Task( media, file ) ) ); m_opToDo += m_services.size(); updateStats(); } void Parser::start() { restore(); for ( auto& s : m_services ) s->start(); } void Parser::pause() { for ( auto& s : m_services ) s->pause(); } void Parser::resume() { for ( auto& s : m_services ) s->resume(); } void Parser::stop() { for ( auto& s : m_services ) { s->signalStop(); } for ( auto& s : m_services ) { s->stop(); } } void Parser::restore() { if ( m_services.empty() == true ) return; static const std::string req = "SELECT * FROM " + policy::FileTable::Name + " WHERE parser_step != ? AND is_present = 1"; auto files = File::fetchAll<File>( m_ml, req, File::ParserStep::Completed ); for ( auto& f : files ) { auto m = f->media(); parse( m, f ); } } void Parser::updateStats() { auto percent = m_opToDo > 0 ? ( m_opDone * 100 / m_opToDo ) : 0; if ( percent != m_percent ) { m_percent = percent; m_callback->onParsingStatsUpdated( m_percent ); } } void Parser::done( std::unique_ptr<parser::Task> t, parser::Task::Status status ) { ++m_opDone; auto serviceIdx = ++t->currentService; if ( status == parser::Task::Status::TemporaryUnavailable || status == parser::Task::Status::Fatal || t->file->parserStep() == File::ParserStep::Completed ) { if ( serviceIdx < m_services.size() ) { // We won't process the next tasks, so we need to keep the number of "todo" operations coherent: m_opToDo -= m_services.size() - serviceIdx; } updateStats(); return; } // If some services declined to parse the file, start over again. if ( serviceIdx == m_services.size() ) { t->currentService = serviceIdx = 0; m_opToDo += m_services.size(); LOG_INFO("Running parser chain again for ", t->file->mrl()); } updateStats(); m_services[serviceIdx]->parse( std::move( t ) ); } }
Remove leftover debug
Parser: Remove leftover debug
C++
lgpl-2.1
chouquette/medialibrary,chouquette/medialibrary,chouquette/medialibrary,chouquette/medialibrary
8e9f7e7458cf3b853e0c7c031a93102142a20580
src/Tools/Math/Distribution/Distributions.cpp
src/Tools/Math/Distribution/Distributions.cpp
#include <sstream> #include <algorithm> #include <vector> #include <iostream> #include "Tools/Exception/exception.hpp" #include "Tools/Arguments/Splitter/Splitter.hpp" #include "Distributions.hpp" using namespace aff3ct; using namespace tools; template<typename R> Distributions<R>:: Distributions() { } template<typename R> Distributions<R>:: Distributions(std::ifstream& f_distributions) { if (f_distributions.fail()) { std::stringstream message; message << "'f_distributions' file descriptor is not valid: failbit is set."; throw runtime_error(__FILE__, __LINE__, __func__, message.str()); } std::string line; std::getline(f_distributions, line); auto desc = tools::Splitter::split(line, "", "", " "); auto ROP_pos = std::find(desc.begin(), desc.end(), "ROP"); auto x_pos = std::find(desc.begin(), desc.end(), "x" ); auto y0_pos = std::find(desc.begin(), desc.end(), "y0" ); auto y1_pos = std::find(desc.begin(), desc.end(), "y1" ); if (ROP_pos == desc.end()) throw runtime_error(__FILE__, __LINE__, __func__, "No ROP in the description of the distribution"); if (x_pos == desc.end()) throw runtime_error(__FILE__, __LINE__, __func__, "No x in the description of the distribution"); if (y0_pos == desc.end()) throw runtime_error(__FILE__, __LINE__, __func__, "No y0 in the description of the distribution"); if (y1_pos == desc.end()) throw runtime_error(__FILE__, __LINE__, __func__, "No y1 in the description of the distribution"); std::string ROP; std::vector<std::string> v_x ; std::vector<std::string> v_y0; std::vector<std::string> v_y1; while (!f_distributions.eof()) { for (auto it = desc.begin(); it != desc.end(); it++) { if (f_distributions.eof()) break; std::getline(f_distributions, line); if (line.empty()) { it--; continue; } if (it == ROP_pos) ROP = std::move(line); else if (it == x_pos) v_x = std::move(tools::Splitter::split(line, "", "", " ")); else if (it == y0_pos) v_y0 = std::move(tools::Splitter::split(line, "", "", " ")); else if (it == y1_pos) v_y1 = std::move(tools::Splitter::split(line, "", "", " ")); else tools::runtime_error(__FILE__, __LINE__, __func__); } if (f_distributions.eof()) break; if (v_x.size() != v_y0.size() || v_x.size() != v_y1.size() ) { std::stringstream message; message << "'v_x' does not have the same size than 'v_y0' or 'v_y1' " << "('v_x.size()' = " << v_x.size() << ", 'v_y0.size()' = " << v_y0.size() << ", 'v_y1.size()' = " << v_y1.size() << " and 'ROP' = " << ROP << ")."; throw invalid_argument(__FILE__, __LINE__, __func__, message.str()); } try { auto ROP_R = (R)stof(ROP); std::vector<R> v_x_R(v_x.size()) ; std::vector<std::vector<R>> v_y_R(2); for(auto& v : v_y_R) v.resize(v_x.size()); // convert string vector to 'R' vector for(unsigned j = 0; j < v_x_R.size(); j++) { v_x_R [j] = (R)stof(v_x [j]); v_y_R[0][j] = (R)stof(v_y0[j]); v_y_R[1][j] = (R)stof(v_y1[j]); } add_distribution(ROP_R, new Distribution<R>(std::move(v_x_R), std::move(v_y_R))); } catch(...) { std::stringstream message; message << "A value does not represent a float"; throw runtime_error(__FILE__, __LINE__, __func__, message.str()); } } } template<typename R> Distributions<R>:: ~Distributions() { for (auto& d : distributions) if (d.second) delete d.second; } template<typename R> std::vector<R> Distributions<R>:: get_noise_range(std::ifstream& f_distributions) { if (f_distributions.fail()) { std::stringstream message; message << "'f_distributions' file descriptor is not valid: failbit is set."; throw runtime_error(__FILE__, __LINE__, __func__, message.str()); } std::string line; std::getline(f_distributions, line); auto desc = tools::Splitter::split(line, "", "", " "); auto ROP_pos = std::find(desc.begin(), desc.end(), "ROP"); std::vector<R> v_noise; while (!f_distributions.eof()) { for (auto it = desc.begin(); it != desc.end(); it++) { if (f_distributions.eof()) break; std::getline(f_distributions, line); if (line.empty()) { it--; continue; } if (it == ROP_pos) v_noise.push_back((R)stof(line)); } } return v_noise; } template<typename R> const Distribution<R>* const Distributions<R>:: get_distribution(const R noise_power) const { int np = (int)(noise_power*(R)saved_noise_precision); auto it_dis = this->distributions.find(np); if (it_dis == this->distributions.end()) return nullptr; return it_dis->second; } template<typename R> void Distributions<R>:: add_distribution(R noise_power, Distribution<R>* new_distribution) { if (get_distribution(noise_power)) { std::stringstream message; message << "A distribution already exist for the given noise power 'noise_power' ('noise_power' = " << noise_power << ")."; throw invalid_argument(__FILE__, __LINE__, __func__, message.str()); } int np = (int)(noise_power*(R)saved_noise_precision); this->distributions[np] = new_distribution; } // ==================================================================================== explicit template instantiation #include "Tools/types.h" #ifdef MULTI_PREC template class aff3ct::tools::Distributions<R_32>; template class aff3ct::tools::Distributions<R_64>; #else template class aff3ct::tools::Distributions<R>; #endif // ==================================================================================== explicit template instantiation
#include <sstream> #include <algorithm> #include <vector> #include <iostream> #include "Tools/Exception/exception.hpp" #include "Tools/Arguments/Splitter/Splitter.hpp" #include "Distributions.hpp" using namespace aff3ct; using namespace tools; template<typename R> Distributions<R>:: Distributions() { } template<typename R> Distributions<R>:: Distributions(std::ifstream& f_distributions) { if (f_distributions.fail()) { std::stringstream message; message << "'f_distributions' file descriptor is not valid: failbit is set."; throw runtime_error(__FILE__, __LINE__, __func__, message.str()); } std::string line; std::getline(f_distributions, line); auto desc = tools::Splitter::split(line, "", "", " "); auto ROP_pos = std::find(desc.begin(), desc.end(), "ROP"); auto x_pos = std::find(desc.begin(), desc.end(), "x" ); auto y0_pos = std::find(desc.begin(), desc.end(), "y0" ); auto y1_pos = std::find(desc.begin(), desc.end(), "y1" ); if (ROP_pos == desc.end()) throw runtime_error(__FILE__, __LINE__, __func__, "No ROP in the description of the distribution"); if (x_pos == desc.end()) throw runtime_error(__FILE__, __LINE__, __func__, "No x in the description of the distribution"); if (y0_pos == desc.end()) throw runtime_error(__FILE__, __LINE__, __func__, "No y0 in the description of the distribution"); if (y1_pos == desc.end()) throw runtime_error(__FILE__, __LINE__, __func__, "No y1 in the description of the distribution"); std::string ROP; std::vector<std::string> v_x ; std::vector<std::string> v_y0; std::vector<std::string> v_y1; while (!f_distributions.eof()) { for (auto it = desc.begin(); it != desc.end(); it++) { if (f_distributions.eof()) break; std::getline(f_distributions, line); if (line.empty()) { it--; continue; } if (it == ROP_pos) ROP = std::move(line); else if (it == x_pos) v_x = std::move(tools::Splitter::split(line, "", "", " ")); else if (it == y0_pos) v_y0 = std::move(tools::Splitter::split(line, "", "", " ")); else if (it == y1_pos) v_y1 = std::move(tools::Splitter::split(line, "", "", " ")); else tools::runtime_error(__FILE__, __LINE__, __func__); } if (f_distributions.eof()) break; if (v_x.size() != v_y0.size() || v_x.size() != v_y1.size() ) { std::stringstream message; message << "'v_x' does not have the same size than 'v_y0' or 'v_y1' " << "('v_x.size()' = " << v_x.size() << ", 'v_y0.size()' = " << v_y0.size() << ", 'v_y1.size()' = " << v_y1.size() << " and 'ROP' = " << ROP << ")."; throw invalid_argument(__FILE__, __LINE__, __func__, message.str()); } try { auto ROP_R = (R)stof(ROP); std::vector<R> v_x_R(v_x.size()) ; std::vector<std::vector<R>> v_y_R(2); for(auto& v : v_y_R) v.resize(v_x.size()); // convert string vector to 'R' vector for(unsigned j = 0; j < v_x_R.size(); j++) { v_x_R [j] = (R)stof(v_x [j]); v_y_R[0][j] = (R)stof(v_y0[j]); v_y_R[1][j] = (R)stof(v_y1[j]); } add_distribution(ROP_R, new Distribution<R>(std::move(v_x_R), std::move(v_y_R))); } catch(...) { std::stringstream message; message << "A value does not represent a float"; throw runtime_error(__FILE__, __LINE__, __func__, message.str()); } } } template<typename R> Distributions<R>:: ~Distributions() { for (auto& d : distributions) if (d.second) delete d.second; } template<typename R> std::vector<R> Distributions<R>:: get_noise_range(std::ifstream& f_distributions) { if (f_distributions.fail()) { std::stringstream message; message << "'f_distributions' file descriptor is not valid: failbit is set."; throw runtime_error(__FILE__, __LINE__, __func__, message.str()); } std::string line; std::getline(f_distributions, line); auto desc = tools::Splitter::split(line, "", "", " "); auto ROP_pos = std::find(desc.begin(), desc.end(), "ROP"); std::vector<R> v_noise; while (!f_distributions.eof()) { for (auto it = desc.begin(); it != desc.end(); it++) { if (f_distributions.eof()) break; std::getline(f_distributions, line); if (line.empty()) { it--; continue; } if (it == ROP_pos) v_noise.push_back((R)stof(line)); } } std::sort(v_noise.begin(), v_noise.end()); return v_noise; } template<typename R> const Distribution<R>* const Distributions<R>:: get_distribution(const R noise_power) const { int np = (int)(noise_power*(R)saved_noise_precision); auto it_dis = this->distributions.find(np); if (it_dis == this->distributions.end()) return nullptr; return it_dis->second; } template<typename R> void Distributions<R>:: add_distribution(R noise_power, Distribution<R>* new_distribution) { if (get_distribution(noise_power)) { std::stringstream message; message << "A distribution already exist for the given noise power 'noise_power' ('noise_power' = " << noise_power << ")."; throw invalid_argument(__FILE__, __LINE__, __func__, message.str()); } int np = (int)(noise_power*(R)saved_noise_precision); this->distributions[np] = new_distribution; } // ==================================================================================== explicit template instantiation #include "Tools/types.h" #ifdef MULTI_PREC template class aff3ct::tools::Distributions<R_32>; template class aff3ct::tools::Distributions<R_64>; #else template class aff3ct::tools::Distributions<R>; #endif // ==================================================================================== explicit template instantiation
Add a sort after getting the ROP range from file
Add a sort after getting the ROP range from file
C++
mit
aff3ct/aff3ct,aff3ct/aff3ct,aff3ct/aff3ct,aff3ct/aff3ct
ae6614f1cb7c65045681cf8e9448d742834818da
google/cloud/storage/tests/bucket_integration_test.cc
google/cloud/storage/tests/bucket_integration_test.cc
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "google/cloud/storage/client.h" #include "google/cloud/storage/list_objects_reader.h" #include "google/cloud/testing_util/init_google_mock.h" #include <gmock/gmock.h> namespace google { namespace cloud { namespace storage { inline namespace STORAGE_CLIENT_NS { namespace { using ::testing::HasSubstr; /// Store the project and instance captured from the command-line arguments. class BucketTestEnvironment : public ::testing::Environment { public: BucketTestEnvironment(std::string project, std::string instance) { project_id_ = std::move(project); bucket_name_ = std::move(instance); } static std::string const& project_id() { return project_id_; } static std::string const& bucket_name() { return bucket_name_; } private: static std::string project_id_; static std::string bucket_name_; }; std::string BucketTestEnvironment::project_id_; std::string BucketTestEnvironment::bucket_name_; class BucketIntegrationTest : public ::testing::Test { protected: std::string MakeEntityName() { // We always use the viewers for the project because it is known to exist. return "project-viewers-" + BucketTestEnvironment::project_id(); } std::string MakeRandomBucketName() { // The total length of this bucket name must be <= 63 characters, static std::string const prefix = "gcs-cpp-test-bucket"; static std::size_t const kMaxBucketNameLength = 63; std::size_t const max_random_characters = kMaxBucketNameLength - prefix.size(); return prefix + google::cloud::internal::Sample(generator_, max_random_characters, "abcdefghijklmnopqrstuvwxyz" "012456789"); } google::cloud::internal::DefaultPRNG generator_ = google::cloud::internal::MakeDefaultPRNG(); }; TEST_F(BucketIntegrationTest, BasicCRUD) { auto project_id = BucketTestEnvironment::project_id(); std::string bucket_name = MakeRandomBucketName(); Client client; auto buckets = client.ListBucketsForProject(project_id); std::vector<BucketMetadata> initial_buckets(buckets.begin(), buckets.end()); auto name_counter = [](std::string const& name, std::vector<BucketMetadata> const& list) { return std::count_if( list.begin(), list.end(), [name](BucketMetadata const& m) { return m.name() == name; }); }; ASSERT_EQ(0, name_counter(bucket_name, initial_buckets)) << "Test aborted. The bucket <" << bucket_name << "> already exists." << " This is unexpected as the test generates a random bucket name."; auto insert_meta = client.CreateBucketForProject(bucket_name, project_id, BucketMetadata()); EXPECT_EQ(bucket_name, insert_meta.name()); buckets = client.ListBucketsForProject(project_id); std::vector<BucketMetadata> current_buckets(buckets.begin(), buckets.end()); EXPECT_EQ(1U, name_counter(bucket_name, current_buckets)); BucketMetadata get_meta = client.GetBucketMetadata(bucket_name); EXPECT_EQ(insert_meta, get_meta); // Create a request to update the metadata, change the storage class because // it is easy. And use either COLDLINE or NEARLINE depending on the existing // value. std::string desired_storage_class = storage_class::Coldline(); if (get_meta.storage_class() == storage_class::Coldline()) { desired_storage_class = storage_class::Nearline(); } BucketMetadata update = get_meta; update.set_storage_class(desired_storage_class); BucketMetadata updated_meta = client.UpdateBucket(bucket_name, update); EXPECT_EQ(desired_storage_class, updated_meta.storage_class()); client.DeleteBucket(bucket_name); buckets = client.ListBucketsForProject(project_id); current_buckets.assign(buckets.begin(), buckets.end()); EXPECT_EQ(0U, name_counter(bucket_name, current_buckets)); } TEST_F(BucketIntegrationTest, GetMetadata) { auto bucket_name = BucketTestEnvironment::bucket_name(); Client client; auto metadata = client.GetBucketMetadata(bucket_name); EXPECT_EQ(bucket_name, metadata.name()); EXPECT_EQ(bucket_name, metadata.id()); EXPECT_EQ("storage#bucket", metadata.kind()); } TEST_F(BucketIntegrationTest, GetMetadataIfMetaGenerationMatch_Success) { auto bucket_name = BucketTestEnvironment::bucket_name(); Client client; auto metadata = client.GetBucketMetadata(bucket_name); EXPECT_EQ(bucket_name, metadata.name()); EXPECT_EQ(bucket_name, metadata.id()); EXPECT_EQ("storage#bucket", metadata.kind()); auto metadata2 = client.GetBucketMetadata( bucket_name, storage::Projection("noAcl"), storage::IfMetaGenerationMatch(metadata.metageneration())); EXPECT_EQ(metadata2, metadata); } TEST_F(BucketIntegrationTest, GetMetadataIfMetaGenerationNotMatch_Failure) { auto bucket_name = BucketTestEnvironment::bucket_name(); Client client; auto metadata = client.GetBucketMetadata(bucket_name); EXPECT_EQ(bucket_name, metadata.name()); EXPECT_EQ(bucket_name, metadata.id()); EXPECT_EQ("storage#bucket", metadata.kind()); #if GOOGLE_CLOUD_CPP_HAVE_EXCEPTIONS EXPECT_THROW( client.GetBucketMetadata( bucket_name, storage::Projection("noAcl"), storage::IfMetaGenerationNotMatch(metadata.metageneration())), std::exception); #else EXPECT_DEATH_IF_SUPPORTED( client.GetBucketMetadata( bucket_name, storage::Projection("noAcl"), storage::IfMetaGenerationNotMatch(metadata.metageneration())), "exceptions are disabled"); #endif // GOOGLE_CLOUD_CPP_HAVE_EXCEPTIONS } TEST_F(BucketIntegrationTest, InsertObjectMedia) { // TODO(#681) - use random names for the object and buckets in the tests. auto bucket_name = BucketTestEnvironment::bucket_name(); Client client; auto object_name = std::string("the-test-object-") + std::to_string( std::chrono::system_clock::now().time_since_epoch().count()); auto metadata = client.InsertObject(bucket_name, object_name, "blah blah"); EXPECT_EQ(bucket_name, metadata.bucket()); EXPECT_EQ(object_name, metadata.name()); EXPECT_EQ("storage#object", metadata.kind()); } TEST_F(BucketIntegrationTest, InsertObjectMediaIfGenerationMatch) { // TODO(#681) - use random names for the object and buckets in the tests. auto bucket_name = BucketTestEnvironment::bucket_name(); Client client; auto object_name = std::string("the-test-object-") + std::to_string( std::chrono::system_clock::now().time_since_epoch().count()); auto original = client.InsertObject(bucket_name, object_name, "blah blah", storage::IfGenerationMatch(0)); EXPECT_EQ(bucket_name, original.bucket()); EXPECT_EQ(object_name, original.name()); EXPECT_EQ("storage#object", original.kind()); #if GOOGLE_CLOUD_CPP_HAVE_EXCEPTIONS EXPECT_THROW(client.InsertObject(bucket_name, object_name, "blah blah", storage::IfGenerationMatch(0)), std::exception); #else EXPECT_DEATH_IF_SUPPORTED( client.InsertObject(bucket_name, object_name, "blah blah", storage::IfGenerationMatch(0)), "exceptions are disabled"); #endif // GOOGLE_CLOUD_CPP_HAVE_EXCEPTIONS } TEST_F(BucketIntegrationTest, InsertObjectMediaIfGenerationNotMatch) { // TODO(#681) - use random names for the object and buckets in the tests. auto bucket_name = BucketTestEnvironment::bucket_name(); Client client; auto object_name = std::string("the-test-object-") + std::to_string( std::chrono::system_clock::now().time_since_epoch().count()); auto original = client.InsertObject(bucket_name, object_name, "blah blah", storage::IfGenerationMatch(0)); EXPECT_EQ(bucket_name, original.bucket()); EXPECT_EQ(object_name, original.name()); EXPECT_EQ("storage#object", original.kind()); auto metadata = client.InsertObject(bucket_name, object_name, "more blah blah", storage::IfGenerationNotMatch(0)); EXPECT_EQ(object_name, metadata.name()); EXPECT_NE(original.generation(), metadata.generation()); } TEST_F(BucketIntegrationTest, ListObjects) { auto bucket_name = BucketTestEnvironment::bucket_name(); Client client; auto gen = google::cloud::internal::MakeDefaultPRNG(); auto create_small_object = [&client, &bucket_name, &gen] { auto object_name = "object-" + google::cloud::internal::Sample( gen, 16, "abcdefghijklmnopqrstuvwxyz0123456789"); auto meta = client.InsertObject(bucket_name, object_name, "blah blah", storage::IfGenerationMatch(0)); return meta.name(); }; std::vector<std::string> expected(3); std::generate_n(expected.begin(), expected.size(), create_small_object); ListObjectsReader reader = client.ListObjects(bucket_name); std::vector<std::string> actual; for (auto it = reader.begin(); it != reader.end(); ++it) { auto const& meta = *it; EXPECT_EQ(bucket_name, meta.bucket()); actual.push_back(meta.name()); } // There may be a lot of other objects in the bucket, so we want to verify // that any objects we created are found there, but cannot expect a perfect // match. for (auto const& name : expected) { EXPECT_EQ(1, std::count(actual.begin(), actual.end(), name)); } } TEST_F(BucketIntegrationTest, AccessControlCRUD) { Client client; auto bucket_name = BucketTestEnvironment::bucket_name(); auto entity_name = MakeEntityName(); std::vector<BucketAccessControl> initial_acl = client.ListBucketAcl(bucket_name); auto name_counter = [](std::string const& name, std::vector<BucketAccessControl> const& list) { auto name_matcher = [](std::string const& name) { return [name](BucketAccessControl const& m) { return m.entity() == name; }; }; return std::count_if(list.begin(), list.end(), name_matcher(name)); }; // TODO(#827) - handle this more gracefully, delete the entry. Or ... // TODO(#821) TODO(#820) - use a new bucket to simplify this test. EXPECT_EQ(0, name_counter(entity_name, initial_acl)) << "Test aborted (without failure). The entity <" << entity_name << "> already exists, and DeleteBucketAcl() is not implemented."; if (name_counter(entity_name, initial_acl) == 0) { return; } BucketAccessControl result = client.CreateBucketAcl(bucket_name, entity_name, "OWNER"); EXPECT_EQ("OWNER", result.role()); auto current_acl = client.ListBucketAcl(bucket_name); EXPECT_FALSE(current_acl.empty()); // Search using the entity name returned by the request, because we use // 'project-editors-<project_id>' this different than the original entity // name, the server "translates" the project id to a project number. EXPECT_EQ(1, name_counter(result.entity(), current_acl)); // TODO(#827) - delete the new entry to leave the bucket in the original // state. } TEST_F(BucketIntegrationTest, DefaultObjectAccessControlCRUD) { Client client; auto bucket_name = BucketTestEnvironment::bucket_name(); auto entity_name = MakeEntityName(); std::vector<ObjectAccessControl> initial_acl = client.ListDefaultObjectAcl(bucket_name); // TODO(#833) TODO(#835) - make stronger assertions once we can modify the // ACL. EXPECT_FALSE(initial_acl.empty()); } } // namespace } // namespace STORAGE_CLIENT_NS } // namespace storage } // namespace cloud } // namespace google int main(int argc, char* argv[]) { google::cloud::testing_util::InitGoogleMock(argc, argv); // Make sure the arguments are valid. if (argc != 3) { std::string const cmd = argv[0]; auto last_slash = std::string(argv[0]).find_last_of('/'); std::cerr << "Usage: " << cmd.substr(last_slash + 1) << " <project> <bucket>" << std::endl; return 1; } std::string const project_id = argv[1]; std::string const bucket_name = argv[2]; (void)::testing::AddGlobalTestEnvironment( new google::cloud::storage::BucketTestEnvironment(project_id, bucket_name)); return RUN_ALL_TESTS(); }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "google/cloud/storage/client.h" #include "google/cloud/storage/list_objects_reader.h" #include "google/cloud/testing_util/init_google_mock.h" #include <gmock/gmock.h> namespace google { namespace cloud { namespace storage { inline namespace STORAGE_CLIENT_NS { namespace { using ::testing::HasSubstr; /// Store the project and instance captured from the command-line arguments. class BucketTestEnvironment : public ::testing::Environment { public: BucketTestEnvironment(std::string project, std::string instance) { project_id_ = std::move(project); bucket_name_ = std::move(instance); } static std::string const& project_id() { return project_id_; } static std::string const& bucket_name() { return bucket_name_; } private: static std::string project_id_; static std::string bucket_name_; }; std::string BucketTestEnvironment::project_id_; std::string BucketTestEnvironment::bucket_name_; class BucketIntegrationTest : public ::testing::Test { protected: std::string MakeEntityName() { // We always use the viewers for the project because it is known to exist. return "project-viewers-" + BucketTestEnvironment::project_id(); } std::string MakeRandomBucketName() { // The total length of this bucket name must be <= 63 characters, static std::string const prefix = "gcs-cpp-test-bucket"; static std::size_t const kMaxBucketNameLength = 63; std::size_t const max_random_characters = kMaxBucketNameLength - prefix.size(); return prefix + google::cloud::internal::Sample( generator_, static_cast<int>(max_random_characters), "abcdefghijklmnopqrstuvwxyz012456789"); } std::string MakeRandomObjectName() { static std::string const prefix = "bucket-integration-test-"; return prefix + google::cloud::internal::Sample(generator_, 64, "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "012456789"); } google::cloud::internal::DefaultPRNG generator_ = google::cloud::internal::MakeDefaultPRNG(); }; TEST_F(BucketIntegrationTest, BasicCRUD) { auto project_id = BucketTestEnvironment::project_id(); std::string bucket_name = MakeRandomBucketName(); Client client; auto buckets = client.ListBucketsForProject(project_id); std::vector<BucketMetadata> initial_buckets(buckets.begin(), buckets.end()); auto name_counter = [](std::string const& name, std::vector<BucketMetadata> const& list) { return std::count_if( list.begin(), list.end(), [name](BucketMetadata const& m) { return m.name() == name; }); }; ASSERT_EQ(0, name_counter(bucket_name, initial_buckets)) << "Test aborted. The bucket <" << bucket_name << "> already exists." << " This is unexpected as the test generates a random bucket name."; auto insert_meta = client.CreateBucketForProject(bucket_name, project_id, BucketMetadata()); EXPECT_EQ(bucket_name, insert_meta.name()); buckets = client.ListBucketsForProject(project_id); std::vector<BucketMetadata> current_buckets(buckets.begin(), buckets.end()); EXPECT_EQ(1U, name_counter(bucket_name, current_buckets)); BucketMetadata get_meta = client.GetBucketMetadata(bucket_name); EXPECT_EQ(insert_meta, get_meta); // Create a request to update the metadata, change the storage class because // it is easy. And use either COLDLINE or NEARLINE depending on the existing // value. std::string desired_storage_class = storage_class::Coldline(); if (get_meta.storage_class() == storage_class::Coldline()) { desired_storage_class = storage_class::Nearline(); } BucketMetadata update = get_meta; update.set_storage_class(desired_storage_class); BucketMetadata updated_meta = client.UpdateBucket(bucket_name, update); EXPECT_EQ(desired_storage_class, updated_meta.storage_class()); client.DeleteBucket(bucket_name); buckets = client.ListBucketsForProject(project_id); current_buckets.assign(buckets.begin(), buckets.end()); EXPECT_EQ(0U, name_counter(bucket_name, current_buckets)); } TEST_F(BucketIntegrationTest, GetMetadata) { auto bucket_name = BucketTestEnvironment::bucket_name(); Client client; auto metadata = client.GetBucketMetadata(bucket_name); EXPECT_EQ(bucket_name, metadata.name()); EXPECT_EQ(bucket_name, metadata.id()); EXPECT_EQ("storage#bucket", metadata.kind()); } TEST_F(BucketIntegrationTest, GetMetadataIfMetaGenerationMatch_Success) { auto bucket_name = BucketTestEnvironment::bucket_name(); Client client; auto metadata = client.GetBucketMetadata(bucket_name); EXPECT_EQ(bucket_name, metadata.name()); EXPECT_EQ(bucket_name, metadata.id()); EXPECT_EQ("storage#bucket", metadata.kind()); auto metadata2 = client.GetBucketMetadata( bucket_name, storage::Projection("noAcl"), storage::IfMetaGenerationMatch(metadata.metageneration())); EXPECT_EQ(metadata2, metadata); } TEST_F(BucketIntegrationTest, GetMetadataIfMetaGenerationNotMatch_Failure) { auto bucket_name = BucketTestEnvironment::bucket_name(); Client client; auto metadata = client.GetBucketMetadata(bucket_name); EXPECT_EQ(bucket_name, metadata.name()); EXPECT_EQ(bucket_name, metadata.id()); EXPECT_EQ("storage#bucket", metadata.kind()); #if GOOGLE_CLOUD_CPP_HAVE_EXCEPTIONS EXPECT_THROW( client.GetBucketMetadata( bucket_name, storage::Projection("noAcl"), storage::IfMetaGenerationNotMatch(metadata.metageneration())), std::exception); #else EXPECT_DEATH_IF_SUPPORTED( client.GetBucketMetadata( bucket_name, storage::Projection("noAcl"), storage::IfMetaGenerationNotMatch(metadata.metageneration())), "exceptions are disabled"); #endif // GOOGLE_CLOUD_CPP_HAVE_EXCEPTIONS } TEST_F(BucketIntegrationTest, InsertObjectMedia) { auto bucket_name = BucketTestEnvironment::bucket_name(); Client client; auto object_name = MakeRandomObjectName(); auto metadata = client.InsertObject(bucket_name, object_name, "blah blah"); EXPECT_EQ(bucket_name, metadata.bucket()); EXPECT_EQ(object_name, metadata.name()); EXPECT_EQ("storage#object", metadata.kind()); } TEST_F(BucketIntegrationTest, InsertObjectMediaIfGenerationMatch) { auto bucket_name = BucketTestEnvironment::bucket_name(); Client client; auto object_name = MakeRandomObjectName(); auto original = client.InsertObject(bucket_name, object_name, "blah blah", storage::IfGenerationMatch(0)); EXPECT_EQ(bucket_name, original.bucket()); EXPECT_EQ(object_name, original.name()); EXPECT_EQ("storage#object", original.kind()); #if GOOGLE_CLOUD_CPP_HAVE_EXCEPTIONS EXPECT_THROW(client.InsertObject(bucket_name, object_name, "blah blah", storage::IfGenerationMatch(0)), std::exception); #else EXPECT_DEATH_IF_SUPPORTED( client.InsertObject(bucket_name, object_name, "blah blah", storage::IfGenerationMatch(0)), "exceptions are disabled"); #endif // GOOGLE_CLOUD_CPP_HAVE_EXCEPTIONS } TEST_F(BucketIntegrationTest, InsertObjectMediaIfGenerationNotMatch) { auto bucket_name = BucketTestEnvironment::bucket_name(); Client client; auto object_name = MakeRandomObjectName(); auto original = client.InsertObject(bucket_name, object_name, "blah blah", storage::IfGenerationMatch(0)); EXPECT_EQ(bucket_name, original.bucket()); EXPECT_EQ(object_name, original.name()); EXPECT_EQ("storage#object", original.kind()); auto metadata = client.InsertObject(bucket_name, object_name, "more blah blah", storage::IfGenerationNotMatch(0)); EXPECT_EQ(object_name, metadata.name()); EXPECT_NE(original.generation(), metadata.generation()); } TEST_F(BucketIntegrationTest, ListObjects) { auto bucket_name = BucketTestEnvironment::bucket_name(); Client client; auto create_small_object = [&client, &bucket_name, this] { auto object_name = MakeRandomObjectName(); auto meta = client.InsertObject(bucket_name, object_name, "blah blah", storage::IfGenerationMatch(0)); return meta.name(); }; std::vector<std::string> expected(3); std::generate_n(expected.begin(), expected.size(), create_small_object); ListObjectsReader reader = client.ListObjects(bucket_name); std::vector<std::string> actual; for (auto it = reader.begin(); it != reader.end(); ++it) { auto const& meta = *it; EXPECT_EQ(bucket_name, meta.bucket()); actual.push_back(meta.name()); } // There may be a lot of other objects in the bucket, so we want to verify // that any objects we created are found there, but cannot expect a perfect // match. for (auto const& name : expected) { EXPECT_EQ(1, std::count(actual.begin(), actual.end(), name)); } } TEST_F(BucketIntegrationTest, AccessControlCRUD) { Client client; auto bucket_name = BucketTestEnvironment::bucket_name(); auto entity_name = MakeEntityName(); std::vector<BucketAccessControl> initial_acl = client.ListBucketAcl(bucket_name); auto name_counter = [](std::string const& name, std::vector<BucketAccessControl> const& list) { auto name_matcher = [](std::string const& name) { return [name](BucketAccessControl const& m) { return m.entity() == name; }; }; return std::count_if(list.begin(), list.end(), name_matcher(name)); }; // TODO(#827) - handle this more gracefully, delete the entry. Or ... // TODO(#821) TODO(#820) - use a new bucket to simplify this test. EXPECT_EQ(0, name_counter(entity_name, initial_acl)) << "Test aborted (without failure). The entity <" << entity_name << "> already exists, and DeleteBucketAcl() is not implemented."; if (name_counter(entity_name, initial_acl) == 0) { return; } BucketAccessControl result = client.CreateBucketAcl(bucket_name, entity_name, "OWNER"); EXPECT_EQ("OWNER", result.role()); auto current_acl = client.ListBucketAcl(bucket_name); EXPECT_FALSE(current_acl.empty()); // Search using the entity name returned by the request, because we use // 'project-editors-<project_id>' this different than the original entity // name, the server "translates" the project id to a project number. EXPECT_EQ(1, name_counter(result.entity(), current_acl)); // TODO(#827) - delete the new entry to leave the bucket in the original // state. } TEST_F(BucketIntegrationTest, DefaultObjectAccessControlCRUD) { Client client; auto bucket_name = BucketTestEnvironment::bucket_name(); auto entity_name = MakeEntityName(); std::vector<ObjectAccessControl> initial_acl = client.ListDefaultObjectAcl(bucket_name); // TODO(#833) TODO(#835) - make stronger assertions once we can modify the // ACL. EXPECT_FALSE(initial_acl.empty()); } } // namespace } // namespace STORAGE_CLIENT_NS } // namespace storage } // namespace cloud } // namespace google int main(int argc, char* argv[]) { google::cloud::testing_util::InitGoogleMock(argc, argv); // Make sure the arguments are valid. if (argc != 3) { std::string const cmd = argv[0]; auto last_slash = std::string(argv[0]).find_last_of('/'); std::cerr << "Usage: " << cmd.substr(last_slash + 1) << " <project> <bucket>" << std::endl; return 1; } std::string const project_id = argv[1]; std::string const bucket_name = argv[2]; (void)::testing::AddGlobalTestEnvironment( new google::cloud::storage::BucketTestEnvironment(project_id, bucket_name)); return RUN_ALL_TESTS(); }
Use random object names in integration test. (#991)
Use random object names in integration test. (#991) This fixes #681. Random object names make it less likely that two tests running simultaneously will conflict with each other. When I first wrote this test we did not have the pseudo-random number helpers in google::cloud, and left a TODO to fix them, time to do that.
C++
apache-2.0
googleapis/google-cloud-cpp,googleapis/google-cloud-cpp,googleapis/google-cloud-cpp,googleapis/google-cloud-cpp
e49813a7e05e1daa23b3c1bf52eb81f0546819b4
test/bgn_test.cpp
test/bgn_test.cpp
#define PUT(x) std::cout << #x << "=" << (x) << std::endl; #include <cybozu/test.hpp> #include <cybozu/benchmark.hpp> #include <cybozu/random_generator.hpp> #include <mcl/bn256.hpp> #include <mcl/bgn.hpp> #if CYBOZU_CPP_VERSION >= CYBOZU_CPP_VERSION_CPP11 #include <random> std::random_device rg; #else cybozu::RandomGenerator rg; #endif typedef mcl::bgn::BGNT<mcl::bn256::BN, mcl::bn256::Fr> BGN; typedef BGN::SecretKey SecretKey; typedef BGN::PublicKey PublicKey; typedef BGN::CipherTextG1 CipherTextG1; typedef BGN::CipherTextG2 CipherTextG2; typedef BGN::CipherTextA CipherTextA; typedef BGN::CipherTextM CipherTextM; typedef BGN::CipherText CipherText; using namespace mcl::bgn; using namespace mcl::bn256; SecretKey g_sec; CYBOZU_TEST_AUTO(log) { BGN::init(); G1 P; BN::hashAndMapToG1(P, "abc"); for (int i = -5; i < 5; i++) { G1 iP; G1::mul(iP, P, i); CYBOZU_TEST_EQUAL(mcl::bgn::local::log(P, iP), i); } } CYBOZU_TEST_AUTO(EcHashTable) { mcl::bgn::local::EcHashTable<G1> hashTbl; G1 P; BN::hashAndMapToG1(P, "abc"); const int maxSize = 100; const int tryNum = 3; hashTbl.init(P, maxSize, tryNum); for (int i = -maxSize; i <= maxSize; i++) { G1 xP; G1::mul(xP, P, i); CYBOZU_TEST_EQUAL(hashTbl.basicLog(xP), i); } for (int i = -maxSize * tryNum; i <= maxSize * tryNum; i++) { G1 xP; G1::mul(xP, P, i); CYBOZU_TEST_EQUAL(hashTbl.log(xP), i); } } CYBOZU_TEST_AUTO(GTHashTable) { mcl::bgn::local::GTHashTable<GT> hashTbl; GT g; { G1 P; BN::hashAndMapToG1(P, "abc"); G2 Q; BN::hashAndMapToG2(Q, "abc"); BN::pairing(g, P, Q); } const int maxSize = 100; const int tryNum = 3; hashTbl.init(g, maxSize, tryNum); for (int i = -maxSize; i <= maxSize; i++) { GT gx; GT::pow(gx, g, i); CYBOZU_TEST_EQUAL(hashTbl.basicLog(gx), i); } for (int i = -maxSize * tryNum; i <= maxSize * tryNum; i++) { GT gx; GT::pow(gx, g, i); CYBOZU_TEST_EQUAL(hashTbl.log(gx), i); } } CYBOZU_TEST_AUTO(enc_dec) { SecretKey& sec = g_sec; sec.setByCSPRNG(rg); sec.setRangeForDLP(1024); PublicKey pub; sec.getPublicKey(pub); CipherText c; for (int i = -5; i < 5; i++) { pub.enc(c, i, rg); CYBOZU_TEST_EQUAL(sec.dec(c), i); pub.rerandomize(c, rg); CYBOZU_TEST_EQUAL(sec.dec(c), i); } } CYBOZU_TEST_AUTO(add_sub_mul) { const SecretKey& sec = g_sec; PublicKey pub; sec.getPublicKey(pub); for (int m1 = -5; m1 < 5; m1++) { for (int m2 = -5; m2 < 5; m2++) { CipherText c1, c2, c3; pub.enc(c1, m1, rg); pub.enc(c2, m2, rg); CipherText::add(c3, c1, c2); CYBOZU_TEST_EQUAL(m1 + m2, sec.dec(c3)); pub.rerandomize(c3, rg); CYBOZU_TEST_EQUAL(m1 + m2, sec.dec(c3)); CipherText::sub(c3, c1, c2); CYBOZU_TEST_EQUAL(m1 - m2, sec.dec(c3)); CipherText::mul(c3, c1, c2); CYBOZU_TEST_EQUAL(m1 * m2, sec.dec(c3)); pub.rerandomize(c3, rg); CYBOZU_TEST_EQUAL(m1 * m2, sec.dec(c3)); } } } CYBOZU_TEST_AUTO(add_mul_add_sub) { const SecretKey& sec = g_sec; PublicKey pub; sec.getPublicKey(pub); int m[8] = { 1, -2, 3, 4, -5, 6, -7, 8 }; CipherText c[8]; for (int i = 0; i < 8; i++) { pub.enc(c[i], m[i], rg); CYBOZU_TEST_EQUAL(sec.dec(c[i]), m[i]); CYBOZU_TEST_ASSERT(!c[i].isMultiplied()); CipherText mc; pub.convertToCipherTextM(mc, c[i]); CYBOZU_TEST_ASSERT(mc.isMultiplied()); CYBOZU_TEST_EQUAL(sec.dec(mc), m[i]); } int ok1 = (m[0] + m[1]) * (m[2] + m[3]); int ok2 = (m[4] + m[5]) * (m[6] + m[7]); int ok = ok1 + ok2; for (int i = 0; i < 4; i++) { c[i * 2].add(c[i * 2 + 1]); CYBOZU_TEST_EQUAL(sec.dec(c[i * 2]), m[i * 2] + m[i * 2 + 1]); } c[0].mul(c[2]); CYBOZU_TEST_EQUAL(sec.dec(c[0]), ok1); c[4].mul(c[6]); CYBOZU_TEST_EQUAL(sec.dec(c[4]), ok2); c[0].add(c[4]); CYBOZU_TEST_EQUAL(sec.dec(c[0]), ok); c[0].sub(c[4]); CYBOZU_TEST_EQUAL(sec.dec(c[0]), ok1); } template<class T> T testIo(const T& x) { std::stringstream ss; ss << x; T y; ss >> y; CYBOZU_TEST_EQUAL(x, y); return y; } CYBOZU_TEST_AUTO(io) { int m; for (int i = 0; i < 2; i++) { if (i == 1) { Fp::setIoMode(mcl::IoFixedSizeByteSeq); G1::setIoMode(mcl::IoFixedSizeByteSeq); } SecretKey sec; sec.setByCSPRNG(rg); sec.setRangeForDLP(100, 2); testIo(sec); PublicKey pub; sec.getPublicKey(pub); testIo(pub); CipherTextG1 g1; pub.enc(g1, 3, rg); m = sec.dec(testIo(g1)); CYBOZU_TEST_EQUAL(m, 3); CipherTextG2 g2; pub.enc(g2, 5, rg); testIo(g2); CipherTextA ca; pub.enc(ca, -4, rg); m = sec.dec(testIo(ca)); CYBOZU_TEST_EQUAL(m, -4); CipherTextM cm; CipherTextM::mul(cm, g1, g2); m = sec.dec(testIo(cm)); CYBOZU_TEST_EQUAL(m, 15); } }
#define PUT(x) std::cout << #x << "=" << (x) << std::endl; #include <cybozu/test.hpp> #include <cybozu/benchmark.hpp> #include <cybozu/random_generator.hpp> #include <mcl/bn256.hpp> #include <mcl/bgn.hpp> #if CYBOZU_CPP_VERSION >= CYBOZU_CPP_VERSION_CPP11 #include <random> std::random_device g_rg; #else cybozu::RandomGenerator g_rg; #endif typedef mcl::bgn::BGNT<mcl::bn256::BN, mcl::bn256::Fr> BGN; typedef BGN::SecretKey SecretKey; typedef BGN::PublicKey PublicKey; typedef BGN::CipherTextG1 CipherTextG1; typedef BGN::CipherTextG2 CipherTextG2; typedef BGN::CipherTextA CipherTextA; typedef BGN::CipherTextM CipherTextM; typedef BGN::CipherText CipherText; using namespace mcl::bgn; using namespace mcl::bn256; SecretKey g_sec; CYBOZU_TEST_AUTO(log) { BGN::init(); G1 P; BN::hashAndMapToG1(P, "abc"); for (int i = -5; i < 5; i++) { G1 iP; G1::mul(iP, P, i); CYBOZU_TEST_EQUAL(mcl::bgn::local::log(P, iP), i); } } CYBOZU_TEST_AUTO(EcHashTable) { mcl::bgn::local::EcHashTable<G1> hashTbl; G1 P; BN::hashAndMapToG1(P, "abc"); const int maxSize = 100; const int tryNum = 3; hashTbl.init(P, maxSize, tryNum); for (int i = -maxSize; i <= maxSize; i++) { G1 xP; G1::mul(xP, P, i); CYBOZU_TEST_EQUAL(hashTbl.basicLog(xP), i); } for (int i = -maxSize * tryNum; i <= maxSize * tryNum; i++) { G1 xP; G1::mul(xP, P, i); CYBOZU_TEST_EQUAL(hashTbl.log(xP), i); } } CYBOZU_TEST_AUTO(GTHashTable) { mcl::bgn::local::GTHashTable<GT> hashTbl; GT g; { G1 P; BN::hashAndMapToG1(P, "abc"); G2 Q; BN::hashAndMapToG2(Q, "abc"); BN::pairing(g, P, Q); } const int maxSize = 100; const int tryNum = 3; hashTbl.init(g, maxSize, tryNum); for (int i = -maxSize; i <= maxSize; i++) { GT gx; GT::pow(gx, g, i); CYBOZU_TEST_EQUAL(hashTbl.basicLog(gx), i); } for (int i = -maxSize * tryNum; i <= maxSize * tryNum; i++) { GT gx; GT::pow(gx, g, i); CYBOZU_TEST_EQUAL(hashTbl.log(gx), i); } } CYBOZU_TEST_AUTO(enc_dec) { SecretKey& sec = g_sec; sec.setByCSPRNG(g_rg); sec.setRangeForDLP(1024); PublicKey pub; sec.getPublicKey(pub); CipherText c; for (int i = -5; i < 5; i++) { pub.enc(c, i, g_rg); CYBOZU_TEST_EQUAL(sec.dec(c), i); pub.rerandomize(c, g_rg); CYBOZU_TEST_EQUAL(sec.dec(c), i); } } CYBOZU_TEST_AUTO(add_sub_mul) { const SecretKey& sec = g_sec; PublicKey pub; sec.getPublicKey(pub); for (int m1 = -5; m1 < 5; m1++) { for (int m2 = -5; m2 < 5; m2++) { CipherText c1, c2, c3; pub.enc(c1, m1, g_rg); pub.enc(c2, m2, g_rg); CipherText::add(c3, c1, c2); CYBOZU_TEST_EQUAL(m1 + m2, sec.dec(c3)); pub.rerandomize(c3, g_rg); CYBOZU_TEST_EQUAL(m1 + m2, sec.dec(c3)); CipherText::sub(c3, c1, c2); CYBOZU_TEST_EQUAL(m1 - m2, sec.dec(c3)); CipherText::mul(c3, c1, c2); CYBOZU_TEST_EQUAL(m1 * m2, sec.dec(c3)); pub.rerandomize(c3, g_rg); CYBOZU_TEST_EQUAL(m1 * m2, sec.dec(c3)); } } } CYBOZU_TEST_AUTO(add_mul_add_sub) { const SecretKey& sec = g_sec; PublicKey pub; sec.getPublicKey(pub); int m[8] = { 1, -2, 3, 4, -5, 6, -7, 8 }; CipherText c[8]; for (int i = 0; i < 8; i++) { pub.enc(c[i], m[i], g_rg); CYBOZU_TEST_EQUAL(sec.dec(c[i]), m[i]); CYBOZU_TEST_ASSERT(!c[i].isMultiplied()); CipherText mc; pub.convertToCipherTextM(mc, c[i]); CYBOZU_TEST_ASSERT(mc.isMultiplied()); CYBOZU_TEST_EQUAL(sec.dec(mc), m[i]); } int ok1 = (m[0] + m[1]) * (m[2] + m[3]); int ok2 = (m[4] + m[5]) * (m[6] + m[7]); int ok = ok1 + ok2; for (int i = 0; i < 4; i++) { c[i * 2].add(c[i * 2 + 1]); CYBOZU_TEST_EQUAL(sec.dec(c[i * 2]), m[i * 2] + m[i * 2 + 1]); } c[0].mul(c[2]); CYBOZU_TEST_EQUAL(sec.dec(c[0]), ok1); c[4].mul(c[6]); CYBOZU_TEST_EQUAL(sec.dec(c[4]), ok2); c[0].add(c[4]); CYBOZU_TEST_EQUAL(sec.dec(c[0]), ok); c[0].sub(c[4]); CYBOZU_TEST_EQUAL(sec.dec(c[0]), ok1); } template<class T> T testIo(const T& x) { std::stringstream ss; ss << x; T y; ss >> y; CYBOZU_TEST_EQUAL(x, y); return y; } CYBOZU_TEST_AUTO(io) { int m; for (int i = 0; i < 2; i++) { if (i == 1) { Fp::setIoMode(mcl::IoFixedSizeByteSeq); G1::setIoMode(mcl::IoFixedSizeByteSeq); } SecretKey sec; sec.setByCSPRNG(g_rg); sec.setRangeForDLP(100, 2); testIo(sec); PublicKey pub; sec.getPublicKey(pub); testIo(pub); CipherTextG1 g1; pub.enc(g1, 3, g_rg); m = sec.dec(testIo(g1)); CYBOZU_TEST_EQUAL(m, 3); CipherTextG2 g2; pub.enc(g2, 5, g_rg); testIo(g2); CipherTextA ca; pub.enc(ca, -4, g_rg); m = sec.dec(testIo(ca)); CYBOZU_TEST_EQUAL(m, -4); CipherTextM cm; CipherTextM::mul(cm, g1, g2); m = sec.dec(testIo(cm)); CYBOZU_TEST_EQUAL(m, 15); } } CYBOZU_TEST_AUTO(bench) { const SecretKey& sec = g_sec; PublicKey pub; sec.getPublicKey(pub); CipherText c1, c2, c3; CYBOZU_BENCH("enc", pub.enc, c1, 5, g_rg); pub.enc(c2, 4, g_rg); CYBOZU_BENCH("add", c1.add, c2); CYBOZU_BENCH("mul", CipherText::mul, c3, c1, c2); pub.enc(c1, 5, g_rg); pub.enc(c2, 4, g_rg); c1.mul(c2); CYBOZU_BENCH("dec", sec.dec, c1); c2 = c1; CYBOZU_BENCH("add after mul", c1.add, c2); }
add benchmark of bgn
add benchmark of bgn
C++
bsd-3-clause
herumi/mcl,herumi/mcl,herumi/mcl,herumi/mcl,herumi/mcl,herumi/mcl,herumi/mcl,herumi/mcl
35b888dc1194eafabb6646abcdd2614339b5dd26
ReactCommon/cxxreact/Instance.cpp
ReactCommon/cxxreact/Instance.cpp
// Copyright 2004-present Facebook. All Rights Reserved. #include "Instance.h" #include "Executor.h" #include "MethodCall.h" #include "RecoverableError.h" #include "SystraceSection.h" #include <folly/json.h> #include <folly/Memory.h> #include <folly/MoveWrapper.h> #include <glog/logging.h> #include <condition_variable> #include <mutex> #include <string> namespace facebook { namespace react { Instance::~Instance() { if (nativeToJsBridge_) { nativeToJsBridge_->destroy(); } } void Instance::initializeBridge( std::unique_ptr<InstanceCallback> callback, std::shared_ptr<JSExecutorFactory> jsef, std::shared_ptr<MessageQueueThread> jsQueue, std::shared_ptr<ModuleRegistry> moduleRegistry) { callback_ = std::move(callback); jsQueue->runOnQueueSync( [this, &jsef, moduleRegistry, jsQueue] () mutable { nativeToJsBridge_ = folly::make_unique<NativeToJsBridge>( jsef.get(), moduleRegistry, jsQueue, callback_); std::lock_guard<std::mutex> lock(m_syncMutex); m_syncReady = true; m_syncCV.notify_all(); }); CHECK(nativeToJsBridge_); } void Instance::loadApplication( std::unique_ptr<JSModulesUnbundle> unbundle, std::unique_ptr<const JSBigString> string, std::string sourceURL) { callback_->incrementPendingJSCalls(); SystraceSection s("reactbridge_xplat_loadApplication", "sourceURL", sourceURL); nativeToJsBridge_->loadApplication(std::move(unbundle), std::move(string), std::move(sourceURL)); } void Instance::loadApplicationSync( std::unique_ptr<JSModulesUnbundle> unbundle, std::unique_ptr<const JSBigString> string, std::string sourceURL) { std::unique_lock<std::mutex> lock(m_syncMutex); m_syncCV.wait(lock, [this] { return m_syncReady; }); SystraceSection s("reactbridge_xplat_loadApplicationSync", "sourceURL", sourceURL); nativeToJsBridge_->loadApplicationSync(std::move(unbundle), std::move(string), std::move(sourceURL)); } void Instance::setSourceURL(std::string sourceURL) { callback_->incrementPendingJSCalls(); SystraceSection s("reactbridge_xplat_setSourceURL", "sourceURL", sourceURL); nativeToJsBridge_->loadApplication(nullptr, nullptr, std::move(sourceURL)); } void Instance::loadScriptFromString(std::unique_ptr<const JSBigString> string, std::string sourceURL, bool loadSynchronously) { SystraceSection s("reactbridge_xplat_loadScriptFromString", "sourceURL", sourceURL); if (loadSynchronously) { loadApplicationSync(nullptr, std::move(string), std::move(sourceURL)); } else { loadApplicationSync(nullptr, std::move(string), std::move(sourceURL)); } } void Instance::loadUnbundle(std::unique_ptr<JSModulesUnbundle> unbundle, std::unique_ptr<const JSBigString> startupScript, std::string startupScriptSourceURL, bool loadSynchronously) { if (loadSynchronously) { loadApplicationSync(std::move(unbundle), std::move(startupScript), std::move(startupScriptSourceURL)); } else { loadApplication(std::move(unbundle), std::move(startupScript), std::move(startupScriptSourceURL)); } } bool Instance::supportsProfiling() { return nativeToJsBridge_->supportsProfiling(); } void Instance::startProfiler(const std::string& title) { return nativeToJsBridge_->startProfiler(title); } void Instance::stopProfiler(const std::string& title, const std::string& filename) { return nativeToJsBridge_->stopProfiler(title, filename); } void Instance::setGlobalVariable(std::string propName, std::unique_ptr<const JSBigString> jsonValue) { nativeToJsBridge_->setGlobalVariable(std::move(propName), std::move(jsonValue)); } void *Instance::getJavaScriptContext() { return nativeToJsBridge_->getJavaScriptContext(); } void Instance::callJSFunction(std::string&& module, std::string&& method, folly::dynamic&& params) { callback_->incrementPendingJSCalls(); nativeToJsBridge_->callFunction(std::move(module), std::move(method), std::move(params)); } void Instance::callJSCallback(uint64_t callbackId, folly::dynamic&& params) { SystraceSection s("<callback>"); callback_->incrementPendingJSCalls(); nativeToJsBridge_->invokeCallback((double) callbackId, std::move(params)); } void Instance::handleMemoryPressureUiHidden() { nativeToJsBridge_->handleMemoryPressureUiHidden(); } void Instance::handleMemoryPressureModerate() { nativeToJsBridge_->handleMemoryPressureModerate(); } void Instance::handleMemoryPressureCritical() { nativeToJsBridge_->handleMemoryPressureCritical(); } } // namespace react } // namespace facebook
// Copyright 2004-present Facebook. All Rights Reserved. #include "Instance.h" #include "Executor.h" #include "MethodCall.h" #include "RecoverableError.h" #include "SystraceSection.h" #include <folly/json.h> #include <folly/Memory.h> #include <folly/MoveWrapper.h> #include <glog/logging.h> #include <condition_variable> #include <mutex> #include <string> namespace facebook { namespace react { Instance::~Instance() { if (nativeToJsBridge_) { nativeToJsBridge_->destroy(); } } void Instance::initializeBridge( std::unique_ptr<InstanceCallback> callback, std::shared_ptr<JSExecutorFactory> jsef, std::shared_ptr<MessageQueueThread> jsQueue, std::shared_ptr<ModuleRegistry> moduleRegistry) { callback_ = std::move(callback); jsQueue->runOnQueueSync( [this, &jsef, moduleRegistry, jsQueue] () mutable { nativeToJsBridge_ = folly::make_unique<NativeToJsBridge>( jsef.get(), moduleRegistry, jsQueue, callback_); std::lock_guard<std::mutex> lock(m_syncMutex); m_syncReady = true; m_syncCV.notify_all(); }); CHECK(nativeToJsBridge_); } void Instance::loadApplication( std::unique_ptr<JSModulesUnbundle> unbundle, std::unique_ptr<const JSBigString> string, std::string sourceURL) { callback_->incrementPendingJSCalls(); SystraceSection s("reactbridge_xplat_loadApplication", "sourceURL", sourceURL); nativeToJsBridge_->loadApplication(std::move(unbundle), std::move(string), std::move(sourceURL)); } void Instance::loadApplicationSync( std::unique_ptr<JSModulesUnbundle> unbundle, std::unique_ptr<const JSBigString> string, std::string sourceURL) { std::unique_lock<std::mutex> lock(m_syncMutex); m_syncCV.wait(lock, [this] { return m_syncReady; }); SystraceSection s("reactbridge_xplat_loadApplicationSync", "sourceURL", sourceURL); nativeToJsBridge_->loadApplicationSync(std::move(unbundle), std::move(string), std::move(sourceURL)); } void Instance::setSourceURL(std::string sourceURL) { callback_->incrementPendingJSCalls(); SystraceSection s("reactbridge_xplat_setSourceURL", "sourceURL", sourceURL); nativeToJsBridge_->loadApplication(nullptr, nullptr, std::move(sourceURL)); } void Instance::loadScriptFromString(std::unique_ptr<const JSBigString> string, std::string sourceURL, bool loadSynchronously) { SystraceSection s("reactbridge_xplat_loadScriptFromString", "sourceURL", sourceURL); if (loadSynchronously) { loadApplicationSync(nullptr, std::move(string), std::move(sourceURL)); } else { loadApplication(nullptr, std::move(string), std::move(sourceURL)); } } void Instance::loadUnbundle(std::unique_ptr<JSModulesUnbundle> unbundle, std::unique_ptr<const JSBigString> startupScript, std::string startupScriptSourceURL, bool loadSynchronously) { if (loadSynchronously) { loadApplicationSync(std::move(unbundle), std::move(startupScript), std::move(startupScriptSourceURL)); } else { loadApplication(std::move(unbundle), std::move(startupScript), std::move(startupScriptSourceURL)); } } bool Instance::supportsProfiling() { return nativeToJsBridge_->supportsProfiling(); } void Instance::startProfiler(const std::string& title) { return nativeToJsBridge_->startProfiler(title); } void Instance::stopProfiler(const std::string& title, const std::string& filename) { return nativeToJsBridge_->stopProfiler(title, filename); } void Instance::setGlobalVariable(std::string propName, std::unique_ptr<const JSBigString> jsonValue) { nativeToJsBridge_->setGlobalVariable(std::move(propName), std::move(jsonValue)); } void *Instance::getJavaScriptContext() { return nativeToJsBridge_->getJavaScriptContext(); } void Instance::callJSFunction(std::string&& module, std::string&& method, folly::dynamic&& params) { callback_->incrementPendingJSCalls(); nativeToJsBridge_->callFunction(std::move(module), std::move(method), std::move(params)); } void Instance::callJSCallback(uint64_t callbackId, folly::dynamic&& params) { SystraceSection s("<callback>"); callback_->incrementPendingJSCalls(); nativeToJsBridge_->invokeCallback((double) callbackId, std::move(params)); } void Instance::handleMemoryPressureUiHidden() { nativeToJsBridge_->handleMemoryPressureUiHidden(); } void Instance::handleMemoryPressureModerate() { nativeToJsBridge_->handleMemoryPressureModerate(); } void Instance::handleMemoryPressureCritical() { nativeToJsBridge_->handleMemoryPressureCritical(); } } // namespace react } // namespace facebook
Fix making loadScriptFromString always synchronous
Fix making loadScriptFromString always synchronous Reviewed By: javache Differential Revision: D5129620 fbshipit-source-id: a0ad5e2704fc38f4cdfe29187a2b59ba4b0ff61b
C++
bsd-3-clause
Ehesp/react-native,pandiaraj44/react-native,peterp/react-native,farazs/react-native,gilesvangruisen/react-native,cdlewis/react-native,cdlewis/react-native,tszajna0/react-native,farazs/react-native,formatlos/react-native,exponentjs/react-native,skevy/react-native,peterp/react-native,negativetwelve/react-native,janicduplessis/react-native,hoastoolshop/react-native,makadaw/react-native,javache/react-native,pandiaraj44/react-native,arthuralee/react-native,ptmt/react-native-macos,Livyli/react-native,skevy/react-native,frantic/react-native,hammerandchisel/react-native,jevakallio/react-native,tszajna0/react-native,rickbeerendonk/react-native,farazs/react-native,skevy/react-native,thotegowda/react-native,Bhullnatik/react-native,Livyli/react-native,Ehesp/react-native,exponent/react-native,jevakallio/react-native,PlexChat/react-native,kesha-antonov/react-native,ptmt/react-native-macos,shrutic123/react-native,javache/react-native,arthuralee/react-native,mironiasty/react-native,farazs/react-native,exponent/react-native,Guardiannw/react-native,rickbeerendonk/react-native,facebook/react-native,myntra/react-native,frantic/react-native,pandiaraj44/react-native,negativetwelve/react-native,forcedotcom/react-native,rickbeerendonk/react-native,mironiasty/react-native,hammerandchisel/react-native,exponent/react-native,gilesvangruisen/react-native,thotegowda/react-native,facebook/react-native,hammerandchisel/react-native,mironiasty/react-native,thotegowda/react-native,javache/react-native,jevakallio/react-native,kesha-antonov/react-native,cpunion/react-native,doochik/react-native,formatlos/react-native,shrutic123/react-native,pandiaraj44/react-native,Ehesp/react-native,Bhullnatik/react-native,hoangpham95/react-native,javache/react-native,formatlos/react-native,formatlos/react-native,Guardiannw/react-native,dikaiosune/react-native,mironiasty/react-native,facebook/react-native,PlexChat/react-native,hoangpham95/react-native,kesha-antonov/react-native,gilesvangruisen/react-native,mironiasty/react-native,cpunion/react-native,makadaw/react-native,hoastoolshop/react-native,javache/react-native,myntra/react-native,myntra/react-native,dikaiosune/react-native,doochik/react-native,javache/react-native,thotegowda/react-native,farazs/react-native,kesha-antonov/react-native,doochik/react-native,myntra/react-native,facebook/react-native,doochik/react-native,Guardiannw/react-native,kesha-antonov/react-native,Livyli/react-native,ptmt/react-native-macos,brentvatne/react-native,peterp/react-native,exponent/react-native,facebook/react-native,Guardiannw/react-native,skevy/react-native,exponent/react-native,myntra/react-native,makadaw/react-native,peterp/react-native,forcedotcom/react-native,forcedotcom/react-native,facebook/react-native,cdlewis/react-native,brentvatne/react-native,dikaiosune/react-native,Ehesp/react-native,pandiaraj44/react-native,jevakallio/react-native,dikaiosune/react-native,PlexChat/react-native,makadaw/react-native,rickbeerendonk/react-native,dikaiosune/react-native,aljs/react-native,Bhullnatik/react-native,forcedotcom/react-native,janicduplessis/react-native,exponentjs/react-native,gilesvangruisen/react-native,jevakallio/react-native,brentvatne/react-native,hoastoolshop/react-native,myntra/react-native,brentvatne/react-native,brentvatne/react-native,brentvatne/react-native,jevakallio/react-native,Guardiannw/react-native,facebook/react-native,javache/react-native,janicduplessis/react-native,shrutic123/react-native,thotegowda/react-native,formatlos/react-native,myntra/react-native,thotegowda/react-native,cpunion/react-native,gilesvangruisen/react-native,hammerandchisel/react-native,doochik/react-native,janicduplessis/react-native,negativetwelve/react-native,PlexChat/react-native,formatlos/react-native,doochik/react-native,makadaw/react-native,aljs/react-native,janicduplessis/react-native,aljs/react-native,makadaw/react-native,Bhullnatik/react-native,shrutic123/react-native,arthuralee/react-native,exponentjs/react-native,farazs/react-native,aljs/react-native,mironiasty/react-native,frantic/react-native,shrutic123/react-native,tszajna0/react-native,farazs/react-native,tszajna0/react-native,negativetwelve/react-native,cpunion/react-native,Livyli/react-native,kesha-antonov/react-native,PlexChat/react-native,farazs/react-native,Bhullnatik/react-native,aljs/react-native,peterp/react-native,tszajna0/react-native,Livyli/react-native,mironiasty/react-native,aljs/react-native,cdlewis/react-native,skevy/react-native,Livyli/react-native,aljs/react-native,doochik/react-native,aljs/react-native,rickbeerendonk/react-native,negativetwelve/react-native,forcedotcom/react-native,Bhullnatik/react-native,myntra/react-native,shrutic123/react-native,mironiasty/react-native,brentvatne/react-native,Ehesp/react-native,dikaiosune/react-native,hammerandchisel/react-native,pandiaraj44/react-native,javache/react-native,skevy/react-native,forcedotcom/react-native,janicduplessis/react-native,PlexChat/react-native,Bhullnatik/react-native,makadaw/react-native,peterp/react-native,hoangpham95/react-native,javache/react-native,negativetwelve/react-native,tszajna0/react-native,Bhullnatik/react-native,skevy/react-native,gilesvangruisen/react-native,exponentjs/react-native,frantic/react-native,brentvatne/react-native,hoangpham95/react-native,doochik/react-native,exponent/react-native,mironiasty/react-native,hoangpham95/react-native,hoastoolshop/react-native,tszajna0/react-native,exponentjs/react-native,tszajna0/react-native,makadaw/react-native,PlexChat/react-native,hoastoolshop/react-native,pandiaraj44/react-native,Ehesp/react-native,peterp/react-native,Livyli/react-native,janicduplessis/react-native,thotegowda/react-native,facebook/react-native,Guardiannw/react-native,exponent/react-native,hoastoolshop/react-native,rickbeerendonk/react-native,Livyli/react-native,cdlewis/react-native,ptmt/react-native-macos,makadaw/react-native,frantic/react-native,pandiaraj44/react-native,jevakallio/react-native,rickbeerendonk/react-native,shrutic123/react-native,negativetwelve/react-native,myntra/react-native,peterp/react-native,cpunion/react-native,arthuralee/react-native,gilesvangruisen/react-native,janicduplessis/react-native,cpunion/react-native,ptmt/react-native-macos,cdlewis/react-native,hoastoolshop/react-native,forcedotcom/react-native,exponentjs/react-native,formatlos/react-native,jevakallio/react-native,ptmt/react-native-macos,Ehesp/react-native,ptmt/react-native-macos,doochik/react-native,kesha-antonov/react-native,rickbeerendonk/react-native,brentvatne/react-native,facebook/react-native,kesha-antonov/react-native,cdlewis/react-native,thotegowda/react-native,cpunion/react-native,hammerandchisel/react-native,Ehesp/react-native,cdlewis/react-native,hoangpham95/react-native,Guardiannw/react-native,hammerandchisel/react-native,PlexChat/react-native,Guardiannw/react-native,dikaiosune/react-native,skevy/react-native,shrutic123/react-native,hoastoolshop/react-native,kesha-antonov/react-native,jevakallio/react-native,ptmt/react-native-macos,hoangpham95/react-native,negativetwelve/react-native,exponentjs/react-native,rickbeerendonk/react-native,hammerandchisel/react-native,cdlewis/react-native,dikaiosune/react-native,forcedotcom/react-native,arthuralee/react-native,formatlos/react-native,cpunion/react-native,exponentjs/react-native,hoangpham95/react-native,negativetwelve/react-native,farazs/react-native,exponent/react-native,formatlos/react-native,gilesvangruisen/react-native
cb516e3acf4c729987007c032c286e76ac628471
RPC/ClientSessionTest.cc
RPC/ClientSessionTest.cc
/* Copyright (c) 2012 Stanford University * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <gtest/gtest.h> #include <thread> #if __GNUC__ >= 4 && __GNUC_MINOR__ >= 5 #include <atomic> #else #include <cstdatomic> #endif #include "Core/Debug.h" #include "Event/Timer.h" #include "RPC/ClientSession.h" namespace LogCabin { namespace RPC { namespace { class RPCClientSessionTest : public ::testing::Test { RPCClientSessionTest() : eventLoop() , eventLoopThread(&Event::Loop::runForever, &eventLoop) , session() , remote(-1) { Address address("127.0.0.1", 0); session = ClientSession::makeSession(eventLoop, address, 1024); int socketPair[2]; EXPECT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, socketPair)); remote = socketPair[1]; session->errorMessage.clear(); session->messageSocket.reset( new ClientSession::ClientMessageSocket( *session, socketPair[0], 1024)); } ~RPCClientSessionTest() { session.reset(); eventLoop.exit(); eventLoopThread.join(); EXPECT_EQ(0, close(remote)); } Event::Loop eventLoop; std::thread eventLoopThread; std::shared_ptr<ClientSession> session; int remote; }; std::string str(const Buffer& buffer) { return std::string(static_cast<const char*>(buffer.getData()), buffer.getLength()); } Buffer buf(const char* stringLiteral) { return Buffer(const_cast<char*>(stringLiteral), static_cast<uint32_t>(strlen(stringLiteral)), NULL); } TEST_F(RPCClientSessionTest, onReceiveMessage) { session->numActiveRPCs = 1; // Unexpected session->messageSocket->onReceiveMessage(1, buf("a")); // Normal session->timer.schedule(1); session->responses[1] = new ClientSession::Response(); session->messageSocket->onReceiveMessage(1, buf("b")); EXPECT_TRUE(session->responses[1]->ready); EXPECT_EQ("b", str(session->responses[1]->reply)); EXPECT_EQ(0U, session->numActiveRPCs); EXPECT_FALSE(session->timer.isScheduled()); // Already ready LogCabin::Core::Debug::setLogPolicy({{"", "ERROR"}}); session->messageSocket->onReceiveMessage(1, buf("c")); EXPECT_EQ("b", str(session->responses[1]->reply)); EXPECT_EQ(0U, session->numActiveRPCs); } TEST_F(RPCClientSessionTest, onReceiveMessage_ping) { // spurious session->messageSocket->onReceiveMessage(0, Buffer()); // ping requested session->numActiveRPCs = 1; session->activePing = true; session->messageSocket->onReceiveMessage(0, Buffer()); session->numActiveRPCs = 0; EXPECT_FALSE(session->activePing); EXPECT_TRUE(session->timer.isScheduled()); } TEST_F(RPCClientSessionTest, onDisconnect) { session->messageSocket->onDisconnect(); EXPECT_EQ("Disconnected from server 127.0.0.1:0 (resolved to 127.0.0.1:0)", session->errorMessage); } TEST_F(RPCClientSessionTest, handleTimerEvent) { // spurious std::unique_ptr<ClientSession::ClientMessageSocket> oldMessageSocket; std::swap(oldMessageSocket, session->messageSocket); session->timer.handleTimerEvent(); std::swap(oldMessageSocket, session->messageSocket); session->timer.handleTimerEvent(); // make sure no actions were taken: EXPECT_FALSE(session->timer.isScheduled()); EXPECT_EQ("", session->errorMessage); // need to send ping session->numActiveRPCs = 1; session->timer.handleTimerEvent(); EXPECT_TRUE(session->activePing); char b; EXPECT_EQ(1U, read(remote, &b, 1)); EXPECT_TRUE(session->timer.isScheduled()); // need to time out session session->numActiveRPCs = 1; session->timer.handleTimerEvent(); EXPECT_EQ("Server 127.0.0.1:0 (resolved to 127.0.0.1:0) timed out", session->errorMessage); session->numActiveRPCs = 0; } TEST_F(RPCClientSessionTest, constructor) { auto session2 = ClientSession::makeSession(eventLoop, Address("127.0.0.1", 0), 1024); EXPECT_EQ("127.0.0.1:0 (resolved to 127.0.0.1:0)", session2->address.toString()); EXPECT_EQ("Failed to connect socket to 127.0.0.1:0 " "(resolved to 127.0.0.1:0)", session2->errorMessage); EXPECT_EQ("Closed session: Failed to connect socket to 127.0.0.1:0 " "(resolved to 127.0.0.1:0)", session2->toString()); EXPECT_FALSE(session2->messageSocket); } TEST_F(RPCClientSessionTest, makeSession) { EXPECT_EQ(session.get(), session->self.lock().get()); } TEST_F(RPCClientSessionTest, destructor) { // nothing visible to test } TEST_F(RPCClientSessionTest, sendRequest) { EXPECT_EQ(1U, session->nextMessageId); session->activePing = true; OpaqueClientRPC rpc = session->sendRequest(buf("hi")); EXPECT_EQ(1U, session->numActiveRPCs); EXPECT_FALSE(session->activePing); EXPECT_TRUE(session->timer.isScheduled()); EXPECT_EQ(session, rpc.session); EXPECT_EQ(1U, rpc.responseToken); EXPECT_FALSE(rpc.ready); EXPECT_EQ(2U, session->nextMessageId); auto it = session->responses.find(1); ASSERT_TRUE(it != session->responses.end()); ClientSession::Response& response = *it->second; EXPECT_FALSE(response.ready); } TEST_F(RPCClientSessionTest, getErrorMessage) { EXPECT_EQ("", session->getErrorMessage()); session->errorMessage = "x"; EXPECT_EQ("x", session->getErrorMessage()); } TEST_F(RPCClientSessionTest, toString) { EXPECT_EQ("Active session to 127.0.0.1:0 (resolved to 127.0.0.1:0)", session->toString()); } TEST_F(RPCClientSessionTest, cancel) { OpaqueClientRPC rpc = session->sendRequest(buf("hi")); EXPECT_EQ(1U, session->numActiveRPCs); rpc.cancel(); rpc.cancel(); // intentionally duplicated EXPECT_EQ(0U, session->numActiveRPCs); EXPECT_TRUE(rpc.ready); EXPECT_FALSE(rpc.session); EXPECT_EQ(0U, rpc.reply.getLength()); EXPECT_EQ("RPC canceled by user", rpc.errorMessage); EXPECT_EQ(0U, session->responses.size()); // TODO(ongaro): Test notify with Core/ConditionVariable } TEST_F(RPCClientSessionTest, updateCanceled) { OpaqueClientRPC rpc = session->sendRequest(buf("hi")); rpc.cancel(); rpc.update(); EXPECT_TRUE(rpc.ready); EXPECT_EQ(0U, rpc.reply.getLength()); EXPECT_EQ("RPC canceled by user", rpc.errorMessage); EXPECT_EQ(0U, session->responses.size()); } TEST_F(RPCClientSessionTest, updateNotReady) { OpaqueClientRPC rpc = session->sendRequest(buf("hi")); rpc.update(); EXPECT_FALSE(rpc.ready); EXPECT_EQ(0U, rpc.reply.getLength()); EXPECT_EQ("", rpc.errorMessage); EXPECT_EQ(1U, session->responses.size()); } TEST_F(RPCClientSessionTest, updateReady) { OpaqueClientRPC rpc = session->sendRequest(buf("hi")); auto it = session->responses.find(1); ASSERT_TRUE(it != session->responses.end()); ClientSession::Response& response = *it->second; response.ready = true; response.reply = buf("bye"); rpc.update(); EXPECT_TRUE(rpc.ready); EXPECT_FALSE(rpc.session); EXPECT_EQ("bye", str(rpc.reply)); EXPECT_EQ("", rpc.errorMessage); EXPECT_EQ(0U, session->responses.size()); } TEST_F(RPCClientSessionTest, updateError) { OpaqueClientRPC rpc = session->sendRequest(buf("hi")); session->errorMessage = "some error"; rpc.update(); EXPECT_TRUE(rpc.ready); EXPECT_FALSE(rpc.session); EXPECT_EQ("", str(rpc.reply)); EXPECT_EQ("some error", rpc.errorMessage); EXPECT_EQ(0U, session->responses.size()); } TEST_F(RPCClientSessionTest, waitNotReady) { // It's hard to test this one since it'll block. // TODO(ongaro): Use Core/ConditionVariable } TEST_F(RPCClientSessionTest, waitCanceled) { OpaqueClientRPC rpc = session->sendRequest(buf("hi")); rpc.cancel(); rpc.waitForReply(); EXPECT_TRUE(rpc.ready); } TEST_F(RPCClientSessionTest, waitReady) { OpaqueClientRPC rpc = session->sendRequest(buf("hi")); auto it = session->responses.find(1); ASSERT_TRUE(it != session->responses.end()); ClientSession::Response& response = *it->second; response.ready = true; response.reply = buf("bye"); rpc.waitForReply(); EXPECT_TRUE(rpc.ready); EXPECT_FALSE(rpc.session); EXPECT_EQ("bye", str(rpc.reply)); EXPECT_EQ("", rpc.errorMessage); EXPECT_EQ(0U, session->responses.size()); } TEST_F(RPCClientSessionTest, waitError) { OpaqueClientRPC rpc = session->sendRequest(buf("hi")); session->errorMessage = "some error"; rpc.waitForReply(); EXPECT_TRUE(rpc.ready); EXPECT_FALSE(rpc.session); EXPECT_EQ("", str(rpc.reply)); EXPECT_EQ("some error", rpc.errorMessage); EXPECT_EQ(0U, session->responses.size()); } } // namespace LogCabin::RPC::<anonymous> } // namespace LogCabin::RPC } // namespace LogCabin
/* Copyright (c) 2012 Stanford University * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <gtest/gtest.h> #include <thread> #if __GNUC__ >= 4 && __GNUC_MINOR__ >= 5 #include <atomic> #else #include <cstdatomic> #endif #include "Core/Debug.h" #include "Event/Timer.h" #include "RPC/ClientSession.h" namespace LogCabin { namespace RPC { namespace { class RPCClientSessionTest : public ::testing::Test { RPCClientSessionTest() : eventLoop() , eventLoopThread(&Event::Loop::runForever, &eventLoop) , session() , remote(-1) { Address address("127.0.0.1", 0); session = ClientSession::makeSession(eventLoop, address, 1024); int socketPair[2]; EXPECT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, socketPair)); remote = socketPair[1]; session->errorMessage.clear(); session->messageSocket.reset( new ClientSession::ClientMessageSocket( *session, socketPair[0], 1024)); } ~RPCClientSessionTest() { session.reset(); eventLoop.exit(); eventLoopThread.join(); EXPECT_EQ(0, close(remote)); } Event::Loop eventLoop; std::thread eventLoopThread; std::shared_ptr<ClientSession> session; int remote; }; std::string str(const Buffer& buffer) { return std::string(static_cast<const char*>(buffer.getData()), buffer.getLength()); } Buffer buf(const char* stringLiteral) { return Buffer(const_cast<char*>(stringLiteral), static_cast<uint32_t>(strlen(stringLiteral)), NULL); } TEST_F(RPCClientSessionTest, onReceiveMessage) { session->numActiveRPCs = 1; // Unexpected session->messageSocket->onReceiveMessage(1, buf("a")); // Normal session->timer.schedule(1000000000); session->responses[1] = new ClientSession::Response(); session->messageSocket->onReceiveMessage(1, buf("b")); EXPECT_TRUE(session->responses[1]->ready); EXPECT_EQ("b", str(session->responses[1]->reply)); EXPECT_EQ(0U, session->numActiveRPCs); EXPECT_FALSE(session->timer.isScheduled()); // Already ready LogCabin::Core::Debug::setLogPolicy({{"", "ERROR"}}); session->messageSocket->onReceiveMessage(1, buf("c")); EXPECT_EQ("b", str(session->responses[1]->reply)); EXPECT_EQ(0U, session->numActiveRPCs); } TEST_F(RPCClientSessionTest, onReceiveMessage_ping) { // spurious session->messageSocket->onReceiveMessage(0, Buffer()); // ping requested session->numActiveRPCs = 1; session->activePing = true; session->messageSocket->onReceiveMessage(0, Buffer()); session->numActiveRPCs = 0; EXPECT_FALSE(session->activePing); EXPECT_TRUE(session->timer.isScheduled()); } TEST_F(RPCClientSessionTest, onDisconnect) { session->messageSocket->onDisconnect(); EXPECT_EQ("Disconnected from server 127.0.0.1:0 (resolved to 127.0.0.1:0)", session->errorMessage); } TEST_F(RPCClientSessionTest, handleTimerEvent) { // spurious std::unique_ptr<ClientSession::ClientMessageSocket> oldMessageSocket; std::swap(oldMessageSocket, session->messageSocket); session->timer.handleTimerEvent(); std::swap(oldMessageSocket, session->messageSocket); session->timer.handleTimerEvent(); // make sure no actions were taken: EXPECT_FALSE(session->timer.isScheduled()); EXPECT_EQ("", session->errorMessage); // need to send ping session->numActiveRPCs = 1; session->timer.handleTimerEvent(); EXPECT_TRUE(session->activePing); char b; EXPECT_EQ(1U, read(remote, &b, 1)); EXPECT_TRUE(session->timer.isScheduled()); // need to time out session session->numActiveRPCs = 1; session->timer.handleTimerEvent(); EXPECT_EQ("Server 127.0.0.1:0 (resolved to 127.0.0.1:0) timed out", session->errorMessage); session->numActiveRPCs = 0; } TEST_F(RPCClientSessionTest, constructor) { auto session2 = ClientSession::makeSession(eventLoop, Address("127.0.0.1", 0), 1024); EXPECT_EQ("127.0.0.1:0 (resolved to 127.0.0.1:0)", session2->address.toString()); EXPECT_EQ("Failed to connect socket to 127.0.0.1:0 " "(resolved to 127.0.0.1:0)", session2->errorMessage); EXPECT_EQ("Closed session: Failed to connect socket to 127.0.0.1:0 " "(resolved to 127.0.0.1:0)", session2->toString()); EXPECT_FALSE(session2->messageSocket); } TEST_F(RPCClientSessionTest, makeSession) { EXPECT_EQ(session.get(), session->self.lock().get()); } TEST_F(RPCClientSessionTest, destructor) { // nothing visible to test } TEST_F(RPCClientSessionTest, sendRequest) { EXPECT_EQ(1U, session->nextMessageId); session->activePing = true; OpaqueClientRPC rpc = session->sendRequest(buf("hi")); EXPECT_EQ(1U, session->numActiveRPCs); EXPECT_FALSE(session->activePing); EXPECT_TRUE(session->timer.isScheduled()); EXPECT_EQ(session, rpc.session); EXPECT_EQ(1U, rpc.responseToken); EXPECT_FALSE(rpc.ready); EXPECT_EQ(2U, session->nextMessageId); auto it = session->responses.find(1); ASSERT_TRUE(it != session->responses.end()); ClientSession::Response& response = *it->second; EXPECT_FALSE(response.ready); } TEST_F(RPCClientSessionTest, getErrorMessage) { EXPECT_EQ("", session->getErrorMessage()); session->errorMessage = "x"; EXPECT_EQ("x", session->getErrorMessage()); } TEST_F(RPCClientSessionTest, toString) { EXPECT_EQ("Active session to 127.0.0.1:0 (resolved to 127.0.0.1:0)", session->toString()); } TEST_F(RPCClientSessionTest, cancel) { OpaqueClientRPC rpc = session->sendRequest(buf("hi")); EXPECT_EQ(1U, session->numActiveRPCs); rpc.cancel(); rpc.cancel(); // intentionally duplicated EXPECT_EQ(0U, session->numActiveRPCs); EXPECT_TRUE(rpc.ready); EXPECT_FALSE(rpc.session); EXPECT_EQ(0U, rpc.reply.getLength()); EXPECT_EQ("RPC canceled by user", rpc.errorMessage); EXPECT_EQ(0U, session->responses.size()); // TODO(ongaro): Test notify with Core/ConditionVariable } TEST_F(RPCClientSessionTest, updateCanceled) { OpaqueClientRPC rpc = session->sendRequest(buf("hi")); rpc.cancel(); rpc.update(); EXPECT_TRUE(rpc.ready); EXPECT_EQ(0U, rpc.reply.getLength()); EXPECT_EQ("RPC canceled by user", rpc.errorMessage); EXPECT_EQ(0U, session->responses.size()); } TEST_F(RPCClientSessionTest, updateNotReady) { OpaqueClientRPC rpc = session->sendRequest(buf("hi")); rpc.update(); EXPECT_FALSE(rpc.ready); EXPECT_EQ(0U, rpc.reply.getLength()); EXPECT_EQ("", rpc.errorMessage); EXPECT_EQ(1U, session->responses.size()); } TEST_F(RPCClientSessionTest, updateReady) { OpaqueClientRPC rpc = session->sendRequest(buf("hi")); auto it = session->responses.find(1); ASSERT_TRUE(it != session->responses.end()); ClientSession::Response& response = *it->second; response.ready = true; response.reply = buf("bye"); rpc.update(); EXPECT_TRUE(rpc.ready); EXPECT_FALSE(rpc.session); EXPECT_EQ("bye", str(rpc.reply)); EXPECT_EQ("", rpc.errorMessage); EXPECT_EQ(0U, session->responses.size()); } TEST_F(RPCClientSessionTest, updateError) { OpaqueClientRPC rpc = session->sendRequest(buf("hi")); session->errorMessage = "some error"; rpc.update(); EXPECT_TRUE(rpc.ready); EXPECT_FALSE(rpc.session); EXPECT_EQ("", str(rpc.reply)); EXPECT_EQ("some error", rpc.errorMessage); EXPECT_EQ(0U, session->responses.size()); } TEST_F(RPCClientSessionTest, waitNotReady) { // It's hard to test this one since it'll block. // TODO(ongaro): Use Core/ConditionVariable } TEST_F(RPCClientSessionTest, waitCanceled) { OpaqueClientRPC rpc = session->sendRequest(buf("hi")); rpc.cancel(); rpc.waitForReply(); EXPECT_TRUE(rpc.ready); } TEST_F(RPCClientSessionTest, waitReady) { OpaqueClientRPC rpc = session->sendRequest(buf("hi")); auto it = session->responses.find(1); ASSERT_TRUE(it != session->responses.end()); ClientSession::Response& response = *it->second; response.ready = true; response.reply = buf("bye"); rpc.waitForReply(); EXPECT_TRUE(rpc.ready); EXPECT_FALSE(rpc.session); EXPECT_EQ("bye", str(rpc.reply)); EXPECT_EQ("", rpc.errorMessage); EXPECT_EQ(0U, session->responses.size()); } TEST_F(RPCClientSessionTest, waitError) { OpaqueClientRPC rpc = session->sendRequest(buf("hi")); session->errorMessage = "some error"; rpc.waitForReply(); EXPECT_TRUE(rpc.ready); EXPECT_FALSE(rpc.session); EXPECT_EQ("", str(rpc.reply)); EXPECT_EQ("some error", rpc.errorMessage); EXPECT_EQ(0U, session->responses.size()); } } // namespace LogCabin::RPC::<anonymous> } // namespace LogCabin::RPC } // namespace LogCabin
Fix RPCClientSessionTest.onReceiveMessage deadlocks
Fix RPCClientSessionTest.onReceiveMessage deadlocks This deadlock would happen when the timer fires while onReceiveMessage deschedules it. This can't happen in normal operation because the timer and onReceiveMessage both always run on the event loop thread, but it was happening in this unit test that calls onReceiveMessage concurrently. The fix was to schedule the timer for 1s instead of 1ns, allowing onReceiveMessage to complete before the timer fires.
C++
isc
dankenigsberg/logcabin,gaoning777/logcabin,tempbottle/logcabin,gaoning777/logcabin,chaozh/logcabin,nhardt/logcabin,dankenigsberg/logcabin,dankenigsberg/logcabin,nhardt/logcabin,logcabin/logcabin,TigerZhang/logcabin,chaozh/logcabin,TigerZhang/logcabin,logcabin/logcabin,nhardt/logcabin,chaozh/logcabin,nhardt/logcabin,tempbottle/logcabin,logcabin/logcabin,logcabin/logcabin,dankenigsberg/logcabin,tempbottle/logcabin,tempbottle/logcabin,chaozh/logcabin,gaoning777/logcabin,gaoning777/logcabin,TigerZhang/logcabin,TigerZhang/logcabin
99d91d9d4a806d63e01ea506a10a1e49bd4eb894
RankTransformDataset.cpp
RankTransformDataset.cpp
#include <boost/program_options.hpp> #include <boost/filesystem.hpp> #include <boost/lambda/lambda.hpp> #include <boost/lambda/bind.hpp> #include <boost/random/uniform_int.hpp> #include <boost/random/mersenne_twister.hpp> #include <cstdio> #include <iostream> #include <fstream> #include <cmath> namespace po = boost::program_options; namespace fs = boost::filesystem; namespace bll = boost::lambda; class RankTransformer { public: RankTransformer(const std::string& aMatrixDir, const std::string& aOutputfile, bool aQuantileNormalisation = false, bool aUseInverse = false, bool aScramble = false) : mMatrixDir(aMatrixDir), mOutputFile(NULL), mData(NULL), mBuf(NULL), mRanks(NULL), mInvRanks(NULL), mRankAvgs(NULL), mRankCounts(NULL), mQuantileNormalisation(aQuantileNormalisation), mUseInverse(aUseInverse), mScramble(aScramble) { mOutputFile = fopen(aOutputfile.c_str(), "w"); fs::path data(mMatrixDir); if (mUseInverse) data /= "inverse_data"; else data /= "data"; mData = fopen(data.string().c_str(), "r"); fs::path genes(mMatrixDir); // Ugly hack: if we are using the inverted data, we simply swap out the // list of genes for the list of arrays, so that nGenes is actually the // number of arrays. This means that the normalisation occurs as normal, // except for each gene across arrays instead of for each array across // genes. if (mUseInverse) genes /= "arrays"; else genes /= "genes"; nGenes = 0; std::ifstream gs(genes.string().c_str()); while (gs.good()) { std::string l; std::getline(gs, l); if (!gs.good()) break; nGenes++; } mBuf = new double[nGenes]; mRanks = new double[nGenes]; if (mQuantileNormalisation) { mRankAvgs = new double[nGenes]; mRankCounts = new uint32_t[nGenes]; memset(mRankAvgs, 0, sizeof(double) * nGenes); memset(mRankCounts, 0, sizeof(uint32_t) * nGenes); } mInvRanks = new uint32_t[nGenes]; processAllData(); } ~RankTransformer() { if (mOutputFile != NULL) fclose(mOutputFile); if (mData != NULL) fclose(mData); if (mBuf != NULL) delete [] mBuf; if (mInvRanks != NULL) delete [] mInvRanks; if (mRankCounts != NULL) delete [] mRankCounts; if (mRankAvgs != NULL) delete [] mRankAvgs; } private: fs::path mMatrixDir; FILE* mOutputFile, * mData; double* mBuf, * mRanks; uint32_t nGenes; uint32_t* mInvRanks; double * mRankAvgs; uint32_t * mRankCounts; bool mQuantileNormalisation, mUseInverse, mScramble; boost::mt19937 mRand; void processAllData() { if (mQuantileNormalisation) { while (fread(mBuf, sizeof(double), nGenes, mData) == nGenes) { processArray(true); } fseek(mData, 0, SEEK_SET); for (uint32_t i = 0; i < nGenes; i++) mRankAvgs[i] /= mRankCounts[i]; } while (fread(mBuf, sizeof(double), nGenes, mData) == nGenes) { processArray(); } } void processArray(bool aAverageMode = false) { uint32_t nNans = 0; if (mScramble) { boost::uniform_int<uint32_t> ui(0, nGenes - 1); for (uint32_t k = 0; k < nGenes; k++) { double t = mBuf[k]; uint32_t h = ui(mRand); mBuf[k] = mBuf[h]; mBuf[h] = t; } } for (uint32_t i = 0; i < nGenes; i++) { mInvRanks[i] = i; nNans += !!finite(mBuf[i]); } uint32_t nNotNans = nGenes - nNans; double rankInflationFactor = (nGenes + 0.0) / nNotNans; // Sort indices by value, with NaNs at the top. std::sort(mInvRanks, mInvRanks + nGenes, (bll::var(mBuf)[bll::_1] < bll::var(mBuf)[bll::_2]) || (bll::bind(finite, bll::var(mBuf)[bll::_1]) && !bll::bind(finite, bll::var(mBuf)[bll::_2]))); uint32_t i; if (aAverageMode) { for (i = 0; i < nGenes && finite(mBuf[mInvRanks[i]]); i++) { mRankAvgs[i] += mBuf[mInvRanks[i]]; mRankCounts[i]++; } } else { if (mQuantileNormalisation) { for (i = 0; i < nGenes && finite(mBuf[mInvRanks[i]]); i++) // We could put code in here to deal with tied ranks by putting in median // ranks, but I doubt it would make enough difference to justify it. mRanks[mInvRanks[i]] = mRankAvgs[i]; } else { for (i = 0; i < nGenes && finite(mBuf[mInvRanks[i]]); i++) // We could put code in here to deal with tied ranks by putting in median // ranks, but I doubt it would make enough difference to justify it. mRanks[mInvRanks[i]] = i * rankInflationFactor; } for (; i < nGenes; i++) mRanks[mInvRanks[i]] = std::numeric_limits<double>::quiet_NaN(); fwrite(mRanks, sizeof(double), nGenes, mOutputFile); } } }; int main(int argc, char** argv) { std::string matrixdir, outputfile; po::options_description desc; desc.add_options() ("matrixdir", po::value<std::string>(&matrixdir), "The directory to read the data from") ("use_inverse", "Use the inverted data-set instead of the original") ("scramble", "Scramble data prior to rank transform") ("output", po::value<std::string>(&outputfile), "The file to write the output into") ("qnorm", "If specified, causes quantile normalisation to be applied to the data") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); std::string wrong; if (!vm.count("help")) { if (!vm.count("matrixdir")) wrong = "matrixdir"; else if (!vm.count("output")) wrong = "output"; } if (wrong != "") std::cerr << "Missing option: " << wrong << std::endl; if (vm.count("help") || wrong != "") { std::cout << desc << std::endl; return 1; } if (!fs::is_directory(matrixdir)) { std::cerr << "Invalid matrix directory path supplied" << std::endl; return 1; } RankTransformer rt(matrixdir, outputfile, vm.count("qnorm") != 0, vm.count("use_inverse") != 0, vm.count("scramble") != 0); }
#include <boost/program_options.hpp> #include <boost/filesystem.hpp> #include <boost/lambda/lambda.hpp> #include <boost/lambda/bind.hpp> #include <boost/random/uniform_int.hpp> #include <boost/random/mersenne_twister.hpp> #include <cstdio> #include <iostream> #include <fstream> #include <cmath> namespace po = boost::program_options; namespace fs = boost::filesystem; namespace bll = boost::lambda; class RankTransformer { public: RankTransformer(const std::string& aMatrixDir, const std::string& aOutputfile, bool aQuantileNormalisation = false, bool aUseInverse = false, bool aScramble = false) : mMatrixDir(aMatrixDir), mOutputFile(NULL), mData(NULL), mBuf(NULL), mRanks(NULL), mInvRanks(NULL), mRankAvgs(NULL), mRankCounts(NULL), mQuantileNormalisation(aQuantileNormalisation), mUseInverse(aUseInverse), mScramble(aScramble) { mOutputFile = fopen(aOutputfile.c_str(), "w"); fs::path data(mMatrixDir); if (mUseInverse) data /= "inverse_data"; else data /= "data"; mData = fopen(data.string().c_str(), "r"); fs::path genes(mMatrixDir); // Ugly hack: if we are using the inverted data, we simply swap out the // list of genes for the list of arrays, so that nGenes is actually the // number of arrays. This means that the normalisation occurs as normal, // except for each gene across arrays instead of for each array across // genes. if (mUseInverse) genes /= "arrays"; else genes /= "genes"; nGenes = 0; std::ifstream gs(genes.string().c_str()); while (gs.good()) { std::string l; std::getline(gs, l); if (!gs.good()) break; nGenes++; } mBuf = new double[nGenes]; mRanks = new double[nGenes]; if (mQuantileNormalisation) { mRankAvgs = new double[nGenes]; mRankCounts = new uint32_t[nGenes]; memset(mRankAvgs, 0, sizeof(double) * nGenes); memset(mRankCounts, 0, sizeof(uint32_t) * nGenes); } mInvRanks = new uint32_t[nGenes]; processAllData(); } ~RankTransformer() { if (mOutputFile != NULL) fclose(mOutputFile); if (mData != NULL) fclose(mData); if (mBuf != NULL) delete [] mBuf; if (mInvRanks != NULL) delete [] mInvRanks; if (mRankCounts != NULL) delete [] mRankCounts; if (mRankAvgs != NULL) delete [] mRankAvgs; } private: fs::path mMatrixDir; FILE* mOutputFile, * mData; double* mBuf, * mRanks; uint32_t nGenes; uint32_t* mInvRanks; double * mRankAvgs; uint32_t * mRankCounts; bool mQuantileNormalisation, mUseInverse, mScramble; boost::mt19937 mRand; void processAllData() { if (mQuantileNormalisation) { while (fread(mBuf, sizeof(double), nGenes, mData) == nGenes) { processArray(true); } fseek(mData, 0, SEEK_SET); for (uint32_t i = 0; i < nGenes; i++) mRankAvgs[i] /= mRankCounts[i]; } while (fread(mBuf, sizeof(double), nGenes, mData) == nGenes) { processArray(); } } void processArray(bool aAverageMode = false) { uint32_t nNotNans = 0; if (mScramble) { boost::uniform_int<uint32_t> ui(0, nGenes - 1); for (uint32_t k = 0; k < nGenes; k++) { double t = mBuf[k]; uint32_t h = ui(mRand); mBuf[k] = mBuf[h]; mBuf[h] = t; } } for (uint32_t i = 0; i < nGenes; i++) { mInvRanks[i] = i; nNotNans += !!finite(mBuf[i]); } double rankInflationFactor = (nGenes + 0.0) / nNotNans; // Sort indices by value, with NaNs at the top. std::sort(mInvRanks, mInvRanks + nGenes, (bll::var(mBuf)[bll::_1] < bll::var(mBuf)[bll::_2]) || (bll::bind(finite, bll::var(mBuf)[bll::_1]) && !bll::bind(finite, bll::var(mBuf)[bll::_2]))); uint32_t i; if (aAverageMode) { for (i = 0; i < nGenes && finite(mBuf[mInvRanks[i]]); i++) { mRankAvgs[i] += mBuf[mInvRanks[i]]; mRankCounts[i]++; } } else { if (mQuantileNormalisation) { for (i = 0; i < nGenes && finite(mBuf[mInvRanks[i]]); i++) // We could put code in here to deal with tied ranks by putting in median // ranks, but I doubt it would make enough difference to justify it. mRanks[mInvRanks[i]] = mRankAvgs[i]; } else { for (i = 0; i < nGenes && finite(mBuf[mInvRanks[i]]); i++) // We could put code in here to deal with tied ranks by putting in median // ranks, but I doubt it would make enough difference to justify it. mRanks[mInvRanks[i]] = i * rankInflationFactor; } for (; i < nGenes; i++) mRanks[mInvRanks[i]] = std::numeric_limits<double>::quiet_NaN(); fwrite(mRanks, sizeof(double), nGenes, mOutputFile); } } }; int main(int argc, char** argv) { std::string matrixdir, outputfile; po::options_description desc; desc.add_options() ("matrixdir", po::value<std::string>(&matrixdir), "The directory to read the data from") ("use_inverse", "Use the inverted data-set instead of the original") ("scramble", "Scramble data prior to rank transform") ("output", po::value<std::string>(&outputfile), "The file to write the output into") ("qnorm", "If specified, causes quantile normalisation to be applied to the data") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); std::string wrong; if (!vm.count("help")) { if (!vm.count("matrixdir")) wrong = "matrixdir"; else if (!vm.count("output")) wrong = "output"; } if (wrong != "") std::cerr << "Missing option: " << wrong << std::endl; if (vm.count("help") || wrong != "") { std::cout << desc << std::endl; return 1; } if (!fs::is_directory(matrixdir)) { std::cerr << "Invalid matrix directory path supplied" << std::endl; return 1; } RankTransformer rt(matrixdir, outputfile, vm.count("qnorm") != 0, vm.count("use_inverse") != 0, vm.count("scramble") != 0); }
Fix a bug where we were counting the number of NaN values incorrectly
Fix a bug where we were counting the number of NaN values incorrectly
C++
agpl-3.0
A1kmm/soft2matrix
e4bf7bd52d468dae944ee64ed0cf17814e4c32c2
libraries/disp3D/engine/model/items/network/networktreeitem.cpp
libraries/disp3D/engine/model/items/network/networktreeitem.cpp
//============================================================================================================= /** * @file networktreeitem.cpp * @author Lorenz Esch <[email protected]>; * Matti Hamalainen <[email protected]> * @version 1.0 * @date January, 2016 * * @section LICENSE * * Copyright (C) 2016, Lorenz Esch and Matti Hamalainen. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that * the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of MNE-CPP authors nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * * @brief NetworkTreeItem class definition. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "networktreeitem.h" #include "../common/metatreeitem.h" #include "../../3dhelpers/renderable3Dentity.h" #include "../../materials/networkmaterial.h" #include "../../3dhelpers/custommesh.h" #include "../../3dhelpers/geometrymultiplier.h" #include "../../materials/geometrymultipliermaterial.h" #include <disp/plots/helpers/colormap.h> #include <connectivity/network/networknode.h> #include <connectivity/network/networkedge.h> #include <fiff/fiff_types.h> #include <mne/mne_sourceestimate.h> #include <mne/mne_forwardsolution.h> //************************************************************************************************************* //============================================================================================================= // Qt INCLUDES //============================================================================================================= #include <Qt3DExtras/QSphereGeometry> #include <Qt3DExtras/QCylinderGeometry> #include <Qt3DCore/QTransform> //************************************************************************************************************* //============================================================================================================= // Eigen INCLUDES //============================================================================================================= #include <Eigen/Core> //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace Eigen; using namespace MNELIB; using namespace DISP3DLIB; using namespace CONNECTIVITYLIB; using namespace DISPLIB; //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= NetworkTreeItem::NetworkTreeItem(Qt3DCore::QEntity *p3DEntityParent, int iType, const QString &text) : AbstractMeshTreeItem(p3DEntityParent, iType, text) { initItem(); } //************************************************************************************************************* void NetworkTreeItem::initItem() { this->setEditable(false); this->setCheckable(true); this->setCheckState(Qt::Checked); this->setToolTip("Network item"); //Add meta information as item children QList<QStandardItem*> list; QVariant data; QVector3D vecEdgeTrehshold(0,5,10); if(!m_pItemNetworkThreshold) { m_pItemNetworkThreshold = new MetaTreeItem(MetaTreeItemTypes::DataThreshold, QString("%1,%2,%3").arg(vecEdgeTrehshold.x()).arg(vecEdgeTrehshold.y()).arg(vecEdgeTrehshold.z())); } list << m_pItemNetworkThreshold; list << new QStandardItem(m_pItemNetworkThreshold->toolTip()); this->appendRow(list); data.setValue(vecEdgeTrehshold); m_pItemNetworkThreshold->setData(data, MetaTreeItemRoles::DataThreshold); connect(m_pItemNetworkThreshold.data(), &MetaTreeItem::dataChanged, this, &NetworkTreeItem::onNetworkThresholdChanged); list.clear(); MetaTreeItem* pItemNetworkMatrix = new MetaTreeItem(MetaTreeItemTypes::NetworkMatrix, "Show network matrix"); list << pItemNetworkMatrix; list << new QStandardItem(pItemNetworkMatrix->toolTip()); this->appendRow(list); //Set material NetworkMaterial* pNetworkMaterial = new NetworkMaterial(); this->setMaterial(pNetworkMaterial); } //************************************************************************************************************* void NetworkTreeItem::addData(const Network& tNetworkData) { //Add data which is held by this NetworkTreeItem QVariant data; Network tNetwork = tNetworkData; tNetwork.setThreshold(m_pItemNetworkThreshold->data(MetaTreeItemRoles::DataThreshold).value<QVector3D>().x()); data.setValue(tNetwork); this->setData(data, Data3DTreeModelItemRoles::Data); MatrixXd matDist = tNetwork.getFullConnectivityMatrix(); data.setValue(matDist); this->setData(data, Data3DTreeModelItemRoles::NetworkDataMatrix); //Plot network plotNetwork(tNetwork); } //************************************************************************************************************* void NetworkTreeItem::setThresholds(const QVector3D& vecThresholds) { if(m_pItemNetworkThreshold) { QVariant data; data.setValue(vecThresholds); m_pItemNetworkThreshold->setData(data, MetaTreeItemRoles::DataThreshold); QString sTemp = QString("%1,%2,%3").arg(vecThresholds.x()).arg(vecThresholds.y()).arg(vecThresholds.z()); data.setValue(sTemp); m_pItemNetworkThreshold->setData(data, Qt::DisplayRole); } } //************************************************************************************************************* void NetworkTreeItem::onNetworkThresholdChanged(const QVariant& vecThresholds) { if(vecThresholds.canConvert<QVector3D>()) { this->data(Data3DTreeModelItemRoles::Data).value<Network>().setThreshold(vecThresholds.value<QVector3D>().x()); Network tNetwork = this->data(Data3DTreeModelItemRoles::Data).value<Network>(); plotNetwork(tNetwork); } } //************************************************************************************************************* void NetworkTreeItem::plotNetwork(const Network& tNetworkData) { //Draw network nodes and edges plotNodes(tNetworkData); plotEdges(tNetworkData); } //************************************************************************************************************* void NetworkTreeItem::plotNodes(const Network& tNetworkData) { if(tNetworkData.isEmpty()) { qDebug() << "NetworkTreeItem::plotNodes - Network data is empty. Returning."; return; } QList<NetworkNode::SPtr> lNetworkNodes = tNetworkData.getNodes(); qint16 iMaxDegree = tNetworkData.getMinMaxThresholdedDegrees().second; if(!m_pNodesEntity) { m_pNodesEntity = new QEntity(this); } //create geometry if(!m_pEdges) { if(!m_pNodesGeometry) { m_pNodesGeometry = QSharedPointer<Qt3DExtras::QSphereGeometry>::create(); m_pNodesGeometry->setRadius(1.0f); } m_pNodes = new GeometryMultiplier(m_pNodesGeometry); m_pNodesEntity->addComponent(m_pNodes); //Add material GeometryMultiplierMaterial* pMaterial = new GeometryMultiplierMaterial(false); pMaterial->setAmbient(Qt::blue); pMaterial->setAlpha(1.0f); m_pNodesEntity->addComponent(pMaterial); } //Create transform matrix for each sphere instance QVector<QMatrix4x4> vTransforms; QVector<QColor> vColorsNodes; vTransforms.reserve(lNetworkNodes.size()); QVector3D tempPos; qint16 iDegree = 0; for(int i = 0; i < lNetworkNodes.size(); ++i) { iDegree = lNetworkNodes.at(i)->getThresholdedDegree(); if(iDegree != 0) { tempPos = QVector3D(lNetworkNodes.at(i)->getVert()(0), lNetworkNodes.at(i)->getVert()(1), lNetworkNodes.at(i)->getVert()(2)); //Set position and scale QMatrix4x4 tempTransform; \ tempTransform.translate(tempPos); tempTransform.scale(((float)iDegree/(float)iMaxDegree)*(0.005f-0.0006f)+0.0006f); vTransforms.push_back(tempTransform); if(iMaxDegree != 0.0f) { vColorsNodes.push_back(QColor(ColorMap::valueToHot((float)iDegree/(float)iMaxDegree))); } else { vColorsNodes.push_back(QColor(ColorMap::valueToHot(0.0f))); } } } //Set instance Transform and colors if(!vTransforms.isEmpty() && !vColorsNodes.isEmpty()) { m_pNodes->setTransforms(vTransforms); m_pNodes->setColors(vColorsNodes); } } //************************************************************************************************************* void NetworkTreeItem::plotEdges(const Network &tNetworkData) { if(tNetworkData.isEmpty()) { qDebug() << "NetworkTreeItem::plotEdges - Network data is empty. Returning."; return; } double dMaxWeight = tNetworkData.getMinMaxThresholdedWeights().second; QList<NetworkEdge::SPtr> lNetworkEdges = tNetworkData.getThresholdedEdges(); QList<NetworkNode::SPtr> lNetworkNodes = tNetworkData.getNodes(); if(!m_pEdgeEntity) { m_pEdgeEntity = new QEntity(this); } //create geometry if(!m_pEdges) { if(!m_pEdgesGeometry) { m_pEdgesGeometry = QSharedPointer<Qt3DExtras::QCylinderGeometry>::create(); m_pEdgesGeometry->setRadius(0.0005f); m_pEdgesGeometry->setLength(1.0f); } m_pEdges = new GeometryMultiplier(m_pEdgesGeometry); m_pEdgeEntity->addComponent(m_pEdges); //Add material GeometryMultiplierMaterial* pMaterial = new GeometryMultiplierMaterial(false); pMaterial->setAmbient(Qt::red); pMaterial->setAlpha(1.0f); m_pEdgeEntity->addComponent(pMaterial); } //Create transform matrix for each cylinder instance QVector<QMatrix4x4> vTransformsEdges; QVector<QColor> vColorsEdges; QVector3D startPos, endPos, edgePos, diff; double dWeight = 0.0f; int iStartID, iEndID; for(int i = 0; i < lNetworkEdges.size(); ++i) { //Plot in edges NetworkEdge::SPtr pNetworkEdge = lNetworkEdges.at(i); if(pNetworkEdge->isActive()) { iStartID = pNetworkEdge->getStartNodeID(); iEndID = pNetworkEdge->getEndNodeID(); RowVectorXf vectorStart = lNetworkNodes.at(iStartID)->getVert(); startPos = QVector3D(vectorStart(0), vectorStart(1), vectorStart(2)); RowVectorXf vectorEnd = lNetworkNodes.at(iEndID)->getVert(); endPos = QVector3D(vectorEnd(0), vectorEnd(1), vectorEnd(2)); if(startPos != endPos) { dWeight = pNetworkEdge->getWeight(); diff = endPos - startPos; edgePos = endPos - diff/2; QMatrix4x4 tempTransform; tempTransform.translate(edgePos); tempTransform.rotate(QQuaternion::rotationTo(QVector3D(0,1,0), diff.normalized()).normalized()); tempTransform.scale(1.0,diff.length(),1.0); vTransformsEdges.push_back(tempTransform); if(dMaxWeight != 0.0f) { vColorsEdges.push_back(QColor(ColorMap::valueToHot(dWeight/dMaxWeight))); } else { vColorsEdges.push_back(QColor(ColorMap::valueToHot(0.0f))); } } } } //Set instance transforms and colors if(!vTransformsEdges.isEmpty() && !vColorsEdges.isEmpty()) { m_pEdges->setTransforms(vTransformsEdges); m_pEdges->setColors(vColorsEdges); } }
//============================================================================================================= /** * @file networktreeitem.cpp * @author Lorenz Esch <[email protected]>; * Matti Hamalainen <[email protected]> * @version 1.0 * @date January, 2016 * * @section LICENSE * * Copyright (C) 2016, Lorenz Esch and Matti Hamalainen. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that * the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of MNE-CPP authors nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * * @brief NetworkTreeItem class definition. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "networktreeitem.h" #include "../common/metatreeitem.h" #include "../../3dhelpers/renderable3Dentity.h" #include "../../materials/networkmaterial.h" #include "../../3dhelpers/custommesh.h" #include "../../3dhelpers/geometrymultiplier.h" #include "../../materials/geometrymultipliermaterial.h" #include <disp/plots/helpers/colormap.h> #include <connectivity/network/networknode.h> #include <connectivity/network/networkedge.h> #include <fiff/fiff_types.h> #include <mne/mne_sourceestimate.h> #include <mne/mne_forwardsolution.h> //************************************************************************************************************* //============================================================================================================= // Qt INCLUDES //============================================================================================================= #include <Qt3DExtras/QSphereGeometry> #include <Qt3DExtras/QCylinderGeometry> #include <Qt3DCore/QTransform> //************************************************************************************************************* //============================================================================================================= // Eigen INCLUDES //============================================================================================================= #include <Eigen/Core> //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace Eigen; using namespace MNELIB; using namespace DISP3DLIB; using namespace CONNECTIVITYLIB; using namespace DISPLIB; //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= NetworkTreeItem::NetworkTreeItem(Qt3DCore::QEntity *p3DEntityParent, int iType, const QString &text) : AbstractMeshTreeItem(p3DEntityParent, iType, text) { initItem(); } //************************************************************************************************************* void NetworkTreeItem::initItem() { this->setEditable(false); this->setCheckable(true); this->setCheckState(Qt::Checked); this->setToolTip("Network item"); //Add meta information as item children QList<QStandardItem*> list; QVariant data; QVector3D vecEdgeTrehshold(0,5,10); if(!m_pItemNetworkThreshold) { m_pItemNetworkThreshold = new MetaTreeItem(MetaTreeItemTypes::DataThreshold, QString("%1,%2,%3").arg(vecEdgeTrehshold.x()).arg(vecEdgeTrehshold.y()).arg(vecEdgeTrehshold.z())); } list << m_pItemNetworkThreshold; list << new QStandardItem(m_pItemNetworkThreshold->toolTip()); this->appendRow(list); data.setValue(vecEdgeTrehshold); m_pItemNetworkThreshold->setData(data, MetaTreeItemRoles::DataThreshold); connect(m_pItemNetworkThreshold.data(), &MetaTreeItem::dataChanged, this, &NetworkTreeItem::onNetworkThresholdChanged); list.clear(); MetaTreeItem* pItemNetworkMatrix = new MetaTreeItem(MetaTreeItemTypes::NetworkMatrix, "Show network matrix"); list << pItemNetworkMatrix; list << new QStandardItem(pItemNetworkMatrix->toolTip()); this->appendRow(list); //Set material NetworkMaterial* pNetworkMaterial = new NetworkMaterial(); this->setMaterial(pNetworkMaterial); } //************************************************************************************************************* void NetworkTreeItem::addData(const Network& tNetworkData) { //Add data which is held by this NetworkTreeItem QVariant data; Network tNetwork = tNetworkData; tNetwork.setThreshold(m_pItemNetworkThreshold->data(MetaTreeItemRoles::DataThreshold).value<QVector3D>().x()); data.setValue(tNetwork); this->setData(data, Data3DTreeModelItemRoles::Data); MatrixXd matDist = tNetwork.getFullConnectivityMatrix(); data.setValue(matDist); this->setData(data, Data3DTreeModelItemRoles::NetworkDataMatrix); //Plot network plotNetwork(tNetwork); } //************************************************************************************************************* void NetworkTreeItem::setThresholds(const QVector3D& vecThresholds) { if(m_pItemNetworkThreshold) { QVariant data; data.setValue(vecThresholds); m_pItemNetworkThreshold->setData(data, MetaTreeItemRoles::DataThreshold); QString sTemp = QString("%1,%2,%3").arg(vecThresholds.x()).arg(vecThresholds.y()).arg(vecThresholds.z()); data.setValue(sTemp); m_pItemNetworkThreshold->setData(data, Qt::DisplayRole); } } //************************************************************************************************************* void NetworkTreeItem::onNetworkThresholdChanged(const QVariant& vecThresholds) { if(vecThresholds.canConvert<QVector3D>()) { this->data(Data3DTreeModelItemRoles::Data).value<Network>().setThreshold(vecThresholds.value<QVector3D>().x()); Network tNetwork = this->data(Data3DTreeModelItemRoles::Data).value<Network>(); plotNetwork(tNetwork); } } //************************************************************************************************************* void NetworkTreeItem::plotNetwork(const Network& tNetworkData) { //Draw network nodes and edges plotNodes(tNetworkData); plotEdges(tNetworkData); } //************************************************************************************************************* void NetworkTreeItem::plotNodes(const Network& tNetworkData) { if(tNetworkData.isEmpty()) { qDebug() << "NetworkTreeItem::plotNodes - Network data is empty. Returning."; return; } QList<NetworkNode::SPtr> lNetworkNodes = tNetworkData.getNodes(); qint16 iMaxDegree = tNetworkData.getMinMaxThresholdedDegrees().second; if(!m_pNodesEntity) { m_pNodesEntity = new QEntity(this); } //create geometry if(!m_pEdges) { if(!m_pNodesGeometry) { m_pNodesGeometry = QSharedPointer<Qt3DExtras::QSphereGeometry>::create(); m_pNodesGeometry->setRadius(1.0f); } m_pNodes = new GeometryMultiplier(m_pNodesGeometry); m_pNodesEntity->addComponent(m_pNodes); //Add material GeometryMultiplierMaterial* pMaterial = new GeometryMultiplierMaterial(false); pMaterial->setAmbient(ColorMap::valueToJet(0.0)); pMaterial->setAlpha(1.0f); m_pNodesEntity->addComponent(pMaterial); } //Create transform matrix for each sphere instance QVector<QMatrix4x4> vTransforms; QVector<QColor> vColorsNodes; vTransforms.reserve(lNetworkNodes.size()); QVector3D tempPos; qint16 iDegree = 0; for(int i = 0; i < lNetworkNodes.size(); ++i) { iDegree = lNetworkNodes.at(i)->getThresholdedDegree(); if(iDegree != 0) { tempPos = QVector3D(lNetworkNodes.at(i)->getVert()(0), lNetworkNodes.at(i)->getVert()(1), lNetworkNodes.at(i)->getVert()(2)); //Set position and scale QMatrix4x4 tempTransform; tempTransform.translate(tempPos); tempTransform.scale(((float)iDegree/(float)iMaxDegree)*(0.005f-0.0006f)+0.0006f); vTransforms.push_back(tempTransform); if(iMaxDegree != 0.0f) { vColorsNodes.push_back(QColor(ColorMap::valueToJet((float)iDegree/(float)iMaxDegree))); } else { vColorsNodes.push_back(QColor(ColorMap::valueToJet(0.0f))); } } } //Set instance Transform and colors if(!vTransforms.isEmpty() && !vColorsNodes.isEmpty()) { m_pNodes->setTransforms(vTransforms); m_pNodes->setColors(vColorsNodes); } } //************************************************************************************************************* void NetworkTreeItem::plotEdges(const Network &tNetworkData) { if(tNetworkData.isEmpty()) { qDebug() << "NetworkTreeItem::plotEdges - Network data is empty. Returning."; return; } double dMaxWeight = tNetworkData.getMinMaxThresholdedWeights().second; QList<NetworkEdge::SPtr> lNetworkEdges = tNetworkData.getThresholdedEdges(); QList<NetworkNode::SPtr> lNetworkNodes = tNetworkData.getNodes(); if(!m_pEdgeEntity) { m_pEdgeEntity = new QEntity(this); } //create geometry if(!m_pEdges) { if(!m_pEdgesGeometry) { m_pEdgesGeometry = QSharedPointer<Qt3DExtras::QCylinderGeometry>::create(); m_pEdgesGeometry->setRadius(0.0005f); m_pEdgesGeometry->setLength(1.0f); } m_pEdges = new GeometryMultiplier(m_pEdgesGeometry); m_pEdgeEntity->addComponent(m_pEdges); //Add material GeometryMultiplierMaterial* pMaterial = new GeometryMultiplierMaterial(false); pMaterial->setAmbient(ColorMap::valueToJet(0.0)); pMaterial->setAlpha(1.0f); m_pEdgeEntity->addComponent(pMaterial); } //Create transform matrix for each cylinder instance QVector<QMatrix4x4> vTransformsEdges; QVector<QColor> vColorsEdges; QVector3D startPos, endPos, edgePos, diff; double dWeight = 0.0f; int iStartID, iEndID; for(int i = 0; i < lNetworkEdges.size(); ++i) { //Plot in edges NetworkEdge::SPtr pNetworkEdge = lNetworkEdges.at(i); if(pNetworkEdge->isActive()) { iStartID = pNetworkEdge->getStartNodeID(); iEndID = pNetworkEdge->getEndNodeID(); RowVectorXf vectorStart = lNetworkNodes.at(iStartID)->getVert(); startPos = QVector3D(vectorStart(0), vectorStart(1), vectorStart(2)); RowVectorXf vectorEnd = lNetworkNodes.at(iEndID)->getVert(); endPos = QVector3D(vectorEnd(0), vectorEnd(1), vectorEnd(2)); if(startPos != endPos) { dWeight = pNetworkEdge->getWeight(); diff = endPos - startPos; edgePos = endPos - diff/2; QMatrix4x4 tempTransform; tempTransform.translate(edgePos); tempTransform.rotate(QQuaternion::rotationTo(QVector3D(0,1,0), diff.normalized()).normalized()); tempTransform.scale(1.0,diff.length(),1.0); vTransformsEdges.push_back(tempTransform); if(dMaxWeight != 0.0f) { vColorsEdges.push_back(QColor(ColorMap::valueToJet(dWeight/dMaxWeight))); } else { vColorsEdges.push_back(QColor(ColorMap::valueToJet(0.0f))); } } } } //Set instance transforms and colors if(!vTransformsEdges.isEmpty() && !vColorsEdges.isEmpty()) { m_pEdges->setTransforms(vTransformsEdges); m_pEdges->setColors(vColorsEdges); } }
Use colormap also for default edge and node colors
[SC-167] Use colormap also for default edge and node colors
C++
bsd-3-clause
mne-tools/mne-cpp,LorenzE/mne-cpp,chdinh/mne-cpp,chdinh/mne-cpp,mne-tools/mne-cpp,chdinh/mne-cpp,mne-tools/mne-cpp,mne-tools/mne-cpp,chdinh/mne-cpp,LorenzE/mne-cpp,mne-tools/mne-cpp,LorenzE/mne-cpp,LorenzE/mne-cpp,mne-tools/mne-cpp,chdinh/mne-cpp,chdinh/mne-cpp
15f6fbec666a6e6a45ae88a8bd1da0268bc882fc
Testing/Unit/sitkTransformTests.cxx
Testing/Unit/sitkTransformTests.cxx
/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "sitkTransform.h" #include "sitkAdditionalProcedures.h" #include "sitkResampleImageFilter.h" #include "sitkHashImageFilter.h" #include "SimpleITKTestHarness.h" namespace sitk = itk::simple; TEST(TransformTest, Construction) { sitk::Transform tx0( 2, sitk::sitkIdentity); std::cout << tx0.ToString() << std::endl; sitk::Transform tx1( 3, sitk::sitkIdentity); std::cout << tx1.ToString() << std::endl; sitk::Transform tx2( 2, sitk::sitkTranslation); std::cout << tx2.ToString() << std::endl; sitk::Transform tx3( 3, sitk::sitkTranslation); std::cout << tx3.ToString() << std::endl; sitk::Transform tx4( 2, sitk::sitkScale); std::cout << tx4.ToString() << std::endl; sitk::Transform tx5( 3, sitk::sitkScale); std::cout << tx5.ToString() << std::endl; sitk::Transform tx6( 2, sitk::sitkScaleLogarithmic); std::cout << tx6.ToString() << std::endl; sitk::Transform tx7( 3, sitk::sitkScaleLogarithmic); std::cout << tx7.ToString() << std::endl; sitk::Transform tx_0( 2, sitk::sitkEuler); std::cout << tx_0.ToString() << std::endl; sitk::Transform tx_1( 3, sitk::sitkEuler); std::cout << tx_1.ToString() << std::endl; sitk::Transform tx_2( 2, sitk::sitkSimilarity); std::cout << tx_2.ToString() << std::endl; sitk::Transform tx_3( 3, sitk::sitkSimilarity); std::cout << tx_3.ToString() << std::endl; EXPECT_ANY_THROW( sitk::Transform tx8( 2, sitk::sitkQuaternionRigid) ); sitk::Transform tx9( 3, sitk::sitkQuaternionRigid); std::cout << tx9.ToString() << std::endl; EXPECT_ANY_THROW( sitk::Transform tx10( 2, sitk::sitkVersor) ); sitk::Transform tx11( 3, sitk::sitkVersor); std::cout << tx11.ToString() << std::endl; EXPECT_ANY_THROW( sitk::Transform tx12( 2, sitk::sitkVersorRigid) ); sitk::Transform tx13( 3, sitk::sitkVersorRigid); std::cout << tx13.ToString() << std::endl; sitk::Transform tx14( 2, sitk::sitkAffine); std::cout << tx14.ToString() << std::endl; sitk::Transform tx15( 3, sitk::sitkAffine); std::cout << tx15.ToString() << std::endl; sitk::Transform tx16( 2, sitk::sitkAffine); std::cout << tx16.ToString() << std::endl; sitk::Transform tx17( 3, sitk::sitkAffine); std::cout << tx17.ToString() << std::endl; // default constructable sitk::Transform tx18; std::cout << tx18.ToString() << std::endl; // displacement fields sitk::Image displacement = sitk::Image( 100, 100, sitk::sitkVectorFloat64 ); sitk::Transform tx19( displacement ); std::cout << tx19.ToString() << std::endl; EXPECT_EQ( displacement.GetSize()[0], 0u ); EXPECT_EQ( displacement.GetSize()[1], 0u ); displacement = sitk::Image( 100,100, 100, sitk::sitkVectorFloat64 ); sitk::Transform tx20( displacement ); std::cout << tx20.ToString() << std::endl; EXPECT_EQ( displacement.GetSize()[0], 0u ); EXPECT_EQ( displacement.GetSize()[1], 0u ); EXPECT_EQ( displacement.GetSize()[2], 0u ); } TEST(TransformTest, Copy) { // Test the copy constructor and asignment operators sitk::Transform tx1( 2, sitk::sitkTranslation); sitk::Transform tx2( tx1 ); sitk::Transform tx3 = sitk::Transform(); tx1 = sitk::Transform(); tx2 = tx1; // check self assignment tx3 = tx3; } TEST(TransformTest, SetGetParameters) { sitk::Transform tx; EXPECT_TRUE( tx.GetParameters().empty() ); EXPECT_TRUE( tx.GetFixedParameters().empty() ); tx = sitk::Transform( 3, sitk::sitkTranslation ); EXPECT_EQ( tx.GetParameters().size(), 3u ); EXPECT_TRUE( tx.GetFixedParameters().empty() ); tx = sitk::Transform( 2, sitk::sitkScale ); EXPECT_EQ( tx.GetParameters().size(), 2u ); EXPECT_TRUE( tx.GetFixedParameters().empty() ); tx = sitk::Transform( 3, sitk::sitkScaleLogarithmic ); EXPECT_EQ( tx.GetParameters().size(), 3u ); EXPECT_TRUE( tx.GetFixedParameters().empty() ); tx = sitk::Transform( 2, sitk::sitkEuler ); EXPECT_EQ( tx.GetParameters().size(), 3u ); EXPECT_EQ( tx.GetFixedParameters().size(), 2u ); tx = sitk::Transform( 3, sitk::sitkEuler ); EXPECT_EQ( tx.GetParameters().size(), 6u ); EXPECT_EQ( tx.GetFixedParameters().size(), 3u ); tx = sitk::Transform( 2, sitk::sitkSimilarity ); EXPECT_EQ( tx.GetParameters().size(), 4u ); EXPECT_EQ( tx.GetFixedParameters().size(), 2u ); tx = sitk::Transform( 3, sitk::sitkSimilarity ); EXPECT_EQ( tx.GetParameters().size(), 7u ); EXPECT_EQ( tx.GetFixedParameters().size(), 3u ); tx = sitk::Transform( 3, sitk::sitkQuaternionRigid ); EXPECT_EQ( tx.GetParameters().size(), 7u ); EXPECT_EQ( tx.GetFixedParameters().size(), 3u ); tx = sitk::Transform( 3, sitk::sitkVersor ); EXPECT_EQ( tx.GetParameters().size(), 3u ); EXPECT_EQ( tx.GetFixedParameters().size(), 3u ); tx = sitk::Transform( 3, sitk::sitkVersorRigid ); EXPECT_EQ( tx.GetParameters().size(), 6u ); EXPECT_EQ( tx.GetFixedParameters().size(), 3u ); tx = sitk::Transform( 2, sitk::sitkAffine ); EXPECT_EQ( tx.GetParameters().size(), 6u ); EXPECT_EQ( tx.GetFixedParameters().size(), 2u ); sitk::Image displacement = sitk::Image( 10, 10, sitk::sitkVectorFloat64 ); tx = sitk::Transform ( displacement ); EXPECT_EQ( tx.GetParameters().size(), 200u ); EXPECT_EQ( tx.GetFixedParameters().size(), 10u ); displacement = sitk::Image( 10, 10, 10, sitk::sitkVectorFloat64 ); tx = sitk::Transform ( displacement ); EXPECT_EQ( tx.GetParameters().size(), 3000u ); EXPECT_EQ( tx.GetFixedParameters().size(), 18u ); } TEST(TransformTest, CopyOnWrite) { sitk::Transform tx1 = sitk::Transform( 2, sitk::sitkAffine ); sitk::Transform tx2 = tx1; sitk::Transform tx3 = tx1; std::vector<double> params = tx1.GetParameters(); params[1] = 0.2; tx2.SetParameters( params ); ASSERT_EQ( tx1.GetParameters().size(), 6u ); EXPECT_EQ( tx1.GetParameters()[1], 0.0 ); ASSERT_EQ( tx2.GetParameters().size(), 6u ); EXPECT_EQ( tx2.GetParameters()[1], 0.2 ); ASSERT_EQ( tx3.GetParameters().size(), 6u ); EXPECT_EQ( tx3.GetParameters()[1], 0.0 ); params[1] = 0.3; tx3.SetParameters( params ); ASSERT_EQ( tx1.GetParameters().size(), 6u ); EXPECT_EQ( tx1.GetParameters()[1], 0.0 ); ASSERT_EQ( tx2.GetParameters().size(), 6u ); EXPECT_EQ( tx2.GetParameters()[1], 0.2 ); ASSERT_EQ( tx3.GetParameters().size(), 6u ); EXPECT_EQ( tx3.GetParameters()[1], 0.3 ); tx1 = tx2; ASSERT_EQ( tx1.GetParameters().size(), 6u ); EXPECT_EQ( tx1.GetParameters()[1], 0.2 ); ASSERT_EQ( tx2.GetParameters().size(), 6u ); EXPECT_EQ( tx2.GetParameters()[1], 0.2 ); ASSERT_EQ( tx3.GetParameters().size(), 6u ); EXPECT_EQ( tx3.GetParameters()[1], 0.3 ); params[1] = 0.4; tx1.SetParameters( params ); ASSERT_EQ( tx1.GetParameters().size(), 6u ); EXPECT_EQ( tx1.GetParameters()[1], 0.4 ); ASSERT_EQ( tx2.GetParameters().size(), 6u ); EXPECT_EQ( tx2.GetParameters()[1], 0.2 ); ASSERT_EQ( tx3.GetParameters().size(), 6u ); EXPECT_EQ( tx3.GetParameters()[1], 0.3 ); } TEST(TransformTest, AddTransform) { sitk::Transform tx1 = sitk::Transform( 2, sitk::sitkAffine ); tx1.AddTransform( sitk::Transform( 2, sitk::sitkAffine ) ); // check we can't add miss match dimension ASSERT_ANY_THROW( tx1.AddTransform( sitk::Transform( 3, sitk::sitkAffine ) ) ); sitk::Transform tx2 = tx1; tx1.AddTransform( sitk::Transform( 2, sitk::sitkIdentity ) ); sitk::Transform tx3( 3, sitk::sitkComposite ); tx1 = tx3; tx3.AddTransform( sitk::Transform( 3, sitk::sitkAffine ) ); } TEST(TransformTest, ReadTransformResample) { const char *txFiles[] = { "Input/xforms/affine_i_3.txt", "Input/xforms/composite_i_3.txt", "Input/xforms/i_3.txt", "Input/xforms/scale_i_3.txt", "Input/xforms/translation_i_3.txt", "Input/xforms/quaternion_rigid_i_3.txt", "Input/xforms/scale_logarithmic_i_3.txt", "Input/xforms/versor_i_3.txt", "" // end with zero length string }; sitk::Transform tx; sitk::Image img = sitk::ReadImage( dataFinder.GetFile("Input/RA-Short.nrrd" ) ); const char **ptxFiles = txFiles; while( strlen( *ptxFiles ) != 0 ) { std::string fname = dataFinder.GetFile( *ptxFiles ); std::cout << "Reading: " << *ptxFiles << std::endl; EXPECT_NO_THROW( tx = sitk::ReadTransform( fname ) ); sitk::Image out = sitk::Resample( img, tx, sitk::sitkNearestNeighbor ); EXPECT_EQ( "126ea8c3ef5573ca1e4e0deece920c2c4a4f38b5", sitk::Hash( out ) ) << "Resampling with identity matrix:" << tx.ToString(); ++ptxFiles; } } TEST(TransformTest, TransformPoint) { sitk::Transform tx2 = sitk::Transform( 2, sitk::sitkIdentity ); sitk::Transform tx3 = sitk::Transform( 3, sitk::sitkIdentity ); std::vector<double> ipt; ipt.push_back( 1.1 ); ipt.push_back( 2.22 ); std::vector<double> opt; opt = tx2.TransformPoint( ipt ); ASSERT_EQ( opt.size(), 2u ); EXPECT_EQ( opt[0], 1.1 ); EXPECT_EQ( opt[1], 2.22 ); EXPECT_ANY_THROW( tx3.TransformPoint( ipt ) ); ipt.push_back( 3.333 ); EXPECT_ANY_THROW( opt = tx2.TransformPoint( ipt ) ); ASSERT_EQ( opt.size(), 2u ); EXPECT_EQ( opt[0], 1.1 ); EXPECT_EQ( opt[1], 2.22 ); opt = tx3.TransformPoint( ipt ); ASSERT_EQ( opt.size(), 3u ); EXPECT_EQ( opt[0], 1.1 ); EXPECT_EQ( opt[1], 2.22 ); EXPECT_EQ( opt[2], 3.333 ); }
/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "sitkTransform.h" #include "sitkAdditionalProcedures.h" #include "sitkResampleImageFilter.h" #include "sitkHashImageFilter.h" #include "SimpleITKTestHarness.h" namespace sitk = itk::simple; TEST(TransformTest, Construction) { sitk::Transform tx0( 2, sitk::sitkIdentity); std::cout << tx0.ToString() << std::endl; sitk::Transform tx1( 3, sitk::sitkIdentity); std::cout << tx1.ToString() << std::endl; sitk::Transform tx2( 2, sitk::sitkTranslation); std::cout << tx2.ToString() << std::endl; sitk::Transform tx3( 3, sitk::sitkTranslation); std::cout << tx3.ToString() << std::endl; sitk::Transform tx4( 2, sitk::sitkScale); std::cout << tx4.ToString() << std::endl; sitk::Transform tx5( 3, sitk::sitkScale); std::cout << tx5.ToString() << std::endl; sitk::Transform tx6( 2, sitk::sitkScaleLogarithmic); std::cout << tx6.ToString() << std::endl; sitk::Transform tx7( 3, sitk::sitkScaleLogarithmic); std::cout << tx7.ToString() << std::endl; sitk::Transform tx_0( 2, sitk::sitkEuler); std::cout << tx_0.ToString() << std::endl; sitk::Transform tx_1( 3, sitk::sitkEuler); std::cout << tx_1.ToString() << std::endl; sitk::Transform tx_2( 2, sitk::sitkSimilarity); std::cout << tx_2.ToString() << std::endl; sitk::Transform tx_3( 3, sitk::sitkSimilarity); std::cout << tx_3.ToString() << std::endl; EXPECT_ANY_THROW( sitk::Transform tx8( 2, sitk::sitkQuaternionRigid) ); sitk::Transform tx9( 3, sitk::sitkQuaternionRigid); std::cout << tx9.ToString() << std::endl; EXPECT_ANY_THROW( sitk::Transform tx10( 2, sitk::sitkVersor) ); sitk::Transform tx11( 3, sitk::sitkVersor); std::cout << tx11.ToString() << std::endl; EXPECT_ANY_THROW( sitk::Transform tx12( 2, sitk::sitkVersorRigid) ); sitk::Transform tx13( 3, sitk::sitkVersorRigid); std::cout << tx13.ToString() << std::endl; sitk::Transform tx14( 2, sitk::sitkAffine); std::cout << tx14.ToString() << std::endl; sitk::Transform tx15( 3, sitk::sitkAffine); std::cout << tx15.ToString() << std::endl; sitk::Transform tx16( 2, sitk::sitkAffine); std::cout << tx16.ToString() << std::endl; sitk::Transform tx17( 3, sitk::sitkAffine); std::cout << tx17.ToString() << std::endl; // default constructable sitk::Transform tx18; std::cout << tx18.ToString() << std::endl; // displacement fields sitk::Image displacement = sitk::Image( 100, 100, sitk::sitkVectorFloat64 ); sitk::Transform tx19( displacement ); std::cout << tx19.ToString() << std::endl; EXPECT_EQ( displacement.GetSize()[0], 0u ); EXPECT_EQ( displacement.GetSize()[1], 0u ); displacement = sitk::Image( 100,100, 100, sitk::sitkVectorFloat64 ); sitk::Transform tx20( displacement ); std::cout << tx20.ToString() << std::endl; EXPECT_EQ( displacement.GetSize()[0], 0u ); EXPECT_EQ( displacement.GetSize()[1], 0u ); } TEST(TransformTest, Copy) { // Test the copy constructor and asignment operators sitk::Transform tx1( 2, sitk::sitkTranslation); sitk::Transform tx2( tx1 ); sitk::Transform tx3 = sitk::Transform(); tx1 = sitk::Transform(); tx2 = tx1; // check self assignment tx3 = tx3; } TEST(TransformTest, SetGetParameters) { sitk::Transform tx; EXPECT_TRUE( tx.GetParameters().empty() ); EXPECT_TRUE( tx.GetFixedParameters().empty() ); tx = sitk::Transform( 3, sitk::sitkTranslation ); EXPECT_EQ( tx.GetParameters().size(), 3u ); EXPECT_TRUE( tx.GetFixedParameters().empty() ); tx = sitk::Transform( 2, sitk::sitkScale ); EXPECT_EQ( tx.GetParameters().size(), 2u ); EXPECT_TRUE( tx.GetFixedParameters().empty() ); tx = sitk::Transform( 3, sitk::sitkScaleLogarithmic ); EXPECT_EQ( tx.GetParameters().size(), 3u ); EXPECT_TRUE( tx.GetFixedParameters().empty() ); tx = sitk::Transform( 2, sitk::sitkEuler ); EXPECT_EQ( tx.GetParameters().size(), 3u ); EXPECT_EQ( tx.GetFixedParameters().size(), 2u ); tx = sitk::Transform( 3, sitk::sitkEuler ); EXPECT_EQ( tx.GetParameters().size(), 6u ); EXPECT_EQ( tx.GetFixedParameters().size(), 3u ); tx = sitk::Transform( 2, sitk::sitkSimilarity ); EXPECT_EQ( tx.GetParameters().size(), 4u ); EXPECT_EQ( tx.GetFixedParameters().size(), 2u ); tx = sitk::Transform( 3, sitk::sitkSimilarity ); EXPECT_EQ( tx.GetParameters().size(), 7u ); EXPECT_EQ( tx.GetFixedParameters().size(), 3u ); tx = sitk::Transform( 3, sitk::sitkQuaternionRigid ); EXPECT_EQ( tx.GetParameters().size(), 7u ); EXPECT_EQ( tx.GetFixedParameters().size(), 3u ); tx = sitk::Transform( 3, sitk::sitkVersor ); EXPECT_EQ( tx.GetParameters().size(), 3u ); EXPECT_EQ( tx.GetFixedParameters().size(), 3u ); tx = sitk::Transform( 3, sitk::sitkVersorRigid ); EXPECT_EQ( tx.GetParameters().size(), 6u ); EXPECT_EQ( tx.GetFixedParameters().size(), 3u ); tx = sitk::Transform( 2, sitk::sitkAffine ); EXPECT_EQ( tx.GetParameters().size(), 6u ); EXPECT_EQ( tx.GetFixedParameters().size(), 2u ); sitk::Image displacement = sitk::Image( 10, 10, sitk::sitkVectorFloat64 ); tx = sitk::Transform ( displacement ); EXPECT_EQ( tx.GetParameters().size(), 200u ); EXPECT_EQ( tx.GetFixedParameters().size(), 10u ); displacement = sitk::Image( 10, 10, 10, sitk::sitkVectorFloat64 ); tx = sitk::Transform ( displacement ); EXPECT_EQ( tx.GetParameters().size(), 3000u ); EXPECT_EQ( tx.GetFixedParameters().size(), 18u ); } TEST(TransformTest, CopyOnWrite) { sitk::Transform tx1 = sitk::Transform( 2, sitk::sitkAffine ); sitk::Transform tx2 = tx1; sitk::Transform tx3 = tx1; std::vector<double> params = tx1.GetParameters(); params[1] = 0.2; tx2.SetParameters( params ); ASSERT_EQ( tx1.GetParameters().size(), 6u ); EXPECT_EQ( tx1.GetParameters()[1], 0.0 ); ASSERT_EQ( tx2.GetParameters().size(), 6u ); EXPECT_EQ( tx2.GetParameters()[1], 0.2 ); ASSERT_EQ( tx3.GetParameters().size(), 6u ); EXPECT_EQ( tx3.GetParameters()[1], 0.0 ); params[1] = 0.3; tx3.SetParameters( params ); ASSERT_EQ( tx1.GetParameters().size(), 6u ); EXPECT_EQ( tx1.GetParameters()[1], 0.0 ); ASSERT_EQ( tx2.GetParameters().size(), 6u ); EXPECT_EQ( tx2.GetParameters()[1], 0.2 ); ASSERT_EQ( tx3.GetParameters().size(), 6u ); EXPECT_EQ( tx3.GetParameters()[1], 0.3 ); tx1 = tx2; ASSERT_EQ( tx1.GetParameters().size(), 6u ); EXPECT_EQ( tx1.GetParameters()[1], 0.2 ); ASSERT_EQ( tx2.GetParameters().size(), 6u ); EXPECT_EQ( tx2.GetParameters()[1], 0.2 ); ASSERT_EQ( tx3.GetParameters().size(), 6u ); EXPECT_EQ( tx3.GetParameters()[1], 0.3 ); params[1] = 0.4; tx1.SetParameters( params ); ASSERT_EQ( tx1.GetParameters().size(), 6u ); EXPECT_EQ( tx1.GetParameters()[1], 0.4 ); ASSERT_EQ( tx2.GetParameters().size(), 6u ); EXPECT_EQ( tx2.GetParameters()[1], 0.2 ); ASSERT_EQ( tx3.GetParameters().size(), 6u ); EXPECT_EQ( tx3.GetParameters()[1], 0.3 ); } TEST(TransformTest, AddTransform) { sitk::Transform tx1 = sitk::Transform( 2, sitk::sitkAffine ); tx1.AddTransform( sitk::Transform( 2, sitk::sitkAffine ) ); // check we can't add miss match dimension ASSERT_ANY_THROW( tx1.AddTransform( sitk::Transform( 3, sitk::sitkAffine ) ) ); sitk::Transform tx2 = tx1; tx1.AddTransform( sitk::Transform( 2, sitk::sitkIdentity ) ); sitk::Transform tx3( 3, sitk::sitkComposite ); tx1 = tx3; tx3.AddTransform( sitk::Transform( 3, sitk::sitkAffine ) ); } TEST(TransformTest, ReadTransformResample) { const char *txFiles[] = { "Input/xforms/affine_i_3.txt", "Input/xforms/composite_i_3.txt", "Input/xforms/i_3.txt", "Input/xforms/scale_i_3.txt", "Input/xforms/translation_i_3.txt", "Input/xforms/quaternion_rigid_i_3.txt", "Input/xforms/scale_logarithmic_i_3.txt", "Input/xforms/versor_i_3.txt", "" // end with zero length string }; sitk::Transform tx; sitk::Image img = sitk::ReadImage( dataFinder.GetFile("Input/RA-Short.nrrd" ) ); const char **ptxFiles = txFiles; while( strlen( *ptxFiles ) != 0 ) { std::string fname = dataFinder.GetFile( *ptxFiles ); std::cout << "Reading: " << *ptxFiles << std::endl; EXPECT_NO_THROW( tx = sitk::ReadTransform( fname ) ); sitk::Image out = sitk::Resample( img, tx, sitk::sitkNearestNeighbor ); EXPECT_EQ( "126ea8c3ef5573ca1e4e0deece920c2c4a4f38b5", sitk::Hash( out ) ) << "Resampling with identity matrix:" << tx.ToString(); ++ptxFiles; } } TEST(TransformTest, TransformPoint) { sitk::Transform tx2 = sitk::Transform( 2, sitk::sitkIdentity ); sitk::Transform tx3 = sitk::Transform( 3, sitk::sitkIdentity ); std::vector<double> ipt; ipt.push_back( 1.1 ); ipt.push_back( 2.22 ); std::vector<double> opt; opt = tx2.TransformPoint( ipt ); ASSERT_EQ( opt.size(), 2u ); EXPECT_EQ( opt[0], 1.1 ); EXPECT_EQ( opt[1], 2.22 ); EXPECT_ANY_THROW( tx3.TransformPoint( ipt ) ); ipt.push_back( 3.333 ); EXPECT_ANY_THROW( opt = tx2.TransformPoint( ipt ) ); ASSERT_EQ( opt.size(), 2u ); EXPECT_EQ( opt[0], 1.1 ); EXPECT_EQ( opt[1], 2.22 ); opt = tx3.TransformPoint( ipt ); ASSERT_EQ( opt.size(), 3u ); EXPECT_EQ( opt[0], 1.1 ); EXPECT_EQ( opt[1], 2.22 ); EXPECT_EQ( opt[2], 3.333 ); }
fix expected test results
fix expected test results Default constructed images are only 2D. Comparison of z size is not valid. Change-Id: I49313e4447f78b14fdbd45523c149ab21c1d8b80
C++
apache-2.0
kaspermarstal/SimpleElastix,blowekamp/SimpleITK,blowekamp/SimpleITK,InsightSoftwareConsortium/SimpleITK,kaspermarstal/SimpleElastix,richardbeare/SimpleITK,hendradarwin/SimpleITK,hendradarwin/SimpleITK,blowekamp/SimpleITK,richardbeare/SimpleITK,InsightSoftwareConsortium/SimpleITK,InsightSoftwareConsortium/SimpleITK,SimpleITK/SimpleITK,hendradarwin/SimpleITK,hendradarwin/SimpleITK,SimpleITK/SimpleITK,blowekamp/SimpleITK,kaspermarstal/SimpleElastix,SimpleITK/SimpleITK,blowekamp/SimpleITK,blowekamp/SimpleITK,InsightSoftwareConsortium/SimpleITK,SimpleITK/SimpleITK,SimpleITK/SimpleITK,hendradarwin/SimpleITK,InsightSoftwareConsortium/SimpleITK,hendradarwin/SimpleITK,hendradarwin/SimpleITK,blowekamp/SimpleITK,InsightSoftwareConsortium/SimpleITK,richardbeare/SimpleITK,richardbeare/SimpleITK,SimpleITK/SimpleITK,InsightSoftwareConsortium/SimpleITK,richardbeare/SimpleITK,kaspermarstal/SimpleElastix,richardbeare/SimpleITK,kaspermarstal/SimpleElastix,richardbeare/SimpleITK,richardbeare/SimpleITK,InsightSoftwareConsortium/SimpleITK,kaspermarstal/SimpleElastix,blowekamp/SimpleITK,SimpleITK/SimpleITK,kaspermarstal/SimpleElastix,SimpleITK/SimpleITK,hendradarwin/SimpleITK
527a0b774f69d31403381cc57d043fdd981d229b
UsbDkController/UsbDkController.cpp
UsbDkController/UsbDkController.cpp
// UsbDkController.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "UsbDkHelper.h" using namespace std; //------------------------------------------------------------------------------- void ShowUsage() { tcout << endl; tcout << TEXT(" UsbDkController usage:") << endl; tcout << endl; tcout << TEXT("UsbDkController -i - install UsbDk driver") << endl; tcout << TEXT("UsbDkController -u - uninstall UsbDk driver") << endl; tcout << TEXT("UsbDkController -n - enumerate USB devices") << endl; tcout << TEXT("UsbDkController -r ID SN - Redirect USB device (start-stop) by ID and serial number") << endl; tcout << endl; } //------------------------------------------------------------------------------- void Controller_InstallDriver() { tcout << TEXT("Installing UsbDk driver") << endl; auto res = InstallDriver(); switch (res) { case InstallSuccess: tcout << TEXT("UsbDk driver installation succeeded") << endl; break; case InstallFailure: tcout << TEXT("UsbDk driver installation failed") << endl; break; case InstallFailureNeedReboot: tcout << TEXT("UsbDk driver installation failed. Reboot your machine") << endl; break; default: tcout << TEXT("UsbDk driver installation returns unknown value") << endl; assert(0); } } //------------------------------------------------------------------------------- void Controller_UninstallDriver() { tcout << TEXT("Uninstalling UsbDk driver") << endl; if (UninstallDriver()) { tcout << TEXT("UsbDk driver uninstall succeeded") << endl; } else { tcout << TEXT("UsbDk driver uninstall failed") << endl; } } //------------------------------------------------------------------------------- static void Controller_DumpConfigurationDescriptors(USB_DK_DEVICE_INFO &Device) { for (UCHAR i = 0; i < Device.DeviceDescriptor.bNumConfigurations; i++) { USB_DK_CONFIG_DESCRIPTOR_REQUEST Request; Request.ID = Device.ID; Request.Index = i; PUSB_CONFIGURATION_DESCRIPTOR Descriptor; ULONG Length; if (!GetConfigurationDescriptor(&Request, &Descriptor, &Length)) { tcout << TEXT("Failed to read configuration descriptor #") << (int) i << endl; } else { tcout << TEXT("Descriptor for configuration #") << (int) i << TEXT(": size ") << Length << endl; ReleaseConfigurationDescriptor(Descriptor); } } } //------------------------------------------------------------------------------- void Controller_EnumerateDevices() { PUSB_DK_DEVICE_INFO devicesArray; ULONG numberDevices; tcout << TEXT("Enumerate USB devices") << endl; if (GetDevicesList(&devicesArray, &numberDevices)) { tcout << TEXT("Found ") << to_tstring(numberDevices) << TEXT(" USB devices:") << endl; for (ULONG deviceIndex = 0; deviceIndex < numberDevices; ++deviceIndex) { auto &Dev = devicesArray[deviceIndex]; tcout << to_tstring(deviceIndex) << TEXT(". ") << TEXT("FilterID: ") << Dev.FilterID << TEXT(", ") << TEXT("Port: ") << Dev.Port << TEXT(", ") << TEXT("ID: ") << hex << setw(4) << setfill(L'0') << static_cast<int>(Dev.DeviceDescriptor.idVendor) << TEXT(":") << setw(4) << setfill(L'0') << static_cast<int>(Dev.DeviceDescriptor.idProduct) << TEXT(", ") << dec << TEXT("Configurations: ") << static_cast<int>(Dev.DeviceDescriptor.bNumConfigurations) << TEXT(" ") << Dev.ID.DeviceID << TEXT(" ") << Dev.ID.InstanceID << endl; Controller_DumpConfigurationDescriptors(Dev); } ReleaseDeviceList(devicesArray); } else { tcout << TEXT("Enumeration failed") << endl; } } //------------------------------------------------------------------------------- void Controller_RedirectDevice(_TCHAR *DeviceID, _TCHAR *InstanceID) { USB_DK_DEVICE_ID deviceID; UsbDkFillIDStruct(&deviceID, tstring2wstring(DeviceID), tstring2wstring(InstanceID)); tcout << TEXT("Redirect USB device ") << deviceID.DeviceID << TEXT(", ") << deviceID.InstanceID << endl; HANDLE redirectedDevice = StartRedirect(&deviceID); if (nullptr == redirectedDevice) { tcout << TEXT("Redirect of USB device failed") << endl; return; } tcout << TEXT("USB device was redirected successfully. Redirected device handle = ") << redirectedDevice << endl; tcout << TEXT("Press some key to stop redirection"); getchar(); // STOP redirect tcout << TEXT("Restore USB device ") << redirectedDevice << endl; if (TRUE == StopRedirect(redirectedDevice)) { tcout << TEXT("USB device redirection was stopped successfully.") << endl; } else { tcout << TEXT("Stopping of USB device redirection failed.") << endl; } } //------------------------------------------------------------------------------- int __cdecl _tmain(int argc, _TCHAR* argv[]) { if (argc > 1) { if (_tcsicmp(L"-i", argv[1]) == 0) { Controller_InstallDriver(); } else if (_tcsicmp(L"-u", argv[1]) == 0) { Controller_UninstallDriver(); } else if (_tcsicmp(L"-n", argv[1]) == 0) { Controller_EnumerateDevices(); } else if (_tcsicmp(L"-r", argv[1]) == 0) { if (argc < 4) { ShowUsage(); return 0; } Controller_RedirectDevice(argv[2], argv[3]); } else { ShowUsage(); } } else { ShowUsage(); } return 0; } //-------------------------------------------------------------------------------
// UsbDkController.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "UsbDkHelper.h" using namespace std; //------------------------------------------------------------------------------- void ShowUsage() { tcout << endl; tcout << TEXT(" UsbDkController usage:") << endl; tcout << endl; tcout << TEXT("UsbDkController -i - install UsbDk driver") << endl; tcout << TEXT("UsbDkController -u - uninstall UsbDk driver") << endl; tcout << TEXT("UsbDkController -n - enumerate USB devices") << endl; tcout << TEXT("UsbDkController -r ID SN - Redirect USB device (start-stop) by ID and serial number") << endl; tcout << endl; } //------------------------------------------------------------------------------- void Controller_InstallDriver() { tcout << TEXT("Installing UsbDk driver") << endl; auto res = InstallDriver(); switch (res) { case InstallSuccess: tcout << TEXT("UsbDk driver installation succeeded") << endl; break; case InstallFailure: tcout << TEXT("UsbDk driver installation failed") << endl; break; case InstallFailureNeedReboot: tcout << TEXT("UsbDk driver installation failed. Reboot your machine") << endl; break; default: tcout << TEXT("UsbDk driver installation returns unknown value") << endl; assert(0); } } //------------------------------------------------------------------------------- void Controller_UninstallDriver() { tcout << TEXT("Uninstalling UsbDk driver") << endl; if (UninstallDriver()) { tcout << TEXT("UsbDk driver uninstall succeeded") << endl; } else { tcout << TEXT("UsbDk driver uninstall failed") << endl; } } //------------------------------------------------------------------------------- static void Controller_DumpConfigurationDescriptors(USB_DK_DEVICE_INFO &Device) { for (UCHAR i = 0; i < Device.DeviceDescriptor.bNumConfigurations; i++) { USB_DK_CONFIG_DESCRIPTOR_REQUEST Request; Request.ID = Device.ID; Request.Index = i; PUSB_CONFIGURATION_DESCRIPTOR Descriptor; ULONG Length; if (!GetConfigurationDescriptor(&Request, &Descriptor, &Length)) { tcout << TEXT("Failed to read configuration descriptor #") << (int) i << endl; } else { tcout << TEXT("Descriptor for configuration #") << (int) i << TEXT(": size ") << Length << endl; ReleaseConfigurationDescriptor(Descriptor); } } } //------------------------------------------------------------------------------- void Controller_EnumerateDevices() { PUSB_DK_DEVICE_INFO devicesArray; ULONG numberDevices; tcout << TEXT("Enumerate USB devices") << endl; if (GetDevicesList(&devicesArray, &numberDevices)) { tcout << TEXT("Found ") << to_tstring(numberDevices) << TEXT(" USB devices:") << endl; for (ULONG deviceIndex = 0; deviceIndex < numberDevices; ++deviceIndex) { auto &Dev = devicesArray[deviceIndex]; tcout << to_tstring(deviceIndex) << TEXT(". ") << TEXT("FilterID: ") << Dev.FilterID << TEXT(", ") << TEXT("Port: ") << Dev.Port << TEXT(", ") << TEXT("ID: ") << hex << setw(4) << setfill(L'0') << static_cast<int>(Dev.DeviceDescriptor.idVendor) << TEXT(":") << setw(4) << setfill(L'0') << static_cast<int>(Dev.DeviceDescriptor.idProduct) << TEXT(", ") << dec << TEXT("Configurations: ") << static_cast<int>(Dev.DeviceDescriptor.bNumConfigurations) << TEXT(" ") << Dev.ID.DeviceID << TEXT(" ") << Dev.ID.InstanceID << endl; Controller_DumpConfigurationDescriptors(Dev); } ReleaseDeviceList(devicesArray); } else { tcout << TEXT("Enumeration failed") << endl; } } //------------------------------------------------------------------------------- void Controller_RedirectDevice(_TCHAR *DeviceID, _TCHAR *InstanceID) { USB_DK_DEVICE_ID deviceID; UsbDkFillIDStruct(&deviceID, tstring2wstring(DeviceID), tstring2wstring(InstanceID)); tcout << TEXT("Redirect USB device ") << deviceID.DeviceID << TEXT(", ") << deviceID.InstanceID << endl; HANDLE redirectedDevice = StartRedirect(&deviceID); if (INVALID_HANDLE_VALUE == redirectedDevice) { tcout << TEXT("Redirect of USB device failed") << endl; return; } tcout << TEXT("USB device was redirected successfully. Redirected device handle = ") << redirectedDevice << endl; tcout << TEXT("Press some key to stop redirection"); getchar(); // STOP redirect tcout << TEXT("Restore USB device ") << redirectedDevice << endl; if (TRUE == StopRedirect(redirectedDevice)) { tcout << TEXT("USB device redirection was stopped successfully.") << endl; } else { tcout << TEXT("Stopping of USB device redirection failed.") << endl; } } //------------------------------------------------------------------------------- int __cdecl _tmain(int argc, _TCHAR* argv[]) { if (argc > 1) { if (_tcsicmp(L"-i", argv[1]) == 0) { Controller_InstallDriver(); } else if (_tcsicmp(L"-u", argv[1]) == 0) { Controller_UninstallDriver(); } else if (_tcsicmp(L"-n", argv[1]) == 0) { Controller_EnumerateDevices(); } else if (_tcsicmp(L"-r", argv[1]) == 0) { if (argc < 4) { ShowUsage(); return 0; } Controller_RedirectDevice(argv[2], argv[3]); } else { ShowUsage(); } } else { ShowUsage(); } return 0; } //-------------------------------------------------------------------------------
Handle start redirect return value properly
UsbDkController: Handle start redirect return value properly Signed-off-by: Dmitry Fleytman <[email protected]>
C++
apache-2.0
SPICE/win32-usbdk,daynix/UsbDk,freedesktop-unofficial-mirror/spice__win32__usbdk,freedesktop-unofficial-mirror/spice__win32__usbdk,daynix/UsbDk,freedesktop-unofficial-mirror/spice__win32__usbdk,SPICE/win32-usbdk
4d0777d42e1177055d38a51b74c582682c04ae64
kaddressbook/imagewidget.cpp
kaddressbook/imagewidget.cpp
/* This file is part of KAddressBook. Copyright (c) 2003 Tobias Koenig <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <kabc/picture.h> #include <kdebug.h> #include <kdialog.h> #include <kglobalsettings.h> #include <kiconloader.h> #include <kimageio.h> #include <kio/netaccess.h> #include <klocale.h> #include <kmessagebox.h> #include <kurlrequester.h> #include <kpixmapregionselectordialog.h> #include <syndication/loader.h> #include <syndication/feed.h> #include <syndication/image.h> #include <QApplication> #include <QCheckBox> #include <q3groupbox.h> #include <QLabel> #include <QLayout> #include <QPixmap> #include <QGridLayout> #include <QFrame> #include <QHBoxLayout> #include <QDropEvent> #include <QDragEnterEvent> #include <QMouseEvent> #include "imagewidget.h" ImageLabel::ImageLabel( const QString &title, QWidget *parent ) : QLabel( title, parent ), mReadOnly( false ) { setAcceptDrops( true ); } void ImageLabel::setReadOnly( bool readOnly ) { mReadOnly = readOnly; } void ImageLabel::startDrag() { if ( pixmap() && !pixmap()->isNull() ) { QDrag *drag = new QDrag( this ); drag->setMimeData( new QMimeData() ); drag->mimeData()->setImageData( pixmap()->toImage() ); drag->start(); } } void ImageLabel::dragEnterEvent( QDragEnterEvent *event ) { const QMimeData *md = event->mimeData(); event->setAccepted( md->hasImage() || md->hasUrls()); } void ImageLabel::dropEvent( QDropEvent *event ) { if ( mReadOnly ) return; const QMimeData *md = event->mimeData(); if ( md->hasImage() ) { QImage image = qvariant_cast<QImage>(md->imageData()); setPixmap( QPixmap::fromImage( image ) ); emit changed(); } KUrl::List urls = KUrl::List::fromMimeData( md ); if ( urls.isEmpty() ) { // oops, no data event->setAccepted( false ); return; } else { emit urlDropped( urls.first() ); emit changed(); } } void ImageLabel::mousePressEvent( QMouseEvent *event ) { mDragStartPos = event->pos(); QLabel::mousePressEvent( event ); } void ImageLabel::mouseMoveEvent( QMouseEvent *event ) { if ( (event->buttons() & Qt::LeftButton) && (event->pos() - mDragStartPos).manhattanLength() > KGlobalSettings::dndEventDelay() ) { startDrag(); } } ImageBaseWidget::ImageBaseWidget( const QString &title, QWidget *parent ) : QWidget( parent ), mReadOnly( false ), mRssLoader( 0 ) { QHBoxLayout *topLayout = new QHBoxLayout( this ); topLayout->setSpacing( KDialog::spacingHint() ); topLayout->setMargin( KDialog::marginHint() ); Q3GroupBox *box = new Q3GroupBox( 0, Qt::Vertical, title, this ); QGridLayout *boxLayout = new QGridLayout(); box->layout()->addItem( boxLayout ); boxLayout->setSpacing( KDialog::spacingHint() ); boxLayout->setRowStretch( 3, 1 ); mImageLabel = new ImageLabel( i18n( "Picture" ), box ); mImageLabel->setFixedSize( 100, 140 ); mImageLabel->setFrameStyle( QFrame::Panel | QFrame::Sunken ); boxLayout->addWidget( mImageLabel, 0, 0, 4, 1, Qt::AlignTop ); mImageUrl = new KUrlRequester( box ); mImageUrl->setFilter( KImageIO::pattern() ); mImageUrl->setMode( KFile::File ); boxLayout->addWidget( mImageUrl, 0, 1 ); mClearButton = new QPushButton( box ); mClearButton->setSizePolicy( QSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum ) ); mClearButton->setIcon( KIcon( QApplication::isRightToLeft() ? "locationbar-erase" : "clear-left" ) ); mClearButton->setEnabled( false ); boxLayout->addWidget( mClearButton, 0, 2 ); mBlogButton = new QPushButton( i18n( "Get From Blog" ), box ); boxLayout->addWidget( mBlogButton, 1, 1, 1, 2 ); connect( mBlogButton, SIGNAL( clicked() ), SLOT( getPictureFromBlog() ) ); showBlogButton( false ); mUseImageUrl = new QCheckBox( i18n( "Store as URL" ), box ); mUseImageUrl->setEnabled( false ); boxLayout->addWidget( mUseImageUrl, 2, 1, 1, 2 ); topLayout->addWidget( box ); mClearButton->setToolTip( i18n( "Reset" ) ); connect( mImageLabel, SIGNAL( changed() ), SIGNAL( changed() ) ); connect( mImageLabel, SIGNAL( urlDropped( const KUrl& ) ), SLOT( urlDropped( const KUrl& ) ) ); connect( mImageUrl, SIGNAL( textChanged( const QString& ) ), SIGNAL( changed() ) ); connect( mImageUrl, SIGNAL( urlSelected( const KUrl& ) ), SLOT( loadImage() ) ); connect( mImageUrl, SIGNAL( urlSelected( const KUrl& ) ), SIGNAL( changed() ) ); connect( mImageUrl, SIGNAL( urlSelected( const KUrl& ) ), SLOT( updateGUI() ) ); connect( mUseImageUrl, SIGNAL( toggled( bool ) ), SIGNAL( changed() ) ); // FIXME: Is there really no race condition with all these mImageUrl signals? connect( mClearButton, SIGNAL( clicked() ), SLOT( clear() ) ); } ImageBaseWidget::~ImageBaseWidget() { } void ImageBaseWidget::setReadOnly( bool readOnly ) { mReadOnly = readOnly; mImageLabel->setReadOnly( mReadOnly ); mImageUrl->setEnabled( !mReadOnly ); if ( !mBlogFeed.isEmpty() ) mBlogButton->setEnabled( !readOnly ); } void ImageBaseWidget::showBlogButton( bool show ) { if ( show ) mBlogButton->show(); else mBlogButton->hide(); } void ImageBaseWidget::setBlogFeed( const QString &feed ) { mBlogFeed = feed; mBlogButton->setEnabled( !feed.isEmpty() ); } void ImageBaseWidget::setImage( const KABC::Picture &photo ) { bool blocked = signalsBlocked(); blockSignals( true ); if ( photo.isIntern() ) { QPixmap px = QPixmap::fromImage( photo.data() ); if ( px.height() != 140 || px.width() != 100 ) { if ( px.height() > px.width() ) px = QPixmap::fromImage( px.toImage().scaledToHeight( 140 ) ); else px = QPixmap::fromImage( px.toImage().scaledToWidth( 100 ) ); } mImageLabel->setPixmap( px ); mUseImageUrl->setChecked( false ); } else { mImageUrl->setUrl( photo.url() ); if ( !photo.url().isEmpty() ) mUseImageUrl->setChecked( true ); loadImage(); } blockSignals( blocked ); updateGUI(); } KABC::Picture ImageBaseWidget::image() const { KABC::Picture photo; if ( mUseImageUrl->isChecked() ) photo.setUrl( mImageUrl->url().url() ); else { if ( mImageLabel->pixmap() ) { photo.setData( mImageLabel->pixmap()->toImage() ); } } return photo; } void ImageBaseWidget::urlDropped( const KUrl &url ) { mImageUrl->setUrl( url ); loadImage(); mImageUrl->setUrl( url ); emit changed(); } void ImageBaseWidget::loadImage() { QPixmap pixmap = loadPixmap( KUrl( mImageUrl->url() ) ); if(! pixmap.isNull() ) mImageLabel->setPixmap( pixmap ); } void ImageBaseWidget::updateGUI() { if ( !mReadOnly ) { mUseImageUrl->setEnabled( !mImageUrl->url().isEmpty() ); mClearButton->setEnabled( !mImageUrl->url().isEmpty() || ( mImageLabel->pixmap() && !mImageLabel->pixmap()->isNull() ) ); } } void ImageBaseWidget::clear() { mImageLabel->clear(); mImageUrl->clear(); mUseImageUrl->setChecked( false ); updateGUI(); emit changed(); } void ImageBaseWidget::imageChanged() { updateGUI(); emit changed(); } QPixmap ImageBaseWidget::loadPixmap( const KUrl &url ) { QString tempFile; QPixmap pixmap; if ( url.isEmpty() ) return pixmap; if ( url.isLocalFile() ) pixmap = QPixmap( url.path() ); else if ( KIO::NetAccess::download( url, tempFile, this ) ) { pixmap = QPixmap( tempFile ); KIO::NetAccess::removeTempFile( tempFile ); } if ( pixmap.isNull() ) { // image does not exist (any more) KMessageBox::sorry( this, i18n( "This contact's image cannot be found." ) ); return pixmap; } QPixmap selectedPixmap = QPixmap::fromImage( KPixmapRegionSelectorDialog::getSelectedImage( pixmap, 100, 140, this ) ); if ( selectedPixmap.isNull() ) return QPixmap(); pixmap = selectedPixmap; mImageUrl->clear(); if ( pixmap.height() != 140 || pixmap.width() != 100 ) { if ( pixmap.height() > pixmap.width() ) pixmap = QPixmap::fromImage( pixmap.toImage().scaledToHeight( 140 ) ); else pixmap = QPixmap::fromImage( pixmap.toImage().scaledToWidth( 100 ) ); } return pixmap; } void ImageBaseWidget::getPictureFromBlog() { if ( mRssLoader ) { return; } mRssLoader = Syndication::Loader::create(); connect( mRssLoader, SIGNAL( loadingComplete( Syndication::Loader *, Syndication::FeedPtr, Syndication::ErrorCode ) ), SLOT( slotLoadingComplete( Syndication::Loader *, Syndication::FeedPtr, Syndication::ErrorCode ) ) ); mRssLoader->loadFrom( mBlogFeed ); // TODO: Show progress for fetching image from blog. } void ImageBaseWidget::slotLoadingComplete( Syndication::Loader *loader, Syndication::FeedPtr feed, Syndication::ErrorCode error ) { if ( error != Syndication::Success ) { KMessageBox::sorry( this, i18n( "Unable to retrieve blog feed from '%1': %2", mBlogFeed , loader->errorCode() ) ); return; } if ( feed->image()->isNull() ) { KMessageBox::sorry( this, i18n( "Blog feed at '%1' does not contain an image.", mBlogFeed ) ); return; } blockSignals( true ); mImageUrl->setUrl( feed->image()->url() ); loadImage(); blockSignals( false ); imageChanged(); mRssLoader = 0; } ImageWidget::ImageWidget( KABC::AddressBook *ab, QWidget *parent ) : KAB::ContactEditorWidget( ab, parent ) { QHBoxLayout *layout = new QHBoxLayout( this ); layout->setSpacing( KDialog::spacingHint() ); layout->setMargin( KDialog::marginHint() ); mPhotoWidget = new ImageBaseWidget( KABC::Addressee::photoLabel(), this ); layout->addWidget( mPhotoWidget ); mPhotoWidget->showBlogButton( true ); mLogoWidget = new ImageBaseWidget( KABC::Addressee::logoLabel(), this ); layout->addWidget( mLogoWidget ); connect( mPhotoWidget, SIGNAL( changed() ), SLOT( setModified() ) ); connect( mLogoWidget, SIGNAL( changed() ), SLOT( setModified() ) ); } void ImageWidget::loadContact( KABC::Addressee *addr ) { mPhotoWidget->setImage( addr->photo() ); mPhotoWidget->setBlogFeed( addr->custom( "KADDRESSBOOK", "BlogFeed" ) ); mLogoWidget->setImage( addr->logo() ); } void ImageWidget::storeContact( KABC::Addressee *addr ) { addr->setPhoto( mPhotoWidget->image() ); addr->setLogo( mLogoWidget->image() ); } void ImageWidget::setReadOnly( bool readOnly ) { mPhotoWidget->setReadOnly( readOnly ); mLogoWidget->setReadOnly( readOnly ); } #include "imagewidget.moc"
/* This file is part of KAddressBook. Copyright (c) 2003 Tobias Koenig <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <kabc/picture.h> #include <kdebug.h> #include <kdialog.h> #include <kglobalsettings.h> #include <kiconloader.h> #include <kimageio.h> #include <kio/netaccess.h> #include <klocale.h> #include <kmessagebox.h> #include <kurlrequester.h> #include <kpixmapregionselectordialog.h> #include <syndication/loader.h> #include <syndication/feed.h> #include <syndication/image.h> #include <QApplication> #include <QCheckBox> #include <q3groupbox.h> #include <QLabel> #include <QLayout> #include <QPixmap> #include <QGridLayout> #include <QFrame> #include <QHBoxLayout> #include <QDropEvent> #include <QDragEnterEvent> #include <QMouseEvent> #include "imagewidget.h" ImageLabel::ImageLabel( const QString &title, QWidget *parent ) : QLabel( title, parent ), mReadOnly( false ) { setAcceptDrops( true ); } void ImageLabel::setReadOnly( bool readOnly ) { mReadOnly = readOnly; } void ImageLabel::startDrag() { if ( pixmap() && !pixmap()->isNull() ) { QDrag *drag = new QDrag( this ); drag->setMimeData( new QMimeData() ); drag->mimeData()->setImageData( pixmap()->toImage() ); drag->start(); } } void ImageLabel::dragEnterEvent( QDragEnterEvent *event ) { const QMimeData *md = event->mimeData(); event->setAccepted( md->hasImage() || md->hasUrls()); } void ImageLabel::dropEvent( QDropEvent *event ) { if ( mReadOnly ) return; const QMimeData *md = event->mimeData(); if ( md->hasImage() ) { QImage image = qvariant_cast<QImage>(md->imageData()); setPixmap( QPixmap::fromImage( image ) ); emit changed(); } KUrl::List urls = KUrl::List::fromMimeData( md ); if ( urls.isEmpty() ) { // oops, no data event->setAccepted( false ); return; } else { emit urlDropped( urls.first() ); emit changed(); } } void ImageLabel::mousePressEvent( QMouseEvent *event ) { mDragStartPos = event->pos(); QLabel::mousePressEvent( event ); } void ImageLabel::mouseMoveEvent( QMouseEvent *event ) { if ( (event->buttons() & Qt::LeftButton) && (event->pos() - mDragStartPos).manhattanLength() > KGlobalSettings::dndEventDelay() ) { startDrag(); } } ImageBaseWidget::ImageBaseWidget( const QString &title, QWidget *parent ) : QWidget( parent ), mReadOnly( false ), mRssLoader( 0 ) { QHBoxLayout *topLayout = new QHBoxLayout( this ); topLayout->setSpacing( KDialog::spacingHint() ); topLayout->setMargin( KDialog::marginHint() ); Q3GroupBox *box = new Q3GroupBox( 0, Qt::Vertical, title, this ); QGridLayout *boxLayout = new QGridLayout(); box->layout()->addItem( boxLayout ); boxLayout->setSpacing( KDialog::spacingHint() ); boxLayout->setRowStretch( 3, 1 ); mImageLabel = new ImageLabel( i18n( "Picture" ), box ); mImageLabel->setFixedSize( 100, 140 ); mImageLabel->setFrameStyle( QFrame::Panel | QFrame::Sunken ); boxLayout->addWidget( mImageLabel, 0, 0, 4, 1, Qt::AlignTop ); mImageUrl = new KUrlRequester( box ); mImageUrl->setFilter( KImageIO::pattern() ); mImageUrl->setMode( KFile::File ); boxLayout->addWidget( mImageUrl, 0, 1 ); mClearButton = new QPushButton( box ); mClearButton->setSizePolicy( QSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum ) ); mClearButton->setIcon( KIcon( QApplication::isRightToLeft() ? "locationbar-erase" : "clear-left" ) ); mClearButton->setEnabled( false ); boxLayout->addWidget( mClearButton, 0, 2 ); mBlogButton = new QPushButton( i18n( "Get From Blog" ), box ); boxLayout->addWidget( mBlogButton, 1, 1, 1, 2 ); connect( mBlogButton, SIGNAL( clicked() ), SLOT( getPictureFromBlog() ) ); showBlogButton( false ); mUseImageUrl = new QCheckBox( i18n( "Store as URL" ), box ); mUseImageUrl->setEnabled( false ); boxLayout->addWidget( mUseImageUrl, 2, 1, 1, 2 ); topLayout->addWidget( box ); mClearButton->setToolTip( i18n( "Reset" ) ); connect( mImageLabel, SIGNAL( changed() ), SIGNAL( changed() ) ); connect( mImageLabel, SIGNAL( urlDropped( const KUrl& ) ), SLOT( urlDropped( const KUrl& ) ) ); connect( mImageUrl, SIGNAL( textChanged( const QString& ) ), SIGNAL( changed() ) ); connect( mImageUrl, SIGNAL( textChanged( const QString& ) ), SLOT( updateGUI() ) ); connect( mImageUrl, SIGNAL( urlSelected( const KUrl& ) ), SLOT( loadImage() ) ); connect( mImageUrl, SIGNAL( urlSelected( const KUrl& ) ), SIGNAL( changed() ) ); connect( mImageUrl, SIGNAL( urlSelected( const KUrl& ) ), SLOT( updateGUI() ) ); connect( mUseImageUrl, SIGNAL( toggled( bool ) ), SIGNAL( changed() ) ); // FIXME: Is there really no race condition with all these mImageUrl signals? connect( mClearButton, SIGNAL( clicked() ), SLOT( clear() ) ); } ImageBaseWidget::~ImageBaseWidget() { } void ImageBaseWidget::setReadOnly( bool readOnly ) { mReadOnly = readOnly; mImageLabel->setReadOnly( mReadOnly ); mImageUrl->setEnabled( !mReadOnly ); if ( !mBlogFeed.isEmpty() ) mBlogButton->setEnabled( !readOnly ); } void ImageBaseWidget::showBlogButton( bool show ) { if ( show ) mBlogButton->show(); else mBlogButton->hide(); } void ImageBaseWidget::setBlogFeed( const QString &feed ) { mBlogFeed = feed; mBlogButton->setEnabled( !feed.isEmpty() ); } void ImageBaseWidget::setImage( const KABC::Picture &photo ) { bool blocked = signalsBlocked(); blockSignals( true ); if ( photo.isIntern() ) { QPixmap px = QPixmap::fromImage( photo.data() ); if ( px.height() != 140 || px.width() != 100 ) { if ( px.height() > px.width() ) px = QPixmap::fromImage( px.toImage().scaledToHeight( 140 ) ); else px = QPixmap::fromImage( px.toImage().scaledToWidth( 100 ) ); } mImageLabel->setPixmap( px ); mUseImageUrl->setChecked( false ); } else { mImageUrl->setUrl( photo.url() ); if ( !photo.url().isEmpty() ) mUseImageUrl->setChecked( true ); loadImage(); } blockSignals( blocked ); updateGUI(); } KABC::Picture ImageBaseWidget::image() const { KABC::Picture photo; if ( mUseImageUrl->isChecked() ) photo.setUrl( mImageUrl->url().url() ); else { if ( mImageLabel->pixmap() ) { photo.setData( mImageLabel->pixmap()->toImage() ); } } return photo; } void ImageBaseWidget::urlDropped( const KUrl &url ) { mImageUrl->setUrl( url ); loadImage(); mImageUrl->setUrl( url ); emit changed(); } void ImageBaseWidget::loadImage() { QPixmap pixmap = loadPixmap( KUrl( mImageUrl->url() ) ); if(! pixmap.isNull() ) mImageLabel->setPixmap( pixmap ); } void ImageBaseWidget::updateGUI() { if ( !mReadOnly ) { mUseImageUrl->setEnabled( !mImageUrl->url().isEmpty() ); mClearButton->setEnabled( !mImageUrl->url().isEmpty() || ( mImageLabel->pixmap() && !mImageLabel->pixmap()->isNull() ) ); } } void ImageBaseWidget::clear() { mImageLabel->clear(); mImageUrl->clear(); mUseImageUrl->setChecked( false ); updateGUI(); emit changed(); } void ImageBaseWidget::imageChanged() { updateGUI(); emit changed(); } QPixmap ImageBaseWidget::loadPixmap( const KUrl &url ) { QString tempFile; QPixmap pixmap; if ( url.isEmpty() ) return pixmap; if ( url.isLocalFile() ) pixmap = QPixmap( url.path() ); else if ( KIO::NetAccess::download( url, tempFile, this ) ) { pixmap = QPixmap( tempFile ); KIO::NetAccess::removeTempFile( tempFile ); } if ( pixmap.isNull() ) { // image does not exist (any more) KMessageBox::sorry( this, i18n( "This contact's image cannot be found." ) ); return pixmap; } QPixmap selectedPixmap = QPixmap::fromImage( KPixmapRegionSelectorDialog::getSelectedImage( pixmap, 100, 140, this ) ); if ( selectedPixmap.isNull() ) return QPixmap(); pixmap = selectedPixmap; mImageUrl->clear(); if ( pixmap.height() != 140 || pixmap.width() != 100 ) { if ( pixmap.height() > pixmap.width() ) pixmap = QPixmap::fromImage( pixmap.toImage().scaledToHeight( 140 ) ); else pixmap = QPixmap::fromImage( pixmap.toImage().scaledToWidth( 100 ) ); } return pixmap; } void ImageBaseWidget::getPictureFromBlog() { if ( mRssLoader ) { return; } mRssLoader = Syndication::Loader::create(); connect( mRssLoader, SIGNAL( loadingComplete( Syndication::Loader *, Syndication::FeedPtr, Syndication::ErrorCode ) ), SLOT( slotLoadingComplete( Syndication::Loader *, Syndication::FeedPtr, Syndication::ErrorCode ) ) ); mRssLoader->loadFrom( mBlogFeed ); // TODO: Show progress for fetching image from blog. } void ImageBaseWidget::slotLoadingComplete( Syndication::Loader *loader, Syndication::FeedPtr feed, Syndication::ErrorCode error ) { if ( error != Syndication::Success ) { KMessageBox::sorry( this, i18n( "Unable to retrieve blog feed from '%1': %2", mBlogFeed , loader->errorCode() ) ); return; } if ( feed->image()->isNull() ) { KMessageBox::sorry( this, i18n( "Blog feed at '%1' does not contain an image.", mBlogFeed ) ); return; } blockSignals( true ); mImageUrl->setUrl( feed->image()->url() ); loadImage(); blockSignals( false ); imageChanged(); mRssLoader = 0; } ImageWidget::ImageWidget( KABC::AddressBook *ab, QWidget *parent ) : KAB::ContactEditorWidget( ab, parent ) { QHBoxLayout *layout = new QHBoxLayout( this ); layout->setSpacing( KDialog::spacingHint() ); layout->setMargin( KDialog::marginHint() ); mPhotoWidget = new ImageBaseWidget( KABC::Addressee::photoLabel(), this ); layout->addWidget( mPhotoWidget ); mPhotoWidget->showBlogButton( true ); mLogoWidget = new ImageBaseWidget( KABC::Addressee::logoLabel(), this ); layout->addWidget( mLogoWidget ); connect( mPhotoWidget, SIGNAL( changed() ), SLOT( setModified() ) ); connect( mLogoWidget, SIGNAL( changed() ), SLOT( setModified() ) ); } void ImageWidget::loadContact( KABC::Addressee *addr ) { mPhotoWidget->setImage( addr->photo() ); mPhotoWidget->setBlogFeed( addr->custom( "KADDRESSBOOK", "BlogFeed" ) ); mLogoWidget->setImage( addr->logo() ); } void ImageWidget::storeContact( KABC::Addressee *addr ) { addr->setPhoto( mPhotoWidget->image() ); addr->setLogo( mLogoWidget->image() ); } void ImageWidget::setReadOnly( bool readOnly ) { mPhotoWidget->setReadOnly( readOnly ); mLogoWidget->setReadOnly( readOnly ); } #include "imagewidget.moc"
Enable reset button when we changed url
Enable reset button when we changed url svn path=/trunk/KDE/kdepim/; revision=662872
C++
lgpl-2.1
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
19d93370a4927cbea9780794cf612aef10f21a32
test/obd_test.cpp
test/obd_test.cpp
#undef NDEBUG #include <assert.h> #include <ellis/codec/elm327.hpp> #include <ellis/core/array_node.hpp> #include <ellis/core/map_node.hpp> #include <ellis/private/codec/obd/pid.hpp> #include <ellis/private/using.hpp> #include <test/assert.hpp> int main() { using namespace ellis; using namespace ellis::obd; using namespace ellis::test; /* OBD. */ assert(*get_mode_string(0x7F) == "unknown"); assert(get_mode_string(0x00) == nullptr); assert(*get_mode_string(0x41) == "current"); assert(*get_mode_string(0x42) == "freeze"); assert(get_mode_string(0xFF) == nullptr); assert(get_pid_string(0xFF) == nullptr); assert(string(get_pid_string(0x0D)) == "vehicle_speed"); assert(dbl_equal(decode_value(0x05, 0xAB000000), 0xAB - 40)); assert(dbl_equal(decode_value(0x05, 0xAB123456), 0xAB - 40)); assert(dbl_equal(decode_value(0x05, 0x00000000), -40)); assert(decode_value(0x0C, 0xABCD0000) == (0xAB*256 + 0xCD)/4.0); assert(decode_value(0x0C, 0xABCD1234) == (0xAB*256 + 0xCD)/4.0); assert(dbl_equal(decode_value(0x0D, 0xAB000000), 0xAB)); assert(dbl_equal(decode_value(0x0D, 0xAB123456), 0xAB)); assert(decode_value(0x10, 0xABCD0000) == (0xAB*256 + 0xCD)/100.0); assert(decode_value(0x10, 0xABCD1234) == (0xAB*256 + 0xCD)/100.0); assert(decode_value(0x14, 0xAB000000) == 0xAB / 200.0); assert(decode_value(0x14, 0xAB123456) == 0xAB / 200.0); /* ELM327. */ { elm327_decoder dec; const byte buf[] = "41 05 B9\n"; size_t count = sizeof(buf) - 1; decoding_status status = dec.consume_buffer(buf, &count); assert(status == decoding_status::END); assert(count == 0); assert(dec.extract_error() == nullptr); node n = *dec.extract_node(); assert(n.as_array().length() == 1); const map_node &m = n.as_array()[0].as_map(); assert(m["mode"] == "current"); assert(m["pid"] == "engine_coolant_temp"); assert(dbl_equal(m["value"], 0xB9 - 40)); } { elm327_decoder dec; const byte buf[] = "41 0C 08 1B\n"; size_t count = sizeof(buf) - 1; decoding_status status = dec.consume_buffer(buf, &count); assert(status == decoding_status::END); assert(count == 0); assert(dec.extract_error() == nullptr); node n = *dec.extract_node(); assert(n.as_array().length() == 1); const map_node &m = n.as_array()[0].as_map(); assert(m["mode"] == "current"); assert(m["pid"] == "engine_rpm"); assert(dbl_equal(m["value"], (0x08*256 + 0x1B)/4.0)); } { elm327_decoder dec; const byte buf[] = ""; size_t count = sizeof(buf) - 1; decoding_status status = dec.consume_buffer(buf, &count); assert(status == decoding_status::ERROR); assert(dec.extract_error() != nullptr); } { elm327_decoder dec; const byte buf[] = "\n"; size_t count = sizeof(buf) - 1; decoding_status status = dec.consume_buffer(buf, &count); assert(status == decoding_status::ERROR); assert(dec.extract_error() != nullptr); } return 0; }
#undef NDEBUG #include <ellis/codec/elm327.hpp> #include <ellis/core/array_node.hpp> #include <ellis/core/map_node.hpp> #include <ellis/private/codec/obd/pid.hpp> #include <ellis/core/system.hpp> #include <ellis/private/using.hpp> #include <test/assert.hpp> int main() { using namespace ellis; using namespace ellis::obd; using namespace ellis::test; /* OBD. */ ELLIS_ASSERT(*get_mode_string(0x7F) == "unknown"); ELLIS_ASSERT(get_mode_string(0x00) == nullptr); ELLIS_ASSERT(*get_mode_string(0x41) == "current"); ELLIS_ASSERT(*get_mode_string(0x42) == "freeze"); ELLIS_ASSERT(get_mode_string(0xFF) == nullptr); ELLIS_ASSERT(get_pid_string(0xFF) == nullptr); ELLIS_ASSERT(string(get_pid_string(0x0D)) == "vehicle_speed"); ELLIS_ASSERT(dbl_equal(decode_value(0x05, 0xAB000000), 0xAB - 40)); ELLIS_ASSERT(dbl_equal(decode_value(0x05, 0xAB123456), 0xAB - 40)); ELLIS_ASSERT(dbl_equal(decode_value(0x05, 0x00000000), -40)); ELLIS_ASSERT(decode_value(0x0C, 0xABCD0000) == (0xAB*256 + 0xCD)/4.0); ELLIS_ASSERT(decode_value(0x0C, 0xABCD1234) == (0xAB*256 + 0xCD)/4.0); ELLIS_ASSERT(dbl_equal(decode_value(0x0D, 0xAB000000), 0xAB)); ELLIS_ASSERT(dbl_equal(decode_value(0x0D, 0xAB123456), 0xAB)); ELLIS_ASSERT(decode_value(0x10, 0xABCD0000) == (0xAB*256 + 0xCD)/100.0); ELLIS_ASSERT(decode_value(0x10, 0xABCD1234) == (0xAB*256 + 0xCD)/100.0); ELLIS_ASSERT(decode_value(0x14, 0xAB000000) == 0xAB / 200.0); ELLIS_ASSERT(decode_value(0x14, 0xAB123456) == 0xAB / 200.0); /* ELM327. */ { elm327_decoder dec; const byte buf[] = "41 05 B9\n"; size_t count = sizeof(buf) - 1; decoding_status status = dec.consume_buffer(buf, &count); ELLIS_ASSERT(status == decoding_status::END); ELLIS_ASSERT(count == 0); ELLIS_ASSERT(dec.extract_error() == nullptr); node n = *dec.extract_node(); ELLIS_ASSERT(n.as_array().length() == 1); const map_node &m = n.as_array()[0].as_map(); ELLIS_ASSERT(m["mode"] == "current"); ELLIS_ASSERT(m["pid"] == "engine_coolant_temp"); ELLIS_ASSERT(dbl_equal(m["value"], 0xB9 - 40)); } { elm327_decoder dec; const byte buf[] = "41 0C 08 1B\n"; size_t count = sizeof(buf) - 1; decoding_status status = dec.consume_buffer(buf, &count); ELLIS_ASSERT(status == decoding_status::END); ELLIS_ASSERT(count == 0); ELLIS_ASSERT(dec.extract_error() == nullptr); node n = *dec.extract_node(); ELLIS_ASSERT(n.as_array().length() == 1); const map_node &m = n.as_array()[0].as_map(); ELLIS_ASSERT(m["mode"] == "current"); ELLIS_ASSERT(m["pid"] == "engine_rpm"); ELLIS_ASSERT(dbl_equal(m["value"], (0x08*256 + 0x1B)/4.0)); } { elm327_decoder dec; const byte buf[] = ""; size_t count = sizeof(buf) - 1; decoding_status status = dec.consume_buffer(buf, &count); ELLIS_ASSERT(status == decoding_status::ERROR); ELLIS_ASSERT(dec.extract_error() != nullptr); } { elm327_decoder dec; const byte buf[] = "\n"; size_t count = sizeof(buf) - 1; decoding_status status = dec.consume_buffer(buf, &count); ELLIS_ASSERT(status == decoding_status::ERROR); ELLIS_ASSERT(dec.extract_error() != nullptr); } return 0; }
use ELLIS_ASSERT instead of assert
obdtest: use ELLIS_ASSERT instead of assert
C++
mit
project-ellis/ellis,project-ellis/ellis
ed3eef1ff134043b8fb49bd2fceff5d0c8a03c3e
src/compiler/translator/RewriteElseBlocks.cpp
src/compiler/translator/RewriteElseBlocks.cpp
// // Copyright (c) 2014 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // RewriteElseBlocks.cpp: Implementation for tree transform to change // all if-else blocks to if-if blocks. // #include "compiler/translator/RewriteElseBlocks.h" #include "compiler/translator/NodeSearch.h" #include "compiler/translator/SymbolTable.h" namespace sh { TIntermSymbol *MakeNewTemporary(const TString &name, TBasicType type) { TType variableType(type, EbpHigh, EvqInternal); return new TIntermSymbol(-1, name, variableType); } TIntermBinary *MakeNewBinary(TOperator op, TIntermTyped *left, TIntermTyped *right, const TType &resultType) { TIntermBinary *binary = new TIntermBinary(op); binary->setLeft(left); binary->setRight(right); binary->setType(resultType); return binary; } TIntermUnary *MakeNewUnary(TOperator op, TIntermTyped *operand) { TIntermUnary *unary = new TIntermUnary(op, operand->getType()); unary->setOperand(operand); return unary; } bool ElseBlockRewriter::visitAggregate(Visit visit, TIntermAggregate *node) { switch (node->getOp()) { case EOpSequence: { for (size_t statementIndex = 0; statementIndex != node->getSequence().size(); statementIndex++) { TIntermNode *statement = node->getSequence()[statementIndex]; TIntermSelection *selection = statement->getAsSelectionNode(); if (selection && selection->getFalseBlock() != NULL) { node->getSequence()[statementIndex] = rewriteSelection(selection); delete selection; } } } break; default: break; } return true; } TIntermNode *ElseBlockRewriter::rewriteSelection(TIntermSelection *selection) { ASSERT(selection->getFalseBlock() != NULL); TString temporaryName = "cond_" + str(mTemporaryIndex++); TIntermTyped *typedCondition = selection->getCondition()->getAsTyped(); TType resultType(EbtBool, EbpUndefined); TIntermSymbol *conditionSymbolA = MakeNewTemporary(temporaryName, EbtBool); TIntermSymbol *conditionSymbolB = MakeNewTemporary(temporaryName, EbtBool); TIntermSymbol *conditionSymbolC = MakeNewTemporary(temporaryName, EbtBool); TIntermBinary *storeCondition = MakeNewBinary(EOpInitialize, conditionSymbolA, typedCondition, resultType); TIntermUnary *negatedCondition = MakeNewUnary(EOpLogicalNot, conditionSymbolB); TIntermSelection *falseBlock = new TIntermSelection(negatedCondition, selection->getFalseBlock(), NULL); TIntermSelection *newIfElse = new TIntermSelection(conditionSymbolC, selection->getTrueBlock(), falseBlock); TIntermAggregate *declaration = new TIntermAggregate(EOpDeclaration); declaration->getSequence().push_back(storeCondition); TIntermAggregate *block = new TIntermAggregate(EOpSequence); block->getSequence().push_back(declaration); block->getSequence().push_back(newIfElse); return block; } void RewriteElseBlocks(TIntermNode *node) { ElseBlockRewriter rewriter; node->traverse(&rewriter); } }
// // Copyright (c) 2014 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // RewriteElseBlocks.cpp: Implementation for tree transform to change // all if-else blocks to if-if blocks. // #include "compiler/translator/RewriteElseBlocks.h" #include "compiler/translator/NodeSearch.h" #include "compiler/translator/SymbolTable.h" namespace sh { TIntermSymbol *MakeNewTemporary(const TString &name, TBasicType type) { TType variableType(type, EbpHigh, EvqInternal); return new TIntermSymbol(-1, name, variableType); } TIntermBinary *MakeNewBinary(TOperator op, TIntermTyped *left, TIntermTyped *right, const TType &resultType) { TIntermBinary *binary = new TIntermBinary(op); binary->setLeft(left); binary->setRight(right); binary->setType(resultType); return binary; } TIntermUnary *MakeNewUnary(TOperator op, TIntermTyped *operand) { TIntermUnary *unary = new TIntermUnary(op, operand->getType()); unary->setOperand(operand); return unary; } bool ElseBlockRewriter::visitAggregate(Visit visit, TIntermAggregate *node) { switch (node->getOp()) { case EOpSequence: { for (size_t statementIndex = 0; statementIndex != node->getSequence().size(); statementIndex++) { TIntermNode *statement = node->getSequence()[statementIndex]; TIntermSelection *selection = statement->getAsSelectionNode(); if (selection && selection->getFalseBlock() != NULL) { // Check for if / else if TIntermSelection *elseIfBranch = selection->getFalseBlock()->getAsSelectionNode(); if (elseIfBranch) { selection->replaceChildNode(elseIfBranch, rewriteSelection(elseIfBranch)); delete elseIfBranch; } node->getSequence()[statementIndex] = rewriteSelection(selection); delete selection; } } } break; default: break; } return true; } TIntermNode *ElseBlockRewriter::rewriteSelection(TIntermSelection *selection) { ASSERT(selection->getFalseBlock() != NULL); TString temporaryName = "cond_" + str(mTemporaryIndex++); TIntermTyped *typedCondition = selection->getCondition()->getAsTyped(); TType resultType(EbtBool, EbpUndefined); TIntermSymbol *conditionSymbolA = MakeNewTemporary(temporaryName, EbtBool); TIntermSymbol *conditionSymbolB = MakeNewTemporary(temporaryName, EbtBool); TIntermSymbol *conditionSymbolC = MakeNewTemporary(temporaryName, EbtBool); TIntermBinary *storeCondition = MakeNewBinary(EOpInitialize, conditionSymbolA, typedCondition, resultType); TIntermUnary *negatedCondition = MakeNewUnary(EOpLogicalNot, conditionSymbolB); TIntermSelection *falseBlock = new TIntermSelection(negatedCondition, selection->getFalseBlock(), NULL); TIntermSelection *newIfElse = new TIntermSelection(conditionSymbolC, selection->getTrueBlock(), falseBlock); TIntermAggregate *declaration = new TIntermAggregate(EOpDeclaration); declaration->getSequence().push_back(storeCondition); TIntermAggregate *block = new TIntermAggregate(EOpSequence); block->getSequence().push_back(declaration); block->getSequence().push_back(newIfElse); return block; } void RewriteElseBlocks(TIntermNode *node) { ElseBlockRewriter rewriter; node->traverse(&rewriter); } }
Fix not rewriting else-if blocks.
Fix not rewriting else-if blocks. We would miss expanding the else-if clauses in a chain of selection statements. BUG=346463 BUG=391697 Change-Id: Iee644b875cf68d0ed3dc0b73542efc49ecb23242 Reviewed-on: https://chromium-review.googlesource.com/206822 Reviewed-by: Nicolas Capens <[email protected]> Tested-by: Jamie Madill <[email protected]> Reviewed-by: Shannon Woods <[email protected]>
C++
bsd-3-clause
ppy/angle,geekboxzone/lollipop_external_chromium_org_third_party_angle,ppy/angle,csa7mdm/angle,mrobinson/rust-angle,MIPS/external-chromium_org-third_party-angle,larsbergstrom/angle,mybios/angle,larsbergstrom/angle,xin3liang/platform_external_chromium_org_third_party_angle,ghostoy/angle,bsergean/angle,jgcaaprom/android_external_chromium_org_third_party_angle,mlfarrell/angle,ecoal95/angle,csa7mdm/angle,mikolalysenko/angle,ghostoy/angle,android-ia/platform_external_chromium_org_third_party_angle,nandhanurrevanth/angle,MIPS/external-chromium_org-third_party-angle,android-ia/platform_external_chromium_org_third_party_angle,mrobinson/rust-angle,mrobinson/rust-angle,jgcaaprom/android_external_chromium_org_third_party_angle,mikolalysenko/angle,csa7mdm/angle,domokit/waterfall,crezefire/angle,MSOpenTech/angle,vvuk/angle,xin3liang/platform_external_chromium_org_third_party_angle,jgcaaprom/android_external_chromium_org_third_party_angle,ecoal95/angle,ecoal95/angle,ecoal95/angle,MSOpenTech/angle,crezefire/angle,larsbergstrom/angle,nandhanurrevanth/angle,xin3liang/platform_external_chromium_org_third_party_angle,mlfarrell/angle,mikolalysenko/angle,mybios/angle,csa7mdm/angle,MSOpenTech/angle,domokit/waterfall,mlfarrell/angle,geekboxzone/lollipop_external_chromium_org_third_party_angle,ppy/angle,crezefire/angle,bsergean/angle,nandhanurrevanth/angle,ghostoy/angle,mrobinson/rust-angle,ghostoy/angle,nandhanurrevanth/angle,mikolalysenko/angle,crezefire/angle,mybios/angle,mybios/angle,android-ia/platform_external_chromium_org_third_party_angle,MIPS/external-chromium_org-third_party-angle,ppy/angle,android-ia/platform_external_chromium_org_third_party_angle,MSOpenTech/angle,mrobinson/rust-angle,vvuk/angle,MIPS/external-chromium_org-third_party-angle,geekboxzone/lollipop_external_chromium_org_third_party_angle,mlfarrell/angle,ecoal95/angle,bsergean/angle,larsbergstrom/angle,vvuk/angle,geekboxzone/lollipop_external_chromium_org_third_party_angle,vvuk/angle,xin3liang/platform_external_chromium_org_third_party_angle,jgcaaprom/android_external_chromium_org_third_party_angle,bsergean/angle
16eed68a1eea02799a8879a148f1fb17ede59f63
orttraining/orttraining/training_ops/cpu/nn/layer_norm.cc
orttraining/orttraining/training_ops/cpu/nn/layer_norm.cc
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "orttraining/training_ops/cpu/nn/layer_norm.h" #include "core/framework/tensor.h" #include "core/util/math_cpuonly.h" #include "core/providers/common.h" namespace onnxruntime { namespace contrib { // LayerNormGrad #define REGISTER_KERNEL_TYPED(T) \ ONNX_OPERATOR_TYPED_KERNEL_EX( \ LayerNormalizationGrad, \ kMSDomain, \ 1, \ T, \ kCpuExecutionProvider, \ KernelDefBuilder() \ .TypeConstraint("T", DataTypeImpl::GetTensorType<T>()), \ LayerNormGrad<T, false>); \ ONNX_OPERATOR_TYPED_KERNEL_EX( \ SimplifiedLayerNormalizationGrad, \ kMSDomain, \ 1, \ T, \ kCpuExecutionProvider, \ KernelDefBuilder() \ .TypeConstraint("T", DataTypeImpl::GetTensorType<T>()), \ LayerNormGrad<T, true>); \ ONNX_OPERATOR_TYPED_KERNEL_EX( \ InvertibleLayerNormalizationGrad, \ kMSDomain, \ 1, \ T, \ kCpuExecutionProvider, \ KernelDefBuilder() \ .TypeConstraint("T", DataTypeImpl::GetTensorType<T>()), \ InvertibleLayerNormGrad<T>); REGISTER_KERNEL_TYPED(float) REGISTER_KERNEL_TYPED(double) #undef REGISTER_KERNEL_TYPED template <typename T, bool simplified> LayerNormGrad<T, simplified>::LayerNormGrad(const OpKernelInfo& op_kernel_info) : OpKernel{op_kernel_info} { ORT_ENFORCE(op_kernel_info.GetAttr("axis", &axis_).IsOK()); } template <typename T, bool simplified> Status LayerNormGrad<T, simplified>::Compute(OpKernelContext* op_kernel_context) const { int input_index = 0; const Tensor* Y_grad = op_kernel_context->Input<Tensor>(input_index++); const Tensor* X = op_kernel_context->Input<Tensor>(input_index++); const auto& X_shape = X->Shape(); const auto axis = HandleNegativeAxis(axis_, X_shape.NumDimensions()); const auto N = X_shape.SizeToDimension(axis); const auto M = X_shape.SizeFromDimension(axis); ORT_ENFORCE(M != 1); const Tensor* scale = op_kernel_context->Input<Tensor>(input_index++); const Tensor* mean; if (!simplified) { mean = op_kernel_context->Input<Tensor>(input_index++); } const Tensor* inv_std_var = op_kernel_context->Input<Tensor>(input_index); const auto& scale_shape = scale->Shape(); Tensor* X_grad = op_kernel_context->Output(0, X_shape); Tensor* scale_grad = op_kernel_context->Output(1, scale_shape); Tensor* bias_grad = (!simplified) ? op_kernel_context->Output(2, scale_shape) : nullptr; // Note: Eigen has column-major storage order by default ConstEigenArrayMap<T> Y_grad_arr{Y_grad->Data<T>(), M, N}; ConstEigenArrayMap<T> X_arr{X->Data<T>(), M, N}; ConstEigenVectorArrayMap<T> scale_vec{scale->Data<T>(), M}; ConstEigenVectorArrayMap<float> mean_vec{simplified ? nullptr : mean->Data<float>(), N}; ConstEigenVectorArrayMap<float> inv_std_var_vec{inv_std_var->Data<float>(), N}; EigenArrayMap<T> X_grad_arr{X_grad->MutableData<T>(), M, N}; EigenVectorArrayMap<T> scale_grad_vec{scale_grad->MutableData<T>(), M}; EigenVectorArrayMap<T> bias_grad_vec = (!simplified) ? EigenVectorArrayMap<T>{bias_grad->MutableData<T>(), M} : EigenVectorArrayMap<T>{nullptr, 0}; using Array = Eigen::ArrayXX<T>; using RowVector = Eigen::Array<T, 1, Eigen::Dynamic>; // A, B, C are calculated as below: // A = Y_grad * (X - mean(X)) * inv_std_var // B = Y_grad * scale * inv_std_var // C = Y_grad * scale * inv_std_var * (X - mean(X)) * inv_std_var // Simplified Layer Norm // A = Y_grad * X * inv_std_var // B = Y_grad * scale * inv_std_var // C = Y_grad * scale * inv_std_var * X * inv_std_var // A, B, and C are M x N Array X_mean_difference_over_std_var; if (simplified) { X_mean_difference_over_std_var = X_arr.rowwise() * inv_std_var_vec.cast<T>().transpose(); } else { X_mean_difference_over_std_var = (X_arr.rowwise() - mean_vec.cast<T>().transpose()).rowwise() * inv_std_var_vec.cast<T>().transpose(); } Array A = Y_grad_arr * X_mean_difference_over_std_var; Array B = (Y_grad_arr.colwise() * scale_vec).rowwise() * inv_std_var_vec.cast<T>().transpose(); Array C = B * X_mean_difference_over_std_var; RowVector mean_C = C.colwise().mean(); // 1 x N if (simplified) { X_grad_arr = B - X_mean_difference_over_std_var.rowwise() * mean_C; } else { RowVector mean_B = B.colwise().mean(); // 1 x N X_grad_arr = B.rowwise() - mean_B - X_mean_difference_over_std_var.rowwise() * mean_C; } if (!simplified) { bias_grad_vec = Y_grad_arr.rowwise().sum(); } scale_grad_vec = A.rowwise().sum(); return Status::OK(); } template <typename T> InvertibleLayerNormGrad<T>::InvertibleLayerNormGrad(const OpKernelInfo& op_kernel_info) : OpKernel{op_kernel_info} { ORT_ENFORCE(op_kernel_info.GetAttr("axis", &axis_).IsOK()); } template <typename T> Status InvertibleLayerNormGrad<T>::Compute(OpKernelContext* op_kernel_context) const { const Tensor* Y_grad = op_kernel_context->Input<Tensor>(0); const Tensor* Y = op_kernel_context->Input<Tensor>(1); const Tensor* scale = op_kernel_context->Input<Tensor>(2); const Tensor* bias = op_kernel_context->Input<Tensor>(3); const Tensor* inv_std_var = op_kernel_context->Input<Tensor>(4); const auto& Y_shape = Y_grad->Shape(); const auto& X_shape = Y_shape; const auto axis = HandleNegativeAxis(axis_, X_shape.NumDimensions()); const auto N = X_shape.SizeToDimension(axis); const auto M = X_shape.SizeFromDimension(axis); ORT_ENFORCE(M != 1); const auto& scale_shape = scale->Shape(); Tensor* X_grad = op_kernel_context->Output(0, X_shape); Tensor* scale_grad = op_kernel_context->Output(1, scale_shape); Tensor* bias_grad = op_kernel_context->Output(2, scale_shape); // Note: Eigen has column-major storage order by default ConstEigenArrayMap<T> Y_grad_arr{Y_grad->Data<T>(), M, N}; ConstEigenArrayMap<T> Y_arr{Y->Data<T>(), M, N}; ConstEigenVectorArrayMap<T> scale_vec{scale->Data<T>(), M}; ConstEigenVectorArrayMap<T> bias_vec{bias->Data<T>(), M}; ConstEigenVectorArrayMap<float> inv_std_var_vec{inv_std_var->Data<float>(), N}; EigenArrayMap<T> X_grad_arr{X_grad->MutableData<T>(), M, N}; EigenVectorArrayMap<T> scale_grad_vec{scale_grad->MutableData<T>(), M}; EigenVectorArrayMap<T> bias_grad_vec{bias_grad->MutableData<T>(), M}; using Array = Eigen::ArrayXX<T>; using RowVector = Eigen::Array<T, 1, Eigen::Dynamic>; // A, B, C are calculated as below: // A = Y_grad * (X - mean(X)) * inv_std_var // B = Y_grad * scale * inv_std_var // C = Y_grad * scale * inv_std_var * (X - mean(X)) * inv_std_var // A, B, and C are M x N Array X_mean_difference_over_std_var = (Y_arr.colwise() - bias_vec).colwise() / scale_vec; Array A = Y_grad_arr * X_mean_difference_over_std_var; Array B = (Y_grad_arr.colwise() * scale_vec).rowwise() * inv_std_var_vec.cast<T>().transpose(); Array C = B * X_mean_difference_over_std_var; // mean_B = mean(Y_grad * scale * inv_std_var) RowVector mean_B = B.colwise().mean(); // 1 x N // mean_C = mean(Y_grad * scale * inv_std_var * (X - mean(X)) * inv_std_var) RowVector mean_C = C.colwise().mean(); // 1 x N // X_grad = Y_grad * scale * inv_std_var - mean_B - (X - mean(X)) * inv_std_var * mean_C // = B - mean_B - (X - mean(X)) * inv_std_var * mean_c X_grad_arr = B.rowwise() - mean_B - X_mean_difference_over_std_var.rowwise() * mean_C; // bias_grad = sum(Y_grad) bias_grad_vec = Y_grad_arr.rowwise().sum(); // scale_grad = sum(Y_grad * (X - mean(X)) * inv_std_var) // = sum(A) scale_grad_vec = A.rowwise().sum(); return Status::OK(); } } // namespace contrib } // namespace onnxruntime
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "orttraining/training_ops/cpu/nn/layer_norm.h" #include "core/framework/tensor.h" #include "core/util/math_cpuonly.h" #include "core/providers/common.h" namespace onnxruntime { namespace contrib { // LayerNormGrad #define REGISTER_KERNEL_TYPED(T) \ ONNX_OPERATOR_TYPED_KERNEL_EX( \ LayerNormalizationGrad, \ kMSDomain, \ 1, \ T, \ kCpuExecutionProvider, \ KernelDefBuilder() \ .TypeConstraint("T", DataTypeImpl::GetTensorType<T>()), \ LayerNormGrad<T, false>); \ ONNX_OPERATOR_TYPED_KERNEL_EX( \ SimplifiedLayerNormalizationGrad, \ kMSDomain, \ 1, \ T, \ kCpuExecutionProvider, \ KernelDefBuilder() \ .TypeConstraint("T", DataTypeImpl::GetTensorType<T>()), \ LayerNormGrad<T, true>); \ ONNX_OPERATOR_TYPED_KERNEL_EX( \ InvertibleLayerNormalizationGrad, \ kMSDomain, \ 1, \ T, \ kCpuExecutionProvider, \ KernelDefBuilder() \ .TypeConstraint("T", DataTypeImpl::GetTensorType<T>()), \ InvertibleLayerNormGrad<T>); REGISTER_KERNEL_TYPED(float) REGISTER_KERNEL_TYPED(double) #undef REGISTER_KERNEL_TYPED template <typename T, bool simplified> LayerNormGrad<T, simplified>::LayerNormGrad(const OpKernelInfo& op_kernel_info) : OpKernel{op_kernel_info} { ORT_ENFORCE(op_kernel_info.GetAttr("axis", &axis_).IsOK()); } template <typename T, bool simplified> Status LayerNormGrad<T, simplified>::Compute(OpKernelContext* op_kernel_context) const { int input_index = 0; const Tensor* Y_grad = op_kernel_context->Input<Tensor>(input_index++); const Tensor* X = op_kernel_context->Input<Tensor>(input_index++); const auto& X_shape = X->Shape(); const auto axis = HandleNegativeAxis(axis_, X_shape.NumDimensions()); ORT_ENFORCE(X_shape.SizeToDimension(axis) <= std::numeric_limits<Eigen::Index>::max()); ORT_ENFORCE(X_shape.SizeFromDimension(axis) <= std::numeric_limits<Eigen::Index>::max()); const auto N = static_cast<Eigen::Index>(X_shape.SizeToDimension(axis)); const auto M = static_cast<Eigen::Index>(X_shape.SizeFromDimension(axis)); ORT_ENFORCE(M != 1); const Tensor* scale = op_kernel_context->Input<Tensor>(input_index++); const Tensor* mean; if (!simplified) { mean = op_kernel_context->Input<Tensor>(input_index++); } const Tensor* inv_std_var = op_kernel_context->Input<Tensor>(input_index); const auto& scale_shape = scale->Shape(); Tensor* X_grad = op_kernel_context->Output(0, X_shape); Tensor* scale_grad = op_kernel_context->Output(1, scale_shape); Tensor* bias_grad = (!simplified) ? op_kernel_context->Output(2, scale_shape) : nullptr; // Note: Eigen has column-major storage order by default ConstEigenArrayMap<T> Y_grad_arr{Y_grad->Data<T>(), M, N}; ConstEigenArrayMap<T> X_arr{X->Data<T>(), M, N}; ConstEigenVectorArrayMap<T> scale_vec{scale->Data<T>(), M}; ConstEigenVectorArrayMap<float> mean_vec{simplified ? nullptr : mean->Data<float>(), N}; ConstEigenVectorArrayMap<float> inv_std_var_vec{inv_std_var->Data<float>(), N}; EigenArrayMap<T> X_grad_arr{X_grad->MutableData<T>(), M, N}; EigenVectorArrayMap<T> scale_grad_vec{scale_grad->MutableData<T>(), M}; EigenVectorArrayMap<T> bias_grad_vec = (!simplified) ? EigenVectorArrayMap<T>{bias_grad->MutableData<T>(), M} : EigenVectorArrayMap<T>{nullptr, 0}; using Array = Eigen::ArrayXX<T>; using RowVector = Eigen::Array<T, 1, Eigen::Dynamic>; // A, B, C are calculated as below: // A = Y_grad * (X - mean(X)) * inv_std_var // B = Y_grad * scale * inv_std_var // C = Y_grad * scale * inv_std_var * (X - mean(X)) * inv_std_var // Simplified Layer Norm // A = Y_grad * X * inv_std_var // B = Y_grad * scale * inv_std_var // C = Y_grad * scale * inv_std_var * X * inv_std_var // A, B, and C are M x N Array X_mean_difference_over_std_var; if (simplified) { X_mean_difference_over_std_var = X_arr.rowwise() * inv_std_var_vec.cast<T>().transpose(); } else { X_mean_difference_over_std_var = (X_arr.rowwise() - mean_vec.cast<T>().transpose()).rowwise() * inv_std_var_vec.cast<T>().transpose(); } Array A = Y_grad_arr * X_mean_difference_over_std_var; Array B = (Y_grad_arr.colwise() * scale_vec).rowwise() * inv_std_var_vec.cast<T>().transpose(); Array C = B * X_mean_difference_over_std_var; RowVector mean_C = C.colwise().mean(); // 1 x N if (simplified) { X_grad_arr = B - X_mean_difference_over_std_var.rowwise() * mean_C; } else { RowVector mean_B = B.colwise().mean(); // 1 x N X_grad_arr = B.rowwise() - mean_B - X_mean_difference_over_std_var.rowwise() * mean_C; } if (!simplified) { bias_grad_vec = Y_grad_arr.rowwise().sum(); } scale_grad_vec = A.rowwise().sum(); return Status::OK(); } template <typename T> InvertibleLayerNormGrad<T>::InvertibleLayerNormGrad(const OpKernelInfo& op_kernel_info) : OpKernel{op_kernel_info} { ORT_ENFORCE(op_kernel_info.GetAttr("axis", &axis_).IsOK()); } template <typename T> Status InvertibleLayerNormGrad<T>::Compute(OpKernelContext* op_kernel_context) const { const Tensor* Y_grad = op_kernel_context->Input<Tensor>(0); const Tensor* Y = op_kernel_context->Input<Tensor>(1); const Tensor* scale = op_kernel_context->Input<Tensor>(2); const Tensor* bias = op_kernel_context->Input<Tensor>(3); const Tensor* inv_std_var = op_kernel_context->Input<Tensor>(4); const auto& Y_shape = Y_grad->Shape(); const auto& X_shape = Y_shape; const auto axis = HandleNegativeAxis(axis_, X_shape.NumDimensions()); ORT_ENFORCE(X_shape.SizeToDimension(axis) <= std::numeric_limits<Eigen::Index>::max()); ORT_ENFORCE(X_shape.SizeFromDimension(axis) <= std::numeric_limits<Eigen::Index>::max()); const auto N = static_cast<Eigen::Index>(X_shape.SizeToDimension(axis)); const auto M = static_cast<Eigen::Index>(X_shape.SizeFromDimension(axis)); ORT_ENFORCE(M != 1); const auto& scale_shape = scale->Shape(); Tensor* X_grad = op_kernel_context->Output(0, X_shape); Tensor* scale_grad = op_kernel_context->Output(1, scale_shape); Tensor* bias_grad = op_kernel_context->Output(2, scale_shape); // Note: Eigen has column-major storage order by default ConstEigenArrayMap<T> Y_grad_arr{Y_grad->Data<T>(), M, N}; ConstEigenArrayMap<T> Y_arr{Y->Data<T>(), M, N}; ConstEigenVectorArrayMap<T> scale_vec{scale->Data<T>(), M}; ConstEigenVectorArrayMap<T> bias_vec{bias->Data<T>(), M}; ConstEigenVectorArrayMap<float> inv_std_var_vec{inv_std_var->Data<float>(), N}; EigenArrayMap<T> X_grad_arr{X_grad->MutableData<T>(), M, N}; EigenVectorArrayMap<T> scale_grad_vec{scale_grad->MutableData<T>(), M}; EigenVectorArrayMap<T> bias_grad_vec{bias_grad->MutableData<T>(), M}; using Array = Eigen::ArrayXX<T>; using RowVector = Eigen::Array<T, 1, Eigen::Dynamic>; // A, B, C are calculated as below: // A = Y_grad * (X - mean(X)) * inv_std_var // B = Y_grad * scale * inv_std_var // C = Y_grad * scale * inv_std_var * (X - mean(X)) * inv_std_var // A, B, and C are M x N Array X_mean_difference_over_std_var = (Y_arr.colwise() - bias_vec).colwise() / scale_vec; Array A = Y_grad_arr * X_mean_difference_over_std_var; Array B = (Y_grad_arr.colwise() * scale_vec).rowwise() * inv_std_var_vec.cast<T>().transpose(); Array C = B * X_mean_difference_over_std_var; // mean_B = mean(Y_grad * scale * inv_std_var) RowVector mean_B = B.colwise().mean(); // 1 x N // mean_C = mean(Y_grad * scale * inv_std_var * (X - mean(X)) * inv_std_var) RowVector mean_C = C.colwise().mean(); // 1 x N // X_grad = Y_grad * scale * inv_std_var - mean_B - (X - mean(X)) * inv_std_var * mean_C // = B - mean_B - (X - mean(X)) * inv_std_var * mean_c X_grad_arr = B.rowwise() - mean_B - X_mean_difference_over_std_var.rowwise() * mean_C; // bias_grad = sum(Y_grad) bias_grad_vec = Y_grad_arr.rowwise().sum(); // scale_grad = sum(Y_grad * (X - mean(X)) * inv_std_var) // = sum(A) scale_grad_vec = A.rowwise().sum(); return Status::OK(); } } // namespace contrib } // namespace onnxruntime
Fix layer_norm.cc on x86 (#6556)
Fix layer_norm.cc on x86 (#6556) * Fix LayerNromGrad on x86 * PR feedback
C++
mit
microsoft/onnxruntime,microsoft/onnxruntime,microsoft/onnxruntime,microsoft/onnxruntime,microsoft/onnxruntime,microsoft/onnxruntime,microsoft/onnxruntime,microsoft/onnxruntime,microsoft/onnxruntime,microsoft/onnxruntime,microsoft/onnxruntime,microsoft/onnxruntime
429d5457ab34e37c8126b47ef4328db7f650bf02
src/cpp/session/modules/SessionCodeSearch.cpp
src/cpp/session/modules/SessionCodeSearch.cpp
/* * SessionCodeSearch.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 "SessionCodeSearch.hpp" #include <iostream> #include <vector> #include <set> #include <boost/bind.hpp> #include <boost/shared_ptr.hpp> #include <boost/foreach.hpp> #include <boost/format.hpp> #include <boost/algorithm/string/predicate.hpp> #include <core/Error.hpp> #include <core/Exec.hpp> #include <core/FilePath.hpp> #include <core/FileSerializer.hpp> #include <core/SafeConvert.hpp> #include <core/r_util/RSourceIndex.hpp> #include <core/system/FileChangeEvent.hpp> #include <core/system/FileMonitor.hpp> #include <R_ext/rlocale.h> #include <session/SessionUserSettings.hpp> #include <session/SessionModuleContext.hpp> #include <session/projects/SessionProjects.hpp> #include "SessionSource.hpp" // TODO: pref for "index R code" in projects using namespace core ; namespace session { namespace modules { namespace code_search { namespace { class SourceFileIndex : boost::noncopyable { public: SourceFileIndex() : indexing_(false) { } virtual ~SourceFileIndex() { } // COPYING: prohibited template <typename ForwardIterator> void enqueFiles(ForwardIterator begin, ForwardIterator end) { // add all R source files to the indexing queue using namespace core::system; for ( ; begin != end; ++begin) { if (isRSourceFile(*begin)) { FileChangeEvent addEvent(FileChangeEvent::FileAdded, *begin); indexingQueue_.push(addEvent); } } // schedule indexing if necessary. perform up to 200ms of work // immediately and then continue in periodic 20ms chunks until // we are completed. if (!indexing_) { indexing_ = true; module_context::scheduleIncrementalWork( boost::posix_time::milliseconds(200), boost::posix_time::milliseconds(20), boost::bind(&SourceFileIndex::dequeAndIndex, this), false /* allow indexing even when non-idle */); } } void enqueFileChange(const core::system::FileChangeEvent& event) { // screen out files which aren't R source files if (!isRSourceFile(event.fileInfo())) return; // add to the queue indexingQueue_.push(event); // schedule indexing if necessary. don't index anything immediately // (this is to defend against large numbers of files being enqued // at once and typing up the main thread). rather, schedule indexing // to occur during idle time in 20ms chunks if (!indexing_) { indexing_ = true; module_context::scheduleIncrementalWork( boost::posix_time::milliseconds(20), boost::bind(&SourceFileIndex::dequeAndIndex, this), false /* allow indexing even when non-idle */); } } void searchSource(const std::string& term, std::size_t maxResults, bool prefixOnly, const std::set<std::string>& excludeContexts, std::vector<r_util::RSourceItem>* pItems) { BOOST_FOREACH(const Entry& entry, entries_) { // bail if this is an exluded context if (excludeContexts.find(entry.pIndex->context()) != excludeContexts.end()) continue; // scan the next index entry.pIndex->search(term, prefixOnly, false, std::back_inserter(*pItems)); // return if we are past maxResults if (pItems->size() >= maxResults) { pItems->resize(maxResults); return; } } } void searchFiles(const std::string& term, std::size_t maxResults, bool prefixOnly, json::Array* pNames, json::Array* pPaths, bool* pMoreAvailable) { // default to no more available *pMoreAvailable = false; // create wildcard pattern if the search has a '*' bool hasWildcard = term.find('*') != std::string::npos; boost::regex pattern; if (hasWildcard) pattern = regex_utils::wildcardPatternToRegex(term); // iterate over the files FilePath projectRoot = projects::projectContext().directory(); BOOST_FOREACH(const Entry& entry, entries_) { // get the next file FilePath filePath(entry.fileInfo.absolutePath()); // get name for comparison std::string name = filePath.filename(); // compare for match (wildcard or standard) bool matches = false; if (hasWildcard) { matches = regex_utils::textMatches(name, pattern, prefixOnly, false); } else { if (prefixOnly) matches = boost::algorithm::istarts_with(name, term); else matches = boost::algorithm::icontains(name, term); } // add the file if we found a match if (matches) { // name and project relative directory pNames->push_back(filePath.filename()); pPaths->push_back(filePath.relativePath(projectRoot)); // return if we are past max results if (pNames->size() > maxResults) { *pMoreAvailable = true; pNames->resize(maxResults); pPaths->resize(maxResults); return; } } } } private: // index entries we are managing struct Entry { Entry(const FileInfo& fileInfo, boost::shared_ptr<core::r_util::RSourceIndex> pIndex) : fileInfo(fileInfo), pIndex(pIndex) { } FileInfo fileInfo; boost::shared_ptr<core::r_util::RSourceIndex> pIndex; bool operator < (const Entry& other) const { return core::fileInfoPathLessThan(fileInfo, other.fileInfo); } }; private: bool dequeAndIndex() { using namespace core::system; // remove the event from the queue FileChangeEvent event = indexingQueue_.front(); indexingQueue_.pop(); // process the change const FileInfo& fileInfo = event.fileInfo(); switch(event.type()) { case FileChangeEvent::FileAdded: case FileChangeEvent::FileModified: { updateIndexEntry(fileInfo); break; } case FileChangeEvent::FileRemoved: { removeIndexEntry(fileInfo); break; } case FileChangeEvent::None: break; } // return status indexing_ = !indexingQueue_.empty(); return indexing_; } void updateIndexEntry(const FileInfo& fileInfo) { // read the file FilePath filePath(fileInfo.absolutePath()); std::string code; Error error = module_context::readAndDecodeFile( filePath, projects::projectContext().defaultEncoding(), true, &code); if (error) { error.addProperty("src-file", filePath.absolutePath()); LOG_ERROR(error); return; } // compute project relative directory (used for context) std::string context = filePath.relativePath(projects::projectContext().directory()); // index the source boost::shared_ptr<r_util::RSourceIndex> pIndex( new r_util::RSourceIndex(context, code)); // attempt to add the entry Entry entry(fileInfo, pIndex); std::pair<std::set<Entry>::iterator,bool> result = entries_.insert(entry); // insert failed, remove then re-add if (result.second == false) { entries_.erase(result.first); entries_.insert(entry); } } void removeIndexEntry(const FileInfo& fileInfo) { // create a fake entry with a null source index to pass to find Entry entry(fileInfo, boost::shared_ptr<r_util::RSourceIndex>()); // do the find (will use Entry::operator< for equivilance test) std::set<Entry>::iterator it = entries_.find(entry); if (it != entries_.end()) entries_.erase(it); } static bool isRSourceFile(const FileInfo& fileInfo) { FilePath filePath(fileInfo.absolutePath()); return !filePath.isDirectory() && filePath.extensionLowerCase() == ".r"; } private: // index entries std::set<Entry> entries_; // indexing queue bool indexing_; std::queue<core::system::FileChangeEvent> indexingQueue_; }; // global source file index SourceFileIndex s_projectIndex; void searchSourceDatabase(const std::string& term, std::size_t maxResults, bool prefixOnly, std::vector<r_util::RSourceItem>* pItems, std::set<std::string>* pContextsSearched) { // get all of the source indexes std::vector<boost::shared_ptr<r_util::RSourceIndex> > rIndexes = modules::source::rIndexes(); BOOST_FOREACH(boost::shared_ptr<r_util::RSourceIndex>& pIndex, rIndexes) { // get file path FilePath docPath = module_context::resolveAliasedPath(pIndex->context()); // bail if the file isn't in the project std::string projRelativePath = docPath.relativePath(projects::projectContext().directory()); if (projRelativePath.empty()) continue; // record that we searched this path pContextsSearched->insert(projRelativePath); // scan the source index pIndex->search(term, projRelativePath, prefixOnly, false, std::back_inserter(*pItems)); // return if we are past maxResults if (pItems->size() >= maxResults) { pItems->resize(maxResults); return; } } } void searchSource(const std::string& term, std::size_t maxResults, bool prefixOnly, std::vector<r_util::RSourceItem>* pItems, bool* pMoreAvailable) { // default to no more available *pMoreAvailable = false; // first search the source database std::set<std::string> srcDBContexts; searchSourceDatabase(term, maxResults, prefixOnly, pItems, &srcDBContexts); // we are done if we had >= maxResults if (pItems->size() > maxResults) { *pMoreAvailable = true; pItems->resize(maxResults); return; } // compute project max results based on existing results std::size_t maxProjResults = maxResults - pItems->size(); // now search the project (excluding contexts already searched in the source db) std::vector<r_util::RSourceItem> projItems; s_projectIndex.searchSource(term, maxProjResults, prefixOnly, srcDBContexts, &projItems); // add project items to the list BOOST_FOREACH(const r_util::RSourceItem& sourceItem, projItems) { // add the item pItems->push_back(sourceItem); // bail if we've hit the max if (pItems->size() > maxResults) { *pMoreAvailable = true; pItems->resize(maxResults); break; } } } template <typename TValue, typename TFunc> json::Array toJsonArray( const std::vector<r_util::RSourceItem> &items, TFunc memberFunc) { json::Array col; std::transform(items.begin(), items.end(), std::back_inserter(col), boost::bind(json::toJsonValue<TValue>, boost::bind(memberFunc, _1))); return col; } bool compareItems(const r_util::RSourceItem& i1, const r_util::RSourceItem& i2) { return i1.name() < i2.name(); } Error searchCode(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { // get params std::string term; int maxResultsInt; Error error = json::readParams(request.params, &term, &maxResultsInt); if (error) return error; std::size_t maxResults = safe_convert::numberTo<std::size_t>(maxResultsInt, 20); // object to return json::Object result; // search files json::Array names; json::Array paths; bool moreFilesAvailable = false; s_projectIndex.searchFiles(term, maxResults, true, &names, &paths, &moreFilesAvailable); json::Object files; files["filename"] = names; files["path"] = paths; result["file_items"] = files; // search source (sort results by name) std::vector<r_util::RSourceItem> items; bool moreSourceItemsAvailable = false; searchSource(term, maxResults, true, &items, &moreSourceItemsAvailable); std::sort(items.begin(), items.end(), compareItems); // see if we need to do src truncation bool truncated = false; if ( (names.size() + items.size()) > maxResults ) { // truncate source items std::size_t srcItems = maxResults - names.size(); items.resize(srcItems); truncated = true; } // return rpc array list (wire efficiency) json::Object src; src["type"] = toJsonArray<int>(items, &r_util::RSourceItem::type); src["name"] = toJsonArray<std::string>(items, &r_util::RSourceItem::name); src["context"] = toJsonArray<std::string>(items, &r_util::RSourceItem::context); src["line"] = toJsonArray<int>(items, &r_util::RSourceItem::line); src["column"] = toJsonArray<int>(items, &r_util::RSourceItem::column); result["source_items"] = src; // set more available bit result["more_available"] = moreFilesAvailable || moreSourceItemsAvailable || truncated; pResponse->setResult(result); return Success(); } void onFileMonitorRegistered(const tree<core::FileInfo>& files) { s_projectIndex.enqueFiles(files.begin_leaf(), files.end_leaf()); } void onFileMonitoringError(const core::Error& error) { // file monitoring either didn't work or has stopped working // notify the client it should disable code searching ClientEvent event(client_events::kCodeIndexingDisabled); module_context::enqueClientEvent(event); // print a warning to the console so the user knows std::string dir = module_context::createAliasedPath( projects::projectContext().directory()); boost::format fmt( "Warning message:\n" "File monitoring failed for directory \"%1%\"; code search features " "are not available for this project [%2% - %3%]"); module_context::consoleWriteError(boost::str( fmt % dir % error.code().value() % error.code().message())); } void onFilesChanged(const std::vector<core::system::FileChangeEvent>& events) { // index all of the changes std::for_each( events.begin(), events.end(), boost::bind(&SourceFileIndex::enqueFileChange, &s_projectIndex, _1)); } } // anonymous namespace bool enabled() { return projects::projectContext().hasFileMonitor(); } Error initialize() { // subscribe to project context file monitoring state changes core::system::file_monitor::Callbacks cb; cb.onRegistered = boost::bind(onFileMonitorRegistered, _2); cb.onRegistrationError = onFileMonitoringError; cb.onMonitoringError = onFileMonitoringError; cb.onFilesChanged = onFilesChanged; projects::projectContext().registerFileMonitorCallbacks(cb); using boost::bind; using namespace module_context; ExecBlock initBlock ; initBlock.addFunctions() (bind(registerRpcMethod, "search_code", searchCode)); ; return initBlock.execute(); } } // namespace code_search } // namespace modules } // namespace session
/* * SessionCodeSearch.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 "SessionCodeSearch.hpp" #include <iostream> #include <vector> #include <set> #include <boost/bind.hpp> #include <boost/shared_ptr.hpp> #include <boost/foreach.hpp> #include <boost/format.hpp> #include <boost/algorithm/string/predicate.hpp> #include <core/Error.hpp> #include <core/Exec.hpp> #include <core/FilePath.hpp> #include <core/FileSerializer.hpp> #include <core/SafeConvert.hpp> #include <core/r_util/RSourceIndex.hpp> #include <core/system/FileChangeEvent.hpp> #include <core/system/FileMonitor.hpp> #include <R_ext/rlocale.h> #include <session/SessionUserSettings.hpp> #include <session/SessionModuleContext.hpp> #include <session/projects/SessionProjects.hpp> #include "SessionSource.hpp" // TODO: pref for "index R code" in projects // TODO: further optimize modify of code index? // TODO: cleaner API for registering project level file monitor dependencies // TODO: don't cache empty code search result sets (return from suspend) // TODO: is reset on the check for changes invalidator on save okay? // (miss changes immediately after save) using namespace core ; namespace session { namespace modules { namespace code_search { namespace { class SourceFileIndex : boost::noncopyable { public: SourceFileIndex() : indexing_(false) { } virtual ~SourceFileIndex() { } // COPYING: prohibited template <typename ForwardIterator> void enqueFiles(ForwardIterator begin, ForwardIterator end) { // add all R source files to the indexing queue using namespace core::system; for ( ; begin != end; ++begin) { if (isRSourceFile(*begin)) { FileChangeEvent addEvent(FileChangeEvent::FileAdded, *begin); indexingQueue_.push(addEvent); } } // schedule indexing if necessary. perform up to 200ms of work // immediately and then continue in periodic 20ms chunks until // we are completed. if (!indexing_) { indexing_ = true; module_context::scheduleIncrementalWork( boost::posix_time::milliseconds(200), boost::posix_time::milliseconds(20), boost::bind(&SourceFileIndex::dequeAndIndex, this), false /* allow indexing even when non-idle */); } } void enqueFileChange(const core::system::FileChangeEvent& event) { // screen out files which aren't R source files if (!isRSourceFile(event.fileInfo())) return; // add to the queue indexingQueue_.push(event); // schedule indexing if necessary. don't index anything immediately // (this is to defend against large numbers of files being enqued // at once and typing up the main thread). rather, schedule indexing // to occur during idle time in 20ms chunks if (!indexing_) { indexing_ = true; module_context::scheduleIncrementalWork( boost::posix_time::milliseconds(20), boost::bind(&SourceFileIndex::dequeAndIndex, this), false /* allow indexing even when non-idle */); } } void searchSource(const std::string& term, std::size_t maxResults, bool prefixOnly, const std::set<std::string>& excludeContexts, std::vector<r_util::RSourceItem>* pItems) { BOOST_FOREACH(const Entry& entry, entries_) { // bail if this is an exluded context if (excludeContexts.find(entry.pIndex->context()) != excludeContexts.end()) continue; // scan the next index entry.pIndex->search(term, prefixOnly, false, std::back_inserter(*pItems)); // return if we are past maxResults if (pItems->size() >= maxResults) { pItems->resize(maxResults); return; } } } void searchFiles(const std::string& term, std::size_t maxResults, bool prefixOnly, json::Array* pNames, json::Array* pPaths, bool* pMoreAvailable) { // default to no more available *pMoreAvailable = false; // create wildcard pattern if the search has a '*' bool hasWildcard = term.find('*') != std::string::npos; boost::regex pattern; if (hasWildcard) pattern = regex_utils::wildcardPatternToRegex(term); // iterate over the files FilePath projectRoot = projects::projectContext().directory(); BOOST_FOREACH(const Entry& entry, entries_) { // get the next file FilePath filePath(entry.fileInfo.absolutePath()); // get name for comparison std::string name = filePath.filename(); // compare for match (wildcard or standard) bool matches = false; if (hasWildcard) { matches = regex_utils::textMatches(name, pattern, prefixOnly, false); } else { if (prefixOnly) matches = boost::algorithm::istarts_with(name, term); else matches = boost::algorithm::icontains(name, term); } // add the file if we found a match if (matches) { // name and project relative directory pNames->push_back(filePath.filename()); pPaths->push_back(filePath.relativePath(projectRoot)); // return if we are past max results if (pNames->size() > maxResults) { *pMoreAvailable = true; pNames->resize(maxResults); pPaths->resize(maxResults); return; } } } } private: // index entries we are managing struct Entry { Entry(const FileInfo& fileInfo, boost::shared_ptr<core::r_util::RSourceIndex> pIndex) : fileInfo(fileInfo), pIndex(pIndex) { } FileInfo fileInfo; boost::shared_ptr<core::r_util::RSourceIndex> pIndex; bool operator < (const Entry& other) const { return core::fileInfoPathLessThan(fileInfo, other.fileInfo); } }; private: bool dequeAndIndex() { using namespace core::system; // remove the event from the queue FileChangeEvent event = indexingQueue_.front(); indexingQueue_.pop(); // process the change const FileInfo& fileInfo = event.fileInfo(); switch(event.type()) { case FileChangeEvent::FileAdded: case FileChangeEvent::FileModified: { updateIndexEntry(fileInfo); break; } case FileChangeEvent::FileRemoved: { removeIndexEntry(fileInfo); break; } case FileChangeEvent::None: break; } // return status indexing_ = !indexingQueue_.empty(); return indexing_; } void updateIndexEntry(const FileInfo& fileInfo) { // read the file FilePath filePath(fileInfo.absolutePath()); std::string code; Error error = module_context::readAndDecodeFile( filePath, projects::projectContext().defaultEncoding(), true, &code); if (error) { error.addProperty("src-file", filePath.absolutePath()); LOG_ERROR(error); return; } // compute project relative directory (used for context) std::string context = filePath.relativePath(projects::projectContext().directory()); // index the source boost::shared_ptr<r_util::RSourceIndex> pIndex( new r_util::RSourceIndex(context, code)); // attempt to add the entry Entry entry(fileInfo, pIndex); std::pair<std::set<Entry>::iterator,bool> result = entries_.insert(entry); // insert failed, remove then re-add if (result.second == false) { entries_.erase(result.first); entries_.insert(entry); } } void removeIndexEntry(const FileInfo& fileInfo) { // create a fake entry with a null source index to pass to find Entry entry(fileInfo, boost::shared_ptr<r_util::RSourceIndex>()); // do the find (will use Entry::operator< for equivilance test) std::set<Entry>::iterator it = entries_.find(entry); if (it != entries_.end()) entries_.erase(it); } static bool isRSourceFile(const FileInfo& fileInfo) { FilePath filePath(fileInfo.absolutePath()); return !filePath.isDirectory() && filePath.extensionLowerCase() == ".r"; } private: // index entries std::set<Entry> entries_; // indexing queue bool indexing_; std::queue<core::system::FileChangeEvent> indexingQueue_; }; // global source file index SourceFileIndex s_projectIndex; void searchSourceDatabase(const std::string& term, std::size_t maxResults, bool prefixOnly, std::vector<r_util::RSourceItem>* pItems, std::set<std::string>* pContextsSearched) { // get all of the source indexes std::vector<boost::shared_ptr<r_util::RSourceIndex> > rIndexes = modules::source::rIndexes(); BOOST_FOREACH(boost::shared_ptr<r_util::RSourceIndex>& pIndex, rIndexes) { // get file path FilePath docPath = module_context::resolveAliasedPath(pIndex->context()); // bail if the file isn't in the project std::string projRelativePath = docPath.relativePath(projects::projectContext().directory()); if (projRelativePath.empty()) continue; // record that we searched this path pContextsSearched->insert(projRelativePath); // scan the source index pIndex->search(term, projRelativePath, prefixOnly, false, std::back_inserter(*pItems)); // return if we are past maxResults if (pItems->size() >= maxResults) { pItems->resize(maxResults); return; } } } void searchSource(const std::string& term, std::size_t maxResults, bool prefixOnly, std::vector<r_util::RSourceItem>* pItems, bool* pMoreAvailable) { // default to no more available *pMoreAvailable = false; // first search the source database std::set<std::string> srcDBContexts; searchSourceDatabase(term, maxResults, prefixOnly, pItems, &srcDBContexts); // we are done if we had >= maxResults if (pItems->size() > maxResults) { *pMoreAvailable = true; pItems->resize(maxResults); return; } // compute project max results based on existing results std::size_t maxProjResults = maxResults - pItems->size(); // now search the project (excluding contexts already searched in the source db) std::vector<r_util::RSourceItem> projItems; s_projectIndex.searchSource(term, maxProjResults, prefixOnly, srcDBContexts, &projItems); // add project items to the list BOOST_FOREACH(const r_util::RSourceItem& sourceItem, projItems) { // add the item pItems->push_back(sourceItem); // bail if we've hit the max if (pItems->size() > maxResults) { *pMoreAvailable = true; pItems->resize(maxResults); break; } } } template <typename TValue, typename TFunc> json::Array toJsonArray( const std::vector<r_util::RSourceItem> &items, TFunc memberFunc) { json::Array col; std::transform(items.begin(), items.end(), std::back_inserter(col), boost::bind(json::toJsonValue<TValue>, boost::bind(memberFunc, _1))); return col; } bool compareItems(const r_util::RSourceItem& i1, const r_util::RSourceItem& i2) { return i1.name() < i2.name(); } Error searchCode(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { // get params std::string term; int maxResultsInt; Error error = json::readParams(request.params, &term, &maxResultsInt); if (error) return error; std::size_t maxResults = safe_convert::numberTo<std::size_t>(maxResultsInt, 20); // object to return json::Object result; // search files json::Array names; json::Array paths; bool moreFilesAvailable = false; s_projectIndex.searchFiles(term, maxResults, true, &names, &paths, &moreFilesAvailable); json::Object files; files["filename"] = names; files["path"] = paths; result["file_items"] = files; // search source (sort results by name) std::vector<r_util::RSourceItem> items; bool moreSourceItemsAvailable = false; searchSource(term, maxResults, true, &items, &moreSourceItemsAvailable); std::sort(items.begin(), items.end(), compareItems); // see if we need to do src truncation bool truncated = false; if ( (names.size() + items.size()) > maxResults ) { // truncate source items std::size_t srcItems = maxResults - names.size(); items.resize(srcItems); truncated = true; } // return rpc array list (wire efficiency) json::Object src; src["type"] = toJsonArray<int>(items, &r_util::RSourceItem::type); src["name"] = toJsonArray<std::string>(items, &r_util::RSourceItem::name); src["context"] = toJsonArray<std::string>(items, &r_util::RSourceItem::context); src["line"] = toJsonArray<int>(items, &r_util::RSourceItem::line); src["column"] = toJsonArray<int>(items, &r_util::RSourceItem::column); result["source_items"] = src; // set more available bit result["more_available"] = moreFilesAvailable || moreSourceItemsAvailable || truncated; pResponse->setResult(result); return Success(); } void onFileMonitorRegistered(const tree<core::FileInfo>& files) { s_projectIndex.enqueFiles(files.begin_leaf(), files.end_leaf()); } void onFileMonitoringError(const core::Error& error) { // file monitoring either didn't work or has stopped working // notify the client it should disable code searching ClientEvent event(client_events::kCodeIndexingDisabled); module_context::enqueClientEvent(event); // print a warning to the console so the user knows std::string dir = module_context::createAliasedPath( projects::projectContext().directory()); boost::format fmt( "Warning message:\n" "File monitoring failed for directory \"%1%\"; code search features " "are not available for this project [%2% - %3%]"); module_context::consoleWriteError(boost::str( fmt % dir % error.code().value() % error.code().message())); } void onFilesChanged(const std::vector<core::system::FileChangeEvent>& events) { // index all of the changes std::for_each( events.begin(), events.end(), boost::bind(&SourceFileIndex::enqueFileChange, &s_projectIndex, _1)); } } // anonymous namespace bool enabled() { return projects::projectContext().hasFileMonitor(); } Error initialize() { // subscribe to project context file monitoring state changes core::system::file_monitor::Callbacks cb; cb.onRegistered = boost::bind(onFileMonitorRegistered, _2); cb.onRegistrationError = onFileMonitoringError; cb.onMonitoringError = onFileMonitoringError; cb.onFilesChanged = onFilesChanged; projects::projectContext().registerFileMonitorCallbacks(cb); using boost::bind; using namespace module_context; ExecBlock initBlock ; initBlock.addFunctions() (bind(registerRpcMethod, "search_code", searchCode)); ; return initBlock.execute(); } } // namespace code_search } // namespace modules } // namespace session
update code search todos
update code search todos
C++
agpl-3.0
githubfun/rstudio,jzhu8803/rstudio,edrogers/rstudio,Sage-Bionetworks/rstudio,thklaus/rstudio,john-r-mcpherson/rstudio,suribes/rstudio,brsimioni/rstudio,jar1karp/rstudio,sfloresm/rstudio,githubfun/rstudio,more1/rstudio,githubfun/rstudio,jar1karp/rstudio,jrnold/rstudio,more1/rstudio,jar1karp/rstudio,pssguy/rstudio,sfloresm/rstudio,JanMarvin/rstudio,jrnold/rstudio,vbelakov/rstudio,thklaus/rstudio,jar1karp/rstudio,jrnold/rstudio,JanMarvin/rstudio,pssguy/rstudio,john-r-mcpherson/rstudio,suribes/rstudio,jrnold/rstudio,john-r-mcpherson/rstudio,piersharding/rstudio,Sage-Bionetworks/rstudio,githubfun/rstudio,edrogers/rstudio,john-r-mcpherson/rstudio,pssguy/rstudio,nvoron23/rstudio,piersharding/rstudio,vbelakov/rstudio,Sage-Bionetworks/rstudio,JanMarvin/rstudio,thklaus/rstudio,brsimioni/rstudio,jzhu8803/rstudio,jar1karp/rstudio,githubfun/rstudio,jzhu8803/rstudio,brsimioni/rstudio,tbarrongh/rstudio,githubfun/rstudio,brsimioni/rstudio,jzhu8803/rstudio,thklaus/rstudio,maligulzar/Rstudio-instrumented,vbelakov/rstudio,sfloresm/rstudio,maligulzar/Rstudio-instrumented,brsimioni/rstudio,brsimioni/rstudio,brsimioni/rstudio,nvoron23/rstudio,pssguy/rstudio,JanMarvin/rstudio,thklaus/rstudio,tbarrongh/rstudio,edrogers/rstudio,pssguy/rstudio,tbarrongh/rstudio,piersharding/rstudio,githubfun/rstudio,githubfun/rstudio,piersharding/rstudio,suribes/rstudio,thklaus/rstudio,JanMarvin/rstudio,Sage-Bionetworks/rstudio,maligulzar/Rstudio-instrumented,more1/rstudio,jar1karp/rstudio,john-r-mcpherson/rstudio,pssguy/rstudio,vbelakov/rstudio,nvoron23/rstudio,tbarrongh/rstudio,maligulzar/Rstudio-instrumented,jar1karp/rstudio,nvoron23/rstudio,sfloresm/rstudio,vbelakov/rstudio,edrogers/rstudio,tbarrongh/rstudio,jrnold/rstudio,jar1karp/rstudio,more1/rstudio,more1/rstudio,piersharding/rstudio,Sage-Bionetworks/rstudio,Sage-Bionetworks/rstudio,maligulzar/Rstudio-instrumented,JanMarvin/rstudio,brsimioni/rstudio,Sage-Bionetworks/rstudio,nvoron23/rstudio,thklaus/rstudio,edrogers/rstudio,sfloresm/rstudio,tbarrongh/rstudio,more1/rstudio,sfloresm/rstudio,piersharding/rstudio,suribes/rstudio,piersharding/rstudio,tbarrongh/rstudio,jzhu8803/rstudio,vbelakov/rstudio,suribes/rstudio,jzhu8803/rstudio,JanMarvin/rstudio,maligulzar/Rstudio-instrumented,edrogers/rstudio,maligulzar/Rstudio-instrumented,jzhu8803/rstudio,jrnold/rstudio,edrogers/rstudio,JanMarvin/rstudio,piersharding/rstudio,john-r-mcpherson/rstudio,suribes/rstudio,jar1karp/rstudio,maligulzar/Rstudio-instrumented,vbelakov/rstudio,jzhu8803/rstudio,more1/rstudio,jrnold/rstudio,nvoron23/rstudio,piersharding/rstudio,maligulzar/Rstudio-instrumented,pssguy/rstudio,vbelakov/rstudio,more1/rstudio,sfloresm/rstudio,pssguy/rstudio,JanMarvin/rstudio,john-r-mcpherson/rstudio,jrnold/rstudio,john-r-mcpherson/rstudio,nvoron23/rstudio,tbarrongh/rstudio,sfloresm/rstudio,thklaus/rstudio,jrnold/rstudio,suribes/rstudio,suribes/rstudio,edrogers/rstudio
81e0bb6816b40f4c5b14eda14cafde5ad9abfc0f
src/cpp/session/modules/SessionCodeSearch.cpp
src/cpp/session/modules/SessionCodeSearch.cpp
/* * SessionCodeSearch.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 "SessionCodeSearch.hpp" #include <iostream> #include <vector> #include <set> #include <boost/bind.hpp> #include <boost/shared_ptr.hpp> #include <boost/foreach.hpp> #include <boost/format.hpp> #include <boost/algorithm/string/predicate.hpp> #include <core/Error.hpp> #include <core/Exec.hpp> #include <core/FilePath.hpp> #include <core/FileSerializer.hpp> #include <core/SafeConvert.hpp> #include <core/r_util/RSourceIndex.hpp> #include <core/system/FileChangeEvent.hpp> #include <core/system/FileMonitor.hpp> #include <R_ext/rlocale.h> #include <session/SessionUserSettings.hpp> #include <session/SessionModuleContext.hpp> #include <session/projects/SessionProjects.hpp> #include "SessionSource.hpp" // TODO: pref for "index R code" in projects // TODO: further optimize modify of code index? // TODO: don't cache empty code search result sets (return from suspend) // TODO: is reset on the check for changes invalidator on save okay? // (miss changes immediately after save) using namespace core ; namespace session { namespace modules { namespace code_search { namespace { class SourceFileIndex : boost::noncopyable { public: SourceFileIndex() : indexing_(false) { } virtual ~SourceFileIndex() { } // COPYING: prohibited template <typename ForwardIterator> void enqueFiles(ForwardIterator begin, ForwardIterator end) { // add all R source files to the indexing queue using namespace core::system; for ( ; begin != end; ++begin) { if (isRSourceFile(*begin)) { FileChangeEvent addEvent(FileChangeEvent::FileAdded, *begin); indexingQueue_.push(addEvent); } } // schedule indexing if necessary. perform up to 200ms of work // immediately and then continue in periodic 20ms chunks until // we are completed. if (!indexing_) { indexing_ = true; module_context::scheduleIncrementalWork( boost::posix_time::milliseconds(200), boost::posix_time::milliseconds(20), boost::bind(&SourceFileIndex::dequeAndIndex, this), false /* allow indexing even when non-idle */); } } void enqueFileChange(const core::system::FileChangeEvent& event) { // screen out files which aren't R source files if (!isRSourceFile(event.fileInfo())) return; // add to the queue indexingQueue_.push(event); // schedule indexing if necessary. don't index anything immediately // (this is to defend against large numbers of files being enqued // at once and typing up the main thread). rather, schedule indexing // to occur during idle time in 20ms chunks if (!indexing_) { indexing_ = true; module_context::scheduleIncrementalWork( boost::posix_time::milliseconds(20), boost::bind(&SourceFileIndex::dequeAndIndex, this), false /* allow indexing even when non-idle */); } } void searchSource(const std::string& term, std::size_t maxResults, bool prefixOnly, const std::set<std::string>& excludeContexts, std::vector<r_util::RSourceItem>* pItems) { BOOST_FOREACH(const Entry& entry, entries_) { // bail if this is an exluded context if (excludeContexts.find(entry.pIndex->context()) != excludeContexts.end()) continue; // scan the next index entry.pIndex->search(term, prefixOnly, false, std::back_inserter(*pItems)); // return if we are past maxResults if (pItems->size() >= maxResults) { pItems->resize(maxResults); return; } } } void searchFiles(const std::string& term, std::size_t maxResults, bool prefixOnly, json::Array* pNames, json::Array* pPaths, bool* pMoreAvailable) { // default to no more available *pMoreAvailable = false; // create wildcard pattern if the search has a '*' bool hasWildcard = term.find('*') != std::string::npos; boost::regex pattern; if (hasWildcard) pattern = regex_utils::wildcardPatternToRegex(term); // iterate over the files FilePath projectRoot = projects::projectContext().directory(); BOOST_FOREACH(const Entry& entry, entries_) { // get the next file FilePath filePath(entry.fileInfo.absolutePath()); // get name for comparison std::string name = filePath.filename(); // compare for match (wildcard or standard) bool matches = false; if (hasWildcard) { matches = regex_utils::textMatches(name, pattern, prefixOnly, false); } else { if (prefixOnly) matches = boost::algorithm::istarts_with(name, term); else matches = boost::algorithm::icontains(name, term); } // add the file if we found a match if (matches) { // name and project relative directory pNames->push_back(filePath.filename()); pPaths->push_back(filePath.relativePath(projectRoot)); // return if we are past max results if (pNames->size() > maxResults) { *pMoreAvailable = true; pNames->resize(maxResults); pPaths->resize(maxResults); return; } } } } private: // index entries we are managing struct Entry { Entry(const FileInfo& fileInfo, boost::shared_ptr<core::r_util::RSourceIndex> pIndex) : fileInfo(fileInfo), pIndex(pIndex) { } FileInfo fileInfo; boost::shared_ptr<core::r_util::RSourceIndex> pIndex; bool operator < (const Entry& other) const { return core::fileInfoPathLessThan(fileInfo, other.fileInfo); } }; private: bool dequeAndIndex() { using namespace core::system; // remove the event from the queue FileChangeEvent event = indexingQueue_.front(); indexingQueue_.pop(); // process the change const FileInfo& fileInfo = event.fileInfo(); switch(event.type()) { case FileChangeEvent::FileAdded: case FileChangeEvent::FileModified: { updateIndexEntry(fileInfo); break; } case FileChangeEvent::FileRemoved: { removeIndexEntry(fileInfo); break; } case FileChangeEvent::None: break; } // return status indexing_ = !indexingQueue_.empty(); return indexing_; } void updateIndexEntry(const FileInfo& fileInfo) { // read the file FilePath filePath(fileInfo.absolutePath()); std::string code; Error error = module_context::readAndDecodeFile( filePath, projects::projectContext().defaultEncoding(), true, &code); if (error) { error.addProperty("src-file", filePath.absolutePath()); LOG_ERROR(error); return; } // compute project relative directory (used for context) std::string context = filePath.relativePath(projects::projectContext().directory()); // index the source boost::shared_ptr<r_util::RSourceIndex> pIndex( new r_util::RSourceIndex(context, code)); // attempt to add the entry Entry entry(fileInfo, pIndex); std::pair<std::set<Entry>::iterator,bool> result = entries_.insert(entry); // insert failed, remove then re-add if (result.second == false) { entries_.erase(result.first); entries_.insert(entry); } } void removeIndexEntry(const FileInfo& fileInfo) { // create a fake entry with a null source index to pass to find Entry entry(fileInfo, boost::shared_ptr<r_util::RSourceIndex>()); // do the find (will use Entry::operator< for equivilance test) std::set<Entry>::iterator it = entries_.find(entry); if (it != entries_.end()) entries_.erase(it); } static bool isRSourceFile(const FileInfo& fileInfo) { FilePath filePath(fileInfo.absolutePath()); return !filePath.isDirectory() && filePath.extensionLowerCase() == ".r"; } private: // index entries std::set<Entry> entries_; // indexing queue bool indexing_; std::queue<core::system::FileChangeEvent> indexingQueue_; }; // global source file index SourceFileIndex s_projectIndex; void searchSourceDatabase(const std::string& term, std::size_t maxResults, bool prefixOnly, std::vector<r_util::RSourceItem>* pItems, std::set<std::string>* pContextsSearched) { // get all of the source indexes std::vector<boost::shared_ptr<r_util::RSourceIndex> > rIndexes = modules::source::rIndexes(); BOOST_FOREACH(boost::shared_ptr<r_util::RSourceIndex>& pIndex, rIndexes) { // get file path FilePath docPath = module_context::resolveAliasedPath(pIndex->context()); // bail if the file isn't in the project std::string projRelativePath = docPath.relativePath(projects::projectContext().directory()); if (projRelativePath.empty()) continue; // record that we searched this path pContextsSearched->insert(projRelativePath); // scan the source index pIndex->search(term, projRelativePath, prefixOnly, false, std::back_inserter(*pItems)); // return if we are past maxResults if (pItems->size() >= maxResults) { pItems->resize(maxResults); return; } } } void searchSource(const std::string& term, std::size_t maxResults, bool prefixOnly, std::vector<r_util::RSourceItem>* pItems, bool* pMoreAvailable) { // default to no more available *pMoreAvailable = false; // first search the source database std::set<std::string> srcDBContexts; searchSourceDatabase(term, maxResults, prefixOnly, pItems, &srcDBContexts); // we are done if we had >= maxResults if (pItems->size() > maxResults) { *pMoreAvailable = true; pItems->resize(maxResults); return; } // compute project max results based on existing results std::size_t maxProjResults = maxResults - pItems->size(); // now search the project (excluding contexts already searched in the source db) std::vector<r_util::RSourceItem> projItems; s_projectIndex.searchSource(term, maxProjResults, prefixOnly, srcDBContexts, &projItems); // add project items to the list BOOST_FOREACH(const r_util::RSourceItem& sourceItem, projItems) { // add the item pItems->push_back(sourceItem); // bail if we've hit the max if (pItems->size() > maxResults) { *pMoreAvailable = true; pItems->resize(maxResults); break; } } } template <typename TValue, typename TFunc> json::Array toJsonArray( const std::vector<r_util::RSourceItem> &items, TFunc memberFunc) { json::Array col; std::transform(items.begin(), items.end(), std::back_inserter(col), boost::bind(json::toJsonValue<TValue>, boost::bind(memberFunc, _1))); return col; } bool compareItems(const r_util::RSourceItem& i1, const r_util::RSourceItem& i2) { return i1.name() < i2.name(); } Error searchCode(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { // get params std::string term; int maxResultsInt; Error error = json::readParams(request.params, &term, &maxResultsInt); if (error) return error; std::size_t maxResults = safe_convert::numberTo<std::size_t>(maxResultsInt, 20); // object to return json::Object result; // search files json::Array names; json::Array paths; bool moreFilesAvailable = false; s_projectIndex.searchFiles(term, maxResults, true, &names, &paths, &moreFilesAvailable); json::Object files; files["filename"] = names; files["path"] = paths; result["file_items"] = files; // search source (sort results by name) std::vector<r_util::RSourceItem> items; bool moreSourceItemsAvailable = false; searchSource(term, maxResults, true, &items, &moreSourceItemsAvailable); std::sort(items.begin(), items.end(), compareItems); // see if we need to do src truncation bool truncated = false; if ( (names.size() + items.size()) > maxResults ) { // truncate source items std::size_t srcItems = maxResults - names.size(); items.resize(srcItems); truncated = true; } // return rpc array list (wire efficiency) json::Object src; src["type"] = toJsonArray<int>(items, &r_util::RSourceItem::type); src["name"] = toJsonArray<std::string>(items, &r_util::RSourceItem::name); src["context"] = toJsonArray<std::string>(items, &r_util::RSourceItem::context); src["line"] = toJsonArray<int>(items, &r_util::RSourceItem::line); src["column"] = toJsonArray<int>(items, &r_util::RSourceItem::column); result["source_items"] = src; // set more available bit result["more_available"] = moreFilesAvailable || moreSourceItemsAvailable || truncated; pResponse->setResult(result); return Success(); } void onFileMonitorEnabled(const tree<core::FileInfo>& files) { s_projectIndex.enqueFiles(files.begin_leaf(), files.end_leaf()); } void onFilesChanged(const std::vector<core::system::FileChangeEvent>& events) { std::for_each( events.begin(), events.end(), boost::bind(&SourceFileIndex::enqueFileChange, &s_projectIndex, _1)); } void onFileMonitorDisabled() { ClientEvent event(client_events::kCodeIndexingDisabled); module_context::enqueClientEvent(event); } } // anonymous namespace bool enabled() { return projects::projectContext().hasFileMonitor(); } Error initialize() { // subscribe to project context file monitoring state changes session::projects::FileMonitorCallbacks cb; cb.onMonitoringEnabled = onFileMonitorEnabled; cb.onFilesChanged = onFilesChanged; cb.onMonitoringDisabled = onFileMonitorDisabled; projects::projectContext().subscribeToFileMonitor("Code searching", cb); using boost::bind; using namespace module_context; ExecBlock initBlock ; initBlock.addFunctions() (bind(registerRpcMethod, "search_code", searchCode)); ; return initBlock.execute(); } } // namespace code_search } // namespace modules } // namespace session
/* * SessionCodeSearch.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 "SessionCodeSearch.hpp" #include <iostream> #include <vector> #include <set> #include <boost/bind.hpp> #include <boost/shared_ptr.hpp> #include <boost/foreach.hpp> #include <boost/format.hpp> #include <boost/algorithm/string/predicate.hpp> #include <core/Error.hpp> #include <core/Exec.hpp> #include <core/FilePath.hpp> #include <core/FileSerializer.hpp> #include <core/SafeConvert.hpp> #include <core/r_util/RSourceIndex.hpp> #include <core/system/FileChangeEvent.hpp> #include <core/system/FileMonitor.hpp> #include <R_ext/rlocale.h> #include <session/SessionUserSettings.hpp> #include <session/SessionModuleContext.hpp> #include <session/projects/SessionProjects.hpp> #include "SessionSource.hpp" // TODO: pref for "index R code" in projects // TODO: don't cache empty code search result sets (return from suspend) // TODO: is reset on the check for changes invalidator on save okay? // (miss changes immediately after save) using namespace core ; namespace session { namespace modules { namespace code_search { namespace { class SourceFileIndex : boost::noncopyable { public: SourceFileIndex() : indexing_(false) { } virtual ~SourceFileIndex() { } // COPYING: prohibited template <typename ForwardIterator> void enqueFiles(ForwardIterator begin, ForwardIterator end) { // add all R source files to the indexing queue using namespace core::system; for ( ; begin != end; ++begin) { if (isRSourceFile(*begin)) { FileChangeEvent addEvent(FileChangeEvent::FileAdded, *begin); indexingQueue_.push(addEvent); } } // schedule indexing if necessary. perform up to 200ms of work // immediately and then continue in periodic 20ms chunks until // we are completed. if (!indexing_) { indexing_ = true; module_context::scheduleIncrementalWork( boost::posix_time::milliseconds(200), boost::posix_time::milliseconds(20), boost::bind(&SourceFileIndex::dequeAndIndex, this), false /* allow indexing even when non-idle */); } } void enqueFileChange(const core::system::FileChangeEvent& event) { // screen out files which aren't R source files if (!isRSourceFile(event.fileInfo())) return; // add to the queue indexingQueue_.push(event); // schedule indexing if necessary. don't index anything immediately // (this is to defend against large numbers of files being enqued // at once and typing up the main thread). rather, schedule indexing // to occur during idle time in 20ms chunks if (!indexing_) { indexing_ = true; module_context::scheduleIncrementalWork( boost::posix_time::milliseconds(20), boost::bind(&SourceFileIndex::dequeAndIndex, this), false /* allow indexing even when non-idle */); } } void searchSource(const std::string& term, std::size_t maxResults, bool prefixOnly, const std::set<std::string>& excludeContexts, std::vector<r_util::RSourceItem>* pItems) { BOOST_FOREACH(const Entry& entry, entries_) { // bail if this is an exluded context if (excludeContexts.find(entry.pIndex->context()) != excludeContexts.end()) continue; // scan the next index entry.pIndex->search(term, prefixOnly, false, std::back_inserter(*pItems)); // return if we are past maxResults if (pItems->size() >= maxResults) { pItems->resize(maxResults); return; } } } void searchFiles(const std::string& term, std::size_t maxResults, bool prefixOnly, json::Array* pNames, json::Array* pPaths, bool* pMoreAvailable) { // default to no more available *pMoreAvailable = false; // create wildcard pattern if the search has a '*' bool hasWildcard = term.find('*') != std::string::npos; boost::regex pattern; if (hasWildcard) pattern = regex_utils::wildcardPatternToRegex(term); // iterate over the files FilePath projectRoot = projects::projectContext().directory(); BOOST_FOREACH(const Entry& entry, entries_) { // get the next file FilePath filePath(entry.fileInfo.absolutePath()); // get name for comparison std::string name = filePath.filename(); // compare for match (wildcard or standard) bool matches = false; if (hasWildcard) { matches = regex_utils::textMatches(name, pattern, prefixOnly, false); } else { if (prefixOnly) matches = boost::algorithm::istarts_with(name, term); else matches = boost::algorithm::icontains(name, term); } // add the file if we found a match if (matches) { // name and project relative directory pNames->push_back(filePath.filename()); pPaths->push_back(filePath.relativePath(projectRoot)); // return if we are past max results if (pNames->size() > maxResults) { *pMoreAvailable = true; pNames->resize(maxResults); pPaths->resize(maxResults); return; } } } } private: // index entries we are managing struct Entry { Entry(const FileInfo& fileInfo, boost::shared_ptr<core::r_util::RSourceIndex> pIndex) : fileInfo(fileInfo), pIndex(pIndex) { } FileInfo fileInfo; boost::shared_ptr<core::r_util::RSourceIndex> pIndex; bool operator < (const Entry& other) const { return core::fileInfoPathLessThan(fileInfo, other.fileInfo); } }; private: bool dequeAndIndex() { using namespace core::system; // remove the event from the queue FileChangeEvent event = indexingQueue_.front(); indexingQueue_.pop(); // process the change const FileInfo& fileInfo = event.fileInfo(); switch(event.type()) { case FileChangeEvent::FileAdded: case FileChangeEvent::FileModified: { updateIndexEntry(fileInfo); break; } case FileChangeEvent::FileRemoved: { removeIndexEntry(fileInfo); break; } case FileChangeEvent::None: break; } // return status indexing_ = !indexingQueue_.empty(); return indexing_; } void updateIndexEntry(const FileInfo& fileInfo) { // read the file FilePath filePath(fileInfo.absolutePath()); std::string code; Error error = module_context::readAndDecodeFile( filePath, projects::projectContext().defaultEncoding(), true, &code); if (error) { error.addProperty("src-file", filePath.absolutePath()); LOG_ERROR(error); return; } // compute project relative directory (used for context) std::string context = filePath.relativePath(projects::projectContext().directory()); // index the source boost::shared_ptr<r_util::RSourceIndex> pIndex( new r_util::RSourceIndex(context, code)); // attempt to add the entry Entry entry(fileInfo, pIndex); std::pair<std::set<Entry>::iterator,bool> result = entries_.insert(entry); // insert failed, remove then re-add if (result.second == false) { // was the first item, erase and re-insert without a hint if (result.first == entries_.begin()) { entries_.erase(result.first); entries_.insert(entry); } // can derive a valid hint else { // derive hint iterator std::set<Entry>::iterator hintIter = result.first; hintIter--; // erase and re-insert with hint entries_.erase(result.first); entries_.insert(hintIter, entry); } } } void removeIndexEntry(const FileInfo& fileInfo) { // create a fake entry with a null source index to pass to find Entry entry(fileInfo, boost::shared_ptr<r_util::RSourceIndex>()); // do the find (will use Entry::operator< for equivilance test) std::set<Entry>::iterator it = entries_.find(entry); if (it != entries_.end()) entries_.erase(it); } static bool isRSourceFile(const FileInfo& fileInfo) { FilePath filePath(fileInfo.absolutePath()); return !filePath.isDirectory() && filePath.extensionLowerCase() == ".r"; } private: // index entries std::set<Entry> entries_; // indexing queue bool indexing_; std::queue<core::system::FileChangeEvent> indexingQueue_; }; // global source file index SourceFileIndex s_projectIndex; void searchSourceDatabase(const std::string& term, std::size_t maxResults, bool prefixOnly, std::vector<r_util::RSourceItem>* pItems, std::set<std::string>* pContextsSearched) { // get all of the source indexes std::vector<boost::shared_ptr<r_util::RSourceIndex> > rIndexes = modules::source::rIndexes(); BOOST_FOREACH(boost::shared_ptr<r_util::RSourceIndex>& pIndex, rIndexes) { // get file path FilePath docPath = module_context::resolveAliasedPath(pIndex->context()); // bail if the file isn't in the project std::string projRelativePath = docPath.relativePath(projects::projectContext().directory()); if (projRelativePath.empty()) continue; // record that we searched this path pContextsSearched->insert(projRelativePath); // scan the source index pIndex->search(term, projRelativePath, prefixOnly, false, std::back_inserter(*pItems)); // return if we are past maxResults if (pItems->size() >= maxResults) { pItems->resize(maxResults); return; } } } void searchSource(const std::string& term, std::size_t maxResults, bool prefixOnly, std::vector<r_util::RSourceItem>* pItems, bool* pMoreAvailable) { // default to no more available *pMoreAvailable = false; // first search the source database std::set<std::string> srcDBContexts; searchSourceDatabase(term, maxResults, prefixOnly, pItems, &srcDBContexts); // we are done if we had >= maxResults if (pItems->size() > maxResults) { *pMoreAvailable = true; pItems->resize(maxResults); return; } // compute project max results based on existing results std::size_t maxProjResults = maxResults - pItems->size(); // now search the project (excluding contexts already searched in the source db) std::vector<r_util::RSourceItem> projItems; s_projectIndex.searchSource(term, maxProjResults, prefixOnly, srcDBContexts, &projItems); // add project items to the list BOOST_FOREACH(const r_util::RSourceItem& sourceItem, projItems) { // add the item pItems->push_back(sourceItem); // bail if we've hit the max if (pItems->size() > maxResults) { *pMoreAvailable = true; pItems->resize(maxResults); break; } } } template <typename TValue, typename TFunc> json::Array toJsonArray( const std::vector<r_util::RSourceItem> &items, TFunc memberFunc) { json::Array col; std::transform(items.begin(), items.end(), std::back_inserter(col), boost::bind(json::toJsonValue<TValue>, boost::bind(memberFunc, _1))); return col; } bool compareItems(const r_util::RSourceItem& i1, const r_util::RSourceItem& i2) { return i1.name() < i2.name(); } Error searchCode(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { // get params std::string term; int maxResultsInt; Error error = json::readParams(request.params, &term, &maxResultsInt); if (error) return error; std::size_t maxResults = safe_convert::numberTo<std::size_t>(maxResultsInt, 20); // object to return json::Object result; // search files json::Array names; json::Array paths; bool moreFilesAvailable = false; s_projectIndex.searchFiles(term, maxResults, true, &names, &paths, &moreFilesAvailable); json::Object files; files["filename"] = names; files["path"] = paths; result["file_items"] = files; // search source (sort results by name) std::vector<r_util::RSourceItem> items; bool moreSourceItemsAvailable = false; searchSource(term, maxResults, true, &items, &moreSourceItemsAvailable); std::sort(items.begin(), items.end(), compareItems); // see if we need to do src truncation bool truncated = false; if ( (names.size() + items.size()) > maxResults ) { // truncate source items std::size_t srcItems = maxResults - names.size(); items.resize(srcItems); truncated = true; } // return rpc array list (wire efficiency) json::Object src; src["type"] = toJsonArray<int>(items, &r_util::RSourceItem::type); src["name"] = toJsonArray<std::string>(items, &r_util::RSourceItem::name); src["context"] = toJsonArray<std::string>(items, &r_util::RSourceItem::context); src["line"] = toJsonArray<int>(items, &r_util::RSourceItem::line); src["column"] = toJsonArray<int>(items, &r_util::RSourceItem::column); result["source_items"] = src; // set more available bit result["more_available"] = moreFilesAvailable || moreSourceItemsAvailable || truncated; pResponse->setResult(result); return Success(); } void onFileMonitorEnabled(const tree<core::FileInfo>& files) { s_projectIndex.enqueFiles(files.begin_leaf(), files.end_leaf()); } void onFilesChanged(const std::vector<core::system::FileChangeEvent>& events) { std::for_each( events.begin(), events.end(), boost::bind(&SourceFileIndex::enqueFileChange, &s_projectIndex, _1)); } void onFileMonitorDisabled() { ClientEvent event(client_events::kCodeIndexingDisabled); module_context::enqueClientEvent(event); } } // anonymous namespace bool enabled() { return projects::projectContext().hasFileMonitor(); } Error initialize() { // subscribe to project context file monitoring state changes session::projects::FileMonitorCallbacks cb; cb.onMonitoringEnabled = onFileMonitorEnabled; cb.onFilesChanged = onFilesChanged; cb.onMonitoringDisabled = onFileMonitorDisabled; projects::projectContext().subscribeToFileMonitor("Code searching", cb); using boost::bind; using namespace module_context; ExecBlock initBlock ; initBlock.addFunctions() (bind(registerRpcMethod, "search_code", searchCode)); ; return initBlock.execute(); } } // namespace code_search } // namespace modules } // namespace session
make modifications to code index O(1)
make modifications to code index O(1)
C++
agpl-3.0
jar1karp/rstudio,vbelakov/rstudio,pssguy/rstudio,Sage-Bionetworks/rstudio,jrnold/rstudio,Sage-Bionetworks/rstudio,jar1karp/rstudio,jzhu8803/rstudio,brsimioni/rstudio,brsimioni/rstudio,john-r-mcpherson/rstudio,brsimioni/rstudio,jzhu8803/rstudio,vbelakov/rstudio,edrogers/rstudio,thklaus/rstudio,nvoron23/rstudio,nvoron23/rstudio,Sage-Bionetworks/rstudio,JanMarvin/rstudio,more1/rstudio,jrnold/rstudio,JanMarvin/rstudio,githubfun/rstudio,brsimioni/rstudio,tbarrongh/rstudio,githubfun/rstudio,nvoron23/rstudio,john-r-mcpherson/rstudio,thklaus/rstudio,piersharding/rstudio,Sage-Bionetworks/rstudio,john-r-mcpherson/rstudio,jzhu8803/rstudio,githubfun/rstudio,suribes/rstudio,jrnold/rstudio,piersharding/rstudio,thklaus/rstudio,suribes/rstudio,jrnold/rstudio,tbarrongh/rstudio,more1/rstudio,jar1karp/rstudio,jar1karp/rstudio,edrogers/rstudio,john-r-mcpherson/rstudio,suribes/rstudio,sfloresm/rstudio,john-r-mcpherson/rstudio,jar1karp/rstudio,brsimioni/rstudio,pssguy/rstudio,john-r-mcpherson/rstudio,suribes/rstudio,more1/rstudio,githubfun/rstudio,vbelakov/rstudio,tbarrongh/rstudio,thklaus/rstudio,brsimioni/rstudio,edrogers/rstudio,more1/rstudio,more1/rstudio,thklaus/rstudio,JanMarvin/rstudio,thklaus/rstudio,maligulzar/Rstudio-instrumented,vbelakov/rstudio,jar1karp/rstudio,pssguy/rstudio,jzhu8803/rstudio,suribes/rstudio,JanMarvin/rstudio,githubfun/rstudio,githubfun/rstudio,JanMarvin/rstudio,nvoron23/rstudio,tbarrongh/rstudio,maligulzar/Rstudio-instrumented,piersharding/rstudio,vbelakov/rstudio,pssguy/rstudio,pssguy/rstudio,jrnold/rstudio,thklaus/rstudio,sfloresm/rstudio,edrogers/rstudio,thklaus/rstudio,edrogers/rstudio,piersharding/rstudio,jrnold/rstudio,jrnold/rstudio,nvoron23/rstudio,nvoron23/rstudio,maligulzar/Rstudio-instrumented,edrogers/rstudio,pssguy/rstudio,jrnold/rstudio,jrnold/rstudio,edrogers/rstudio,jar1karp/rstudio,nvoron23/rstudio,tbarrongh/rstudio,piersharding/rstudio,Sage-Bionetworks/rstudio,brsimioni/rstudio,maligulzar/Rstudio-instrumented,more1/rstudio,suribes/rstudio,sfloresm/rstudio,Sage-Bionetworks/rstudio,maligulzar/Rstudio-instrumented,vbelakov/rstudio,vbelakov/rstudio,edrogers/rstudio,sfloresm/rstudio,brsimioni/rstudio,maligulzar/Rstudio-instrumented,tbarrongh/rstudio,JanMarvin/rstudio,Sage-Bionetworks/rstudio,sfloresm/rstudio,JanMarvin/rstudio,john-r-mcpherson/rstudio,JanMarvin/rstudio,tbarrongh/rstudio,githubfun/rstudio,maligulzar/Rstudio-instrumented,maligulzar/Rstudio-instrumented,john-r-mcpherson/rstudio,piersharding/rstudio,piersharding/rstudio,piersharding/rstudio,jzhu8803/rstudio,jar1karp/rstudio,sfloresm/rstudio,jzhu8803/rstudio,githubfun/rstudio,sfloresm/rstudio,more1/rstudio,vbelakov/rstudio,more1/rstudio,pssguy/rstudio,tbarrongh/rstudio,jzhu8803/rstudio,sfloresm/rstudio,jzhu8803/rstudio,maligulzar/Rstudio-instrumented,piersharding/rstudio,suribes/rstudio,pssguy/rstudio,jar1karp/rstudio,JanMarvin/rstudio,suribes/rstudio
2196c422cfe50713200e97d206c7d183308dfce6
src/rate_limiting.cpp
src/rate_limiting.cpp
#include <franka/rate_limiting.h> #include <Eigen/Dense> #include <franka/exception.h> namespace franka { std::array<double, 7> limitRate(const std::array<double, 7>& max_derivatives, const std::array<double, 7>& desired_values, const std::array<double, 7>& last_desired_values) { std::array<double, 7> limited_values{}; for (size_t i = 0; i < 7; i++) { double desired_derivative = (desired_values[i] - last_desired_values[i]) / kDeltaT; limited_values[i] = last_desired_values[i] + std::max(std::min(desired_derivative, max_derivatives[i]), -max_derivatives[i]) * kDeltaT; } return limited_values; } double limitRate(double max_velocity, double max_acceleration, double max_jerk, double desired_velocity, double last_desired_velocity, double last_desired_acceleration) { // Differentiate to get jerk double desired_jerk = (((desired_velocity - last_desired_velocity) / kDeltaT) - last_desired_acceleration) / kDeltaT; // Limit jerk double desired_acceleration = last_desired_acceleration + std::max(std::min(desired_jerk, max_jerk), -max_jerk) * kDeltaT; // Compute acceleration limits double safe_max_acceleration = std::min( (max_jerk / max_acceleration) * (max_velocity - last_desired_velocity), max_acceleration); double safe_min_acceleration = std::max( (max_jerk / max_acceleration) * (-max_velocity - last_desired_velocity), -max_acceleration); // Limit acceleration and integrate to get desired velocities return last_desired_velocity + std::max(std::min(desired_acceleration, safe_max_acceleration), safe_min_acceleration) * kDeltaT; } double limitRate(double max_velocity, double max_acceleration, double max_jerk, double desired_position, double last_desired_position, double last_desired_velocity, double last_desired_acceleration) { return last_desired_position + limitRate(max_velocity, max_acceleration, max_jerk, (desired_position - last_desired_position) / kDeltaT, last_desired_velocity, last_desired_acceleration) * kDeltaT; } std::array<double, 7> limitRate(const std::array<double, 7>& max_velocity, const std::array<double, 7>& max_acceleration, const std::array<double, 7>& max_jerk, const std::array<double, 7>& desired_velocities, const std::array<double, 7>& last_desired_velocities, const std::array<double, 7>& last_desired_accelerations) { std::array<double, 7> limited_desired_velocities{}; for (size_t i = 0; i < 7; i++) { limited_desired_velocities[i] = limitRate(max_velocity[i], max_acceleration[i], max_jerk[i], desired_velocities[i], last_desired_velocities[i], last_desired_accelerations[i]); } return limited_desired_velocities; } std::array<double, 7> limitRate(const std::array<double, 7>& max_velocity, const std::array<double, 7>& max_acceleration, const std::array<double, 7>& max_jerk, const std::array<double, 7>& desired_positions, const std::array<double, 7>& last_desired_positions, const std::array<double, 7>& last_desired_velocities, const std::array<double, 7>& last_desired_accelerations) { std::array<double, 7> limited_desired_positions{}; for (size_t i = 0; i < 7; i++) { limited_desired_positions[i] = limitRate( max_velocity[i], max_acceleration[i], max_jerk[i], desired_positions[i], last_desired_positions[i], last_desired_velocities[i], last_desired_accelerations[i]); } return limited_desired_positions; } namespace { Eigen::Vector3d limitRate(double max_velocity, double max_acceleration, double max_jerk, Eigen::Vector3d desired_velocity, Eigen::Vector3d last_desired_velocity, Eigen::Vector3d last_desired_acceleration) { // Differentiate to get jerk Eigen::Vector3d desired_jerk = (((desired_velocity - last_desired_velocity) / kDeltaT) - last_desired_acceleration) / kDeltaT; // Limit jerk and get desired acceleration Eigen::Vector3d desired_acceleration = last_desired_acceleration; if (desired_jerk.norm() > kNormEps) { desired_acceleration += (desired_jerk / desired_jerk.norm()) * std::max(std::min(desired_jerk.norm(), max_jerk), -max_jerk) * kDeltaT; } // Compute acceleration limits double safe_max_acceleration = std::min((max_jerk / max_acceleration) * (max_velocity - last_desired_velocity.norm()), max_acceleration); double safe_min_acceleration = std::max((max_jerk / max_acceleration) * (-max_velocity - last_desired_velocity.norm()), -max_acceleration); // Limit acceleration and integrate to get desired velocities Eigen::Vector3d limited_desired_velocity = last_desired_velocity; if (desired_acceleration.norm() > kNormEps) { limited_desired_velocity += (desired_acceleration / desired_acceleration.norm()) * std::max(std::min(desired_acceleration.norm(), safe_max_acceleration), safe_min_acceleration) * kDeltaT; } return limited_desired_velocity; } } // namespace std::array<double, 6> limitRate( double max_translational_velocity, double max_translational_acceleration, double max_translational_jerk, double max_rotational_velocity, double max_rotational_acceleration, double max_rotational_jerk, const std::array<double, 6>& O_dP_EE_d, // NOLINT (readability-identifier-naming) const std::array<double, 6>& last_O_dP_EE_d, // NOLINT (readability-identifier-naming) const std::array<double, 6>& last_O_ddP_EE_d) { // NOLINT (readability-identifier-naming) Eigen::Matrix<double, 6, 1> dx(O_dP_EE_d.data()); Eigen::Matrix<double, 6, 1> last_dx(last_O_dP_EE_d.data()); Eigen::Matrix<double, 6, 1> last_ddx(last_O_ddP_EE_d.data()); dx.head(3) << limitRate(max_translational_velocity, max_translational_acceleration, max_translational_jerk, dx.head(3), last_dx.head(3), last_ddx.head(3)); dx.tail(3) << limitRate(max_rotational_velocity, max_rotational_acceleration, max_rotational_jerk, dx.tail(3), last_dx.tail(3), last_ddx.tail(3)); std::array<double, 6> limited_values{}; Eigen::Map<Eigen::Matrix<double, 6, 1>>(&limited_values[0], 6, 1) = dx; return limited_values; } std::array<double, 16> limitRate( double max_translational_velocity, double max_translational_acceleration, double max_translational_jerk, double max_rotational_velocity, double max_rotational_acceleration, double max_rotational_jerk, const std::array<double, 16>& O_T_EE_d, // NOLINT (readability-identifier-naming) const std::array<double, 16>& last_O_T_EE_d, // NOLINT (readability-identifier-naming) const std::array<double, 6>& last_O_dP_EE_d, // NOLINT (readability-identifier-naming) const std::array<double, 6>& last_O_ddP_EE_d) { // NOLINT (readability-identifier-naming) Eigen::Matrix<double, 6, 1> dx; Eigen::Affine3d desired_pose(Eigen::Matrix4d::Map(O_T_EE_d.data())); Eigen::Affine3d limited_desired_pose = Eigen::Affine3d::Identity(); Eigen::Affine3d last_desired_pose(Eigen::Matrix4d::Map(last_O_T_EE_d.data())); // Compute translational velocity dx.head(3) << (desired_pose.translation() - last_desired_pose.translation()) / kDeltaT; // Compute rotational velocity auto delta_rotation = (desired_pose.linear() - last_desired_pose.linear()) / kDeltaT; Eigen::Matrix3d rotational_twist = delta_rotation * last_desired_pose.linear(); dx.tail(3) << rotational_twist(2, 1), rotational_twist(0, 2), rotational_twist(1, 0); // Limit the rate of the twist std::array<double, 6> desired_O_dP_EE_d{}; // NOLINT (readability-identifier-naming) Eigen::Map<Eigen::Matrix<double, 6, 1>>(&desired_O_dP_EE_d[0], 6, 1) = dx; desired_O_dP_EE_d = limitRate(max_translational_velocity, max_translational_acceleration, max_translational_jerk, max_rotational_velocity, max_rotational_acceleration, max_rotational_jerk, desired_O_dP_EE_d, last_O_dP_EE_d, last_O_ddP_EE_d); dx = Eigen::Matrix<double, 6, 1>(desired_O_dP_EE_d.data()); // Integrate limited twist Eigen::Matrix3d omega_skew; omega_skew << 0, -dx(5), dx(4), dx(5), 0, -dx(3), -dx(4), dx(3), 0; limited_desired_pose.linear() << last_desired_pose.linear() + omega_skew * last_desired_pose.linear() * kDeltaT; limited_desired_pose.translation() << last_desired_pose.translation() + dx.head(3) * kDeltaT; std::array<double, 16> limited_values{}; Eigen::Map<Eigen::Matrix4d>(&limited_values[0], 4, 4) = limited_desired_pose.matrix(); return limited_values; } } // namespace franka
#include <franka/rate_limiting.h> #include <Eigen/Dense> #include <franka/exception.h> namespace franka { std::array<double, 7> limitRate(const std::array<double, 7>& max_derivatives, const std::array<double, 7>& desired_values, const std::array<double, 7>& last_desired_values) { std::array<double, 7> limited_values{}; for (size_t i = 0; i < 7; i++) { double desired_derivative = (desired_values[i] - last_desired_values[i]) / kDeltaT; limited_values[i] = last_desired_values[i] + std::max(std::min(desired_derivative, max_derivatives[i]), -max_derivatives[i]) * kDeltaT; } return limited_values; } double limitRate(double max_velocity, double max_acceleration, double max_jerk, double desired_velocity, double last_desired_velocity, double last_desired_acceleration) { // Differentiate to get jerk double desired_jerk = (((desired_velocity - last_desired_velocity) / kDeltaT) - last_desired_acceleration) / kDeltaT; // Limit jerk and integrate to get acceleration double desired_acceleration = last_desired_acceleration + std::max(std::min(desired_jerk, max_jerk), -max_jerk) * kDeltaT; // Compute acceleration limits double safe_max_acceleration = std::min( (max_jerk / max_acceleration) * (max_velocity - last_desired_velocity), max_acceleration); double safe_min_acceleration = std::max( (max_jerk / max_acceleration) * (-max_velocity - last_desired_velocity), -max_acceleration); // Limit acceleration and integrate to get desired velocities return last_desired_velocity + std::max(std::min(desired_acceleration, safe_max_acceleration), safe_min_acceleration) * kDeltaT; } double limitRate(double max_velocity, double max_acceleration, double max_jerk, double desired_position, double last_desired_position, double last_desired_velocity, double last_desired_acceleration) { return last_desired_position + limitRate(max_velocity, max_acceleration, max_jerk, (desired_position - last_desired_position) / kDeltaT, last_desired_velocity, last_desired_acceleration) * kDeltaT; } std::array<double, 7> limitRate(const std::array<double, 7>& max_velocity, const std::array<double, 7>& max_acceleration, const std::array<double, 7>& max_jerk, const std::array<double, 7>& desired_velocities, const std::array<double, 7>& last_desired_velocities, const std::array<double, 7>& last_desired_accelerations) { std::array<double, 7> limited_desired_velocities{}; for (size_t i = 0; i < 7; i++) { limited_desired_velocities[i] = limitRate(max_velocity[i], max_acceleration[i], max_jerk[i], desired_velocities[i], last_desired_velocities[i], last_desired_accelerations[i]); } return limited_desired_velocities; } std::array<double, 7> limitRate(const std::array<double, 7>& max_velocity, const std::array<double, 7>& max_acceleration, const std::array<double, 7>& max_jerk, const std::array<double, 7>& desired_positions, const std::array<double, 7>& last_desired_positions, const std::array<double, 7>& last_desired_velocities, const std::array<double, 7>& last_desired_accelerations) { std::array<double, 7> limited_desired_positions{}; for (size_t i = 0; i < 7; i++) { limited_desired_positions[i] = limitRate( max_velocity[i], max_acceleration[i], max_jerk[i], desired_positions[i], last_desired_positions[i], last_desired_velocities[i], last_desired_accelerations[i]); } return limited_desired_positions; } namespace { Eigen::Vector3d limitRate(double max_velocity, double max_acceleration, double max_jerk, Eigen::Vector3d desired_velocity, Eigen::Vector3d last_desired_velocity, Eigen::Vector3d last_desired_acceleration) { // Differentiate to get jerk Eigen::Vector3d desired_jerk = (((desired_velocity - last_desired_velocity) / kDeltaT) - last_desired_acceleration) / kDeltaT; // Limit jerk and integrate to get desired acceleration Eigen::Vector3d desired_acceleration = last_desired_acceleration; if (desired_jerk.norm() > kNormEps) { desired_acceleration += (desired_jerk / desired_jerk.norm()) * std::max(std::min(desired_jerk.norm(), max_jerk), -max_jerk) * kDeltaT; } // Compute Euclidean distance to the max velocity vector that would be reached starting from // last_desired_velocity with the direction of the desired acceleration Eigen::Vector3d unit_desired_acceleration = desired_acceleration / desired_acceleration.norm(); double dot_product = unit_desired_acceleration.transpose() * last_desired_velocity; double distance_to_max_velocity = -dot_product + std::sqrt(pow(dot_product, 2.0) - last_desired_velocity.squaredNorm() + pow(max_velocity, 2.0)); // Compute safe acceleration limits double safe_max_acceleration = std::min((max_jerk / max_acceleration) * distance_to_max_velocity, max_acceleration); // Limit acceleration and integrate to get desired velocities Eigen::Vector3d limited_desired_velocity = last_desired_velocity; if (desired_acceleration.norm() > kNormEps) { limited_desired_velocity += unit_desired_acceleration * std::min(desired_acceleration.norm(), safe_max_acceleration) * kDeltaT; } return limited_desired_velocity; } } // namespace std::array<double, 6> limitRate( double max_translational_velocity, double max_translational_acceleration, double max_translational_jerk, double max_rotational_velocity, double max_rotational_acceleration, double max_rotational_jerk, const std::array<double, 6>& O_dP_EE_d, // NOLINT (readability-identifier-naming) const std::array<double, 6>& last_O_dP_EE_d, // NOLINT (readability-identifier-naming) const std::array<double, 6>& last_O_ddP_EE_d) { // NOLINT (readability-identifier-naming) Eigen::Matrix<double, 6, 1> dx(O_dP_EE_d.data()); Eigen::Matrix<double, 6, 1> last_dx(last_O_dP_EE_d.data()); Eigen::Matrix<double, 6, 1> last_ddx(last_O_ddP_EE_d.data()); dx.head(3) << limitRate(max_translational_velocity, max_translational_acceleration, max_translational_jerk, dx.head(3), last_dx.head(3), last_ddx.head(3)); dx.tail(3) << limitRate(max_rotational_velocity, max_rotational_acceleration, max_rotational_jerk, dx.tail(3), last_dx.tail(3), last_ddx.tail(3)); std::array<double, 6> limited_values{}; Eigen::Map<Eigen::Matrix<double, 6, 1>>(&limited_values[0], 6, 1) = dx; return limited_values; } std::array<double, 16> limitRate( double max_translational_velocity, double max_translational_acceleration, double max_translational_jerk, double max_rotational_velocity, double max_rotational_acceleration, double max_rotational_jerk, const std::array<double, 16>& O_T_EE_d, // NOLINT (readability-identifier-naming) const std::array<double, 16>& last_O_T_EE_d, // NOLINT (readability-identifier-naming) const std::array<double, 6>& last_O_dP_EE_d, // NOLINT (readability-identifier-naming) const std::array<double, 6>& last_O_ddP_EE_d) { // NOLINT (readability-identifier-naming) Eigen::Matrix<double, 6, 1> dx; Eigen::Affine3d desired_pose(Eigen::Matrix4d::Map(O_T_EE_d.data())); Eigen::Affine3d limited_desired_pose = Eigen::Affine3d::Identity(); Eigen::Affine3d last_desired_pose(Eigen::Matrix4d::Map(last_O_T_EE_d.data())); // Compute translational velocity dx.head(3) << (desired_pose.translation() - last_desired_pose.translation()) / kDeltaT; // Compute rotational velocity auto delta_rotation = (desired_pose.linear() - last_desired_pose.linear()) / kDeltaT; Eigen::Matrix3d rotational_twist = delta_rotation * last_desired_pose.linear(); dx.tail(3) << rotational_twist(2, 1), rotational_twist(0, 2), rotational_twist(1, 0); // Limit the rate of the twist std::array<double, 6> desired_O_dP_EE_d{}; // NOLINT (readability-identifier-naming) Eigen::Map<Eigen::Matrix<double, 6, 1>>(&desired_O_dP_EE_d[0], 6, 1) = dx; desired_O_dP_EE_d = limitRate(max_translational_velocity, max_translational_acceleration, max_translational_jerk, max_rotational_velocity, max_rotational_acceleration, max_rotational_jerk, desired_O_dP_EE_d, last_O_dP_EE_d, last_O_ddP_EE_d); dx = Eigen::Matrix<double, 6, 1>(desired_O_dP_EE_d.data()); // Integrate limited twist Eigen::Matrix3d omega_skew; omega_skew << 0, -dx(5), dx(4), dx(5), 0, -dx(3), -dx(4), dx(3), 0; limited_desired_pose.linear() << last_desired_pose.linear() + omega_skew * last_desired_pose.linear() * kDeltaT; limited_desired_pose.translation() << last_desired_pose.translation() + dx.head(3) * kDeltaT; std::array<double, 16> limited_values{}; Eigen::Map<Eigen::Matrix4d>(&limited_values[0], 4, 4) = limited_desired_pose.matrix(); return limited_values; } } // namespace franka
Add Euclidean distance computation for Cartesian safe acceleration limits
Add Euclidean distance computation for Cartesian safe acceleration limits
C++
apache-2.0
frankaemika/libfranka,frankaemika/libfranka,frankaemika/libfranka
0379d8cfeac189a7fd815e23908b422b861592c7
test/pc/e2e/analyzer/audio/default_audio_quality_analyzer.cc
test/pc/e2e/analyzer/audio/default_audio_quality_analyzer.cc
/* * Copyright (c) 2019 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "test/pc/e2e/analyzer/audio/default_audio_quality_analyzer.h" #include "api/stats_types.h" #include "rtc_base/logging.h" #include "test/testsupport/perf_test.h" namespace webrtc { namespace webrtc_pc_e2e { namespace { static const char kStatsAudioMediaType[] = "audio"; } // namespace void DefaultAudioQualityAnalyzer::Start( std::string test_case_name, TrackIdStreamLabelMap* analyzer_helper) { test_case_name_ = std::move(test_case_name); analyzer_helper_ = analyzer_helper; } void DefaultAudioQualityAnalyzer::OnStatsReports( const std::string& pc_label, const StatsReports& stats_reports) { for (const StatsReport* stats_report : stats_reports) { // NetEq stats are only present in kStatsReportTypeSsrc reports, so all // other reports are just ignored. if (stats_report->type() != StatsReport::StatsType::kStatsReportTypeSsrc) { continue; } // Ignoring stats reports of "video" SSRC. const webrtc::StatsReport::Value* media_type = stats_report->FindValue( StatsReport::StatsValueName::kStatsValueNameMediaType); RTC_CHECK(media_type); if (strcmp(media_type->static_string_val(), kStatsAudioMediaType) != 0) { continue; } const webrtc::StatsReport::Value* bytes_received = stats_report->FindValue( StatsReport::StatsValueName::kStatsValueNameBytesReceived); if (bytes_received == nullptr || bytes_received->int64_val() == 0) { // Discarding stats in the following situations: // - When bytes_received is not present, because NetEq stats are only // available in recv-side SSRC. // - When bytes_received is present but its value is 0. This means // that media is not yet flowing so there is no need to keep this // stats report into account (since all its fields would be 0). continue; } const webrtc::StatsReport::Value* expand_rate = stats_report->FindValue( StatsReport::StatsValueName::kStatsValueNameExpandRate); const webrtc::StatsReport::Value* accelerate_rate = stats_report->FindValue( StatsReport::StatsValueName::kStatsValueNameAccelerateRate); const webrtc::StatsReport::Value* preemptive_rate = stats_report->FindValue( StatsReport::StatsValueName::kStatsValueNamePreemptiveExpandRate); const webrtc::StatsReport::Value* speech_expand_rate = stats_report->FindValue( StatsReport::StatsValueName::kStatsValueNameSpeechExpandRate); const webrtc::StatsReport::Value* preferred_buffer_size_ms = stats_report->FindValue(StatsReport::StatsValueName:: kStatsValueNamePreferredJitterBufferMs); RTC_CHECK(expand_rate); RTC_CHECK(accelerate_rate); RTC_CHECK(preemptive_rate); RTC_CHECK(speech_expand_rate); RTC_CHECK(preferred_buffer_size_ms); const std::string& stream_label = GetStreamLabelFromStatsReport(stats_report); rtc::CritScope crit(&lock_); AudioStreamStats& audio_stream_stats = streams_stats_[stream_label]; audio_stream_stats.expand_rate.AddSample(expand_rate->float_val()); audio_stream_stats.accelerate_rate.AddSample(accelerate_rate->float_val()); audio_stream_stats.preemptive_rate.AddSample(preemptive_rate->float_val()); audio_stream_stats.speech_expand_rate.AddSample( speech_expand_rate->float_val()); audio_stream_stats.preferred_buffer_size_ms.AddSample( preferred_buffer_size_ms->int_val()); } } const std::string& DefaultAudioQualityAnalyzer::GetStreamLabelFromStatsReport( const StatsReport* stats_report) const { const webrtc::StatsReport::Value* report_track_id = stats_report->FindValue( StatsReport::StatsValueName::kStatsValueNameTrackId); RTC_CHECK(report_track_id); return analyzer_helper_->GetStreamLabelFromTrackId( report_track_id->string_val()); } std::string DefaultAudioQualityAnalyzer::GetTestCaseName( const std::string& stream_label) const { return test_case_name_ + "/" + stream_label; } void DefaultAudioQualityAnalyzer::Stop() { rtc::CritScope crit(&lock_); for (auto& item : streams_stats_) { ReportResult("expand_rate", item.first, item.second.expand_rate, "unitless"); ReportResult("accelerate_rate", item.first, item.second.accelerate_rate, "unitless"); ReportResult("preemptive_rate", item.first, item.second.preemptive_rate, "unitless"); ReportResult("speech_expand_rate", item.first, item.second.speech_expand_rate, "unitless"); ReportResult("preferred_buffer_size_ms", item.first, item.second.preferred_buffer_size_ms, "ms"); } } std::map<std::string, AudioStreamStats> DefaultAudioQualityAnalyzer::GetAudioStreamsStats() const { rtc::CritScope crit(&lock_); return streams_stats_; } void DefaultAudioQualityAnalyzer::ReportResult( const std::string& metric_name, const std::string& stream_label, const SamplesStatsCounter& counter, const std::string& unit) const { test::PrintResultMeanAndError( metric_name, /*modifier=*/"", GetTestCaseName(stream_label), counter.IsEmpty() ? 0 : counter.GetAverage(), counter.IsEmpty() ? 0 : counter.GetStandardDeviation(), unit, /*important=*/false); } } // namespace webrtc_pc_e2e } // namespace webrtc
/* * Copyright (c) 2019 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "test/pc/e2e/analyzer/audio/default_audio_quality_analyzer.h" #include "api/stats_types.h" #include "rtc_base/logging.h" #include "test/testsupport/perf_test.h" namespace webrtc { namespace webrtc_pc_e2e { namespace { static const char kStatsAudioMediaType[] = "audio"; } // namespace void DefaultAudioQualityAnalyzer::Start( std::string test_case_name, TrackIdStreamLabelMap* analyzer_helper) { test_case_name_ = std::move(test_case_name); analyzer_helper_ = analyzer_helper; } void DefaultAudioQualityAnalyzer::OnStatsReports( const std::string& pc_label, const StatsReports& stats_reports) { for (const StatsReport* stats_report : stats_reports) { // NetEq stats are only present in kStatsReportTypeSsrc reports, so all // other reports are just ignored. if (stats_report->type() != StatsReport::StatsType::kStatsReportTypeSsrc) { continue; } // Ignoring stats reports of "video" SSRC. const webrtc::StatsReport::Value* media_type = stats_report->FindValue( StatsReport::StatsValueName::kStatsValueNameMediaType); RTC_CHECK(media_type); if (strcmp(media_type->static_string_val(), kStatsAudioMediaType) != 0) { continue; } if (stats_report->FindValue( webrtc::StatsReport::kStatsValueNameBytesSent)) { // If kStatsValueNameBytesSent is present, it means it's a send stream, // but we need audio metrics for receive stream, so skip it. continue; } const webrtc::StatsReport::Value* expand_rate = stats_report->FindValue( StatsReport::StatsValueName::kStatsValueNameExpandRate); const webrtc::StatsReport::Value* accelerate_rate = stats_report->FindValue( StatsReport::StatsValueName::kStatsValueNameAccelerateRate); const webrtc::StatsReport::Value* preemptive_rate = stats_report->FindValue( StatsReport::StatsValueName::kStatsValueNamePreemptiveExpandRate); const webrtc::StatsReport::Value* speech_expand_rate = stats_report->FindValue( StatsReport::StatsValueName::kStatsValueNameSpeechExpandRate); const webrtc::StatsReport::Value* preferred_buffer_size_ms = stats_report->FindValue(StatsReport::StatsValueName:: kStatsValueNamePreferredJitterBufferMs); RTC_CHECK(expand_rate); RTC_CHECK(accelerate_rate); RTC_CHECK(preemptive_rate); RTC_CHECK(speech_expand_rate); RTC_CHECK(preferred_buffer_size_ms); const std::string& stream_label = GetStreamLabelFromStatsReport(stats_report); rtc::CritScope crit(&lock_); AudioStreamStats& audio_stream_stats = streams_stats_[stream_label]; audio_stream_stats.expand_rate.AddSample(expand_rate->float_val()); audio_stream_stats.accelerate_rate.AddSample(accelerate_rate->float_val()); audio_stream_stats.preemptive_rate.AddSample(preemptive_rate->float_val()); audio_stream_stats.speech_expand_rate.AddSample( speech_expand_rate->float_val()); audio_stream_stats.preferred_buffer_size_ms.AddSample( preferred_buffer_size_ms->int_val()); } } const std::string& DefaultAudioQualityAnalyzer::GetStreamLabelFromStatsReport( const StatsReport* stats_report) const { const webrtc::StatsReport::Value* report_track_id = stats_report->FindValue( StatsReport::StatsValueName::kStatsValueNameTrackId); RTC_CHECK(report_track_id); return analyzer_helper_->GetStreamLabelFromTrackId( report_track_id->string_val()); } std::string DefaultAudioQualityAnalyzer::GetTestCaseName( const std::string& stream_label) const { return test_case_name_ + "/" + stream_label; } void DefaultAudioQualityAnalyzer::Stop() { rtc::CritScope crit(&lock_); for (auto& item : streams_stats_) { ReportResult("expand_rate", item.first, item.second.expand_rate, "unitless"); ReportResult("accelerate_rate", item.first, item.second.accelerate_rate, "unitless"); ReportResult("preemptive_rate", item.first, item.second.preemptive_rate, "unitless"); ReportResult("speech_expand_rate", item.first, item.second.speech_expand_rate, "unitless"); ReportResult("preferred_buffer_size_ms", item.first, item.second.preferred_buffer_size_ms, "ms"); } } std::map<std::string, AudioStreamStats> DefaultAudioQualityAnalyzer::GetAudioStreamsStats() const { rtc::CritScope crit(&lock_); return streams_stats_; } void DefaultAudioQualityAnalyzer::ReportResult( const std::string& metric_name, const std::string& stream_label, const SamplesStatsCounter& counter, const std::string& unit) const { test::PrintResultMeanAndError( metric_name, /*modifier=*/"", GetTestCaseName(stream_label), counter.IsEmpty() ? 0 : counter.GetAverage(), counter.IsEmpty() ? 0 : counter.GetStandardDeviation(), unit, /*important=*/false); } } // namespace webrtc_pc_e2e } // namespace webrtc
Change a way, how receive stream is determined in DefaultAudioQualityAnalyzer.
Change a way, how receive stream is determined in DefaultAudioQualityAnalyzer. Bug: webrtc:10138 Change-Id: I8955c30f0a5d98abeca029323396e469a2fb243b Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/136683 Reviewed-by: Mirko Bonadei <[email protected]> Commit-Queue: Artem Titov <[email protected]> Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#27927}
C++
bsd-3-clause
ShiftMediaProject/libilbc,TimothyGu/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc
6e28f6918023260845a33b91b9cbec65268c0c41
src/libaktualizr/uptane/uptane_serial_test.cc
src/libaktualizr/uptane/uptane_serial_test.cc
#include <gtest/gtest.h> #include <memory> #include <string> #include <utility> #include <vector> #include <boost/filesystem.hpp> #include <boost/program_options.hpp> #include "httpfake.h" #include "logging/logging.h" #include "primary/reportqueue.h" #include "primary/sotauptaneclient.h" #include "storage/invstorage.h" #include "test_utils.h" #include "uptane/tuf.h" #include "uptane/uptanerepository.h" #include "utilities/utils.h" namespace bpo = boost::program_options; boost::filesystem::path build_dir; /** * Check that aktualizr generates random ecu_serial for primary and all * secondaries. */ TEST(Uptane, RandomSerial) { RecordProperty("zephyr_key", "OTA-989,TST-155"); TemporaryDirectory temp_dir1, temp_dir2; Config conf_1("tests/config/basic.toml"); conf_1.storage.path = temp_dir1.Path(); Config conf_2("tests/config/basic.toml"); conf_2.storage.path = temp_dir2.Path(); conf_1.provision.primary_ecu_serial = ""; conf_2.provision.primary_ecu_serial = ""; // add secondaries Uptane::SecondaryConfig ecu_config; ecu_config.secondary_type = Uptane::SecondaryType::kVirtual; ecu_config.partial_verifying = false; ecu_config.full_client_dir = temp_dir1.Path() / "sec_1"; ecu_config.ecu_serial = ""; ecu_config.ecu_hardware_id = "secondary_hardware"; ecu_config.ecu_private_key = "sec.priv"; ecu_config.ecu_public_key = "sec.pub"; ecu_config.firmware_path = temp_dir1.Path() / "firmware.txt"; ecu_config.target_name_path = temp_dir1.Path() / "firmware_name.txt"; ecu_config.metadata_path = temp_dir1.Path() / "secondary_metadata"; conf_1.uptane.secondary_configs.push_back(ecu_config); ecu_config.full_client_dir = temp_dir2.Path() / "sec_2"; ecu_config.firmware_path = temp_dir2.Path() / "firmware.txt"; ecu_config.target_name_path = temp_dir2.Path() / "firmware_name.txt"; ecu_config.metadata_path = temp_dir2.Path() / "secondary_metadata"; conf_2.uptane.secondary_configs.push_back(ecu_config); auto storage_1 = INvStorage::newStorage(conf_1.storage); auto storage_2 = INvStorage::newStorage(conf_2.storage); auto http1 = std::make_shared<HttpFake>(temp_dir1.Path()); auto http2 = std::make_shared<HttpFake>(temp_dir2.Path()); auto uptane_client1 = SotaUptaneClient::newTestClient(conf_1, storage_1, http1); EXPECT_NO_THROW(uptane_client1->initialize()); auto uptane_client2 = SotaUptaneClient::newTestClient(conf_2, storage_2, http2); EXPECT_NO_THROW(uptane_client2->initialize()); EcuSerials ecu_serials_1; EcuSerials ecu_serials_2; EXPECT_TRUE(storage_1->loadEcuSerials(&ecu_serials_1)); EXPECT_TRUE(storage_2->loadEcuSerials(&ecu_serials_2)); EXPECT_EQ(ecu_serials_1.size(), 2); EXPECT_EQ(ecu_serials_2.size(), 2); EXPECT_FALSE(ecu_serials_1[0].first.ToString().empty()); EXPECT_FALSE(ecu_serials_1[1].first.ToString().empty()); EXPECT_FALSE(ecu_serials_2[0].first.ToString().empty()); EXPECT_FALSE(ecu_serials_2[1].first.ToString().empty()); EXPECT_NE(ecu_serials_1[0].first, ecu_serials_2[0].first); EXPECT_NE(ecu_serials_1[1].first, ecu_serials_2[1].first); EXPECT_NE(ecu_serials_1[0].first, ecu_serials_1[1].first); EXPECT_NE(ecu_serials_2[0].first, ecu_serials_2[1].first); } /** * Check that aktualizr saves random ecu_serial for primary and all secondaries. */ TEST(Uptane, ReloadSerial) { RecordProperty("zephyr_key", "OTA-989,TST-156"); TemporaryDirectory temp_dir; EcuSerials ecu_serials_1; EcuSerials ecu_serials_2; Uptane::SecondaryConfig ecu_config; ecu_config.secondary_type = Uptane::SecondaryType::kVirtual; ecu_config.partial_verifying = false; ecu_config.full_client_dir = temp_dir.Path() / "sec"; ecu_config.ecu_serial = ""; ecu_config.ecu_hardware_id = "secondary_hardware"; ecu_config.ecu_private_key = "sec.priv"; ecu_config.ecu_public_key = "sec.pub"; ecu_config.firmware_path = temp_dir.Path() / "firmware.txt"; ecu_config.target_name_path = temp_dir.Path() / "firmware_name.txt"; ecu_config.metadata_path = temp_dir.Path() / "secondary_metadata"; // Initialize and store serials. { Config conf("tests/config/basic.toml"); conf.storage.path = temp_dir.Path(); conf.provision.primary_ecu_serial = ""; conf.uptane.secondary_configs.push_back(ecu_config); auto storage = INvStorage::newStorage(conf.storage); auto http = std::make_shared<HttpFake>(temp_dir.Path()); auto uptane_client = SotaUptaneClient::newTestClient(conf, storage, http); EXPECT_NO_THROW(uptane_client->initialize()); EXPECT_TRUE(storage->loadEcuSerials(&ecu_serials_1)); EXPECT_EQ(ecu_serials_1.size(), 2); EXPECT_FALSE(ecu_serials_1[0].first.ToString().empty()); EXPECT_FALSE(ecu_serials_1[1].first.ToString().empty()); } // Initialize new objects and load serials. { Config conf("tests/config/basic.toml"); conf.storage.path = temp_dir.Path(); conf.provision.primary_ecu_serial = ""; conf.uptane.secondary_configs.push_back(ecu_config); auto storage = INvStorage::newStorage(conf.storage); auto http = std::make_shared<HttpFake>(temp_dir.Path()); auto uptane_client = SotaUptaneClient::newTestClient(conf, storage, http); EXPECT_NO_THROW(uptane_client->initialize()); EXPECT_TRUE(storage->loadEcuSerials(&ecu_serials_2)); EXPECT_EQ(ecu_serials_2.size(), 2); EXPECT_FALSE(ecu_serials_2[0].first.ToString().empty()); EXPECT_FALSE(ecu_serials_2[1].first.ToString().empty()); } EXPECT_EQ(ecu_serials_1[0].first, ecu_serials_2[0].first); EXPECT_EQ(ecu_serials_1[1].first, ecu_serials_2[1].first); EXPECT_NE(ecu_serials_1[0].first, ecu_serials_1[1].first); EXPECT_NE(ecu_serials_2[0].first, ecu_serials_2[1].first); } TEST(Uptane, LegacySerial) { TemporaryDirectory temp_dir; const std::string conf_path_str = (temp_dir.Path() / "config.toml").string(); TestUtils::writePathToConfig("tests/config/basic.toml", conf_path_str, temp_dir.Path()); bpo::variables_map cmd; bpo::options_description description("some text"); // clang-format off description.add_options() ("legacy-interface", bpo::value<boost::filesystem::path>()->composing(), "path to legacy secondary ECU interface program") ("config,c", bpo::value<std::vector<boost::filesystem::path> >()->composing(), "configuration directory"); // clang-format on std::string path = (build_dir / "src/external_secondaries/example-interface").string(); const char* argv[] = {"aktualizr", "--legacy-interface", path.c_str(), "-c", conf_path_str.c_str()}; bpo::store(bpo::parse_command_line(5, argv, description), cmd); EcuSerials ecu_serials_1; EcuSerials ecu_serials_2; // Initialize and store serials. { Config conf(cmd); conf.provision.primary_ecu_serial = ""; auto storage = INvStorage::newStorage(conf.storage); auto http = std::make_shared<HttpFake>(temp_dir.Path()); auto uptane_client = SotaUptaneClient::newTestClient(conf, storage, http); EXPECT_NO_THROW(uptane_client->initialize()); EXPECT_TRUE(storage->loadEcuSerials(&ecu_serials_1)); EXPECT_EQ(ecu_serials_1.size(), 3); EXPECT_FALSE(ecu_serials_1[0].first.ToString().empty()); EXPECT_FALSE(ecu_serials_1[1].first.ToString().empty()); EXPECT_FALSE(ecu_serials_1[2].first.ToString().empty()); } // Initialize new objects and load serials. { Config conf(cmd); conf.provision.primary_ecu_serial = ""; auto storage = INvStorage::newStorage(conf.storage); auto http = std::make_shared<HttpFake>(temp_dir.Path()); auto uptane_client = SotaUptaneClient::newTestClient(conf, storage, http); EXPECT_NO_THROW(uptane_client->initialize()); EXPECT_TRUE(storage->loadEcuSerials(&ecu_serials_2)); EXPECT_EQ(ecu_serials_2.size(), 3); EXPECT_FALSE(ecu_serials_2[0].first.ToString().empty()); EXPECT_FALSE(ecu_serials_2[1].first.ToString().empty()); EXPECT_FALSE(ecu_serials_2[2].first.ToString().empty()); } EXPECT_EQ(ecu_serials_1[0].first, ecu_serials_2[0].first); EXPECT_EQ(ecu_serials_1[1].first, ecu_serials_2[1].first); EXPECT_EQ(ecu_serials_1[2].first, ecu_serials_2[2].first); EXPECT_NE(ecu_serials_1[0].first, ecu_serials_1[1].first); EXPECT_NE(ecu_serials_1[0].first, ecu_serials_1[2].first); EXPECT_NE(ecu_serials_1[1].first, ecu_serials_1[2].first); EXPECT_NE(ecu_serials_2[0].first, ecu_serials_2[1].first); EXPECT_NE(ecu_serials_2[0].first, ecu_serials_2[2].first); EXPECT_NE(ecu_serials_2[1].first, ecu_serials_2[2].first); } #ifndef __NO_MAIN__ int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); logger_set_threshold(boost::log::trivial::trace); if (argc != 2) { std::cerr << "Error: " << argv[0] << " requires the path to the build directory as an input argument.\n"; return EXIT_FAILURE; } build_dir = argv[1]; return RUN_ALL_TESTS(); } #endif
#include <gtest/gtest.h> #include <memory> #include <string> #include <utility> #include <vector> #include <boost/filesystem.hpp> #include <boost/program_options.hpp> #include "httpfake.h" #include "logging/logging.h" #include "primary/reportqueue.h" #include "primary/sotauptaneclient.h" #include "storage/invstorage.h" #include "test_utils.h" #include "uptane/tuf.h" #include "uptane/uptanerepository.h" #include "utilities/utils.h" namespace bpo = boost::program_options; boost::filesystem::path build_dir; /** * Check that aktualizr generates random ecu_serial for primary and all * secondaries. */ TEST(Uptane, RandomSerial) { RecordProperty("zephyr_key", "OTA-989,TST-155"); // Make two configs, neither of which specify a primary serial. TemporaryDirectory temp_dir1, temp_dir2; Config conf_1("tests/config/basic.toml"); conf_1.storage.path = temp_dir1.Path(); Config conf_2("tests/config/basic.toml"); conf_2.storage.path = temp_dir2.Path(); conf_1.provision.primary_ecu_serial = ""; conf_2.provision.primary_ecu_serial = ""; // Add a secondary to each config, again not specifying serials. Uptane::SecondaryConfig ecu_config; ecu_config.secondary_type = Uptane::SecondaryType::kVirtual; ecu_config.partial_verifying = false; ecu_config.full_client_dir = temp_dir1.Path() / "sec_1"; ecu_config.ecu_serial = ""; ecu_config.ecu_hardware_id = "secondary_hardware"; ecu_config.ecu_private_key = "sec.priv"; ecu_config.ecu_public_key = "sec.pub"; ecu_config.firmware_path = temp_dir1.Path() / "firmware.txt"; ecu_config.target_name_path = temp_dir1.Path() / "firmware_name.txt"; ecu_config.metadata_path = temp_dir1.Path() / "secondary_metadata"; conf_1.uptane.secondary_configs.push_back(ecu_config); ecu_config.full_client_dir = temp_dir2.Path() / "sec_2"; ecu_config.firmware_path = temp_dir2.Path() / "firmware.txt"; ecu_config.target_name_path = temp_dir2.Path() / "firmware_name.txt"; ecu_config.metadata_path = temp_dir2.Path() / "secondary_metadata"; conf_2.uptane.secondary_configs.push_back(ecu_config); // Initialize. auto storage_1 = INvStorage::newStorage(conf_1.storage); auto storage_2 = INvStorage::newStorage(conf_2.storage); auto http1 = std::make_shared<HttpFake>(temp_dir1.Path()); auto http2 = std::make_shared<HttpFake>(temp_dir2.Path()); auto uptane_client1 = SotaUptaneClient::newTestClient(conf_1, storage_1, http1); EXPECT_NO_THROW(uptane_client1->initialize()); auto uptane_client2 = SotaUptaneClient::newTestClient(conf_2, storage_2, http2); EXPECT_NO_THROW(uptane_client2->initialize()); // Verify that none of the serials match. EcuSerials ecu_serials_1; EcuSerials ecu_serials_2; EXPECT_TRUE(storage_1->loadEcuSerials(&ecu_serials_1)); EXPECT_TRUE(storage_2->loadEcuSerials(&ecu_serials_2)); EXPECT_EQ(ecu_serials_1.size(), 2); EXPECT_EQ(ecu_serials_2.size(), 2); EXPECT_FALSE(ecu_serials_1[0].first.ToString().empty()); EXPECT_FALSE(ecu_serials_1[1].first.ToString().empty()); EXPECT_FALSE(ecu_serials_2[0].first.ToString().empty()); EXPECT_FALSE(ecu_serials_2[1].first.ToString().empty()); EXPECT_NE(ecu_serials_1[0].first, ecu_serials_2[0].first); EXPECT_NE(ecu_serials_1[1].first, ecu_serials_2[1].first); EXPECT_NE(ecu_serials_1[0].first, ecu_serials_1[1].first); EXPECT_NE(ecu_serials_2[0].first, ecu_serials_2[1].first); } /** * Check that aktualizr saves random ecu_serial for primary and all secondaries. * * Test with a virtual secondary. */ TEST(Uptane, ReloadSerial) { RecordProperty("zephyr_key", "OTA-989,TST-156"); TemporaryDirectory temp_dir; EcuSerials ecu_serials_1; EcuSerials ecu_serials_2; Uptane::SecondaryConfig ecu_config; ecu_config.secondary_type = Uptane::SecondaryType::kVirtual; ecu_config.partial_verifying = false; ecu_config.full_client_dir = temp_dir.Path() / "sec"; ecu_config.ecu_serial = ""; ecu_config.ecu_hardware_id = "secondary_hardware"; ecu_config.ecu_private_key = "sec.priv"; ecu_config.ecu_public_key = "sec.pub"; ecu_config.firmware_path = temp_dir.Path() / "firmware.txt"; ecu_config.target_name_path = temp_dir.Path() / "firmware_name.txt"; ecu_config.metadata_path = temp_dir.Path() / "secondary_metadata"; // Initialize. Should store new serials. { Config conf("tests/config/basic.toml"); conf.storage.path = temp_dir.Path(); conf.provision.primary_ecu_serial = ""; conf.uptane.secondary_configs.push_back(ecu_config); auto storage = INvStorage::newStorage(conf.storage); auto http = std::make_shared<HttpFake>(temp_dir.Path()); auto uptane_client = SotaUptaneClient::newTestClient(conf, storage, http); EXPECT_NO_THROW(uptane_client->initialize()); EXPECT_TRUE(storage->loadEcuSerials(&ecu_serials_1)); EXPECT_EQ(ecu_serials_1.size(), 2); EXPECT_FALSE(ecu_serials_1[0].first.ToString().empty()); EXPECT_FALSE(ecu_serials_1[1].first.ToString().empty()); } // Keep storage directory, but initialize new objects. Should load existing // serials. { Config conf("tests/config/basic.toml"); conf.storage.path = temp_dir.Path(); conf.provision.primary_ecu_serial = ""; conf.uptane.secondary_configs.push_back(ecu_config); auto storage = INvStorage::newStorage(conf.storage); auto http = std::make_shared<HttpFake>(temp_dir.Path()); auto uptane_client = SotaUptaneClient::newTestClient(conf, storage, http); EXPECT_NO_THROW(uptane_client->initialize()); EXPECT_TRUE(storage->loadEcuSerials(&ecu_serials_2)); EXPECT_EQ(ecu_serials_2.size(), 2); EXPECT_FALSE(ecu_serials_2[0].first.ToString().empty()); EXPECT_FALSE(ecu_serials_2[1].first.ToString().empty()); } // Verify that serials match across initializations. EXPECT_EQ(ecu_serials_1[0].first, ecu_serials_2[0].first); EXPECT_EQ(ecu_serials_1[1].first, ecu_serials_2[1].first); // Sanity check that primary and secondary serials do not match. EXPECT_NE(ecu_serials_1[0].first, ecu_serials_1[1].first); EXPECT_NE(ecu_serials_2[0].first, ecu_serials_2[1].first); } /** * Check that aktualizr saves random ecu_serial for primary and all secondaries. * * Test with a legacy secondary interface with two secondaries. */ TEST(Uptane, LegacySerial) { RecordProperty("zephyr_key", "OTA-989,TST-156"); TemporaryDirectory temp_dir; const std::string conf_path_str = (temp_dir.Path() / "config.toml").string(); TestUtils::writePathToConfig("tests/config/basic.toml", conf_path_str, temp_dir.Path()); bpo::variables_map cmd; bpo::options_description description("some text"); // clang-format off description.add_options() ("legacy-interface", bpo::value<boost::filesystem::path>()->composing(), "path to legacy secondary ECU interface program") ("config,c", bpo::value<std::vector<boost::filesystem::path> >()->composing(), "configuration directory"); // clang-format on std::string path = (build_dir / "src/external_secondaries/example-interface").string(); const char* argv[] = {"aktualizr", "--legacy-interface", path.c_str(), "-c", conf_path_str.c_str()}; bpo::store(bpo::parse_command_line(5, argv, description), cmd); EcuSerials ecu_serials_1; EcuSerials ecu_serials_2; // Initialize. Should store new serials. { Config conf(cmd); conf.provision.primary_ecu_serial = ""; auto storage = INvStorage::newStorage(conf.storage); auto http = std::make_shared<HttpFake>(temp_dir.Path()); auto uptane_client = SotaUptaneClient::newTestClient(conf, storage, http); EXPECT_NO_THROW(uptane_client->initialize()); EXPECT_TRUE(storage->loadEcuSerials(&ecu_serials_1)); EXPECT_EQ(ecu_serials_1.size(), 3); EXPECT_FALSE(ecu_serials_1[0].first.ToString().empty()); EXPECT_FALSE(ecu_serials_1[1].first.ToString().empty()); EXPECT_FALSE(ecu_serials_1[2].first.ToString().empty()); } // Keep storage directory, but initialize new objects. Should load existing // serials. { Config conf(cmd); conf.provision.primary_ecu_serial = ""; auto storage = INvStorage::newStorage(conf.storage); auto http = std::make_shared<HttpFake>(temp_dir.Path()); auto uptane_client = SotaUptaneClient::newTestClient(conf, storage, http); EXPECT_NO_THROW(uptane_client->initialize()); EXPECT_TRUE(storage->loadEcuSerials(&ecu_serials_2)); EXPECT_EQ(ecu_serials_2.size(), 3); EXPECT_FALSE(ecu_serials_2[0].first.ToString().empty()); EXPECT_FALSE(ecu_serials_2[1].first.ToString().empty()); EXPECT_FALSE(ecu_serials_2[2].first.ToString().empty()); } // Verify that serials match across initializations. EXPECT_EQ(ecu_serials_1[0].first, ecu_serials_2[0].first); EXPECT_EQ(ecu_serials_1[1].first, ecu_serials_2[1].first); EXPECT_EQ(ecu_serials_1[2].first, ecu_serials_2[2].first); // Sanity check that primary and secondary serials do not match. EXPECT_NE(ecu_serials_1[0].first, ecu_serials_1[1].first); EXPECT_NE(ecu_serials_1[0].first, ecu_serials_1[2].first); EXPECT_NE(ecu_serials_1[1].first, ecu_serials_1[2].first); EXPECT_NE(ecu_serials_2[0].first, ecu_serials_2[1].first); EXPECT_NE(ecu_serials_2[0].first, ecu_serials_2[2].first); EXPECT_NE(ecu_serials_2[1].first, ecu_serials_2[2].first); } #ifndef __NO_MAIN__ int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); logger_set_threshold(boost::log::trivial::trace); if (argc != 2) { std::cerr << "Error: " << argv[0] << " requires the path to the build directory as an input argument.\n"; return EXIT_FAILURE; } build_dir = argv[1]; return RUN_ALL_TESTS(); } #endif
Update comments for uptane serial tests.
Update comments for uptane serial tests.
C++
mpl-2.0
advancedtelematic/sota_client_cpp,advancedtelematic/aktualizr,advancedtelematic/aktualizr,advancedtelematic/aktualizr,advancedtelematic/sota_client_cpp,advancedtelematic/aktualizr
75f00280601c18d179668b3497cc49476098abed
src/libcsg/modules/io/h5mdtrajectoryreader.cc
src/libcsg/modules/io/h5mdtrajectoryreader.cc
#include <memory> /* * Copyright 2009-2019 The VOTCA Development Team (http://www.votca.org) * * 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 "h5mdtrajectoryreader.h" #include "hdf5.h" #include <vector> namespace votca { namespace csg { using namespace std; H5MDTrajectoryReader::H5MDTrajectoryReader() { has_velocity_ = H5MDTrajectoryReader::NONE; has_force_ = H5MDTrajectoryReader::NONE; has_id_group_ = H5MDTrajectoryReader::NONE; has_box_ = H5MDTrajectoryReader::NONE; } H5MDTrajectoryReader::~H5MDTrajectoryReader() { if (file_opened_) { H5Fclose(file_id_); file_opened_ = false; } } bool H5MDTrajectoryReader::Open(const string &file) { // Checks if we deal with hdf5 file. if (!H5Fis_hdf5(file.c_str())) { cout << file << " is not recognise as HDF5 file format" << endl; return false; } file_id_ = H5Fopen(file.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT); file_opened_ = true; // Check the version of the file. hid_t g_h5md = H5Gopen(file_id_, "h5md", H5P_DEFAULT); CheckError(g_h5md, "Unable to open /h5md group."); hid_t at_version = H5Aopen(g_h5md, "version", H5P_DEFAULT); CheckError(at_version, "Unable to read version attribute."); int version[2] = {0, 0}; H5Aread(at_version, H5Aget_type(at_version), &version); if (version[0] != 1 || version[1] > 1) { cout << "Found H5MD version: " << version[0] << "." << version[1] << endl; throw ios_base::failure("Wrong version of H5MD file."); } // Clean up. H5Aclose(at_version); H5Gclose(g_h5md); // Checks if the particles group exists and what is the number of members. particle_group_ = H5Gopen(file_id_, "particles", H5P_DEFAULT); CheckError(particle_group_, "Unable to open /particles group."); hsize_t num_obj = 0; H5Gget_num_objs(particle_group_, &num_obj); if (num_obj == 0) { throw ios_base::failure("The particles group is empty."); } first_frame_ = true; // Handle errors by internal check up. H5Eset_auto2(H5E_DEFAULT, nullptr, nullptr); return true; } void H5MDTrajectoryReader::Close() { if (file_opened_) { H5Fclose(file_id_); file_opened_ = false; } } void H5MDTrajectoryReader::Initialize(Topology &top) { string particle_group_name_ = top.getParticleGroup(); if (particle_group_name_.compare("unassigned") == 0) { throw ios_base::failure( "Missing particle group in topology. Please set `h5md_particle_group` " "tag with `name` attribute set to the particle group."); } string position_group_name = particle_group_name_ + "/position"; atom_position_group_ = H5Gopen(particle_group_, position_group_name.c_str(), H5P_DEFAULT); CheckError(atom_position_group_, "Unable to open " + position_group_name + " group"); idx_frame_ = -1; ds_atom_position_ = H5Dopen(atom_position_group_, "value", H5P_DEFAULT); CheckError(ds_atom_position_, "Unable to open " + position_group_name + "/value dataset"); // Reads the box information. string box_gr_name = particle_group_name_ + "/box"; hid_t g_box = H5Gopen(particle_group_, box_gr_name.c_str(), H5P_DEFAULT); CheckError(g_box, "Unable to open " + box_gr_name + " group"); hid_t at_box_dimension = H5Aopen(g_box, "dimension", H5P_DEFAULT); CheckError(at_box_dimension, "Unable to open dimension attribute."); Index dimension; H5Aread(at_box_dimension, H5Aget_type(at_box_dimension), &dimension); if (dimension != 3) { throw ios_base::failure("Wrong dimension " + boost::lexical_cast<string>(dimension)); } // TODO: check if boundary is periodic. string box_edges_name = particle_group_name_ + "/box/edges"; if (GroupExists(particle_group_, box_edges_name)) { g_box = H5Gopen(particle_group_, box_gr_name.c_str(), H5P_DEFAULT); edges_group_ = H5Gopen(g_box, "edges", H5P_DEFAULT); ds_edges_group_ = H5Dopen(edges_group_, "value", H5P_DEFAULT); cout << "H5MD: has /box/edges" << endl; cout << "H5MD: time dependent box size" << endl; has_box_ = H5MDTrajectoryReader::TIMEDEPENDENT; } else { cout << "H5MD: static box" << endl; hid_t ds_edges = H5Dopen(g_box, "edges", H5P_DEFAULT); CheckError(ds_edges, "Unable to open /box/edges"); unique_ptr<double[]> box = unique_ptr<double[]>{new double[3]}; ReadStaticData<double[]>(ds_edges, H5T_NATIVE_DOUBLE, box); cout << "H5MD: Found box " << box[0] << " x " << box[1] << " x " << box[2] << endl; // Sets box size. m = Eigen::Matrix3d::Zero(); m(0, 0) = box[0]; m(1, 1) = box[1]; m(2, 2) = box[2]; top.setBox(m); has_box_ = H5MDTrajectoryReader::STATIC; } H5Gclose(g_box); // Gets the force group. string force_group_name = particle_group_name_ + "/force"; if (GroupExists(particle_group_, force_group_name)) { atom_force_group_ = H5Gopen(particle_group_, force_group_name.c_str(), H5P_DEFAULT); ds_atom_force_ = H5Dopen(atom_force_group_, "value", H5P_DEFAULT); has_force_ = H5MDTrajectoryReader::TIMEDEPENDENT; cout << "H5MD: has /force" << endl; } else { has_force_ = H5MDTrajectoryReader::NONE; } // Gets the velocity group. string velocity_group_name = particle_group_name_ + "/velocity"; if (GroupExists(particle_group_, velocity_group_name)) { atom_velocity_group_ = H5Gopen(particle_group_, velocity_group_name.c_str(), H5P_DEFAULT); ds_atom_velocity_ = H5Dopen(atom_velocity_group_, "value", H5P_DEFAULT); has_velocity_ = H5MDTrajectoryReader::TIMEDEPENDENT; cout << "H5MD: has /velocity" << endl; } else { has_velocity_ = H5MDTrajectoryReader::NONE; } // Gets the id group so that the atom id is taken from this group. string id_group_name = particle_group_name_ + "/id"; if (GroupExists(particle_group_, id_group_name)) { atom_id_group_ = H5Gopen(particle_group_, id_group_name.c_str(), H5P_DEFAULT); ds_atom_id_ = H5Dopen(atom_id_group_, "value", H5P_DEFAULT); has_id_group_ = H5MDTrajectoryReader::TIMEDEPENDENT; cout << "H5MD: has /id group" << endl; } else { has_id_group_ = H5MDTrajectoryReader::NONE; } // Gets number of particles and dimensions. hid_t fs_atom_position_ = H5Dget_space(ds_atom_position_); CheckError(fs_atom_position_, "Unable to open atom position space."); hsize_t dims[3]; rank_ = H5Sget_simple_extent_dims(fs_atom_position_, dims, nullptr); N_particles_ = dims[1]; vec_components_ = (int)dims[2]; max_idx_frame_ = dims[0] - 1; // TODO: reads mass, charge and particle type. if (has_id_group_ == H5MDTrajectoryReader::NONE && top.BeadCount() > 0 && N_particles_ != top.BeadCount()) { cout << "Warning: The number of beads (" << N_particles_ << ")"; cout << " in the trajectory is different than defined in the topology (" << top.BeadCount() << ")" << endl; cout << "The number of beads from topology will be used!" << endl; N_particles_ = top.BeadCount(); } } bool H5MDTrajectoryReader::FirstFrame(Topology &top) { // NOLINT const // reference if (first_frame_) { first_frame_ = false; Initialize(top); } NextFrame(top); return true; } /// Reading the data. bool H5MDTrajectoryReader::NextFrame(Topology &top) { // NOLINT const reference // Reads the position row. idx_frame_++; if (idx_frame_ > max_idx_frame_) { return false; } cout << '\r' << "Reading frame: " << idx_frame_ << "\n"; cout.flush(); // Set volume of box because top on workers somehow does not have this // information. if (has_box_ == H5MDTrajectoryReader::TIMEDEPENDENT) { unique_ptr<double[]> box = unique_ptr<double[]>{new double[3]}; ReadBox(ds_edges_group_, H5T_NATIVE_DOUBLE, idx_frame_, box); m = Eigen::Matrix3d::Zero(); m(0, 0) = box.get()[0]; m(1, 1) = box.get()[1]; m(2, 2) = box.get()[2]; cout << "Time dependent box:" << endl; cout << m << endl; } top.setBox(m); double *positions; double *forces = nullptr; double *velocities = nullptr; Index *ids = nullptr; try { positions = ReadVectorData<double>(ds_atom_position_, H5T_NATIVE_DOUBLE, idx_frame_); } catch (const runtime_error &e) { return false; } if (has_velocity_ != H5MDTrajectoryReader::NONE) { velocities = ReadVectorData<double>(ds_atom_velocity_, H5T_NATIVE_DOUBLE, idx_frame_); } if (has_force_ != H5MDTrajectoryReader::NONE) { forces = ReadVectorData<double>(ds_atom_force_, H5T_NATIVE_DOUBLE, idx_frame_); } if (has_id_group_ != H5MDTrajectoryReader::NONE) { ids = ReadScalarData<Index>(ds_atom_id_, H5T_NATIVE_INT, idx_frame_); } // Process atoms. for (Index at_idx = 0; at_idx < N_particles_; at_idx++) { double x, y, z; Index array_index = at_idx * vec_components_; x = positions[array_index]; y = positions[array_index + 1]; z = positions[array_index + 2]; // Set atom id, or it is an index of a row in dataset or from id dataset. Index atom_id = at_idx; if (has_id_group_ != H5MDTrajectoryReader::NONE) { if (ids[at_idx] == -1) { // ignore values where id == -1 continue; } atom_id = ids[at_idx]; } // Topology has to be defined in the xml file or in other // topology files. The h5md only stores the trajectory data. Bead *b = top.getBead(atom_id); if (b == nullptr) { throw runtime_error("Bead not found: " + boost::lexical_cast<string>(atom_id)); } b->setPos(Eigen::Vector3d(x, y, z)); if (has_velocity_ == H5MDTrajectoryReader::TIMEDEPENDENT) { double vx, vy, vz; vx = velocities[array_index]; vy = velocities[array_index + 1]; vz = velocities[array_index + 2]; b->setVel(Eigen::Vector3d(vx, vy, vz)); } if (has_force_ == H5MDTrajectoryReader::TIMEDEPENDENT) { double fx, fy, fz; fx = forces[array_index]; fy = forces[array_index + 1]; fz = forces[array_index + 2]; b->setF(Eigen::Vector3d(fx, fy, fz)); } } // Clean up pointers. delete[] positions; if (has_force_ == H5MDTrajectoryReader::TIMEDEPENDENT) { delete[] forces; } if (has_velocity_ == H5MDTrajectoryReader::TIMEDEPENDENT) { delete[] velocities; } if (has_id_group_ == H5MDTrajectoryReader::TIMEDEPENDENT) { delete[] ids; } return true; } void H5MDTrajectoryReader::ReadBox(hid_t ds, hid_t ds_data_type, Index row, unique_ptr<double[]> &data_out) { hsize_t offset[2]; offset[0] = row; offset[1] = 0; hsize_t ch_rows[2]; ch_rows[0] = 1; ch_rows[1] = 3; hid_t dsp = H5Dget_space(ds); H5Sselect_hyperslab(dsp, H5S_SELECT_SET, offset, nullptr, ch_rows, nullptr); hid_t mspace1 = H5Screate_simple(2, ch_rows, nullptr); herr_t status = H5Dread(ds, ds_data_type, mspace1, dsp, H5P_DEFAULT, data_out.get()); if (status < 0) { throw std::runtime_error("Error ReadScalarData: " + boost::lexical_cast<std::string>(status)); } } } // namespace csg } // namespace votca
#include <memory> /* * Copyright 2009-2019 The VOTCA Development Team (http://www.votca.org) * * 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 "h5mdtrajectoryreader.h" #include "hdf5.h" #include <vector> namespace votca { namespace csg { using namespace std; H5MDTrajectoryReader::H5MDTrajectoryReader() { has_velocity_ = H5MDTrajectoryReader::NONE; has_force_ = H5MDTrajectoryReader::NONE; has_id_group_ = H5MDTrajectoryReader::NONE; has_box_ = H5MDTrajectoryReader::NONE; } H5MDTrajectoryReader::~H5MDTrajectoryReader() { if (file_opened_) { H5Fclose(file_id_); file_opened_ = false; } } bool H5MDTrajectoryReader::Open(const string &file) { // Checks if we deal with hdf5 file. if (!H5Fis_hdf5(file.c_str())) { cout << file << " is not recognise as HDF5 file format" << endl; return false; } file_id_ = H5Fopen(file.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT); file_opened_ = true; // Check the version of the file. hid_t g_h5md = H5Gopen(file_id_, "h5md", H5P_DEFAULT); CheckError(g_h5md, "Unable to open /h5md group."); hid_t at_version = H5Aopen(g_h5md, "version", H5P_DEFAULT); CheckError(at_version, "Unable to read version attribute."); int version[2] = {0, 0}; H5Aread(at_version, H5Aget_type(at_version), &version); if (version[0] != 1 || version[1] > 1) { cout << "Found H5MD version: " << version[0] << "." << version[1] << endl; throw ios_base::failure("Wrong version of H5MD file."); } // Clean up. H5Aclose(at_version); H5Gclose(g_h5md); // Checks if the particles group exists and what is the number of members. particle_group_ = H5Gopen(file_id_, "particles", H5P_DEFAULT); CheckError(particle_group_, "Unable to open /particles group."); hsize_t num_obj = 0; H5Gget_num_objs(particle_group_, &num_obj); if (num_obj == 0) { throw ios_base::failure("The particles group is empty."); } first_frame_ = true; // Handle errors by internal check up. H5Eset_auto2(H5E_DEFAULT, nullptr, nullptr); return true; } void H5MDTrajectoryReader::Close() { if (file_opened_) { H5Fclose(file_id_); file_opened_ = false; } } void H5MDTrajectoryReader::Initialize(Topology &top) { string particle_group_name_ = top.getParticleGroup(); if (particle_group_name_.compare("unassigned") == 0) { throw ios_base::failure( "Missing particle group in topology. Please set `h5md_particle_group` " "tag with `name` attribute set to the particle group."); } string position_group_name = particle_group_name_ + "/position"; atom_position_group_ = H5Gopen(particle_group_, position_group_name.c_str(), H5P_DEFAULT); CheckError(atom_position_group_, "Unable to open " + position_group_name + " group"); idx_frame_ = -1; ds_atom_position_ = H5Dopen(atom_position_group_, "value", H5P_DEFAULT); CheckError(ds_atom_position_, "Unable to open " + position_group_name + "/value dataset"); // Reads the box information. string box_gr_name = particle_group_name_ + "/box"; hid_t g_box = H5Gopen(particle_group_, box_gr_name.c_str(), H5P_DEFAULT); CheckError(g_box, "Unable to open " + box_gr_name + " group"); hid_t at_box_dimension = H5Aopen(g_box, "dimension", H5P_DEFAULT); CheckError(at_box_dimension, "Unable to open dimension attribute."); int dimension; H5Aread(at_box_dimension, H5Aget_type(at_box_dimension), &dimension); if (dimension != 3) { throw ios_base::failure("Wrong dimension " + boost::lexical_cast<string>(dimension)); } // TODO: check if boundary is periodic. string box_edges_name = particle_group_name_ + "/box/edges"; if (GroupExists(particle_group_, box_edges_name)) { g_box = H5Gopen(particle_group_, box_gr_name.c_str(), H5P_DEFAULT); edges_group_ = H5Gopen(g_box, "edges", H5P_DEFAULT); ds_edges_group_ = H5Dopen(edges_group_, "value", H5P_DEFAULT); cout << "H5MD: has /box/edges" << endl; cout << "H5MD: time dependent box size" << endl; has_box_ = H5MDTrajectoryReader::TIMEDEPENDENT; } else { cout << "H5MD: static box" << endl; hid_t ds_edges = H5Dopen(g_box, "edges", H5P_DEFAULT); CheckError(ds_edges, "Unable to open /box/edges"); unique_ptr<double[]> box = unique_ptr<double[]>{new double[3]}; ReadStaticData<double[]>(ds_edges, H5T_NATIVE_DOUBLE, box); cout << "H5MD: Found box " << box[0] << " x " << box[1] << " x " << box[2] << endl; // Sets box size. m = Eigen::Matrix3d::Zero(); m(0, 0) = box[0]; m(1, 1) = box[1]; m(2, 2) = box[2]; top.setBox(m); has_box_ = H5MDTrajectoryReader::STATIC; } H5Gclose(g_box); // Gets the force group. string force_group_name = particle_group_name_ + "/force"; if (GroupExists(particle_group_, force_group_name)) { atom_force_group_ = H5Gopen(particle_group_, force_group_name.c_str(), H5P_DEFAULT); ds_atom_force_ = H5Dopen(atom_force_group_, "value", H5P_DEFAULT); has_force_ = H5MDTrajectoryReader::TIMEDEPENDENT; cout << "H5MD: has /force" << endl; } else { has_force_ = H5MDTrajectoryReader::NONE; } // Gets the velocity group. string velocity_group_name = particle_group_name_ + "/velocity"; if (GroupExists(particle_group_, velocity_group_name)) { atom_velocity_group_ = H5Gopen(particle_group_, velocity_group_name.c_str(), H5P_DEFAULT); ds_atom_velocity_ = H5Dopen(atom_velocity_group_, "value", H5P_DEFAULT); has_velocity_ = H5MDTrajectoryReader::TIMEDEPENDENT; cout << "H5MD: has /velocity" << endl; } else { has_velocity_ = H5MDTrajectoryReader::NONE; } // Gets the id group so that the atom id is taken from this group. string id_group_name = particle_group_name_ + "/id"; if (GroupExists(particle_group_, id_group_name)) { atom_id_group_ = H5Gopen(particle_group_, id_group_name.c_str(), H5P_DEFAULT); ds_atom_id_ = H5Dopen(atom_id_group_, "value", H5P_DEFAULT); has_id_group_ = H5MDTrajectoryReader::TIMEDEPENDENT; cout << "H5MD: has /id group" << endl; } else { has_id_group_ = H5MDTrajectoryReader::NONE; } // Gets number of particles and dimensions. hid_t fs_atom_position_ = H5Dget_space(ds_atom_position_); CheckError(fs_atom_position_, "Unable to open atom position space."); hsize_t dims[3]; rank_ = H5Sget_simple_extent_dims(fs_atom_position_, dims, nullptr); N_particles_ = dims[1]; vec_components_ = (int)dims[2]; max_idx_frame_ = dims[0] - 1; // TODO: reads mass, charge and particle type. if (has_id_group_ == H5MDTrajectoryReader::NONE && top.BeadCount() > 0 && N_particles_ != top.BeadCount()) { cout << "Warning: The number of beads (" << N_particles_ << ")"; cout << " in the trajectory is different than defined in the topology (" << top.BeadCount() << ")" << endl; cout << "The number of beads from topology will be used!" << endl; N_particles_ = top.BeadCount(); } } bool H5MDTrajectoryReader::FirstFrame(Topology &top) { // NOLINT const // reference if (first_frame_) { first_frame_ = false; Initialize(top); } NextFrame(top); return true; } /// Reading the data. bool H5MDTrajectoryReader::NextFrame(Topology &top) { // NOLINT const reference // Reads the position row. idx_frame_++; if (idx_frame_ > max_idx_frame_) { return false; } cout << '\r' << "Reading frame: " << idx_frame_ << "\n"; cout.flush(); // Set volume of box because top on workers somehow does not have this // information. if (has_box_ == H5MDTrajectoryReader::TIMEDEPENDENT) { unique_ptr<double[]> box = unique_ptr<double[]>{new double[3]}; ReadBox(ds_edges_group_, H5T_NATIVE_DOUBLE, idx_frame_, box); m = Eigen::Matrix3d::Zero(); m(0, 0) = box.get()[0]; m(1, 1) = box.get()[1]; m(2, 2) = box.get()[2]; cout << "Time dependent box:" << endl; cout << m << endl; } top.setBox(m); double *positions; double *forces = nullptr; double *velocities = nullptr; Index *ids = nullptr; try { positions = ReadVectorData<double>(ds_atom_position_, H5T_NATIVE_DOUBLE, idx_frame_); } catch (const runtime_error &e) { return false; } if (has_velocity_ != H5MDTrajectoryReader::NONE) { velocities = ReadVectorData<double>(ds_atom_velocity_, H5T_NATIVE_DOUBLE, idx_frame_); } if (has_force_ != H5MDTrajectoryReader::NONE) { forces = ReadVectorData<double>(ds_atom_force_, H5T_NATIVE_DOUBLE, idx_frame_); } if (has_id_group_ != H5MDTrajectoryReader::NONE) { ids = ReadScalarData<Index>(ds_atom_id_, H5T_NATIVE_INT, idx_frame_); } // Process atoms. for (Index at_idx = 0; at_idx < N_particles_; at_idx++) { double x, y, z; Index array_index = at_idx * vec_components_; x = positions[array_index]; y = positions[array_index + 1]; z = positions[array_index + 2]; // Set atom id, or it is an index of a row in dataset or from id dataset. Index atom_id = at_idx; if (has_id_group_ != H5MDTrajectoryReader::NONE) { if (ids[at_idx] == -1) { // ignore values where id == -1 continue; } atom_id = ids[at_idx]; } // Topology has to be defined in the xml file or in other // topology files. The h5md only stores the trajectory data. Bead *b = top.getBead(atom_id); if (b == nullptr) { throw runtime_error("Bead not found: " + boost::lexical_cast<string>(atom_id)); } b->setPos(Eigen::Vector3d(x, y, z)); if (has_velocity_ == H5MDTrajectoryReader::TIMEDEPENDENT) { double vx, vy, vz; vx = velocities[array_index]; vy = velocities[array_index + 1]; vz = velocities[array_index + 2]; b->setVel(Eigen::Vector3d(vx, vy, vz)); } if (has_force_ == H5MDTrajectoryReader::TIMEDEPENDENT) { double fx, fy, fz; fx = forces[array_index]; fy = forces[array_index + 1]; fz = forces[array_index + 2]; b->setF(Eigen::Vector3d(fx, fy, fz)); } } // Clean up pointers. delete[] positions; if (has_force_ == H5MDTrajectoryReader::TIMEDEPENDENT) { delete[] forces; } if (has_velocity_ == H5MDTrajectoryReader::TIMEDEPENDENT) { delete[] velocities; } if (has_id_group_ == H5MDTrajectoryReader::TIMEDEPENDENT) { delete[] ids; } return true; } void H5MDTrajectoryReader::ReadBox(hid_t ds, hid_t ds_data_type, Index row, unique_ptr<double[]> &data_out) { hsize_t offset[2]; offset[0] = row; offset[1] = 0; hsize_t ch_rows[2]; ch_rows[0] = 1; ch_rows[1] = 3; hid_t dsp = H5Dget_space(ds); H5Sselect_hyperslab(dsp, H5S_SELECT_SET, offset, nullptr, ch_rows, nullptr); hid_t mspace1 = H5Screate_simple(2, ch_rows, nullptr); herr_t status = H5Dread(ds, ds_data_type, mspace1, dsp, H5P_DEFAULT, data_out.get()); if (status < 0) { throw std::runtime_error("Error ReadScalarData: " + boost::lexical_cast<std::string>(status)); } } } // namespace csg } // namespace votca
fix another wrong Index
h5mdtrajectoryreader: fix another wrong Index
C++
apache-2.0
votca/csg,MrTheodor/csg,MrTheodor/csg,MrTheodor/csg,MrTheodor/csg,votca/csg,MrTheodor/csg,votca/csg,votca/csg
8d8293eefba5c79c409e9faeff38a89c6ea90686
lib/ReaderWriter/ELF/Hexagon/HexagonTargetHandler.cpp
lib/ReaderWriter/ELF/Hexagon/HexagonTargetHandler.cpp
//===- lib/ReaderWriter/ELF/Hexagon/HexagonTargetHandler.cpp --------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "HexagonExecutableWriter.h" #include "HexagonDynamicLibraryWriter.h" #include "HexagonLinkingContext.h" #include "HexagonTargetHandler.h" using namespace lld; using namespace elf; using namespace llvm::ELF; using llvm::makeArrayRef; HexagonTargetHandler::HexagonTargetHandler(HexagonLinkingContext &ctx) : _ctx(ctx), _hexagonRuntimeFile(new HexagonRuntimeFile<HexagonELFType>(ctx)), _hexagonTargetLayout(new HexagonTargetLayout<HexagonELFType>(ctx)), _hexagonRelocationHandler( new HexagonTargetRelocationHandler(*_hexagonTargetLayout)) {} std::unique_ptr<Writer> HexagonTargetHandler::getWriter() { switch (_ctx.getOutputELFType()) { case llvm::ELF::ET_EXEC: return llvm::make_unique<HexagonExecutableWriter<HexagonELFType>>( _ctx, *_hexagonTargetLayout.get()); case llvm::ELF::ET_DYN: return llvm::make_unique<HexagonDynamicLibraryWriter<HexagonELFType>>( _ctx, *_hexagonTargetLayout.get()); case llvm::ELF::ET_REL: llvm_unreachable("TODO: support -r mode"); default: llvm_unreachable("unsupported output type"); } } using namespace llvm::ELF; // .got atom const uint8_t hexagonGotAtomContent[4] = { 0 }; // .got.plt atom (entry 0) const uint8_t hexagonGotPlt0AtomContent[16] = { 0 }; // .got.plt atom (all other entries) const uint8_t hexagonGotPltAtomContent[4] = { 0 }; // .plt (entry 0) const uint8_t hexagonPlt0AtomContent[28] = { 0x00, 0x40, 0x00, 0x00, // { immext (#0) 0x1c, 0xc0, 0x49, 0x6a, // r28 = add (pc, ##GOT0@PCREL) } # address of GOT0 0x0e, 0x42, 0x9c, 0xe2, // { r14 -= add (r28, #16) # offset of GOTn from GOTa 0x4f, 0x40, 0x9c, 0x91, // r15 = memw (r28 + #8) # object ID at GOT2 0x3c, 0xc0, 0x9c, 0x91, // r28 = memw (r28 + #4) }# dynamic link at GOT1 0x0e, 0x42, 0x0e, 0x8c, // { r14 = asr (r14, #2) # index of PLTn 0x00, 0xc0, 0x9c, 0x52, // jumpr r28 } # call dynamic linker }; // .plt (other entries) const uint8_t hexagonPltAtomContent[16] = { 0x00, 0x40, 0x00, 0x00, // { immext (#0) 0x0e, 0xc0, 0x49, 0x6a, // r14 = add (pc, ##GOTn@PCREL) } # address of GOTn 0x1c, 0xc0, 0x8e, 0x91, // r28 = memw (r14) # contents of GOTn 0x00, 0xc0, 0x9c, 0x52, // jumpr r28 # call it }; class HexagonGOTAtom : public GOTAtom { public: HexagonGOTAtom(const File &f) : GOTAtom(f, ".got") {} ArrayRef<uint8_t> rawContent() const override { return makeArrayRef(hexagonGotAtomContent); } Alignment alignment() const override { return 4; } }; class HexagonGOTPLTAtom : public GOTAtom { public: HexagonGOTPLTAtom(const File &f) : GOTAtom(f, ".got.plt") {} ArrayRef<uint8_t> rawContent() const override { return makeArrayRef(hexagonGotPltAtomContent); } Alignment alignment() const override { return 4; } }; class HexagonGOTPLT0Atom : public GOTAtom { public: HexagonGOTPLT0Atom(const File &f) : GOTAtom(f, ".got.plt") {} ArrayRef<uint8_t> rawContent() const override { return makeArrayRef(hexagonGotPlt0AtomContent); } Alignment alignment() const override { return 8; } }; class HexagonPLT0Atom : public PLT0Atom { public: HexagonPLT0Atom(const File &f) : PLT0Atom(f) {} ArrayRef<uint8_t> rawContent() const override { return makeArrayRef(hexagonPlt0AtomContent); } }; class HexagonPLTAtom : public PLTAtom { public: HexagonPLTAtom(const File &f, StringRef secName) : PLTAtom(f, secName) {} ArrayRef<uint8_t> rawContent() const override { return makeArrayRef(hexagonPltAtomContent); } }; class ELFPassFile : public SimpleFile { public: ELFPassFile(const ELFLinkingContext &eti) : SimpleFile("ELFPassFile") { setOrdinal(eti.getNextOrdinalAndIncrement()); } llvm::BumpPtrAllocator _alloc; }; /// \brief Create GOT and PLT entries for relocations. Handles standard GOT/PLT template <class Derived> class GOTPLTPass : public Pass { /// \brief Handle a specific reference. void handleReference(const DefinedAtom &atom, const Reference &ref) { if (ref.kindNamespace() != Reference::KindNamespace::ELF) return; assert(ref.kindArch() == Reference::KindArch::Hexagon); switch (ref.kindValue()) { case R_HEX_PLT_B22_PCREL: case R_HEX_B22_PCREL: static_cast<Derived *>(this)->handlePLT32(ref); break; case R_HEX_GOT_LO16: case R_HEX_GOT_HI16: case R_HEX_GOT_32_6_X: case R_HEX_GOT_16_X: case R_HEX_GOT_11_X: static_cast<Derived *>(this)->handleGOTREL(ref); break; } } protected: /// \brief Create a GOT entry containing 0. const GOTAtom *getNullGOT() { if (!_null) { _null = new (_file._alloc) HexagonGOTPLTAtom(_file); #ifndef NDEBUG _null->_name = "__got_null"; #endif } return _null; } public: GOTPLTPass(const ELFLinkingContext &ctx) : _file(ctx), _null(nullptr), _plt0(nullptr), _got0(nullptr) {} /// \brief Do the pass. /// /// The goal here is to first process each reference individually. Each call /// to handleReference may modify the reference itself and/or create new /// atoms which must be stored in one of the maps below. /// /// After all references are handled, the atoms created during that are all /// added to mf. void perform(std::unique_ptr<MutableFile> &mf) override { // Process all references. for (const auto &atom : mf->defined()) for (const auto &ref : *atom) handleReference(*atom, *ref); // Add all created atoms to the link. uint64_t ordinal = 0; if (_plt0) { _plt0->setOrdinal(ordinal++); mf->addAtom(*_plt0); } for (auto &plt : _pltVector) { plt->setOrdinal(ordinal++); mf->addAtom(*plt); } if (_null) { _null->setOrdinal(ordinal++); mf->addAtom(*_null); } if (_got0) { _got0->setOrdinal(ordinal++); mf->addAtom(*_got0); } for (auto &got : _gotVector) { got->setOrdinal(ordinal++); mf->addAtom(*got); } } protected: /// \brief Owner of all the Atoms created by this pass. ELFPassFile _file; /// \brief Map Atoms to their GOT entries. llvm::DenseMap<const Atom *, GOTAtom *> _gotMap; /// \brief Map Atoms to their PLT entries. llvm::DenseMap<const Atom *, PLTAtom *> _pltMap; /// \brief the list of GOT/PLT atoms std::vector<GOTAtom *> _gotVector; std::vector<PLTAtom *> _pltVector; /// \brief GOT entry that is always 0. Used for undefined weaks. GOTAtom *_null; /// \brief The got and plt entries for .PLT0. This is used to call into the /// dynamic linker for symbol resolution. /// @{ PLT0Atom *_plt0; GOTAtom *_got0; /// @} }; class DynamicGOTPLTPass final : public GOTPLTPass<DynamicGOTPLTPass> { public: DynamicGOTPLTPass(const elf::HexagonLinkingContext &ctx) : GOTPLTPass(ctx) { _got0 = new (_file._alloc) HexagonGOTPLT0Atom(_file); #ifndef NDEBUG _got0->_name = "__got0"; #endif } const PLT0Atom *getPLT0() { if (_plt0) return _plt0; _plt0 = new (_file._alloc) HexagonPLT0Atom(_file); _plt0->addReferenceELF_Hexagon(R_HEX_B32_PCREL_X, 0, _got0, 0); _plt0->addReferenceELF_Hexagon(R_HEX_6_PCREL_X, 4, _got0, 4); DEBUG_WITH_TYPE("PLT", llvm::dbgs() << "[ PLT0/GOT0 ] " << "Adding plt0/got0 \n"); return _plt0; } const PLTAtom *getPLTEntry(const Atom *a) { auto plt = _pltMap.find(a); if (plt != _pltMap.end()) return plt->second; auto ga = new (_file._alloc) HexagonGOTPLTAtom(_file); ga->addReferenceELF_Hexagon(R_HEX_JMP_SLOT, 0, a, 0); auto pa = new (_file._alloc) HexagonPLTAtom(_file, ".plt"); pa->addReferenceELF_Hexagon(R_HEX_B32_PCREL_X, 0, ga, 0); pa->addReferenceELF_Hexagon(R_HEX_6_PCREL_X, 4, ga, 4); // Point the got entry to the PLT0 atom initially ga->addReferenceELF_Hexagon(R_HEX_32, 0, getPLT0(), 0); #ifndef NDEBUG ga->_name = "__got_"; ga->_name += a->name(); pa->_name = "__plt_"; pa->_name += a->name(); DEBUG_WITH_TYPE("PLT", llvm::dbgs() << "[" << a->name() << "] " << "Adding plt/got: " << pa->_name << "/" << ga->_name << "\n"); #endif _gotMap[a] = ga; _pltMap[a] = pa; _gotVector.push_back(ga); _pltVector.push_back(pa); return pa; } const GOTAtom *getGOTEntry(const Atom *a) { auto got = _gotMap.find(a); if (got != _gotMap.end()) return got->second; auto ga = new (_file._alloc) HexagonGOTAtom(_file); ga->addReferenceELF_Hexagon(R_HEX_GLOB_DAT, 0, a, 0); #ifndef NDEBUG ga->_name = "__got_"; ga->_name += a->name(); DEBUG_WITH_TYPE("GOT", llvm::dbgs() << "[" << a->name() << "] " << "Adding got: " << ga->_name << "\n"); #endif _gotMap[a] = ga; _gotVector.push_back(ga); return ga; } std::error_code handleGOTREL(const Reference &ref) { // Turn this so that the target is set to the GOT entry const_cast<Reference &>(ref).setTarget(getGOTEntry(ref.target())); return std::error_code(); } std::error_code handlePLT32(const Reference &ref) { // Turn this into a PC32 to the PLT entry. assert(ref.kindNamespace() == Reference::KindNamespace::ELF); assert(ref.kindArch() == Reference::KindArch::Hexagon); const_cast<Reference &>(ref).setKindValue(R_HEX_B22_PCREL); const_cast<Reference &>(ref).setTarget(getPLTEntry(ref.target())); return std::error_code(); } }; void elf::HexagonLinkingContext::addPasses(PassManager &pm) { if (isDynamic()) pm.add(llvm::make_unique<DynamicGOTPLTPass>(*this)); ELFLinkingContext::addPasses(pm); } void HexagonTargetHandler::registerRelocationNames(Registry &registry) { registry.addKindTable(Reference::KindNamespace::ELF, Reference::KindArch::Hexagon, kindStrings); } #define ELF_RELOC(name, value) LLD_KIND_STRING_ENTRY(name), const Registry::KindStrings HexagonTargetHandler::kindStrings[] = { #include "llvm/Support/ELFRelocs/Hexagon.def" LLD_KIND_STRING_END }; #undef ELF_RELOC
//===- lib/ReaderWriter/ELF/Hexagon/HexagonTargetHandler.cpp --------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "HexagonExecutableWriter.h" #include "HexagonDynamicLibraryWriter.h" #include "HexagonLinkingContext.h" #include "HexagonTargetHandler.h" using namespace lld; using namespace elf; using namespace llvm::ELF; using llvm::makeArrayRef; HexagonTargetHandler::HexagonTargetHandler(HexagonLinkingContext &ctx) : _ctx(ctx), _hexagonRuntimeFile(new HexagonRuntimeFile<HexagonELFType>(ctx)), _hexagonTargetLayout(new HexagonTargetLayout<HexagonELFType>(ctx)), _hexagonRelocationHandler( new HexagonTargetRelocationHandler(*_hexagonTargetLayout)) {} std::unique_ptr<Writer> HexagonTargetHandler::getWriter() { switch (_ctx.getOutputELFType()) { case llvm::ELF::ET_EXEC: return llvm::make_unique<HexagonExecutableWriter<HexagonELFType>>( _ctx, *_hexagonTargetLayout.get()); case llvm::ELF::ET_DYN: return llvm::make_unique<HexagonDynamicLibraryWriter<HexagonELFType>>( _ctx, *_hexagonTargetLayout.get()); case llvm::ELF::ET_REL: llvm_unreachable("TODO: support -r mode"); default: llvm_unreachable("unsupported output type"); } } using namespace llvm::ELF; // .got atom const uint8_t hexagonGotAtomContent[4] = { 0 }; // .got.plt atom (entry 0) const uint8_t hexagonGotPlt0AtomContent[16] = { 0 }; // .got.plt atom (all other entries) const uint8_t hexagonGotPltAtomContent[4] = { 0 }; // .plt (entry 0) const uint8_t hexagonPlt0AtomContent[28] = { 0x00, 0x40, 0x00, 0x00, // { immext (#0) 0x1c, 0xc0, 0x49, 0x6a, // r28 = add (pc, ##GOT0@PCREL) } # address of GOT0 0x0e, 0x42, 0x9c, 0xe2, // { r14 -= add (r28, #16) # offset of GOTn from GOTa 0x4f, 0x40, 0x9c, 0x91, // r15 = memw (r28 + #8) # object ID at GOT2 0x3c, 0xc0, 0x9c, 0x91, // r28 = memw (r28 + #4) }# dynamic link at GOT1 0x0e, 0x42, 0x0e, 0x8c, // { r14 = asr (r14, #2) # index of PLTn 0x00, 0xc0, 0x9c, 0x52, // jumpr r28 } # call dynamic linker }; // .plt (other entries) const uint8_t hexagonPltAtomContent[16] = { 0x00, 0x40, 0x00, 0x00, // { immext (#0) 0x0e, 0xc0, 0x49, 0x6a, // r14 = add (pc, ##GOTn@PCREL) } # address of GOTn 0x1c, 0xc0, 0x8e, 0x91, // r28 = memw (r14) # contents of GOTn 0x00, 0xc0, 0x9c, 0x52, // jumpr r28 # call it }; class HexagonGOTAtom : public GOTAtom { public: HexagonGOTAtom(const File &f) : GOTAtom(f, ".got") {} ArrayRef<uint8_t> rawContent() const override { return makeArrayRef(hexagonGotAtomContent); } Alignment alignment() const override { return 4; } }; class HexagonGOTPLTAtom : public GOTAtom { public: HexagonGOTPLTAtom(const File &f) : GOTAtom(f, ".got.plt") {} ArrayRef<uint8_t> rawContent() const override { return makeArrayRef(hexagonGotPltAtomContent); } Alignment alignment() const override { return 4; } }; class HexagonGOTPLT0Atom : public GOTAtom { public: HexagonGOTPLT0Atom(const File &f) : GOTAtom(f, ".got.plt") {} ArrayRef<uint8_t> rawContent() const override { return makeArrayRef(hexagonGotPlt0AtomContent); } Alignment alignment() const override { return 8; } }; class HexagonPLT0Atom : public PLT0Atom { public: HexagonPLT0Atom(const File &f) : PLT0Atom(f) {} ArrayRef<uint8_t> rawContent() const override { return makeArrayRef(hexagonPlt0AtomContent); } }; class HexagonPLTAtom : public PLTAtom { public: HexagonPLTAtom(const File &f, StringRef secName) : PLTAtom(f, secName) {} ArrayRef<uint8_t> rawContent() const override { return makeArrayRef(hexagonPltAtomContent); } }; class ELFPassFile : public SimpleFile { public: ELFPassFile(const ELFLinkingContext &eti) : SimpleFile("ELFPassFile") { setOrdinal(eti.getNextOrdinalAndIncrement()); } llvm::BumpPtrAllocator _alloc; }; /// \brief Create GOT and PLT entries for relocations. Handles standard GOT/PLT template <class Derived> class GOTPLTPass : public Pass { /// \brief Handle a specific reference. void handleReference(const DefinedAtom &atom, const Reference &ref) { if (ref.kindNamespace() != Reference::KindNamespace::ELF) return; assert(ref.kindArch() == Reference::KindArch::Hexagon); switch (ref.kindValue()) { case R_HEX_PLT_B22_PCREL: case R_HEX_B22_PCREL: static_cast<Derived *>(this)->handlePLT32(ref); break; case R_HEX_GOT_LO16: case R_HEX_GOT_HI16: case R_HEX_GOT_32_6_X: case R_HEX_GOT_16_X: case R_HEX_GOT_11_X: static_cast<Derived *>(this)->handleGOTREL(ref); break; } } protected: /// \brief Create a GOT entry containing 0. const GOTAtom *getNullGOT() { if (!_null) { _null = new (_file._alloc) HexagonGOTPLTAtom(_file); #ifndef NDEBUG _null->_name = "__got_null"; #endif } return _null; } public: GOTPLTPass(const ELFLinkingContext &ctx) : _file(ctx) {} /// \brief Do the pass. /// /// The goal here is to first process each reference individually. Each call /// to handleReference may modify the reference itself and/or create new /// atoms which must be stored in one of the maps below. /// /// After all references are handled, the atoms created during that are all /// added to mf. void perform(std::unique_ptr<MutableFile> &mf) override { // Process all references. for (const auto &atom : mf->defined()) for (const auto &ref : *atom) handleReference(*atom, *ref); // Add all created atoms to the link. uint64_t ordinal = 0; if (_plt0) { _plt0->setOrdinal(ordinal++); mf->addAtom(*_plt0); } for (auto &plt : _pltVector) { plt->setOrdinal(ordinal++); mf->addAtom(*plt); } if (_null) { _null->setOrdinal(ordinal++); mf->addAtom(*_null); } if (_got0) { _got0->setOrdinal(ordinal++); mf->addAtom(*_got0); } for (auto &got : _gotVector) { got->setOrdinal(ordinal++); mf->addAtom(*got); } } protected: /// \brief Owner of all the Atoms created by this pass. ELFPassFile _file; /// \brief Map Atoms to their GOT entries. llvm::DenseMap<const Atom *, GOTAtom *> _gotMap; /// \brief Map Atoms to their PLT entries. llvm::DenseMap<const Atom *, PLTAtom *> _pltMap; /// \brief the list of GOT/PLT atoms std::vector<GOTAtom *> _gotVector; std::vector<PLTAtom *> _pltVector; /// \brief GOT entry that is always 0. Used for undefined weaks. GOTAtom *_null = nullptr; /// \brief The got and plt entries for .PLT0. This is used to call into the /// dynamic linker for symbol resolution. /// @{ PLT0Atom *_plt0 = nullptr; GOTAtom *_got0 = nullptr; /// @} }; class DynamicGOTPLTPass final : public GOTPLTPass<DynamicGOTPLTPass> { public: DynamicGOTPLTPass(const elf::HexagonLinkingContext &ctx) : GOTPLTPass(ctx) { _got0 = new (_file._alloc) HexagonGOTPLT0Atom(_file); #ifndef NDEBUG _got0->_name = "__got0"; #endif } const PLT0Atom *getPLT0() { if (_plt0) return _plt0; _plt0 = new (_file._alloc) HexagonPLT0Atom(_file); _plt0->addReferenceELF_Hexagon(R_HEX_B32_PCREL_X, 0, _got0, 0); _plt0->addReferenceELF_Hexagon(R_HEX_6_PCREL_X, 4, _got0, 4); DEBUG_WITH_TYPE("PLT", llvm::dbgs() << "[ PLT0/GOT0 ] " << "Adding plt0/got0 \n"); return _plt0; } const PLTAtom *getPLTEntry(const Atom *a) { auto plt = _pltMap.find(a); if (plt != _pltMap.end()) return plt->second; auto ga = new (_file._alloc) HexagonGOTPLTAtom(_file); ga->addReferenceELF_Hexagon(R_HEX_JMP_SLOT, 0, a, 0); auto pa = new (_file._alloc) HexagonPLTAtom(_file, ".plt"); pa->addReferenceELF_Hexagon(R_HEX_B32_PCREL_X, 0, ga, 0); pa->addReferenceELF_Hexagon(R_HEX_6_PCREL_X, 4, ga, 4); // Point the got entry to the PLT0 atom initially ga->addReferenceELF_Hexagon(R_HEX_32, 0, getPLT0(), 0); #ifndef NDEBUG ga->_name = "__got_"; ga->_name += a->name(); pa->_name = "__plt_"; pa->_name += a->name(); DEBUG_WITH_TYPE("PLT", llvm::dbgs() << "[" << a->name() << "] " << "Adding plt/got: " << pa->_name << "/" << ga->_name << "\n"); #endif _gotMap[a] = ga; _pltMap[a] = pa; _gotVector.push_back(ga); _pltVector.push_back(pa); return pa; } const GOTAtom *getGOTEntry(const Atom *a) { auto got = _gotMap.find(a); if (got != _gotMap.end()) return got->second; auto ga = new (_file._alloc) HexagonGOTAtom(_file); ga->addReferenceELF_Hexagon(R_HEX_GLOB_DAT, 0, a, 0); #ifndef NDEBUG ga->_name = "__got_"; ga->_name += a->name(); DEBUG_WITH_TYPE("GOT", llvm::dbgs() << "[" << a->name() << "] " << "Adding got: " << ga->_name << "\n"); #endif _gotMap[a] = ga; _gotVector.push_back(ga); return ga; } std::error_code handleGOTREL(const Reference &ref) { // Turn this so that the target is set to the GOT entry const_cast<Reference &>(ref).setTarget(getGOTEntry(ref.target())); return std::error_code(); } std::error_code handlePLT32(const Reference &ref) { // Turn this into a PC32 to the PLT entry. assert(ref.kindNamespace() == Reference::KindNamespace::ELF); assert(ref.kindArch() == Reference::KindArch::Hexagon); const_cast<Reference &>(ref).setKindValue(R_HEX_B22_PCREL); const_cast<Reference &>(ref).setTarget(getPLTEntry(ref.target())); return std::error_code(); } }; void elf::HexagonLinkingContext::addPasses(PassManager &pm) { if (isDynamic()) pm.add(llvm::make_unique<DynamicGOTPLTPass>(*this)); ELFLinkingContext::addPasses(pm); } void HexagonTargetHandler::registerRelocationNames(Registry &registry) { registry.addKindTable(Reference::KindNamespace::ELF, Reference::KindArch::Hexagon, kindStrings); } #define ELF_RELOC(name, value) LLD_KIND_STRING_ENTRY(name), const Registry::KindStrings HexagonTargetHandler::kindStrings[] = { #include "llvm/Support/ELFRelocs/Hexagon.def" LLD_KIND_STRING_END }; #undef ELF_RELOC
Use C++ non-static member initialization.
Use C++ non-static member initialization. git-svn-id: f6089bf0e6284f307027cef4f64114ee9ebb0424@233739 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/lld,llvm-mirror/lld
fb1065bfb34727e7727de770946a345da0c1bc5e
src/libgetenv/benchmarks/benchmark_getenv.cpp
src/libgetenv/benchmarks/benchmark_getenv.cpp
/** * @file * * @brief benchmark for getenv * * @copyright BSD License (see doc/COPYING or http://www.libelektra.org) * */ #include <keyset.hpp> #include <kdbtimer.hpp> #include <fstream> #include <iostream> #include <dlfcn.h> #include <string.h> extern "C" char **environ; // long long iterations = 100000000000LL; // elitebenchmark lookup long long iterations = 100000000LL; // elitebenchmark // long long iterations = 100LL; // valgrind // not needed in benchmarks: long long iterations1 = iterations / 100; const int benchmarkIterations = 11; // is a good number to not need mean values for median const std::string filename = "check.txt"; const std::string csvfilename = "data.csv"; std::ofstream dump(filename); std::ofstream data(csvfilename); // from libgetenv namespace ckdb{ char *elektraBootstrapGetEnv(const char *name); } // very fast benchmarks without any if: __attribute__((noinline)) void benchmark_nothing() { static Timer t("nothing"); t.start(); t.stop(); std::cout << t; dump << t.name << std::endl; } #define _STRING_ARCH_unaligned 1 /* Return the value of the environment variable NAME. This implementation is tuned a bit in that it assumes no environment variable has an empty name which of course should always be true. We have a special case for one character names so that for the general case we can assume at least two characters which we can access. By doing this we can avoid using the `strncmp' most of the time. */ __attribute__((noinline)) char * libc_getenv (const char *name) { size_t len = strlen (name); char **ep; uint16_t name_start; if (environ == NULL || name[0] == '\0') return NULL; if (name[1] == '\0') { /* The name of the variable consists of only one character. Therefore the first two characters of the environment entry are this character and a '=' character. */ #if __BYTE_ORDER == __LITTLE_ENDIAN || !_STRING_ARCH_unaligned name_start = ('=' << 8) | *(const unsigned char *) name; #else # if __BYTE_ORDER == __BIG_ENDIAN name_start = '=' | ((*(const unsigned char *) name) << 8); # else #error "Funny byte order." # endif #endif for (ep = environ; *ep != NULL; ++ep) { #if _STRING_ARCH_unaligned uint16_t ep_start = *(uint16_t *) *ep; #else uint16_t ep_start = (((unsigned char *) *ep)[0] | (((unsigned char *) *ep)[1] << 8)); #endif if (name_start == ep_start) return &(*ep)[2]; } } else { #if _STRING_ARCH_unaligned name_start = *(const uint16_t *) name; #else name_start = (((const unsigned char *) name)[0] | (((const unsigned char *) name)[1] << 8)); #endif len -= 2; name += 2; for (ep = environ; *ep != NULL; ++ep) { #if _STRING_ARCH_unaligned uint16_t ep_start = *(uint16_t *) *ep; #else uint16_t ep_start = (((unsigned char *) *ep)[0] | (((unsigned char *) *ep)[1] << 8)); #endif if (name_start == ep_start && !strncmp (*ep + 2, name, len) && (*ep)[len + 2] == '=') return &(*ep)[len + 3]; } } return NULL; } __attribute__((noinline)) void benchmark_libc_getenv() { static Timer t("libc getenv"); t.start(); for (long long i=0; i<iterations; ++i) { libc_getenv("HELLO"); __asm__(""); } t.stop(); std::cout << t; dump << t.name << std::endl; } __attribute__((noinline)) void benchmark_dl_libc_getenv() { static Timer t("dl libc getenv"); typedef char *(* gfcn)(const char *); union Sym{void*d; gfcn f;} sym; sym.d = dlsym(RTLD_NEXT, "getenv"); gfcn dl_libc_getenv = sym.f; t.start(); for (long long i=0; i<iterations; ++i) { dl_libc_getenv("HELLO"); __asm__(""); } t.stop(); std::cout << t; dump << t.name << std::endl; } __attribute__((noinline)) void benchmark_bootstrap_getenv() { static Timer t("bootstrap getenv"); t.start(); for (long long i=0; i<iterations; ++i) { ckdb::elektraBootstrapGetEnv("HELLO"); __asm__(""); } t.stop(); std::cout << t; dump << t.name << std::endl; } __attribute__((noinline)) void benchmark_kslookup() { static Timer t("kslookup"); using namespace kdb; // needed for KS_END kdb::KeySet ks( 100, /* *kdb::Key("user/env/override/some", KEY_END), *kdb::Key("user/env/override/a/key", KEY_END), *kdb::Key("user/env/override/b/key", KEY_END), *kdb::Key("user/env/override/c/key", KEY_END), *kdb::Key("user/env/override/d/key", KEY_END), */ KS_END); for (int i=0; i<1000; ++i) { char x[100]; sprintf(x, "user/env/override/hello%d_%d", i, i); ks.append(*kdb::Key(x, KEY_END)); } Key lookupKey ("user/env/override/HELLO", KEY_END); t.start(); for (long long i=0; i<iterations; ++i) { ks.lookup(lookupKey); __asm__(""); } t.stop(); std::cout << t; } #include <unistd.h> #ifdef _WIN32 # include <winsock2.h> #endif void computer_info() { char hostname[1024]; gethostname(hostname, 1023); std::cout << std::endl; std::cout << std::endl; std::cout << "hostname " << hostname << std::endl; #ifdef __GNUC__ std::cout << "gcc: " << __GNUC__ << std::endl; #endif #ifdef __INTEL_COMPILER std::cout << "icc: " << __INTEL_COMPILER << std::endl; #endif #ifdef __clang__ std::cout << "clang: " << __clang__ << std::endl; #endif std::cout << "sizeof(int) " << sizeof(int) << std::endl; std::cout << "sizeof(long) " << sizeof(long) << std::endl; std::cout << "sizeof(long long) " << sizeof(long long) << std::endl; std::cout << "iterations " << iterations << std::endl; std::cout << "filename " << filename << std::endl; std::cout << std::endl; } int main(int argc, char**argv) { computer_info(); clearenv(); for (int i=0; i<1000; ++i) { char x[100]; sprintf(x, "hello%d_%d", i, i); setenv(x, x, 0); } if (argc==2) { iterations = atoll(argv[1]); iterations1 = iterations / 100; } for (int i=0; i<benchmarkIterations; ++i) { std::cout << i << std::endl; benchmark_nothing(); benchmark_libc_getenv(); // benchmark_dl_libc_getenv(); //TODO benchmark_bootstrap_getenv(); benchmark_kslookup(); // benchmark_hashmap(); // benchmark_hashmap_find(); } data << "value,benchmark" << std::endl; }
/** * @file * * @brief benchmark for getenv * * @copyright BSD License (see doc/COPYING or http://www.libelektra.org) * */ #include <keyset.hpp> #include <kdbtimer.hpp> #include <fstream> #include <iostream> #include <dlfcn.h> #include <string.h> extern "C" char **environ; const long long nr_keys = 100; // long long iterations = 100000000000LL; // elitebenchmark lookup long long iterations = 100000000LL; // elitebenchmark // long long iterations = 100LL; // valgrind // not needed in benchmarks: long long iterations1 = iterations / 100; const int benchmarkIterations = 11; // is a good number to not need mean values for median const std::string filename = "check.txt"; const std::string csvfilename = "data.csv"; std::ofstream dump(filename); std::ofstream data(csvfilename); // from libgetenv namespace ckdb{ char *elektraBootstrapGetEnv(const char *name); } // very fast benchmarks without any if: __attribute__((noinline)) void benchmark_nothing() { static Timer t("nothing"); t.start(); t.stop(); std::cout << t; dump << t.name << std::endl; } #define _STRING_ARCH_unaligned 1 /* Return the value of the environment variable NAME. This implementation is tuned a bit in that it assumes no environment variable has an empty name which of course should always be true. We have a special case for one character names so that for the general case we can assume at least two characters which we can access. By doing this we can avoid using the `strncmp' most of the time. */ __attribute__((noinline)) char * libc_getenv (const char *name) { size_t len = strlen (name); char **ep; uint16_t name_start; if (environ == NULL || name[0] == '\0') return NULL; if (name[1] == '\0') { /* The name of the variable consists of only one character. Therefore the first two characters of the environment entry are this character and a '=' character. */ #if __BYTE_ORDER == __LITTLE_ENDIAN || !_STRING_ARCH_unaligned name_start = ('=' << 8) | *(const unsigned char *) name; #else # if __BYTE_ORDER == __BIG_ENDIAN name_start = '=' | ((*(const unsigned char *) name) << 8); # else #error "Funny byte order." # endif #endif for (ep = environ; *ep != NULL; ++ep) { #if _STRING_ARCH_unaligned uint16_t ep_start = *(uint16_t *) *ep; #else uint16_t ep_start = (((unsigned char *) *ep)[0] | (((unsigned char *) *ep)[1] << 8)); #endif if (name_start == ep_start) return &(*ep)[2]; } } else { #if _STRING_ARCH_unaligned name_start = *(const uint16_t *) name; #else name_start = (((const unsigned char *) name)[0] | (((const unsigned char *) name)[1] << 8)); #endif len -= 2; name += 2; for (ep = environ; *ep != NULL; ++ep) { #if _STRING_ARCH_unaligned uint16_t ep_start = *(uint16_t *) *ep; #else uint16_t ep_start = (((unsigned char *) *ep)[0] | (((unsigned char *) *ep)[1] << 8)); #endif if (name_start == ep_start && !strncmp (*ep + 2, name, len) && (*ep)[len + 2] == '=') return &(*ep)[len + 3]; } } return NULL; } __attribute__((noinline)) void benchmark_libc_getenv() { static Timer t("libc getenv"); t.start(); for (long long i=0; i<iterations; ++i) { libc_getenv("HELLO"); __asm__(""); } t.stop(); std::cout << t; dump << t.name << std::endl; } __attribute__((noinline)) void benchmark_dl_libc_getenv() { static Timer t("dl libc getenv"); typedef char *(* gfcn)(const char *); union Sym{void*d; gfcn f;} sym; sym.d = dlsym(RTLD_NEXT, "getenv"); gfcn dl_libc_getenv = sym.f; t.start(); for (long long i=0; i<iterations; ++i) { dl_libc_getenv("HELLO"); __asm__(""); } t.stop(); std::cout << t; dump << t.name << std::endl; } __attribute__((noinline)) void benchmark_bootstrap_getenv() { static Timer t("bootstrap getenv"); t.start(); for (long long i=0; i<iterations; ++i) { ckdb::elektraBootstrapGetEnv("HELLO"); __asm__(""); } t.stop(); std::cout << t; dump << t.name << std::endl; } __attribute__((noinline)) void benchmark_kslookup() { static Timer t("kslookup"); using namespace kdb; // needed for KS_END kdb::KeySet ks( 100, /* *kdb::Key("user/env/override/some", KEY_END), *kdb::Key("user/env/override/a/key", KEY_END), *kdb::Key("user/env/override/b/key", KEY_END), *kdb::Key("user/env/override/c/key", KEY_END), *kdb::Key("user/env/override/d/key", KEY_END), */ KS_END); for (int i=0; i<nr_keys; ++i) { char x[100]; sprintf(x, "user/env/override/hello%d_%d", i, i); ks.append(*kdb::Key(x, KEY_END)); } Key lookupKey ("user/env/override/HELLO", KEY_END); t.start(); for (long long i=0; i<iterations; ++i) { ks.lookup(lookupKey); __asm__(""); } t.stop(); std::cout << t; } #include <unistd.h> #ifdef _WIN32 # include <winsock2.h> #endif void computer_info() { char hostname[1024]; gethostname(hostname, 1023); std::cout << std::endl; std::cout << std::endl; std::cout << "hostname " << hostname << std::endl; #ifdef __GNUC__ std::cout << "gcc: " << __GNUC__ << std::endl; #endif #ifdef __INTEL_COMPILER std::cout << "icc: " << __INTEL_COMPILER << std::endl; #endif #ifdef __clang__ std::cout << "clang: " << __clang__ << std::endl; #endif std::cout << "sizeof(int) " << sizeof(int) << std::endl; std::cout << "sizeof(long) " << sizeof(long) << std::endl; std::cout << "sizeof(long long) " << sizeof(long long) << std::endl; std::cout << "iterations " << iterations << std::endl; std::cout << "filename " << filename << std::endl; std::cout << std::endl; } int main(int argc, char**argv) { computer_info(); clearenv(); for (int i=0; i<nr_keys; ++i) { char x[100]; sprintf(x, "hello%d_%d", i, i); setenv(x, x, 0); } if (argc==2) { iterations = atoll(argv[1]); iterations1 = iterations / 100; } for (int i=0; i<benchmarkIterations; ++i) { std::cout << i << std::endl; benchmark_nothing(); benchmark_libc_getenv(); // benchmark_dl_libc_getenv(); //TODO benchmark_bootstrap_getenv(); benchmark_kslookup(); // benchmark_hashmap(); // benchmark_hashmap_find(); } data << "value,benchmark" << std::endl; }
make nr_keys var+change to 100
getenv: make nr_keys var+change to 100
C++
bsd-3-clause
BernhardDenner/libelektra,mpranj/libelektra,e1528532/libelektra,ElektraInitiative/libelektra,BernhardDenner/libelektra,ElektraInitiative/libelektra,petermax2/libelektra,petermax2/libelektra,petermax2/libelektra,mpranj/libelektra,mpranj/libelektra,petermax2/libelektra,mpranj/libelektra,ElektraInitiative/libelektra,petermax2/libelektra,e1528532/libelektra,ElektraInitiative/libelektra,BernhardDenner/libelektra,e1528532/libelektra,mpranj/libelektra,petermax2/libelektra,BernhardDenner/libelektra,ElektraInitiative/libelektra,mpranj/libelektra,ElektraInitiative/libelektra,mpranj/libelektra,BernhardDenner/libelektra,BernhardDenner/libelektra,BernhardDenner/libelektra,petermax2/libelektra,mpranj/libelektra,e1528532/libelektra,petermax2/libelektra,ElektraInitiative/libelektra,BernhardDenner/libelektra,e1528532/libelektra,mpranj/libelektra,e1528532/libelektra,ElektraInitiative/libelektra,e1528532/libelektra,mpranj/libelektra,mpranj/libelektra,ElektraInitiative/libelektra,ElektraInitiative/libelektra,petermax2/libelektra,e1528532/libelektra,BernhardDenner/libelektra,ElektraInitiative/libelektra
d9eee0cd32d07a773ddea79a9aab6b339592423c
src/main/activemq/util/PrimitiveValueNode.cpp
src/main/activemq/util/PrimitiveValueNode.cpp
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "PrimitiveValueNode.h" #include <activemq/util/PrimitiveList.h> #include <activemq/util/PrimitiveMap.h> #include <decaf/lang/exceptions/NullPointerException.h> #include <decaf/util/StlMap.h> #include <decaf/util/StlList.h> using namespace std; using namespace activemq; using namespace activemq::util; //////////////////////////////////////////////////////////////////////////////// PrimitiveValueNode::PrimitiveValueNode() { valueType = NULL_TYPE; memset( &value, 0, sizeof(value) ); } //////////////////////////////////////////////////////////////////////////////// PrimitiveValueNode::PrimitiveValueNode( bool value ) { this->valueType = NULL_TYPE; this->setBool( value ); } //////////////////////////////////////////////////////////////////////////////// PrimitiveValueNode::PrimitiveValueNode( unsigned char value ) { this->valueType = NULL_TYPE; this->setByte( value ); } //////////////////////////////////////////////////////////////////////////////// PrimitiveValueNode::PrimitiveValueNode( char value ) { this->valueType = NULL_TYPE; this->setChar( value ); } //////////////////////////////////////////////////////////////////////////////// PrimitiveValueNode::PrimitiveValueNode( short value ) { this->valueType = NULL_TYPE; this->setShort( value ); } //////////////////////////////////////////////////////////////////////////////// PrimitiveValueNode::PrimitiveValueNode( int value ) { this->valueType = NULL_TYPE; this->setInt( value ); } //////////////////////////////////////////////////////////////////////////////// PrimitiveValueNode::PrimitiveValueNode( long long value ) { this->valueType = NULL_TYPE; this->setLong( value ); } //////////////////////////////////////////////////////////////////////////////// PrimitiveValueNode::PrimitiveValueNode( float value ) { this->valueType = NULL_TYPE; this->setFloat( value ); } //////////////////////////////////////////////////////////////////////////////// PrimitiveValueNode::PrimitiveValueNode( double value ) { this->valueType = NULL_TYPE; this->setDouble( value ); } //////////////////////////////////////////////////////////////////////////////// PrimitiveValueNode::PrimitiveValueNode( const char* value ) { this->valueType = NULL_TYPE; if( value != NULL ) { this->setString( string( value ) ); } } //////////////////////////////////////////////////////////////////////////////// PrimitiveValueNode::PrimitiveValueNode( const std::string& value ) { this->valueType = NULL_TYPE; this->setString( value ); } //////////////////////////////////////////////////////////////////////////////// PrimitiveValueNode::PrimitiveValueNode( const std::vector<unsigned char>& value ) { this->valueType = NULL_TYPE; this->setByteArray( value ); } //////////////////////////////////////////////////////////////////////////////// PrimitiveValueNode::PrimitiveValueNode( const decaf::util::List<PrimitiveValueNode>& value ) { this->valueType = NULL_TYPE; this->setList( value ); } //////////////////////////////////////////////////////////////////////////////// PrimitiveValueNode::PrimitiveValueNode( const decaf::util::Map<std::string, PrimitiveValueNode>& value ) { this->valueType = NULL_TYPE; this->setMap( value ); } //////////////////////////////////////////////////////////////////////////////// PrimitiveValueNode::PrimitiveValueNode( const PrimitiveValueNode& node ){ valueType = NULL_TYPE; (*this) = node; } //////////////////////////////////////////////////////////////////////////////// PrimitiveValueNode& PrimitiveValueNode::operator =( const PrimitiveValueNode& node ){ clear(); this->setValue( node.getValue(), node.getValueType() ); return *this; } //////////////////////////////////////////////////////////////////////////////// bool PrimitiveValueNode::operator==( const PrimitiveValueNode& node ) const{ if( valueType != node.valueType ) { return false; } if( valueType == BOOLEAN_TYPE && value.boolValue == node.value.boolValue ) { return true; } else if( valueType == BYTE_TYPE && value.byteValue == node.value.byteValue ) { return true; } else if( valueType == CHAR_TYPE && value.charValue == node.value.charValue ) { return true; } else if( valueType == SHORT_TYPE && value.shortValue == node.value.shortValue ) { return true; } else if( valueType == INTEGER_TYPE && value.intValue == node.value.intValue ) { return true; } else if( valueType == LONG_TYPE && value.longValue == node.value.longValue ) { return true; } else if( valueType == DOUBLE_TYPE && value.doubleValue == node.value.doubleValue ) { return true; } else if( valueType == FLOAT_TYPE && value.floatValue == node.value.floatValue ) { return true; } else if( valueType == STRING_TYPE && *value.stringValue == *node.value.stringValue ) { return true; } else if( valueType == BYTE_ARRAY_TYPE && *value.byteArrayValue == *node.value.byteArrayValue ) { return true; } else if( valueType == LIST_TYPE && value.listValue->equals( *node.value.listValue ) ) { return true; } else if( valueType == MAP_TYPE && value.mapValue->equals( *node.value.mapValue ) ) { return true; } return false; } //////////////////////////////////////////////////////////////////////////////// void PrimitiveValueNode::clear(){ if( valueType == STRING_TYPE && value.stringValue != NULL ){ delete value.stringValue; } else if( valueType == BYTE_ARRAY_TYPE && value.byteArrayValue != NULL ){ delete value.byteArrayValue; } else if( valueType == LIST_TYPE && value.listValue != NULL ){ delete value.listValue; } else if( valueType == MAP_TYPE && value.mapValue != NULL ){ delete value.mapValue; } valueType = NULL_TYPE; memset( &value, 0, sizeof(value) ); } //////////////////////////////////////////////////////////////////////////////// void PrimitiveValueNode::setValue( const PrimitiveValue& value, PrimitiveValueTypeEnum valueType ) { if( valueType == BOOLEAN_TYPE ) { this->setBool( value.boolValue ); } else if( valueType == BYTE_TYPE ) { this->setByte( value.byteValue ); } else if( valueType == CHAR_TYPE ) { this->setChar( value.charValue ); } else if( valueType == SHORT_TYPE ) { this->setShort( value.shortValue ); } else if( valueType == INTEGER_TYPE ) { this->setInt( value.intValue ); } else if( valueType == LONG_TYPE ) { this->setLong( value.longValue ); } else if( valueType == DOUBLE_TYPE ) { this->setDouble( value.doubleValue ); } else if( valueType == FLOAT_TYPE ) { this->setFloat( value.floatValue ); } else if( valueType == STRING_TYPE || valueType == BIG_STRING_TYPE ) { this->setString( *value.stringValue ); } else if( valueType == BYTE_ARRAY_TYPE ) { this->setByteArray( *value.byteArrayValue ); } else if( valueType == LIST_TYPE ) { this->setList( *value.listValue ); } else if( valueType == MAP_TYPE ) { this->setMap( *value.mapValue ); } else { this->clear(); } } //////////////////////////////////////////////////////////////////////////////// void PrimitiveValueNode::setBool( bool lvalue ){ clear(); valueType = BOOLEAN_TYPE; value.boolValue = lvalue; } //////////////////////////////////////////////////////////////////////////////// bool PrimitiveValueNode::getBool() const throw( decaf::lang::exceptions::NoSuchElementException ){ if( valueType != BOOLEAN_TYPE ){ throw decaf::lang::exceptions::NoSuchElementException( __FILE__, __LINE__, "PrimitiveValue is not BOOLEAN_TYPE" ); } return value.boolValue; } //////////////////////////////////////////////////////////////////////////////// void PrimitiveValueNode::setByte( unsigned char lvalue ){ clear(); valueType = BYTE_TYPE; value.byteValue = lvalue; } //////////////////////////////////////////////////////////////////////////////// unsigned char PrimitiveValueNode::getByte() const throw( decaf::lang::exceptions::NoSuchElementException){ if( valueType != BYTE_TYPE ){ throw decaf::lang::exceptions::NoSuchElementException( __FILE__, __LINE__, "PrimitiveValue is not BYTE_TYPE" ); } return value.byteValue; } //////////////////////////////////////////////////////////////////////////////// void PrimitiveValueNode::setChar( char lvalue ){ clear(); valueType = CHAR_TYPE; value.charValue = lvalue; } //////////////////////////////////////////////////////////////////////////////// char PrimitiveValueNode::getChar() const throw(decaf::lang::exceptions::NoSuchElementException){ if( valueType != CHAR_TYPE ){ throw decaf::lang::exceptions::NoSuchElementException( __FILE__, __LINE__, "PrimitiveValue is not CHAR_TYPE" ); } return value.charValue; } //////////////////////////////////////////////////////////////////////////////// void PrimitiveValueNode::setShort( short lvalue ){ clear(); valueType = SHORT_TYPE; value.shortValue = lvalue; } //////////////////////////////////////////////////////////////////////////////// short PrimitiveValueNode::getShort() const throw(decaf::lang::exceptions::NoSuchElementException){ if( valueType != SHORT_TYPE ){ throw decaf::lang::exceptions::NoSuchElementException( __FILE__, __LINE__, "PrimitiveValue is not SHORT_TYPE" ); } return value.shortValue; } //////////////////////////////////////////////////////////////////////////////// void PrimitiveValueNode::setInt( int lvalue ){ clear(); valueType = INTEGER_TYPE; value.intValue = lvalue; } //////////////////////////////////////////////////////////////////////////////// int PrimitiveValueNode::getInt() const throw(decaf::lang::exceptions::NoSuchElementException){ if( valueType != INTEGER_TYPE ){ throw decaf::lang::exceptions::NoSuchElementException( __FILE__, __LINE__, "PrimitiveValue is not INTEGER_TYPE" ); } return value.intValue; } //////////////////////////////////////////////////////////////////////////////// void PrimitiveValueNode::setLong( long long lvalue ){ clear(); valueType = LONG_TYPE; value.longValue = lvalue; } //////////////////////////////////////////////////////////////////////////////// long long PrimitiveValueNode::getLong() const throw(decaf::lang::exceptions::NoSuchElementException){ if( valueType != LONG_TYPE ){ throw decaf::lang::exceptions::NoSuchElementException( __FILE__, __LINE__, "PrimitiveValue is not LONG_TYPE" ); } return value.longValue; } //////////////////////////////////////////////////////////////////////////////// void PrimitiveValueNode::setDouble( double lvalue ){ clear(); valueType = DOUBLE_TYPE; value.doubleValue = lvalue; } //////////////////////////////////////////////////////////////////////////////// double PrimitiveValueNode::getDouble() const throw(decaf::lang::exceptions::NoSuchElementException){ if( valueType != DOUBLE_TYPE ){ throw decaf::lang::exceptions::NoSuchElementException( __FILE__, __LINE__, "PrimitiveValue is not DOUBLE_TYPE" ); } return value.doubleValue; } //////////////////////////////////////////////////////////////////////////////// void PrimitiveValueNode::setFloat( float lvalue ){ clear(); valueType = FLOAT_TYPE; value.floatValue = lvalue; } //////////////////////////////////////////////////////////////////////////////// float PrimitiveValueNode::getFloat() const throw(decaf::lang::exceptions::NoSuchElementException){ if( valueType != FLOAT_TYPE ){ throw decaf::lang::exceptions::NoSuchElementException( __FILE__, __LINE__, "PrimitiveValue is not FLOAT_TYPE" ); } return value.floatValue; } //////////////////////////////////////////////////////////////////////////////// void PrimitiveValueNode::setString( const std::string& lvalue ){ clear(); valueType = STRING_TYPE; value.stringValue = new std::string( lvalue ); } //////////////////////////////////////////////////////////////////////////////// std::string PrimitiveValueNode::getString() const throw(decaf::lang::exceptions::NoSuchElementException){ if( valueType != STRING_TYPE ){ throw decaf::lang::exceptions::NoSuchElementException( __FILE__, __LINE__, "PrimitiveValue is not STRING_TYPE" ); } if( value.stringValue == NULL ){ return std::string(); } return *value.stringValue; } //////////////////////////////////////////////////////////////////////////////// void PrimitiveValueNode::setByteArray( const std::vector<unsigned char>& lvalue ){ clear(); valueType = BYTE_ARRAY_TYPE; value.byteArrayValue = new std::vector<unsigned char>( lvalue ); } //////////////////////////////////////////////////////////////////////////////// std::vector<unsigned char> PrimitiveValueNode::getByteArray() const throw( decaf::lang::exceptions::NoSuchElementException ) { if( valueType != BYTE_ARRAY_TYPE ){ throw decaf::lang::exceptions::NoSuchElementException( __FILE__, __LINE__, "PrimitiveValue is not BYTE_ARRAY_TYPE" ); } if( value.byteArrayValue == NULL ){ return std::vector<unsigned char>(); } return *value.byteArrayValue; } //////////////////////////////////////////////////////////////////////////////// void PrimitiveValueNode::setList( const decaf::util::List<PrimitiveValueNode>& lvalue ){ clear(); valueType = LIST_TYPE; value.listValue = new decaf::util::StlList<PrimitiveValueNode>( lvalue ); } //////////////////////////////////////////////////////////////////////////////// const decaf::util::List<PrimitiveValueNode>& PrimitiveValueNode::getList() const throw( decaf::lang::exceptions::NoSuchElementException ) { if( valueType != LIST_TYPE ){ throw decaf::lang::exceptions::NoSuchElementException( __FILE__, __LINE__, "PrimitiveValue is not LIST_TYPE" ); } if( value.listValue == NULL ){ throw decaf::lang::exceptions::NullPointerException( __FILE__, __LINE__, "PrimitiveValue is not set but an element was placed in the Map" ); } return *value.listValue; } //////////////////////////////////////////////////////////////////////////////// void PrimitiveValueNode::setMap( const decaf::util::Map<std::string, PrimitiveValueNode>& lvalue ){ clear(); valueType = MAP_TYPE; value.mapValue = new decaf::util::StlMap<std::string, PrimitiveValueNode>( lvalue ); } //////////////////////////////////////////////////////////////////////////////// const decaf::util::Map<std::string, PrimitiveValueNode>& PrimitiveValueNode::getMap() const throw( decaf::lang::exceptions::NoSuchElementException ) { if( valueType != MAP_TYPE ){ throw decaf::lang::exceptions::NoSuchElementException( __FILE__, __LINE__, "PrimitiveValue is not MAP_TYPE" ); } if( value.mapValue == NULL ){ throw decaf::lang::exceptions::NullPointerException( __FILE__, __LINE__, "PrimitiveValue is not set but an element was placed in the Map" ); } return *value.mapValue; } //////////////////////////////////////////////////////////////////////////////// std::string PrimitiveValueNode::toString() const { std::ostringstream stream; if( valueType == BOOLEAN_TYPE ) { stream << std::boolalpha << value.boolValue; } else if( valueType == BYTE_TYPE ) { stream << value.byteValue; } else if( valueType == CHAR_TYPE ) { stream << value.charValue; } else if( valueType == SHORT_TYPE ) { stream << value.shortValue; } else if( valueType == INTEGER_TYPE ) { stream << value.intValue; } else if( valueType == LONG_TYPE ) { stream << value.longValue; } else if( valueType == DOUBLE_TYPE ) { stream << value.doubleValue; } else if( valueType == FLOAT_TYPE ) { stream << value.floatValue; } else if( valueType == STRING_TYPE || valueType == BIG_STRING_TYPE ) { stream << *value.stringValue; } else if( valueType == BYTE_ARRAY_TYPE ) { std::vector<unsigned char>::const_iterator iter = value.byteArrayValue->begin(); for( ; iter != value.byteArrayValue->end(); ++iter ) { stream << '[' << (int)(*iter) << ']'; } } else if( valueType == LIST_TYPE ) { stream << PrimitiveList( *value.listValue ).toString(); } else if( valueType == MAP_TYPE ) { stream << PrimitiveMap( *value.mapValue ).toString(); } return stream.str(); }
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "PrimitiveValueNode.h" #include <activemq/util/PrimitiveList.h> #include <activemq/util/PrimitiveMap.h> #include <decaf/lang/exceptions/NullPointerException.h> #include <decaf/util/StlMap.h> #include <decaf/util/StlList.h> using namespace std; using namespace activemq; using namespace activemq::util; //////////////////////////////////////////////////////////////////////////////// PrimitiveValueNode::PrimitiveValueNode() { valueType = NULL_TYPE; memset( &value, 0, sizeof(value) ); } //////////////////////////////////////////////////////////////////////////////// PrimitiveValueNode::PrimitiveValueNode( bool value ) { this->valueType = NULL_TYPE; this->setBool( value ); } //////////////////////////////////////////////////////////////////////////////// PrimitiveValueNode::PrimitiveValueNode( unsigned char value ) { this->valueType = NULL_TYPE; this->setByte( value ); } //////////////////////////////////////////////////////////////////////////////// PrimitiveValueNode::PrimitiveValueNode( char value ) { this->valueType = NULL_TYPE; this->setChar( value ); } //////////////////////////////////////////////////////////////////////////////// PrimitiveValueNode::PrimitiveValueNode( short value ) { this->valueType = NULL_TYPE; this->setShort( value ); } //////////////////////////////////////////////////////////////////////////////// PrimitiveValueNode::PrimitiveValueNode( int value ) { this->valueType = NULL_TYPE; this->setInt( value ); } //////////////////////////////////////////////////////////////////////////////// PrimitiveValueNode::PrimitiveValueNode( long long value ) { this->valueType = NULL_TYPE; this->setLong( value ); } //////////////////////////////////////////////////////////////////////////////// PrimitiveValueNode::PrimitiveValueNode( float value ) { this->valueType = NULL_TYPE; this->setFloat( value ); } //////////////////////////////////////////////////////////////////////////////// PrimitiveValueNode::PrimitiveValueNode( double value ) { this->valueType = NULL_TYPE; this->setDouble( value ); } //////////////////////////////////////////////////////////////////////////////// PrimitiveValueNode::PrimitiveValueNode( const char* value ) { this->valueType = NULL_TYPE; if( value != NULL ) { this->setString( string( value ) ); } } //////////////////////////////////////////////////////////////////////////////// PrimitiveValueNode::PrimitiveValueNode( const std::string& value ) { this->valueType = NULL_TYPE; this->setString( value ); } //////////////////////////////////////////////////////////////////////////////// PrimitiveValueNode::PrimitiveValueNode( const std::vector<unsigned char>& value ) { this->valueType = NULL_TYPE; this->setByteArray( value ); } //////////////////////////////////////////////////////////////////////////////// PrimitiveValueNode::PrimitiveValueNode( const decaf::util::List<PrimitiveValueNode>& value ) { this->valueType = NULL_TYPE; this->setList( value ); } //////////////////////////////////////////////////////////////////////////////// PrimitiveValueNode::PrimitiveValueNode( const decaf::util::Map<std::string, PrimitiveValueNode>& value ) { this->valueType = NULL_TYPE; this->setMap( value ); } //////////////////////////////////////////////////////////////////////////////// PrimitiveValueNode::PrimitiveValueNode( const PrimitiveValueNode& node ){ valueType = NULL_TYPE; (*this) = node; } //////////////////////////////////////////////////////////////////////////////// PrimitiveValueNode& PrimitiveValueNode::operator =( const PrimitiveValueNode& node ){ clear(); this->setValue( node.getValue(), node.getValueType() ); return *this; } //////////////////////////////////////////////////////////////////////////////// bool PrimitiveValueNode::operator==( const PrimitiveValueNode& node ) const{ if( valueType != node.valueType ) { return false; } if( valueType == BOOLEAN_TYPE && value.boolValue == node.value.boolValue ) { return true; } else if( valueType == BYTE_TYPE && value.byteValue == node.value.byteValue ) { return true; } else if( valueType == CHAR_TYPE && value.charValue == node.value.charValue ) { return true; } else if( valueType == SHORT_TYPE && value.shortValue == node.value.shortValue ) { return true; } else if( valueType == INTEGER_TYPE && value.intValue == node.value.intValue ) { return true; } else if( valueType == LONG_TYPE && value.longValue == node.value.longValue ) { return true; } else if( valueType == DOUBLE_TYPE && value.doubleValue == node.value.doubleValue ) { return true; } else if( valueType == FLOAT_TYPE && value.floatValue == node.value.floatValue ) { return true; } else if( valueType == STRING_TYPE && *value.stringValue == *node.value.stringValue ) { return true; } else if( valueType == BYTE_ARRAY_TYPE && *value.byteArrayValue == *node.value.byteArrayValue ) { return true; } else if( valueType == LIST_TYPE && value.listValue->equals( *node.value.listValue ) ) { return true; } else if( valueType == MAP_TYPE && value.mapValue->equals( *node.value.mapValue ) ) { return true; } return false; } //////////////////////////////////////////////////////////////////////////////// void PrimitiveValueNode::clear(){ if( valueType == STRING_TYPE && value.stringValue != NULL ){ delete value.stringValue; } else if( valueType == BYTE_ARRAY_TYPE && value.byteArrayValue != NULL ){ delete value.byteArrayValue; } else if( valueType == LIST_TYPE && value.listValue != NULL ){ delete value.listValue; } else if( valueType == MAP_TYPE && value.mapValue != NULL ){ delete value.mapValue; } valueType = NULL_TYPE; memset( &value, 0, sizeof(value) ); } //////////////////////////////////////////////////////////////////////////////// void PrimitiveValueNode::setValue( const PrimitiveValue& value, PrimitiveValueTypeEnum valueType ) { if( valueType == BOOLEAN_TYPE ) { this->setBool( value.boolValue ); } else if( valueType == BYTE_TYPE ) { this->setByte( value.byteValue ); } else if( valueType == CHAR_TYPE ) { this->setChar( value.charValue ); } else if( valueType == SHORT_TYPE ) { this->setShort( value.shortValue ); } else if( valueType == INTEGER_TYPE ) { this->setInt( value.intValue ); } else if( valueType == LONG_TYPE ) { this->setLong( value.longValue ); } else if( valueType == DOUBLE_TYPE ) { this->setDouble( value.doubleValue ); } else if( valueType == FLOAT_TYPE ) { this->setFloat( value.floatValue ); } else if( valueType == STRING_TYPE || valueType == BIG_STRING_TYPE ) { this->setString( *value.stringValue ); } else if( valueType == BYTE_ARRAY_TYPE ) { this->setByteArray( *value.byteArrayValue ); } else if( valueType == LIST_TYPE ) { this->setList( *value.listValue ); } else if( valueType == MAP_TYPE ) { this->setMap( *value.mapValue ); } else { this->clear(); } } //////////////////////////////////////////////////////////////////////////////// void PrimitiveValueNode::setBool( bool lvalue ){ clear(); valueType = BOOLEAN_TYPE; value.boolValue = lvalue; } //////////////////////////////////////////////////////////////////////////////// bool PrimitiveValueNode::getBool() const throw( decaf::lang::exceptions::NoSuchElementException ){ if( valueType != BOOLEAN_TYPE ){ throw decaf::lang::exceptions::NoSuchElementException( __FILE__, __LINE__, "PrimitiveValue is not BOOLEAN_TYPE" ); } return value.boolValue; } //////////////////////////////////////////////////////////////////////////////// void PrimitiveValueNode::setByte( unsigned char lvalue ){ clear(); valueType = BYTE_TYPE; value.byteValue = lvalue; } //////////////////////////////////////////////////////////////////////////////// unsigned char PrimitiveValueNode::getByte() const throw( decaf::lang::exceptions::NoSuchElementException){ if( valueType != BYTE_TYPE ){ throw decaf::lang::exceptions::NoSuchElementException( __FILE__, __LINE__, "PrimitiveValue is not BYTE_TYPE" ); } return value.byteValue; } //////////////////////////////////////////////////////////////////////////////// void PrimitiveValueNode::setChar( char lvalue ){ clear(); valueType = CHAR_TYPE; value.charValue = lvalue; } //////////////////////////////////////////////////////////////////////////////// char PrimitiveValueNode::getChar() const throw(decaf::lang::exceptions::NoSuchElementException){ if( valueType != CHAR_TYPE ){ throw decaf::lang::exceptions::NoSuchElementException( __FILE__, __LINE__, "PrimitiveValue is not CHAR_TYPE" ); } return value.charValue; } //////////////////////////////////////////////////////////////////////////////// void PrimitiveValueNode::setShort( short lvalue ){ clear(); valueType = SHORT_TYPE; value.shortValue = lvalue; } //////////////////////////////////////////////////////////////////////////////// short PrimitiveValueNode::getShort() const throw(decaf::lang::exceptions::NoSuchElementException){ if( valueType != SHORT_TYPE ){ throw decaf::lang::exceptions::NoSuchElementException( __FILE__, __LINE__, "PrimitiveValue is not SHORT_TYPE" ); } return value.shortValue; } //////////////////////////////////////////////////////////////////////////////// void PrimitiveValueNode::setInt( int lvalue ){ clear(); valueType = INTEGER_TYPE; value.intValue = lvalue; } //////////////////////////////////////////////////////////////////////////////// int PrimitiveValueNode::getInt() const throw(decaf::lang::exceptions::NoSuchElementException){ if( valueType != INTEGER_TYPE ){ throw decaf::lang::exceptions::NoSuchElementException( __FILE__, __LINE__, "PrimitiveValue is not INTEGER_TYPE" ); } return value.intValue; } //////////////////////////////////////////////////////////////////////////////// void PrimitiveValueNode::setLong( long long lvalue ){ clear(); valueType = LONG_TYPE; value.longValue = lvalue; } //////////////////////////////////////////////////////////////////////////////// long long PrimitiveValueNode::getLong() const throw(decaf::lang::exceptions::NoSuchElementException){ if( valueType != LONG_TYPE ){ throw decaf::lang::exceptions::NoSuchElementException( __FILE__, __LINE__, "PrimitiveValue is not LONG_TYPE" ); } return value.longValue; } //////////////////////////////////////////////////////////////////////////////// void PrimitiveValueNode::setDouble( double lvalue ){ clear(); valueType = DOUBLE_TYPE; value.doubleValue = lvalue; } //////////////////////////////////////////////////////////////////////////////// double PrimitiveValueNode::getDouble() const throw(decaf::lang::exceptions::NoSuchElementException){ if( valueType != DOUBLE_TYPE ){ throw decaf::lang::exceptions::NoSuchElementException( __FILE__, __LINE__, "PrimitiveValue is not DOUBLE_TYPE" ); } return value.doubleValue; } //////////////////////////////////////////////////////////////////////////////// void PrimitiveValueNode::setFloat( float lvalue ){ clear(); valueType = FLOAT_TYPE; value.floatValue = lvalue; } //////////////////////////////////////////////////////////////////////////////// float PrimitiveValueNode::getFloat() const throw(decaf::lang::exceptions::NoSuchElementException){ if( valueType != FLOAT_TYPE ){ throw decaf::lang::exceptions::NoSuchElementException( __FILE__, __LINE__, "PrimitiveValue is not FLOAT_TYPE" ); } return value.floatValue; } //////////////////////////////////////////////////////////////////////////////// void PrimitiveValueNode::setString( const std::string& lvalue ){ clear(); valueType = STRING_TYPE; value.stringValue = new std::string( lvalue ); } //////////////////////////////////////////////////////////////////////////////// std::string PrimitiveValueNode::getString() const throw(decaf::lang::exceptions::NoSuchElementException){ if( valueType != STRING_TYPE ){ throw decaf::lang::exceptions::NoSuchElementException( __FILE__, __LINE__, "PrimitiveValue is not STRING_TYPE" ); } if( value.stringValue == NULL ){ return std::string(); } return *value.stringValue; } //////////////////////////////////////////////////////////////////////////////// void PrimitiveValueNode::setByteArray( const std::vector<unsigned char>& lvalue ){ clear(); valueType = BYTE_ARRAY_TYPE; value.byteArrayValue = new std::vector<unsigned char>( lvalue ); } //////////////////////////////////////////////////////////////////////////////// std::vector<unsigned char> PrimitiveValueNode::getByteArray() const throw( decaf::lang::exceptions::NoSuchElementException ) { if( valueType != BYTE_ARRAY_TYPE ){ throw decaf::lang::exceptions::NoSuchElementException( __FILE__, __LINE__, "PrimitiveValue is not BYTE_ARRAY_TYPE" ); } if( value.byteArrayValue == NULL ){ return std::vector<unsigned char>(); } return *value.byteArrayValue; } //////////////////////////////////////////////////////////////////////////////// void PrimitiveValueNode::setList( const decaf::util::List<PrimitiveValueNode>& lvalue ){ clear(); valueType = LIST_TYPE; value.listValue = new decaf::util::StlList<PrimitiveValueNode>(); value.listValue->copy( lvalue ); } //////////////////////////////////////////////////////////////////////////////// const decaf::util::List<PrimitiveValueNode>& PrimitiveValueNode::getList() const throw( decaf::lang::exceptions::NoSuchElementException ) { if( valueType != LIST_TYPE ){ throw decaf::lang::exceptions::NoSuchElementException( __FILE__, __LINE__, "PrimitiveValue is not LIST_TYPE" ); } if( value.listValue == NULL ){ throw decaf::lang::exceptions::NullPointerException( __FILE__, __LINE__, "PrimitiveValue is not set but an element was placed in the Map" ); } return *value.listValue; } //////////////////////////////////////////////////////////////////////////////// void PrimitiveValueNode::setMap( const decaf::util::Map<std::string, PrimitiveValueNode>& lvalue ){ clear(); valueType = MAP_TYPE; value.mapValue = new decaf::util::StlMap<std::string, PrimitiveValueNode>( lvalue ); } //////////////////////////////////////////////////////////////////////////////// const decaf::util::Map<std::string, PrimitiveValueNode>& PrimitiveValueNode::getMap() const throw( decaf::lang::exceptions::NoSuchElementException ) { if( valueType != MAP_TYPE ){ throw decaf::lang::exceptions::NoSuchElementException( __FILE__, __LINE__, "PrimitiveValue is not MAP_TYPE" ); } if( value.mapValue == NULL ){ throw decaf::lang::exceptions::NullPointerException( __FILE__, __LINE__, "PrimitiveValue is not set but an element was placed in the Map" ); } return *value.mapValue; } //////////////////////////////////////////////////////////////////////////////// std::string PrimitiveValueNode::toString() const { std::ostringstream stream; if( valueType == BOOLEAN_TYPE ) { stream << std::boolalpha << value.boolValue; } else if( valueType == BYTE_TYPE ) { stream << value.byteValue; } else if( valueType == CHAR_TYPE ) { stream << value.charValue; } else if( valueType == SHORT_TYPE ) { stream << value.shortValue; } else if( valueType == INTEGER_TYPE ) { stream << value.intValue; } else if( valueType == LONG_TYPE ) { stream << value.longValue; } else if( valueType == DOUBLE_TYPE ) { stream << value.doubleValue; } else if( valueType == FLOAT_TYPE ) { stream << value.floatValue; } else if( valueType == STRING_TYPE || valueType == BIG_STRING_TYPE ) { stream << *value.stringValue; } else if( valueType == BYTE_ARRAY_TYPE ) { std::vector<unsigned char>::const_iterator iter = value.byteArrayValue->begin(); for( ; iter != value.byteArrayValue->end(); ++iter ) { stream << '[' << (int)(*iter) << ']'; } } else if( valueType == LIST_TYPE ) { stream << PrimitiveList( *value.listValue ).toString(); } else if( valueType == MAP_TYPE ) { stream << PrimitiveMap( *value.mapValue ).toString(); } return stream.str(); }
Fix segfault in unit tests
Fix segfault in unit tests git-svn-id: 0fb8a5a922afe2085ae9a967a0cf0864fe09ecff@749820 13f79535-47bb-0310-9956-ffa450edef68
C++
apache-2.0
apache/activemq-cpp,apache/activemq-cpp,apache/activemq-cpp,apache/activemq-cpp
eebbd9dc5c80e461dbfe024a02829b3a7a416c37
utils/image.cc
utils/image.cc
#include "utils.hpp" #include "image.hpp" #include <cerrno> #include <cstdio> #include <cassert> const Color Image::red(1, 0, 0); const Color Image::green(0, 1, 0); const Color Image::blue(0, 0, 1); const Color Image::black(0, 0, 0); const Color Image::white(1, 1, 1); const Color somecolors[] = { Color(0.0, 0.6, 0.0), // Dark green Color(0.0, 0.0, 0.6), // Dark blue Color(0.5, 0.0, 0.5), // Purple Color(1.0, 0.54, 0.0), // Dark orange Color(0.28, 0.24, 0.55), // Slate blue Color(0.42, 0.56, 0.14), // Olive drab Color(0.25, 0.80, 0.80), // "Skyish" Color(0.80, 0.80, 0.20), // Mustard }; const unsigned int Nsomecolors = sizeof(somecolors) / sizeof(somecolors[0]); Image::Image(unsigned int width, unsigned int height, const char *t) : w(width), h(height), title(t), data(NULL) { } Image::~Image(void) { while (!comps.empty()) { delete comps.back(); comps.pop_back(); } if (data) delete[] data; } void Image::save(const char *path, bool usletter, int marginpt) const { FILE *f = fopen(path, "w"); if (!f) fatalx(errno, "Failed to open %s for writing\n", path); output(f, usletter, marginpt); fclose(f); } void Image::output(FILE *out, bool usletter, int marginpt) const { if (marginpt < 0) marginpt = usletter ? 72/2 : 0; /* 72/2 pt == ½ in */ if (usletter) outputhdr_usletter(out, marginpt); else outputhdr(out, marginpt); if (data) outputdata(out); for (unsigned int i = 0; i < comps.size(); i++) { fputc('\n', out); comps[i]->write(out); } fprintf(out, "showpage\n"); } enum { Widthpt = 612, /* pts == 8.5 in */ Heightpt = 792, /* pts = 11 in */ }; void Image::outputhdr_usletter(FILE *out, unsigned int marginpt) const { fprintf(out, "%%!PS-Adobe-3.0\n"); fprintf(out, "%%%%Creator: UNH-AI C++ Search Framework\n"); fprintf(out, "%%%%Title: %s\n", title.c_str()); fprintf(out, "%%%%BoundingBox: 0 0 %u %u\n", Widthpt, Heightpt); fprintf(out, "%%%%EndComments\n"); double maxw = Widthpt - marginpt * 2, maxh = Heightpt - marginpt * 2; double scalex = maxw / w, scaley = maxh / h; double transx = marginpt, transy = (Heightpt - h * scalex) / 2; double scale = scalex; if (scaley < scalex) { scale = scaley; transx = (Widthpt - w * scaley) / 2; } fprintf(out, "%g %g translate\n", transx, transy); fprintf(out, "%g %g scale\n", scale, scale); } void Image::outputhdr(FILE *out, unsigned int marginpt) const { fprintf(out, "%%!PS-Adobe-3.0\n"); fprintf(out, "%%%%Creator: UNH-AI C++ Search Framework\n"); fprintf(out, "%%%%Title: %s\n", title.c_str()); fprintf(out, "%%%%BoundingBox: 0 0 %u %u\n", w + 2 * marginpt, h + 2 * marginpt); fprintf(out, "%%%%EndComments\n"); fprintf(out, "%u %u translate\n", marginpt, marginpt); } void Image::outputdata(FILE *out) const { fprintf(out, "\n%% Image data\n"); fprintf(out, "gsave\n"); fprintf(out, "%u %u scale %% scale pixels to points\n", w, h); fprintf(out, "%u %u 8 [%u 0 0 %u 0 0] ", w, h, w, h); fprintf(out, "%% width height colordepth transform\n"); fprintf(out, "/datasource currentfile "); fprintf(out, "/ASCII85Decode filter /RunLengthDecode filter def\n"); fprintf(out, "/datastring %u string def ", w * 3); fprintf(out, "%% %u = width * color components\n", w * 3); fprintf(out, "{datasource datastring readstring pop}\n"); fprintf(out, "false %% false == single data source (rgb)\n"); fprintf(out, "3 %% number of color components\n"); fprintf(out, "colorimage\n"); std::string encoded; encodedata(encoded); fprintf(out, "%s\n", encoded.c_str()); fprintf(out, "grestore\n"); } void Image::encodedata(std::string &dst) const { std::string cs; for (unsigned int i = 0; i < w * h; i++) { cs.push_back(data[i].getred255()); cs.push_back(data[i].getgreen255()); cs.push_back(data[i].getblue255()); } std::string rlenc; runlenenc(rlenc, cs); ascii85enc(dst, rlenc); dst.push_back('~'); dst.push_back('>'); } Image::Path::~Path(void) { while (!segs.empty()) { delete segs.back(); segs.pop_back(); } } void Image::Path::write(FILE *out) const { fprintf(out, "%% Path\n"); fprintf(out, "newpath\n"); for (unsigned int i = 0; i < segs.size(); i++) segs[i]->write(out); if (_closepath) fprintf(out, "closepath\n"); if (!_fill) fprintf(out, "stroke\n"); else fprintf(out, "fill\n"); } void Image::Path::LineJoin::write(FILE *out) const { fprintf(out, "%d setlinejoin\n", type); } void Image::Path::MoveTo::write(FILE *out) const { fprintf(out, "%g %g moveto\n", x, y); } Image::Path::Loc Image::Path::MoveTo::move(Loc p) const { return Loc(std::pair<double,double>(x, y)); } void Image::Path::LineTo::write(FILE *out) const { fprintf(out, "%g %g lineto\n", x, y); } Image::Path::Loc Image::Path::LineTo::move(Loc p) const { return Loc(std::pair<double,double>(x, y)); } void Image::Path::SetLineWidth::write(FILE *out) const { fprintf(out, "%g setlinewidth\n", w); } void Image::Path::SetColor::write(FILE *out) const { fprintf(out, "%g %g %g setrgbcolor\n", c.getred(), c.getgreen(), c.getblue()); } void Image::Path::Arc::write(FILE *out) const { const char *fun = "arc"; if (dt < 0) fun = "arcn"; fprintf(out, "%g %g %g %g %g %s\n", x, y, r, t, t + dt, fun); } Image::Path::Loc Image::Path::Arc::move(Loc p) const { double x1 = x + r * cos((t + dt) * M_PI / 180); double y1 = y + r * sin((t + dt) * M_PI / 180); return Loc(std::pair<double,double>(x1, y1)); } static bool dbleq(double a, double b) { static const double Epsilon = 0.01; return fabs(a - b) < Epsilon; } void Image::Path::line(double x0, double y0, double x1, double y1) { if (!cur || !dbleq(cur->first, x0) || !dbleq(cur->second, y0)) addseg(new MoveTo(x0, y0)); addseg(new LineTo(x1, y1)); } void Image::Path::nauticalcurve(double xc, double yc, double r, double t, double dt) { NauticalArc *a = new NauticalArc(xc, yc, r, t, dt); double x0 = xc + a->r * cos(a->t * M_PI / 180); double y0 = yc + a->r * sin(a->t * M_PI / 180); if (!cur || !dbleq(cur->first, x0) || !dbleq(cur->second, y0)) addseg(new MoveTo(x0, y0)); addseg(a); } void Image::Path::curve(double xc, double yc, double r, double t, double dt) { Arc *a = new Arc(xc, yc, r, t, dt); double x0 = xc + a->r * cos(a->t * M_PI / 180); double y0 = yc + a->r * sin(a->t * M_PI / 180); if (!cur || !dbleq(cur->first, x0) || !dbleq(cur->second, y0)) addseg(new MoveTo(x0, y0)); addseg(a); } void Image::Text::write(FILE *out) const { fprintf(out, "%% Text\n"); fprintf(out, "/%s findfont %g scalefont setfont\n", font.c_str(), sz); fprintf(out, "%u %u moveto\n", x, y); fprintf(out, "%g %g %g setrgbcolor\n", c.getred(), c.getgreen(), c.getblue()); fprintf(out, "(%s) ", text.c_str()); switch (pos) { case Left: fprintf(out, "show\n"); break; case Right: fprintf(out, "dup stringwidth pop neg 0 rmoveto show\n"); break; case Centered: fprintf(out, "dup stringwidth pop 2 div neg 0 rmoveto show\n"); break; default: fatal("Unknown text position: %d\n", pos); } } void Image::Triangle::write(FILE *out) const { double wrad = w * M_PI / 180; double rotrad = rot * M_PI / 180; double side = ht / cos(wrad / 2); double xtop = ht / 2; double xbot = -ht / 2; double y1 = side * sin(wrad / 2); double y2 = -side * sin(wrad / 2); double x0r = xtop * cos(rotrad); double y0r = xtop * sin(rotrad); double x1r = xbot * cos(rotrad) - y1 * sin(rotrad); double y1r = xbot * sin(rotrad) + y1 * cos(rotrad); double x2r = xbot * cos(rotrad) - y2 * sin(rotrad); double y2r = xbot * sin(rotrad) + y2 * cos(rotrad); fprintf(out, "%% Triangle\n"); fprintf(out, "newpath\n"); fprintf(out, "%g %g %g setrgbcolor\n", c.getred(), c.getgreen(), c.getblue()); if (linewidth >= 0) fprintf(out, "%g setlinewidth\n", linewidth); else fprintf(out, "0.1 setlinewidth\n"); fprintf(out, "%g %g moveto\n", x0r + x, y0r + y); fprintf(out, "%g %g lineto\n", x1r + x, y1r + y); fprintf(out, "%g %g lineto\n", x2r + x, y2r + y); fprintf(out, "closepath\n"); if (linewidth < 0) fprintf(out, "fill\n"); else fprintf(out, "stroke\n"); } void Image::Circle::write(FILE *out) const { fprintf(out, "%% Circle\n"); const char *finish = "stroke"; if (lwidth <= 0) { finish = "fill"; fprintf(out, "0.1 setlinewidth\n"); } else { fprintf(out, "%g setlinewidth\n", lwidth); } fprintf(out, "%g %g %g setrgbcolor\n", c.getred(), c.getgreen(), c.getblue()); fprintf(out, "newpath %g %g %g 0 360 arc %s\n", x, y, r, finish); } void Image::Rect::write(FILE *out) const { fprintf(out, "%% Rect\n"); const char *finish = "stroke"; if (lwidth <= 0) { finish = "fill"; fprintf(out, "0.1 setlinewidth\n"); } else { fprintf(out, "%g setlinewidth\n", lwidth); } fprintf(out, "%g %g %g setrgbcolor\n", c.getred(), c.getgreen(), c.getblue()); fputs("0 setlinejoin\n", out); fputs("newpath\n", out); fprintf(out, "%g %g moveto\n", x, y); fprintf(out, "%g %g lineto\n", x + w, y); fprintf(out, "%g %g lineto\n", x + w, y + h); fprintf(out, "%g %g lineto\n", x, y + h); fprintf(out, "closepath\n%s\n", finish); }
#include "utils.hpp" #include "image.hpp" #include <cerrno> #include <cstdio> #include <cassert> const Color Image::red(1, 0, 0); const Color Image::green(0, 1, 0); const Color Image::blue(0, 0, 1); const Color Image::black(0, 0, 0); const Color Image::white(1, 1, 1); const Color somecolors[] = { Color(0.0, 0.6, 0.0), // Dark green Color(0.0, 0.0, 0.6), // Dark blue Color(0.5, 0.0, 0.5), // Purple Color(1.0, 0.54, 0.0), // Dark orange Color(0.28, 0.24, 0.55), // Slate blue Color(0.42, 0.56, 0.14), // Olive drab Color(0.25, 0.80, 0.80), // "Skyish" Color(0.80, 0.80, 0.20), // Mustard }; const unsigned int Nsomecolors = sizeof(somecolors) / sizeof(somecolors[0]); Image::Image(unsigned int width, unsigned int height, const char *t) : w(width), h(height), title(t), data(NULL) { } Image::~Image(void) { while (!comps.empty()) { delete comps.back(); comps.pop_back(); } if (data) delete[] data; } void Image::save(const char *path, bool usletter, int marginpt) const { FILE *f = fopen(path, "w"); if (!f) fatalx(errno, "Failed to open %s for writing\n", path); output(f, usletter, marginpt); fclose(f); } void Image::output(FILE *out, bool usletter, int marginpt) const { if (marginpt < 0) marginpt = usletter ? 72/2 : 0; /* 72/2 pt == ½ in */ if (usletter) outputhdr_usletter(out, marginpt); else outputhdr(out, marginpt); if (data) outputdata(out); for (unsigned int i = 0; i < comps.size(); i++) { fputc('\n', out); comps[i]->write(out); } fprintf(out, "showpage\n"); } enum { Widthpt = 612, /* pts == 8.5 in */ Heightpt = 792, /* pts = 11 in */ }; void Image::outputhdr_usletter(FILE *out, unsigned int marginpt) const { fprintf(out, "%%!PS-Adobe-3.0\n"); fprintf(out, "%%%%Creator: UNH-AI C++ Search Framework\n"); fprintf(out, "%%%%Title: %s\n", title.c_str()); fprintf(out, "%%%%BoundingBox: 0 0 %u %u\n", Widthpt, Heightpt); fprintf(out, "%%%%EndComments\n"); double maxw = Widthpt - marginpt * 2, maxh = Heightpt - marginpt * 2; double scalex = maxw / w, scaley = maxh / h; double transx = marginpt, transy = (Heightpt - h * scalex) / 2; double scale = scalex; if (scaley < scalex) { scale = scaley; transy = marginpt; transx = (Widthpt - w * scaley) / 2; } fprintf(out, "%g %g translate\n", transx, transy); fprintf(out, "%g %g scale\n", scale, scale); } void Image::outputhdr(FILE *out, unsigned int marginpt) const { fprintf(out, "%%!PS-Adobe-3.0\n"); fprintf(out, "%%%%Creator: UNH-AI C++ Search Framework\n"); fprintf(out, "%%%%Title: %s\n", title.c_str()); fprintf(out, "%%%%BoundingBox: 0 0 %u %u\n", w + 2 * marginpt, h + 2 * marginpt); fprintf(out, "%%%%EndComments\n"); fprintf(out, "%u %u translate\n", marginpt, marginpt); } void Image::outputdata(FILE *out) const { fprintf(out, "\n%% Image data\n"); fprintf(out, "gsave\n"); fprintf(out, "%u %u scale %% scale pixels to points\n", w, h); fprintf(out, "%u %u 8 [%u 0 0 %u 0 0] ", w, h, w, h); fprintf(out, "%% width height colordepth transform\n"); fprintf(out, "/datasource currentfile "); fprintf(out, "/ASCII85Decode filter /RunLengthDecode filter def\n"); fprintf(out, "/datastring %u string def ", w * 3); fprintf(out, "%% %u = width * color components\n", w * 3); fprintf(out, "{datasource datastring readstring pop}\n"); fprintf(out, "false %% false == single data source (rgb)\n"); fprintf(out, "3 %% number of color components\n"); fprintf(out, "colorimage\n"); std::string encoded; encodedata(encoded); fprintf(out, "%s\n", encoded.c_str()); fprintf(out, "grestore\n"); } void Image::encodedata(std::string &dst) const { std::string cs; for (unsigned int i = 0; i < w * h; i++) { cs.push_back(data[i].getred255()); cs.push_back(data[i].getgreen255()); cs.push_back(data[i].getblue255()); } std::string rlenc; runlenenc(rlenc, cs); ascii85enc(dst, rlenc); dst.push_back('~'); dst.push_back('>'); } Image::Path::~Path(void) { while (!segs.empty()) { delete segs.back(); segs.pop_back(); } } void Image::Path::write(FILE *out) const { fprintf(out, "%% Path\n"); fprintf(out, "newpath\n"); for (unsigned int i = 0; i < segs.size(); i++) segs[i]->write(out); if (_closepath) fprintf(out, "closepath\n"); if (!_fill) fprintf(out, "stroke\n"); else fprintf(out, "fill\n"); } void Image::Path::LineJoin::write(FILE *out) const { fprintf(out, "%d setlinejoin\n", type); } void Image::Path::MoveTo::write(FILE *out) const { fprintf(out, "%g %g moveto\n", x, y); } Image::Path::Loc Image::Path::MoveTo::move(Loc p) const { return Loc(std::pair<double,double>(x, y)); } void Image::Path::LineTo::write(FILE *out) const { fprintf(out, "%g %g lineto\n", x, y); } Image::Path::Loc Image::Path::LineTo::move(Loc p) const { return Loc(std::pair<double,double>(x, y)); } void Image::Path::SetLineWidth::write(FILE *out) const { fprintf(out, "%g setlinewidth\n", w); } void Image::Path::SetColor::write(FILE *out) const { fprintf(out, "%g %g %g setrgbcolor\n", c.getred(), c.getgreen(), c.getblue()); } void Image::Path::Arc::write(FILE *out) const { const char *fun = "arc"; if (dt < 0) fun = "arcn"; fprintf(out, "%g %g %g %g %g %s\n", x, y, r, t, t + dt, fun); } Image::Path::Loc Image::Path::Arc::move(Loc p) const { double x1 = x + r * cos((t + dt) * M_PI / 180); double y1 = y + r * sin((t + dt) * M_PI / 180); return Loc(std::pair<double,double>(x1, y1)); } static bool dbleq(double a, double b) { static const double Epsilon = 0.01; return fabs(a - b) < Epsilon; } void Image::Path::line(double x0, double y0, double x1, double y1) { if (!cur || !dbleq(cur->first, x0) || !dbleq(cur->second, y0)) addseg(new MoveTo(x0, y0)); addseg(new LineTo(x1, y1)); } void Image::Path::nauticalcurve(double xc, double yc, double r, double t, double dt) { NauticalArc *a = new NauticalArc(xc, yc, r, t, dt); double x0 = xc + a->r * cos(a->t * M_PI / 180); double y0 = yc + a->r * sin(a->t * M_PI / 180); if (!cur || !dbleq(cur->first, x0) || !dbleq(cur->second, y0)) addseg(new MoveTo(x0, y0)); addseg(a); } void Image::Path::curve(double xc, double yc, double r, double t, double dt) { Arc *a = new Arc(xc, yc, r, t, dt); double x0 = xc + a->r * cos(a->t * M_PI / 180); double y0 = yc + a->r * sin(a->t * M_PI / 180); if (!cur || !dbleq(cur->first, x0) || !dbleq(cur->second, y0)) addseg(new MoveTo(x0, y0)); addseg(a); } void Image::Text::write(FILE *out) const { fprintf(out, "%% Text\n"); fprintf(out, "/%s findfont %g scalefont setfont\n", font.c_str(), sz); fprintf(out, "%u %u moveto\n", x, y); fprintf(out, "%g %g %g setrgbcolor\n", c.getred(), c.getgreen(), c.getblue()); fprintf(out, "(%s) ", text.c_str()); switch (pos) { case Left: fprintf(out, "show\n"); break; case Right: fprintf(out, "dup stringwidth pop neg 0 rmoveto show\n"); break; case Centered: fprintf(out, "dup stringwidth pop 2 div neg 0 rmoveto show\n"); break; default: fatal("Unknown text position: %d\n", pos); } } void Image::Triangle::write(FILE *out) const { double wrad = w * M_PI / 180; double rotrad = rot * M_PI / 180; double side = ht / cos(wrad / 2); double xtop = ht / 2; double xbot = -ht / 2; double y1 = side * sin(wrad / 2); double y2 = -side * sin(wrad / 2); double x0r = xtop * cos(rotrad); double y0r = xtop * sin(rotrad); double x1r = xbot * cos(rotrad) - y1 * sin(rotrad); double y1r = xbot * sin(rotrad) + y1 * cos(rotrad); double x2r = xbot * cos(rotrad) - y2 * sin(rotrad); double y2r = xbot * sin(rotrad) + y2 * cos(rotrad); fprintf(out, "%% Triangle\n"); fprintf(out, "newpath\n"); fprintf(out, "%g %g %g setrgbcolor\n", c.getred(), c.getgreen(), c.getblue()); if (linewidth >= 0) fprintf(out, "%g setlinewidth\n", linewidth); else fprintf(out, "0.1 setlinewidth\n"); fprintf(out, "%g %g moveto\n", x0r + x, y0r + y); fprintf(out, "%g %g lineto\n", x1r + x, y1r + y); fprintf(out, "%g %g lineto\n", x2r + x, y2r + y); fprintf(out, "closepath\n"); if (linewidth < 0) fprintf(out, "fill\n"); else fprintf(out, "stroke\n"); } void Image::Circle::write(FILE *out) const { fprintf(out, "%% Circle\n"); const char *finish = "stroke"; if (lwidth <= 0) { finish = "fill"; fprintf(out, "0.1 setlinewidth\n"); } else { fprintf(out, "%g setlinewidth\n", lwidth); } fprintf(out, "%g %g %g setrgbcolor\n", c.getred(), c.getgreen(), c.getblue()); fprintf(out, "newpath %g %g %g 0 360 arc %s\n", x, y, r, finish); } void Image::Rect::write(FILE *out) const { fprintf(out, "%% Rect\n"); const char *finish = "stroke"; if (lwidth <= 0) { finish = "fill"; fprintf(out, "0.1 setlinewidth\n"); } else { fprintf(out, "%g setlinewidth\n", lwidth); } fprintf(out, "%g %g %g setrgbcolor\n", c.getred(), c.getgreen(), c.getblue()); fputs("0 setlinejoin\n", out); fputs("newpath\n", out); fprintf(out, "%g %g moveto\n", x, y); fprintf(out, "%g %g lineto\n", x + w, y); fprintf(out, "%g %g lineto\n", x + w, y + h); fprintf(out, "%g %g lineto\n", x, y + h); fprintf(out, "closepath\n%s\n", finish); }
fix translation.
image: fix translation.
C++
mit
eaburns/search,skiesel/search,skiesel/search,eaburns/search,eaburns/search,skiesel/search
28d41f213a83ce0ec2a65ff6227550662b022c8d
src/mem/ruby/network/garnet2.0/NetworkLink.cc
src/mem/ruby/network/garnet2.0/NetworkLink.cc
/* * Copyright (c) 2020 Advanced Micro Devices, Inc. * Copyright (c) 2020 Inria * Copyright (c) 2016 Georgia Institute of Technology * Copyright (c) 2008 Princeton University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "mem/ruby/network/garnet2.0/NetworkLink.hh" #include "base/trace.hh" #include "debug/RubyNetwork.hh" #include "mem/ruby/network/garnet2.0/CreditLink.hh" NetworkLink::NetworkLink(const Params *p) : ClockedObject(p), Consumer(this), m_id(p->link_id), m_type(NUM_LINK_TYPES_), m_latency(p->link_latency), m_link_utilized(0), m_virt_nets(p->virt_nets), linkBuffer(), link_consumer(nullptr), link_srcQueue(nullptr) { int num_vnets = (p->supported_vnets).size(); assert(num_vnets > 0); mVnets.resize(num_vnets); bitWidth = p->width; for (int i = 0; i < num_vnets; i++) { mVnets[i] = p->supported_vnets[i]; } } void NetworkLink::setLinkConsumer(Consumer *consumer) { link_consumer = consumer; } void NetworkLink::setVcsPerVnet(uint32_t consumerVcs) { m_vc_load.resize(m_virt_nets * consumerVcs); } void NetworkLink::setSourceQueue(flitBuffer *src_queue, ClockedObject *srcClockObj) { link_srcQueue = src_queue; src_object = srcClockObj; } void NetworkLink::wakeup() { DPRINTF(RubyNetwork, "Woke up to transfer flits from %s\n", src_object->name()); assert(link_srcQueue != nullptr); assert(curTick() == clockEdge()); if (link_srcQueue->isReady(curTick())) { flit *t_flit = link_srcQueue->getTopFlit(); DPRINTF(RubyNetwork, "Transmission will finish at %ld :%s\n", clockEdge(m_latency), *t_flit); if (m_type != NUM_LINK_TYPES_) { // Only for assertions and debug messages assert(t_flit->m_width == bitWidth); assert((std::find(mVnets.begin(), mVnets.end(), t_flit->get_vnet()) != mVnets.end()) || (mVnets.size() == 0)); } t_flit->set_time(clockEdge(m_latency)); linkBuffer.insert(t_flit); link_consumer->scheduleEventAbsolute(clockEdge(m_latency)); m_link_utilized++; m_vc_load[t_flit->get_vc()]++; } if (!link_srcQueue->isEmpty()) { scheduleEvent(Cycles(1)); } } void NetworkLink::resetStats() { for (int i = 0; i < m_vc_load.size(); i++) { m_vc_load[i] = 0; } m_link_utilized = 0; } NetworkLink * NetworkLinkParams::create() { return new NetworkLink(this); } CreditLink * CreditLinkParams::create() { return new CreditLink(this); } uint32_t NetworkLink::functionalWrite(Packet *pkt) { return linkBuffer.functionalWrite(pkt); }
/* * Copyright (c) 2020 Advanced Micro Devices, Inc. * Copyright (c) 2020 Inria * Copyright (c) 2016 Georgia Institute of Technology * Copyright (c) 2008 Princeton University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "mem/ruby/network/garnet2.0/NetworkLink.hh" #include "base/trace.hh" #include "debug/RubyNetwork.hh" #include "mem/ruby/network/garnet2.0/CreditLink.hh" NetworkLink::NetworkLink(const Params *p) : ClockedObject(p), Consumer(this), m_id(p->link_id), m_type(NUM_LINK_TYPES_), m_latency(p->link_latency), m_link_utilized(0), m_virt_nets(p->virt_nets), linkBuffer(), link_consumer(nullptr), link_srcQueue(nullptr) { int num_vnets = (p->supported_vnets).size(); mVnets.resize(num_vnets); bitWidth = p->width; for (int i = 0; i < num_vnets; i++) { mVnets[i] = p->supported_vnets[i]; } } void NetworkLink::setLinkConsumer(Consumer *consumer) { link_consumer = consumer; } void NetworkLink::setVcsPerVnet(uint32_t consumerVcs) { m_vc_load.resize(m_virt_nets * consumerVcs); } void NetworkLink::setSourceQueue(flitBuffer *src_queue, ClockedObject *srcClockObj) { link_srcQueue = src_queue; src_object = srcClockObj; } void NetworkLink::wakeup() { DPRINTF(RubyNetwork, "Woke up to transfer flits from %s\n", src_object->name()); assert(link_srcQueue != nullptr); assert(curTick() == clockEdge()); if (link_srcQueue->isReady(curTick())) { flit *t_flit = link_srcQueue->getTopFlit(); DPRINTF(RubyNetwork, "Transmission will finish at %ld :%s\n", clockEdge(m_latency), *t_flit); if (m_type != NUM_LINK_TYPES_) { // Only for assertions and debug messages assert(t_flit->m_width == bitWidth); assert((std::find(mVnets.begin(), mVnets.end(), t_flit->get_vnet()) != mVnets.end()) || (mVnets.size() == 0)); } t_flit->set_time(clockEdge(m_latency)); linkBuffer.insert(t_flit); link_consumer->scheduleEventAbsolute(clockEdge(m_latency)); m_link_utilized++; m_vc_load[t_flit->get_vc()]++; } if (!link_srcQueue->isEmpty()) { scheduleEvent(Cycles(1)); } } void NetworkLink::resetStats() { for (int i = 0; i < m_vc_load.size(); i++) { m_vc_load[i] = 0; } m_link_utilized = 0; } NetworkLink * NetworkLinkParams::create() { return new NetworkLink(this); } CreditLink * CreditLinkParams::create() { return new CreditLink(this); } uint32_t NetworkLink::functionalWrite(Packet *pkt) { return linkBuffer.functionalWrite(pkt); }
Allow empty vnet list for garnet network links
mem-garnet: Allow empty vnet list for garnet network links An empty supporting_vnet list is the default and implies that all vnets are supported. This removes the assert which requires the list to have a minimum list size of 1. Change-Id: I6710ba06041164bbd597d98e75374a26a1aa5655 Reviewed-on: https://gem5-review.googlesource.com/c/public/gem5/+/34258 Reviewed-by: Jason Lowe-Power <[email protected]> Maintainer: Jason Lowe-Power <[email protected]> Tested-by: kokoro <[email protected]>
C++
bsd-3-clause
gem5/gem5,gem5/gem5,gem5/gem5,gem5/gem5,gem5/gem5,gem5/gem5,gem5/gem5
1bcb9f4934e35b9176ab1d97bf6c0798d64640ef
src/plugins/cppeditor/cppincludehierarchy.cpp
src/plugins/cppeditor/cppincludehierarchy.cpp
/**************************************************************************** ** ** Copyright (C) 2014 Przemyslaw Gorszkowski <[email protected]> ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "cppincludehierarchy.h" #include "cppeditor.h" #include "cppeditorconstants.h" #include "cppeditorplugin.h" #include "cppelementevaluator.h" #include "cppincludehierarchymodel.h" #include "cppincludehierarchytreeview.h" #include <coreplugin/editormanager/editormanager.h> #include <coreplugin/find/itemviewfind.h> #include <cplusplus/CppDocument.h> #include <utils/annotateditemdelegate.h> #include <utils/fileutils.h> #include <QDir> #include <QLabel> #include <QLatin1String> #include <QModelIndex> #include <QStandardItem> #include <QVBoxLayout> using namespace CppEditor; using namespace CppEditor::Internal; using namespace Utils; namespace CppEditor { namespace Internal { class CppIncludeLabel : public QLabel { public: CppIncludeLabel(QWidget *parent) : QLabel(parent) {} void setup(const QString &fileName, const QString &filePath) { setText(fileName); m_link = CppEditorWidget::Link(filePath); } private: void mousePressEvent(QMouseEvent *) { if (!m_link.hasValidTarget()) return; Core::EditorManager::openEditorAt(m_link.targetFileName, m_link.targetLine, m_link.targetColumn, Constants::CPPEDITOR_ID); } CppEditorWidget::Link m_link; }; // CppIncludeHierarchyWidget CppIncludeHierarchyWidget::CppIncludeHierarchyWidget() : QWidget(0), m_treeView(0), m_model(0), m_delegate(0), m_includeHierarchyInfoLabel(0), m_editor(0) { m_inspectedFile = new CppIncludeLabel(this); m_inspectedFile->setMargin(5); m_model = new CppIncludeHierarchyModel(this); m_treeView = new CppIncludeHierarchyTreeView(this); m_delegate = new AnnotatedItemDelegate(this); m_delegate->setDelimiter(QLatin1String(" ")); m_delegate->setAnnotationRole(AnnotationRole); m_treeView->setModel(m_model); m_treeView->setEditTriggers(QAbstractItemView::NoEditTriggers); m_treeView->setItemDelegate(m_delegate); connect(m_treeView, SIGNAL(activated(QModelIndex)), this, SLOT(onItemActivated(QModelIndex))); m_includeHierarchyInfoLabel = new QLabel(tr("No include hierarchy available"), this); m_includeHierarchyInfoLabel->setAlignment(Qt::AlignCenter); m_includeHierarchyInfoLabel->setAutoFillBackground(true); m_includeHierarchyInfoLabel->setBackgroundRole(QPalette::Base); QVBoxLayout *layout = new QVBoxLayout; layout->setMargin(0); layout->setSpacing(0); layout->addWidget(m_inspectedFile); layout->addWidget(Core::ItemViewFind::createSearchableWrapper( m_treeView, Core::ItemViewFind::DarkColored, Core::ItemViewFind::FetchMoreWhileSearching)); layout->addWidget(m_includeHierarchyInfoLabel); setLayout(layout); connect(CppEditorPlugin::instance(), SIGNAL(includeHierarchyRequested()), SLOT(perform())); connect(Core::EditorManager::instance(), SIGNAL(editorsClosed(QList<Core::IEditor*>)), this, SLOT(editorsClosed(QList<Core::IEditor*>))); } CppIncludeHierarchyWidget::~CppIncludeHierarchyWidget() { } void CppIncludeHierarchyWidget::perform() { showNoIncludeHierarchyLabel(); m_editor = qobject_cast<CppEditor *>(Core::EditorManager::currentEditor()); if (!m_editor) return; CppEditorWidget *widget = qobject_cast<CppEditorWidget *>(m_editor->widget()); if (!widget) return; m_model->clear(); m_model->buildHierarchy(m_editor, widget->textDocument()->filePath()); if (m_model->isEmpty()) return; m_inspectedFile->setup(widget->textDocument()->displayName(), widget->textDocument()->filePath()); //expand "Includes" m_treeView->expand(m_model->index(0, 0)); //expand "Included by" m_treeView->expand(m_model->index(1, 0)); showIncludeHierarchy(); } void CppIncludeHierarchyWidget::onItemActivated(const QModelIndex &index) { const TextEditor::BaseTextEditorWidget::Link link = index.data(LinkRole).value<TextEditor::BaseTextEditorWidget::Link>(); if (link.hasValidTarget()) Core::EditorManager::openEditorAt(link.targetFileName, link.targetLine, link.targetColumn, Constants::CPPEDITOR_ID); } void CppIncludeHierarchyWidget::editorsClosed(QList<Core::IEditor *> editors) { foreach (Core::IEditor *editor, editors) { if (m_editor == editor) perform(); } } void CppIncludeHierarchyWidget::showNoIncludeHierarchyLabel() { m_inspectedFile->hide(); m_treeView->hide(); m_includeHierarchyInfoLabel->show(); } void CppIncludeHierarchyWidget::showIncludeHierarchy() { m_inspectedFile->show(); m_treeView->show(); m_includeHierarchyInfoLabel->hide(); } // CppIncludeHierarchyStackedWidget CppIncludeHierarchyStackedWidget::CppIncludeHierarchyStackedWidget(QWidget *parent) : QStackedWidget(parent), m_typeHiearchyWidgetInstance(new CppIncludeHierarchyWidget) { addWidget(m_typeHiearchyWidgetInstance); } CppIncludeHierarchyStackedWidget::~CppIncludeHierarchyStackedWidget() { delete m_typeHiearchyWidgetInstance; } // CppIncludeHierarchyFactory CppIncludeHierarchyFactory::CppIncludeHierarchyFactory() { setDisplayName(tr("Include Hierarchy")); setPriority(800); setId(Constants::INCLUDE_HIERARCHY_ID); } Core::NavigationView CppIncludeHierarchyFactory::createWidget() { CppIncludeHierarchyStackedWidget *w = new CppIncludeHierarchyStackedWidget; static_cast<CppIncludeHierarchyWidget *>(w->currentWidget())->perform(); Core::NavigationView navigationView; navigationView.widget = w; return navigationView; } } // namespace Internal } // namespace CppEditor
/**************************************************************************** ** ** Copyright (C) 2014 Przemyslaw Gorszkowski <[email protected]> ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "cppincludehierarchy.h" #include "cppeditor.h" #include "cppeditorconstants.h" #include "cppeditorplugin.h" #include "cppelementevaluator.h" #include "cppincludehierarchymodel.h" #include "cppincludehierarchytreeview.h" #include <coreplugin/editormanager/editormanager.h> #include <coreplugin/find/itemviewfind.h> #include <cplusplus/CppDocument.h> #include <utils/annotateditemdelegate.h> #include <utils/fileutils.h> #include <QDir> #include <QLabel> #include <QLatin1String> #include <QModelIndex> #include <QStandardItem> #include <QVBoxLayout> using namespace CppEditor; using namespace CppEditor::Internal; using namespace Utils; namespace CppEditor { namespace Internal { class CppIncludeLabel : public QLabel { public: CppIncludeLabel(QWidget *parent) : QLabel(parent) {} void setup(const QString &fileName, const QString &filePath) { setText(fileName); m_link = CppEditorWidget::Link(filePath); } private: void mousePressEvent(QMouseEvent *) { if (!m_link.hasValidTarget()) return; Core::EditorManager::openEditorAt(m_link.targetFileName, m_link.targetLine, m_link.targetColumn, Constants::CPPEDITOR_ID); } CppEditorWidget::Link m_link; }; // CppIncludeHierarchyWidget CppIncludeHierarchyWidget::CppIncludeHierarchyWidget() : QWidget(0), m_treeView(0), m_model(0), m_delegate(0), m_includeHierarchyInfoLabel(0), m_editor(0) { m_inspectedFile = new CppIncludeLabel(this); m_inspectedFile->setMargin(5); m_model = new CppIncludeHierarchyModel(this); m_treeView = new CppIncludeHierarchyTreeView(this); m_delegate = new AnnotatedItemDelegate(this); m_delegate->setDelimiter(QLatin1String(" ")); m_delegate->setAnnotationRole(AnnotationRole); m_treeView->setModel(m_model); m_treeView->setEditTriggers(QAbstractItemView::NoEditTriggers); m_treeView->setItemDelegate(m_delegate); connect(m_treeView, SIGNAL(activated(QModelIndex)), this, SLOT(onItemActivated(QModelIndex))); m_includeHierarchyInfoLabel = new QLabel(tr("No include hierarchy available"), this); m_includeHierarchyInfoLabel->setAlignment(Qt::AlignCenter); m_includeHierarchyInfoLabel->setAutoFillBackground(true); m_includeHierarchyInfoLabel->setBackgroundRole(QPalette::Base); m_includeHierarchyInfoLabel->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); QVBoxLayout *layout = new QVBoxLayout; layout->setMargin(0); layout->setSpacing(0); layout->addWidget(m_inspectedFile); layout->addWidget(Core::ItemViewFind::createSearchableWrapper( m_treeView, Core::ItemViewFind::DarkColored, Core::ItemViewFind::FetchMoreWhileSearching)); layout->addWidget(m_includeHierarchyInfoLabel); setLayout(layout); connect(CppEditorPlugin::instance(), SIGNAL(includeHierarchyRequested()), SLOT(perform())); connect(Core::EditorManager::instance(), SIGNAL(editorsClosed(QList<Core::IEditor*>)), this, SLOT(editorsClosed(QList<Core::IEditor*>))); } CppIncludeHierarchyWidget::~CppIncludeHierarchyWidget() { } void CppIncludeHierarchyWidget::perform() { showNoIncludeHierarchyLabel(); m_editor = qobject_cast<CppEditor *>(Core::EditorManager::currentEditor()); if (!m_editor) return; CppEditorWidget *widget = qobject_cast<CppEditorWidget *>(m_editor->widget()); if (!widget) return; m_model->clear(); m_model->buildHierarchy(m_editor, widget->textDocument()->filePath()); if (m_model->isEmpty()) return; m_inspectedFile->setup(widget->textDocument()->displayName(), widget->textDocument()->filePath()); //expand "Includes" m_treeView->expand(m_model->index(0, 0)); //expand "Included by" m_treeView->expand(m_model->index(1, 0)); showIncludeHierarchy(); } void CppIncludeHierarchyWidget::onItemActivated(const QModelIndex &index) { const TextEditor::BaseTextEditorWidget::Link link = index.data(LinkRole).value<TextEditor::BaseTextEditorWidget::Link>(); if (link.hasValidTarget()) Core::EditorManager::openEditorAt(link.targetFileName, link.targetLine, link.targetColumn, Constants::CPPEDITOR_ID); } void CppIncludeHierarchyWidget::editorsClosed(QList<Core::IEditor *> editors) { foreach (Core::IEditor *editor, editors) { if (m_editor == editor) perform(); } } void CppIncludeHierarchyWidget::showNoIncludeHierarchyLabel() { m_inspectedFile->hide(); m_treeView->hide(); m_includeHierarchyInfoLabel->show(); } void CppIncludeHierarchyWidget::showIncludeHierarchy() { m_inspectedFile->show(); m_treeView->show(); m_includeHierarchyInfoLabel->hide(); } // CppIncludeHierarchyStackedWidget CppIncludeHierarchyStackedWidget::CppIncludeHierarchyStackedWidget(QWidget *parent) : QStackedWidget(parent), m_typeHiearchyWidgetInstance(new CppIncludeHierarchyWidget) { addWidget(m_typeHiearchyWidgetInstance); } CppIncludeHierarchyStackedWidget::~CppIncludeHierarchyStackedWidget() { delete m_typeHiearchyWidgetInstance; } // CppIncludeHierarchyFactory CppIncludeHierarchyFactory::CppIncludeHierarchyFactory() { setDisplayName(tr("Include Hierarchy")); setPriority(800); setId(Constants::INCLUDE_HIERARCHY_ID); } Core::NavigationView CppIncludeHierarchyFactory::createWidget() { CppIncludeHierarchyStackedWidget *w = new CppIncludeHierarchyStackedWidget; static_cast<CppIncludeHierarchyWidget *>(w->currentWidget())->perform(); Core::NavigationView navigationView; navigationView.widget = w; return navigationView; } } // namespace Internal } // namespace CppEditor
Fix size policy in CppIncludeHierarchyWidget
CppEditor: Fix size policy in CppIncludeHierarchyWidget Re-produce the fixed problem with: 1. Shut down Qt Creator while having the include hierarchy sidebar open. 2. Re-start Qt Creator - the side bar is displayed again, but the "No include hierarchy available" label is not scaled at the full sidebar size, but only to 50%. Change-Id: I24e84bfd7cbb9dd9383a60179f5444de9401015d Reviewed-by: Przemyslaw Gorszkowski <[email protected]> Reviewed-by: Christian Stenger <[email protected]>
C++
lgpl-2.1
amyvmiwei/qt-creator,danimo/qt-creator,danimo/qt-creator,martyone/sailfish-qtcreator,kuba1/qtcreator,danimo/qt-creator,AltarBeastiful/qt-creator,martyone/sailfish-qtcreator,Distrotech/qtcreator,farseerri/git_code,amyvmiwei/qt-creator,xianian/qt-creator,farseerri/git_code,kuba1/qtcreator,AltarBeastiful/qt-creator,AltarBeastiful/qt-creator,danimo/qt-creator,Distrotech/qtcreator,AltarBeastiful/qt-creator,danimo/qt-creator,xianian/qt-creator,amyvmiwei/qt-creator,danimo/qt-creator,martyone/sailfish-qtcreator,danimo/qt-creator,amyvmiwei/qt-creator,xianian/qt-creator,farseerri/git_code,xianian/qt-creator,AltarBeastiful/qt-creator,martyone/sailfish-qtcreator,kuba1/qtcreator,farseerri/git_code,martyone/sailfish-qtcreator,kuba1/qtcreator,AltarBeastiful/qt-creator,martyone/sailfish-qtcreator,Distrotech/qtcreator,kuba1/qtcreator,Distrotech/qtcreator,xianian/qt-creator,amyvmiwei/qt-creator,danimo/qt-creator,kuba1/qtcreator,martyone/sailfish-qtcreator,kuba1/qtcreator,AltarBeastiful/qt-creator,farseerri/git_code,AltarBeastiful/qt-creator,Distrotech/qtcreator,Distrotech/qtcreator,farseerri/git_code,martyone/sailfish-qtcreator,amyvmiwei/qt-creator,danimo/qt-creator,farseerri/git_code,xianian/qt-creator,amyvmiwei/qt-creator,amyvmiwei/qt-creator,Distrotech/qtcreator,martyone/sailfish-qtcreator,kuba1/qtcreator,xianian/qt-creator,xianian/qt-creator,farseerri/git_code,xianian/qt-creator,kuba1/qtcreator
a79d47c888e7ae12608f7809250f03e7aa3d3b10
src/plugins/projectexplorer/ioutputparser.cpp
src/plugins/projectexplorer/ioutputparser.cpp
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "ioutputparser.h" #include "task.h" /*! \class ProjectExplorer::IOutputParser \brief The IOutputParser class provides an interface for an output parser that emits issues (tasks). \sa ProjectExplorer::Task */ /*! \fn void ProjectExplorer::IOutputParser::appendOutputParser(IOutputParser *parser) \brief Append a subparser to this parser, of which IOutputParser will take ownership. */ /*! \fn IOutputParser *ProjectExplorer::IOutputParser::takeOutputParserChain() \brief Remove the appended outputparser chain from this parser, transferring ownership of the parser chain to the caller. */ /*! \fn IOutputParser *ProjectExplorer::IOutputParser::childParser() const \brief Return the head of this parsers output parser children, IOutputParser keeps ownership. */ /*! \fn void ProjectExplorer::IOutputParser::stdOutput(const QString &line) \brief Called once for each line if standard output to parse. */ /*! \fn void ProjectExplorer::IOutputParser::stdError(const QString &line) \brief Called once for each line if standard error to parse. */ /*! \fn bool ProjectExplorer::IOutputParser::hasFatalErrors() const \brief This is mainly a symbian specific quirk. */ /*! \fn void ProjectExplorer::IOutputParser::addOutput(const QString &string, ProjectExplorer::BuildStep::OutputFormat format) \brief Should be emitted whenever some additional information should be added to the output. Note: This is additional information. There is no need to add each line! */ /*! \fn void ProjectExplorer::IOutputParser::addTask(const ProjectExplorer::Task &task) \brief Should be emitted for each task seen in the output. */ /*! \fn void ProjectExplorer::IOutputParser::outputAdded(const QString &string, ProjectExplorer::BuildStep::OutputFormat format) \brief Subparsers have their addOutput signal connected to this slot. */ /*! \fn void ProjectExplorer::IOutputParser::outputAdded(const QString &string, ProjectExplorer::BuildStep::OutputFormat format) \brief This method can be overwritten to change the string. */ /*! \fn void ProjectExplorer::IOutputParser::taskAdded(const ProjectExplorer::Task &task) \brief Subparsers have their addTask signal connected to this slot. This method can be overwritten to change the task. */ /*! \fn void ProjectExplorer::IOutputParser::doFlush() \brief This method is called whenever a parser is supposed to flush his state. Parsers may have state (e.g. because they need to aggregate several lines into one task). This method is called when this state needs to be flushed out to be visible. doFlush() is called by flush(). flush() is called on childparsers whenever a new task is added. It is also called once when all input has been parsed. */ namespace ProjectExplorer { IOutputParser::IOutputParser() : m_parser(0) { } IOutputParser::~IOutputParser() { delete m_parser; } void IOutputParser::appendOutputParser(IOutputParser *parser) { if (!parser) return; if (m_parser) { m_parser->appendOutputParser(parser); return; } m_parser = parser; connect(parser, SIGNAL(addOutput(QString,ProjectExplorer::BuildStep::OutputFormat)), this, SLOT(outputAdded(QString,ProjectExplorer::BuildStep::OutputFormat)), Qt::DirectConnection); connect(parser, SIGNAL(addTask(ProjectExplorer::Task)), this, SLOT(taskAdded(ProjectExplorer::Task)), Qt::DirectConnection); } IOutputParser *IOutputParser::takeOutputParserChain() { IOutputParser *parser = m_parser; disconnect(parser, SIGNAL(addOutput(QString,ProjectExplorer::BuildStep::OutputFormat)), this, SLOT(outputAdded(QString,ProjectExplorer::BuildStep::OutputFormat))); disconnect(parser, SIGNAL(addTask(ProjectExplorer::Task)), this, SLOT(taskAdded(ProjectExplorer::Task))); m_parser = 0; return parser; } IOutputParser *IOutputParser::childParser() const { return m_parser; } void IOutputParser::setChildParser(IOutputParser *parser) { if (m_parser != parser) delete m_parser; m_parser = parser; } void IOutputParser::stdOutput(const QString &line) { if (m_parser) m_parser->stdOutput(line); } void IOutputParser::stdError(const QString &line) { if (m_parser) m_parser->stdError(line); } void IOutputParser::outputAdded(const QString &string, ProjectExplorer::BuildStep::OutputFormat format) { emit addOutput(string, format); } void IOutputParser::taskAdded(const ProjectExplorer::Task &task) { emit addTask(task); } void IOutputParser::doFlush() { } bool IOutputParser::hasFatalErrors() const { return false || (m_parser && m_parser->hasFatalErrors()); } void IOutputParser::setWorkingDirectory(const QString &workingDirectory) { if (m_parser) m_parser->setWorkingDirectory(workingDirectory); } void IOutputParser::flush() { doFlush(); if (m_parser) m_parser->flush(); } QString IOutputParser::rightTrimmed(const QString &in) { int pos = in.length(); for (; pos > 0; --pos) { if (!in.at(pos - 1).isSpace()) break; } return in.mid(0, pos); } }
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "ioutputparser.h" #include "task.h" /*! \class ProjectExplorer::IOutputParser \brief The IOutputParser class provides an interface for an output parser that emits issues (tasks). \sa ProjectExplorer::Task */ /*! \fn void ProjectExplorer::IOutputParser::appendOutputParser(IOutputParser *parser) \brief Append a subparser to this parser, of which IOutputParser will take ownership. */ /*! \fn IOutputParser *ProjectExplorer::IOutputParser::takeOutputParserChain() \brief Remove the appended outputparser chain from this parser, transferring ownership of the parser chain to the caller. */ /*! \fn IOutputParser *ProjectExplorer::IOutputParser::childParser() const \brief Return the head of this parsers output parser children, IOutputParser keeps ownership. */ /*! \fn void ProjectExplorer::IOutputParser::stdOutput(const QString &line) \brief Called once for each line if standard output to parse. */ /*! \fn void ProjectExplorer::IOutputParser::stdError(const QString &line) \brief Called once for each line if standard error to parse. */ /*! \fn bool ProjectExplorer::IOutputParser::hasFatalErrors() const \brief This is mainly a symbian specific quirk. */ /*! \fn void ProjectExplorer::IOutputParser::addOutput(const QString &string, ProjectExplorer::BuildStep::OutputFormat format) \brief Should be emitted whenever some additional information should be added to the output. Note: This is additional information. There is no need to add each line! */ /*! \fn void ProjectExplorer::IOutputParser::addTask(const ProjectExplorer::Task &task) \brief Should be emitted for each task seen in the output. */ /*! \fn void ProjectExplorer::IOutputParser::outputAdded(const QString &string, ProjectExplorer::BuildStep::OutputFormat format) \brief Subparsers have their addOutput signal connected to this slot. */ /*! \fn void ProjectExplorer::IOutputParser::outputAdded(const QString &string, ProjectExplorer::BuildStep::OutputFormat format) \brief This method can be overwritten to change the string. */ /*! \fn void ProjectExplorer::IOutputParser::taskAdded(const ProjectExplorer::Task &task) \brief Subparsers have their addTask signal connected to this slot. This method can be overwritten to change the task. */ /*! \fn void ProjectExplorer::IOutputParser::doFlush() \brief This method is called whenever a parser is supposed to flush his state. Parsers may have state (e.g. because they need to aggregate several lines into one task). This method is called when this state needs to be flushed out to be visible. doFlush() is called by flush(). flush() is called on childparsers whenever a new task is added. It is also called once when all input has been parsed. */ namespace ProjectExplorer { IOutputParser::IOutputParser() : m_parser(0) { } IOutputParser::~IOutputParser() { delete m_parser; } void IOutputParser::appendOutputParser(IOutputParser *parser) { if (!parser) return; if (m_parser) { m_parser->appendOutputParser(parser); return; } m_parser = parser; connect(parser, SIGNAL(addOutput(QString,ProjectExplorer::BuildStep::OutputFormat)), this, SLOT(outputAdded(QString,ProjectExplorer::BuildStep::OutputFormat)), Qt::DirectConnection); connect(parser, SIGNAL(addTask(ProjectExplorer::Task)), this, SLOT(taskAdded(ProjectExplorer::Task)), Qt::DirectConnection); } IOutputParser *IOutputParser::takeOutputParserChain() { IOutputParser *parser = m_parser; disconnect(parser, SIGNAL(addOutput(QString,ProjectExplorer::BuildStep::OutputFormat)), this, SLOT(outputAdded(QString,ProjectExplorer::BuildStep::OutputFormat))); disconnect(parser, SIGNAL(addTask(ProjectExplorer::Task)), this, SLOT(taskAdded(ProjectExplorer::Task))); m_parser = 0; return parser; } IOutputParser *IOutputParser::childParser() const { return m_parser; } void IOutputParser::setChildParser(IOutputParser *parser) { if (m_parser != parser) delete m_parser; m_parser = parser; } void IOutputParser::stdOutput(const QString &line) { if (m_parser) m_parser->stdOutput(line); } void IOutputParser::stdError(const QString &line) { if (m_parser) m_parser->stdError(line); } void IOutputParser::outputAdded(const QString &string, ProjectExplorer::BuildStep::OutputFormat format) { emit addOutput(string, format); } void IOutputParser::taskAdded(const ProjectExplorer::Task &task) { emit addTask(task); } void IOutputParser::doFlush() { } bool IOutputParser::hasFatalErrors() const { return m_parser && m_parser->hasFatalErrors(); } void IOutputParser::setWorkingDirectory(const QString &workingDirectory) { if (m_parser) m_parser->setWorkingDirectory(workingDirectory); } void IOutputParser::flush() { doFlush(); if (m_parser) m_parser->flush(); } QString IOutputParser::rightTrimmed(const QString &in) { int pos = in.length(); for (; pos > 0; --pos) { if (!in.at(pos - 1).isSpace()) break; } return in.mid(0, pos); } }
Simplify detection of fatal errors a bit.
OutputParser: Simplify detection of fatal errors a bit. Change-Id: I46f6942a8bee8a1c9711dc97db6424893dd3f276 Reviewed-by: Tobias Hunger <[email protected]>
C++
lgpl-2.1
richardmg/qtcreator,maui-packages/qt-creator,danimo/qt-creator,amyvmiwei/qt-creator,xianian/qt-creator,martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,richardmg/qtcreator,amyvmiwei/qt-creator,richardmg/qtcreator,farseerri/git_code,AltarBeastiful/qt-creator,colede/qtcreator,Distrotech/qtcreator,xianian/qt-creator,darksylinc/qt-creator,danimo/qt-creator,amyvmiwei/qt-creator,maui-packages/qt-creator,omniacreator/qtcreator,Distrotech/qtcreator,kuba1/qtcreator,amyvmiwei/qt-creator,kuba1/qtcreator,amyvmiwei/qt-creator,kuba1/qtcreator,martyone/sailfish-qtcreator,colede/qtcreator,omniacreator/qtcreator,colede/qtcreator,colede/qtcreator,AltarBeastiful/qt-creator,kuba1/qtcreator,colede/qtcreator,maui-packages/qt-creator,Distrotech/qtcreator,colede/qtcreator,farseerri/git_code,xianian/qt-creator,martyone/sailfish-qtcreator,farseerri/git_code,Distrotech/qtcreator,omniacreator/qtcreator,amyvmiwei/qt-creator,xianian/qt-creator,xianian/qt-creator,omniacreator/qtcreator,AltarBeastiful/qt-creator,danimo/qt-creator,martyone/sailfish-qtcreator,colede/qtcreator,farseerri/git_code,danimo/qt-creator,danimo/qt-creator,kuba1/qtcreator,martyone/sailfish-qtcreator,maui-packages/qt-creator,darksylinc/qt-creator,richardmg/qtcreator,danimo/qt-creator,xianian/qt-creator,farseerri/git_code,Distrotech/qtcreator,richardmg/qtcreator,AltarBeastiful/qt-creator,danimo/qt-creator,farseerri/git_code,martyone/sailfish-qtcreator,amyvmiwei/qt-creator,AltarBeastiful/qt-creator,darksylinc/qt-creator,richardmg/qtcreator,xianian/qt-creator,amyvmiwei/qt-creator,darksylinc/qt-creator,maui-packages/qt-creator,maui-packages/qt-creator,maui-packages/qt-creator,AltarBeastiful/qt-creator,omniacreator/qtcreator,Distrotech/qtcreator,omniacreator/qtcreator,martyone/sailfish-qtcreator,AltarBeastiful/qt-creator,kuba1/qtcreator,richardmg/qtcreator,kuba1/qtcreator,Distrotech/qtcreator,xianian/qt-creator,kuba1/qtcreator,darksylinc/qt-creator,darksylinc/qt-creator,omniacreator/qtcreator,martyone/sailfish-qtcreator,farseerri/git_code,farseerri/git_code,danimo/qt-creator,xianian/qt-creator,darksylinc/qt-creator,AltarBeastiful/qt-creator,kuba1/qtcreator,darksylinc/qt-creator,danimo/qt-creator
72f38d4f62e8dfd505af976c8a0d35b38592bb2b
src/togo/resource/resource_handler/shader.cpp
src/togo/resource/resource_handler/shader.cpp
#line 2 "togo/resource/resource_handler/shader.cpp" /** @copyright MIT license; see @ref index or the accompanying LICENSE file. */ #include <togo/config.hpp> #include <togo/error/assert.hpp> #include <togo/collection/array.hpp> #include <togo/collection/fixed_array.hpp> #include <togo/resource/types.hpp> #include <togo/resource/resource.hpp> #include <togo/resource/resource_handler.hpp> #include <togo/resource/resource_manager.hpp> #include <togo/serialization/serializer.hpp> #include <togo/serialization/gfx/shader_def.hpp> #include <togo/serialization/binary_serializer.hpp> #include <togo/gfx/types.hpp> #include <togo/gfx/renderer/types.hpp> #include <togo/gfx/shader_def.hpp> #include <togo/gfx/renderer.hpp> namespace togo { namespace resource_handler { namespace shader { namespace { static void push_def( gfx::ShaderSpec& spec, gfx::ShaderStage& stage, gfx::ShaderDef const& def, ResourceManager& manager, bool const push_param_blocks ) { for (auto const dep_name : def.prelude) { auto const* const dep_def = static_cast<gfx::ShaderDef const*>( resource_manager::get_resource(manager, RES_TYPE_SHADER_PRELUDE, dep_name).pointer ); TOGO_DEBUG_ASSERTE(dep_def); push_def(spec, stage, *dep_def, manager, push_param_blocks); } // Push sources StringRef source = gfx::shader_def::shared_source(def); if (source.any()) { fixed_array::push_back(stage.sources, source); } source = gfx::shader_def::stage_source(def, stage.type); if (source.any()) { fixed_array::push_back(stage.sources, source); } if (push_param_blocks) { for (auto const& pb_def : def.fixed_param_blocks) { fixed_array::push_back(spec.fixed_param_blocks, pb_def); } for (auto const& pb_def : def.draw_param_blocks) { fixed_array::push_back(spec.draw_param_blocks, pb_def); } } } static void add_stage( gfx::ShaderSpec& spec, gfx::ShaderStage::Type const type, gfx::ShaderDef const& def, ResourceManager& manager, bool const push_param_blocks ) { fixed_array::increase_size(spec.stages, 1); gfx::ShaderStage& stage = fixed_array::back(spec.stages); stage.type = type; fixed_array::clear(stage.sources); // Push shared configuration if it exists if (resource_manager::has_resource( manager, RES_TYPE_SHADER_PRELUDE, RES_NAME_SHADER_CONFIG )) { auto const* const shader_config_def = static_cast<gfx::ShaderDef const*>( resource_manager::load_resource( manager, RES_TYPE_SHADER_PRELUDE, RES_NAME_SHADER_CONFIG ).pointer ); if (shader_config_def) { push_def(spec, stage, *shader_config_def, manager, push_param_blocks); } } // Push graph push_def(spec, stage, def, manager, push_param_blocks); } static gfx::ParamBlockDef const* find_conflicting_param_block( FixedArray<gfx::ParamBlockDef, TOGO_GFX_NUM_PARAM_BLOCKS_BY_KIND> const& param_blocks, gfx::ParamBlockDef const& pb_def, unsigned const from_index, bool const index_conflicts ) { for (unsigned index = from_index; index < fixed_array::size(param_blocks); ++index) { auto const& pb_def_it = param_blocks[index]; if ( pb_def.name_hash == pb_def_it.name_hash || (index_conflicts && pb_def.index == pb_def_it.index) ) { return &pb_def_it; } } return nullptr; } static void check_conflicting_param_blocks( StringRef const desc, FixedArray<gfx::ParamBlockDef, TOGO_GFX_NUM_PARAM_BLOCKS_BY_KIND> const& param_blocks_a, FixedArray<gfx::ParamBlockDef, TOGO_GFX_NUM_PARAM_BLOCKS_BY_KIND> const& param_blocks_b, bool const index_conflicts ) { bool const same = &param_blocks_a == &param_blocks_b; for (unsigned index = 0; index < fixed_array::size(param_blocks_a); ++index) { auto const* const pb_def_a = &param_blocks_a[index]; auto const* const pb_def_b = find_conflicting_param_block( param_blocks_b, *pb_def_a, same ? (index + 1) : 0, index_conflicts ); TOGO_ASSERTF( !pb_def_b, "conflicting param blocks (%.*s): {%.*s, %u} with {%.*s, %u}", desc.size, desc.data, pb_def_a->name.size, pb_def_a->name.data, pb_def_a->index, pb_def_b->name.size, pb_def_b->name.data, pb_def_b->index ); } } } // anonymous namespace static ResourceValue load( void* const type_data, ResourceManager& manager, ResourcePackage& package, ResourceMetadata const& metadata ) { auto* const renderer = static_cast<gfx::Renderer*>(type_data); auto& def = renderer->_shader_stage; {// Deserialize resource ResourceStreamLock lock{package, metadata.id}; BinaryInputSerializer ser{lock.stream()}; ser % def; } gfx::shader_def::patch_param_block_names(def); // Validate TOGO_DEBUG_ASSERTE(gfx::shader_def::type(def) == gfx::ShaderDef::TYPE_UNIT); TOGO_ASSERTE( gfx::renderer::type(renderer) == gfx::RENDERER_TYPE_OPENGL && gfx::shader_def::language(def) == gfx::ShaderDef::LANG_GLSL ); // Load dependencies for (auto const dep_name : def.prelude) { TOGO_ASSERTF( resource_manager::load_resource(manager, RES_TYPE_SHADER_PRELUDE, dep_name).valid(), "failed to load shader dependency: [%16lx]", dep_name ); } // Build specification gfx::ShaderSpec spec; add_stage(spec, gfx::ShaderStage::Type::vertex, def, manager, true); add_stage(spec, gfx::ShaderStage::Type::fragment, def, manager, false); // Validate param blocks check_conflicting_param_blocks("fixed", spec.fixed_param_blocks, spec.fixed_param_blocks, true); check_conflicting_param_blocks("fixed -> draw", spec.fixed_param_blocks, spec.draw_param_blocks, false); check_conflicting_param_blocks("draw", spec.draw_param_blocks, spec.draw_param_blocks, false); {// Reindexed draw param blocks unsigned index = 0; for (auto& pb_def : spec.draw_param_blocks) { pb_def.index = index++; }} // Create shader gfx::ShaderID const id = gfx::renderer::create_shader(renderer, spec); TOGO_DEBUG_ASSERTE(id.valid()); return id._value; } static void unload( void* const type_data, ResourceManager& /*manager*/, ResourceValue const resource ) { auto* const renderer = static_cast<gfx::Renderer*>(type_data); gfx::ShaderID const id{resource.uinteger}; gfx::renderer::destroy_shader(renderer, id); } } // namespace shader } // namespace resource_handler void resource_handler::register_shader( ResourceManager& rm, gfx::Renderer* const renderer ) { TOGO_DEBUG_ASSERTE(renderer); ResourceHandler const handler{ RES_TYPE_SHADER, SER_FORMAT_VERSION_SHADER_DEF, renderer, resource_handler::shader::load, resource_handler::shader::unload }; resource_manager::register_handler(rm, handler); } } // namespace togo
#line 2 "togo/resource/resource_handler/shader.cpp" /** @copyright MIT license; see @ref index or the accompanying LICENSE file. */ #include <togo/config.hpp> #include <togo/error/assert.hpp> #include <togo/collection/array.hpp> #include <togo/collection/fixed_array.hpp> #include <togo/resource/types.hpp> #include <togo/resource/resource.hpp> #include <togo/resource/resource_handler.hpp> #include <togo/resource/resource_manager.hpp> #include <togo/serialization/serializer.hpp> #include <togo/serialization/gfx/shader_def.hpp> #include <togo/serialization/binary_serializer.hpp> #include <togo/gfx/types.hpp> #include <togo/gfx/renderer/types.hpp> #include <togo/gfx/shader_def.hpp> #include <togo/gfx/renderer.hpp> namespace togo { namespace resource_handler { namespace shader { namespace { static void push_def( gfx::ShaderSpec& spec, gfx::ShaderStage& stage, gfx::ShaderDef const& def, ResourceManager& manager, bool const push_param_blocks ) { for (auto const dep_name : def.prelude) { auto const* const dep_def = static_cast<gfx::ShaderDef const*>( resource_manager::get_resource(manager, RES_TYPE_SHADER_PRELUDE, dep_name).pointer ); TOGO_DEBUG_ASSERTE(dep_def); push_def(spec, stage, *dep_def, manager, push_param_blocks); } // Push sources StringRef source = gfx::shader_def::shared_source(def); if (source.any()) { fixed_array::push_back(stage.sources, source); } source = gfx::shader_def::stage_source(def, stage.type); if (source.any()) { fixed_array::push_back(stage.sources, source); } if (push_param_blocks) { for (auto const& pb_def : def.fixed_param_blocks) { fixed_array::push_back(spec.fixed_param_blocks, pb_def); } for (auto const& pb_def : def.draw_param_blocks) { fixed_array::push_back(spec.draw_param_blocks, pb_def); } } } static void add_stage( gfx::ShaderSpec& spec, gfx::ShaderStage::Type const type, gfx::ShaderDef const& def, ResourceManager& manager, bool const push_param_blocks ) { fixed_array::increase_size(spec.stages, 1); gfx::ShaderStage& stage = fixed_array::back(spec.stages); stage.type = type; fixed_array::clear(stage.sources); // Push shared configuration if it exists if (resource_manager::has_resource( manager, RES_TYPE_SHADER_PRELUDE, RES_NAME_SHADER_CONFIG )) { auto const* const shader_config_def = static_cast<gfx::ShaderDef const*>( resource_manager::load_resource( manager, RES_TYPE_SHADER_PRELUDE, RES_NAME_SHADER_CONFIG ).pointer ); if (shader_config_def) { push_def(spec, stage, *shader_config_def, manager, push_param_blocks); } } // Push graph push_def(spec, stage, def, manager, push_param_blocks); } static gfx::ParamBlockDef const* find_conflicting_param_block( FixedArray<gfx::ParamBlockDef, TOGO_GFX_NUM_PARAM_BLOCKS_BY_KIND> const& param_blocks, gfx::ParamBlockDef const& pb_def, unsigned const from_index, bool const index_conflicts ) { for (unsigned index = from_index; index < fixed_array::size(param_blocks); ++index) { auto const& pb_def_it = param_blocks[index]; if ( pb_def.name_hash == pb_def_it.name_hash || (index_conflicts && pb_def.index == pb_def_it.index) ) { return &pb_def_it; } } return nullptr; } static void check_conflicting_param_blocks( StringRef const desc, FixedArray<gfx::ParamBlockDef, TOGO_GFX_NUM_PARAM_BLOCKS_BY_KIND> const& param_blocks_a, FixedArray<gfx::ParamBlockDef, TOGO_GFX_NUM_PARAM_BLOCKS_BY_KIND> const& param_blocks_b, bool const index_conflicts ) { bool const same = &param_blocks_a == &param_blocks_b; for (unsigned index = 0; index < fixed_array::size(param_blocks_a); ++index) { auto const* const pb_def_a = &param_blocks_a[index]; auto const* const pb_def_b = find_conflicting_param_block( param_blocks_b, *pb_def_a, same ? (index + 1) : 0, index_conflicts ); TOGO_ASSERTF( !pb_def_b, "conflicting param blocks (%.*s): {%.*s (%08x), %u} with {%.*s (%08x), %u}", desc.size, desc.data, pb_def_a->name.size, pb_def_a->name.data, pb_def_a->name_hash, pb_def_a->index, pb_def_b->name.size, pb_def_b->name.data, pb_def_b->name_hash, pb_def_b->index ); } } } // anonymous namespace static ResourceValue load( void* const type_data, ResourceManager& manager, ResourcePackage& package, ResourceMetadata const& metadata ) { auto* const renderer = static_cast<gfx::Renderer*>(type_data); auto& def = renderer->_shader_stage; {// Deserialize resource ResourceStreamLock lock{package, metadata.id}; BinaryInputSerializer ser{lock.stream()}; ser % def; } gfx::shader_def::patch_param_block_names(def); // Validate TOGO_DEBUG_ASSERTE(gfx::shader_def::type(def) == gfx::ShaderDef::TYPE_UNIT); TOGO_ASSERTE( gfx::renderer::type(renderer) == gfx::RENDERER_TYPE_OPENGL && gfx::shader_def::language(def) == gfx::ShaderDef::LANG_GLSL ); // Load dependencies for (auto const dep_name : def.prelude) { TOGO_ASSERTF( resource_manager::load_resource(manager, RES_TYPE_SHADER_PRELUDE, dep_name).valid(), "failed to load shader dependency: [%16lx]", dep_name ); } // Build specification gfx::ShaderSpec spec; add_stage(spec, gfx::ShaderStage::Type::vertex, def, manager, true); add_stage(spec, gfx::ShaderStage::Type::fragment, def, manager, false); // Validate param blocks check_conflicting_param_blocks("fixed", spec.fixed_param_blocks, spec.fixed_param_blocks, true); check_conflicting_param_blocks("fixed -> draw", spec.fixed_param_blocks, spec.draw_param_blocks, false); check_conflicting_param_blocks("draw", spec.draw_param_blocks, spec.draw_param_blocks, false); {// Reindexed draw param blocks unsigned index = 0; for (auto& pb_def : spec.draw_param_blocks) { pb_def.index = index++; }} // Create shader gfx::ShaderID const id = gfx::renderer::create_shader(renderer, spec); TOGO_DEBUG_ASSERTE(id.valid()); return id._value; } static void unload( void* const type_data, ResourceManager& /*manager*/, ResourceValue const resource ) { auto* const renderer = static_cast<gfx::Renderer*>(type_data); gfx::ShaderID const id{resource.uinteger}; gfx::renderer::destroy_shader(renderer, id); } } // namespace shader } // namespace resource_handler void resource_handler::register_shader( ResourceManager& rm, gfx::Renderer* const renderer ) { TOGO_DEBUG_ASSERTE(renderer); ResourceHandler const handler{ RES_TYPE_SHADER, SER_FORMAT_VERSION_SHADER_DEF, renderer, resource_handler::shader::load, resource_handler::shader::unload }; resource_manager::register_handler(rm, handler); } } // namespace togo
print param block name hash in validation assertion.
resource/resource_handler/shader: print param block name hash in validation assertion.
C++
mit
komiga/togo,komiga/togo,komiga/togo
e4922a4fdc7a3da3859fb04b2edfa317bb387385
strapon/resource_manager/resource_manager.hpp
strapon/resource_manager/resource_manager.hpp
#ifndef RESOURCE_MANAGER_HPP #define RESOURCE_MANAGER_HPP #include <iostream> #include <SDL2/SDL.h> #include <string> #include <map> #include <iostream> #include <SDL2/SDL_image.h> #include <SDL2/SDL_ttf.h> #ifdef __EMSCRIPTEN__ #include <SDL/SDL_mixer.h> #else #include <SDL2/SDL_mixer.h> #endif class ResourceManager { public: /***/ void shutdown() { for(auto e : m_textures) { SDL_DestroyTexture(e.second); } for(auto e : m_sounds) { Mix_FreeChunk(e.second); } for(auto e : m_music) { Mix_FreeMusic(e.second); } for(auto e : m_fonts) { TTF_CloseFont(e.second); } } /***/ bool load_texture(const std::string &key, const std::string &path, SDL_Renderer *ren) { SDL_Texture *texture; texture = IMG_LoadTexture(ren, path.c_str()); if (!texture) { std::cerr << "IMG_Load:" << IMG_GetError() << std::endl; return false; } m_textures[key] = texture; return true; } /***/ bool load_sound(const std::string &key, const std::string &path) { Mix_Chunk *new_sound = Mix_LoadWAV(path.c_str()); if (new_sound == NULL) { std::cerr << "Error: could not load sound from" << path << std::endl; return false; } m_sounds[key] = new_sound; return true; } /***/ bool load_music(const std::string &key, const std::string &path) { Mix_Music *new_music = Mix_LoadMUS(path.c_str()); if (new_music == NULL) { std::cerr << "Error: could not load music from " << path << ": "<< Mix_GetError() << std::endl; return false; } m_music[key] = new_music; return true; } /***/ bool load_font(const std::string &key, const std::string &path, int size) { TTF_Font *new_font = TTF_OpenFont(path.c_str(), size); if (new_font == NULL) { std::cerr << "Error: could not load font from " << path << ": "<< TTF_GetError() << std::endl; return false; } m_fonts[key] = new_font; return true; } /***/ SDL_Texture *get_texture(std::string key) { return m_textures.at(key); } /***/ Mix_Chunk *get_sound(std::string key) { return m_sounds.at(key); } /***/ Mix_Music *get_music(std::string key) { return m_music.at(key); } /***/ TTF_Font *get_font(std::string key) { return m_fonts.at(key); } private: std::map<std::string, SDL_Texture*> m_textures; std::map<std::string, Mix_Chunk*> m_sounds; std::map<std::string, Mix_Music*> m_music; std::map<std::string, TTF_Font*> m_fonts; }; #endif
#ifndef RESOURCE_MANAGER_HPP #define RESOURCE_MANAGER_HPP #include <iostream> #include <SDL2/SDL.h> #include <string> #include <map> #include <iostream> #include <SDL2/SDL_image.h> #ifdef __EMSCRIPTEN__ #include <SDL/SDL_mixer.h> #include <SDL/SDL_ttf.h> #else #include <SDL2/SDL_mixer.h> #include <SDL2/SDL_ttf.h> #endif class ResourceManager { public: /***/ void shutdown() { for(auto e : m_textures) { SDL_DestroyTexture(e.second); } for(auto e : m_sounds) { Mix_FreeChunk(e.second); } for(auto e : m_music) { Mix_FreeMusic(e.second); } for(auto e : m_fonts) { TTF_CloseFont(e.second); } } /***/ bool load_texture(const std::string &key, const std::string &path, SDL_Renderer *ren) { SDL_Texture *texture; texture = IMG_LoadTexture(ren, path.c_str()); if (!texture) { std::cerr << "IMG_Load:" << IMG_GetError() << std::endl; return false; } m_textures[key] = texture; return true; } /***/ bool load_sound(const std::string &key, const std::string &path) { Mix_Chunk *new_sound = Mix_LoadWAV(path.c_str()); if (new_sound == NULL) { std::cerr << "Error: could not load sound from" << path << std::endl; return false; } m_sounds[key] = new_sound; return true; } /***/ bool load_music(const std::string &key, const std::string &path) { Mix_Music *new_music = Mix_LoadMUS(path.c_str()); if (new_music == NULL) { std::cerr << "Error: could not load music from " << path << ": "<< Mix_GetError() << std::endl; return false; } m_music[key] = new_music; return true; } /***/ bool load_font(const std::string &key, const std::string &path, int size) { TTF_Font *new_font = TTF_OpenFont(path.c_str(), size); if (new_font == NULL) { std::cerr << "Error: could not load font from " << path << ": "<< TTF_GetError() << std::endl; return false; } m_fonts[key] = new_font; return true; } /***/ SDL_Texture *get_texture(std::string key) { return m_textures.at(key); } /***/ Mix_Chunk *get_sound(std::string key) { return m_sounds.at(key); } /***/ Mix_Music *get_music(std::string key) { return m_music.at(key); } /***/ TTF_Font *get_font(std::string key) { return m_fonts.at(key); } private: std::map<std::string, SDL_Texture*> m_textures; std::map<std::string, Mix_Chunk*> m_sounds; std::map<std::string, Mix_Music*> m_music; std::map<std::string, TTF_Font*> m_fonts; }; #endif
Fix for emscripten
ResourceManager: Fix for emscripten
C++
mit
svenstaro/strapon
4307b2ce216f54ee28f9ea51b33651eb244e1c3c
src/script/ismine.cpp
src/script/ismine.cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2018 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 <script/ismine.h> #include <key.h> #include <keystore.h> #include <script/script.h> #include <script/sign.h> typedef std::vector<unsigned char> valtype; /** * This is an enum that tracks the execution context of a script, similar to * SigVersion in script/interpreter. It is separate however because we want to * distinguish between top-level scriptPubKey execution and P2SH redeemScript * execution (a distinction that has no impact on consensus rules). */ enum class IsMineSigVersion { TOP = 0, //! scriptPubKey execution P2SH = 1, //! P2SH redeemScript WITNESS_V0 = 2 //! P2WSH witness script execution }; static bool PermitsUncompressed(IsMineSigVersion sigversion) { return sigversion == IsMineSigVersion::TOP || sigversion == IsMineSigVersion::P2SH; } static bool HaveKeys(const std::vector<valtype>& pubkeys, const CKeyStore& keystore) { for (const valtype& pubkey : pubkeys) { CKeyID keyID = CPubKey(pubkey).GetID(); if (!keystore.HaveKey(keyID)) return false; } return true; } static isminetype IsMineInner(const CKeyStore& keystore, const CScript& scriptPubKey, bool& isInvalid, IsMineSigVersion sigversion) { isInvalid = false; std::vector<valtype> vSolutions; txnouttype whichType; if (!Solver(scriptPubKey, whichType, vSolutions)) { if (keystore.HaveWatchOnly(scriptPubKey)) return ISMINE_WATCH_UNSOLVABLE; return ISMINE_NO; } CKeyID keyID; switch (whichType) { case TX_NONSTANDARD: case TX_NULL_DATA: case TX_WITNESS_UNKNOWN: break; case TX_PUBKEY: keyID = CPubKey(vSolutions[0]).GetID(); if (!PermitsUncompressed(sigversion) && vSolutions[0].size() != 33) { isInvalid = true; return ISMINE_NO; } if (keystore.HaveKey(keyID)) return ISMINE_SPENDABLE; break; case TX_WITNESS_V0_KEYHASH: { if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) { // We do not support bare witness outputs unless the P2SH version of it would be // acceptable as well. This protects against matching before segwit activates. // This also applies to the P2WSH case. break; } isminetype ret = IsMineInner(keystore, GetScriptForDestination(CKeyID(uint160(vSolutions[0]))), isInvalid, IsMineSigVersion::WITNESS_V0); if (ret == ISMINE_SPENDABLE || ret == ISMINE_WATCH_SOLVABLE || (ret == ISMINE_NO && isInvalid)) return ret; break; } case TX_PUBKEYHASH: keyID = CKeyID(uint160(vSolutions[0])); if (!PermitsUncompressed(sigversion)) { CPubKey pubkey; if (keystore.GetPubKey(keyID, pubkey) && !pubkey.IsCompressed()) { isInvalid = true; return ISMINE_NO; } } if (keystore.HaveKey(keyID)) return ISMINE_SPENDABLE; break; case TX_SCRIPTHASH: { CScriptID scriptID = CScriptID(uint160(vSolutions[0])); CScript subscript; if (keystore.GetCScript(scriptID, subscript)) { isminetype ret = IsMineInner(keystore, subscript, isInvalid, IsMineSigVersion::P2SH); if (ret == ISMINE_SPENDABLE || ret == ISMINE_WATCH_SOLVABLE || (ret == ISMINE_NO && isInvalid)) return ret; } break; } case TX_WITNESS_V0_SCRIPTHASH: { if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) { break; } uint160 hash; CRIPEMD160().Write(&vSolutions[0][0], vSolutions[0].size()).Finalize(hash.begin()); CScriptID scriptID = CScriptID(hash); CScript subscript; if (keystore.GetCScript(scriptID, subscript)) { isminetype ret = IsMineInner(keystore, subscript, isInvalid, IsMineSigVersion::WITNESS_V0); if (ret == ISMINE_SPENDABLE || ret == ISMINE_WATCH_SOLVABLE || (ret == ISMINE_NO && isInvalid)) return ret; } break; } case TX_MULTISIG: { // Never treat bare multisig outputs as ours (they can still be made watchonly-though) if (sigversion == IsMineSigVersion::TOP) break; // Only consider transactions "mine" if we own ALL the // keys involved. Multi-signature transactions that are // partially owned (somebody else has a key that can spend // them) enable spend-out-from-under-you attacks, especially // in shared-wallet situations. std::vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1); if (!PermitsUncompressed(sigversion)) { for (size_t i = 0; i < keys.size(); i++) { if (keys[i].size() != 33) { isInvalid = true; return ISMINE_NO; } } } if (HaveKeys(keys, keystore)) return ISMINE_SPENDABLE; break; } } if (keystore.HaveWatchOnly(scriptPubKey)) { // TODO: This could be optimized some by doing some work after the above solver SignatureData sigs; return ProduceSignature(keystore, DUMMY_SIGNATURE_CREATOR, scriptPubKey, sigs) ? ISMINE_WATCH_SOLVABLE : ISMINE_WATCH_UNSOLVABLE; } return ISMINE_NO; } isminetype IsMine(const CKeyStore& keystore, const CScript& scriptPubKey, bool& isInvalid) { return IsMineInner(keystore, scriptPubKey, isInvalid, IsMineSigVersion::TOP); } isminetype IsMine(const CKeyStore& keystore, const CScript& scriptPubKey) { bool isInvalid = false; return IsMine(keystore, scriptPubKey, isInvalid); } isminetype IsMine(const CKeyStore& keystore, const CTxDestination& dest) { CScript script = GetScriptForDestination(dest); return IsMine(keystore, script); }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2018 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 <script/ismine.h> #include <key.h> #include <keystore.h> #include <script/script.h> #include <script/sign.h> typedef std::vector<unsigned char> valtype; namespace { /** * This is an enum that tracks the execution context of a script, similar to * SigVersion in script/interpreter. It is separate however because we want to * distinguish between top-level scriptPubKey execution and P2SH redeemScript * execution (a distinction that has no impact on consensus rules). */ enum class IsMineSigVersion { TOP = 0, //! scriptPubKey execution P2SH = 1, //! P2SH redeemScript WITNESS_V0 = 2 //! P2WSH witness script execution }; bool PermitsUncompressed(IsMineSigVersion sigversion) { return sigversion == IsMineSigVersion::TOP || sigversion == IsMineSigVersion::P2SH; } bool HaveKeys(const std::vector<valtype>& pubkeys, const CKeyStore& keystore) { for (const valtype& pubkey : pubkeys) { CKeyID keyID = CPubKey(pubkey).GetID(); if (!keystore.HaveKey(keyID)) return false; } return true; } isminetype IsMineInner(const CKeyStore& keystore, const CScript& scriptPubKey, bool& isInvalid, IsMineSigVersion sigversion) { isInvalid = false; std::vector<valtype> vSolutions; txnouttype whichType; if (!Solver(scriptPubKey, whichType, vSolutions)) { if (keystore.HaveWatchOnly(scriptPubKey)) return ISMINE_WATCH_UNSOLVABLE; return ISMINE_NO; } CKeyID keyID; switch (whichType) { case TX_NONSTANDARD: case TX_NULL_DATA: case TX_WITNESS_UNKNOWN: break; case TX_PUBKEY: keyID = CPubKey(vSolutions[0]).GetID(); if (!PermitsUncompressed(sigversion) && vSolutions[0].size() != 33) { isInvalid = true; return ISMINE_NO; } if (keystore.HaveKey(keyID)) return ISMINE_SPENDABLE; break; case TX_WITNESS_V0_KEYHASH: { if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) { // We do not support bare witness outputs unless the P2SH version of it would be // acceptable as well. This protects against matching before segwit activates. // This also applies to the P2WSH case. break; } isminetype ret = IsMineInner(keystore, GetScriptForDestination(CKeyID(uint160(vSolutions[0]))), isInvalid, IsMineSigVersion::WITNESS_V0); if (ret == ISMINE_SPENDABLE || ret == ISMINE_WATCH_SOLVABLE || (ret == ISMINE_NO && isInvalid)) return ret; break; } case TX_PUBKEYHASH: keyID = CKeyID(uint160(vSolutions[0])); if (!PermitsUncompressed(sigversion)) { CPubKey pubkey; if (keystore.GetPubKey(keyID, pubkey) && !pubkey.IsCompressed()) { isInvalid = true; return ISMINE_NO; } } if (keystore.HaveKey(keyID)) return ISMINE_SPENDABLE; break; case TX_SCRIPTHASH: { CScriptID scriptID = CScriptID(uint160(vSolutions[0])); CScript subscript; if (keystore.GetCScript(scriptID, subscript)) { isminetype ret = IsMineInner(keystore, subscript, isInvalid, IsMineSigVersion::P2SH); if (ret == ISMINE_SPENDABLE || ret == ISMINE_WATCH_SOLVABLE || (ret == ISMINE_NO && isInvalid)) return ret; } break; } case TX_WITNESS_V0_SCRIPTHASH: { if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) { break; } uint160 hash; CRIPEMD160().Write(&vSolutions[0][0], vSolutions[0].size()).Finalize(hash.begin()); CScriptID scriptID = CScriptID(hash); CScript subscript; if (keystore.GetCScript(scriptID, subscript)) { isminetype ret = IsMineInner(keystore, subscript, isInvalid, IsMineSigVersion::WITNESS_V0); if (ret == ISMINE_SPENDABLE || ret == ISMINE_WATCH_SOLVABLE || (ret == ISMINE_NO && isInvalid)) return ret; } break; } case TX_MULTISIG: { // Never treat bare multisig outputs as ours (they can still be made watchonly-though) if (sigversion == IsMineSigVersion::TOP) break; // Only consider transactions "mine" if we own ALL the // keys involved. Multi-signature transactions that are // partially owned (somebody else has a key that can spend // them) enable spend-out-from-under-you attacks, especially // in shared-wallet situations. std::vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1); if (!PermitsUncompressed(sigversion)) { for (size_t i = 0; i < keys.size(); i++) { if (keys[i].size() != 33) { isInvalid = true; return ISMINE_NO; } } } if (HaveKeys(keys, keystore)) return ISMINE_SPENDABLE; break; } } if (keystore.HaveWatchOnly(scriptPubKey)) { // TODO: This could be optimized some by doing some work after the above solver SignatureData sigs; return ProduceSignature(keystore, DUMMY_SIGNATURE_CREATOR, scriptPubKey, sigs) ? ISMINE_WATCH_SOLVABLE : ISMINE_WATCH_UNSOLVABLE; } return ISMINE_NO; } } // namespace isminetype IsMine(const CKeyStore& keystore, const CScript& scriptPubKey, bool& isInvalid) { return IsMineInner(keystore, scriptPubKey, isInvalid, IsMineSigVersion::TOP); } isminetype IsMine(const CKeyStore& keystore, const CScript& scriptPubKey) { bool isInvalid = false; return IsMine(keystore, scriptPubKey, isInvalid); } isminetype IsMine(const CKeyStore& keystore, const CTxDestination& dest) { CScript script = GetScriptForDestination(dest); return IsMine(keystore, script); }
Use anonymous namespace instead of static functions
Use anonymous namespace instead of static functions
C++
mit
chaincoin/chaincoin,chaincoin/chaincoin,chaincoin/chaincoin,chaincoin/chaincoin,chaincoin/chaincoin,chaincoin/chaincoin
5fed164d7002f93fbe46c9e4b6d5c055a4635cb4
lib/VMCore/IntrinsicInst.cpp
lib/VMCore/IntrinsicInst.cpp
//===-- InstrinsicInst.cpp - Intrinsic Instruction Wrappers -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by James M. Laskey and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements methods that make it really easy to deal with intrinsic // functions with the isa/dyncast family of functions. In particular, this // allows you to do things like: // // if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(Inst)) // ... SPI->getFileName() ... SPI->getDirectory() ... // // All intrinsic function calls are instances of the call instruction, so these // are all subclasses of the CallInst class. Note that none of these classes // has state or virtual methods, which is an important part of this gross/neat // hack working. // // In some cases, arguments to intrinsics need to be generic and are defined as // type pointer to empty struct { }*. To access the real item of interest the // cast instruction needs to be stripped away. // //===----------------------------------------------------------------------===// #include "llvm/IntrinsicInst.h" #include "llvm/Constants.h" #include "llvm/GlobalVariable.h" #include "llvm/CodeGen/MachineDebugInfo.h" using namespace llvm; //===----------------------------------------------------------------------===// /// DbgInfoIntrinsic - This is the common base class for debug info intrinsics /// static Value *CastOperand(Value *C) { if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) if (CE->isCast()) return CE->getOperand(0); return NULL; } Value *DbgInfoIntrinsic::StripCast(Value *C) { if (Value *CO = CastOperand(C)) { C = StripCast(CO); } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) { if (GV->hasInitializer()) if (Value *CO = CastOperand(GV->getInitializer())) C = StripCast(CO); } return dyn_cast<GlobalVariable>(C); } //===----------------------------------------------------------------------===// /// DbgStopPointInst - This represents the llvm.dbg.stoppoint instruction. /// std::string DbgStopPointInst::getFileName() const { // Once the operand indices are verified, update this assert assert(LLVMDebugVersion == (5 << 16) && "Verify operand indices"); GlobalVariable *GV = cast<GlobalVariable>(getContext()); if (!GV->hasInitializer()) return ""; ConstantStruct *CS = cast<ConstantStruct>(GV->getInitializer()); return CS->getOperand(3)->getStringValue(); } std::string DbgStopPointInst::getDirectory() const { // Once the operand indices are verified, update this assert assert(LLVMDebugVersion == (5 << 16) && "Verify operand indices"); GlobalVariable *GV = cast<GlobalVariable>(getContext()); if (!GV->hasInitializer()) return ""; ConstantStruct *CS = cast<ConstantStruct>(GV->getInitializer()); return CS->getOperand(4)->getStringValue(); } //===----------------------------------------------------------------------===// /// Ensure that users of IntrinsicInst.h will link with this module. DEFINING_FILE_FOR(IntrinsicInst)
//===-- InstrinsicInst.cpp - Intrinsic Instruction Wrappers -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by James M. Laskey and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements methods that make it really easy to deal with intrinsic // functions with the isa/dyncast family of functions. In particular, this // allows you to do things like: // // if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(Inst)) // ... SPI->getFileName() ... SPI->getDirectory() ... // // All intrinsic function calls are instances of the call instruction, so these // are all subclasses of the CallInst class. Note that none of these classes // has state or virtual methods, which is an important part of this gross/neat // hack working. // // In some cases, arguments to intrinsics need to be generic and are defined as // type pointer to empty struct { }*. To access the real item of interest the // cast instruction needs to be stripped away. // //===----------------------------------------------------------------------===// #include "llvm/IntrinsicInst.h" #include "llvm/Constants.h" #include "llvm/GlobalVariable.h" #include "llvm/CodeGen/MachineDebugInfo.h" using namespace llvm; //===----------------------------------------------------------------------===// /// DbgInfoIntrinsic - This is the common base class for debug info intrinsics /// static Value *CastOperand(Value *C) { if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) if (CE->isCast()) return CE->getOperand(0); return NULL; } Value *DbgInfoIntrinsic::StripCast(Value *C) { if (Value *CO = CastOperand(C)) { C = StripCast(CO); } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) { if (GV->hasInitializer()) if (Value *CO = CastOperand(GV->getInitializer())) C = StripCast(CO); } return dyn_cast<GlobalVariable>(C); } //===----------------------------------------------------------------------===// /// DbgStopPointInst - This represents the llvm.dbg.stoppoint instruction. /// std::string DbgStopPointInst::getFileName() const { // Once the operand indices are verified, update this assert assert(LLVMDebugVersion == (6 << 16) && "Verify operand indices"); GlobalVariable *GV = cast<GlobalVariable>(getContext()); if (!GV->hasInitializer()) return ""; ConstantStruct *CS = cast<ConstantStruct>(GV->getInitializer()); return CS->getOperand(3)->getStringValue(); } std::string DbgStopPointInst::getDirectory() const { // Once the operand indices are verified, update this assert assert(LLVMDebugVersion == (6 << 16) && "Verify operand indices"); GlobalVariable *GV = cast<GlobalVariable>(getContext()); if (!GV->hasInitializer()) return ""; ConstantStruct *CS = cast<ConstantStruct>(GV->getInitializer()); return CS->getOperand(4)->getStringValue(); } //===----------------------------------------------------------------------===// /// Ensure that users of IntrinsicInst.h will link with this module. DEFINING_FILE_FOR(IntrinsicInst)
Update version in safe guards.
Update version in safe guards. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@32546 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,dslab-epfl/asap,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,apple/swift-llvm,dslab-epfl/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,chubbymaggie/asap,dslab-epfl/asap,dslab-epfl/asap,llvm-mirror/llvm,dslab-epfl/asap,llvm-mirror/llvm,chubbymaggie/asap,chubbymaggie/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,chubbymaggie/asap,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm
b5754b092e633db64b2371eed16e496622e9755a
Modules/Learning/Supervised/include/otbNeuralNetworkMachineLearningModel.hxx
Modules/Learning/Supervised/include/otbNeuralNetworkMachineLearningModel.hxx
/* * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 otbNeuralNetworkMachineLearningModel_hxx #define otbNeuralNetworkMachineLearningModel_hxx #include <fstream> #include "otbNeuralNetworkMachineLearningModel.h" #include "itkMacro.h" // itkExceptionMacro namespace otb { template<class TInputValue, class TOutputValue> NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::NeuralNetworkMachineLearningModel() : #ifdef OTB_OPENCV_3 m_ANNModel(cv::ml::ANN_MLP::create()), // TODO #else m_ANNModel (new CvANN_MLP), #endif m_TrainMethod(CvANN_MLP_TrainParams::RPROP), m_ActivateFunction(CvANN_MLP::SIGMOID_SYM), m_Alpha(1.), m_Beta(1.), m_BackPropDWScale(0.1), m_BackPropMomentScale(0.1), m_RegPropDW0(0.1), m_RegPropDWMin(FLT_EPSILON), m_TermCriteriaType(CV_TERMCRIT_ITER + CV_TERMCRIT_EPS), m_MaxIter(1000), m_Epsilon(0.01) { this->m_ConfidenceIndex = true; this->m_IsRegressionSupported = true; } template<class TInputValue, class TOutputValue> NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::~NeuralNetworkMachineLearningModel() { #ifndef OTB_OPENCV_3 delete m_ANNModel; #endif } /** Sets the topology of the NN */ template<class TInputValue, class TOutputValue> void NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::SetLayerSizes(const std::vector<unsigned int> layers) { const unsigned int nbLayers = layers.size(); if (nbLayers < 3) itkExceptionMacro(<< "Number of layers in the Neural Network must be >= 3") m_LayerSizes = layers; } /** Converts a ListSample of VariableLengthVector to a CvMat. The user * is responsible for freeing the output pointer with the * cvReleaseMat function. A null pointer is resturned in case the * conversion failed. */ template<class TInputValue, class TOutputValue> void NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::LabelsToMat(const TargetListSampleType * labels, cv::Mat & output) { unsigned int nbSamples = 0; if (labels != nullptr) { nbSamples = labels->Size(); } // Check for valid listSample if (nbSamples > 0) { // Build an iterator typename TargetListSampleType::ConstIterator labelSampleIt = labels->Begin(); TargetValueType classLabel; for (; labelSampleIt != labels->End(); ++labelSampleIt) { // Retrieve labelSample typename TargetListSampleType::MeasurementVectorType labelSample = labelSampleIt.GetMeasurementVector(); classLabel = labelSample[0]; if (m_MapOfLabels.count(classLabel) == 0) { m_MapOfLabels[classLabel] = -1; } } unsigned int nbClasses = m_MapOfLabels.size(); m_MatrixOfLabels = cv::Mat(1,nbClasses, CV_32FC1); unsigned int itLabel = 0; for (auto& kv : m_MapOfLabels) { classLabel = kv.first; kv.second = itLabel; m_MatrixOfLabels.at<float>(0,itLabel) = classLabel; ++itLabel; } // Sample index unsigned int sampleIdx = 0; labelSampleIt = labels->Begin(); output.create(nbSamples, nbClasses, CV_32FC1); output.setTo(-m_Beta); // Fill the cv matrix for (; labelSampleIt != labels->End(); ++labelSampleIt, ++sampleIdx) { // Retrieve labelSample typename TargetListSampleType::MeasurementVectorType labelSample = labelSampleIt.GetMeasurementVector(); classLabel = labelSample[0]; unsigned int indexLabel = m_MapOfLabels[classLabel]; output.at<float> (sampleIdx, indexLabel) = m_Beta; } } } template<class TInputValue, class TOutputValue> void NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::CreateNetwork() { //Create the neural network const unsigned int nbLayers = m_LayerSizes.size(); if ( nbLayers == 0 ) itkExceptionMacro(<< "Number of layers in the Neural Network must be >= 3") cv::Mat layers = cv::Mat(nbLayers, 1, CV_32SC1); for (unsigned int i = 0; i < nbLayers; i++) { layers.row(i) = m_LayerSizes[i]; } #ifdef OTB_OPENCV_3 m_ANNModel->setLayerSizes(layers); m_ANNModel->setActivationFunction(m_ActivateFunction, m_Alpha, m_Beta); #else m_ANNModel->create(layers, m_ActivateFunction, m_Alpha, m_Beta); #endif } #ifndef OTB_OPENCV_3 template<class TInputValue, class TOutputValue> CvANN_MLP_TrainParams NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::SetNetworkParameters() { CvANN_MLP_TrainParams params; params.train_method = m_TrainMethod; params.bp_dw_scale = m_BackPropDWScale; params.bp_moment_scale = m_BackPropMomentScale; params.rp_dw0 = m_RegPropDW0; params.rp_dw_min = m_RegPropDWMin; CvTermCriteria term_crit = cvTermCriteria(m_TermCriteriaType, m_MaxIter, m_Epsilon); params.term_crit = term_crit; return params; } #endif template<class TInputValue, class TOutputValue> void NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::SetupNetworkAndTrain(cv::Mat& labels) { //convert listsample to opencv matrix cv::Mat samples; otb::ListSampleToMat<InputListSampleType>(this->GetInputListSample(), samples); this->CreateNetwork(); #ifdef OTB_OPENCV_3 int flags = (this->m_RegressionMode ? 0 : cv::ml::ANN_MLP::NO_OUTPUT_SCALE); m_ANNModel->setTrainMethod(m_TrainMethod); m_ANNModel->setBackpropMomentumScale(m_BackPropMomentScale); m_ANNModel->setBackpropWeightScale(m_BackPropDWScale); m_ANNModel->setRpropDW0(m_RegPropDW0); //m_ANNModel->setRpropDWMax( ); m_ANNModel->setRpropDWMin(m_RegPropDWMin); //m_ANNModel->setRpropDWMinus( ); //m_ANNModel->setRpropDWPlus( ); m_ANNModel->setTermCriteria(cv::TermCriteria(m_TermCriteriaType,m_MaxIter,m_Epsilon)); m_ANNModel->train(cv::ml::TrainData::create( samples, cv::ml::ROW_SAMPLE, labels), flags); #else CvANN_MLP_TrainParams params = this->SetNetworkParameters(); //train the Neural network model m_ANNModel->train(samples, labels, cv::Mat(), cv::Mat(), params); #endif } /** Train the machine learning model for classification*/ template<class TInputValue, class TOutputValue> void NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::Train() { //Transform the targets into a matrix of labels cv::Mat matOutputANN; if (this->m_RegressionMode) { // MODE REGRESSION otb::ListSampleToMat<TargetListSampleType>(this->GetTargetListSample(), matOutputANN); } else { // MODE CLASSIFICATION : store the map between internal labels and output labels LabelsToMat(this->GetTargetListSample(), matOutputANN); } this->SetupNetworkAndTrain(matOutputANN); } template<class TInputValue, class TOutputValue> typename NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::TargetSampleType NeuralNetworkMachineLearningModel< TInputValue, TOutputValue>::DoPredict(const InputSampleType & input, ConfidenceValueType *quality, ProbaSampleType *proba) const { TargetSampleType target; //convert listsample to Mat cv::Mat sample; otb::SampleToMat<InputSampleType>(input, sample); cv::Mat response; //(1, 1, CV_32FC1); m_ANNModel->predict(sample, response); float currentResponse = 0; float maxResponse = response.at<float> (0, 0); if (this->m_RegressionMode) { // MODE REGRESSION : only output first response target[0] = maxResponse; return target; } // MODE CLASSIFICATION : find the highest response float secondResponse = -1e10; target[0] = m_MatrixOfLabels.at<TOutputValue>(0); unsigned int nbClasses = m_MatrixOfLabels.size[1]; for (unsigned itLabel = 1; itLabel < nbClasses; ++itLabel) { currentResponse = response.at<float> (0, itLabel); if (currentResponse > maxResponse) { secondResponse = maxResponse; maxResponse = currentResponse; target[0] = m_MatrixOfLabels.at<TOutputValue>(itLabel); } else { if (currentResponse > secondResponse) { secondResponse = currentResponse; } } } if (quality != nullptr) { (*quality) = static_cast<ConfidenceValueType>(maxResponse) - static_cast<ConfidenceValueType>(secondResponse); } if (proba != nullptr && !this->m_ProbaIndex) itkExceptionMacro("Probability per class not available for this classifier !"); return target; } template<class TInputValue, class TOutputValue> void NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::Save(const std::string & filename, const std::string & name) {std::cout << "save!!!!!" << std::endl; #ifdef OTB_OPENCV_3 cv::FileStorage fs(filename, cv::FileStorage::WRITE); fs << (name.empty() ? m_ANNModel->getDefaultName() : cv::String(name)) << "{"; m_ANNModel->write(fs); if (!m_MatrixOfLabels.empty()) { fs << "class_labels" << m_MatrixOfLabels; } fs << "}"; fs.release(); #else const char* lname = "my_nn"; if ( !name.empty() ) lname = name.c_str(); CvFileStorage* fs = nullptr; fs = cvOpenFileStorage(filename.c_str(), nullptr, CV_STORAGE_WRITE); if ( !fs ) { itkExceptionMacro("Could not open the file " << filename << " for writing"); } m_ANNModel->write(fs, lname); if (!m_MatrixOfLabels.empty()) { // cvWrite can't write cv::Mat auto tmpMat = CvMat(m_MatrixOfLabels); cvWrite(fs, "class_labels", &tmpMat); } cvReleaseFileStorage(&fs); #endif std::cout << "endsave!!!!!" << std::endl; } template<class TInputValue, class TOutputValue> void NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::Load(const std::string & filename, const std::string & name) { #ifdef OTB_OPENCV_3 cv::FileStorage fs(filename, cv::FileStorage::READ); cv::FileNode model_node(name.empty() ? fs.getFirstTopLevelNode() : fs[name]); m_ANNModel->read(model_node); model_node["class_labels"] >> m_MatrixOfLabels; fs.release(); #else const char* lname = nullptr; if ( !name.empty() ) lname = name.c_str(); cv::FileNode model_node; cv::FileStorage fs(filename,cv::FileStorage::READ); if (!fs.isOpened()) { itkExceptionMacro("Could not open the file " << filename << " for reading"); } if( lname ) model_node = fs[lname]; else { cv::FileNode root = fs.root(); if ( root.size() > 0) { model_node = *(root.begin()); } } m_ANNModel->read(*fs,*model_node); model_node["class_labels"] >> m_MatrixOfLabels; fs.release(); #endif } template<class TInputValue, class TOutputValue> bool NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::CanReadFile(const std::string & file) { std::ifstream ifs; ifs.open(file); if (!ifs) { std::cerr << "Could not read file " << file << std::endl; return false; } while (!ifs.eof()) { std::string line; std::getline(ifs, line); if (line.find(CV_TYPE_NAME_ML_ANN_MLP) != std::string::npos #ifdef OTB_OPENCV_3 || line.find(m_ANNModel->getDefaultName()) != std::string::npos #endif ) { return true; } } ifs.close(); return false; } template<class TInputValue, class TOutputValue> bool NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::CanWriteFile(const std::string & itkNotUsed(file)) { return false; } template<class TInputValue, class TOutputValue> void NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::PrintSelf(std::ostream& os, itk::Indent indent) const { // Call superclass implementation Superclass::PrintSelf(os, indent); } } //end namespace otb #endif
/* * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 otbNeuralNetworkMachineLearningModel_hxx #define otbNeuralNetworkMachineLearningModel_hxx #include <fstream> #include "otbNeuralNetworkMachineLearningModel.h" #include "itkMacro.h" // itkExceptionMacro namespace otb { template<class TInputValue, class TOutputValue> NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::NeuralNetworkMachineLearningModel() : #ifdef OTB_OPENCV_3 m_ANNModel(cv::ml::ANN_MLP::create()), // TODO #else m_ANNModel (new CvANN_MLP), #endif m_TrainMethod(CvANN_MLP_TrainParams::RPROP), m_ActivateFunction(CvANN_MLP::SIGMOID_SYM), m_Alpha(1.), m_Beta(1.), m_BackPropDWScale(0.1), m_BackPropMomentScale(0.1), m_RegPropDW0(0.1), m_RegPropDWMin(FLT_EPSILON), m_TermCriteriaType(CV_TERMCRIT_ITER + CV_TERMCRIT_EPS), m_MaxIter(1000), m_Epsilon(0.01) { this->m_ConfidenceIndex = true; this->m_IsRegressionSupported = true; } template<class TInputValue, class TOutputValue> NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::~NeuralNetworkMachineLearningModel() { #ifndef OTB_OPENCV_3 delete m_ANNModel; #endif } /** Sets the topology of the NN */ template<class TInputValue, class TOutputValue> void NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::SetLayerSizes(const std::vector<unsigned int> layers) { const unsigned int nbLayers = layers.size(); if (nbLayers < 3) itkExceptionMacro(<< "Number of layers in the Neural Network must be >= 3") m_LayerSizes = layers; } /** Converts a ListSample of VariableLengthVector to a CvMat. The user * is responsible for freeing the output pointer with the * cvReleaseMat function. A null pointer is resturned in case the * conversion failed. */ template<class TInputValue, class TOutputValue> void NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::LabelsToMat(const TargetListSampleType * labels, cv::Mat & output) { unsigned int nbSamples = 0; if (labels != nullptr) { nbSamples = labels->Size(); } // Check for valid listSample if (nbSamples > 0) { // Build an iterator typename TargetListSampleType::ConstIterator labelSampleIt = labels->Begin(); TargetValueType classLabel; for (; labelSampleIt != labels->End(); ++labelSampleIt) { // Retrieve labelSample typename TargetListSampleType::MeasurementVectorType labelSample = labelSampleIt.GetMeasurementVector(); classLabel = labelSample[0]; if (m_MapOfLabels.count(classLabel) == 0) { m_MapOfLabels[classLabel] = -1; } } unsigned int nbClasses = m_MapOfLabels.size(); m_MatrixOfLabels = cv::Mat(1,nbClasses, CV_32FC1); unsigned int itLabel = 0; for (auto& kv : m_MapOfLabels) { classLabel = kv.first; kv.second = itLabel; m_MatrixOfLabels.at<float>(0,itLabel) = classLabel; ++itLabel; } // Sample index unsigned int sampleIdx = 0; labelSampleIt = labels->Begin(); output.create(nbSamples, nbClasses, CV_32FC1); output.setTo(-m_Beta); // Fill the cv matrix for (; labelSampleIt != labels->End(); ++labelSampleIt, ++sampleIdx) { // Retrieve labelSample typename TargetListSampleType::MeasurementVectorType labelSample = labelSampleIt.GetMeasurementVector(); classLabel = labelSample[0]; unsigned int indexLabel = m_MapOfLabels[classLabel]; output.at<float> (sampleIdx, indexLabel) = m_Beta; } } } template<class TInputValue, class TOutputValue> void NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::CreateNetwork() { //Create the neural network const unsigned int nbLayers = m_LayerSizes.size(); if ( nbLayers == 0 ) itkExceptionMacro(<< "Number of layers in the Neural Network must be >= 3") cv::Mat layers = cv::Mat(nbLayers, 1, CV_32SC1); for (unsigned int i = 0; i < nbLayers; i++) { layers.row(i) = m_LayerSizes[i]; } #ifdef OTB_OPENCV_3 m_ANNModel->setLayerSizes(layers); m_ANNModel->setActivationFunction(m_ActivateFunction, m_Alpha, m_Beta); #else m_ANNModel->create(layers, m_ActivateFunction, m_Alpha, m_Beta); #endif } #ifndef OTB_OPENCV_3 template<class TInputValue, class TOutputValue> CvANN_MLP_TrainParams NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::SetNetworkParameters() { CvANN_MLP_TrainParams params; params.train_method = m_TrainMethod; params.bp_dw_scale = m_BackPropDWScale; params.bp_moment_scale = m_BackPropMomentScale; params.rp_dw0 = m_RegPropDW0; params.rp_dw_min = m_RegPropDWMin; CvTermCriteria term_crit = cvTermCriteria(m_TermCriteriaType, m_MaxIter, m_Epsilon); params.term_crit = term_crit; return params; } #endif template<class TInputValue, class TOutputValue> void NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::SetupNetworkAndTrain(cv::Mat& labels) { //convert listsample to opencv matrix cv::Mat samples; otb::ListSampleToMat<InputListSampleType>(this->GetInputListSample(), samples); this->CreateNetwork(); #ifdef OTB_OPENCV_3 int flags = (this->m_RegressionMode ? 0 : cv::ml::ANN_MLP::NO_OUTPUT_SCALE); m_ANNModel->setTrainMethod(m_TrainMethod); m_ANNModel->setBackpropMomentumScale(m_BackPropMomentScale); m_ANNModel->setBackpropWeightScale(m_BackPropDWScale); m_ANNModel->setRpropDW0(m_RegPropDW0); //m_ANNModel->setRpropDWMax( ); m_ANNModel->setRpropDWMin(m_RegPropDWMin); //m_ANNModel->setRpropDWMinus( ); //m_ANNModel->setRpropDWPlus( ); m_ANNModel->setTermCriteria(cv::TermCriteria(m_TermCriteriaType,m_MaxIter,m_Epsilon)); m_ANNModel->train(cv::ml::TrainData::create( samples, cv::ml::ROW_SAMPLE, labels), flags); #else CvANN_MLP_TrainParams params = this->SetNetworkParameters(); //train the Neural network model m_ANNModel->train(samples, labels, cv::Mat(), cv::Mat(), params); #endif } /** Train the machine learning model for classification*/ template<class TInputValue, class TOutputValue> void NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::Train() { //Transform the targets into a matrix of labels cv::Mat matOutputANN; if (this->m_RegressionMode) { // MODE REGRESSION otb::ListSampleToMat<TargetListSampleType>(this->GetTargetListSample(), matOutputANN); } else { // MODE CLASSIFICATION : store the map between internal labels and output labels LabelsToMat(this->GetTargetListSample(), matOutputANN); } this->SetupNetworkAndTrain(matOutputANN); } template<class TInputValue, class TOutputValue> typename NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::TargetSampleType NeuralNetworkMachineLearningModel< TInputValue, TOutputValue>::DoPredict(const InputSampleType & input, ConfidenceValueType *quality, ProbaSampleType *proba) const { TargetSampleType target; //convert listsample to Mat cv::Mat sample; otb::SampleToMat<InputSampleType>(input, sample); cv::Mat response; //(1, 1, CV_32FC1); m_ANNModel->predict(sample, response); float currentResponse = 0; float maxResponse = response.at<float> (0, 0); if (this->m_RegressionMode) { // MODE REGRESSION : only output first response target[0] = maxResponse; return target; } // MODE CLASSIFICATION : find the highest response float secondResponse = -1e10; target[0] = m_MatrixOfLabels.at<TOutputValue>(0); unsigned int nbClasses = m_MatrixOfLabels.size[1]; for (unsigned itLabel = 1; itLabel < nbClasses; ++itLabel) { currentResponse = response.at<float> (0, itLabel); if (currentResponse > maxResponse) { secondResponse = maxResponse; maxResponse = currentResponse; target[0] = m_MatrixOfLabels.at<TOutputValue>(itLabel); } else { if (currentResponse > secondResponse) { secondResponse = currentResponse; } } } if (quality != nullptr) { (*quality) = static_cast<ConfidenceValueType>(maxResponse) - static_cast<ConfidenceValueType>(secondResponse); } if (proba != nullptr && !this->m_ProbaIndex) itkExceptionMacro("Probability per class not available for this classifier !"); return target; } template<class TInputValue, class TOutputValue> void NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::Save(const std::string & filename, const std::string & name) { #ifdef OTB_OPENCV_3 cv::FileStorage fs(filename, cv::FileStorage::WRITE); fs << (name.empty() ? m_ANNModel->getDefaultName() : cv::String(name)) << "{"; m_ANNModel->write(fs); if (!m_MatrixOfLabels.empty()) { fs << "class_labels" << m_MatrixOfLabels; } fs << "}"; fs.release(); #else const char* lname = "my_nn"; if ( !name.empty() ) lname = name.c_str(); CvFileStorage* fs = nullptr; fs = cvOpenFileStorage(filename.c_str(), nullptr, CV_STORAGE_WRITE); if ( !fs ) { itkExceptionMacro("Could not open the file " << filename << " for writing"); } m_ANNModel->write(fs, lname); if (!m_MatrixOfLabels.empty()) { // cvWrite can't write cv::Mat auto tmpMat = CvMat(m_MatrixOfLabels); cvWrite(fs, "class_labels", &tmpMat); } cvReleaseFileStorage(&fs); #endif } template<class TInputValue, class TOutputValue> void NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::Load(const std::string & filename, const std::string & name) { #ifdef OTB_OPENCV_3 cv::FileStorage fs(filename, cv::FileStorage::READ); cv::FileNode model_node(name.empty() ? fs.getFirstTopLevelNode() : fs[name]); m_ANNModel->read(model_node); model_node["class_labels"] >> m_MatrixOfLabels; fs.release(); #else const char* lname = nullptr; if ( !name.empty() ) lname = name.c_str(); cv::FileNode model_node; cv::FileStorage fs(filename,cv::FileStorage::READ); if (!fs.isOpened()) { itkExceptionMacro("Could not open the file " << filename << " for reading"); } if( lname ) model_node = fs[lname]; else { cv::FileNode root = fs.root(); if ( root.size() > 0) { model_node = *(root.begin()); } } m_ANNModel->read(*fs,*model_node); model_node["class_labels"] >> m_MatrixOfLabels; fs.release(); #endif } template<class TInputValue, class TOutputValue> bool NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::CanReadFile(const std::string & file) { std::ifstream ifs; ifs.open(file); if (!ifs) { std::cerr << "Could not read file " << file << std::endl; return false; } while (!ifs.eof()) { std::string line; std::getline(ifs, line); if (line.find(CV_TYPE_NAME_ML_ANN_MLP) != std::string::npos #ifdef OTB_OPENCV_3 || line.find(m_ANNModel->getDefaultName()) != std::string::npos #endif ) { return true; } } ifs.close(); return false; } template<class TInputValue, class TOutputValue> bool NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::CanWriteFile(const std::string & itkNotUsed(file)) { return false; } template<class TInputValue, class TOutputValue> void NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::PrintSelf(std::ostream& os, itk::Indent indent) const { // Call superclass implementation Superclass::PrintSelf(os, indent); } } //end namespace otb #endif
remove debug cout
STY: remove debug cout
C++
apache-2.0
orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB
68a16d01bb72dfe7bf466de11ee3740f4f6a2d83
automated-tests/src/dali/dali-test-suite-utils/test-platform-abstraction.cpp
automated-tests/src/dali/dali-test-suite-utils/test-platform-abstraction.cpp
/* * Copyright (c) 2014 Samsung Electronics Co., Ltd. * * 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 "test-platform-abstraction.h" #include "dali-test-suite-utils.h" #include <dali/integration-api/bitmap.h> namespace Dali { /** * Constructor */ TestPlatformAbstraction::TestPlatformAbstraction() : mRequest(0), mDynamicsFactory(NULL) { Initialize(); } /** * Destructor */ TestPlatformAbstraction::~TestPlatformAbstraction() { delete mDynamicsFactory; } /** * @copydoc PlatformAbstraction::GetTimeMicroseconds() */ void TestPlatformAbstraction::GetTimeMicroseconds(unsigned int &seconds, unsigned int &microSeconds) { seconds = mSeconds; microSeconds = mMicroSeconds; mTrace.PushCall("GetTimeMicroseconds", ""); } /** * @copydoc PlatformAbstraction::Suspend() */ void TestPlatformAbstraction::Suspend() { mTrace.PushCall("Suspend", ""); } /** * @copydoc PlatformAbstraction::Resume() */ void TestPlatformAbstraction::Resume() { mTrace.PushCall("Resume", ""); } ImageDimensions TestPlatformAbstraction::GetClosestImageSize( const std::string& filename, ImageDimensions size, FittingMode::Type fittingMode, SamplingMode::Type samplingMode, bool orientationCorrection ) { ImageDimensions closestSize = ImageDimensions( mClosestSize.x, mClosestSize.y ); mTrace.PushCall("GetClosestImageSize", ""); return closestSize; } ImageDimensions TestPlatformAbstraction::GetClosestImageSize( Integration::ResourcePointer resourceBuffer, ImageDimensions size, FittingMode::Type fittingMode, SamplingMode::Type samplingMode, bool orientationCorrection ) { ImageDimensions closestSize = ImageDimensions( mClosestSize.x, mClosestSize.y ); mTrace.PushCall("GetClosestImageSize", ""); return closestSize; } /** * @copydoc PlatformAbstraction::LoadResource() */ void TestPlatformAbstraction::LoadResource(const Integration::ResourceRequest& request) { std::ostringstream out; out << "Type:" << request.GetType()->id << ", Path: " << request.GetPath() << std::endl ; mTrace.PushCall("LoadResource", out.str()); if(mRequest != NULL) { delete mRequest; tet_infoline ("Warning: multiple resource requests not handled by Test Suite. You may see unexpected errors"); } mRequest = new Integration::ResourceRequest(request); } Integration::ResourcePointer TestPlatformAbstraction::LoadResourceSynchronously( const Integration::ResourceType& resourceType, const std::string& resourcePath ) { mTrace.PushCall("LoadResourceSynchronously", ""); return mResources.loadedResource; } /** * @copydoc PlatformAbstraction::SaveResource() */ void TestPlatformAbstraction::SaveResource(const Integration::ResourceRequest& request) { mTrace.PushCall("SaveResource", ""); if(mRequest != NULL) { delete mRequest; tet_infoline ("Warning: multiple resource requests not handled by Test Suite. You may see unexpected errors"); } mRequest = new Integration::ResourceRequest(request); } /** * @copydoc PlatformAbstraction::CancelLoad() */ void TestPlatformAbstraction::CancelLoad(Integration::ResourceId id, Integration::ResourceTypeId typeId) { mTrace.PushCall("CancelLoad", ""); } /** * @copydoc PlatformAbstraction::GetResources() */ void TestPlatformAbstraction::GetResources(Integration::ResourceCache& cache) { mTrace.PushCall("GetResources", ""); if(mResources.loaded) { cache.LoadResponse( mResources.loadedId, mResources.loadedType, mResources.loadedResource, Integration::RESOURCE_COMPLETELY_LOADED ); } if(mResources.loadFailed) { cache.LoadFailed( mResources.loadFailedId, mResources.loadFailure ); } if(mResources.saved) { cache.SaveComplete( mResources.savedId, mResources.savedType ); } if(mResources.saveFailed) { cache.SaveFailed( mResources.saveFailedId, mResources.saveFailure ); } } /** * @copydoc PlatformAbstraction::IsLoading() */ bool TestPlatformAbstraction::IsLoading() { mTrace.PushCall("IsLoading", ""); return mIsLoadingResult; } /** * @copydoc PlatformAbstraction::GetDefaultFontDescription() */ void TestPlatformAbstraction::GetDefaultFontDescription( std::string& family, std::string& style ) const { mTrace.PushCall("GetDefaultFontFamily", ""); family = mGetDefaultFontFamilyResult; style = mGetDefaultFontStyleResult; } /** * @copydoc PlatformAbstraction::GetDefaultFontSize() */ int TestPlatformAbstraction::GetDefaultFontSize() const { mTrace.PushCall("GetDefaultFontSize", ""); return mGetDefaultFontSizeResult; } /** * @copydoc PlatformAbstraction::SetDpi() */ void TestPlatformAbstraction::SetDpi (unsigned int dpiHorizontal, unsigned int dpiVertical) { mTrace.PushCall("SetDpi", ""); } /** * @copydoc PlatformAbstraction::LoadFile() */ bool TestPlatformAbstraction::LoadFile( const std::string& filename, std::vector< unsigned char >& buffer ) const { mTrace.PushCall("LoadFile", ""); if( mLoadFileResult.loadResult ) { buffer = mLoadFileResult.buffer; } return mLoadFileResult.loadResult; } /** * @copydoc PlatformAbstraction::LoadShaderBinFile() */ bool TestPlatformAbstraction::LoadShaderBinFile( const std::string& filename, std::vector< unsigned char >& buffer ) const { mTrace.PushCall("LoadShaderBinFile", ""); if( mLoadFileResult.loadResult ) { buffer = mLoadFileResult.buffer; } return mLoadFileResult.loadResult; } /** * @copydoc PlatformAbstraction::SaveFile() */ bool TestPlatformAbstraction::SaveFile(const std::string& filename, std::vector< unsigned char >& buffer) const { mTrace.PushCall("SaveFile", ""); return false; } void TestPlatformAbstraction::JoinLoaderThreads() { mTrace.PushCall("JoinLoaderThreads", ""); } Integration::DynamicsFactory* TestPlatformAbstraction::GetDynamicsFactory() { mTrace.PushCall("GetDynamicsFactory", ""); if( mDynamicsFactory == NULL ) { mDynamicsFactory = new TestDynamicsFactory( mTrace ); } return mDynamicsFactory; } /** Call this every test */ void TestPlatformAbstraction::Initialize() { mTrace.Reset(); mTrace.Enable(true); memset(&mResources, 0, sizeof(Resources)); mSeconds=0; mMicroSeconds=0; mIsLoadingResult=false; if(mRequest) { delete mRequest; mRequest = 0; } } bool TestPlatformAbstraction::WasCalled(TestFuncEnum func) { switch(func) { case GetTimeMicrosecondsFunc: return mTrace.FindMethod("GetTimeMicroseconds"); case SuspendFunc: return mTrace.FindMethod("Suspend"); case ResumeFunc: return mTrace.FindMethod("Resume"); case LoadResourceFunc: return mTrace.FindMethod("LoadResource"); case SaveResourceFunc: return mTrace.FindMethod("SaveResource"); case LoadFileFunc: return mTrace.FindMethod("LoadFile"); case SaveFileFunc: return mTrace.FindMethod("SaveFile"); case CancelLoadFunc: return mTrace.FindMethod("CancelLoad"); case GetResourcesFunc: return mTrace.FindMethod("GetResources"); case IsLoadingFunc: return mTrace.FindMethod("IsLoading"); case SetDpiFunc: return mTrace.FindMethod("SetDpi"); case JoinLoaderThreadsFunc: return mTrace.FindMethod("JoinLoaderThreads"); case GetDynamicsFactoryFunc: return mTrace.FindMethod("GetDynamicsFactory"); } return false; } void TestPlatformAbstraction::SetGetTimeMicrosecondsResult(size_t sec, size_t usec) { mSeconds = sec; mMicroSeconds = usec; } void TestPlatformAbstraction::IncrementGetTimeResult(size_t milliseconds) { mMicroSeconds += milliseconds * 1000u; unsigned int additionalSeconds = mMicroSeconds / 1000000u; mSeconds += additionalSeconds; mMicroSeconds -= additionalSeconds * 1000000u; } void TestPlatformAbstraction::SetIsLoadingResult(bool result) { mIsLoadingResult = result; } void TestPlatformAbstraction::ClearReadyResources() { memset(&mResources, 0, sizeof(Resources)); } void TestPlatformAbstraction::SetResourceLoaded(Integration::ResourceId loadedId, Integration::ResourceTypeId loadedType, Integration::ResourcePointer loadedResource) { mResources.loaded = true; mResources.loadedId = loadedId; mResources.loadedType = loadedType; mResources.loadedResource = loadedResource; } void TestPlatformAbstraction::SetResourceLoadFailed(Integration::ResourceId id, Integration::ResourceFailure failure) { mResources.loadFailed = true; mResources.loadFailedId = id; mResources.loadFailure = failure; } void TestPlatformAbstraction::SetResourceSaved(Integration::ResourceId savedId, Integration::ResourceTypeId savedType) { mResources.saved = true; mResources.savedId = savedId; mResources.savedType = savedType; } void TestPlatformAbstraction::SetResourceSaveFailed(Integration::ResourceId id, Integration::ResourceFailure failure) { mResources.saveFailed = true; mResources.saveFailedId = id; mResources.saveFailure = failure; } Integration::ResourceRequest* TestPlatformAbstraction::GetRequest() { return mRequest; } void TestPlatformAbstraction::DiscardRequest() { delete mRequest; mRequest = NULL; } void TestPlatformAbstraction::SetClosestImageSize(const Vector2& size) { mClosestSize = size; } void TestPlatformAbstraction::SetLoadFileResult( bool result, std::vector< unsigned char >& buffer ) { mLoadFileResult.loadResult = result; if( result ) { mLoadFileResult.buffer = buffer; } } void TestPlatformAbstraction::SetSaveFileResult( bool result ) { mSaveFileResult = result; } } // namespace Dali
/* * Copyright (c) 2014 Samsung Electronics Co., Ltd. * * 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 "test-platform-abstraction.h" #include "dali-test-suite-utils.h" #include <dali/integration-api/bitmap.h> namespace Dali { /** * Constructor */ TestPlatformAbstraction::TestPlatformAbstraction() : mTrace(), mSeconds( 0u ), mMicroSeconds( 0u ), mIsLoadingResult( false ), mGetDefaultFontFamilyResult(), mGetDefaultFontStyleResult(), mGetDefaultFontSizeResult( 0 ), mResources(), mRequest( NULL ), mSize(), mClosestSize(), mLoadFileResult(), mSaveFileResult( false ), mDynamicsFactory( NULL ) { Initialize(); } /** * Destructor */ TestPlatformAbstraction::~TestPlatformAbstraction() { delete mDynamicsFactory; } /** * @copydoc PlatformAbstraction::GetTimeMicroseconds() */ void TestPlatformAbstraction::GetTimeMicroseconds(unsigned int &seconds, unsigned int &microSeconds) { seconds = mSeconds; microSeconds = mMicroSeconds; mTrace.PushCall("GetTimeMicroseconds", ""); } /** * @copydoc PlatformAbstraction::Suspend() */ void TestPlatformAbstraction::Suspend() { mTrace.PushCall("Suspend", ""); } /** * @copydoc PlatformAbstraction::Resume() */ void TestPlatformAbstraction::Resume() { mTrace.PushCall("Resume", ""); } ImageDimensions TestPlatformAbstraction::GetClosestImageSize( const std::string& filename, ImageDimensions size, FittingMode::Type fittingMode, SamplingMode::Type samplingMode, bool orientationCorrection ) { ImageDimensions closestSize = ImageDimensions( mClosestSize.x, mClosestSize.y ); mTrace.PushCall("GetClosestImageSize", ""); return closestSize; } ImageDimensions TestPlatformAbstraction::GetClosestImageSize( Integration::ResourcePointer resourceBuffer, ImageDimensions size, FittingMode::Type fittingMode, SamplingMode::Type samplingMode, bool orientationCorrection ) { ImageDimensions closestSize = ImageDimensions( mClosestSize.x, mClosestSize.y ); mTrace.PushCall("GetClosestImageSize", ""); return closestSize; } /** * @copydoc PlatformAbstraction::LoadResource() */ void TestPlatformAbstraction::LoadResource(const Integration::ResourceRequest& request) { std::ostringstream out; out << "Type:" << request.GetType()->id << ", Path: " << request.GetPath() << std::endl ; mTrace.PushCall("LoadResource", out.str()); if(mRequest != NULL) { delete mRequest; tet_infoline ("Warning: multiple resource requests not handled by Test Suite. You may see unexpected errors"); } mRequest = new Integration::ResourceRequest(request); } Integration::ResourcePointer TestPlatformAbstraction::LoadResourceSynchronously( const Integration::ResourceType& resourceType, const std::string& resourcePath ) { mTrace.PushCall("LoadResourceSynchronously", ""); return mResources.loadedResource; } /** * @copydoc PlatformAbstraction::SaveResource() */ void TestPlatformAbstraction::SaveResource(const Integration::ResourceRequest& request) { mTrace.PushCall("SaveResource", ""); if(mRequest != NULL) { delete mRequest; tet_infoline ("Warning: multiple resource requests not handled by Test Suite. You may see unexpected errors"); } mRequest = new Integration::ResourceRequest(request); } /** * @copydoc PlatformAbstraction::CancelLoad() */ void TestPlatformAbstraction::CancelLoad(Integration::ResourceId id, Integration::ResourceTypeId typeId) { mTrace.PushCall("CancelLoad", ""); } /** * @copydoc PlatformAbstraction::GetResources() */ void TestPlatformAbstraction::GetResources(Integration::ResourceCache& cache) { mTrace.PushCall("GetResources", ""); if(mResources.loaded) { cache.LoadResponse( mResources.loadedId, mResources.loadedType, mResources.loadedResource, Integration::RESOURCE_COMPLETELY_LOADED ); } if(mResources.loadFailed) { cache.LoadFailed( mResources.loadFailedId, mResources.loadFailure ); } if(mResources.saved) { cache.SaveComplete( mResources.savedId, mResources.savedType ); } if(mResources.saveFailed) { cache.SaveFailed( mResources.saveFailedId, mResources.saveFailure ); } } /** * @copydoc PlatformAbstraction::IsLoading() */ bool TestPlatformAbstraction::IsLoading() { mTrace.PushCall("IsLoading", ""); return mIsLoadingResult; } /** * @copydoc PlatformAbstraction::GetDefaultFontDescription() */ void TestPlatformAbstraction::GetDefaultFontDescription( std::string& family, std::string& style ) const { mTrace.PushCall("GetDefaultFontFamily", ""); family = mGetDefaultFontFamilyResult; style = mGetDefaultFontStyleResult; } /** * @copydoc PlatformAbstraction::GetDefaultFontSize() */ int TestPlatformAbstraction::GetDefaultFontSize() const { mTrace.PushCall("GetDefaultFontSize", ""); return mGetDefaultFontSizeResult; } /** * @copydoc PlatformAbstraction::SetDpi() */ void TestPlatformAbstraction::SetDpi (unsigned int dpiHorizontal, unsigned int dpiVertical) { mTrace.PushCall("SetDpi", ""); } /** * @copydoc PlatformAbstraction::LoadFile() */ bool TestPlatformAbstraction::LoadFile( const std::string& filename, std::vector< unsigned char >& buffer ) const { mTrace.PushCall("LoadFile", ""); if( mLoadFileResult.loadResult ) { buffer = mLoadFileResult.buffer; } return mLoadFileResult.loadResult; } /** * @copydoc PlatformAbstraction::LoadShaderBinFile() */ bool TestPlatformAbstraction::LoadShaderBinFile( const std::string& filename, std::vector< unsigned char >& buffer ) const { mTrace.PushCall("LoadShaderBinFile", ""); if( mLoadFileResult.loadResult ) { buffer = mLoadFileResult.buffer; } return mLoadFileResult.loadResult; } /** * @copydoc PlatformAbstraction::SaveFile() */ bool TestPlatformAbstraction::SaveFile(const std::string& filename, std::vector< unsigned char >& buffer) const { mTrace.PushCall("SaveFile", ""); return false; } void TestPlatformAbstraction::JoinLoaderThreads() { mTrace.PushCall("JoinLoaderThreads", ""); } Integration::DynamicsFactory* TestPlatformAbstraction::GetDynamicsFactory() { mTrace.PushCall("GetDynamicsFactory", ""); if( mDynamicsFactory == NULL ) { mDynamicsFactory = new TestDynamicsFactory( mTrace ); } return mDynamicsFactory; } /** Call this every test */ void TestPlatformAbstraction::Initialize() { mTrace.Reset(); mTrace.Enable(true); memset(&mResources, 0, sizeof(Resources)); mSeconds=0; mMicroSeconds=0; mIsLoadingResult=false; if(mRequest) { delete mRequest; mRequest = 0; } } bool TestPlatformAbstraction::WasCalled(TestFuncEnum func) { switch(func) { case GetTimeMicrosecondsFunc: return mTrace.FindMethod("GetTimeMicroseconds"); case SuspendFunc: return mTrace.FindMethod("Suspend"); case ResumeFunc: return mTrace.FindMethod("Resume"); case LoadResourceFunc: return mTrace.FindMethod("LoadResource"); case SaveResourceFunc: return mTrace.FindMethod("SaveResource"); case LoadFileFunc: return mTrace.FindMethod("LoadFile"); case SaveFileFunc: return mTrace.FindMethod("SaveFile"); case CancelLoadFunc: return mTrace.FindMethod("CancelLoad"); case GetResourcesFunc: return mTrace.FindMethod("GetResources"); case IsLoadingFunc: return mTrace.FindMethod("IsLoading"); case SetDpiFunc: return mTrace.FindMethod("SetDpi"); case JoinLoaderThreadsFunc: return mTrace.FindMethod("JoinLoaderThreads"); case GetDynamicsFactoryFunc: return mTrace.FindMethod("GetDynamicsFactory"); } return false; } void TestPlatformAbstraction::SetGetTimeMicrosecondsResult(size_t sec, size_t usec) { mSeconds = sec; mMicroSeconds = usec; } void TestPlatformAbstraction::IncrementGetTimeResult(size_t milliseconds) { mMicroSeconds += milliseconds * 1000u; unsigned int additionalSeconds = mMicroSeconds / 1000000u; mSeconds += additionalSeconds; mMicroSeconds -= additionalSeconds * 1000000u; } void TestPlatformAbstraction::SetIsLoadingResult(bool result) { mIsLoadingResult = result; } void TestPlatformAbstraction::ClearReadyResources() { memset(&mResources, 0, sizeof(Resources)); } void TestPlatformAbstraction::SetResourceLoaded(Integration::ResourceId loadedId, Integration::ResourceTypeId loadedType, Integration::ResourcePointer loadedResource) { mResources.loaded = true; mResources.loadedId = loadedId; mResources.loadedType = loadedType; mResources.loadedResource = loadedResource; } void TestPlatformAbstraction::SetResourceLoadFailed(Integration::ResourceId id, Integration::ResourceFailure failure) { mResources.loadFailed = true; mResources.loadFailedId = id; mResources.loadFailure = failure; } void TestPlatformAbstraction::SetResourceSaved(Integration::ResourceId savedId, Integration::ResourceTypeId savedType) { mResources.saved = true; mResources.savedId = savedId; mResources.savedType = savedType; } void TestPlatformAbstraction::SetResourceSaveFailed(Integration::ResourceId id, Integration::ResourceFailure failure) { mResources.saveFailed = true; mResources.saveFailedId = id; mResources.saveFailure = failure; } Integration::ResourceRequest* TestPlatformAbstraction::GetRequest() { return mRequest; } void TestPlatformAbstraction::DiscardRequest() { delete mRequest; mRequest = NULL; } void TestPlatformAbstraction::SetClosestImageSize(const Vector2& size) { mClosestSize = size; } void TestPlatformAbstraction::SetLoadFileResult( bool result, std::vector< unsigned char >& buffer ) { mLoadFileResult.loadResult = result; if( result ) { mLoadFileResult.buffer = buffer; } } void TestPlatformAbstraction::SetSaveFileResult( bool result ) { mSaveFileResult = result; } } // namespace Dali
Fix Klocwork issue.
Fix Klocwork issue. Change-Id: I134af7bf46aec9226f406d6f7ec81103fef52150 Signed-off-by: Victor Cebollada <[email protected]>
C++
apache-2.0
dalihub/dali-core,dalihub/dali-core,pwisbey/dali-core,pwisbey/dali-core,dalihub/dali-core,pwisbey/dali-core,pwisbey/dali-core,dalihub/dali-core
b188058fd5f5ec23b90045af2ff451235de85f02
01/PrintAll.cpp
01/PrintAll.cpp
#include <iostream> #include "PrintAll.h" using namespace std; void samples::PrintEverything() { int integer = 10; float decimal = 1.5f; char letter = 'A'; char string[] = "Hello, world!"; cout << integer << endl; cout << decimal << endl; cout << letter << endl; cout << string << endl; return 0; }
#include "PrintAll.h"
Revert "no message"
Revert "no message" This reverts commit 3947e5cbf62d301e59921aaa5181a43bfe21c435.
C++
mit
popekim/CppSamples
602ca6492750a87ef110a7bccf07b5bd574859ff
Game/Square.cpp
Game/Square.cpp
#include "Square.h" Square::Square() { // Vertices vertexNr = 4; vertexData = new Vertex[vertexNr]; vertexData[0] = { glm::vec3(0.5f, 0.5f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec2(1.0f, 0.0f) }; vertexData[1] = { glm::vec3(-0.5f, -0.5f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec2(0.0f, 1.0f) }; vertexData[2] = { glm::vec3(0.5f, -0.5f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec2(1.0f, 1.0f) }; vertexData[3] = { glm::vec3(-0.5f, 0.5f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec2(0.0f, 0.0f) }; // Vertexindices indexNr = 6; indexData = new unsigned int[indexNr]; indexData[0] = 0; indexData[1] = 1; indexData[2] = 2; indexData[3] = 0; indexData[4] = 3; indexData[5] = 1; generateBuffers(); generateVertexArray(); } Square::~Square() { delete[] vertexData; delete[] indexData; } Geometry::Vertex* Square::vertices() const { return vertexData; } unsigned int Square::vertexCount() const { return vertexNr; } unsigned int* Square::indices() const { return indexData; } unsigned int Square::indexCount() const { return indexNr; }
#include "Square.h" Square::Square() { // Vertices vertexNr = 4; vertexData = new Vertex[vertexNr]; vertexData[0] = { glm::vec3(0.5f, 0.5f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec2(1.0f, 0.0f), glm::vec3(1.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f) }; vertexData[1] = { glm::vec3(-0.5f, -0.5f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec2(0.0f, 1.0f), glm::vec3(1.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f) }; vertexData[2] = { glm::vec3(0.5f, -0.5f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec2(1.0f, 1.0f), glm::vec3(1.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f) }; vertexData[3] = { glm::vec3(-0.5f, 0.5f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec2(0.0f, 0.0f), glm::vec3(1.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f) }; // Vertexindices indexNr = 6; indexData = new unsigned int[indexNr]; indexData[0] = 0; indexData[1] = 1; indexData[2] = 2; indexData[3] = 0; indexData[4] = 3; indexData[5] = 1; generateBuffers(); generateVertexArray(); } Square::~Square() { delete[] vertexData; delete[] indexData; } Geometry::Vertex* Square::vertices() const { return vertexData; } unsigned int Square::vertexCount() const { return vertexNr; } unsigned int* Square::indices() const { return indexData; } unsigned int Square::indexCount() const { return indexNr; }
Add tangents and bitangents to Square
Add tangents and bitangents to Square
C++
mit
NinjaDanz3r/NinjaOctopushBurgersOfDoom,NinjaDanz3r/NinjaOctopushBurgersOfDoom
236a805fd034a36908a7cdd8aa3d5fe3c6851828
HumanPlayer.cpp
HumanPlayer.cpp
#include <cstdlib> #include <cstdio> #include <list> #include <cctype> #include "HumanPlayer.h" #include "ChessBoard.h" HumanPlayer::HumanPlayer(int color) : ChessPlayer(color) {} HumanPlayer::~HumanPlayer() {} bool HumanPlayer::getMove(ChessBoard & board, Move & move) { list<Move> regulars, nulls; char * input; bool found, done = false; // get all moves board.getMoves(this->color, regulars, regulars, nulls); while(!done) { found = false; for(list<Move>::iterator it = regulars.begin(); it != regulars.end() && !found; ++it) { board.move(*it); if(!board.isVulnerable((this->color ? board.black_king_pos : board.white_king_pos), this->color)) { found = true; } board.undoMove(*it); } if(!found) return false; while(true) { printf("\n>>"); if((input = readInput()) == NULL) { printf("Could not read input. Try again.\n"); continue; } if(!processInput(input, move)) { printf("Error while parsing input. Try again.\n"); continue; } break; } found = false; for(list<Move>::iterator it = regulars.begin(); it != regulars.end(); ++it) { if(move.from == (*it).from && move.to == (*it).to) { move = *it; found = true; break; } } if(!found) { printf("Invalid move. Try again.\n"); continue; } board.move(move); if(board.isVulnerable(this->color ? board.black_king_pos : board.white_king_pos, this->color)) { printf("Invalid move, putting your king in jeopardy.\n"); } else { done = true; } board.undoMove(move); } return true; } char * HumanPlayer::readInput(void) { int buffsize = 8, c, i; char * buffer, * tmp; // allocate buffer buffer = reinterpret_cast<char*>(malloc(buffsize)); if(!buffer) { return NULL; } // read one line for(i = 0; (c = fgetc(stdin)) != '\n'; i++) { if(i >= buffsize - 1) { if((buffsize << 1) < buffsize) { fprintf(stderr, "HumanPlayer::readInput(): " \ "Someone is trying a buffer overrun.\n"); free(buffer); return NULL; } tmp = reinterpret_cast<char*>(realloc(buffer, buffsize<<1)); if(!tmp) { free(buffer); return NULL; } buffer = tmp; buffsize <<= 1; } buffer[i] = c; } // terminate buffer buffer[i] = '\0'; return buffer; } bool HumanPlayer::processInput(char * buf, Move & move) { int i = 0, j, l, n; // skip whitespace while(true) { if(buf[i] == '\0') { free(buf); return false; } else if(!isspace(buf[i])) { break; } else { i++; } } // convert from sth. like "b1c3" for(j = 0; j < 2; j++) { l = buf[i++]; n = buf[i++]; if(l >= 'a' && l <= 'h') { l = l - 'a'; } else if(l >= 'A' && l <= 'H') { l = l - 'A'; } else { free(buf); return false; } if(n >= '1' && n <= '8') { n = n - '1'; } else { free(buf); return false; } if(j == 0) move.from = n * 8 + l; else move.to = n * 8 + l; } free(buf); return true; }
#include <cstdlib> #include <cstdio> #include <list> #include <cctype> #include <cstring> #include "HumanPlayer.h" #include "ChessBoard.h" HumanPlayer::HumanPlayer(int color) : ChessPlayer(color) {} HumanPlayer::~HumanPlayer() {} bool HumanPlayer::getMove(ChessBoard & board, Move & move) { list<Move> regulars, nulls; char * input; bool found, done = false; // get all moves board.getMoves(this->color, regulars, regulars, nulls); while(!done) { found = false; for(list<Move>::iterator it = regulars.begin(); it != regulars.end() && !found; ++it) { board.move(*it); if(!board.isVulnerable((this->color ? board.black_king_pos : board.white_king_pos), this->color)) { found = true; } board.undoMove(*it); } if(!found) return false; while(true) { printf("\n>>"); if((input = readInput()) == NULL) { printf("Could not read input. Try again.\n"); continue; } if(!processInput(input, move)) { printf("Error while parsing input. Try again.\n"); continue; } break; } found = false; for(list<Move>::iterator it = regulars.begin(); it != regulars.end(); ++it) { if(move.from == (*it).from && move.to == (*it).to) { move = *it; found = true; break; } } if(!found) { printf("Invalid move. Try again.\n"); continue; } board.move(move); if(board.isVulnerable(this->color ? board.black_king_pos : board.white_king_pos, this->color)) { printf("Invalid move, putting your king in jeopardy.\n"); } else { done = true; } board.undoMove(move); } return true; } char * HumanPlayer::readInput(void) { int buffsize = 8, c, i; char * buffer, * tmp; // allocate buffer buffer = reinterpret_cast<char*>(malloc(buffsize)); if(!buffer) { return NULL; } // read one line for(i = 0; (c = fgetc(stdin)) != '\n'; i++) { if(i >= buffsize - 1) { if((buffsize << 1) < buffsize) { fprintf(stderr, "HumanPlayer::readInput(): " \ "Someone is trying a buffer overrun.\n"); free(buffer); return NULL; } tmp = reinterpret_cast<char*>(realloc(buffer, buffsize<<1)); if(!tmp) { free(buffer); return NULL; } buffer = tmp; buffsize <<= 1; } buffer[i] = c; } // terminate buffer buffer[i] = '\0'; return buffer; } bool HumanPlayer::processInput(char * buf, Move & move) { int i = 0, j, l, n; // skip whitespace while(true) { if(buf[i] == '\0') { free(buf); return false; } else if(!isspace(buf[i])) { break; } else { i++; } } if(strncmp(&buf[i], "quit", 4) == 0) exit(0); // convert from sth. like "b1c3" for(j = 0; j < 2; j++) { l = buf[i++]; n = buf[i++]; if(l >= 'a' && l <= 'h') { l = l - 'a'; } else if(l >= 'A' && l <= 'H') { l = l - 'A'; } else { free(buf); return false; } if(n >= '1' && n <= '8') { n = n - '1'; } else { free(buf); return false; } if(j == 0) move.from = n * 8 + l; else move.to = n * 8 + l; } free(buf); return true; }
Allow user to exit by typing 'quit'
Allow user to exit by typing 'quit'
C++
bsd-2-clause
tobijk/simple-chess,tobijk/simple-chess
3742fa1b670e7478c930fd93d502972edabd685c
KTp/contact.cpp
KTp/contact.cpp
/* * Copyright (C) 2012 David Edmundson <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "contact.h" #include <TelepathyQt/ContactManager> #include <TelepathyQt/Connection> #include <TelepathyQt/ContactCapabilities> #include <TelepathyQt/AvatarData> #include <TelepathyQt/Utils> #include <QBitmap> #include <QPixmap> #include <QPixmapCache> #include <KIconLoader> #include <KConfigGroup> #include <KConfig> #include "capabilities-hack-private.h" KTp::Contact::Contact(Tp::ContactManager *manager, const Tp::ReferencedHandles &handle, const Tp::Features &requestedFeatures, const QVariantMap &attributes) : Tp::Contact(manager, handle, requestedFeatures, attributes) { m_accountUniqueIdentifier = manager->connection()->property("accountUID").toString(); connect(manager->connection().data(), SIGNAL(destroyed()), SIGNAL(invalidated())); connect(manager->connection().data(), SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)), SIGNAL(invalidated())); connect(this, SIGNAL(avatarTokenChanged(QString)), SLOT(invalidateAvatarCache())); connect(this, SIGNAL(avatarDataChanged(Tp::AvatarData)), SLOT(invalidateAvatarCache())); connect(this, SIGNAL(presenceChanged(Tp::Presence)), SIGNAL(onPresenceChanged(Tp::Presence))); } void KTp::Contact::onPresenceChanged(const Tp::Presence &presence) { Q_UNUSED(presence) /* Temporary workaround for upstream bug https://bugs.freedesktop.org/show_bug.cgi?id=55883) * Close https://bugs.kde.org/show_bug.cgi?id=308217 when fixed upstream */ Q_EMIT clientTypesChanged(clientTypes()); } QString KTp::Contact::accountUniqueIdentifier() const { return m_accountUniqueIdentifier; } KTp::Presence KTp::Contact::presence() const { return KTp::Presence(Tp::Contact::presence()); } bool KTp::Contact::textChatCapability() const { if (!manager() || !manager()->connection()) { return false; } return capabilities().textChats(); } bool KTp::Contact::audioCallCapability() const { if (!manager() || !manager()->connection()) { return false; } Tp::ConnectionPtr connection = manager()->connection(); bool contactCanStreamAudio = CapabilitiesHackPrivate::audioCalls( capabilities(), connection->cmName()); bool selfCanStreamAudio = CapabilitiesHackPrivate::audioCalls( connection->selfContact()->capabilities(), connection->cmName()); return contactCanStreamAudio && selfCanStreamAudio; } bool KTp::Contact::videoCallCapability() const { if (!manager() || !manager()->connection()) { return false; } Tp::ConnectionPtr connection = manager()->connection(); bool contactCanStreamVideo = CapabilitiesHackPrivate::videoCalls( capabilities(), connection->cmName()); bool selfCanStreamVideo = CapabilitiesHackPrivate::videoCalls( connection->selfContact()->capabilities(), connection->cmName()); return contactCanStreamVideo && selfCanStreamVideo; } bool KTp::Contact::fileTransferCapability() const { if (!manager() || !manager()->connection()) { return false; } bool contactCanHandleFiles = capabilities().fileTransfers(); bool selfCanHandleFiles = manager()->connection()->selfContact()->capabilities().fileTransfers(); return contactCanHandleFiles && selfCanHandleFiles; } bool KTp::Contact::collaborativeEditingCapability() const { if (!manager() || !manager()->connection()) { return false; } static const QString collab(QLatin1String("infinote")); bool selfCanShare = manager()->connection()->selfContact()->capabilities().streamTubes(collab); bool otherCanShare = capabilities().streamTubes(collab); return selfCanShare && otherCanShare; } QStringList KTp::Contact::dbusTubeServicesCapability() const { if (!manager() || !manager()->connection()) { return QStringList(); } return getCommonElements(capabilities().dbusTubeServices(), manager()->connection()->selfContact()->capabilities().dbusTubeServices()); } QStringList KTp::Contact::streamTubeServicesCapability() const { if (!manager() || !manager()->connection()) { return QStringList(); } return getCommonElements(capabilities().streamTubeServices(), manager()->connection()->selfContact()->capabilities().streamTubeServices()); } QStringList KTp::Contact::clientTypes() const { /* Temporary workaround for upstream bug https://bugs.freedesktop.org/show_bug.cgi?id=55883) * Close https://bugs.kde.org/show_bug.cgi?id=308217 when fixed upstream */ if (Tp::Contact::presence().type() == Tp::ConnectionPresenceTypeOffline) { return QStringList(); } //supress any errors trying to access ClientTypes when we don't have them if (! actualFeatures().contains(Tp::Contact::FeatureClientTypes)) { return QStringList(); } return Tp::Contact::clientTypes(); } QPixmap KTp::Contact::avatarPixmap() { QPixmap avatar; //check pixmap cache for the avatar, if not present, load the avatar if (!QPixmapCache::find(keyCache(), avatar)){ QString file = avatarData().fileName; //if contact does not provide path, let's see if we have avatar for the stored token if (file.isEmpty()) { KConfig config(QLatin1String("ktelepathy-avatarsrc")); KConfigGroup avatarTokenGroup = config.group(id()); QString avatarToken = avatarTokenGroup.readEntry(QLatin1String("avatarToken")); //only bother loading the pixmap if the token is not empty if (!avatarToken.isEmpty()) { avatar.load(buildAvatarPath(avatarToken)); } } else { avatar.load(file); } //if neither above succeeded, we need to load the icon if (avatar.isNull()) { avatar = KIconLoader::global()->loadIcon(QLatin1String("im-user"), KIconLoader::NoGroup, 96); } //if the contact is offline, gray it out if (presence().type() == Tp::ConnectionPresenceTypeOffline) { avatarToGray(avatar); } //insert the contact into pixmap cache for faster lookup QPixmapCache::insert(keyCache(), avatar); } return avatar; } void KTp::Contact::avatarToGray(QPixmap &avatar) { QImage image = avatar.toImage(); QPixmap alpha= avatar.alphaChannel(); for (int i = 0; i < image.width(); ++i) { for (int j = 0; j < image.height(); ++j) { int colour = qGray(image.pixel(i, j)); image.setPixel(i, j, qRgb(colour, colour, colour)); } } avatar = avatar.fromImage(image); avatar.setAlphaChannel(alpha); } QString KTp::Contact::keyCache() const { return id() + (presence().type() == Tp::ConnectionPresenceTypeOffline ? QLatin1String("-offline") : QLatin1String("-online")); } QString KTp::Contact::buildAvatarPath(const QString &avatarToken) { QString cacheDir = QString::fromLatin1(qgetenv("XDG_CACHE_HOME")); if (cacheDir.isEmpty()) { cacheDir = QString::fromLatin1("%1/.cache").arg(QLatin1String(qgetenv("HOME"))); } if (manager().isNull()) { return QString(); } if (manager()->connection().isNull()) { return QString(); } Tp::ConnectionPtr conn = manager()->connection(); QString path = QString::fromLatin1("%1/telepathy/avatars/%2/%3"). arg(cacheDir).arg(conn->cmName()).arg(conn->protocolName()); QString avatarFileName = QString::fromLatin1("%1/%2").arg(path).arg(Tp::escapeAsIdentifier(avatarToken)); return avatarFileName; } void KTp::Contact::invalidateAvatarCache() { QPixmapCache::remove(id() + QLatin1String("-offline")); QPixmapCache::remove(id() + QLatin1String("-online")); } QStringList KTp::Contact::getCommonElements(const QStringList &list1, const QStringList &list2) { /* QStringList::contains(QString) perform iterative comparsion, so there is no reason * to select smaller list as base for this cycle. */ QStringList commonElements; Q_FOREACH(const QString &i, list1) { if (list2.contains(i)) { commonElements << i; } } return commonElements; }
/* * Copyright (C) 2012 David Edmundson <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "contact.h" #include <TelepathyQt/ContactManager> #include <TelepathyQt/Connection> #include <TelepathyQt/ContactCapabilities> #include <TelepathyQt/AvatarData> #include <TelepathyQt/Utils> #include <QBitmap> #include <QPixmap> #include <QPixmapCache> #include <KIconLoader> #include <KConfigGroup> #include <KConfig> #include "capabilities-hack-private.h" KTp::Contact::Contact(Tp::ContactManager *manager, const Tp::ReferencedHandles &handle, const Tp::Features &requestedFeatures, const QVariantMap &attributes) : Tp::Contact(manager, handle, requestedFeatures, attributes) { m_accountUniqueIdentifier = manager->connection()->property("accountUID").toString(); connect(manager->connection().data(), SIGNAL(destroyed()), SIGNAL(invalidated())); connect(manager->connection().data(), SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)), SIGNAL(invalidated())); connect(this, SIGNAL(avatarTokenChanged(QString)), SLOT(invalidateAvatarCache())); connect(this, SIGNAL(avatarDataChanged(Tp::AvatarData)), SLOT(invalidateAvatarCache())); connect(this, SIGNAL(presenceChanged(Tp::Presence)), SLOT(onPresenceChanged(Tp::Presence))); } void KTp::Contact::onPresenceChanged(const Tp::Presence &presence) { Q_UNUSED(presence) /* Temporary workaround for upstream bug https://bugs.freedesktop.org/show_bug.cgi?id=55883) * Close https://bugs.kde.org/show_bug.cgi?id=308217 when fixed upstream */ Q_EMIT clientTypesChanged(clientTypes()); } QString KTp::Contact::accountUniqueIdentifier() const { return m_accountUniqueIdentifier; } KTp::Presence KTp::Contact::presence() const { return KTp::Presence(Tp::Contact::presence()); } bool KTp::Contact::textChatCapability() const { if (!manager() || !manager()->connection()) { return false; } return capabilities().textChats(); } bool KTp::Contact::audioCallCapability() const { if (!manager() || !manager()->connection()) { return false; } Tp::ConnectionPtr connection = manager()->connection(); bool contactCanStreamAudio = CapabilitiesHackPrivate::audioCalls( capabilities(), connection->cmName()); bool selfCanStreamAudio = CapabilitiesHackPrivate::audioCalls( connection->selfContact()->capabilities(), connection->cmName()); return contactCanStreamAudio && selfCanStreamAudio; } bool KTp::Contact::videoCallCapability() const { if (!manager() || !manager()->connection()) { return false; } Tp::ConnectionPtr connection = manager()->connection(); bool contactCanStreamVideo = CapabilitiesHackPrivate::videoCalls( capabilities(), connection->cmName()); bool selfCanStreamVideo = CapabilitiesHackPrivate::videoCalls( connection->selfContact()->capabilities(), connection->cmName()); return contactCanStreamVideo && selfCanStreamVideo; } bool KTp::Contact::fileTransferCapability() const { if (!manager() || !manager()->connection()) { return false; } bool contactCanHandleFiles = capabilities().fileTransfers(); bool selfCanHandleFiles = manager()->connection()->selfContact()->capabilities().fileTransfers(); return contactCanHandleFiles && selfCanHandleFiles; } bool KTp::Contact::collaborativeEditingCapability() const { if (!manager() || !manager()->connection()) { return false; } static const QString collab(QLatin1String("infinote")); bool selfCanShare = manager()->connection()->selfContact()->capabilities().streamTubes(collab); bool otherCanShare = capabilities().streamTubes(collab); return selfCanShare && otherCanShare; } QStringList KTp::Contact::dbusTubeServicesCapability() const { if (!manager() || !manager()->connection()) { return QStringList(); } return getCommonElements(capabilities().dbusTubeServices(), manager()->connection()->selfContact()->capabilities().dbusTubeServices()); } QStringList KTp::Contact::streamTubeServicesCapability() const { if (!manager() || !manager()->connection()) { return QStringList(); } return getCommonElements(capabilities().streamTubeServices(), manager()->connection()->selfContact()->capabilities().streamTubeServices()); } QStringList KTp::Contact::clientTypes() const { /* Temporary workaround for upstream bug https://bugs.freedesktop.org/show_bug.cgi?id=55883) * Close https://bugs.kde.org/show_bug.cgi?id=308217 when fixed upstream */ if (Tp::Contact::presence().type() == Tp::ConnectionPresenceTypeOffline) { return QStringList(); } //supress any errors trying to access ClientTypes when we don't have them if (! actualFeatures().contains(Tp::Contact::FeatureClientTypes)) { return QStringList(); } return Tp::Contact::clientTypes(); } QPixmap KTp::Contact::avatarPixmap() { QPixmap avatar; //check pixmap cache for the avatar, if not present, load the avatar if (!QPixmapCache::find(keyCache(), avatar)){ QString file = avatarData().fileName; //if contact does not provide path, let's see if we have avatar for the stored token if (file.isEmpty()) { KConfig config(QLatin1String("ktelepathy-avatarsrc")); KConfigGroup avatarTokenGroup = config.group(id()); QString avatarToken = avatarTokenGroup.readEntry(QLatin1String("avatarToken")); //only bother loading the pixmap if the token is not empty if (!avatarToken.isEmpty()) { avatar.load(buildAvatarPath(avatarToken)); } } else { avatar.load(file); } //if neither above succeeded, we need to load the icon if (avatar.isNull()) { avatar = KIconLoader::global()->loadIcon(QLatin1String("im-user"), KIconLoader::NoGroup, 96); } //if the contact is offline, gray it out if (presence().type() == Tp::ConnectionPresenceTypeOffline) { avatarToGray(avatar); } //insert the contact into pixmap cache for faster lookup QPixmapCache::insert(keyCache(), avatar); } return avatar; } void KTp::Contact::avatarToGray(QPixmap &avatar) { QImage image = avatar.toImage(); QPixmap alpha= avatar.alphaChannel(); for (int i = 0; i < image.width(); ++i) { for (int j = 0; j < image.height(); ++j) { int colour = qGray(image.pixel(i, j)); image.setPixel(i, j, qRgb(colour, colour, colour)); } } avatar = avatar.fromImage(image); avatar.setAlphaChannel(alpha); } QString KTp::Contact::keyCache() const { return id() + (presence().type() == Tp::ConnectionPresenceTypeOffline ? QLatin1String("-offline") : QLatin1String("-online")); } QString KTp::Contact::buildAvatarPath(const QString &avatarToken) { QString cacheDir = QString::fromLatin1(qgetenv("XDG_CACHE_HOME")); if (cacheDir.isEmpty()) { cacheDir = QString::fromLatin1("%1/.cache").arg(QLatin1String(qgetenv("HOME"))); } if (manager().isNull()) { return QString(); } if (manager()->connection().isNull()) { return QString(); } Tp::ConnectionPtr conn = manager()->connection(); QString path = QString::fromLatin1("%1/telepathy/avatars/%2/%3"). arg(cacheDir).arg(conn->cmName()).arg(conn->protocolName()); QString avatarFileName = QString::fromLatin1("%1/%2").arg(path).arg(Tp::escapeAsIdentifier(avatarToken)); return avatarFileName; } void KTp::Contact::invalidateAvatarCache() { QPixmapCache::remove(id() + QLatin1String("-offline")); QPixmapCache::remove(id() + QLatin1String("-online")); } QStringList KTp::Contact::getCommonElements(const QStringList &list1, const QStringList &list2) { /* QStringList::contains(QString) perform iterative comparsion, so there is no reason * to select smaller list as base for this cycle. */ QStringList commonElements; Q_FOREACH(const QString &i, list1) { if (list2.contains(i)) { commonElements << i; } } return commonElements; }
Fix signal connection
Fix signal connection
C++
lgpl-2.1
KDE/ktp-common-internals,KDE/ktp-common-internals,KDE/ktp-common-internals
38ef048d761817e8564051abcd3055c397f7e737
test/AppTest/src/AppTestApp.cpp
test/AppTest/src/AppTestApp.cpp
#include "cinder/app/App.h" #include "cinder/app/RendererGl.h" #include "cinder/gl/gl.h" #include "cinder/gl/Texture.h" #include "cinder/Log.h" #include "cinder/CinderAssert.h" #include "cinder/ImageIo.h" #include "cinder/Text.h" #include "cinder/Utilities.h" #include "Resources.h" #include <boost/format.hpp> using namespace ci; using namespace ci::app; using namespace std; void prepareSettings( App::Settings *settings ) { CI_LOG_I( "bang" ); const auto &args = settings->getCommandLineArgs(); if( ! args.empty() ) { CI_LOG_I( "command line args: " ); for( size_t i = 0; i < args.size(); i++ ) console() << "\t[" << i << "] " << args[i] << endl; } CI_LOG_I( "environment vars: " ); const auto &envVars = getEnvironmentVariables(); for( auto &env : envVars ) CI_LOG_I( "{" << env.first << "} = {" << env.second << "}" ); settings->setWindowPos( 50, 50 ); settings->setWindowSize( 900, 500 ); settings->setHighDensityDisplayEnabled(); // settings->setResizable( false ); // settings->setBorderless(); // settings->setAlwaysOnTop(); // settings->setMultiTouchEnabled(); // settings->setMultiTouchEnabled( false ); // settings->disableFrameRate(); // settings->setFrameRate( 20 ); // settings->setTitle( "Blarg" ); // FIXME: seems broken on mac, but did it ever work? // settings->setShouldQuit(); #if defined( CINDER_COCOA_TOUCH ) settings->setStatusBarEnabled( false ); // FIXME: status bar is always visible? #endif #if defined( CINDER_MSW ) settings->setConsoleWindowEnabled(); #endif // test loading an asset before application has been instanciated: auto asset = loadAsset( "mustache-green.png" ); CI_ASSERT( asset ); } struct SomeMemberObj { gl::TextureRef mTex; SomeMemberObj() { CI_LOG_I( "bang" ); auto resource = loadResource( RES_IMAGE ); mTex = gl::Texture::create( loadImage( resource ) ); CI_CHECK_GL(); } }; class AppTestApp : public App { public: AppTestApp(); ~AppTestApp(); void setup() override; void keyDown( KeyEvent event ) override; void mouseDown( MouseEvent event ) override; void touchesBegan( TouchEvent event ) override; void touchesMoved( TouchEvent event ) override; void touchesEnded( TouchEvent event ) override; void resize() override; void update() override; void draw() override; void cleanup() override; void drawInfo(); SomeMemberObj mSomeMemberObj; gl::TextureRef mTexStartup, mTexAsset, mTexResource; }; AppTestApp::AppTestApp() { CI_LOG_I( "bang" ); // Surface8u surface( 140, 140, false ); // Surface8u::Iter iter = surface.getIter(); // while( iter.line() ) { // while( iter.pixel() ) { // iter.r() = 0; // iter.g() = iter.x(); // iter.b() = iter.y(); // } // } // mTexStartup = gl::Texture::create( surface ); auto asset = loadAsset( "mustache-green.png" ); mTexStartup = gl::Texture::create( loadImage( asset ) ); CI_CHECK_GL(); } AppTestApp::~AppTestApp() { CI_LOG_I( "bang" ); } void AppTestApp::setup() { CI_LOG_I( "bang" ); auto asset = loadAsset( "mustache-green.png" ); mTexAsset = gl::Texture::create( loadImage( asset ) ); auto resource = loadResource( RES_IMAGE ); mTexResource = gl::Texture::create( loadImage( resource ) ); gl::enableAlphaBlending(); CI_LOG_I( "target fps: " << getFrameRate() ); CI_CHECK_GL(); CI_LOG_I( "complete" ); } void AppTestApp::keyDown( KeyEvent event ) { if( event.getChar() == 'f' ) { setFullScreen( ! isFullScreen() ); } else if( event.getChar() == 'o' ) { auto filePath = getOpenFilePath(); CI_LOG_I( "result of getOpenFilePath(): " << filePath ); } else if( event.getChar() == 'p' ) { auto filePath = getFolderPath(); CI_LOG_I( "result of getFolderPath(): " << filePath ); } else if( event.getChar() == 's' ) { auto filePath = getSaveFilePath(); CI_LOG_I( "result of getSaveFilePath(): " << filePath ); } } void AppTestApp::mouseDown( MouseEvent event ) { CI_LOG_I( "mouse pos: " << event.getPos() ); } void AppTestApp::touchesBegan( TouchEvent event ) { const auto &touches = event.getTouches(); CI_LOG_I( "num touches:" << touches.size() ); for( size_t i = 0; i < touches.size(); i++ ) console() << "\t\t[" << i << "] pos: " << touches.at( i ).getPos() << endl; } void AppTestApp::touchesMoved( TouchEvent event ) { const auto &touches = event.getTouches(); CI_LOG_I( "num touches:" << touches.size() ); for( size_t i = 0; i < touches.size(); i++ ) console() << "\t\t[" << i << "] pos: " << touches.at( i ).getPos() << endl; } void AppTestApp::touchesEnded( TouchEvent event ) { const auto &touches = event.getTouches(); CI_LOG_I( "num touches: " << touches.size() ); for( size_t i = 0; i < touches.size(); i++ ) console() << "\t\t[" << i << "] pos: " << touches.at( i ).getPos() << endl; } void AppTestApp::resize() { CI_LOG_I( "window pos: " << getWindowPos() << ", size: " << getWindowSize() << ", pixel size: " << toPixels( getWindowSize() ) ); } void AppTestApp::update() { } void AppTestApp::draw() { gl::clear( Color( 0.2f, 0.1f, 0 ) ); // draw something animated { gl::ScopedColor colorScope( ColorA( 0, 0, 1, 0.5f ) ); gl::ScopedModelMatrix modelScope; gl::translate( getWindowCenter() ); gl::rotate( getElapsedSeconds() * 0.5f, vec3( 0, 0, 1 ) ); const float t = 200; gl::drawSolidRect( Rectf( -t, -t, t, t ) ); } // draw test textures auto offset = vec2( 0 ); if( mTexAsset ) { gl::draw( mTexAsset, offset ); } if( mTexResource ) { offset.x += 256; gl::draw( mTexResource, offset ); } if( mTexStartup ) { offset.x = 0; offset.y += 200; gl::draw( mTexStartup, offset ); } if( mSomeMemberObj.mTex ) { offset.x += mSomeMemberObj.mTex->getWidth(); gl::draw( mSomeMemberObj.mTex, offset ); } drawInfo(); CI_CHECK_GL(); } void AppTestApp::cleanup() { CI_LOG_I( "Shutdown" ); } void AppTestApp::drawInfo() { TextLayout layout; layout.setFont( Font( "Arial", 16 ) ); layout.setColor( ColorA::gray( 0.9f, 0.75f ) ); auto fps = boost::format( "%0.2f" ) % getAverageFps(); layout.addLine( "fps: " + fps.str() ); layout.addLine( "v-sync enabled: " + string( gl::isVerticalSyncEnabled() ? "true" : "false" ) ); auto tex = gl::Texture::create( layout.render( true ) ); vec2 offset( 6, getWindowHeight() - tex->getHeight() - 6 ); // bottom left gl::color( Color::white() ); gl::draw( tex, offset ); } // no settings fn: //CINDER_APP( AppTestApp, RendererGl ) // settings fn from top of file: CINDER_APP( AppTestApp, RendererGl, prepareSettings ) // passing in options to Renderer //CINDER_APP( AppTestApp, RendererGl( RendererGl::Options().msaa( 0 ) ), prepareSettings ) // settings fn by lambda //CINDER_APP( AppTestApp, RendererGl, []( AppTestApp::Settings *settings ) { // CI_LOG_I( "bang" ); //} )
#include "cinder/app/App.h" #include "cinder/app/RendererGl.h" #include "cinder/gl/gl.h" #include "cinder/gl/Texture.h" #include "cinder/Log.h" #include "cinder/CinderAssert.h" #include "cinder/ImageIo.h" #include "cinder/Text.h" #include "cinder/Utilities.h" #include "Resources.h" #include <boost/format.hpp> using namespace ci; using namespace ci::app; using namespace std; void prepareSettings( App::Settings *settings ) { CI_LOG_I( "bang" ); const auto &args = settings->getCommandLineArgs(); if( ! args.empty() ) { CI_LOG_I( "command line args: " ); for( size_t i = 0; i < args.size(); i++ ) console() << "\t[" << i << "] " << args[i] << endl; } CI_LOG_I( "environment vars: " ); const auto &envVars = getEnvironmentVariables(); for( auto &env : envVars ) CI_LOG_I( "{" << env.first << "} = {" << env.second << "}" ); settings->setWindowPos( 50, 50 ); settings->setWindowSize( 900, 500 ); settings->setHighDensityDisplayEnabled(); // settings->setResizable( false ); // settings->setBorderless(); // settings->setAlwaysOnTop(); // settings->setMultiTouchEnabled(); // settings->setMultiTouchEnabled( false ); // settings->disableFrameRate(); // settings->setFrameRate( 20 ); // settings->setTitle( "Blarg" ); // FIXME: seems broken on mac, but did it ever work? // settings->setShouldQuit(); #if defined( CINDER_COCOA_TOUCH ) settings->setStatusBarEnabled( false ); // FIXME: status bar is always visible? #endif #if defined( CINDER_MSW ) settings->setConsoleWindowEnabled(); #endif // test loading an asset before application has been instanciated: auto asset = loadAsset( "mustache-green.png" ); CI_ASSERT( asset ); } struct SomeMemberObj { gl::TextureRef mTex; SomeMemberObj() { CI_LOG_I( "bang" ); auto resource = loadResource( RES_IMAGE ); mTex = gl::Texture::create( loadImage( resource ) ); CI_CHECK_GL(); } }; class AppTestApp : public App { public: AppTestApp(); ~AppTestApp(); void setup() override; void keyDown( KeyEvent event ) override; void mouseDown( MouseEvent event ) override; void touchesBegan( TouchEvent event ) override; void touchesMoved( TouchEvent event ) override; void touchesEnded( TouchEvent event ) override; void resize() override; void update() override; void draw() override; void cleanup() override; void drawInfo(); SomeMemberObj mSomeMemberObj; gl::TextureRef mTexStartup, mTexAsset, mTexResource; }; AppTestApp::AppTestApp() { CI_LOG_I( "bang" ); // Surface8u surface( 140, 140, false ); // Surface8u::Iter iter = surface.getIter(); // while( iter.line() ) { // while( iter.pixel() ) { // iter.r() = 0; // iter.g() = iter.x(); // iter.b() = iter.y(); // } // } // mTexStartup = gl::Texture::create( surface ); auto asset = loadAsset( "mustache-green.png" ); mTexStartup = gl::Texture::create( loadImage( asset ) ); CI_CHECK_GL(); } AppTestApp::~AppTestApp() { CI_LOG_I( "bang" ); } void AppTestApp::setup() { CI_LOG_I( "bang" ); auto asset = loadAsset( "mustache-green.png" ); mTexAsset = gl::Texture::create( loadImage( asset ) ); auto resource = loadResource( RES_IMAGE ); mTexResource = gl::Texture::create( loadImage( resource ) ); gl::enableAlphaBlending(); CI_LOG_I( "target fps: " << getFrameRate() ); CI_CHECK_GL(); CI_LOG_I( "complete" ); } void AppTestApp::keyDown( KeyEvent event ) { if( event.getChar() == 'f' ) { setFullScreen( ! isFullScreen() ); } else if( event.getChar() == 'o' ) { auto filePath = getOpenFilePath(); CI_LOG_I( "result of getOpenFilePath(): " << filePath ); } else if( event.getChar() == 'p' ) { auto filePath = getFolderPath(); CI_LOG_I( "result of getFolderPath(): " << filePath ); } else if( event.getChar() == 's' ) { auto filePath = getSaveFilePath(); CI_LOG_I( "result of getSaveFilePath(): " << filePath ); } else if( event.getChar() == 'r' ) { // iterate through some framerate settings int targetFrameRate = (int)lround( getFrameRate() ); if( ! isFrameRateEnabled() ) { CI_LOG_I( "setting framerate to 60" ); setFrameRate( 60 ); } else if( targetFrameRate == 60 ) { CI_LOG_I( "setting framerate to 30" ); setFrameRate( 30 ); } else if( targetFrameRate == 30 ) { CI_LOG_I( "disabling framerate" ); disableFrameRate(); } else { CI_ASSERT_NOT_REACHABLE(); } } else if( event.getChar() == 'v' ) { gl::enableVerticalSync( ! gl::isVerticalSyncEnabled() ); } } void AppTestApp::mouseDown( MouseEvent event ) { CI_LOG_I( "mouse pos: " << event.getPos() ); } void AppTestApp::touchesBegan( TouchEvent event ) { const auto &touches = event.getTouches(); CI_LOG_I( "num touches:" << touches.size() ); for( size_t i = 0; i < touches.size(); i++ ) console() << "\t\t[" << i << "] pos: " << touches.at( i ).getPos() << endl; } void AppTestApp::touchesMoved( TouchEvent event ) { const auto &touches = event.getTouches(); CI_LOG_I( "num touches:" << touches.size() ); for( size_t i = 0; i < touches.size(); i++ ) console() << "\t\t[" << i << "] pos: " << touches.at( i ).getPos() << endl; } void AppTestApp::touchesEnded( TouchEvent event ) { const auto &touches = event.getTouches(); CI_LOG_I( "num touches: " << touches.size() ); for( size_t i = 0; i < touches.size(); i++ ) console() << "\t\t[" << i << "] pos: " << touches.at( i ).getPos() << endl; } void AppTestApp::resize() { CI_LOG_I( "window pos: " << getWindowPos() << ", size: " << getWindowSize() << ", pixel size: " << toPixels( getWindowSize() ) ); } void AppTestApp::update() { } void AppTestApp::draw() { gl::clear( Color( 0.2f, 0.1f, 0 ) ); // draw something animated { gl::ScopedColor colorScope( ColorA( 0, 0, 1, 0.5f ) ); gl::ScopedModelMatrix modelScope; gl::translate( getWindowCenter() ); gl::rotate( getElapsedSeconds() * 0.5f, vec3( 0, 0, 1 ) ); const float t = 200; gl::drawSolidRect( Rectf( -t, -t, t, t ) ); } // draw test textures auto offset = vec2( 0 ); if( mTexAsset ) { gl::draw( mTexAsset, offset ); } if( mTexResource ) { offset.x += 256; gl::draw( mTexResource, offset ); } if( mTexStartup ) { offset.x = 0; offset.y += 200; gl::draw( mTexStartup, offset ); } if( mSomeMemberObj.mTex ) { offset.x += mSomeMemberObj.mTex->getWidth(); gl::draw( mSomeMemberObj.mTex, offset ); } drawInfo(); CI_CHECK_GL(); } void AppTestApp::cleanup() { CI_LOG_I( "Shutdown" ); } void AppTestApp::drawInfo() { TextLayout layout; layout.setFont( Font( "Arial", 16 ) ); layout.setColor( ColorA::gray( 0.9f, 0.75f ) ); auto fps = boost::format( "%0.2f" ) % getAverageFps(); layout.addLine( "fps: " + fps.str() ); layout.addLine( "v-sync enabled: " + string( gl::isVerticalSyncEnabled() ? "true" : "false" ) ); auto tex = gl::Texture::create( layout.render( true ) ); vec2 offset( 6, getWindowHeight() - tex->getHeight() - 6 ); // bottom left gl::color( Color::white() ); gl::draw( tex, offset ); } // no settings fn: //CINDER_APP( AppTestApp, RendererGl ) // settings fn from top of file: CINDER_APP( AppTestApp, RendererGl, prepareSettings ) // passing in options to Renderer //CINDER_APP( AppTestApp, RendererGl( RendererGl::Options().msaa( 0 ) ), prepareSettings ) // settings fn by lambda //CINDER_APP( AppTestApp, RendererGl, []( AppTestApp::Settings *settings ) { // CI_LOG_I( "bang" ); //} )
add some framerate setting test code to AppTest
add some framerate setting test code to AppTest
C++
bsd-2-clause
sosolimited/Cinder,sosolimited/Cinder,2666hz/Cinder,2666hz/Cinder,2666hz/Cinder,sosolimited/Cinder,morbozoo/sonyHeadphones,morbozoo/sonyHeadphones,sosolimited/Cinder,morbozoo/sonyHeadphones,2666hz/Cinder,morbozoo/sonyHeadphones
8ec87473ac7087d73b4bd0897f86695908ef1eec
include/tao/pegtl/internal/always_false.hpp
include/tao/pegtl/internal/always_false.hpp
// Copyright (c) 2018 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #ifndef TAO_PEGTL_INTERNAL_ALWAYS_FALSE_HPP #define TAO_PEGTL_INTERNAL_ALWAYS_FALSE_HPP #include "../config.hpp" #include <type_traits> namespace tao { namespace TAO_PEGTL_NAMESPACE { namespace internal { template< typename... > using always_false = std::false_type; } // namespace internal } // namespace TAO_PEGTL_NAMESPACE } // namespace tao #endif
// Copyright (c) 2018 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #ifndef TAO_PEGTL_INTERNAL_ALWAYS_FALSE_HPP #define TAO_PEGTL_INTERNAL_ALWAYS_FALSE_HPP #include "../config.hpp" #include <type_traits> namespace tao { namespace TAO_PEGTL_NAMESPACE { namespace internal { template< typename... > struct always_false : std::false_type { }; } // namespace internal } // namespace TAO_PEGTL_NAMESPACE } // namespace tao #endif
Fix helper
Fix helper
C++
mit
ColinH/PEGTL,ColinH/PEGTL
4bc13e98c21f107ddfa5b56b81a156e95c948e88
Source/modules/serviceworkers/RespondWithObserver.cpp
Source/modules/serviceworkers/RespondWithObserver.cpp
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #include "modules/serviceworkers/RespondWithObserver.h" #include "V8Response.h" #include "bindings/v8/ScriptFunction.h" #include "bindings/v8/ScriptPromise.h" #include "bindings/v8/ScriptValue.h" #include "bindings/v8/V8Binding.h" #include "core/dom/ExecutionContext.h" #include "modules/serviceworkers/ServiceWorkerGlobalScopeClient.h" #include "wtf/Assertions.h" #include "wtf/RefPtr.h" namespace WebCore { class RespondWithObserver::ThenFunction FINAL : public ScriptFunction { public: enum ResolveType { Fulfilled, Rejected, }; static PassOwnPtr<ScriptFunction> create(PassRefPtr<RespondWithObserver> observer, ResolveType type) { return adoptPtr(new ThenFunction(toIsolate(observer->executionContext()), observer, type)); } private: ThenFunction(v8::Isolate* isolate, PassRefPtr<RespondWithObserver> observer, ResolveType type) : ScriptFunction(isolate) , m_observer(observer) , m_resolveType(type) { } virtual ScriptValue call(ScriptValue value) OVERRIDE { ASSERT(m_observer); ASSERT(m_resolveType == Fulfilled || m_resolveType == Rejected); if (m_resolveType == Rejected) m_observer->responseWasRejected(); else m_observer->responseWasFulfilled(value); m_observer = nullptr; return value; } RefPtr<RespondWithObserver> m_observer; ResolveType m_resolveType; }; PassRefPtr<RespondWithObserver> RespondWithObserver::create(ExecutionContext* context, int eventID) { return adoptRef(new RespondWithObserver(context, eventID)); } RespondWithObserver::~RespondWithObserver() { ASSERT(m_state == Done); } void RespondWithObserver::contextDestroyed() { ContextLifecycleObserver::contextDestroyed(); m_state = Done; } void RespondWithObserver::didDispatchEvent() { if (m_state == Initial) sendResponse(nullptr); } void RespondWithObserver::respondWith(const ScriptValue& value) { if (m_state != Initial) return; m_state = Pending; ScriptPromise::cast(value).then( ThenFunction::create(this, ThenFunction::Fulfilled), ThenFunction::create(this, ThenFunction::Rejected)); } void RespondWithObserver::sendResponse(PassRefPtr<Response> response) { if (!executionContext()) return; ServiceWorkerGlobalScopeClient::from(executionContext())->didHandleFetchEvent(m_eventID, response); m_state = Done; } void RespondWithObserver::responseWasRejected() { // FIXME: Throw a NetworkError to service worker's execution context. sendResponse(nullptr); } void RespondWithObserver::responseWasFulfilled(const ScriptValue& value) { if (!executionContext()) return; if (!V8Response::hasInstance(value.v8Value(), toIsolate(executionContext()))) { responseWasRejected(); return; } v8::Handle<v8::Object> object = v8::Handle<v8::Object>::Cast(value.v8Value()); sendResponse(V8Response::toNative(object)); } RespondWithObserver::RespondWithObserver(ExecutionContext* context, int eventID) : ContextLifecycleObserver(context) , m_eventID(eventID) , m_state(Initial) { } } // namespace WebCore
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #include "modules/serviceworkers/RespondWithObserver.h" #include "V8Response.h" #include "bindings/v8/ScriptFunction.h" #include "bindings/v8/ScriptPromise.h" #include "bindings/v8/ScriptValue.h" #include "bindings/v8/V8Binding.h" #include "core/dom/ExecutionContext.h" #include "modules/serviceworkers/ServiceWorkerGlobalScopeClient.h" #include "wtf/Assertions.h" #include "wtf/RefPtr.h" namespace WebCore { class RespondWithObserver::ThenFunction FINAL : public ScriptFunction { public: enum ResolveType { Fulfilled, Rejected, }; static PassOwnPtr<ScriptFunction> create(PassRefPtr<RespondWithObserver> observer, ResolveType type) { ExecutionContext* executionContext = observer->executionContext(); return adoptPtr(new ThenFunction(toIsolate(executionContext), observer, type)); } private: ThenFunction(v8::Isolate* isolate, PassRefPtr<RespondWithObserver> observer, ResolveType type) : ScriptFunction(isolate) , m_observer(observer) , m_resolveType(type) { } virtual ScriptValue call(ScriptValue value) OVERRIDE { ASSERT(m_observer); ASSERT(m_resolveType == Fulfilled || m_resolveType == Rejected); if (m_resolveType == Rejected) m_observer->responseWasRejected(); else m_observer->responseWasFulfilled(value); m_observer = nullptr; return value; } RefPtr<RespondWithObserver> m_observer; ResolveType m_resolveType; }; PassRefPtr<RespondWithObserver> RespondWithObserver::create(ExecutionContext* context, int eventID) { return adoptRef(new RespondWithObserver(context, eventID)); } RespondWithObserver::~RespondWithObserver() { ASSERT(m_state == Done); } void RespondWithObserver::contextDestroyed() { ContextLifecycleObserver::contextDestroyed(); m_state = Done; } void RespondWithObserver::didDispatchEvent() { if (m_state == Initial) sendResponse(nullptr); } void RespondWithObserver::respondWith(const ScriptValue& value) { if (m_state != Initial) return; m_state = Pending; ScriptPromise::cast(value).then( ThenFunction::create(this, ThenFunction::Fulfilled), ThenFunction::create(this, ThenFunction::Rejected)); } void RespondWithObserver::sendResponse(PassRefPtr<Response> response) { if (!executionContext()) return; ServiceWorkerGlobalScopeClient::from(executionContext())->didHandleFetchEvent(m_eventID, response); m_state = Done; } void RespondWithObserver::responseWasRejected() { // FIXME: Throw a NetworkError to service worker's execution context. sendResponse(nullptr); } void RespondWithObserver::responseWasFulfilled(const ScriptValue& value) { if (!executionContext()) return; if (!V8Response::hasInstance(value.v8Value(), toIsolate(executionContext()))) { responseWasRejected(); return; } v8::Handle<v8::Object> object = v8::Handle<v8::Object>::Cast(value.v8Value()); sendResponse(V8Response::toNative(object)); } RespondWithObserver::RespondWithObserver(ExecutionContext* context, int eventID) : ContextLifecycleObserver(context) , m_eventID(eventID) , m_state(Initial) { } } // namespace WebCore
Fix crash in RespondWithObserver::respondWith
Fix crash in RespondWithObserver::respondWith This is the same fix as r166987 for WaitUntilObserver. No test is added. The upcoming Chromium CL https://codereview.chromium.org/178343011/ caught this crash so it will be tested by it. BUG=342301 Review URL: https://codereview.chromium.org/192603002 git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@168833 bbb929c8-8fbe-4397-9dbb-9b2b20218538
C++
bsd-3-clause
kurli/blink-crosswalk,crosswalk-project/blink-crosswalk-efl,modulexcite/blink,Pluto-tv/blink-crosswalk,smishenk/blink-crosswalk,hgl888/blink-crosswalk-efl,XiaosongWei/blink-crosswalk,hgl888/blink-crosswalk-efl,nwjs/blink,crosswalk-project/blink-crosswalk-efl,crosswalk-project/blink-crosswalk-efl,ondra-novak/blink,Pluto-tv/blink-crosswalk,hgl888/blink-crosswalk-efl,smishenk/blink-crosswalk,smishenk/blink-crosswalk,ondra-novak/blink,Pluto-tv/blink-crosswalk,nwjs/blink,modulexcite/blink,kurli/blink-crosswalk,Bysmyyr/blink-crosswalk,Pluto-tv/blink-crosswalk,modulexcite/blink,jtg-gg/blink,ondra-novak/blink,XiaosongWei/blink-crosswalk,smishenk/blink-crosswalk,kurli/blink-crosswalk,crosswalk-project/blink-crosswalk-efl,kurli/blink-crosswalk,Bysmyyr/blink-crosswalk,ondra-novak/blink,ondra-novak/blink,crosswalk-project/blink-crosswalk-efl,XiaosongWei/blink-crosswalk,jtg-gg/blink,Pluto-tv/blink-crosswalk,PeterWangIntel/blink-crosswalk,PeterWangIntel/blink-crosswalk,jtg-gg/blink,PeterWangIntel/blink-crosswalk,Bysmyyr/blink-crosswalk,hgl888/blink-crosswalk-efl,smishenk/blink-crosswalk,Pluto-tv/blink-crosswalk,Pluto-tv/blink-crosswalk,jtg-gg/blink,jtg-gg/blink,nwjs/blink,kurli/blink-crosswalk,Bysmyyr/blink-crosswalk,modulexcite/blink,smishenk/blink-crosswalk,Pluto-tv/blink-crosswalk,nwjs/blink,modulexcite/blink,smishenk/blink-crosswalk,smishenk/blink-crosswalk,Bysmyyr/blink-crosswalk,kurli/blink-crosswalk,modulexcite/blink,PeterWangIntel/blink-crosswalk,Pluto-tv/blink-crosswalk,hgl888/blink-crosswalk-efl,kurli/blink-crosswalk,XiaosongWei/blink-crosswalk,crosswalk-project/blink-crosswalk-efl,nwjs/blink,kurli/blink-crosswalk,PeterWangIntel/blink-crosswalk,crosswalk-project/blink-crosswalk-efl,Bysmyyr/blink-crosswalk,Pluto-tv/blink-crosswalk,crosswalk-project/blink-crosswalk-efl,Bysmyyr/blink-crosswalk,hgl888/blink-crosswalk-efl,kurli/blink-crosswalk,XiaosongWei/blink-crosswalk,kurli/blink-crosswalk,XiaosongWei/blink-crosswalk,PeterWangIntel/blink-crosswalk,modulexcite/blink,nwjs/blink,jtg-gg/blink,hgl888/blink-crosswalk-efl,XiaosongWei/blink-crosswalk,modulexcite/blink,crosswalk-project/blink-crosswalk-efl,jtg-gg/blink,nwjs/blink,hgl888/blink-crosswalk-efl,Bysmyyr/blink-crosswalk,ondra-novak/blink,jtg-gg/blink,smishenk/blink-crosswalk,PeterWangIntel/blink-crosswalk,nwjs/blink,jtg-gg/blink,jtg-gg/blink,XiaosongWei/blink-crosswalk,PeterWangIntel/blink-crosswalk,XiaosongWei/blink-crosswalk,modulexcite/blink,hgl888/blink-crosswalk-efl,Bysmyyr/blink-crosswalk,ondra-novak/blink,nwjs/blink,XiaosongWei/blink-crosswalk,Bysmyyr/blink-crosswalk,modulexcite/blink,hgl888/blink-crosswalk-efl,ondra-novak/blink,PeterWangIntel/blink-crosswalk,PeterWangIntel/blink-crosswalk,smishenk/blink-crosswalk,ondra-novak/blink,nwjs/blink
33805c64436117a4d24271c462ff818069c4bcf5
test/click_transformer_test.cpp
test/click_transformer_test.cpp
#include "simplecp/click_transformer.h" #include <boost/shared_ptr.hpp> #include <gtest/gtest.h> #include <ros/console.h> #include <ros/duration.h> #include <ros/node_handle.h> #include <ros/publisher.h> #include <ros/subscriber.h> #include <ros/time.h> #include <ros/topic.h> #include <visualization_msgs/InteractiveMarkerFeedback.h> #include "simplecp/MarkerEvent.h" namespace simplecp { typedef visualization_msgs::InteractiveMarkerFeedback Feedback; class ClickTransformerTest : public ::testing::Test { public: ClickTransformerTest() : node_handle_("simplecp"), marker_publisher_( node_handle_.advertise<Feedback>( "/pr2_marker_control_transparent/feedback", 5)), event_subscriber_( node_handle_.subscribe("marker_events", 5, &ClickTransformerTest::MarkerEventCallback, this)) { } void SetUp() { while (!IsNodeAlive()) { ros::spinOnce(); } } void Publish(int event_type, std::string marker_name, std::string control_name) { Feedback feedback; feedback.event_type = event_type; feedback.marker_name = marker_name; feedback.control_name = control_name; marker_publisher_.publish(feedback); } boost::shared_ptr<const MarkerEvent> WaitForEvent() { return ros::topic::waitForMessage<MarkerEvent>( event_subscriber_.getTopic(), ros::Duration(1)); } private: ros::NodeHandle node_handle_; ros::Publisher marker_publisher_; ros::Subscriber event_subscriber_; void MarkerEventCallback(const MarkerEvent& event) { } bool IsNodeAlive() { return (marker_publisher_.getNumSubscribers() > 0) && (event_subscriber_.getNumPublishers() > 0); } }; TEST_F(ClickTransformerTest, Click) { Publish(Feedback::MOUSE_DOWN, "l_gripper_control", "_u0"); ros::Duration(0, ClickTransformer::kClickNanoseconds / 2).sleep(); Publish(Feedback::MOUSE_UP, "l_gripper_control", "_u0"); auto event = WaitForEvent(); EXPECT_TRUE(event != NULL); EXPECT_EQ(MarkerEvent::CLICK, event->type); EXPECT_EQ("l_gripper_control", event->marker_name); } TEST_F(ClickTransformerTest, Drag) { Publish(Feedback::MOUSE_DOWN, "r_gripper_control", "_u0"); ros::Duration(0, ClickTransformer::kClickNanoseconds + 1000).sleep(); Publish(Feedback::MOUSE_UP, "r_gripper_control", "_u0"); auto event = WaitForEvent(); EXPECT_TRUE(event != NULL); EXPECT_EQ(MarkerEvent::DRAG, event->type); EXPECT_EQ("r_gripper_control", event->marker_name); } TEST_F(ClickTransformerTest, MultipleClickDrag) { Publish(Feedback::MOUSE_DOWN, "l_gripper_control", "_u0"); ros::Duration(0, ClickTransformer::kClickNanoseconds / 2).sleep(); Publish(Feedback::MOUSE_UP, "l_gripper_control", "_u0"); auto event = WaitForEvent(); EXPECT_TRUE(event != NULL); EXPECT_EQ(MarkerEvent::CLICK, event->type); EXPECT_EQ("l_gripper_control", event->marker_name); Publish(Feedback::MOUSE_DOWN, "r_gripper_control", "_u0"); ros::Duration(0, ClickTransformer::kClickNanoseconds + 1000).sleep(); Publish(Feedback::MOUSE_UP, "r_gripper_control", "_u0"); event = WaitForEvent(); EXPECT_TRUE(event != NULL); EXPECT_EQ(MarkerEvent::DRAG, event->type); EXPECT_EQ("r_gripper_control", event->marker_name); } TEST_F(ClickTransformerTest, UnsupportedMarkerDoesNothing) { Publish(Feedback::MOUSE_DOWN, "unsupported_control", "_u0"); ros::Duration(0, ClickTransformer::kClickNanoseconds - 1000).sleep(); Publish(Feedback::MOUSE_UP, "unsupported_control", "_u0"); auto event = WaitForEvent(); EXPECT_EQ(NULL, event.get()); } TEST_F(ClickTransformerTest, ConvertKnownControl) { Publish(Feedback::MOUSE_DOWN, "l_gripper_control", "_u0"); ros::Duration(0, ClickTransformer::kClickNanoseconds / 2).sleep(); Publish(Feedback::MOUSE_UP, "l_gripper_control", "_u0"); auto event = WaitForEvent(); EXPECT_TRUE(event != NULL); EXPECT_EQ(ClickTransformer::kGripperControls.at("_u0"), event->control_type); } TEST_F(ClickTransformerTest, ConvertPostureControl) { Publish(Feedback::MOUSE_DOWN, "l_posture_control", ""); ros::Duration(0, ClickTransformer::kClickNanoseconds / 2).sleep(); Publish(Feedback::MOUSE_UP, "l_posture_control", ""); auto event = WaitForEvent(); EXPECT_TRUE(event != NULL); EXPECT_EQ(MarkerEvent::ROLL, event->control_type); } TEST_F(ClickTransformerTest, UnknownControlDoesNothing) { Publish(Feedback::MOUSE_DOWN, "l_gripper_control", "unknown_control"); ros::Duration(0, ClickTransformer::kClickNanoseconds / 2).sleep(); Publish(Feedback::MOUSE_UP, "l_gripper_control", "unknown_control"); auto event = WaitForEvent(); EXPECT_EQ(NULL, event.get()); } } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); ros::init(argc, argv, "click_transformer_test"); ros::AsyncSpinner spinner(1); spinner.start(); int ret = RUN_ALL_TESTS(); spinner.stop(); ros::shutdown(); return ret; }
#include "simplecp/click_transformer.h" #include <boost/shared_ptr.hpp> #include <gtest/gtest.h> #include <ros/console.h> #include <ros/duration.h> #include <ros/node_handle.h> #include <ros/publisher.h> #include <ros/subscriber.h> #include <ros/time.h> #include <ros/topic.h> #include <visualization_msgs/InteractiveMarkerFeedback.h> #include "simplecp/MarkerEvent.h" namespace simplecp { typedef visualization_msgs::InteractiveMarkerFeedback Feedback; class ClickTransformerTest : public ::testing::Test { public: ClickTransformerTest() : node_handle_("simplecp"), marker_publisher_( node_handle_.advertise<Feedback>( "/pr2_marker_control_transparent/feedback", 5)), event_subscriber_( node_handle_.subscribe("marker_events", 5, &ClickTransformerTest::MarkerEventCallback, this)) { } void SetUp() { while (!IsNodeAlive()) { ros::spinOnce(); } } void Publish(int event_type, std::string marker_name, std::string control_name) { Feedback feedback; feedback.event_type = event_type; feedback.marker_name = marker_name; feedback.control_name = control_name; marker_publisher_.publish(feedback); } boost::shared_ptr<const MarkerEvent> WaitForEvent() { return ros::topic::waitForMessage<MarkerEvent>( event_subscriber_.getTopic(), ros::Duration(1)); } private: ros::NodeHandle node_handle_; ros::Publisher marker_publisher_; ros::Subscriber event_subscriber_; void MarkerEventCallback(const MarkerEvent& event) { } bool IsNodeAlive() { return (marker_publisher_.getNumSubscribers() > 0) && (event_subscriber_.getNumPublishers() > 0); } }; TEST_F(ClickTransformerTest, Click) { Publish(Feedback::MOUSE_DOWN, "l_gripper_control", "_u0"); ros::Duration(0, ClickTransformer::kClickNanoseconds / 2).sleep(); Publish(Feedback::MOUSE_UP, "l_gripper_control", "_u0"); auto event = WaitForEvent(); EXPECT_TRUE(event != NULL); EXPECT_EQ(MarkerEvent::CLICK, event->type); EXPECT_EQ("l_gripper_control", event->marker_name); } TEST_F(ClickTransformerTest, Drag) { Publish(Feedback::MOUSE_DOWN, "r_gripper_control", "_u0"); ros::Duration(0, ClickTransformer::kClickNanoseconds * 2).sleep(); Publish(Feedback::MOUSE_UP, "r_gripper_control", "_u0"); auto event = WaitForEvent(); EXPECT_TRUE(event != NULL); EXPECT_EQ(MarkerEvent::DRAG, event->type); EXPECT_EQ("r_gripper_control", event->marker_name); } TEST_F(ClickTransformerTest, MultipleClickDrag) { Publish(Feedback::MOUSE_DOWN, "l_gripper_control", "_u0"); ros::Duration(0, ClickTransformer::kClickNanoseconds / 2).sleep(); Publish(Feedback::MOUSE_UP, "l_gripper_control", "_u0"); auto event = WaitForEvent(); EXPECT_TRUE(event != NULL); EXPECT_EQ(MarkerEvent::CLICK, event->type); EXPECT_EQ("l_gripper_control", event->marker_name); Publish(Feedback::MOUSE_DOWN, "r_gripper_control", "_u0"); ros::Duration(0, ClickTransformer::kClickNanoseconds * 2).sleep(); Publish(Feedback::MOUSE_UP, "r_gripper_control", "_u0"); event = WaitForEvent(); EXPECT_TRUE(event != NULL); EXPECT_EQ(MarkerEvent::DRAG, event->type); EXPECT_EQ("r_gripper_control", event->marker_name); } TEST_F(ClickTransformerTest, UnsupportedMarkerDoesNothing) { Publish(Feedback::MOUSE_DOWN, "unsupported_control", "_u0"); ros::Duration(0, ClickTransformer::kClickNanoseconds / 2).sleep(); Publish(Feedback::MOUSE_UP, "unsupported_control", "_u0"); auto event = WaitForEvent(); EXPECT_EQ(NULL, event.get()); } TEST_F(ClickTransformerTest, ConvertKnownControl) { Publish(Feedback::MOUSE_DOWN, "l_gripper_control", "_u0"); ros::Duration(0, ClickTransformer::kClickNanoseconds / 2).sleep(); Publish(Feedback::MOUSE_UP, "l_gripper_control", "_u0"); auto event = WaitForEvent(); EXPECT_TRUE(event != NULL); EXPECT_EQ(ClickTransformer::kGripperControls.at("_u0"), event->control_type); } TEST_F(ClickTransformerTest, ConvertPostureControl) { Publish(Feedback::MOUSE_DOWN, "l_posture_control", ""); ros::Duration(0, ClickTransformer::kClickNanoseconds / 2).sleep(); Publish(Feedback::MOUSE_UP, "l_posture_control", ""); auto event = WaitForEvent(); EXPECT_TRUE(event != NULL); EXPECT_EQ(MarkerEvent::ROLL, event->control_type); } TEST_F(ClickTransformerTest, UnknownControlDoesNothing) { Publish(Feedback::MOUSE_DOWN, "l_gripper_control", "unknown_control"); ros::Duration(0, ClickTransformer::kClickNanoseconds / 2).sleep(); Publish(Feedback::MOUSE_UP, "l_gripper_control", "unknown_control"); auto event = WaitForEvent(); EXPECT_EQ(NULL, event.get()); } } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); ros::init(argc, argv, "click_transformer_test"); ros::AsyncSpinner spinner(1); spinner.start(); int ret = RUN_ALL_TESTS(); spinner.stop(); ros::shutdown(); return ret; }
Use consistent click/drag times.
Use consistent click/drag times.
C++
mit
jstnhuang/simplecp
2264f6c9134fd9d0ce4a96212370e45806743836
frameworks/C++/lithium/lithium.cc
frameworks/C++/lithium/lithium.cc
#include "lithium_http_backend.hh" #if TFB_MYSQL #include "lithium_mysql.hh" #elif TFB_PGSQL #include "lithium_pgsql.hh" #endif #include "symbols.hh" using namespace li; template <typename B> void escape_html_entities(B& buffer, const std::string& data) { for(size_t pos = 0; pos != data.size(); ++pos) { switch(data[pos]) { case '&': buffer << "&amp;"; break; case '\"': buffer << "&quot;"; break; case '\'': buffer << "&apos;"; break; case '<': buffer << "&lt;"; break; case '>': buffer << "&gt;"; break; default: buffer << data[pos]; break; } } } int main(int argc, char* argv[]) { if (argc != 3) { std::cerr << "Usage: " << argv[0] << " sql_host port" << std::endl; return 1; } int port = atoi(argv[2]); int nprocs = std::thread::hardware_concurrency(); #if TFB_MYSQL auto sql_db = mysql_database(s::host = argv[1], s::database = "hello_world", s::user = "benchmarkdbuser", s::password = "benchmarkdbpass", s::port = 3306, s::charset = "utf8"); int mysql_max_connection = sql_db.connect()("SELECT @@GLOBAL.max_connections;").read<int>() * 0.75; li::max_mysql_connections_per_thread = (mysql_max_connection / nprocs); std::cout << "Using " << li::max_mysql_connections_per_thread << " connections per thread. " << nprocs << " threads." << std::endl; #elif TFB_PGSQL auto sql_db = pgsql_database(s::host = argv[1], s::database = "hello_world", s::user = "benchmarkdbuser", s::password = "benchmarkdbpass", s::port = 5432, s::charset = "utf8"); int pgsql_max_connection = atoi(sql_db.connect()("SHOW max_connections;").read<std::string>().c_str()) * 0.75; li::max_pgsql_connections_per_thread = (pgsql_max_connection / nprocs); std::cout << "Using " << li::max_pgsql_connections_per_thread << " connections per thread. " << nprocs << " threads." << std::endl; #endif auto fortunes = sql_orm_schema(sql_db, "Fortune").fields( s::id(s::auto_increment, s::primary_key) = int(), s::message = std::string()); auto random_numbers = sql_orm_schema(sql_db, "World").fields( s::id(s::auto_increment, s::primary_key) = int(), s::randomNumber = int()); http_api my_api; my_api.get("/plaintext") = [&](http_request& request, http_response& response) { response.set_header("Content-Type", "text/plain"); response.write("Hello, World!"); }; my_api.get("/json") = [&](http_request& request, http_response& response) { response.write_json(s::message = "Hello, World!"); }; my_api.get("/db") = [&](http_request& request, http_response& response) { response.write_json(random_numbers.connect(request.yield).find_one(s::id = 1234).value()); }; my_api.get("/queries") = [&](http_request& request, http_response& response) { std::string N_str = request.get_parameters(s::N = std::optional<std::string>()).N.value_or("1"); int N = atoi(N_str.c_str()); N = std::max(1, std::min(N, 500)); auto c = random_numbers.connect(request.yield); std::vector<decltype(random_numbers.all_fields())> numbers(N); for (int i = 0; i < N; i++) numbers[i] = c.find_one(s::id = 1 + rand() % 9999).value(); response.write_json(numbers); }; my_api.get("/updates") = [&](http_request& request, http_response& response) { std::string N_str = request.get_parameters(s::N = std::optional<std::string>()).N.value_or("1"); int N = atoi(N_str.c_str()); N = std::max(1, std::min(N, 500)); auto c = random_numbers.connect(request.yield); auto& raw_c = c.backend_connection(); std::vector<decltype(random_numbers.all_fields())> numbers(N); #if TFB_MYSQL raw_c("START TRANSACTION"); #endif for (int i = 0; i < N; i++) { numbers[i] = c.find_one(s::id = 1 + rand() % 9999).value(); numbers[i].randomNumber = 1 + rand() % 9999; } std::sort(numbers.begin(), numbers.end(), [] (auto a, auto b) { return a.id < b.id; }); #if TFB_MYSQL for (int i = 0; i < N; i++) c.update(numbers[i]); raw_c("COMMIT"); #elif TFB_PGSQL raw_c.cached_statement ([N] { std::ostringstream ss; ss << "UPDATE World SET randomNumber=tmp.randomNumber FROM (VALUES "; for (int i = 0; i < N; i++) ss << "($" << i*2+1 << "::integer, $" << i*2+2 << "::integer) "<< (i == N-1 ? "": ","); ss << ") AS tmp(id, randomNumber) WHERE tmp.id = World.id"; return ss.str(); }, N)(numbers); #endif response.write_json(numbers); }; my_api.get("/fortunes") = [&](http_request& request, http_response& response) { typedef decltype(fortunes.all_fields()) fortune; std::vector<fortune> table; auto c = fortunes.connect(request.yield); c.forall([&] (auto f) { table.emplace_back(f); }); table.emplace_back(0, "Additional fortune added at request time."); std::sort(table.begin(), table.end(), [] (const fortune& a, const fortune& b) { return a.message < b.message; }); char b[100000]; li::output_buffer ss(b, sizeof(b)); ss << "<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>"; for(auto& f : table) { ss << "<tr><td>" << f.id << "</td><td>"; escape_html_entities(ss, f.message); ss << "</td></tr>"; } ss << "</table></body></html>"; response.set_header("Content-Type", "text/html; charset=utf-8"); response.write(ss.to_string_view()); }; http_serve(my_api, port, s::nthreads = nprocs); return 0; }
#include "lithium_http_backend.hh" #if TFB_MYSQL #include "lithium_mysql.hh" #elif TFB_PGSQL #include "lithium_pgsql.hh" #endif #include "symbols.hh" using namespace li; template <typename B> void escape_html_entities(B& buffer, const std::string& data) { for(size_t pos = 0; pos != data.size(); ++pos) { switch(data[pos]) { case '&': buffer << "&amp;"; break; case '\"': buffer << "&quot;"; break; case '\'': buffer << "&apos;"; break; case '<': buffer << "&lt;"; break; case '>': buffer << "&gt;"; break; default: buffer << data[pos]; break; } } } int main(int argc, char* argv[]) { if (argc != 3) { std::cerr << "Usage: " << argv[0] << " sql_host port" << std::endl; return 1; } int port = atoi(argv[2]); int nprocs = std::thread::hardware_concurrency(); #if TFB_MYSQL auto sql_db = mysql_database(s::host = argv[1], s::database = "hello_world", s::user = "benchmarkdbuser", s::password = "benchmarkdbpass", s::port = 3306, s::charset = "utf8"); int mysql_max_connection = 512; li::max_mysql_connections_per_thread = (mysql_max_connection / nprocs); std::cout << "Using " << li::max_mysql_connections_per_thread << " connections per thread. " << nprocs << " threads." << std::endl; #elif TFB_PGSQL auto sql_db = pgsql_database(s::host = argv[1], s::database = "hello_world", s::user = "benchmarkdbuser", s::password = "benchmarkdbpass", s::port = 5432, s::charset = "utf8"); int pgsql_max_connection = 512; li::max_pgsql_connections_per_thread = (pgsql_max_connection / nprocs); std::cout << "Using " << li::max_pgsql_connections_per_thread << " connections per thread. " << nprocs << " threads." << std::endl; #endif auto fortunes = sql_orm_schema(sql_db, "Fortune").fields( s::id(s::auto_increment, s::primary_key) = int(), s::message = std::string()); auto random_numbers = sql_orm_schema(sql_db, "World").fields( s::id(s::auto_increment, s::primary_key) = int(), s::randomNumber = int()); http_api my_api; my_api.get("/plaintext") = [&](http_request& request, http_response& response) { response.set_header("Content-Type", "text/plain"); response.write("Hello, World!"); }; my_api.get("/json") = [&](http_request& request, http_response& response) { response.write_json(s::message = "Hello, World!"); }; my_api.get("/db") = [&](http_request& request, http_response& response) { response.write_json(random_numbers.connect(request.yield).find_one(s::id = 1234).value()); }; my_api.get("/queries") = [&](http_request& request, http_response& response) { std::string N_str = request.get_parameters(s::N = std::optional<std::string>()).N.value_or("1"); int N = atoi(N_str.c_str()); N = std::max(1, std::min(N, 500)); auto c = random_numbers.connect(request.yield); std::vector<decltype(random_numbers.all_fields())> numbers(N); for (int i = 0; i < N; i++) numbers[i] = c.find_one(s::id = 1 + rand() % 9999).value(); response.write_json(numbers); }; my_api.get("/updates") = [&](http_request& request, http_response& response) { std::string N_str = request.get_parameters(s::N = std::optional<std::string>()).N.value_or("1"); int N = atoi(N_str.c_str()); N = std::max(1, std::min(N, 500)); auto c = random_numbers.connect(request.yield); auto& raw_c = c.backend_connection(); std::vector<decltype(random_numbers.all_fields())> numbers(N); #if TFB_MYSQL raw_c("START TRANSACTION"); #endif for (int i = 0; i < N; i++) { numbers[i] = c.find_one(s::id = 1 + rand() % 9999).value(); numbers[i].randomNumber = 1 + rand() % 9999; } std::sort(numbers.begin(), numbers.end(), [] (auto a, auto b) { return a.id < b.id; }); #if TFB_MYSQL for (int i = 0; i < N; i++) c.update(numbers[i]); raw_c("COMMIT"); #elif TFB_PGSQL raw_c.cached_statement ([N] { std::ostringstream ss; ss << "UPDATE World SET randomNumber=tmp.randomNumber FROM (VALUES "; for (int i = 0; i < N; i++) ss << "($" << i*2+1 << "::integer, $" << i*2+2 << "::integer) "<< (i == N-1 ? "": ","); ss << ") AS tmp(id, randomNumber) WHERE tmp.id = World.id"; return ss.str(); }, N)(numbers); #endif response.write_json(numbers); }; my_api.get("/fortunes") = [&](http_request& request, http_response& response) { typedef decltype(fortunes.all_fields()) fortune; std::vector<fortune> table; auto c = fortunes.connect(request.yield); c.forall([&] (auto f) { table.emplace_back(f); }); table.emplace_back(0, "Additional fortune added at request time."); std::sort(table.begin(), table.end(), [] (const fortune& a, const fortune& b) { return a.message < b.message; }); char b[100000]; li::output_buffer ss(b, sizeof(b)); ss << "<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>"; for(auto& f : table) { ss << "<tr><td>" << f.id << "</td><td>"; escape_html_entities(ss, f.message); ss << "</td></tr>"; } ss << "</table></body></html>"; response.set_header("Content-Type", "text/html; charset=utf-8"); response.write(ss.to_string_view()); }; http_serve(my_api, port, s::nthreads = nprocs); return 0; }
Stop using max_connections SQL connections. (#5408)
Lithium: Stop using max_connections SQL connections. (#5408)
C++
bsd-3-clause
sagenschneider/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,jamming/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,jamming/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,jamming/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,jamming/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,jamming/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,jamming/FrameworkBenchmarks,jamming/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,jamming/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,jamming/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,jamming/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,jamming/FrameworkBenchmarks,jamming/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,jamming/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,jamming/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks
8a61097500f891a51918eef717007be76306e389
source/level_assembler.cxx
source/level_assembler.cxx
#include <boomhs/billboard.hpp> #include <boomhs/components.hpp> #include <boomhs/dungeon_generator.hpp> #include <boomhs/level_assembler.hpp> #include <boomhs/level_loader.hpp> #include <boomhs/player.hpp> #include <boomhs/start_area_generator.hpp> #include <boomhs/tilegrid_algorithms.hpp> #include <boomhs/world_object.hpp> #include <boomhs/obj.hpp> #include <opengl/constants.hpp> #include <opengl/gpu.hpp> #include <opengl/lighting.hpp> #include <sstream> #include <stlw/os.hpp> #include <stlw/random.hpp> using namespace boomhs; using namespace opengl; namespace { ZoneState assemble(LevelGeneratedData&& gendata, LevelAssets&& assets, EntityRegistry& registry) { auto const player_eid = find_player(registry); EnttLookup player_lookup{player_eid, registry}; auto const FORWARD = -Z_UNIT_VECTOR; auto constexpr UP = Y_UNIT_VECTOR; WorldObject player{player_lookup, FORWARD, UP}; // Combine the generated data with the asset data, creating the LevelData instance. LevelData level_data{MOVE(gendata.tilegrid), MOVE(assets.tile_table), MOVE(gendata.startpos), MOVE(gendata.rivers), MOVE(gendata.terrain), MOVE(gendata.water), assets.fog, assets.global_light, MOVE(assets.obj_store), MOVE(player)}; GfxState gfx{MOVE(assets.shader_programs), MOVE(assets.texture_table)}; return ZoneState{MOVE(level_data), MOVE(gfx), registry}; } void bridge_staircases(ZoneState& a, ZoneState& b) { auto& tilegrid_a = a.level_data.tilegrid(); auto& tilegrid_b = b.level_data.tilegrid(); auto const stairs_up_a = find_upstairs(a.registry, tilegrid_a); assert(!stairs_up_a.empty()); auto const stairs_down_b = find_downstairs(b.registry, tilegrid_b); assert(!stairs_down_b.empty()); auto& a_registry = a.registry; auto& b_registry = b.registry; auto const behavior = TileLookupBehavior::VERTICAL_HORIZONTAL_ONLY; assert(stairs_up_a.size() == stairs_down_b.size()); auto const num_stairs = stairs_up_a.size(); FOR(i, num_stairs) { auto const a_updowneid = stairs_up_a[i]; auto const b_downeid = stairs_down_b[i]; assert(a_registry.has<StairInfo>(a_updowneid)); StairInfo& si_a = a_registry.get<StairInfo>(a_updowneid); assert(b_registry.has<StairInfo>(b_downeid)); StairInfo& si_b = b_registry.get<StairInfo>(b_downeid); // find a suitable neighbor tile for each stair auto const a_neighbors = find_immediate_neighbors(tilegrid_a, si_a.tile_position, TileType::FLOOR, behavior); assert(!a_neighbors.empty()); auto const b_neighbors = find_immediate_neighbors(tilegrid_b, si_b.tile_position, TileType::FLOOR, behavior); assert(!b_neighbors.empty()); // Set A's exit position to B's neighbor, and visa versa si_a.exit_position = b_neighbors.front(); si_b.exit_position = a_neighbors.front(); } } using copy_assets_pair_t = std::pair<EntityDrawHandleMap, TileDrawHandles>; Result<copy_assets_pair_t, std::string> copy_assets_gpu(stlw::Logger& logger, ShaderPrograms& sps, TileSharedInfoTable const& ttable, EntityRegistry& registry, ObjStore const& obj_store) { EntityDrawHandleMap entity_drawmap; // copy CUBES to GPU registry.view<ShaderName, CubeRenderable, PointLight>().each( [&](auto entity, auto& sn, auto&&...) { auto& va = sps.ref_sp(sn.value).va(); auto handle = opengl::gpu::copy_cubevertexonly_gpu(logger, va); entity_drawmap.add(entity, MOVE(handle)); }); registry.view<ShaderName, CubeRenderable, TextureRenderable>().each( [&](auto entity, auto& sn, auto&, auto& texture) { auto& va = sps.ref_sp(sn.value).va(); auto handle = opengl::gpu::copy_cubetexture_gpu(logger, va); entity_drawmap.add(entity, MOVE(handle)); }); // copy MESHES to GPU registry.view<ShaderName, MeshRenderable, Color>().each( [&](auto entity, auto& sn, auto& mesh, auto&) { auto& va = sps.ref_sp(sn.value).va(); auto const qa = BufferFlags::from_va(va); auto const qo = ObjQuery{mesh.name, qa}; auto const& obj = obj_store.get_obj(logger, qo); auto handle = opengl::gpu::copy_gpu(logger, va, obj); entity_drawmap.add(entity, MOVE(handle)); }); registry.view<ShaderName, MeshRenderable, TextureRenderable>().each( [&](auto entity, auto& sn, auto& mesh, auto& texture) { auto& va = sps.ref_sp(sn.value).va(); auto const qa = BufferFlags::from_va(va); auto const qo = ObjQuery{mesh.name, qa}; auto const& obj = obj_store.get_obj(logger, qo); auto handle = opengl::gpu::copy_gpu(logger, va, obj); entity_drawmap.add(entity, MOVE(handle)); }); registry.view<ShaderName, BillboardRenderable, TextureRenderable>().each( [&](auto entity, auto& sn, auto&, auto& texture) { auto& va = sps.ref_sp(sn.value).va(); auto const v = OF::rectangle_vertices(); auto* ti = texture.texture_info; assert(ti); auto handle = opengl::gpu::copy_rectangle_uvs(logger, va, v, *ti); entity_drawmap.add(entity, MOVE(handle)); }); registry.view<ShaderName, MeshRenderable, JunkEntityFromFILE>().each( [&](auto entity, auto& sn, auto& mesh, auto&&...) { auto& va = sps.ref_sp(sn.value).va(); auto const qa = BufferFlags::from_va(va); auto const qo = ObjQuery{mesh.name, qa}; auto const& obj = obj_store.get_obj(logger, qo); auto handle = opengl::gpu::copy_gpu(logger, va, obj); entity_drawmap.add(entity, MOVE(handle)); }); // copy TILES to GPU std::vector<DrawInfo> tile_dinfos; tile_dinfos.reserve(static_cast<size_t>(TileType::UNDEFINED)); for (auto const& it : ttable) { auto const& mesh_name = it.mesh_name; auto const& vshader_name = it.vshader_name; auto& va = sps.ref_sp(vshader_name).va(); auto const qa = BufferFlags::from_va(va); auto const qo = ObjQuery{mesh_name, qa}; auto const& obj = obj_store.get_obj(logger, qo); auto handle = opengl::gpu::copy_gpu(logger, sps.ref_sp(vshader_name).va(), obj); assert(it.type < TileType::UNDEFINED); auto const index = static_cast<size_t>(it.type); assert(index < tile_dinfos.capacity()); tile_dinfos[index] = MOVE(handle); } TileDrawHandles td{MOVE(tile_dinfos)}; return Ok(std::make_pair(MOVE(entity_drawmap), MOVE(td))); } void copy_to_gpu(stlw::Logger& logger, ZoneState& zs) { auto& ldata = zs.level_data; auto const& ttable = ldata.tiletable(); auto const& objcache = ldata.obj_store; auto& gfx_state = zs.gfx_state; auto& sps = gfx_state.sps; auto& registry = zs.registry; auto copy_result = copy_assets_gpu(logger, sps, ttable, registry, objcache); assert(copy_result); auto handles = copy_result.expect_moveout("Error copying asset to gpu"); auto edh = MOVE(handles.first); auto tdh = MOVE(handles.second); EntityDrawHandleMap bbox_dh; { auto eid = registry.create(); auto& mr = registry.assign<MeshRenderable>(eid); mr.name = "tree_lowpoly"; auto& tree_transform = registry.assign<Transform>(eid); registry.assign<Material>(eid); registry.assign<JunkEntityFromFILE>(eid); { auto& isv = registry.assign<IsVisible>(eid); isv.value = true; } registry.assign<Name>(eid).value = "custom tree"; { registry.assign<AABoundingBox>(eid); registry.assign<Selectable>(eid); auto constexpr WIREFRAME_SHADER = "wireframe"; auto& va = sps.ref_sp(WIREFRAME_SHADER).va(); auto dinfo = opengl::gpu::copy_cube_wireframevertexonly_gpu(logger, va); bbox_dh.add(eid, MOVE(dinfo)); } auto& sn = registry.assign<ShaderName>(eid); sn.value = "3d_pos_normal_color"; { auto& cc = registry.assign<Color>(eid); *&cc = LOC::WHITE; } auto& va = sps.ref_sp(sn.value).va(); ObjQuery const query{mr.name, BufferFlags{true, true, true, false}}; auto& ldata = zs.level_data; auto const& obj_store = ldata.obj_store; auto& obj = obj_store.get_obj(logger, query); auto dinfo = opengl::gpu::copy_gpu(logger, va, obj); edh.add(eid, MOVE(dinfo)); } { /* auto const add_wireframe_cube = [&](glm::vec3 const& world_pos) { auto eid = registry.create(); auto& tr = registry.assign<Transform>(eid); tr.translation = world_pos; registry.assign<Material>(eid); registry.assign<JunkEntityFromFILE>(eid); registry.assign<IsVisible>(eid).value = true; registry.assign<Selectable>(eid); registry.assign<AABoundingBox>(eid); registry.assign<CubeRenderable>(eid); registry.assign<Name>(eid).value = "collider rect"; auto& sn = registry.assign<ShaderName>(eid); sn.value = WIREFRAME_SHADER; }; add_wireframe_cube(glm::vec3{0.0f}); add_wireframe_cube(glm::vec3{5.0, 0.0f, 5.0f}); */ } auto& gpu_state = gfx_state.gpu_state; gpu_state.entities = MOVE(edh); gpu_state.entity_boundingboxes = MOVE(bbox_dh); gpu_state.tiles = MOVE(tdh); } } // namespace namespace boomhs { Result<ZoneStates, std::string> LevelAssembler::assemble_levels(stlw::Logger& logger, std::vector<EntityRegistry>& registries) { auto const level_string = [&](int const floor_number) { return "area" + std::to_string(floor_number) + ".toml"; }; auto const DUNGEON_FLOOR_COUNT = 2; std::vector<ZoneState> zstates; zstates.reserve(DUNGEON_FLOOR_COUNT + 1); stlw::float_generator rng; { // generate starting area auto& registry = registries[0]; auto level_assets = TRY_MOVEOUT(LevelLoader::load_level(logger, registry, level_string(0))); auto& ttable = level_assets.texture_table; auto& sps = level_assets.shader_programs; auto gendata = StartAreaGenerator::gen_level(logger, registry, rng, sps, ttable); ZoneState zs = assemble(MOVE(gendata), MOVE(level_assets), registry); zstates.emplace_back(MOVE(zs)); } auto const stairs_perfloor = 8; int const width = 40, height = 40; TileGridConfig const tdconfig{width, height}; // TODO: it is currently not thread safe to call load_level() from multiple threads. // // The logger isn't thread safe, need to ensure that the logger isn't using "during" level gen, // or somehow give it unique access during writing (read/write lock?). for (auto i = 0; i < DUNGEON_FLOOR_COUNT; ++i) { auto& registry = registries[i + 1]; auto level_assets = TRY_MOVEOUT(LevelLoader::load_level(logger, registry, level_string(i))); StairGenConfig const stairconfig{DUNGEON_FLOOR_COUNT, i, stairs_perfloor}; LevelConfig const config{stairconfig, tdconfig}; auto& ttable = level_assets.texture_table; auto& sps = level_assets.shader_programs; auto gendata = dungeon_generator::gen_level(logger, config, registry, rng, sps, ttable); ZoneState zs = assemble(MOVE(gendata), MOVE(level_assets), registry); zstates.emplace_back(MOVE(zs)); } // insert a teleport tile on level1 for now (hacky) zstates[1].level_data.tilegrid().data(0, 0).type = TileType::TELEPORTER; // copy the first zonestate to GPU assert(zstates.size() > 0); copy_to_gpu(logger, zstates.front()); copy_to_gpu(logger, zstates[1]); for (auto i = 2; i < DUNGEON_FLOOR_COUNT + 1; ++i) { bridge_staircases(zstates[i - 1], zstates[i]); // TODO: maybe lazily load these? copy_to_gpu(logger, zstates[i]); } return OK_MOVE(zstates); } } // namespace boomhs
#include <boomhs/billboard.hpp> #include <boomhs/components.hpp> #include <boomhs/dungeon_generator.hpp> #include <boomhs/level_assembler.hpp> #include <boomhs/level_loader.hpp> #include <boomhs/player.hpp> #include <boomhs/start_area_generator.hpp> #include <boomhs/tilegrid_algorithms.hpp> #include <boomhs/world_object.hpp> #include <boomhs/obj.hpp> #include <opengl/constants.hpp> #include <opengl/gpu.hpp> #include <opengl/lighting.hpp> #include <sstream> #include <stlw/os.hpp> #include <stlw/random.hpp> using namespace boomhs; using namespace opengl; namespace { ZoneState assemble(LevelGeneratedData&& gendata, LevelAssets&& assets, EntityRegistry& registry) { auto const player_eid = find_player(registry); EnttLookup player_lookup{player_eid, registry}; auto const FORWARD = -Z_UNIT_VECTOR; auto constexpr UP = Y_UNIT_VECTOR; WorldObject player{player_lookup, FORWARD, UP}; // Combine the generated data with the asset data, creating the LevelData instance. LevelData level_data{MOVE(gendata.tilegrid), MOVE(assets.tile_table), MOVE(gendata.startpos), MOVE(gendata.rivers), MOVE(gendata.terrain), MOVE(gendata.water), assets.fog, assets.global_light, MOVE(assets.obj_store), MOVE(player)}; GfxState gfx{MOVE(assets.shader_programs), MOVE(assets.texture_table)}; return ZoneState{MOVE(level_data), MOVE(gfx), registry}; } void bridge_staircases(ZoneState& a, ZoneState& b) { auto& tilegrid_a = a.level_data.tilegrid(); auto& tilegrid_b = b.level_data.tilegrid(); auto const stairs_up_a = find_upstairs(a.registry, tilegrid_a); assert(!stairs_up_a.empty()); auto const stairs_down_b = find_downstairs(b.registry, tilegrid_b); assert(!stairs_down_b.empty()); auto& a_registry = a.registry; auto& b_registry = b.registry; auto const behavior = TileLookupBehavior::VERTICAL_HORIZONTAL_ONLY; assert(stairs_up_a.size() == stairs_down_b.size()); auto const num_stairs = stairs_up_a.size(); FOR(i, num_stairs) { auto const a_updowneid = stairs_up_a[i]; auto const b_downeid = stairs_down_b[i]; assert(a_registry.has<StairInfo>(a_updowneid)); StairInfo& si_a = a_registry.get<StairInfo>(a_updowneid); assert(b_registry.has<StairInfo>(b_downeid)); StairInfo& si_b = b_registry.get<StairInfo>(b_downeid); // find a suitable neighbor tile for each stair auto const a_neighbors = find_immediate_neighbors(tilegrid_a, si_a.tile_position, TileType::FLOOR, behavior); assert(!a_neighbors.empty()); auto const b_neighbors = find_immediate_neighbors(tilegrid_b, si_b.tile_position, TileType::FLOOR, behavior); assert(!b_neighbors.empty()); // Set A's exit position to B's neighbor, and visa versa si_a.exit_position = b_neighbors.front(); si_b.exit_position = a_neighbors.front(); } } using copy_assets_pair_t = std::pair<EntityDrawHandleMap, TileDrawHandles>; Result<copy_assets_pair_t, std::string> copy_assets_gpu(stlw::Logger& logger, ShaderPrograms& sps, TileSharedInfoTable const& ttable, EntityRegistry& registry, ObjStore const& obj_store) { EntityDrawHandleMap entity_drawmap; // copy CUBES to GPU registry.view<ShaderName, CubeRenderable, PointLight>().each( [&](auto entity, auto& sn, auto&&...) { auto& va = sps.ref_sp(sn.value).va(); auto handle = opengl::gpu::copy_cubevertexonly_gpu(logger, va); entity_drawmap.add(entity, MOVE(handle)); }); registry.view<ShaderName, CubeRenderable, TextureRenderable>().each( [&](auto entity, auto& sn, auto&, auto& texture) { auto& va = sps.ref_sp(sn.value).va(); auto handle = opengl::gpu::copy_cubetexture_gpu(logger, va); entity_drawmap.add(entity, MOVE(handle)); }); // copy MESHES to GPU registry.view<ShaderName, MeshRenderable, Color>().each( [&](auto entity, auto& sn, auto& mesh, auto&) { auto& va = sps.ref_sp(sn.value).va(); auto const qa = BufferFlags::from_va(va); auto const qo = ObjQuery{mesh.name, qa}; auto const& obj = obj_store.get_obj(logger, qo); auto handle = opengl::gpu::copy_gpu(logger, va, obj); entity_drawmap.add(entity, MOVE(handle)); }); registry.view<ShaderName, MeshRenderable, TextureRenderable>().each( [&](auto entity, auto& sn, auto& mesh, auto& texture) { auto& va = sps.ref_sp(sn.value).va(); auto const qa = BufferFlags::from_va(va); auto const qo = ObjQuery{mesh.name, qa}; auto const& obj = obj_store.get_obj(logger, qo); auto handle = opengl::gpu::copy_gpu(logger, va, obj); entity_drawmap.add(entity, MOVE(handle)); }); registry.view<ShaderName, BillboardRenderable, TextureRenderable>().each( [&](auto entity, auto& sn, auto&, auto& texture) { auto& va = sps.ref_sp(sn.value).va(); auto const v = OF::rectangle_vertices(); auto* ti = texture.texture_info; assert(ti); auto handle = opengl::gpu::copy_rectangle_uvs(logger, va, v, *ti); entity_drawmap.add(entity, MOVE(handle)); }); registry.view<ShaderName, MeshRenderable, JunkEntityFromFILE>().each( [&](auto entity, auto& sn, auto& mesh, auto&&...) { auto& va = sps.ref_sp(sn.value).va(); auto const qa = BufferFlags::from_va(va); auto const qo = ObjQuery{mesh.name, qa}; auto const& obj = obj_store.get_obj(logger, qo); auto handle = opengl::gpu::copy_gpu(logger, va, obj); entity_drawmap.add(entity, MOVE(handle)); }); // copy TILES to GPU std::vector<DrawInfo> tile_dinfos; tile_dinfos.reserve(static_cast<size_t>(TileType::UNDEFINED)); for (auto const& it : ttable) { auto const& mesh_name = it.mesh_name; auto const& vshader_name = it.vshader_name; auto& va = sps.ref_sp(vshader_name).va(); auto const qa = BufferFlags::from_va(va); auto const qo = ObjQuery{mesh_name, qa}; auto const& obj = obj_store.get_obj(logger, qo); auto handle = opengl::gpu::copy_gpu(logger, sps.ref_sp(vshader_name).va(), obj); assert(it.type < TileType::UNDEFINED); auto const index = static_cast<size_t>(it.type); assert(index < tile_dinfos.capacity()); tile_dinfos[index] = MOVE(handle); } TileDrawHandles td{MOVE(tile_dinfos)}; return Ok(std::make_pair(MOVE(entity_drawmap), MOVE(td))); } void copy_to_gpu(stlw::Logger& logger, ZoneState& zs) { auto& ldata = zs.level_data; auto const& ttable = ldata.tiletable(); auto const& objcache = ldata.obj_store; auto& gfx_state = zs.gfx_state; auto& sps = gfx_state.sps; auto& registry = zs.registry; auto copy_result = copy_assets_gpu(logger, sps, ttable, registry, objcache); assert(copy_result); auto handles = copy_result.expect_moveout("Error copying asset to gpu"); auto edh = MOVE(handles.first); auto tdh = MOVE(handles.second); auto const add_tree = [&](auto const& world_pos) { auto eid = registry.create(); auto& mr = registry.assign<MeshRenderable>(eid); mr.name = "tree_lowpoly"; auto& tree_transform = registry.assign<Transform>(eid); tree_transform.translation = world_pos; registry.assign<Material>(eid); { auto& isv = registry.assign<IsVisible>(eid); isv.value = true; } registry.assign<Name>(eid).value = "custom tree"; auto& sn = registry.assign<ShaderName>(eid); sn.value = "3d_pos_normal_color"; { auto& cc = registry.assign<Color>(eid); *&cc = LOC::WHITE; } auto& va = sps.ref_sp(sn.value).va(); ObjQuery const query{mr.name, BufferFlags{true, true, true, false}}; auto& ldata = zs.level_data; auto const& obj_store = ldata.obj_store; auto& obj = obj_store.get_obj(logger, query); auto dinfo = opengl::gpu::copy_gpu(logger, va, obj); edh.add(eid, MOVE(dinfo)); }; add_tree(glm::vec3{0}); add_tree(glm::vec3{1}); add_tree(glm::vec3{2}); add_tree(glm::vec3{3}); EntityDrawHandleMap bbox_dh; for (auto const eid : registry.view<MeshRenderable>()) { { registry.assign<AABoundingBox>(eid); registry.assign<Selectable>(eid); auto constexpr WIREFRAME_SHADER = "wireframe"; auto& va = sps.ref_sp(WIREFRAME_SHADER).va(); auto dinfo = opengl::gpu::copy_cube_wireframevertexonly_gpu(logger, va); bbox_dh.add(eid, MOVE(dinfo)); } } auto& gpu_state = gfx_state.gpu_state; gpu_state.entities = MOVE(edh); gpu_state.entity_boundingboxes = MOVE(bbox_dh); gpu_state.tiles = MOVE(tdh); } } // namespace namespace boomhs { Result<ZoneStates, std::string> LevelAssembler::assemble_levels(stlw::Logger& logger, std::vector<EntityRegistry>& registries) { auto const level_string = [&](int const floor_number) { return "area" + std::to_string(floor_number) + ".toml"; }; auto const DUNGEON_FLOOR_COUNT = 2; std::vector<ZoneState> zstates; zstates.reserve(DUNGEON_FLOOR_COUNT + 1); stlw::float_generator rng; { // generate starting area auto& registry = registries[0]; auto level_assets = TRY_MOVEOUT(LevelLoader::load_level(logger, registry, level_string(0))); auto& ttable = level_assets.texture_table; auto& sps = level_assets.shader_programs; auto gendata = StartAreaGenerator::gen_level(logger, registry, rng, sps, ttable); ZoneState zs = assemble(MOVE(gendata), MOVE(level_assets), registry); zstates.emplace_back(MOVE(zs)); } auto const stairs_perfloor = 8; int const width = 40, height = 40; TileGridConfig const tdconfig{width, height}; // TODO: it is currently not thread safe to call load_level() from multiple threads. // // The logger isn't thread safe, need to ensure that the logger isn't using "during" level gen, // or somehow give it unique access during writing (read/write lock?). for (auto i = 0; i < DUNGEON_FLOOR_COUNT; ++i) { auto& registry = registries[i + 1]; auto level_assets = TRY_MOVEOUT(LevelLoader::load_level(logger, registry, level_string(i))); StairGenConfig const stairconfig{DUNGEON_FLOOR_COUNT, i, stairs_perfloor}; LevelConfig const config{stairconfig, tdconfig}; auto& ttable = level_assets.texture_table; auto& sps = level_assets.shader_programs; auto gendata = dungeon_generator::gen_level(logger, config, registry, rng, sps, ttable); ZoneState zs = assemble(MOVE(gendata), MOVE(level_assets), registry); zstates.emplace_back(MOVE(zs)); } // insert a teleport tile on level1 for now (hacky) zstates[1].level_data.tilegrid().data(0, 0).type = TileType::TELEPORTER; // copy the first zonestate to GPU assert(zstates.size() > 0); copy_to_gpu(logger, zstates.front()); copy_to_gpu(logger, zstates[1]); for (auto i = 2; i < DUNGEON_FLOOR_COUNT + 1; ++i) { bridge_staircases(zstates[i - 1], zstates[i]); // TODO: maybe lazily load these? copy_to_gpu(logger, zstates[i]); } return OK_MOVE(zstates); } } // namespace boomhs
Add a bounding box to each OBJ loaded through the level assembler
Add a bounding box to each OBJ loaded through the level assembler
C++
mit
bjadamson/BoomHS,bjadamson/BoomHS
b751058c517b20d9bbe3ecc8ca9bb1944b6338c0
eval/src/vespa/eval/instruction/generic_peek.cpp
eval/src/vespa/eval/instruction/generic_peek.cpp
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "generic_peek.h" #include <vespa/eval/eval/nested_loop.h> #include <vespa/eval/eval/wrap_param.h> #include <vespa/vespalib/util/overload.h> #include <vespa/vespalib/util/stash.h> #include <vespa/vespalib/util/typify.h> #include <vespa/vespalib/util/visit_ranges.h> #include <cassert> using namespace vespalib::eval::tensor_function; namespace vespalib::eval::instruction { using State = InterpretedFunction::State; using Instruction = InterpretedFunction::Instruction; namespace { static constexpr size_t npos = -1; using Spec = GenericPeek::SpecMap; size_t count_children(const Spec &spec) { size_t num_children = 0; for (const auto & [dim_name, child_or_label] : spec) { if (std::holds_alternative<size_t>(child_or_label)) { ++num_children; } } return num_children; } struct DimSpec { vespalib::stringref name; GenericPeek::MyLabel child_or_label; bool has_child() const { return std::holds_alternative<size_t>(child_or_label); } bool has_label() const { return std::holds_alternative<TensorSpec::Label>(child_or_label); } size_t get_child_idx() const { return std::get<size_t>(child_or_label); } vespalib::stringref get_label_name() const { auto label = std::get<TensorSpec::Label>(child_or_label); assert(label.is_mapped()); return label.name; } size_t get_label_index() const { auto label = std::get<TensorSpec::Label>(child_or_label); assert(label.is_indexed()); return label.index; } }; struct ExtractedSpecs { using Dimension = ValueType::Dimension; struct MyComp { bool operator() (const Dimension &a, const Spec::value_type &b) { return a.name < b.first; } bool operator() (const Spec::value_type &a, const Dimension &b) { return a.first < b.name; } }; std::vector<Dimension> dimensions; std::vector<DimSpec> specs; ExtractedSpecs(bool indexed, const std::vector<Dimension> &input_dims, const Spec &spec) { auto visitor = overload { [&](visit_ranges_first, const auto &a) { if (a.is_indexed() == indexed) dimensions.push_back(a); }, [&](visit_ranges_second, const auto &) { // spec has unknown dimension abort(); }, [&](visit_ranges_both, const auto &a, const auto &b) { if (a.is_indexed() == indexed) { dimensions.push_back(a); const auto & [spec_dim_name, child_or_label] = b; assert(a.name == spec_dim_name); specs.emplace_back(DimSpec{a.name, child_or_label}); } } }; visit_ranges(visitor, input_dims.begin(), input_dims.end(), spec.begin(), spec.end(), MyComp()); } ~ExtractedSpecs(); }; ExtractedSpecs::~ExtractedSpecs() = default; struct DenseSizes { std::vector<size_t> size; std::vector<size_t> stride; size_t cur_size; DenseSizes(const std::vector<ValueType::Dimension> &dims) : size(), stride(), cur_size(1) { for (const auto &dim : dims) { assert(dim.is_indexed()); size.push_back(dim.size); } stride.resize(size.size()); for (size_t i = size.size(); i-- > 0; ) { stride[i] = cur_size; cur_size *= size[i]; } } }; /** Compute input offsets for all output cells */ struct DensePlan { size_t in_dense_size; size_t out_dense_size; std::vector<size_t> loop_cnt; std::vector<size_t> in_stride; size_t verbatim_offset = 0; struct Child { size_t idx; size_t stride; size_t limit; }; std::vector<Child> children; DensePlan(const ValueType &input_type, const Spec &spec) { const ExtractedSpecs mine(true, input_type.dimensions(), spec); DenseSizes sizes(mine.dimensions); in_dense_size = sizes.cur_size; out_dense_size = 1; auto pos = mine.specs.begin(); for (size_t i = 0; i < mine.dimensions.size(); ++i) { const auto &dim = mine.dimensions[i]; if ((pos == mine.specs.end()) || (dim.name < pos->name)) { loop_cnt.push_back(sizes.size[i]); in_stride.push_back(sizes.stride[i]); out_dense_size *= sizes.size[i]; } else { assert(dim.name == pos->name); if (pos->has_child()) { children.push_back(Child{pos->get_child_idx(), sizes.stride[i], sizes.size[i]}); } else { assert(pos->has_label()); size_t label_index = pos->get_label_index(); assert(label_index < sizes.size[i]); verbatim_offset += label_index * sizes.stride[i]; } ++pos; } } assert(pos == mine.specs.end()); } /** Get initial offset (from verbatim labels and child values) */ template <typename Getter> size_t get_offset(const Getter &get_child_value) const { size_t offset = verbatim_offset; for (size_t i = 0; i < children.size(); ++i) { size_t from_child = get_child_value(children[i].idx); if (from_child < children[i].limit) { offset += from_child * children[i].stride; } else { return npos; } } return offset; } template<typename F> void execute(size_t offset, const F &f) const { run_nested_loop<F>(offset, loop_cnt, in_stride, f); } }; struct SparseState { std::vector<vespalib::string> view_addr; std::vector<vespalib::stringref> view_refs; std::vector<const vespalib::stringref *> lookup_refs; std::vector<vespalib::stringref> output_addr; std::vector<vespalib::stringref *> fetch_addr; SparseState(std::vector<vespalib::string> view_addr_in, size_t out_dims) : view_addr(std::move(view_addr_in)), view_refs(view_addr.size()), lookup_refs(view_addr.size()), output_addr(out_dims), fetch_addr(out_dims) { for (size_t i = 0; i < view_addr.size(); ++i) { view_refs[i] = view_addr[i]; lookup_refs[i] = &view_refs[i]; } for (size_t i = 0; i < out_dims; ++i) { fetch_addr[i] = &output_addr[i]; } } ~SparseState(); }; SparseState::~SparseState() = default; struct SparsePlan { size_t out_mapped_dims; std::vector<DimSpec> lookup_specs; std::vector<size_t> view_dims; SparsePlan(const ValueType &input_type, const GenericPeek::SpecMap &spec) : out_mapped_dims(0), view_dims() { ExtractedSpecs mine(false, input_type.dimensions(), spec); lookup_specs = std::move(mine.specs); auto pos = lookup_specs.begin(); for (size_t dim_idx = 0; dim_idx < mine.dimensions.size(); ++dim_idx) { const auto & dim = mine.dimensions[dim_idx]; if ((pos == lookup_specs.end()) || (dim.name < pos->name)) { ++out_mapped_dims; } else { assert(dim.name == pos->name); view_dims.push_back(dim_idx); ++pos; } } assert(pos == lookup_specs.end()); } ~SparsePlan(); template <typename Getter> SparseState make_state(const Getter &get_child_value) const { std::vector<vespalib::string> view_addr; for (const auto & dim : lookup_specs) { if (dim.has_child()) { int64_t child_value = get_child_value(dim.get_child_idx()); view_addr.push_back(vespalib::make_string("%" PRId64, child_value)); } else { view_addr.push_back(dim.get_label_name()); } } assert(view_addr.size() == view_dims.size()); return SparseState(std::move(view_addr), out_mapped_dims); } }; SparsePlan::~SparsePlan() = default; struct PeekParam { const ValueType res_type; DensePlan dense_plan; SparsePlan sparse_plan; size_t num_children; const ValueBuilderFactory &factory; PeekParam(const ValueType &input_type, const ValueType &res_type_in, const GenericPeek::SpecMap &spec_in, const ValueBuilderFactory &factory_in) : res_type(res_type_in), dense_plan(input_type, spec_in), sparse_plan(input_type, spec_in), num_children(count_children(spec_in)), factory(factory_in) { assert(dense_plan.in_dense_size == input_type.dense_subspace_size()); assert(dense_plan.out_dense_size == res_type.dense_subspace_size()); } }; template <typename ICT, typename OCT, typename Getter> Value::UP generic_mixed_peek(const ValueType &res_type, const Value &input_value, const SparsePlan &sparse_plan, const DensePlan &dense_plan, const ValueBuilderFactory &factory, const Getter &get_child_value) { auto input_cells = input_value.cells().typify<ICT>(); size_t bad_guess = 1; auto builder = factory.create_value_builder<OCT>(res_type, sparse_plan.out_mapped_dims, dense_plan.out_dense_size, bad_guess); size_t filled_subspaces = 0; size_t dense_offset = dense_plan.get_offset(get_child_value); if (dense_offset != npos) { SparseState state = sparse_plan.make_state(get_child_value); auto view = input_value.index().create_view(sparse_plan.view_dims); view->lookup(state.lookup_refs); size_t input_subspace; while (view->next_result(state.fetch_addr, input_subspace)) { auto dst = builder->add_subspace(state.output_addr).begin(); auto input_offset = input_subspace * dense_plan.in_dense_size; dense_plan.execute(dense_offset + input_offset, [&](size_t idx) { *dst++ = input_cells[idx]; }); ++filled_subspaces; } } if ((sparse_plan.out_mapped_dims == 0) && (filled_subspaces == 0)) { for (auto & v : builder->add_subspace({})) { v = OCT{}; } } return builder->build(std::move(builder)); } template <typename ICT, typename OCT> void my_generic_peek_op(State &state, uint64_t param_in) { const auto &param = unwrap_param<PeekParam>(param_in); const Value & input_value = state.peek(param.num_children); const size_t last_child = param.num_children - 1; auto get_child_value = [&] (size_t child_idx) { size_t stack_idx = last_child - child_idx; return int64_t(state.peek(stack_idx).as_double()); }; auto up = generic_mixed_peek<ICT,OCT>(param.res_type, input_value, param.sparse_plan, param.dense_plan, param.factory, get_child_value); const Value &result = *state.stash.create<Value::UP>(std::move(up)); // num_children does not include the "input" param state.pop_n_push(param.num_children + 1, result); } struct SelectGenericPeekOp { template <typename ICT, typename OCT> static auto invoke() { return my_generic_peek_op<ICT,OCT>; } }; //----------------------------------------------------------------------------- } // namespace <unnamed> Instruction GenericPeek::make_instruction(const ValueType &input_type, const ValueType &res_type, const SpecMap &spec, const ValueBuilderFactory &factory, Stash &stash) { const auto &param = stash.create<PeekParam>(input_type, res_type, spec, factory); auto fun = typify_invoke<2,TypifyCellType,SelectGenericPeekOp>(input_type.cell_type(), res_type.cell_type()); return Instruction(fun, wrap_param<PeekParam>(param)); } } // namespace
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "generic_peek.h" #include <vespa/eval/eval/nested_loop.h> #include <vespa/eval/eval/wrap_param.h> #include <vespa/vespalib/util/overload.h> #include <vespa/vespalib/util/stash.h> #include <vespa/vespalib/util/typify.h> #include <vespa/vespalib/util/visit_ranges.h> #include <cassert> using namespace vespalib::eval::tensor_function; namespace vespalib::eval::instruction { using State = InterpretedFunction::State; using Instruction = InterpretedFunction::Instruction; namespace { static constexpr size_t npos = -1; using Spec = GenericPeek::SpecMap; size_t count_children(const Spec &spec) { size_t num_children = 0; for (const auto & [dim_name, child_or_label] : spec) { if (std::holds_alternative<size_t>(child_or_label)) { ++num_children; } } return num_children; } struct DimSpec { vespalib::stringref name; GenericPeek::MyLabel child_or_label; bool has_child() const { return std::holds_alternative<size_t>(child_or_label); } bool has_label() const { return std::holds_alternative<TensorSpec::Label>(child_or_label); } size_t get_child_idx() const { return std::get<size_t>(child_or_label); } vespalib::stringref get_label_name() const { auto & label = std::get<TensorSpec::Label>(child_or_label); assert(label.is_mapped()); return label.name; } size_t get_label_index() const { auto & label = std::get<TensorSpec::Label>(child_or_label); assert(label.is_indexed()); return label.index; } }; struct ExtractedSpecs { using Dimension = ValueType::Dimension; struct MyComp { bool operator() (const Dimension &a, const Spec::value_type &b) { return a.name < b.first; } bool operator() (const Spec::value_type &a, const Dimension &b) { return a.first < b.name; } }; std::vector<Dimension> dimensions; std::vector<DimSpec> specs; ExtractedSpecs(bool indexed, const std::vector<Dimension> &input_dims, const Spec &spec) { auto visitor = overload { [&](visit_ranges_first, const auto &a) { if (a.is_indexed() == indexed) dimensions.push_back(a); }, [&](visit_ranges_second, const auto &) { // spec has unknown dimension abort(); }, [&](visit_ranges_both, const auto &a, const auto &b) { if (a.is_indexed() == indexed) { dimensions.push_back(a); const auto & [spec_dim_name, child_or_label] = b; assert(a.name == spec_dim_name); specs.emplace_back(DimSpec{a.name, child_or_label}); } } }; visit_ranges(visitor, input_dims.begin(), input_dims.end(), spec.begin(), spec.end(), MyComp()); } ~ExtractedSpecs(); }; ExtractedSpecs::~ExtractedSpecs() = default; struct DenseSizes { std::vector<size_t> size; std::vector<size_t> stride; size_t cur_size; DenseSizes(const std::vector<ValueType::Dimension> &dims) : size(), stride(), cur_size(1) { for (const auto &dim : dims) { assert(dim.is_indexed()); size.push_back(dim.size); } stride.resize(size.size()); for (size_t i = size.size(); i-- > 0; ) { stride[i] = cur_size; cur_size *= size[i]; } } }; /** Compute input offsets for all output cells */ struct DensePlan { size_t in_dense_size; size_t out_dense_size; std::vector<size_t> loop_cnt; std::vector<size_t> in_stride; size_t verbatim_offset = 0; struct Child { size_t idx; size_t stride; size_t limit; }; std::vector<Child> children; DensePlan(const ValueType &input_type, const Spec &spec) { const ExtractedSpecs mine(true, input_type.dimensions(), spec); DenseSizes sizes(mine.dimensions); in_dense_size = sizes.cur_size; out_dense_size = 1; auto pos = mine.specs.begin(); for (size_t i = 0; i < mine.dimensions.size(); ++i) { const auto &dim = mine.dimensions[i]; if ((pos == mine.specs.end()) || (dim.name < pos->name)) { loop_cnt.push_back(sizes.size[i]); in_stride.push_back(sizes.stride[i]); out_dense_size *= sizes.size[i]; } else { assert(dim.name == pos->name); if (pos->has_child()) { children.push_back(Child{pos->get_child_idx(), sizes.stride[i], sizes.size[i]}); } else { assert(pos->has_label()); size_t label_index = pos->get_label_index(); assert(label_index < sizes.size[i]); verbatim_offset += label_index * sizes.stride[i]; } ++pos; } } assert(pos == mine.specs.end()); } /** Get initial offset (from verbatim labels and child values) */ template <typename Getter> size_t get_offset(const Getter &get_child_value) const { size_t offset = verbatim_offset; for (size_t i = 0; i < children.size(); ++i) { size_t from_child = get_child_value(children[i].idx); if (from_child < children[i].limit) { offset += from_child * children[i].stride; } else { return npos; } } return offset; } template<typename F> void execute(size_t offset, const F &f) const { run_nested_loop<F>(offset, loop_cnt, in_stride, f); } }; struct SparseState { std::vector<vespalib::string> view_addr; std::vector<vespalib::stringref> view_refs; std::vector<const vespalib::stringref *> lookup_refs; std::vector<vespalib::stringref> output_addr; std::vector<vespalib::stringref *> fetch_addr; SparseState(std::vector<vespalib::string> view_addr_in, size_t out_dims) : view_addr(std::move(view_addr_in)), view_refs(view_addr.size()), lookup_refs(view_addr.size()), output_addr(out_dims), fetch_addr(out_dims) { for (size_t i = 0; i < view_addr.size(); ++i) { view_refs[i] = view_addr[i]; lookup_refs[i] = &view_refs[i]; } for (size_t i = 0; i < out_dims; ++i) { fetch_addr[i] = &output_addr[i]; } } ~SparseState(); }; SparseState::~SparseState() = default; struct SparsePlan { size_t out_mapped_dims; std::vector<DimSpec> lookup_specs; std::vector<size_t> view_dims; SparsePlan(const ValueType &input_type, const GenericPeek::SpecMap &spec) : out_mapped_dims(0), view_dims() { ExtractedSpecs mine(false, input_type.dimensions(), spec); lookup_specs = std::move(mine.specs); auto pos = lookup_specs.begin(); for (size_t dim_idx = 0; dim_idx < mine.dimensions.size(); ++dim_idx) { const auto & dim = mine.dimensions[dim_idx]; if ((pos == lookup_specs.end()) || (dim.name < pos->name)) { ++out_mapped_dims; } else { assert(dim.name == pos->name); view_dims.push_back(dim_idx); ++pos; } } assert(pos == lookup_specs.end()); } ~SparsePlan(); template <typename Getter> SparseState make_state(const Getter &get_child_value) const { std::vector<vespalib::string> view_addr; for (const auto & dim : lookup_specs) { if (dim.has_child()) { int64_t child_value = get_child_value(dim.get_child_idx()); view_addr.push_back(vespalib::make_string("%" PRId64, child_value)); } else { view_addr.push_back(dim.get_label_name()); } } assert(view_addr.size() == view_dims.size()); return SparseState(std::move(view_addr), out_mapped_dims); } }; SparsePlan::~SparsePlan() = default; struct PeekParam { const ValueType res_type; DensePlan dense_plan; SparsePlan sparse_plan; size_t num_children; const ValueBuilderFactory &factory; PeekParam(const ValueType &input_type, const ValueType &res_type_in, const GenericPeek::SpecMap &spec_in, const ValueBuilderFactory &factory_in) : res_type(res_type_in), dense_plan(input_type, spec_in), sparse_plan(input_type, spec_in), num_children(count_children(spec_in)), factory(factory_in) { assert(dense_plan.in_dense_size == input_type.dense_subspace_size()); assert(dense_plan.out_dense_size == res_type.dense_subspace_size()); } }; template <typename ICT, typename OCT, typename Getter> Value::UP generic_mixed_peek(const ValueType &res_type, const Value &input_value, const SparsePlan &sparse_plan, const DensePlan &dense_plan, const ValueBuilderFactory &factory, const Getter &get_child_value) { auto input_cells = input_value.cells().typify<ICT>(); size_t bad_guess = 1; auto builder = factory.create_value_builder<OCT>(res_type, sparse_plan.out_mapped_dims, dense_plan.out_dense_size, bad_guess); size_t filled_subspaces = 0; size_t dense_offset = dense_plan.get_offset(get_child_value); if (dense_offset != npos) { SparseState state = sparse_plan.make_state(get_child_value); auto view = input_value.index().create_view(sparse_plan.view_dims); view->lookup(state.lookup_refs); size_t input_subspace; while (view->next_result(state.fetch_addr, input_subspace)) { auto dst = builder->add_subspace(state.output_addr).begin(); auto input_offset = input_subspace * dense_plan.in_dense_size; dense_plan.execute(dense_offset + input_offset, [&](size_t idx) { *dst++ = input_cells[idx]; }); ++filled_subspaces; } } if ((sparse_plan.out_mapped_dims == 0) && (filled_subspaces == 0)) { for (auto & v : builder->add_subspace({})) { v = OCT{}; } } return builder->build(std::move(builder)); } template <typename ICT, typename OCT> void my_generic_peek_op(State &state, uint64_t param_in) { const auto &param = unwrap_param<PeekParam>(param_in); const Value & input_value = state.peek(param.num_children); const size_t last_child = param.num_children - 1; auto get_child_value = [&] (size_t child_idx) { size_t stack_idx = last_child - child_idx; return int64_t(state.peek(stack_idx).as_double()); }; auto up = generic_mixed_peek<ICT,OCT>(param.res_type, input_value, param.sparse_plan, param.dense_plan, param.factory, get_child_value); const Value &result = *state.stash.create<Value::UP>(std::move(up)); // num_children does not include the "input" param state.pop_n_push(param.num_children + 1, result); } struct SelectGenericPeekOp { template <typename ICT, typename OCT> static auto invoke() { return my_generic_peek_op<ICT,OCT>; } }; //----------------------------------------------------------------------------- } // namespace <unnamed> Instruction GenericPeek::make_instruction(const ValueType &input_type, const ValueType &res_type, const SpecMap &spec, const ValueBuilderFactory &factory, Stash &stash) { const auto &param = stash.create<PeekParam>(input_type, res_type, spec, factory); auto fun = typify_invoke<2,TypifyCellType,SelectGenericPeekOp>(input_type.cell_type(), res_type.cell_type()); return Instruction(fun, wrap_param<PeekParam>(param)); } } // namespace
fix bug found by AddressSanitizer
fix bug found by AddressSanitizer * using "auto label" would copy the TensorSpec::Label (including its string) into a temporary stack object, and then we would reference into the temporary with a stringref.
C++
apache-2.0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
83cb09442ee76e4dfe1820432229e15a638371bc
tensorflow/core/tpu/tpu_initializer_helper.cc
tensorflow/core/tpu/tpu_initializer_helper.cc
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/tpu/tpu_initializer_helper.h" #include <fcntl.h> #include <stdlib.h> #include <unistd.h> #include "absl/strings/str_cat.h" #include "absl/strings/str_split.h" #include "absl/synchronization/mutex.h" #include "tensorflow/core/platform/logging.h" namespace tensorflow { namespace tpu { namespace { static std::string GetEnvVar(const char* name) { // Constructing a std::string directly from nullptr is undefined behavior. return absl::StrCat(getenv(name)); } } // namespace bool TryAcquireTpuLock() { static absl::Mutex* mu = new absl::Mutex(); absl::MutexLock l(mu); static bool attempted_file_open = false; static bool should_load_library = false; if (!attempted_file_open) { std::string load_library_override = absl::StrCat(getenv("TPU_LOAD_LIBRARY")); if (load_library_override == "1") { return true; } else if (load_library_override == "0") { return false; } should_load_library = true; // If TPU_CHIPS_PER_HOST_BOUND doesn't include all chips, we assume we're // using different chips in different processes and thus multiple libtpu // loads are ok. // TODO(skyewm): we could make per-chip lock files and look at // TPU_VISIBLE_DEVICES if we wanted to make this really precise. std::string chips_per_host_bounds = GetEnvVar("TPU_CHIPS_PER_HOST_BOUNDS"); if (chips_per_host_bounds.empty() || chips_per_host_bounds == "2,2,1") { int fd = open("/tmp/libtpu_lockfile", O_CREAT | O_RDWR, 0644); // This lock is held until the process exits intentionally. The underlying // TPU device will be held on until it quits. if (lockf(fd, F_TLOCK, 0) != 0) { LOG(INFO) << "libtpu.so already in used by another process. Not " "attempting to load libtpu.so in this process."; should_load_library = false; } else { should_load_library = true; } } else { VLOG(1) << "TPU_HOST_BOUNDS or TPU_VISIBLE_DEVICES is not empty, " "therefore allowing multiple libtpu.so loads."; should_load_library = true; } } return should_load_library; } std::pair<std::vector<std::string>, std::vector<const char*>> GetLibTpuInitArguments() { // We make copies of the arguments returned by getenv because the memory // returned may be altered or invalidated by further calls to getenv. std::vector<std::string> args; std::vector<const char*> arg_ptrs; // Retrieve arguments from environment if applicable. char* env = getenv("LIBTPU_INIT_ARGS"); if (env != nullptr) { // TODO(frankchn): Handles quotes properly if necessary. args = absl::StrSplit(env, ' '); } arg_ptrs.reserve(args.size()); for (int i = 0; i < args.size(); ++i) { arg_ptrs.push_back(args[i].data()); } return {std::move(args), std::move(arg_ptrs)}; } } // namespace tpu } // namespace tensorflow
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/tpu/tpu_initializer_helper.h" #include <fcntl.h> #include <stdlib.h> #include <unistd.h> #include "absl/strings/str_cat.h" #include "absl/strings/str_split.h" #include "absl/synchronization/mutex.h" #include "tensorflow/core/platform/logging.h" namespace tensorflow { namespace tpu { namespace { static std::string GetEnvVar(const char* name) { // Constructing a std::string directly from nullptr is undefined behavior. return absl::StrCat(getenv(name)); } } // namespace bool TryAcquireTpuLock() { static absl::Mutex* mu = new absl::Mutex(); absl::MutexLock l(mu); static bool attempted_file_open = false; static bool should_load_library = false; if (!attempted_file_open) { std::string load_library_override = absl::StrCat(getenv("TPU_LOAD_LIBRARY")); if (load_library_override == "1") { return true; } else if (load_library_override == "0") { return false; } should_load_library = true; // If TPU_CHIPS_PER_PROCESS_BOUNDS doesn't include all chips, we assume // we're using different chips in different processes and thus multiple // libtpu loads are ok. // TODO(skyewm): we could make per-chip lock files and look at // TPU_VISIBLE_DEVICES if we wanted to make this really precise. std::string chips_per_process_bounds = GetEnvVar("TPU_CHIPS_PER_PROCESS_BOUNDS"); // TODO(skyewm): remove this when TPU_CHIPS_PER_HOST_BOUNDS is fully // deprecated if (chips_per_process_bounds.empty()) { chips_per_process_bounds = GetEnvVar("TPU_CHIPS_PER_HOST_BOUNDS"); } if (chips_per_process_bounds.empty() || chips_per_process_bounds == "2,2,1") { int fd = open("/tmp/libtpu_lockfile", O_CREAT | O_RDWR, 0644); // This lock is held until the process exits intentionally. The underlying // TPU device will be held on until it quits. if (lockf(fd, F_TLOCK, 0) != 0) { LOG(INFO) << "libtpu.so already in use by another process. Not " "attempting to load libtpu.so in this process."; should_load_library = false; } else { should_load_library = true; } } else { VLOG(1) << "TPU_HOST_BOUNDS or TPU_VISIBLE_DEVICES is not empty, " "therefore allowing multiple libtpu.so loads."; should_load_library = true; } } return should_load_library; } std::pair<std::vector<std::string>, std::vector<const char*>> GetLibTpuInitArguments() { // We make copies of the arguments returned by getenv because the memory // returned may be altered or invalidated by further calls to getenv. std::vector<std::string> args; std::vector<const char*> arg_ptrs; // Retrieve arguments from environment if applicable. char* env = getenv("LIBTPU_INIT_ARGS"); if (env != nullptr) { // TODO(frankchn): Handles quotes properly if necessary. args = absl::StrSplit(env, ' '); } arg_ptrs.reserve(args.size()); for (int i = 0; i < args.size(); ++i) { arg_ptrs.push_back(args[i].data()); } return {std::move(args), std::move(arg_ptrs)}; } } // namespace tpu } // namespace tensorflow
Update Cloud TPU VM topology env vars
Update Cloud TPU VM topology env vars PiperOrigin-RevId: 402352593 Change-Id: I584f40675883106d5939b58522bfc3b10a6d167e
C++
apache-2.0
tensorflow/tensorflow-pywrap_saved_model,gautam1858/tensorflow,paolodedios/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-tensorflow/tensorflow,gautam1858/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,gautam1858/tensorflow,yongtang/tensorflow,karllessard/tensorflow,karllessard/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,Intel-Corporation/tensorflow,yongtang/tensorflow,gautam1858/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_saved_model,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,paolodedios/tensorflow,karllessard/tensorflow,yongtang/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_saved_model,Intel-Corporation/tensorflow,tensorflow/tensorflow-pywrap_saved_model,yongtang/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-tensorflow/tensorflow,karllessard/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,tensorflow/tensorflow,paolodedios/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,karllessard/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,paolodedios/tensorflow,tensorflow/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow,paolodedios/tensorflow,karllessard/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gautam1858/tensorflow,Intel-tensorflow/tensorflow,yongtang/tensorflow,gautam1858/tensorflow,Intel-Corporation/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-Corporation/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,karllessard/tensorflow,yongtang/tensorflow,Intel-tensorflow/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-Corporation/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow,Intel-tensorflow/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow,paolodedios/tensorflow,yongtang/tensorflow,karllessard/tensorflow,yongtang/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,gautam1858/tensorflow,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,yongtang/tensorflow,Intel-tensorflow/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow,gautam1858/tensorflow
ab63bb576525aa44b0b2becd2fb17f74b2d017aa
test/test_main.cc
test/test_main.cc
/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "rtc_base/flags.h" #include "rtc_base/logging.h" #include "system_wrappers/include/metrics_default.h" #include "test/field_trial.h" #include "test/gmock.h" #include "test/gtest.h" #include "test/testsupport/fileutils.h" #if defined(WEBRTC_IOS) #include "test/ios/test_support.h" DEFINE_string(NSTreatUnknownArgumentsAsOpen, "", "Intentionally ignored flag intended for iOS simulator."); DEFINE_string(ApplePersistenceIgnoreState, "", "Intentionally ignored flag intended for iOS simulator."); #endif DEFINE_bool(logs, false, "print logs to stderr"); DEFINE_string(force_fieldtrials, "", "Field trials control experimental feature code which can be forced. " "E.g. running with --force_fieldtrials=WebRTC-FooFeature/Enable/" " will assign the group Enable to field trial WebRTC-FooFeature."); DEFINE_bool(help, false, "Print this message."); int main(int argc, char* argv[]) { ::testing::InitGoogleMock(&argc, argv); // Default to LS_INFO, even for release builds to provide better test logging. // TODO(pbos): Consider adding a command-line override. if (rtc::LogMessage::GetLogToDebug() > rtc::LS_INFO) rtc::LogMessage::LogToDebug(rtc::LS_INFO); if (rtc::FlagList::SetFlagsFromCommandLine(&argc, argv, false)) { return 1; } if (FLAG_help) { rtc::FlagList::Print(nullptr, false); return 0; } webrtc::test::SetExecutablePath(argv[0]); std::string fieldtrials = FLAG_force_fieldtrials; webrtc::test::InitFieldTrialsFromString(fieldtrials); webrtc::metrics::Enable(); rtc::LogMessage::SetLogToStderr(FLAG_logs); #if defined(WEBRTC_IOS) rtc::test::InitTestSuite(RUN_ALL_TESTS, argc, argv); rtc::test::RunTestsFromIOSApp(); #endif return RUN_ALL_TESTS(); }
/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "rtc_base/file.h" #include "rtc_base/flags.h" #include "rtc_base/logging.h" #include "system_wrappers/include/metrics_default.h" #include "test/field_trial.h" #include "test/gmock.h" #include "test/gtest.h" #include "test/testsupport/fileutils.h" #include "test/testsupport/perf_test.h" #if defined(WEBRTC_IOS) #include "test/ios/test_support.h" DEFINE_string(NSTreatUnknownArgumentsAsOpen, "", "Intentionally ignored flag intended for iOS simulator."); DEFINE_string(ApplePersistenceIgnoreState, "", "Intentionally ignored flag intended for iOS simulator."); #endif DEFINE_bool(logs, false, "print logs to stderr"); DEFINE_string(force_fieldtrials, "", "Field trials control experimental feature code which can be forced. " "E.g. running with --force_fieldtrials=WebRTC-FooFeature/Enable/" " will assign the group Enable to field trial WebRTC-FooFeature."); DEFINE_string( perf_results_json_path, "", "Path where the perf results should be stored it the JSON format described " "by " "https://github.com/catapult-project/catapult/blob/master/dashboard/docs/" "data-format.md."); DEFINE_bool(help, false, "Print this message."); int main(int argc, char* argv[]) { ::testing::InitGoogleMock(&argc, argv); // Default to LS_INFO, even for release builds to provide better test logging. // TODO(pbos): Consider adding a command-line override. if (rtc::LogMessage::GetLogToDebug() > rtc::LS_INFO) rtc::LogMessage::LogToDebug(rtc::LS_INFO); if (rtc::FlagList::SetFlagsFromCommandLine(&argc, argv, false)) { return 1; } if (FLAG_help) { rtc::FlagList::Print(nullptr, false); return 0; } webrtc::test::SetExecutablePath(argv[0]); std::string fieldtrials = FLAG_force_fieldtrials; webrtc::test::InitFieldTrialsFromString(fieldtrials); webrtc::metrics::Enable(); rtc::LogMessage::SetLogToStderr(FLAG_logs); #if defined(WEBRTC_IOS) rtc::test::InitTestSuite(RUN_ALL_TESTS, argc, argv); rtc::test::RunTestsFromIOSApp(); #endif int exit_code = RUN_ALL_TESTS(); std::string perf_results_json_path = FLAG_perf_results_json_path; if (perf_results_json_path != "") { std::string json_results = webrtc::test::GetPerfResultsJSON(); rtc::File json_file = rtc::File::Open(perf_results_json_path); json_file.Write(reinterpret_cast<const uint8_t*>(json_results.c_str()), json_results.size()); json_file.Close(); } return exit_code; }
Add a flag to store perf results as a JSON file.
Add a flag to store perf results as a JSON file. Add a flag to store perf results as a JSON file in the format specified by https://github.com/catapult-project/catapult/blob/master/dashboard/docs/data-format.md Bug: webrtc:7156 Change-Id: Ia5b0317f0f5dc8767fa219f42bc39bf4073203e8 Reviewed-on: https://webrtc-review.googlesource.com/29160 Reviewed-by: Patrik Höglund <[email protected]> Commit-Queue: Edward Lemur <[email protected]> Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#21082}
C++
bsd-3-clause
TimothyGu/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc,ShiftMediaProject/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc
26c2bca77ee80ae8b7413bd11f78280116606e78
examples/exti/exti.cpp
examples/exti/exti.cpp
/* * This file is a part of the open source stm32plus library. * Copyright (c) 2011,2012,2013,2014 Andy Brown <www.andybrown.me.uk> * Please see website for licensing terms. */ #include "config/stm32plus.h" #include "config/button.h" #include "config/exti.h" using namespace stm32plus; /** * Button demo that uses EXTI interrupts to signal that the button is pressed. * EXTI allows you to process input from GPIO pins asynchronously. * * This demo assumes that you have a button on PA8 and an LED on PF6. The LED * will light as long as the button is held down. * * An Exti8 (external interrupt) is attached to PA8 and is configured to trigger * on both rising (pressed) and falling (released) edges. * * To use this demo on the STM32F4DISCOVERY board you will need to make the * following changes to target the onboard button and LEDs: * * LED_PIN to 13 * BUTTON_PIN to 0 * GpioF... to GpioD... * Exti8 to Exit0 * * To use this demo on the STM32VLDISCOVERY board you will need to make the * following changes to target the onboard button and LEDs: * * LED_PIN to 8 * BUTTON_PIN to 0 * GpioF... to GpioC... * Exti8 to Exti0 * * Compatible MCU: * STM32F0 * STM32F1 * STM32F4 * * Tested on devices: * STM32F051R8T6 * STM32F100RBT6 * STM32F103ZET6 * STM32F407VGT6 */ class ExtiTest { protected: volatile bool _stateChanged; enum { LED_PIN = 6, BUTTON_PIN = 8 }; public: void run() { // initialise the LED and button pins GpioF<DefaultDigitalOutputFeature<LED_PIN> > pf; GpioA<DefaultDigitalInputFeature<BUTTON_PIN> > pa; // enable EXTI on the button pin and subscribe to interrupts Exti8 exti(EXTI_Mode_Interrupt,EXTI_Trigger_Rising_Falling,pa[BUTTON_PIN]); exti.ExtiInterruptEventSender.insertSubscriber( ExtiInterruptEventSourceSlot::bind(this,&ExtiTest::onInterrupt) ); // lights off (this LED is active low, i.e. PF6 is a sink) pf[LED_PIN].set(); // main loop for(;;) { _stateChanged=false; // race conditition, but it's demo code... // wait for the interrupt to tell us that there's been a button press/release while(!_stateChanged); // act on the new state and reset for the next run pf[LED_PIN].setState(pa[BUTTON_PIN].read()); } } /** * Interrupt callback from the EXTI interrupt */ void onInterrupt(uint8_t /* extiLine */) { _stateChanged=true; } }; /* * Main entry point */ int main() { ExtiTest test; test.run(); // not reached return 0; }
/* * This file is a part of the open source stm32plus library. * Copyright (c) 2011,2012,2013,2014 Andy Brown <www.andybrown.me.uk> * Please see website for licensing terms. */ #include "config/stm32plus.h" #include "config/button.h" #include "config/exti.h" using namespace stm32plus; /** * Button demo that uses EXTI interrupts to signal that the button is pressed. * EXTI allows you to process input from GPIO pins asynchronously. * * This demo assumes that you have a button on PA8 and an LED on PF6. The LED * will light as long as the button is held down. * * An Exti8 (external interrupt) is attached to PA8 and is configured to trigger * on both rising (pressed) and falling (released) edges. * * To use this demo on the STM32F4DISCOVERY board you will need to make the * following changes to target the onboard button and LEDs: * * LED_PIN to 13 * BUTTON_PIN to 0 * GpioF... to GpioD... * Exti8 to Exit0 * * To use this demo on the STM32VLDISCOVERY or the STM32F0DISCOVERY board you * will need to make the following changes to target the onboard button and LEDs: * * LED_PIN to 8 * BUTTON_PIN to 0 * GpioF... to GpioC... * Exti8 to Exti0 * * Compatible MCU: * STM32F0 * STM32F1 * STM32F4 * * Tested on devices: * STM32F051R8T6 * STM32F100RBT6 * STM32F103ZET6 * STM32F407VGT6 */ class ExtiTest { protected: volatile bool _stateChanged; enum { LED_PIN = 6, BUTTON_PIN = 8 }; public: void run() { // initialise the LED and button pins GpioF<DefaultDigitalOutputFeature<LED_PIN> > pf; GpioA<DefaultDigitalInputFeature<BUTTON_PIN> > pa; // enable EXTI on the button pin and subscribe to interrupts Exti8 exti(EXTI_Mode_Interrupt,EXTI_Trigger_Rising_Falling,pa[BUTTON_PIN]); exti.ExtiInterruptEventSender.insertSubscriber( ExtiInterruptEventSourceSlot::bind(this,&ExtiTest::onInterrupt) ); // lights off (this LED is active low, i.e. PF6 is a sink) pf[LED_PIN].set(); // main loop for(;;) { _stateChanged=false; // race conditition, but it's demo code... // wait for the interrupt to tell us that there's been a button press/release while(!_stateChanged); // act on the new state and reset for the next run pf[LED_PIN].setState(pa[BUTTON_PIN].read()); } } /** * Interrupt callback from the EXTI interrupt */ void onInterrupt(uint8_t /* extiLine */) { _stateChanged=true; } }; /* * Main entry point */ int main() { ExtiTest test; test.run(); // not reached return 0; }
include f0 in comment
include f0 in comment
C++
bsd-3-clause
trigrass2/stm32plus,phynex/stm32plus,phynex/stm32plus,tokoro10g/stm32plus,phynex/stm32plus,ThanhVic/stm32plus,punkkeks/stm32plus,ThanhVic/stm32plus,punkkeks/stm32plus,trigrass2/stm32plus,ThanhVic/stm32plus,ThanhVic/stm32plus,lcbowling/stm32plus,tokoro10g/stm32plus,tokoro10g/stm32plus,lcbowling/stm32plus,tokoro10g/stm32plus,tokoro10g/stm32plus,punkkeks/stm32plus,trigrass2/stm32plus,trigrass2/stm32plus,punkkeks/stm32plus,phynex/stm32plus,spiralray/stm32plus,punkkeks/stm32plus,lcbowling/stm32plus,punkkeks/stm32plus,trigrass2/stm32plus,lcbowling/stm32plus,tokoro10g/stm32plus,spiralray/stm32plus,phynex/stm32plus,lcbowling/stm32plus,lcbowling/stm32plus,tokoro10g/stm32plus,phynex/stm32plus,ThanhVic/stm32plus,trigrass2/stm32plus,spiralray/stm32plus,punkkeks/stm32plus,ThanhVic/stm32plus,spiralray/stm32plus,spiralray/stm32plus,phynex/stm32plus,trigrass2/stm32plus,spiralray/stm32plus,lcbowling/stm32plus,ThanhVic/stm32plus,spiralray/stm32plus
f1a93a0e613e46121039f8aa1415bb8f02946cf9
src/option_manager.hh
src/option_manager.hh
#ifndef option_manager_hh_INCLUDED #define option_manager_hh_INCLUDED #include "completion.hh" #include "containers.hh" #include "exception.hh" #include "flags.hh" #include "option_types.hh" #include "vector.hh" #include <memory> namespace Kakoune { class OptionManager; enum class OptionFlags { None = 0, Hidden = 1, }; template<> struct WithBitOps<OptionFlags> : std::true_type {}; class OptionDesc { public: OptionDesc(String name, String docstring, OptionFlags flags); const String& name() const { return m_name; } const String& docstring() const { return m_docstring; } OptionFlags flags() const { return m_flags; } private: String m_name; String m_docstring; OptionFlags m_flags; }; class Option { public: virtual ~Option() = default; template<typename T> const T& get() const; template<typename T> T& get_mutable(); template<typename T> void set(const T& val, bool notify=true); template<typename T> bool is_of_type() const; virtual String get_as_string() const = 0; virtual void set_from_string(StringView str) = 0; virtual void add_from_string(StringView str) = 0; virtual Option* clone(OptionManager& manager) const = 0; OptionManager& manager() const { return m_manager; } const String& name() const { return m_desc.name(); } const String& docstring() const { return m_desc.docstring(); } OptionFlags flags() const { return m_desc.flags(); } protected: Option(const OptionDesc& desc, OptionManager& manager); OptionManager& m_manager; const OptionDesc& m_desc; }; class OptionManagerWatcher { public: virtual ~OptionManagerWatcher() {} virtual void on_option_changed(const Option& option) = 0; }; class OptionManager : private OptionManagerWatcher { public: OptionManager(OptionManager& parent); ~OptionManager(); Option& operator[] (StringView name); const Option& operator[] (StringView name) const; Option& get_local_option(StringView name); void unset_option(StringView name); using OptionList = Vector<const Option*>; OptionList flatten_options() const; void register_watcher(OptionManagerWatcher& watcher); void unregister_watcher(OptionManagerWatcher& watcher); void on_option_changed(const Option& option) override; private: OptionManager() : m_parent(nullptr) {} // the only one allowed to construct a root option manager friend class Scope; friend class OptionsRegistry; Vector<std::unique_ptr<Option>, MemoryDomain::Options> m_options; OptionManager* m_parent; Vector<OptionManagerWatcher*, MemoryDomain::Options> m_watchers; }; template<typename T> class TypedOption : public Option { public: TypedOption(OptionManager& manager, const OptionDesc& desc, const T& value) : Option(desc, manager), m_value(value) {} void set(T value, bool notify = true) { validate(value); if (m_value != value) { m_value = std::move(value); if (notify) manager().on_option_changed(*this); } } const T& get() const { return m_value; } T& get_mutable() { return m_value; } String get_as_string() const override { return option_to_string(m_value); } void set_from_string(StringView str) override { T val; option_from_string(str, val); set(std::move(val)); } void add_from_string(StringView str) override { if (option_add(m_value, str)) m_manager.on_option_changed(*this); } using Alloc = Allocator<TypedOption, MemoryDomain::Options>; static void* operator new (std::size_t sz) { kak_assert(sz == sizeof(TypedOption)); return Alloc{}.allocate(1); } static void operator delete (void* ptr) { return Alloc{}.deallocate(reinterpret_cast<TypedOption*>(ptr), 1); } private: virtual void validate(const T& value) const {} T m_value; }; template<typename T, void (*validator)(const T&)> class TypedCheckedOption : public TypedOption<T> { using TypedOption<T>::TypedOption; Option* clone(OptionManager& manager) const override { return new TypedCheckedOption{manager, this->m_desc, this->get()}; } void validate(const T& value) const override { if (validator != nullptr) validator(value); } }; template<typename T> const T& Option::get() const { auto* typed_opt = dynamic_cast<const TypedOption<T>*>(this); if (not typed_opt) throw runtime_error(format("option '{}' is not of type '{}'", name(), typeid(T).name())); return typed_opt->get(); } template<typename T> T& Option::get_mutable() { return const_cast<T&>(get<T>()); } template<typename T> void Option::set(const T& val, bool notify) { auto* typed_opt = dynamic_cast<TypedOption<T>*>(this); if (not typed_opt) throw runtime_error(format("option '{}' is not of type '{}'", name(), typeid(T).name())); return typed_opt->set(val, notify); } template<typename T> bool Option::is_of_type() const { return dynamic_cast<const TypedOption<T>*>(this) != nullptr; } template<typename T> auto find_option(T& container, StringView name) -> decltype(container.begin()) { using ptr_type = decltype(*container.begin()); return find_if(container, [&name](const ptr_type& opt) { return opt->name() == name; }); } class OptionsRegistry { public: OptionsRegistry(OptionManager& global_manager) : m_global_manager(global_manager) {} template<typename T, void (*validator)(const T&) = nullptr> Option& declare_option(const String& name, const String& docstring, const T& value, OptionFlags flags = OptionFlags::None) { auto& opts = m_global_manager.m_options; auto it = find_option(opts, name); if (it != opts.end()) { if ((*it)->is_of_type<T>() and (*it)->flags() == flags) return **it; throw runtime_error(format("option '{}' already declared with different type or flags", name)); } m_descs.emplace_back(new OptionDesc{name, docstring, flags}); opts.emplace_back(new TypedCheckedOption<T, validator>{m_global_manager, *m_descs.back(), value}); return *opts.back(); } const OptionDesc* option_desc(StringView name) const { auto it = find_if(m_descs, [&name](const std::unique_ptr<OptionDesc>& opt) { return opt->name() == name; }); return it != m_descs.end() ? it->get() : nullptr; } bool option_exists(StringView name) const { return option_desc(name) != nullptr; } CandidateList complete_option_name(StringView prefix, ByteCount cursor_pos) const; private: OptionManager& m_global_manager; Vector<std::unique_ptr<OptionDesc>, MemoryDomain::Options> m_descs; }; } #endif // option_manager_hh_INCLUDED
#ifndef option_manager_hh_INCLUDED #define option_manager_hh_INCLUDED #include "completion.hh" #include "containers.hh" #include "exception.hh" #include "flags.hh" #include "option_types.hh" #include "vector.hh" #include <memory> namespace Kakoune { class OptionManager; enum class OptionFlags { None = 0, Hidden = 1, }; template<> struct WithBitOps<OptionFlags> : std::true_type {}; class OptionDesc { public: OptionDesc(String name, String docstring, OptionFlags flags); const String& name() const { return m_name; } const String& docstring() const { return m_docstring; } OptionFlags flags() const { return m_flags; } private: String m_name; String m_docstring; OptionFlags m_flags; }; class Option { public: virtual ~Option() = default; template<typename T> const T& get() const; template<typename T> T& get_mutable(); template<typename T> void set(const T& val, bool notify=true); template<typename T> bool is_of_type() const; virtual String get_as_string() const = 0; virtual void set_from_string(StringView str) = 0; virtual void add_from_string(StringView str) = 0; virtual Option* clone(OptionManager& manager) const = 0; OptionManager& manager() const { return m_manager; } const String& name() const { return m_desc.name(); } const String& docstring() const { return m_desc.docstring(); } OptionFlags flags() const { return m_desc.flags(); } protected: Option(const OptionDesc& desc, OptionManager& manager); OptionManager& m_manager; const OptionDesc& m_desc; }; class OptionManagerWatcher { public: virtual ~OptionManagerWatcher() {} virtual void on_option_changed(const Option& option) = 0; }; class OptionManager : private OptionManagerWatcher { public: OptionManager(OptionManager& parent); ~OptionManager(); Option& operator[] (StringView name); const Option& operator[] (StringView name) const; Option& get_local_option(StringView name); void unset_option(StringView name); using OptionList = Vector<const Option*>; OptionList flatten_options() const; void register_watcher(OptionManagerWatcher& watcher); void unregister_watcher(OptionManagerWatcher& watcher); void on_option_changed(const Option& option) override; private: OptionManager() : m_parent(nullptr) {} // the only one allowed to construct a root option manager friend class Scope; friend class OptionsRegistry; Vector<std::unique_ptr<Option>, MemoryDomain::Options> m_options; OptionManager* m_parent; Vector<OptionManagerWatcher*, MemoryDomain::Options> m_watchers; }; template<typename T> class TypedOption : public Option { public: TypedOption(OptionManager& manager, const OptionDesc& desc, const T& value) : Option(desc, manager), m_value(value) {} void set(T value, bool notify = true) { validate(value); if (m_value != value) { m_value = std::move(value); if (notify) manager().on_option_changed(*this); } } const T& get() const { return m_value; } T& get_mutable() { return m_value; } String get_as_string() const override { return option_to_string(m_value); } void set_from_string(StringView str) override { T val; option_from_string(str, val); set(std::move(val)); } void add_from_string(StringView str) override { if (option_add(m_value, str)) m_manager.on_option_changed(*this); } using Alloc = Allocator<TypedOption, MemoryDomain::Options>; static void* operator new (std::size_t sz) { kak_assert(sz == sizeof(TypedOption)); return Alloc{}.allocate(1); } static void operator delete (void* ptr) { return Alloc{}.deallocate(reinterpret_cast<TypedOption*>(ptr), 1); } private: virtual void validate(const T& value) const {} T m_value; }; template<typename T, void (*validator)(const T&)> class TypedCheckedOption : public TypedOption<T> { using TypedOption<T>::TypedOption; Option* clone(OptionManager& manager) const override { return new TypedCheckedOption{manager, this->m_desc, this->get()}; } void validate(const T& value) const override { if (validator != nullptr) validator(value); } }; template<typename T> const T& Option::get() const { auto* typed_opt = dynamic_cast<const TypedOption<T>*>(this); if (not typed_opt) throw runtime_error(format("option '{}' is not of type '{}'", name(), typeid(T).name())); return typed_opt->get(); } template<typename T> T& Option::get_mutable() { return const_cast<T&>(get<T>()); } template<typename T> void Option::set(const T& val, bool notify) { auto* typed_opt = dynamic_cast<TypedOption<T>*>(this); if (not typed_opt) throw runtime_error(format("option '{}' is not of type '{}'", name(), typeid(T).name())); return typed_opt->set(val, notify); } template<typename T> bool Option::is_of_type() const { return dynamic_cast<const TypedOption<T>*>(this) != nullptr; } template<typename T> auto find_option(T& container, StringView name) -> decltype(container.begin()) { using ptr_type = decltype(*container.begin()); return find_if(container, [&name](const ptr_type& opt) { return opt->name() == name; }); } class OptionsRegistry { public: OptionsRegistry(OptionManager& global_manager) : m_global_manager(global_manager) {} template<typename T, void (*validator)(const T&) = nullptr> Option& declare_option(StringView name, StringView docstring, const T& value, OptionFlags flags = OptionFlags::None) { auto& opts = m_global_manager.m_options; auto it = find_option(opts, name); if (it != opts.end()) { if ((*it)->is_of_type<T>() and (*it)->flags() == flags) return **it; throw runtime_error(format("option '{}' already declared with different type or flags", name)); } m_descs.emplace_back(new OptionDesc{name.str(), docstring.str(), flags}); opts.emplace_back(new TypedCheckedOption<T, validator>{m_global_manager, *m_descs.back(), value}); return *opts.back(); } const OptionDesc* option_desc(StringView name) const { auto it = find_if(m_descs, [&name](const std::unique_ptr<OptionDesc>& opt) { return opt->name() == name; }); return it != m_descs.end() ? it->get() : nullptr; } bool option_exists(StringView name) const { return option_desc(name) != nullptr; } CandidateList complete_option_name(StringView prefix, ByteCount cursor_pos) const; private: OptionManager& m_global_manager; Vector<std::unique_ptr<OptionDesc>, MemoryDomain::Options> m_descs; }; } #endif // option_manager_hh_INCLUDED
Replace some const String& with StringView in option_manager.hh
Replace some const String& with StringView in option_manager.hh
C++
unlicense
ekie/kakoune,danr/kakoune,ekie/kakoune,jjthrash/kakoune,jkonecny12/kakoune,ekie/kakoune,mawww/kakoune,flavius/kakoune,occivink/kakoune,alexherbo2/kakoune,mawww/kakoune,lenormf/kakoune,mawww/kakoune,casimir/kakoune,occivink/kakoune,jjthrash/kakoune,Somasis/kakoune,flavius/kakoune,jjthrash/kakoune,danr/kakoune,Somasis/kakoune,casimir/kakoune,jkonecny12/kakoune,Somasis/kakoune,alexherbo2/kakoune,lenormf/kakoune,danr/kakoune,lenormf/kakoune,ekie/kakoune,danr/kakoune,flavius/kakoune,casimir/kakoune,lenormf/kakoune,Somasis/kakoune,occivink/kakoune,jkonecny12/kakoune,occivink/kakoune,jkonecny12/kakoune,casimir/kakoune,alexherbo2/kakoune,flavius/kakoune,alexherbo2/kakoune,mawww/kakoune,jjthrash/kakoune
32084534c185dc9dde301c58890a7fc1ff10ade6
SurgSim/Devices/Novint/UnitTests/NovintDeviceTest.cpp
SurgSim/Devices/Novint/UnitTests/NovintDeviceTest.cpp
// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// \file /// Tests for the NovintDevice class. #include <memory> #include <string> #include <boost/thread.hpp> #include <boost/chrono.hpp> #include <gtest/gtest.h> #include <SurgSim/Devices/Novint/NovintDevice.h> //#include <SurgSim/Devices/Novint/NovintScaffold.h> // only needed if calling setDefaultLogLevel() #include <SurgSim/DataStructures/DataGroup.h> #include <SurgSim/Input/InputConsumerInterface.h> #include <SurgSim/Input/OutputProducerInterface.h> #include <SurgSim/Math/RigidTransform.h> #include <SurgSim/Math/Matrix.h> using SurgSim::Device::NovintDevice; using SurgSim::Device::NovintScaffold; using SurgSim::DataStructures::DataGroup; using SurgSim::Input::InputConsumerInterface; using SurgSim::Input::OutputProducerInterface; using SurgSim::Math::RigidTransform3d; using SurgSim::Math::Matrix44d; // Define common device names used in the Novint device tests. extern const char* const NOVINT_TEST_DEVICE_NAME = "FALCON_HTHR_R"; extern const char* const NOVINT_TEST_DEVICE_NAME_2 = "FALCON_FRANKEN_L"; //extern const char* const NOVINT_TEST_DEVICE_NAME = "FALCON_BURRv3_1"; //extern const char* const NOVINT_TEST_DEVICE_NAME_2 = "FALCON_BURRv3_2"; struct TestListener : public InputConsumerInterface, public OutputProducerInterface { public: TestListener() : m_numTimesInitializedInput(0), m_numTimesReceivedInput(0), m_numTimesRequestedOutput(0) { } virtual void initializeInput(const std::string& device, const DataGroup& inputData); virtual void handleInput(const std::string& device, const DataGroup& inputData); virtual bool requestOutput(const std::string& device, DataGroup* outputData); int m_numTimesInitializedInput; int m_numTimesReceivedInput; int m_numTimesRequestedOutput; DataGroup m_lastReceivedInput; }; void TestListener::initializeInput(const std::string& device, const DataGroup& inputData) { ++m_numTimesInitializedInput; } void TestListener::handleInput(const std::string& device, const DataGroup& inputData) { ++m_numTimesReceivedInput; m_lastReceivedInput = inputData; } bool TestListener::requestOutput(const std::string& device, DataGroup* outputData) { ++m_numTimesRequestedOutput; return false; } TEST(NovintDeviceTest, CreateUninitializedDevice) { //NovintScaffold::setDefaultLogLevel(SurgSim::Framework::LOG_LEVEL_DEBUG); std::shared_ptr<NovintDevice> device = std::make_shared<NovintDevice>("TestFalcon", NOVINT_TEST_DEVICE_NAME); ASSERT_TRUE(device != nullptr) << "Device creation failed."; } TEST(NovintDeviceTest, CreateAndInitializeDevice) { //NovintScaffold::setDefaultLogLevel(SurgSim::Framework::LOG_LEVEL_DEBUG); std::shared_ptr<NovintDevice> device = std::make_shared<NovintDevice>("TestFalcon", NOVINT_TEST_DEVICE_NAME); ASSERT_TRUE(device != nullptr) << "Device creation failed."; EXPECT_FALSE(device->isInitialized()); ASSERT_TRUE(device->initialize()) << "Initialization failed. Is a Novint device plugged in?"; EXPECT_TRUE(device->isInitialized()); } // Note: this should work if the "Default Falcon" device can be initialized... but we have no reason to think it can, // so I'm going to disable the test. TEST(NovintDeviceTest, DISABLED_CreateAndInitializeDefaultDevice) { //NovintScaffold::setDefaultLogLevel(SurgSim::Framework::LOG_LEVEL_DEBUG); std::shared_ptr<NovintDevice> device = std::make_shared<NovintDevice>("TestFalcon", ""); ASSERT_TRUE(device != nullptr) << "Device creation failed."; EXPECT_FALSE(device->isInitialized()); ASSERT_TRUE(device->initialize()) << "Initialization failed. Is a Novint device plugged in?"; EXPECT_TRUE(device->isInitialized()); } TEST(NovintDeviceTest, Name) { //NovintScaffold::setDefaultLogLevel(SurgSim::Framework::LOG_LEVEL_DEBUG); std::shared_ptr<NovintDevice> device = std::make_shared<NovintDevice>("TestFalcon", NOVINT_TEST_DEVICE_NAME); ASSERT_TRUE(device != nullptr) << "Device creation failed."; EXPECT_EQ("TestFalcon", device->getName()); EXPECT_TRUE(device->initialize()) << "Initialization failed. Is a Novint device plugged in?"; EXPECT_EQ("TestFalcon", device->getName()); } static void testCreateDeviceSeveralTimes(bool doSleep) { for (int i = 0; i < 6; ++i) { std::shared_ptr<NovintDevice> device = std::make_shared<NovintDevice>("TestFalcon", NOVINT_TEST_DEVICE_NAME); ASSERT_TRUE(device != nullptr) << "Device creation failed."; ASSERT_TRUE(device->initialize()) << "Initialization failed. Is a Novint device plugged in?"; if (doSleep) { boost::this_thread::sleep_until(boost::chrono::steady_clock::now() + boost::chrono::milliseconds(100)); } // the device will be destroyed here } } TEST(NovintDeviceTest, CreateDeviceSeveralTimes) { //NovintScaffold::setDefaultLogLevel(SurgSim::Framework::LOG_LEVEL_DEBUG); testCreateDeviceSeveralTimes(true); } TEST(NovintDeviceTest, CreateSeveralDevices) { //NovintScaffold::setDefaultLogLevel(SurgSim::Framework::LOG_LEVEL_DEBUG); std::shared_ptr<NovintDevice> device1 = std::make_shared<NovintDevice>("Novint1", NOVINT_TEST_DEVICE_NAME); ASSERT_TRUE(device1 != nullptr) << "Device creation failed."; ASSERT_TRUE(device1->initialize()) << "Initialization failed. Is a Novint device plugged in?"; // We can't check what happens with the scaffolds, since those are no longer a part of the device's API... std::shared_ptr<NovintDevice> device2 = std::make_shared<NovintDevice>("Novint2", NOVINT_TEST_DEVICE_NAME_2); ASSERT_TRUE(device2 != nullptr) << "Device creation failed."; if (! device2->initialize()) { std::cerr << "[Warning: second Novint did not come up; is it plugged in?]" << std::endl; } } TEST(NovintDeviceTest, CreateDevicesWithSameName) { //NovintScaffold::setDefaultLogLevel(SurgSim::Framework::LOG_LEVEL_DEBUG); std::shared_ptr<NovintDevice> device1 = std::make_shared<NovintDevice>("Novint", NOVINT_TEST_DEVICE_NAME); ASSERT_TRUE(device1 != nullptr) << "Device creation failed."; ASSERT_TRUE(device1->initialize()) << "Initialization failed. Is a Novint device plugged in?"; std::shared_ptr<NovintDevice> device2 = std::make_shared<NovintDevice>("Novint", NOVINT_TEST_DEVICE_NAME_2); ASSERT_TRUE(device2 != nullptr) << "Device creation failed."; ASSERT_FALSE(device2->initialize()) << "Initialization succeeded despite duplicate name."; } TEST(NovintDeviceTest, CreateDevicesWithSameInitializationName) { //NovintScaffold::setDefaultLogLevel(SurgSim::Framework::LOG_LEVEL_DEBUG); std::shared_ptr<NovintDevice> device1 = std::make_shared<NovintDevice>("Novint1", NOVINT_TEST_DEVICE_NAME); ASSERT_TRUE(device1 != nullptr) << "Device creation failed."; ASSERT_TRUE(device1->initialize()) << "Initialization failed. Is a Novint device plugged in?"; std::shared_ptr<NovintDevice> device2 = std::make_shared<NovintDevice>("Novint2", NOVINT_TEST_DEVICE_NAME); ASSERT_TRUE(device2 != nullptr) << "Device creation failed."; ASSERT_FALSE(device2->initialize()) << "Initialization succeeded despite duplicate initialization name."; } TEST(NovintDeviceTest, InputConsumer) { //NovintScaffold::setDefaultLogLevel(SurgSim::Framework::LOG_LEVEL_DEBUG); std::shared_ptr<NovintDevice> device = std::make_shared<NovintDevice>("TestFalcon", NOVINT_TEST_DEVICE_NAME); ASSERT_TRUE(device != nullptr) << "Device creation failed."; EXPECT_TRUE(device->initialize()) << "Initialization failed. Is a Novint device plugged in?"; std::shared_ptr<TestListener> consumer = std::make_shared<TestListener>(); EXPECT_EQ(0, consumer->m_numTimesReceivedInput); EXPECT_FALSE(device->removeInputConsumer(consumer)); EXPECT_EQ(0, consumer->m_numTimesReceivedInput); EXPECT_TRUE(device->addInputConsumer(consumer)); // Adding the same input consumer again should fail. EXPECT_FALSE(device->addInputConsumer(consumer)); // Sleep for a second, to see how many times the consumer is invoked. // (A Novint device is supposed to run at 1KHz.) boost::this_thread::sleep_until(boost::chrono::steady_clock::now() + boost::chrono::milliseconds(1000)); EXPECT_TRUE(device->removeInputConsumer(consumer)); // Removing the same input consumer again should fail. EXPECT_FALSE(device->removeInputConsumer(consumer)); // Check the number of invocations. EXPECT_GE(consumer->m_numTimesReceivedInput, 700); EXPECT_LE(consumer->m_numTimesReceivedInput, 1300); EXPECT_TRUE(consumer->m_lastReceivedInput.poses().hasData("pose")); EXPECT_TRUE(consumer->m_lastReceivedInput.booleans().hasData("button1")); } TEST(NovintDeviceTest, OutputProducer) { //NovintScaffold::setDefaultLogLevel(SurgSim::Framework::LOG_LEVEL_DEBUG); std::shared_ptr<NovintDevice> device = std::make_shared<NovintDevice>("TestFalcon", NOVINT_TEST_DEVICE_NAME); ASSERT_TRUE(device != nullptr) << "Device creation failed."; EXPECT_TRUE(device->initialize()) << "Initialization failed. Is a Novint device plugged in?"; std::shared_ptr<TestListener> producer = std::make_shared<TestListener>(); EXPECT_EQ(0, producer->m_numTimesRequestedOutput); EXPECT_FALSE(device->removeOutputProducer(producer)); EXPECT_EQ(0, producer->m_numTimesRequestedOutput); EXPECT_TRUE(device->setOutputProducer(producer)); // Sleep for a second, to see how many times the producer is invoked. // (A Novint Falcon device is supposed to run at 1KHz.) boost::this_thread::sleep_until(boost::chrono::steady_clock::now() + boost::chrono::milliseconds(1000)); EXPECT_TRUE(device->removeOutputProducer(producer)); // Removing the same input producer again should fail. EXPECT_FALSE(device->removeOutputProducer(producer)); // Check the number of invocations. EXPECT_GE(producer->m_numTimesRequestedOutput, 700); EXPECT_LE(producer->m_numTimesRequestedOutput, 1300); }
// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// \file /// Tests for the NovintDevice class. #include <memory> #include <string> #include <boost/thread.hpp> #include <boost/chrono.hpp> #include <gtest/gtest.h> #include <SurgSim/Devices/Novint/NovintDevice.h> //#include <SurgSim/Devices/Novint/NovintScaffold.h> // only needed if calling setDefaultLogLevel() #include <SurgSim/DataStructures/DataGroup.h> #include <SurgSim/Input/InputConsumerInterface.h> #include <SurgSim/Input/OutputProducerInterface.h> #include <SurgSim/Math/RigidTransform.h> #include <SurgSim/Math/Matrix.h> #include <SurgSim/Framework/Clock.h> using SurgSim::Device::NovintDevice; using SurgSim::Device::NovintScaffold; using SurgSim::DataStructures::DataGroup; using SurgSim::Input::InputConsumerInterface; using SurgSim::Input::OutputProducerInterface; using SurgSim::Math::RigidTransform3d; using SurgSim::Math::Matrix44d; using SurgSim::Framework::Clock; // Define common device names used in the Novint device tests. extern const char* const NOVINT_TEST_DEVICE_NAME = "FALCON_HTHR_R"; extern const char* const NOVINT_TEST_DEVICE_NAME_2 = "FALCON_FRANKEN_L"; //extern const char* const NOVINT_TEST_DEVICE_NAME = "FALCON_BURRv3_1"; //extern const char* const NOVINT_TEST_DEVICE_NAME_2 = "FALCON_BURRv3_2"; struct TestListener : public InputConsumerInterface, public OutputProducerInterface { public: TestListener() : m_numTimesInitializedInput(0), m_numTimesReceivedInput(0), m_numTimesRequestedOutput(0) { } virtual void initializeInput(const std::string& device, const DataGroup& inputData); virtual void handleInput(const std::string& device, const DataGroup& inputData); virtual bool requestOutput(const std::string& device, DataGroup* outputData); int m_numTimesInitializedInput; int m_numTimesReceivedInput; int m_numTimesRequestedOutput; DataGroup m_lastReceivedInput; }; void TestListener::initializeInput(const std::string& device, const DataGroup& inputData) { ++m_numTimesInitializedInput; } void TestListener::handleInput(const std::string& device, const DataGroup& inputData) { ++m_numTimesReceivedInput; m_lastReceivedInput = inputData; } bool TestListener::requestOutput(const std::string& device, DataGroup* outputData) { ++m_numTimesRequestedOutput; return false; } TEST(NovintDeviceTest, CreateUninitializedDevice) { //NovintScaffold::setDefaultLogLevel(SurgSim::Framework::LOG_LEVEL_DEBUG); std::shared_ptr<NovintDevice> device = std::make_shared<NovintDevice>("TestFalcon", NOVINT_TEST_DEVICE_NAME); ASSERT_TRUE(device != nullptr) << "Device creation failed."; } TEST(NovintDeviceTest, CreateAndInitializeDevice) { //NovintScaffold::setDefaultLogLevel(SurgSim::Framework::LOG_LEVEL_DEBUG); std::shared_ptr<NovintDevice> device = std::make_shared<NovintDevice>("TestFalcon", NOVINT_TEST_DEVICE_NAME); ASSERT_TRUE(device != nullptr) << "Device creation failed."; EXPECT_FALSE(device->isInitialized()); ASSERT_TRUE(device->initialize()) << "Initialization failed. Is a Novint device plugged in?"; EXPECT_TRUE(device->isInitialized()); } // Note: this should work if the "Default Falcon" device can be initialized... but we have no reason to think it can, // so I'm going to disable the test. TEST(NovintDeviceTest, DISABLED_CreateAndInitializeDefaultDevice) { //NovintScaffold::setDefaultLogLevel(SurgSim::Framework::LOG_LEVEL_DEBUG); std::shared_ptr<NovintDevice> device = std::make_shared<NovintDevice>("TestFalcon", ""); ASSERT_TRUE(device != nullptr) << "Device creation failed."; EXPECT_FALSE(device->isInitialized()); ASSERT_TRUE(device->initialize()) << "Initialization failed. Is a Novint device plugged in?"; EXPECT_TRUE(device->isInitialized()); } TEST(NovintDeviceTest, Name) { //NovintScaffold::setDefaultLogLevel(SurgSim::Framework::LOG_LEVEL_DEBUG); std::shared_ptr<NovintDevice> device = std::make_shared<NovintDevice>("TestFalcon", NOVINT_TEST_DEVICE_NAME); ASSERT_TRUE(device != nullptr) << "Device creation failed."; EXPECT_EQ("TestFalcon", device->getName()); EXPECT_TRUE(device->initialize()) << "Initialization failed. Is a Novint device plugged in?"; EXPECT_EQ("TestFalcon", device->getName()); } static void testCreateDeviceSeveralTimes(bool doSleep) { for (int i = 0; i < 6; ++i) { std::shared_ptr<NovintDevice> device = std::make_shared<NovintDevice>("TestFalcon", NOVINT_TEST_DEVICE_NAME); ASSERT_TRUE(device != nullptr) << "Device creation failed."; ASSERT_TRUE(device->initialize()) << "Initialization failed. Is a Novint device plugged in?"; if (doSleep) { boost::this_thread::sleep_until(Clock::now() + boost::chrono::milliseconds(100)); } // the device will be destroyed here } } TEST(NovintDeviceTest, CreateDeviceSeveralTimes) { //NovintScaffold::setDefaultLogLevel(SurgSim::Framework::LOG_LEVEL_DEBUG); testCreateDeviceSeveralTimes(true); } TEST(NovintDeviceTest, CreateSeveralDevices) { //NovintScaffold::setDefaultLogLevel(SurgSim::Framework::LOG_LEVEL_DEBUG); std::shared_ptr<NovintDevice> device1 = std::make_shared<NovintDevice>("Novint1", NOVINT_TEST_DEVICE_NAME); ASSERT_TRUE(device1 != nullptr) << "Device creation failed."; ASSERT_TRUE(device1->initialize()) << "Initialization failed. Is a Novint device plugged in?"; // We can't check what happens with the scaffolds, since those are no longer a part of the device's API... std::shared_ptr<NovintDevice> device2 = std::make_shared<NovintDevice>("Novint2", NOVINT_TEST_DEVICE_NAME_2); ASSERT_TRUE(device2 != nullptr) << "Device creation failed."; if (! device2->initialize()) { std::cerr << "[Warning: second Novint did not come up; is it plugged in?]" << std::endl; } } TEST(NovintDeviceTest, CreateDevicesWithSameName) { //NovintScaffold::setDefaultLogLevel(SurgSim::Framework::LOG_LEVEL_DEBUG); std::shared_ptr<NovintDevice> device1 = std::make_shared<NovintDevice>("Novint", NOVINT_TEST_DEVICE_NAME); ASSERT_TRUE(device1 != nullptr) << "Device creation failed."; ASSERT_TRUE(device1->initialize()) << "Initialization failed. Is a Novint device plugged in?"; std::shared_ptr<NovintDevice> device2 = std::make_shared<NovintDevice>("Novint", NOVINT_TEST_DEVICE_NAME_2); ASSERT_TRUE(device2 != nullptr) << "Device creation failed."; ASSERT_FALSE(device2->initialize()) << "Initialization succeeded despite duplicate name."; } TEST(NovintDeviceTest, CreateDevicesWithSameInitializationName) { //NovintScaffold::setDefaultLogLevel(SurgSim::Framework::LOG_LEVEL_DEBUG); std::shared_ptr<NovintDevice> device1 = std::make_shared<NovintDevice>("Novint1", NOVINT_TEST_DEVICE_NAME); ASSERT_TRUE(device1 != nullptr) << "Device creation failed."; ASSERT_TRUE(device1->initialize()) << "Initialization failed. Is a Novint device plugged in?"; std::shared_ptr<NovintDevice> device2 = std::make_shared<NovintDevice>("Novint2", NOVINT_TEST_DEVICE_NAME); ASSERT_TRUE(device2 != nullptr) << "Device creation failed."; ASSERT_FALSE(device2->initialize()) << "Initialization succeeded despite duplicate initialization name."; } TEST(NovintDeviceTest, InputConsumer) { //NovintScaffold::setDefaultLogLevel(SurgSim::Framework::LOG_LEVEL_DEBUG); std::shared_ptr<NovintDevice> device = std::make_shared<NovintDevice>("TestFalcon", NOVINT_TEST_DEVICE_NAME); ASSERT_TRUE(device != nullptr) << "Device creation failed."; EXPECT_TRUE(device->initialize()) << "Initialization failed. Is a Novint device plugged in?"; std::shared_ptr<TestListener> consumer = std::make_shared<TestListener>(); EXPECT_EQ(0, consumer->m_numTimesReceivedInput); EXPECT_FALSE(device->removeInputConsumer(consumer)); EXPECT_EQ(0, consumer->m_numTimesReceivedInput); EXPECT_TRUE(device->addInputConsumer(consumer)); // Adding the same input consumer again should fail. EXPECT_FALSE(device->addInputConsumer(consumer)); // Sleep for a second, to see how many times the consumer is invoked. // (A Novint device is supposed to run at 1KHz.) boost::this_thread::sleep_until(Clock::now() + boost::chrono::milliseconds(1000)); EXPECT_TRUE(device->removeInputConsumer(consumer)); // Removing the same input consumer again should fail. EXPECT_FALSE(device->removeInputConsumer(consumer)); // Check the number of invocations. EXPECT_GE(consumer->m_numTimesReceivedInput, 700); EXPECT_LE(consumer->m_numTimesReceivedInput, 1300); EXPECT_TRUE(consumer->m_lastReceivedInput.poses().hasData("pose")); EXPECT_TRUE(consumer->m_lastReceivedInput.booleans().hasData("button1")); } TEST(NovintDeviceTest, OutputProducer) { //NovintScaffold::setDefaultLogLevel(SurgSim::Framework::LOG_LEVEL_DEBUG); std::shared_ptr<NovintDevice> device = std::make_shared<NovintDevice>("TestFalcon", NOVINT_TEST_DEVICE_NAME); ASSERT_TRUE(device != nullptr) << "Device creation failed."; EXPECT_TRUE(device->initialize()) << "Initialization failed. Is a Novint device plugged in?"; std::shared_ptr<TestListener> producer = std::make_shared<TestListener>(); EXPECT_EQ(0, producer->m_numTimesRequestedOutput); EXPECT_FALSE(device->removeOutputProducer(producer)); EXPECT_EQ(0, producer->m_numTimesRequestedOutput); EXPECT_TRUE(device->setOutputProducer(producer)); // Sleep for a second, to see how many times the producer is invoked. // (A Novint Falcon device is supposed to run at 1KHz.) boost::this_thread::sleep_until(Clock::now() + boost::chrono::milliseconds(1000)); EXPECT_TRUE(device->removeOutputProducer(producer)); // Removing the same input producer again should fail. EXPECT_FALSE(device->removeOutputProducer(producer)); // Check the number of invocations. EXPECT_GE(producer->m_numTimesRequestedOutput, 700); EXPECT_LE(producer->m_numTimesRequestedOutput, 1300); }
Use the Framework::Clock alias in NovintDeviceTest.
Use the Framework::Clock alias in NovintDeviceTest.
C++
apache-2.0
simquest/opensurgsim,simquest/opensurgsim,simquest/opensurgsim,simquest/opensurgsim
0d02c2cbdf73bdf5a667aaf85ef8ab7b7feadb89
renderer/shader/phong_shader.cc
renderer/shader/phong_shader.cc
/* * Author: Dino Wernli */ #include "phong_shader.h" #include <cmath> #include <glog/logging.h> #include <memory> #include "renderer/intersection_data.h" #include "scene/material.h" #include "scene/point_light.h" #include "scene/scene.h" PhongShader::PhongShader(bool shadows) : shadows_(shadows) { } PhongShader::~PhongShader() { } Color3 PhongShader::Shade(const IntersectionData& data, const Scene& scene) { const Material& material = *data.material; Color3 emission(material.emission().Clamped()); Color3 ambient((material.ambient() * scene.ambient()).Clamped()); Color3 diffuse(0, 0, 0); Color3 specular(0, 0, 0); const std::vector<std::unique_ptr<Light>>& lights = scene.lights(); for (auto it = lights.begin(); it != lights.end(); ++it) { const Light* light = it->get(); Ray light_ray = light->GenerateRay(data.position); // Ignore the contribution from this light if it is occluded. if (shadows_ && scene.Intersect(light_ray)) { continue; } Vector3 point_to_light = -1 * light_ray.direction(); const Point3& cam_pos = scene.camera().position(); Vector3 point_to_camera = data.position.VectorTo(cam_pos).Normalized(); Vector3 normal = data.normal.Normalized(); Scalar prod = point_to_light.Dot(normal); // Flip normal if the light is inside the element. if (prod < 0) { normal = -normal; } // Add diffuse contribution. Color3 diff = material.diffuse() * light->color(); diffuse += (diff * prod).Clamped(); // Add specular contribution. Color3 spec = material.specular() * light->color(); Vector3 reflection = (-point_to_light).ReflectedOnPlane(normal); // Flip reflection if the camera is not on the same side of the element as // the light. if (prod < 0) { reflection = -reflection; } // Prevent cosine from turning positive through exponentiation. Scalar cosine = reflection.Dot(point_to_camera); cosine = cosine < 0 ? 0 : cosine; cosine = cosine > 1 ? 1 : cosine; specular += (spec * pow(cosine, material.shininess())).Clamped(); } return (emission + ambient + diffuse + specular).Clamped(); }
/* * Author: Dino Wernli */ #include "phong_shader.h" #include <cmath> #include <glog/logging.h> #include <memory> #include "renderer/intersection_data.h" #include "scene/material.h" #include "scene/point_light.h" #include "scene/scene.h" PhongShader::PhongShader(bool shadows) : shadows_(shadows) { } PhongShader::~PhongShader() { } Color3 PhongShader::Shade(const IntersectionData& data, const Scene& scene) { const Material& material = *data.material; Color3 emission(material.emission().Clamped()); Color3 ambient((material.ambient() * scene.ambient()).Clamped()); Color3 diffuse(0, 0, 0); Color3 specular(0, 0, 0); const std::vector<std::unique_ptr<Light>>& lights = scene.lights(); for (auto it = lights.begin(); it != lights.end(); ++it) { const Light* light = it->get(); Ray light_ray = light->GenerateRay(data.position); // Ignore the contribution from this light if it is occluded. if (shadows_ && scene.Intersect(light_ray)) { continue; } Vector3 point_to_light = -1 * light_ray.direction(); const Point3& cam_pos = scene.camera().position(); Vector3 point_to_camera = data.position.VectorTo(cam_pos).Normalized(); Vector3 normal = data.normal.Normalized(); Scalar prod = point_to_light.Dot(normal); // Flip normal if the light is inside the element. if (prod < 0) { normal = -normal; } // Add diffuse contribution. Color3 diff = material.diffuse() * light->color(); diffuse += diff * prod; // Add specular contribution. Color3 spec = material.specular() * light->color(); Vector3 reflection = (-point_to_light).ReflectedOnPlane(normal); // Flip reflection if the camera is not on the same side of the element as // the light. if (prod < 0) { reflection = -reflection; } // Prevent cosine from turning positive through exponentiation. Scalar cosine = reflection.Dot(point_to_camera); cosine = cosine < 0 ? 0 : cosine; cosine = cosine > 1 ? 1 : cosine; specular += spec * pow(cosine, material.shininess()); } return (emission + ambient + diffuse + specular).Clamped(); }
Remove unnecessary clamping in phong shader.
Remove unnecessary clamping in phong shader.
C++
mit
dinowernli/raytracer,dinowernli/raytracer,dinowernli/raytracer,dinowernli/raytracer
ec31600ca601eca956fca623b309655e83c9f94a
test/prototype_factory_test.cpp
test/prototype_factory_test.cpp
/** * * Modern Wheel : all the things that shouldn't be reinvented from one project to the other * * The MIT License (MIT) * * Copyright (C) 2015 Massimiliano Culpo * * 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 <mwheel/prototype_factory.h> #include <boost/test/unit_test.hpp> #include <boost/test/unit_test_suite.hpp> #include <string> using namespace std; namespace { class Base { public: using clone_type = shared_ptr<Base>; virtual clone_type clone() = 0; virtual int get() = 0; virtual ~Base() {} }; struct DerivedA : public Base { Base::clone_type clone() override { return make_shared<DerivedA>(); } int get() override { return 1; } }; class BaseMultiParms { public: using clone_type = shared_ptr<BaseMultiParms>; virtual clone_type clone(int a) = 0; virtual clone_type clone(int a, int b) = 0; virtual int get() = 0; }; class DerivedSum : public BaseMultiParms { public: explicit DerivedSum(int a) : m_a(a) {} BaseMultiParms::clone_type clone(int a) override { return make_shared<DerivedSum>(a); } BaseMultiParms::clone_type clone(int a, int b) override { return make_shared<DerivedSum>(a + b); } int get() override { return m_a; } private: int m_a = 0; }; } BOOST_AUTO_TEST_SUITE(PrototypeFactoryTest) BOOST_AUTO_TEST_CASE(NoParameters) { // Create a factory using FactoryType = mwheel::PrototypeFactory<Base, string>; FactoryType factory; // Register types DerivedA a; // Registering a type under a new tag should work BOOST_CHECK_EQUAL(factory.register_prototype("DerivedA", a), true); BOOST_CHECK_EQUAL(factory.register_prototype("SDerivedA", make_shared<DerivedA>()), true); // Check the construction of the list of products auto products = factory.product_list(); BOOST_CHECK_EQUAL(products.size(), 2); BOOST_CHECK_EQUAL(products[0], "DerivedA"); BOOST_CHECK_EQUAL(products[1], "SDerivedA"); // Trying to register under the same tag should fail BOOST_CHECK_EQUAL(factory.register_prototype("DerivedA", a), false); BOOST_CHECK_EQUAL(factory.register_prototype("SDerivedA", make_shared<DerivedA>()), false); // Check that the correct object is created auto obj = factory.create("DerivedA"); BOOST_CHECK_EQUAL(obj->get(), 1); auto sobj = factory.create("DerivedA"); BOOST_CHECK_EQUAL(sobj->get(), 1); // Unregister an existent tag should work BOOST_CHECK_EQUAL(factory.has_tag("DerivedA"), true); BOOST_CHECK_EQUAL(factory.unregister_prototype("DerivedA"), true); // Unregister a non-existent tag should fail BOOST_CHECK_EQUAL(factory.has_tag("DerivedA"), false); BOOST_CHECK_EQUAL(factory.unregister_prototype("DerivedA"), false); // Check the default behavior with throws BOOST_CHECK_THROW(factory.create("DerivedA"), FactoryType::tag_not_registered); // Check customization of on_tag_not_registered factory.on_tag_not_registered([](FactoryType::tag_type tag) { return nullptr; }); BOOST_CHECK_EQUAL(factory.create("DerivedA"), FactoryType::product_type(nullptr)); } BOOST_AUTO_TEST_CASE(MultipleParameters) { // Create a factory and register a type using FactoryType = mwheel::PrototypeFactory<BaseMultiParms, int>; FactoryType factory; BOOST_CHECK_EQUAL(factory.register_prototype(0, make_shared<DerivedSum>(10)), true); // Check creation using multiple parameters auto obja = factory.create(0, 3); BOOST_CHECK_EQUAL(obja->get(), 3); auto objb = factory.create(0, 3, 6); BOOST_CHECK_EQUAL(objb->get(), 9); } BOOST_AUTO_TEST_SUITE_END()
/** * * Modern Wheel : all the things that shouldn't be reinvented from one project to the other * * The MIT License (MIT) * * Copyright (C) 2015 Massimiliano Culpo * * 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 <mwheel/prototype_factory.h> #include <boost/test/unit_test.hpp> #include <boost/test/unit_test_suite.hpp> #include <string> using namespace std; namespace { class Base { public: using clone_type = shared_ptr<Base>; virtual clone_type clone() = 0; virtual int get() = 0; virtual ~Base() {} }; struct DerivedA : public Base { Base::clone_type clone() override { return make_shared<DerivedA>(); } int get() override { return 1; } }; class BaseMultiParms { public: using clone_type = shared_ptr<BaseMultiParms>; virtual clone_type clone(int a) = 0; virtual clone_type clone(int a, int b) = 0; virtual int get() = 0; virtual ~BaseMultiParms() {} }; class DerivedSum : public BaseMultiParms { public: explicit DerivedSum(int a) : m_a(a) {} BaseMultiParms::clone_type clone(int a) override { return make_shared<DerivedSum>(a); } BaseMultiParms::clone_type clone(int a, int b) override { return make_shared<DerivedSum>(a + b); } int get() override { return m_a; } private: int m_a = 0; }; } BOOST_AUTO_TEST_SUITE(PrototypeFactoryTest) BOOST_AUTO_TEST_CASE(NoParameters) { // Create a factory using FactoryType = mwheel::PrototypeFactory<Base, string>; FactoryType factory; // Register types DerivedA a; // Registering a type under a new tag should work BOOST_CHECK_EQUAL(factory.register_prototype("DerivedA", a), true); BOOST_CHECK_EQUAL(factory.register_prototype("SDerivedA", make_shared<DerivedA>()), true); // Check the construction of the list of products auto products = factory.product_list(); BOOST_CHECK_EQUAL(products.size(), 2); BOOST_CHECK_EQUAL(products[0], "DerivedA"); BOOST_CHECK_EQUAL(products[1], "SDerivedA"); // Trying to register under the same tag should fail BOOST_CHECK_EQUAL(factory.register_prototype("DerivedA", a), false); BOOST_CHECK_EQUAL(factory.register_prototype("SDerivedA", make_shared<DerivedA>()), false); // Check that the correct object is created auto obj = factory.create("DerivedA"); BOOST_CHECK_EQUAL(obj->get(), 1); auto sobj = factory.create("DerivedA"); BOOST_CHECK_EQUAL(sobj->get(), 1); // Unregister an existent tag should work BOOST_CHECK_EQUAL(factory.has_tag("DerivedA"), true); BOOST_CHECK_EQUAL(factory.unregister_prototype("DerivedA"), true); // Unregister a non-existent tag should fail BOOST_CHECK_EQUAL(factory.has_tag("DerivedA"), false); BOOST_CHECK_EQUAL(factory.unregister_prototype("DerivedA"), false); // Check the default behavior with throws BOOST_CHECK_THROW(factory.create("DerivedA"), FactoryType::tag_not_registered); // Check customization of on_tag_not_registered factory.on_tag_not_registered([](FactoryType::tag_type tag) { return nullptr; }); BOOST_CHECK_EQUAL(factory.create("DerivedA"), FactoryType::product_type(nullptr)); } BOOST_AUTO_TEST_CASE(MultipleParameters) { // Create a factory and register a type using FactoryType = mwheel::PrototypeFactory<BaseMultiParms, int>; FactoryType factory; BOOST_CHECK_EQUAL(factory.register_prototype(0, make_shared<DerivedSum>(10)), true); // Check creation using multiple parameters auto obja = factory.create(0, 3); BOOST_CHECK_EQUAL(obja->get(), 3); auto objb = factory.create(0, 3, 6); BOOST_CHECK_EQUAL(objb->get(), 9); } BOOST_AUTO_TEST_SUITE_END()
Add virtual destructor to BaseMultiParms class (#16)
Add virtual destructor to BaseMultiParms class (#16)
C++
mit
alalazo/modern_wheel
a6741a4f8ed167adda6b27a359eec9291e8b3b8e
rclcpp/test/rclcpp/test_logger.cpp
rclcpp/test/rclcpp/test_logger.cpp
// Copyright 2017 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <gtest/gtest.h> #include <string> #include "rclcpp/logger.hpp" #include "rclcpp/logging.hpp" TEST(TestLogger, factory_functions) { rclcpp::Logger logger = rclcpp::get_logger("test_logger"); EXPECT_STREQ("test_logger", logger.get_name()); rclcpp::Logger logger_copy = rclcpp::Logger(logger); EXPECT_STREQ("test_logger", logger_copy.get_name()); } TEST(TestLogger, hierarchy) { rclcpp::Logger logger = rclcpp::get_logger("test_logger"); rclcpp::Logger sublogger = logger.get_child("child"); EXPECT_STREQ("test_logger.child", sublogger.get_name()); rclcpp::Logger subsublogger = sublogger.get_child("grandchild"); EXPECT_STREQ("test_logger.child.grandchild", subsublogger.get_name()); }
// Copyright 2017 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <gtest/gtest.h> #include <memory> #include <string> #include "rclcpp/logger.hpp" #include "rclcpp/logging.hpp" #include "rclcpp/node.hpp" TEST(TestLogger, factory_functions) { rclcpp::Logger logger = rclcpp::get_logger("test_logger"); EXPECT_STREQ("test_logger", logger.get_name()); rclcpp::Logger logger_copy = rclcpp::Logger(logger); EXPECT_STREQ("test_logger", logger_copy.get_name()); } TEST(TestLogger, hierarchy) { rclcpp::Logger logger = rclcpp::get_logger("test_logger"); rclcpp::Logger sublogger = logger.get_child("child"); EXPECT_STREQ("test_logger.child", sublogger.get_name()); rclcpp::Logger subsublogger = sublogger.get_child("grandchild"); EXPECT_STREQ("test_logger.child.grandchild", subsublogger.get_name()); } TEST(TestLogger, get_node_logger) { rclcpp::init(0, nullptr); auto node = std::make_shared<rclcpp::Node>("my_node", "/ns"); auto node_base = rclcpp::node_interfaces::get_node_base_interface(node); auto logger = rclcpp::get_node_logger(node_base->get_rcl_node_handle()); EXPECT_STREQ(logger.get_name(), "ns.my_node"); logger = rclcpp::get_node_logger(nullptr); EXPECT_STREQ(logger.get_name(), "rclcpp"); rclcpp::shutdown(); }
Add unit tests for logging functionality (#1184)
Add unit tests for logging functionality (#1184) Signed-off-by: Stephen Brawner <[email protected]>
C++
apache-2.0
ros2/rclcpp,ros2/rclcpp
b985b5c9efdd158f4cf4ae71631c3df22e8e3a78
res/generators/templates/api/platform/android/gen/jni/montana_js_wrap.cpp
res/generators/templates/api/platform/android/gen/jni/montana_js_wrap.cpp
#include "<%= $cur_module.name %>.h" #include "MethodResultJni.h" <%if $cur_module.is_template_default_instance %> #include "api_generator/MethodResult.h" #include "api_generator/MethodResultConvertor.h" #include "api_generator/JSONResultConvertor.h" <% end %> #include "rhodes/JNIRhoJS.h" #include "logging/RhoLog.h" #undef DEFAULT_LOGCATEGORY #define DEFAULT_LOGCATEGORY "<%= $cur_module.name %>JS" typedef <%= api_generator_cpp_MakeNamespace($cur_module.parents)%>C<%= $cur_module.name %>Proxy<ArgumentsAdapter<rho::json::CJSONArray> > ObjectProxy; using namespace rho::apiGenerator; <% if $cur_module.is_template_default_instance %> <%= api_generator_MakeJSMethodDecl($cur_module.name, "getDefaultID", true) %> { RAWTRACE(__FUNCTION__); rho::apiGenerator::CMethodResult result(false); result.set(ObjectProxy::getDefaultID()); return CMethodResultConvertor().toJSON(result); } <%= api_generator_MakeJSMethodDecl($cur_module.name, "getDefault", true) %> { RAWTRACE(__FUNCTION__); rho::apiGenerator::CMethodResult result(false); result.setJSObjectClassPath("<%= api_generator_getJSModuleName(api_generator_getRubyModuleFullName($cur_module))%>"); result.set(ObjectProxy::getDefaultID()); return CMethodResultConvertor().toJSON(result); } <%= api_generator_MakeJSMethodDecl($cur_module.name, "setDefaultID", true) %> { RAWTRACE(__FUNCTION__); rho::apiGenerator::CMethodResult result(false); ObjectProxy::setDefaultID(strObjID); return CMethodResultConvertor().toJSON(result); } <% end %> <% $cur_module.methods.each do |method| %> <%= api_generator_MakeJSMethodDecl($cur_module.name, method.native_name, method.access == ModuleMethod::ACCESS_STATIC) %> { RAWTRACE2("%s(id=%s)", __FUNCTION__, strObjID.c_str()); MethodResultJni result(false); if(!result) { result.setError("JNI error: failed to initialize MethodResult java object"); RAWLOG_ERROR("JNI error: failed to initialize MethodResult java object ^^^"); return CMethodResultConvertor().toJSON(result); } <% unless method.access == ModuleMethod::ACCESS_STATIC %> ObjectProxy <%= $cur_module.name.downcase %>(strObjID);<% end min_params = 0 max_params = method.params.size method.params.each_index do |idx| param = method.params[idx] next if param.can_be_nil min_params = idx + 1 end #if method.has_callback == ModuleMethod::CALLBACK_MANDATORY # min_params = method.params.size + 1 #elsif method.has_callback == ModuleMethod::CALLBACK_NONE # max_params = method.params.size #end %> int argc = argv.getSize(); if((argc < <%= min_params %>) || (argc > <%= max_params %>)) { result.setArgError("Wrong number of arguments"); RAWLOG_ERROR1("Wrong number of arguments: %d ^^^", argc); return CMethodResultConvertor().toJSON(result); } if(strCallbackID.length() != 0) { result.setCallBack(strCallbackID, strCallbackParam); } <% if method.has_callback == ModuleMethod::CALLBACK_MANDATORY %> if(!result.hasCallback()) { if(!result.isError()) { result.setArgError("No callback handler provided"); } RAWLOG_ERROR1("Error setting callback: %s", result.getErrorMessage().c_str()); return CMethodResultConvertor().toJSON(result); } <% end if api_generator_isApiObjectParam(method.result) if method.result.type == MethodParam::TYPE_SELF %> result.setObjectClassPath("<%= api_generator_getJSModuleName(api_generator_getRubyModuleFullName($cur_module))%>"); RAWTRACE("Object class path is set");<% else %> result.setObjectClassPath("<%= api_generator_getJSModuleName(api_generator_ruby_makeApiObjectTypeName(method.result, $cur_module)) %>"); RAWTRACE("Object class path is set");<% end end if method.access == ModuleMethod::ACCESS_STATIC %> ObjectProxy::<%= method.native_name %>(argumentsAdapter(argv), result); <% else %> <%= $cur_module.name.downcase %>.<%= method.native_name %>(argumentsAdapter(argv), result); <% end %> rho::String res = CMethodResultConvertor().toJSON(result); RAWTRACE(res.c_str()); RAWTRACE2("%s(id=%s) end ^^^", __FUNCTION__, strObjID.c_str()); return res; }<% end %>
#include "<%= $cur_module.name %>.h" #include "MethodResultJni.h" <%if $cur_module.is_template_default_instance %> #include "api_generator/MethodResult.h" #include "api_generator/MethodResultConvertor.h" #include "api_generator/JSONResultConvertor.h" <% end %> #include "rhodes/JNIRhoJS.h" #include "logging/RhoLog.h" #undef DEFAULT_LOGCATEGORY #define DEFAULT_LOGCATEGORY "<%= $cur_module.name %>JS" typedef <%= api_generator_cpp_MakeNamespace($cur_module.parents)%>C<%= $cur_module.name %>Proxy<ArgumentsAdapter<rho::json::CJSONArray> > ObjectProxy; using namespace rho::apiGenerator; <% if $cur_module.is_template_default_instance %> <%= api_generator_MakeJSMethodDecl($cur_module.name, "getDefaultID", true) %> { RAWTRACE(__FUNCTION__); rho::apiGenerator::CMethodResult result(false); result.set(ObjectProxy::getDefaultID()); return CMethodResultConvertor().toJSON(result); } <%= api_generator_MakeJSMethodDecl($cur_module.name, "getDefault", true) %> { RAWTRACE(__FUNCTION__); rho::apiGenerator::CMethodResult result(false); result.setJSObjectClassPath("<%= api_generator_getJSModuleName(api_generator_getRubyModuleFullName($cur_module))%>"); result.set(ObjectProxy::getDefaultID()); return CMethodResultConvertor().toJSON(result); } <%= api_generator_MakeJSMethodDecl($cur_module.name, "setDefaultID", true) %> { RAWTRACE(__FUNCTION__); rho::apiGenerator::CMethodResult result(false); ObjectProxy::setDefaultID(argv.getItem(0).getString()); return CMethodResultConvertor().toJSON(result); } <% end %> <% $cur_module.methods.each do |method| %> <%= api_generator_MakeJSMethodDecl($cur_module.name, method.native_name, method.access == ModuleMethod::ACCESS_STATIC) %> { RAWTRACE2("%s(id=%s)", __FUNCTION__, strObjID.c_str()); MethodResultJni result(false); if(!result) { result.setError("JNI error: failed to initialize MethodResult java object"); RAWLOG_ERROR("JNI error: failed to initialize MethodResult java object ^^^"); return CMethodResultConvertor().toJSON(result); } <% unless method.access == ModuleMethod::ACCESS_STATIC %> ObjectProxy <%= $cur_module.name.downcase %>(strObjID);<% end min_params = 0 max_params = method.params.size method.params.each_index do |idx| param = method.params[idx] next if param.can_be_nil min_params = idx + 1 end #if method.has_callback == ModuleMethod::CALLBACK_MANDATORY # min_params = method.params.size + 1 #elsif method.has_callback == ModuleMethod::CALLBACK_NONE # max_params = method.params.size #end %> int argc = argv.getSize(); if((argc < <%= min_params %>) || (argc > <%= max_params %>)) { result.setArgError("Wrong number of arguments"); RAWLOG_ERROR1("Wrong number of arguments: %d ^^^", argc); return CMethodResultConvertor().toJSON(result); } if(strCallbackID.length() != 0) { result.setCallBack(strCallbackID, strCallbackParam); } <% if method.has_callback == ModuleMethod::CALLBACK_MANDATORY %> if(!result.hasCallback()) { if(!result.isError()) { result.setArgError("No callback handler provided"); } RAWLOG_ERROR1("Error setting callback: %s", result.getErrorMessage().c_str()); return CMethodResultConvertor().toJSON(result); } <% end if api_generator_isApiObjectParam(method.result) if method.result.type == MethodParam::TYPE_SELF %> result.setObjectClassPath("<%= api_generator_getJSModuleName(api_generator_getRubyModuleFullName($cur_module))%>"); RAWTRACE("Object class path is set");<% else %> result.setObjectClassPath("<%= api_generator_getJSModuleName(api_generator_ruby_makeApiObjectTypeName(method.result, $cur_module)) %>"); RAWTRACE("Object class path is set");<% end end if method.access == ModuleMethod::ACCESS_STATIC %> ObjectProxy::<%= method.native_name %>(argumentsAdapter(argv), result); <% else %> <%= $cur_module.name.downcase %>.<%= method.native_name %>(argumentsAdapter(argv), result); <% end %> rho::String res = CMethodResultConvertor().toJSON(result); RAWTRACE(res.c_str()); RAWTRACE2("%s(id=%s) end ^^^", __FUNCTION__, strObjID.c_str()); return res; }<% end %>
Fix setDefault in generator
Android: Fix setDefault in generator
C++
mit
louisatome/rhodes,rhosilver/rhodes-1,rhosilver/rhodes-1,UIKit0/rhodes,rhosilver/rhodes-1,UIKit0/rhodes,louisatome/rhodes,UIKit0/rhodes,UIKit0/rhodes,rhosilver/rhodes-1,UIKit0/rhodes,rhosilver/rhodes-1,UIKit0/rhodes,louisatome/rhodes,rhosilver/rhodes-1,louisatome/rhodes,rhosilver/rhodes-1,rhosilver/rhodes-1,rhosilver/rhodes-1,UIKit0/rhodes,louisatome/rhodes,UIKit0/rhodes,louisatome/rhodes,louisatome/rhodes,rhosilver/rhodes-1,UIKit0/rhodes,UIKit0/rhodes,louisatome/rhodes,louisatome/rhodes
e722c9486b68198196ea2b5b9b7f3409e2559b57
addons/medical/script_component.hpp
addons/medical/script_component.hpp
#define COMPONENT medical #include "\z\fpa\addons\main\script_mod.hpp" #define DEBUG_MODE_FULL // #define DISABLE_COMPILE_CACHE // #define CBA_DEBUG_SYNCHRONOUS // #define ENABLE_PERFORMANCE_COUNTERS #include "\z\fpa\addons\main\script_macros.hpp"
#define COMPONENT medical #include "\z\fpa\addons\main\script_mod.hpp" // #define DEBUG_MODE_FULL // #define DISABLE_COMPILE_CACHE // #define CBA_DEBUG_SYNCHRONOUS // #define ENABLE_PERFORMANCE_COUNTERS #include "\z\fpa\addons\main\script_macros.hpp"
disable debug mode
disable debug mode
C++
mit
fparma/fparma-mods,fparma/fparma-mods,fparma/fparma-mods
e507648688eefa966038e36241bf2e11847a19ce
Source/Samples/SamplesManager.cpp
Source/Samples/SamplesManager.cpp
// // Copyright (c) 2017-2019 the rbfx project. // // 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 <Urho3D/Engine/EngineDefs.h> #include <Urho3D/Core/CoreEvents.h> #include <Urho3D/Core/CommandLine.h> #include <Urho3D/Core/StringUtils.h> #include <Urho3D/Input/Input.h> #include <Urho3D/Input/InputEvents.h> #include <Urho3D/IO/FileSystem.h> #include <Urho3D/Resource/ResourceCache.h> #include <Urho3D/UI/Font.h> #include <Urho3D/UI/Button.h> #include <Urho3D/UI/ListView.h> #include <Urho3D/UI/Text.h> #include <Urho3D/UI/UI.h> #include <Urho3D/UI/UIEvents.h> #include "01_HelloWorld/HelloWorld.h" #include "02_HelloGUI/HelloGUI.h" #include "03_Sprites/Sprites.h" #include "04_StaticScene/StaticScene.h" #include "05_AnimatingScene/AnimatingScene.h" #include "06_SkeletalAnimation/SkeletalAnimation.h" #include "07_Billboards/Billboards.h" #include "08_Decals/Decals.h" #include "09_MultipleViewports/MultipleViewports.h" #include "10_RenderToTexture/RenderToTexture.h" #if URHO3D_PHYSICS #include "11_Physics/Physics.h" #include "12_PhysicsStressTest/PhysicsStressTest.h" #include "13_Ragdolls/Ragdolls.h" #endif #include "14_SoundEffects/SoundEffects.h" #if URHO3D_NAVIGATION #include "15_Navigation/Navigation.h" #endif #if URHO3D_NETWORK #include "16_Chat/Chat.h" #include "17_SceneReplication/SceneReplication.h" #endif #if URHO3D_PHYSICS #include "18_CharacterDemo/CharacterDemo.h" #include "19_VehicleDemo/VehicleDemo.h" #endif #include "20_HugeObjectCount/HugeObjectCount.h" #include "23_Water/Water.h" #if URHO3D_URHO2D #include "24_Urho2DSprite/Urho2DSprite.h" #include "25_Urho2DParticle/Urho2DParticle.h" #include "26_ConsoleInput/ConsoleInput.h" #include "27_Urho2DPhysics/Urho2DPhysics.h" #include "28_Urho2DPhysicsRope/Urho2DPhysicsRope.h" #endif #include "29_SoundSynthesis/SoundSynthesis.h" #include "30_LightAnimation/LightAnimation.h" #include "31_MaterialAnimation/MaterialAnimation.h" #if URHO3D_URHO2D #include "32_Urho2DConstraints/Urho2DConstraints.h" #include "33_Urho2DSpriterAnimation/Urho2DSpriterAnimation.h" #endif #include "34_DynamicGeometry/DynamicGeometry.h" #include "35_SignedDistanceFieldText/SignedDistanceFieldText.h" #if URHO3D_URHO2D #include "36_Urho2DTileMap/Urho2DTileMap.h" #endif #include "37_UIDrag/UIDrag.h" #include "38_SceneAndUILoad/SceneAndUILoad.h" #if URHO3D_NAVIGATION #include "39_CrowdNavigation/CrowdNavigation.h" #endif #include "40_Localization/L10n.h" #if !__EMSCRIPTEN__ #include "42_PBRMaterials/PBRMaterials.h" #endif #if URHO3D_NETWORK #include "43_HttpRequestDemo/HttpRequestDemo.h" #endif #include "44_RibbonTrailDemo/RibbonTrailDemo.h" #if URHO3D_PHYSICS #if URHO3D_IK #include "45_InverseKinematics/InverseKinematics.h" #endif #include "46_RaycastVehicle/RaycastVehicleDemo.h" #endif #include "47_Typography/Typography.h" #include "48_Hello3DUI/Hello3DUI.h" #if URHO3D_URHO2D #include "49_Urho2DIsometricDemo/Urho2DIsometricDemo.h" #include "50_Urho2DPlatformer/Urho2DPlatformer.h" #endif #if URHO3D_NETWORK #include "52_NATPunchtrough/NATPunchtrough.h" #include "53_LANDiscovery/LANDiscovery.h" #endif #if URHO3D_SYSTEMUI #include "100_HelloSystemUI/HelloSystemUI.h" #endif #include "105_Serialization/Serialization.h" #include "Rotator.h" #include "SamplesManager.h" // Expands to this example's entry-point URHO3D_DEFINE_APPLICATION_MAIN(Urho3D::SamplesManager); namespace Urho3D { SamplesManager::SamplesManager(Context* context) : Application(context) { } void SamplesManager::Setup() { // Modify engine startup parameters engineParameters_[EP_WINDOW_TITLE] = "rbfx samples"; engineParameters_[EP_LOG_NAME] = GetSubsystem<FileSystem>()->GetAppPreferencesDir("rbfx", "samples") + GetTypeName() + ".log"; engineParameters_[EP_FULL_SCREEN] = false; engineParameters_[EP_HEADLESS] = false; engineParameters_[EP_SOUND] = true; #if MOBILE engineParameters_[EP_ORIENTATIONS] = "Portrait"; #else engineParameters_[EP_WINDOW_WIDTH] = 1440; engineParameters_[EP_WINDOW_HEIGHT] = 900; #endif if (!engineParameters_.contains(EP_RESOURCE_PREFIX_PATHS)) engineParameters_[EP_RESOURCE_PREFIX_PATHS] = ";..;../.."; GetCommandLineParser().add_option("--sample", startSample_); } void SamplesManager::Start() { Input* input = context_->GetInput(); UI* ui = context_->GetUI(); // Register an object factory for our custom Rotator component so that we can create them to scene nodes context_->RegisterFactory<Rotator>(); input->SetMouseMode(MM_FREE); input->SetMouseVisible(true); #if URHO3D_SYSTEMUI context_->GetEngine()->CreateDebugHud()->ToggleAll(); #endif SubscribeToEvent(E_RELEASED, [this](StringHash, VariantMap& args) { OnClickSample(args); }); SubscribeToEvent(E_KEYUP, [this](StringHash, VariantMap& args) { OnKeyPress(args); }); SubscribeToEvent(E_BEGINFRAME, [this](StringHash, VariantMap& args) { OnFrameStart(); }); ui->GetRoot()->SetDefaultStyle(context_->GetCache()->GetResource<XMLFile>("UI/DefaultStyle.xml")); auto* layout = ui->GetRoot()->CreateChild<UIElement>(); listViewHolder_ = layout; layout->SetLayoutMode(LM_VERTICAL); layout->SetAlignment(HA_CENTER, VA_CENTER); layout->SetSize(300, 600); layout->SetStyleAuto(); auto* list = layout->CreateChild<ListView>(); list->SetMinSize(300, 600); list->SetSelectOnClickEnd(true); list->SetHighlightMode(HM_ALWAYS); list->SetStyleAuto(); list->SetName("SampleList"); // Get logo texture ResourceCache* cache = GetSubsystem<ResourceCache>(); Texture2D* logoTexture = cache->GetResource<Texture2D>("Textures/rbfx-logo.png"); if (!logoTexture) return; logoSprite_ = ui->GetRoot()->CreateChild<Sprite>(); logoSprite_->SetTexture(logoTexture); int textureWidth = logoTexture->GetWidth(); int textureHeight = logoTexture->GetHeight(); logoSprite_->SetScale(256.0f / textureWidth); logoSprite_->SetSize(textureWidth, textureHeight); logoSprite_->SetHotSpot(textureWidth, textureHeight); logoSprite_->SetAlignment(HA_RIGHT, VA_BOTTOM); logoSprite_->SetOpacity(0.9f); logoSprite_->SetPriority(-100); RegisterSample<HelloWorld>(); RegisterSample<HelloGUI>(); RegisterSample<Sprites>(); RegisterSample<StaticScene>(); RegisterSample<AnimatingScene>(); RegisterSample<SkeletalAnimation>(); RegisterSample<Billboards>(); RegisterSample<Decals>(); RegisterSample<MultipleViewports>(); RegisterSample<RenderToTexture>(); #if URHO3D_PHYSICS RegisterSample<Physics>(); RegisterSample<PhysicsStressTest>(); RegisterSample<Ragdolls>(); #endif RegisterSample<SoundEffects>(); #if URHO3D_NAVIGATION RegisterSample<Navigation>(); #endif #if URHO3D_NETWORK RegisterSample<Chat>(); RegisterSample<SceneReplication>(); #endif #if URHO3D_PHYSICS RegisterSample<CharacterDemo>(); RegisterSample<VehicleDemo>(); #endif RegisterSample<HugeObjectCount>(); RegisterSample<Water>(); #if URHO3D_URHO2D RegisterSample<Urho2DSprite>(); RegisterSample<Urho2DParticle>(); #endif #if URHO3D_SYSTEMUI RegisterSample<ConsoleInput>(); #endif #if URHO3D_URHO2D RegisterSample<Urho2DPhysics>(); RegisterSample<Urho2DPhysicsRope>(); #endif RegisterSample<SoundSynthesis>(); RegisterSample<LightAnimation>(); RegisterSample<MaterialAnimation>(); #if URHO3D_URHO2D RegisterSample<Urho2DConstraints>(); RegisterSample<Urho2DSpriterAnimation>(); #endif RegisterSample<DynamicGeometry>(); RegisterSample<SignedDistanceFieldText>(); #if URHO3D_URHO2D RegisterSample<Urho2DTileMap>(); #endif RegisterSample<UIDrag>(); RegisterSample<SceneAndUILoad>(); #if URHO3D_NAVIGATION RegisterSample<CrowdNavigation>(); #endif RegisterSample<L10n>(); #if !__EMSCRIPTEN__ RegisterSample<PBRMaterials>(); #endif #if URHO3D_NETWORK RegisterSample<HttpRequestDemo>(); #endif RegisterSample<RibbonTrailDemo>(); #if URHO3D_PHYSICS #if URHO3D_IK RegisterSample<InverseKinematics>(); #endif RegisterSample<RaycastVehicleDemo>(); #endif RegisterSample<Typography>(); RegisterSample<Hello3DUI>(); #if URHO3D_URHO2D RegisterSample<Urho2DIsometricDemo>(); RegisterSample<Urho2DPlatformer>(); #endif #if URHO3D_NETWORK RegisterSample<NATPunchtrough>(); RegisterSample<LANDiscovery>(); #endif #if URHO3D_SYSTEMUI RegisterSample<HelloSystemUi>(); #endif RegisterSample<Serialization>(); if (!startSample_.empty()) StartSample(startSample_); } void SamplesManager::Stop() { engine_->DumpResources(true); } void SamplesManager::OnClickSample(VariantMap& args) { using namespace Released; StringHash sampleType = static_cast<UIElement*>(args[P_ELEMENT].GetPtr())->GetVar("SampleType").GetStringHash(); if (!sampleType) return; StartSample(sampleType); } void SamplesManager::StartSample(StringHash sampleType) { UI* ui = context_->GetUI(); ui->GetRoot()->RemoveAllChildren(); ui->SetFocusElement(nullptr); #if MOBILE Graphics* graphics = context_->GetGraphics(); graphics->SetOrientations("LandscapeLeft LandscapeRight"); IntVector2 screenSize = graphics->GetSize(); graphics->SetMode(Max(screenSize.x_, screenSize.y_), Min(screenSize.x_, screenSize.y_)); #endif runningSample_.StaticCast<Object>(context_->CreateObject(sampleType)); if (runningSample_.NotNull()) runningSample_->Start(); else ErrorExit("Specified sample does not exist."); } void SamplesManager::OnKeyPress(VariantMap& args) { using namespace KeyUp; int key = args[P_KEY].GetInt(); // Close console (if open) or exit when ESC is pressed if (key == KEY_ESCAPE) isClosing_ = true; } void SamplesManager::OnFrameStart() { if (isClosing_) { isClosing_ = false; if (runningSample_.NotNull()) { Input* input = context_->GetInput(); UI* ui = context_->GetUI(); runningSample_->Stop(); runningSample_ = nullptr; input->SetMouseMode(MM_FREE); input->SetMouseVisible(true); ui->SetCursor(nullptr); ui->GetRoot()->RemoveAllChildren(); ui->GetRoot()->AddChild(listViewHolder_); ui->GetRoot()->AddChild(logoSprite_); #if MOBILE Graphics* graphics = context_->GetGraphics(); graphics->SetOrientations("Portrait"); IntVector2 screenSize = graphics->GetSize(); graphics->SetMode(Min(screenSize.x_, screenSize.y_), Max(screenSize.x_, screenSize.y_)); #endif } else { #if URHO3D_SYSTEMUI if (auto* console = GetSubsystem<Console>()) { if (console->IsVisible()) { console->SetVisible(false); return; } } #endif context_->GetEngine()->Exit(); } } } template<typename T> void SamplesManager::RegisterSample() { context_->RegisterFactory<T>(); auto* button = context_->CreateObject<Button>().Detach(); button->SetMinHeight(30); button->SetStyleAuto(); button->SetVar("SampleType", T::GetTypeStatic()); auto* title = button->CreateChild<Text>(); title->SetAlignment(HA_CENTER, VA_CENTER); title->SetText(T::GetTypeNameStatic()); title->SetFont(context_->GetCache()->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 30); title->SetStyleAuto(); context_->GetUI()->GetRoot()->GetChildStaticCast<ListView>("SampleList", true)->AddItem(button); } }
// // Copyright (c) 2017-2019 the rbfx project. // // 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 <Urho3D/Engine/EngineDefs.h> #include <Urho3D/Core/CoreEvents.h> #include <Urho3D/Core/CommandLine.h> #include <Urho3D/Core/StringUtils.h> #include <Urho3D/Input/Input.h> #include <Urho3D/Input/InputEvents.h> #include <Urho3D/IO/FileSystem.h> #include <Urho3D/Resource/ResourceCache.h> #include <Urho3D/UI/Font.h> #include <Urho3D/UI/Button.h> #include <Urho3D/UI/ListView.h> #include <Urho3D/UI/Text.h> #include <Urho3D/UI/UI.h> #include <Urho3D/UI/UIEvents.h> #include "01_HelloWorld/HelloWorld.h" #include "02_HelloGUI/HelloGUI.h" #include "03_Sprites/Sprites.h" #include "04_StaticScene/StaticScene.h" #include "05_AnimatingScene/AnimatingScene.h" #include "06_SkeletalAnimation/SkeletalAnimation.h" #include "07_Billboards/Billboards.h" #include "08_Decals/Decals.h" #include "09_MultipleViewports/MultipleViewports.h" #include "10_RenderToTexture/RenderToTexture.h" #if URHO3D_PHYSICS #include "11_Physics/Physics.h" #include "12_PhysicsStressTest/PhysicsStressTest.h" #include "13_Ragdolls/Ragdolls.h" #endif #include "14_SoundEffects/SoundEffects.h" #if URHO3D_NAVIGATION #include "15_Navigation/Navigation.h" #endif #if URHO3D_NETWORK #include "16_Chat/Chat.h" #include "17_SceneReplication/SceneReplication.h" #endif #if URHO3D_PHYSICS #include "18_CharacterDemo/CharacterDemo.h" #include "19_VehicleDemo/VehicleDemo.h" #endif #include "20_HugeObjectCount/HugeObjectCount.h" #include "23_Water/Water.h" #if URHO3D_URHO2D #include "24_Urho2DSprite/Urho2DSprite.h" #include "25_Urho2DParticle/Urho2DParticle.h" #include "26_ConsoleInput/ConsoleInput.h" #include "27_Urho2DPhysics/Urho2DPhysics.h" #include "28_Urho2DPhysicsRope/Urho2DPhysicsRope.h" #endif #include "29_SoundSynthesis/SoundSynthesis.h" #include "30_LightAnimation/LightAnimation.h" #include "31_MaterialAnimation/MaterialAnimation.h" #if URHO3D_URHO2D #include "32_Urho2DConstraints/Urho2DConstraints.h" #include "33_Urho2DSpriterAnimation/Urho2DSpriterAnimation.h" #endif #include "34_DynamicGeometry/DynamicGeometry.h" #include "35_SignedDistanceFieldText/SignedDistanceFieldText.h" #if URHO3D_URHO2D #include "36_Urho2DTileMap/Urho2DTileMap.h" #endif #include "37_UIDrag/UIDrag.h" #include "38_SceneAndUILoad/SceneAndUILoad.h" #if URHO3D_NAVIGATION #include "39_CrowdNavigation/CrowdNavigation.h" #endif #include "40_Localization/L10n.h" #if !__EMSCRIPTEN__ #include "42_PBRMaterials/PBRMaterials.h" #endif #if URHO3D_NETWORK #include "43_HttpRequestDemo/HttpRequestDemo.h" #endif #include "44_RibbonTrailDemo/RibbonTrailDemo.h" #if URHO3D_PHYSICS #if URHO3D_IK #include "45_InverseKinematics/InverseKinematics.h" #endif #include "46_RaycastVehicle/RaycastVehicleDemo.h" #endif #include "47_Typography/Typography.h" #include "48_Hello3DUI/Hello3DUI.h" #if URHO3D_URHO2D #include "49_Urho2DIsometricDemo/Urho2DIsometricDemo.h" #include "50_Urho2DPlatformer/Urho2DPlatformer.h" #endif #if URHO3D_NETWORK #include "52_NATPunchtrough/NATPunchtrough.h" #include "53_LANDiscovery/LANDiscovery.h" #endif #if URHO3D_SYSTEMUI #include "100_HelloSystemUI/HelloSystemUI.h" #endif #include "105_Serialization/Serialization.h" #include "Rotator.h" #include "SamplesManager.h" // Expands to this example's entry-point URHO3D_DEFINE_APPLICATION_MAIN(Urho3D::SamplesManager); namespace Urho3D { SamplesManager::SamplesManager(Context* context) : Application(context) { } void SamplesManager::Setup() { // Modify engine startup parameters engineParameters_[EP_WINDOW_TITLE] = "rbfx samples"; engineParameters_[EP_LOG_NAME] = GetSubsystem<FileSystem>()->GetAppPreferencesDir("rbfx", "samples") + GetTypeName() + ".log"; engineParameters_[EP_FULL_SCREEN] = false; engineParameters_[EP_HEADLESS] = false; engineParameters_[EP_SOUND] = true; #if MOBILE engineParameters_[EP_ORIENTATIONS] = "Portrait"; #endif if (!engineParameters_.contains(EP_RESOURCE_PREFIX_PATHS)) engineParameters_[EP_RESOURCE_PREFIX_PATHS] = ";..;../.."; GetCommandLineParser().add_option("--sample", startSample_); } void SamplesManager::Start() { Input* input = context_->GetInput(); UI* ui = context_->GetUI(); // Register an object factory for our custom Rotator component so that we can create them to scene nodes context_->RegisterFactory<Rotator>(); input->SetMouseMode(MM_FREE); input->SetMouseVisible(true); #if URHO3D_SYSTEMUI context_->GetEngine()->CreateDebugHud()->ToggleAll(); #endif SubscribeToEvent(E_RELEASED, [this](StringHash, VariantMap& args) { OnClickSample(args); }); SubscribeToEvent(E_KEYUP, [this](StringHash, VariantMap& args) { OnKeyPress(args); }); SubscribeToEvent(E_BEGINFRAME, [this](StringHash, VariantMap& args) { OnFrameStart(); }); ui->GetRoot()->SetDefaultStyle(context_->GetCache()->GetResource<XMLFile>("UI/DefaultStyle.xml")); auto* layout = ui->GetRoot()->CreateChild<UIElement>(); listViewHolder_ = layout; layout->SetLayoutMode(LM_VERTICAL); layout->SetAlignment(HA_CENTER, VA_CENTER); layout->SetSize(300, 600); layout->SetStyleAuto(); auto* list = layout->CreateChild<ListView>(); list->SetMinSize(300, 600); list->SetSelectOnClickEnd(true); list->SetHighlightMode(HM_ALWAYS); list->SetStyleAuto(); list->SetName("SampleList"); // Get logo texture ResourceCache* cache = GetSubsystem<ResourceCache>(); Texture2D* logoTexture = cache->GetResource<Texture2D>("Textures/rbfx-logo.png"); if (!logoTexture) return; logoSprite_ = ui->GetRoot()->CreateChild<Sprite>(); logoSprite_->SetTexture(logoTexture); int textureWidth = logoTexture->GetWidth(); int textureHeight = logoTexture->GetHeight(); logoSprite_->SetScale(256.0f / textureWidth); logoSprite_->SetSize(textureWidth, textureHeight); logoSprite_->SetHotSpot(textureWidth, textureHeight); logoSprite_->SetAlignment(HA_RIGHT, VA_BOTTOM); logoSprite_->SetOpacity(0.9f); logoSprite_->SetPriority(-100); RegisterSample<HelloWorld>(); RegisterSample<HelloGUI>(); RegisterSample<Sprites>(); RegisterSample<StaticScene>(); RegisterSample<AnimatingScene>(); RegisterSample<SkeletalAnimation>(); RegisterSample<Billboards>(); RegisterSample<Decals>(); RegisterSample<MultipleViewports>(); RegisterSample<RenderToTexture>(); #if URHO3D_PHYSICS RegisterSample<Physics>(); RegisterSample<PhysicsStressTest>(); RegisterSample<Ragdolls>(); #endif RegisterSample<SoundEffects>(); #if URHO3D_NAVIGATION RegisterSample<Navigation>(); #endif #if URHO3D_NETWORK RegisterSample<Chat>(); RegisterSample<SceneReplication>(); #endif #if URHO3D_PHYSICS RegisterSample<CharacterDemo>(); RegisterSample<VehicleDemo>(); #endif RegisterSample<HugeObjectCount>(); RegisterSample<Water>(); #if URHO3D_URHO2D RegisterSample<Urho2DSprite>(); RegisterSample<Urho2DParticle>(); #endif #if URHO3D_SYSTEMUI RegisterSample<ConsoleInput>(); #endif #if URHO3D_URHO2D RegisterSample<Urho2DPhysics>(); RegisterSample<Urho2DPhysicsRope>(); #endif RegisterSample<SoundSynthesis>(); RegisterSample<LightAnimation>(); RegisterSample<MaterialAnimation>(); #if URHO3D_URHO2D RegisterSample<Urho2DConstraints>(); RegisterSample<Urho2DSpriterAnimation>(); #endif RegisterSample<DynamicGeometry>(); RegisterSample<SignedDistanceFieldText>(); #if URHO3D_URHO2D RegisterSample<Urho2DTileMap>(); #endif RegisterSample<UIDrag>(); RegisterSample<SceneAndUILoad>(); #if URHO3D_NAVIGATION RegisterSample<CrowdNavigation>(); #endif RegisterSample<L10n>(); #if !__EMSCRIPTEN__ RegisterSample<PBRMaterials>(); #endif #if URHO3D_NETWORK RegisterSample<HttpRequestDemo>(); #endif RegisterSample<RibbonTrailDemo>(); #if URHO3D_PHYSICS #if URHO3D_IK RegisterSample<InverseKinematics>(); #endif RegisterSample<RaycastVehicleDemo>(); #endif RegisterSample<Typography>(); RegisterSample<Hello3DUI>(); #if URHO3D_URHO2D RegisterSample<Urho2DIsometricDemo>(); RegisterSample<Urho2DPlatformer>(); #endif #if URHO3D_NETWORK RegisterSample<NATPunchtrough>(); RegisterSample<LANDiscovery>(); #endif #if URHO3D_SYSTEMUI RegisterSample<HelloSystemUi>(); #endif RegisterSample<Serialization>(); if (!startSample_.empty()) StartSample(startSample_); } void SamplesManager::Stop() { engine_->DumpResources(true); } void SamplesManager::OnClickSample(VariantMap& args) { using namespace Released; StringHash sampleType = static_cast<UIElement*>(args[P_ELEMENT].GetPtr())->GetVar("SampleType").GetStringHash(); if (!sampleType) return; StartSample(sampleType); } void SamplesManager::StartSample(StringHash sampleType) { UI* ui = context_->GetUI(); ui->GetRoot()->RemoveAllChildren(); ui->SetFocusElement(nullptr); #if MOBILE Graphics* graphics = context_->GetGraphics(); graphics->SetOrientations("LandscapeLeft LandscapeRight"); IntVector2 screenSize = graphics->GetSize(); graphics->SetMode(Max(screenSize.x_, screenSize.y_), Min(screenSize.x_, screenSize.y_)); #endif runningSample_.StaticCast<Object>(context_->CreateObject(sampleType)); if (runningSample_.NotNull()) runningSample_->Start(); else ErrorExit("Specified sample does not exist."); } void SamplesManager::OnKeyPress(VariantMap& args) { using namespace KeyUp; int key = args[P_KEY].GetInt(); // Close console (if open) or exit when ESC is pressed if (key == KEY_ESCAPE) isClosing_ = true; } void SamplesManager::OnFrameStart() { if (isClosing_) { isClosing_ = false; if (runningSample_.NotNull()) { Input* input = context_->GetInput(); UI* ui = context_->GetUI(); runningSample_->Stop(); runningSample_ = nullptr; input->SetMouseMode(MM_FREE); input->SetMouseVisible(true); ui->SetCursor(nullptr); ui->GetRoot()->RemoveAllChildren(); ui->GetRoot()->AddChild(listViewHolder_); ui->GetRoot()->AddChild(logoSprite_); #if MOBILE Graphics* graphics = context_->GetGraphics(); graphics->SetOrientations("Portrait"); IntVector2 screenSize = graphics->GetSize(); graphics->SetMode(Min(screenSize.x_, screenSize.y_), Max(screenSize.x_, screenSize.y_)); #endif } else { #if URHO3D_SYSTEMUI if (auto* console = GetSubsystem<Console>()) { if (console->IsVisible()) { console->SetVisible(false); return; } } #endif context_->GetEngine()->Exit(); } } } template<typename T> void SamplesManager::RegisterSample() { context_->RegisterFactory<T>(); auto* button = context_->CreateObject<Button>().Detach(); button->SetMinHeight(30); button->SetStyleAuto(); button->SetVar("SampleType", T::GetTypeStatic()); auto* title = button->CreateChild<Text>(); title->SetAlignment(HA_CENTER, VA_CENTER); title->SetText(T::GetTypeNameStatic()); title->SetFont(context_->GetCache()->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 30); title->SetStyleAuto(); context_->GetUI()->GetRoot()->GetChildStaticCast<ListView>("SampleList", true)->AddItem(button); } }
Fix use of --full-screen and --borderless flags with samples.
Samples: Fix use of --full-screen and --borderless flags with samples. Fixes #164
C++
mit
rokups/Urho3D,rokups/Urho3D,rokups/Urho3D,rokups/Urho3D,rokups/Urho3D,rokups/Urho3D
9407ca7c9a561defa3d6132327d246a2be469b29
Source/Tools/Editor/SceneView.cpp
Source/Tools/Editor/SceneView.cpp
// // Copyright (c) 2008-2017 the Urho3D project. // // 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 "SceneView.h" #include "EditorConstants.h" #include "EditorEvents.h" #include <Toolbox/DebugCameraController.h> #include <ImGui/imgui_internal.h> #include <ImGuizmo/ImGuizmo.h> #include <Toolbox/ImGuiDock.h> #include <IconFontCppHeaders/IconsFontAwesome.h> namespace Urho3D { SceneView::SceneView(Context* context) : Object(context) , gizmo_(context) { scene_ = SharedPtr<Scene>(new Scene(context)); scene_->CreateComponent<Octree>(); view_ = SharedPtr<Texture2D>(new Texture2D(context)); view_->SetFilterMode(FILTER_ANISOTROPIC); CreateEditorObjects(); SubscribeToEvent(this, E_EDITORSELECTIONCHANGED, std::bind(&SceneView::OnNodeSelectionChanged, this)); } SceneView::~SceneView() { renderer_->Remove(); } void SceneView::SetScreenRect(const IntRect& rect) { if (rect == screenRect_) return; screenRect_ = rect; view_->SetSize(rect.Width(), rect.Height(), Graphics::GetRGBFormat(), TEXTURE_RENDERTARGET); viewport_ = SharedPtr<Viewport>(new Viewport(context_, scene_, camera_->GetComponent<Camera>(), IntRect(IntVector2::ZERO, rect.Size()))); view_->GetRenderSurface()->SetViewport(0, viewport_); gizmo_.SetScreenRect(rect); } bool SceneView::RenderWindow() { bool open = true; auto& style = ui::GetStyle(); auto padding = style.WindowPadding; style.WindowPadding = {0, 0}; if (ui::BeginDock(title_.CString(), &open, windowFlags_)) { isActive_ = ui::IsWindowHovered(); camera_->GetComponent<DebugCameraController>()->SetEnabled(isActive_); ImGuizmo::SetDrawlist(); ui::Image(view_, ToImGui(screenRect_.Size())); gizmo_.ManipulateSelection(GetCamera()); // Update scene view rect according to window position { auto titlebarHeight = ui::GetCurrentContext()->CurrentWindow->TitleBarHeight(); auto pos = ui::GetWindowPos(); pos.y += titlebarHeight; auto size = ui::GetWindowSize(); size.y -= titlebarHeight; if (size.x > 0 && size.y > 0) { IntRect newRect(ToIntVector2(pos), ToIntVector2(pos + size)); SetScreenRect(newRect); } } if (ui::IsItemHovered()) { // Prevent dragging window when scene view is clicked. windowFlags_ = ImGuiWindowFlags_NoMove; // Handle object selection. if (!gizmo_.IsActive() && GetInput()->GetMouseButtonPress(MOUSEB_LEFT)) { IntVector2 pos = GetInput()->GetMousePosition(); pos -= screenRect_.Min(); Ray cameraRay = camera_->GetComponent<Camera>()->GetScreenRay((float)pos.x_ / screenRect_.Width(), (float)pos.y_ / screenRect_.Height()); // Pick only geometry objects, not eg. zones or lights, only get the first (closest) hit PODVector<RayQueryResult> results; RayOctreeQuery query(results, cameraRay, RAY_TRIANGLE, M_INFINITY, DRAWABLE_GEOMETRY); scene_->GetComponent<Octree>()->RaycastSingle(query); if (!results.Size()) { // When object geometry was not hit by a ray - query for object bounding box. RayOctreeQuery query2(results, cameraRay, RAY_OBB, M_INFINITY, DRAWABLE_GEOMETRY); scene_->GetComponent<Octree>()->RaycastSingle(query2); } if (results.Size()) { WeakPtr<Node> clickNode(results[0].drawable_->GetNode()); if (!GetInput()->GetKeyDown(KEY_CTRL)) UnselectAll(); ToggleSelection(clickNode); } else UnselectAll(); } } else windowFlags_ = 0; } ui::EndDock(); style.WindowPadding = padding; return open; } void SceneView::LoadScene(const String& filePath) { if (filePath.EndsWith(".xml", false)) { if (scene_->LoadXML(GetCache()->GetResource<XMLFile>(filePath)->GetRoot())) CreateEditorObjects(); else URHO3D_LOGERRORF("Loading scene %s failed", GetFileName(filePath).CString()); } else if (filePath.EndsWith(".json", false)) { if (scene_->LoadJSON(GetCache()->GetResource<JSONFile>(filePath)->GetRoot())) CreateEditorObjects(); else URHO3D_LOGERRORF("Loading scene %s failed", GetFileName(filePath).CString()); } else URHO3D_LOGERRORF("Unknown scene file format %s", GetExtension(filePath).CString()); } void SceneView::CreateEditorObjects() { camera_ = scene_->CreateChild("DebugCamera"); camera_->AddTag(InternalEditorElementTag); camera_->CreateComponent<Camera>(); camera_->CreateComponent<DebugCameraController>(); scene_->GetOrCreateComponent<DebugRenderer>()->SetView(GetCamera()); } void SceneView::Select(Node* node) { if (gizmo_.Select(node)) { using namespace EditorSelectionChanged; SendEvent(E_EDITORSELECTIONCHANGED, P_SCENEVIEW, this); } } void SceneView::Unselect(Node* node) { if (gizmo_.Unselect(node)) { using namespace EditorSelectionChanged; SendEvent(E_EDITORSELECTIONCHANGED, P_SCENEVIEW, this); } } void SceneView::ToggleSelection(Node* node) { gizmo_.ToggleSelection(node); using namespace EditorSelectionChanged; SendEvent(E_EDITORSELECTIONCHANGED, P_SCENEVIEW, this); } void SceneView::UnselectAll() { if (gizmo_.UnselectAll()) { using namespace EditorSelectionChanged; SendEvent(E_EDITORSELECTIONCHANGED, P_SCENEVIEW, this); } } const Vector<WeakPtr<Node>>& SceneView::GetSelection() const { return gizmo_.GetSelection(); } void SceneView::RenderGizmoButtons() { const auto& style = ui::GetStyle(); auto drawGizmoOperationButton = [&](GizmoOperation operation, const char* icon, const char* tooltip) { if (gizmo_.GetOperation() == operation) ui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_ButtonActive]); else ui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_Button]); if (ui::ButtonEx(icon, {0, 0}, ImGuiButtonFlags_PressedOnClick)) gizmo_.SetOperation(operation); ui::PopStyleColor(); ui::SameLine(); if (ui::IsItemHovered()) ui::SetTooltip(tooltip); }; auto drawGizmoTransformButton = [&](TransformSpace transformSpace, const char* icon, const char* tooltip) { if (gizmo_.GetTransformSpace() == transformSpace) ui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_ButtonActive]); else ui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_Button]); if (ui::ButtonEx(icon, {0, 0}, ImGuiButtonFlags_PressedOnClick)) gizmo_.SetTransformSpace(transformSpace); ui::PopStyleColor(); ui::SameLine(); if (ui::IsItemHovered()) ui::SetTooltip(tooltip); }; drawGizmoOperationButton(GIZMOOP_TRANSLATE, ICON_FA_ARROWS, "Translate"); drawGizmoOperationButton(GIZMOOP_ROTATE, ICON_FA_REPEAT, "Rotate"); drawGizmoOperationButton(GIZMOOP_SCALE, ICON_FA_ARROWS_ALT, "Scale"); ui::TextUnformatted("|"); ui::SameLine(); drawGizmoTransformButton(TS_WORLD, ICON_FA_ARROWS, "World"); drawGizmoTransformButton(TS_LOCAL, ICON_FA_ARROWS_ALT, "Local"); } bool SceneView::IsSelected(Node* node) const { return gizmo_.IsSelected(node); } void SceneView::Select(Serializable* serializable) { selectedSerializable_ = serializable; } void SceneView::OnNodeSelectionChanged() { using namespace EditorSelectionChanged; // TODO: inspector for multi-selection. const auto& selection = GetSelection(); if (selection.Size() == 1) Select(DynamicCast<Serializable>(selection.Front())); else Select((Serializable*)nullptr); } }
// // Copyright (c) 2008-2017 the Urho3D project. // // 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 "SceneView.h" #include "EditorConstants.h" #include "EditorEvents.h" #include <Toolbox/DebugCameraController.h> #include <ImGui/imgui_internal.h> #include <ImGuizmo/ImGuizmo.h> #include <Toolbox/ImGuiDock.h> #include <IconFontCppHeaders/IconsFontAwesome.h> namespace Urho3D { SceneView::SceneView(Context* context) : Object(context) , gizmo_(context) { scene_ = SharedPtr<Scene>(new Scene(context)); scene_->CreateComponent<Octree>(); view_ = SharedPtr<Texture2D>(new Texture2D(context)); view_->SetFilterMode(FILTER_ANISOTROPIC); CreateEditorObjects(); SubscribeToEvent(this, E_EDITORSELECTIONCHANGED, std::bind(&SceneView::OnNodeSelectionChanged, this)); } SceneView::~SceneView() { renderer_->Remove(); } void SceneView::SetScreenRect(const IntRect& rect) { if (rect == screenRect_) return; screenRect_ = rect; view_->SetSize(rect.Width(), rect.Height(), Graphics::GetRGBFormat(), TEXTURE_RENDERTARGET); viewport_ = SharedPtr<Viewport>(new Viewport(context_, scene_, camera_->GetComponent<Camera>(), IntRect(IntVector2::ZERO, rect.Size()))); view_->GetRenderSurface()->SetViewport(0, viewport_); gizmo_.SetScreenRect(rect); } bool SceneView::RenderWindow() { bool open = true; auto& style = ui::GetStyle(); auto padding = style.WindowPadding; style.WindowPadding = {0, 0}; if (ui::BeginDock(title_.CString(), &open, windowFlags_)) { isActive_ = ui::IsWindowHovered(); camera_->GetComponent<DebugCameraController>()->SetEnabled(isActive_); ImGuizmo::SetDrawlist(); ui::Image(view_, ToImGui(screenRect_.Size())); gizmo_.ManipulateSelection(GetCamera()); // Update scene view rect according to window position { auto titlebarHeight = ui::GetCurrentContext()->CurrentWindow->TitleBarHeight(); auto pos = ui::GetWindowPos(); pos.y += titlebarHeight; auto size = ui::GetWindowSize(); size.y -= titlebarHeight; if (size.x > 0 && size.y > 0) { IntRect newRect(ToIntVector2(pos), ToIntVector2(pos + size)); SetScreenRect(newRect); } } if (ui::IsItemHovered()) { // Prevent dragging window when scene view is clicked. windowFlags_ = ImGuiWindowFlags_NoMove; // Handle object selection. if (!gizmo_.IsActive() && GetInput()->GetMouseButtonPress(MOUSEB_LEFT)) { IntVector2 pos = GetInput()->GetMousePosition(); pos -= screenRect_.Min(); Ray cameraRay = camera_->GetComponent<Camera>()->GetScreenRay((float)pos.x_ / screenRect_.Width(), (float)pos.y_ / screenRect_.Height()); // Pick only geometry objects, not eg. zones or lights, only get the first (closest) hit PODVector<RayQueryResult> results; RayOctreeQuery query(results, cameraRay, RAY_TRIANGLE, M_INFINITY, DRAWABLE_GEOMETRY); scene_->GetComponent<Octree>()->RaycastSingle(query); if (!results.Size()) { // When object geometry was not hit by a ray - query for object bounding box. RayOctreeQuery query2(results, cameraRay, RAY_OBB, M_INFINITY, DRAWABLE_GEOMETRY); scene_->GetComponent<Octree>()->RaycastSingle(query2); } if (results.Size()) { WeakPtr<Node> clickNode(results[0].drawable_->GetNode()); if (!GetInput()->GetKeyDown(KEY_CTRL)) UnselectAll(); ToggleSelection(clickNode); } else UnselectAll(); } } else windowFlags_ = 0; } ui::EndDock(); style.WindowPadding = padding; return open; } void SceneView::LoadScene(const String& filePath) { if (filePath.EndsWith(".xml", false)) { if (scene_->LoadXML(GetCache()->GetResource<XMLFile>(filePath)->GetRoot())) CreateEditorObjects(); else URHO3D_LOGERRORF("Loading scene %s failed", GetFileName(filePath).CString()); } else if (filePath.EndsWith(".json", false)) { if (scene_->LoadJSON(GetCache()->GetResource<JSONFile>(filePath)->GetRoot())) CreateEditorObjects(); else URHO3D_LOGERRORF("Loading scene %s failed", GetFileName(filePath).CString()); } else URHO3D_LOGERRORF("Unknown scene file format %s", GetExtension(filePath).CString()); } void SceneView::CreateEditorObjects() { camera_ = scene_->CreateChild("DebugCamera"); camera_->AddTag(InternalEditorElementTag); camera_->CreateComponent<Camera>(); camera_->CreateComponent<DebugCameraController>(); scene_->GetOrCreateComponent<DebugRenderer>()->SetView(GetCamera()); } void SceneView::Select(Node* node) { if (gizmo_.Select(node)) { using namespace EditorSelectionChanged; SendEvent(E_EDITORSELECTIONCHANGED, P_SCENEVIEW, this); } } void SceneView::Unselect(Node* node) { if (gizmo_.Unselect(node)) { using namespace EditorSelectionChanged; SendEvent(E_EDITORSELECTIONCHANGED, P_SCENEVIEW, this); } } void SceneView::ToggleSelection(Node* node) { gizmo_.ToggleSelection(node); using namespace EditorSelectionChanged; SendEvent(E_EDITORSELECTIONCHANGED, P_SCENEVIEW, this); } void SceneView::UnselectAll() { if (gizmo_.UnselectAll()) { using namespace EditorSelectionChanged; SendEvent(E_EDITORSELECTIONCHANGED, P_SCENEVIEW, this); } } const Vector<WeakPtr<Node>>& SceneView::GetSelection() const { return gizmo_.GetSelection(); } void SceneView::RenderGizmoButtons() { const auto& style = ui::GetStyle(); auto drawGizmoOperationButton = [&](GizmoOperation operation, const char* icon, const char* tooltip) { if (gizmo_.GetOperation() == operation) ui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_ButtonActive]); else ui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_Button]); if (ui::ButtonEx(icon, {20, 20}, ImGuiButtonFlags_PressedOnClick)) gizmo_.SetOperation(operation); ui::PopStyleColor(); ui::SameLine(); if (ui::IsItemHovered()) ui::SetTooltip(tooltip); }; auto drawGizmoTransformButton = [&](TransformSpace transformSpace, const char* icon, const char* tooltip) { if (gizmo_.GetTransformSpace() == transformSpace) ui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_ButtonActive]); else ui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_Button]); if (ui::ButtonEx(icon, {20, 20}, ImGuiButtonFlags_PressedOnClick)) gizmo_.SetTransformSpace(transformSpace); ui::PopStyleColor(); ui::SameLine(); if (ui::IsItemHovered()) ui::SetTooltip(tooltip); }; drawGizmoOperationButton(GIZMOOP_TRANSLATE, ICON_FA_ARROWS, "Translate"); drawGizmoOperationButton(GIZMOOP_ROTATE, ICON_FA_REPEAT, "Rotate"); drawGizmoOperationButton(GIZMOOP_SCALE, ICON_FA_ARROWS_ALT, "Scale"); ui::TextUnformatted("|"); ui::SameLine(); drawGizmoTransformButton(TS_WORLD, ICON_FA_ARROWS, "World"); drawGizmoTransformButton(TS_LOCAL, ICON_FA_ARROWS_ALT, "Local"); ui::TextUnformatted("|"); ui::SameLine(); auto light = camera_->GetComponent<Light>(); if (light->IsEnabled()) ui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_ButtonActive]); else ui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_Button]); if (ui::Button(ICON_FA_LIGHTBULB_O, {20, 20})) light->SetEnabled(!light->IsEnabled()); ui::PopStyleColor(); ui::SameLine(); if (ui::IsItemHovered()) ui::SetTooltip("Camera Headlight"); } bool SceneView::IsSelected(Node* node) const { return gizmo_.IsSelected(node); } void SceneView::Select(Serializable* serializable) { selectedSerializable_ = serializable; } void SceneView::OnNodeSelectionChanged() { using namespace EditorSelectionChanged; // TODO: inspector for multi-selection. const auto& selection = GetSelection(); if (selection.Size() == 1) Select(DynamicCast<Serializable>(selection.Front())); else Select((Serializable*)nullptr); } }
Add button for toggling headlight of the scene camera
Editor: Add button for toggling headlight of the scene camera
C++
mit
rokups/Urho3D,rokups/Urho3D,rokups/Urho3D,rokups/Urho3D,rokups/Urho3D,rokups/Urho3D
718d0c7abbe0a279ca713e6c59acc83d722356ce
Testing/mitkExternalToolsTest.cpp
Testing/mitkExternalToolsTest.cpp
/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile: mitkPropertyManager.cpp,v $ Language: C++ Date: $Date$ Version: $Revision: 1.12 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <iostream> #include <string> #include <stdlib.h> // for system() call int mitkExternalToolsTest(int argc, char* argv[]) { std::cout << "Got " << argc << " parameters" << std::endl; if ( argc == 4 ) { // "parse" commandline std::string cmakeBinary( argv[1] ); std::string mitkBinaryDirectory( argv[2] ); std::string sourceDirectory( argv[3] ); // try to configure MITK external project std::cout << "Calling CMake as '" << cmakeBinary << "'" << std::endl; std::cout << "MITK was compiled in '" << mitkBinaryDirectory << "'" << std::endl; std::cout << "Configuring project in '" << sourceDirectory << "'" << std::endl; if (system((std::string("cd ") + mitkBinaryDirectory).c_str()) != 0) { std::cerr << "Couldn't change to MITK build dir. See output above." << std::endl; return EXIT_FAILURE; } std::string commandline(cmakeBinary); commandline += " -DMITK_DIR:PATH="; commandline += """"; commandline += mitkBinaryDirectory; commandline += """"; commandline += " "; commandline += """"; commandline += sourceDirectory; commandline += """"; std::cout << "Calling system() with '" << commandline << "'" << std::endl; int returnCode = system(commandline.c_str()); std::cout << "system() returned " << returnCode << std::endl; if (returnCode != 0) { std::cerr << "Configure FAILED. See output above." << std::endl; return EXIT_FAILURE; } // try to build MITK external project #ifndef WIN32 commandline = "make"; // commented out because mbits configures with Qt4. Have to check this monday. //returnCode = system(commandline.c_str()); if (returnCode != 0) // make should return 0 { std::cout << "make returned " << returnCode << std::endl; std::cerr << "Building the project FAILED. See output above." << std::endl; return EXIT_FAILURE; } #endif // // TODO extend test here to support windows... // return returnCode; } else { std::cout << "Invoke this test with three parameters:" << std::endl; std::cout << " 1. CMake binary including necessary path" << std::endl; std::cout << " 2. MITK binary path (top-level directory)" << std::endl; std::cout << " 3. Source directory containing CMakeLists.txt" << std::endl; return EXIT_FAILURE; } }
/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile: mitkPropertyManager.cpp,v $ Language: C++ Date: $Date$ Version: $Revision: 1.12 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <iostream> #include <string> #include <stdlib.h> // for system() call #ifdef WIN32 #include <direct.h> #else #include <unistd.h> #endif int mitkExternalToolsTest(int argc, char* argv[]) { std::cout << "Got " << argc << " parameters" << std::endl; if ( argc == 4 ) { // "parse" commandline std::string cmakeBinary( argv[1] ); std::string mitkBinaryDirectory( argv[2] ); std::string sourceDirectory( argv[3] ); // try to configure MITK external project std::cout << "Calling CMake as '" << cmakeBinary << "'" << std::endl; std::cout << "MITK was compiled in '" << mitkBinaryDirectory << "'" << std::endl; std::cout << "Configuring project in '" << sourceDirectory << "'" << std::endl; #ifdef WIN32 if ( _chdir(mitkBinaryDirectory) != 0 ) #else if ( chdir(mitkBinaryDirectory) != 0 ) #endif { std::cerr << "Couldn't change to MITK build dir. See output above." << std::endl; return EXIT_FAILURE; } std::string commandline(cmakeBinary); commandline += " -DMITK_DIR:PATH="; commandline += """"; commandline += mitkBinaryDirectory; commandline += """"; commandline += " "; commandline += """"; commandline += sourceDirectory; commandline += """"; std::cout << "Calling system() with '" << commandline << "'" << std::endl; int returnCode = system(commandline.c_str()); std::cout << "system() returned " << returnCode << std::endl; if (returnCode != 0) { std::cerr << "Configure FAILED. See output above." << std::endl; return EXIT_FAILURE; } // try to build MITK external project #ifdef WIN32 #else commandline = "make"; // commented out because mbits configures with Qt4. Have to check this monday. //returnCode = system(commandline.c_str()); if (returnCode != 0) // make should return 0 { std::cout << "make returned " << returnCode << std::endl; std::cerr << "Building the project FAILED. See output above." << std::endl; return EXIT_FAILURE; } #endif // // TODO extend test here to support windows... // return returnCode; } else { std::cout << "Invoke this test with three parameters:" << std::endl; std::cout << " 1. CMake binary including necessary path" << std::endl; std::cout << " 2. MITK binary path (top-level directory)" << std::endl; std::cout << " 3. Source directory containing CMakeLists.txt" << std::endl; return EXIT_FAILURE; } }
FIX (#1513): Provide mechanism to add tools as external MITK developer
FIX (#1513): Provide mechanism to add tools as external MITK developer Changing directory to MITK binary directory using chdir/_chdir now.
C++
bsd-3-clause
NifTK/MITK,iwegner/MITK,nocnokneo/MITK,MITK/MITK,iwegner/MITK,nocnokneo/MITK,iwegner/MITK,MITK/MITK,NifTK/MITK,fmilano/mitk,nocnokneo/MITK,fmilano/mitk,RabadanLab/MITKats,fmilano/mitk,NifTK/MITK,MITK/MITK,danielknorr/MITK,danielknorr/MITK,rfloca/MITK,nocnokneo/MITK,lsanzdiaz/MITK-BiiG,danielknorr/MITK,NifTK/MITK,nocnokneo/MITK,rfloca/MITK,NifTK/MITK,fmilano/mitk,lsanzdiaz/MITK-BiiG,nocnokneo/MITK,lsanzdiaz/MITK-BiiG,rfloca/MITK,rfloca/MITK,nocnokneo/MITK,danielknorr/MITK,RabadanLab/MITKats,NifTK/MITK,rfloca/MITK,rfloca/MITK,danielknorr/MITK,danielknorr/MITK,danielknorr/MITK,RabadanLab/MITKats,lsanzdiaz/MITK-BiiG,lsanzdiaz/MITK-BiiG,RabadanLab/MITKats,lsanzdiaz/MITK-BiiG,RabadanLab/MITKats,MITK/MITK,lsanzdiaz/MITK-BiiG,iwegner/MITK,rfloca/MITK,fmilano/mitk,RabadanLab/MITKats,lsanzdiaz/MITK-BiiG,MITK/MITK,iwegner/MITK,iwegner/MITK,MITK/MITK,fmilano/mitk,fmilano/mitk
dcc5248dc537cf78e8b82c87b0910206ad61dcb5
examples/maxcommonsubseq/testmaxcommonsubseq.cpp
examples/maxcommonsubseq/testmaxcommonsubseq.cpp
/* Copyright (c) 2013 Quanta Research Cambridge, Inc * * 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 <stdio.h> #include <sys/mman.h> #include <stdlib.h> #include <unistd.h> #include <assert.h> #include <semaphore.h> #include <ctime> #include <monkit.h> #include <mp.h> #include "StdDmaIndication.h" #include "MaxcommonsubseqIndicationWrapper.h" #include "MaxcommonsubseqRequestProxy.h" #include "GeneratedTypes.h" #include "DmaConfigProxy.h" sem_t test_sem; sem_t setup_sem; int sw_match_cnt = 0; int hw_match_cnt = 0; unsigned result_len = 0; class MaxcommonsubseqIndication : public MaxcommonsubseqIndicationWrapper { public: MaxcommonsubseqIndication(unsigned int id) : MaxcommonsubseqIndicationWrapper(id){}; virtual void setupAComplete() { fprintf(stderr, "setupAComplete\n"); sem_post(&setup_sem); } virtual void setupBComplete() { fprintf(stderr, "setupBComplete\n"); sem_post(&setup_sem); } virtual void fetchComplete() { fprintf(stderr, "fetchComplete\n"); sem_post(&setup_sem); } virtual void searchResult (int v){ fprintf(stderr, "searchResult = %d\n", v); result_len = v; sem_post(&test_sem); } }; int main(int argc, const char **argv) { MaxcommonsubseqRequestProxy *device = 0; DmaConfigProxy *dma = 0; MaxcommonsubseqIndication *deviceIndication = 0; DmaIndication *dmaIndication = 0; fprintf(stderr, "%s %s\n", __DATE__, __TIME__); device = new MaxcommonsubseqRequestProxy(IfcNames_MaxcommonsubseqRequest); dma = new DmaConfigProxy(IfcNames_DmaConfig); deviceIndication = new MaxcommonsubseqIndication(IfcNames_MaxcommonsubseqIndication); dmaIndication = new DmaIndication(dma, IfcNames_DmaIndication); if(sem_init(&test_sem, 1, 0)){ fprintf(stderr, "failed to init test_sem\n"); return -1; } if(sem_init(&setup_sem, 1, 0)){ fprintf(stderr, "failed to init setup_sem\n"); return -1; } pthread_t tid; fprintf(stderr, "creating exec thread\n"); if(pthread_create(&tid, NULL, portalExec, NULL)){ fprintf(stderr, "error creating exec thread\n"); exit(1); } fprintf(stderr, "simple tests\n"); PortalAlloc *strAAlloc; PortalAlloc *strBAlloc; PortalAlloc *fetchAlloc; unsigned int alloc_len = 128; unsigned int fetch_len = alloc_len * alloc_len; dma->alloc(alloc_len, &strAAlloc); dma->alloc(alloc_len, &strBAlloc); dma->alloc(fetch_len, &fetchAlloc); char *strA = (char *)mmap(0, alloc_len, PROT_READ|PROT_WRITE, MAP_SHARED, strAAlloc->header.fd, 0); char *strB = (char *)mmap(0, alloc_len, PROT_READ|PROT_WRITE, MAP_SHARED, strBAlloc->header.fd, 0); int *fetch = (int *)mmap(0, fetch_len, PROT_READ|PROT_WRITE, MAP_SHARED, fetchAlloc->header.fd, 0); const char *strA_text = " a b c "; const char *strB_text = "..a........b......"; assert(strlen(strA_text) < alloc_len); assert(strlen(strB_text) < alloc_len); strncpy(strA, strA_text, alloc_len); strncpy(strB, strB_text, alloc_len); int strA_len = strlen(strA); int strB_len = strlen(strB); uint16_t swFetch[fetch_len]; for (int i = 0; i < strA_len; i += 1) { strA[i] = i; strB[i] = 255 - i; } start_timer(0); fprintf(stderr, "elapsed time (hw cycles): %zd\n", lap_timer(0)); dma->dCacheFlushInval(strAAlloc, strA); dma->dCacheFlushInval(strBAlloc, strB); dma->dCacheFlushInval(fetchAlloc, fetch); unsigned int ref_strAAlloc = dma->reference(strAAlloc); unsigned int ref_strBAlloc = dma->reference(strBAlloc); unsigned int ref_fetchAlloc = dma->reference(fetchAlloc); device->setupA(ref_strAAlloc, strA_len); sem_wait(&setup_sem); device->setupB(ref_strBAlloc, strB_len); sem_wait(&setup_sem); start_timer(0); device->start(); sem_wait(&test_sem); uint64_t cycles = lap_timer(0); uint64_t beats = dma->show_mem_stats(ChannelType_Read); fprintf(stderr, "hw cycles: %f\n", (float)cycles); assert(result_len < alloc_len * alloc_len); device->fetch(ref_fetchAlloc, result_len); printf("fetch called %d\n", result_len); sem_wait(&setup_sem); printf("fetch finished \n"); memcpy(swFetch, fetch, result_len * sizeof(uint16_t)); for (int i = 0; i < result_len; i += 1) { // if (swFetch[i] != (strA[i] << 8 | strB[i])) printf("mismatch i %d A %02x B %02x R %04x\n", i, strA[i], strB[i], swFetch[i]); } close(strAAlloc->header.fd); close(strBAlloc->header.fd); close(fetchAlloc->header.fd); }
/* Copyright (c) 2013 Quanta Research Cambridge, Inc * * 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 <stdio.h> #include <sys/mman.h> #include <stdlib.h> #include <unistd.h> #include <assert.h> #include <semaphore.h> #include <ctime> #include <monkit.h> #include <mp.h> #include "StdDmaIndication.h" #include "MaxcommonsubseqIndicationWrapper.h" #include "MaxcommonsubseqRequestProxy.h" #include "GeneratedTypes.h" #include "DmaConfigProxy.h" sem_t test_sem; sem_t setup_sem; int sw_match_cnt = 0; int hw_match_cnt = 0; unsigned result_len = 0; class MaxcommonsubseqIndication : public MaxcommonsubseqIndicationWrapper { public: MaxcommonsubseqIndication(unsigned int id) : MaxcommonsubseqIndicationWrapper(id){}; virtual void setupAComplete() { fprintf(stderr, "setupAComplete\n"); sem_post(&setup_sem); } virtual void setupBComplete() { fprintf(stderr, "setupBComplete\n"); sem_post(&setup_sem); } virtual void fetchComplete() { fprintf(stderr, "fetchComplete\n"); sem_post(&setup_sem); } virtual void searchResult (int v){ fprintf(stderr, "searchResult = %d\n", v); result_len = v; sem_post(&test_sem); } }; int main(int argc, const char **argv) { MaxcommonsubseqRequestProxy *device = 0; DmaConfigProxy *dma = 0; MaxcommonsubseqIndication *deviceIndication = 0; DmaIndication *dmaIndication = 0; fprintf(stderr, "%s %s\n", __DATE__, __TIME__); device = new MaxcommonsubseqRequestProxy(IfcNames_MaxcommonsubseqRequest); dma = new DmaConfigProxy(IfcNames_DmaConfig); deviceIndication = new MaxcommonsubseqIndication(IfcNames_MaxcommonsubseqIndication); dmaIndication = new DmaIndication(dma, IfcNames_DmaIndication); if(sem_init(&test_sem, 1, 0)){ fprintf(stderr, "failed to init test_sem\n"); return -1; } if(sem_init(&setup_sem, 1, 0)){ fprintf(stderr, "failed to init setup_sem\n"); return -1; } pthread_t tid; fprintf(stderr, "creating exec thread\n"); if(pthread_create(&tid, NULL, portalExec, NULL)){ fprintf(stderr, "error creating exec thread\n"); exit(1); } fprintf(stderr, "simple tests\n"); PortalAlloc *strAAlloc; PortalAlloc *strBAlloc; PortalAlloc *fetchAlloc; unsigned int alloc_len = 128; unsigned int fetch_len = alloc_len * alloc_len; dma->alloc(alloc_len, &strAAlloc); dma->alloc(alloc_len, &strBAlloc); dma->alloc(fetch_len, &fetchAlloc); char *strA = (char *)mmap(0, alloc_len, PROT_READ|PROT_WRITE, MAP_SHARED, strAAlloc->header.fd, 0); char *strB = (char *)mmap(0, alloc_len, PROT_READ|PROT_WRITE, MAP_SHARED, strBAlloc->header.fd, 0); int *fetch = (int *)mmap(0, fetch_len, PROT_READ|PROT_WRITE, MAP_SHARED, fetchAlloc->header.fd, 0); const char *strA_text = " a b c "; const char *strB_text = "..a........b......"; assert(strlen(strA_text) < alloc_len); assert(strlen(strB_text) < alloc_len); strncpy(strA, strA_text, alloc_len); strncpy(strB, strB_text, alloc_len); int strA_len = strlen(strA); int strB_len = strlen(strB); uint16_t swFetch[fetch_len]; for (int i = 0; i < strA_len; i += 1) { strA[i] = i; strB[i] = 255 - i; } start_timer(0); fprintf(stderr, "elapsed time (hw cycles): %zd\n", lap_timer(0)); dma->dCacheFlushInval(strAAlloc, strA); dma->dCacheFlushInval(strBAlloc, strB); dma->dCacheFlushInval(fetchAlloc, fetch); unsigned int ref_strAAlloc = dma->reference(strAAlloc); unsigned int ref_strBAlloc = dma->reference(strBAlloc); unsigned int ref_fetchAlloc = dma->reference(fetchAlloc); device->setupA(ref_strAAlloc, strA_len); sem_wait(&setup_sem); device->setupB(ref_strBAlloc, strB_len); sem_wait(&setup_sem); start_timer(0); device->start(); sem_wait(&test_sem); uint64_t cycles = lap_timer(0); uint64_t beats = dma->show_mem_stats(ChannelType_Read); fprintf(stderr, "hw cycles: %f\n", (float)cycles); assert(result_len < alloc_len * alloc_len); // device->fetch(ref_fetchAlloc, (result_len+7)& ~7); device->fetch(ref_fetchAlloc, 32); printf("fetch called %d\n", result_len); sem_wait(&setup_sem); printf("fetch finished \n"); memcpy(swFetch, fetch, result_len * sizeof(uint16_t)); for (int i = 0; i < result_len; i += 1) { if (swFetch[i] != (strA[i] << 8 | strB[i])) printf("mismatch i %d A %02x B %02x R %04x\n", i, strA[i], strB[i], swFetch[i]); } close(strAAlloc->header.fd); close(strBAlloc->header.fd); close(fetchAlloc->header.fd); }
put back the checker
put back the checker
C++
mit
8l/connectal,chenm001/connectal,cambridgehackers/connectal,chenm001/connectal,csail-csg/connectal,8l/connectal,cambridgehackers/connectal,chenm001/connectal,cambridgehackers/connectal,hanw/connectal,csail-csg/connectal,hanw/connectal,cambridgehackers/connectal,8l/connectal,8l/connectal,8l/connectal,chenm001/connectal,hanw/connectal,hanw/connectal,csail-csg/connectal,chenm001/connectal,hanw/connectal,csail-csg/connectal,csail-csg/connectal,cambridgehackers/connectal
be57fee12b40394e9524fcf982f8e1a9d1cc1bea
examples/stm32f4_discovery/stm32f4_discovery.hpp
examples/stm32f4_discovery/stm32f4_discovery.hpp
// coding: utf-8 /* Copyright (c) 2013, Roboterclub Aachen e.V. * All Rights Reserved. * * The file is part of the xpcc library and is released under the 3-clause BSD * license. See the file `LICENSE` for the full license governing this code. */ // ---------------------------------------------------------------------------- // // STM32F4DISCOVERY // Discovery kit for STM32F407/417 lines // http://www.st.com/web/en/catalog/tools/FM116/SC959/SS1532/PF252419 // #ifndef XPCC_STM32_F4_DISCOVERY_HPP #define XPCC_STM32_F4_DISCOVERY_HPP #include <xpcc/architecture/platform.hpp> #include <xpcc/driver/inertial/lis3dsh.hpp> using namespace xpcc::stm32; namespace Board { /// STM32F4 running at 168MHz (USB Clock qt 48MHz) generated from the /// external on-board 8MHz crystal typedef SystemClock<Pll<ExternalCrystal<MHz8>, MHz168, MHz48> > systemClock; typedef GpioInputA0 Button; // Blue PushButton typedef GpioOutputA8 ClockOut; typedef GpioOutputC9 SystemClockOut; typedef GpioOutputD13 LedOrange; // User LED 3 typedef GpioOutputD12 LedGreen; // User LED 4 typedef GpioOutputD14 LedRed; // User LED 5 typedef GpioOutputD15 LedBlue; // User LED 6 namespace lis3 { typedef GpioInputE1 Int; // LIS302DL_INT2 typedef GpioOutputE3 Cs; // LIS302DL_CS_I2C/SPI typedef GpioOutputA5 Sck; // SPI1_SCK typedef GpioOutputA7 Mosi; // SPI1_MOSI typedef GpioInputA6 Miso; // SPI1_MISO typedef SpiMaster1 SpiMaster; typedef xpcc::Lis3TransportSpi< SpiMaster, Cs > Transport; } namespace cs43 { typedef GpioOutputA4 Lrck; // I2S3_WS typedef GpioOutputC7 Mclk; // I2S3_MCK typedef GpioOutputC10 Sclk; // I2S3_SCK typedef GpioOutputC12 Sdin; // I2S3_SD typedef GpioOutputD4 Reset; // Audio_RST typedef GpioOutputB6 Scl; // Audio_SCL typedef GpioOutputB9 Sda; // Audio_SDA typedef I2cMaster1 I2cMaster; //typedef I2sMaster3 I2sMaster; } namespace mp45 { typedef GpioOutputB10 Clk; // CLK_IN: I2S2_CK typedef GpioOutputC3 Dout; // PDM_OUT: I2S2_SD //typedef I2sMaster2 I2sMaster; } namespace usb { typedef GpioOutputA11 Dm; // OTG_FS_DM: USB_OTG_FS_DM typedef GpioOutputA12 Dp; // OTG_FS_DP: USB_OTG_FS_DP typedef GpioOutputA10 Id; // OTG_FS_ID: USB_OTG_FS_ID typedef GpioOutputC0 Power; // OTG_FS_PowerSwitchOn typedef GpioInputD5 Overcurrent; // OTG_FS_OverCurrent typedef GpioInputA9 Vbus; // OTG_FS_VBUS //typedef UsbFs Device; } inline void initialize() { systemClock::enable(); xpcc::cortex::SysTickTimer::enable(); LedOrange::setOutput(xpcc::Gpio::Low); LedGreen::setOutput(xpcc::Gpio::Low); LedRed::setOutput(xpcc::Gpio::Low); LedBlue::setOutput(xpcc::Gpio::Low); Button::setInput(); Button::setInputTrigger(Gpio::InputTrigger::RisingEdge); Button::enableExternalInterrupt(); // Button::enableExternalInterruptVector(12); } inline void initializeLis3() { lis3::Cs::setOutput(xpcc::Gpio::High); lis3::Int::setInput(); lis3::Int::setInputTrigger(Gpio::InputTrigger::RisingEdge); lis3::Int::enableExternalInterrupt(); // lis3::Int::enableExternalInterruptVector(12); lis3::Sck::connect(lis3::SpiMaster::Sck); lis3::Mosi::connect(lis3::SpiMaster::Mosi); lis3::Miso::connect(lis3::SpiMaster::Miso); lis3::SpiMaster::initialize<systemClock, MHz10>(); lis3::SpiMaster::setDataMode(lis3::SpiMaster::DataMode::Mode3); } /// not supported yet, due to missing I2S driver inline void initializeCs43() { // cs43::Lrck::connect(cs43::I2sMaster::Ws); // cs43::Mclk::connect(cs43::I2sMaster::Mck); // cs43::Sclk::connect(cs43::I2sMaster::Ck); // cs43::Sdin::connect(cs43::I2sMaster::Sd); // cs43::Reset::setOutput(xpcc::Gpio::High); // cs43::Scl::connect(cs43::I2cMaster::Scl); // cs43::Sda::connect(cs43::I2cMaster::Sda); // cs43::I2cMaster::initialize<systemClock, cs43::I2cMaster::Baudrate::Standard>(); } /// not supported yet, due to missing I2S driver inline void initializeMp45() { // mp45::Clk::connect(mp45::I2sMaster::Ck); // mp45::Dout::connect(mp45::I2sMaster::Sd); } /// not supported yet, due to missing USB driver inline void initializeUsb() { // usb::Dm::connect(usb::Device::Dm); // usb::Dp::connect(usb::Device::Dp); // usb::Id::connect(usb::Device::Id); // usb::Overcurrent::setInput(Gpio::InputType::Floating); // usb::Power::setOutput(Gpio::OutputType::PushPull, Gpio::OutputSpeed::MHz2); // usb::Vbus::setInput(Gpio::InputType::Floating); } } #endif // XPCC_STM32_F4_DISCOVERY_HPP
// coding: utf-8 /* Copyright (c) 2013, Roboterclub Aachen e.V. * All Rights Reserved. * * The file is part of the xpcc library and is released under the 3-clause BSD * license. See the file `LICENSE` for the full license governing this code. */ // ---------------------------------------------------------------------------- // // STM32F4DISCOVERY // Discovery kit for STM32F407/417 lines // http://www.st.com/web/en/catalog/tools/FM116/SC959/SS1532/PF252419 // #ifndef XPCC_STM32_F4_DISCOVERY_HPP #define XPCC_STM32_F4_DISCOVERY_HPP #include <xpcc/architecture/platform.hpp> #include <xpcc/driver/inertial/lis3dsh.hpp> using namespace xpcc::stm32; namespace Board { /// STM32F4 running at 168MHz (USB Clock qt 48MHz) generated from the /// external on-board 8MHz crystal typedef SystemClock<Pll<ExternalCrystal<MHz8>, MHz168, MHz48> > systemClock; typedef GpioInputA0 Button; // Blue PushButton typedef GpioOutputA8 ClockOut; typedef GpioOutputC9 SystemClockOut; typedef GpioOutputD13 LedOrange; // User LED 3 typedef GpioOutputD12 LedGreen; // User LED 4 typedef GpioOutputD14 LedRed; // User LED 5 typedef GpioOutputD15 LedBlue; // User LED 6 namespace lis3 { typedef GpioInputE1 Int; // LIS302DL_INT2 typedef GpioOutputE3 Cs; // LIS302DL_CS_I2C/SPI typedef GpioOutputA5 Sck; // SPI1_SCK typedef GpioOutputA7 Mosi; // SPI1_MOSI typedef GpioInputA6 Miso; // SPI1_MISO typedef SpiMaster1 SpiMaster; typedef xpcc::Lis3TransportSpi< SpiMaster, Cs > Transport; } namespace cs43 { typedef GpioOutputA4 Lrck; // I2S3_WS typedef GpioOutputC7 Mclk; // I2S3_MCK typedef GpioOutputC10 Sclk; // I2S3_SCK typedef GpioOutputC12 Sdin; // I2S3_SD typedef GpioOutputD4 Reset; // Audio_RST typedef GpioB6 Scl; // Audio_SCL typedef GpioB9 Sda; // Audio_SDA typedef I2cMaster1 I2cMaster; //typedef I2sMaster3 I2sMaster; } namespace mp45 { typedef GpioOutputB10 Clk; // CLK_IN: I2S2_CK typedef GpioInputC3 Dout; // PDM_OUT: I2S2_SD //typedef I2sMaster2 I2sMaster; } namespace usb { typedef GpioA11 Dm; // OTG_FS_DM: USB_OTG_FS_DM typedef GpioA12 Dp; // OTG_FS_DP: USB_OTG_FS_DP typedef GpioA10 Id; // OTG_FS_ID: USB_OTG_FS_ID typedef GpioOutputC0 Power; // OTG_FS_PowerSwitchOn typedef GpioInputD5 Overcurrent; // OTG_FS_OverCurrent typedef GpioInputA9 Vbus; // OTG_FS_VBUS //typedef UsbFs Device; } inline void initialize() { systemClock::enable(); xpcc::cortex::SysTickTimer::enable(); LedOrange::setOutput(xpcc::Gpio::Low); LedGreen::setOutput(xpcc::Gpio::Low); LedRed::setOutput(xpcc::Gpio::Low); LedBlue::setOutput(xpcc::Gpio::Low); Button::setInput(); Button::setInputTrigger(Gpio::InputTrigger::RisingEdge); Button::enableExternalInterrupt(); // Button::enableExternalInterruptVector(12); } inline void initializeLis3() { lis3::Int::setInput(); lis3::Int::setInputTrigger(Gpio::InputTrigger::RisingEdge); lis3::Int::enableExternalInterrupt(); // lis3::Int::enableExternalInterruptVector(12); lis3::Cs::setOutput(xpcc::Gpio::High); lis3::Sck::connect(lis3::SpiMaster::Sck); lis3::Mosi::connect(lis3::SpiMaster::Mosi); lis3::Miso::connect(lis3::SpiMaster::Miso); lis3::SpiMaster::initialize<systemClock, MHz10>(); lis3::SpiMaster::setDataMode(lis3::SpiMaster::DataMode::Mode3); } /// not supported yet, due to missing I2S driver inline void initializeCs43() { // cs43::Lrck::connect(cs43::I2sMaster::Ws); // cs43::Mclk::connect(cs43::I2sMaster::Mck); // cs43::Sclk::connect(cs43::I2sMaster::Ck); // cs43::Sdin::connect(cs43::I2sMaster::Sd); cs43::Reset::setOutput(xpcc::Gpio::High); cs43::Scl::connect(cs43::I2cMaster::Scl); cs43::Sda::connect(cs43::I2cMaster::Sda); cs43::I2cMaster::initialize<systemClock, cs43::I2cMaster::Baudrate::Standard>(); } /// not supported yet, due to missing I2S driver inline void initializeMp45() { // mp45::Clk::connect(mp45::I2sMaster::Ck); // mp45::Dout::connect(mp45::I2sMaster::Sd); } /// not supported yet, due to missing USB driver inline void initializeUsb() { // usb::Dm::connect(usb::Device::Dm); // usb::Dp::connect(usb::Device::Dp); // usb::Id::connect(usb::Device::Id); usb::Power::setOutput(Gpio::OutputType::PushPull, Gpio::OutputSpeed::MHz2); usb::Overcurrent::setInput(Gpio::InputType::Floating); usb::Vbus::setInput(Gpio::InputType::Floating); } } #endif // XPCC_STM32_F4_DISCOVERY_HPP
Improve STM32F4 Discovery board header.
Examples: Improve STM32F4 Discovery board header.
C++
bsd-3-clause
chrism333/xpcc,chrism333/xpcc,dergraaf/xpcc,dergraaf/xpcc,chrism333/xpcc,chrism333/xpcc,dergraaf/xpcc,dergraaf/xpcc
fb71dd1fc8d83f7f908de56b9670de8f68426a06
agi/migrate.cpp
agi/migrate.cpp
#include "ngraph.h" #include <PCU.h> #include <unordered_set> #include <vector> namespace agi { typedef std::unordered_set<GraphVertex*> VertexVector; //TODO: Make a vector by using a "tag" on the edges to detect added or not typedef std::unordered_set<GraphEdge*> EdgeVector; void Ngraph::updateGhostOwners(Migration* plan) { PCU_Comm_Begin(); Migration::iterator itr; for (itr = plan->begin();itr!=plan->end();itr++) { GraphVertex* v = itr->first; part_t toSend = itr->second; GraphIterator* gitr = adjacent(v); GraphVertex* other; while ((other=iterate(gitr))) { part_t own = owner(other); if (own!=PCU_Comm_Self()) { gid_t gid = globalID(v); PCU_COMM_PACK(own,gid); PCU_COMM_PACK(own,toSend); } } } PCU_Comm_Send(); while (PCU_Comm_Receive()) { gid_t gid; part_t own; PCU_COMM_UNPACK(gid); PCU_COMM_UNPACK(own); lid_t lid = vtx_mapping[gid]; assert(lid>=num_local_verts); owners[lid-num_local_verts]=own; } } /* Finds the vertices and edges that need to be communicated Also stores the local vertices and edges that will be owned on this part after migration */ void getAffected(Ngraph* g, Migration* plan, VertexVector& verts, EdgeVector* edges) { verts.reserve(plan->size()); Migration::iterator itr; for (itr = plan->begin();itr!=plan->end();itr++) { GraphVertex* v = itr->first; part_t toSend = itr->second; if (toSend!=PCU_Comm_Self()) { verts.insert(v); } } //For each edge type for (etype t = 0;t<g->numEdgeTypes();t++) { //edges[t].reserve(verts.size()); VertexVector::iterator itr; //loop through the vertices being sent for (itr = verts.begin();itr!=verts.end();itr++) { GraphIterator* gitr =g->adjacent(*itr); GraphEdge* e; GraphEdge* old=NULL; GraphVertex* v; while ((v = g->iterate(gitr))) { e=g->edge(gitr); if (old==NULL||e!=old) edges[t].insert(e); } } } } void addVertices(Ngraph* g, std::vector<gid_t>& ownedVerts, VertexVector& verts, std::vector<wgt_t>& weights, std::vector<part_t>& originalOwners) { VertexIterator* vitr = g->begin(); GraphVertex* v; while ((v = g->iterate(vitr))) { if (verts.find(v)==verts.end()) { ownedVerts.push_back(g->globalID(v)); weights.push_back(g->weight(v)); originalOwners.push_back(g->originalOwner(v)); } } } void addEdges(Ngraph* g, Migration* plan, std::vector<gid_t>& ownedEdges, std::vector<wgt_t>& edgeWeights, std::vector<lid_t>& degrees,std::vector<gid_t>& pins, std::unordered_map<gid_t,part_t>& ghost_owners, std::unordered_set<gid_t>& addedEdges) { VertexIterator* itr = g->begin(); GraphVertex* v; while ((v = g->iterate(itr))) { if (plan->find(v)!=plan->end()) continue; GraphVertex* other; GraphIterator* gitr = g->adjacent(v); GraphEdge* e,*old = NULL; while ((other = g->iterate(gitr))) { e=g->edge(gitr); if (addedEdges.find(g->globalID(e))!=addedEdges.end()) continue; if (old==NULL||e!=old) { if (old&&g->isHyper()) addedEdges.insert(g->globalID(old)); if (g->isHyper()) { ownedEdges.push_back(g->globalID(e)); edgeWeights.push_back(g->weight(e)); degrees.push_back(g->degree(e)); } else { ownedEdges.push_back(g->localID(e)); edgeWeights.push_back(g->weight(e)); pins.push_back(g->globalID(v)); degrees.push_back(2); } } old=e; gid_t other_gid = g->globalID(other); pins.push_back(other_gid); part_t owner = g->owner(other); if (plan->find(other)!=plan->end()) owner = plan->find(other)->second; if (owner!=PCU_Comm_Self()) ghost_owners[other_gid] = owner; } addedEdges.insert(g->globalID(old)); } } void Ngraph::sendVertex(GraphVertex* vtx, part_t toSend) { gid_t gid = globalID(vtx); wgt_t w = weight(vtx); part_t old_owner = originalOwner(vtx); PCU_COMM_PACK(toSend,gid); PCU_COMM_PACK(toSend,w); PCU_COMM_PACK(toSend,old_owner); } void Ngraph::recvVertex(std::vector<gid_t>& recv, std::vector<wgt_t>& wgts, std::vector<part_t>& old_owners) { gid_t gid; PCU_COMM_UNPACK(gid); wgt_t w; PCU_COMM_UNPACK(w); part_t old_owner; PCU_COMM_UNPACK(old_owner); recv.push_back(gid); wgts.push_back(w); old_owners.push_back(old_owner); } void Ngraph::migrate(Migration* plan) { updateGhostOwners(plan); VertexVector affectedVerts; EdgeVector* affectedEdges = new EdgeVector[num_types]; std::vector<gid_t> ownedVerts; std::vector<wgt_t> vertWeights; std::vector<part_t> old_owners; ownedVerts.reserve(num_local_verts); vertWeights.reserve(num_local_verts); std::vector<gid_t> ownedEdges; std::vector<wgt_t> edgeWeights; ownedEdges.reserve(num_local_edges[0]); edgeWeights.reserve(num_local_edges[0]); std::vector<lid_t> degrees; std::vector<gid_t> pins; std::unordered_map<gid_t,part_t> ghost_owners; getAffected(this,plan,affectedVerts,affectedEdges); addVertices(this,ownedVerts,affectedVerts,vertWeights,old_owners); std::unordered_set<gid_t> addedEdges; addEdges(this,plan,ownedEdges,edgeWeights,degrees,pins,ghost_owners, addedEdges); Migration::iterator itr; PCU_Comm_Begin(); //Send vertices for (itr = plan->begin();itr!=plan->end();itr++) { sendVertex(itr->first,itr->second); } PCU_Comm_Send(); //Recieve vertices while (PCU_Comm_Receive()) { recvVertex(ownedVerts,vertWeights,old_owners); } for (etype t = 0;t < num_types;t++) { PCU_Comm_Begin(); EdgeVector::iterator eitr; for (eitr = affectedEdges[t].begin();eitr!=affectedEdges[t].end(); eitr++) { GraphEdge* e = *eitr; gid_t* pin; part_t* pin_owners; lid_t deg=0; gid_t id; wgt_t eweight = weight(e); std::unordered_set<part_t> residence; if (isHyperGraph) { id = globalID(e); pin = new gid_t[degree(e)]; pin_owners = new part_t[degree(e)]; agi::PinIterator* pitr = this->pins(e); agi::GraphVertex* vtx; for (lid_t i=0;i<degree(e);i++) { vtx = iterate(pitr); part_t o = owner(vtx); if (plan->find(vtx)!=plan->end()) o= plan->find(vtx)->second; pin_owners[deg]=o; pin[deg++] = globalID(vtx); residence.insert(o); } g->destroy(pitr); } else { id = localID(e); pin = new gid_t[2]; pin_owners = new part_t[2]; GraphVertex* source = u(e); pin_owners[deg] = owner(source); pin[deg++] = globalID(source); GraphVertex* dest = v(e); part_t o = owner(dest); if (plan->find(dest)!=plan->end()) o= plan->find(dest)->second; pin_owners[deg] = o; pin[deg++] = globalID(dest); Migration::iterator mitr = plan->find(source); pin_owners[0] = mitr->second; assert(mitr!=plan->end()); residence.insert(mitr->second); } std::unordered_set<part_t>::iterator sitr; for (sitr=residence.begin();sitr!=residence.end();sitr++) { PCU_COMM_PACK(*sitr,id); PCU_COMM_PACK(*sitr,eweight); PCU_COMM_PACK(*sitr,deg); PCU_Comm_Pack(*sitr,pin,deg*sizeof(gid_t)); PCU_Comm_Pack(*sitr,pin_owners,deg*sizeof(part_t)); } delete [] pin; delete [] pin_owners; } PCU_Comm_Send(); while (PCU_Comm_Receive()) { gid_t id; wgt_t eweight; lid_t deg; PCU_COMM_UNPACK(id); PCU_COMM_UNPACK(eweight); PCU_COMM_UNPACK(deg); gid_t* pin = new gid_t[deg]; part_t* pin_owners = new part_t[deg]; PCU_Comm_Unpack(pin,deg*sizeof(gid_t)); PCU_Comm_Unpack(pin_owners,deg*sizeof(part_t)); if (isHyperGraph) { if (addedEdges.find(id)!=addedEdges.end()) continue; } addedEdges.insert(id); edge_mapping[t][id]=0; ownedEdges.push_back(id); edgeWeights.push_back(eweight); degrees.push_back(deg); for (lid_t i=0;i<deg;i++) { pins.push_back(pin[i]); if (pin_owners[i]!=PCU_Comm_Self()) ghost_owners[pin[i]]=pin_owners[i]; } delete [] pin; delete [] pin_owners; } } constructGraph(isHyperGraph,ownedVerts,vertWeights,ownedEdges,degrees, pins,ghost_owners); setOriginalOwners(old_owners); setEdgeWeights(edgeWeights,0); delete [] affectedEdges; delete plan; } }
#include "ngraph.h" #include <PCU.h> #include <unordered_set> #include <vector> namespace agi { typedef std::unordered_set<GraphVertex*> VertexVector; //TODO: Make a vector by using a "tag" on the edges to detect added or not typedef std::unordered_set<GraphEdge*> EdgeVector; void Ngraph::updateGhostOwners(Migration* plan) { PCU_Comm_Begin(); Migration::iterator itr; for (itr = plan->begin();itr!=plan->end();itr++) { GraphVertex* v = itr->first; part_t toSend = itr->second; GraphIterator* gitr = adjacent(v); GraphVertex* other; while ((other=iterate(gitr))) { part_t own = owner(other); if (own!=PCU_Comm_Self()) { gid_t gid = globalID(v); PCU_COMM_PACK(own,gid); PCU_COMM_PACK(own,toSend); } } } PCU_Comm_Send(); while (PCU_Comm_Receive()) { gid_t gid; part_t own; PCU_COMM_UNPACK(gid); PCU_COMM_UNPACK(own); lid_t lid = vtx_mapping[gid]; assert(lid>=num_local_verts); owners[lid-num_local_verts]=own; } } /* Finds the vertices and edges that need to be communicated Also stores the local vertices and edges that will be owned on this part after migration */ void getAffected(Ngraph* g, Migration* plan, VertexVector& verts, EdgeVector* edges) { verts.reserve(plan->size()); Migration::iterator itr; for (itr = plan->begin();itr!=plan->end();itr++) { GraphVertex* v = itr->first; part_t toSend = itr->second; if (toSend!=PCU_Comm_Self()) { verts.insert(v); } } //For each edge type for (etype t = 0;t<g->numEdgeTypes();t++) { //edges[t].reserve(verts.size()); VertexVector::iterator itr; //loop through the vertices being sent for (itr = verts.begin();itr!=verts.end();itr++) { GraphIterator* gitr =g->adjacent(*itr); GraphEdge* e; GraphEdge* old=NULL; GraphVertex* v; while ((v = g->iterate(gitr))) { e=g->edge(gitr); if (old==NULL||e!=old) edges[t].insert(e); } } } } void addVertices(Ngraph* g, std::vector<gid_t>& ownedVerts, VertexVector& verts, std::vector<wgt_t>& weights, std::vector<part_t>& originalOwners) { VertexIterator* vitr = g->begin(); GraphVertex* v; while ((v = g->iterate(vitr))) { if (verts.find(v)==verts.end()) { ownedVerts.push_back(g->globalID(v)); weights.push_back(g->weight(v)); originalOwners.push_back(g->originalOwner(v)); } } } void addEdges(Ngraph* g, Migration* plan, std::vector<gid_t>& ownedEdges, std::vector<wgt_t>& edgeWeights, std::vector<lid_t>& degrees,std::vector<gid_t>& pins, std::unordered_map<gid_t,part_t>& ghost_owners, std::unordered_set<gid_t>& addedEdges) { VertexIterator* itr = g->begin(); GraphVertex* v; while ((v = g->iterate(itr))) { if (plan->find(v)!=plan->end()) continue; GraphVertex* other; GraphIterator* gitr = g->adjacent(v); GraphEdge* e,*old = NULL; while ((other = g->iterate(gitr))) { e=g->edge(gitr); if (addedEdges.find(g->globalID(e))!=addedEdges.end()) continue; if (old==NULL||e!=old) { if (old&&g->isHyper()) addedEdges.insert(g->globalID(old)); if (g->isHyper()) { ownedEdges.push_back(g->globalID(e)); edgeWeights.push_back(g->weight(e)); degrees.push_back(g->degree(e)); } else { ownedEdges.push_back(g->localID(e)); edgeWeights.push_back(g->weight(e)); pins.push_back(g->globalID(v)); degrees.push_back(2); } } old=e; gid_t other_gid = g->globalID(other); pins.push_back(other_gid); part_t owner = g->owner(other); if (plan->find(other)!=plan->end()) owner = plan->find(other)->second; if (owner!=PCU_Comm_Self()) ghost_owners[other_gid] = owner; } addedEdges.insert(g->globalID(old)); } } void Ngraph::sendVertex(GraphVertex* vtx, part_t toSend) { gid_t gid = globalID(vtx); wgt_t w = weight(vtx); part_t old_owner = originalOwner(vtx); PCU_COMM_PACK(toSend,gid); PCU_COMM_PACK(toSend,w); PCU_COMM_PACK(toSend,old_owner); } void Ngraph::recvVertex(std::vector<gid_t>& recv, std::vector<wgt_t>& wgts, std::vector<part_t>& old_owners) { gid_t gid; PCU_COMM_UNPACK(gid); wgt_t w; PCU_COMM_UNPACK(w); part_t old_owner; PCU_COMM_UNPACK(old_owner); recv.push_back(gid); wgts.push_back(w); old_owners.push_back(old_owner); } void Ngraph::migrate(Migration* plan) { updateGhostOwners(plan); VertexVector affectedVerts; EdgeVector* affectedEdges = new EdgeVector[num_types]; std::vector<gid_t> ownedVerts; std::vector<wgt_t> vertWeights; std::vector<part_t> old_owners; ownedVerts.reserve(num_local_verts); vertWeights.reserve(num_local_verts); std::vector<gid_t> ownedEdges; std::vector<wgt_t> edgeWeights; ownedEdges.reserve(num_local_edges[0]); edgeWeights.reserve(num_local_edges[0]); std::vector<lid_t> degrees; std::vector<gid_t> pins; std::unordered_map<gid_t,part_t> ghost_owners; getAffected(this,plan,affectedVerts,affectedEdges); addVertices(this,ownedVerts,affectedVerts,vertWeights,old_owners); std::unordered_set<gid_t> addedEdges; addEdges(this,plan,ownedEdges,edgeWeights,degrees,pins,ghost_owners, addedEdges); Migration::iterator itr; PCU_Comm_Begin(); //Send vertices for (itr = plan->begin();itr!=plan->end();itr++) { sendVertex(itr->first,itr->second); } PCU_Comm_Send(); //Recieve vertices while (PCU_Comm_Receive()) { recvVertex(ownedVerts,vertWeights,old_owners); } for (etype t = 0;t < num_types;t++) { PCU_Comm_Begin(); EdgeVector::iterator eitr; for (eitr = affectedEdges[t].begin();eitr!=affectedEdges[t].end(); eitr++) { GraphEdge* e = *eitr; gid_t* pin; part_t* pin_owners; lid_t deg=0; gid_t id; wgt_t eweight = weight(e); std::unordered_set<part_t> residence; if (isHyperGraph) { id = globalID(e); pin = new gid_t[degree(e)]; pin_owners = new part_t[degree(e)]; agi::PinIterator* pitr = this->pins(e); agi::GraphVertex* vtx; for (lid_t i=0;i<degree(e);i++) { vtx = iterate(pitr); part_t o = owner(vtx); if (plan->find(vtx)!=plan->end()) o= plan->find(vtx)->second; pin_owners[deg]=o; pin[deg++] = globalID(vtx); residence.insert(o); } destroy(pitr); } else { id = localID(e); pin = new gid_t[2]; pin_owners = new part_t[2]; GraphVertex* source = u(e); pin_owners[deg] = owner(source); pin[deg++] = globalID(source); GraphVertex* dest = v(e); part_t o = owner(dest); if (plan->find(dest)!=plan->end()) o= plan->find(dest)->second; pin_owners[deg] = o; pin[deg++] = globalID(dest); Migration::iterator mitr = plan->find(source); pin_owners[0] = mitr->second; assert(mitr!=plan->end()); residence.insert(mitr->second); } std::unordered_set<part_t>::iterator sitr; for (sitr=residence.begin();sitr!=residence.end();sitr++) { PCU_COMM_PACK(*sitr,id); PCU_COMM_PACK(*sitr,eweight); PCU_COMM_PACK(*sitr,deg); PCU_Comm_Pack(*sitr,pin,deg*sizeof(gid_t)); PCU_Comm_Pack(*sitr,pin_owners,deg*sizeof(part_t)); } delete [] pin; delete [] pin_owners; } PCU_Comm_Send(); while (PCU_Comm_Receive()) { gid_t id; wgt_t eweight; lid_t deg; PCU_COMM_UNPACK(id); PCU_COMM_UNPACK(eweight); PCU_COMM_UNPACK(deg); gid_t* pin = new gid_t[deg]; part_t* pin_owners = new part_t[deg]; PCU_Comm_Unpack(pin,deg*sizeof(gid_t)); PCU_Comm_Unpack(pin_owners,deg*sizeof(part_t)); if (isHyperGraph) { if (addedEdges.find(id)!=addedEdges.end()) continue; } addedEdges.insert(id); edge_mapping[t][id]=0; ownedEdges.push_back(id); edgeWeights.push_back(eweight); degrees.push_back(deg); for (lid_t i=0;i<deg;i++) { pins.push_back(pin[i]); if (pin_owners[i]!=PCU_Comm_Self()) ghost_owners[pin[i]]=pin_owners[i]; } delete [] pin; delete [] pin_owners; } } constructGraph(isHyperGraph,ownedVerts,vertWeights,ownedEdges,degrees, pins,ghost_owners); setOriginalOwners(old_owners); setEdgeWeights(edgeWeights,0); delete [] affectedEdges; delete plan; } }
Fix a small compile error
Fix a small compile error
C++
bsd-3-clause
SCOREC/EnGPar,SCOREC/EnGPar,SCOREC/EnGPar
cea3759383af0114544bb29803d86bd064924bff
modules/drivers/velodyne/parser/velodyne128_parser.cc
modules/drivers/velodyne/parser/velodyne128_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/drivers/velodyne/parser/velodyne_parser.h" namespace apollo { namespace drivers { namespace velodyne { Velodyne128Parser::Velodyne128Parser(const Config& config) : VelodyneParser(config), previous_packet_stamp_(0), gps_base_usec_(0) { inner_time_ = &velodyne::INNER_TIME_128; need_two_pt_correction_ = false; } void Velodyne128Parser::GeneratePointcloud( const std::shared_ptr<VelodyneScan>& scan_msg, std::shared_ptr<PointCloud> out_msg) { // allocate a point cloud with same time and frame ID as raw data out_msg->mutable_header()->set_frame_id(scan_msg->header().frame_id()); out_msg->mutable_header()->set_timestamp_sec( cybertron::Time().Now().ToSecond()); out_msg->set_height(1); // us gps_base_usec_ = scan_msg->basetime(); for (int i = 0; i < scan_msg->firing_pkts_size(); ++i) { Unpack(scan_msg->firing_pkts(i), out_msg); last_time_stamp_ = out_msg->measurement_time(); } size_t size = out_msg->point_size(); if (size == 0) { // we discard this pointcloud if empty AERROR << "All points is NAN!Please check velodyne:" << config_.model(); return; } else { uint64_t timestamp = out_msg->point(size - 1).timestamp(); out_msg->set_measurement_time(timestamp / 1e9); out_msg->mutable_header()->set_lidar_timestamp(timestamp); } out_msg->set_width(out_msg->point_size()); } uint64_t Velodyne128Parser::GetTimestamp(double base_time, float time_offset, uint16_t block_id) { (void)block_id; double t = base_time - time_offset; uint64_t timestamp = GetGpsStamp(t, &previous_packet_stamp_, &gps_base_usec_); return timestamp; } // TODO(dengchengliang): No manual about order for lidar128 by now. void Velodyne128Parser::Order(std::shared_ptr<PointCloud> cloud) { (void)cloud; } void Velodyne128Parser::Unpack(const VelodynePacket& pkt, std::shared_ptr<PointCloud> pc) { float azimuth_diff, azimuth_corrected_f; float last_azimuth_diff = 0; uint16_t azimuth, azimuth_next, azimuth_corrected; // float x_coord, y_coord, z_coord; // const raw_packet_t *raw = (const raw_packet_t *)&pkt.data[0]; const RawPacket* raw = (const RawPacket*)pkt.data().c_str(); double basetime = raw->gps_timestamp; for (int block = 0; block < BLOCKS_PER_PACKET; block++) { // Calculate difference between current and next block's azimuth angle. if (block == 0) { azimuth = raw->blocks[block].rotation; } else { azimuth = azimuth_next; } if (block < (BLOCKS_PER_PACKET - 1)) { azimuth_next = raw->blocks[block + 1].rotation; azimuth_diff = static_cast<float>((36000 + azimuth_next - azimuth) % 36000); last_azimuth_diff = azimuth_diff; } else { azimuth_diff = last_azimuth_diff; } /*condition added to avoid calculating points which are not in the interesting defined area (min_angle < area < max_angle)*/ for (int j = 0, k = 0; j < SCANS_PER_BLOCK; j++, k += RAW_SCAN_SIZE) { uint8_t group = block % 4; uint8_t chan_id = j + group * 32; uint8_t firing_order = chan_id / 8; firing_order = 0; LaserCorrection& corrections = calibration_.laser_corrections_[chan_id]; // distance extraction // union two_bytes tmp; union RawDistance raw_distance; raw_distance.bytes[0] = raw->blocks[block].data[k]; raw_distance.bytes[1] = raw->blocks[block].data[k + 1]; float real_distance = raw_distance.raw_distance * VSL128_DISTANCE_RESOLUTION; float distance = real_distance + corrections.dist_correction; uint64_t timestamp = GetTimestamp(basetime, (*inner_time_)[block][j], block); if (!is_scan_valid(azimuth, distance)) { // todo orgnized if (config_.organized()) { apollo::drivers::PointXYZIT* point_new = pc->add_point(); point_new->set_x(nan); point_new->set_y(nan); point_new->set_z(nan); point_new->set_timestamp(timestamp); point_new->set_intensity(0); } continue; } // if (pointInRange(distance)) { float intensity = static_cast<float>(raw->blocks[block].data[k + 2]); /** correct for the laser rotation as a function of timing during the * firings **/ azimuth_corrected_f = azimuth + (azimuth_diff * (firing_order * CHANNEL_TDURATION) / SEQ_TDURATION); azimuth_corrected = (static_cast<uint16_t>(round(azimuth_corrected_f))) % 36000; // add new point PointXYZIT* point_new = pc->add_point(); // compute time , time offset is zero point_new->set_timestamp(timestamp); ComputeCoords(real_distance, corrections, azimuth_corrected, point_new); intensity = IntensityCompensate(corrections, raw_distance.raw_distance, intensity); point_new->set_intensity(intensity); } // } } } int Velodyne128Parser::IntensityCompensate(const LaserCorrection& corrections, const uint16_t raw_distance, int intensity) { float focal_offset = 256 * (1 - corrections.focal_distance / 13100) * (1 - corrections.focal_distance / 13100); float focal_slope = corrections.focal_slope; intensity += focal_slope * (abs(focal_offset - 256 * (1 - static_cast<float>(raw_distance) / 65535) * (1 - static_cast<float>(raw_distance) / 65535))); if (intensity < corrections.min_intensity) { intensity = corrections.min_intensity; } if (intensity > corrections.max_intensity) { intensity = corrections.max_intensity; } return intensity; } } // namespace velodyne } // namespace drivers } // 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/drivers/velodyne/parser/velodyne_parser.h" namespace apollo { namespace drivers { namespace velodyne { Velodyne128Parser::Velodyne128Parser(const Config& config) : VelodyneParser(config), previous_packet_stamp_(0), gps_base_usec_(0) { inner_time_ = &velodyne::INNER_TIME_128; need_two_pt_correction_ = false; } void Velodyne128Parser::GeneratePointcloud( const std::shared_ptr<VelodyneScan>& scan_msg, std::shared_ptr<PointCloud> out_msg) { // allocate a point cloud with same time and frame ID as raw data out_msg->mutable_header()->set_frame_id(scan_msg->header().frame_id()); out_msg->mutable_header()->set_timestamp_sec( cybertron::Time().Now().ToSecond()); out_msg->set_height(1); // us gps_base_usec_ = scan_msg->basetime(); for (int i = 0; i < scan_msg->firing_pkts_size(); ++i) { Unpack(scan_msg->firing_pkts(i), out_msg); last_time_stamp_ = out_msg->measurement_time(); } size_t size = out_msg->point_size(); if (size == 0) { // we discard this pointcloud if empty AERROR << "All points is NAN!Please check velodyne:" << config_.model(); return; } else { uint64_t timestamp = out_msg->point(size - 1).timestamp(); out_msg->set_measurement_time(timestamp / 1e9); out_msg->mutable_header()->set_lidar_timestamp(timestamp); } out_msg->set_width(out_msg->point_size()); } uint64_t Velodyne128Parser::GetTimestamp(double base_time, float time_offset, uint16_t block_id) { (void)block_id; double t = base_time + time_offset; uint64_t timestamp = GetGpsStamp(t, &previous_packet_stamp_, &gps_base_usec_); return timestamp; } // TODO(dengchengliang): No manual about order for lidar128 by now. void Velodyne128Parser::Order(std::shared_ptr<PointCloud> cloud) { (void)cloud; } void Velodyne128Parser::Unpack(const VelodynePacket& pkt, std::shared_ptr<PointCloud> pc) { float azimuth_diff, azimuth_corrected_f; float last_azimuth_diff = 0; uint16_t azimuth, azimuth_next, azimuth_corrected; // float x_coord, y_coord, z_coord; // const raw_packet_t *raw = (const raw_packet_t *)&pkt.data[0]; const RawPacket* raw = (const RawPacket*)pkt.data().c_str(); double basetime = raw->gps_timestamp; for (int block = 0; block < BLOCKS_PER_PACKET; block++) { // Calculate difference between current and next block's azimuth angle. if (block == 0) { azimuth = raw->blocks[block].rotation; } else { azimuth = azimuth_next; } if (block < (BLOCKS_PER_PACKET - 1)) { azimuth_next = raw->blocks[block + 1].rotation; azimuth_diff = static_cast<float>((36000 + azimuth_next - azimuth) % 36000); last_azimuth_diff = azimuth_diff; } else { azimuth_diff = last_azimuth_diff; } /*condition added to avoid calculating points which are not in the interesting defined area (min_angle < area < max_angle)*/ for (int j = 0, k = 0; j < SCANS_PER_BLOCK; j++, k += RAW_SCAN_SIZE) { uint8_t group = block % 4; uint8_t chan_id = j + group * 32; uint8_t firing_order = chan_id / 8; firing_order = 0; LaserCorrection& corrections = calibration_.laser_corrections_[chan_id]; // distance extraction // union two_bytes tmp; union RawDistance raw_distance; raw_distance.bytes[0] = raw->blocks[block].data[k]; raw_distance.bytes[1] = raw->blocks[block].data[k + 1]; float real_distance = raw_distance.raw_distance * VSL128_DISTANCE_RESOLUTION; float distance = real_distance + corrections.dist_correction; uint64_t timestamp = GetTimestamp(basetime, (*inner_time_)[block][j], block); if (!is_scan_valid(azimuth, distance)) { // todo orgnized if (config_.organized()) { apollo::drivers::PointXYZIT* point_new = pc->add_point(); point_new->set_x(nan); point_new->set_y(nan); point_new->set_z(nan); point_new->set_timestamp(timestamp); point_new->set_intensity(0); } continue; } // if (pointInRange(distance)) { float intensity = static_cast<float>(raw->blocks[block].data[k + 2]); /** correct for the laser rotation as a function of timing during the * firings **/ azimuth_corrected_f = azimuth + (azimuth_diff * (firing_order * CHANNEL_TDURATION) / SEQ_TDURATION); azimuth_corrected = (static_cast<uint16_t>(round(azimuth_corrected_f))) % 36000; // add new point PointXYZIT* point_new = pc->add_point(); // compute time , time offset is zero point_new->set_timestamp(timestamp); ComputeCoords(real_distance, corrections, azimuth_corrected, point_new); intensity = IntensityCompensate(corrections, raw_distance.raw_distance, intensity); point_new->set_intensity(intensity); } // } } } int Velodyne128Parser::IntensityCompensate(const LaserCorrection& corrections, const uint16_t raw_distance, int intensity) { float focal_offset = 256 * (1 - corrections.focal_distance / 13100) * (1 - corrections.focal_distance / 13100); float focal_slope = corrections.focal_slope; intensity += focal_slope * (abs(focal_offset - 256 * (1 - static_cast<float>(raw_distance) / 65535) * (1 - static_cast<float>(raw_distance) / 65535))); if (intensity < corrections.min_intensity) { intensity = corrections.min_intensity; } if (intensity > corrections.max_intensity) { intensity = corrections.max_intensity; } return intensity; } } // namespace velodyne } // namespace drivers } // namespace apollo
fix velodyne128 timestamp issue (#459)
Drivers: fix velodyne128 timestamp issue (#459)
C++
apache-2.0
wanglei828/apollo,ycool/apollo,ApolloAuto/apollo,xiaoxq/apollo,wanglei828/apollo,ycool/apollo,ApolloAuto/apollo,ApolloAuto/apollo,wanglei828/apollo,ApolloAuto/apollo,ycool/apollo,xiaoxq/apollo,jinghaomiao/apollo,jinghaomiao/apollo,jinghaomiao/apollo,ycool/apollo,xiaoxq/apollo,jinghaomiao/apollo,wanglei828/apollo,jinghaomiao/apollo,ApolloAuto/apollo,xiaoxq/apollo,wanglei828/apollo,xiaoxq/apollo,wanglei828/apollo,ApolloAuto/apollo,xiaoxq/apollo,ycool/apollo,jinghaomiao/apollo,ycool/apollo
30382a11c174b9fae6b5431fce93ca0f5fc75ced
modules/gles2/functional/es2fFboCompletenessTests.cpp
modules/gles2/functional/es2fFboCompletenessTests.cpp
/*------------------------------------------------------------------------- * drawElements Quality Program OpenGL (ES) Module * ----------------------------------------------- * * Copyright 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief Framebuffer completeness tests. *//*--------------------------------------------------------------------*/ #include "es2fFboCompletenessTests.hpp" #include "glsFboCompletenessTests.hpp" #include "gluObjectWrapper.hpp" using namespace glw; using deqp::gls::Range; using namespace deqp::gls::FboUtil; using namespace deqp::gls::FboUtil::config; namespace fboc = deqp::gls::fboc; typedef tcu::TestCase::IterateResult IterateResult; namespace deqp { namespace gles2 { namespace Functional { static const FormatKey s_es2ColorRenderables[] = { GL_RGBA4, GL_RGB5_A1, GL_RGB565, }; // GLES2 does not strictly allow these, but this seems to be a bug in the // specification. For now, let's assume the unsized formats corresponding to // the color-renderable sized formats are allowed. // See https://cvs.khronos.org/bugzilla/show_bug.cgi?id=7333 static const FormatKey s_es2UnsizedColorRenderables[] = { GLS_UNSIZED_FORMATKEY(GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4), GLS_UNSIZED_FORMATKEY(GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1), GLS_UNSIZED_FORMATKEY(GL_RGB, GL_UNSIGNED_SHORT_5_6_5) }; static const FormatKey s_es2DepthRenderables[] = { GL_DEPTH_COMPONENT16, }; static const FormatKey s_es2StencilRenderables[] = { GL_STENCIL_INDEX8, }; static const FormatEntry s_es2Formats[] = { { COLOR_RENDERABLE | TEXTURE_VALID, GLS_ARRAY_RANGE(s_es2UnsizedColorRenderables) }, { REQUIRED_RENDERABLE | COLOR_RENDERABLE | RENDERBUFFER_VALID, GLS_ARRAY_RANGE(s_es2ColorRenderables) }, { REQUIRED_RENDERABLE | DEPTH_RENDERABLE | RENDERBUFFER_VALID, GLS_ARRAY_RANGE(s_es2DepthRenderables) }, { REQUIRED_RENDERABLE | STENCIL_RENDERABLE | RENDERBUFFER_VALID, GLS_ARRAY_RANGE(s_es2StencilRenderables) }, }; // We have here only the extensions that are redundant in vanilla GLES3. Those // that are applicable both to GLES2 and GLES3 are in glsFboCompletenessTests.cpp. // GL_OES_texture_float static const FormatKey s_oesTextureFloatFormats[] = { GLS_UNSIZED_FORMATKEY(GL_RGBA, GL_FLOAT), GLS_UNSIZED_FORMATKEY(GL_RGB, GL_FLOAT), }; // GL_OES_texture_half_float static const FormatKey s_oesTextureHalfFloatFormats[] = { GLS_UNSIZED_FORMATKEY(GL_RGBA, GL_HALF_FLOAT_OES), GLS_UNSIZED_FORMATKEY(GL_RGB, GL_HALF_FLOAT_OES), }; // GL_EXT_sRGB_write_control static const FormatKey s_extSrgbWriteControlFormats[] = { GL_SRGB8_ALPHA8 }; // DEQP_gles3_core_no_extension_features static const FormatKey s_es3NoExtRboFormats[] = { GL_RGB10_A2, }; static const FormatKey s_es3NoExtTextureFormats[] = { GL_R16F, GL_RG16F, GL_RGB16F, GL_RGBA16F, GL_R11F_G11F_B10F, }; static const FormatKey s_es3NoExtTextureColorRenderableFormats[] = { GL_R8, GL_RG8, }; // with ES3 core and GL_EXT_color_buffer_float static const FormatKey s_es3NoExtExtColorBufferFloatFormats[] = { // \note Only the GLES2+exts subset of formats GL_R11F_G11F_B10F, GL_RGBA16F, GL_RG16F, GL_R16F, }; // with ES3 core with OES_texture_stencil8 static const FormatKey s_es3NoExtOesTextureStencil8Formats[] = { GL_STENCIL_INDEX8, }; static const FormatExtEntry s_es2ExtFormats[] = { // The extension does not specify these to be color-renderable. { "GL_OES_texture_float", (deUint32)TEXTURE_VALID, GLS_ARRAY_RANGE(s_oesTextureFloatFormats) }, { "GL_OES_texture_half_float", (deUint32)TEXTURE_VALID, GLS_ARRAY_RANGE(s_oesTextureHalfFloatFormats) }, // GL_EXT_sRGB_write_control makes SRGB8_ALPHA8 color-renderable { "GL_EXT_sRGB_write_control", (deUint32)(REQUIRED_RENDERABLE | TEXTURE_VALID | COLOR_RENDERABLE | RENDERBUFFER_VALID), GLS_ARRAY_RANGE(s_extSrgbWriteControlFormats) }, // Since GLES3 is "backwards compatible" to GLES2, we might actually be running on a GLES3 // context. Since GLES3 added some features to core with no corresponding GLES2 extension, // some tests might produce wrong results (since they are using rules of GLES2 & extensions) // // To avoid this, require new features of GLES3 that have no matching GLES2 extension if // context is GLES3. This can be done with a DEQP_* extensions. // // \note Not all feature changes are listed here but only those that alter GLES2 subset of // the formats { "DEQP_gles3_core_compatible", (deUint32)(REQUIRED_RENDERABLE | COLOR_RENDERABLE | RENDERBUFFER_VALID), GLS_ARRAY_RANGE(s_es3NoExtRboFormats) }, { "DEQP_gles3_core_compatible", (deUint32)TEXTURE_VALID, GLS_ARRAY_RANGE(s_es3NoExtTextureFormats) }, { "DEQP_gles3_core_compatible", (deUint32)(REQUIRED_RENDERABLE | TEXTURE_VALID | COLOR_RENDERABLE), GLS_ARRAY_RANGE(s_es3NoExtTextureColorRenderableFormats) }, { "DEQP_gles3_core_compatible GL_EXT_color_buffer_float", (deUint32)(REQUIRED_RENDERABLE | COLOR_RENDERABLE | RENDERBUFFER_VALID), GLS_ARRAY_RANGE(s_es3NoExtExtColorBufferFloatFormats) }, { "DEQP_gles3_core_compatible GL_OES_texture_stencil8", (deUint32)(REQUIRED_RENDERABLE | STENCIL_RENDERABLE | TEXTURE_VALID), GLS_ARRAY_RANGE(s_es3NoExtOesTextureStencil8Formats) }, }; class ES2Checker : public Checker { public: ES2Checker (const glu::RenderContext& ctx); void check (GLenum attPoint, const Attachment& att, const Image* image); private: GLsizei m_width; //< The common width of images GLsizei m_height; //< The common height of images }; ES2Checker::ES2Checker (const glu::RenderContext& ctx)\ : Checker (ctx) , m_width (-1) , m_height (-1) { } void ES2Checker::check (GLenum attPoint, const Attachment& att, const Image* image) { DE_UNREF(attPoint); DE_UNREF(att); // GLES2: "All attached images have the same width and height." if (m_width == -1) { m_width = image->width; m_height = image->height; } else if (image->width != m_width || image->height != m_height) { // Since GLES3 is "backwards compatible" to GLES2, we might actually be running // on a GLES3 context. On GLES3, FRAMEBUFFER_INCOMPLETE_DIMENSIONS is not generated // if attachments have different sizes. if (!gls::FboUtil::checkExtensionSupport(m_renderCtx, "DEQP_gles3_core_compatible")) { // running on GLES2 addFBOStatus(GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS, "Sizes of attachments differ"); } } // GLES2, 4.4.5: "some implementations may not support rendering to // particular combinations of internal formats. If the combination of // formats of the images attached to a framebuffer object are not // supported by the implementation, then the framebuffer is not complete // under the clause labeled FRAMEBUFFER_UNSUPPORTED." // // Hence it is _always_ allowed to report FRAMEBUFFER_UNSUPPORTED. addPotentialFBOStatus(GL_FRAMEBUFFER_UNSUPPORTED, "Particular format combinations need not to be supported"); } struct FormatCombination { GLenum colorKind; ImageFormat colorFmt; GLenum depthKind; ImageFormat depthFmt; GLenum stencilKind; ImageFormat stencilFmt; }; class SupportedCombinationTest : public fboc::TestBase { public: SupportedCombinationTest (fboc::Context& ctx, const char* name, const char* desc) : TestBase (ctx, name, desc) {} IterateResult iterate (void); bool tryCombination (const FormatCombination& comb); GLenum formatKind (ImageFormat fmt); }; bool SupportedCombinationTest::tryCombination (const FormatCombination& comb) { glu::Framebuffer fbo(m_ctx.getRenderContext()); FboBuilder builder(*fbo, GL_FRAMEBUFFER, fboc::gl(*this)); attachTargetToNew(GL_COLOR_ATTACHMENT0, comb.colorKind, comb.colorFmt, 64, 64, builder); attachTargetToNew(GL_DEPTH_ATTACHMENT, comb.depthKind, comb.depthFmt, 64, 64, builder); attachTargetToNew(GL_STENCIL_ATTACHMENT, comb.stencilKind, comb.stencilFmt, 64, 64, builder); const GLenum glStatus = fboc::gl(*this).checkFramebufferStatus(GL_FRAMEBUFFER); return (glStatus == GL_FRAMEBUFFER_COMPLETE); } GLenum SupportedCombinationTest::formatKind (ImageFormat fmt) { if (fmt.format == GL_NONE) return GL_NONE; const FormatFlags flags = m_ctx.getCoreFormats().getFormatInfo(fmt); const bool rbo = (flags & RENDERBUFFER_VALID) != 0; // exactly one of renderbuffer and texture is supported by vanilla GLES2 formats DE_ASSERT(rbo != ((flags & TEXTURE_VALID) != 0)); return rbo ? GL_RENDERBUFFER : GL_TEXTURE; } IterateResult SupportedCombinationTest::iterate (void) { const FormatDB& db = m_ctx.getCoreFormats(); const ImageFormat none = ImageFormat::none(); Formats colorFmts = db.getFormats(COLOR_RENDERABLE); Formats depthFmts = db.getFormats(DEPTH_RENDERABLE); Formats stencilFmts = db.getFormats(STENCIL_RENDERABLE); FormatCombination comb; bool succ = false; colorFmts.insert(none); depthFmts.insert(none); stencilFmts.insert(none); for (Formats::const_iterator col = colorFmts.begin(); col != colorFmts.end(); col++) { comb.colorFmt = *col; comb.colorKind = formatKind(*col); for (Formats::const_iterator dep = depthFmts.begin(); dep != depthFmts.end(); dep++) { comb.depthFmt = *dep; comb.depthKind = formatKind(*dep); for (Formats::const_iterator stc = stencilFmts.begin(); stc != stencilFmts.end(); stc++) { comb.stencilFmt = *stc; comb.stencilKind = formatKind(*stc); succ = tryCombination(comb); if (succ) break; } } } if (succ) pass(); else fail("No supported format combination found"); return STOP; } class ES2CheckerFactory : public CheckerFactory { public: Checker* createChecker (const glu::RenderContext& ctx) { return new ES2Checker(ctx); } }; class TestGroup : public TestCaseGroup { public: TestGroup (Context& ctx); void init (void); private: ES2CheckerFactory m_checkerFactory; fboc::Context m_fboc; }; TestGroup::TestGroup (Context& ctx) : TestCaseGroup (ctx, "completeness", "Completeness tests") , m_checkerFactory () , m_fboc (ctx.getTestContext(), ctx.getRenderContext(), m_checkerFactory) { const FormatEntries stdRange = GLS_ARRAY_RANGE(s_es2Formats); const FormatExtEntries extRange = GLS_ARRAY_RANGE(s_es2ExtFormats); m_fboc.addFormats(stdRange); m_fboc.addExtFormats(extRange); m_fboc.setHaveMulticolorAtts( ctx.getContextInfo().isExtensionSupported("GL_NV_fbo_color_attachments")); } void TestGroup::init (void) { tcu::TestCaseGroup* attCombTests = m_fboc.createAttachmentTests(); addChild(m_fboc.createRenderableTests()); attCombTests->addChild(new SupportedCombinationTest( m_fboc, "exists_supported", "Test for existence of a supported combination of formats")); addChild(attCombTests); addChild(m_fboc.createSizeTests()); } tcu::TestCaseGroup* createFboCompletenessTests (Context& context) { return new TestGroup(context); } } // Functional } // gles2 } // deqp
/*------------------------------------------------------------------------- * drawElements Quality Program OpenGL (ES) Module * ----------------------------------------------- * * Copyright 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief Framebuffer completeness tests. *//*--------------------------------------------------------------------*/ #include "es2fFboCompletenessTests.hpp" #include "glsFboCompletenessTests.hpp" #include "gluObjectWrapper.hpp" using namespace glw; using deqp::gls::Range; using namespace deqp::gls::FboUtil; using namespace deqp::gls::FboUtil::config; namespace fboc = deqp::gls::fboc; typedef tcu::TestCase::IterateResult IterateResult; namespace deqp { namespace gles2 { namespace Functional { static const FormatKey s_es2ColorRenderables[] = { GL_RGBA4, GL_RGB5_A1, GL_RGB565, }; // GLES2 does not strictly allow these, but this seems to be a bug in the // specification. For now, let's assume the unsized formats corresponding to // the color-renderable sized formats are allowed. // See https://cvs.khronos.org/bugzilla/show_bug.cgi?id=7333 static const FormatKey s_es2UnsizedColorRenderables[] = { GLS_UNSIZED_FORMATKEY(GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4), GLS_UNSIZED_FORMATKEY(GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1), GLS_UNSIZED_FORMATKEY(GL_RGB, GL_UNSIGNED_SHORT_5_6_5) }; static const FormatKey s_es2DepthRenderables[] = { GL_DEPTH_COMPONENT16, }; static const FormatKey s_es2StencilRenderables[] = { GL_STENCIL_INDEX8, }; static const FormatEntry s_es2Formats[] = { { COLOR_RENDERABLE | TEXTURE_VALID, GLS_ARRAY_RANGE(s_es2UnsizedColorRenderables) }, { REQUIRED_RENDERABLE | COLOR_RENDERABLE | RENDERBUFFER_VALID, GLS_ARRAY_RANGE(s_es2ColorRenderables) }, { REQUIRED_RENDERABLE | DEPTH_RENDERABLE | RENDERBUFFER_VALID, GLS_ARRAY_RANGE(s_es2DepthRenderables) }, { REQUIRED_RENDERABLE | STENCIL_RENDERABLE | RENDERBUFFER_VALID, GLS_ARRAY_RANGE(s_es2StencilRenderables) }, }; // We have here only the extensions that are redundant in vanilla GLES3. Those // that are applicable both to GLES2 and GLES3 are in glsFboCompletenessTests.cpp. // GL_OES_texture_float static const FormatKey s_oesTextureFloatFormats[] = { GLS_UNSIZED_FORMATKEY(GL_RGBA, GL_FLOAT), GLS_UNSIZED_FORMATKEY(GL_RGB, GL_FLOAT), }; // GL_OES_texture_half_float static const FormatKey s_oesTextureHalfFloatFormats[] = { GLS_UNSIZED_FORMATKEY(GL_RGBA, GL_HALF_FLOAT_OES), GLS_UNSIZED_FORMATKEY(GL_RGB, GL_HALF_FLOAT_OES), }; // GL_EXT_sRGB_write_control static const FormatKey s_extSrgbWriteControlFormats[] = { GL_SRGB8_ALPHA8 }; // DEQP_gles3_core_no_extension_features static const FormatKey s_es3NoExtRboFormats[] = { GL_RGB10_A2, }; static const FormatKey s_es3NoExtTextureFormats[] = { GL_R16F, GL_RG16F, GL_RGB16F, GL_RGBA16F, GL_R11F_G11F_B10F, }; static const FormatKey s_es3NoExtTextureColorRenderableFormats[] = { GL_R8, GL_RG8, }; // with ES3 core and GL_EXT_color_buffer_float static const FormatKey s_es3NoExtExtColorBufferFloatFormats[] = { // \note Only the GLES2+exts subset of formats GL_R11F_G11F_B10F, GL_RGBA16F, GL_RG16F, GL_R16F, }; // with ES3 core with OES_texture_stencil8 static const FormatKey s_es3NoExtOesTextureStencil8Formats[] = { GL_STENCIL_INDEX8, }; static const FormatExtEntry s_es2ExtFormats[] = { // The extension does not specify these to be color-renderable. { "GL_OES_texture_float", (deUint32)TEXTURE_VALID, GLS_ARRAY_RANGE(s_oesTextureFloatFormats) }, { "GL_OES_texture_half_float", (deUint32)TEXTURE_VALID, GLS_ARRAY_RANGE(s_oesTextureHalfFloatFormats) }, // GL_EXT_sRGB_write_control makes SRGB8_ALPHA8 color-renderable { "GL_EXT_sRGB_write_control", (deUint32)(REQUIRED_RENDERABLE | TEXTURE_VALID | COLOR_RENDERABLE | RENDERBUFFER_VALID), GLS_ARRAY_RANGE(s_extSrgbWriteControlFormats) }, // Since GLES3 is "backwards compatible" to GLES2, we might actually be running on a GLES3 // context. Since GLES3 added some features to core with no corresponding GLES2 extension, // some tests might produce wrong results (since they are using rules of GLES2 & extensions) // // To avoid this, require new features of GLES3 that have no matching GLES2 extension if // context is GLES3. This can be done with a DEQP_* extensions. // // \note Not all feature changes are listed here but only those that alter GLES2 subset of // the formats { "DEQP_gles3_core_compatible", (deUint32)(REQUIRED_RENDERABLE | COLOR_RENDERABLE | RENDERBUFFER_VALID), GLS_ARRAY_RANGE(s_es3NoExtRboFormats) }, { "DEQP_gles3_core_compatible", (deUint32)TEXTURE_VALID, GLS_ARRAY_RANGE(s_es3NoExtTextureFormats) }, { "DEQP_gles3_core_compatible", (deUint32)(REQUIRED_RENDERABLE | TEXTURE_VALID | COLOR_RENDERABLE | RENDERBUFFER_VALID), GLS_ARRAY_RANGE(s_es3NoExtTextureColorRenderableFormats) }, { "DEQP_gles3_core_compatible GL_EXT_color_buffer_float", (deUint32)(REQUIRED_RENDERABLE | COLOR_RENDERABLE | RENDERBUFFER_VALID), GLS_ARRAY_RANGE(s_es3NoExtExtColorBufferFloatFormats) }, { "DEQP_gles3_core_compatible GL_OES_texture_stencil8", (deUint32)(REQUIRED_RENDERABLE | STENCIL_RENDERABLE | TEXTURE_VALID), GLS_ARRAY_RANGE(s_es3NoExtOesTextureStencil8Formats) }, }; class ES2Checker : public Checker { public: ES2Checker (const glu::RenderContext& ctx); void check (GLenum attPoint, const Attachment& att, const Image* image); private: GLsizei m_width; //< The common width of images GLsizei m_height; //< The common height of images }; ES2Checker::ES2Checker (const glu::RenderContext& ctx)\ : Checker (ctx) , m_width (-1) , m_height (-1) { } void ES2Checker::check (GLenum attPoint, const Attachment& att, const Image* image) { DE_UNREF(attPoint); DE_UNREF(att); // GLES2: "All attached images have the same width and height." if (m_width == -1) { m_width = image->width; m_height = image->height; } else if (image->width != m_width || image->height != m_height) { // Since GLES3 is "backwards compatible" to GLES2, we might actually be running // on a GLES3 context. On GLES3, FRAMEBUFFER_INCOMPLETE_DIMENSIONS is not generated // if attachments have different sizes. if (!gls::FboUtil::checkExtensionSupport(m_renderCtx, "DEQP_gles3_core_compatible")) { // running on GLES2 addFBOStatus(GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS, "Sizes of attachments differ"); } } // GLES2, 4.4.5: "some implementations may not support rendering to // particular combinations of internal formats. If the combination of // formats of the images attached to a framebuffer object are not // supported by the implementation, then the framebuffer is not complete // under the clause labeled FRAMEBUFFER_UNSUPPORTED." // // Hence it is _always_ allowed to report FRAMEBUFFER_UNSUPPORTED. addPotentialFBOStatus(GL_FRAMEBUFFER_UNSUPPORTED, "Particular format combinations need not to be supported"); } struct FormatCombination { GLenum colorKind; ImageFormat colorFmt; GLenum depthKind; ImageFormat depthFmt; GLenum stencilKind; ImageFormat stencilFmt; }; class SupportedCombinationTest : public fboc::TestBase { public: SupportedCombinationTest (fboc::Context& ctx, const char* name, const char* desc) : TestBase (ctx, name, desc) {} IterateResult iterate (void); bool tryCombination (const FormatCombination& comb); GLenum formatKind (ImageFormat fmt); }; bool SupportedCombinationTest::tryCombination (const FormatCombination& comb) { glu::Framebuffer fbo(m_ctx.getRenderContext()); FboBuilder builder(*fbo, GL_FRAMEBUFFER, fboc::gl(*this)); attachTargetToNew(GL_COLOR_ATTACHMENT0, comb.colorKind, comb.colorFmt, 64, 64, builder); attachTargetToNew(GL_DEPTH_ATTACHMENT, comb.depthKind, comb.depthFmt, 64, 64, builder); attachTargetToNew(GL_STENCIL_ATTACHMENT, comb.stencilKind, comb.stencilFmt, 64, 64, builder); const GLenum glStatus = fboc::gl(*this).checkFramebufferStatus(GL_FRAMEBUFFER); return (glStatus == GL_FRAMEBUFFER_COMPLETE); } GLenum SupportedCombinationTest::formatKind (ImageFormat fmt) { if (fmt.format == GL_NONE) return GL_NONE; const FormatFlags flags = m_ctx.getCoreFormats().getFormatInfo(fmt); const bool rbo = (flags & RENDERBUFFER_VALID) != 0; // exactly one of renderbuffer and texture is supported by vanilla GLES2 formats DE_ASSERT(rbo != ((flags & TEXTURE_VALID) != 0)); return rbo ? GL_RENDERBUFFER : GL_TEXTURE; } IterateResult SupportedCombinationTest::iterate (void) { const FormatDB& db = m_ctx.getCoreFormats(); const ImageFormat none = ImageFormat::none(); Formats colorFmts = db.getFormats(COLOR_RENDERABLE); Formats depthFmts = db.getFormats(DEPTH_RENDERABLE); Formats stencilFmts = db.getFormats(STENCIL_RENDERABLE); FormatCombination comb; bool succ = false; colorFmts.insert(none); depthFmts.insert(none); stencilFmts.insert(none); for (Formats::const_iterator col = colorFmts.begin(); col != colorFmts.end(); col++) { comb.colorFmt = *col; comb.colorKind = formatKind(*col); for (Formats::const_iterator dep = depthFmts.begin(); dep != depthFmts.end(); dep++) { comb.depthFmt = *dep; comb.depthKind = formatKind(*dep); for (Formats::const_iterator stc = stencilFmts.begin(); stc != stencilFmts.end(); stc++) { comb.stencilFmt = *stc; comb.stencilKind = formatKind(*stc); succ = tryCombination(comb); if (succ) break; } } } if (succ) pass(); else fail("No supported format combination found"); return STOP; } class ES2CheckerFactory : public CheckerFactory { public: Checker* createChecker (const glu::RenderContext& ctx) { return new ES2Checker(ctx); } }; class TestGroup : public TestCaseGroup { public: TestGroup (Context& ctx); void init (void); private: ES2CheckerFactory m_checkerFactory; fboc::Context m_fboc; }; TestGroup::TestGroup (Context& ctx) : TestCaseGroup (ctx, "completeness", "Completeness tests") , m_checkerFactory () , m_fboc (ctx.getTestContext(), ctx.getRenderContext(), m_checkerFactory) { const FormatEntries stdRange = GLS_ARRAY_RANGE(s_es2Formats); const FormatExtEntries extRange = GLS_ARRAY_RANGE(s_es2ExtFormats); m_fboc.addFormats(stdRange); m_fboc.addExtFormats(extRange); m_fboc.setHaveMulticolorAtts( ctx.getContextInfo().isExtensionSupported("GL_NV_fbo_color_attachments")); } void TestGroup::init (void) { tcu::TestCaseGroup* attCombTests = m_fboc.createAttachmentTests(); addChild(m_fboc.createRenderableTests()); attCombTests->addChild(new SupportedCombinationTest( m_fboc, "exists_supported", "Test for existence of a supported combination of formats")); addChild(attCombTests); addChild(m_fboc.createSizeTests()); } tcu::TestCaseGroup* createFboCompletenessTests (Context& context) { return new TestGroup(context); } } // Functional } // gles2 } // deqp
Add RENDERBUFFER_VALID bit to R8, RG8 definition am: 1d7c8df82e
Add RENDERBUFFER_VALID bit to R8, RG8 definition am: 1d7c8df82e Change-Id: Icac62d124fbf4343bd4df66b996df29e141bf904
C++
apache-2.0
googlestadia/VK-GL-CTS,KhronosGroup/Vulkan-CTS,KhronosGroup/VK-GL-CTS,googlestadia/VK-GL-CTS,KhronosGroup/VK-GL-CTS,KhronosGroup/Vulkan-CTS,KhronosGroup/VK-GL-CTS,KhronosGroup/Vulkan-CTS,KhronosGroup/VK-GL-CTS,googlestadia/VK-GL-CTS,KhronosGroup/Vulkan-CTS,googlestadia/VK-GL-CTS,KhronosGroup/VK-GL-CTS,googlestadia/VK-GL-CTS,KhronosGroup/Vulkan-CTS,KhronosGroup/Vulkan-CTS,googlestadia/VK-GL-CTS,KhronosGroup/VK-GL-CTS
c485d9b25a3a739785b24f43f15de70aa8f3c83d
base/QtMain.cpp
base/QtMain.cpp
/* * Copyright (c) 2012 Sacha Refshauge * */ // Qt 4.7+ / 5.0+ implementation of the framework. // Currently supports: Symbian, Blackberry, Meego, Linux, Windows #include <QApplication> #include <QUrl> #include <QDir> #include <QDesktopWidget> #include <QDesktopServices> #include <QLocale> #include <QThread> #ifdef __SYMBIAN32__ #include <e32std.h> #include <QSystemScreenSaver> #include <QFeedbackHapticsEffect> #include "SymbianMediaKeys.h" #endif #include "QtMain.h" InputState* input_state; std::string System_GetProperty(SystemProperty prop) { switch (prop) { case SYSPROP_NAME: #ifdef __SYMBIAN32__ return "Qt:Symbian"; #elif defined(BLACKBERRY) return "Qt:Blackberry10"; #elif defined(MEEGO_EDITION_HARMATTAN) return "Qt:Meego"; #elif defined(Q_OS_LINUX) return "Qt:Linux"; #elif defined(_WIN32) return "Qt:Windows"; #else return "Qt"; #endif case SYSPROP_LANGREGION: return QLocale::system().name().toStdString(); default: return ""; } } void Vibrate(int length_ms) { if (length_ms == -1 || length_ms == -3) length_ms = 50; else if (length_ms == -2) length_ms = 25; // Symbian only for now #if defined(__SYMBIAN32__) QFeedbackHapticsEffect effect; effect.setIntensity(0.2); effect.setDuration(length_ms); effect.start(); #endif } void LaunchBrowser(const char *url) { QDesktopServices::openUrl(QUrl(url)); } float CalculateDPIScale() { // Sane default rather than check DPI #ifdef __SYMBIAN32__ return 1.4f; #elif defined(ARM) return 1.2f; #else return 1.0f; #endif } Q_DECL_EXPORT int main(int argc, char *argv[]) { #ifdef Q_OS_LINUX QApplication::setAttribute(Qt::AA_X11InitThreads, true); #endif QApplication a(argc, argv); QSize res = QApplication::desktop()->screenGeometry().size(); if (res.width() < res.height()) res.transpose(); pixel_xres = res.width(); pixel_yres = res.height(); g_dpi_scale = CalculateDPIScale(); dp_xres = (int)(pixel_xres * g_dpi_scale); dp_yres = (int)(pixel_yres * g_dpi_scale); net::Init(); #ifdef __SYMBIAN32__ const char *savegame_dir = "E:/PPSSPP/"; const char *assets_dir = "E:/PPSSPP/"; #elif defined(BLACKBERRY) const char *savegame_dir = "/accounts/1000/shared/misc/"; const char *assets_dir = "app/native/assets/"; #elif defined(MEEGO_EDITION_HARMATTAN) const char *savegame_dir = "/home/user/MyDocs/PPSSPP/"; QDir myDocs("/home/user/MyDocs/"); if (!myDocs.exists("PPSSPP")) myDocs.mkdir("PPSSPP"); const char *assets_dir = "/opt/PPSSPP/"; #else const char *savegame_dir = "./"; const char *assets_dir = "./"; #endif NativeInit(argc, (const char **)argv, savegame_dir, assets_dir, "BADCOFFEE"); #if !defined(Q_OS_LINUX) || defined(ARM) MainUI w; w.resize(pixel_xres, pixel_yres); #ifdef ARM w.showFullScreen(); #else w.show(); #endif #endif #ifdef __SYMBIAN32__ // Set RunFast hardware mode for VFPv2. User::SetFloatingPointMode(EFpModeRunFast); // Disable screensaver QSystemScreenSaver *ssObject = new QSystemScreenSaver(&w); ssObject->setScreenSaverInhibit(); SymbianMediaKeys* mediakeys = new SymbianMediaKeys(); #endif QThread* thread = new QThread; MainAudio *audio = new MainAudio(); audio->moveToThread(thread); QObject::connect(thread, SIGNAL(started()), audio, SLOT(run())); QObject::connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); thread->start(); int ret = a.exec(); delete audio; thread->quit(); NativeShutdown(); net::Shutdown(); return ret; }
/* * Copyright (c) 2012 Sacha Refshauge * */ // Qt 4.7+ / 5.0+ implementation of the framework. // Currently supports: Symbian, Blackberry, Meego, Linux, Windows #include <QApplication> #include <QUrl> #include <QDir> #include <QDesktopWidget> #include <QDesktopServices> #include <QLocale> #include <QThread> #ifdef __SYMBIAN32__ #include <e32std.h> #include <QSystemScreenSaver> #include <QFeedbackHapticsEffect> #include "SymbianMediaKeys.h" #endif #include "QtMain.h" InputState* input_state; std::string System_GetProperty(SystemProperty prop) { switch (prop) { case SYSPROP_NAME: #ifdef __SYMBIAN32__ return "Qt:Symbian"; #elif defined(BLACKBERRY) return "Qt:Blackberry10"; #elif defined(MEEGO_EDITION_HARMATTAN) return "Qt:Meego"; #elif defined(Q_OS_LINUX) return "Qt:Linux"; #elif defined(_WIN32) return "Qt:Windows"; #else return "Qt"; #endif case SYSPROP_LANGREGION: return QLocale::system().name().toStdString(); default: return ""; } } void Vibrate(int length_ms) { if (length_ms == -1 || length_ms == -3) length_ms = 50; else if (length_ms == -2) length_ms = 25; // Symbian only for now #if defined(__SYMBIAN32__) QFeedbackHapticsEffect effect; effect.setIntensity(0.4); effect.setDuration(length_ms); effect.start(); #endif } void LaunchBrowser(const char *url) { QDesktopServices::openUrl(QUrl(url)); } float CalculateDPIScale() { // Sane default rather than check DPI #ifdef __SYMBIAN32__ return 1.4f; #elif defined(ARM) return 1.2f; #else return 1.0f; #endif } Q_DECL_EXPORT int main(int argc, char *argv[]) { #ifdef Q_OS_LINUX QApplication::setAttribute(Qt::AA_X11InitThreads, true); #endif QApplication a(argc, argv); QSize res = QApplication::desktop()->screenGeometry().size(); if (res.width() < res.height()) res.transpose(); pixel_xres = res.width(); pixel_yres = res.height(); g_dpi_scale = CalculateDPIScale(); dp_xres = (int)(pixel_xres * g_dpi_scale); dp_yres = (int)(pixel_yres * g_dpi_scale); net::Init(); #ifdef __SYMBIAN32__ const char *savegame_dir = "E:/PPSSPP/"; const char *assets_dir = "E:/PPSSPP/"; #elif defined(BLACKBERRY) const char *savegame_dir = "/accounts/1000/shared/misc/"; const char *assets_dir = "app/native/assets/"; #elif defined(MEEGO_EDITION_HARMATTAN) const char *savegame_dir = "/home/user/MyDocs/PPSSPP/"; QDir myDocs("/home/user/MyDocs/"); if (!myDocs.exists("PPSSPP")) myDocs.mkdir("PPSSPP"); const char *assets_dir = "/opt/PPSSPP/"; #else const char *savegame_dir = "./"; const char *assets_dir = "./"; #endif NativeInit(argc, (const char **)argv, savegame_dir, assets_dir, "BADCOFFEE"); #if !defined(Q_OS_LINUX) || defined(ARM) MainUI w; w.resize(pixel_xres, pixel_yres); #ifdef ARM w.showFullScreen(); #else w.show(); #endif #endif #ifdef __SYMBIAN32__ // Set RunFast hardware mode for VFPv2. User::SetFloatingPointMode(EFpModeRunFast); // Disable screensaver QSystemScreenSaver *ssObject = new QSystemScreenSaver(&w); ssObject->setScreenSaverInhibit(); SymbianMediaKeys* mediakeys = new SymbianMediaKeys(); #endif QThread* thread = new QThread; MainAudio *audio = new MainAudio(); audio->moveToThread(thread); QObject::connect(thread, SIGNAL(started()), audio, SLOT(run())); QObject::connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); thread->start(); int ret = a.exec(); delete audio; thread->quit(); NativeShutdown(); net::Shutdown(); return ret; }
Increase vibration on Symbian.
Increase vibration on Symbian.
C++
mit
unknownbrackets/native,unknownbrackets/native,libretro/ppsspp-native,libretro/ppsspp-native,libretro/ppsspp-native,libretro/ppsspp-native,unknownbrackets/native,zhykzhykzhyk/ppsspp-native,hrydgard/native,hrydgard/native,zhykzhykzhyk/ppsspp-native,zhykzhykzhyk/ppsspp-native,zhykzhykzhyk/ppsspp-native,hrydgard/native,hrydgard/native,unknownbrackets/native
8d57a8b8ba764b9a09ada35f7212fc2e9a2c1fbb
modules/gui/qt4/components/playlist/standardpanel.cpp
modules/gui/qt4/components/playlist/standardpanel.cpp
/***************************************************************************** * standardpanel.cpp : The "standard" playlist panel : just a treeview **************************************************************************** * Copyright (C) 2000-2005 the VideoLAN team * $Id$ * * Authors: Clément Stenac <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "qt4.hpp" #include "dialogs_provider.hpp" #include "components/playlist/playlist_model.hpp" #include "components/playlist/panels.hpp" #include "util/customwidgets.hpp" #include <vlc_intf_strings.h> #include <QTreeView> #include <QPushButton> #include <QHBoxLayout> #include <QVBoxLayout> #include <QHeaderView> #include <QKeyEvent> #include <QModelIndexList> #include <QToolBar> #include <QLabel> #include <QSpacerItem> #include <QMenu> #include <QSignalMapper> #include <assert.h> #include "sorting.h" StandardPLPanel::StandardPLPanel( PlaylistWidget *_parent, intf_thread_t *_p_intf, playlist_t *p_playlist, playlist_item_t *p_root ): PLPanel( _parent, _p_intf ) { model = new PLModel( p_playlist, p_intf, p_root, -1, this ); QVBoxLayout *layout = new QVBoxLayout(); layout->setSpacing( 0 ); layout->setMargin( 0 ); /* Create and configure the QTreeView */ view = new QVLCTreeView( 0 ); view->setSortingEnabled( true ); view->sortByColumn( 0 , Qt::AscendingOrder ); view->setModel( model ); view->setIconSize( QSize( 20, 20 ) ); view->setAlternatingRowColors( true ); view->setAnimated( true ); view->setSelectionMode( QAbstractItemView::ExtendedSelection ); view->setDragEnabled( true ); view->setAcceptDrops( true ); view->setDropIndicatorShown( true ); view->setAutoScroll( true ); getSettings()->beginGroup("Playlist"); #if HAS_QT43 if( getSettings()->contains( "headerState" ) ) { view->header()->restoreState( getSettings()->value( "headerState" ).toByteArray() ); } else #endif { /* Configure the size of the header */ view->header()->resizeSection( 0, 200 ); view->header()->resizeSection( 1, 80 ); view->header()->setSortIndicatorShown( true ); view->header()->setClickable( true ); view->header()->setContextMenuPolicy( Qt::CustomContextMenu ); } getSettings()->endGroup(); /* Connections for the TreeView */ CONNECT( view, activated( const QModelIndex& ) , model,activateItem( const QModelIndex& ) ); CONNECT( view, rightClicked( QModelIndex , QPoint ), this, doPopup( QModelIndex, QPoint ) ); CONNECT( model, dataChanged( const QModelIndex&, const QModelIndex& ), this, handleExpansion( const QModelIndex& ) ); CONNECT( view->header(), customContextMenuRequested( const QPoint & ), this, popupSelectColumn( QPoint ) ); currentRootId = -1; CONNECT( parent, rootChanged( int ), this, setCurrentRootId( int ) ); /* Buttons configuration */ QHBoxLayout *buttons = new QHBoxLayout; /* Add item to the playlist button */ addButton = new QPushButton; addButton->setIcon( QIcon( ":/playlist_add" ) ); addButton->setMaximumWidth( 30 ); BUTTONACT( addButton, popupAdd() ); buttons->addWidget( addButton ); /* Random 2-state button */ randomButton = new QPushButton( this ); if( model->hasRandom() ) { randomButton->setIcon( QIcon( ":/shuffle_on" )); randomButton->setToolTip( qtr( I_PL_RANDOM )); } else { randomButton->setIcon( QIcon( ":/shuffle_off" ) ); randomButton->setToolTip( qtr( I_PL_NORANDOM )); } BUTTONACT( randomButton, toggleRandom() ); buttons->addWidget( randomButton ); /* Repeat 3-state button */ repeatButton = new QPushButton( this ); if( model->hasRepeat() ) { repeatButton->setIcon( QIcon( ":/repeat_one" ) ); repeatButton->setToolTip( qtr( I_PL_REPEAT )); } else if( model->hasLoop() ) { repeatButton->setIcon( QIcon( ":/repeat_all" ) ); repeatButton->setToolTip( qtr( I_PL_LOOP )); } else { repeatButton->setIcon( QIcon( ":/repeat_off" ) ); repeatButton->setToolTip( qtr( I_PL_NOREPEAT )); } BUTTONACT( repeatButton, toggleRepeat() ); buttons->addWidget( repeatButton ); /* Goto */ gotoPlayingButton = new QPushButton; BUTTON_SET_ACT_I( gotoPlayingButton, "", jump_to, qtr( "Show the current item" ), gotoPlayingItem() ); buttons->addWidget( gotoPlayingButton ); /* A Spacer and the search possibilities */ QSpacerItem *spacer = new QSpacerItem( 10, 20 ); buttons->addItem( spacer ); QLabel *filter = new QLabel( qtr(I_PL_SEARCH) + " " ); buttons->addWidget( filter ); searchLine = new ClickLineEdit( qtr(I_PL_FILTER), 0 ); searchLine->setMinimumWidth( 80 ); CONNECT( searchLine, textChanged(QString), this, search(QString)); buttons->addWidget( searchLine ); filter->setBuddy( searchLine ); QPushButton *clear = new QPushButton; clear->setMaximumWidth( 30 ); BUTTON_SET_ACT_I( clear, "", clear, qtr( "Clear" ), clearFilter() ); buttons->addWidget( clear ); /* Finish the layout */ layout->addWidget( view ); layout->addLayout( buttons ); // layout->addWidget( bar ); setLayout( layout ); } /* Function to toggle between the Repeat states */ void StandardPLPanel::toggleRepeat() { if( model->hasRepeat() ) { model->setRepeat( false ); model->setLoop( true ); repeatButton->setIcon( QIcon( ":/repeat_all" ) ); repeatButton->setToolTip( qtr( I_PL_LOOP )); } else if( model->hasLoop() ) { model->setRepeat( false ) ; model->setLoop( false ); repeatButton->setIcon( QIcon( ":/repeat_off" ) ); repeatButton->setToolTip( qtr( I_PL_NOREPEAT )); } else { model->setRepeat( true ); repeatButton->setIcon( QIcon( ":/repeat_one" ) ); repeatButton->setToolTip( qtr( I_PL_REPEAT )); } } /* Function to toggle between the Random states */ void StandardPLPanel::toggleRandom() { bool prev = model->hasRandom(); model->setRandom( !prev ); randomButton->setIcon( prev ? QIcon( ":/shuffle_off" ) : QIcon( ":/shuffle_on" ) ); randomButton->setToolTip( prev ? qtr( I_PL_NORANDOM ) : qtr(I_PL_RANDOM ) ); } void StandardPLPanel::gotoPlayingItem() { view->scrollTo( view->currentIndex() ); } void StandardPLPanel::handleExpansion( const QModelIndex &index ) { if( model->isCurrent( index ) ) view->scrollTo( index, QAbstractItemView::EnsureVisible ); } void StandardPLPanel::setCurrentRootId( int _new ) { currentRootId = _new; if( currentRootId == THEPL->p_local_category->i_id || currentRootId == THEPL->p_local_onelevel->i_id ) { addButton->setEnabled( true ); addButton->setToolTip( qtr(I_PL_ADDPL) ); } else if( ( THEPL->p_ml_category && currentRootId == THEPL->p_ml_category->i_id ) || ( THEPL->p_ml_onelevel && currentRootId == THEPL->p_ml_onelevel->i_id ) ) { addButton->setEnabled( true ); addButton->setToolTip( qtr(I_PL_ADDML) ); } else addButton->setEnabled( false ); } /* PopupAdd Menu for the Add Menu */ void StandardPLPanel::popupAdd() { QMenu popup; if( currentRootId == THEPL->p_local_category->i_id || currentRootId == THEPL->p_local_onelevel->i_id ) { popup.addAction( qtr(I_PL_ADDF), THEDP, SLOT(PLAppendDialog()) ); popup.addAction( qtr(I_PL_ADDDIR), THEDP, SLOT( PLAppendDir()) ); } else if( ( THEPL->p_ml_category && currentRootId == THEPL->p_ml_category->i_id ) || ( THEPL->p_ml_onelevel && currentRootId == THEPL->p_ml_onelevel->i_id ) ) { popup.addAction( qtr(I_PL_ADDF), THEDP, SLOT( MLAppendDialog() ) ); popup.addAction( qtr(I_PL_ADDDIR), THEDP, SLOT( MLAppendDir() ) ); } popup.exec( QCursor::pos() - addButton->mapFromGlobal( QCursor::pos() ) + QPoint( 0, addButton->height() ) ); } void StandardPLPanel::popupSelectColumn( QPoint pos ) { ContextUpdateMapper = new QSignalMapper(this); QMenu selectColMenu; CONNECT( ContextUpdateMapper, mapped( int ), model, viewchanged( int ) ); int i_column = 1; for( i_column = 1; i_column != COLUMN_END; i_column<<=1 ) { QAction* option = selectColMenu.addAction( qfu( psz_column_title( i_column ) ) ); option->setCheckable( true ); option->setChecked( model->shownFlags() & i_column ); ContextUpdateMapper->setMapping( option, i_column ); CONNECT( option, triggered(), ContextUpdateMapper, map() ); } selectColMenu.exec( QCursor::pos() ); } /* ClearFilter LineEdit */ void StandardPLPanel::clearFilter() { searchLine->setText( "" ); } /* Search in the playlist */ void StandardPLPanel::search( QString searchText ) { model->search( searchText ); } void StandardPLPanel::doPopup( QModelIndex index, QPoint point ) { if( !index.isValid() ) return; QItemSelectionModel *selection = view->selectionModel(); QModelIndexList list = selection->selectedIndexes(); model->popup( index, point, list ); } /* Set the root of the new Playlist */ /* This activated by the selector selection */ void StandardPLPanel::setRoot( int i_root_id ) { QPL_LOCK; playlist_item_t *p_item = playlist_ItemGetById( THEPL, i_root_id, pl_Locked ); assert( p_item ); p_item = playlist_GetPreferredNode( THEPL, p_item ); assert( p_item ); QPL_UNLOCK; model->rebuild( p_item ); } void StandardPLPanel::removeItem( int i_id ) { model->removeItem( i_id ); } /* Delete and Suppr key remove the selection FilterKey function and code function */ void StandardPLPanel::keyPressEvent( QKeyEvent *e ) { switch( e->key() ) { case Qt::Key_Back: case Qt::Key_Delete: deleteSelection(); break; } } void StandardPLPanel::deleteSelection() { QItemSelectionModel *selection = view->selectionModel(); QModelIndexList list = selection->selectedIndexes(); model->doDelete( list ); } StandardPLPanel::~StandardPLPanel() { #if HAS_QT43 getSettings()->beginGroup("Playlist"); getSettings()->setValue( "headerState", view->header()->saveState() ); getSettings()->endGroup(); #endif }
/***************************************************************************** * standardpanel.cpp : The "standard" playlist panel : just a treeview **************************************************************************** * Copyright (C) 2000-2005 the VideoLAN team * $Id$ * * Authors: Clément Stenac <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "qt4.hpp" #include "dialogs_provider.hpp" #include "components/playlist/playlist_model.hpp" #include "components/playlist/panels.hpp" #include "util/customwidgets.hpp" #include <vlc_intf_strings.h> #include <QTreeView> #include <QPushButton> #include <QHBoxLayout> #include <QVBoxLayout> #include <QHeaderView> #include <QKeyEvent> #include <QModelIndexList> #include <QToolBar> #include <QLabel> #include <QSpacerItem> #include <QMenu> #include <QSignalMapper> #include <assert.h> #include "sorting.h" StandardPLPanel::StandardPLPanel( PlaylistWidget *_parent, intf_thread_t *_p_intf, playlist_t *p_playlist, playlist_item_t *p_root ): PLPanel( _parent, _p_intf ) { model = new PLModel( p_playlist, p_intf, p_root, -1, this ); QVBoxLayout *layout = new QVBoxLayout(); layout->setSpacing( 0 ); layout->setMargin( 0 ); /* Create and configure the QTreeView */ view = new QVLCTreeView( 0 ); view->setSortingEnabled( true ); view->sortByColumn( 0 , Qt::AscendingOrder ); view->setModel( model ); view->setIconSize( QSize( 20, 20 ) ); view->setAlternatingRowColors( true ); view->setAnimated( true ); view->setSelectionMode( QAbstractItemView::ExtendedSelection ); view->setDragEnabled( true ); view->setAcceptDrops( true ); view->setDropIndicatorShown( true ); view->setAutoScroll( true ); getSettings()->beginGroup("Playlist"); #if HAS_QT43 if( getSettings()->contains( "headerState" ) ) { view->header()->restoreState( getSettings()->value( "headerState" ).toByteArray() ); } else #endif { /* Configure the size of the header */ view->header()->resizeSection( 0, 200 ); view->header()->resizeSection( 1, 80 ); } view->header()->setSortIndicatorShown( true ); view->header()->setClickable( true ); view->header()->setContextMenuPolicy( Qt::CustomContextMenu ); getSettings()->endGroup(); /* Connections for the TreeView */ CONNECT( view, activated( const QModelIndex& ) , model,activateItem( const QModelIndex& ) ); CONNECT( view, rightClicked( QModelIndex , QPoint ), this, doPopup( QModelIndex, QPoint ) ); CONNECT( model, dataChanged( const QModelIndex&, const QModelIndex& ), this, handleExpansion( const QModelIndex& ) ); CONNECT( view->header(), customContextMenuRequested( const QPoint & ), this, popupSelectColumn( QPoint ) ); currentRootId = -1; CONNECT( parent, rootChanged( int ), this, setCurrentRootId( int ) ); /* Buttons configuration */ QHBoxLayout *buttons = new QHBoxLayout; /* Add item to the playlist button */ addButton = new QPushButton; addButton->setIcon( QIcon( ":/playlist_add" ) ); addButton->setMaximumWidth( 30 ); BUTTONACT( addButton, popupAdd() ); buttons->addWidget( addButton ); /* Random 2-state button */ randomButton = new QPushButton( this ); if( model->hasRandom() ) { randomButton->setIcon( QIcon( ":/shuffle_on" )); randomButton->setToolTip( qtr( I_PL_RANDOM )); } else { randomButton->setIcon( QIcon( ":/shuffle_off" ) ); randomButton->setToolTip( qtr( I_PL_NORANDOM )); } BUTTONACT( randomButton, toggleRandom() ); buttons->addWidget( randomButton ); /* Repeat 3-state button */ repeatButton = new QPushButton( this ); if( model->hasRepeat() ) { repeatButton->setIcon( QIcon( ":/repeat_one" ) ); repeatButton->setToolTip( qtr( I_PL_REPEAT )); } else if( model->hasLoop() ) { repeatButton->setIcon( QIcon( ":/repeat_all" ) ); repeatButton->setToolTip( qtr( I_PL_LOOP )); } else { repeatButton->setIcon( QIcon( ":/repeat_off" ) ); repeatButton->setToolTip( qtr( I_PL_NOREPEAT )); } BUTTONACT( repeatButton, toggleRepeat() ); buttons->addWidget( repeatButton ); /* Goto */ gotoPlayingButton = new QPushButton; BUTTON_SET_ACT_I( gotoPlayingButton, "", jump_to, qtr( "Show the current item" ), gotoPlayingItem() ); buttons->addWidget( gotoPlayingButton ); /* A Spacer and the search possibilities */ QSpacerItem *spacer = new QSpacerItem( 10, 20 ); buttons->addItem( spacer ); QLabel *filter = new QLabel( qtr(I_PL_SEARCH) + " " ); buttons->addWidget( filter ); searchLine = new ClickLineEdit( qtr(I_PL_FILTER), 0 ); searchLine->setMinimumWidth( 80 ); CONNECT( searchLine, textChanged(QString), this, search(QString)); buttons->addWidget( searchLine ); filter->setBuddy( searchLine ); QPushButton *clear = new QPushButton; clear->setMaximumWidth( 30 ); BUTTON_SET_ACT_I( clear, "", clear, qtr( "Clear" ), clearFilter() ); buttons->addWidget( clear ); /* Finish the layout */ layout->addWidget( view ); layout->addLayout( buttons ); // layout->addWidget( bar ); setLayout( layout ); } /* Function to toggle between the Repeat states */ void StandardPLPanel::toggleRepeat() { if( model->hasRepeat() ) { model->setRepeat( false ); model->setLoop( true ); repeatButton->setIcon( QIcon( ":/repeat_all" ) ); repeatButton->setToolTip( qtr( I_PL_LOOP )); } else if( model->hasLoop() ) { model->setRepeat( false ) ; model->setLoop( false ); repeatButton->setIcon( QIcon( ":/repeat_off" ) ); repeatButton->setToolTip( qtr( I_PL_NOREPEAT )); } else { model->setRepeat( true ); repeatButton->setIcon( QIcon( ":/repeat_one" ) ); repeatButton->setToolTip( qtr( I_PL_REPEAT )); } } /* Function to toggle between the Random states */ void StandardPLPanel::toggleRandom() { bool prev = model->hasRandom(); model->setRandom( !prev ); randomButton->setIcon( prev ? QIcon( ":/shuffle_off" ) : QIcon( ":/shuffle_on" ) ); randomButton->setToolTip( prev ? qtr( I_PL_NORANDOM ) : qtr(I_PL_RANDOM ) ); } void StandardPLPanel::gotoPlayingItem() { view->scrollTo( view->currentIndex() ); } void StandardPLPanel::handleExpansion( const QModelIndex &index ) { if( model->isCurrent( index ) ) view->scrollTo( index, QAbstractItemView::EnsureVisible ); } void StandardPLPanel::setCurrentRootId( int _new ) { currentRootId = _new; if( currentRootId == THEPL->p_local_category->i_id || currentRootId == THEPL->p_local_onelevel->i_id ) { addButton->setEnabled( true ); addButton->setToolTip( qtr(I_PL_ADDPL) ); } else if( ( THEPL->p_ml_category && currentRootId == THEPL->p_ml_category->i_id ) || ( THEPL->p_ml_onelevel && currentRootId == THEPL->p_ml_onelevel->i_id ) ) { addButton->setEnabled( true ); addButton->setToolTip( qtr(I_PL_ADDML) ); } else addButton->setEnabled( false ); } /* PopupAdd Menu for the Add Menu */ void StandardPLPanel::popupAdd() { QMenu popup; if( currentRootId == THEPL->p_local_category->i_id || currentRootId == THEPL->p_local_onelevel->i_id ) { popup.addAction( qtr(I_PL_ADDF), THEDP, SLOT(PLAppendDialog()) ); popup.addAction( qtr(I_PL_ADDDIR), THEDP, SLOT( PLAppendDir()) ); } else if( ( THEPL->p_ml_category && currentRootId == THEPL->p_ml_category->i_id ) || ( THEPL->p_ml_onelevel && currentRootId == THEPL->p_ml_onelevel->i_id ) ) { popup.addAction( qtr(I_PL_ADDF), THEDP, SLOT( MLAppendDialog() ) ); popup.addAction( qtr(I_PL_ADDDIR), THEDP, SLOT( MLAppendDir() ) ); } popup.exec( QCursor::pos() - addButton->mapFromGlobal( QCursor::pos() ) + QPoint( 0, addButton->height() ) ); } void StandardPLPanel::popupSelectColumn( QPoint pos ) { ContextUpdateMapper = new QSignalMapper(this); QMenu selectColMenu; CONNECT( ContextUpdateMapper, mapped( int ), model, viewchanged( int ) ); int i_column = 1; for( i_column = 1; i_column != COLUMN_END; i_column<<=1 ) { QAction* option = selectColMenu.addAction( qfu( psz_column_title( i_column ) ) ); option->setCheckable( true ); option->setChecked( model->shownFlags() & i_column ); ContextUpdateMapper->setMapping( option, i_column ); CONNECT( option, triggered(), ContextUpdateMapper, map() ); } selectColMenu.exec( QCursor::pos() ); } /* ClearFilter LineEdit */ void StandardPLPanel::clearFilter() { searchLine->setText( "" ); } /* Search in the playlist */ void StandardPLPanel::search( QString searchText ) { model->search( searchText ); } void StandardPLPanel::doPopup( QModelIndex index, QPoint point ) { if( !index.isValid() ) return; QItemSelectionModel *selection = view->selectionModel(); QModelIndexList list = selection->selectedIndexes(); model->popup( index, point, list ); } /* Set the root of the new Playlist */ /* This activated by the selector selection */ void StandardPLPanel::setRoot( int i_root_id ) { QPL_LOCK; playlist_item_t *p_item = playlist_ItemGetById( THEPL, i_root_id, pl_Locked ); assert( p_item ); p_item = playlist_GetPreferredNode( THEPL, p_item ); assert( p_item ); QPL_UNLOCK; model->rebuild( p_item ); } void StandardPLPanel::removeItem( int i_id ) { model->removeItem( i_id ); } /* Delete and Suppr key remove the selection FilterKey function and code function */ void StandardPLPanel::keyPressEvent( QKeyEvent *e ) { switch( e->key() ) { case Qt::Key_Back: case Qt::Key_Delete: deleteSelection(); break; } } void StandardPLPanel::deleteSelection() { QItemSelectionModel *selection = view->selectionModel(); QModelIndexList list = selection->selectedIndexes(); model->doDelete( list ); } StandardPLPanel::~StandardPLPanel() { #if HAS_QT43 getSettings()->beginGroup("Playlist"); getSettings()->setValue( "headerState", view->header()->saveState() ); getSettings()->endGroup(); #endif }
Fix the header menu popup when you have a header-state saved.
[Qt] Fix the header menu popup when you have a header-state saved.
C++
lgpl-2.1
xkfz007/vlc,krichter722/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,xkfz007/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,shyamalschandra/vlc,shyamalschandra/vlc,vlc-mirror/vlc,shyamalschandra/vlc,krichter722/vlc,xkfz007/vlc,jomanmuk/vlc-2.1,krichter722/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc,vlc-mirror/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.1,krichter722/vlc,vlc-mirror/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,krichter722/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,shyamalschandra/vlc,shyamalschandra/vlc,krichter722/vlc,jomanmuk/vlc-2.2,xkfz007/vlc,krichter722/vlc,jomanmuk/vlc-2.2,xkfz007/vlc,xkfz007/vlc,vlc-mirror/vlc,xkfz007/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1
000ebedaed8f4076e698c060a5180c35c798c435
libs/vds_dht_network/impl/udp_transport.cpp
libs/vds_dht_network/impl/udp_transport.cpp
/* Copyright (c) 2017, Vadim Malyshev, [email protected] All rights reserved */ #include "stdafx.h" #include "private/udp_transport.h" #include "messages/dht_route_messages.h" #include "private/dht_session.h" #include "logger.h" #include "dht_network_client.h" #include "dht_network_client_p.h" vds::dht::network::udp_transport::udp_transport(){ } vds::dht::network::udp_transport::~udp_transport() { } void vds::dht::network::udp_transport::start( const service_provider * sp, const std::shared_ptr<certificate> & node_cert, const std::shared_ptr<asymmetric_private_key> & node_key, uint16_t port) { this->send_thread_ = std::make_shared<thread_apartment>(sp); this->sp_ = sp; this->this_node_id_ = node_cert->fingerprint(hash::sha256()); this->node_cert_ = node_cert; this->node_key_ = node_key; try { auto [reader, writer] = this->server_.start(sp, network_address::any_ip6(port)); this->reader_ = reader; this->writer_ = writer; } catch (...) { auto[reader, writer] = this->server_.start(sp, network_address::any_ip4(port)); this->reader_ = reader; this->writer_ = writer; } this->continue_read().detach(); } void vds::dht::network::udp_transport::stop() { this->server_.stop(); } vds::async_task<void> vds::dht::network::udp_transport::write_async( const udp_datagram& datagram) { auto result = std::make_shared<vds::async_result<void>>(); this->send_thread_->schedule([result, this, datagram]() { try{ this->writer_->write_async(datagram).get(); } catch (...){ result->set_exception(std::current_exception()); return; } result->set_value(); }); return result->get_future(); // std::unique_lock<std::debug_mutex> lock(this->write_mutex_); // while(this->write_in_progress_) { // this->write_cond_.wait(*reinterpret_cast<std::unique_lock<std::mutex> *>(&lock)); // } // this->write_in_progress_ = true; //#ifdef _DEBUG //#ifndef _WIN32 // this->owner_id_ = syscall(SYS_gettid); //#else // this->owner_id_ = GetCurrentThreadId(); //#endif //#endif//_DEBUG //co_await this->writer_->write_async(sp, datagram); } vds::async_task<void> vds::dht::network::udp_transport::try_handshake( const std::string& address_str) { auto address = network_address::parse(this->server_.address().family(), address_str); this->sessions_mutex_.lock(); auto p = this->sessions_.find(address); if (this->sessions_.end() == p) { this->sessions_mutex_.unlock(); } else { auto & session_info = p->second; this->sessions_mutex_.unlock(); session_info.session_mutex_.lock(); if (session_info.blocked_) { if ((std::chrono::steady_clock::now() - session_info.update_time_) <= std::chrono::minutes(1)) { session_info.session_mutex_.unlock(); co_return; } } else if(session_info.session_) { session_info.session_mutex_.unlock(); co_return; } session_info.session_mutex_.unlock(); } resizable_data_buffer out_message; out_message.add((uint8_t)protocol_message_type_t::HandshakeBroadcast); out_message.add(MAGIC_LABEL >> 24); out_message.add(MAGIC_LABEL >> 16); out_message.add(MAGIC_LABEL >> 8); out_message.add(MAGIC_LABEL); out_message.add(PROTOCOL_VERSION); binary_serializer bs; bs << this->node_cert_->der(); out_message += bs.move_data(); co_await this->write_async(udp_datagram( address, out_message.move_data(), false)); } vds::async_task<void> vds::dht::network::udp_transport::on_timer() { std::list<std::shared_ptr<dht_session>> sessions; this->sessions_mutex_.lock_shared(); for(auto & p : this->sessions_) { if (p.second.session_) { sessions.push_back(p.second.session_); } } this->sessions_mutex_.unlock_shared(); for(auto & s : sessions) { co_await s->on_timer(this->shared_from_this()); } } void vds::dht::network::udp_transport::get_session_statistics(session_statistic& session_statistic) { session_statistic.output_size_ = this->send_thread_->size(); std::shared_lock<std::shared_mutex> lock(this->sessions_mutex_); for (const auto& p : this->sessions_) { const auto & session = p.second; if (session.session_) { session_statistic.items_.push_back(session.session_->get_statistic()); } } } vds::async_task<void> vds::dht::network::udp_transport::continue_read( ) { for (;;) { udp_datagram datagram; try { datagram = co_await this->reader_->read_async(); } catch(const std::system_error & ex) { continue; } if (this->sp_->get_shutdown_event().is_shuting_down()) { co_return; } this->sessions_mutex_.lock(); auto & session_info = this->sessions_[datagram.address()]; this->sessions_mutex_.unlock(); session_info.session_mutex_.lock(); if (session_info.blocked_) { if ((std::chrono::steady_clock::now() - session_info.update_time_) > std::chrono::minutes(1) && (*datagram.data() == (uint8_t)protocol_message_type_t::Handshake || *datagram.data() == (uint8_t)protocol_message_type_t::HandshakeBroadcast || *datagram.data() == (uint8_t)protocol_message_type_t::Welcome)) { logger::get(this->sp_)->trace(ThisModule, "Unblock session %s", datagram.address().to_string().c_str()); session_info.blocked_ = false; } else { session_info.session_mutex_.unlock(); if (*datagram.data() != (uint8_t)protocol_message_type_t::Failed && *datagram.data() != (uint8_t)protocol_message_type_t::Handshake && *datagram.data() != (uint8_t)protocol_message_type_t::HandshakeBroadcast && *datagram.data() != (uint8_t)protocol_message_type_t::Welcome) { uint8_t out_message[] = { (uint8_t)protocol_message_type_t::Failed }; try { co_await this->write_async(udp_datagram(datagram.address(), const_data_buffer(out_message, sizeof(out_message)))); } catch (...) { } } continue; } } switch ((protocol_message_type_t)datagram.data()[0]) { case protocol_message_type_t::HandshakeBroadcast: case protocol_message_type_t::Handshake: { if (session_info.session_) { session_info.session_mutex_.unlock(); continue; } if ( (uint8_t)(MAGIC_LABEL >> 24) == datagram.data()[1] && (uint8_t)(MAGIC_LABEL >> 16) == datagram.data()[2] && (uint8_t)(MAGIC_LABEL >> 8) == datagram.data()[3] && (uint8_t)(MAGIC_LABEL) == datagram.data()[4] && PROTOCOL_VERSION == datagram.data()[5]) { binary_deserializer bd(datagram.data() + 6, datagram.data_size() - 6); const_data_buffer partner_node_cert_der; bd >> partner_node_cert_der; auto partner_node_cert = certificate::parse_der(partner_node_cert_der); auto partner_node_id = partner_node_cert.fingerprint(hash::sha256()); if (partner_node_id == this->this_node_id_) { session_info.session_mutex_.unlock(); break; } if (!session_info.session_key_ || (std::chrono::steady_clock::now() - session_info.update_time_) > std::chrono::minutes(10)) { session_info.update_time_ = std::chrono::steady_clock::now(); session_info.session_key_.resize(32); crypto_service::rand_bytes(session_info.session_key_.data(), session_info.session_key_.size()); } session_info.session_ = std::make_shared<dht_session>( this->sp_, datagram.address(), this->this_node_id_, partner_node_id, session_info.session_key_); this->sp_->get<logger>()->debug(ThisModule, "Add session %s", datagram.address().to_string().c_str()); (*this->sp_->get<client>())->add_session(session_info.session_, 0); resizable_data_buffer out_message; out_message.add(static_cast<uint8_t>(protocol_message_type_t::Welcome)); out_message.add(MAGIC_LABEL >> 24); out_message.add(MAGIC_LABEL >> 16); out_message.add(MAGIC_LABEL >> 8); out_message.add(MAGIC_LABEL); binary_serializer bs; bs << this->node_cert_->der() << partner_node_cert.public_key().encrypt(session_info.session_key_); session_info.session_mutex_.unlock(); out_message += bs.move_data(); co_await this->write_async(udp_datagram(datagram.address(), out_message.move_data(), false)); co_await (*this->sp_->get<client>())->send_neighbors( message_create<messages::dht_find_node_response>( std::list<messages::dht_find_node_response::target_node>({ messages::dht_find_node_response::target_node(partner_node_id, datagram.address().to_string(), 0) }))); co_await this->sp_->get<imessage_map>()->on_new_session( partner_node_id); } else { session_info.session_mutex_.unlock(); throw std::runtime_error("Invalid protocol"); } break; } case protocol_message_type_t::Welcome: { if (datagram.data_size() > 5 && (uint8_t)(MAGIC_LABEL >> 24) == datagram.data()[1] && (uint8_t)(MAGIC_LABEL >> 16) == datagram.data()[2] && (uint8_t)(MAGIC_LABEL >> 8) == datagram.data()[3] && (uint8_t)(MAGIC_LABEL) == datagram.data()[4]) { const_data_buffer cert_buffer; const_data_buffer key_buffer; binary_deserializer bd(datagram.data() + 5, datagram.data_size() - 5); bd >> cert_buffer >> key_buffer; auto cert = certificate::parse_der(cert_buffer); auto key = this->node_key_->decrypt(key_buffer); auto partner_id = cert.fingerprint(hash::sha256()); //TODO: validate cert auto session = std::make_shared<dht_session>( this->sp_, datagram.address(), this->this_node_id_, partner_id, key); session_info.session_ = session; session_info.session_mutex_.unlock(); this->sp_->get<logger>()->debug(ThisModule, "Add session %s", datagram.address().to_string().c_str()); (*this->sp_->get<client>())->add_session(session, 0); co_await this->sp_->get<imessage_map>()->on_new_session( partner_id); } else { session_info.session_mutex_.unlock(); throw std::runtime_error("Invalid protocol"); } break; } case protocol_message_type_t::Failed: { logger::get(this->sp_)->trace(ThisModule, "Block session %s", datagram.address().to_string().c_str()); (*this->sp_->get<client>())->remove_session(session_info.session_); session_info.blocked_ = true; session_info.session_.reset(); session_info.update_time_ = std::chrono::steady_clock::now(); session_info.session_mutex_.unlock(); break; } default: { if (session_info.session_) { try { auto session = session_info.session_; session_info.session_mutex_.unlock(); bool failed = false; try { co_await session->process_datagram( this->shared_from_this(), const_data_buffer(datagram.data(), datagram.data_size())); } catch (const std::exception & ex) { logger::get(this->sp_)->debug(ThisModule, "%s at process message from %s", ex.what(), datagram.address().to_string().c_str()); failed = true; } if(failed) { session_info.session_mutex_.lock(); logger::get(this->sp_)->trace(ThisModule, "Block session %s", datagram.address().to_string().c_str()); (*this->sp_->get<client>())->remove_session(session_info.session_); session_info.blocked_ = true; session_info.session_.reset(); session_info.update_time_ = std::chrono::steady_clock::now(); session_info.session_mutex_.unlock(); uint8_t out_message[] = { (uint8_t)protocol_message_type_t::Failed }; co_await this->write_async(udp_datagram(datagram.address(), const_data_buffer(out_message, sizeof(out_message)))); } } catch (...) { session_info.session_mutex_.lock(); logger::get(this->sp_)->trace(ThisModule, "Block session %s", datagram.address().to_string().c_str()); (*this->sp_->get<client>())->remove_session(session_info.session_); session_info.blocked_ = true; session_info.session_.reset(); session_info.update_time_ = std::chrono::steady_clock::now(); session_info.session_mutex_.unlock(); } } else { logger::get(this->sp_)->trace(ThisModule, "Block session %s", datagram.address().to_string().c_str()); (*this->sp_->get<client>())->remove_session(session_info.session_); session_info.blocked_ = true; session_info.session_.reset(); session_info.update_time_ = std::chrono::steady_clock::now(); session_info.session_mutex_.unlock(); uint8_t out_message[] = { (uint8_t)protocol_message_type_t::Failed }; try { co_await this->write_async(udp_datagram(datagram.address(), const_data_buffer(out_message, sizeof(out_message)))); } catch (...) { } } break; } } } }
/* Copyright (c) 2017, Vadim Malyshev, [email protected] All rights reserved */ #include "stdafx.h" #include "private/udp_transport.h" #include "messages/dht_route_messages.h" #include "private/dht_session.h" #include "logger.h" #include "dht_network_client.h" #include "dht_network_client_p.h" vds::dht::network::udp_transport::udp_transport(){ } vds::dht::network::udp_transport::~udp_transport() { } void vds::dht::network::udp_transport::start( const service_provider * sp, const std::shared_ptr<certificate> & node_cert, const std::shared_ptr<asymmetric_private_key> & node_key, uint16_t port) { this->send_thread_ = std::make_shared<thread_apartment>(sp); this->sp_ = sp; this->this_node_id_ = node_cert->fingerprint(hash::sha256()); this->node_cert_ = node_cert; this->node_key_ = node_key; try { auto [reader, writer] = this->server_.start(sp, network_address::any_ip6(port)); this->reader_ = reader; this->writer_ = writer; } catch (...) { auto[reader, writer] = this->server_.start(sp, network_address::any_ip4(port)); this->reader_ = reader; this->writer_ = writer; } this->continue_read().detach(); } void vds::dht::network::udp_transport::stop() { this->server_.stop(); } vds::async_task<void> vds::dht::network::udp_transport::write_async( const udp_datagram& datagram) { auto result = std::make_shared<vds::async_result<void>>(); this->send_thread_->schedule([result, this, datagram]() { try{ this->writer_->write_async(datagram).get(); } catch (...){ result->set_exception(std::current_exception()); return; } result->set_value(); }); return result->get_future(); // std::unique_lock<std::debug_mutex> lock(this->write_mutex_); // while(this->write_in_progress_) { // this->write_cond_.wait(*reinterpret_cast<std::unique_lock<std::mutex> *>(&lock)); // } // this->write_in_progress_ = true; //#ifdef _DEBUG //#ifndef _WIN32 // this->owner_id_ = syscall(SYS_gettid); //#else // this->owner_id_ = GetCurrentThreadId(); //#endif //#endif//_DEBUG //co_await this->writer_->write_async(sp, datagram); } vds::async_task<void> vds::dht::network::udp_transport::try_handshake( const std::string& address_str) { auto address = network_address::parse(this->server_.address().family(), address_str); this->sessions_mutex_.lock(); auto p = this->sessions_.find(address); if (this->sessions_.end() == p) { this->sessions_mutex_.unlock(); } else { auto & session_info = p->second; this->sessions_mutex_.unlock(); session_info.session_mutex_.lock(); if (session_info.blocked_) { if ((std::chrono::steady_clock::now() - session_info.update_time_) <= std::chrono::minutes(1)) { session_info.session_mutex_.unlock(); co_return; } } else if(session_info.session_) { session_info.session_mutex_.unlock(); co_return; } session_info.session_mutex_.unlock(); } resizable_data_buffer out_message; out_message.add((uint8_t)protocol_message_type_t::HandshakeBroadcast); out_message.add(MAGIC_LABEL >> 24); out_message.add(MAGIC_LABEL >> 16); out_message.add(MAGIC_LABEL >> 8); out_message.add(MAGIC_LABEL); out_message.add(PROTOCOL_VERSION); binary_serializer bs; bs << this->node_cert_->der(); out_message += bs.move_data(); co_await this->write_async(udp_datagram( address, out_message.move_data(), false)); } vds::async_task<void> vds::dht::network::udp_transport::on_timer() { std::list<std::shared_ptr<dht_session>> sessions; this->sessions_mutex_.lock_shared(); for(auto & p : this->sessions_) { if (p.second.session_) { sessions.push_back(p.second.session_); } } this->sessions_mutex_.unlock_shared(); for(auto & s : sessions) { co_await s->on_timer(this->shared_from_this()); } } void vds::dht::network::udp_transport::get_session_statistics(session_statistic& session_statistic) { session_statistic.output_size_ = this->send_thread_->size(); std::shared_lock<std::shared_mutex> lock(this->sessions_mutex_); for (const auto& p : this->sessions_) { const auto & session = p.second; if (session.session_) { session_statistic.items_.push_back(session.session_->get_statistic()); } } } vds::async_task<void> vds::dht::network::udp_transport::continue_read( ) { for (;;) { udp_datagram datagram; try { datagram = co_await this->reader_->read_async(); } catch(const std::system_error & ex) { continue; } if (this->sp_->get_shutdown_event().is_shuting_down()) { co_return; } this->sessions_mutex_.lock(); auto & session_info = this->sessions_[datagram.address()]; this->sessions_mutex_.unlock(); session_info.session_mutex_.lock(); if (session_info.blocked_) { if ((std::chrono::steady_clock::now() - session_info.update_time_) > std::chrono::minutes(1) && (*datagram.data() == (uint8_t)protocol_message_type_t::Handshake || *datagram.data() == (uint8_t)protocol_message_type_t::HandshakeBroadcast || *datagram.data() == (uint8_t)protocol_message_type_t::Welcome)) { logger::get(this->sp_)->trace(ThisModule, "Unblock session %s", datagram.address().to_string().c_str()); session_info.blocked_ = false; } else { session_info.session_mutex_.unlock(); if (*datagram.data() != (uint8_t)protocol_message_type_t::Failed && *datagram.data() != (uint8_t)protocol_message_type_t::Handshake && *datagram.data() != (uint8_t)protocol_message_type_t::HandshakeBroadcast && *datagram.data() != (uint8_t)protocol_message_type_t::Welcome) { uint8_t out_message[] = { (uint8_t)protocol_message_type_t::Failed }; try { co_await this->write_async(udp_datagram(datagram.address(), const_data_buffer(out_message, sizeof(out_message)))); } catch (...) { } } continue; } } switch ((protocol_message_type_t)datagram.data()[0]) { case protocol_message_type_t::HandshakeBroadcast: case protocol_message_type_t::Handshake: { if (session_info.session_) { session_info.session_mutex_.unlock(); continue; } if ( (uint8_t)(MAGIC_LABEL >> 24) == datagram.data()[1] && (uint8_t)(MAGIC_LABEL >> 16) == datagram.data()[2] && (uint8_t)(MAGIC_LABEL >> 8) == datagram.data()[3] && (uint8_t)(MAGIC_LABEL) == datagram.data()[4] && PROTOCOL_VERSION == datagram.data()[5]) { binary_deserializer bd(datagram.data() + 6, datagram.data_size() - 6); const_data_buffer partner_node_cert_der; bd >> partner_node_cert_der; auto partner_node_cert = certificate::parse_der(partner_node_cert_der); auto partner_node_id = partner_node_cert.fingerprint(hash::sha256()); if (partner_node_id == this->this_node_id_) { session_info.session_mutex_.unlock(); break; } if (!session_info.session_key_ || (std::chrono::steady_clock::now() - session_info.update_time_) > std::chrono::minutes(10)) { session_info.update_time_ = std::chrono::steady_clock::now(); session_info.session_key_.resize(32); crypto_service::rand_bytes(session_info.session_key_.data(), session_info.session_key_.size()); } session_info.session_ = std::make_shared<dht_session>( this->sp_, datagram.address(), this->this_node_id_, partner_node_id, session_info.session_key_); this->sp_->get<logger>()->debug(ThisModule, "Add session %s", datagram.address().to_string().c_str()); (*this->sp_->get<client>())->add_session(session_info.session_, 0); resizable_data_buffer out_message; out_message.add(static_cast<uint8_t>(protocol_message_type_t::Welcome)); out_message.add(MAGIC_LABEL >> 24); out_message.add(MAGIC_LABEL >> 16); out_message.add(MAGIC_LABEL >> 8); out_message.add(MAGIC_LABEL); binary_serializer bs; bs << this->node_cert_->der() << partner_node_cert.public_key().encrypt(session_info.session_key_); session_info.session_mutex_.unlock(); out_message += bs.move_data(); co_await this->write_async(udp_datagram(datagram.address(), out_message.move_data(), false)); co_await this->sp_->get<imessage_map>()->on_new_session(partner_node_id); } else { session_info.session_mutex_.unlock(); throw std::runtime_error("Invalid protocol"); } break; } case protocol_message_type_t::Welcome: { if (datagram.data_size() > 5 && (uint8_t)(MAGIC_LABEL >> 24) == datagram.data()[1] && (uint8_t)(MAGIC_LABEL >> 16) == datagram.data()[2] && (uint8_t)(MAGIC_LABEL >> 8) == datagram.data()[3] && (uint8_t)(MAGIC_LABEL) == datagram.data()[4]) { const_data_buffer cert_buffer; const_data_buffer key_buffer; binary_deserializer bd(datagram.data() + 5, datagram.data_size() - 5); bd >> cert_buffer >> key_buffer; auto cert = certificate::parse_der(cert_buffer); auto key = this->node_key_->decrypt(key_buffer); auto partner_id = cert.fingerprint(hash::sha256()); //TODO: validate cert auto session = std::make_shared<dht_session>( this->sp_, datagram.address(), this->this_node_id_, partner_id, key); session_info.session_ = session; session_info.session_mutex_.unlock(); this->sp_->get<logger>()->debug(ThisModule, "Add session %s", datagram.address().to_string().c_str()); (*this->sp_->get<client>())->add_session(session, 0); co_await this->sp_->get<imessage_map>()->on_new_session( partner_id); } else { session_info.session_mutex_.unlock(); throw std::runtime_error("Invalid protocol"); } break; } case protocol_message_type_t::Failed: { logger::get(this->sp_)->trace(ThisModule, "Block session %s", datagram.address().to_string().c_str()); (*this->sp_->get<client>())->remove_session(session_info.session_); session_info.blocked_ = true; session_info.session_.reset(); session_info.update_time_ = std::chrono::steady_clock::now(); session_info.session_mutex_.unlock(); break; } default: { if (session_info.session_) { try { auto session = session_info.session_; session_info.session_mutex_.unlock(); bool failed = false; try { co_await session->process_datagram( this->shared_from_this(), const_data_buffer(datagram.data(), datagram.data_size())); } catch (const std::exception & ex) { logger::get(this->sp_)->debug(ThisModule, "%s at process message from %s", ex.what(), datagram.address().to_string().c_str()); failed = true; } if(failed) { session_info.session_mutex_.lock(); logger::get(this->sp_)->trace(ThisModule, "Block session %s", datagram.address().to_string().c_str()); (*this->sp_->get<client>())->remove_session(session_info.session_); session_info.blocked_ = true; session_info.session_.reset(); session_info.update_time_ = std::chrono::steady_clock::now(); session_info.session_mutex_.unlock(); uint8_t out_message[] = { (uint8_t)protocol_message_type_t::Failed }; co_await this->write_async(udp_datagram(datagram.address(), const_data_buffer(out_message, sizeof(out_message)))); } } catch (...) { session_info.session_mutex_.lock(); logger::get(this->sp_)->trace(ThisModule, "Block session %s", datagram.address().to_string().c_str()); (*this->sp_->get<client>())->remove_session(session_info.session_); session_info.blocked_ = true; session_info.session_.reset(); session_info.update_time_ = std::chrono::steady_clock::now(); session_info.session_mutex_.unlock(); } } else { logger::get(this->sp_)->trace(ThisModule, "Block session %s", datagram.address().to_string().c_str()); (*this->sp_->get<client>())->remove_session(session_info.session_); session_info.blocked_ = true; session_info.session_.reset(); session_info.update_time_ = std::chrono::steady_clock::now(); session_info.session_mutex_.unlock(); uint8_t out_message[] = { (uint8_t)protocol_message_type_t::Failed }; try { co_await this->write_async(udp_datagram(datagram.address(), const_data_buffer(out_message, sizeof(out_message)))); } catch (...) { } } break; } } } }
change UDP MTU size
change UDP MTU size
C++
mit
lboss75/vds,lboss75/vds,lboss75/vds,lboss75/vds,lboss75/vds,lboss75/vds,lboss75/vds,lboss75/vds
41c12703f9d520844ce7c6f39785dddbf337bdc9
libcaf_core/caf/optional.hpp
libcaf_core/caf/optional.hpp
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2014 * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #pragma once #include <memory> #include <new> #include <utility> #include "caf/none.hpp" #include "caf/unit.hpp" #include "caf/config.hpp" #include "caf/deep_to_string.hpp" #include "caf/detail/safe_equal.hpp" #include "caf/detail/scope_guard.hpp" namespace caf { /// A C++17 compatible `optional` implementation. template <class T> class optional { public: /// Typdef for `T`. using type = T; /// Creates an instance without value. optional(const none_t& = none) : m_valid(false) { // nop } /// Creates an valid instance from `value`. template <class U, class E = typename std::enable_if< std::is_convertible<U, T>::value >::type> optional(U x) : m_valid(false) { cr(std::move(x)); } optional(const optional& other) : m_valid(false) { if (other.m_valid) { cr(other.m_value); } } optional(optional&& other) noexcept(std::is_nothrow_move_constructible<T>::value) : m_valid(false) { if (other.m_valid) { cr(std::move(other.m_value)); } } ~optional() { destroy(); } optional& operator=(const optional& other) { if (m_valid) { if (other.m_valid) m_value = other.m_value; else destroy(); } else if (other.m_valid) { cr(other.m_value); } return *this; } optional& operator=(optional&& other) noexcept(std::is_nothrow_destructible<T>::value && std::is_nothrow_move_assignable<T>::value) { if (m_valid) { if (other.m_valid) m_value = std::move(other.m_value); else destroy(); } else if (other.m_valid) { cr(std::move(other.m_value)); } return *this; } /// Checks whether this object contains a value. explicit operator bool() const { return m_valid; } /// Checks whether this object does not contain a value. bool operator!() const { return !m_valid; } /// Returns the value. T& operator*() { CAF_ASSERT(m_valid); return m_value; } /// Returns the value. const T& operator*() const { CAF_ASSERT(m_valid); return m_value; } /// Returns the value. const T* operator->() const { CAF_ASSERT(m_valid); return &m_value; } /// Returns the value. T* operator->() { CAF_ASSERT(m_valid); return &m_value; } /// Returns the value. T& value() { CAF_ASSERT(m_valid); return m_value; } /// Returns the value. const T& value() const { CAF_ASSERT(m_valid); return m_value; } /// Returns the value if `m_valid`, otherwise returns `default_value`. const T& value_or(const T& default_value) const { return m_valid ? value() : default_value; } private: void destroy() { if (m_valid) { m_value.~T(); m_valid = false; } } template <class V> void cr(V&& x) { CAF_ASSERT(!m_valid); m_valid = true; new (std::addressof(m_value)) T(std::forward<V>(x)); } bool m_valid; union { T m_value; }; }; /// Template specialization to allow `optional` to hold a reference /// rather than an actual value with minimal overhead. template <class T> class optional<T&> { public: using type = T; optional(const none_t& = none) : m_value(nullptr) { // nop } optional(T& x) : m_value(&x) { // nop } optional(T* x) : m_value(x) { // nop } optional(const optional& other) = default; optional& operator=(const optional& other) = default; explicit operator bool() const { return m_value != nullptr; } bool operator!() const { return !m_value; } T& operator*() { CAF_ASSERT(m_value); return *m_value; } const T& operator*() const { CAF_ASSERT(m_value); return *m_value; } T* operator->() { CAF_ASSERT(m_value); return m_value; } const T* operator->() const { CAF_ASSERT(m_value); return m_value; } T& value() { CAF_ASSERT(m_value); return *m_value; } const T& value() const { CAF_ASSERT(m_value); return *m_value; } const T& value_or(const T& default_value) const { if (m_value) return value(); return default_value; } private: T* m_value; }; template <> class optional<void> { public: using type = unit_t; optional(none_t = none) : m_value(false) { // nop } optional(unit_t) : m_value(true) { // nop } optional(const optional& other) = default; optional& operator=(const optional& other) = default; explicit operator bool() const { return m_value; } bool operator!() const { return !m_value; } private: bool m_value; }; template <class Inspector, class T> typename std::enable_if<Inspector::reads_state, typename Inspector::result_type>::type inspect(Inspector& f, optional<T>& x) { return x ? f(true, *x) : f(false); } template <class T> struct optional_inspect_helper { bool& enabled; T& storage; template <class Inspector> friend typename Inspector::result_type inspect(Inspector& f, optional_inspect_helper& x) { return x.enabled ? f(x.storage) : f(); } }; template <class Inspector, class T> typename std::enable_if<Inspector::writes_state, typename Inspector::result_type>::type inspect(Inspector& f, optional<T>& x) { bool flag; typename optional<T>::type tmp; optional_inspect_helper<T> helper{flag, tmp}; auto guard = detail::make_scope_guard([&] { if (flag) x = std::move(tmp); else x = none; }); return f(flag, helper); } /// @relates optional template <class T> std::string to_string(const optional<T>& x) { return x ? "*" + deep_to_string(*x) : "none"; } // -- [X.Y.8] comparison with optional ---------------------------------------- /// @relates optional template <class T> bool operator==(const optional<T>& lhs, const optional<T>& rhs) { return static_cast<bool>(lhs) == static_cast<bool>(rhs) && (!lhs || *lhs == *rhs); } /// @relates optional template <class T> bool operator!=(const optional<T>& lhs, const optional<T>& rhs) { return !(lhs == rhs); } /// @relates optional template <class T> bool operator<(const optional<T>& lhs, const optional<T>& rhs) { return static_cast<bool>(rhs) && (!lhs || *lhs < *rhs); } /// @relates optional template <class T> bool operator<=(const optional<T>& lhs, const optional<T>& rhs) { return !(rhs < lhs); } /// @relates optional template <class T> bool operator>=(const optional<T>& lhs, const optional<T>& rhs) { return !(lhs < rhs); } /// @relates optional template <class T> bool operator>(const optional<T>& lhs, const optional<T>& rhs) { return rhs < lhs; } // -- [X.Y.9] comparison with none_t (aka. nullopt_t) ------------------------- /// @relates optional template <class T> bool operator==(const optional<T>& lhs, none_t) { return !lhs; } /// @relates optional template <class T> bool operator==(none_t, const optional<T>& rhs) { return !rhs; } /// @relates optional template <class T> bool operator!=(const optional<T>& lhs, none_t) { return static_cast<bool>(lhs); } /// @relates optional template <class T> bool operator!=(none_t, const optional<T>& rhs) { return static_cast<bool>(rhs); } /// @relates optional template <class T> bool operator<(const optional<T>&, none_t) { return false; } /// @relates optional template <class T> bool operator<(none_t, const optional<T>& rhs) { return static_cast<bool>(rhs); } /// @relates optional template <class T> bool operator<=(const optional<T>& lhs, none_t) { return !lhs; } /// @relates optional template <class T> bool operator<=(none_t, const optional<T>&) { return true; } /// @relates optional template <class T> bool operator>(const optional<T>& lhs, none_t) { return static_cast<bool>(lhs); } /// @relates optional template <class T> bool operator>(none_t, const optional<T>&) { return false; } /// @relates optional template <class T> bool operator>=(const optional<T>&, none_t) { return true; } /// @relates optional template <class T> bool operator>=(none_t, const optional<T>&) { return true; } // -- [X.Y.10] comparison with value type ------------------------------------ /// @relates optional template <class T> bool operator==(const optional<T>& lhs, const T& rhs) { return lhs && *lhs == rhs; } /// @relates optional template <class T> bool operator==(const T& lhs, const optional<T>& rhs) { return rhs && lhs == *rhs; } /// @relates optional template <class T> bool operator!=(const optional<T>& lhs, const T& rhs) { return !lhs || !(*lhs == rhs); } /// @relates optional template <class T> bool operator!=(const T& lhs, const optional<T>& rhs) { return !rhs || !(lhs == *rhs); } /// @relates optional template <class T> bool operator<(const optional<T>& lhs, const T& rhs) { return !lhs || *lhs < rhs; } /// @relates optional template <class T> bool operator<(const T& lhs, const optional<T>& rhs) { return rhs && lhs < *rhs; } /// @relates optional template <class T> bool operator<=(const optional<T>& lhs, const T& rhs) { return !lhs || !(rhs < *lhs); } /// @relates optional template <class T> bool operator<=(const T& lhs, const optional<T>& rhs) { return rhs && !(rhs < lhs); } /// @relates optional template <class T> bool operator>(const optional<T>& lhs, const T& rhs) { return lhs && rhs < *lhs; } /// @relates optional template <class T> bool operator>(const T& lhs, const optional<T>& rhs) { return !rhs || *rhs < lhs; } /// @relates optional template <class T> bool operator>=(const optional<T>& lhs, const T& rhs) { return lhs && !(*lhs < rhs); } /// @relates optional template <class T> bool operator>=(const T& lhs, const optional<T>& rhs) { return !rhs || !(lhs < *rhs); } } // namespace caf
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2014 * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #pragma once #include <memory> #include <new> #include <utility> #include "caf/none.hpp" #include "caf/unit.hpp" #include "caf/config.hpp" #include "caf/deep_to_string.hpp" #include "caf/detail/safe_equal.hpp" #include "caf/detail/scope_guard.hpp" namespace caf { /// A C++17 compatible `optional` implementation. template <class T> class optional { public: /// Typdef for `T`. using type = T; /// Creates an instance without value. optional(const none_t& = none) : m_valid(false) { // nop } /// Creates an valid instance from `value`. template <class U, class E = typename std::enable_if< std::is_convertible<U, T>::value >::type> optional(U x) : m_valid(false) { cr(std::move(x)); } optional(const optional& other) : m_valid(false) { if (other.m_valid) { cr(other.m_value); } } optional(optional&& other) noexcept(std::is_nothrow_move_constructible<T>::value) : m_valid(false) { if (other.m_valid) { cr(std::move(other.m_value)); } } ~optional() { destroy(); } optional& operator=(const optional& other) { if (m_valid) { if (other.m_valid) m_value = other.m_value; else destroy(); } else if (other.m_valid) { cr(other.m_value); } return *this; } optional& operator=(optional&& other) noexcept(std::is_nothrow_destructible<T>::value && std::is_nothrow_move_assignable<T>::value) { if (m_valid) { if (other.m_valid) m_value = std::move(other.m_value); else destroy(); } else if (other.m_valid) { cr(std::move(other.m_value)); } return *this; } /// Checks whether this object contains a value. explicit operator bool() const { return m_valid; } /// Checks whether this object does not contain a value. bool operator!() const { return !m_valid; } /// Returns the value. T& operator*() { CAF_ASSERT(m_valid); return m_value; } /// Returns the value. const T& operator*() const { CAF_ASSERT(m_valid); return m_value; } /// Returns the value. const T* operator->() const { CAF_ASSERT(m_valid); return &m_value; } /// Returns the value. T* operator->() { CAF_ASSERT(m_valid); return &m_value; } /// Returns the value. T& value() { CAF_ASSERT(m_valid); return m_value; } /// Returns the value. const T& value() const { CAF_ASSERT(m_valid); return m_value; } /// Returns the value if `m_valid`, otherwise returns `default_value`. const T& value_or(const T& default_value) const { return m_valid ? value() : default_value; } private: void destroy() { if (m_valid) { m_value.~T(); m_valid = false; } } template <class V> void cr(V&& x) { CAF_ASSERT(!m_valid); m_valid = true; new (std::addressof(m_value)) T(std::forward<V>(x)); } bool m_valid; union { T m_value; }; }; /// Template specialization to allow `optional` to hold a reference /// rather than an actual value with minimal overhead. template <class T> class optional<T&> { public: using type = T; optional(const none_t& = none) : m_value(nullptr) { // nop } optional(T& x) : m_value(&x) { // nop } optional(T* x) : m_value(x) { // nop } optional(const optional& other) = default; optional& operator=(const optional& other) = default; explicit operator bool() const { return m_value != nullptr; } bool operator!() const { return !m_value; } T& operator*() { CAF_ASSERT(m_value); return *m_value; } const T& operator*() const { CAF_ASSERT(m_value); return *m_value; } T* operator->() { CAF_ASSERT(m_value); return m_value; } const T* operator->() const { CAF_ASSERT(m_value); return m_value; } T& value() { CAF_ASSERT(m_value); return *m_value; } const T& value() const { CAF_ASSERT(m_value); return *m_value; } const T& value_or(const T& default_value) const { if (m_value) return value(); return default_value; } private: T* m_value; }; template <> class optional<void> { public: using type = unit_t; optional(none_t = none) : m_value(false) { // nop } optional(unit_t) : m_value(true) { // nop } optional(const optional& other) = default; optional& operator=(const optional& other) = default; explicit operator bool() const { return m_value; } bool operator!() const { return !m_value; } private: bool m_value; }; template <class Inspector, class T> typename std::enable_if<Inspector::reads_state, typename Inspector::result_type>::type inspect(Inspector& f, optional<T>& x) { return x ? f(true, *x) : f(false); } template <class T> struct optional_inspect_helper { bool& enabled; T& storage; template <class Inspector> friend typename Inspector::result_type inspect(Inspector& f, optional_inspect_helper& x) { return x.enabled ? f(x.storage) : f(); } }; template <class Inspector, class T> typename std::enable_if<Inspector::writes_state, typename Inspector::result_type>::type inspect(Inspector& f, optional<T>& x) { bool flag = false; typename optional<T>::type tmp{}; optional_inspect_helper<T> helper{flag, tmp}; auto guard = detail::make_scope_guard([&] { if (flag) x = std::move(tmp); else x = none; }); return f(flag, helper); } /// @relates optional template <class T> std::string to_string(const optional<T>& x) { return x ? "*" + deep_to_string(*x) : "none"; } // -- [X.Y.8] comparison with optional ---------------------------------------- /// @relates optional template <class T> bool operator==(const optional<T>& lhs, const optional<T>& rhs) { return static_cast<bool>(lhs) == static_cast<bool>(rhs) && (!lhs || *lhs == *rhs); } /// @relates optional template <class T> bool operator!=(const optional<T>& lhs, const optional<T>& rhs) { return !(lhs == rhs); } /// @relates optional template <class T> bool operator<(const optional<T>& lhs, const optional<T>& rhs) { return static_cast<bool>(rhs) && (!lhs || *lhs < *rhs); } /// @relates optional template <class T> bool operator<=(const optional<T>& lhs, const optional<T>& rhs) { return !(rhs < lhs); } /// @relates optional template <class T> bool operator>=(const optional<T>& lhs, const optional<T>& rhs) { return !(lhs < rhs); } /// @relates optional template <class T> bool operator>(const optional<T>& lhs, const optional<T>& rhs) { return rhs < lhs; } // -- [X.Y.9] comparison with none_t (aka. nullopt_t) ------------------------- /// @relates optional template <class T> bool operator==(const optional<T>& lhs, none_t) { return !lhs; } /// @relates optional template <class T> bool operator==(none_t, const optional<T>& rhs) { return !rhs; } /// @relates optional template <class T> bool operator!=(const optional<T>& lhs, none_t) { return static_cast<bool>(lhs); } /// @relates optional template <class T> bool operator!=(none_t, const optional<T>& rhs) { return static_cast<bool>(rhs); } /// @relates optional template <class T> bool operator<(const optional<T>&, none_t) { return false; } /// @relates optional template <class T> bool operator<(none_t, const optional<T>& rhs) { return static_cast<bool>(rhs); } /// @relates optional template <class T> bool operator<=(const optional<T>& lhs, none_t) { return !lhs; } /// @relates optional template <class T> bool operator<=(none_t, const optional<T>&) { return true; } /// @relates optional template <class T> bool operator>(const optional<T>& lhs, none_t) { return static_cast<bool>(lhs); } /// @relates optional template <class T> bool operator>(none_t, const optional<T>&) { return false; } /// @relates optional template <class T> bool operator>=(const optional<T>&, none_t) { return true; } /// @relates optional template <class T> bool operator>=(none_t, const optional<T>&) { return true; } // -- [X.Y.10] comparison with value type ------------------------------------ /// @relates optional template <class T> bool operator==(const optional<T>& lhs, const T& rhs) { return lhs && *lhs == rhs; } /// @relates optional template <class T> bool operator==(const T& lhs, const optional<T>& rhs) { return rhs && lhs == *rhs; } /// @relates optional template <class T> bool operator!=(const optional<T>& lhs, const T& rhs) { return !lhs || !(*lhs == rhs); } /// @relates optional template <class T> bool operator!=(const T& lhs, const optional<T>& rhs) { return !rhs || !(lhs == *rhs); } /// @relates optional template <class T> bool operator<(const optional<T>& lhs, const T& rhs) { return !lhs || *lhs < rhs; } /// @relates optional template <class T> bool operator<(const T& lhs, const optional<T>& rhs) { return rhs && lhs < *rhs; } /// @relates optional template <class T> bool operator<=(const optional<T>& lhs, const T& rhs) { return !lhs || !(rhs < *lhs); } /// @relates optional template <class T> bool operator<=(const T& lhs, const optional<T>& rhs) { return rhs && !(rhs < lhs); } /// @relates optional template <class T> bool operator>(const optional<T>& lhs, const T& rhs) { return lhs && rhs < *lhs; } /// @relates optional template <class T> bool operator>(const T& lhs, const optional<T>& rhs) { return !rhs || *rhs < lhs; } /// @relates optional template <class T> bool operator>=(const optional<T>& lhs, const T& rhs) { return lhs && !(*lhs < rhs); } /// @relates optional template <class T> bool operator>=(const T& lhs, const optional<T>& rhs) { return !rhs || !(lhs < *rhs); } } // namespace caf
Initialize temporaries in optional's inspect
Initialize temporaries in optional's inspect
C++
bsd-3-clause
actor-framework/actor-framework,DavadDi/actor-framework,DavadDi/actor-framework,actor-framework/actor-framework,DavadDi/actor-framework,DavadDi/actor-framework,actor-framework/actor-framework,actor-framework/actor-framework
8c366626269a9225311fc2eeff8c0ffcddc31d1a
fml/message_loop_task_queues_unittests.cc
fml/message_loop_task_queues_unittests.cc
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #define FML_USED_ON_EMBEDDER #include "flutter/fml/message_loop_task_queues.h" #include <thread> #include "flutter/fml/synchronization/count_down_latch.h" #include "flutter/fml/synchronization/waitable_event.h" #include "gtest/gtest.h" namespace fml { namespace testing { class TestWakeable : public fml::Wakeable { public: using WakeUpCall = std::function<void(const fml::TimePoint)>; explicit TestWakeable(WakeUpCall call) : wake_up_call_(call) {} void WakeUp(fml::TimePoint time_point) override { wake_up_call_(time_point); } private: WakeUpCall wake_up_call_; }; TEST(MessageLoopTaskQueue, StartsWithNoPendingTasks) { auto task_queue = fml::MessageLoopTaskQueues::GetInstance(); auto queue_id = task_queue->CreateTaskQueue(); ASSERT_FALSE(task_queue->HasPendingTasks(queue_id)); } TEST(MessageLoopTaskQueue, RegisterOneTask) { const auto time = fml::TimePoint::Max(); auto task_queue = fml::MessageLoopTaskQueues::GetInstance(); auto queue_id = task_queue->CreateTaskQueue(); task_queue->SetWakeable(queue_id, new TestWakeable([&time](fml::TimePoint wake_time) { ASSERT_TRUE(wake_time == time); })); task_queue->RegisterTask( queue_id, [] {}, time); ASSERT_TRUE(task_queue->HasPendingTasks(queue_id)); ASSERT_TRUE(task_queue->GetNumPendingTasks(queue_id) == 1); } TEST(MessageLoopTaskQueue, RegisterTwoTasksAndCount) { auto task_queue = fml::MessageLoopTaskQueues::GetInstance(); auto queue_id = task_queue->CreateTaskQueue(); task_queue->RegisterTask( queue_id, [] {}, fml::TimePoint::Now()); task_queue->RegisterTask( queue_id, [] {}, fml::TimePoint::Max()); ASSERT_TRUE(task_queue->HasPendingTasks(queue_id)); ASSERT_TRUE(task_queue->GetNumPendingTasks(queue_id) == 2); } TEST(MessageLoopTaskQueue, PreserveTaskOrdering) { auto task_queue = fml::MessageLoopTaskQueues::GetInstance(); auto queue_id = task_queue->CreateTaskQueue(); int test_val = 0; // order: 0 task_queue->RegisterTask( queue_id, [&test_val]() { test_val = 1; }, fml::TimePoint::Now()); // order: 1 task_queue->RegisterTask( queue_id, [&test_val]() { test_val = 2; }, fml::TimePoint::Now()); const auto now = fml::TimePoint::Now(); int expected_value = 1; for (;;) { fml::closure invocation = task_queue->GetNextTaskToRun(queue_id, now); if (!invocation) { break; } invocation(); ASSERT_TRUE(test_val == expected_value); expected_value++; } } void TestNotifyObservers(fml::TaskQueueId queue_id) { auto task_queue = fml::MessageLoopTaskQueues::GetInstance(); std::vector<fml::closure> observers = task_queue->GetObserversToNotify(queue_id); for (const auto& observer : observers) { observer(); } } TEST(MessageLoopTaskQueue, AddRemoveNotifyObservers) { auto task_queue = fml::MessageLoopTaskQueues::GetInstance(); auto queue_id = task_queue->CreateTaskQueue(); int test_val = 0; intptr_t key = 123; task_queue->AddTaskObserver(queue_id, key, [&test_val]() { test_val = 1; }); TestNotifyObservers(queue_id); ASSERT_TRUE(test_val == 1); test_val = 0; task_queue->RemoveTaskObserver(queue_id, key); TestNotifyObservers(queue_id); ASSERT_TRUE(test_val == 0); } TEST(MessageLoopTaskQueue, WakeUpIndependentOfTime) { auto task_queue = fml::MessageLoopTaskQueues::GetInstance(); auto queue_id = task_queue->CreateTaskQueue(); int num_wakes = 0; task_queue->SetWakeable( queue_id, new TestWakeable( [&num_wakes](fml::TimePoint wake_time) { ++num_wakes; })); task_queue->RegisterTask( queue_id, []() {}, fml::TimePoint::Now()); task_queue->RegisterTask( queue_id, []() {}, fml::TimePoint::Max()); ASSERT_TRUE(num_wakes == 2); } TEST(MessageLoopTaskQueue, WokenUpWithNewerTime) { auto task_queue = fml::MessageLoopTaskQueues::GetInstance(); auto queue_id = task_queue->CreateTaskQueue(); fml::CountDownLatch latch(2); fml::TimePoint expected = fml::TimePoint::Max(); task_queue->SetWakeable( queue_id, new TestWakeable([&latch, &expected](fml::TimePoint wake_time) { ASSERT_TRUE(wake_time == expected); latch.CountDown(); })); task_queue->RegisterTask( queue_id, []() {}, fml::TimePoint::Max()); const auto now = fml::TimePoint::Now(); expected = now; task_queue->RegisterTask( queue_id, []() {}, now); latch.Wait(); } TEST(MessageLoopTaskQueue, NotifyObserversWhileCreatingQueues) { auto task_queues = fml::MessageLoopTaskQueues::GetInstance(); fml::TaskQueueId queue_id = task_queues->CreateTaskQueue(); fml::AutoResetWaitableEvent first_observer_executing, before_second_observer; task_queues->AddTaskObserver(queue_id, queue_id + 1, [&]() { first_observer_executing.Signal(); before_second_observer.Wait(); }); for (int i = 0; i < 100; i++) { task_queues->AddTaskObserver(queue_id, queue_id + i + 2, [] {}); } std::thread notify_observers([&]() { TestNotifyObservers(queue_id); }); first_observer_executing.Wait(); for (int i = 0; i < 100; i++) { task_queues->CreateTaskQueue(); } before_second_observer.Signal(); notify_observers.join(); } TEST(MessageLoopTaskQueue, QueueDoNotOwnItself) { auto task_queue = fml::MessageLoopTaskQueues::GetInstance(); auto queue_id = task_queue->CreateTaskQueue(); ASSERT_FALSE(task_queue->Owns(queue_id, queue_id)); } TEST(MessageLoopTaskQueue, QueueDoNotOwnUnmergedTaskQueueId) { auto task_queue = fml::MessageLoopTaskQueues::GetInstance(); ASSERT_FALSE(task_queue->Owns(task_queue->CreateTaskQueue(), _kUnmerged)); ASSERT_FALSE(task_queue->Owns(_kUnmerged, task_queue->CreateTaskQueue())); ASSERT_FALSE(task_queue->Owns(_kUnmerged, _kUnmerged)); } // TODO(chunhtai): This unit-test is flaky and sometimes fails asynchronizely // after the test has finished. // https://github.com/flutter/flutter/issues/43858 TEST(MessageLoopTaskQueue, DISABLED_ConcurrentQueueAndTaskCreatingCounts) { auto task_queues = fml::MessageLoopTaskQueues::GetInstance(); const int base_queue_id = task_queues->CreateTaskQueue(); const int num_queues = 100; std::atomic_bool created[num_queues * 3]; std::atomic_int num_tasks[num_queues * 3]; std::mutex task_count_mutex[num_queues * 3]; std::atomic_int done = 0; for (int i = 0; i < num_queues * 3; i++) { num_tasks[i] = 0; created[i] = false; } auto creation_func = [&] { for (int i = 0; i < num_queues; i++) { fml::TaskQueueId queue_id = task_queues->CreateTaskQueue(); int limit = queue_id - base_queue_id; created[limit] = true; for (int cur_q = 1; cur_q < limit; cur_q++) { if (created[cur_q]) { std::scoped_lock counter(task_count_mutex[cur_q]); int cur_num_tasks = rand() % 10; for (int k = 0; k < cur_num_tasks; k++) { task_queues->RegisterTask( fml::TaskQueueId(base_queue_id + cur_q), [] {}, fml::TimePoint::Now()); } num_tasks[cur_q] += cur_num_tasks; } } } done++; }; std::thread creation_1(creation_func); std::thread creation_2(creation_func); while (done < 2) { for (int i = 0; i < num_queues * 3; i++) { if (created[i]) { std::scoped_lock counter(task_count_mutex[i]); int num_pending = task_queues->GetNumPendingTasks( fml::TaskQueueId(base_queue_id + i)); int num_added = num_tasks[i]; ASSERT_EQ(num_pending, num_added); } } } creation_1.join(); creation_2.join(); } TEST(MessageLoopTaskQueue, RegisterTaskWakesUpOwnerQueue) { auto task_queue = fml::MessageLoopTaskQueues::GetInstance(); auto platform_queue = task_queue->CreateTaskQueue(); auto raster_queue = task_queue->CreateTaskQueue(); std::vector<fml::TimePoint> wakes; task_queue->SetWakeable(platform_queue, new TestWakeable([&wakes](fml::TimePoint wake_time) { wakes.push_back(wake_time); })); task_queue->SetWakeable(raster_queue, new TestWakeable([](fml::TimePoint wake_time) { // The raster queue is owned by the platform queue. ASSERT_FALSE(true); })); auto time1 = fml::TimePoint::Now() + fml::TimeDelta::FromMilliseconds(1); auto time2 = fml::TimePoint::Now() + fml::TimeDelta::FromMilliseconds(2); ASSERT_EQ(0UL, wakes.size()); task_queue->RegisterTask( platform_queue, []() {}, time1); ASSERT_EQ(1UL, wakes.size()); ASSERT_EQ(time1, wakes[0]); task_queue->Merge(platform_queue, raster_queue); task_queue->RegisterTask( raster_queue, []() {}, time2); ASSERT_EQ(3UL, wakes.size()); ASSERT_EQ(time1, wakes[1]); ASSERT_EQ(time1, wakes[2]); } } // namespace testing } // namespace fml
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #define FML_USED_ON_EMBEDDER #include "flutter/fml/message_loop_task_queues.h" #include <algorithm> #include <cstdlib> #include <thread> #include "flutter/fml/synchronization/count_down_latch.h" #include "flutter/fml/synchronization/waitable_event.h" #include "gtest/gtest.h" namespace fml { namespace testing { class TestWakeable : public fml::Wakeable { public: using WakeUpCall = std::function<void(const fml::TimePoint)>; explicit TestWakeable(WakeUpCall call) : wake_up_call_(call) {} void WakeUp(fml::TimePoint time_point) override { wake_up_call_(time_point); } private: WakeUpCall wake_up_call_; }; TEST(MessageLoopTaskQueue, StartsWithNoPendingTasks) { auto task_queue = fml::MessageLoopTaskQueues::GetInstance(); auto queue_id = task_queue->CreateTaskQueue(); ASSERT_FALSE(task_queue->HasPendingTasks(queue_id)); } TEST(MessageLoopTaskQueue, RegisterOneTask) { const auto time = fml::TimePoint::Max(); auto task_queue = fml::MessageLoopTaskQueues::GetInstance(); auto queue_id = task_queue->CreateTaskQueue(); task_queue->SetWakeable(queue_id, new TestWakeable([&time](fml::TimePoint wake_time) { ASSERT_TRUE(wake_time == time); })); task_queue->RegisterTask( queue_id, [] {}, time); ASSERT_TRUE(task_queue->HasPendingTasks(queue_id)); ASSERT_TRUE(task_queue->GetNumPendingTasks(queue_id) == 1); } TEST(MessageLoopTaskQueue, RegisterTwoTasksAndCount) { auto task_queue = fml::MessageLoopTaskQueues::GetInstance(); auto queue_id = task_queue->CreateTaskQueue(); task_queue->RegisterTask( queue_id, [] {}, fml::TimePoint::Now()); task_queue->RegisterTask( queue_id, [] {}, fml::TimePoint::Max()); ASSERT_TRUE(task_queue->HasPendingTasks(queue_id)); ASSERT_TRUE(task_queue->GetNumPendingTasks(queue_id) == 2); } TEST(MessageLoopTaskQueue, PreserveTaskOrdering) { auto task_queue = fml::MessageLoopTaskQueues::GetInstance(); auto queue_id = task_queue->CreateTaskQueue(); int test_val = 0; // order: 0 task_queue->RegisterTask( queue_id, [&test_val]() { test_val = 1; }, fml::TimePoint::Now()); // order: 1 task_queue->RegisterTask( queue_id, [&test_val]() { test_val = 2; }, fml::TimePoint::Now()); const auto now = fml::TimePoint::Now(); int expected_value = 1; for (;;) { fml::closure invocation = task_queue->GetNextTaskToRun(queue_id, now); if (!invocation) { break; } invocation(); ASSERT_TRUE(test_val == expected_value); expected_value++; } } void TestNotifyObservers(fml::TaskQueueId queue_id) { auto task_queue = fml::MessageLoopTaskQueues::GetInstance(); std::vector<fml::closure> observers = task_queue->GetObserversToNotify(queue_id); for (const auto& observer : observers) { observer(); } } TEST(MessageLoopTaskQueue, AddRemoveNotifyObservers) { auto task_queue = fml::MessageLoopTaskQueues::GetInstance(); auto queue_id = task_queue->CreateTaskQueue(); int test_val = 0; intptr_t key = 123; task_queue->AddTaskObserver(queue_id, key, [&test_val]() { test_val = 1; }); TestNotifyObservers(queue_id); ASSERT_TRUE(test_val == 1); test_val = 0; task_queue->RemoveTaskObserver(queue_id, key); TestNotifyObservers(queue_id); ASSERT_TRUE(test_val == 0); } TEST(MessageLoopTaskQueue, WakeUpIndependentOfTime) { auto task_queue = fml::MessageLoopTaskQueues::GetInstance(); auto queue_id = task_queue->CreateTaskQueue(); int num_wakes = 0; task_queue->SetWakeable( queue_id, new TestWakeable( [&num_wakes](fml::TimePoint wake_time) { ++num_wakes; })); task_queue->RegisterTask( queue_id, []() {}, fml::TimePoint::Now()); task_queue->RegisterTask( queue_id, []() {}, fml::TimePoint::Max()); ASSERT_TRUE(num_wakes == 2); } TEST(MessageLoopTaskQueue, WokenUpWithNewerTime) { auto task_queue = fml::MessageLoopTaskQueues::GetInstance(); auto queue_id = task_queue->CreateTaskQueue(); fml::CountDownLatch latch(2); fml::TimePoint expected = fml::TimePoint::Max(); task_queue->SetWakeable( queue_id, new TestWakeable([&latch, &expected](fml::TimePoint wake_time) { ASSERT_TRUE(wake_time == expected); latch.CountDown(); })); task_queue->RegisterTask( queue_id, []() {}, fml::TimePoint::Max()); const auto now = fml::TimePoint::Now(); expected = now; task_queue->RegisterTask( queue_id, []() {}, now); latch.Wait(); } TEST(MessageLoopTaskQueue, NotifyObserversWhileCreatingQueues) { auto task_queues = fml::MessageLoopTaskQueues::GetInstance(); fml::TaskQueueId queue_id = task_queues->CreateTaskQueue(); fml::AutoResetWaitableEvent first_observer_executing, before_second_observer; task_queues->AddTaskObserver(queue_id, queue_id + 1, [&]() { first_observer_executing.Signal(); before_second_observer.Wait(); }); for (int i = 0; i < 100; i++) { task_queues->AddTaskObserver(queue_id, queue_id + i + 2, [] {}); } std::thread notify_observers([&]() { TestNotifyObservers(queue_id); }); first_observer_executing.Wait(); for (int i = 0; i < 100; i++) { task_queues->CreateTaskQueue(); } before_second_observer.Signal(); notify_observers.join(); } TEST(MessageLoopTaskQueue, QueueDoNotOwnItself) { auto task_queue = fml::MessageLoopTaskQueues::GetInstance(); auto queue_id = task_queue->CreateTaskQueue(); ASSERT_FALSE(task_queue->Owns(queue_id, queue_id)); } TEST(MessageLoopTaskQueue, QueueDoNotOwnUnmergedTaskQueueId) { auto task_queue = fml::MessageLoopTaskQueues::GetInstance(); ASSERT_FALSE(task_queue->Owns(task_queue->CreateTaskQueue(), _kUnmerged)); ASSERT_FALSE(task_queue->Owns(_kUnmerged, task_queue->CreateTaskQueue())); ASSERT_FALSE(task_queue->Owns(_kUnmerged, _kUnmerged)); } //------------------------------------------------------------------------------ /// Verifies that tasks can be added to task queues concurrently. /// TEST(MessageLoopTaskQueue, ConcurrentQueueAndTaskCreatingCounts) { auto task_queues = fml::MessageLoopTaskQueues::GetInstance(); // kThreadCount threads post kThreadTaskCount tasks each to kTaskQueuesCount // task queues. Each thread picks a task queue randomly for each task. constexpr size_t kThreadCount = 4; constexpr size_t kTaskQueuesCount = 2; constexpr size_t kThreadTaskCount = 500; std::vector<TaskQueueId> task_queue_ids; for (size_t i = 0; i < kTaskQueuesCount; ++i) { task_queue_ids.emplace_back(task_queues->CreateTaskQueue()); } ASSERT_EQ(task_queue_ids.size(), kTaskQueuesCount); fml::CountDownLatch tasks_posted_latch(kThreadCount); auto thread_main = [&]() { for (size_t i = 0; i < kThreadTaskCount; i++) { const auto current_task_queue_id = task_queue_ids[std::rand() % kTaskQueuesCount]; const auto empty_task = []() {}; // The timepoint doesn't matter as the queue is never going to be drained. const auto task_timepoint = fml::TimePoint::Now(); task_queues->RegisterTask(current_task_queue_id, empty_task, task_timepoint); } tasks_posted_latch.CountDown(); }; std::vector<std::thread> threads; for (size_t i = 0; i < kThreadCount; i++) { threads.emplace_back(std::thread{thread_main}); } ASSERT_EQ(threads.size(), kThreadCount); for (size_t i = 0; i < kThreadCount; i++) { threads[i].join(); } // All tasks have been posted by now. Check that they are all pending. size_t pending_tasks = 0u; std::for_each(task_queue_ids.begin(), task_queue_ids.end(), [&](const auto& queue) { pending_tasks += task_queues->GetNumPendingTasks(queue); }); ASSERT_EQ(pending_tasks, kThreadCount * kThreadTaskCount); } TEST(MessageLoopTaskQueue, RegisterTaskWakesUpOwnerQueue) { auto task_queue = fml::MessageLoopTaskQueues::GetInstance(); auto platform_queue = task_queue->CreateTaskQueue(); auto raster_queue = task_queue->CreateTaskQueue(); std::vector<fml::TimePoint> wakes; task_queue->SetWakeable(platform_queue, new TestWakeable([&wakes](fml::TimePoint wake_time) { wakes.push_back(wake_time); })); task_queue->SetWakeable(raster_queue, new TestWakeable([](fml::TimePoint wake_time) { // The raster queue is owned by the platform queue. ASSERT_FALSE(true); })); auto time1 = fml::TimePoint::Now() + fml::TimeDelta::FromMilliseconds(1); auto time2 = fml::TimePoint::Now() + fml::TimeDelta::FromMilliseconds(2); ASSERT_EQ(0UL, wakes.size()); task_queue->RegisterTask( platform_queue, []() {}, time1); ASSERT_EQ(1UL, wakes.size()); ASSERT_EQ(time1, wakes[0]); task_queue->Merge(platform_queue, raster_queue); task_queue->RegisterTask( raster_queue, []() {}, time2); ASSERT_EQ(3UL, wakes.size()); ASSERT_EQ(time1, wakes[1]); ASSERT_EQ(time1, wakes[2]); } } // namespace testing } // namespace fml
Fix and re-enable flaky test `MessageLoopTaskQueue::ConcurrentQueueAndTaskCreatingCounts`. (#25826)
Fix and re-enable flaky test `MessageLoopTaskQueue::ConcurrentQueueAndTaskCreatingCounts`. (#25826)
C++
bsd-3-clause
jason-simmons/sky_engine,jason-simmons/flutter_engine,jamesr/flutter_engine,jason-simmons/flutter_engine,devoncarew/sky_engine,Hixie/sky_engine,chinmaygarde/flutter_engine,jason-simmons/sky_engine,devoncarew/engine,jamesr/flutter_engine,jason-simmons/flutter_engine,chinmaygarde/sky_engine,jason-simmons/sky_engine,devoncarew/sky_engine,jamesr/flutter_engine,jamesr/flutter_engine,chinmaygarde/flutter_engine,devoncarew/engine,aam/engine,aam/engine,aam/engine,jamesr/sky_engine,devoncarew/sky_engine,jamesr/flutter_engine,devoncarew/engine,flutter/engine,chinmaygarde/sky_engine,chinmaygarde/sky_engine,Hixie/sky_engine,Hixie/sky_engine,jamesr/sky_engine,jamesr/flutter_engine,devoncarew/sky_engine,jamesr/sky_engine,flutter/engine,jamesr/flutter_engine,flutter/engine,aam/engine,devoncarew/sky_engine,aam/engine,aam/engine,chinmaygarde/sky_engine,devoncarew/engine,jason-simmons/flutter_engine,flutter/engine,chinmaygarde/flutter_engine,jamesr/flutter_engine,devoncarew/sky_engine,rmacnak-google/engine,rmacnak-google/engine,flutter/engine,jason-simmons/flutter_engine,flutter/engine,jason-simmons/sky_engine,rmacnak-google/engine,jason-simmons/sky_engine,jason-simmons/sky_engine,devoncarew/sky_engine,aam/engine,rmacnak-google/engine,jamesr/sky_engine,chinmaygarde/sky_engine,jamesr/sky_engine,Hixie/sky_engine,jason-simmons/flutter_engine,chinmaygarde/flutter_engine,jamesr/flutter_engine,Hixie/sky_engine,aam/engine,jason-simmons/sky_engine,jamesr/sky_engine,jason-simmons/flutter_engine,devoncarew/engine,devoncarew/engine,devoncarew/engine,rmacnak-google/engine,chinmaygarde/sky_engine,chinmaygarde/flutter_engine,jamesr/sky_engine,Hixie/sky_engine,chinmaygarde/sky_engine,Hixie/sky_engine,rmacnak-google/engine,chinmaygarde/flutter_engine,Hixie/sky_engine,flutter/engine,chinmaygarde/flutter_engine,rmacnak-google/engine,flutter/engine,jason-simmons/flutter_engine
dad37444de893b131ccbf9e402a17615a067824a
agency/cuda/detail/future/event.hpp
agency/cuda/detail/future/event.hpp
#pragma once #include <agency/detail/config.hpp> #include <agency/cuda/detail/feature_test.hpp> #include <agency/cuda/detail/terminate.hpp> #include <agency/cuda/detail/launch_kernel.hpp> #include <agency/cuda/detail/kernel.hpp> #include <agency/cuda/detail/future/stream.hpp> #include <agency/cuda/gpu.hpp> namespace agency { namespace cuda { namespace detail { class event { public: struct construct_ready_t {}; static constexpr construct_ready_t construct_ready{}; private: static constexpr int event_create_flags = cudaEventDisableTiming; __host__ __device__ event(construct_ready_t, detail::stream&& s) : stream_(std::move(s)) { #if __cuda_lib_has_cudart detail::throw_on_error(cudaEventCreateWithFlags(&e_, event_create_flags), "cudaEventCreateWithFlags in cuda::detail::event ctor"); #else detail::terminate_with_message("cuda::detail::event ctor requires CUDART"); #endif } // constructs a new event recorded on the given stream __host__ __device__ event(detail::stream&& s) : event(construct_ready, std::move(s)) { #if __cuda_lib_has_cudart detail::throw_on_error(cudaEventRecord(e_, stream().native_handle()), "cudaEventRecord in cuda::detail::event ctor"); #else detail::terminate_with_message("cuda::detail::event ctor requires CUDART"); #endif } public: // creates an invalid event __host__ __device__ event() : stream_(), e_{0} {} __host__ __device__ event(construct_ready_t) : event(construct_ready, detail::stream()) {} __host__ __device__ event(const event&) = delete; __host__ __device__ event(event&& other) : event() { swap(other); } __host__ __device__ ~event() { if(valid()) { destroy_event(); } } __host__ __device__ event& operator=(event&& other) { swap(other); return *this; } __host__ __device__ bool valid() const { return e_ != 0; } __host__ __device__ bool is_ready() const { if(valid()) { #if __cuda_lib_has_cudart cudaError_t result = cudaEventQuery(e_); if(result != cudaErrorNotReady && result != cudaSuccess) { detail::throw_on_error(result, "cudaEventQuery in cuda::detail::event::is_ready"); } return result == cudaSuccess; #else detail::terminate_with_message("cuda::detail::event::is_ready requires CUDART"); #endif } return false; } __host__ __device__ void wait() const { // XXX should probably check for valid() here #if __cuda_lib_has_cudart #ifndef __CUDA_ARCH__ detail::throw_on_error(cudaEventSynchronize(e_), "cudaEventSynchronize in cuda::detail::event::wait"); #else detail::throw_on_error(cudaDeviceSynchronize(), "cudaDeviceSynchronize in cuda::detail::event::wait"); #endif // __CUDA_ARCH__ #else detail::terminate_with_message("cuda::detail::event::wait requires CUDART"); #endif // __cuda_lib_has_cudart } __host__ __device__ void swap(event& other) { stream().swap(other.stream()); cudaEvent_t tmp = e_; e_ = other.e_; other.e_ = tmp; } template<class Function, class... Args> __host__ __device__ static void *then_kernel() { return reinterpret_cast<void*>(&cuda_kernel<Function,Args...>); } template<class Function, class... Args> __host__ __device__ static void *then_kernel(const Function&, const Args&...) { return then_kernel<Function,Args...>(); } // this form of then() leaves this event in a valid state afterwards template<class Function, class... Args> __host__ __device__ event then(Function f, dim3 grid_dim, dim3 block_dim, int shared_memory_size, const Args&... args) { // create a stream for the kernel detail::stream result_stream; // make the result_stream wait on this event before further launches stream_wait(result_stream, *this); // get the address of the kernel auto kernel = then_kernel(f,args...); // launch the kernel on the result's stream detail::checked_launch_kernel(kernel, grid_dim, block_dim, shared_memory_size, result_stream.native_handle(), f, args...); // return a new event return event(std::move(result_stream)); } // this form of then() leaves this event in an invalid state afterwards template<class Function, class... Args> __host__ __device__ event then_and_invalidate(Function f, dim3 grid_dim, dim3 block_dim, int shared_memory_size, const Args&... args) { // make the stream wait on this event before further launches stream_wait_and_invalidate(); // get the address of the kernel auto kernel = then_kernel(f,args...); // launch the kernel on this event's stream detail::checked_launch_kernel(kernel, grid_dim, block_dim, shared_memory_size, stream().native_handle(), f, args...); // return a new event return event(std::move(stream())); } template<class Function, class... Args> __host__ __device__ static void *then_on_kernel() { return reinterpret_cast<void*>(&cuda_kernel<Function,Args...>); } template<class Function, class... Args> __host__ __device__ static void *then_on_kernel(const Function&, const Args&...) { return then_on_kernel<Function,Args...>(); } // this form of then_on() leaves this event in an invalid state afterwards template<class Function, class... Args> __host__ __device__ event then_on_and_invalidate(Function f, dim3 grid_dim, dim3 block_dim, int shared_memory_size, const gpu_id& gpu, const Args&... args) { // get the address of the kernel auto kernel = then_on_kernel(f,args...); // if gpu differs from this event's stream's gpu, we need to create a new one for the launch // otherwise, just reuse this event's stream detail::stream new_stream = (gpu == stream().gpu()) ? std::move(stream()) : detail::stream(gpu); // make the new stream wait on this event stream_wait(new_stream, *this); // launch the kernel on the new stream detail::checked_launch_kernel_on_device(kernel, grid_dim, block_dim, shared_memory_size, new_stream.native_handle(), gpu.native_handle(), f, args...); // invalidate this event *this = event(); // return a new event return event(std::move(new_stream)); } private: stream stream_; cudaEvent_t e_; // this function returns 0 so that we can pass it as an argument to swallow(...) __host__ __device__ int destroy_event() { #if __cuda_lib_has_cudart // since this will likely be called from destructors, swallow errors cudaError_t error = cudaEventDestroy(e_); e_ = 0; #if __cuda_lib_has_printf if(error) { printf("CUDA error after cudaEventDestroy in cuda::detail::event::destroy_event: %s", cudaGetErrorString(error)); } // end if #endif // __cuda_lib_has_printf #endif // __cuda_lib_has_cudart return 0; } __host__ __device__ stream& stream() { return stream_; } // makes the given stream wait on the given event // XXX this should be moved into the implementation of detail::stream __host__ __device__ static void stream_wait(const detail::stream& s, const detail::event& e) { #if __cuda_lib_has_cudart // make the next launch wait on the event throw_on_error(cudaStreamWaitEvent(s.native_handle(), e.e_, 0), "cuda::detail::event::stream_wait(): cudaStreamWaitEvent()"); #else throw_on_error(cudaErrorNotSupported, "cuda::detail::event::stream_wait(): cudaStreamWaitEvent() requires CUDART"); #endif // __cuda_lib_has_cudart } // makes the given stream wait on this event __host__ __device__ int stream_wait(const detail::stream& s) const { stream_wait(s, *this); return 0; } // makes the given stream wait on this event and invalidates this event // this function returns 0 so that we can pass it as an argument to swallow(...) __host__ __device__ int stream_wait_and_invalidate(const detail::stream& s) { stream_wait(s); // this operation invalidates this event destroy_event(); return 0; } // makes this event's stream wait on this event and invalidates this event __host__ __device__ int stream_wait_and_invalidate() { return stream_wait_and_invalidate(stream()); } template<class... Args> inline __host__ __device__ static void swallow(Args&&... args) {} template<class... Events> __host__ __device__ friend event when_all_events_are_ready(const gpu_id& gpu, Events&... events); template<class... Events> __host__ __device__ friend event when_all_events_are_ready(Events&... events); }; template<class... Events> __host__ __device__ event when_all_events_are_ready(const gpu_id& gpu, Events&... events) { detail::stream s{gpu}; // tell the stream to wait on all the events event::swallow(events.stream_wait_and_invalidate(s)...); // return a new event recorded on the stream return event(std::move(s)); } template<class... Events> __host__ __device__ event when_all_events_are_ready(Events&... events) { // just use the current gpu // XXX we might prefer the gpu associated with the first event return agency::cuda::detail::when_all_events_are_ready(current_gpu(), events...); } } // end detail } // end cuda } // end agency
#pragma once #include <agency/detail/config.hpp> #include <agency/cuda/detail/feature_test.hpp> #include <agency/cuda/detail/terminate.hpp> #include <agency/cuda/detail/launch_kernel.hpp> #include <agency/cuda/detail/kernel.hpp> #include <agency/cuda/detail/future/stream.hpp> #include <agency/cuda/gpu.hpp> namespace agency { namespace cuda { namespace detail { class event { public: struct construct_ready_t {}; static constexpr construct_ready_t construct_ready{}; private: static constexpr int event_create_flags = cudaEventDisableTiming; __host__ __device__ event(construct_ready_t, detail::stream&& s) : stream_(std::move(s)) { #if __cuda_lib_has_cudart detail::throw_on_error(cudaEventCreateWithFlags(&e_, event_create_flags), "cudaEventCreateWithFlags in cuda::detail::event ctor"); #else detail::terminate_with_message("cuda::detail::event ctor requires CUDART"); #endif } // constructs a new event recorded on the given stream __host__ __device__ event(detail::stream&& s) : event(construct_ready, std::move(s)) { #if __cuda_lib_has_cudart detail::throw_on_error(cudaEventRecord(e_, stream().native_handle()), "cudaEventRecord in cuda::detail::event ctor"); #else detail::terminate_with_message("cuda::detail::event ctor requires CUDART"); #endif } public: // creates an invalid event __host__ __device__ event() : stream_(), e_{0} {} __host__ __device__ event(construct_ready_t) : event(construct_ready, detail::stream()) {} __host__ __device__ event(const event&) = delete; __host__ __device__ event(event&& other) : event() { swap(other); } __host__ __device__ ~event() { if(valid()) { destroy_event(); } } __host__ __device__ event& operator=(event&& other) { swap(other); return *this; } __host__ __device__ bool valid() const { return e_ != 0; } __host__ __device__ bool is_ready() const { if(valid()) { #if __cuda_lib_has_cudart cudaError_t result = cudaEventQuery(e_); if(result != cudaErrorNotReady && result != cudaSuccess) { detail::throw_on_error(result, "cudaEventQuery in cuda::detail::event::is_ready"); } return result == cudaSuccess; #else detail::terminate_with_message("cuda::detail::event::is_ready requires CUDART"); #endif } return false; } __host__ __device__ void wait() const { // XXX should probably check for valid() here #if __cuda_lib_has_cudart #ifndef __CUDA_ARCH__ detail::throw_on_error(cudaEventSynchronize(e_), "cudaEventSynchronize in cuda::detail::event::wait"); #else detail::throw_on_error(cudaDeviceSynchronize(), "cudaDeviceSynchronize in cuda::detail::event::wait"); #endif // __CUDA_ARCH__ #else detail::terminate_with_message("cuda::detail::event::wait requires CUDART"); #endif // __cuda_lib_has_cudart } __host__ __device__ void swap(event& other) { stream().swap(other.stream()); cudaEvent_t tmp = e_; e_ = other.e_; other.e_ = tmp; } template<class Function, class... Args> __host__ __device__ static void *then_kernel() { return reinterpret_cast<void*>(&cuda_kernel<Function,Args...>); } template<class Function, class... Args> __host__ __device__ static void *then_kernel(const Function&, const Args&...) { return then_kernel<Function,Args...>(); } // this form of then() leaves this event in a valid state afterwards template<class Function, class... Args> __host__ __device__ event then(Function f, dim3 grid_dim, dim3 block_dim, int shared_memory_size, const Args&... args) { return then_on(f, grid_dim, block_dim, shared_memory_size, stream().gpu(), args...); } // this form of then() leaves this event in an invalid state afterwards template<class Function, class... Args> __host__ __device__ event then_and_invalidate(Function f, dim3 grid_dim, dim3 block_dim, int shared_memory_size, const Args&... args) { // make the stream wait on this event before further launches stream_wait_and_invalidate(); // get the address of the kernel auto kernel = then_kernel(f,args...); // launch the kernel on this event's stream detail::checked_launch_kernel(kernel, grid_dim, block_dim, shared_memory_size, stream().native_handle(), f, args...); // return a new event return event(std::move(stream())); } template<class Function, class... Args> __host__ __device__ static void *then_on_kernel() { return reinterpret_cast<void*>(&cuda_kernel<Function,Args...>); } template<class Function, class... Args> __host__ __device__ static void *then_on_kernel(const Function&, const Args&...) { return then_on_kernel<Function,Args...>(); } // this form of then_on() leaves this event in an invalid state afterwards template<class Function, class... Args> __host__ __device__ event then_on_and_invalidate(Function f, dim3 grid_dim, dim3 block_dim, int shared_memory_size, const gpu_id& gpu, const Args&... args) { // if gpu differs from this event's stream's gpu, we need to create a new one for the launch // otherwise, just reuse this event's stream detail::stream new_stream = (gpu == stream().gpu()) ? std::move(stream()) : detail::stream(gpu); // make the new stream wait on this event stream_wait(new_stream, *this); // get the address of the kernel auto kernel = then_on_kernel(f,args...); // launch the kernel on the new stream detail::checked_launch_kernel_on_device(kernel, grid_dim, block_dim, shared_memory_size, new_stream.native_handle(), gpu.native_handle(), f, args...); // invalidate this event *this = event(); // return a new event return event(std::move(new_stream)); } // this form of then_on() leaves this event in a valid state afterwards template<class Function, class... Args> __host__ __device__ event then_on(Function f, dim3 grid_dim, dim3 block_dim, int shared_memory_size, const gpu_id& gpu, const Args&... args) { // create a stream for the kernel detail::stream new_stream; // make the new stream wait on this event stream_wait(new_stream, *this); // get the address of the kernel auto kernel = then_on_kernel(f,args...); // launch the kernel on the new stream detail::checked_launch_kernel_on_device(kernel, grid_dim, block_dim, shared_memory_size, new_stream.native_handle(), gpu.native_handle(), f, args...); // return a new event return event(std::move(new_stream)); } private: stream stream_; cudaEvent_t e_; // this function returns 0 so that we can pass it as an argument to swallow(...) __host__ __device__ int destroy_event() { #if __cuda_lib_has_cudart // since this will likely be called from destructors, swallow errors cudaError_t error = cudaEventDestroy(e_); e_ = 0; #if __cuda_lib_has_printf if(error) { printf("CUDA error after cudaEventDestroy in cuda::detail::event::destroy_event: %s", cudaGetErrorString(error)); } // end if #endif // __cuda_lib_has_printf #endif // __cuda_lib_has_cudart return 0; } __host__ __device__ stream& stream() { return stream_; } // makes the given stream wait on the given event // XXX this should be moved into the implementation of detail::stream __host__ __device__ static void stream_wait(const detail::stream& s, const detail::event& e) { #if __cuda_lib_has_cudart // make the next launch wait on the event throw_on_error(cudaStreamWaitEvent(s.native_handle(), e.e_, 0), "cuda::detail::event::stream_wait(): cudaStreamWaitEvent()"); #else throw_on_error(cudaErrorNotSupported, "cuda::detail::event::stream_wait(): cudaStreamWaitEvent() requires CUDART"); #endif // __cuda_lib_has_cudart } // makes the given stream wait on this event __host__ __device__ int stream_wait(const detail::stream& s) const { stream_wait(s, *this); return 0; } // makes the given stream wait on this event and invalidates this event // this function returns 0 so that we can pass it as an argument to swallow(...) __host__ __device__ int stream_wait_and_invalidate(const detail::stream& s) { stream_wait(s); // this operation invalidates this event destroy_event(); return 0; } // makes this event's stream wait on this event and invalidates this event __host__ __device__ int stream_wait_and_invalidate() { return stream_wait_and_invalidate(stream()); } template<class... Args> inline __host__ __device__ static void swallow(Args&&... args) {} template<class... Events> __host__ __device__ friend event when_all_events_are_ready(const gpu_id& gpu, Events&... events); template<class... Events> __host__ __device__ friend event when_all_events_are_ready(Events&... events); }; template<class... Events> __host__ __device__ event when_all_events_are_ready(const gpu_id& gpu, Events&... events) { detail::stream s{gpu}; // tell the stream to wait on all the events event::swallow(events.stream_wait_and_invalidate(s)...); // return a new event recorded on the stream return event(std::move(s)); } template<class... Events> __host__ __device__ event when_all_events_are_ready(Events&... events) { // just use the current gpu // XXX we might prefer the gpu associated with the first event return agency::cuda::detail::when_all_events_are_ready(current_gpu(), events...); } } // end detail } // end cuda } // end agency
Add cuda::detail::event::then_on()
Add cuda::detail::event::then_on()
C++
bsd-3-clause
egaburov/agency,egaburov/agency
f72dff6adc0e3ef0283f4f34ef5f787d5c6f190a
akonadi/kcm/akonadiconfigmodule.cpp
akonadi/kcm/akonadiconfigmodule.cpp
/* Copyright (c) 2008 Volker Krause <[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 "akonadiconfigmodule.h" #include <kpluginfactory.h> #include <kpluginloader.h> K_PLUGIN_FACTORY( AkonadiConfigModuleFactory, registerPlugin<AkonadiConfigModule>(); ) K_EXPORT_PLUGIN( AkonadiConfigModuleFactory( "kcm_akonadi" ) ) AkonadiConfigModule::AkonadiConfigModule( QWidget * parent, const QVariantList & args ) : KCModuleContainer( parent ) { Q_UNUSED( args ); setButtons( KCModule::Default | KCModule::Apply ); addModule( QLatin1String("kcm_akonadi_server") ); addModule( QLatin1String("kcm_akonadi_resources") ); } #include "akonadiconfigmodule.moc"
/* Copyright (c) 2008 Volker Krause <[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 "akonadiconfigmodule.h" #include <kpluginfactory.h> #include <kpluginloader.h> K_PLUGIN_FACTORY( AkonadiConfigModuleFactory, registerPlugin<AkonadiConfigModule>(); ) K_EXPORT_PLUGIN( AkonadiConfigModuleFactory( "kcm_akonadi" ) ) AkonadiConfigModule::AkonadiConfigModule( QWidget * parent, const QVariantList & args ) : KCModuleContainer( parent ) { Q_UNUSED( args ); setButtons( KCModule::Default | KCModule::Apply ); addModule( QLatin1String("kcm_akonadi_resources") ); addModule( QLatin1String("kcm_akonadi_server") ); } #include "akonadiconfigmodule.moc"
Revert 910521, since most users will only need to configure resources.
Revert 910521, since most users will only need to configure resources. svn path=/trunk/KDE/kdepim/; revision=910525
C++
lgpl-2.1
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
ac30830212e2d3884dd9afbba82261f876913c67
dtrace_provider.cc
dtrace_provider.cc
#include "dtrace_provider.h" #include <v8.h> #include <node.h> #include <stdio.h> namespace node { using namespace v8; Persistent<FunctionTemplate> DTraceProvider::constructor_template; void DTraceProvider::Initialize(Handle<Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(DTraceProvider::New); constructor_template = Persistent<FunctionTemplate>::New(t); constructor_template->InstanceTemplate()->SetInternalFieldCount(1); constructor_template->SetClassName(String::NewSymbol("DTraceProvider")); NODE_SET_PROTOTYPE_METHOD(constructor_template, "addProbe", DTraceProvider::AddProbe); NODE_SET_PROTOTYPE_METHOD(constructor_template, "removeProbe", DTraceProvider::RemoveProbe); NODE_SET_PROTOTYPE_METHOD(constructor_template, "enable", DTraceProvider::Enable); NODE_SET_PROTOTYPE_METHOD(constructor_template, "disable", DTraceProvider::Disable); NODE_SET_PROTOTYPE_METHOD(constructor_template, "fire", DTraceProvider::Fire); NODE_SET_PROTOTYPE_METHOD(t, "addProbe", DTraceProvider::AddProbe); NODE_SET_PROTOTYPE_METHOD(t, "enable", DTraceProvider::Enable); NODE_SET_PROTOTYPE_METHOD(t, "fire", DTraceProvider::Fire); DTraceProbe::Initialize(target); } Handle<Value> DTraceProvider::New(const Arguments& args) { HandleScope scope; DTraceProvider *p = new DTraceProvider(); if (args.Length() != 1 || !args[0]->IsString()) { return ThrowException(Exception::Error(String::New( "Must give provider name as argument"))); } String::AsciiValue name(args[0]->ToString()); if ((p->provider = usdt_create_provider(*name, "modname")) == NULL) { return ThrowException(Exception::Error(String::New( "usdt_create_provider failed"))); } p->Wrap(args.Holder()); return args.This(); } Handle<Value> DTraceProvider::AddProbe(const Arguments& args) { HandleScope scope; const char *types[USDT_ARG_MAX]; int argc = 0; Handle<Object> obj = args.Holder(); DTraceProvider *provider = ObjectWrap::Unwrap<DTraceProvider>(obj); // create a DTraceProbe object Handle<Function> klass = DTraceProbe::constructor_template->GetFunction(); Handle<Object> pd = Persistent<Object>::New(klass->NewInstance()); // store in provider object DTraceProbe *probe = ObjectWrap::Unwrap<DTraceProbe>(pd->ToObject()); obj->Set(args[0]->ToString(), pd); // add probe to provider for (int i = 0; i < USDT_ARG_MAX; i++) { if (i < args.Length() - 1) { String::AsciiValue type(args[i + 1]->ToString()); types[i] = strdup(*type); argc++; } } String::AsciiValue name(args[0]->ToString()); probe->probedef = usdt_create_probe(*name, *name, argc, types); usdt_provider_add_probe(provider->provider, probe->probedef); return pd; } Handle<Value> DTraceProvider::RemoveProbe(const Arguments& args) { HandleScope scope; Handle<Object> provider_obj = args.Holder(); DTraceProvider *provider = ObjectWrap::Unwrap<DTraceProvider>(provider_obj); Handle<Object> probe_obj = Local<Object>::Cast(args[0]); DTraceProbe *probe = ObjectWrap::Unwrap<DTraceProbe>(probe_obj); Handle<String> name = String::New(probe->probedef->name); provider_obj->Delete(name); if (usdt_provider_remove_probe(provider->provider, probe->probedef) != 0) return ThrowException(Exception::Error(String::New(usdt_errstr(provider->provider)))); return True(); } Handle<Value> DTraceProvider::Enable(const Arguments& args) { HandleScope scope; DTraceProvider *provider = ObjectWrap::Unwrap<DTraceProvider>(args.Holder()); if (usdt_provider_enable(provider->provider) != 0) return ThrowException(Exception::Error(String::New(usdt_errstr(provider->provider)))); return Undefined(); } Handle<Value> DTraceProvider::Disable(const Arguments& args) { HandleScope scope; DTraceProvider *provider = ObjectWrap::Unwrap<DTraceProvider>(args.Holder()); if (usdt_provider_disable(provider->provider) != 0) return ThrowException(Exception::Error(String::New(usdt_errstr(provider->provider)))); return Undefined(); } Handle<Value> DTraceProvider::Fire(const Arguments& args) { HandleScope scope; if (!args[0]->IsString()) { return ThrowException(Exception::Error(String::New( "Must give probe name as first argument"))); } if (!args[1]->IsFunction()) { return ThrowException(Exception::Error(String::New( "Must give probe value callback as second argument"))); } Handle<Object> provider = args.Holder(); Handle<Object> probe = Local<Object>::Cast(provider->Get(args[0])); DTraceProbe *p = ObjectWrap::Unwrap<DTraceProbe>(probe); if (p == NULL) return Undefined(); p->_fire(args[1]); return True(); } extern "C" void init(Handle<Object> target) { DTraceProvider::Initialize(target); } } // namespace node
#include "dtrace_provider.h" #include <v8.h> #include <node.h> #include <stdio.h> namespace node { using namespace v8; Persistent<FunctionTemplate> DTraceProvider::constructor_template; void DTraceProvider::Initialize(Handle<Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(DTraceProvider::New); constructor_template = Persistent<FunctionTemplate>::New(t); constructor_template->InstanceTemplate()->SetInternalFieldCount(1); constructor_template->SetClassName(String::NewSymbol("DTraceProvider")); NODE_SET_PROTOTYPE_METHOD(constructor_template, "addProbe", DTraceProvider::AddProbe); NODE_SET_PROTOTYPE_METHOD(constructor_template, "removeProbe", DTraceProvider::RemoveProbe); NODE_SET_PROTOTYPE_METHOD(constructor_template, "enable", DTraceProvider::Enable); NODE_SET_PROTOTYPE_METHOD(constructor_template, "disable", DTraceProvider::Disable); NODE_SET_PROTOTYPE_METHOD(constructor_template, "fire", DTraceProvider::Fire); target->Set(String::NewSymbol("DTraceProvider"), constructor_template->GetFunction()); DTraceProbe::Initialize(target); } Handle<Value> DTraceProvider::New(const Arguments& args) { HandleScope scope; DTraceProvider *p = new DTraceProvider(); p->Wrap(args.This()); if (args.Length() != 1 || !args[0]->IsString()) { return ThrowException(Exception::Error(String::New( "Must give provider name as argument"))); } String::AsciiValue name(args[0]->ToString()); if ((p->provider = usdt_create_provider(*name, "modname")) == NULL) { return ThrowException(Exception::Error(String::New( "usdt_create_provider failed"))); } return args.This(); } Handle<Value> DTraceProvider::AddProbe(const Arguments& args) { HandleScope scope; const char *types[USDT_ARG_MAX]; int argc = 0; Handle<Object> obj = args.Holder(); DTraceProvider *provider = ObjectWrap::Unwrap<DTraceProvider>(obj); // create a DTraceProbe object Handle<Function> klass = DTraceProbe::constructor_template->GetFunction(); Handle<Object> pd = Persistent<Object>::New(klass->NewInstance()); // store in provider object DTraceProbe *probe = ObjectWrap::Unwrap<DTraceProbe>(pd->ToObject()); obj->Set(args[0]->ToString(), pd); // add probe to provider for (int i = 0; i < USDT_ARG_MAX; i++) { if (i < args.Length() - 1) { String::AsciiValue type(args[i + 1]->ToString()); types[i] = strdup(*type); argc++; } } String::AsciiValue name(args[0]->ToString()); probe->probedef = usdt_create_probe(*name, *name, argc, types); usdt_provider_add_probe(provider->provider, probe->probedef); return pd; } Handle<Value> DTraceProvider::RemoveProbe(const Arguments& args) { HandleScope scope; Handle<Object> provider_obj = args.Holder(); DTraceProvider *provider = ObjectWrap::Unwrap<DTraceProvider>(provider_obj); Handle<Object> probe_obj = Local<Object>::Cast(args[0]); DTraceProbe *probe = ObjectWrap::Unwrap<DTraceProbe>(probe_obj); Handle<String> name = String::New(probe->probedef->name); provider_obj->Delete(name); if (usdt_provider_remove_probe(provider->provider, probe->probedef) != 0) return ThrowException(Exception::Error(String::New(usdt_errstr(provider->provider)))); return True(); } Handle<Value> DTraceProvider::Enable(const Arguments& args) { HandleScope scope; DTraceProvider *provider = ObjectWrap::Unwrap<DTraceProvider>(args.Holder()); if (usdt_provider_enable(provider->provider) != 0) return ThrowException(Exception::Error(String::New(usdt_errstr(provider->provider)))); return Undefined(); } Handle<Value> DTraceProvider::Disable(const Arguments& args) { HandleScope scope; DTraceProvider *provider = ObjectWrap::Unwrap<DTraceProvider>(args.Holder()); if (usdt_provider_disable(provider->provider) != 0) return ThrowException(Exception::Error(String::New(usdt_errstr(provider->provider)))); return Undefined(); } Handle<Value> DTraceProvider::Fire(const Arguments& args) { HandleScope scope; if (!args[0]->IsString()) { return ThrowException(Exception::Error(String::New( "Must give probe name as first argument"))); } if (!args[1]->IsFunction()) { return ThrowException(Exception::Error(String::New( "Must give probe value callback as second argument"))); } Handle<Object> provider = args.Holder(); Handle<Object> probe = Local<Object>::Cast(provider->Get(args[0])); DTraceProbe *p = ObjectWrap::Unwrap<DTraceProbe>(probe); if (p == NULL) return Undefined(); p->_fire(args[1]); return True(); } extern "C" void init(Handle<Object> target) { DTraceProvider::Initialize(target); } } // namespace node
Fix mismerge to master.
Fix mismerge to master.
C++
bsd-2-clause
dieface/node-dtrace-provider,DataSweeper/node-dtrace-provider,mgenereu/node-dtrace-provider,DataSweeper/node-dtrace-provider,tjfontaine/node-dtrace-provider,DataSweeper/node-dtrace-provider,dieface/node-dtrace-provider,mgenereu/node-dtrace-provider,dieface/node-dtrace-provider,DataSweeper/node-dtrace-provider,mgenereu/node-dtrace-provider,mgenereu/node-dtrace-provider,tjfontaine/node-dtrace-provider,tjfontaine/node-dtrace-provider,tjfontaine/node-dtrace-provider,dieface/node-dtrace-provider
e1c835b10358afc8e76f2bc0b8bcab4a6120cb0a
media/filters/ffmpeg_video_decode_engine.cc
media/filters/ffmpeg_video_decode_engine.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 "media/filters/ffmpeg_video_decode_engine.h" #include "base/task.h" #include "media/base/buffers.h" #include "media/base/callback.h" #include "media/base/limits.h" #include "media/ffmpeg/ffmpeg_common.h" #include "media/ffmpeg/ffmpeg_util.h" #include "media/filters/ffmpeg_demuxer.h" namespace media { FFmpegVideoDecodeEngine::FFmpegVideoDecodeEngine() : codec_context_(NULL), state_(kCreated) { } FFmpegVideoDecodeEngine::~FFmpegVideoDecodeEngine() { } void FFmpegVideoDecodeEngine::Initialize(AVStream* stream, Task* done_cb) { AutoTaskRunner done_runner(done_cb); // Always try to use two threads for video decoding. There is little reason // not to since current day CPUs tend to be multi-core and we measured // performance benefits on older machines such as P4s with hyperthreading. // // Handling decoding on separate threads also frees up the pipeline thread to // continue processing. Although it'd be nice to have the option of a single // decoding thread, FFmpeg treats having one thread the same as having zero // threads (i.e., avcodec_decode_video() will execute on the calling thread). // Yet another reason for having two threads :) static const int kDecodeThreads = 2; CHECK(state_ == kCreated); codec_context_ = stream->codec; codec_context_->flags2 |= CODEC_FLAG2_FAST; // Enable faster H264 decode. // Enable motion vector search (potentially slow), strong deblocking filter // for damaged macroblocks, and set our error detection sensitivity. codec_context_->error_concealment = FF_EC_GUESS_MVS | FF_EC_DEBLOCK; codec_context_->error_recognition = FF_ER_CAREFUL; AVCodec* codec = avcodec_find_decoder(codec_context_->codec_id); // TODO(fbarchard): On next ffmpeg roll, retest Theora multi-threading. int decode_threads = (codec_context_->codec_id == CODEC_ID_THEORA) ? 1 : kDecodeThreads; // We don't allocate AVFrame on the stack since different versions of FFmpeg // may change the size of AVFrame, causing stack corruption. The solution is // to let FFmpeg allocate the structure via avcodec_alloc_frame(). av_frame_.reset(avcodec_alloc_frame()); if (codec && avcodec_thread_init(codec_context_, decode_threads) >= 0 && avcodec_open(codec_context_, codec) >= 0 && av_frame_.get()) { state_ = kNormal; } else { state_ = kError; } } static void CopyPlane(size_t plane, scoped_refptr<VideoFrame> video_frame, const AVFrame* frame) { DCHECK(video_frame->width() % 2 == 0); const uint8* source = frame->data[plane]; const size_t source_stride = frame->linesize[plane]; uint8* dest = video_frame->data(plane); const size_t dest_stride = video_frame->stride(plane); size_t bytes_per_line = video_frame->width(); size_t copy_lines = video_frame->height(); if (plane != VideoFrame::kYPlane) { bytes_per_line /= 2; if (video_frame->format() == VideoFrame::YV12) { copy_lines = (copy_lines + 1) / 2; } } DCHECK(bytes_per_line <= source_stride && bytes_per_line <= dest_stride); for (size_t i = 0; i < copy_lines; ++i) { memcpy(dest, source, bytes_per_line); source += source_stride; dest += dest_stride; } } // Decodes one frame of video with the given buffer. void FFmpegVideoDecodeEngine::DecodeFrame( Buffer* buffer, scoped_refptr<VideoFrame>* video_frame, bool* got_frame, Task* done_cb) { AutoTaskRunner done_runner(done_cb); *got_frame = false; *video_frame = NULL; // Create a packet for input data. // Due to FFmpeg API changes we no longer have const read-only pointers. AVPacket packet; av_init_packet(&packet); packet.data = const_cast<uint8*>(buffer->GetData()); packet.size = buffer->GetDataSize(); int frame_decoded = 0; int result = avcodec_decode_video2(codec_context_, av_frame_.get(), &frame_decoded, &packet); // Log the problem if we can't decode a video frame and exit early. if (result < 0) { LOG(INFO) << "Error decoding a video frame with timestamp: " << buffer->GetTimestamp().InMicroseconds() << " us" << " , duration: " << buffer->GetDuration().InMicroseconds() << " us" << " , packet size: " << buffer->GetDataSize() << " bytes"; *got_frame = false; } else { // If frame_decoded == 0, then no frame was produced. *got_frame = frame_decoded != 0; if (*got_frame) { // TODO(fbarchard): Work around for FFmpeg http://crbug.com/27675 // The decoder is in a bad state and not decoding correctly. // Checking for NULL avoids a crash in CopyPlane(). if (!av_frame_->data[VideoFrame::kYPlane] || !av_frame_->data[VideoFrame::kUPlane] || !av_frame_->data[VideoFrame::kVPlane]) { // TODO(jiesun): this is also an error case handled as normal. *got_frame = false; return; } VideoFrame::CreateFrame(GetSurfaceFormat(), codec_context_->width, codec_context_->height, StreamSample::kInvalidTimestamp, StreamSample::kInvalidTimestamp, video_frame); if (!video_frame->get()) { // TODO(jiesun): this is also an error case handled as normal. *got_frame = false; return; } // Copy the frame data since FFmpeg reuses internal buffers for AVFrame // output, meaning the data is only valid until the next // avcodec_decode_video() call. // TODO(scherkus): figure out pre-allocation/buffer cycling scheme. // TODO(scherkus): is there a cleaner way to figure out the # of planes? CopyPlane(VideoFrame::kYPlane, video_frame->get(), av_frame_.get()); CopyPlane(VideoFrame::kUPlane, video_frame->get(), av_frame_.get()); CopyPlane(VideoFrame::kVPlane, video_frame->get(), av_frame_.get()); DCHECK_LE(av_frame_->repeat_pict, 2); // Sanity check. (*video_frame)->SetRepeatCount(av_frame_->repeat_pict); } } } void FFmpegVideoDecodeEngine::Flush(Task* done_cb) { AutoTaskRunner done_runner(done_cb); avcodec_flush_buffers(codec_context_); } VideoFrame::Format FFmpegVideoDecodeEngine::GetSurfaceFormat() const { // J (Motion JPEG) versions of YUV are full range 0..255. // Regular (MPEG) YUV is 16..240. // For now we will ignore the distinction and treat them the same. switch (codec_context_->pix_fmt) { case PIX_FMT_YUV420P: case PIX_FMT_YUVJ420P: return VideoFrame::YV12; break; case PIX_FMT_YUV422P: case PIX_FMT_YUVJ422P: return VideoFrame::YV16; break; default: // TODO(scherkus): More formats here? return VideoFrame::INVALID; } } } // namespace media
// 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 "media/filters/ffmpeg_video_decode_engine.h" #include "base/task.h" #include "media/base/buffers.h" #include "media/base/callback.h" #include "media/base/limits.h" #include "media/ffmpeg/ffmpeg_common.h" #include "media/ffmpeg/ffmpeg_util.h" #include "media/filters/ffmpeg_demuxer.h" namespace media { FFmpegVideoDecodeEngine::FFmpegVideoDecodeEngine() : codec_context_(NULL), state_(kCreated) { } FFmpegVideoDecodeEngine::~FFmpegVideoDecodeEngine() { } void FFmpegVideoDecodeEngine::Initialize(AVStream* stream, Task* done_cb) { AutoTaskRunner done_runner(done_cb); // Always try to use two threads for video decoding. There is little reason // not to since current day CPUs tend to be multi-core and we measured // performance benefits on older machines such as P4s with hyperthreading. // // Handling decoding on separate threads also frees up the pipeline thread to // continue processing. Although it'd be nice to have the option of a single // decoding thread, FFmpeg treats having one thread the same as having zero // threads (i.e., avcodec_decode_video() will execute on the calling thread). // Yet another reason for having two threads :) static const int kDecodeThreads = 2; CHECK(state_ == kCreated); codec_context_ = stream->codec; codec_context_->flags2 |= CODEC_FLAG2_FAST; // Enable faster H264 decode. // Enable motion vector search (potentially slow), strong deblocking filter // for damaged macroblocks, and set our error detection sensitivity. codec_context_->error_concealment = FF_EC_GUESS_MVS | FF_EC_DEBLOCK; codec_context_->error_recognition = FF_ER_CAREFUL; AVCodec* codec = avcodec_find_decoder(codec_context_->codec_id); // TODO(fbarchard): On next ffmpeg roll, retest Theora multi-threading. int decode_threads = (codec_context_->codec_id == CODEC_ID_THEORA) ? 1 : kDecodeThreads; // We don't allocate AVFrame on the stack since different versions of FFmpeg // may change the size of AVFrame, causing stack corruption. The solution is // to let FFmpeg allocate the structure via avcodec_alloc_frame(). av_frame_.reset(avcodec_alloc_frame()); if (codec && avcodec_thread_init(codec_context_, decode_threads) >= 0 && avcodec_open(codec_context_, codec) >= 0 && av_frame_.get()) { state_ = kNormal; } else { state_ = kError; } } static void CopyPlane(size_t plane, scoped_refptr<VideoFrame> video_frame, const AVFrame* frame) { DCHECK(video_frame->width() % 2 == 0); const uint8* source = frame->data[plane]; const size_t source_stride = frame->linesize[plane]; uint8* dest = video_frame->data(plane); const size_t dest_stride = video_frame->stride(plane); size_t bytes_per_line = video_frame->width(); size_t copy_lines = video_frame->height(); if (plane != VideoFrame::kYPlane) { bytes_per_line /= 2; if (video_frame->format() == VideoFrame::YV12) { copy_lines = (copy_lines + 1) / 2; } } DCHECK(bytes_per_line <= source_stride && bytes_per_line <= dest_stride); for (size_t i = 0; i < copy_lines; ++i) { memcpy(dest, source, bytes_per_line); source += source_stride; dest += dest_stride; } } // Decodes one frame of video with the given buffer. void FFmpegVideoDecodeEngine::DecodeFrame( Buffer* buffer, scoped_refptr<VideoFrame>* video_frame, bool* got_frame, Task* done_cb) { AutoTaskRunner done_runner(done_cb); *got_frame = false; *video_frame = NULL; // Create a packet for input data. // Due to FFmpeg API changes we no longer have const read-only pointers. AVPacket packet; av_init_packet(&packet); packet.data = const_cast<uint8*>(buffer->GetData()); packet.size = buffer->GetDataSize(); int frame_decoded = 0; int result = avcodec_decode_video2(codec_context_, av_frame_.get(), &frame_decoded, &packet); // Log the problem if we can't decode a video frame and exit early. if (result < 0) { LOG(INFO) << "Error decoding a video frame with timestamp: " << buffer->GetTimestamp().InMicroseconds() << " us" << " , duration: " << buffer->GetDuration().InMicroseconds() << " us" << " , packet size: " << buffer->GetDataSize() << " bytes"; *got_frame = false; return; } // If frame_decoded == 0, then no frame was produced. *got_frame = frame_decoded != 0; if (!*got_frame) { return; } // TODO(fbarchard): Work around for FFmpeg http://crbug.com/27675 // The decoder is in a bad state and not decoding correctly. // Checking for NULL avoids a crash in CopyPlane(). if (!av_frame_->data[VideoFrame::kYPlane] || !av_frame_->data[VideoFrame::kUPlane] || !av_frame_->data[VideoFrame::kVPlane]) { // TODO(jiesun): this is also an error case handled as normal. *got_frame = false; return; } VideoFrame::CreateFrame(GetSurfaceFormat(), codec_context_->width, codec_context_->height, StreamSample::kInvalidTimestamp, StreamSample::kInvalidTimestamp, video_frame); if (!video_frame->get()) { // TODO(jiesun): this is also an error case handled as normal. *got_frame = false; return; } // Copy the frame data since FFmpeg reuses internal buffers for AVFrame // output, meaning the data is only valid until the next // avcodec_decode_video() call. // TODO(scherkus): figure out pre-allocation/buffer cycling scheme. // TODO(scherkus): is there a cleaner way to figure out the # of planes? CopyPlane(VideoFrame::kYPlane, video_frame->get(), av_frame_.get()); CopyPlane(VideoFrame::kUPlane, video_frame->get(), av_frame_.get()); CopyPlane(VideoFrame::kVPlane, video_frame->get(), av_frame_.get()); DCHECK_LE(av_frame_->repeat_pict, 2); // Sanity check. (*video_frame)->SetRepeatCount(av_frame_->repeat_pict); } void FFmpegVideoDecodeEngine::Flush(Task* done_cb) { AutoTaskRunner done_runner(done_cb); avcodec_flush_buffers(codec_context_); } VideoFrame::Format FFmpegVideoDecodeEngine::GetSurfaceFormat() const { // J (Motion JPEG) versions of YUV are full range 0..255. // Regular (MPEG) YUV is 16..240. // For now we will ignore the distinction and treat them the same. switch (codec_context_->pix_fmt) { case PIX_FMT_YUV420P: case PIX_FMT_YUVJ420P: return VideoFrame::YV12; break; case PIX_FMT_YUV422P: case PIX_FMT_YUVJ422P: return VideoFrame::YV16; break; default: // TODO(scherkus): More formats here? return VideoFrame::INVALID; } } } // namespace media
Fix nested ifs and incorrect indentation in ffmpeg_video_decode_engine.cc.
Fix nested ifs and incorrect indentation in ffmpeg_video_decode_engine.cc. No logic change, just inserting returns and de-nesting ifs. BUG=none TEST=media_unittests Review URL: http://codereview.chromium.org/1735012 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@45788 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
adobe/chromium,gavinp/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,gavinp/chromium,yitian134/chromium,ropik/chromium,ropik/chromium,ropik/chromium,adobe/chromium,yitian134/chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,ropik/chromium,gavinp/chromium,adobe/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,adobe/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,yitian134/chromium,ropik/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,yitian134/chromium,ropik/chromium
20d280d404b42a0eb48dcc025c2c14a697d376a7
mjolnir/input/read_external_interaction.hpp
mjolnir/input/read_external_interaction.hpp
#ifndef MJOLNIR_READ_EXTERNAL_INTERACTION_HPP #define MJOLNIR_READ_EXTERNAL_INTERACTION_HPP #include <extlib/toml/toml.hpp> #include <mjolnir/interaction/ExternalDistanceInteraction.hpp> #include <mjolnir/core/AxisAlignedPlane.hpp> #include <mjolnir/util/make_unique.hpp> #include <mjolnir/util/throw_exception.hpp> #include <mjolnir/util/get_toml_value.hpp> #include <mjolnir/util/logger.hpp> #include <mjolnir/input/read_external_potential.hpp> #include <memory> namespace mjolnir { // ---------------------------------------------------------------------------- // external interaction // ---------------------------------------------------------------------------- template<typename traitsT, typename shapeT> std::unique_ptr<ExternalForceInteractionBase<traitsT>> read_external_distance_interaction(const toml::Table& external, shapeT&& shape) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_SCOPE(read_global_distance_interaction(), 0); using real_type = typename traitsT::real_type; const auto potential = get_toml_value<std::string>( external, "potential", "[forcefield.external]"); if(potential == "ImplicitMembrane") { MJOLNIR_LOG_NOTICE("-- potential functions is Implicit Membrane."); using potential_t = ImplicitMembranePotential<real_type>; using interaction_t = ExternalDistanceInteraction< traitsT, potential_t, shapeT>; return make_unique<interaction_t>(std::move(shape), read_implicit_membrane_potential<real_type>(external)); } else if(potential == "LennardJonesWall") { MJOLNIR_LOG_NOTICE("-- potential functions is Lennard-Jones."); using potential_t = LennardJonesWallPotential<real_type>; using interaction_t = ExternalDistanceInteraction< traitsT, potential_t, shapeT>; return make_unique<interaction_t>(std::move(shape), read_lennard_jones_wall_potential<real_type>(external)); } else if(potential == "ExcludedVolumeWall") { MJOLNIR_LOG_NOTICE("-- potential functions is Excluded-Volume."); using potential_t = ExcludedVolumeWallPotential<real_type>; using interaction_t = ExternalDistanceInteraction< traitsT, potential_t, shapeT>; return make_unique<interaction_t>(std::move(shape), read_excluded_volume_wall_potential<real_type>(external)); } else { throw_exception<std::runtime_error>( "invalid potential as ExternalDistanceInteraction: ", potential); } } template<typename traitsT> std::unique_ptr<ExternalForceInteractionBase<traitsT>> read_external_distance_interaction_shape(const toml::Table& external) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_SCOPE(read_global_distance_interaction(), 0); using real_type = typename traitsT::real_type; const auto shape = get_toml_value<toml::Table>(external, "shape", "[forcefield.external] for ExternalDistance"); const auto name = get_toml_value<std::string>(shape, "name", "[forcefield.external.shape] for ExternalDistance"); if(name == "AxisAlignedPlane") { const auto pos = get_toml_value<real_type>(shape, "position", "[forcefield.external.shape] for ExternalDistance"); const auto margin = get_toml_value<real_type>(shape, "margin", "[forcefield.external.shape] for ExternalDistance"); MJOLNIR_LOG_INFO("pos = ", pos); MJOLNIR_LOG_INFO("margin = ", margin); const auto axis = get_toml_value<std::string>(shape, "axis", "[forcefield.external.shape] for ExternalDistance"); MJOLNIR_LOG_INFO("axis = ", axis); if(axis == "X" || axis == "+X") { MJOLNIR_LOG_NOTICE("-- interaction shape is YZ-Plane (+)."); using shape_t = AxisAlignedPlane<traitsT, PositiveXDirection>; return read_external_distance_interaction<traitsT, shape_t>( external, shape_t(pos, margin)); } else if(axis == "-X") { MJOLNIR_LOG_NOTICE("-- interaction shape is YZ-Plane (-)."); using shape_t = AxisAlignedPlane<traitsT, NegativeXDirection>; return read_external_distance_interaction<traitsT, shape_t>( external, shape_t(pos, margin)); } else if(axis == "Y" || axis == "+Y") { MJOLNIR_LOG_NOTICE("-- interaction shape is ZX-Plane (+)."); using shape_t = AxisAlignedPlane<traitsT, PositiveYDirection>; return read_external_distance_interaction<traitsT, shape_t>( external, shape_t(pos, margin)); } else if(axis == "-Y") { MJOLNIR_LOG_NOTICE("-- interaction shape is ZX-Plane (-)."); using shape_t = AxisAlignedPlane<traitsT, NegativeYDirection>; return read_external_distance_interaction<traitsT, shape_t>( external, shape_t(pos, margin)); } else if(axis == "Z" || axis == "+Z") { MJOLNIR_LOG_NOTICE("-- interaction shape is XY-Plane (+)."); using shape_t = AxisAlignedPlane<traitsT, PositiveZDirection>; return read_external_distance_interaction<traitsT, shape_t>( external, shape_t(pos, margin)); } else if(axis == "-Z") { MJOLNIR_LOG_NOTICE("-- interaction shape is XY-Plane (-)."); using shape_t = AxisAlignedPlane<traitsT, NegativeZDirection>; return read_external_distance_interaction<traitsT, shape_t>( external, shape_t(pos, margin)); } else { throw std::runtime_error("invalid axis name: " + axis); } } else { throw std::runtime_error("invalid external forcefield shape: " + name); } } // ---------------------------------------------------------------------------- // general read_external_interaction function // ---------------------------------------------------------------------------- template<typename traitsT> std::unique_ptr<ExternalForceInteractionBase<traitsT>> read_external_interaction(const toml::Table& external) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_SCOPE(read_external_interaction(), 0); const auto interaction = get_toml_value<std::string>( external, "interaction", "[forcefields.external]"); if(interaction == "Distance") { MJOLNIR_LOG_NOTICE("Distance interaction found."); return read_external_distance_interaction_shape<traitsT>(external); } else { throw std::runtime_error( "invalid external interaction type: " + interaction); } } } // mjolnir #endif// MJOLNIR_READ_EXTERNAL_INTERACTION_HPP
#ifndef MJOLNIR_READ_EXTERNAL_INTERACTION_HPP #define MJOLNIR_READ_EXTERNAL_INTERACTION_HPP #include <extlib/toml/toml.hpp> #include <mjolnir/interaction/ExternalDistanceInteraction.hpp> #include <mjolnir/core/AxisAlignedPlane.hpp> #include <mjolnir/util/make_unique.hpp> #include <mjolnir/util/throw_exception.hpp> #include <mjolnir/util/logger.hpp> #include <mjolnir/input/read_external_potential.hpp> #include <memory> namespace mjolnir { // ---------------------------------------------------------------------------- // external interaction // ---------------------------------------------------------------------------- template<typename traitsT, typename shapeT> std::unique_ptr<ExternalForceInteractionBase<traitsT>> read_external_distance_interaction(const toml::value& external, shapeT&& shape) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_SCOPE(read_global_distance_interaction(), 0); using real_type = typename traitsT::real_type; const auto potential = toml::find<std::string>(external, "potential"); if(potential == "ImplicitMembrane") { MJOLNIR_LOG_NOTICE("-- potential functions is Implicit Membrane."); using potential_t = ImplicitMembranePotential<real_type>; using interaction_t = ExternalDistanceInteraction< traitsT, potential_t, shapeT>; return make_unique<interaction_t>(std::move(shape), read_implicit_membrane_potential<real_type>(external)); } else if(potential == "LennardJonesWall") { MJOLNIR_LOG_NOTICE("-- potential functions is Lennard-Jones."); using potential_t = LennardJonesWallPotential<real_type>; using interaction_t = ExternalDistanceInteraction< traitsT, potential_t, shapeT>; return make_unique<interaction_t>(std::move(shape), read_lennard_jones_wall_potential<real_type>(external)); } else if(potential == "ExcludedVolumeWall") { MJOLNIR_LOG_NOTICE("-- potential functions is Excluded-Volume."); using potential_t = ExcludedVolumeWallPotential<real_type>; using interaction_t = ExternalDistanceInteraction< traitsT, potential_t, shapeT>; return make_unique<interaction_t>(std::move(shape), read_excluded_volume_wall_potential<real_type>(external)); } else { throw_exception<std::runtime_error>(toml::format_error("[error] " "mjolnir::read_external_distance_interaction: invalid potential", toml::find<toml::value>(external, "potential"), "here", { "expected value is one of the following.", "- \"ExcludedVolumeWall\": repulsive r^12 potential", "- \"LennardJonesWall\" : famous r^12 - r^6 potential", "- \"ImplicitMembrane\" : single-well interaction that models a membrane" })); } } template<typename traitsT> std::unique_ptr<ExternalForceInteractionBase<traitsT>> read_external_distance_interaction_shape(const toml::value& external) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_SCOPE(read_global_distance_interaction(), 0); using real_type = typename traitsT::real_type; const auto shape = toml::find<toml::value>(external, "shape"); const auto name = toml::find<std::string>(shape, "name"); if(name == "AxisAlignedPlane") { const auto pos = toml::find<real_type>(shape, "position"); const auto margin = toml::find<real_type>(shape, "margin"); MJOLNIR_LOG_INFO("pos = ", pos); MJOLNIR_LOG_INFO("margin = ", margin); const auto axis = toml::find<std::string>(shape, "axis"); MJOLNIR_LOG_INFO("axis = ", axis); if(axis == "X" || axis == "+X") { MJOLNIR_LOG_NOTICE("-- interaction shape is YZ-Plane (+)."); using shape_t = AxisAlignedPlane<traitsT, PositiveXDirection>; return read_external_distance_interaction<traitsT, shape_t>( external, shape_t(pos, margin)); } else if(axis == "-X") { MJOLNIR_LOG_NOTICE("-- interaction shape is YZ-Plane (-)."); using shape_t = AxisAlignedPlane<traitsT, NegativeXDirection>; return read_external_distance_interaction<traitsT, shape_t>( external, shape_t(pos, margin)); } else if(axis == "Y" || axis == "+Y") { MJOLNIR_LOG_NOTICE("-- interaction shape is ZX-Plane (+)."); using shape_t = AxisAlignedPlane<traitsT, PositiveYDirection>; return read_external_distance_interaction<traitsT, shape_t>( external, shape_t(pos, margin)); } else if(axis == "-Y") { MJOLNIR_LOG_NOTICE("-- interaction shape is ZX-Plane (-)."); using shape_t = AxisAlignedPlane<traitsT, NegativeYDirection>; return read_external_distance_interaction<traitsT, shape_t>( external, shape_t(pos, margin)); } else if(axis == "Z" || axis == "+Z") { MJOLNIR_LOG_NOTICE("-- interaction shape is XY-Plane (+)."); using shape_t = AxisAlignedPlane<traitsT, PositiveZDirection>; return read_external_distance_interaction<traitsT, shape_t>( external, shape_t(pos, margin)); } else if(axis == "-Z") { MJOLNIR_LOG_NOTICE("-- interaction shape is XY-Plane (-)."); using shape_t = AxisAlignedPlane<traitsT, NegativeZDirection>; return read_external_distance_interaction<traitsT, shape_t>( external, shape_t(pos, margin)); } else { throw_exception<std::runtime_error>(toml::format_error("[error] " "mjolnir::read_external_distance_interaction_shape: invalid shape", toml::find<toml::value>(external, "shape"), "expected [+-]?[XYZ]")); } } else { throw std::runtime_error("invalid external forcefield shape: " + name); } } // ---------------------------------------------------------------------------- // general read_external_interaction function // ---------------------------------------------------------------------------- template<typename traitsT> std::unique_ptr<ExternalForceInteractionBase<traitsT>> read_external_interaction(const toml::value& external) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_SCOPE(read_external_interaction(), 0); const auto interaction = toml::find<std::string>(external, "interaction"); if(interaction == "Distance") { MJOLNIR_LOG_NOTICE("Distance interaction found."); return read_external_distance_interaction_shape<traitsT>(external); } else { throw std::runtime_error(toml::format_error("[error] " "mjolnir::read_external_interaction: invalid interaction", toml::find<toml::value>(external, "interaction"), "here", { "expected value is one of the following.", "- \"Distance\": interaction depending on the distance between particle and spatial structure" })); } } } // mjolnir #endif// MJOLNIR_READ_EXTERNAL_INTERACTION_HPP
refactor read_external_interaction w/ toml11-v2 features
refactor read_external_interaction w/ toml11-v2 features
C++
mit
ToruNiina/Mjolnir,ToruNiina/Mjolnir,ToruNiina/Mjolnir
fc35b267ac0b9bc755ada51c7bfb53e1970ac6b0
pw_string/format_test.cc
pw_string/format_test.cc
// Copyright 2019 The Pigweed Authors // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // https://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 "pw_string/format.h" #include <cstdarg> #include "gtest/gtest.h" #include "pw_span/span.h" namespace pw::string { namespace { TEST(Format, ValidFormatString_Succeeds) { char buffer[32]; auto result = Format(buffer, "-_-"); EXPECT_EQ(Status::OK, result.status()); EXPECT_EQ(3u, result.size()); EXPECT_STREQ("-_-", buffer); } TEST(Format, ValidFormatStringAndArguments_Succeeds) { char buffer[32]; auto result = Format(buffer, "%d4%s", 123, "5"); EXPECT_EQ(Status::OK, result.status()); EXPECT_EQ(5u, result.size()); EXPECT_STREQ("12345", buffer); } TEST(Format, InvalidConversionSpecifier_ReturnsInvalidArgumentAndTerminates) { char buffer[32] = {'?', '?', '?', '?', '\0'}; // Make the format string volatile to prevent the compiler from potentially // checking this as a format string. const char* volatile fmt = "abc %9999999999999999999999999999999999d4%s"; if (std::snprintf(buffer, sizeof(buffer), fmt, 123, "5") >= 0) { // This snprintf implementation does not detect invalid format strings. return; } auto result = Format(buffer, fmt, 123, "5"); EXPECT_EQ(Status::INVALID_ARGUMENT, result.status()); EXPECT_STREQ("", buffer); } TEST(Format, EmptyBuffer_ReturnsResourceExhausted) { auto result = Format(span<char>(), "?"); EXPECT_EQ(Status::RESOURCE_EXHAUSTED, result.status()); EXPECT_EQ(0u, result.size()); } TEST(Format, FormatLargerThanBuffer_ReturnsResourceExhausted) { char buffer[5]; auto result = Format(buffer, "2big!"); EXPECT_EQ(Status::RESOURCE_EXHAUSTED, result.status()); EXPECT_EQ(4u, result.size()); EXPECT_STREQ("2big", buffer); } TEST(Format, ArgumentLargerThanBuffer_ReturnsResourceExhausted) { char buffer[5]; auto result = Format(buffer, "%s", "2big!"); EXPECT_EQ(Status::RESOURCE_EXHAUSTED, result.status()); EXPECT_EQ(4u, result.size()); EXPECT_STREQ("2big", buffer); } StatusWithSize CallFormatWithVaList(span<char> buffer, const char* fmt, ...) { va_list args; va_start(args, fmt); StatusWithSize result = FormatVaList(buffer, fmt, args); va_end(args); return result; } TEST(Format, CallFormatWithVaList_CallsCorrectFormatOverload) { char buffer[8]; auto result = CallFormatWithVaList(buffer, "Yo%s", "?!"); EXPECT_EQ(Status::OK, result.status()); EXPECT_EQ(4u, result.size()); EXPECT_STREQ("Yo?!", buffer); } } // namespace } // namespace pw::string
// Copyright 2019 The Pigweed Authors // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // https://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 "pw_string/format.h" #include <cstdarg> #include "gtest/gtest.h" #include "pw_span/span.h" namespace pw::string { namespace { TEST(Format, ValidFormatString_Succeeds) { char buffer[32]; auto result = Format(buffer, "-_-"); EXPECT_EQ(Status::OK, result.status()); EXPECT_EQ(3u, result.size()); EXPECT_STREQ("-_-", buffer); } TEST(Format, ValidFormatStringAndArguments_Succeeds) { char buffer[32]; auto result = Format(buffer, "%d4%s", 123, "5"); EXPECT_EQ(Status::OK, result.status()); EXPECT_EQ(5u, result.size()); EXPECT_STREQ("12345", buffer); } TEST(Format, EmptyBuffer_ReturnsResourceExhausted) { auto result = Format(span<char>(), "?"); EXPECT_EQ(Status::RESOURCE_EXHAUSTED, result.status()); EXPECT_EQ(0u, result.size()); } TEST(Format, FormatLargerThanBuffer_ReturnsResourceExhausted) { char buffer[5]; auto result = Format(buffer, "2big!"); EXPECT_EQ(Status::RESOURCE_EXHAUSTED, result.status()); EXPECT_EQ(4u, result.size()); EXPECT_STREQ("2big", buffer); } TEST(Format, ArgumentLargerThanBuffer_ReturnsResourceExhausted) { char buffer[5]; auto result = Format(buffer, "%s", "2big!"); EXPECT_EQ(Status::RESOURCE_EXHAUSTED, result.status()); EXPECT_EQ(4u, result.size()); EXPECT_STREQ("2big", buffer); } StatusWithSize CallFormatWithVaList(span<char> buffer, const char* fmt, ...) { va_list args; va_start(args, fmt); StatusWithSize result = FormatVaList(buffer, fmt, args); va_end(args); return result; } TEST(Format, CallFormatWithVaList_CallsCorrectFormatOverload) { char buffer[8]; auto result = CallFormatWithVaList(buffer, "Yo%s", "?!"); EXPECT_EQ(Status::OK, result.status()); EXPECT_EQ(4u, result.size()); EXPECT_STREQ("Yo?!", buffer); } } // namespace } // namespace pw::string
Remove problematic test
pw_string: Remove problematic test Remove a test that attempts to trigger a negative (error) return value for snprintf. The format strings that trigger these errors vary by platform, and a format that returns a negative result on one platform (Linux) may crash another (Windows). Change-Id: I7b60bc301cd534d0e78228829ea6288687e05c43
C++
apache-2.0
google/pigweed,google/pigweed,google/pigweed,google/pigweed,google/pigweed,google/pigweed,google/pigweed,google/pigweed,google/pigweed,google/pigweed
ba344d8ce81804cb7d36f9891ee24afa3624660f
autotests/vktestbase.cpp
autotests/vktestbase.cpp
/* * Unit tests for libkvkontakte. * Copyright (C) 2015 Alexander Potashev <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "vktestbase.h" #include "vkapi.h" #include <QtCore/QEventLoop> #include <QtCore/QFile> #include <QtCore/QTextStream> #include <QtTest/QTest> #define VK_APP_ID "2446321" VkTestBase::VkTestBase() : m_vkapi(0) { } VkTestBase::~VkTestBase() { if (m_vkapi) { delete m_vkapi; } } QString VkTestBase::getSavedToken() const { QFile file(AUTOTESTS_API_TOKEN_PATH); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { return QString(); } QTextStream in(&file); QString line = in.readLine(); return line.trimmed(); } void VkTestBase::authenticate() { m_vkapi = new KIPIVkontaktePlugin::VkApi(0); m_vkapi->setAppId(VK_APP_ID); // TODO: library should better not crash if setAppId is not called m_vkapi->setRequiredPermissions( Vkontakte::AppPermissions::Photos | Vkontakte::AppPermissions::Offline | Vkontakte::AppPermissions::Notes | Vkontakte::AppPermissions::Messages); QString token = getSavedToken(); if (!token.isEmpty()) { m_vkapi->setInitialAccessToken(token); } m_vkapi->startAuthentication(false); // Wait for any outcome of the authentication process, including failure QEventLoop loop; connect(m_vkapi, SIGNAL(authenticated()), &loop, SLOT(quit())); connect(m_vkapi, SIGNAL(canceled()), &loop, SLOT(quit())); loop.exec(); QVERIFY(m_vkapi->isAuthenticated()); } QString VkTestBase::accessToken() const { return m_vkapi->accessToken(); } #include "vktestbase.moc"
/* * Unit tests for libkvkontakte. * Copyright (C) 2015 Alexander Potashev <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "vktestbase.h" #include "vkapi.h" #include <QtCore/QEventLoop> #include <QtCore/QFile> #include <QtCore/QTextStream> #include <QtTest/QTest> #define VK_APP_ID "2446321" VkTestBase::VkTestBase() : m_vkapi(new KIPIVkontaktePlugin::VkApi(0)) { } VkTestBase::~VkTestBase() { if (m_vkapi) { delete m_vkapi; } } QString VkTestBase::getSavedToken() const { QFile file(AUTOTESTS_API_TOKEN_PATH); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { return QString(); } QTextStream in(&file); QString line = in.readLine(); return line.trimmed(); } void VkTestBase::authenticate() { m_vkapi->setAppId(VK_APP_ID); // TODO: library should better not crash if setAppId is not called m_vkapi->setRequiredPermissions( Vkontakte::AppPermissions::Photos | Vkontakte::AppPermissions::Offline | Vkontakte::AppPermissions::Notes | Vkontakte::AppPermissions::Messages); QString token = getSavedToken(); if (!token.isEmpty()) { m_vkapi->setInitialAccessToken(token); } m_vkapi->startAuthentication(false); // Wait for any outcome of the authentication process, including failure QEventLoop loop; connect(m_vkapi, SIGNAL(authenticated()), &loop, SLOT(quit())); connect(m_vkapi, SIGNAL(canceled()), &loop, SLOT(quit())); loop.exec(); QVERIFY(m_vkapi->isAuthenticated()); } QString VkTestBase::accessToken() const { return m_vkapi->accessToken(); } #include "vktestbase.moc"
Fix crash in VkTestBase::accessToken() if authenticate() was not called
autotests: Fix crash in VkTestBase::accessToken() if authenticate() was not called
C++
lgpl-2.1
KDE/libkvkontakte,KDE/libkvkontakte
223fa4f0ce6fde93d646afa547828fb38807ce5f
tracking/save_camera_images.cpp
tracking/save_camera_images.cpp
#include "FlyCapture2.h" #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream> #include <fstream> #include <boost/filesystem.hpp> #include <boost/date_time/posix_time/posix_time.hpp> static void help() { std::cout << "------------------------------------------------------------------------------" << std::endl << "This program writes image files from camera." << std::endl << "Usage:" << std::endl << "save-camera-images output_path_base" << std::endl << "------------------------------------------------------------------------------" << std::endl << std::endl; } boost::filesystem::path createDirectory(const boost::filesystem::path &path) { if (!boost::filesystem::exists(path)) { if(boost::filesystem::create_directory(path)) { std::cout << "Created directory: " << path << std::endl; } else { std::cout << "Unable to create directory: " << path << std::endl; } } else if (boost::filesystem::is_directory(path)) { std::cout << "Directory exists: " << path << std::endl; } else { std::cout << "Error! " << path << " exists, but is not a directory!" << std::endl; } return path; } int main(int argc, char *argv[]) { help(); if (argc != 2) { std::cout << "Not enough parameters" << std::endl; return -1; } // Create base directory boost::filesystem::path output_path_base(argv[1]); createDirectory(output_path_base); // Create directory for saving images boost::posix_time::ptime date_time = boost::posix_time::second_clock::local_time(); std::string date_time_string = boost::posix_time::to_iso_string(date_time); boost::filesystem::path output_dir(date_time_string); boost::filesystem::path output_path = output_path_base / output_dir; createDirectory(output_path); // Save information about run into file boost::filesystem::path run_info_file_path("run_info"); boost::filesystem::path run_info_file_path_full = output_path_base / run_info_file_path; std::ofstream run_info_file; run_info_file.open(run_info_file_path_full.string().c_str()); run_info_file << output_path << std::endl; run_info_file.close(); // Setup image parameters std::vector<int> compression_params; compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION); compression_params.push_back(0); // Connect the camera FlyCapture2::Error error; FlyCapture2::Camera camera; FlyCapture2::CameraInfo camInfo; error = camera.Connect( 0 ); if ( error != FlyCapture2::PGRERROR_OK ) { std::cout << "Failed to connect to camera" << std::endl; return false; } // Get the camera info and print it out error = camera.GetCameraInfo( &camInfo ); if ( error != FlyCapture2::PGRERROR_OK ) { std::cout << "Failed to get camera info from camera" << std::endl; return false; } std::cout << camInfo.vendorName << " " << camInfo.modelName << " " << camInfo.serialNumber << std::endl; error = camera.StartCapture(); if ( error == FlyCapture2::PGRERROR_ISOCH_BANDWIDTH_EXCEEDED ) { std::cout << "Bandwidth exceeded" << std::endl; return false; } else if ( error != FlyCapture2::PGRERROR_OK ) { std::cout << "Failed to start image capture" << std::endl; return false; } // Capture loop char key = 0; while(key != 'q') { // Get the image FlyCapture2::Image rawImage; FlyCapture2::Error error = camera.RetrieveBuffer( &rawImage ); if ( error != FlyCapture2::PGRERROR_OK ) { std::cout << "capture error" << std::endl; continue; } // Convert to rgb FlyCapture2::Image rgbImage; rawImage.Convert( FlyCapture2::PIXEL_FORMAT_BGR, &rgbImage ); // Convert to OpenCV Mat unsigned int rowBytes = (double)rgbImage.GetReceivedDataSize()/(double)rgbImage.GetRows(); cv::Mat image = cv::Mat(rgbImage.GetRows(), rgbImage.GetCols(), CV_8UC3, rgbImage.GetData(),rowBytes); // Show image // cv::imshow("image", image); // key = cv::waitKey(30); // Create full image output path date_time = boost::posix_time::microsec_clock::local_time(); std::string time_string = boost::posix_time::to_iso_string(date_time); std::ostringstream image_file_name; image_file_name << time_string << ".png"; std::string image_file_name_string = image_file_name.str(); boost::filesystem::path output_file_name_path(image_file_name_string); boost::filesystem::path output_path_full = output_path / output_file_name_path; // Write image to file cv::imwrite(output_path_full.string(),image,compression_params); } error = camera.StopCapture(); if ( error != FlyCapture2::PGRERROR_OK ) { // This may fail when the camera was removed, so don't show // an error message } camera.Disconnect(); return 0; }
#include "FlyCapture2.h" #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream> #include <fstream> #include <boost/filesystem.hpp> #include <boost/date_time/posix_time/posix_time.hpp> static void help() { std::cout << "------------------------------------------------------------------------------" << std::endl << "This program writes image files from camera." << std::endl << "Usage:" << std::endl << "save-camera-images output_path_base" << std::endl << "------------------------------------------------------------------------------" << std::endl << std::endl; } boost::filesystem::path createDirectory(const boost::filesystem::path &path) { if (!boost::filesystem::exists(path)) { if(boost::filesystem::create_directory(path)) { std::cout << "Created directory: " << path << std::endl; } else { std::cout << "Unable to create directory: " << path << std::endl; } } else if (boost::filesystem::is_directory(path)) { std::cout << "Directory exists: " << path << std::endl; } else { std::cout << "Error! " << path << " exists, but is not a directory!" << std::endl; } return path; } int main(int argc, char *argv[]) { help(); if (argc != 2) { std::cout << "Not enough parameters" << std::endl; return -1; } // Create base directory boost::filesystem::path output_path_base(argv[1]); createDirectory(output_path_base); // Create directory for saving images boost::posix_time::ptime date_time = boost::posix_time::second_clock::local_time(); std::string date_time_string = boost::posix_time::to_iso_string(date_time); boost::filesystem::path output_dir(date_time_string); boost::filesystem::path output_path = output_path_base / output_dir; createDirectory(output_path); // Save information about run into file boost::filesystem::path run_info_file_path("run_info"); boost::filesystem::path run_info_file_path_full = output_path_base / run_info_file_path; std::ofstream run_info_file; run_info_file.open(run_info_file_path_full.string().c_str()); run_info_file << output_path << std::endl; run_info_file.close(); // Setup image parameters std::vector<int> compression_params; compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION); compression_params.push_back(0); // Connect the camera FlyCapture2::Error error; FlyCapture2::Camera camera; FlyCapture2::CameraInfo camInfo; error = camera.Connect( 0 ); if (error != FlyCapture2::PGRERROR_OK) { std::cout << "Failed to connect to camera" << std::endl; return false; } // Get the camera info and print it out error = camera.GetCameraInfo(&camInfo); if (error != FlyCapture2::PGRERROR_OK) { std::cout << "Failed to get camera info from camera" << std::endl; return false; } std::cout << camInfo.vendorName << " " << camInfo.modelName << " " << camInfo.serialNumber << std::endl; error = camera.StartCapture(); if (error == FlyCapture2::PGRERROR_ISOCH_BANDWIDTH_EXCEEDED) { std::cout << "Bandwidth exceeded" << std::endl; return false; } else if (error != FlyCapture2::PGRERROR_OK) { std::cout << "Failed to start image capture" << std::endl; return false; } // Capture loop char key = 0; while(key != 'q') { // Get the image FlyCapture2::Image rawImage; FlyCapture2::Error error = camera.RetrieveBuffer(&rawImage); if (error != FlyCapture2::PGRERROR_OK) { std::cout << "capture error" << std::endl; continue; } // Convert to rgb FlyCapture2::Image rgbImage; rawImage.Convert(FlyCapture2::PIXEL_FORMAT_BGR, &rgbImage); // Convert to OpenCV Mat unsigned int rowBytes = (double)rgbImage.GetReceivedDataSize()/(double)rgbImage.GetRows(); cv::Mat image = cv::Mat(rgbImage.GetRows(), rgbImage.GetCols(), CV_8UC3, rgbImage.GetData(),rowBytes); // Convert to grayscale cv::Mat image_gray; cv::cvtColor(image, image_gray, CV_BGR2GRAY); // Show image // cv::imshow("image", image_gray); // key = cv::waitKey(30); // Create full image output path date_time = boost::posix_time::microsec_clock::local_time(); std::string time_string = boost::posix_time::to_iso_string(date_time); std::ostringstream image_file_name; image_file_name << time_string << ".png"; std::string image_file_name_string = image_file_name.str(); boost::filesystem::path output_file_name_path(image_file_name_string); boost::filesystem::path output_path_full = output_path / output_file_name_path; // Write image to file cv::imwrite(output_path_full.string(),image_gray,compression_params); } error = camera.StopCapture(); if (error != FlyCapture2::PGRERROR_OK) { // This may fail when the camera was removed, so don't show // an error message } camera.Disconnect(); return 0; }
Convert image to grayscale before saving.
Convert image to grayscale before saving.
C++
bsd-3-clause
janelia-idf/stern_odor_rig,peterpolidoro/stern_odor_rig,peterpolidoro/stern_odor_rig,JaneliaSciComp/stern_odor_rig,JaneliaSciComp/stern_odor_rig,JaneliaSciComp/stern_odor_rig,peterpolidoro/stern_odor_rig,janelia-idf/stern_odor_rig,janelia-idf/stern_odor_rig
3f044c0803b245b8ddfa80cb5e05425f2d5ebacf
Code/UtilitiesAdapters/OssimAdapters/otbAeronetFileReader.cxx
Code/UtilitiesAdapters/OssimAdapters/otbAeronetFileReader.cxx
/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbAeronetFileReader.h" #include <fstream> #include <iostream> #include <iomanip> #include "otbMath.h" #include "otbAeronetData.h" #include "ossim/base/ossimDate.h" namespace otb { namespace internal { /** * Generate date method */ ossimLocalTm ParseDate(const std::string& date, const std::string& time) { ossimLocalTm currentDate; ossimString word(""); word = date[0]; word += date[1]; currentDate.setDay(word.toInt()); word = date[3]; word += date[4]; currentDate.setMonth(word.toInt()); word = date[6]; word += date[7]; word += date[8]; word += date[9]; currentDate.setYear(word.toInt()); word = time[0]; word += time[1]; currentDate.setHour(word.toInt()); word = time[3]; word += time[4]; currentDate.setMin(word.toInt()); word = time[6]; word += time[7]; currentDate.setSec(word.toInt()); return currentDate; } } /** * Constructor */ AeronetFileReader ::AeronetFileReader() : m_FileName(""), m_Day(1), m_Month(1), m_Year(2000), m_Hour(12), m_Minute(0), m_Epsilon(0.4) { this->Superclass::SetNumberOfRequiredOutputs(1); this->Superclass::SetNthOutput(0, AeronetData::New().GetPointer()); } /** * Destructor */ AeronetFileReader ::~AeronetFileReader() { } /** * Get the output aeronet data * \return The aeronet data extracted. */ AeronetData * AeronetFileReader ::GetOutput(void) { if (this->GetNumberOfOutputs() < 1) { return 0; } return static_cast<AeronetData *> (this->ProcessObject::GetOutput(0)); } /** * Parse line method */ AeronetFileReader::VectorString AeronetFileReader ::ParseLine(const std::string& line) const { VectorString strVector; std::string word(""); strVector.clear(); for (unsigned int i = 0; i < line.size(); ++i) { if (line[i] == ',') { strVector.push_back(word); word = ""; } else if (i == (line.size() - 1)) { word.push_back(line[i]); strVector.push_back(word); word = ""; } else { word.push_back(line[i]); } } return strVector; } /** * Parse a valid line method */ void AeronetFileReader ::ParseValidLine(const double& ref_date, const VectorString& line, const double& epsilon, VectorDouble& water, VectorDouble& angst, VectorDouble& tau_day, VectorDouble& solarZenithAngle) const { unsigned int col_date = 0; unsigned int col_time = 1; unsigned int col_670 = 6; unsigned int col_440 = 15; unsigned int col_angst = 37; unsigned int col_vapor = 19; unsigned int col_solarZenithAngle = 44; ossimLocalTm current_date = internal::ParseDate(line[col_date], line[col_time]); double dcurrent_date = current_date.getJulian(); // Check hour +/- epsilon if (vcl_abs(dcurrent_date - ref_date) < epsilon) { double dwater = atof(line[col_vapor].c_str()); double dangst = atof(line[col_angst].c_str()); double dsolarZenithAngle = atof(line[col_solarZenithAngle].c_str()); double dtau_670 = atof(line[col_670].c_str()); double dtau_440 = atof(line[col_440].c_str()); double dtau_550 = ((670. - 550.) * dtau_440 + (550 - 440) * dtau_670) / (670. - 440.); tau_day.push_back(dtau_550); angst.push_back(dangst); water.push_back(dwater); solarZenithAngle.push_back(dsolarZenithAngle); } } /** * Compute statistics method */ void AeronetFileReader ::GetStatistics(const VectorDouble& vec, double& mean, double& stddev) const { double sum(0.); double sumOfSquares(0.); mean = 0.; stddev = 0.; if (vec.size() <= 0) return; for (unsigned int i = 0; i < vec.size(); ++i) { sum += vec[i]; sumOfSquares += vec[i] * vec[i]; } // get the mean value const double num = static_cast<double>(vec.size()); if (num == 1) { mean = sum; stddev = 0.; } else if (num > 1) { mean = sum / num; stddev = (sumOfSquares - (sum * sum / num)) / (num - 1.); } } /** * Generate data method */ void AeronetFileReader ::GenerateData() { std::ifstream fin; std::string line; // open file input stream fin.open(m_FileName.c_str()); // Test if the file has been opened correctly if (!fin) { AeronetFileReaderException e(__FILE__, __LINE__); std::ostringstream msg; msg << " Could not open IO object for file "; msg << m_FileName << "." << std::endl; e.SetDescription(msg.str().c_str()); throw e; return; } // Read informations lines (5 lines) std::getline(fin, line); std::getline(fin, line); std::getline(fin, line); std::getline(fin, line); std::getline(fin, line); unsigned int col_date = 0; unsigned int col_time = 1; unsigned int col_670 = 6; unsigned int col_440 = 15; unsigned int col_angst = 37; unsigned int col_vapor = 19; unsigned int col_solarZenithAngle = 44; VectorString list_str; list_str = ParseLine(line); if ((list_str[col_date] != "Date(dd-mm-yy)") || (list_str[col_time] != "Time(hh:mm:ss)") || (list_str[col_670] != "AOT_675") || (list_str[col_440] != "AOT_440") || (list_str[col_angst] != "440-870Angstrom") || (list_str[col_vapor] != "Water(cm)") || (list_str[col_solarZenithAngle] != "Solar_Zenith_Angle") ) { AeronetFileReaderException e(__FILE__, __LINE__); std::ostringstream msg; msg << " The file "; msg << m_FileName << " is not conform." << std::endl; e.SetDescription(msg.str().c_str()); throw e; return; } //Compute input date ossimLocalTm inputDate; inputDate.setDay(m_Day); inputDate.setMonth(m_Month); inputDate.setYear(m_Year); inputDate.setHour(m_Hour); inputDate.setMin(m_Minute); inputDate.setSec(0); double dinputDate = inputDate.getJulian(); MatrixString tabStr; // if so, parse it and select only valid lines for the input date while (!fin.eof()) { std::getline(fin, line); std::string word(""); VectorString listStr; listStr = ParseLine(line); // Select only valid lines: good day if (listStr.size() > 0) { ossimLocalTm currentDate = internal::ParseDate(listStr[col_date], listStr[col_time]); if ((listStr[col_670] != "N/A") && (listStr[col_440] != "N/A") && (static_cast<int>(currentDate.getJulian()) == static_cast<int>(dinputDate)) ) { tabStr.push_back(listStr); } } } fin.close(); if (tabStr.size() <= 0) { itkExceptionMacro( << "The aeronet file (" << m_FileName << ") doesn't contain valid data for the day (dd/mm/yyyy) " << m_Day << "/" << m_Month << "/" << m_Year << "."); } //Compute time for one hour ossimLocalTm temp; temp.setDay(m_Day); temp.setMonth(m_Month); temp.setYear(m_Year); temp.setMin(0); temp.setSec(0); temp.setHour(10); double dhour1 = temp.getJulian(); temp.setHour(11); double dhour2 = temp.getJulian(); // Update epsilon for one hour double epsilon = m_Epsilon * (dhour2 - dhour1); VectorDouble water; VectorDouble tau_day; VectorDouble angst; VectorDouble solarZenithAngle; for (unsigned int idCurrentLine = 0; idCurrentLine < tabStr.size(); idCurrentLine++) { VectorString current_line2 = tabStr[idCurrentLine]; ossimLocalTm currentDate = internal::ParseDate(current_line2[col_date], current_line2[col_time]); ParseValidLine(dinputDate, current_line2, epsilon, water, angst, tau_day, solarZenithAngle); } if (tau_day.size() <= 0) { itkExceptionMacro( << "The aeronet file (" << m_FileName << ") doesn't contain valid data for the time (hh:mm:ss) " << m_Hour << ":" << m_Minute << ":00 with a tolerance of " << m_Epsilon << ". Select an other file or increase the epsilon value."); } double tau_mean(0.); double tau_stddev(0.); GetStatistics(tau_day, tau_mean, tau_stddev); if (tau_stddev > 0.8) { itkExceptionMacro(<< "The stddev of the Aerosol Optical Thickness selected is upper than 0.8."); } double angst_mean(0.); double angst_stddev(0.); double water_mean(0.); double water_stddev(0.); double solarZenithAngle_mean(0.); double solarZenithAngle_stddev(0.); // double stddev = (0.02 > tau_stddev ? 0.02 : tau_stddev ); double stddev(tau_stddev); GetStatistics(angst, angst_mean, angst_stddev); GetStatistics(water, water_mean, water_stddev); GetStatistics(solarZenithAngle, solarZenithAngle_mean, solarZenithAngle_stddev); AeronetData * aeronetData = this->GetOutput(); aeronetData->SetAerosolOpticalThickness(tau_mean); aeronetData->SetStdDev(stddev); aeronetData->SetAngstromCoefficient(angst_mean); aeronetData->SetWater(water_mean); aeronetData->SetSolarZenithAngle(solarZenithAngle_mean); std::ostringstream msg; msg << "(hh/mm/yyyy hh:mm:ss) " << m_Day << "/" << m_Month << "/" << m_Year << " " << m_Hour << ":" << m_Minute << ":00"; std::string str(msg.str()); aeronetData->SetDataDate(str); aeronetData->SetNumberOfDateUsed(tau_day.size()); aeronetData->SetEpsilonDate(m_Epsilon); // Cloud estimation if (stddev > 0.05) { aeronetData->SetCloudEstimation(true); } else { aeronetData->SetCloudEstimation(false); } } /** * PrintSelf method */ void AeronetFileReader ::PrintSelf(std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf(os, indent); } } // end namespace otb
/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbAeronetFileReader.h" #include <fstream> #include <iostream> #include <iomanip> #include "otbMath.h" #include "otbAeronetData.h" namespace otb { namespace internal { typedef struct { int year; int month; int day; int hour; int minute; int second; } Date; double GetJulian(const Date& date) { // From // http://en.wikipedia.org/wiki/Julian_day#Converting_Julian_or_Gregorian_calendar_date_to_Julian_Day_Number // the value is slightly different than the one provided by the ossim // method, but this is now correct according to // http://aa.usno.navy.mil/data/docs/JulianDate.php int a = (14-date.month)/12.0; int y = date.year + 4800 - a; int m = date.month + 12 * a - 3; int jdn = date.day + (153 * m +2)/5 + 365*y + y/4 - y/100 + y/400 - 32045; return jdn + (date.hour-12)/24. + date.minute/1440. + date.second/86400.; } Date ParseDate(const std::string& d, const std::string& t) { Date date; date.day = atoi(d.substr(0,2).c_str()); date.month = atoi(d.substr(3,2).c_str()); date.year = atoi(d.substr(6,4).c_str()); date.hour = atoi(t.substr(0,2).c_str()); date.minute = atoi(t.substr(3,2).c_str()); date.second = atoi(t.substr(6,2).c_str()); return date; } } /** * Constructor */ AeronetFileReader ::AeronetFileReader() : m_FileName(""), m_Day(1), m_Month(1), m_Year(2000), m_Hour(12), m_Minute(0), m_Epsilon(0.4) { this->Superclass::SetNumberOfRequiredOutputs(1); this->Superclass::SetNthOutput(0, AeronetData::New().GetPointer()); } /** * Destructor */ AeronetFileReader ::~AeronetFileReader() { } /** * Get the output aeronet data * \return The aeronet data extracted. */ AeronetData * AeronetFileReader ::GetOutput(void) { if (this->GetNumberOfOutputs() < 1) { return 0; } return static_cast<AeronetData *> (this->ProcessObject::GetOutput(0)); } /** * Parse line method */ AeronetFileReader::VectorString AeronetFileReader ::ParseLine(const std::string& line) const { VectorString strVector; std::string word(""); strVector.clear(); for (unsigned int i = 0; i < line.size(); ++i) { if (line[i] == ',') { strVector.push_back(word); word = ""; } else if (i == (line.size() - 1)) { word.push_back(line[i]); strVector.push_back(word); word = ""; } else { word.push_back(line[i]); } } return strVector; } /** * Parse a valid line method */ void AeronetFileReader ::ParseValidLine(const double& ref_date, const VectorString& line, const double& epsilon, VectorDouble& water, VectorDouble& angst, VectorDouble& tau_day, VectorDouble& solarZenithAngle) const { unsigned int col_date = 0; unsigned int col_time = 1; unsigned int col_670 = 6; unsigned int col_440 = 15; unsigned int col_angst = 37; unsigned int col_vapor = 19; unsigned int col_solarZenithAngle = 44; internal::Date current_date = internal::ParseDate(line[col_date], line[col_time]); double dcurrent_date = GetJulian(current_date); // Check hour +/- epsilon if (vcl_abs(dcurrent_date - ref_date) < epsilon) { double dwater = atof(line[col_vapor].c_str()); double dangst = atof(line[col_angst].c_str()); double dsolarZenithAngle = atof(line[col_solarZenithAngle].c_str()); double dtau_670 = atof(line[col_670].c_str()); double dtau_440 = atof(line[col_440].c_str()); double dtau_550 = ((670. - 550.) * dtau_440 + (550 - 440) * dtau_670) / (670. - 440.); tau_day.push_back(dtau_550); angst.push_back(dangst); water.push_back(dwater); solarZenithAngle.push_back(dsolarZenithAngle); } } /** * Compute statistics method */ void AeronetFileReader ::GetStatistics(const VectorDouble& vec, double& mean, double& stddev) const { double sum(0.); double sumOfSquares(0.); mean = 0.; stddev = 0.; if (vec.size() <= 0) return; for (unsigned int i = 0; i < vec.size(); ++i) { sum += vec[i]; sumOfSquares += vec[i] * vec[i]; } // get the mean value const double num = static_cast<double>(vec.size()); if (num == 1) { mean = sum; stddev = 0.; } else if (num > 1) { mean = sum / num; stddev = (sumOfSquares - (sum * sum / num)) / (num - 1.); } } /** * Generate data method */ void AeronetFileReader ::GenerateData() { std::ifstream fin; std::string line; // open file input stream fin.open(m_FileName.c_str()); // Test if the file has been opened correctly if (!fin) { AeronetFileReaderException e(__FILE__, __LINE__); std::ostringstream msg; msg << " Could not open IO object for file "; msg << m_FileName << "." << std::endl; e.SetDescription(msg.str().c_str()); throw e; return; } // Read informations lines (5 lines) std::getline(fin, line); std::getline(fin, line); std::getline(fin, line); std::getline(fin, line); std::getline(fin, line); unsigned int col_date = 0; unsigned int col_time = 1; unsigned int col_670 = 6; unsigned int col_440 = 15; unsigned int col_angst = 37; unsigned int col_vapor = 19; unsigned int col_solarZenithAngle = 44; VectorString list_str; list_str = ParseLine(line); if ((list_str[col_date] != "Date(dd-mm-yy)") || (list_str[col_time] != "Time(hh:mm:ss)") || (list_str[col_670] != "AOT_675") || (list_str[col_440] != "AOT_440") || (list_str[col_angst] != "440-870Angstrom") || (list_str[col_vapor] != "Water(cm)") || (list_str[col_solarZenithAngle] != "Solar_Zenith_Angle") ) { AeronetFileReaderException e(__FILE__, __LINE__); std::ostringstream msg; msg << " The file "; msg << m_FileName << " is not conform." << std::endl; e.SetDescription(msg.str().c_str()); throw e; return; } //Compute input date internal::Date date = {m_Year, m_Month, m_Day, m_Hour, m_Minute, 0}; double dinputDate = internal::GetJulian(date); MatrixString tabStr; // if so, parse it and select only valid lines for the input date while (!fin.eof()) { std::getline(fin, line); std::string word(""); VectorString listStr; listStr = ParseLine(line); // Select only valid lines: good day if (listStr.size() > 0) { internal::Date currentDate = internal::ParseDate(listStr[col_date], listStr[col_time]); if ((listStr[col_670] != "N/A") && (listStr[col_440] != "N/A") && (static_cast<int>(GetJulian(currentDate)) == static_cast<int>(dinputDate)) ) { tabStr.push_back(listStr); } } } fin.close(); if (tabStr.size() <= 0) { itkExceptionMacro( << "The aeronet file (" << m_FileName << ") doesn't contain valid data for the day (dd/mm/yyyy) " << m_Day << "/" << m_Month << "/" << m_Year << "."); } //Compute time for one hour internal::Date temp = {m_Year, m_Month, m_Day, 10, 0, 0}; double dhour1 = internal::GetJulian(temp); temp.hour = 11; double dhour2 = internal::GetJulian(temp); // Update epsilon for one hour double epsilon = m_Epsilon * (dhour2 - dhour1); VectorDouble water; VectorDouble tau_day; VectorDouble angst; VectorDouble solarZenithAngle; for (unsigned int idCurrentLine = 0; idCurrentLine < tabStr.size(); idCurrentLine++) { VectorString current_line2 = tabStr[idCurrentLine]; ParseValidLine(dinputDate, current_line2, epsilon, water, angst, tau_day, solarZenithAngle); } if (tau_day.size() <= 0) { itkExceptionMacro( << "The aeronet file (" << m_FileName << ") doesn't contain valid data for the time (hh:mm:ss) " << m_Hour << ":" << m_Minute << ":00 with a tolerance of " << m_Epsilon << ". Select an other file or increase the epsilon value."); } double tau_mean(0.); double tau_stddev(0.); GetStatistics(tau_day, tau_mean, tau_stddev); if (tau_stddev > 0.8) { itkExceptionMacro(<< "The stddev of the Aerosol Optical Thickness selected is upper than 0.8."); } double angst_mean(0.); double angst_stddev(0.); double water_mean(0.); double water_stddev(0.); double solarZenithAngle_mean(0.); double solarZenithAngle_stddev(0.); // double stddev = (0.02 > tau_stddev ? 0.02 : tau_stddev ); double stddev(tau_stddev); GetStatistics(angst, angst_mean, angst_stddev); GetStatistics(water, water_mean, water_stddev); GetStatistics(solarZenithAngle, solarZenithAngle_mean, solarZenithAngle_stddev); AeronetData * aeronetData = this->GetOutput(); aeronetData->SetAerosolOpticalThickness(tau_mean); aeronetData->SetStdDev(stddev); aeronetData->SetAngstromCoefficient(angst_mean); aeronetData->SetWater(water_mean); aeronetData->SetSolarZenithAngle(solarZenithAngle_mean); std::ostringstream msg; msg << "(hh/mm/yyyy hh:mm:ss) " << m_Day << "/" << m_Month << "/" << m_Year << " " << m_Hour << ":" << m_Minute << ":00"; std::string str(msg.str()); aeronetData->SetDataDate(str); aeronetData->SetNumberOfDateUsed(tau_day.size()); aeronetData->SetEpsilonDate(m_Epsilon); // Cloud estimation if (stddev > 0.05) { aeronetData->SetCloudEstimation(true); } else { aeronetData->SetCloudEstimation(false); } } /** * PrintSelf method */ void AeronetFileReader ::PrintSelf(std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf(os, indent); } } // end namespace otb
Remove ossim dependencies from aeronet file reader
Remove ossim dependencies from aeronet file reader
C++
apache-2.0
orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB
7c44ccd39638b26dc98b8258e83e7a980728346e
Tudat/Astrodynamics/Radiation/UnitTests/unitTestParseSolarActivityData.cpp
Tudat/Astrodynamics/Radiation/UnitTests/unitTestParseSolarActivityData.cpp
/* Copyright (c) 2010-2012, Delft University of Technology * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * - Neither the name of the Delft University of Technology nor the names of its contributors * may be used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * Changelog * YYMMDD Author Comment * 120701 A. Ronse Creation of code. * * References * Data source for validation figures: * http://celestrak.com/SpaceData/sw19571001.txt * */ #define BOOST_TEST_MAIN #include <istream> #include <string> #include <vector> #include <boost/shared_ptr.hpp> #include <boost/test/unit_test.hpp> #include <Eigen/Core> #include "Tudat/InputOutput/parsedDataVectorUtilities.h" #include "Tudat/Astrodynamics/Radiation/parseSolarActivityData.h" #include "Tudat/Astrodynamics/Radiation/extractSolarActivityData.h" #include "Tudat/Astrodynamics/Radiation/solarActivityData.h" #include "Tudat/InputOutput/basicInputOutput.h" #include <TudatCore/Basics/testMacros.h> namespace tudat { namespace unit_tests { BOOST_AUTO_TEST_SUITE( test_Solar_Activity_Parser_Extractor ) //! Test parsing and extraction process of solar dummy activity file BOOST_AUTO_TEST_CASE( test_parsing_and_extraction ) { tudat::input_output::parsed_data_vector_utilities::ParsedDataVectorPtr parsedDataVectorPtr; tudat::radiation::solar_activity::ParseSolarActivityData solarActivityParser; tudat::radiation::solar_activity::ExtractSolarActivityData solarActivityExtractor; // Parse file std::string fileName = tudat::input_output::getTudatRootPath( ) + "Astrodynamics/Radiation/UnitTests/testSolarActivity.txt"; std::ifstream dataFile; dataFile.open(fileName.c_str(), std::ifstream::in); parsedDataVectorPtr = solarActivityParser.parse( dataFile ); dataFile.close(); // Extract data to object of solarActivityData class std::vector< boost::shared_ptr<tudat::radiation::solar_activity::SolarActivityData> > solarActivityData( 6 ); solarActivityData[0] = solarActivityExtractor.extract( parsedDataVectorPtr->at( 0 ) ); solarActivityData[1] = solarActivityExtractor.extract( parsedDataVectorPtr->at( 3 ) ); solarActivityData[2] = solarActivityExtractor.extract( parsedDataVectorPtr->at( 8 ) ); solarActivityData[3] = solarActivityExtractor.extract( parsedDataVectorPtr->at( 9 ) ); solarActivityData[4] = solarActivityExtractor.extract( parsedDataVectorPtr->at( 12 ) ); solarActivityData[5] = solarActivityExtractor.extract( parsedDataVectorPtr->at( 15 ) ); // Check single parameters BOOST_CHECK_EQUAL( solarActivityData[0]->dataType, 1 ); BOOST_CHECK_EQUAL( solarActivityData[1]->planetaryDailyCharacterFigure, 0.0 ); BOOST_CHECK_EQUAL( solarActivityData[1]->solarRadioFlux107Adjusted, 103.0 ); BOOST_CHECK_EQUAL( solarActivityData[2]->month, 5 ); BOOST_CHECK_EQUAL( solarActivityData[2]->internationalSunspotNumber, 0 ); BOOST_CHECK_EQUAL( solarActivityData[3]->planetaryRangeIndexSum, 176 ); BOOST_CHECK_EQUAL( solarActivityData[3]->planetaryDailyCharacterFigureConverted, 0 ); BOOST_CHECK_EQUAL( solarActivityData[4]->bartelsSolarRotationNumber, 2441 ); BOOST_CHECK_EQUAL( solarActivityData[5]->last81DaySolarRadioFlux107Observed, 187.8 ); // Check planetaryEquivalentAmplitudeVectors Eigen::VectorXd correctPlanetaryEquivalentAmplitudeVector1( 8 ); correctPlanetaryEquivalentAmplitudeVector1 << 32, 27, 15, 7, 22, 9, 32, 22; Eigen::VectorXd correctPlanetaryEquivalentAmplitudeVector2 = Eigen::VectorXd::Zero( 8 ); TUDAT_CHECK_MATRIX_CLOSE( solarActivityData[0]->planetaryEquivalentAmplitudeVector, correctPlanetaryEquivalentAmplitudeVector1, 0 ); TUDAT_CHECK_MATRIX_CLOSE( solarActivityData[4]->planetaryEquivalentAmplitudeVector, correctPlanetaryEquivalentAmplitudeVector2 , 0); TUDAT_CHECK_MATRIX_CLOSE( solarActivityData[5]->planetaryEquivalentAmplitudeVector, correctPlanetaryEquivalentAmplitudeVector2, 0 ); } BOOST_AUTO_TEST_SUITE_END( ) } // unit_tests } // tudat
/* Copyright (c) 2010-2016, Delft University of Technology * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * - Neither the name of the Delft University of Technology nor the names of its contributors * may be used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * Changelog * YYMMDD Author Comment * 120701 A. Ronse Creation of code. * 160324 R. Hoogendoorn Update for use in current version of Tudat * * References * Data source for validation figures: * http://celestrak.com/SpaceData/sw19571001.txt * */ #define BOOST_TEST_MAIN #include <istream> #include <string> #include <vector> #include <boost/shared_ptr.hpp> #include <boost/test/unit_test.hpp> #include <Eigen/Core> #include "Tudat/InputOutput/parsedDataVectorUtilities.h" #include "Tudat/Astrodynamics/Radiation/parseSolarActivityData.h" #include "Tudat/Astrodynamics/Radiation/extractSolarActivityData.h" #include "Tudat/Astrodynamics/Radiation/solarActivityData.h" #include "Tudat/InputOutput/basicInputOutput.h" #include <tudat/Basics/testMacros.h> namespace tudat { namespace unit_tests { BOOST_AUTO_TEST_SUITE( test_Solar_Activity_Parser_Extractor ) //! Test parsing and extraction process of solar dummy activity file BOOST_AUTO_TEST_CASE( test_parsing_and_extraction ) { tudat::input_output::parsed_data_vector_utilities::ParsedDataVectorPtr parsedDataVectorPtr; tudat::radiation::solar_activity::ParseSolarActivityData solarActivityParser; tudat::radiation::solar_activity::ExtractSolarActivityData solarActivityExtractor; // Parse file // save path of cpp file std::string cppPath( __FILE__ ); // Strip filename from temporary string and return root-path string. std::string folder = cppPath.substr( 0, cppPath.find_last_of("/\\")+1); std::string filePath = folder + "testSolarActivity.txt" ; //std::string fileName = tudat::input_output::getTudatRootPath( ) + // "Astrodynamics/Radiation/UnitTests/testSolarActivity.txt"; // Open dataFile std::ifstream dataFile; //dataFile.open(fileName.c_str(), std::ifstream::in); dataFile.open(filePath.c_str(), std::ifstream::in); parsedDataVectorPtr = solarActivityParser.parse( dataFile ); dataFile.close(); // Extract data to object of solarActivityData class std::vector< boost::shared_ptr<tudat::radiation::solar_activity::SolarActivityData> > solarActivityData( 6 ); solarActivityData[0] = solarActivityExtractor.extract( parsedDataVectorPtr->at( 0 ) ); solarActivityData[1] = solarActivityExtractor.extract( parsedDataVectorPtr->at( 3 ) ); solarActivityData[2] = solarActivityExtractor.extract( parsedDataVectorPtr->at( 8 ) ); solarActivityData[3] = solarActivityExtractor.extract( parsedDataVectorPtr->at( 9 ) ); solarActivityData[4] = solarActivityExtractor.extract( parsedDataVectorPtr->at( 12 ) ); solarActivityData[5] = solarActivityExtractor.extract( parsedDataVectorPtr->at( 15 ) ); // Check single parameters BOOST_CHECK_EQUAL( solarActivityData[0]->dataType, 1 ); BOOST_CHECK_EQUAL( solarActivityData[1]->planetaryDailyCharacterFigure, 0.0 ); BOOST_CHECK_EQUAL( solarActivityData[1]->solarRadioFlux107Adjusted, 103.0 ); BOOST_CHECK_EQUAL( solarActivityData[2]->month, 5 ); BOOST_CHECK_EQUAL( solarActivityData[2]->internationalSunspotNumber, 0 ); BOOST_CHECK_EQUAL( solarActivityData[3]->planetaryRangeIndexSum, 176 ); BOOST_CHECK_EQUAL( solarActivityData[3]->planetaryDailyCharacterFigureConverted, 0 ); BOOST_CHECK_EQUAL( solarActivityData[4]->bartelsSolarRotationNumber, 2441 ); BOOST_CHECK_EQUAL( solarActivityData[5]->last81DaySolarRadioFlux107Observed, 187.8 ); // Check planetaryEquivalentAmplitudeVectors Eigen::VectorXd correctPlanetaryEquivalentAmplitudeVector1( 8 ); correctPlanetaryEquivalentAmplitudeVector1 << 32, 27, 15, 7, 22, 9, 32, 22; Eigen::VectorXd correctPlanetaryEquivalentAmplitudeVector2 = Eigen::VectorXd::Zero( 8 ); TUDAT_CHECK_MATRIX_CLOSE( solarActivityData[0]->planetaryEquivalentAmplitudeVector, correctPlanetaryEquivalentAmplitudeVector1, 0 ); TUDAT_CHECK_MATRIX_CLOSE( solarActivityData[4]->planetaryEquivalentAmplitudeVector, correctPlanetaryEquivalentAmplitudeVector2 , 0); TUDAT_CHECK_MATRIX_CLOSE( solarActivityData[5]->planetaryEquivalentAmplitudeVector, correctPlanetaryEquivalentAmplitudeVector2, 0 ); } BOOST_AUTO_TEST_SUITE_END( ) } // unit_tests } // tudat
Update current Tudat
Update current Tudat
C++
bsd-3-clause
DominicDirkx/tudat,JPelamatti/TudatDevelopment,DominicDirkx/tudat,Tudat/tudat,JPelamatti/TudatDevelopment,Tudat/tudat,Tudat/tudat,JPelamatti/TudatDevelopment,DominicDirkx/tudat,Tudat/tudat
92983b9d00b8d36985c3d10f01158df96e2d0e23
NFComm/NFKernelPlugin/NFScheduleModule.cpp
NFComm/NFKernelPlugin/NFScheduleModule.cpp
/* This file is part of: NoahFrame https://github.com/ketoo/NoahGameFrame Copyright 2009 - 2020 NoahFrame(NoahGameFrame) File creator: lvsheng.huang NoahFrame is open-source software and you can redistribute it and/or modify it under the terms of the License; besides, anyone who use this file/software must include this copyright announcement. 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 "NFScheduleModule.h" void NFScheduleElement::DoHeartBeatEvent(NFINT64 nowTime) { if (mnRemainCount > 0 ) { mnRemainCount--; } mnTriggerTime = nowTime + (NFINT64)(mfIntervalTime * 1000); #if NF_PLATFORM != NF_PLATFORM_WIN NF_CRASH_TRY #endif OBJECT_SCHEDULE_FUNCTOR_PTR cb; bool bRet = this->mxObjectFunctor.First(cb); while (bRet) { cb.get()->operator()(self, mstrScheduleName, mfIntervalTime, mnRemainCount); bRet = this->mxObjectFunctor.Next(cb); } #if NF_PLATFORM != NF_PLATFORM_WIN NF_CRASH_END #endif } NFScheduleModule::NFScheduleModule(NFIPluginManager* p) { pPluginManager = p; m_bIsExecute = true; } NFScheduleModule::~NFScheduleModule() { mObjectScheduleMap.ClearAll(); } bool NFScheduleModule::Init() { m_pLogModule = pPluginManager->FindModule<NFILogModule>(); m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>(); m_pSceneModule = pPluginManager->FindModule<NFISceneModule>(); m_pKernelModule->RegisterCommonClassEvent(this, &NFScheduleModule::OnClassCommonEvent); m_pSceneModule->AddSceneGroupDestroyedCallBack(this, &NFScheduleModule::OnGroupCommonEvent); return true; } bool NFScheduleModule::Execute() { NFPerformance performanceObject; NFINT64 nowTime = NFGetTimeMS(); static std::vector<TickElement> elements; elements.clear(); for (auto it = mScheduleMap.begin(); it != mScheduleMap.end();) { if (nowTime >= it->triggerTime) { //std::cout << nowTime << it->scheduleName << ">>>>>" << it->triggerTime << std::endl; auto objectMap = mObjectScheduleMap.GetElement(it->self); if (objectMap) { auto scheduleElement = objectMap->GetElement(it->scheduleName); if (scheduleElement) { scheduleElement->DoHeartBeatEvent(nowTime); if (scheduleElement->mnRemainCount != 0) { TickElement element; element.scheduleName = scheduleElement->mstrScheduleName; element.triggerTime = scheduleElement->mnTriggerTime; element.self = scheduleElement->self; elements.push_back(element); } else { objectMap->RemoveElement(it->scheduleName); } } } it = mScheduleMap.erase(it); } else { break; } } for (auto& item : elements) { mScheduleMap.insert(item); } if (performanceObject.CheckTimePoint(1)) { std::ostringstream os; os << "---------------module schedule performance problem "; os << performanceObject.TimeScope(); os << "---------- "; m_pLogModule->LogWarning(NFGUID(), os, __FUNCTION__, __LINE__); } return true; } bool NFScheduleModule::AddSchedule(const NFGUID self, const std::string& scheduleName, const OBJECT_SCHEDULE_FUNCTOR_PTR& cb, const float time, const int count) { auto objectMap = mObjectScheduleMap.GetElement(self); if (!objectMap) { objectMap = NF_SHARE_PTR< NFMapEx <std::string, NFScheduleElement >>(NF_NEW NFMapEx <std::string, NFScheduleElement >()); mObjectScheduleMap.AddElement(self, objectMap); } auto scheduleObject = objectMap->GetElement(scheduleName); if (!scheduleObject) { scheduleObject = NF_SHARE_PTR<NFScheduleElement>(NF_NEW NFScheduleElement()); scheduleObject->mstrScheduleName = scheduleName; scheduleObject->mfIntervalTime = time; scheduleObject->mnTriggerTime = NFGetTimeMS() + (NFINT64)(time * 1000); scheduleObject->mnRemainCount = count; scheduleObject->self = self; scheduleObject->mxObjectFunctor.Add(cb); objectMap->AddElement(scheduleName, scheduleObject); TickElement tickElement; tickElement.scheduleName = scheduleObject->mstrScheduleName; tickElement.triggerTime = scheduleObject->mnTriggerTime; tickElement.self = scheduleObject->self; mScheduleMap.insert(tickElement); } return true; } bool NFScheduleModule::RemoveSchedule(const NFGUID self) { return mObjectScheduleMap.RemoveElement(self); } bool NFScheduleModule::RemoveSchedule(const NFGUID self, const std::string& scheduleName) { auto objectMap = mObjectScheduleMap.GetElement(self); if (objectMap) { return objectMap->RemoveElement(scheduleName); } return false; } bool NFScheduleModule::ExistSchedule(const NFGUID self, const std::string& scheduleName) { auto objectScheduleMap = mObjectScheduleMap.GetElement(self); if (NULL == objectScheduleMap) { return false; } return objectScheduleMap->ExistElement(scheduleName); } NF_SHARE_PTR<NFScheduleElement> NFScheduleModule::GetSchedule(const NFGUID self, const std::string & scheduleName) { NF_SHARE_PTR< NFMapEx <std::string, NFScheduleElement >> xObjectScheduleMap = mObjectScheduleMap.GetElement(self); if (NULL == xObjectScheduleMap) { return nullptr; } return xObjectScheduleMap->GetElement(scheduleName); } int NFScheduleModule::OnClassCommonEvent(const NFGUID & self, const std::string & className, const CLASS_OBJECT_EVENT classEvent, const NFDataList & var) { if (CLASS_OBJECT_EVENT::COE_DESTROY == classEvent) { this->RemoveSchedule(self); } return 0; } int NFScheduleModule::OnGroupCommonEvent(const NFGUID &self, const int scene, const int group, const int type, const NFDataList &arg) { this->RemoveSchedule(NFGUID(scene, group)); return 0; }
/* This file is part of: NoahFrame https://github.com/ketoo/NoahGameFrame Copyright 2009 - 2020 NoahFrame(NoahGameFrame) File creator: lvsheng.huang NoahFrame is open-source software and you can redistribute it and/or modify it under the terms of the License; besides, anyone who use this file/software must include this copyright announcement. 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 "NFScheduleModule.h" void NFScheduleElement::DoHeartBeatEvent(NFINT64 nowTime) { if (mnRemainCount > 0 ) { mnRemainCount--; } mnTriggerTime = nowTime + (NFINT64)(mfIntervalTime * 1000); #if NF_PLATFORM != NF_PLATFORM_WIN NF_CRASH_TRY #endif OBJECT_SCHEDULE_FUNCTOR_PTR cb; bool bRet = this->mxObjectFunctor.First(cb); while (bRet) { cb.get()->operator()(self, mstrScheduleName, mfIntervalTime, mnRemainCount); bRet = this->mxObjectFunctor.Next(cb); } #if NF_PLATFORM != NF_PLATFORM_WIN NF_CRASH_END #endif } NFScheduleModule::NFScheduleModule(NFIPluginManager* p) { pPluginManager = p; m_bIsExecute = true; } NFScheduleModule::~NFScheduleModule() { mObjectScheduleMap.ClearAll(); } bool NFScheduleModule::Init() { m_pLogModule = pPluginManager->FindModule<NFILogModule>(); m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>(); m_pSceneModule = pPluginManager->FindModule<NFISceneModule>(); m_pKernelModule->RegisterCommonClassEvent(this, &NFScheduleModule::OnClassCommonEvent); m_pSceneModule->AddSceneGroupDestroyedCallBack(this, &NFScheduleModule::OnGroupCommonEvent); return true; } bool NFScheduleModule::Execute() { NFPerformance performanceObject; NFINT64 nowTime = NFGetTimeMS(); static std::vector<TickElement> elements; elements.clear(); for (auto it = mScheduleMap.begin(); it != mScheduleMap.end();) { if (nowTime >= it->triggerTime) { //std::cout << nowTime << it->scheduleName << ">>>>>" << it->triggerTime << std::endl; auto objectMap = mObjectScheduleMap.GetElement(it->self); if (objectMap) { auto scheduleElement = objectMap->GetElement(it->scheduleName); if (scheduleElement) { if(scheduleElement->mnRemainCount == 1){ objectMap->RemoveElement(it->scheduleName); } scheduleElement->DoHeartBeatEvent(nowTime); if (scheduleElement->mnRemainCount != 0) { TickElement element; element.scheduleName = scheduleElement->mstrScheduleName; element.triggerTime = scheduleElement->mnTriggerTime; element.self = scheduleElement->self; elements.push_back(element); } } } it = mScheduleMap.erase(it); } else { break; } } for (auto& item : elements) { mScheduleMap.insert(item); } if (performanceObject.CheckTimePoint(1)) { std::ostringstream os; os << "---------------module schedule performance problem "; os << performanceObject.TimeScope(); os << "---------- "; m_pLogModule->LogWarning(NFGUID(), os, __FUNCTION__, __LINE__); } return true; } bool NFScheduleModule::AddSchedule(const NFGUID self, const std::string& scheduleName, const OBJECT_SCHEDULE_FUNCTOR_PTR& cb, const float time, const int count) { auto objectMap = mObjectScheduleMap.GetElement(self); if (!objectMap) { objectMap = NF_SHARE_PTR< NFMapEx <std::string, NFScheduleElement >>(NF_NEW NFMapEx <std::string, NFScheduleElement >()); mObjectScheduleMap.AddElement(self, objectMap); } auto scheduleObject = objectMap->GetElement(scheduleName); if (!scheduleObject) { scheduleObject = NF_SHARE_PTR<NFScheduleElement>(NF_NEW NFScheduleElement()); scheduleObject->mstrScheduleName = scheduleName; scheduleObject->mfIntervalTime = time; scheduleObject->mnTriggerTime = NFGetTimeMS() + (NFINT64)(time * 1000); scheduleObject->mnRemainCount = count; scheduleObject->self = self; scheduleObject->mxObjectFunctor.Add(cb); objectMap->AddElement(scheduleName, scheduleObject); TickElement tickElement; tickElement.scheduleName = scheduleObject->mstrScheduleName; tickElement.triggerTime = scheduleObject->mnTriggerTime; tickElement.self = scheduleObject->self; mScheduleMap.insert(tickElement); } return true; } bool NFScheduleModule::RemoveSchedule(const NFGUID self) { return mObjectScheduleMap.RemoveElement(self); } bool NFScheduleModule::RemoveSchedule(const NFGUID self, const std::string& scheduleName) { auto objectMap = mObjectScheduleMap.GetElement(self); if (objectMap) { return objectMap->RemoveElement(scheduleName); } return false; } bool NFScheduleModule::ExistSchedule(const NFGUID self, const std::string& scheduleName) { auto objectScheduleMap = mObjectScheduleMap.GetElement(self); if (NULL == objectScheduleMap) { return false; } return objectScheduleMap->ExistElement(scheduleName); } NF_SHARE_PTR<NFScheduleElement> NFScheduleModule::GetSchedule(const NFGUID self, const std::string & scheduleName) { NF_SHARE_PTR< NFMapEx <std::string, NFScheduleElement >> xObjectScheduleMap = mObjectScheduleMap.GetElement(self); if (NULL == xObjectScheduleMap) { return nullptr; } return xObjectScheduleMap->GetElement(scheduleName); } int NFScheduleModule::OnClassCommonEvent(const NFGUID & self, const std::string & className, const CLASS_OBJECT_EVENT classEvent, const NFDataList & var) { if (CLASS_OBJECT_EVENT::COE_DESTROY == classEvent) { this->RemoveSchedule(self); } return 0; } int NFScheduleModule::OnGroupCommonEvent(const NFGUID &self, const int scene, const int group, const int type, const NFDataList &arg) { this->RemoveSchedule(NFGUID(scene, group)); return 0; }
modify when invalid timer remove
modify when invalid timer remove
C++
apache-2.0
ketoo/NoahGameFrame,ketoo/NoahGameFrame,zh423328/NoahGameFrame,zh423328/NoahGameFrame,ketoo/NoahGameFrame,zh423328/NoahGameFrame,zh423328/NoahGameFrame,zh423328/NoahGameFrame,ketoo/NoahGameFrame,zh423328/NoahGameFrame,zh423328/NoahGameFrame,ketoo/NoahGameFrame,ketoo/NoahGameFrame,ketoo/NoahGameFrame,zh423328/NoahGameFrame
da9e09c6f61f410a1926ffef1be49909a98090be
OpenSim/Common/Test/testAPDMDataReader.cpp
OpenSim/Common/Test/testAPDMDataReader.cpp
/* -------------------------------------------------------------------------- * * OpenSim: testAPDMDataReader.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2017 Stanford University and the Authors * * * * Licensed under the Apache License, Version 2.0 (the "License"); you may * * not use this file except in compliance with the License. You may obtain a * * copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * -------------------------------------------------------------------------- */ #include "OpenSim/Common/DataAdapter.h" #include "OpenSim/Common/APDMDataReader.h" #include "OpenSim/Common/STOFileAdapter.h" #include <OpenSim/Auxiliary/auxiliaryTestFunctions.h> using namespace OpenSim; void testAPDMFormat7(); int main() { try { APDMDataReaderSettings readerSettings; std::vector<std::string> imu_names{ "torso", "pelvis", "shank" }; std::vector<std::string> names_in_experiment{ "Static", "Upper", "Middle" }; // Programmatically add items to name mapping, write to xml for (int index = 0; index < imu_names.size(); ++index) { ExperimentalSensor nextSensor(names_in_experiment[index], imu_names[index]); readerSettings.append_ExperimentalSensors(nextSensor); } readerSettings.print("apdm_reader.xml"); // read xml we wrote into a new APDMDataReader to readTrial APDMDataReaderSettings roundTripReaderSettings("apdm_reader.xml"); APDMDataReader reader(roundTripReaderSettings); DataAdapter::OutputTables tables = reader.read("imuData01.csv"); // Write tables to sto files // Accelerations const TimeSeriesTableVec3& accelTableTyped = reader.getLinearAccelerationsTable(tables); STOFileAdapterVec3::write(accelTableTyped, "accelerations.sto"); const SimTK::RowVectorView_<SimTK::Vec3>& rvv = accelTableTyped.getRowAtIndex(0); SimTK::Vec3 fromTable = accelTableTyped.getRowAtIndex(0)[0]; SimTK::Vec3 fromFile = SimTK::Vec3{ 0.102542184,0.048829611,9.804986382 }; double tolerance = SimTK::Eps; ASSERT_EQUAL(fromTable, fromFile, tolerance); // test last row as well to make sure all data is read correctly, // size is as expected size_t numRows = accelTableTyped.getIndependentColumn().size(); ASSERT(numRows==1024); fromTable = accelTableTyped.getRowAtIndex(numRows - 1)[0]; fromFile = SimTK::Vec3{ 0.158696249,0.298471016,9.723807335 }; ASSERT_EQUAL(fromTable, fromFile, tolerance); // Magnetometer const TimeSeriesTableVec3& magTableTyped = reader.getMagneticHeadingTable(tables); STOFileAdapterVec3::write(magTableTyped, "magnetometers.sto"); fromTable = magTableTyped.getRowAtIndex(0)[0]; fromFile = SimTK::Vec3{ 31.27780876,13.46964874,-62.79244003 }; ASSERT_EQUAL(fromTable, fromFile, tolerance); // test last row as well fromTable = magTableTyped.getRowAtIndex(numRows - 1)[0]; fromFile = SimTK::Vec3{ 31.1386445,13.62834516,-62.70943031 }; ASSERT_EQUAL(fromTable, fromFile, tolerance); // Gyro const TimeSeriesTableVec3& gyroTableTyped = reader.getAngularVelocityTable(tables); STOFileAdapterVec3::write(gyroTableTyped, "gyros.sto"); fromTable = gyroTableTyped.getRowAtIndex(0)[0]; fromFile = SimTK::Vec3{ 0.002136296, 0.008331553,-0.008972442 }; ASSERT_EQUAL(fromTable, fromFile, tolerance); fromTable = gyroTableTyped.getRowAtIndex(numRows - 1)[0]; fromFile = SimTK::Vec3{ 0.008545183,0.007797479,-0.012817774 }; ASSERT_EQUAL(fromTable, fromFile, tolerance); // Orientation const TimeSeriesTableQuaternion& quatTableTyped = reader.getOrientationsTable(tables); STOFileAdapterQuaternion::write(quatTableTyped, "quaternions.sto"); SimTK::Quaternion quatFromTable = quatTableTyped.getRowAtIndex(0)[0]; SimTK::Quaternion quatFromFile = SimTK::Quaternion(0.979286375, 0.000865605, -0.005158994, -0.202412525); ASSERT_EQUAL(quatFromTable, quatFromFile, tolerance); // last row quatFromTable = quatTableTyped.getRowAtIndex(numRows - 1)[0]; quatFromFile = SimTK::Quaternion(0.979175344,0.00110321,-0.005109196,-0.202949069); ASSERT_EQUAL(quatFromTable, quatFromFile, tolerance); // Now test new Fromat=7 testAPDMFormat7(); } catch (const std::exception& ex) { std::cout << "testAPDMDataReader FAILED: " << ex.what() << std::endl; return 1; } std::cout << "\n All testAPDMDataReader cases passed." << std::endl; return 0; } void testAPDMFormat7() { APDMDataReaderSettings readerSettings; std::vector<std::string> imu_names{ "imu1", "imu2", "imu4" }; std::vector<std::string> names_in_experiment{ "5718", "5778", "6570" }; // Programmatically add items to name mapping, write to xml for (int index = 0; index < imu_names.size(); ++index) { ExperimentalSensor nextSensor(names_in_experiment[index], imu_names[index]); readerSettings.append_ExperimentalSensors(nextSensor); } APDMDataReader reader(readerSettings); DataAdapter::OutputTables tables = reader.read("apdm_format7.csv"); const TimeSeriesTableVec3& accelTable = reader.getLinearAccelerationsTable(tables); // First row acceleration //-9.982604,-2.450636,0.515763 const SimTK::Vec3 refAccel{ -9.982604,-2.450636,0.515763 }; const SimTK::Vec3 fromFile = accelTable.getRowAtIndex(0)[0]; double tolerance = SimTK::Eps; ASSERT_EQUAL(refAccel, fromFile, tolerance); const SimTK::Vec3 refGyro{ -0.928487, -0.085719, -0.059549 }; const SimTK::Vec3 fromFileGyro = reader.getAngularVelocityTable(tables).getRowAtIndex(0)[0]; ASSERT_EQUAL(refGyro, fromFileGyro, tolerance); const SimTK::Vec3 refMagneto{ 9.564500, 12.689596, -7.455671 }; const SimTK::Vec3 fromFileMagneto = reader.getMagneticHeadingTable(tables).getRowAtIndex(2)[0]; ASSERT_EQUAL(refMagneto, fromFileMagneto, tolerance); }
/* -------------------------------------------------------------------------- * * OpenSim: testAPDMDataReader.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2017 Stanford University and the Authors * * * * Licensed under the Apache License, Version 2.0 (the "License"); you may * * not use this file except in compliance with the License. You may obtain a * * copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * -------------------------------------------------------------------------- */ #include "OpenSim/Common/DataAdapter.h" #include "OpenSim/Common/APDMDataReader.h" #include "OpenSim/Common/STOFileAdapter.h" #include <OpenSim/Auxiliary/auxiliaryTestFunctions.h> using namespace OpenSim; void testAPDMFormat7(); int main() { try { APDMDataReaderSettings readerSettings; std::vector<std::string> imu_names{ "torso", "pelvis", "shank" }; std::vector<std::string> names_in_experiment{ "Static", "Upper", "Middle" }; // Programmatically add items to name mapping, write to xml for (int index = 0; index < imu_names.size(); ++index) { ExperimentalSensor nextSensor(names_in_experiment[index], imu_names[index]); readerSettings.append_ExperimentalSensors(nextSensor); } readerSettings.print("apdm_reader.xml"); // read xml we wrote into a new APDMDataReader to readTrial APDMDataReaderSettings roundTripReaderSettings("apdm_reader.xml"); APDMDataReader reader(roundTripReaderSettings); DataAdapter::OutputTables tables = reader.read("imuData01.csv"); // Write tables to sto files // Accelerations const TimeSeriesTableVec3& accelTableTyped = reader.getLinearAccelerationsTable(tables); STOFileAdapterVec3::write(accelTableTyped, "accelerations.sto"); const SimTK::RowVectorView_<SimTK::Vec3>& rvv = accelTableTyped.getRowAtIndex(0); SimTK::Vec3 fromTable = accelTableTyped.getRowAtIndex(0)[0]; SimTK::Vec3 fromFile = SimTK::Vec3{ 0.102542184,0.048829611,9.804986382 }; double tolerance = SimTK::Eps; ASSERT_EQUAL(fromTable, fromFile, tolerance); // test last row as well to make sure all data is read correctly, // size is as expected size_t numRows = accelTableTyped.getIndependentColumn().size(); ASSERT(numRows==1024); fromTable = accelTableTyped.getRowAtIndex(numRows - 1)[0]; fromFile = SimTK::Vec3{ 0.158696249,0.298471016,9.723807335 }; ASSERT_EQUAL(fromTable, fromFile, tolerance); // Magnetometer const TimeSeriesTableVec3& magTableTyped = reader.getMagneticHeadingTable(tables); STOFileAdapterVec3::write(magTableTyped, "magnetometers.sto"); fromTable = magTableTyped.getRowAtIndex(0)[0]; fromFile = SimTK::Vec3{ 31.27780876,13.46964874,-62.79244003 }; ASSERT_EQUAL(fromTable, fromFile, tolerance); // test last row as well fromTable = magTableTyped.getRowAtIndex(numRows - 1)[0]; fromFile = SimTK::Vec3{ 31.1386445,13.62834516,-62.70943031 }; ASSERT_EQUAL(fromTable, fromFile, tolerance); // Gyro const TimeSeriesTableVec3& gyroTableTyped = reader.getAngularVelocityTable(tables); STOFileAdapterVec3::write(gyroTableTyped, "gyros.sto"); fromTable = gyroTableTyped.getRowAtIndex(0)[0]; fromFile = SimTK::Vec3{ 0.002136296, 0.008331553,-0.008972442 }; ASSERT_EQUAL(fromTable, fromFile, tolerance); fromTable = gyroTableTyped.getRowAtIndex(numRows - 1)[0]; fromFile = SimTK::Vec3{ 0.008545183,0.007797479,-0.012817774 }; ASSERT_EQUAL(fromTable, fromFile, tolerance); // Orientation const TimeSeriesTableQuaternion& quatTableTyped = reader.getOrientationsTable(tables); STOFileAdapterQuaternion::write(quatTableTyped, "quaternions.sto"); SimTK::Quaternion quatFromTable = quatTableTyped.getRowAtIndex(0)[0]; SimTK::Quaternion quatFromFile = SimTK::Quaternion(0.979286375, 0.000865605, -0.005158994, -0.202412525); ASSERT_EQUAL(quatFromTable, quatFromFile, tolerance); // last row quatFromTable = quatTableTyped.getRowAtIndex(numRows - 1)[0]; quatFromFile = SimTK::Quaternion(0.979175344,0.00110321,-0.005109196,-0.202949069); ASSERT_EQUAL(quatFromTable, quatFromFile, tolerance); // Now test new Fromat=7 testAPDMFormat7(); } catch (const std::exception& ex) { std::cout << "testAPDMDataReader FAILED: " << ex.what() << std::endl; return 1; } std::cout << "\n All testAPDMDataReader cases passed." << std::endl; return 0; } void testAPDMFormat7() { APDMDataReaderSettings readerSettings; std::vector<std::string> imu_names{ "imu1", "imu2", "imu4" }; std::vector<std::string> names_in_experiment{ "5718", "5778", "6570" }; // Programmatically add items to name mapping, write to xml for (int index = 0; index < imu_names.size(); ++index) { ExperimentalSensor nextSensor(names_in_experiment[index], imu_names[index]); readerSettings.append_ExperimentalSensors(nextSensor); } APDMDataReader reader(readerSettings); DataAdapter::OutputTables tables = reader.read("apdm_format7.csv"); const TimeSeriesTableVec3& accelTable = reader.getLinearAccelerationsTable(tables); // First row acceleration //-9.982604,-2.450636,0.515763 const SimTK::Vec3 refAccel{ -9.982604,-2.450636,0.515763 }; const SimTK::Vec3 fromFile = accelTable.getRowAtIndex(0)[0]; double tolerance = SimTK::Eps; ASSERT_EQUAL(refAccel, fromFile, tolerance); const SimTK::Vec3 refGyro{ -0.928487, -0.085719, -0.059549 }; const SimTK::Vec3 fromFileGyro = reader.getAngularVelocityTable(tables).getRowAtIndex(0)[0]; ASSERT_EQUAL(refGyro, fromFileGyro, tolerance); // Magnetometer data on a different imu from the last row const SimTK::Vec3 refMagneto{ -55.436261,-1.704153,16.382336 }; const SimTK::Vec3 fromFileMagneto = reader.getMagneticHeadingTable(tables).getRowAtIndex(2)[1]; ASSERT_EQUAL(refMagneto, fromFileMagneto, tolerance); }
Use different imu in testing last row of data
Use different imu in testing last row of data
C++
apache-2.0
opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core
37c707892172626f63dc1302ae8853e1ac86c7d3
Rendering/OpenGL2/vtkOpenGLShaderCache.cxx
Rendering/OpenGL2/vtkOpenGLShaderCache.cxx
/*========================================================================= Program: Visualization Toolkit Module: vtkOpenGLShaderCache.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 "vtkOpenGLShaderCache.h" #include "vtk_glew.h" #include "vtkObjectFactory.h" #include "vtkOpenGLError.h" #include "vtkOpenGLRenderWindow.h" #include "vtkShader.h" #include "vtkShaderProgram.h" #include "vtkOpenGLHelper.h" #include <math.h> #include <sstream> #include "vtksys/MD5.h" class vtkOpenGLShaderCache::Private { public: vtksysMD5* md5; // map of hash to shader program structs std::map<std::string, vtkShaderProgram *> ShaderPrograms; Private() { md5 = vtksysMD5_New(); } ~Private() { vtksysMD5_Delete(this->md5); } //----------------------------------------------------------------------------- void ComputeMD5(const char* content, const char* content2, const char* content3, std::string &hash) { unsigned char digest[16]; char md5Hash[33]; md5Hash[32] = '\0'; vtksysMD5_Initialize(this->md5); vtksysMD5_Append(this->md5, reinterpret_cast<const unsigned char *>(content), (int)strlen(content)); vtksysMD5_Append(this->md5, reinterpret_cast<const unsigned char *>(content2), (int)strlen(content2)); vtksysMD5_Append(this->md5, reinterpret_cast<const unsigned char *>(content3), (int)strlen(content3)); vtksysMD5_Finalize(this->md5, digest); vtksysMD5_DigestToHex(digest, md5Hash); hash = md5Hash; } }; // ---------------------------------------------------------------------------- vtkStandardNewMacro(vtkOpenGLShaderCache); // ---------------------------------------------------------------------------- vtkOpenGLShaderCache::vtkOpenGLShaderCache() : Internal(new Private) { this->LastShaderBound = NULL; } // ---------------------------------------------------------------------------- vtkOpenGLShaderCache::~vtkOpenGLShaderCache() { typedef std::map<std::string,vtkShaderProgram*>::const_iterator SMapIter; SMapIter iter = this->Internal->ShaderPrograms.begin(); for ( ; iter != this->Internal->ShaderPrograms.end(); iter++) { iter->second->Delete(); } delete this->Internal; } // return NULL if there is an issue vtkShaderProgram *vtkOpenGLShaderCache::ReadyShader( const char *vertexCode, const char *fragmentCode, const char *geometryCode) { // perform system wide shader replacements // desktops to not use percision statements #if GL_ES_VERSION_2_0 != 1 unsigned int count = 0; std::string VSSource = vertexCode; std::string FSSource = fragmentCode; std::string GSSource = geometryCode; if (vtkOpenGLRenderWindow::GetContextSupportsOpenGL32()) { vtkShaderProgram::Substitute(VSSource,"//VTK::System::Dec", "#version 150\n" "#define attribute in\n" "#define varying out\n" "#define highp\n" "#define mediump\n" "#define lowp"); vtkShaderProgram::Substitute(FSSource,"//VTK::System::Dec", "#version 150\n" "#define varying in\n" "#define highp\n" "#define mediump\n" "#define lowp\n" "#define texelFetchBuffer texelFetch\n" "#define texture1D texture\n" "#define texture2D texture\n" "#define texture3D texture\n" ); vtkShaderProgram::Substitute(GSSource,"//VTK::System::Dec", "#version 150\n" "#define highp\n" "#define mediump\n" "#define lowp" ); std::string fragDecls; bool done = false; while (!done) { std::ostringstream src; std::ostringstream dst; src << "gl_FragData[" << count << "]"; // this naming has to match the bindings // in vtkOpenGLShaderProgram.cxx dst << "fragOutput" << count; done = !vtkShaderProgram::Substitute(FSSource, src.str(),dst.str()); if (!done) { fragDecls += "out vec4 " + dst.str() + ";\n"; count++; } } vtkShaderProgram::Substitute(FSSource,"//VTK::Output::Dec",fragDecls); vtkShaderProgram::Substitute(GSSource,"//VTK::System::Dec", "#version 150\n" "#define highp\n" "#define mediump\n" "#define lowp"); } else { vtkShaderProgram::Substitute(VSSource,"//VTK::System::Dec", "#version 120\n" "#define highp\n" "#define mediump\n" "#define lowp"); vtkShaderProgram::Substitute(FSSource,"//VTK::System::Dec", "#version 120\n" "#extension GL_EXT_gpu_shader4 : require\n" "#define highp\n" "#define mediump\n" "#define lowp"); vtkShaderProgram::Substitute(GSSource,"//VTK::System::Dec", "#version 120\n" "#define highp\n" "#define mediump\n" "#define lowp"); } vtkShaderProgram *shader = this->GetShader(VSSource.c_str(), FSSource.c_str(), GSSource.c_str()); shader->SetNumberOfOutputs(count); #else std::string FSSource = fragmentCode; FSSource = replace(FSSource,"//VTK::System::Dec", "#ifdef GL_ES\n" "#ifdef GL_FRAGMENT_PRECISION_HIGH\n" "precision highp float;\n" "#else\n" "precision mediump float;\n" "#endif\n" "#endif\n"); vtkShaderProgram *shader = this->GetShader(vertexCode, FSSource.c_str(), geometryCode); #endif if (!shader) { return NULL; } // compile if needed if (!shader->GetCompiled() && !shader->CompileShader()) { return NULL; } // bind if needed if (!this->BindShader(shader)) { return NULL; } return shader; } // return NULL if there is an issue vtkShaderProgram *vtkOpenGLShaderCache::ReadyShader( vtkShaderProgram *shader) { // compile if needed if (!shader->GetCompiled() && !shader->CompileShader()) { return NULL; } // bind if needed if (!this->BindShader(shader)) { return NULL; } return shader; } vtkShaderProgram *vtkOpenGLShaderCache::GetShader( const char *vertexCode, const char *fragmentCode, const char *geometryCode) { // compute the MD5 and the check the map std::string result; this->Internal->ComputeMD5(vertexCode, fragmentCode, geometryCode, result); // does it already exist? typedef std::map<std::string,vtkShaderProgram*>::const_iterator SMapIter; SMapIter found = this->Internal->ShaderPrograms.find(result); if (found == this->Internal->ShaderPrograms.end()) { // create one vtkShaderProgram *sps = vtkShaderProgram::New(); sps->GetVertexShader()->SetSource(vertexCode); sps->GetFragmentShader()->SetSource(fragmentCode); if (geometryCode != NULL) { sps->GetGeometryShader()->SetSource(geometryCode); } sps->SetMD5Hash(result); // needed? this->Internal->ShaderPrograms.insert(std::make_pair(result, sps)); return sps; } else { return found->second; } } void vtkOpenGLShaderCache::ReleaseGraphicsResources(vtkWindow *win) { // NOTE: // In the current implementation as of October 26th, if a shader // program is created by ShaderCache then it should make sure // that it releases the graphics resouces used by these programs. // It is not wisely for callers to do that since then they would // have to loop over all the programs were in use and invoke // release graphics resources individually. this->ReleaseCurrentShader(); typedef std::map<std::string,vtkShaderProgram*>::const_iterator SMapIter; SMapIter iter = this->Internal->ShaderPrograms.begin(); for ( ; iter != this->Internal->ShaderPrograms.end(); iter++) { iter->second->ReleaseGraphicsResources(win); } } void vtkOpenGLShaderCache::ReleaseCurrentShader() { // release prior shader if (this->LastShaderBound) { this->LastShaderBound->Release(); this->LastShaderBound = NULL; } } int vtkOpenGLShaderCache::BindShader(vtkShaderProgram* shader) { if (this->LastShaderBound == shader) { return 1; } // release prior shader if (this->LastShaderBound) { this->LastShaderBound->Release(); } shader->Bind(); this->LastShaderBound = shader; return 1; } // ---------------------------------------------------------------------------- void vtkOpenGLShaderCache::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); }
/*========================================================================= Program: Visualization Toolkit Module: vtkOpenGLShaderCache.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 "vtkOpenGLShaderCache.h" #include "vtk_glew.h" #include "vtkObjectFactory.h" #include "vtkOpenGLError.h" #include "vtkOpenGLRenderWindow.h" #include "vtkShader.h" #include "vtkShaderProgram.h" #include "vtkOpenGLHelper.h" #include <math.h> #include <sstream> #include "vtksys/MD5.h" class vtkOpenGLShaderCache::Private { public: vtksysMD5* md5; // map of hash to shader program structs std::map<std::string, vtkShaderProgram *> ShaderPrograms; Private() { md5 = vtksysMD5_New(); } ~Private() { vtksysMD5_Delete(this->md5); } //----------------------------------------------------------------------------- void ComputeMD5(const char* content, const char* content2, const char* content3, std::string &hash) { unsigned char digest[16]; char md5Hash[33]; md5Hash[32] = '\0'; vtksysMD5_Initialize(this->md5); vtksysMD5_Append(this->md5, reinterpret_cast<const unsigned char *>(content), (int)strlen(content)); vtksysMD5_Append(this->md5, reinterpret_cast<const unsigned char *>(content2), (int)strlen(content2)); vtksysMD5_Append(this->md5, reinterpret_cast<const unsigned char *>(content3), (int)strlen(content3)); vtksysMD5_Finalize(this->md5, digest); vtksysMD5_DigestToHex(digest, md5Hash); hash = md5Hash; } }; // ---------------------------------------------------------------------------- vtkStandardNewMacro(vtkOpenGLShaderCache); // ---------------------------------------------------------------------------- vtkOpenGLShaderCache::vtkOpenGLShaderCache() : Internal(new Private) { this->LastShaderBound = NULL; } // ---------------------------------------------------------------------------- vtkOpenGLShaderCache::~vtkOpenGLShaderCache() { typedef std::map<std::string,vtkShaderProgram*>::const_iterator SMapIter; SMapIter iter = this->Internal->ShaderPrograms.begin(); for ( ; iter != this->Internal->ShaderPrograms.end(); iter++) { iter->second->Delete(); } delete this->Internal; } // return NULL if there is an issue vtkShaderProgram *vtkOpenGLShaderCache::ReadyShader( const char *vertexCode, const char *fragmentCode, const char *geometryCode) { // perform system wide shader replacements // desktops to not use percision statements #if GL_ES_VERSION_2_0 != 1 unsigned int count = 0; std::string VSSource = vertexCode; std::string FSSource = fragmentCode; std::string GSSource = geometryCode; if (vtkOpenGLRenderWindow::GetContextSupportsOpenGL32()) { vtkShaderProgram::Substitute(VSSource,"//VTK::System::Dec", "#version 150\n" "#define attribute in\n" "#define varying out\n" "#define highp\n" "#define mediump\n" "#define lowp"); vtkShaderProgram::Substitute(FSSource,"//VTK::System::Dec", "#version 150\n" "#define varying in\n" "#define highp\n" "#define mediump\n" "#define lowp\n" "#define texelFetchBuffer texelFetch\n" "#define texture1D texture\n" "#define texture2D texture\n" "#define texture3D texture\n" ); vtkShaderProgram::Substitute(GSSource,"//VTK::System::Dec", "#version 150\n" "#define highp\n" "#define mediump\n" "#define lowp" ); std::string fragDecls; bool done = false; while (!done) { std::ostringstream src; std::ostringstream dst; src << "gl_FragData[" << count << "]"; // this naming has to match the bindings // in vtkOpenGLShaderProgram.cxx dst << "fragOutput" << count; done = !vtkShaderProgram::Substitute(FSSource, src.str(),dst.str()); if (!done) { fragDecls += "out vec4 " + dst.str() + ";\n"; count++; } } vtkShaderProgram::Substitute(FSSource,"//VTK::Output::Dec",fragDecls); vtkShaderProgram::Substitute(GSSource,"//VTK::System::Dec", "#version 150\n" "#define highp\n" "#define mediump\n" "#define lowp"); } else { vtkShaderProgram::Substitute(VSSource,"//VTK::System::Dec", "#version 120\n" "#define highp\n" "#define mediump\n" "#define lowp"); vtkShaderProgram::Substitute(FSSource,"//VTK::System::Dec", "#version 120\n" "#extension GL_EXT_gpu_shader4 : require\n" "#define highp\n" "#define mediump\n" "#define lowp"); vtkShaderProgram::Substitute(GSSource,"//VTK::System::Dec", "#version 120\n" "#define highp\n" "#define mediump\n" "#define lowp"); } vtkShaderProgram *shader = this->GetShader(VSSource.c_str(), FSSource.c_str(), GSSource.c_str()); shader->SetNumberOfOutputs(count); #else std::string FSSource = fragmentCode; vtkShaderProgram::Substitute(FSSource,"//VTK::System::Dec", "#ifdef GL_ES\n" "#ifdef GL_FRAGMENT_PRECISION_HIGH\n" "precision highp float;\n" "#else\n" "precision mediump float;\n" "#endif\n" "#endif\n"); vtkShaderProgram *shader = this->GetShader(vertexCode, FSSource.c_str(), geometryCode); #endif if (!shader) { return NULL; } // compile if needed if (!shader->GetCompiled() && !shader->CompileShader()) { return NULL; } // bind if needed if (!this->BindShader(shader)) { return NULL; } return shader; } // return NULL if there is an issue vtkShaderProgram *vtkOpenGLShaderCache::ReadyShader( vtkShaderProgram *shader) { // compile if needed if (!shader->GetCompiled() && !shader->CompileShader()) { return NULL; } // bind if needed if (!this->BindShader(shader)) { return NULL; } return shader; } vtkShaderProgram *vtkOpenGLShaderCache::GetShader( const char *vertexCode, const char *fragmentCode, const char *geometryCode) { // compute the MD5 and the check the map std::string result; this->Internal->ComputeMD5(vertexCode, fragmentCode, geometryCode, result); // does it already exist? typedef std::map<std::string,vtkShaderProgram*>::const_iterator SMapIter; SMapIter found = this->Internal->ShaderPrograms.find(result); if (found == this->Internal->ShaderPrograms.end()) { // create one vtkShaderProgram *sps = vtkShaderProgram::New(); sps->GetVertexShader()->SetSource(vertexCode); sps->GetFragmentShader()->SetSource(fragmentCode); if (geometryCode != NULL) { sps->GetGeometryShader()->SetSource(geometryCode); } sps->SetMD5Hash(result); // needed? this->Internal->ShaderPrograms.insert(std::make_pair(result, sps)); return sps; } else { return found->second; } } void vtkOpenGLShaderCache::ReleaseGraphicsResources(vtkWindow *win) { // NOTE: // In the current implementation as of October 26th, if a shader // program is created by ShaderCache then it should make sure // that it releases the graphics resouces used by these programs. // It is not wisely for callers to do that since then they would // have to loop over all the programs were in use and invoke // release graphics resources individually. this->ReleaseCurrentShader(); typedef std::map<std::string,vtkShaderProgram*>::const_iterator SMapIter; SMapIter iter = this->Internal->ShaderPrograms.begin(); for ( ; iter != this->Internal->ShaderPrograms.end(); iter++) { iter->second->ReleaseGraphicsResources(win); } } void vtkOpenGLShaderCache::ReleaseCurrentShader() { // release prior shader if (this->LastShaderBound) { this->LastShaderBound->Release(); this->LastShaderBound = NULL; } } int vtkOpenGLShaderCache::BindShader(vtkShaderProgram* shader) { if (this->LastShaderBound == shader) { return 1; } // release prior shader if (this->LastShaderBound) { this->LastShaderBound->Release(); } shader->Bind(); this->LastShaderBound = shader; return 1; } // ---------------------------------------------------------------------------- void vtkOpenGLShaderCache::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); }
Fix for compile issue on OpenGLES
Fix for compile issue on OpenGLES
C++
bsd-3-clause
demarle/VTK,gram526/VTK,SimVascular/VTK,sumedhasingla/VTK,gram526/VTK,sankhesh/VTK,sumedhasingla/VTK,msmolens/VTK,jmerkow/VTK,msmolens/VTK,sumedhasingla/VTK,candy7393/VTK,sankhesh/VTK,msmolens/VTK,gram526/VTK,msmolens/VTK,keithroe/vtkoptix,jmerkow/VTK,jmerkow/VTK,msmolens/VTK,sankhesh/VTK,keithroe/vtkoptix,sankhesh/VTK,sankhesh/VTK,sumedhasingla/VTK,SimVascular/VTK,gram526/VTK,sumedhasingla/VTK,jmerkow/VTK,keithroe/vtkoptix,mspark93/VTK,keithroe/vtkoptix,gram526/VTK,candy7393/VTK,sankhesh/VTK,sankhesh/VTK,mspark93/VTK,msmolens/VTK,gram526/VTK,SimVascular/VTK,candy7393/VTK,candy7393/VTK,jmerkow/VTK,SimVascular/VTK,demarle/VTK,mspark93/VTK,gram526/VTK,demarle/VTK,SimVascular/VTK,mspark93/VTK,demarle/VTK,mspark93/VTK,demarle/VTK,sumedhasingla/VTK,keithroe/vtkoptix,SimVascular/VTK,msmolens/VTK,demarle/VTK,candy7393/VTK,mspark93/VTK,sumedhasingla/VTK,jmerkow/VTK,keithroe/vtkoptix,candy7393/VTK,candy7393/VTK,demarle/VTK,SimVascular/VTK,SimVascular/VTK,sankhesh/VTK,keithroe/vtkoptix,gram526/VTK,jmerkow/VTK,candy7393/VTK,mspark93/VTK,mspark93/VTK,jmerkow/VTK,msmolens/VTK,keithroe/vtkoptix,sumedhasingla/VTK,demarle/VTK
13f18b143e84b3a0f899ca5712fbaa55ba68308d
src/persons-model.cpp
src/persons-model.cpp
/* Persons Model Copyright (C) 2012 Martin Klapetek <[email protected]> Copyright (C) 2012 Aleix Pol Gonzalez <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "persons-model.h" #include "persons-model-item.h" #include "persons-model-contact-item.h" #include "resource-watcher-service.h" #include <Soprano/Query/QueryLanguage> #include <Soprano/QueryResultIterator> #include <Soprano/Model> #include <Nepomuk2/ResourceManager> #include <Nepomuk2/Variant> #include <Nepomuk2/Vocabulary/PIMO> #include <Nepomuk2/Vocabulary/NCO> #include <Nepomuk2/Vocabulary/NIE> #include <Nepomuk2/SimpleResource> #include <Nepomuk2/SimpleResourceGraph> #include <Nepomuk2/StoreResourcesJob> #include <KDebug> struct PersonsModelPrivate { }; PersonsModel::PersonsModel(QObject *parent, bool init, const QString& customQuery) : QStandardItemModel(parent) , d_ptr(new PersonsModelPrivate) { QHash<int, QByteArray> names = roleNames(); names.insert(PersonsModel::EmailRole, "email"); names.insert(PersonsModel::PhoneRole, "phone"); names.insert(PersonsModel::ContactIdRole, "contactId"); names.insert(PersonsModel::ContactTypeRole, "contactType"); names.insert(PersonsModel::IMRole, "im"); names.insert(PersonsModel::NickRole, "nick"); names.insert(PersonsModel::UriRole, "uri"); names.insert(PersonsModel::NameRole, "name"); names.insert(PersonsModel::PhotoRole, "photo"); names.insert(PersonsModel::ContactsCount, "contactsCount"); setRoleNames(names); if(init) { QString nco_query = customQuery; if(customQuery.isEmpty()) nco_query = QString::fromUtf8( "select DISTINCT ?uri ?pimo_groundingOccurrence ?nco_hasIMAccount" "?nco_imNickname ?telepathy_statusType ?nco_imID ?nco_imAccountType ?nco_hasEmailAddress" "?nco_imStatus ?nie_url " "WHERE { " "?uri a nco:PersonContact. " "OPTIONAL { ?pimo_groundingOccurrence pimo:groundingOccurrence ?uri. }" "OPTIONAL { " "?uri nco:hasIMAccount ?nco_hasIMAccount. " "OPTIONAL { ?nco_hasIMAccount nco:imNickname ?nco_imNickname. } " "OPTIONAL { ?nco_hasIMAccount telepathy:statusType ?telepathy_statusType. } " "OPTIONAL { ?nco_hasIMAccount nco:imStatus ?nco_imStatus. } " "OPTIONAL { ?nco_hasIMAccount nco:imID ?nco_imID. } " "OPTIONAL { ?nco_hasIMAccount nco:imAccountType ?nco_imAccountType. } " " } " "OPTIONAL {" "?uri nco:photo ?phRes. " "?phRes nie:url ?nie_url. " " } " "OPTIONAL { " "?uri nco:hasEmailAddress ?nco_hasEmailAddress. " "?nco_hasEmailAddress nco:emailAddress ?nco_emailAddress. " " } " "}"); QMetaObject::invokeMethod(this, "query", Qt::QueuedConnection, Q_ARG(QString, nco_query)); new ResourceWatcherService(this); } } template <class T> QList<QStandardItem*> toStandardItems(const QList<T*>& items) { QList<QStandardItem*> ret; foreach(QStandardItem* it, items) { ret += it; } return ret; } QHash<QString, QUrl> initUriToBinding() { QHash<QString, QUrl> ret; QList<QUrl> list; list << Nepomuk2::Vocabulary::NCO::imNickname() << Nepomuk2::Vocabulary::NCO::imAccountType() << Nepomuk2::Vocabulary::NCO::imID() // << Nepomuk2::Vocabulary::Telepathy::statusType() // << Nepomuk2::Vocabulary::Telepathy::accountIdentifier() << QUrl(QLatin1String("http://nepomuk.kde.org/ontologies/2009/06/20/telepathy#statusType")) << Nepomuk2::Vocabulary::NCO::imStatus() << Nepomuk2::Vocabulary::NCO::hasIMAccount() << Nepomuk2::Vocabulary::NCO::emailAddress() << Nepomuk2::Vocabulary::NIE::url(); foreach(const QUrl& keyUri, list) { QString keyString = keyUri.toString(); //convert every key to correspond to the nepomuk bindings keyString = keyString.mid(keyString.lastIndexOf(QLatin1Char('/')) + 1).replace(QLatin1Char('#'), QLatin1Char('_')); ret[keyString] = keyUri; } return ret; } void PersonsModel::query(const QString& nco_query) { Q_ASSERT(rowCount()==0); QHash<QString, QUrl> uriToBinding = initUriToBinding(); Soprano::Model* m = Nepomuk2::ResourceManager::instance()->mainModel(); Soprano::QueryResultIterator it = m->executeQuery(nco_query, Soprano::Query::QueryLanguageSparql); QHash<QUrl, PersonsModelContactItem*> contacts; QHash<QUrl, PersonsModelItem*> persons; while(it.next()) { QUrl currentUri = it[QLatin1String("uri")].uri(); PersonsModelContactItem* contactNode = contacts.value(currentUri); bool newContact = !contactNode; if(!contactNode) { contactNode = new PersonsModelContactItem(currentUri); contacts.insert(currentUri, contactNode); } for(QHash<QString, QUrl>::const_iterator iter=uriToBinding.constBegin(), itEnd=uriToBinding.constEnd(); iter!=itEnd; ++iter) { contactNode->addData(iter.value(), it[iter.key()].toString()); } if(newContact) { QUrl pimoPersonUri = it[QLatin1String("pimo_groundingOccurrence")].uri(); Q_ASSERT(!pimoPersonUri.isEmpty()); QHash< QUrl, PersonsModelItem* >::const_iterator pos = persons.constFind(pimoPersonUri); if (pos == persons.constEnd()) pos = persons.insert(pimoPersonUri, new PersonsModelItem(pimoPersonUri)); pos.value()->appendRow(contactNode); } } invisibleRootItem()->appendRows(toStandardItems(persons.values())); emit peopleAdded(); } void PersonsModel::unmerge(const QUrl& contactUri, const QUrl& personUri) { Nepomuk2::Resource oldPerson(personUri); Q_ASSERT(oldPerson.property(Nepomuk2::Vocabulary::PIMO::groundingOccurrence()).toUrlList().size()>=2 && "there's nothing to unmerge..."); oldPerson.removeProperty(Nepomuk2::Vocabulary::PIMO::groundingOccurrence(), contactUri); Nepomuk2::SimpleResource newPerson; newPerson.addType( Nepomuk2::Vocabulary::PIMO::Person() ); newPerson.setProperty(Nepomuk2::Vocabulary::PIMO::groundingOccurrence(), contactUri); Nepomuk2::SimpleResourceGraph graph; graph << newPerson; KJob * job = Nepomuk2::storeResources( graph ); job->setProperty("uri", contactUri); job->setObjectName("Unmerge"); connect(job, SIGNAL(finished(KJob*)), SLOT(jobFinished(KJob*))); job->start(); } void PersonsModel::merge(const QList< QUrl >& persons) { KJob* job = Nepomuk2::mergeResources( persons ); job->setObjectName("Merge"); connect(job, SIGNAL(finished(KJob*)), SLOT(jobFinished(KJob*))); } void PersonsModel::merge(const QVariantList& persons) { QList<QUrl> conv; foreach(const QVariant& p, persons) conv += p.toUrl(); merge(conv); } void PersonsModel::jobFinished(KJob* job) { if(job->error()!=0) { kWarning() << job->objectName() << " failed for "<< job->property("uri").toString() << job->errorText() << job->errorString(); } else { kWarning() << job->objectName() << " done: "<< job->property("uri").toString(); } } QModelIndex PersonsModel::findRecursively(int role, const QVariant& value, const QModelIndex& idx) const { if(idx.isValid() && data(idx, role)==value) return idx; int rows = rowCount(idx); for(int i=0; i<rows; i++) { QModelIndex ret = findRecursively(role, value, index(i, 0, idx)); if(ret.isValid()) return ret; } return QModelIndex(); } QModelIndex PersonsModel::indexForUri(const QUrl& uri) const { return findRecursively(PersonsModel::UriRole, uri); } void PersonsModel::createPerson(const Nepomuk2::Resource& res) { Q_ASSERT(!indexForUri(res.uri()).isValid()); appendRow(new PersonsModelItem(res)); } PersonsModelContactItem* PersonsModel::contactForIMAccount(const QUrl& uri) const { QStandardItem* it = itemFromIndex(findRecursively(PersonsModel::IMAccountUriRole, uri)); return dynamic_cast<PersonsModelContactItem*>(it); }
/* Persons Model Copyright (C) 2012 Martin Klapetek <[email protected]> Copyright (C) 2012 Aleix Pol Gonzalez <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "persons-model.h" #include "persons-model-item.h" #include "persons-model-contact-item.h" #include "resource-watcher-service.h" #include <Soprano/Query/QueryLanguage> #include <Soprano/QueryResultIterator> #include <Soprano/Model> #include <Nepomuk2/ResourceManager> #include <Nepomuk2/Variant> #include <Nepomuk2/Vocabulary/PIMO> #include <Nepomuk2/Vocabulary/NCO> #include <Nepomuk2/Vocabulary/NIE> #include <Nepomuk2/SimpleResource> #include <Nepomuk2/SimpleResourceGraph> #include <Nepomuk2/StoreResourcesJob> #include <KDebug> struct PersonsModelPrivate { }; PersonsModel::PersonsModel(QObject *parent, bool init, const QString& customQuery) : QStandardItemModel(parent) , d_ptr(new PersonsModelPrivate) { QHash<int, QByteArray> names = roleNames(); names.insert(PersonsModel::EmailRole, "email"); names.insert(PersonsModel::PhoneRole, "phone"); names.insert(PersonsModel::ContactIdRole, "contactId"); names.insert(PersonsModel::ContactTypeRole, "contactType"); names.insert(PersonsModel::IMRole, "im"); names.insert(PersonsModel::NickRole, "nick"); names.insert(PersonsModel::UriRole, "uri"); names.insert(PersonsModel::NameRole, "name"); names.insert(PersonsModel::PhotoRole, "photo"); names.insert(PersonsModel::ContactsCount, "contactsCount"); setRoleNames(names); if(init) { QString nco_query = customQuery; if(customQuery.isEmpty()) nco_query = QString::fromUtf8( "select DISTINCT ?uri ?pimo_groundingOccurrence ?nco_hasIMAccount" "?nco_imNickname ?telepathy_statusType ?nco_imID ?nco_imAccountType ?nco_hasEmailAddress" "?nco_imStatus ?nie_url " "WHERE { " "?uri a nco:PersonContact. " "OPTIONAL { ?pimo_groundingOccurrence pimo:groundingOccurrence ?uri. }" "OPTIONAL { " "?uri nco:hasIMAccount ?nco_hasIMAccount. " "OPTIONAL { ?nco_hasIMAccount nco:imNickname ?nco_imNickname. } " "OPTIONAL { ?nco_hasIMAccount telepathy:statusType ?telepathy_statusType. } " "OPTIONAL { ?nco_hasIMAccount nco:imStatus ?nco_imStatus. } " "OPTIONAL { ?nco_hasIMAccount nco:imID ?nco_imID. } " "OPTIONAL { ?nco_hasIMAccount nco:imAccountType ?nco_imAccountType. } " " } " "OPTIONAL {" "?uri nco:photo ?phRes. " "?phRes nie:url ?nie_url. " " } " "OPTIONAL { " "?uri nco:hasEmailAddress ?nco_hasEmailAddress. " "?nco_hasEmailAddress nco:emailAddress ?nco_emailAddress. " " } " "}"); QMetaObject::invokeMethod(this, "query", Qt::QueuedConnection, Q_ARG(QString, nco_query)); new ResourceWatcherService(this); } } template <class T> QList<QStandardItem*> toStandardItems(const QList<T*>& items) { QList<QStandardItem*> ret; foreach(QStandardItem* it, items) { ret += it; } return ret; } QHash<QString, QUrl> initUriToBinding() { QHash<QString, QUrl> ret; QList<QUrl> list; list << Nepomuk2::Vocabulary::NCO::imNickname() << Nepomuk2::Vocabulary::NCO::imAccountType() << Nepomuk2::Vocabulary::NCO::imID() // << Nepomuk2::Vocabulary::Telepathy::statusType() // << Nepomuk2::Vocabulary::Telepathy::accountIdentifier() << QUrl(QLatin1String("http://nepomuk.kde.org/ontologies/2009/06/20/telepathy#statusType")) << Nepomuk2::Vocabulary::NCO::imStatus() << Nepomuk2::Vocabulary::NCO::hasIMAccount() << Nepomuk2::Vocabulary::NCO::emailAddress() << Nepomuk2::Vocabulary::NIE::url(); foreach(const QUrl& keyUri, list) { QString keyString = keyUri.toString(); //convert every key to correspond to the nepomuk bindings keyString = keyString.mid(keyString.lastIndexOf(QLatin1Char('/')) + 1).replace(QLatin1Char('#'), QLatin1Char('_')); ret[keyString] = keyUri; } return ret; } void PersonsModel::query(const QString& nco_query) { Q_ASSERT(rowCount()==0); QHash<QString, QUrl> uriToBinding = initUriToBinding(); Soprano::Model* m = Nepomuk2::ResourceManager::instance()->mainModel(); Soprano::QueryResultIterator it = m->executeQuery(nco_query, Soprano::Query::QueryLanguageSparql); QHash<QUrl, PersonsModelContactItem*> contacts; QHash<QUrl, PersonsModelItem*> persons; while(it.next()) { QUrl currentUri = it[QLatin1String("uri")].uri(); PersonsModelContactItem* contactNode = contacts.value(currentUri); bool newContact = !contactNode; if(!contactNode) { contactNode = new PersonsModelContactItem(currentUri); } for(QHash<QString, QUrl>::const_iterator iter=uriToBinding.constBegin(), itEnd=uriToBinding.constEnd(); iter!=itEnd; ++iter) { contactNode->addData(iter.value(), it[iter.key()].toString()); } QUrl pimoPersonUri = it[QLatin1String("pimo_groundingOccurrence")].uri(); if (pimoPersonUri.isEmpty()) { //TODO: look for other contacts and possibly automerge contacts.insert(currentUri, contactNode); } else { QHash< QUrl, PersonsModelItem* >::const_iterator pos = persons.constFind(pimoPersonUri); if (pos == persons.constEnd()) { pos = persons.insert(pimoPersonUri, new PersonsModelItem(pimoPersonUri)); } pos.value()->appendRow(contactNode); } } invisibleRootItem()->appendRows(toStandardItems(persons.values())); invisibleRootItem()->appendRows(toStandardItems(contacts.values())); emit peopleAdded(); kDebug() << "Model ready"; } void PersonsModel::unmerge(const QUrl& contactUri, const QUrl& personUri) { Nepomuk2::Resource oldPerson(personUri); Q_ASSERT(oldPerson.property(Nepomuk2::Vocabulary::PIMO::groundingOccurrence()).toUrlList().size()>=2 && "there's nothing to unmerge..."); oldPerson.removeProperty(Nepomuk2::Vocabulary::PIMO::groundingOccurrence(), contactUri); Nepomuk2::SimpleResource newPerson; newPerson.addType( Nepomuk2::Vocabulary::PIMO::Person() ); newPerson.setProperty(Nepomuk2::Vocabulary::PIMO::groundingOccurrence(), contactUri); Nepomuk2::SimpleResourceGraph graph; graph << newPerson; KJob * job = Nepomuk2::storeResources( graph ); job->setProperty("uri", contactUri); job->setObjectName("Unmerge"); connect(job, SIGNAL(finished(KJob*)), SLOT(jobFinished(KJob*))); job->start(); } void PersonsModel::merge(const QList< QUrl >& persons) { KJob* job = Nepomuk2::mergeResources( persons ); job->setObjectName("Merge"); connect(job, SIGNAL(finished(KJob*)), SLOT(jobFinished(KJob*))); } void PersonsModel::merge(const QVariantList& persons) { QList<QUrl> conv; foreach(const QVariant& p, persons) conv += p.toUrl(); merge(conv); } void PersonsModel::jobFinished(KJob* job) { if(job->error()!=0) { kWarning() << job->objectName() << " failed for "<< job->property("uri").toString() << job->errorText() << job->errorString(); } else { kWarning() << job->objectName() << " done: "<< job->property("uri").toString(); } } QModelIndex PersonsModel::findRecursively(int role, const QVariant& value, const QModelIndex& idx) const { if(idx.isValid() && data(idx, role)==value) return idx; int rows = rowCount(idx); for(int i=0; i<rows; i++) { QModelIndex ret = findRecursively(role, value, index(i, 0, idx)); if(ret.isValid()) return ret; } return QModelIndex(); } QModelIndex PersonsModel::indexForUri(const QUrl& uri) const { return findRecursively(PersonsModel::UriRole, uri); } void PersonsModel::createPerson(const Nepomuk2::Resource& res) { Q_ASSERT(!indexForUri(res.uri()).isValid()); appendRow(new PersonsModelItem(res)); } PersonsModelContactItem* PersonsModel::contactForIMAccount(const QUrl& uri) const { QStandardItem* it = itemFromIndex(findRecursively(PersonsModel::IMAccountUriRole, uri)); return dynamic_cast<PersonsModelContactItem*>(it); }
Append the standalone contacts to the root item directly
Append the standalone contacts to the root item directly
C++
lgpl-2.1
detrout/libkpeople-debian,detrout/libkpeople-debian,detrout/libkpeople-debian
247866ef4f6af2368ab25e46c28cbdf142dceed0
src/plugins/os/os.cpp
src/plugins/os/os.cpp
// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp: /* Copyright (c) 2008 Rüdiger Sonderfeld 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 WIN32 #define POSIX #endif #include "flusspferd/class.hpp" #include "flusspferd/create.hpp" #include "flusspferd/security.hpp" #include <cstdlib> #ifdef POSIX #include <time.h> #include <cerrno> #elif WIN32 #include <windows.h> #else #error "OS not supported by os plugin" #endif using namespace flusspferd; #ifdef POSIX void sleep_(unsigned ms) { timespec ts; ts.tv_sec = ms/1000; ts.tv_nsec = (ms%1000) * 1000000; // convert ms to ns timespec rem; while(nanosleep(&ts, &rem) == -1 && errno == EINTR) ts = rem; } #elif WIN32 void sleep_(unsigned ms) { Sleep(ms); } #endif namespace { extern "C" void flusspferd_load(object os) { create_native_function(os, "system", &std::system); create_native_function(os, "sleep", &sleep_); } }
// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp: /* Copyright (c) 2008 Rüdiger Sonderfeld 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 WIN32 #define POSIX #endif #include "flusspferd/class.hpp" #include "flusspferd/create.hpp" #include "flusspferd/security.hpp" #include <cstdlib> #ifdef POSIX #include <time.h> #include <cerrno> #elif WIN32 #include <windows.h> #else #error "OS not supported by os plugin" #endif using namespace flusspferd; namespace { #ifdef POSIX void sleep_(unsigned ms) { timespec ts; ts.tv_sec = ms/1000; ts.tv_nsec = (ms%1000) * 1000000; // convert ms to ns timespec rem; while(nanosleep(&ts, &rem) == -1 && errno == EINTR) ts = rem; } #elif WIN32 void sleep_(unsigned ms) { Sleep(ms); } #endif extern "C" void flusspferd_load(object os) { create_native_function(os, "system", &std::system); create_native_function(os, "sleep", &sleep_); } }
put sleep_ into hidden namespace
plugins.os: put sleep_ into hidden namespace
C++
mit
Flusspferd/flusspferd,Flusspferd/flusspferd,Flusspferd/flusspferd,Flusspferd/flusspferd,Flusspferd/flusspferd
209864d7caa931c8b76e35241c47c9b74343c579
tests/src/NetAccessorTest/NetAccessorTest.cpp
tests/src/NetAccessorTest/NetAccessorTest.cpp
/* * Copyright 1999-2000,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id$ * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/util/XMLString.hpp> #include <xercesc/util/XMLURL.hpp> #include <xercesc/util/XMLNetAccessor.hpp> #include <xercesc/util/BinInputStream.hpp> #include <iostream> XERCES_CPP_NAMESPACE_USE inline XERCES_STD_QUALIFIER ostream& operator<<(XERCES_STD_QUALIFIER ostream& os, const XMLCh* xmlStr) { char* transcoded = XMLString::transcode(xmlStr); os << transcoded; XMLString::release(&transcoded); return os; } void exercise(BinInputStream& stream) { static float percents[] = { 1.0, 0.5, 0.25, 0.1, 0.15, 0.113, 0.333, 0.0015, 0.0013 }; int numPercents = sizeof(percents) / sizeof(float); const unsigned int bufferMax = 4096; XMLByte buffer[bufferMax]; int iteration = 0; unsigned int bytesRead = 0; do { // Calculate a percentage of our maximum buffer size, going through // them round-robin float percent = percents[iteration % numPercents]; unsigned int bufCnt = (unsigned int)(bufferMax * percent); // Check to make sure we didn't go out of bounds if (bufCnt <= 0) bufCnt = 1; if (bufCnt > bufferMax) bufCnt = bufferMax; // Read bytes into our buffer bytesRead = stream.readBytes(buffer, bufCnt); //XERCES_STD_QUALIFIER cerr << "Read " << bytesRead << " bytes into a " << bufCnt << " byte buffer\n"; if (bytesRead > 0) { // Write the data to standard out XERCES_STD_QUALIFIER cout.write((char*)buffer, bytesRead); } ++iteration; } while (bytesRead > 0); } // --------------------------------------------------------------------------- // Program entry point // --------------------------------------------------------------------------- int main(int argc, char** argv) { // Init the XML platform try { XMLPlatformUtils::Initialize(); } catch(const XMLException& toCatch) { XERCES_STD_QUALIFIER cout << "Error during platform init! Message:\n" << toCatch.getMessage() << XERCES_STD_QUALIFIER endl; return 1; } // Look for our one and only parameter if (argc != 2) { XERCES_STD_QUALIFIER cerr << "Usage: NetAccessorTest url\n" "\n" "This test reads data from the given url and writes the result\n" "to standard output.\n" "\n" "A variety of buffer sizes is are used during the test.\n" "\n" ; exit(1); } // Get the URL char* url = argv[1]; // Do the test try { XMLURL xmlURL(url); // Get the netaccessor XMLNetAccessor* na = XMLPlatformUtils::fgNetAccessor; if (na == 0) { XERCES_STD_QUALIFIER cerr << "No netaccessor is available. Aborting.\n"; exit(2); } // Build a binary input stream BinInputStream* is = na->makeNew(xmlURL); if (is == 0) { XERCES_STD_QUALIFIER cerr << "No binary input stream created. Aborting.\n"; exit(3); } // Exercise the inputstream exercise(*is); // Delete the is delete is; } catch(const XMLException& toCatch) { XERCES_STD_QUALIFIER cout << "Exception during test:\n " << toCatch.getMessage() << XERCES_STD_QUALIFIER endl; } // And call the termination method XMLPlatformUtils::Terminate(); return 0; }
/* * Copyright 1999-2000,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id$ * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/util/XMLString.hpp> #include <xercesc/util/XMLURL.hpp> #include <xercesc/util/XMLNetAccessor.hpp> #include <xercesc/util/BinInputStream.hpp> #if defined(XERCES_NEW_IOSTREAMS) #include <iostream> #else #include <iostream.h> #endif XERCES_CPP_NAMESPACE_USE inline XERCES_STD_QUALIFIER ostream& operator<<(XERCES_STD_QUALIFIER ostream& os, const XMLCh* xmlStr) { char* transcoded = XMLString::transcode(xmlStr); os << transcoded; XMLString::release(&transcoded); return os; } void exercise(BinInputStream& stream) { static float percents[] = { 1.0, 0.5, 0.25, 0.1, 0.15, 0.113, 0.333, 0.0015, 0.0013 }; int numPercents = sizeof(percents) / sizeof(float); const unsigned int bufferMax = 4096; XMLByte buffer[bufferMax]; int iteration = 0; unsigned int bytesRead = 0; do { // Calculate a percentage of our maximum buffer size, going through // them round-robin float percent = percents[iteration % numPercents]; unsigned int bufCnt = (unsigned int)(bufferMax * percent); // Check to make sure we didn't go out of bounds if (bufCnt <= 0) bufCnt = 1; if (bufCnt > bufferMax) bufCnt = bufferMax; // Read bytes into our buffer bytesRead = stream.readBytes(buffer, bufCnt); //XERCES_STD_QUALIFIER cerr << "Read " << bytesRead << " bytes into a " << bufCnt << " byte buffer\n"; if (bytesRead > 0) { // Write the data to standard out XERCES_STD_QUALIFIER cout.write((char*)buffer, bytesRead); } ++iteration; } while (bytesRead > 0); } // --------------------------------------------------------------------------- // Program entry point // --------------------------------------------------------------------------- int main(int argc, char** argv) { // Init the XML platform try { XMLPlatformUtils::Initialize(); } catch(const XMLException& toCatch) { XERCES_STD_QUALIFIER cout << "Error during platform init! Message:\n" << toCatch.getMessage() << XERCES_STD_QUALIFIER endl; return 1; } // Look for our one and only parameter if (argc != 2) { XERCES_STD_QUALIFIER cerr << "Usage: NetAccessorTest url\n" "\n" "This test reads data from the given url and writes the result\n" "to standard output.\n" "\n" "A variety of buffer sizes is are used during the test.\n" "\n" ; exit(1); } // Get the URL char* url = argv[1]; // Do the test try { XMLURL xmlURL(url); // Get the netaccessor XMLNetAccessor* na = XMLPlatformUtils::fgNetAccessor; if (na == 0) { XERCES_STD_QUALIFIER cerr << "No netaccessor is available. Aborting.\n"; exit(2); } // Build a binary input stream BinInputStream* is = na->makeNew(xmlURL); if (is == 0) { XERCES_STD_QUALIFIER cerr << "No binary input stream created. Aborting.\n"; exit(3); } // Exercise the inputstream exercise(*is); // Delete the is delete is; } catch(const XMLException& toCatch) { XERCES_STD_QUALIFIER cout << "Exception during test:\n " << toCatch.getMessage() << XERCES_STD_QUALIFIER endl; } // And call the termination method XMLPlatformUtils::Terminate(); return 0; }
Allow for old iostreams to be able to compile on some platforms.
Allow for old iostreams to be able to compile on some platforms. git-svn-id: 95233098a850bdf68e142cb551b6b3e756f38fc7@436885 13f79535-47bb-0310-9956-ffa450edef68
C++
apache-2.0
svn2github/xerces-c,svn2github/xerces-c,svn2github/xerces-c,svn2github/xerces-c,svn2github/xerces-c
0bbc6042487364ef097765d3a7277e04a32f3268
src/provider/main.cpp
src/provider/main.cpp
#include <chrono> #include <cstdint> #include <cstdlib> #include <cstring> #include <exception> #include <iostream> #include <string> #include <vector> #include "boost/filesystem.hpp" #include "boost/lexical_cast.hpp" #include "zmq.hpp" #include "coral/fmi/fmu.hpp" #include "coral/fmi/importer.hpp" #include "coral/log.hpp" #include "coral/net.hpp" #include "coral/net/zmqx.hpp" #include "coral/provider.hpp" #include "coral/util.hpp" #include "coral/util/console.hpp" namespace { const std::string DEFAULT_NETWORK_INTERFACE = "*"; const std::uint16_t DEFAULT_DISCOVERY_PORT = 10272; } struct MySlaveCreator : public coral::provider::SlaveCreator { public: MySlaveCreator( coral::fmi::Importer& importer, const boost::filesystem::path& fmuPath, const coral::net::ip::Address& networkInterface, const std::string& slaveExe, std::chrono::seconds commTimeout, const std::string& outputDir) : m_fmuPath{fmuPath} , m_fmu{importer.Import(fmuPath)} , m_networkInterface{networkInterface} , m_slaveExe(slaveExe) , m_commTimeout{commTimeout} , m_outputDir(outputDir.empty() ? "." : outputDir) { } const coral::model::SlaveTypeDescription& Description() const override { return m_fmu->Description(); } bool Instantiate( std::chrono::milliseconds timeout, coral::net::SlaveLocator& slaveLocator) override { m_instantiationFailureDescription.clear(); try { auto slaveStatusSocket = zmq::socket_t(coral::net::zmqx::GlobalContext(), ZMQ_PULL); const auto slaveStatusPort = coral::net::zmqx::BindToEphemeralPort(slaveStatusSocket); const auto slaveStatusEp = "tcp://localhost:" + boost::lexical_cast<std::string>(slaveStatusPort); std::vector<std::string> args; args.push_back(slaveStatusEp); args.push_back(m_fmuPath.string()); args.push_back(m_networkInterface.ToString()); args.push_back(std::to_string(m_commTimeout.count())); args.push_back(m_outputDir); std::cout << "\nStarting slave...\n" << " FMU : " << m_fmuPath << '\n' << std::flush; coral::util::SpawnProcess(m_slaveExe, args); std::clog << "Waiting for verification..." << std::flush; std::vector<zmq::message_t> slaveStatus; const auto feedbackTimedOut = !coral::net::zmqx::WaitForIncoming( slaveStatusSocket, timeout); if (feedbackTimedOut) { throw std::runtime_error( "Slave took more than " + boost::lexical_cast<std::string>(timeout.count()) + " milliseconds to start; presumably it has failed altogether"); } coral::net::zmqx::Receive(slaveStatusSocket, slaveStatus); if (coral::net::zmqx::ToString(slaveStatus[0]) == "ERROR" && slaveStatus.size() == 2) { throw std::runtime_error(coral::net::zmqx::ToString(slaveStatus[1])); } else if (coral::net::zmqx::ToString(slaveStatus[0]) != "OK" || slaveStatus.size() < 3 || slaveStatus[1].size() == 0 || slaveStatus[2].size() == 0) { throw std::runtime_error("Invalid data received from slave executable"); } // At this point, we know that slaveStatus contains three frames, where // the first one is "OK", signifying that the slave seems to be up and // running. The following two contains the endpoints to which the slave // is bound. slaveLocator = coral::net::SlaveLocator{ coral::net::ip::Endpoint{coral::net::zmqx::ToString(slaveStatus[1])} .ToEndpoint("tcp"), coral::net::ip::Endpoint{coral::net::zmqx::ToString(slaveStatus[2])} .ToEndpoint("tcp") }; std::clog << "OK" << std::endl; return true; } catch (const std::exception& e) { m_instantiationFailureDescription = e.what(); return false; } } std::string InstantiationFailureDescription() const override { return m_instantiationFailureDescription; } private: boost::filesystem::path m_fmuPath; std::shared_ptr<coral::fmi::FMU> m_fmu; coral::net::ip::Address m_networkInterface; std::string m_slaveExe; std::chrono::seconds m_commTimeout; std::string m_outputDir; std::string m_instantiationFailureDescription; }; void ScanDirectoryForFMUs( const std::string& directory, std::vector<std::string>& fmuPaths) { namespace fs = boost::filesystem; for (auto it = fs::recursive_directory_iterator(directory); it != fs::recursive_directory_iterator(); ++it) { if (it->path().extension() == ".fmu") { fmuPaths.push_back(it->path().string()); } } } int main(int argc, const char** argv) { try { #ifdef CORAL_LOG_TRACE_ENABLED coral::log::SetLevel(coral::log::trace); #elif defined(CORAL_LOG_DEBUG_ENABLED) coral::log::SetLevel(coral::log::debug); #endif const auto fmuCacheDir = boost::filesystem::temp_directory_path() / "coral" / "cache"; auto importer = coral::fmi::Importer::Create(fmuCacheDir); namespace po = boost::program_options; po::options_description options("Options"); options.add_options() ("clean-cache", "Clear the cache which contains previously unpacked FMU contents." "The program will exit immediately after performing this action.") ("interface", po::value<std::string>()->default_value(DEFAULT_NETWORK_INTERFACE), "The IP address or (OS-specific) name of the network interface to " "use for network communications, or \"*\" for all/any.") ("output-dir,o", po::value<std::string>()->default_value("."), "The directory where output files should be written") ("port", po::value<std::uint16_t>()->default_value(DEFAULT_DISCOVERY_PORT), "The UDP port used to broadcast information about this slave provider. " "The master must listen on the same port.") ("slave-exe", po::value<std::string>(), "The path to the slave executable") ("timeout", po::value<unsigned int>()->default_value(3600), "The number of seconds of inactivity before a slave shuts itself down"); po::options_description positionalOptions("Arguments"); positionalOptions.add_options() ("fmu", po::value<std::vector<std::string>>(), "The FMU files and directories"); po::positional_options_description positions; positions.add("fmu", -1); const auto args = coral::util::CommandLine(argc-1, argv+1); const auto optionValues = coral::util::ParseArguments( args, options, positionalOptions, positions, std::cerr, "slave_provider", "Slave provider (" CORAL_PROGRAM_NAME_VERSION ")\n\n" "This program loads one or more FMUs and makes them available as\n" "slaves on a domain."); if (!optionValues) return 0; if (optionValues->count("clean-cache")) { importer->CleanCache(); return 0; } if (!optionValues->count("fmu")) throw std::runtime_error("No FMUs specified"); const auto networkInterface = coral::net::ip::Address{ (*optionValues)["interface"].as<std::string>()}; const auto outputDir = (*optionValues)["output-dir"].as<std::string>(); const auto discoveryPort = coral::net::ip::Port{ (*optionValues)["port"].as<std::uint16_t>()}; const auto timeout = std::chrono::seconds((*optionValues)["timeout"].as<unsigned int>()); std::string slaveExe; if (optionValues->count("slave-exe")) { slaveExe = (*optionValues)["slave-exe"].as<std::string>(); } else if (const auto slaveExeEnv = std::getenv("CORAL_SLAVE_EXE")) { slaveExe = slaveExeEnv; } else { #ifdef _WIN32 const auto exeName = "slave.exe"; #else const auto exeName = "slave"; #endif auto tryPath = coral::util::ThisExePath().parent_path() / exeName; if (boost::filesystem::exists(tryPath)) { slaveExe = tryPath.string(); } else { throw std::runtime_error("Slave executable not specified or found"); } } assert (!slaveExe.empty()); std::vector<std::string> fmuPaths; for (const auto& fmuSpec : (*optionValues)["fmu"].as<std::vector<std::string>>()) { if (boost::filesystem::is_directory(fmuSpec)) { ScanDirectoryForFMUs(fmuSpec, fmuPaths); } else { fmuPaths.push_back(fmuSpec); } } std::vector<std::unique_ptr<coral::provider::SlaveCreator>> fmus; for (const auto& p : fmuPaths) { fmus.push_back(std::make_unique<MySlaveCreator>( *importer, p, networkInterface, slaveExe, timeout, outputDir)); std::cout << "FMU loaded: " << p << std::endl; } std::cout << fmus.size() << " FMUs loaded" << std::endl; coral::provider::SlaveProvider slaveProvider{ coral::util::RandomUUID(), std::move(fmus), networkInterface, discoveryPort, [](std::exception_ptr e) { try { std::rethrow_exception(e); } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; std::exit(1); } } }; std::cout << "Press ENTER to quit" << std::flush; std::cin.ignore(); slaveProvider.Stop(); } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } return 0; }
#include <chrono> #include <cstdint> #include <cstdlib> #include <cstring> #include <exception> #include <iostream> #include <string> #include <vector> #include "boost/filesystem.hpp" #include "boost/lexical_cast.hpp" #include "zmq.hpp" #include "coral/fmi/fmu.hpp" #include "coral/fmi/importer.hpp" #include "coral/log.hpp" #include "coral/net.hpp" #include "coral/net/zmqx.hpp" #include "coral/provider.hpp" #include "coral/util.hpp" #include "coral/util/console.hpp" namespace { const std::string DEFAULT_NETWORK_INTERFACE = "*"; const std::uint16_t DEFAULT_DISCOVERY_PORT = 10272; #ifdef _WIN32 const std::string DEFAULT_SLAVE_EXE = "coralslave.exe"; #else const std::string DEFAULT_SLAVE_EXE = "coralslave"; #endif } struct MySlaveCreator : public coral::provider::SlaveCreator { public: MySlaveCreator( coral::fmi::Importer& importer, const boost::filesystem::path& fmuPath, const coral::net::ip::Address& networkInterface, const std::string& slaveExe, std::chrono::seconds commTimeout, const std::string& outputDir) : m_fmuPath{fmuPath} , m_fmu{importer.Import(fmuPath)} , m_networkInterface{networkInterface} , m_slaveExe(slaveExe) , m_commTimeout{commTimeout} , m_outputDir(outputDir.empty() ? "." : outputDir) { } const coral::model::SlaveTypeDescription& Description() const override { return m_fmu->Description(); } bool Instantiate( std::chrono::milliseconds timeout, coral::net::SlaveLocator& slaveLocator) override { m_instantiationFailureDescription.clear(); try { auto slaveStatusSocket = zmq::socket_t(coral::net::zmqx::GlobalContext(), ZMQ_PULL); const auto slaveStatusPort = coral::net::zmqx::BindToEphemeralPort(slaveStatusSocket); const auto slaveStatusEp = "tcp://localhost:" + boost::lexical_cast<std::string>(slaveStatusPort); std::vector<std::string> args; args.push_back(slaveStatusEp); args.push_back(m_fmuPath.string()); args.push_back(m_networkInterface.ToString()); args.push_back(std::to_string(m_commTimeout.count())); args.push_back(m_outputDir); std::cout << "\nStarting slave...\n" << " FMU : " << m_fmuPath << '\n' << std::flush; coral::util::SpawnProcess(m_slaveExe, args); std::clog << "Waiting for verification..." << std::flush; std::vector<zmq::message_t> slaveStatus; const auto feedbackTimedOut = !coral::net::zmqx::WaitForIncoming( slaveStatusSocket, timeout); if (feedbackTimedOut) { throw std::runtime_error( "Slave took more than " + boost::lexical_cast<std::string>(timeout.count()) + " milliseconds to start; presumably it has failed altogether"); } coral::net::zmqx::Receive(slaveStatusSocket, slaveStatus); if (coral::net::zmqx::ToString(slaveStatus[0]) == "ERROR" && slaveStatus.size() == 2) { throw std::runtime_error(coral::net::zmqx::ToString(slaveStatus[1])); } else if (coral::net::zmqx::ToString(slaveStatus[0]) != "OK" || slaveStatus.size() < 3 || slaveStatus[1].size() == 0 || slaveStatus[2].size() == 0) { throw std::runtime_error("Invalid data received from slave executable"); } // At this point, we know that slaveStatus contains three frames, where // the first one is "OK", signifying that the slave seems to be up and // running. The following two contains the endpoints to which the slave // is bound. slaveLocator = coral::net::SlaveLocator{ coral::net::ip::Endpoint{coral::net::zmqx::ToString(slaveStatus[1])} .ToEndpoint("tcp"), coral::net::ip::Endpoint{coral::net::zmqx::ToString(slaveStatus[2])} .ToEndpoint("tcp") }; std::clog << "OK" << std::endl; return true; } catch (const std::exception& e) { m_instantiationFailureDescription = e.what(); return false; } } std::string InstantiationFailureDescription() const override { return m_instantiationFailureDescription; } private: boost::filesystem::path m_fmuPath; std::shared_ptr<coral::fmi::FMU> m_fmu; coral::net::ip::Address m_networkInterface; std::string m_slaveExe; std::chrono::seconds m_commTimeout; std::string m_outputDir; std::string m_instantiationFailureDescription; }; void ScanDirectoryForFMUs( const std::string& directory, std::vector<std::string>& fmuPaths) { namespace fs = boost::filesystem; for (auto it = fs::recursive_directory_iterator(directory); it != fs::recursive_directory_iterator(); ++it) { if (it->path().extension() == ".fmu") { fmuPaths.push_back(it->path().string()); } } } int main(int argc, const char** argv) { try { #ifdef CORAL_LOG_TRACE_ENABLED coral::log::SetLevel(coral::log::trace); #elif defined(CORAL_LOG_DEBUG_ENABLED) coral::log::SetLevel(coral::log::debug); #endif const auto fmuCacheDir = boost::filesystem::temp_directory_path() / "coral" / "cache"; auto importer = coral::fmi::Importer::Create(fmuCacheDir); namespace po = boost::program_options; po::options_description options("Options"); options.add_options() ("clean-cache", "Clear the cache which contains previously unpacked FMU contents." "The program will exit immediately after performing this action.") ("interface", po::value<std::string>()->default_value(DEFAULT_NETWORK_INTERFACE), "The IP address or (OS-specific) name of the network interface to " "use for network communications, or \"*\" for all/any.") ("output-dir,o", po::value<std::string>()->default_value("."), "The directory where output files should be written") ("port", po::value<std::uint16_t>()->default_value(DEFAULT_DISCOVERY_PORT), "The UDP port used to broadcast information about this slave provider. " "The master must listen on the same port.") ("slave-exe", po::value<std::string>(), "The path to the slave executable") ("timeout", po::value<unsigned int>()->default_value(3600), "The number of seconds of inactivity before a slave shuts itself down"); po::options_description positionalOptions("Arguments"); positionalOptions.add_options() ("fmu", po::value<std::vector<std::string>>(), "The FMU files and directories"); po::positional_options_description positions; positions.add("fmu", -1); const auto args = coral::util::CommandLine(argc-1, argv+1); const auto optionValues = coral::util::ParseArguments( args, options, positionalOptions, positions, std::cerr, "slave_provider", "Slave provider (" CORAL_PROGRAM_NAME_VERSION ")\n\n" "This program loads one or more FMUs and makes them available as\n" "slaves on a domain."); if (!optionValues) return 0; if (optionValues->count("clean-cache")) { importer->CleanCache(); return 0; } if (!optionValues->count("fmu")) throw std::runtime_error("No FMUs specified"); const auto networkInterface = coral::net::ip::Address{ (*optionValues)["interface"].as<std::string>()}; const auto outputDir = (*optionValues)["output-dir"].as<std::string>(); const auto discoveryPort = coral::net::ip::Port{ (*optionValues)["port"].as<std::uint16_t>()}; const auto timeout = std::chrono::seconds((*optionValues)["timeout"].as<unsigned int>()); std::string slaveExe; if (optionValues->count("slave-exe")) { slaveExe = (*optionValues)["slave-exe"].as<std::string>(); } else if (const auto slaveExeEnv = std::getenv("CORAL_SLAVE_EXE")) { slaveExe = slaveExeEnv; } else { const auto tryPath = coral::util::ThisExePath().parent_path() / DEFAULT_SLAVE_EXE; if (boost::filesystem::exists(tryPath)) { slaveExe = tryPath.string(); } else { throw std::runtime_error("Slave executable not specified or found"); } } assert (!slaveExe.empty()); std::vector<std::string> fmuPaths; for (const auto& fmuSpec : (*optionValues)["fmu"].as<std::vector<std::string>>()) { if (boost::filesystem::is_directory(fmuSpec)) { ScanDirectoryForFMUs(fmuSpec, fmuPaths); } else { fmuPaths.push_back(fmuSpec); } } std::vector<std::unique_ptr<coral::provider::SlaveCreator>> fmus; for (const auto& p : fmuPaths) { fmus.push_back(std::make_unique<MySlaveCreator>( *importer, p, networkInterface, slaveExe, timeout, outputDir)); std::cout << "FMU loaded: " << p << std::endl; } std::cout << fmus.size() << " FMUs loaded" << std::endl; coral::provider::SlaveProvider slaveProvider{ coral::util::RandomUUID(), std::move(fmus), networkInterface, discoveryPort, [](std::exception_ptr e) { try { std::rethrow_exception(e); } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; std::exit(1); } } }; std::cout << "Press ENTER to quit" << std::flush; std::cin.ignore(); slaveProvider.Stop(); } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } return 0; }
Update slave executable name in slave provider
Update slave executable name in slave provider
C++
mpl-2.0
kyllingstad/coral,kyllingstad/coral,viproma/coral
61b5b58ab7077a22d585a38f45400283d7a9e8d6
specific_object_type_implementations.cpp
specific_object_type_implementations.cpp
/* Copyright Eli Dupree and Isaac Dupree, 2011, 2012 This file is part of Lasercake. Lasercake 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. Lasercake 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 Lasercake. If not, see <http://www.gnu.org/licenses/>. */ #include "specific_object_types.hpp" namespace /* anonymous */ { typedef non_normalized_rational<polygon_int_type> rational; typedef std::pair<bool, rational> bool_and_rational; struct beam_first_contact_finder : world_collision_detector::visitor { beam_first_contact_finder(world const& w, line_segment beam):w(w),beam(beam),best_intercept_point(false, rational(1)){} world const& w; line_segment beam; bool_and_rational best_intercept_point; unordered_set<object_or_tile_identifier> ignores; object_or_tile_identifier thing_hit; void handle_new_find(object_or_tile_identifier id) { if (ignores.find(id) != ignores.end()) return; // TODO : long beams, overflow? bool_and_rational result = w.get_detail_shape_of_object_or_tile(id).first_intersection(beam); if (result.first) { if (!best_intercept_point.first || result.second < best_intercept_point.second) { best_intercept_point = result; thing_hit = id; } } } virtual bool should_be_considered__dynamic(bounding_box const& bb)const { // hack - avoid overflow const uint64_t too_large = (1ULL << 32) - 1; if (bb.size_minus_one(X) >= too_large || bb.size_minus_one(Y) >= too_large || bb.size_minus_one(Z) >= too_large) { // if there might be overflow, only do a bounds check return beam.bounds().overlaps(bb); } bool_and_rational result = shape(bb).first_intersection(beam); return result.first && (!best_intercept_point.first || result.second < best_intercept_point.second); } virtual bool bbox_ordering(bounding_box const& bb1, bounding_box const& bb2)const { for (int dim = 0; dim < 3; ++dim) { if (beam.ends[0][dim] < beam.ends[1][dim]) { if (bb1.min(dim) < bb2.min(dim)) return true; if (bb1.min(dim) > bb2.min(dim)) return false; } if (beam.ends[0][dim] > beam.ends[1][dim]) { if (bb1.min(dim) > bb2.min(dim)) return true; if (bb1.min(dim) < bb2.min(dim)) return false; } } return false; } }; void fire_standard_laser(world& w, object_identifier my_id, vector3<fine_scalar> location, vector3<fine_scalar> facing) { facing = facing * tile_width * 2 / facing.magnitude_within_32_bits(); beam_first_contact_finder finder(w, line_segment(location, location + facing * 50)); finder.ignores.insert(my_id); w.get_things_exposed_to_collision().search(&finder); if (finder.best_intercept_point.first) { // TODO do I have to worry about overflow? w.add_laser_sfx(location, facing * 50 * finder.best_intercept_point.second.numerator / finder.best_intercept_point.second.denominator); if(tile_location const* locp = finder.thing_hit.get_tile_location()) { if (locp->stuff_at().contents() == ROCK) { w.replace_substance(*locp, ROCK, RUBBLE); } } } else { w.add_laser_sfx(location, facing * 50); } } const int robot_max_carrying_capacity = 4; } /* end anonymous namespace */ shape robot::get_initial_personal_space_shape()const { return shape(bounding_box( location_ - vector3<fine_scalar>(tile_width * 3 / 10, tile_width * 3 / 10, tile_width * 3 / 10), location_ + vector3<fine_scalar>(tile_width * 3 / 10, tile_width * 3 / 10, tile_width * 3 / 10) )); } shape robot::get_initial_detail_shape()const { return get_initial_personal_space_shape(); } void robot::update(world& w, object_identifier my_id) { const bounding_box shape_bounds = w.get_object_personal_space_shapes().find(my_id)->second.bounds(); const vector3<fine_scalar> middle = (shape_bounds.min + shape_bounds.max) / 2; location_ = middle; const vector3<fine_scalar> bottom_middle(middle.x, middle.y, shape_bounds.min.z); const tile_location l = w.make_tile_location(get_containing_tile_coordinates(bottom_middle), CONTENTS_ONLY); const tile_location lminus = l.get_neighbor<zminus>(CONTENTS_ONLY); if (lminus.stuff_at().contents() != AIR) { // goal: decay towards levitating... fine_scalar target_height = (lower_bound_in_fine_units(l.coords().z, 2) + tile_height * 5 / 4); fine_scalar deficiency = target_height - shape_bounds.min.z; fine_scalar target_vel = gravity_acceleration_magnitude + deficiency * velocity_scale_factor / 8; if (velocity.z < target_vel) { velocity.z = std::min(velocity.z + gravity_acceleration_magnitude * 5, target_vel); } } input_representation::input_news_t const& input_news = w.input_news(); velocity.x -= velocity.x / 2; velocity.y -= velocity.y / 2; const fine_scalar xymag = i64sqrt(facing_.x*facing_.x + facing_.y*facing_.y); if (input_news.is_currently_pressed("x")) { velocity.x = facing_.x * tile_width * velocity_scale_factor / 8 / xymag; velocity.y = facing_.y * tile_width * velocity_scale_factor / 8 / xymag; } if (input_news.is_currently_pressed("right")) { fine_scalar new_facing_x = facing_.x + facing_.y / 20; fine_scalar new_facing_y = facing_.y - facing_.x / 20; facing_.x = new_facing_x; facing_.y = new_facing_y; } if (input_news.is_currently_pressed("left")) { fine_scalar new_facing_x = facing_.x - facing_.y / 20; fine_scalar new_facing_y = facing_.y + facing_.x / 20; facing_.x = new_facing_x; facing_.y = new_facing_y; } if (input_news.is_currently_pressed("up") != input_news.is_currently_pressed("down")) { const fine_scalar which_way = (input_news.is_currently_pressed("up") ? 1 : -1); const fine_scalar new_xymag = xymag - (which_way * facing_.z / 20); if (new_xymag > tile_width / 8) { facing_.z += which_way * xymag / 20; facing_.y = facing_.y * new_xymag / xymag; facing_.x = facing_.x * new_xymag / xymag; } } facing_ = facing_ * tile_width / facing_.magnitude_within_32_bits(); vector3<fine_scalar> beam_delta = facing_ * 3 / 2; if (input_news.is_currently_pressed("c") || input_news.is_currently_pressed("v")) { beam_first_contact_finder finder(w, line_segment(location_, location_ + beam_delta)); finder.ignores.insert(my_id); w.get_things_exposed_to_collision().search(&finder); if (finder.best_intercept_point.first) { // TODO do I have to worry about overflow? w.add_laser_sfx(location_, beam_delta * finder.best_intercept_point.second.numerator / finder.best_intercept_point.second.denominator); if(tile_location const* locp = finder.thing_hit.get_tile_location()) { if (input_news.is_currently_pressed("c") && (carrying_ < robot_max_carrying_capacity) && (locp->stuff_at().contents() == ROCK || locp->stuff_at().contents() == RUBBLE)) { ++carrying_; w.replace_substance(*locp, locp->stuff_at().contents(), AIR); } /*if (carrying && locp->stuff_at().contents() == ROCK) { w.replace_substance(*locp, ROCK, RUBBLE); }*/ } } else { w.add_laser_sfx(location_, beam_delta); if (input_news.is_currently_pressed("v") && (carrying_ > 0)) { --carrying_; const tile_location target_loc = w.make_tile_location(get_containing_tile_coordinates(location_ + beam_delta), FULL_REALIZATION); w.replace_substance(target_loc, AIR, RUBBLE); } } } if (input_news.is_currently_pressed("b")) { const vector3<fine_scalar> offset(-facing_.y / 4, facing_.x / 4, 0); fire_standard_laser(w, my_id, location_ + offset, facing_); fire_standard_laser(w, my_id, location_ - offset, facing_); } } shape laser_emitter::get_initial_personal_space_shape()const { return shape(bounding_box( location_ - vector3<fine_scalar>(tile_width * 4 / 10, tile_width * 4 / 10, tile_width * 4 / 10), location_ + vector3<fine_scalar>(tile_width * 4 / 10, tile_width * 4 / 10, tile_width * 4 / 10) )); } shape laser_emitter::get_initial_detail_shape()const { return get_initial_personal_space_shape(); } void laser_emitter::update(world& w, object_identifier my_id) { const bounding_box shape_bounds = w.get_object_personal_space_shapes().find(my_id)->second.bounds(); const vector3<fine_scalar> middle = (shape_bounds.min + shape_bounds.max) / 2; location_ = middle; const boost::random::uniform_int_distribution<get_primitive_int_type<fine_scalar>::type> random_delta(-1023, 1023); for (int i = 0; i < 100; ++i) { do { facing_.x = random_delta(w.get_rng()); facing_.y = random_delta(w.get_rng()); facing_.z = random_delta(w.get_rng()); } while (facing_.magnitude_within_32_bits_is_greater_than(1023) || facing_.magnitude_within_32_bits_is_less_than(512)); fire_standard_laser(w, my_id, location_, facing_); } }
/* Copyright Eli Dupree and Isaac Dupree, 2011, 2012 This file is part of Lasercake. Lasercake 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. Lasercake 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 Lasercake. If not, see <http://www.gnu.org/licenses/>. */ #include "specific_object_types.hpp" namespace /* anonymous */ { typedef non_normalized_rational<polygon_int_type> rational; typedef std::pair<bool, rational> bool_and_rational; struct beam_first_contact_finder : world_collision_detector::visitor { beam_first_contact_finder(world const& w, line_segment beam):w(w),beam(beam),best_intercept_point(false, rational(1)){} world const& w; line_segment beam; bool_and_rational best_intercept_point; unordered_set<object_or_tile_identifier> ignores; object_or_tile_identifier thing_hit; void handle_new_find(object_or_tile_identifier id) { if (ignores.find(id) != ignores.end()) return; // TODO : long beams, overflow? bool_and_rational result = w.get_detail_shape_of_object_or_tile(id).first_intersection(beam); if (result.first) { if (!best_intercept_point.first || result.second < best_intercept_point.second) { best_intercept_point = result; thing_hit = id; } } } bool should_be_considered__dynamic(bounding_box const& bb)const { // hack - avoid overflow const uint64_t too_large = (1ULL << 32) - 1; if (bb.size_minus_one(X) >= too_large || bb.size_minus_one(Y) >= too_large || bb.size_minus_one(Z) >= too_large) { // if there might be overflow, only do a bounds check return beam.bounds().overlaps(bb); } bool_and_rational result = shape(bb).first_intersection(beam); return result.first && (!best_intercept_point.first || result.second < best_intercept_point.second); } bool bbox_less_than(bounding_box const& bb1, bounding_box const& bb2)const { for (int dim = 0; dim < 3; ++dim) { if (beam.ends[0][dim] < beam.ends[1][dim]) { if (bb1.min(dim) < bb2.min(dim)) return true; if (bb1.min(dim) > bb2.min(dim)) return false; } if (beam.ends[0][dim] > beam.ends[1][dim]) { if (bb1.min(dim) > bb2.min(dim)) return true; if (bb1.min(dim) < bb2.min(dim)) return false; } } return false; } }; void fire_standard_laser(world& w, object_identifier my_id, vector3<fine_scalar> location, vector3<fine_scalar> facing) { facing = facing * tile_width * 2 / facing.magnitude_within_32_bits(); beam_first_contact_finder finder(w, line_segment(location, location + facing * 50)); finder.ignores.insert(my_id); w.get_things_exposed_to_collision().search(&finder); if (finder.best_intercept_point.first) { // TODO do I have to worry about overflow? w.add_laser_sfx(location, facing * 50 * finder.best_intercept_point.second.numerator / finder.best_intercept_point.second.denominator); if(tile_location const* locp = finder.thing_hit.get_tile_location()) { if (locp->stuff_at().contents() == ROCK) { w.replace_substance(*locp, ROCK, RUBBLE); } } } else { w.add_laser_sfx(location, facing * 50); } } const int robot_max_carrying_capacity = 4; } /* end anonymous namespace */ shape robot::get_initial_personal_space_shape()const { return shape(bounding_box( location_ - vector3<fine_scalar>(tile_width * 3 / 10, tile_width * 3 / 10, tile_width * 3 / 10), location_ + vector3<fine_scalar>(tile_width * 3 / 10, tile_width * 3 / 10, tile_width * 3 / 10) )); } shape robot::get_initial_detail_shape()const { return get_initial_personal_space_shape(); } void robot::update(world& w, object_identifier my_id) { const bounding_box shape_bounds = w.get_object_personal_space_shapes().find(my_id)->second.bounds(); const vector3<fine_scalar> middle = (shape_bounds.min + shape_bounds.max) / 2; location_ = middle; const vector3<fine_scalar> bottom_middle(middle.x, middle.y, shape_bounds.min.z); const tile_location l = w.make_tile_location(get_containing_tile_coordinates(bottom_middle), CONTENTS_ONLY); const tile_location lminus = l.get_neighbor<zminus>(CONTENTS_ONLY); if (lminus.stuff_at().contents() != AIR) { // goal: decay towards levitating... fine_scalar target_height = (lower_bound_in_fine_units(l.coords().z, 2) + tile_height * 5 / 4); fine_scalar deficiency = target_height - shape_bounds.min.z; fine_scalar target_vel = gravity_acceleration_magnitude + deficiency * velocity_scale_factor / 8; if (velocity.z < target_vel) { velocity.z = std::min(velocity.z + gravity_acceleration_magnitude * 5, target_vel); } } input_representation::input_news_t const& input_news = w.input_news(); velocity.x -= velocity.x / 2; velocity.y -= velocity.y / 2; const fine_scalar xymag = i64sqrt(facing_.x*facing_.x + facing_.y*facing_.y); if (input_news.is_currently_pressed("x")) { velocity.x = facing_.x * tile_width * velocity_scale_factor / 8 / xymag; velocity.y = facing_.y * tile_width * velocity_scale_factor / 8 / xymag; } if (input_news.is_currently_pressed("right")) { fine_scalar new_facing_x = facing_.x + facing_.y / 20; fine_scalar new_facing_y = facing_.y - facing_.x / 20; facing_.x = new_facing_x; facing_.y = new_facing_y; } if (input_news.is_currently_pressed("left")) { fine_scalar new_facing_x = facing_.x - facing_.y / 20; fine_scalar new_facing_y = facing_.y + facing_.x / 20; facing_.x = new_facing_x; facing_.y = new_facing_y; } if (input_news.is_currently_pressed("up") != input_news.is_currently_pressed("down")) { const fine_scalar which_way = (input_news.is_currently_pressed("up") ? 1 : -1); const fine_scalar new_xymag = xymag - (which_way * facing_.z / 20); if (new_xymag > tile_width / 8) { facing_.z += which_way * xymag / 20; facing_.y = facing_.y * new_xymag / xymag; facing_.x = facing_.x * new_xymag / xymag; } } facing_ = facing_ * tile_width / facing_.magnitude_within_32_bits(); vector3<fine_scalar> beam_delta = facing_ * 3 / 2; if (input_news.is_currently_pressed("c") || input_news.is_currently_pressed("v")) { beam_first_contact_finder finder(w, line_segment(location_, location_ + beam_delta)); finder.ignores.insert(my_id); w.get_things_exposed_to_collision().search(&finder); if (finder.best_intercept_point.first) { // TODO do I have to worry about overflow? w.add_laser_sfx(location_, beam_delta * finder.best_intercept_point.second.numerator / finder.best_intercept_point.second.denominator); if(tile_location const* locp = finder.thing_hit.get_tile_location()) { if (input_news.is_currently_pressed("c") && (carrying_ < robot_max_carrying_capacity) && (locp->stuff_at().contents() == ROCK || locp->stuff_at().contents() == RUBBLE)) { ++carrying_; w.replace_substance(*locp, locp->stuff_at().contents(), AIR); } /*if (carrying && locp->stuff_at().contents() == ROCK) { w.replace_substance(*locp, ROCK, RUBBLE); }*/ } } else { w.add_laser_sfx(location_, beam_delta); if (input_news.is_currently_pressed("v") && (carrying_ > 0)) { --carrying_; const tile_location target_loc = w.make_tile_location(get_containing_tile_coordinates(location_ + beam_delta), FULL_REALIZATION); w.replace_substance(target_loc, AIR, RUBBLE); } } } if (input_news.is_currently_pressed("b")) { const vector3<fine_scalar> offset(-facing_.y / 4, facing_.x / 4, 0); fire_standard_laser(w, my_id, location_ + offset, facing_); fire_standard_laser(w, my_id, location_ - offset, facing_); } } shape laser_emitter::get_initial_personal_space_shape()const { return shape(bounding_box( location_ - vector3<fine_scalar>(tile_width * 4 / 10, tile_width * 4 / 10, tile_width * 4 / 10), location_ + vector3<fine_scalar>(tile_width * 4 / 10, tile_width * 4 / 10, tile_width * 4 / 10) )); } shape laser_emitter::get_initial_detail_shape()const { return get_initial_personal_space_shape(); } void laser_emitter::update(world& w, object_identifier my_id) { const bounding_box shape_bounds = w.get_object_personal_space_shapes().find(my_id)->second.bounds(); const vector3<fine_scalar> middle = (shape_bounds.min + shape_bounds.max) / 2; location_ = middle; const boost::random::uniform_int_distribution<get_primitive_int_type<fine_scalar>::type> random_delta(-1023, 1023); for (int i = 0; i < 100; ++i) { do { facing_.x = random_delta(w.get_rng()); facing_.y = random_delta(w.get_rng()); facing_.z = random_delta(w.get_rng()); } while (facing_.magnitude_within_32_bits_is_greater_than(1023) || facing_.magnitude_within_32_bits_is_less_than(512)); fire_standard_laser(w, my_id, location_, facing_); } }
Fix beam_first_contact_finder virtual method naming.
Fix beam_first_contact_finder virtual method naming. I don't notice any practical effect from making this change (I did check that I'm now overriding by using C++11 'override' contextual-keyword, which I'm not leaving in the commit because not enough compilers support it and the benefit of leaving it there seems small. We don't use virtuals/overriding enough to make too many of these mistakes.) It turns out that the laser irregularities I was noticing mostly had to do with other uncommitted changes I had [and have not committed as of this commit]. I think the lasers are fine before and after this commit, and after those will-be-committed-next changes too - it was probably some intermediate state screwing things up.
C++
agpl-3.0
idupree/Lasercake,elidupree/Lasercake,Lasercake/Lasercake,idupree/Lasercake,elidupree/Lasercake,elidupree/Lasercake,elidupree/Lasercake,Lasercake/Lasercake,idupree/Lasercake,Lasercake/Lasercake,idupree/Lasercake,idupree/Lasercake,elidupree/Lasercake,idupree/Lasercake,Lasercake/Lasercake,idupree/Lasercake,elidupree/Lasercake,Lasercake/Lasercake,elidupree/Lasercake
aa6b93169825738230d0b3c486d62ba3ed0ed2db
rtos/TARGET_CORTEX/SysTimer.cpp
rtos/TARGET_CORTEX/SysTimer.cpp
/* mbed Microcontroller Library * Copyright (c) 2006-2012 ARM Limited * * 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 "rtos/TARGET_CORTEX/SysTimer.h" #if DEVICE_LOWPOWERTIMER #include "hal/lp_ticker_api.h" #include "mbed_critical.h" #include "rtx_core_cm.h" extern "C" { #include "rtx_lib.h" } #if (defined(NO_SYSTICK)) /** * Return an IRQ number that can be used in the absence of SysTick * * @return Free IRQ number that can be used */ extern "C" IRQn_Type mbed_get_m0_tick_irqn(void); #endif namespace rtos { namespace internal { SysTimer::SysTimer() : TimerEvent(get_lp_ticker_data()), _start_time(0), _tick(0) { _start_time = ticker_read_us(_ticker_data); _suspend_time_passed = true; _suspended = false; } SysTimer::SysTimer(const ticker_data_t *data) : TimerEvent(data), _start_time(0), _tick(0) { _start_time = ticker_read_us(_ticker_data); } void SysTimer::setup_irq() { #if (defined(NO_SYSTICK)) NVIC_SetVector(mbed_get_m0_tick_irqn(), (uint32_t)SysTick_Handler); NVIC_SetPriority(mbed_get_m0_tick_irqn(), 0xFF); /* RTOS requires lowest priority */ NVIC_EnableIRQ(mbed_get_m0_tick_irqn()); #else // Ensure SysTick has the correct priority as it is still used // to trigger software interrupts on each tick. The period does // not matter since it will never start counting. OS_Tick_Setup(osRtxConfig.tick_freq, OS_TICK_HANDLER); #endif } void SysTimer::suspend(uint32_t ticks) { core_util_critical_section_enter(); schedule_tick(ticks); _suspend_time_passed = false; _suspended = true; core_util_critical_section_exit(); } bool SysTimer::suspend_time_passed() { return _suspend_time_passed; } uint32_t SysTimer::resume() { core_util_critical_section_enter(); _suspended = false; _suspend_time_passed = true; remove(); uint64_t new_tick = (ticker_read_us(_ticker_data) - _start_time) * OS_TICK_FREQ / 1000000; if (new_tick > _tick) { // Don't update to the current tick. Instead, update to the // previous tick and let the SysTick handler increment it // to the current value. This allows scheduling restart // successfully after the OS is resumed. new_tick--; } uint32_t elapsed_ticks = new_tick - _tick; _tick = new_tick; core_util_critical_section_exit(); return elapsed_ticks; } void SysTimer::schedule_tick(uint32_t delta) { core_util_critical_section_enter(); insert_absolute(_start_time + (_tick + delta) * 1000000ULL / OS_TICK_FREQ); core_util_critical_section_exit(); } void SysTimer::cancel_tick() { core_util_critical_section_enter(); remove(); core_util_critical_section_exit(); } uint32_t SysTimer::get_tick() { return _tick & 0xFFFFFFFF; } us_timestamp_t SysTimer::get_time() { return ticker_read_us(_ticker_data); } SysTimer::~SysTimer() { } void SysTimer::_set_irq_pending() { // Protected function synchronized externally #if (defined(NO_SYSTICK)) NVIC_SetPendingIRQ(mbed_get_m0_tick_irqn()); #else SCB->ICSR = SCB_ICSR_PENDSTSET_Msk; #endif } void SysTimer::_increment_tick() { // Protected function synchronized externally _tick++; } void SysTimer::handler() { core_util_critical_section_enter(); if (_suspended) { _suspend_time_passed = true; } else { _set_irq_pending(); _increment_tick(); } core_util_critical_section_exit(); } } } #endif
/* mbed Microcontroller Library * Copyright (c) 2006-2012 ARM Limited * * 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 "rtos/TARGET_CORTEX/SysTimer.h" #if DEVICE_LOWPOWERTIMER #include "hal/lp_ticker_api.h" #include "mbed_critical.h" #include "rtx_core_cm.h" extern "C" { #include "rtx_lib.h" } #if (defined(NO_SYSTICK)) /** * Return an IRQ number that can be used in the absence of SysTick * * @return Free IRQ number that can be used */ extern "C" IRQn_Type mbed_get_m0_tick_irqn(void); #endif namespace rtos { namespace internal { SysTimer::SysTimer() : TimerEvent(get_lp_ticker_data()), _start_time(0), _tick(0) { _start_time = ticker_read_us(_ticker_data); _suspend_time_passed = true; _suspended = false; } SysTimer::SysTimer(const ticker_data_t *data) : TimerEvent(data), _start_time(0), _tick(0) { _start_time = ticker_read_us(_ticker_data); } void SysTimer::setup_irq() { #if (defined(NO_SYSTICK)) NVIC_SetVector(mbed_get_m0_tick_irqn(), (uint32_t)SysTick_Handler); NVIC_SetPriority(mbed_get_m0_tick_irqn(), 0xFF); /* RTOS requires lowest priority */ NVIC_EnableIRQ(mbed_get_m0_tick_irqn()); #else // Ensure SysTick has the correct priority as it is still used // to trigger software interrupts on each tick. The period does // not matter since it will never start counting. OS_Tick_Setup(osRtxConfig.tick_freq, OS_TICK_HANDLER); #endif } void SysTimer::suspend(uint32_t ticks) { core_util_critical_section_enter(); remove(); schedule_tick(ticks); _suspend_time_passed = false; _suspended = true; core_util_critical_section_exit(); } bool SysTimer::suspend_time_passed() { return _suspend_time_passed; } uint32_t SysTimer::resume() { core_util_critical_section_enter(); _suspended = false; _suspend_time_passed = true; remove(); uint64_t new_tick = (ticker_read_us(_ticker_data) - _start_time) * OS_TICK_FREQ / 1000000; if (new_tick > _tick) { // Don't update to the current tick. Instead, update to the // previous tick and let the SysTick handler increment it // to the current value. This allows scheduling restart // successfully after the OS is resumed. new_tick--; } uint32_t elapsed_ticks = new_tick - _tick; _tick = new_tick; core_util_critical_section_exit(); return elapsed_ticks; } void SysTimer::schedule_tick(uint32_t delta) { core_util_critical_section_enter(); insert_absolute(_start_time + (_tick + delta) * 1000000ULL / OS_TICK_FREQ); core_util_critical_section_exit(); } void SysTimer::cancel_tick() { core_util_critical_section_enter(); remove(); core_util_critical_section_exit(); } uint32_t SysTimer::get_tick() { return _tick & 0xFFFFFFFF; } us_timestamp_t SysTimer::get_time() { return ticker_read_us(_ticker_data); } SysTimer::~SysTimer() { } void SysTimer::_set_irq_pending() { // Protected function synchronized externally #if (defined(NO_SYSTICK)) NVIC_SetPendingIRQ(mbed_get_m0_tick_irqn()); #else SCB->ICSR = SCB_ICSR_PENDSTSET_Msk; #endif } void SysTimer::_increment_tick() { // Protected function synchronized externally _tick++; } void SysTimer::handler() { core_util_critical_section_enter(); if (_suspended) { _suspend_time_passed = true; } else { _set_irq_pending(); _increment_tick(); } core_util_critical_section_exit(); } } } #endif
Fix possible bug with SysTimer
Fix possible bug with SysTimer Ensure the SysTimer isn't added to the timer list twice by adding an extra call to remove() inside suspend().
C++
apache-2.0
mbedmicro/mbed,betzw/mbed-os,andcor02/mbed-os,betzw/mbed-os,mbedmicro/mbed,kjbracey-arm/mbed,mbedmicro/mbed,betzw/mbed-os,andcor02/mbed-os,c1728p9/mbed-os,c1728p9/mbed-os,kjbracey-arm/mbed,mbedmicro/mbed,c1728p9/mbed-os,c1728p9/mbed-os,andcor02/mbed-os,betzw/mbed-os,c1728p9/mbed-os,betzw/mbed-os,kjbracey-arm/mbed,mbedmicro/mbed,andcor02/mbed-os,kjbracey-arm/mbed,c1728p9/mbed-os,betzw/mbed-os,andcor02/mbed-os,andcor02/mbed-os
c27fe5fdce940ec249dd6df7880961373fdebafc
core/imt/inc/ROOT/TExecutor.hxx
core/imt/inc/ROOT/TExecutor.hxx
// @(#)root/thread:$Id$ // Author: Xavier Valls September 2020 /************************************************************************* * Copyright (C) 1995-2006, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT_TExecutor #define ROOT_TExecutor #include <ROOT/RMakeUnique.hxx> #include "ROOT/TExecutorCRTP.hxx" #include "ROOT/TSequentialExecutor.hxx" #ifdef R__USE_IMT #include "ROOT/TThreadExecutor.hxx" #endif #include "ROOT/TProcessExecutor.hxx" #include "TROOT.h" #include "ExecutionPolicy.hxx" #include <memory> #include <stdexcept> #include <thread> namespace ROOT{ namespace Internal{ class TExecutor: public TExecutorCRTP<TExecutor> { public: explicit TExecutor(unsigned nProcessingUnits = 0) : TExecutor(ROOT::IsImplicitMTEnabled() ? ROOT::Internal::ExecutionPolicy::kMultithread : ROOT::Internal::ExecutionPolicy::kSerial, nProcessingUnits) {} explicit TExecutor(ROOT::Internal::ExecutionPolicy execPolicy, unsigned nProcessingUnits = 0) : fExecPolicy(execPolicy) { fExecPolicy = execPolicy; switch(fExecPolicy) { case ROOT::Internal::ExecutionPolicy::kSerial: fSeqPool = std::make_unique<ROOT::TSequentialExecutor>(); break; #ifdef R__USE_IMT case ROOT::Internal::ExecutionPolicy::kMultithread: fThreadPool = std::make_unique<ROOT::TThreadExecutor>(nProcessingUnits); break; #endif case ROOT::Internal::ExecutionPolicy::kMultiprocess: fProcPool = std::make_unique<ROOT::TProcessExecutor>(nProcessingUnits); break; default: throw std::invalid_argument("kMultithread policy not available when ROOT is compiled without imt."); } } TExecutor(TExecutor &) = delete; TExecutor &operator=(TExecutor &) = delete; ROOT::Internal::ExecutionPolicy Policy(){ return fExecPolicy; } using TExecutorCRTP<TExecutor>::Map; template<class F, class Cond = noReferenceCond<F>> auto Map(F func, unsigned nTimes) -> std::vector<typename std::result_of<F()>::type>; template<class F, class INTEGER, class Cond = noReferenceCond<F, INTEGER>> auto Map(F func, ROOT::TSeq<INTEGER> args) -> std::vector<typename std::result_of<F(INTEGER)>::type>; template<class F, class T, class Cond = noReferenceCond<F, T>> auto Map(F func, std::vector<T> &args) -> std::vector<typename std::result_of<F(T)>::type>; // // MapReduce // // the late return types also check at compile-time whether redfunc is compatible with func, // // other than checking that func is compatible with the type of arguments. // // a static_assert check in TExecutor::Reduce is used to check that redfunc is compatible with the type returned by func using TExecutorCRTP<TExecutor>::MapReduce; template<class F, class R, class Cond = noReferenceCond<F>> auto MapReduce(F func, unsigned nTimes, R redfunc) -> typename std::result_of<F()>::type; template<class F, class R, class Cond = noReferenceCond<F>> auto MapReduce(F func, unsigned nTimes, R redfunc, unsigned nChunks) -> typename std::result_of<F()>::type; template<class F, class INTEGER, class R, class Cond = noReferenceCond<F, INTEGER>> auto MapReduce(F func, ROOT::TSeq<INTEGER> args, R redfunc, unsigned nChunks) -> typename std::result_of<F(INTEGER)>::type; /// \cond template<class F, class T, class R, class Cond = noReferenceCond<F, T>> auto MapReduce(F func, std::initializer_list<T> args, R redfunc, unsigned nChunks) -> typename std::result_of<F(T)>::type; /// \endcond template<class F, class T, class R, class Cond = noReferenceCond<F, T>> auto MapReduce(F func, std::vector<T> &args, R redfunc) -> typename std::result_of<F(T)>::type; template<class F, class T, class R, class Cond = noReferenceCond<F, T>> auto MapReduce(F func, std::vector<T> &args, R redfunc, unsigned nChunks) -> typename std::result_of<F(T)>::type; using TExecutorCRTP<TExecutor>::Reduce; template<class T, class R> auto Reduce(const std::vector<T> &objs, R redfunc) -> decltype(redfunc(objs)); protected: template<class F, class R, class Cond = noReferenceCond<F>> auto Map(F func, unsigned nTimes, R redfunc, unsigned nChunks) -> std::vector<typename std::result_of<F()>::type>; template<class F, class INTEGER, class R, class Cond = noReferenceCond<F, INTEGER>> auto Map(F func, ROOT::TSeq<INTEGER> args, R redfunc, unsigned nChunks) -> std::vector<typename std::result_of<F(INTEGER)>::type>; template<class F, class T, class R, class Cond = noReferenceCond<F, T>> auto Map(F func, std::vector<T> &args, R redfunc, unsigned nChunks) -> std::vector<typename std::result_of<F(T)>::type>; template<class F, class T, class R, class Cond = noReferenceCond<F, T>> auto Map(F func, std::initializer_list<T> args, R redfunc, unsigned nChunks) -> std::vector<typename std::result_of<F(T)>::type>; private: ROOT::Internal::ExecutionPolicy fExecPolicy; #ifdef R__USE_IMT std::unique_ptr<ROOT::TThreadExecutor> fThreadPool; #endif std::unique_ptr<ROOT::TProcessExecutor> fProcPool; std::unique_ptr<ROOT::TSequentialExecutor> fSeqPool; }; ////////////////////////////////////////////////////////////////////////// /// Execute func (with no arguments) nTimes in parallel. /// A vector containg executions' results is returned. /// Functions that take more than zero arguments can be executed (with /// fixed arguments) by wrapping them in a lambda or with std::bind. template<class F, class Cond> auto TExecutor::Map(F func, unsigned nTimes) -> std::vector<typename std::result_of<F()>::type> { using retType = decltype(func()); std::vector<retType> res;; switch(fExecPolicy){ case ROOT::Internal::ExecutionPolicy::kSerial: res = fSeqPool->Map(func, nTimes); break; #ifdef R__USE_IMT case ROOT::Internal::ExecutionPolicy::kMultithread: res = fThreadPool->Map(func, nTimes); break; #endif case ROOT::Internal::ExecutionPolicy::kMultiprocess: res = fProcPool->Map(func, nTimes); break; default: break; } return res; } ////////////////////////////////////////////////////////////////////////// /// Execute func in parallel, taking an element of a /// sequence as argument. /// A vector containg executions' results is returned. template<class F, class INTEGER, class Cond> auto TExecutor::Map(F func, ROOT::TSeq<INTEGER> args) -> std::vector<typename std::result_of<F(INTEGER)>::type> { using retType = decltype(func(args.front())); std::vector<retType> res; switch(fExecPolicy){ case ROOT::Internal::ExecutionPolicy::kSerial: res = fSeqPool->Map(func, args); break; #ifdef R__USE_IMT case ROOT::Internal::ExecutionPolicy::kMultithread: res = fThreadPool->Map(func, args); break; #endif case ROOT::Internal::ExecutionPolicy::kMultiprocess: res = fProcPool->Map(func, args); break; default: break; } return res; } ////////////////////////////////////////////////////////////////////////// /// Execute func (with no arguments) nTimes in parallel. /// Divides and groups the executions in nChunks (if it doesn't make sense will reduce the number of chunks) with partial reduction; /// A vector containg partial reductions' results is returned. template<class F, class R, class Cond> auto TExecutor::Map(F func, unsigned nTimes, R redfunc, unsigned nChunks) -> std::vector<typename std::result_of<F()>::type> { using retType = decltype(func()); std::vector<retType> res;; switch(fExecPolicy){ case ROOT::Internal::ExecutionPolicy::kSerial: res = fSeqPool->Map(func, nTimes, redfunc, 1); break; #ifdef R__USE_IMT case ROOT::Internal::ExecutionPolicy::kMultithread: res = fThreadPool->Map(func, nTimes, redfunc, nChunks); break; #endif case ROOT::Internal::ExecutionPolicy::kMultiprocess: res = fProcPool->Map(func, nTimes, redfunc, nChunks); break; default: break; } return res; } ////////////////////////////////////////////////////////////////////////// /// Execute func in parallel, taking an element of an /// std::vector as argument. /// A vector containg executions' results is returned. // actual implementation of the Map method. all other calls with arguments eventually // call this one template<class F, class T, class Cond> auto TExecutor::Map(F func, std::vector<T> &args) -> std::vector<typename std::result_of<F(T)>::type> { // //check whether func is callable using retType = decltype(func(args.front())); std::vector<retType> res;; switch(fExecPolicy){ case ROOT::Internal::ExecutionPolicy::kSerial: res = fSeqPool->Map(func, args); break; #ifdef R__USE_IMT case ROOT::Internal::ExecutionPolicy::kMultithread: res = fThreadPool->Map(func, args); break; #endif case ROOT::Internal::ExecutionPolicy::kMultiprocess: res = fProcPool->Map(func, args); break; default: break; } return res; } ////////////////////////////////////////////////////////////////////////// /// Execute func in parallel, taking an element of a /// sequence as argument. /// Divides and groups the executions in nChunks (if it doesn't make sense will reduce the number of chunks) with partial reduction\n /// A vector containg partial reductions' results is returned. template<class F, class INTEGER, class R, class Cond> auto TExecutor::Map(F func, ROOT::TSeq<INTEGER> args, R redfunc, unsigned nChunks) -> std::vector<typename std::result_of<F(INTEGER)>::type> { using retType = decltype(func(args.front())); std::vector<retType> res;; switch(fExecPolicy){ case ROOT::Internal::ExecutionPolicy::kSerial: res = fSeqPool->Map(func, args, redfunc, 1); break; #ifdef R__USE_IMT case ROOT::Internal::ExecutionPolicy::kMultithread: res = fThreadPool->Map(func, args, redfunc, nChunks); break; #endif case ROOT::Internal::ExecutionPolicy::kMultiprocess: res = fProcPool->Map(func, args, redfunc, nChunks); break; default: break; } return res; } /// \cond ////////////////////////////////////////////////////////////////////////// /// Execute func in parallel, taking an element of an /// std::vector as argument. Divides and groups the executions in nChunks with partial reduction. /// If it doesn't make sense will reduce the number of chunks.\n /// A vector containg partial reductions' results is returned. template<class F, class T, class R, class Cond> auto TExecutor::Map(F func, std::vector<T> &args, R redfunc, unsigned nChunks) -> std::vector<typename std::result_of<F(T)>::type> { using retType = decltype(func(args.front())); std::vector<retType> res;; switch(fExecPolicy){ case ROOT::Internal::ExecutionPolicy::kSerial: res = fSeqPool->Map(func, args, redfunc, 1); break; #ifdef R__USE_IMT case ROOT::Internal::ExecutionPolicy::kMultithread: res = fThreadPool->Map(func, args, redfunc, nChunks); break; #endif case ROOT::Internal::ExecutionPolicy::kMultiprocess: res = fProcPool->Map(func, args, redfunc, nChunks); break; default: break; } return res; } ////////////////////////////////////////////////////////////////////////// /// Execute func in parallel, taking an element of an /// std::initializer_list as an argument. Divides and groups the executions in nChunks with partial reduction. /// If it doesn't make sense will reduce the number of chunks.\n /// A vector containg partial reductions' results is returned. template<class F, class T, class R, class Cond> auto TExecutor::Map(F func, std::initializer_list<T> args, R redfunc, unsigned nChunks) -> std::vector<typename std::result_of<F(T)>::type> { std::vector<T> vargs(std::move(args)); const auto &reslist = Map(func, vargs, redfunc, nChunks); return reslist; } /// \endcond ////////////////////////////////////////////////////////////////////////// /// This method behaves just like Map, but an additional redfunc function /// must be provided. redfunc is applied to the vector Map would return and /// must return the same type as func. In practice, redfunc can be used to /// "squash" the vector returned by Map into a single object by merging, /// adding, mixing the elements of the vector.\n /// The fourth argument indicates the number of chunks we want to divide our work in. template<class F, class R, class Cond> auto TExecutor::MapReduce(F func, unsigned nTimes, R redfunc) -> typename std::result_of<F()>::type { return Reduce(Map(func, nTimes), redfunc); } template<class F, class R, class Cond> auto TExecutor::MapReduce(F func, unsigned nTimes, R redfunc, unsigned nChunks) -> typename std::result_of<F()>::type { return Reduce(Map(func, nTimes, redfunc, nChunks), redfunc); } template<class F, class INTEGER, class R, class Cond> auto TExecutor::MapReduce(F func, ROOT::TSeq<INTEGER> args, R redfunc, unsigned nChunks) -> typename std::result_of<F(INTEGER)>::type { return Reduce(Map(func, args, redfunc, nChunks), redfunc); } /// \cond template<class F, class T, class R, class Cond> auto TExecutor::MapReduce(F func, std::initializer_list<T> args, R redfunc, unsigned nChunks) -> typename std::result_of<F(T)>::type { return Reduce(Map(func, args, redfunc, nChunks), redfunc); } /// \endcond template<class F, class T, class R, class Cond> auto TExecutor::MapReduce(F func, std::vector<T> &args, R redfunc) -> typename std::result_of<F(T)>::type { return Reduce(Map(func, args), redfunc); } template<class F, class T, class R, class Cond> auto TExecutor::MapReduce(F func, std::vector<T> &args, R redfunc, unsigned nChunks) -> typename std::result_of<F(T)>::type { return Reduce(Map(func, args, redfunc, nChunks), redfunc); } ////////////////////////////////////////////////////////////////////////// /// "Reduce" an std::vector into a single object by passing a /// function as the second argument defining the reduction operation. template<class T, class R> auto TExecutor::Reduce(const std::vector<T> &objs, R redfunc) -> decltype(redfunc(objs)) { // check we can apply reduce to objs static_assert(std::is_same<decltype(redfunc(objs)), T>::value, "redfunc does not have the correct signature"); return redfunc(objs); } } } #endif
// @(#)root/thread:$Id$ // Author: Xavier Valls September 2020 /************************************************************************* * Copyright (C) 1995-2006, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT_TExecutor #define ROOT_TExecutor #include <ROOT/RMakeUnique.hxx> #include "ROOT/TExecutorCRTP.hxx" #include "ROOT/TSequentialExecutor.hxx" #ifdef R__USE_IMT #include "ROOT/TThreadExecutor.hxx" #endif #include "ROOT/TProcessExecutor.hxx" #include "TROOT.h" #include "ExecutionPolicy.hxx" #include <memory> #include <stdexcept> #include <thread> namespace ROOT{ namespace Internal{ class TExecutor: public TExecutorCRTP<TExecutor> { public: explicit TExecutor(unsigned nProcessingUnits = 0) : TExecutor(ROOT::IsImplicitMTEnabled() ? ROOT::Internal::ExecutionPolicy::kMultithread : ROOT::Internal::ExecutionPolicy::kSerial, nProcessingUnits) {} explicit TExecutor(ROOT::Internal::ExecutionPolicy execPolicy, unsigned nProcessingUnits = 0) : fExecPolicy(execPolicy) { fExecPolicy = execPolicy; switch(fExecPolicy) { case ROOT::Internal::ExecutionPolicy::kSerial: fSeqPool = std::make_unique<ROOT::TSequentialExecutor>(); break; #ifdef R__USE_IMT case ROOT::Internal::ExecutionPolicy::kMultithread: fThreadPool = std::make_unique<ROOT::TThreadExecutor>(nProcessingUnits); break; #endif case ROOT::Internal::ExecutionPolicy::kMultiprocess: fProcPool = std::make_unique<ROOT::TProcessExecutor>(nProcessingUnits); break; default: throw std::invalid_argument("kMultithread policy not available when ROOT is compiled without imt."); } } TExecutor(TExecutor &) = delete; TExecutor &operator=(TExecutor &) = delete; ROOT::Internal::ExecutionPolicy Policy(){ return fExecPolicy; } using TExecutorCRTP<TExecutor>::Map; template<class F, class Cond = noReferenceCond<F>> auto Map(F func, unsigned nTimes) -> std::vector<typename std::result_of<F()>::type>; template<class F, class INTEGER, class Cond = noReferenceCond<F, INTEGER>> auto Map(F func, ROOT::TSeq<INTEGER> args) -> std::vector<typename std::result_of<F(INTEGER)>::type>; template<class F, class T, class Cond = noReferenceCond<F, T>> auto Map(F func, std::vector<T> &args) -> std::vector<typename std::result_of<F(T)>::type>; // // MapReduce // // the late return types also check at compile-time whether redfunc is compatible with func, // // other than checking that func is compatible with the type of arguments. // // a static_assert check in TExecutor::Reduce is used to check that redfunc is compatible with the type returned by func using TExecutorCRTP<TExecutor>::MapReduce; template<class F, class R, class Cond = noReferenceCond<F>> auto MapReduce(F func, unsigned nTimes, R redfunc) -> typename std::result_of<F()>::type; template<class F, class R, class Cond = noReferenceCond<F>> auto MapReduce(F func, unsigned nTimes, R redfunc, unsigned nChunks) -> typename std::result_of<F()>::type; template<class F, class INTEGER, class R, class Cond = noReferenceCond<F, INTEGER>> auto MapReduce(F func, ROOT::TSeq<INTEGER> args, R redfunc, unsigned nChunks) -> typename std::result_of<F(INTEGER)>::type; /// \cond template<class F, class T, class R, class Cond = noReferenceCond<F, T>> auto MapReduce(F func, std::initializer_list<T> args, R redfunc, unsigned nChunks) -> typename std::result_of<F(T)>::type; /// \endcond template<class F, class T, class R, class Cond = noReferenceCond<F, T>> auto MapReduce(F func, std::vector<T> &args, R redfunc) -> typename std::result_of<F(T)>::type; template<class F, class T, class R, class Cond = noReferenceCond<F, T>> auto MapReduce(F func, std::vector<T> &args, R redfunc, unsigned nChunks) -> typename std::result_of<F(T)>::type; using TExecutorCRTP<TExecutor>::Reduce; template<class T, class R> auto Reduce(const std::vector<T> &objs, R redfunc) -> decltype(redfunc(objs)); protected: template<class F, class R, class Cond = noReferenceCond<F>> auto Map(F func, unsigned nTimes, R redfunc, unsigned nChunks) -> std::vector<typename std::result_of<F()>::type>; template<class F, class INTEGER, class R, class Cond = noReferenceCond<F, INTEGER>> auto Map(F func, ROOT::TSeq<INTEGER> args, R redfunc, unsigned nChunks) -> std::vector<typename std::result_of<F(INTEGER)>::type>; template<class F, class T, class R, class Cond = noReferenceCond<F, T>> auto Map(F func, std::vector<T> &args, R redfunc, unsigned nChunks) -> std::vector<typename std::result_of<F(T)>::type>; template<class F, class T, class R, class Cond = noReferenceCond<F, T>> auto Map(F func, std::initializer_list<T> args, R redfunc, unsigned nChunks) -> std::vector<typename std::result_of<F(T)>::type>; private: ROOT::Internal::ExecutionPolicy fExecPolicy; #ifdef R__USE_IMT std::unique_ptr<ROOT::TThreadExecutor> fThreadPool; #endif std::unique_ptr<ROOT::TProcessExecutor> fProcPool; std::unique_ptr<ROOT::TSequentialExecutor> fSeqPool; }; ////////////////////////////////////////////////////////////////////////// /// Execute func (with no arguments) nTimes in parallel. /// A vector containg executions' results is returned. /// Functions that take more than zero arguments can be executed (with /// fixed arguments) by wrapping them in a lambda or with std::bind. template<class F, class Cond> auto TExecutor::Map(F func, unsigned nTimes) -> std::vector<typename std::result_of<F()>::type> { using retType = decltype(func()); std::vector<retType> res; switch(fExecPolicy){ case ROOT::Internal::ExecutionPolicy::kSerial: res = fSeqPool->Map(func, nTimes); break; #ifdef R__USE_IMT case ROOT::Internal::ExecutionPolicy::kMultithread: res = fThreadPool->Map(func, nTimes); break; #endif case ROOT::Internal::ExecutionPolicy::kMultiprocess: res = fProcPool->Map(func, nTimes); break; default: break; } return res; } ////////////////////////////////////////////////////////////////////////// /// Execute func in parallel, taking an element of a /// sequence as argument. /// A vector containg executions' results is returned. template<class F, class INTEGER, class Cond> auto TExecutor::Map(F func, ROOT::TSeq<INTEGER> args) -> std::vector<typename std::result_of<F(INTEGER)>::type> { using retType = decltype(func(args.front())); std::vector<retType> res; switch(fExecPolicy){ case ROOT::Internal::ExecutionPolicy::kSerial: res = fSeqPool->Map(func, args); break; #ifdef R__USE_IMT case ROOT::Internal::ExecutionPolicy::kMultithread: res = fThreadPool->Map(func, args); break; #endif case ROOT::Internal::ExecutionPolicy::kMultiprocess: res = fProcPool->Map(func, args); break; default: break; } return res; } ////////////////////////////////////////////////////////////////////////// /// Execute func (with no arguments) nTimes in parallel. /// Divides and groups the executions in nChunks (if it doesn't make sense will reduce the number of chunks) with partial reduction; /// A vector containg partial reductions' results is returned. template<class F, class R, class Cond> auto TExecutor::Map(F func, unsigned nTimes, R redfunc, unsigned nChunks) -> std::vector<typename std::result_of<F()>::type> { using retType = decltype(func()); std::vector<retType> res;; switch(fExecPolicy){ case ROOT::Internal::ExecutionPolicy::kSerial: (void) nChunks; res = fSeqPool->Map(func, nTimes, redfunc); break; #ifdef R__USE_IMT case ROOT::Internal::ExecutionPolicy::kMultithread: res = fThreadPool->Map(func, nTimes, redfunc, nChunks); break; #endif case ROOT::Internal::ExecutionPolicy::kMultiprocess: res = fProcPool->Map(func, nTimes, redfunc, nChunks); break; default: break; } return res; } ////////////////////////////////////////////////////////////////////////// /// Execute func in parallel, taking an element of an /// std::vector as argument. /// A vector containg executions' results is returned. // actual implementation of the Map method. all other calls with arguments eventually // call this one template<class F, class T, class Cond> auto TExecutor::Map(F func, std::vector<T> &args) -> std::vector<typename std::result_of<F(T)>::type> { // //check whether func is callable using retType = decltype(func(args.front())); std::vector<retType> res;; switch(fExecPolicy){ case ROOT::Internal::ExecutionPolicy::kSerial: res = fSeqPool->Map(func, args); break; #ifdef R__USE_IMT case ROOT::Internal::ExecutionPolicy::kMultithread: res = fThreadPool->Map(func, args); break; #endif case ROOT::Internal::ExecutionPolicy::kMultiprocess: res = fProcPool->Map(func, args); break; default: break; } return res; } ////////////////////////////////////////////////////////////////////////// /// Execute func in parallel, taking an element of a /// sequence as argument. /// Divides and groups the executions in nChunks (if it doesn't make sense will reduce the number of chunks) with partial reduction\n /// A vector containg partial reductions' results is returned. template<class F, class INTEGER, class R, class Cond> auto TExecutor::Map(F func, ROOT::TSeq<INTEGER> args, R redfunc, unsigned nChunks) -> std::vector<typename std::result_of<F(INTEGER)>::type> { using retType = decltype(func(args.front())); std::vector<retType> res;; switch(fExecPolicy){ case ROOT::Internal::ExecutionPolicy::kSerial: (void) nChunks; res = fSeqPool->Map(func, args, redfunc); break; #ifdef R__USE_IMT case ROOT::Internal::ExecutionPolicy::kMultithread: res = fThreadPool->Map(func, args, redfunc, nChunks); break; #endif case ROOT::Internal::ExecutionPolicy::kMultiprocess: res = fProcPool->Map(func, args, redfunc, nChunks); break; default: break; } return res; } /// \cond ////////////////////////////////////////////////////////////////////////// /// Execute func in parallel, taking an element of an /// std::vector as argument. Divides and groups the executions in nChunks with partial reduction. /// If it doesn't make sense will reduce the number of chunks.\n /// A vector containg partial reductions' results is returned. template<class F, class T, class R, class Cond> auto TExecutor::Map(F func, std::vector<T> &args, R redfunc, unsigned nChunks) -> std::vector<typename std::result_of<F(T)>::type> { using retType = decltype(func(args.front())); std::vector<retType> res;; switch(fExecPolicy){ case ROOT::Internal::ExecutionPolicy::kSerial: (void) nChunks; res = fSeqPool->Map(func, args, redfunc); break; #ifdef R__USE_IMT case ROOT::Internal::ExecutionPolicy::kMultithread: res = fThreadPool->Map(func, args, redfunc, nChunks); break; #endif case ROOT::Internal::ExecutionPolicy::kMultiprocess: res = fProcPool->Map(func, args, redfunc, nChunks); break; default: break; } return res; } ////////////////////////////////////////////////////////////////////////// /// Execute func in parallel, taking an element of an /// std::initializer_list as an argument. Divides and groups the executions in nChunks with partial reduction. /// If it doesn't make sense will reduce the number of chunks.\n /// A vector containg partial reductions' results is returned. template<class F, class T, class R, class Cond> auto TExecutor::Map(F func, std::initializer_list<T> args, R redfunc, unsigned nChunks) -> std::vector<typename std::result_of<F(T)>::type> { std::vector<T> vargs(std::move(args)); const auto &reslist = Map(func, vargs, redfunc, nChunks); return reslist; } /// \endcond ////////////////////////////////////////////////////////////////////////// /// This method behaves just like Map, but an additional redfunc function /// must be provided. redfunc is applied to the vector Map would return and /// must return the same type as func. In practice, redfunc can be used to /// "squash" the vector returned by Map into a single object by merging, /// adding, mixing the elements of the vector.\n /// The fourth argument indicates the number of chunks we want to divide our work in. template<class F, class R, class Cond> auto TExecutor::MapReduce(F func, unsigned nTimes, R redfunc) -> typename std::result_of<F()>::type { return Reduce(Map(func, nTimes), redfunc); } template<class F, class R, class Cond> auto TExecutor::MapReduce(F func, unsigned nTimes, R redfunc, unsigned nChunks) -> typename std::result_of<F()>::type { return Reduce(Map(func, nTimes, redfunc, nChunks), redfunc); } template<class F, class INTEGER, class R, class Cond> auto TExecutor::MapReduce(F func, ROOT::TSeq<INTEGER> args, R redfunc, unsigned nChunks) -> typename std::result_of<F(INTEGER)>::type { return Reduce(Map(func, args, redfunc, nChunks), redfunc); } /// \cond template<class F, class T, class R, class Cond> auto TExecutor::MapReduce(F func, std::initializer_list<T> args, R redfunc, unsigned nChunks) -> typename std::result_of<F(T)>::type { return Reduce(Map(func, args, redfunc, nChunks), redfunc); } /// \endcond template<class F, class T, class R, class Cond> auto TExecutor::MapReduce(F func, std::vector<T> &args, R redfunc) -> typename std::result_of<F(T)>::type { return Reduce(Map(func, args), redfunc); } template<class F, class T, class R, class Cond> auto TExecutor::MapReduce(F func, std::vector<T> &args, R redfunc, unsigned nChunks) -> typename std::result_of<F(T)>::type { return Reduce(Map(func, args, redfunc, nChunks), redfunc); } ////////////////////////////////////////////////////////////////////////// /// "Reduce" an std::vector into a single object by passing a /// function as the second argument defining the reduction operation. template<class T, class R> auto TExecutor::Reduce(const std::vector<T> &objs, R redfunc) -> decltype(redfunc(objs)) { // check we can apply reduce to objs static_assert(std::is_same<decltype(redfunc(objs)), T>::value, "redfunc does not have the correct signature"); return redfunc(objs); } } } #endif
fix parameters for TSequentialExecutor
fix parameters for TSequentialExecutor Avoid unused variable warnings
C++
lgpl-2.1
root-mirror/root,root-mirror/root,olifre/root,root-mirror/root,olifre/root,olifre/root,root-mirror/root,olifre/root,root-mirror/root,olifre/root,root-mirror/root,olifre/root,olifre/root,olifre/root,olifre/root,olifre/root,root-mirror/root,root-mirror/root,olifre/root,root-mirror/root,root-mirror/root,root-mirror/root
56d6070c6e9f8135479e7d96d9198e1ee1105dab
RPC/ProtoBuf.cc
RPC/ProtoBuf.cc
/* Copyright (c) 2012 Stanford University * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <string> #include "include/Debug.h" #include "include/ProtoBuf.h" #include "RPC/ProtoBuf.h" namespace LogCabin { namespace RPC { /** * Utilities for dealing with protocol buffers in RPCs. */ namespace ProtoBuf { namespace { /// Remove the last character from the end of a string. std::string truncateEnd(std::string str) { str.resize(str.length() - 1); return str; } } // anonymous namespace bool parse(const RPC::Buffer& from, google::protobuf::Message& to, uint32_t skipBytes) { if (!to.ParseFromArray( static_cast<const char*>(from.getData()) + skipBytes, from.getLength() - skipBytes)) { LOG(WARNING, "Missing fields in protocol buffer: %s", to.InitializationErrorString().c_str()); return false; } LOG(DBG, "%s:\n%s", to.GetTypeName().c_str(), truncateEnd(DLog::ProtoBuf::dumpString(to)).c_str()); return true; } void serialize(const google::protobuf::Message& from, RPC::Buffer& to, uint32_t skipBytes) { // SerializeToArray seems to always return true, so we explicitly check // IsInitialized to make sure all required fields are set. if (!from.IsInitialized()) { PANIC("Missing fields in protocol buffer of type %s: %s", from.GetTypeName().c_str(), from.InitializationErrorString().c_str()); } uint32_t length = from.ByteSize(); char* data = new char[skipBytes + length]; from.SerializeToArray(data + skipBytes, length); to.setData(data, skipBytes + length, RPC::Buffer::deleteArrayFn<char>); } } // namespace LogCabin::RPC::ProtoBuf } // namespace LogCabin::RPC } // namespace LogCabin
/* Copyright (c) 2012 Stanford University * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <string> #include "include/Debug.h" #include "include/ProtoBuf.h" #include "RPC/ProtoBuf.h" namespace LogCabin { namespace RPC { /** * Utilities for dealing with protocol buffers in RPCs. */ namespace ProtoBuf { namespace { /// Remove the last character from the end of a string. std::string truncateEnd(std::string str) { if (!str.empty()) str.resize(str.length() - 1, 0); return str; } } // anonymous namespace bool parse(const RPC::Buffer& from, google::protobuf::Message& to, uint32_t skipBytes) { if (!to.ParseFromArray( static_cast<const char*>(from.getData()) + skipBytes, from.getLength() - skipBytes)) { LOG(WARNING, "Missing fields in protocol buffer: %s", to.InitializationErrorString().c_str()); return false; } LOG(DBG, "%s:\n%s", to.GetTypeName().c_str(), truncateEnd(DLog::ProtoBuf::dumpString(to)).c_str()); return true; } void serialize(const google::protobuf::Message& from, RPC::Buffer& to, uint32_t skipBytes) { // SerializeToArray seems to always return true, so we explicitly check // IsInitialized to make sure all required fields are set. if (!from.IsInitialized()) { PANIC("Missing fields in protocol buffer of type %s: %s", from.GetTypeName().c_str(), from.InitializationErrorString().c_str()); } uint32_t length = from.ByteSize(); char* data = new char[skipBytes + length]; from.SerializeToArray(data + skipBytes, length); to.setData(data, skipBytes + length, RPC::Buffer::deleteArrayFn<char>); } } // namespace LogCabin::RPC::ProtoBuf } // namespace LogCabin::RPC } // namespace LogCabin
Fix bug in printing log message
Fix bug in printing log message
C++
isc
dankenigsberg/logcabin,nhardt/logcabin,jimpelton/mingle-logcabin,dankenigsberg/logcabin,logcabin/logcabin,TigerZhang/logcabin,gaoning777/logcabin,logcabin/logcabin,chaozh/logcabin,logcabin/logcabin,jimpelton/mingle-logcabin,gaoning777/logcabin,gaoning777/logcabin,chaozh/logcabin,logcabin/logcabin,jimpelton/mingle-logcabin,nhardt/logcabin,chaozh/logcabin,TigerZhang/logcabin,gaoning777/logcabin,TigerZhang/logcabin,tempbottle/logcabin,tempbottle/logcabin,dankenigsberg/logcabin,dankenigsberg/logcabin,tempbottle/logcabin,chaozh/logcabin,TigerZhang/logcabin,nhardt/logcabin,tempbottle/logcabin,nhardt/logcabin
9ec9a903a37be323d53d05de21f9fa105e24ee1c
cpp/Tests/TestsTensorConfig.cpp
cpp/Tests/TestsTensorConfig.cpp
#include "catch.hpp" #include <cmath> #include <cstdio> #include <iostream> #include <sstream> #include <vector> #include <SmurffCpp/Types.h> #include <SmurffCpp/Types.h> #include <SmurffCpp/Utils/MatrixUtils.h> #include <SmurffCpp/Utils/TensorUtils.h> #include <SmurffCpp/Configs/TensorConfig.h> namespace smurff { static NoiseConfig fixed_ncfg(NoiseTypes::fixed); TEST_CASE("TensorConfig(const std::vector<std::uint64_t>& dims, const std::vector<double> values, const NoiseConfig& noiseConfig)") { std::vector<std::uint64_t> tensorConfigDims = { 3, 4 }; std::vector<double> tensorConfigValues = { 1, 5, 9, 2, 6, 10, 3, 7, 11, 4, 8, 12 }; TensorConfig tensorConfig(tensorConfigDims, tensorConfigValues.data(), fixed_ncfg); Matrix actualMatrix = matrix_utils::dense_to_eigen(tensorConfig); Matrix expectedMatrix(3, 4); expectedMatrix << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12; REQUIRE(matrix_utils::equals(actualMatrix, expectedMatrix)); } TEST_CASE("TensorConfig(const std::vector<std::uint64_t>& dims, const std::vector<std::vector<std::uint32_t>>& columns, const std::vector<double>& values, const NoiseConfig& noiseConfig)") { std::vector<std::uint64_t> tensorConfigDims = { 3, 4 }; std::vector<std::vector<std::uint32_t>> tensorConfigColumns = { { 0, 0, 0, 0, 2, 2, 2, 2 }, { 0, 1, 2, 3, 0, 1, 2, 3 } }; std::vector<double> tensorConfigValues = { 1, 2, 3, 4, 9, 10, 11, 12 }; TensorConfig tensorConfig(tensorConfigDims, tensorConfigColumns, tensorConfigValues, fixed_ncfg, false); SparseMatrix actualMatrix = matrix_utils::sparse_to_eigen(tensorConfig); SparseMatrix expectedMatrix(3, 4); std::vector<Eigen::Triplet<double> > expectedMatrixTriplets; expectedMatrixTriplets.push_back(Eigen::Triplet<double>(0, 0, 1)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(0, 1, 2)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(0, 2, 3)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(0, 3, 4)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(2, 0, 9)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(2, 1, 10)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(2, 2, 11)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(2, 3, 12)); expectedMatrix.setFromTriplets(expectedMatrixTriplets.begin(), expectedMatrixTriplets.end()); REQUIRE(matrix_utils::equals(actualMatrix, expectedMatrix)); } TEST_CASE("TensorConfig(const std::vector<std::uint64_t>& dims, const std::vector<std::vector<std::uint32_t>>& columns, const NoiseConfig& noiseConfig)") { std::vector<std::uint64_t> tensorConfigDims = { 3, 4 }; std::vector<std::vector<std::uint32_t>> tensorConfigColumns = { { 0, 0, 0, 0, 2, 2, 2, 2 }, { 0, 1, 2, 3, 0, 1, 2, 3 } }; TensorConfig tensorConfig(tensorConfigDims, tensorConfigColumns, fixed_ncfg, false); SparseMatrix actualMatrix = matrix_utils::sparse_to_eigen(tensorConfig); SparseMatrix expectedMatrix(3, 4); std::vector<Eigen::Triplet<double> > expectedMatrixTriplets; expectedMatrixTriplets.push_back(Eigen::Triplet<double>(0, 0, 1)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(0, 1, 1)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(0, 2, 1)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(0, 3, 1)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(2, 0, 1)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(2, 1, 1)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(2, 2, 1)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(2, 3, 1)); expectedMatrix.setFromTriplets(expectedMatrixTriplets.begin(), expectedMatrixTriplets.end()); REQUIRE(matrix_utils::equals(actualMatrix, expectedMatrix)); } } // end namespace smurff
#include "catch.hpp" #include <cmath> #include <cstdio> #include <iostream> #include <sstream> #include <vector> #include <SmurffCpp/Types.h> #include <SmurffCpp/Types.h> #include <SmurffCpp/Utils/MatrixUtils.h> #include <SmurffCpp/Utils/TensorUtils.h> #include <Utils/Tensor.h> namespace smurff { TEST_CASE("DenseTensor(const std::vector<std::uint64_t>& dims, const std::vector<double> values)") { std::vector<std::uint64_t> tensorConfigDims = { 3, 4 }; std::vector<double> tensorConfigValues = { 1, 5, 9, 2, 6, 10, 3, 7, 11, 4, 8, 12 }; DenseTensor tensorConfig(tensorConfigDims, tensorConfigValues); Matrix actualMatrix = matrix_utils::dense_to_eigen(tensorConfig); Matrix expectedMatrix(3, 4); expectedMatrix << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12; REQUIRE(matrix_utils::equals(actualMatrix, expectedMatrix)); } TEST_CASE("SparseTensor(const std::vector<std::uint64_t>& dims, const std::vector<std::vector<std::uint32_t>>& columns, const std::vector<double>& values)") { std::vector<std::uint64_t> tensorConfigDims = { 3, 4 }; std::vector<std::vector<std::uint32_t>> tensorConfigColumns = { { 0, 0, 0, 0, 2, 2, 2, 2 }, { 0, 1, 2, 3, 0, 1, 2, 3 } }; std::vector<double> tensorConfigValues = { 1, 2, 3, 4, 9, 10, 11, 12 }; SparseTensor tensorConfig(tensorConfigDims, tensorConfigColumns, tensorConfigValues); SparseMatrix actualMatrix = matrix_utils::sparse_to_eigen(tensorConfig); SparseMatrix expectedMatrix(3, 4); std::vector<Eigen::Triplet<double> > expectedMatrixTriplets; expectedMatrixTriplets.push_back(Eigen::Triplet<double>(0, 0, 1)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(0, 1, 2)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(0, 2, 3)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(0, 3, 4)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(2, 0, 9)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(2, 1, 10)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(2, 2, 11)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(2, 3, 12)); expectedMatrix.setFromTriplets(expectedMatrixTriplets.begin(), expectedMatrixTriplets.end()); REQUIRE(matrix_utils::equals(actualMatrix, expectedMatrix)); } } // end namespace smurff
test DenseTensor and SparseTensor i.o. TensorConfig
WIP: test DenseTensor and SparseTensor i.o. TensorConfig
C++
mit
ExaScience/smurff,ExaScience/smurff,ExaScience/smurff,ExaScience/smurff,ExaScience/smurff,ExaScience/smurff
50172d19a17db4385d4e593176048e460e0b4c09
cpp/add_ub_sigil_to_articles.cc
cpp/add_ub_sigil_to_articles.cc
/** \file * \author Johannes Riedl * * New implementation to derive information for articles about being available in Tübingen * from superior works and augment LOK data appropriately */ /* Copyright (C) 2017, Library of the University of Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <iostream> #include <cstring> #include "Compiler.h" #include "FileUtil.h" #include "TextUtil.h" #include "MarcRecord.h" #include "RegexMatcher.h" #include "util.h" static unsigned extracted_count(0); static unsigned modified_count(0); static std::unordered_set<std::string> de21_superior_ppns; static const RegexMatcher * const tue_sigil_matcher(RegexMatcher::RegexMatcherFactory("^DE-21.*")); static const RegexMatcher * const superior_ppn_matcher(RegexMatcher::RegexMatcherFactory(".DE-576.(.*)")); void Usage() { std::cerr << "Usage: " << ::progname << " spr_augmented_marc_input marc_output\n"; std::cerr << " Adds DE-21 sigils, as appropriate, to article entries found in the\n"; std::cerr << " master_marc_input and writes this augmented file as marc_output.\n\n"; std::cerr << " Notice that this program requires the SPR tag for superior works\n"; std::cerr << " to be set for appropriate results"; std::exit(EXIT_FAILURE); } void ProcessSuperiorRecord(const MarcRecord &record) { // We are done if this is not a superior work if (record.getFieldData("SPR").empty()) return; std::vector<std::pair<size_t, size_t>> local_block_boundaries; ssize_t local_data_count = record.findAllLocalDataBlocks(&local_block_boundaries); if (local_data_count == 0) return; for (const auto &block_start_and_end : local_block_boundaries) { std::vector<size_t> field_indices; record.findFieldsInLocalBlock("852", "??", block_start_and_end, &field_indices); for (size_t field_index : field_indices) { const std::string field_data(record.getFieldData(field_index)); const Subfields subfields(field_data); std::string sigil; if (subfields.extractSubfieldWithPattern('a', *tue_sigil_matcher, &sigil)) { de21_superior_ppns.insert(record.getControlNumber()); ++extracted_count; } } } } void LoadDE21PPNs(MarcReader * const marc_reader) { while (const MarcRecord record = marc_reader->read()) ProcessSuperiorRecord(record); } void CollectSuperiorPPNs(const MarcRecord &record, std::unordered_set<std::string> * const superior_ppn_set) { // Determine superior PPNs from 800w:810w:830w:773w:776w const std::vector<std::string> tags({ "800", "810", "830", "773", "776" }); for (const auto &tag : tags) { std::vector<std::string> superior_ppn_vector; record.extractSubfields(tag , "w", &superior_ppn_vector); // Remove superfluous prefixes for (auto &superior_ppn : superior_ppn_vector) { std::string err_msg; if (not superior_ppn_matcher->matched(superior_ppn, &err_msg)) { if (not err_msg.empty()) Error("Error with regex für superior works " + err_msg); continue; } superior_ppn = (*superior_ppn_matcher)[1]; } std::copy(superior_ppn_vector.begin(), superior_ppn_vector.end(), std::inserter(*superior_ppn_set, superior_ppn_set->end())); } } void InsertDE21ToLOK852(MarcRecord * const record) { record->insertField("LOK", " ""\x1F""0852""\x1F""aDE-21"); ++modified_count; } bool AlreadyHasLOK852DE21(const MarcRecord &record) { std::vector<std::pair<size_t, size_t>> local_block_boundaries; ssize_t local_data_count = record.findAllLocalDataBlocks(&local_block_boundaries); if (local_data_count == 0) return false; for (const auto &block_start_and_end : local_block_boundaries) { std::vector<size_t> field_indices; record.findFieldsInLocalBlock("852", "??", block_start_and_end, &field_indices); for (size_t field_index : field_indices) { const std::string field_data(record.getFieldData(field_index)); const Subfields subfields(field_data); std::string sigil; if (subfields.extractSubfieldWithPattern('a', *tue_sigil_matcher, &sigil)) { return true; } } } return false; } void ProcessRecord(MarcRecord * const record, MarcWriter * const marc_writer) { const Leader &leader(record->getLeader()); if (not leader.isArticle()) { marc_writer->write(*record); return; } if (AlreadyHasLOK852DE21(*record)) { marc_writer->write(*record); return; } std::unordered_set<std::string> superior_ppn_set; CollectSuperiorPPNs(*record, &superior_ppn_set); // Do we have superior PPN that has DE-21 for (const auto &superior_ppn : superior_ppn_set) { if (de21_superior_ppns.find(superior_ppn) != de21_superior_ppns.end()) { InsertDE21ToLOK852(record); marc_writer->write(*record); return; } } } void AugmentRecords(MarcReader * const marc_reader, MarcWriter * const marc_writer) { marc_reader->rewind(); while (MarcRecord record = marc_reader->read()) ProcessRecord(&record, marc_writer); std::cerr << "Extracted " << extracted_count << " superior PPNs with DE-21 and modified " << modified_count << " records\n"; } int main(int argc, char **argv) { ::progname = argv[0]; if (argc != 3) Usage(); const std::unique_ptr<MarcReader> marc_reader(MarcReader::Factory(argv[1])); const std::unique_ptr<MarcWriter> marc_writer(MarcWriter::Factory(argv[2])); try { LoadDE21PPNs(marc_reader.get()); AugmentRecords(marc_reader.get(), marc_writer.get()); } catch (const std::exception &x) { Error("caught exception: " + std::string(x.what())); } }
/** \file add_ub_sigil_to_articles.cc * \author Johannes Riedl * * New implementation to derive information for articles about being available in Tübingen * from superior works and augment LOK data appropriately */ /* Copyright (C) 2017, Library of the University of Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <iostream> #include <cstring> #include "Compiler.h" #include "FileUtil.h" #include "TextUtil.h" #include "MarcRecord.h" #include "RegexMatcher.h" #include "util.h" static unsigned extracted_count(0); static unsigned modified_count(0); static std::unordered_set<std::string> de21_superior_ppns; static const RegexMatcher * const tue_sigil_matcher(RegexMatcher::RegexMatcherFactory("^DE-21.*")); static const RegexMatcher * const superior_ppn_matcher(RegexMatcher::RegexMatcherFactory(".DE-576.(.*)")); void Usage() { std::cerr << "Usage: " << ::progname << " spr_augmented_marc_input marc_output\n"; std::cerr << " Adds DE-21 sigils, as appropriate, to article entries found in the\n"; std::cerr << " master_marc_input and writes this augmented file as marc_output.\n\n"; std::cerr << " Notice that this program requires the SPR tag for superior works\n"; std::cerr << " to be set for appropriate results"; std::exit(EXIT_FAILURE); } void ProcessSuperiorRecord(const MarcRecord &record) { // We are done if this is not a superior work if (record.getFieldData("SPR").empty()) return; std::vector<std::pair<size_t, size_t>> local_block_boundaries; ssize_t local_data_count = record.findAllLocalDataBlocks(&local_block_boundaries); for (const auto &block_start_and_end : local_block_boundaries) { std::vector<size_t> field_indices; record.findFieldsInLocalBlock("852", "??", block_start_and_end, &field_indices); for (size_t field_index : field_indices) { const std::string field_data(record.getFieldData(field_index)); const Subfields subfields(field_data); std::string sigil; if (subfields.extractSubfieldWithPattern('a', *tue_sigil_matcher, &sigil)) { de21_superior_ppns.insert(record.getControlNumber()); ++extracted_count; } } } } void LoadDE21PPNs(MarcReader * const marc_reader) { while (const MarcRecord record = marc_reader->read()) ProcessSuperiorRecord(record); } void CollectSuperiorPPNs(const MarcRecord &record, std::unordered_set<std::string> * const superior_ppn_set) { // Determine superior PPNs from 800w:810w:830w:773w:776w const std::vector<std::string> tags({ "800", "810", "830", "773", "776" }); for (const auto &tag : tags) { std::vector<std::string> superior_ppn_vector; record.extractSubfields(tag , "w", &superior_ppn_vector); // Remove superfluous prefixes for (auto &superior_ppn : superior_ppn_vector) { std::string err_msg; if (not superior_ppn_matcher->matched(superior_ppn, &err_msg)) { if (not err_msg.empty()) Error("Error with regex für superior works " + err_msg); continue; } superior_ppn = (*superior_ppn_matcher)[1]; } std::copy(superior_ppn_vector.begin(), superior_ppn_vector.end(), std::inserter(*superior_ppn_set, superior_ppn_set->end())); } } void InsertDE21ToLOK852(MarcRecord * const record) { record->insertField("LOK", " ""\x1F""0852""\x1F""aDE-21"); ++modified_count; } bool AlreadyHasLOK852DE21(const MarcRecord &record) { std::vector<std::pair<size_t, size_t>> local_block_boundaries; ssize_t local_data_count = record.findAllLocalDataBlocks(&local_block_boundaries); if (local_data_count == 0) return false; for (const auto &block_start_and_end : local_block_boundaries) { std::vector<size_t> field_indices; record.findFieldsInLocalBlock("852", "??", block_start_and_end, &field_indices); for (size_t field_index : field_indices) { const std::string field_data(record.getFieldData(field_index)); const Subfields subfields(field_data); std::string sigil; if (subfields.extractSubfieldWithPattern('a', *tue_sigil_matcher, &sigil)) { return true; } } } return false; } void ProcessRecord(MarcRecord * const record, MarcWriter * const marc_writer) { const Leader &leader(record->getLeader()); if (not leader.isArticle()) { marc_writer->write(*record); return; } if (AlreadyHasLOK852DE21(*record)) { marc_writer->write(*record); return; } std::unordered_set<std::string> superior_ppn_set; CollectSuperiorPPNs(*record, &superior_ppn_set); // Do we have superior PPN that has DE-21 for (const auto &superior_ppn : superior_ppn_set) { if (de21_superior_ppns.find(superior_ppn) != de21_superior_ppns.end()) { InsertDE21ToLOK852(record); marc_writer->write(*record); return; } } } void AugmentRecords(MarcReader * const marc_reader, MarcWriter * const marc_writer) { marc_reader->rewind(); while (MarcRecord record = marc_reader->read()) ProcessRecord(&record, marc_writer); std::cerr << "Extracted " << extracted_count << " superior PPNs with DE-21 and modified " << modified_count << " records\n"; } int main(int argc, char **argv) { ::progname = argv[0]; if (argc != 3) Usage(); const std::unique_ptr<MarcReader> marc_reader(MarcReader::Factory(argv[1])); const std::unique_ptr<MarcWriter> marc_writer(MarcWriter::Factory(argv[2])); try { LoadDE21PPNs(marc_reader.get()); AugmentRecords(marc_reader.get(), marc_writer.get()); } catch (const std::exception &x) { Error("caught exception: " + std::string(x.what())); } }
Update add_ub_sigil_to_articles.cc
Update add_ub_sigil_to_articles.cc
C++
agpl-3.0
ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools
1a7d6665deafc1e35e5f8d56106a81a4686a6e44
selfdrive/sensord/sensors_qcom2.cc
selfdrive/sensord/sensors_qcom2.cc
#include <sys/resource.h> #include <chrono> #include <thread> #include <vector> #include <poll.h> #include <linux/gpio.h> #include "cereal/messaging/messaging.h" #include "common/i2c.h" #include "common/swaglog.h" #include "common/timing.h" #include "common/util.h" #include "selfdrive/sensord/sensors/bmx055_accel.h" #include "selfdrive/sensord/sensors/bmx055_gyro.h" #include "selfdrive/sensord/sensors/bmx055_magn.h" #include "selfdrive/sensord/sensors/bmx055_temp.h" #include "selfdrive/sensord/sensors/constants.h" #include "selfdrive/sensord/sensors/light_sensor.h" #include "selfdrive/sensord/sensors/lsm6ds3_accel.h" #include "selfdrive/sensord/sensors/lsm6ds3_gyro.h" #include "selfdrive/sensord/sensors/lsm6ds3_temp.h" #include "selfdrive/sensord/sensors/mmc5603nj_magn.h" #include "selfdrive/sensord/sensors/sensor.h" #define I2C_BUS_IMU 1 ExitHandler do_exit; std::mutex pm_mutex; void interrupt_loop(int fd, std::vector<Sensor *>& sensors, PubMaster& pm) { struct pollfd fd_list[1] = {0}; fd_list[0].fd = fd; fd_list[0].events = POLLIN | POLLPRI; uint64_t offset = nanos_since_epoch() - nanos_since_boot(); while (!do_exit) { int err = poll(fd_list, 1, 100); if (err == -1) { if (errno == EINTR) { continue; } return; } else if (err == 0) { LOGE("poll timed out"); continue; } if ((fd_list[0].revents & (POLLIN | POLLPRI)) == 0) { LOGE("no poll events set"); continue; } // Read all events struct gpioevent_data evdata[16]; err = read(fd, evdata, sizeof(evdata)); if (err < 0 || err % sizeof(*evdata) != 0) { LOGE("error reading event data %d", err); continue; } int num_events = err / sizeof(*evdata); uint64_t ts = evdata[num_events - 1].timestamp - offset; MessageBuilder msg; auto orphanage = msg.getOrphanage(); std::vector<capnp::Orphan<cereal::SensorEventData>> collected_events; collected_events.reserve(sensors.size()); for (Sensor *sensor : sensors) { auto orphan = orphanage.newOrphan<cereal::SensorEventData>(); auto event = orphan.get(); if (!sensor->get_event(event)) { continue; } event.setTimestamp(ts); collected_events.push_back(kj::mv(orphan)); } if (collected_events.size() == 0) { continue; } auto events = msg.initEvent().initSensorEvents(collected_events.size()); for (int i = 0; i < collected_events.size(); ++i) { events.adoptWithCaveats(i, kj::mv(collected_events[i])); } { std::lock_guard<std::mutex> lock(pm_mutex); pm.send("sensorEvents", msg); } } // poweroff sensors, disable interrupts for (Sensor *sensor : sensors) { sensor->shutdown(); } } int sensor_loop() { I2CBus *i2c_bus_imu; try { i2c_bus_imu = new I2CBus(I2C_BUS_IMU); } catch (std::exception &e) { LOGE("I2CBus init failed"); return -1; } BMX055_Accel bmx055_accel(i2c_bus_imu); BMX055_Gyro bmx055_gyro(i2c_bus_imu); BMX055_Magn bmx055_magn(i2c_bus_imu); BMX055_Temp bmx055_temp(i2c_bus_imu); LSM6DS3_Accel lsm6ds3_accel(i2c_bus_imu, GPIO_LSM_INT); LSM6DS3_Gyro lsm6ds3_gyro(i2c_bus_imu, GPIO_LSM_INT, true); // GPIO shared with accel LSM6DS3_Temp lsm6ds3_temp(i2c_bus_imu); MMC5603NJ_Magn mmc5603nj_magn(i2c_bus_imu); LightSensor light("/sys/class/i2c-adapter/i2c-2/2-0038/iio:device1/in_intensity_both_raw"); // Sensor init std::vector<std::pair<Sensor *, bool>> sensors_init; // Sensor, required sensors_init.push_back({&bmx055_accel, false}); sensors_init.push_back({&bmx055_gyro, false}); sensors_init.push_back({&bmx055_magn, false}); sensors_init.push_back({&bmx055_temp, false}); sensors_init.push_back({&lsm6ds3_accel, true}); sensors_init.push_back({&lsm6ds3_gyro, true}); sensors_init.push_back({&lsm6ds3_temp, true}); sensors_init.push_back({&mmc5603nj_magn, false}); sensors_init.push_back({&light, true}); bool has_magnetometer = false; // Initialize sensors std::vector<Sensor *> sensors; for (auto &sensor : sensors_init) { int err = sensor.first->init(); if (err < 0) { // Fail on required sensors if (sensor.second) { LOGE("Error initializing sensors"); delete i2c_bus_imu; return -1; } } else { if (sensor.first == &bmx055_magn || sensor.first == &mmc5603nj_magn) { has_magnetometer = true; } if (!sensor.first->has_interrupt_enabled()) { sensors.push_back(sensor.first); } } } if (!has_magnetometer) { LOGE("No magnetometer present"); delete i2c_bus_imu; return -1; } PubMaster pm({"sensorEvents"}); // thread for reading events via interrupts std::vector<Sensor *> lsm_interrupt_sensors = {&lsm6ds3_accel, &lsm6ds3_gyro}; std::thread lsm_interrupt_thread(&interrupt_loop, lsm6ds3_accel.gpio_fd, std::ref(lsm_interrupt_sensors), std::ref(pm)); // polling loop for non interrupt handled sensors while (!do_exit) { std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now(); const int num_events = sensors.size(); MessageBuilder msg; auto sensor_events = msg.initEvent().initSensorEvents(num_events); for (int i = 0; i < num_events; i++) { auto event = sensor_events[i]; sensors[i]->get_event(event); } { std::lock_guard<std::mutex> lock(pm_mutex); pm.send("sensorEvents", msg); } std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now(); std::this_thread::sleep_for(std::chrono::milliseconds(10) - (end - begin)); } lsm_interrupt_thread.join(); delete i2c_bus_imu; return 0; } int main(int argc, char *argv[]) { setpriority(PRIO_PROCESS, 0, -18); return sensor_loop(); }
#include <sys/resource.h> #include <chrono> #include <thread> #include <vector> #include <poll.h> #include <linux/gpio.h> #include "cereal/messaging/messaging.h" #include "common/i2c.h" #include "common/swaglog.h" #include "common/timing.h" #include "common/util.h" #include "selfdrive/sensord/sensors/bmx055_accel.h" #include "selfdrive/sensord/sensors/bmx055_gyro.h" #include "selfdrive/sensord/sensors/bmx055_magn.h" #include "selfdrive/sensord/sensors/bmx055_temp.h" #include "selfdrive/sensord/sensors/constants.h" #include "selfdrive/sensord/sensors/light_sensor.h" #include "selfdrive/sensord/sensors/lsm6ds3_accel.h" #include "selfdrive/sensord/sensors/lsm6ds3_gyro.h" #include "selfdrive/sensord/sensors/lsm6ds3_temp.h" #include "selfdrive/sensord/sensors/mmc5603nj_magn.h" #include "selfdrive/sensord/sensors/sensor.h" #define I2C_BUS_IMU 1 ExitHandler do_exit; std::mutex pm_mutex; void interrupt_loop(int fd, std::vector<Sensor *>& sensors, PubMaster& pm) { struct pollfd fd_list[1] = {0}; fd_list[0].fd = fd; fd_list[0].events = POLLIN | POLLPRI; uint64_t offset = nanos_since_epoch() - nanos_since_boot(); while (!do_exit) { int err = poll(fd_list, 1, 100); if (err == -1) { if (errno == EINTR) { continue; } return; } else if (err == 0) { LOGE("poll timed out"); continue; } if ((fd_list[0].revents & (POLLIN | POLLPRI)) == 0) { LOGE("no poll events set"); continue; } // Read all events struct gpioevent_data evdata[16]; err = read(fd, evdata, sizeof(evdata)); if (err < 0 || err % sizeof(*evdata) != 0) { LOGE("error reading event data %d", err); continue; } int num_events = err / sizeof(*evdata); uint64_t ts = evdata[num_events - 1].timestamp - offset; MessageBuilder msg; auto orphanage = msg.getOrphanage(); std::vector<capnp::Orphan<cereal::SensorEventData>> collected_events; collected_events.reserve(sensors.size()); for (Sensor *sensor : sensors) { auto orphan = orphanage.newOrphan<cereal::SensorEventData>(); auto event = orphan.get(); if (!sensor->get_event(event)) { continue; } event.setTimestamp(ts); collected_events.push_back(kj::mv(orphan)); } if (collected_events.size() == 0) { continue; } auto events = msg.initEvent().initSensorEvents(collected_events.size()); for (int i = 0; i < collected_events.size(); ++i) { events.adoptWithCaveats(i, kj::mv(collected_events[i])); } std::lock_guard<std::mutex> lock(pm_mutex); pm.send("sensorEvents", msg); } // poweroff sensors, disable interrupts for (Sensor *sensor : sensors) { sensor->shutdown(); } } int sensor_loop() { I2CBus *i2c_bus_imu; try { i2c_bus_imu = new I2CBus(I2C_BUS_IMU); } catch (std::exception &e) { LOGE("I2CBus init failed"); return -1; } BMX055_Accel bmx055_accel(i2c_bus_imu); BMX055_Gyro bmx055_gyro(i2c_bus_imu); BMX055_Magn bmx055_magn(i2c_bus_imu); BMX055_Temp bmx055_temp(i2c_bus_imu); LSM6DS3_Accel lsm6ds3_accel(i2c_bus_imu, GPIO_LSM_INT); LSM6DS3_Gyro lsm6ds3_gyro(i2c_bus_imu, GPIO_LSM_INT, true); // GPIO shared with accel LSM6DS3_Temp lsm6ds3_temp(i2c_bus_imu); MMC5603NJ_Magn mmc5603nj_magn(i2c_bus_imu); LightSensor light("/sys/class/i2c-adapter/i2c-2/2-0038/iio:device1/in_intensity_both_raw"); // Sensor init std::vector<std::pair<Sensor *, bool>> sensors_init; // Sensor, required sensors_init.push_back({&bmx055_accel, false}); sensors_init.push_back({&bmx055_gyro, false}); sensors_init.push_back({&bmx055_magn, false}); sensors_init.push_back({&bmx055_temp, false}); sensors_init.push_back({&lsm6ds3_accel, true}); sensors_init.push_back({&lsm6ds3_gyro, true}); sensors_init.push_back({&lsm6ds3_temp, true}); sensors_init.push_back({&mmc5603nj_magn, false}); sensors_init.push_back({&light, true}); bool has_magnetometer = false; // Initialize sensors std::vector<Sensor *> sensors; for (auto &sensor : sensors_init) { int err = sensor.first->init(); if (err < 0) { // Fail on required sensors if (sensor.second) { LOGE("Error initializing sensors"); delete i2c_bus_imu; return -1; } } else { if (sensor.first == &bmx055_magn || sensor.first == &mmc5603nj_magn) { has_magnetometer = true; } if (!sensor.first->has_interrupt_enabled()) { sensors.push_back(sensor.first); } } } if (!has_magnetometer) { LOGE("No magnetometer present"); delete i2c_bus_imu; return -1; } PubMaster pm({"sensorEvents"}); // thread for reading events via interrupts std::vector<Sensor *> lsm_interrupt_sensors = {&lsm6ds3_accel, &lsm6ds3_gyro}; std::thread lsm_interrupt_thread(&interrupt_loop, lsm6ds3_accel.gpio_fd, std::ref(lsm_interrupt_sensors), std::ref(pm)); // polling loop for non interrupt handled sensors while (!do_exit) { std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now(); const int num_events = sensors.size(); MessageBuilder msg; auto sensor_events = msg.initEvent().initSensorEvents(num_events); for (int i = 0; i < num_events; i++) { auto event = sensor_events[i]; sensors[i]->get_event(event); } { std::lock_guard<std::mutex> lock(pm_mutex); pm.send("sensorEvents", msg); } std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now(); std::this_thread::sleep_for(std::chrono::milliseconds(10) - (end - begin)); } lsm_interrupt_thread.join(); delete i2c_bus_imu; return 0; } int main(int argc, char *argv[]) { setpriority(PRIO_PROCESS, 0, -18); return sensor_loop(); }
remove unnecessary brace pair (#25816)
sensord: remove unnecessary brace pair (#25816) Remove unnecessary brace pair
C++
mit
commaai/openpilot,commaai/openpilot,commaai/openpilot,commaai/openpilot,commaai/openpilot,commaai/openpilot
95554a8fb4f518771da407ad2e492f4c0a55b72a
ui/views/corewm/tooltip_aura.cc
ui/views/corewm/tooltip_aura.cc
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/corewm/tooltip_aura.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "ui/aura/window.h" #include "ui/aura/window_tree_host.h" #include "ui/gfx/canvas.h" #include "ui/gfx/render_text.h" #include "ui/gfx/screen.h" #include "ui/gfx/text_elider.h" #include "ui/gfx/text_utils.h" #include "ui/native_theme/native_theme.h" #include "ui/views/background.h" #include "ui/views/border.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" namespace { // Max visual tooltip width. If a tooltip is greater than this width, it will // be wrapped. const int kTooltipMaxWidthPixels = 400; // FIXME: get cursor offset from actual cursor size. const int kCursorOffsetX = 10; const int kCursorOffsetY = 15; // Creates a widget of type TYPE_TOOLTIP views::Widget* CreateTooltipWidget(aura::Window* tooltip_window) { views::Widget* widget = new views::Widget; views::Widget::InitParams params; // For aura, since we set the type to TYPE_TOOLTIP, the widget will get // auto-parented to the right container. params.type = views::Widget::InitParams::TYPE_TOOLTIP; params.context = tooltip_window; DCHECK(params.context); params.keep_on_top = true; params.accept_events = false; widget->Init(params); return widget; } } // namespace namespace views { namespace corewm { // TODO(oshima): Consider to use views::Label. class TooltipAura::TooltipView : public views::View { public: TooltipView() : render_text_(gfx::RenderText::CreateInstance()), max_width_(0) { set_owned_by_client(); render_text_->SetMultiline(true); ResetDisplayRect(); } ~TooltipView() override {} // views:View: void OnPaint(gfx::Canvas* canvas) override { OnPaintBackground(canvas); render_text_->SetDisplayRect(gfx::Rect(size())); render_text_->Draw(canvas); OnPaintBorder(canvas); } gfx::Size GetPreferredSize() const override { return render_text_->GetStringSize(); } const char* GetClassName() const override { return "TooltipView"; } void SetText(const base::string16& text) { render_text_->SetHorizontalAlignment(gfx::ALIGN_TO_HEAD); render_text_->SetText(text); } void SetForegroundColor(SkColor color) { render_text_->SetColor(color); } void SetMaxWidth(int width) { max_width_ = width; ResetDisplayRect(); } private: void ResetDisplayRect() { render_text_->SetDisplayRect(gfx::Rect(0, 0, max_width_, 100000)); } scoped_ptr<gfx::RenderText> render_text_; int max_width_; DISALLOW_COPY_AND_ASSIGN(TooltipView); }; TooltipAura::TooltipAura() : tooltip_view_(new TooltipView), widget_(NULL), tooltip_window_(NULL) { const int kHorizontalPadding = 3; const int kVerticalPadding = 2; tooltip_view_->SetBorder(Border::CreateEmptyBorder( kVerticalPadding, kHorizontalPadding, kVerticalPadding, kHorizontalPadding)); } TooltipAura::~TooltipAura() { DestroyWidget(); } void TooltipAura::SetTooltipBounds(const gfx::Point& mouse_pos, const gfx::Size& tooltip_size) { gfx::Rect tooltip_rect(mouse_pos, tooltip_size); tooltip_rect.Offset(kCursorOffsetX, kCursorOffsetY); gfx::Screen* screen = gfx::Screen::GetScreenFor(tooltip_window_); gfx::Rect display_bounds(screen->GetDisplayNearestPoint(mouse_pos).bounds()); // If tooltip is out of bounds on the x axis, we simply shift it // horizontally by the offset. if (tooltip_rect.right() > display_bounds.right()) { int h_offset = tooltip_rect.right() - display_bounds.right(); tooltip_rect.Offset(-h_offset, 0); } // If tooltip is out of bounds on the y axis, we flip it to appear above the // mouse cursor instead of below. if (tooltip_rect.bottom() > display_bounds.bottom()) tooltip_rect.set_y(mouse_pos.y() - tooltip_size.height()); tooltip_rect.AdjustToFit(display_bounds); widget_->SetBounds(tooltip_rect); } void TooltipAura::DestroyWidget() { if (widget_) { widget_->RemoveObserver(this); widget_->Close(); widget_ = NULL; } } int TooltipAura::GetMaxWidth(const gfx::Point& location, aura::Window* context) const { gfx::Screen* screen = gfx::Screen::GetScreenFor(context); gfx::Rect display_bounds(screen->GetDisplayNearestPoint(location).bounds()); return std::min(kTooltipMaxWidthPixels, (display_bounds.width() + 1) / 2); } void TooltipAura::SetText(aura::Window* window, const base::string16& tooltip_text, const gfx::Point& location) { tooltip_window_ = window; tooltip_view_->SetMaxWidth(GetMaxWidth(location, window)); tooltip_view_->SetText(tooltip_text); if (!widget_) { widget_ = CreateTooltipWidget(tooltip_window_); widget_->SetContentsView(tooltip_view_.get()); widget_->AddObserver(this); } SetTooltipBounds(location, tooltip_view_->GetPreferredSize()); ui::NativeTheme* native_theme = widget_->GetNativeTheme(); tooltip_view_->set_background( views::Background::CreateSolidBackground( native_theme->GetSystemColor( ui::NativeTheme::kColorId_TooltipBackground))); tooltip_view_->SetForegroundColor(native_theme->GetSystemColor( ui::NativeTheme::kColorId_TooltipText)); } void TooltipAura::Show() { if (widget_) { widget_->Show(); widget_->StackAtTop(); } } void TooltipAura::Hide() { tooltip_window_ = NULL; if (widget_) widget_->Hide(); } bool TooltipAura::IsVisible() { return widget_ && widget_->IsVisible(); } void TooltipAura::OnWidgetDestroying(views::Widget* widget) { DCHECK_EQ(widget_, widget); widget_ = NULL; tooltip_window_ = NULL; } } // namespace corewm } // namespace views
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/corewm/tooltip_aura.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "ui/aura/window.h" #include "ui/aura/window_tree_host.h" #include "ui/gfx/canvas.h" #include "ui/gfx/render_text.h" #include "ui/gfx/screen.h" #include "ui/gfx/text_elider.h" #include "ui/gfx/text_utils.h" #include "ui/native_theme/native_theme.h" #include "ui/views/background.h" #include "ui/views/border.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" namespace { // Max visual tooltip width. If a tooltip is greater than this width, it will // be wrapped. const int kTooltipMaxWidthPixels = 400; // FIXME: get cursor offset from actual cursor size. const int kCursorOffsetX = 10; const int kCursorOffsetY = 15; // Creates a widget of type TYPE_TOOLTIP views::Widget* CreateTooltipWidget(aura::Window* tooltip_window) { views::Widget* widget = new views::Widget; views::Widget::InitParams params; // For aura, since we set the type to TYPE_TOOLTIP, the widget will get // auto-parented to the right container. params.type = views::Widget::InitParams::TYPE_TOOLTIP; params.context = tooltip_window; DCHECK(params.context); params.keep_on_top = true; params.accept_events = false; widget->Init(params); return widget; } } // namespace namespace views { namespace corewm { // TODO(oshima): Consider to use views::Label. class TooltipAura::TooltipView : public views::View { public: TooltipView() : render_text_(gfx::RenderText::CreateInstance()), max_width_(0) { const int kHorizontalPadding = 3; const int kVerticalPadding = 2; SetBorder(Border::CreateEmptyBorder( kVerticalPadding, kHorizontalPadding, kVerticalPadding, kHorizontalPadding)); set_owned_by_client(); render_text_->SetMultiline(true); ResetDisplayRect(); } ~TooltipView() override {} // views:View: void OnPaint(gfx::Canvas* canvas) override { OnPaintBackground(canvas); gfx::Size text_size = size(); gfx::Insets insets = border()->GetInsets(); text_size.Enlarge(-insets.width(), -insets.height()); render_text_->SetDisplayRect(gfx::Rect(text_size)); canvas->Save(); canvas->Translate(gfx::Vector2d(insets.left(), insets.top())); render_text_->Draw(canvas); canvas->Restore(); OnPaintBorder(canvas); } gfx::Size GetPreferredSize() const override { gfx::Size view_size = render_text_->GetStringSize(); gfx::Insets insets = border()->GetInsets(); view_size.Enlarge(insets.width(), insets.height()); return view_size; } const char* GetClassName() const override { return "TooltipView"; } void SetText(const base::string16& text) { render_text_->SetHorizontalAlignment(gfx::ALIGN_TO_HEAD); render_text_->SetText(text); } void SetForegroundColor(SkColor color) { render_text_->SetColor(color); } void SetMaxWidth(int width) { max_width_ = width; ResetDisplayRect(); } private: void ResetDisplayRect() { gfx::Insets insets = border()->GetInsets(); int max_text_width = max_width_ - insets.width(); render_text_->SetDisplayRect(gfx::Rect(0, 0, max_text_width, 100000)); } scoped_ptr<gfx::RenderText> render_text_; int max_width_; DISALLOW_COPY_AND_ASSIGN(TooltipView); }; TooltipAura::TooltipAura() : tooltip_view_(new TooltipView), widget_(NULL), tooltip_window_(NULL) { } TooltipAura::~TooltipAura() { DestroyWidget(); } void TooltipAura::SetTooltipBounds(const gfx::Point& mouse_pos, const gfx::Size& tooltip_size) { gfx::Rect tooltip_rect(mouse_pos, tooltip_size); tooltip_rect.Offset(kCursorOffsetX, kCursorOffsetY); gfx::Screen* screen = gfx::Screen::GetScreenFor(tooltip_window_); gfx::Rect display_bounds(screen->GetDisplayNearestPoint(mouse_pos).bounds()); // If tooltip is out of bounds on the x axis, we simply shift it // horizontally by the offset. if (tooltip_rect.right() > display_bounds.right()) { int h_offset = tooltip_rect.right() - display_bounds.right(); tooltip_rect.Offset(-h_offset, 0); } // If tooltip is out of bounds on the y axis, we flip it to appear above the // mouse cursor instead of below. if (tooltip_rect.bottom() > display_bounds.bottom()) tooltip_rect.set_y(mouse_pos.y() - tooltip_size.height()); tooltip_rect.AdjustToFit(display_bounds); widget_->SetBounds(tooltip_rect); } void TooltipAura::DestroyWidget() { if (widget_) { widget_->RemoveObserver(this); widget_->Close(); widget_ = NULL; } } int TooltipAura::GetMaxWidth(const gfx::Point& location, aura::Window* context) const { gfx::Screen* screen = gfx::Screen::GetScreenFor(context); gfx::Rect display_bounds(screen->GetDisplayNearestPoint(location).bounds()); return std::min(kTooltipMaxWidthPixels, (display_bounds.width() + 1) / 2); } void TooltipAura::SetText(aura::Window* window, const base::string16& tooltip_text, const gfx::Point& location) { tooltip_window_ = window; tooltip_view_->SetMaxWidth(GetMaxWidth(location, window)); tooltip_view_->SetText(tooltip_text); if (!widget_) { widget_ = CreateTooltipWidget(tooltip_window_); widget_->SetContentsView(tooltip_view_.get()); widget_->AddObserver(this); } SetTooltipBounds(location, tooltip_view_->GetPreferredSize()); ui::NativeTheme* native_theme = widget_->GetNativeTheme(); tooltip_view_->set_background( views::Background::CreateSolidBackground( native_theme->GetSystemColor( ui::NativeTheme::kColorId_TooltipBackground))); tooltip_view_->SetForegroundColor(native_theme->GetSystemColor( ui::NativeTheme::kColorId_TooltipText)); } void TooltipAura::Show() { if (widget_) { widget_->Show(); widget_->StackAtTop(); } } void TooltipAura::Hide() { tooltip_window_ = NULL; if (widget_) widget_->Hide(); } bool TooltipAura::IsVisible() { return widget_ && widget_->IsVisible(); } void TooltipAura::OnWidgetDestroying(views::Widget* widget) { DCHECK_EQ(widget_, widget); widget_ = NULL; tooltip_window_ = NULL; } } // namespace corewm } // namespace views
Add padding around tooltip
Add padding around tooltip I missed this in https://codereview.chromium.org/924433002. mukai's label change is still under review in case you're interested. BUG=None TEST=manually tested with RTL,LTR multiline tooltips Review URL: https://codereview.chromium.org/981933003 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#319370}
C++
bsd-3-clause
axinging/chromium-crosswalk,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,ltilve/chromium,axinging/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,ltilve/chromium,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,ltilve/chromium,fujunwei/chromium-crosswalk,ltilve/chromium,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,Chilledheart/chromium,ltilve/chromium,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,ltilve/chromium,chuan9/chromium-crosswalk,ltilve/chromium,Just-D/chromium-1,axinging/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,Just-D/chromium-1,fujunwei/chromium-crosswalk,Chilledheart/chromium,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,ltilve/chromium,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,ltilve/chromium,Chilledheart/chromium,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,Chilledheart/chromium,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,Chilledheart/chromium,Just-D/chromium-1,axinging/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk
f3930de28bfd13e29fa0cd4d78e7525be386383d
src/riscv-elf-file.cc
src/riscv-elf-file.cc
// // riscv-elf-file.cc // #include <cstdio> #include <cstdint> #include <cerrno> #include <string> #include <vector> #include <map> #include <functional> #include <sys/stat.h> #include "riscv-elf.h" #include "riscv-elf-file.h" #include "riscv-elf-format.h" #include "riscv-util.h" elf_file::elf_file(std::string filename) : filename(filename) { struct stat stat_buf; // open file FILE *file = fopen(filename.c_str(), "r"); if (!file) { panic("error fopen: %s: %s", filename.c_str(), strerror(errno)); } // check file length if (fstat(fileno(file), &stat_buf) < 0) { fclose(file); panic("error fstat: %s: %s", filename.c_str(), strerror(errno)); } // read magic if (stat_buf.st_size < EI_NIDENT) { fclose(file); panic("error invalid ELF file: %s", filename.c_str()); } filesize = stat_buf.st_size; buf.resize(EI_NIDENT); size_t bytes_read = fread(buf.data(), 1, EI_NIDENT, file); if (bytes_read != EI_NIDENT || !elf_check_magic(buf.data())) { fclose(file); panic("error invalid ELF magic: %s", filename.c_str()); } ei_class = buf[EI_CLASS]; ei_data = buf[EI_DATA]; // read remaining data buf.resize(filesize); bytes_read = fread(buf.data() + EI_NIDENT, 1, filesize - EI_NIDENT, file); if (bytes_read != (size_t)filesize - EI_NIDENT) { fclose(file); panic("error fread: %s", filename.c_str()); } fclose(file); // byteswap and normalize file header switch (ei_class) { case ELFCLASS32: elf_bswap_ehdr32((Elf32_Ehdr*)buf.data(), ei_data); elf_convert_to_ehdr64(&ehdr, (Elf32_Ehdr*)buf.data()); break; case ELFCLASS64: elf_bswap_ehdr64((Elf64_Ehdr*)buf.data(), ei_data); memcpy(&ehdr, (Elf64_Ehdr*)buf.data(), sizeof(Elf64_Ehdr)); break; default: panic("error invalid ELF class: %s", filename.c_str()); } // check header version if (ehdr.e_version != EV_CURRENT) { panic("error invalid ELF version: %s", filename.c_str()); } // byteswap and normalize program and section headers switch (ei_class) { case ELFCLASS32: for (int i = 0; i < ehdr.e_phnum; i++) { Elf32_Phdr *phdr32 = (Elf32_Phdr*)(buf.data() + ehdr.e_phoff + i * sizeof(Elf32_Phdr)); Elf64_Phdr phdr64; elf_bswap_phdr32(phdr32, ei_data); elf_convert_to_phdr64(&phdr64, phdr32); phdrs.push_back(phdr64); } for (int i = 0; i < ehdr.e_shnum; i++) { Elf32_Shdr *shdr32 = (Elf32_Shdr*)(buf.data() + ehdr.e_shoff + i * sizeof(Elf32_Shdr)); Elf64_Shdr shdr64; elf_bswap_shdr32(shdr32, ei_data); elf_convert_to_shdr64(&shdr64, shdr32); shdrs.push_back(shdr64); } break; case ELFCLASS64: for (int i = 0; i < ehdr.e_phnum; i++) { Elf64_Phdr *phdr64 = (Elf64_Phdr*)(buf.data() + ehdr.e_phoff + i * sizeof(Elf64_Phdr)); elf_bswap_phdr64(phdr64, ei_data); phdrs.push_back(*phdr64); } for (int i = 0; i < ehdr.e_shnum; i++) { Elf64_Shdr *shdr64 = (Elf64_Shdr*)(buf.data() + ehdr.e_shoff + i * sizeof(Elf64_Shdr)); elf_bswap_shdr64(shdr64, ei_data); shdrs.push_back(*shdr64); } break; } // Find strtab and symtab shstrtab = symtab = strtab = nullptr; for (size_t i = 0; i < shdrs.size(); i++) { if (shstrtab == nullptr && shdrs[i].sh_type == SHT_STRTAB) { shstrtab = &shdrs[i]; } else if (symtab == nullptr && shdrs[i].sh_type == SHT_SYMTAB) { symtab = &shdrs[i]; if (shdrs[i].sh_link > 0) { strtab = &shdrs[shdrs[i].sh_link]; } } } if (!symtab) return; // byteswap and normalize symbol table entries size_t num_symbols = symtab->sh_size / symtab->sh_entsize; switch (ei_class) { case ELFCLASS32: for (size_t i = 0; i < num_symbols; i++) { Elf32_Sym *sym32 = (Elf32_Sym*)(buf.data() + symtab->sh_offset + i * sizeof(Elf32_Sym)); Elf64_Sym sym64; elf_bswap_sym32(sym32, ei_data); elf_convert_to_sym64(&sym64, sym32); symbols.push_back(sym64); addr_symbol_map[sym64.st_value] = symbols.size() - 1; } break; case ELFCLASS64: for (size_t i = 0; i < num_symbols; i++) { Elf64_Sym *sym64 = (Elf64_Sym*)(buf.data() + symtab->sh_offset + i * sizeof(Elf64_Sym)); elf_bswap_sym64(sym64, ei_data); symbols.push_back(*sym64); addr_symbol_map[sym64->st_value] = symbols.size() - 1; } break; } }
// // riscv-elf-file.cc // #include <cstdio> #include <cstdint> #include <cstring> #include <cerrno> #include <string> #include <vector> #include <map> #include <functional> #include <sys/stat.h> #include "riscv-elf.h" #include "riscv-elf-file.h" #include "riscv-elf-format.h" #include "riscv-util.h" elf_file::elf_file(std::string filename) : filename(filename) { struct stat stat_buf; // open file FILE *file = fopen(filename.c_str(), "r"); if (!file) { panic("error fopen: %s: %s", filename.c_str(), strerror(errno)); } // check file length if (fstat(fileno(file), &stat_buf) < 0) { fclose(file); panic("error fstat: %s: %s", filename.c_str(), strerror(errno)); } // read magic if (stat_buf.st_size < EI_NIDENT) { fclose(file); panic("error invalid ELF file: %s", filename.c_str()); } filesize = stat_buf.st_size; buf.resize(EI_NIDENT); size_t bytes_read = fread(buf.data(), 1, EI_NIDENT, file); if (bytes_read != EI_NIDENT || !elf_check_magic(buf.data())) { fclose(file); panic("error invalid ELF magic: %s", filename.c_str()); } ei_class = buf[EI_CLASS]; ei_data = buf[EI_DATA]; // read remaining data buf.resize(filesize); bytes_read = fread(buf.data() + EI_NIDENT, 1, filesize - EI_NIDENT, file); if (bytes_read != (size_t)filesize - EI_NIDENT) { fclose(file); panic("error fread: %s", filename.c_str()); } fclose(file); // byteswap and normalize file header switch (ei_class) { case ELFCLASS32: elf_bswap_ehdr32((Elf32_Ehdr*)buf.data(), ei_data); elf_convert_to_ehdr64(&ehdr, (Elf32_Ehdr*)buf.data()); break; case ELFCLASS64: elf_bswap_ehdr64((Elf64_Ehdr*)buf.data(), ei_data); memcpy(&ehdr, (Elf64_Ehdr*)buf.data(), sizeof(Elf64_Ehdr)); break; default: panic("error invalid ELF class: %s", filename.c_str()); } // check header version if (ehdr.e_version != EV_CURRENT) { panic("error invalid ELF version: %s", filename.c_str()); } // byteswap and normalize program and section headers switch (ei_class) { case ELFCLASS32: for (int i = 0; i < ehdr.e_phnum; i++) { Elf32_Phdr *phdr32 = (Elf32_Phdr*)(buf.data() + ehdr.e_phoff + i * sizeof(Elf32_Phdr)); Elf64_Phdr phdr64; elf_bswap_phdr32(phdr32, ei_data); elf_convert_to_phdr64(&phdr64, phdr32); phdrs.push_back(phdr64); } for (int i = 0; i < ehdr.e_shnum; i++) { Elf32_Shdr *shdr32 = (Elf32_Shdr*)(buf.data() + ehdr.e_shoff + i * sizeof(Elf32_Shdr)); Elf64_Shdr shdr64; elf_bswap_shdr32(shdr32, ei_data); elf_convert_to_shdr64(&shdr64, shdr32); shdrs.push_back(shdr64); } break; case ELFCLASS64: for (int i = 0; i < ehdr.e_phnum; i++) { Elf64_Phdr *phdr64 = (Elf64_Phdr*)(buf.data() + ehdr.e_phoff + i * sizeof(Elf64_Phdr)); elf_bswap_phdr64(phdr64, ei_data); phdrs.push_back(*phdr64); } for (int i = 0; i < ehdr.e_shnum; i++) { Elf64_Shdr *shdr64 = (Elf64_Shdr*)(buf.data() + ehdr.e_shoff + i * sizeof(Elf64_Shdr)); elf_bswap_shdr64(shdr64, ei_data); shdrs.push_back(*shdr64); } break; } // Find strtab and symtab shstrtab = symtab = strtab = nullptr; for (size_t i = 0; i < shdrs.size(); i++) { if (shstrtab == nullptr && shdrs[i].sh_type == SHT_STRTAB) { shstrtab = &shdrs[i]; } else if (symtab == nullptr && shdrs[i].sh_type == SHT_SYMTAB) { symtab = &shdrs[i]; if (shdrs[i].sh_link > 0) { strtab = &shdrs[shdrs[i].sh_link]; } } } if (!symtab) return; // byteswap and normalize symbol table entries size_t num_symbols = symtab->sh_size / symtab->sh_entsize; switch (ei_class) { case ELFCLASS32: for (size_t i = 0; i < num_symbols; i++) { Elf32_Sym *sym32 = (Elf32_Sym*)(buf.data() + symtab->sh_offset + i * sizeof(Elf32_Sym)); Elf64_Sym sym64; elf_bswap_sym32(sym32, ei_data); elf_convert_to_sym64(&sym64, sym32); symbols.push_back(sym64); addr_symbol_map[sym64.st_value] = symbols.size() - 1; } break; case ELFCLASS64: for (size_t i = 0; i < num_symbols; i++) { Elf64_Sym *sym64 = (Elf64_Sym*)(buf.data() + symtab->sh_offset + i * sizeof(Elf64_Sym)); elf_bswap_sym64(sym64, ei_data); symbols.push_back(*sym64); addr_symbol_map[sym64->st_value] = symbols.size() - 1; } break; } }
Add #include <cstring> to riscv-elf-file.cc
Add #include <cstring> to riscv-elf-file.cc
C++
mit
rv8-io/rv8,rv8-io/rv8,rv8-io/rv8
88695412607167315822d0ceca59f5d9bc5128a6
unit_testing/test_unpublish.cpp
unit_testing/test_unpublish.cpp
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2015 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #include <thread> #include <atomic> #include "test.hpp" #include "caf/all.hpp" #include "caf/io/all.hpp" using namespace caf; namespace { std::atomic<long> s_dtor_called; class dummy : public event_based_actor { public: ~dummy() { ++s_dtor_called; } behavior make_behavior() override { return { others() >> CAF_UNEXPECTED_MSG_CB(this) }; } }; uint16_t publish_at_some_port(uint16_t first_port, actor whom) { auto port = first_port; for (;;) { try { io::publish(whom, port); return port; } catch (bind_failure&) { // try next port ++port; } } } } // namespace <anonymous> int main() { CAF_TEST(test_unpublish); auto d = spawn<dummy>(); auto port = publish_at_some_port(4242, d); std::this_thread::sleep_for(std::chrono::milliseconds(50)); io::unpublish(d, port); CAF_CHECKPOINT(); // must fail now try { auto oops = io::remote_actor("127.0.0.1", port); CAF_FAILURE("unexpected: remote actor succeeded!"); } catch (network_error&) { CAF_CHECKPOINT(); } anon_send_exit(d, exit_reason::user_shutdown); d = invalid_actor; await_all_actors_done(); shutdown(); CAF_CHECK_EQUAL(s_dtor_called.load(), 1); return CAF_TEST_RESULT(); }
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2015 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #include <thread> #include <atomic> #include "test.hpp" #include "caf/all.hpp" #include "caf/io/all.hpp" using namespace caf; namespace { std::atomic<long> s_dtor_called; class dummy : public event_based_actor { public: ~dummy() { ++s_dtor_called; } behavior make_behavior() override { return { others() >> CAF_UNEXPECTED_MSG_CB(this) }; } }; uint16_t publish_at_some_port(uint16_t first_port, actor whom) { auto port = first_port; for (;;) { try { io::publish(whom, port); return port; } catch (bind_failure&) { // try next port ++port; } } } actor invalid_unpublish(uint16_t port) { auto d = spawn<dummy>(); io::unpublish(d, port); anon_send_exit(d, exit_reason::user_shutdown); d = invalid_actor; return io::remote_actor("127.0.0.1", port); } } // namespace <anonymous> int main() { CAF_TEST(test_unpublish); auto d = spawn<dummy>(); auto port = publish_at_some_port(4242, d); std::this_thread::sleep_for(std::chrono::milliseconds(50)); CAF_CHECK_EQUAL(invalid_unpublish(port), d); io::unpublish(d, port); CAF_CHECKPOINT(); // must fail now try { auto oops = io::remote_actor("127.0.0.1", port); CAF_FAILURE("unexpected: remote actor succeeded!"); } catch (network_error&) { CAF_CHECKPOINT(); } anon_send_exit(d, exit_reason::user_shutdown); d = invalid_actor; await_all_actors_done(); shutdown(); CAF_CHECK_EQUAL(s_dtor_called.load(), 2); return CAF_TEST_RESULT(); }
Improve unpublish unit test
Improve unpublish unit test
C++
bsd-3-clause
szdavid92/actor-framework,actor-framework/actor-framework,tbenthompson/actor-framework,TanNgocDo/actor-framework,firegurafiku/actor-framework,actor-framework/actor-framework,cmaughan/actor-framework,szdavid92/actor-framework,actor-framework/actor-framework,tbenthompson/actor-framework,tempbottle/actor-framework,tempbottle/actor-framework,actor-framework/actor-framework,szdavid92/actor-framework,1blankz7/actor-framework,rvlm/actor-framework,DavadDi/actor-framework,TanNgocDo/actor-framework,tempbottle/actor-framework,rvlm/actor-framework,TanNgocDo/actor-framework,firegurafiku/actor-framework,DavadDi/actor-framework,1blankz7/actor-framework,cmaughan/actor-framework,1blankz7/actor-framework,cmaughan/actor-framework,1blankz7/actor-framework,DavadDi/actor-framework,nq-ebaratte/actor-framework,tbenthompson/actor-framework,DavadDi/actor-framework,nq-ebaratte/actor-framework,rvlm/actor-framework,nq-ebaratte/actor-framework,firegurafiku/actor-framework,PlexChat/actor-framework,nq-ebaratte/actor-framework,PlexChat/actor-framework,PlexChat/actor-framework
43c0cee390ccfe0eff192a2d6e2f250298d70cd6
unittests/ADT/BitVectorTest.cpp
unittests/ADT/BitVectorTest.cpp
//===- llvm/unittest/ADT/BitVectorTest.cpp - BitVector tests --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // Some of these tests fail on PowerPC for unknown reasons. #ifndef __ppc__ #include "llvm/ADT/BitVector.h" #include "llvm/ADT/SmallBitVector.h" #include "gtest/gtest.h" using namespace llvm; namespace { // Test fixture template <typename T> class BitVectorTest : public ::testing::Test { }; // Test both BitVector and SmallBitVector with the same suite of tests. typedef ::testing::Types<BitVector, SmallBitVector> BitVectorTestTypes; TYPED_TEST_CASE(BitVectorTest, BitVectorTestTypes); TYPED_TEST(BitVectorTest, TrivialOperation) { TypeParam Vec; EXPECT_EQ(0U, Vec.count()); EXPECT_EQ(0U, Vec.size()); EXPECT_FALSE(Vec.any()); EXPECT_TRUE(Vec.all()); EXPECT_TRUE(Vec.none()); EXPECT_TRUE(Vec.empty()); Vec.resize(5, true); EXPECT_EQ(5U, Vec.count()); EXPECT_EQ(5U, Vec.size()); EXPECT_TRUE(Vec.any()); EXPECT_TRUE(Vec.all()); EXPECT_FALSE(Vec.none()); EXPECT_FALSE(Vec.empty()); Vec.resize(11); EXPECT_EQ(5U, Vec.count()); EXPECT_EQ(11U, Vec.size()); EXPECT_TRUE(Vec.any()); EXPECT_FALSE(Vec.all()); EXPECT_FALSE(Vec.none()); EXPECT_FALSE(Vec.empty()); TypeParam Inv = Vec; Inv.flip(); EXPECT_EQ(6U, Inv.count()); EXPECT_EQ(11U, Inv.size()); EXPECT_TRUE(Inv.any()); EXPECT_FALSE(Inv.all()); EXPECT_FALSE(Inv.none()); EXPECT_FALSE(Inv.empty()); EXPECT_FALSE(Inv == Vec); EXPECT_TRUE(Inv != Vec); Vec.flip(); EXPECT_TRUE(Inv == Vec); EXPECT_FALSE(Inv != Vec); // Add some "interesting" data to Vec. Vec.resize(23, true); Vec.resize(25, false); Vec.resize(26, true); Vec.resize(29, false); Vec.resize(33, true); Vec.resize(57, false); unsigned Count = 0; for (unsigned i = Vec.find_first(); i != -1u; i = Vec.find_next(i)) { ++Count; EXPECT_TRUE(Vec[i]); EXPECT_TRUE(Vec.test(i)); } EXPECT_EQ(Count, Vec.count()); EXPECT_EQ(Count, 23u); EXPECT_FALSE(Vec[0]); EXPECT_TRUE(Vec[32]); EXPECT_FALSE(Vec[56]); Vec.resize(61, false); TypeParam Copy = Vec; TypeParam Alt(3, false); Alt.resize(6, true); std::swap(Alt, Vec); EXPECT_TRUE(Copy == Alt); EXPECT_TRUE(Vec.size() == 6); EXPECT_TRUE(Vec.count() == 3); EXPECT_TRUE(Vec.find_first() == 3); std::swap(Copy, Vec); // Add some more "interesting" data. Vec.resize(68, true); Vec.resize(78, false); Vec.resize(89, true); Vec.resize(90, false); Vec.resize(91, true); Vec.resize(130, false); Count = 0; for (unsigned i = Vec.find_first(); i != -1u; i = Vec.find_next(i)) { ++Count; EXPECT_TRUE(Vec[i]); EXPECT_TRUE(Vec.test(i)); } EXPECT_EQ(Count, Vec.count()); EXPECT_EQ(Count, 42u); EXPECT_FALSE(Vec[0]); EXPECT_TRUE(Vec[32]); EXPECT_FALSE(Vec[60]); EXPECT_FALSE(Vec[129]); Vec.flip(60); EXPECT_TRUE(Vec[60]); EXPECT_EQ(Count + 1, Vec.count()); Vec.flip(60); EXPECT_FALSE(Vec[60]); EXPECT_EQ(Count, Vec.count()); Vec.reset(32); EXPECT_FALSE(Vec[32]); EXPECT_EQ(Count - 1, Vec.count()); Vec.set(32); EXPECT_TRUE(Vec[32]); EXPECT_EQ(Count, Vec.count()); Vec.flip(); EXPECT_EQ(Vec.size() - Count, Vec.count()); Vec.reset(); EXPECT_EQ(0U, Vec.count()); EXPECT_EQ(130U, Vec.size()); EXPECT_FALSE(Vec.any()); EXPECT_FALSE(Vec.all()); EXPECT_TRUE(Vec.none()); EXPECT_FALSE(Vec.empty()); Vec.flip(); EXPECT_EQ(130U, Vec.count()); EXPECT_EQ(130U, Vec.size()); EXPECT_TRUE(Vec.any()); EXPECT_TRUE(Vec.all()); EXPECT_FALSE(Vec.none()); EXPECT_FALSE(Vec.empty()); Vec.resize(64); EXPECT_EQ(64U, Vec.count()); EXPECT_EQ(64U, Vec.size()); EXPECT_TRUE(Vec.any()); EXPECT_TRUE(Vec.all()); EXPECT_FALSE(Vec.none()); EXPECT_FALSE(Vec.empty()); Vec.flip(); EXPECT_EQ(0U, Vec.count()); EXPECT_EQ(64U, Vec.size()); EXPECT_FALSE(Vec.any()); EXPECT_FALSE(Vec.all()); EXPECT_TRUE(Vec.none()); EXPECT_FALSE(Vec.empty()); Inv = TypeParam().flip(); EXPECT_EQ(0U, Inv.count()); EXPECT_EQ(0U, Inv.size()); EXPECT_FALSE(Inv.any()); EXPECT_TRUE(Inv.all()); EXPECT_TRUE(Inv.none()); EXPECT_TRUE(Inv.empty()); Vec.clear(); EXPECT_EQ(0U, Vec.count()); EXPECT_EQ(0U, Vec.size()); EXPECT_FALSE(Vec.any()); EXPECT_TRUE(Vec.all()); EXPECT_TRUE(Vec.none()); EXPECT_TRUE(Vec.empty()); } TYPED_TEST(BitVectorTest, CompoundAssignment) { TypeParam A; A.resize(10); A.set(4); A.set(7); TypeParam B; B.resize(50); B.set(5); B.set(18); A |= B; EXPECT_TRUE(A.test(4)); EXPECT_TRUE(A.test(5)); EXPECT_TRUE(A.test(7)); EXPECT_TRUE(A.test(18)); EXPECT_EQ(4U, A.count()); EXPECT_EQ(50U, A.size()); B.resize(10); B.set(); B.reset(2); B.reset(7); A &= B; EXPECT_FALSE(A.test(2)); EXPECT_FALSE(A.test(7)); EXPECT_EQ(2U, A.count()); EXPECT_EQ(50U, A.size()); B.resize(100); B.set(); A ^= B; EXPECT_TRUE(A.test(2)); EXPECT_TRUE(A.test(7)); EXPECT_EQ(98U, A.count()); EXPECT_EQ(100U, A.size()); } TYPED_TEST(BitVectorTest, ProxyIndex) { TypeParam Vec(3); EXPECT_TRUE(Vec.none()); Vec[0] = Vec[1] = Vec[2] = true; EXPECT_EQ(Vec.size(), Vec.count()); Vec[2] = Vec[1] = Vec[0] = false; EXPECT_TRUE(Vec.none()); } TYPED_TEST(BitVectorTest, PortableBitMask) { TypeParam A; const uint32_t Mask1[] = { 0x80000000, 6, 5 }; A.resize(10); A.setBitsInMask(Mask1, 2); EXPECT_EQ(10u, A.size()); EXPECT_FALSE(A.test(0)); A.resize(32); A.setBitsInMask(Mask1, 2); EXPECT_FALSE(A.test(0)); EXPECT_TRUE(A.test(31)); EXPECT_EQ(1u, A.count()); A.resize(33); A.setBitsInMask(Mask1, 1); EXPECT_EQ(1u, A.count()); A.setBitsInMask(Mask1, 2); EXPECT_EQ(1u, A.count()); A.resize(34); A.setBitsInMask(Mask1, 2); EXPECT_EQ(2u, A.count()); A.resize(65); A.setBitsInMask(Mask1, 3); EXPECT_EQ(4u, A.count()); A.setBitsNotInMask(Mask1, 1); EXPECT_EQ(32u+3u, A.count()); A.setBitsNotInMask(Mask1, 3); EXPECT_EQ(65u, A.count()); A.resize(96); EXPECT_EQ(65u, A.count()); A.clear(); A.resize(128); A.setBitsNotInMask(Mask1, 3); EXPECT_EQ(96u-5u, A.count()); A.clearBitsNotInMask(Mask1, 1); EXPECT_EQ(64-4u, A.count()); } TYPED_TEST(BitVectorTest, BinOps) { TypeParam A; TypeParam B; A.resize(65); EXPECT_FALSE(A.anyCommon(B)); EXPECT_FALSE(B.anyCommon(B)); B.resize(64); A.set(64); EXPECT_FALSE(A.anyCommon(B)); EXPECT_FALSE(B.anyCommon(A)); B.set(63); EXPECT_FALSE(A.anyCommon(B)); EXPECT_FALSE(B.anyCommon(A)); A.set(63); EXPECT_TRUE(A.anyCommon(B)); EXPECT_TRUE(B.anyCommon(A)); B.resize(70); B.set(64); B.reset(63); A.resize(64); EXPECT_FALSE(A.anyCommon(B)); EXPECT_FALSE(B.anyCommon(A)); } TYPED_TEST(BitVectorTest, RangeOps) { TypeParam A; A.resize(256); A.reset(); A.set(1, 255); EXPECT_FALSE(A.test(0)); EXPECT_TRUE( A.test(1)); EXPECT_TRUE( A.test(23)); EXPECT_TRUE( A.test(254)); EXPECT_FALSE(A.test(255)); TypeParam B; B.resize(256); B.set(); B.reset(1, 255); EXPECT_TRUE( B.test(0)); EXPECT_FALSE(B.test(1)); EXPECT_FALSE(B.test(23)); EXPECT_FALSE(B.test(254)); EXPECT_TRUE( B.test(255)); TypeParam C; C.resize(3); C.reset(); C.set(0, 1); EXPECT_TRUE(C.test(0)); EXPECT_FALSE( C.test(1)); EXPECT_FALSE( C.test(2)); TypeParam D; D.resize(3); D.set(); D.reset(0, 1); EXPECT_FALSE(D.test(0)); EXPECT_TRUE( D.test(1)); EXPECT_TRUE( D.test(2)); TypeParam E; E.resize(128); E.reset(); E.set(1, 33); EXPECT_FALSE(E.test(0)); EXPECT_TRUE( E.test(1)); EXPECT_TRUE( E.test(32)); EXPECT_FALSE(E.test(33)); TypeParam BufferOverrun; unsigned size = sizeof(unsigned long) * 8; BufferOverrun.resize(size); BufferOverrun.reset(0, size); BufferOverrun.set(0, size); } TYPED_TEST(BitVectorTest, CompoundTestReset) { TypeParam A(50, true); TypeParam B(50, false); TypeParam C(100, true); TypeParam D(100, false); EXPECT_FALSE(A.test(A)); EXPECT_TRUE(A.test(B)); EXPECT_FALSE(A.test(C)); EXPECT_TRUE(A.test(D)); EXPECT_FALSE(B.test(A)); EXPECT_FALSE(B.test(B)); EXPECT_FALSE(B.test(C)); EXPECT_FALSE(B.test(D)); EXPECT_TRUE(C.test(A)); EXPECT_TRUE(C.test(B)); EXPECT_FALSE(C.test(C)); EXPECT_TRUE(C.test(D)); A.reset(B); A.reset(D); EXPECT_TRUE(A.all()); A.reset(A); EXPECT_TRUE(A.none()); A.set(); A.reset(C); EXPECT_TRUE(A.none()); A.set(); C.reset(A); EXPECT_EQ(50, C.find_first()); C.reset(C); EXPECT_TRUE(C.none()); } } #endif
//===- llvm/unittest/ADT/BitVectorTest.cpp - BitVector tests --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // Some of these tests fail on PowerPC for unknown reasons. #ifndef __ppc__ #include "llvm/ADT/BitVector.h" #include "llvm/ADT/SmallBitVector.h" #include "gtest/gtest.h" using namespace llvm; namespace { // Test fixture template <typename T> class BitVectorTest : public ::testing::Test { }; // Test both BitVector and SmallBitVector with the same suite of tests. typedef ::testing::Types<BitVector, SmallBitVector> BitVectorTestTypes; TYPED_TEST_CASE(BitVectorTest, BitVectorTestTypes); TYPED_TEST(BitVectorTest, TrivialOperation) { TypeParam Vec; EXPECT_EQ(0U, Vec.count()); EXPECT_EQ(0U, Vec.size()); EXPECT_FALSE(Vec.any()); EXPECT_TRUE(Vec.all()); EXPECT_TRUE(Vec.none()); EXPECT_TRUE(Vec.empty()); Vec.resize(5, true); EXPECT_EQ(5U, Vec.count()); EXPECT_EQ(5U, Vec.size()); EXPECT_TRUE(Vec.any()); EXPECT_TRUE(Vec.all()); EXPECT_FALSE(Vec.none()); EXPECT_FALSE(Vec.empty()); Vec.resize(11); EXPECT_EQ(5U, Vec.count()); EXPECT_EQ(11U, Vec.size()); EXPECT_TRUE(Vec.any()); EXPECT_FALSE(Vec.all()); EXPECT_FALSE(Vec.none()); EXPECT_FALSE(Vec.empty()); TypeParam Inv = Vec; Inv.flip(); EXPECT_EQ(6U, Inv.count()); EXPECT_EQ(11U, Inv.size()); EXPECT_TRUE(Inv.any()); EXPECT_FALSE(Inv.all()); EXPECT_FALSE(Inv.none()); EXPECT_FALSE(Inv.empty()); EXPECT_FALSE(Inv == Vec); EXPECT_TRUE(Inv != Vec); Vec.flip(); EXPECT_TRUE(Inv == Vec); EXPECT_FALSE(Inv != Vec); // Add some "interesting" data to Vec. Vec.resize(23, true); Vec.resize(25, false); Vec.resize(26, true); Vec.resize(29, false); Vec.resize(33, true); Vec.resize(57, false); unsigned Count = 0; for (unsigned i = Vec.find_first(); i != -1u; i = Vec.find_next(i)) { ++Count; EXPECT_TRUE(Vec[i]); EXPECT_TRUE(Vec.test(i)); } EXPECT_EQ(Count, Vec.count()); EXPECT_EQ(Count, 23u); EXPECT_FALSE(Vec[0]); EXPECT_TRUE(Vec[32]); EXPECT_FALSE(Vec[56]); Vec.resize(61, false); TypeParam Copy = Vec; TypeParam Alt(3, false); Alt.resize(6, true); std::swap(Alt, Vec); EXPECT_TRUE(Copy == Alt); EXPECT_TRUE(Vec.size() == 6); EXPECT_TRUE(Vec.count() == 3); EXPECT_TRUE(Vec.find_first() == 3); std::swap(Copy, Vec); // Add some more "interesting" data. Vec.resize(68, true); Vec.resize(78, false); Vec.resize(89, true); Vec.resize(90, false); Vec.resize(91, true); Vec.resize(130, false); Count = 0; for (unsigned i = Vec.find_first(); i != -1u; i = Vec.find_next(i)) { ++Count; EXPECT_TRUE(Vec[i]); EXPECT_TRUE(Vec.test(i)); } EXPECT_EQ(Count, Vec.count()); EXPECT_EQ(Count, 42u); EXPECT_FALSE(Vec[0]); EXPECT_TRUE(Vec[32]); EXPECT_FALSE(Vec[60]); EXPECT_FALSE(Vec[129]); Vec.flip(60); EXPECT_TRUE(Vec[60]); EXPECT_EQ(Count + 1, Vec.count()); Vec.flip(60); EXPECT_FALSE(Vec[60]); EXPECT_EQ(Count, Vec.count()); Vec.reset(32); EXPECT_FALSE(Vec[32]); EXPECT_EQ(Count - 1, Vec.count()); Vec.set(32); EXPECT_TRUE(Vec[32]); EXPECT_EQ(Count, Vec.count()); Vec.flip(); EXPECT_EQ(Vec.size() - Count, Vec.count()); Vec.reset(); EXPECT_EQ(0U, Vec.count()); EXPECT_EQ(130U, Vec.size()); EXPECT_FALSE(Vec.any()); EXPECT_FALSE(Vec.all()); EXPECT_TRUE(Vec.none()); EXPECT_FALSE(Vec.empty()); Vec.flip(); EXPECT_EQ(130U, Vec.count()); EXPECT_EQ(130U, Vec.size()); EXPECT_TRUE(Vec.any()); EXPECT_TRUE(Vec.all()); EXPECT_FALSE(Vec.none()); EXPECT_FALSE(Vec.empty()); Vec.resize(64); EXPECT_EQ(64U, Vec.count()); EXPECT_EQ(64U, Vec.size()); EXPECT_TRUE(Vec.any()); EXPECT_TRUE(Vec.all()); EXPECT_FALSE(Vec.none()); EXPECT_FALSE(Vec.empty()); Vec.flip(); EXPECT_EQ(0U, Vec.count()); EXPECT_EQ(64U, Vec.size()); EXPECT_FALSE(Vec.any()); EXPECT_FALSE(Vec.all()); EXPECT_TRUE(Vec.none()); EXPECT_FALSE(Vec.empty()); Inv = TypeParam().flip(); EXPECT_EQ(0U, Inv.count()); EXPECT_EQ(0U, Inv.size()); EXPECT_FALSE(Inv.any()); EXPECT_TRUE(Inv.all()); EXPECT_TRUE(Inv.none()); EXPECT_TRUE(Inv.empty()); Vec.clear(); EXPECT_EQ(0U, Vec.count()); EXPECT_EQ(0U, Vec.size()); EXPECT_FALSE(Vec.any()); EXPECT_TRUE(Vec.all()); EXPECT_TRUE(Vec.none()); EXPECT_TRUE(Vec.empty()); } TYPED_TEST(BitVectorTest, CompoundAssignment) { TypeParam A; A.resize(10); A.set(4); A.set(7); TypeParam B; B.resize(50); B.set(5); B.set(18); A |= B; EXPECT_TRUE(A.test(4)); EXPECT_TRUE(A.test(5)); EXPECT_TRUE(A.test(7)); EXPECT_TRUE(A.test(18)); EXPECT_EQ(4U, A.count()); EXPECT_EQ(50U, A.size()); B.resize(10); B.set(); B.reset(2); B.reset(7); A &= B; EXPECT_FALSE(A.test(2)); EXPECT_FALSE(A.test(7)); EXPECT_EQ(2U, A.count()); EXPECT_EQ(50U, A.size()); B.resize(100); B.set(); A ^= B; EXPECT_TRUE(A.test(2)); EXPECT_TRUE(A.test(7)); EXPECT_EQ(98U, A.count()); EXPECT_EQ(100U, A.size()); } TYPED_TEST(BitVectorTest, ProxyIndex) { TypeParam Vec(3); EXPECT_TRUE(Vec.none()); Vec[0] = Vec[1] = Vec[2] = true; EXPECT_EQ(Vec.size(), Vec.count()); Vec[2] = Vec[1] = Vec[0] = false; EXPECT_TRUE(Vec.none()); } TYPED_TEST(BitVectorTest, PortableBitMask) { TypeParam A; const uint32_t Mask1[] = { 0x80000000, 6, 5 }; A.resize(10); A.setBitsInMask(Mask1, 1); EXPECT_EQ(10u, A.size()); EXPECT_FALSE(A.test(0)); A.resize(32); A.setBitsInMask(Mask1, 1); EXPECT_FALSE(A.test(0)); EXPECT_TRUE(A.test(31)); EXPECT_EQ(1u, A.count()); A.resize(33); A.setBitsInMask(Mask1, 1); EXPECT_EQ(1u, A.count()); A.setBitsInMask(Mask1, 2); EXPECT_EQ(1u, A.count()); A.resize(34); A.setBitsInMask(Mask1, 2); EXPECT_EQ(2u, A.count()); A.resize(65); A.setBitsInMask(Mask1, 3); EXPECT_EQ(4u, A.count()); A.setBitsNotInMask(Mask1, 1); EXPECT_EQ(32u+3u, A.count()); A.setBitsNotInMask(Mask1, 3); EXPECT_EQ(65u, A.count()); A.resize(96); EXPECT_EQ(65u, A.count()); A.clear(); A.resize(128); A.setBitsNotInMask(Mask1, 3); EXPECT_EQ(96u-5u, A.count()); A.clearBitsNotInMask(Mask1, 1); EXPECT_EQ(64-4u, A.count()); } TYPED_TEST(BitVectorTest, BinOps) { TypeParam A; TypeParam B; A.resize(65); EXPECT_FALSE(A.anyCommon(B)); EXPECT_FALSE(B.anyCommon(B)); B.resize(64); A.set(64); EXPECT_FALSE(A.anyCommon(B)); EXPECT_FALSE(B.anyCommon(A)); B.set(63); EXPECT_FALSE(A.anyCommon(B)); EXPECT_FALSE(B.anyCommon(A)); A.set(63); EXPECT_TRUE(A.anyCommon(B)); EXPECT_TRUE(B.anyCommon(A)); B.resize(70); B.set(64); B.reset(63); A.resize(64); EXPECT_FALSE(A.anyCommon(B)); EXPECT_FALSE(B.anyCommon(A)); } TYPED_TEST(BitVectorTest, RangeOps) { TypeParam A; A.resize(256); A.reset(); A.set(1, 255); EXPECT_FALSE(A.test(0)); EXPECT_TRUE( A.test(1)); EXPECT_TRUE( A.test(23)); EXPECT_TRUE( A.test(254)); EXPECT_FALSE(A.test(255)); TypeParam B; B.resize(256); B.set(); B.reset(1, 255); EXPECT_TRUE( B.test(0)); EXPECT_FALSE(B.test(1)); EXPECT_FALSE(B.test(23)); EXPECT_FALSE(B.test(254)); EXPECT_TRUE( B.test(255)); TypeParam C; C.resize(3); C.reset(); C.set(0, 1); EXPECT_TRUE(C.test(0)); EXPECT_FALSE( C.test(1)); EXPECT_FALSE( C.test(2)); TypeParam D; D.resize(3); D.set(); D.reset(0, 1); EXPECT_FALSE(D.test(0)); EXPECT_TRUE( D.test(1)); EXPECT_TRUE( D.test(2)); TypeParam E; E.resize(128); E.reset(); E.set(1, 33); EXPECT_FALSE(E.test(0)); EXPECT_TRUE( E.test(1)); EXPECT_TRUE( E.test(32)); EXPECT_FALSE(E.test(33)); TypeParam BufferOverrun; unsigned size = sizeof(unsigned long) * 8; BufferOverrun.resize(size); BufferOverrun.reset(0, size); BufferOverrun.set(0, size); } TYPED_TEST(BitVectorTest, CompoundTestReset) { TypeParam A(50, true); TypeParam B(50, false); TypeParam C(100, true); TypeParam D(100, false); EXPECT_FALSE(A.test(A)); EXPECT_TRUE(A.test(B)); EXPECT_FALSE(A.test(C)); EXPECT_TRUE(A.test(D)); EXPECT_FALSE(B.test(A)); EXPECT_FALSE(B.test(B)); EXPECT_FALSE(B.test(C)); EXPECT_FALSE(B.test(D)); EXPECT_TRUE(C.test(A)); EXPECT_TRUE(C.test(B)); EXPECT_FALSE(C.test(C)); EXPECT_TRUE(C.test(D)); A.reset(B); A.reset(D); EXPECT_TRUE(A.all()); A.reset(A); EXPECT_TRUE(A.none()); A.set(); A.reset(C); EXPECT_TRUE(A.none()); A.set(); C.reset(A); EXPECT_EQ(50, C.find_first()); C.reset(C); EXPECT_TRUE(C.none()); } } #endif
Fix BitVectorTest on 32-bit hosts after r247972. We can't apply two words of 32-bit mask in the small case where the internal storage is just one 32-bit word.
Fix BitVectorTest on 32-bit hosts after r247972. We can't apply two words of 32-bit mask in the small case where the internal storage is just one 32-bit word. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@247974 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm
8a21e77eb8a1c7cfbd284d3f471a102918668d91
src/IntersonArrayCxxImagingContainer.cxx
src/IntersonArrayCxxImagingContainer.cxx
/*========================================================================= Library: IntersonArray Copyright Kitware Inc. 28 Corporate Drive, Clifton Park, NY, 12065, USA. 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. =========================================================================*/ #pragma unmanaged #include "IntersonArrayCxxImagingContainer.h" #include <iostream> #pragma managed #include <vcclr.h> #include <msclr/marshal_cppstd.h> #include <msclr/auto_gcroot.h> #using "IntersonArray.dll" namespace IntersonArrayCxx { namespace Imaging { // // Begin Capture // ref class NewRFImageHandler { public: typedef Container::NewRFImageCallbackType NewRFImageCallbackType; typedef IntersonArrayCxx::Imaging::Container::RFPixelType RFPixelType; typedef IntersonArrayCxx::Imaging::Container::RFImagePixelType RFImagePixelType; typedef cli::array< RFPixelType, 2 > RFArrayType; NewRFImageHandler( RFArrayType ^managedRFBuffer ): NewRFImageCallback( NULL ), NewRFImageCallbackClientData( NULL ), bufferWidth( Container::MAX_RFSAMPLES ), bufferHeight( Container::MAX_RFSAMPLES ), NativeRFBuffer(new RFImagePixelType[Container::MAX_RFSAMPLES * Container::NBOFLINES] ), ManagedRFBuffer( managedRFBuffer ) { } ~NewRFImageHandler() { delete [] NativeRFBuffer; } void HandleNewRFImage( IntersonArray::Imaging::Capture ^scan2D, System::EventArgs ^eventArgs ) { if ( this->NewRFImageCallback != NULL ) { for ( int ii = 0; ii < bufferHeight; ++ii ) { for ( int jj = 0; jj < bufferWidth; ++jj ) { this->NativeRFBuffer[bufferWidth * ii + jj] = (short) this->ManagedRFBuffer[ii, jj]; } } this->NewRFImageCallback( this->NativeRFBuffer, this->NewRFImageCallbackClientData ); } } void SetImageSize( int width, int height ) { bufferWidth = width; bufferHeight = height; } void SetNewRFImageCallback( NewRFImageCallbackType callback, void *clientData ) { this->NewRFImageCallback = callback; this->NewRFImageCallbackClientData = clientData; } private: NewRFImageCallbackType NewRFImageCallback; void * NewRFImageCallbackClientData; RFImagePixelType * NativeRFBuffer; RFArrayType ^ ManagedRFBuffer; int bufferWidth; int bufferHeight; }; ref class NewImageHandler { public: typedef Container::NewImageCallbackType NewImageCallbackType; typedef IntersonArrayCxx::Imaging::Container::PixelType PixelType; typedef cli::array< byte, 2 > ArrayType; NewImageHandler( ArrayType ^managedBuffer ): NewImageCallback( NULL ), NewImageCallbackClientData( NULL ), bufferWidth( Container::MAX_SAMPLES ), bufferHeight( Container::MAX_SAMPLES ), NativeBuffer( new PixelType[Container::MAX_SAMPLES * Container::MAX_SAMPLES] ), ManagedBuffer( managedBuffer ) { } ~NewImageHandler() { delete [] NativeBuffer; } void HandleNewImage( IntersonArray::Imaging::Capture ^scan2D, System::EventArgs ^eventArgs ) { if ( this->NewImageCallback != NULL ) { for ( int ii = 0; ii < bufferHeight; ++ii ) { for ( int jj = 0; jj < bufferWidth; ++jj ) { this->NativeBuffer[bufferWidth * ii + jj] = this->ManagedBuffer[ii, jj]; } } this->NewImageCallback( this->NativeBuffer, this->NewImageCallbackClientData ); } } void SetImageSize( int width, int height ) { bufferWidth = width; bufferHeight = height; } void SetNewImageCallback( NewImageCallbackType callback, void *clientData ) { this->NewImageCallback = callback; this->NewImageCallbackClientData = clientData; } private: NewImageCallbackType NewImageCallback; void * NewImageCallbackClientData; PixelType * NativeBuffer; ArrayType ^ ManagedBuffer; int bufferWidth; int bufferHeight; }; // End Capture class ContainerImpl { public: typedef cli::array< Container::PixelType, 2 > ArrayType; typedef cli::array< Container::RFPixelType, 2 > RFArrayType; typedef Container::NewImageCallbackType NewImageCallbackType; typedef Container::NewRFImageCallbackType NewRFImageCallbackType; ContainerImpl() { WrappedScanConverter = gcnew IntersonArray::Imaging::ScanConverter(); WrappedImageBuilding = gcnew IntersonArray::Imaging::ImageBuilding(); WrappedCapture = gcnew IntersonArray::Imaging::Capture(); Buffer = gcnew ArrayType( Container::MAX_SAMPLES, Container::MAX_SAMPLES); Handler = gcnew NewImageHandler( Buffer ); HandlerDelegate = gcnew IntersonArray::Imaging::Capture::NewImageHandler( Handler, & NewImageHandler::HandleNewImage ); WrappedCapture->NewImageTick += HandlerDelegate; RFBuffer = gcnew RFArrayType(Container::NBOFLINES , Container::MAX_RFSAMPLES); RFHandler = gcnew NewRFImageHandler( RFBuffer ); RFHandlerDelegate = gcnew IntersonArray::Imaging::Capture::NewImageHandler( RFHandler, & NewRFImageHandler::HandleNewRFImage ); } ~ContainerImpl() { WrappedCapture->NewImageTick -= RFHandlerDelegate; WrappedCapture->NewImageTick -= HandlerDelegate; } bool GetCompound() { return WrappedScanConverter->Compound; } void SetCompound( bool value ) { WrappedScanConverter->Compound = value; } bool GetDoubler() { return WrappedScanConverter->Doubler; } void SetDoubler( bool value ) { WrappedScanConverter->Doubler = value; } int GetHeightScan() const { return WrappedScanConverter->HeightScan; } float GetMmPerPixel() const { return WrappedScanConverter->MmPerPixel; } double GetTrueDepth() const { return WrappedScanConverter->TrueDepth; } int GetWidthScan() const { return WrappedScanConverter->WidthScan; } int GetZeroOfYScale() const { return WrappedScanConverter->ZeroOfYScale; } Container::ScanConverterError HardInitScanConverter( int depth, int widthScan, int heightScan, int steering ) { return static_cast< Container::ScanConverterError >( WrappedScanConverter->HardInitScanConverter( depth, widthScan, heightScan, steering, WrappedCapture.get(), WrappedImageBuilding.get() ) ); } Container::ScanConverterError IdleInitScanConverter( int depth, int widthScan, int heightScan, short idleId, int idleSteering, bool idleDoubler, bool idleCompound, int idleCompoundAngle ) { return static_cast< Container::ScanConverterError >( WrappedScanConverter->IdleInitScanConverter( depth, widthScan, heightScan, idleId, idleSteering, idleDoubler, idleCompound, idleCompoundAngle, WrappedImageBuilding.get() ) ); } // // Begin Capture // bool GetFrameAvg() { return WrappedCapture->FrameAvg; } void SetFrameAvg( bool value) { WrappedCapture->FrameAvg = value; } bool GetRFData() { return WrappedCapture->RFData; } void SetRFData( bool value ) { if (value){ this->hwControls->ReadFPGAVersion(); } WrappedCapture->RFData = value; //Set correct image handler if (value){ WrappedCapture->NewImageTick -= HandlerDelegate; WrappedCapture->NewImageTick += RFHandlerDelegate; } else{ WrappedCapture->NewImageTick -= RFHandlerDelegate; WrappedCapture->NewImageTick += HandlerDelegate; } } double GetScanOn() { return WrappedCapture->ScanOn; } void AbortScan() { WrappedCapture->AbortScan(); } void DisposeScan() { WrappedCapture->DisposeScan(); } void StartReadScan() { WrappedCapture->StartReadScan( (ArrayType ^)Buffer ); } void StartRFReadScan() { WrappedCapture->StartRFReadScan( (RFArrayType ^)RFBuffer ); } void StopReadScan() { WrappedCapture->StopReadScan(); } void SetNewImageCallback( NewImageCallbackType callback, void *clientData = 0 ) { this->Handler->SetNewImageCallback( callback, clientData ); this->Handler->SetImageSize( this->GetWidthScan(), this->GetHeightScan() ); } void SetNewRFImageCallback( NewRFImageCallbackType callback, void *clientData = 0 ) { this->RFHandler->SetNewRFImageCallback( callback, clientData ); this->RFHandler->SetImageSize(Container::MAX_RFSAMPLES, Container::NBOFLINES); } void SetHWControls(IntersonArrayCxx::Controls::HWControls * controls) { this->hwControls = controls; } // // Begin Wrapped ImageBuilding // private: IntersonArrayCxx::Controls::HWControls * hwControls; msclr::auto_gcroot< IntersonArray::Imaging::ScanConverter ^ > WrappedScanConverter; msclr::auto_gcroot< IntersonArray::Imaging::ImageBuilding ^ > WrappedImageBuilding; msclr::auto_gcroot< IntersonArray::Imaging::Capture ^ > WrappedCapture; gcroot< ArrayType ^ > Buffer; gcroot< RFArrayType ^ > RFBuffer; gcroot< NewImageHandler ^ > Handler; gcroot< NewRFImageHandler ^ > RFHandler; gcroot< IntersonArray::Imaging::Capture::NewImageHandler ^ > HandlerDelegate; gcroot< IntersonArray::Imaging::Capture::NewImageHandler ^ > RFHandlerDelegate; }; #pragma unmanaged Container ::Container(): Impl( new ContainerImpl() ) { } Container ::~Container() { delete Impl; } bool Container ::GetCompound() { return Impl->GetCompound(); } void Container ::SetCompound( bool value ) { Impl->SetCompound( value ); } bool Container ::GetDoubler() { return Impl->GetDoubler(); } void Container ::SetDoubler( bool value ) { Impl->SetDoubler( value ); } int Container ::GetHeightScan() const { return Impl->GetHeightScan(); } float Container ::GetMmPerPixel() const { return Impl->GetMmPerPixel(); } double Container ::GetTrueDepth() const { return Impl->GetMmPerPixel(); } int Container ::GetWidthScan() const { return Impl->GetWidthScan(); } int Container ::GetZeroOfYScale() const { return Impl->GetZeroOfYScale(); } Container::ScanConverterError Container ::HardInitScanConverter( int depth, int widthScan, int heightScan, int steering ) { return Impl->HardInitScanConverter( depth, widthScan, heightScan, steering ); } Container::ScanConverterError Container ::IdleInitScanConverter( int depth, int width, int height, short idleId, int idleSteering, bool idleDoubler, bool idleCompound, int idleCompoundAngle ) { return Impl->IdleInitScanConverter( depth, width, height, idleId, idleSteering, idleDoubler, idleCompound, idleCompoundAngle ); } // // Begin Capture // bool Container ::GetRFData() { return Impl->GetRFData(); } void Container ::SetRFData( bool transferOn ) { Impl->SetRFData( transferOn ); } bool Container ::GetFrameAvg() { return Impl->GetFrameAvg(); } void Container ::SetFrameAvg( bool doAveraging ) { Impl->SetFrameAvg( doAveraging ); } bool Container ::GetScanOn() const { return Impl->GetScanOn(); } void Container ::AbortScan() { Impl->AbortScan(); } void Container ::DisposeScan() { Impl->DisposeScan(); } void Container ::StartReadScan() { Impl->StartReadScan(); } void Container ::StartRFReadScan() { Impl->StartRFReadScan(); } void Container ::StopReadScan() { Impl->StopReadScan(); } void Container ::SetNewImageCallback( NewImageCallbackType callback, void *clientData ) { Impl->SetNewImageCallback( callback, clientData ); } void Container ::SetNewRFImageCallback( NewRFImageCallbackType callback, void *clientData ) { Impl->SetNewRFImageCallback( callback, clientData ); } void Container ::SetHWControls(IntersonArrayCxx::Controls::HWControls * controls) { Impl->SetHWControls(controls); } } // end namespace Imaging } // end namespace IntersonArrayCxx
/*========================================================================= Library: IntersonArray Copyright Kitware Inc. 28 Corporate Drive, Clifton Park, NY, 12065, USA. 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. =========================================================================*/ #pragma unmanaged #include "IntersonArrayCxxImagingContainer.h" #include <iostream> #pragma managed #include <vcclr.h> #include <msclr/marshal_cppstd.h> #include <msclr/auto_gcroot.h> #using "IntersonArray.dll" namespace IntersonArrayCxx { namespace Imaging { // // Begin Capture // ref class NewRFImageHandler { public: typedef Container::NewRFImageCallbackType NewRFImageCallbackType; typedef IntersonArrayCxx::Imaging::Container::RFPixelType RFPixelType; typedef IntersonArrayCxx::Imaging::Container::RFImagePixelType RFImagePixelType; typedef cli::array< RFPixelType, 2 > RFArrayType; NewRFImageHandler( RFArrayType ^managedRFBuffer ): NewRFImageCallback( NULL ), NewRFImageCallbackClientData( NULL ), bufferWidth( Container::MAX_RFSAMPLES ), bufferHeight( Container::NBOFLINES ), NativeRFBuffer(new RFImagePixelType[Container::MAX_RFSAMPLES * Container::NBOFLINES] ), ManagedRFBuffer( managedRFBuffer ) { } ~NewRFImageHandler() { delete [] NativeRFBuffer; } void HandleNewRFImage( IntersonArray::Imaging::Capture ^scan2D, System::EventArgs ^eventArgs ) { if ( this->NewRFImageCallback != NULL ) { for ( int ii = 0; ii < bufferHeight; ++ii ) { for ( int jj = 0; jj < bufferWidth; ++jj ) { this->NativeRFBuffer[bufferWidth * ii + jj] = (short) this->ManagedRFBuffer[ii, jj]; } } this->NewRFImageCallback( this->NativeRFBuffer, this->NewRFImageCallbackClientData ); } } void SetImageSize( int width, int height ) { //bufferWidth = width; //bufferHeight = height; } void SetNewRFImageCallback( NewRFImageCallbackType callback, void *clientData ) { this->NewRFImageCallback = callback; this->NewRFImageCallbackClientData = clientData; } private: NewRFImageCallbackType NewRFImageCallback; void * NewRFImageCallbackClientData; RFImagePixelType * NativeRFBuffer; RFArrayType ^ ManagedRFBuffer; int bufferWidth; int bufferHeight; }; ref class NewImageHandler { public: typedef Container::NewImageCallbackType NewImageCallbackType; typedef IntersonArrayCxx::Imaging::Container::PixelType PixelType; typedef cli::array< byte, 2 > ArrayType; NewImageHandler( ArrayType ^managedBuffer ): NewImageCallback( NULL ), NewImageCallbackClientData( NULL ), bufferWidth( Container::MAX_SAMPLES ), bufferHeight( Container::NBOFLINES ), NativeBuffer( new PixelType[Container::MAX_SAMPLES * Container::NBOFLINES ] ), ManagedBuffer( managedBuffer ) { std::cout << "Conatiner NBOFLINES: " << Container::NBOFLINES << std::endl; } ~NewImageHandler() { delete [] NativeBuffer; } void HandleNewImage( IntersonArray::Imaging::Capture ^scan2D, System::EventArgs ^eventArgs ) { if ( this->NewImageCallback != NULL ) { for ( int ii = 0; ii < bufferHeight; ++ii ) { for ( int jj = 0; jj < bufferWidth; ++jj ) { this->NativeBuffer[bufferWidth * ii + jj] = this->ManagedBuffer[ii, jj]; } } this->NewImageCallback( this->NativeBuffer, this->NewImageCallbackClientData ); } } void SetImageSize( int width, int height ) { // bufferWidth = width; // bufferHeight = height; } void SetNewImageCallback( NewImageCallbackType callback, void *clientData ) { this->NewImageCallback = callback; this->NewImageCallbackClientData = clientData; } private: NewImageCallbackType NewImageCallback; void * NewImageCallbackClientData; PixelType * NativeBuffer; ArrayType ^ ManagedBuffer; int bufferWidth; int bufferHeight; }; // End Capture class ContainerImpl { public: typedef cli::array< Container::PixelType, 2 > ArrayType; typedef cli::array< Container::RFPixelType, 2 > RFArrayType; typedef Container::NewImageCallbackType NewImageCallbackType; typedef Container::NewRFImageCallbackType NewRFImageCallbackType; ContainerImpl() { WrappedScanConverter = gcnew IntersonArray::Imaging::ScanConverter(); WrappedImageBuilding = gcnew IntersonArray::Imaging::ImageBuilding(); WrappedCapture = gcnew IntersonArray::Imaging::Capture(); Buffer = gcnew ArrayType( Container::NBOFLINES, Container::MAX_SAMPLES ); Handler = gcnew NewImageHandler( Buffer ); HandlerDelegate = gcnew IntersonArray::Imaging::Capture::NewImageHandler( Handler, & NewImageHandler::HandleNewImage ); WrappedCapture->NewImageTick += HandlerDelegate; RFBuffer = gcnew RFArrayType(Container::NBOFLINES , Container::MAX_RFSAMPLES); RFHandler = gcnew NewRFImageHandler( RFBuffer ); RFHandlerDelegate = gcnew IntersonArray::Imaging::Capture::NewImageHandler( RFHandler, & NewRFImageHandler::HandleNewRFImage ); } ~ContainerImpl() { WrappedCapture->NewImageTick -= RFHandlerDelegate; WrappedCapture->NewImageTick -= HandlerDelegate; } bool GetCompound() { return WrappedScanConverter->Compound; } void SetCompound( bool value ) { WrappedScanConverter->Compound = value; } bool GetDoubler() { return WrappedScanConverter->Doubler; } void SetDoubler( bool value ) { WrappedScanConverter->Doubler = value; } int GetHeightScan() const { return WrappedScanConverter->HeightScan; } float GetMmPerPixel() const { return WrappedScanConverter->MmPerPixel; } double GetTrueDepth() const { return WrappedScanConverter->TrueDepth; } int GetWidthScan() const { return WrappedScanConverter->WidthScan; } int GetZeroOfYScale() const { return WrappedScanConverter->ZeroOfYScale; } Container::ScanConverterError HardInitScanConverter( int depth, int widthScan, int heightScan, int steering ) { return static_cast< Container::ScanConverterError >( WrappedScanConverter->HardInitScanConverter( depth, widthScan, heightScan, steering, WrappedCapture.get(), WrappedImageBuilding.get() ) ); } Container::ScanConverterError IdleInitScanConverter( int depth, int widthScan, int heightScan, short idleId, int idleSteering, bool idleDoubler, bool idleCompound, int idleCompoundAngle ) { return static_cast< Container::ScanConverterError >( WrappedScanConverter->IdleInitScanConverter( depth, widthScan, heightScan, idleId, idleSteering, idleDoubler, idleCompound, idleCompoundAngle, WrappedImageBuilding.get() ) ); } // // Begin Capture // bool GetFrameAvg() { return WrappedCapture->FrameAvg; } void SetFrameAvg( bool value) { WrappedCapture->FrameAvg = value; } bool GetRFData() { return WrappedCapture->RFData; } void SetRFData( bool value ) { if (value){ this->hwControls->ReadFPGAVersion(); } WrappedCapture->RFData = value; //Set correct image handler if (value){ WrappedCapture->NewImageTick -= HandlerDelegate; WrappedCapture->NewImageTick += RFHandlerDelegate; } else{ WrappedCapture->NewImageTick -= RFHandlerDelegate; WrappedCapture->NewImageTick += HandlerDelegate; } } double GetScanOn() { return WrappedCapture->ScanOn; } void AbortScan() { WrappedCapture->AbortScan(); } void DisposeScan() { WrappedCapture->DisposeScan(); } void StartReadScan() { WrappedCapture->StartReadScan( (ArrayType ^)Buffer ); } void StartRFReadScan() { WrappedCapture->StartRFReadScan( (RFArrayType ^)RFBuffer ); } void StopReadScan() { WrappedCapture->StopReadScan(); } void SetNewImageCallback( NewImageCallbackType callback, void *clientData = 0 ) { this->Handler->SetNewImageCallback( callback, clientData ); //this->Handler->SetImageSize( this->GetWidthScan(), // this->GetHeightScan() ); } void SetNewRFImageCallback( NewRFImageCallbackType callback, void *clientData = 0 ) { this->RFHandler->SetNewRFImageCallback( callback, clientData ); this->RFHandler->SetImageSize(Container::MAX_RFSAMPLES, Container::NBOFLINES); } void SetHWControls(IntersonArrayCxx::Controls::HWControls * controls) { this->hwControls = controls; } // // Begin Wrapped ImageBuilding // private: IntersonArrayCxx::Controls::HWControls * hwControls; msclr::auto_gcroot< IntersonArray::Imaging::ScanConverter ^ > WrappedScanConverter; msclr::auto_gcroot< IntersonArray::Imaging::ImageBuilding ^ > WrappedImageBuilding; msclr::auto_gcroot< IntersonArray::Imaging::Capture ^ > WrappedCapture; gcroot< ArrayType ^ > Buffer; gcroot< RFArrayType ^ > RFBuffer; gcroot< NewImageHandler ^ > Handler; gcroot< NewRFImageHandler ^ > RFHandler; gcroot< IntersonArray::Imaging::Capture::NewImageHandler ^ > HandlerDelegate; gcroot< IntersonArray::Imaging::Capture::NewImageHandler ^ > RFHandlerDelegate; }; #pragma unmanaged Container ::Container(): Impl( new ContainerImpl() ) { } Container ::~Container() { delete Impl; } bool Container ::GetCompound() { return Impl->GetCompound(); } void Container ::SetCompound( bool value ) { Impl->SetCompound( value ); } bool Container ::GetDoubler() { return Impl->GetDoubler(); } void Container ::SetDoubler( bool value ) { Impl->SetDoubler( value ); } int Container ::GetHeightScan() const { return Impl->GetHeightScan(); } float Container ::GetMmPerPixel() const { return Impl->GetMmPerPixel(); } double Container ::GetTrueDepth() const { return Impl->GetMmPerPixel(); } int Container ::GetWidthScan() const { return Impl->GetWidthScan(); } int Container ::GetZeroOfYScale() const { return Impl->GetZeroOfYScale(); } Container::ScanConverterError Container ::HardInitScanConverter( int depth, int widthScan, int heightScan, int steering ) { return Impl->HardInitScanConverter( depth, widthScan, heightScan, steering ); } Container::ScanConverterError Container ::IdleInitScanConverter( int depth, int width, int height, short idleId, int idleSteering, bool idleDoubler, bool idleCompound, int idleCompoundAngle ) { return Impl->IdleInitScanConverter( depth, width, height, idleId, idleSteering, idleDoubler, idleCompound, idleCompoundAngle ); } // // Begin Capture // bool Container ::GetRFData() { return Impl->GetRFData(); } void Container ::SetRFData( bool transferOn ) { Impl->SetRFData( transferOn ); } bool Container ::GetFrameAvg() { return Impl->GetFrameAvg(); } void Container ::SetFrameAvg( bool doAveraging ) { Impl->SetFrameAvg( doAveraging ); } bool Container ::GetScanOn() const { return Impl->GetScanOn(); } void Container ::AbortScan() { Impl->AbortScan(); } void Container ::DisposeScan() { Impl->DisposeScan(); } void Container ::StartReadScan() { Impl->StartReadScan(); } void Container ::StartRFReadScan() { Impl->StartRFReadScan(); } void Container ::StopReadScan() { Impl->StopReadScan(); } void Container ::SetNewImageCallback( NewImageCallbackType callback, void *clientData ) { Impl->SetNewImageCallback( callback, clientData ); } void Container ::SetNewRFImageCallback( NewRFImageCallbackType callback, void *clientData ) { Impl->SetNewRFImageCallback( callback, clientData ); } void Container ::SetHWControls(IntersonArrayCxx::Controls::HWControls * controls) { Impl->SetHWControls(controls); } } // end namespace Imaging } // end namespace IntersonArrayCxx
Fix Buffer Size
Fix Buffer Size The buffer size in the Bmode image was to large. The buffer size is unaffacted by scanWidth and scanHeight in the ScanConverter and appers to have a fixed size of NBOLINES x MAX_SAMPLES. Now teh BMode images is received at full depth and the image size does not ahve to be set to MAX_SMAPLES/2.
C++
apache-2.0
KitwareMedical/IntersonArraySDKCxx
c04b650e7cbcdee53b07f71cb1428182133c21fc
src/Nazara/Shader/Ast/ExpressionType.cpp
src/Nazara/Shader/Ast/ExpressionType.cpp
// Copyright (C) 2022 Jérôme "Lynix" Leclercq ([email protected]) // This file is part of the "Nazara Engine - Shader module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Shader/Ast/ExpressionType.hpp> #include <Nazara/Shader/Ast/AstCloner.hpp> #include <Nazara/Shader/Ast/AstCompare.hpp> #include <Nazara/Shader/Debug.hpp> namespace Nz::ShaderAst { AliasType::AliasType(const AliasType& alias) : aliasIndex(alias.aliasIndex) { assert(alias.targetType); targetType = std::make_unique<ContainedType>(*alias.targetType); } AliasType& AliasType::operator=(const AliasType& alias) { aliasIndex = alias.aliasIndex; assert(alias.targetType); targetType = std::make_unique<ContainedType>(*alias.targetType); return *this; } bool AliasType::operator==(const AliasType& rhs) const { assert(targetType); assert(rhs.targetType); if (aliasIndex != rhs.aliasIndex) return false; if (targetType->type != rhs.targetType->type) return false; return true; } ArrayType::ArrayType(const ArrayType& array) : length(array.length) { assert(array.containedType); containedType = std::make_unique<ContainedType>(*array.containedType); } ArrayType& ArrayType::operator=(const ArrayType& array) { assert(array.containedType); containedType = std::make_unique<ContainedType>(*array.containedType); length = array.length; return *this; } bool ArrayType::operator==(const ArrayType& rhs) const { assert(containedType); assert(rhs.containedType); if (length != rhs.length) return false; if (containedType->type != rhs.containedType->type) return false; return true; } MethodType::MethodType(const MethodType& methodType) : methodIndex(methodType.methodIndex) { assert(methodType.objectType); objectType = std::make_unique<ContainedType>(*methodType.objectType); } MethodType& MethodType::operator=(const MethodType& methodType) { assert(methodType.objectType); methodIndex = methodType.methodIndex; objectType = std::make_unique<ContainedType>(*methodType.objectType); return *this; } bool MethodType::operator==(const MethodType& rhs) const { assert(objectType); assert(rhs.objectType); return objectType->type == rhs.objectType->type && methodIndex == rhs.methodIndex; } std::string ToString(const AliasType& type, const Stringifier& stringifier) { std::string str = "alias "; if (stringifier.aliasStringifier) str += stringifier.aliasStringifier(type.aliasIndex); else { str += "#"; str += std::to_string(type.aliasIndex); } str += " -> "; str += ToString(type.targetType->type); return str; } std::string ToString(const ArrayType& type, const Stringifier& stringifier) { std::string str = "array["; str += ToString(type.containedType->type, stringifier); str += ", "; str += std::to_string(type.length); str += "]"; return str; } std::string ShaderAst::ToString(const ExpressionType& type, const Stringifier& stringifier) { return std::visit([&](auto&& arg) { return ToString(arg, stringifier); }, type); } std::string ToString(const FunctionType& /*type*/, const Stringifier& /*stringifier*/) { return "<function type>"; } std::string ToString(const IntrinsicFunctionType& /*type*/, const Stringifier& /*stringifier*/) { return "<intrinsic function type>"; } std::string ToString(const MatrixType& type, const Stringifier& /*stringifier*/) { std::string str = "mat"; if (type.columnCount == type.rowCount) str += std::to_string(type.columnCount); else { str += std::to_string(type.columnCount); str += "x"; str += std::to_string(type.rowCount); } str += "["; str += ToString(type.type); str += "]"; return str; } std::string ToString(const MethodType& type, const Stringifier& /*stringifier*/) { return "<method of object " + ToString(type.objectType->type) + " type>"; } std::string ToString(NoType /*type*/, const Stringifier& /*stringifier*/) { return "()"; } std::string ToString(PrimitiveType type, const Stringifier& /*stringifier*/) { switch (type) { case ShaderAst::PrimitiveType::Boolean: return "bool"; case ShaderAst::PrimitiveType::Float32: return "f32"; case ShaderAst::PrimitiveType::Int32: return "i32"; case ShaderAst::PrimitiveType::UInt32: return "u32"; case ShaderAst::PrimitiveType::String: return "string"; } return "<unhandled primitive type>"; } std::string ToString(const SamplerType& type, const Stringifier& /*stringifier*/) { std::string str = "sampler"; switch (type.dim) { case ImageType::E1D: str += "1D"; break; case ImageType::E1D_Array: str += "1DArray"; break; case ImageType::E2D: str += "2D"; break; case ImageType::E2D_Array: str += "2DArray"; break; case ImageType::E3D: str += "3D"; break; case ImageType::Cubemap: str += "Cube"; break; } str += "["; str += ToString(type.sampledType); str += "]"; return str; } std::string ToString(const StructType& type, const Stringifier& stringifier) { if (stringifier.structStringifier) return "struct " + stringifier.structStringifier(type.structIndex); else return "struct #" + std::to_string(type.structIndex); } std::string ToString(const Type& type, const Stringifier& stringifier) { if (stringifier.typeStringifier) return "type " + stringifier.typeStringifier(type.typeIndex); else return "type #" + std::to_string(type.typeIndex); } std::string ToString(const UniformType& type, const Stringifier& stringifier) { std::string str = "uniform["; str += ToString(type.containedType, stringifier); str += "]"; return str; } std::string ToString(const VectorType& type, const Stringifier& /*stringifier*/) { std::string str = "vec"; str += std::to_string(type.componentCount); str += "["; str += ToString(type.type); str += "]"; return str; } }
// Copyright (C) 2022 Jérôme "Lynix" Leclercq ([email protected]) // This file is part of the "Nazara Engine - Shader module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Shader/Ast/ExpressionType.hpp> #include <Nazara/Shader/Ast/AstCloner.hpp> #include <Nazara/Shader/Ast/AstCompare.hpp> #include <Nazara/Shader/Debug.hpp> namespace Nz::ShaderAst { AliasType::AliasType(const AliasType& alias) : aliasIndex(alias.aliasIndex) { assert(alias.targetType); targetType = std::make_unique<ContainedType>(*alias.targetType); } AliasType& AliasType::operator=(const AliasType& alias) { aliasIndex = alias.aliasIndex; assert(alias.targetType); targetType = std::make_unique<ContainedType>(*alias.targetType); return *this; } bool AliasType::operator==(const AliasType& rhs) const { assert(targetType); assert(rhs.targetType); if (aliasIndex != rhs.aliasIndex) return false; if (targetType->type != rhs.targetType->type) return false; return true; } ArrayType::ArrayType(const ArrayType& array) : length(array.length) { assert(array.containedType); containedType = std::make_unique<ContainedType>(*array.containedType); } ArrayType& ArrayType::operator=(const ArrayType& array) { assert(array.containedType); containedType = std::make_unique<ContainedType>(*array.containedType); length = array.length; return *this; } bool ArrayType::operator==(const ArrayType& rhs) const { assert(containedType); assert(rhs.containedType); if (length != rhs.length) return false; if (containedType->type != rhs.containedType->type) return false; return true; } MethodType::MethodType(const MethodType& methodType) : methodIndex(methodType.methodIndex) { assert(methodType.objectType); objectType = std::make_unique<ContainedType>(*methodType.objectType); } MethodType& MethodType::operator=(const MethodType& methodType) { assert(methodType.objectType); methodIndex = methodType.methodIndex; objectType = std::make_unique<ContainedType>(*methodType.objectType); return *this; } bool MethodType::operator==(const MethodType& rhs) const { assert(objectType); assert(rhs.objectType); return objectType->type == rhs.objectType->type && methodIndex == rhs.methodIndex; } std::string ToString(const AliasType& type, const Stringifier& stringifier) { std::string str = "alias "; if (stringifier.aliasStringifier) str += stringifier.aliasStringifier(type.aliasIndex); else { str += "#"; str += std::to_string(type.aliasIndex); } str += " -> "; str += ToString(type.targetType->type); return str; } std::string ToString(const ArrayType& type, const Stringifier& stringifier) { std::string str = "array["; str += ToString(type.containedType->type, stringifier); str += ", "; str += std::to_string(type.length); str += "]"; return str; } std::string ToString(const ExpressionType& type, const Stringifier& stringifier) { return std::visit([&](auto&& arg) { return ToString(arg, stringifier); }, type); } std::string ToString(const FunctionType& /*type*/, const Stringifier& /*stringifier*/) { return "<function type>"; } std::string ToString(const IntrinsicFunctionType& /*type*/, const Stringifier& /*stringifier*/) { return "<intrinsic function type>"; } std::string ToString(const MatrixType& type, const Stringifier& /*stringifier*/) { std::string str = "mat"; if (type.columnCount == type.rowCount) str += std::to_string(type.columnCount); else { str += std::to_string(type.columnCount); str += "x"; str += std::to_string(type.rowCount); } str += "["; str += ToString(type.type); str += "]"; return str; } std::string ToString(const MethodType& type, const Stringifier& /*stringifier*/) { return "<method of object " + ToString(type.objectType->type) + " type>"; } std::string ToString(NoType /*type*/, const Stringifier& /*stringifier*/) { return "()"; } std::string ToString(PrimitiveType type, const Stringifier& /*stringifier*/) { switch (type) { case ShaderAst::PrimitiveType::Boolean: return "bool"; case ShaderAst::PrimitiveType::Float32: return "f32"; case ShaderAst::PrimitiveType::Int32: return "i32"; case ShaderAst::PrimitiveType::UInt32: return "u32"; case ShaderAst::PrimitiveType::String: return "string"; } return "<unhandled primitive type>"; } std::string ToString(const SamplerType& type, const Stringifier& /*stringifier*/) { std::string str = "sampler"; switch (type.dim) { case ImageType::E1D: str += "1D"; break; case ImageType::E1D_Array: str += "1DArray"; break; case ImageType::E2D: str += "2D"; break; case ImageType::E2D_Array: str += "2DArray"; break; case ImageType::E3D: str += "3D"; break; case ImageType::Cubemap: str += "Cube"; break; } str += "["; str += ToString(type.sampledType); str += "]"; return str; } std::string ToString(const StructType& type, const Stringifier& stringifier) { if (stringifier.structStringifier) return "struct " + stringifier.structStringifier(type.structIndex); else return "struct #" + std::to_string(type.structIndex); } std::string ToString(const Type& type, const Stringifier& stringifier) { if (stringifier.typeStringifier) return "type " + stringifier.typeStringifier(type.typeIndex); else return "type #" + std::to_string(type.typeIndex); } std::string ToString(const UniformType& type, const Stringifier& stringifier) { std::string str = "uniform["; str += ToString(type.containedType, stringifier); str += "]"; return str; } std::string ToString(const VectorType& type, const Stringifier& /*stringifier*/) { std::string str = "vec"; str += std::to_string(type.componentCount); str += "["; str += ToString(type.type); str += "]"; return str; } }
Fix compilation
Fix compilation
C++
mit
DigitalPulseSoftware/NazaraEngine
1f6e213d1548156a4d415699433e89261204ec98
src/RemoveDuplicatesfromSortedArray2.cpp
src/RemoveDuplicatesfromSortedArray2.cpp
//Follow up for "Remove Duplicates": //What if duplicates are allowed at most twice? // //For example, //Given sorted array A = [1,1,1,2,2,3], // //Your function should return length = 5, and A is now [1,1,2,2,3]. #include <iostream> #include <vector> #include <set> #include <algorithm> using namespace std; class Solution { public: int removeDuplicates(int A[], int n) { if(n<3) return n; int length=2; for(int i=2;i<n;i++) { if(A[length-2]!=A[i]) { A[length]=A[i]; length++; } } return length; } }; int main() { int a[] = {1,1,1,2,2,3}; Solution solute; int result = solute.removeDuplicates(a,6); return 0; }
//Follow up for "Remove Duplicates": //What if duplicates are allowed at most twice? // //For example, //Given sorted array A = [1,1,1,2,2,3], // //Your function should return length = 5, and A is now [1,1,2,2,3]. #include <iostream> #include <vector> #include <set> #include <algorithm> using namespace std; class Solution { public: int removeDuplicates(int A[], int n) { int index = 0; for (int i = 0; i < n; ++i) { if (i > 0 && i < n - 1 && A[i] == A[i - 1] && A[i] == A[i + 1]) continue; A[index++] = A[i]; } return index; } }; int main() { int a[] = {1,1,1,2,2,3}; Solution solute; int result = solute.removeDuplicates(a,6); return 0; }
Change Algorithm
Change Algorithm This is more clear
C++
mit
lzz5235/leetcode