text
stringlengths 54
60.6k
|
|---|
<commit_before><commit_msg>fix scissor override<commit_after><|endoftext|>
|
<commit_before>#include <jni.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <srt/srt.h>
#define DEBUG
#ifdef DEBUG
#include <android/log.h>
#define LOG_TAG "SRT-JNI"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)
#else
#define LOGI(...)
#define LOGD(...)
#define LOGE(...)
#define LOGW(...)
#endif
/**
* JNI のパッケージ名、クラス名を定義.
*/
#define JNI_METHOD_NAME(name) Java_org_deviceconnect_android_libsrt_NdkHelper_##name
#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT void JNICALL
JNI_METHOD_NAME(startup)(JNIEnv *env, jclass clazz) {
LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_startup()");
srt_startup();
}
JNIEXPORT void JNICALL
JNI_METHOD_NAME(cleanup)(JNIEnv *env, jclass clazz) {
LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_cleanup()");
srt_cleanup();
}
JNIEXPORT jlong JNICALL
JNI_METHOD_NAME(createSrtSocket)(JNIEnv *env, jclass clazz, jstring address, jint port, jint backlog) {
LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_createSrtSocket()");
int yes = 1;
int st;
int ss = srt_create_socket();
if (ss == SRT_ERROR) {
LOGE("srt_socket: %s", srt_getlasterror_str());
return -1;
}
const char *addressString = env->GetStringUTFChars(address, nullptr);
struct sockaddr_in sa;
sa.sin_family = AF_INET;
sa.sin_port = htons(port);
if (inet_pton(AF_INET, addressString, &sa.sin_addr) != 1) {
LOGE("inet_pton error.");
env->ReleaseStringUTFChars(address, addressString);
return -1;
}
env->ReleaseStringUTFChars(address, addressString);
srt_setsockflag(ss, SRTO_RCVSYN, &yes, sizeof yes);
st = srt_bind(ss, (struct sockaddr*)&sa, sizeof sa);
if (st == SRT_ERROR) {
LOGE("srt_bind: %s", srt_getlasterror_str());
return -1;
}
st = srt_listen(ss, backlog);
if (st == SRT_ERROR) {
LOGE("srt_listen: %s\n", srt_getlasterror_str());
return -1;
}
return ss;
}
JNIEXPORT void JNICALL
JNI_METHOD_NAME(closeSrtSocket)(JNIEnv *env, jclass clazz, jlong ptr) {
LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_closeSrtSocket()");
int st = srt_close((int) ptr);
if (st == SRT_ERROR) {
LOGE("srt_close: %s\n", srt_getlasterror_str());
}
}
JNIEXPORT jlong JNICALL
JNI_METHOD_NAME(accept)(JNIEnv *env, jclass clazz, jlong ptr, jobject socket) {
LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_accept()");
struct sockaddr addr;
int addrlen;
int st = srt_accept((int) ptr, &addr, &addrlen);
if (st == SRT_ERROR) {
LOGE("srt_accept: %s\n", srt_getlasterror_str());
return -1;
}
// クライアント側のソケットへのポインタ
jclass socketCls = env->FindClass("org/deviceconnect/android/libsrt/SRTSocket");
jfieldID socketPtr = env->GetFieldID(socketCls, "mNativePtr", "J");
env->SetLongField(socket, socketPtr, st);
// クライアントのIPアドレス
char format[] = "%d.%d.%d.%d";
char buf[15];
sprintf(buf, format, addr.sa_data[2], addr.sa_data[3], addr.sa_data[4], addr.sa_data[5]);
jstring address = env->NewStringUTF(buf);
jfieldID addressField = env->GetFieldID(socketCls, "mSocketAddress", "Ljava/lang/String;");
env->SetObjectField(socket, addressField, address);
return st;
}
JNIEXPORT int JNICALL
JNI_METHOD_NAME(sendMessage)(JNIEnv *env, jclass clazz, jlong ptr, jbyteArray byteArray, jint offset, jint length) {
jboolean isCopy;
jbyte* data = env->GetByteArrayElements(byteArray, &isCopy);
if (data == nullptr) {
return -1;
}
int result = srt_sendmsg((int) ptr, (const char *) &data[offset], length, -1, 0);
if (result < SRT_ERROR) {
LOGE("srt_send: %s\n", srt_getlasterror_str());
}
env->ReleaseByteArrayElements(byteArray, data, 0);
return result;
}
JNIEXPORT int JNICALL
JNI_METHOD_NAME(recvMessage)(JNIEnv *env, jclass clazz, jlong ptr, jbyteArray byteArray, jint length) {
jboolean isCopy;
jbyte* data = env->GetByteArrayElements(byteArray, &isCopy);
if (data == nullptr) {
return -1;
}
int result = srt_recvmsg((int) ptr, (char *) data, length);
if (result < SRT_ERROR) {
LOGE("srt_send: %s\n", srt_getlasterror_str());
}
env->ReleaseByteArrayElements(byteArray, data, 0);
return result;
}
JNIEXPORT void JNICALL
JNI_METHOD_NAME(dumpStats)(JNIEnv *env, jclass clazz, jlong ptr) {
LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_dumpStats(): ptr=%d", ptr);
SRT_TRACEBSTATS stats;
int result = srt_bstats((int) ptr, &stats, 0);
if (result == SRT_ERROR) {
return;
}
LOGD("dumpStats: pktSentTotal=%ld, pktRetransTotal=%d, pktSndLossTotal=%d", stats.pktSentTotal, stats.pktRetransTotal, stats.pktSndLossTotal);
LOGD("dumpStats: mbpsBandwidth=%f, mbpsMaxBW=%f, byteAvailSndBuf=%d", stats.mbpsBandwidth, stats.mbpsMaxBW, stats.byteAvailSndBuf);
}
#ifdef __cplusplus
}
#endif
<commit_msg>NdkHelper.accept() と NDK の返り値が一致していなかったので修正<commit_after>#include <jni.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <srt/srt.h>
#define DEBUG
#ifdef DEBUG
#include <android/log.h>
#define LOG_TAG "SRT-JNI"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)
#else
#define LOGI(...)
#define LOGD(...)
#define LOGE(...)
#define LOGW(...)
#endif
/**
* JNI のパッケージ名、クラス名を定義.
*/
#define JNI_METHOD_NAME(name) Java_org_deviceconnect_android_libsrt_NdkHelper_##name
#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT void JNICALL
JNI_METHOD_NAME(startup)(JNIEnv *env, jclass clazz) {
LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_startup()");
srt_startup();
}
JNIEXPORT void JNICALL
JNI_METHOD_NAME(cleanup)(JNIEnv *env, jclass clazz) {
LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_cleanup()");
srt_cleanup();
}
JNIEXPORT jlong JNICALL
JNI_METHOD_NAME(createSrtSocket)(JNIEnv *env, jclass clazz, jstring address, jint port, jint backlog) {
LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_createSrtSocket()");
int yes = 1;
int st;
int ss = srt_create_socket();
if (ss == SRT_ERROR) {
LOGE("srt_socket: %s", srt_getlasterror_str());
return -1;
}
const char *addressString = env->GetStringUTFChars(address, nullptr);
struct sockaddr_in sa;
sa.sin_family = AF_INET;
sa.sin_port = htons(port);
if (inet_pton(AF_INET, addressString, &sa.sin_addr) != 1) {
LOGE("inet_pton error.");
env->ReleaseStringUTFChars(address, addressString);
return -1;
}
env->ReleaseStringUTFChars(address, addressString);
srt_setsockflag(ss, SRTO_RCVSYN, &yes, sizeof yes);
st = srt_bind(ss, (struct sockaddr*)&sa, sizeof sa);
if (st == SRT_ERROR) {
LOGE("srt_bind: %s", srt_getlasterror_str());
return -1;
}
st = srt_listen(ss, backlog);
if (st == SRT_ERROR) {
LOGE("srt_listen: %s\n", srt_getlasterror_str());
return -1;
}
return ss;
}
JNIEXPORT void JNICALL
JNI_METHOD_NAME(closeSrtSocket)(JNIEnv *env, jclass clazz, jlong ptr) {
LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_closeSrtSocket()");
int st = srt_close((int) ptr);
if (st == SRT_ERROR) {
LOGE("srt_close: %s\n", srt_getlasterror_str());
}
}
JNIEXPORT void JNICALL
JNI_METHOD_NAME(accept)(JNIEnv *env, jclass clazz, jlong ptr, jobject socket) {
LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_accept()");
struct sockaddr addr;
int addrlen;
int st = srt_accept((int) ptr, &addr, &addrlen);
if (st == SRT_ERROR) {
LOGE("srt_accept: %s\n", srt_getlasterror_str());
return;
}
// クライアント側のソケットへのポインタ
jclass socketCls = env->FindClass("org/deviceconnect/android/libsrt/SRTSocket");
jfieldID socketPtr = env->GetFieldID(socketCls, "mNativePtr", "J");
env->SetLongField(socket, socketPtr, st);
// クライアントのIPアドレス
char format[] = "%d.%d.%d.%d";
char buf[15];
sprintf(buf, format, addr.sa_data[2], addr.sa_data[3], addr.sa_data[4], addr.sa_data[5]);
jstring address = env->NewStringUTF(buf);
jfieldID addressField = env->GetFieldID(socketCls, "mSocketAddress", "Ljava/lang/String;");
env->SetObjectField(socket, addressField, address);
}
JNIEXPORT int JNICALL
JNI_METHOD_NAME(sendMessage)(JNIEnv *env, jclass clazz, jlong ptr, jbyteArray byteArray, jint offset, jint length) {
jboolean isCopy;
jbyte* data = env->GetByteArrayElements(byteArray, &isCopy);
if (data == nullptr) {
return -1;
}
int result = srt_sendmsg((int) ptr, (const char *) &data[offset], length, -1, 0);
if (result < SRT_ERROR) {
LOGE("srt_send: %s\n", srt_getlasterror_str());
}
env->ReleaseByteArrayElements(byteArray, data, 0);
return result;
}
JNIEXPORT int JNICALL
JNI_METHOD_NAME(recvMessage)(JNIEnv *env, jclass clazz, jlong ptr, jbyteArray byteArray, jint length) {
jboolean isCopy;
jbyte* data = env->GetByteArrayElements(byteArray, &isCopy);
if (data == nullptr) {
return -1;
}
int result = srt_recvmsg((int) ptr, (char *) data, length);
if (result < SRT_ERROR) {
LOGE("srt_send: %s\n", srt_getlasterror_str());
}
env->ReleaseByteArrayElements(byteArray, data, 0);
return result;
}
JNIEXPORT void JNICALL
JNI_METHOD_NAME(dumpStats)(JNIEnv *env, jclass clazz, jlong ptr) {
LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_dumpStats(): ptr=%d", ptr);
SRT_TRACEBSTATS stats;
int result = srt_bstats((int) ptr, &stats, 0);
if (result == SRT_ERROR) {
return;
}
LOGD("dumpStats: pktSentTotal=%ld, pktRetransTotal=%d, pktSndLossTotal=%d", stats.pktSentTotal, stats.pktRetransTotal, stats.pktSndLossTotal);
LOGD("dumpStats: mbpsBandwidth=%f, mbpsMaxBW=%f, byteAvailSndBuf=%d", stats.mbpsBandwidth, stats.mbpsMaxBW, stats.byteAvailSndBuf);
}
#ifdef __cplusplus
}
#endif
<|endoftext|>
|
<commit_before>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
*
* 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.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "ThumbnailerWorker.h"
#include "Media.h"
#include "File.h"
#include "Folder.h"
#include "logging/Logger.h"
#include "MediaLibrary.h"
#include "utils/ModificationsNotifier.h"
#include "utils/Filename.h"
#include <algorithm>
namespace medialibrary
{
ThumbnailerWorker::ThumbnailerWorker( MediaLibraryPtr ml,
std::shared_ptr<IThumbnailer> thumbnailer )
: m_ml( ml )
, m_run( false )
, m_generator( std::move( thumbnailer ) )
, m_paused( false )
{
}
ThumbnailerWorker::~ThumbnailerWorker()
{
stop();
}
void ThumbnailerWorker::requestThumbnail( MediaPtr media )
{
std::unique_lock<compat::Mutex> lock( m_mutex );
m_tasks.push( std::move( media ) );
if ( m_thread.get_id() == compat::Thread::id{} )
{
m_run = true;
m_thread = compat::Thread( &ThumbnailerWorker::run, this );
}
else
m_cond.notify_all();
}
void ThumbnailerWorker::pause()
{
std::lock_guard<compat::Mutex> lock( m_mutex );
m_paused = true;
}
void ThumbnailerWorker::resume()
{
std::lock_guard<compat::Mutex> lock( m_mutex );
if ( m_paused == false )
return;
m_paused = false;
m_cond.notify_all();
}
void ThumbnailerWorker::run()
{
LOG_INFO( "Starting thumbnailer thread" );
while ( m_run == true )
{
MediaPtr media;
{
std::unique_lock<compat::Mutex> lock( m_mutex );
if ( m_tasks.size() == 0 || m_paused == true )
{
m_cond.wait( lock, [this]() {
return ( m_tasks.size() > 0 && m_paused == false ) ||
m_run == false;
});
if ( m_run == false )
break;
}
media = std::move( m_tasks.front() );
m_tasks.pop();
}
if ( media->isThumbnailGenerated() == true )
{
LOG_INFO( "Skipping thumbnail generation of a media with a thumbnail ", media->fileName() );
m_ml->getCb()->onMediaThumbnailReady( media, media->thumbnailMrl().empty() == false );
continue;
}
bool res = generateThumbnail( media );
if ( res == false )
{
auto m = static_cast<Media*>( media.get() );
m->setThumbnail( "", Thumbnail::Origin::Media, true );
}
m_ml->getCb()->onMediaThumbnailReady( media, res );
}
LOG_INFO( "Exiting thumbnailer thread" );
}
void ThumbnailerWorker::stop()
{
bool running = true;
if ( m_run.compare_exchange_strong( running, false ) )
{
{
std::unique_lock<compat::Mutex> lock( m_mutex );
while ( m_tasks.empty() == false )
m_tasks.pop();
}
m_cond.notify_all();
m_thread.join();
}
}
bool ThumbnailerWorker::generateThumbnail( MediaPtr media )
{
assert( media->type() != Media::Type::Audio );
const auto files = media->files();
if ( files.empty() == true )
{
LOG_WARN( "Can't generate thumbnail for a media without associated files (",
media->title() );
return false;
}
auto mainFileIt = std::find_if( files.cbegin(), files.cend(),
[](FilePtr f) {
return f->isMain();
});
assert( mainFileIt != files.cend() );
auto file = std::static_pointer_cast<File>( *mainFileIt );
std::string mrl;
try
{
mrl = file->mrl();
}
catch ( const fs::DeviceRemovedException& )
{
LOG_WARN( "Aborting file ", file->rawMrl(), " generation due to its "
"containing device being missing" );
return false;
}
auto dest = Thumbnail::pathForMedia( m_ml, media->id() );
LOG_DEBUG( "Generating ", mrl, " thumbnail in ", dest );
auto m = static_cast<Media*>( media.get() );
if ( m_generator->generate( media, mrl, dest ) == false )
return false;
auto destMrl = utils::file::toMrl( dest );
if ( m->setThumbnail( destMrl, Thumbnail::Origin::Media, true ) == false )
return false;
m_ml->getNotifier()->notifyMediaModification( media );
return true;
}
}
<commit_msg>Thumbnailer: Don't retry thumbnail generations<commit_after>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
*
* 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.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "ThumbnailerWorker.h"
#include "Media.h"
#include "File.h"
#include "Folder.h"
#include "logging/Logger.h"
#include "MediaLibrary.h"
#include "utils/ModificationsNotifier.h"
#include "utils/Filename.h"
#include <algorithm>
namespace medialibrary
{
ThumbnailerWorker::ThumbnailerWorker( MediaLibraryPtr ml,
std::shared_ptr<IThumbnailer> thumbnailer )
: m_ml( ml )
, m_run( false )
, m_generator( std::move( thumbnailer ) )
, m_paused( false )
{
}
ThumbnailerWorker::~ThumbnailerWorker()
{
stop();
}
void ThumbnailerWorker::requestThumbnail( MediaPtr media )
{
std::unique_lock<compat::Mutex> lock( m_mutex );
m_tasks.push( std::move( media ) );
if ( m_thread.get_id() == compat::Thread::id{} )
{
m_run = true;
m_thread = compat::Thread( &ThumbnailerWorker::run, this );
}
else
m_cond.notify_all();
}
void ThumbnailerWorker::pause()
{
std::lock_guard<compat::Mutex> lock( m_mutex );
m_paused = true;
}
void ThumbnailerWorker::resume()
{
std::lock_guard<compat::Mutex> lock( m_mutex );
if ( m_paused == false )
return;
m_paused = false;
m_cond.notify_all();
}
void ThumbnailerWorker::run()
{
LOG_INFO( "Starting thumbnailer thread" );
while ( m_run == true )
{
MediaPtr media;
{
std::unique_lock<compat::Mutex> lock( m_mutex );
if ( m_tasks.size() == 0 || m_paused == true )
{
m_cond.wait( lock, [this]() {
return ( m_tasks.size() > 0 && m_paused == false ) ||
m_run == false;
});
if ( m_run == false )
break;
}
media = std::move( m_tasks.front() );
m_tasks.pop();
}
if ( media->isThumbnailGenerated() == true )
{
LOG_INFO( "Skipping thumbnail generation of a media with a thumbnail ", media->fileName() );
m_ml->getCb()->onMediaThumbnailReady( media, media->thumbnailMrl().empty() == false );
continue;
}
bool res = generateThumbnail( media );
m_ml->getCb()->onMediaThumbnailReady( media, res );
}
LOG_INFO( "Exiting thumbnailer thread" );
}
void ThumbnailerWorker::stop()
{
bool running = true;
if ( m_run.compare_exchange_strong( running, false ) )
{
{
std::unique_lock<compat::Mutex> lock( m_mutex );
while ( m_tasks.empty() == false )
m_tasks.pop();
}
m_cond.notify_all();
m_thread.join();
}
}
bool ThumbnailerWorker::generateThumbnail( MediaPtr media )
{
assert( media->type() != Media::Type::Audio );
const auto files = media->files();
if ( files.empty() == true )
{
LOG_WARN( "Can't generate thumbnail for a media without associated files (",
media->title() );
return false;
}
auto mainFileIt = std::find_if( files.cbegin(), files.cend(),
[](FilePtr f) {
return f->isMain();
});
assert( mainFileIt != files.cend() );
auto file = std::static_pointer_cast<File>( *mainFileIt );
std::string mrl;
try
{
mrl = file->mrl();
}
catch ( const fs::DeviceRemovedException& )
{
LOG_WARN( "Aborting file ", file->rawMrl(), " generation due to its "
"containing device being missing" );
return false;
}
auto dest = Thumbnail::pathForMedia( m_ml, media->id() );
LOG_DEBUG( "Generating ", mrl, " thumbnail in ", dest );
auto m = static_cast<Media*>( media.get() );
/*
* Insert a failure record before computing the thumbnail.
* If the thumbnailer crashes, we don't want to re-run it. If it succeeds,
* the thumbnail will be updated right after
* This is done here instead of from the mainloop as we don't want to prevent
* the thumbnail generation of a file that has been removed.
*/
m->setThumbnail( "", Thumbnail::Origin::Media, true );
if ( m_generator->generate( media, mrl, dest ) == false )
return false;
auto destMrl = utils::file::toMrl( dest );
if ( m->setThumbnail( destMrl, Thumbnail::Origin::Media, true ) == false )
return false;
m_ml->getNotifier()->notifyMediaModification( media );
return true;
}
}
<|endoftext|>
|
<commit_before>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "PatternedMesh.h"
#include "Parser.h"
#include "InputParameters.h"
// libMesh includes
#include "libmesh/mesh_modification.h"
#include "libmesh/serial_mesh.h"
#include "libmesh/exodusII_io.h"
template<>
InputParameters validParams<PatternedMesh>()
{
InputParameters params = validParams<MooseMesh>();
params.addRequiredParam<std::vector<MeshFileName> >("files", "The name of the mesh files to read. They are automatically assigned ids starting with zero.");
params.addRangeCheckedParam<Real>("x_width", 0, "x_width>=0", "The tile width in the x direction");
params.addRangeCheckedParam<Real>("y_width", 0, "y_width>=0", "The tile width in the y direction");
params.addRangeCheckedParam<Real>("z_width", 0, "z_width>=0", "The tile width in the z direction");
// x boundary names
params.addParam<BoundaryName>("left_boundary", "left_boundary", "name of the left (x) boundary");
params.addParam<BoundaryName>("right_boundary", "right_boundary", "name of the right (x) boundary");
// y boundary names
params.addParam<BoundaryName>("top_boundary", "top_boundary", "name of the top (y) boundary");
params.addParam<BoundaryName>("bottom_boundary", "bottom_boundary", "name of the bottom (y) boundary");
// z boundary names
params.addParam<BoundaryName>("front_boundary", "front_boundary", "name of the front (z) boundary");
params.addParam<BoundaryName>("back_boundary", "back_boundary", "name of the back (z) boundary");
params.addRequiredParam<std::vector<std::vector<unsigned int> > >("pattern", "A double-indexed array starting with the upper-left corner");
params.addClassDescription("Creates a 2D mesh from a specified set of unique 'tiles' meshes and a two-dimensional pattern.");
return params;
}
PatternedMesh::PatternedMesh(const InputParameters & parameters) :
MooseMesh(parameters),
_files(getParam<std::vector<MeshFileName> >("files")),
_pattern(getParam<std::vector<std::vector<unsigned int> > >("pattern")),
_x_width(getParam<Real>("x_width")),
_y_width(getParam<Real>("y_width")),
_z_width(getParam<Real>("z_width"))
{
// The PatternedMesh class only works with SerialMesh
errorIfParallelDistribution("PatternedMesh");
_meshes.resize(_files.size());
// Read in all of the meshes
for (unsigned int i = 0; i < _files.size(); i++)
{
SerialMesh * mesh = new SerialMesh(_communicator);
mesh->read(_files[i]);
_meshes[i] = mesh;
}
_row_meshes.resize(_pattern.size());
// The zeroth row (which is the top row) will be the real mesh
_row_meshes[0] = dynamic_cast<SerialMesh*>( &getMesh() );
// Create a mesh for all the other rows
for (unsigned int i = 1; i < _pattern.size(); i++)
{
SerialMesh * mesh = new SerialMesh(_communicator);
_row_meshes[i] = mesh;
}
}
PatternedMesh::PatternedMesh(const PatternedMesh & other_mesh) :
MooseMesh(other_mesh),
_files(other_mesh._files),
_pattern(other_mesh._pattern),
_x_width(other_mesh._x_width),
_y_width(other_mesh._y_width),
_z_width(other_mesh._z_width)
{
}
PatternedMesh::~PatternedMesh()
{
// Clean up the mesh we made (see what I did there?)
for (unsigned int i = 0; i < _meshes.size(); i++)
delete _meshes[i];
// Don't delete the first row - it is the real mesh - it will be cleaned up later
for (unsigned int i = 1; i < _meshes.size(); i++)
delete _row_meshes[i];
}
MooseMesh &
PatternedMesh::clone() const
{
return *(new PatternedMesh(*this));
}
void
PatternedMesh::buildMesh()
{
// stitch_meshes() is only implemented for SerialMesh. So make sure
// we have one here before continuing.
SerialMesh* the_mesh = dynamic_cast<SerialMesh*>( &getMesh() );
if (!the_mesh)
mooseError("Error, PatternedMesh calls stitch_meshes() which only works on SerialMesh.");
else
{
BoundaryID left = getBoundaryID(getParam<BoundaryName>("left_boundary"));
BoundaryID right = getBoundaryID(getParam<BoundaryName>("right_boundary"));
BoundaryID top = getBoundaryID(getParam<BoundaryName>("top_boundary"));
BoundaryID bottom = getBoundaryID(getParam<BoundaryName>("bottom_boundary"));
BoundaryID front = getBoundaryID(getParam<BoundaryName>("front_boundary"));
BoundaryID back = getBoundaryID(getParam<BoundaryName>("back_boundary"));
// Build each row mesh
for (int i = 0; i < _pattern.size(); i++)
{
for (int j = 0; j < _pattern[i].size(); j++)
{
// If this is the first cell of the row initialize the row mesh
if (j == 0)
{
_row_meshes[i]->read(_files[_pattern[i][j]]);
MeshTools::Modification::translate(*_row_meshes[i], j*_x_width, -i*_y_width, 0);
continue;
}
SerialMesh & cell_mesh = *_meshes[_pattern[i][j]];
// Move the mesh into the right spot. -i because we are starting at the top
MeshTools::Modification::translate(cell_mesh, j*_x_width, -i*_y_width, 0);
_row_meshes[i]->stitch_meshes(dynamic_cast<SerialMesh &>(cell_mesh), right, left, TOLERANCE, /*clear_stitched_boundary_ids=*/true);
// Undo the translation
MeshTools::Modification::translate(cell_mesh, -j*_x_width, i*_y_width, 0);
}
}
// Now stitch together the rows
// We're going to stitch them all to row 0 (which is the real mesh)
for (int i = 1; i < _pattern.size(); i++)
_row_meshes[0]->stitch_meshes(*_row_meshes[i], bottom, top, TOLERANCE, /*clear_stitched_boundary_ids=*/true);
}
}
<commit_msg>Make sure all _row_meshes are deleted.<commit_after>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "PatternedMesh.h"
#include "Parser.h"
#include "InputParameters.h"
// libMesh includes
#include "libmesh/mesh_modification.h"
#include "libmesh/serial_mesh.h"
#include "libmesh/exodusII_io.h"
template<>
InputParameters validParams<PatternedMesh>()
{
InputParameters params = validParams<MooseMesh>();
params.addRequiredParam<std::vector<MeshFileName> >("files", "The name of the mesh files to read. They are automatically assigned ids starting with zero.");
params.addRangeCheckedParam<Real>("x_width", 0, "x_width>=0", "The tile width in the x direction");
params.addRangeCheckedParam<Real>("y_width", 0, "y_width>=0", "The tile width in the y direction");
params.addRangeCheckedParam<Real>("z_width", 0, "z_width>=0", "The tile width in the z direction");
// x boundary names
params.addParam<BoundaryName>("left_boundary", "left_boundary", "name of the left (x) boundary");
params.addParam<BoundaryName>("right_boundary", "right_boundary", "name of the right (x) boundary");
// y boundary names
params.addParam<BoundaryName>("top_boundary", "top_boundary", "name of the top (y) boundary");
params.addParam<BoundaryName>("bottom_boundary", "bottom_boundary", "name of the bottom (y) boundary");
// z boundary names
params.addParam<BoundaryName>("front_boundary", "front_boundary", "name of the front (z) boundary");
params.addParam<BoundaryName>("back_boundary", "back_boundary", "name of the back (z) boundary");
params.addRequiredParam<std::vector<std::vector<unsigned int> > >("pattern", "A double-indexed array starting with the upper-left corner");
params.addClassDescription("Creates a 2D mesh from a specified set of unique 'tiles' meshes and a two-dimensional pattern.");
return params;
}
PatternedMesh::PatternedMesh(const InputParameters & parameters) :
MooseMesh(parameters),
_files(getParam<std::vector<MeshFileName> >("files")),
_pattern(getParam<std::vector<std::vector<unsigned int> > >("pattern")),
_x_width(getParam<Real>("x_width")),
_y_width(getParam<Real>("y_width")),
_z_width(getParam<Real>("z_width"))
{
// The PatternedMesh class only works with SerialMesh
errorIfParallelDistribution("PatternedMesh");
_meshes.resize(_files.size());
// Read in all of the meshes
for (unsigned int i = 0; i < _files.size(); i++)
{
SerialMesh * mesh = new SerialMesh(_communicator);
mesh->read(_files[i]);
_meshes[i] = mesh;
}
_row_meshes.resize(_pattern.size());
// The zeroth row (which is the top row) will be the real mesh
_row_meshes[0] = dynamic_cast<SerialMesh*>( &getMesh() );
// Create a mesh for all the other rows
for (unsigned int i = 1; i < _pattern.size(); i++)
{
SerialMesh * mesh = new SerialMesh(_communicator);
_row_meshes[i] = mesh;
}
}
PatternedMesh::PatternedMesh(const PatternedMesh & other_mesh) :
MooseMesh(other_mesh),
_files(other_mesh._files),
_pattern(other_mesh._pattern),
_x_width(other_mesh._x_width),
_y_width(other_mesh._y_width),
_z_width(other_mesh._z_width)
{
}
PatternedMesh::~PatternedMesh()
{
// Clean up the mesh we made (see what I did there?)
for (unsigned int i = 0; i < _meshes.size(); i++)
delete _meshes[i];
// Don't delete the first row - it is the real mesh - it will be cleaned up later
for (unsigned int i = 1; i < _row_meshes.size(); i++)
delete _row_meshes[i];
}
MooseMesh &
PatternedMesh::clone() const
{
return *(new PatternedMesh(*this));
}
void
PatternedMesh::buildMesh()
{
// stitch_meshes() is only implemented for SerialMesh. So make sure
// we have one here before continuing.
SerialMesh* the_mesh = dynamic_cast<SerialMesh*>( &getMesh() );
if (!the_mesh)
mooseError("Error, PatternedMesh calls stitch_meshes() which only works on SerialMesh.");
else
{
BoundaryID left = getBoundaryID(getParam<BoundaryName>("left_boundary"));
BoundaryID right = getBoundaryID(getParam<BoundaryName>("right_boundary"));
BoundaryID top = getBoundaryID(getParam<BoundaryName>("top_boundary"));
BoundaryID bottom = getBoundaryID(getParam<BoundaryName>("bottom_boundary"));
BoundaryID front = getBoundaryID(getParam<BoundaryName>("front_boundary"));
BoundaryID back = getBoundaryID(getParam<BoundaryName>("back_boundary"));
// Build each row mesh
for (int i = 0; i < _pattern.size(); i++)
{
for (int j = 0; j < _pattern[i].size(); j++)
{
// If this is the first cell of the row initialize the row mesh
if (j == 0)
{
_row_meshes[i]->read(_files[_pattern[i][j]]);
MeshTools::Modification::translate(*_row_meshes[i], j*_x_width, -i*_y_width, 0);
continue;
}
SerialMesh & cell_mesh = *_meshes[_pattern[i][j]];
// Move the mesh into the right spot. -i because we are starting at the top
MeshTools::Modification::translate(cell_mesh, j*_x_width, -i*_y_width, 0);
_row_meshes[i]->stitch_meshes(dynamic_cast<SerialMesh &>(cell_mesh), right, left, TOLERANCE, /*clear_stitched_boundary_ids=*/true);
// Undo the translation
MeshTools::Modification::translate(cell_mesh, -j*_x_width, i*_y_width, 0);
}
}
// Now stitch together the rows
// We're going to stitch them all to row 0 (which is the real mesh)
for (int i = 1; i < _pattern.size(); i++)
_row_meshes[0]->stitch_meshes(*_row_meshes[i], bottom, top, TOLERANCE, /*clear_stitched_boundary_ids=*/true);
}
}
<|endoftext|>
|
<commit_before>/****************************************************************************
** Meta object code from reading C++ file 'multilauemain.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.7.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../MultiLaueGUI/multilauemain.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'multilauemain.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.7.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_MultiLaueMain_t {
QByteArrayData data[1];
char stringdata0[14];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_MultiLaueMain_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_MultiLaueMain_t qt_meta_stringdata_MultiLaueMain = {
{
QT_MOC_LITERAL(0, 0, 13) // "MultiLaueMain"
},
"MultiLaueMain"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_MultiLaueMain[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
void MultiLaueMain::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
const QMetaObject MultiLaueMain::staticMetaObject = {
{ &QMainWindow::staticMetaObject, qt_meta_stringdata_MultiLaueMain.data,
qt_meta_data_MultiLaueMain, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *MultiLaueMain::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *MultiLaueMain::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_MultiLaueMain.stringdata0))
return static_cast<void*>(const_cast< MultiLaueMain*>(this));
return QMainWindow::qt_metacast(_clname);
}
int MultiLaueMain::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QMainWindow::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_END_MOC_NAMESPACE
<commit_msg>Delete moc_multilauemain.cpp<commit_after><|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
#include "../../StroikaPreComp.h"
#if qPlatform_Windows
#include <Windows.h>
#endif
#include "../../../Foundation/Characters/Format.h"
#include "../../../Foundation/Characters/Tokenize.h"
#include "../../../Foundation/Containers/Sequence.h"
#include "../../../Foundation/Debug/Assertions.h"
#include "../../../Foundation/Execution/ProcessRunner.h"
#include "../../../Foundation/Streams/BasicBinaryInputOutputStream.h"
#include "../../../Foundation/Streams/TextInputStreamBinaryAdapter.h"
#include "../CommonMeasurementTypes.h"
#include "MountedFilesystemUsage.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::Execution;
using namespace Stroika::Foundation::Memory;
using namespace Stroika::Frameworks;
using namespace Stroika::Frameworks::SystemPerformance;
namespace {
struct VolumeInfo_ {
String fFileSystemType;
String fDeviceOrVolumeName;
String fVolumeID;
String fMountedOnName;
Optional<double> fDiskSizeInBytes;
Optional<double> fUsedSizeInBytes;
};
}
namespace {
#if qPlatform_Windows
Sequence<VolumeInfo_> capture_ ()
{
Sequence<VolumeInfo_> result;
TCHAR volumeNameBuf[1024];
for (HANDLE hVol = FindFirstVolume (volumeNameBuf, NEltsOf(volumeNameBuf)); hVol != INVALID_HANDLE_VALUE; ) {
DWORD lpMaximumComponentLength;
DWORD dwSysFlags;
TCHAR FileSysNameBuf[1024];
if (::GetVolumeInformation( volumeNameBuf, NULL, NEltsOf(volumeNameBuf), NULL, &lpMaximumComponentLength, &dwSysFlags, FileSysNameBuf, NEltsOf(FileSysNameBuf))) {
VolumeInfo_ v;
v.fFileSystemType = String::FromSDKString (FileSysNameBuf);
v.fVolumeID = String::FromSDKString (volumeNameBuf);
{
// @todo - use
// http://msdn.microsoft.com/en-us/library/windows/desktop/cc542456(v=vs.85).aspx
// CharCount = QueryDosDeviceW(&VolumeName[4], DeviceName, ARRAYSIZE(DeviceName));
// to get DEVICENAME
//
TCHAR volPathsBuf[1024];
DWORD retLen = 0;
DWORD x = GetVolumePathNamesForVolumeName (volumeNameBuf, volPathsBuf, NEltsOf(volPathsBuf), &retLen);
if (volPathsBuf[0] == 0) {
v.fMountedOnName.clear ();
result.push_back (v);
}
else {
for (const TCHAR* NameIdx = volPathsBuf; NameIdx[0] != L'\0'; NameIdx += wcslen(NameIdx) + 1) {
v.fMountedOnName = String::FromSDKString (NameIdx);
{
ULARGE_INTEGER freeBytesAvailable;
ULARGE_INTEGER totalNumberOfBytes;
ULARGE_INTEGER totalNumberOfFreeBytes;
memset (&freeBytesAvailable, 0, sizeof (freeBytesAvailable));
memset (&totalNumberOfBytes, 0, sizeof (totalNumberOfBytes));
memset (&totalNumberOfFreeBytes, 0, sizeof (totalNumberOfFreeBytes));
DWORD xxx = GetDiskFreeSpaceEx (v.fMountedOnName.c_str (), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes);
v.fDiskSizeInBytes = static_cast<double> (totalNumberOfBytes.QuadPart);
v.fUsedSizeInBytes = *v.fDiskSizeInBytes - freeBytesAvailable.QuadPart;
}
result.push_back (v);
}
}
}
}
else {
// warning...
}
// find next
if (not ::FindNextVolume (hVol, volumeNameBuf, NEltsOf(volumeNameBuf))) {
FindVolumeClose (hVol);
hVol = INVALID_HANDLE_VALUE;
}
}
return result;
}
#elif qPlatform_POSIX
Sequence<VolumeInfo_> capture_ ()
{
// I looked through the /proc filesystem stuff and didnt see anything obvious to retrive this info...
// run def with ProcessRunner
Sequence<VolumeInfo_> result;
ProcessRunner pr (SDKSTR ("/bin/df"));
#if 1
Streams::BasicBinaryInputOutputStream useStdOut;
pr.SetStdOut (useStdOut);
pr.Run ();
String out;
Streams::TextInputStreamBinaryAdapter stdOut = Streams::TextInputStreamBinaryAdapter (useStdOut);
bool skippedHeader = false;
for (String i = stdOut.ReadLine (); not i.empty (); i = stdOut.ReadLine ()) {
if (not skippedHeader) {
skippedHeader = true;
continue;
}
Sequence<String> l = Characters::Tokenize<String> (i, L" ");
if (l.size () < 6) {
DbgTrace ("skipping line cuz len=%d", l.size ());
continue;
}
VolumeInfo_ v;
v.fMountedOnName = l[5];
v.fDeviceOrVolumeName = l[0];
v.fDiskSizeInBytes = Characters::String2Float (l[1]) * 1024;
v.fUsedSizeInBytes = Characters::String2Float (l[2]) * 1024;
result.Append (v);
}
//String out = stdOut.ReadAll ();
// redo with a bunch of readlines
#else
String out = pr.Run (L"");
#endif
#if 0
VolumeInfo_ foo;
foo.fMountedOnName = out;
result.Append (foo); //tmphack to test
#endif
return result;
}
#endif
}
/*
********************************************************************************
***************** Instruments::GetMountedFilesystemUsage ***********************
********************************************************************************
*/
Instrument SystemPerformance::Instruments::GetMountedFilesystemUsage ()
{
static Instrument kInstrument_ = Instrument (
InstrumentNameType (L"Mounted-Filesystem-Usage"),
[] () -> Measurements {
Measurements results;
DateTime before = DateTime::Now ();
Sequence<VolumeInfo_> volumes = capture_ ();
results.fMeasuredAt = DateTimeRange (before, DateTime::Now ());
Sequence<VariantValue> volumnesAsVariants;
for (VolumeInfo_ v : volumes)
{
Mapping<String, VariantValue> vv;
vv.Add (L"Filesystem-Type", v.fFileSystemType);
if (not v.fDeviceOrVolumeName.empty ()) {
vv.Add (L"Device-Name", v.fDeviceOrVolumeName);
}
vv.Add (L"Volume-ID", v.fVolumeID);
vv.Add (L"Mounted-On", v.fMountedOnName);
if (v.fDiskSizeInBytes.IsPresent ()) {
vv.Add (L"Disk-Size", *v.fDiskSizeInBytes);
}
if (v.fUsedSizeInBytes.IsPresent ()) {
vv.Add (L"Disk-Used-Size", *v.fUsedSizeInBytes);
}
volumnesAsVariants.Append (VariantValue (vv));
}
Measurement m;
m.fValue = volumnesAsVariants;
m.fType = kMountedVolumeUsage;
results.fMeasurements.Add (m);
return results;
},
{kMountedVolumeUsage}
);
return kInstrument_;
}
<commit_msg>cleanups to /SystemPerformance/Instruments/MountedFilesystemUsage<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
#include "../../StroikaPreComp.h"
#if qPlatform_Windows
#include <Windows.h>
#endif
#include "../../../Foundation/Characters/Format.h"
#include "../../../Foundation/Characters/Tokenize.h"
#include "../../../Foundation/Containers/Sequence.h"
#include "../../../Foundation/Debug/Assertions.h"
#include "../../../Foundation/Execution/ProcessRunner.h"
#include "../../../Foundation/Streams/BasicBinaryInputOutputStream.h"
#include "../../../Foundation/Streams/TextInputStreamBinaryAdapter.h"
#include "../CommonMeasurementTypes.h"
#include "MountedFilesystemUsage.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::Execution;
using namespace Stroika::Foundation::Memory;
using namespace Stroika::Frameworks;
using namespace Stroika::Frameworks::SystemPerformance;
namespace {
struct VolumeInfo_ {
String fFileSystemType;
String fDeviceOrVolumeName;
String fVolumeID;
String fMountedOnName;
Optional<double> fDiskSizeInBytes;
Optional<double> fUsedSizeInBytes;
};
}
namespace {
#if qPlatform_Windows
Sequence<VolumeInfo_> capture_ ()
{
Sequence<VolumeInfo_> result;
TCHAR volumeNameBuf[1024];
for (HANDLE hVol = FindFirstVolume (volumeNameBuf, NEltsOf(volumeNameBuf)); hVol != INVALID_HANDLE_VALUE; ) {
DWORD lpMaximumComponentLength;
DWORD dwSysFlags;
TCHAR FileSysNameBuf[1024];
if (::GetVolumeInformation( volumeNameBuf, NULL, NEltsOf(volumeNameBuf), NULL, &lpMaximumComponentLength, &dwSysFlags, FileSysNameBuf, NEltsOf(FileSysNameBuf))) {
VolumeInfo_ v;
v.fFileSystemType = String::FromSDKString (FileSysNameBuf);
v.fVolumeID = String::FromSDKString (volumeNameBuf);
{
// @todo - use
// http://msdn.microsoft.com/en-us/library/windows/desktop/cc542456(v=vs.85).aspx
// CharCount = QueryDosDeviceW(&VolumeName[4], DeviceName, ARRAYSIZE(DeviceName));
// to get DEVICENAME
//
TCHAR volPathsBuf[1024];
DWORD retLen = 0;
DWORD x = GetVolumePathNamesForVolumeName (volumeNameBuf, volPathsBuf, NEltsOf(volPathsBuf), &retLen);
if (volPathsBuf[0] == 0) {
v.fMountedOnName.clear ();
result.push_back (v);
}
else {
for (const TCHAR* NameIdx = volPathsBuf; NameIdx[0] != L'\0'; NameIdx += wcslen(NameIdx) + 1) {
v.fMountedOnName = String::FromSDKString (NameIdx);
{
ULARGE_INTEGER freeBytesAvailable;
ULARGE_INTEGER totalNumberOfBytes;
ULARGE_INTEGER totalNumberOfFreeBytes;
memset (&freeBytesAvailable, 0, sizeof (freeBytesAvailable));
memset (&totalNumberOfBytes, 0, sizeof (totalNumberOfBytes));
memset (&totalNumberOfFreeBytes, 0, sizeof (totalNumberOfFreeBytes));
DWORD xxx = GetDiskFreeSpaceEx (v.fMountedOnName.c_str (), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes);
v.fDiskSizeInBytes = static_cast<double> (totalNumberOfBytes.QuadPart);
v.fUsedSizeInBytes = *v.fDiskSizeInBytes - freeBytesAvailable.QuadPart;
}
result.push_back (v);
}
}
}
}
else {
// warning...
}
// find next
if (not ::FindNextVolume (hVol, volumeNameBuf, NEltsOf(volumeNameBuf))) {
FindVolumeClose (hVol);
hVol = INVALID_HANDLE_VALUE;
}
}
return result;
}
#elif qPlatform_POSIX
Sequence<VolumeInfo_> capture_ ()
{
// I looked through the /proc filesystem stuff and didnt see anything obvious to retrive this info...
// run def with ProcessRunner
Sequence<VolumeInfo_> result;
ProcessRunner pr (SDKSTR ("/bin/df"));
Streams::BasicBinaryInputOutputStream useStdOut;
pr.SetStdOut (useStdOut);
pr.Run ();
String out;
Streams::TextInputStreamBinaryAdapter stdOut = Streams::TextInputStreamBinaryAdapter (useStdOut);
bool skippedHeader = false;
for (String i = stdOut.ReadLine (); not i.empty (); i = stdOut.ReadLine ()) {
if (not skippedHeader) {
skippedHeader = true;
continue;
}
Sequence<String> l = Characters::Tokenize<String> (i, L" ");
if (l.size () < 6) {
DbgTrace ("skipping line cuz len=%d", l.size ());
continue;
}
VolumeInfo_ v;
v.fMountedOnName = l[5];
v.fDeviceOrVolumeName = l[0];
v.fDiskSizeInBytes = Characters::String2Float<double> (l[1]) * 1024;
v.fUsedSizeInBytes = Characters::String2Float<double> (l[2]) * 1024;
result.Append (v);
}
return result;
}
#endif
}
/*
********************************************************************************
***************** Instruments::GetMountedFilesystemUsage ***********************
********************************************************************************
*/
Instrument SystemPerformance::Instruments::GetMountedFilesystemUsage ()
{
static Instrument kInstrument_ = Instrument (
InstrumentNameType (L"Mounted-Filesystem-Usage"),
[] () -> Measurements {
Measurements results;
DateTime before = DateTime::Now ();
Sequence<VolumeInfo_> volumes = capture_ ();
results.fMeasuredAt = DateTimeRange (before, DateTime::Now ());
Sequence<VariantValue> volumnesAsVariants;
for (VolumeInfo_ v : volumes)
{
Mapping<String, VariantValue> vv;
vv.Add (L"Filesystem-Type", v.fFileSystemType);
if (not v.fDeviceOrVolumeName.empty ()) {
vv.Add (L"Device-Name", v.fDeviceOrVolumeName);
}
vv.Add (L"Volume-ID", v.fVolumeID);
vv.Add (L"Mounted-On", v.fMountedOnName);
if (v.fDiskSizeInBytes.IsPresent ()) {
vv.Add (L"Disk-Size", *v.fDiskSizeInBytes);
}
if (v.fUsedSizeInBytes.IsPresent ()) {
vv.Add (L"Disk-Used-Size", *v.fUsedSizeInBytes);
}
volumnesAsVariants.Append (VariantValue (vv));
}
Measurement m;
m.fValue = volumnesAsVariants;
m.fType = kMountedVolumeUsage;
results.fMeasurements.Add (m);
return results;
},
{kMountedVolumeUsage}
);
return kInstrument_;
}
<|endoftext|>
|
<commit_before>#pragma once
#include <windows.h>
#include <boost/asio.hpp>
#include <stdexcept>
#include "GenericTransport.hpp"
namespace Ethereum{namespace Connector{
typedef boost::asio::windows::stream_handle NamedPipeSocket;
class NamedPipeConnector
{
public:
bool connect(NamedPipeSocket &, const char *);
};
typedef GenericTransport<NamedPipeSocket, NamedPipeConnector> NamedPipeTransport;
}}
<commit_msg>fixed asio conflict on windows<commit_after>#pragma once
#include <boost/asio.hpp>
#include <stdexcept>
#include "GenericTransport.hpp"
namespace Ethereum{namespace Connector{
typedef boost::asio::windows::stream_handle NamedPipeSocket;
class NamedPipeConnector
{
public:
bool connect(NamedPipeSocket &, const char *);
};
typedef GenericTransport<NamedPipeSocket, NamedPipeConnector> NamedPipeTransport;
}}
<|endoftext|>
|
<commit_before>//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
//
// Based on Poly2Tri algorithm.
// Poly2Tri Copyright (c) 2009-2010, Poly2Tri Contributors
// http://code.google.com/p/poly2tri/
//
#include "Triangulate.h"
#include "Sweep.h"
#include "SweepContext.h"
#include "Shapes.h"
using namespace std;
namespace avg {
std::vector<int> triangulatePolygon(const Vec2Vector& points,
const std::vector<int>& holeIndexes)
{
std::vector<Point*> polyline;
std::vector<Point*> holeLine;
unsigned int contourEnd;
if (holeIndexes.size() > 0) {
contourEnd = holeIndexes[0];
} else {
contourEnd = points.size();
}
for (unsigned int i = 0; i < contourEnd; i++) {
polyline.push_back(new Point(points[i].x, points[i].y, i));
}
SweepContext* sweepContext = new SweepContext(polyline);
Sweep* sweep = new Sweep;
if (holeIndexes.size() > 0) {
for (unsigned int i = 0; i < holeIndexes.size(); i++) {
if ( i < holeIndexes.size()-1) {
for (unsigned int j = holeIndexes[i]; j < points.size() && j <
holeIndexes[i+1]; j++)
{
holeLine.push_back(new Point(points[j].x, points[j].y, j));
}
} else {
for (unsigned int j = holeIndexes[i]; j < points.size(); j++) {
holeLine.push_back(new Point(points[j].x, points[j].y, j));
}
}
sweepContext->addHole(holeLine);
holeLine.clear();
}
}
sweep->Triangulate(*sweepContext);
std::vector<int> result;
std::vector<avg::TriangulationTriangle*> triangles = sweepContext->getTriangles();
for (unsigned int i = 0; i < triangles.size(); ++i) {
result.push_back(triangles[i]->getPoint(0)->m_Index);
result.push_back(triangles[i]->getPoint(1)->m_Index);
result.push_back(triangles[i]->getPoint(2)->m_Index);
}
delete sweep;
delete sweepContext;
for (unsigned int i = 0; i < polyline.size(); i++) {
delete polyline[i];
}
return result;
}
}
<commit_msg>Indentation fix.<commit_after>//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
//
// Based on Poly2Tri algorithm.
// Poly2Tri Copyright (c) 2009-2010, Poly2Tri Contributors
// http://code.google.com/p/poly2tri/
//
#include "Triangulate.h"
#include "Sweep.h"
#include "SweepContext.h"
#include "Shapes.h"
using namespace std;
namespace avg {
std::vector<int> triangulatePolygon(const Vec2Vector& points,
const std::vector<int>& holeIndexes)
{
std::vector<Point*> polyline;
std::vector<Point*> holeLine;
unsigned int contourEnd;
if (holeIndexes.size() > 0) {
contourEnd = holeIndexes[0];
} else {
contourEnd = points.size();
}
for (unsigned int i = 0; i < contourEnd; i++) {
polyline.push_back(new Point(points[i].x, points[i].y, i));
}
SweepContext* sweepContext = new SweepContext(polyline);
Sweep* sweep = new Sweep;
if (holeIndexes.size() > 0) {
for (unsigned int i = 0; i < holeIndexes.size(); i++) {
if ( i < holeIndexes.size()-1) {
for (unsigned int j = holeIndexes[i]; j < points.size() && j <
holeIndexes[i+1]; j++)
{
holeLine.push_back(new Point(points[j].x, points[j].y, j));
}
} else {
for (unsigned int j = holeIndexes[i]; j < points.size(); j++) {
holeLine.push_back(new Point(points[j].x, points[j].y, j));
}
}
sweepContext->addHole(holeLine);
holeLine.clear();
}
}
sweep->Triangulate(*sweepContext);
std::vector<int> result;
std::vector<avg::TriangulationTriangle*> triangles = sweepContext->getTriangles();
for (unsigned int i = 0; i < triangles.size(); ++i) {
result.push_back(triangles[i]->getPoint(0)->m_Index);
result.push_back(triangles[i]->getPoint(1)->m_Index);
result.push_back(triangles[i]->getPoint(2)->m_Index);
}
delete sweep;
delete sweepContext;
for (unsigned int i = 0; i < polyline.size(); i++) {
delete polyline[i];
}
return result;
}
}
<|endoftext|>
|
<commit_before>#include "ScanGridProvider.h"
ScanGridProvider::ScanGridProvider()
:
cameraID(CameraInfo::Top)
{
DEBUG_REQUEST_REGISTER("Vision:ScanGridProvider:draw_verticals", "draw vertical scanlines", false);
DEBUG_REQUEST_REGISTER("Vision:ScanGridProvider:draw_horizontals", "draw horizontal scanlines", false);
DEBUG_REQUEST_REGISTER("Vision:ScanGridProvider:draw_vertical_min_y", "", false);
getDebugParameterList().add(¶meters);
}
ScanGridProvider::~ScanGridProvider()
{
getDebugParameterList().remove(¶meters);
}
void ScanGridProvider::execute(CameraInfo::CameraID id)
{
if(!getCameraMatrix().valid) {
return;
}
this->cameraID = id;
getScanGrid().reset();
const int width = getImage().width();
const int height = getImage().height();
// calculate horizon
int horizon_offset = 2;
int max_horizon = std::max((int) (getArtificialHorizon().begin().y + horizon_offset), 0);
int min_horizon = std::max((int) (getArtificialHorizon().end().y + horizon_offset), 0);
if (min_horizon > max_horizon) {
std::swap(min_horizon, max_horizon);
}
if (max_horizon >= height) {
// camera doesn't point to the ground
return;
}
Vector2i pointInImage;
int min_scan_y;
// project max_scan_distance_mm on the image plain to obtain the upper limit of vertical scanlines
Vector3d cameraMatrixOffset = Vector3d(getCameraMatrix().translation.x, getCameraMatrix().translation.y, 0);
if(CameraGeometry::relativePointToImage(
getCameraMatrix(), getCameraInfo(),
(RotationMatrix::getRotationZ(getCameraMatrix().rotation.getZAngle()) * Vector3d(parameters.max_scan_distance_mm, 0, 0))
+ cameraMatrixOffset,
pointInImage)
)
{
min_scan_y = std::max(pointInImage.y, 0);
if(min_scan_y >= height-1) {
return;
}
} else {
return;
}
min_scan_y = std::max(min_scan_y, max_horizon);
DEBUG_REQUEST("Vision:ScanGridProvider:draw_vertical_min_y",
LINE_PX(ColorClasses::black, 0, min_scan_y, width-1, min_scan_y);
);
double fieldWidthCovered = calculateMaxFieldWidth(min_scan_y);
if (fieldWidthCovered <= 0) {
return;
}
// calculate number of vertical scanlines with a vertical_gap_mm
int numberOfVerticals = std::min((int) (fieldWidthCovered / parameters.vertical_gap_mm), parameters.max_vertical_scanlines);
double minGap = width / (double) numberOfVerticals;
double gapRatio = parameters.horizontal_gap_mm / parameters.vertical_gap_mm;
int max_scan_y;
double y = min_scan_y;
double distance;
std::vector<ScanGrid::VScanLine> linesIncreasingLength;
for(double gap=2*minGap; gap < width; gap*=2)
{
// determine the lower bound of the vertical scanline
// distance of gap if it would be the size of vertical_gap_mm
distance = parameters.vertical_gap_mm * getCameraInfo().getFocalLength() / gap;
if(distance < getCameraMatrix().translation.z) {
max_scan_y = height-1;
} else {
distance = std::sqrt(distance*distance - getCameraMatrix().translation.z*getCameraMatrix().translation.z);
Vector3d pointOnField = (RotationMatrix::getRotationZ(getCameraMatrix().rotation.getZAngle())
* Vector3d(distance, 0, 0))
+ cameraMatrixOffset;
if(!CameraGeometry::relativePointToImage(
getCameraMatrix(), getCameraInfo(),
pointOnField,
pointInImage)) {
break;
}
max_scan_y = std::min(pointInImage.y, height-1);
if (max_scan_y <= min_scan_y) {
continue;
}
}
// fill vertical scan pattern
double ySkip = std::max(gapRatio * gap/2, parameters.min_horizontal_gap_px);
for(;y <= max_scan_y; y+=ySkip)
{
getScanGrid().vScanPattern.push_back((int) y);
}
// scanline with vScanPattern index
ScanGrid::VScanLine scanline;
scanline.top = 0;
scanline.bottom = getScanGrid().vScanPattern.size()-1;
linesIncreasingLength.push_back(scanline);
if(max_scan_y >= height-1) {
break;
}
}
if(linesIncreasingLength.empty() || getScanGrid().vScanPattern.empty()) {
return;
}
getScanGrid().vertical.resize(numberOfVerticals);
std::vector<ScanGrid::VScanLine>::iterator line = linesIncreasingLength.begin();
int frequency;
for(int i=1; i<=numberOfVerticals; i*=2) {
frequency = i*2;
for(int j=i-1; j<numberOfVerticals; j+=frequency) {
int x = (int) (j*minGap);
ScanGrid::VScanLine scanline;
scanline.x = x;
scanline.bottom = line->bottom;
scanline.top = 0;
getScanGrid().vertical[j] = scanline;
if(next(line) == linesIncreasingLength.end()) {
getScanGrid().longverticals.push_back(j);
}
}
if(next(line) != linesIncreasingLength.end()){
++line;
}
}
// fill horizontal scan pattern
for (const ScanGrid::VScanLine& vertical : getScanGrid().vertical) {
getScanGrid().hScanPattern.push_back(vertical.x);
}
// create horizontal scanlines
getScanGrid().horizontal.resize(getScanGrid().vScanPattern.size());
line = linesIncreasingLength.begin();
int hSkip = 1;
int i=0;
for(const int& y : getScanGrid().vScanPattern) {
if(y > getScanGrid().vScanPattern[line->bottom]) {
++line;
hSkip *= 2;
}
ScanGrid::HScanLine horizontal;
horizontal.left = 0;
horizontal.right = getScanGrid().hScanPattern.size()-1;
horizontal.y = y;
horizontal.skip = hSkip;
getScanGrid().horizontal[i] = horizontal;
++i;
}
DEBUG_REQUEST("Vision:ScanGridProvider:draw_verticals",
for(const ScanGrid::VScanLine& scanline: getScanGrid().vertical)
{
LINE_PX(ColorClasses::blue, scanline.x, getScanGrid().vScanPattern.at(scanline.bottom), scanline.x, getScanGrid().vScanPattern.at(scanline.top));
for(size_t i=scanline.top; i<=scanline.bottom; ++i)
{
POINT_PX(ColorClasses::red, scanline.x, getScanGrid().vScanPattern.at(i));
//Test
const int xx = scanline.x;
const int yy = getScanGrid().vScanPattern.at(i);
getImage().getY(xx, yy);
}
}
);
DEBUG_REQUEST("Vision:ScanGridProvider:draw_horizontals",
for(const ScanGrid::HScanLine& scanline: getScanGrid().horizontal)
{
LINE_PX(ColorClasses::blue, getScanGrid().hScanPattern.at(scanline.left), scanline.y, getScanGrid().hScanPattern.at(scanline.right), scanline.y);
for(size_t i=scanline.left; i<=scanline.right; i+=scanline.skip)
{
POINT_PX(ColorClasses::red, getScanGrid().hScanPattern.at(i), scanline.y);
//Test
const int xx = getScanGrid().hScanPattern.at(i);
const int yy = scanline.y;
getImage().getY(xx, yy);
}
}
);
}//end execute
double ScanGridProvider::calculateMaxFieldWidth(int y) {
Vector2d projectedLeftCorner;
if(!CameraGeometry::imagePixelToFieldCoord(
getCameraMatrix(), getCameraInfo(),
0,
y,
0.0,
projectedLeftCorner))
{
return -1.;
}
Vector2d projectedRightCorner;
if(!CameraGeometry::imagePixelToFieldCoord(
getCameraMatrix(), getCameraInfo(),
getImage().width()-1,
y,
0.0,
projectedRightCorner))
{
return -1.;
}
return (projectedLeftCorner - projectedRightCorner).abs();
}
<commit_msg>small fixes, comments and cleanup<commit_after>#include "ScanGridProvider.h"
ScanGridProvider::ScanGridProvider()
:
cameraID(CameraInfo::Top)
{
DEBUG_REQUEST_REGISTER("Vision:ScanGridProvider:draw_verticals", "draw vertical scanlines", false);
DEBUG_REQUEST_REGISTER("Vision:ScanGridProvider:draw_horizontals", "draw horizontal scanlines", false);
DEBUG_REQUEST_REGISTER("Vision:ScanGridProvider:draw_vertical_min_y", "", false);
getDebugParameterList().add(¶meters);
}
ScanGridProvider::~ScanGridProvider()
{
getDebugParameterList().remove(¶meters);
}
void ScanGridProvider::execute(CameraInfo::CameraID id)
{
this->cameraID = id;
if(!getCameraMatrix().valid) {
return;
}
getScanGrid().reset();
const int width = getImage().width();
const int height = getImage().height();
// calculate horizon
int horizon_offset = 2;
int max_horizon =
std::max((int) (getArtificialHorizon().begin().y + horizon_offset), 0);
int min_horizon =
std::max((int) (getArtificialHorizon().end().y + horizon_offset), 0);
if (min_horizon > max_horizon) {
std::swap(min_horizon, max_horizon);
}
if (max_horizon >= height) {
// camera doesn't point to the ground
return;
}
Vector2i pointInImage;
// project max_scan_distance_mm on the image plain
// to obtain the upper limit of vertical scanlines
Vector3d cameraMatrixOffset = Vector3d(getCameraMatrix().translation.x,
getCameraMatrix().translation.y,
0);
Vector3d farthestPoint = cameraMatrixOffset +
(RotationMatrix::getRotationZ(getCameraMatrix().rotation.getZAngle()) *
Vector3d(parameters.max_scan_distance_mm, 0, 0));
bool projectionSucces = CameraGeometry::relativePointToImage(
getCameraMatrix(), getCameraInfo(), farthestPoint, pointInImage);
int min_scan_y;
if(projectionSucces)
{
// should not be heigher than the top of the image
min_scan_y = std::max(pointInImage.y, 0);
// should not be lower than the bottom of the image
if(min_scan_y >= height) {
return;
}
} else {
return;
}
// should not be over the horizon
min_scan_y = std::max(min_scan_y, max_horizon);
DEBUG_REQUEST("Vision:ScanGridProvider:draw_vertical_min_y",
LINE_PX(ColorClasses::black, 0, min_scan_y, width-1, min_scan_y);
);
double fieldWidthCovered = calculateMaxFieldWidth(min_scan_y);
if (fieldWidthCovered <= 0) {
return;
}
// calculate number of vertical scanlines with a vertical_gap_mm
int numberOfVerticals = std::min(
(int) (fieldWidthCovered / parameters.vertical_gap_mm),
parameters.max_vertical_scanlines);
double minGap = width / (double) numberOfVerticals;
// transforms verticle gap sizes into horizontal gap sizes
double gapRatio = parameters.horizontal_gap_mm / parameters.vertical_gap_mm;
double focalLength = getCameraInfo().getFocalLength();
double cameraHeight = getCameraMatrix().translation.z;
int max_scan_y;
double y = min_scan_y;
double distance;
std::vector<ScanGrid::VScanLine> linesIncreasingLength;
for(double gap = 2 * minGap; gap < width; gap *= 2)
{
// distance of the gap if it would have a field size of vertical_gap_mm
distance = parameters.vertical_gap_mm * focalLength / gap;
// determine the start of the vertical scanline
if(distance < cameraHeight) {
max_scan_y = height-1;
} else {
distance = std::sqrt(distance * distance - cameraHeight * cameraHeight);
// project gap distance onto the image to obtain the start of the scanline
Vector3d pointOnField = cameraMatrixOffset +
(RotationMatrix::getRotationZ(getCameraMatrix().rotation.getZAngle())
* Vector3d(distance, 0, 0));
bool projectionSucces = CameraGeometry::relativePointToImage(
getCameraMatrix(), getCameraInfo(),
pointOnField,
pointInImage);
if(!projectionSucces) {
break;
}
max_scan_y = std::min(pointInImage.y, height-1);
if (max_scan_y <= min_scan_y) {
continue;
}
}
// fill vertical scan pattern
double ySkip = std::max(gapRatio * gap/2, parameters.min_horizontal_gap_px);
for(;y <= max_scan_y; y+=ySkip)
{
getScanGrid().vScanPattern.push_back((int) y);
}
// scanline with vScanPattern index
ScanGrid::VScanLine scanline;
scanline.top = 0;
scanline.bottom = getScanGrid().vScanPattern.size()-1;
linesIncreasingLength.push_back(scanline);
if(max_scan_y >= height-1) {
// bottom of the image reached
break;
}
}
if(linesIncreasingLength.empty() || getScanGrid().vScanPattern.empty()) {
return;
}
// fill the image with vertical scanlines
getScanGrid().vertical.resize(numberOfVerticals);
std::vector<ScanGrid::VScanLine>::iterator line = linesIncreasingLength.begin();
int frequency;
for(int i=1; i<=numberOfVerticals; i*=2) {
frequency = i*2;
for(int j=i-1; j<numberOfVerticals; j+=frequency) {
int x = (int) (j*minGap);
ScanGrid::VScanLine scanline;
scanline.x = x;
scanline.bottom = line->bottom;
scanline.top = 0;
getScanGrid().vertical[j] = scanline;
if(next(line) == linesIncreasingLength.end()) {
getScanGrid().longverticals.push_back(j);
}
}
if(next(line) != linesIncreasingLength.end()){
++line;
}
}
// fill horizontal scan pattern
for (const ScanGrid::VScanLine& vertical : getScanGrid().vertical) {
getScanGrid().hScanPattern.push_back(vertical.x);
}
// fill the image with horizontal scanlines
getScanGrid().horizontal.resize(getScanGrid().vScanPattern.size());
line = linesIncreasingLength.begin();
int hSkip = 1;
int i=0;
for(const int& y : getScanGrid().vScanPattern) {
if(y > getScanGrid().vScanPattern[line->bottom]) {
++line;
hSkip *= 2;
}
ScanGrid::HScanLine horizontal;
horizontal.left = 0;
horizontal.right = getScanGrid().hScanPattern.size()-1;
horizontal.y = y;
horizontal.skip = hSkip;
getScanGrid().horizontal[i] = horizontal;
++i;
}
DEBUG_REQUEST("Vision:ScanGridProvider:draw_verticals",
for(const ScanGrid::VScanLine& scanline: getScanGrid().vertical)
{
LINE_PX(ColorClasses::blue, scanline.x, getScanGrid().vScanPattern.at(scanline.bottom), scanline.x, getScanGrid().vScanPattern.at(scanline.top));
for(size_t i=scanline.top; i<=scanline.bottom; ++i)
{
POINT_PX(ColorClasses::red, scanline.x, getScanGrid().vScanPattern.at(i));
//Test
const int xx = scanline.x;
const int yy = getScanGrid().vScanPattern.at(i);
getImage().getY(xx, yy);
}
}
);
DEBUG_REQUEST("Vision:ScanGridProvider:draw_horizontals",
for(const ScanGrid::HScanLine& scanline: getScanGrid().horizontal)
{
LINE_PX(ColorClasses::blue, getScanGrid().hScanPattern.at(scanline.left), scanline.y, getScanGrid().hScanPattern.at(scanline.right), scanline.y);
for(size_t i=scanline.left; i<=scanline.right; i+=scanline.skip)
{
POINT_PX(ColorClasses::red, getScanGrid().hScanPattern.at(i), scanline.y);
//Test
const int xx = getScanGrid().hScanPattern.at(i);
const int yy = scanline.y;
getImage().getY(xx, yy);
}
}
);
}//end execute
double ScanGridProvider::calculateMaxFieldWidth(int y) {
// project the left and right image corner onto the field
// and caluclate the distance between thems
Vector2d projectedLeftCorner;
if(!CameraGeometry::imagePixelToFieldCoord(
getCameraMatrix(), getCameraInfo(),
0,
y,
0.0,
projectedLeftCorner))
{
return -1.;
}
Vector2d projectedRightCorner;
if(!CameraGeometry::imagePixelToFieldCoord(
getCameraMatrix(), getCameraInfo(),
getImage().width()-1,
y,
0.0,
projectedRightCorner))
{
return -1.;
}
return (projectedLeftCorner - projectedRightCorner).abs();
}
<|endoftext|>
|
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Ioan Sucan */
#include "ompl/geometric/planners/ryodo_sbl/RyodoSBL.h"
#include "ompl/base/goals/GoalSampleableRegion.h"
#include "ompl/base/samplers/ProbablicUniformValidStateSampler.h"
#include "ompl/tools/config/SelfConfig.h"
#include <limits>
#include <cassert>
ompl::base::ValidStateSamplerPtr allocProbablicUniformValidStateSampler(const ompl::base::SpaceInformation *si)
{
return ompl::base::ValidStateSamplerPtr(new ompl::base::ProbablicUniformValidStateSampler(si));
}
ompl::geometric::RyodoSBL::RyodoSBL(const base::SpaceInformationPtr &si) : base::Planner(si, "SBL")
{
specs_.recognizedGoal = base::GOAL_SAMPLEABLE_REGION;
maxDistance_ = 0.0;
connectionPoint_ = std::make_pair<base::State*, base::State*>(NULL, NULL);
Planner::declareParam<double>("range", this, &RyodoSBL::setRange, &RyodoSBL::getRange, "0.:1.:10000.");
}
ompl::geometric::RyodoSBL::~RyodoSBL()
{
freeMemory();
}
void ompl::geometric::RyodoSBL::setup()
{
Planner::setup();
tools::SelfConfig sc(si_, getName());
sc.configureProjectionEvaluator(projectionEvaluator_);
sc.configurePlannerRange(maxDistance_);
tStart_.grid.setDimension(projectionEvaluator_->getDimension());
tGoal_.grid.setDimension(projectionEvaluator_->getDimension());
}
void ompl::geometric::RyodoSBL::freeGridMotions(Grid<MotionInfo> &grid)
{
for (Grid<MotionInfo>::iterator it = grid.begin(); it != grid.end() ; ++it)
{
for (unsigned int i = 0 ; i < it->second->data.size() ; ++i)
{
if (it->second->data[i]->state)
si_->freeState(it->second->data[i]->state);
delete it->second->data[i];
}
}
}
ompl::base::PlannerStatus ompl::geometric::RyodoSBL::solve(const base::PlannerTerminationCondition &ptc)
{
checkValidity();
base::GoalSampleableRegion *goal = dynamic_cast<base::GoalSampleableRegion*>(pdef_->getGoal().get());
if (!goal)
{
OMPL_ERROR("%s: Unknown type of goal", getName().c_str());
return base::PlannerStatus::UNRECOGNIZED_GOAL_TYPE;
}
while (const base::State *st = pis_.nextStart())
{
Motion *motion = new Motion(si_);
si_->copyState(motion->state, st);
motion->valid = true;
motion->root = motion->state;
addMotion(tStart_, motion);
}
if (tStart_.size == 0)
{
OMPL_ERROR("%s: Motion planning start tree could not be initialized!", getName().c_str());
return base::PlannerStatus::INVALID_START;
}
if (!goal->couldSample())
{
OMPL_ERROR("%s: Insufficient states in sampleable goal region", getName().c_str());
return base::PlannerStatus::INVALID_GOAL;
}
if (!sampler_){
si_->setValidStateSamplerAllocator(boost::bind(&allocProbablicUniformValidStateSampler, _1));
sampler_ = si_->allocValidStateSampler();
}
OMPL_INFORM("%s: Starting planning with %d states already in datastructure", getName().c_str(), (int)(tStart_.size + tGoal_.size));
std::vector<Motion*> solution;
base::State *xstate = si_->allocState();
bool startTree = true;
bool solved = false;
while (ptc == false)
{
TreeData &tree = startTree ? tStart_ : tGoal_;
startTree = !startTree;
TreeData &otherTree = startTree ? tStart_ : tGoal_;
// if we have not sampled too many goals already
if (tGoal_.size == 0 || pis_.getSampledGoalsCount() < tGoal_.size / 2)
{
const base::State *st = tGoal_.size == 0 ? pis_.nextGoal(ptc) : pis_.nextGoal();
if (st)
{
Motion *motion = new Motion(si_);
si_->copyState(motion->state, st);
motion->root = motion->state;
motion->valid = true;
addMotion(tGoal_, motion);
}
if (tGoal_.size == 0)
{
OMPL_ERROR("%s: Unable to sample any valid states for goal tree", getName().c_str());
break;
}
}
Motion *existing = selectMotion(tree);
assert(existing);
if (!sampler_->sampleNear(xstate, existing->state, maxDistance_))
continue;
/* create a motion */
Motion *motion = new Motion(si_);
si_->copyState(motion->state, xstate);
motion->parent = existing;
motion->root = existing->root;
existing->children.push_back(motion);
addMotion(tree, motion);
if (checkSolution(!startTree, tree, otherTree, motion, solution))
{
PathGeometric *path = new PathGeometric(si_);
for (unsigned int i = 0 ; i < solution.size() ; ++i)
path->append(solution[i]->state);
pdef_->addSolutionPath(base::PathPtr(path), false, 0.0, getName());
solved = true;
break;
}
}
si_->freeState(xstate);
OMPL_INFORM("%s: Created %u (%u start + %u goal) states in %u cells (%u start + %u goal)",
getName().c_str(), tStart_.size + tGoal_.size, tStart_.size, tGoal_.size,
tStart_.grid.size() + tGoal_.grid.size(), tStart_.grid.size(), tGoal_.grid.size());
return solved ? base::PlannerStatus::EXACT_SOLUTION : base::PlannerStatus::TIMEOUT;
}
bool ompl::geometric::RyodoSBL::checkSolution(bool start, TreeData &tree, TreeData &otherTree, Motion *motion, std::vector<Motion*> &solution)
{
Grid<MotionInfo>::Coord coord;
projectionEvaluator_->computeCoordinates(motion->state, coord);
Grid<MotionInfo>::Cell* cell = otherTree.grid.getCell(coord);
if (cell && !cell->data.empty())
{
Motion *connectOther = cell->data[rng_.uniformInt(0, cell->data.size() - 1)];
if (pdef_->getGoal()->isStartGoalPairValid(start ? motion->root : connectOther->root, start ? connectOther->root : motion->root))
{
Motion *connect = new Motion(si_);
si_->copyState(connect->state, connectOther->state);
connect->parent = motion;
connect->root = motion->root; motion->children.push_back(connect);
addMotion(tree, connect);
if (isPathValid(tree, connect) && isPathValid(otherTree, connectOther))
{
if (start)
connectionPoint_ = std::make_pair(motion->state, connectOther->state);
else
connectionPoint_ = std::make_pair(connectOther->state, motion->state);
/* extract the motions and put them in solution vector */
std::vector<Motion*> mpath1;
while (motion != NULL)
{
mpath1.push_back(motion);
motion = motion->parent;
}
std::vector<Motion*> mpath2;
while (connectOther != NULL)
{
mpath2.push_back(connectOther);
connectOther = connectOther->parent;
}
if (!start)
mpath1.swap(mpath2);
for (int i = mpath1.size() - 1 ; i >= 0 ; --i)
solution.push_back(mpath1[i]);
solution.insert(solution.end(), mpath2.begin(), mpath2.end());
return true;
}
}
}
return false;
}
bool ompl::geometric::RyodoSBL::isPathValid(TreeData &tree, Motion *motion)
{
std::vector<Motion*> mpath;
/* construct the solution path */
while (motion != NULL)
{
mpath.push_back(motion);
motion = motion->parent;
}
/* check the path */
for (int i = mpath.size() - 1 ; i >= 0 ; --i)
if (!mpath[i]->valid)
{
if (si_->checkMotion(mpath[i]->parent->state, mpath[i]->state))
mpath[i]->valid = true;
else
{
removeMotion(tree, mpath[i]);
return false;
}
}
return true;
}
ompl::geometric::RyodoSBL::Motion* ompl::geometric::RyodoSBL::selectMotion(TreeData &tree)
{
GridCell* cell = tree.pdf.sample(rng_.uniform01());
return cell && !cell->data.empty() ? cell->data[rng_.uniformInt(0, cell->data.size() - 1)] : NULL;
}
void ompl::geometric::RyodoSBL::removeMotion(TreeData &tree, Motion *motion)
{
/* remove from grid */
Grid<MotionInfo>::Coord coord;
projectionEvaluator_->computeCoordinates(motion->state, coord);
Grid<MotionInfo>::Cell* cell = tree.grid.getCell(coord);
if (cell)
{
for (unsigned int i = 0 ; i < cell->data.size(); ++i)
{
if (cell->data[i] == motion)
{
cell->data.erase(cell->data.begin() + i);
tree.size--;
break;
}
}
if (cell->data.empty())
{
tree.pdf.remove(cell->data.elem_);
tree.grid.remove(cell);
tree.grid.destroyCell(cell);
}
else
{
tree.pdf.update(cell->data.elem_, 1.0/cell->data.size());
}
}
/* remove self from parent list */
if (motion->parent)
{
for (unsigned int i = 0 ; i < motion->parent->children.size() ; ++i)
{
if (motion->parent->children[i] == motion)
{
motion->parent->children.erase(motion->parent->children.begin() + i);
break;
}
}
}
/* remove children */
for (unsigned int i = 0 ; i < motion->children.size() ; ++i)
{
motion->children[i]->parent = NULL;
removeMotion(tree, motion->children[i]);
}
if (motion->state)
si_->freeState(motion->state);
delete motion;
}
void ompl::geometric::RyodoSBL::addMotion(TreeData &tree, Motion *motion)
{
Grid<MotionInfo>::Coord coord;
projectionEvaluator_->computeCoordinates(motion->state, coord);
Grid<MotionInfo>::Cell* cell = tree.grid.getCell(coord);
if (cell)
{
cell->data.push_back(motion);
tree.pdf.update(cell->data.elem_, 1.0/cell->data.size());
}
else
{
cell = tree.grid.createCell(coord);
cell->data.push_back(motion);
tree.grid.add(cell);
cell->data.elem_ = tree.pdf.add(cell, 1.0);
}
tree.size++;
}
void ompl::geometric::RyodoSBL::clear()
{
Planner::clear();
sampler_.reset();
freeMemory();
tStart_.grid.clear();
tStart_.size = 0;
tStart_.pdf.clear();
tGoal_.grid.clear();
tGoal_.size = 0;
tGoal_.pdf.clear();
connectionPoint_ = std::make_pair<base::State*, base::State*>(NULL, NULL);
}
void ompl::geometric::RyodoSBL::getPlannerData(base::PlannerData &data) const
{
Planner::getPlannerData(data);
std::vector<MotionInfo> motions;
tStart_.grid.getContent(motions);
for (unsigned int i = 0 ; i < motions.size() ; ++i)
for (unsigned int j = 0 ; j < motions[i].size() ; ++j)
if (motions[i][j]->parent == NULL)
data.addStartVertex(base::PlannerDataVertex(motions[i][j]->state, 1));
else
data.addEdge(base::PlannerDataVertex(motions[i][j]->parent->state, 1),
base::PlannerDataVertex(motions[i][j]->state, 1));
motions.clear();
tGoal_.grid.getContent(motions);
for (unsigned int i = 0 ; i < motions.size() ; ++i)
for (unsigned int j = 0 ; j < motions[i].size() ; ++j)
if (motions[i][j]->parent == NULL)
data.addGoalVertex(base::PlannerDataVertex(motions[i][j]->state, 2));
else
// The edges in the goal tree are reversed so that they are in the same direction as start tree
data.addEdge(base::PlannerDataVertex(motions[i][j]->state, 2),
base::PlannerDataVertex(motions[i][j]->parent->state, 2));
data.addEdge(data.vertexIndex(connectionPoint_.first), data.vertexIndex(connectionPoint_.second));
}
<commit_msg>[modiry] sampler name<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Ioan Sucan */
#include "ompl/geometric/planners/ryodo_sbl/RyodoSBL.h"
#include "ompl/base/goals/GoalSampleableRegion.h"
#include "ompl/base/samplers/ObstacleEstimationSampler.h"
#include "ompl/tools/config/SelfConfig.h"
#include <limits>
#include <cassert>
ompl::base::ValidStateSamplerPtr allocObstacleEstimationSampler(const ompl::base::SpaceInformation *si)
{
return ompl::base::ValidStateSamplerPtr(new ompl::base::ObstacleEstimationSampler(si));
}
ompl::geometric::RyodoSBL::RyodoSBL(const base::SpaceInformationPtr &si) : base::Planner(si, "SBL")
{
specs_.recognizedGoal = base::GOAL_SAMPLEABLE_REGION;
maxDistance_ = 0.0;
connectionPoint_ = std::make_pair<base::State*, base::State*>(NULL, NULL);
Planner::declareParam<double>("range", this, &RyodoSBL::setRange, &RyodoSBL::getRange, "0.:1.:10000.");
}
ompl::geometric::RyodoSBL::~RyodoSBL()
{
freeMemory();
}
void ompl::geometric::RyodoSBL::setup()
{
Planner::setup();
tools::SelfConfig sc(si_, getName());
sc.configureProjectionEvaluator(projectionEvaluator_);
sc.configurePlannerRange(maxDistance_);
tStart_.grid.setDimension(projectionEvaluator_->getDimension());
tGoal_.grid.setDimension(projectionEvaluator_->getDimension());
}
void ompl::geometric::RyodoSBL::freeGridMotions(Grid<MotionInfo> &grid)
{
for (Grid<MotionInfo>::iterator it = grid.begin(); it != grid.end() ; ++it)
{
for (unsigned int i = 0 ; i < it->second->data.size() ; ++i)
{
if (it->second->data[i]->state)
si_->freeState(it->second->data[i]->state);
delete it->second->data[i];
}
}
}
ompl::base::PlannerStatus ompl::geometric::RyodoSBL::solve(const base::PlannerTerminationCondition &ptc)
{
checkValidity();
base::GoalSampleableRegion *goal = dynamic_cast<base::GoalSampleableRegion*>(pdef_->getGoal().get());
if (!goal)
{
OMPL_ERROR("%s: Unknown type of goal", getName().c_str());
return base::PlannerStatus::UNRECOGNIZED_GOAL_TYPE;
}
while (const base::State *st = pis_.nextStart())
{
Motion *motion = new Motion(si_);
si_->copyState(motion->state, st);
motion->valid = true;
motion->root = motion->state;
addMotion(tStart_, motion);
}
if (tStart_.size == 0)
{
OMPL_ERROR("%s: Motion planning start tree could not be initialized!", getName().c_str());
return base::PlannerStatus::INVALID_START;
}
if (!goal->couldSample())
{
OMPL_ERROR("%s: Insufficient states in sampleable goal region", getName().c_str());
return base::PlannerStatus::INVALID_GOAL;
}
if (!sampler_){
si_->setValidStateSamplerAllocator(boost::bind(&allocObstacleEstimationSampler, _1));
sampler_ = si_->allocValidStateSampler();
}
OMPL_INFORM("%s: Starting planning with %d states already in datastructure", getName().c_str(), (int)(tStart_.size + tGoal_.size));
std::vector<Motion*> solution;
base::State *xstate = si_->allocState();
bool startTree = true;
bool solved = false;
while (ptc == false)
{
TreeData &tree = startTree ? tStart_ : tGoal_;
startTree = !startTree;
TreeData &otherTree = startTree ? tStart_ : tGoal_;
// if we have not sampled too many goals already
if (tGoal_.size == 0 || pis_.getSampledGoalsCount() < tGoal_.size / 2)
{
const base::State *st = tGoal_.size == 0 ? pis_.nextGoal(ptc) : pis_.nextGoal();
if (st)
{
Motion *motion = new Motion(si_);
si_->copyState(motion->state, st);
motion->root = motion->state;
motion->valid = true;
addMotion(tGoal_, motion);
}
if (tGoal_.size == 0)
{
OMPL_ERROR("%s: Unable to sample any valid states for goal tree", getName().c_str());
break;
}
}
Motion *existing = selectMotion(tree);
assert(existing);
if (!sampler_->sampleNear(xstate, existing->state, maxDistance_))
continue;
/* create a motion */
Motion *motion = new Motion(si_);
si_->copyState(motion->state, xstate);
motion->parent = existing;
motion->root = existing->root;
existing->children.push_back(motion);
addMotion(tree, motion);
if (checkSolution(!startTree, tree, otherTree, motion, solution))
{
PathGeometric *path = new PathGeometric(si_);
for (unsigned int i = 0 ; i < solution.size() ; ++i)
path->append(solution[i]->state);
pdef_->addSolutionPath(base::PathPtr(path), false, 0.0, getName());
solved = true;
break;
}
}
si_->freeState(xstate);
OMPL_INFORM("%s: Created %u (%u start + %u goal) states in %u cells (%u start + %u goal)",
getName().c_str(), tStart_.size + tGoal_.size, tStart_.size, tGoal_.size,
tStart_.grid.size() + tGoal_.grid.size(), tStart_.grid.size(), tGoal_.grid.size());
return solved ? base::PlannerStatus::EXACT_SOLUTION : base::PlannerStatus::TIMEOUT;
}
bool ompl::geometric::RyodoSBL::checkSolution(bool start, TreeData &tree, TreeData &otherTree, Motion *motion, std::vector<Motion*> &solution)
{
Grid<MotionInfo>::Coord coord;
projectionEvaluator_->computeCoordinates(motion->state, coord);
Grid<MotionInfo>::Cell* cell = otherTree.grid.getCell(coord);
if (cell && !cell->data.empty())
{
Motion *connectOther = cell->data[rng_.uniformInt(0, cell->data.size() - 1)];
if (pdef_->getGoal()->isStartGoalPairValid(start ? motion->root : connectOther->root, start ? connectOther->root : motion->root))
{
Motion *connect = new Motion(si_);
si_->copyState(connect->state, connectOther->state);
connect->parent = motion;
connect->root = motion->root; motion->children.push_back(connect);
addMotion(tree, connect);
if (isPathValid(tree, connect) && isPathValid(otherTree, connectOther))
{
if (start)
connectionPoint_ = std::make_pair(motion->state, connectOther->state);
else
connectionPoint_ = std::make_pair(connectOther->state, motion->state);
/* extract the motions and put them in solution vector */
std::vector<Motion*> mpath1;
while (motion != NULL)
{
mpath1.push_back(motion);
motion = motion->parent;
}
std::vector<Motion*> mpath2;
while (connectOther != NULL)
{
mpath2.push_back(connectOther);
connectOther = connectOther->parent;
}
if (!start)
mpath1.swap(mpath2);
for (int i = mpath1.size() - 1 ; i >= 0 ; --i)
solution.push_back(mpath1[i]);
solution.insert(solution.end(), mpath2.begin(), mpath2.end());
return true;
}
}
}
return false;
}
bool ompl::geometric::RyodoSBL::isPathValid(TreeData &tree, Motion *motion)
{
std::vector<Motion*> mpath;
/* construct the solution path */
while (motion != NULL)
{
mpath.push_back(motion);
motion = motion->parent;
}
/* check the path */
for (int i = mpath.size() - 1 ; i >= 0 ; --i)
if (!mpath[i]->valid)
{
if (si_->checkMotion(mpath[i]->parent->state, mpath[i]->state))
mpath[i]->valid = true;
else
{
removeMotion(tree, mpath[i]);
return false;
}
}
return true;
}
ompl::geometric::RyodoSBL::Motion* ompl::geometric::RyodoSBL::selectMotion(TreeData &tree)
{
GridCell* cell = tree.pdf.sample(rng_.uniform01());
return cell && !cell->data.empty() ? cell->data[rng_.uniformInt(0, cell->data.size() - 1)] : NULL;
}
void ompl::geometric::RyodoSBL::removeMotion(TreeData &tree, Motion *motion)
{
/* remove from grid */
Grid<MotionInfo>::Coord coord;
projectionEvaluator_->computeCoordinates(motion->state, coord);
Grid<MotionInfo>::Cell* cell = tree.grid.getCell(coord);
if (cell)
{
for (unsigned int i = 0 ; i < cell->data.size(); ++i)
{
if (cell->data[i] == motion)
{
cell->data.erase(cell->data.begin() + i);
tree.size--;
break;
}
}
if (cell->data.empty())
{
tree.pdf.remove(cell->data.elem_);
tree.grid.remove(cell);
tree.grid.destroyCell(cell);
}
else
{
tree.pdf.update(cell->data.elem_, 1.0/cell->data.size());
}
}
/* remove self from parent list */
if (motion->parent)
{
for (unsigned int i = 0 ; i < motion->parent->children.size() ; ++i)
{
if (motion->parent->children[i] == motion)
{
motion->parent->children.erase(motion->parent->children.begin() + i);
break;
}
}
}
/* remove children */
for (unsigned int i = 0 ; i < motion->children.size() ; ++i)
{
motion->children[i]->parent = NULL;
removeMotion(tree, motion->children[i]);
}
if (motion->state)
si_->freeState(motion->state);
delete motion;
}
void ompl::geometric::RyodoSBL::addMotion(TreeData &tree, Motion *motion)
{
Grid<MotionInfo>::Coord coord;
projectionEvaluator_->computeCoordinates(motion->state, coord);
Grid<MotionInfo>::Cell* cell = tree.grid.getCell(coord);
if (cell)
{
cell->data.push_back(motion);
tree.pdf.update(cell->data.elem_, 1.0/cell->data.size());
}
else
{
cell = tree.grid.createCell(coord);
cell->data.push_back(motion);
tree.grid.add(cell);
cell->data.elem_ = tree.pdf.add(cell, 1.0);
}
tree.size++;
}
void ompl::geometric::RyodoSBL::clear()
{
Planner::clear();
sampler_.reset();
freeMemory();
tStart_.grid.clear();
tStart_.size = 0;
tStart_.pdf.clear();
tGoal_.grid.clear();
tGoal_.size = 0;
tGoal_.pdf.clear();
connectionPoint_ = std::make_pair<base::State*, base::State*>(NULL, NULL);
}
void ompl::geometric::RyodoSBL::getPlannerData(base::PlannerData &data) const
{
Planner::getPlannerData(data);
std::vector<MotionInfo> motions;
tStart_.grid.getContent(motions);
for (unsigned int i = 0 ; i < motions.size() ; ++i)
for (unsigned int j = 0 ; j < motions[i].size() ; ++j)
if (motions[i][j]->parent == NULL)
data.addStartVertex(base::PlannerDataVertex(motions[i][j]->state, 1));
else
data.addEdge(base::PlannerDataVertex(motions[i][j]->parent->state, 1),
base::PlannerDataVertex(motions[i][j]->state, 1));
motions.clear();
tGoal_.grid.getContent(motions);
for (unsigned int i = 0 ; i < motions.size() ; ++i)
for (unsigned int j = 0 ; j < motions[i].size() ; ++j)
if (motions[i][j]->parent == NULL)
data.addGoalVertex(base::PlannerDataVertex(motions[i][j]->state, 2));
else
// The edges in the goal tree are reversed so that they are in the same direction as start tree
data.addEdge(base::PlannerDataVertex(motions[i][j]->state, 2),
base::PlannerDataVertex(motions[i][j]->parent->state, 2));
data.addEdge(data.vertexIndex(connectionPoint_.first), data.vertexIndex(connectionPoint_.second));
}
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <algorithm>
#include <memory>
#include <boost/variant/variant.hpp>
#include "VariableChecker.hpp"
#include "ast/Program.hpp"
#include "IsConstantVisitor.hpp"
#include "GetTypeVisitor.hpp"
#include "SemanticalException.hpp"
#include "Context.hpp"
#include "FunctionContext.hpp"
#include "Types.hpp"
#include "Variable.hpp"
#include "VisitorUtils.hpp"
#include "ASTVisitor.hpp"
using namespace eddic;
struct CheckerVisitor : public boost::static_visitor<> {
AUTO_RECURSE_PROGRAM()
AUTO_RECURSE_FUNCTION_CALLS()
AUTO_RECURSE_SIMPLE_LOOPS()
AUTO_RECURSE_BRANCHES()
AUTO_RECURSE_BINARY_CONDITION()
void operator()(ASTFunctionDeclaration& declaration){
//Add all the parameters to the function context
for(auto& parameter : declaration.Content->parameters){
Type type = stringToType(parameter.parameterType);
declaration.Content->context->addParameter(parameter.parameterName, type);
}
visit_each(*this, declaration.Content->instructions);
}
void operator()(GlobalVariableDeclaration& declaration){
if (declaration.Content->context->exists(declaration.Content->variableName)) {
throw SemanticalException("The global Variable " + declaration.Content->variableName + " has already been declared");
}
if(!boost::apply_visitor(IsConstantVisitor(), declaration.Content->value)){
throw SemanticalException("The value must be constant");
}
Type type = stringToType(declaration.Content->variableType);
declaration.Content->context->addVariable(declaration.Content->variableName, type, declaration.Content->value);
Type valueType = boost::apply_visitor(GetTypeVisitor(), declaration.Content->value);
if (valueType != type) {
throw SemanticalException("Incompatible type for global variable " + declaration.Content->variableName);
}
}
void operator()(ASTForeach& foreach){
if(foreach.Content->context->exists(foreach.Content->variableName)){
throw SemanticalException("The foreach variable " + foreach.Content->variableName + " has already been declared");
}
foreach.Content->context->addVariable(foreach.Content->variableName, stringToType(foreach.Content->variableType));
visit_each(*this, foreach.Content->instructions);
}
void operator()(ASTAssignment& assignment){
if (!assignment.Content->context->exists(assignment.Content->variableName)) {
throw SemanticalException("Variable " + assignment.Content->variableName + " has not been declared");
}
visit(*this, assignment.Content->value);
std::shared_ptr<Variable> var = assignment.Content->context->getVariable(assignment.Content->variableName);
Type valueType = boost::apply_visitor(GetTypeVisitor(), assignment.Content->value);
if (valueType != var->type()) {
throw SemanticalException("Incompatible type in assignment of variable " + assignment.Content->variableName);
}
}
void operator()(ASTDeclaration& declaration){
if (declaration.Content->context->exists(declaration.Content->variableName)) {
throw SemanticalException("Variable " + declaration.Content->variableName + " has already been declared");
}
Type variableType = stringToType(declaration.Content->variableType);
declaration.Content->context->addVariable(declaration.Content->variableName, variableType);
visit(*this, declaration.Content->value);
Type valueType = boost::apply_visitor(GetTypeVisitor(), declaration.Content->value);
if (valueType != variableType) {
throw SemanticalException("Incompatible type in declaration of variable " + declaration.Content->variableName);
}
}
void operator()(ASTSwap& swap){
if (swap.Content->lhs == swap.Content->rhs) {
throw SemanticalException("Cannot swap a variable with itself");
}
if (!swap.Content->context->exists(swap.Content->lhs) || !swap.Content->context->exists(swap.Content->rhs)) {
throw SemanticalException("Variable has not been declared in the swap");
}
swap.Content->lhs_var = swap.Content->context->getVariable(swap.Content->lhs);
swap.Content->rhs_var = swap.Content->context->getVariable(swap.Content->rhs);
if (swap.Content->lhs_var->type() != swap.Content->rhs_var->type()) {
throw SemanticalException("Swap of variables of incompatible type");
}
}
void operator()(ASTVariable& variable){
if (!variable.Content->context->exists(variable.Content->variableName)) {
throw SemanticalException("Variable " + variable.Content->variableName + " has not been declared");
}
variable.Content->var = variable.Content->context->getVariable(variable.Content->variableName);
}
void operator()(ASTComposedValue& value){
visit(*this, value.Content->first);
for_each(value.Content->operations.begin(), value.Content->operations.end(),
[&](boost::tuple<char, ASTValue>& operation){ visit(*this, operation.get<1>()); });
GetTypeVisitor visitor;
Type type = boost::apply_visitor(visitor, value.Content->first);
for(auto& operation : value.Content->operations){
Type operationType = boost::apply_visitor(visitor, operation.get<1>());
if(type != operationType){
throw SemanticalException("Incompatible type");
}
}
}
void operator()(TerminalNode&){
//Terminal nodes have no need for variable checking
}
};
void VariableChecker::check(ASTProgram& program){
CheckerVisitor visitor;
visitor(program);
}
<commit_msg>Count the references<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <algorithm>
#include <memory>
#include <boost/variant/variant.hpp>
#include "VariableChecker.hpp"
#include "ast/Program.hpp"
#include "IsConstantVisitor.hpp"
#include "GetTypeVisitor.hpp"
#include "SemanticalException.hpp"
#include "Context.hpp"
#include "FunctionContext.hpp"
#include "Types.hpp"
#include "Variable.hpp"
#include "VisitorUtils.hpp"
#include "ASTVisitor.hpp"
using namespace eddic;
struct CheckerVisitor : public boost::static_visitor<> {
AUTO_RECURSE_PROGRAM()
AUTO_RECURSE_FUNCTION_CALLS()
AUTO_RECURSE_SIMPLE_LOOPS()
AUTO_RECURSE_BRANCHES()
AUTO_RECURSE_BINARY_CONDITION()
void operator()(ASTFunctionDeclaration& declaration){
//Add all the parameters to the function context
for(auto& parameter : declaration.Content->parameters){
Type type = stringToType(parameter.parameterType);
declaration.Content->context->addParameter(parameter.parameterName, type);
}
visit_each(*this, declaration.Content->instructions);
}
void operator()(GlobalVariableDeclaration& declaration){
if (declaration.Content->context->exists(declaration.Content->variableName)) {
throw SemanticalException("The global Variable " + declaration.Content->variableName + " has already been declared");
}
if(!boost::apply_visitor(IsConstantVisitor(), declaration.Content->value)){
throw SemanticalException("The value must be constant");
}
Type type = stringToType(declaration.Content->variableType);
declaration.Content->context->addVariable(declaration.Content->variableName, type, declaration.Content->value);
Type valueType = boost::apply_visitor(GetTypeVisitor(), declaration.Content->value);
if (valueType != type) {
throw SemanticalException("Incompatible type for global variable " + declaration.Content->variableName);
}
}
void operator()(ASTForeach& foreach){
if(foreach.Content->context->exists(foreach.Content->variableName)){
throw SemanticalException("The foreach variable " + foreach.Content->variableName + " has already been declared");
}
foreach.Content->context->addVariable(foreach.Content->variableName, stringToType(foreach.Content->variableType));
visit_each(*this, foreach.Content->instructions);
}
void operator()(ASTAssignment& assignment){
if (!assignment.Content->context->exists(assignment.Content->variableName)) {
throw SemanticalException("Variable " + assignment.Content->variableName + " has not been declared");
}
visit(*this, assignment.Content->value);
auto var = assignment.Content->context->getVariable(assignment.Content->variableName);
Type valueType = boost::apply_visitor(GetTypeVisitor(), assignment.Content->value);
if (valueType != var->type()) {
throw SemanticalException("Incompatible type in assignment of variable " + assignment.Content->variableName);
}
var->addReference();
}
void operator()(ASTDeclaration& declaration){
if (declaration.Content->context->exists(declaration.Content->variableName)) {
throw SemanticalException("Variable " + declaration.Content->variableName + " has already been declared");
}
Type variableType = stringToType(declaration.Content->variableType);
declaration.Content->context->addVariable(declaration.Content->variableName, variableType);
visit(*this, declaration.Content->value);
Type valueType = boost::apply_visitor(GetTypeVisitor(), declaration.Content->value);
if (valueType != variableType) {
throw SemanticalException("Incompatible type in declaration of variable " + declaration.Content->variableName);
}
}
void operator()(ASTSwap& swap){
if (swap.Content->lhs == swap.Content->rhs) {
throw SemanticalException("Cannot swap a variable with itself");
}
if (!swap.Content->context->exists(swap.Content->lhs) || !swap.Content->context->exists(swap.Content->rhs)) {
throw SemanticalException("Variable has not been declared in the swap");
}
swap.Content->lhs_var = swap.Content->context->getVariable(swap.Content->lhs);
swap.Content->rhs_var = swap.Content->context->getVariable(swap.Content->rhs);
if (swap.Content->lhs_var->type() != swap.Content->rhs_var->type()) {
throw SemanticalException("Swap of variables of incompatible type");
}
//Reference both variables
swap.Content->lhs_var->addReference();
swap.Content->rhs_var->addReference();
}
void operator()(ASTVariable& variable){
if (!variable.Content->context->exists(variable.Content->variableName)) {
throw SemanticalException("Variable " + variable.Content->variableName + " has not been declared");
}
variable.Content->var = variable.Content->context->getVariable(variable.Content->variableName);
//Reference the variable
variable.Content->var->addReference();
}
void operator()(ASTComposedValue& value){
visit(*this, value.Content->first);
for_each(value.Content->operations.begin(), value.Content->operations.end(),
[&](boost::tuple<char, ASTValue>& operation){ visit(*this, operation.get<1>()); });
GetTypeVisitor visitor;
Type type = boost::apply_visitor(visitor, value.Content->first);
for(auto& operation : value.Content->operations){
Type operationType = boost::apply_visitor(visitor, operation.get<1>());
if(type != operationType){
throw SemanticalException("Incompatible type");
}
}
}
void operator()(TerminalNode&){
//Terminal nodes have no need for variable checking
}
};
void VariableChecker::check(ASTProgram& program){
CheckerVisitor visitor;
visitor(program);
}
<|endoftext|>
|
<commit_before>#include "loginscreenwidget.h"
#include <iostream>
#include <QCoreApplication>
#include <QFormLayout>
#include <QPalette>
#include <QDialogButtonBox>
using namespace std;
loginScreenWidget::loginScreenWidget(MainWindow * parent):
QWidget(parent) {
parent_ = parent;
//-------------------------BACKGROUND SETTINGS---------------------------
QVBoxLayout * layout = new QVBoxLayout;
QLabel * image = new QLabel(this);
image->setPixmap(QPixmap(QCoreApplication::applicationDirPath() + "/images/loginScreen2.png"));
layout->addWidget(image);
this->setLayout(layout);
//----------------------------SIZE SETTINGS---------------------------
this->setFixedHeight(720);
this->setFixedWidth(1280);
//----------------------------LINE/BUTTONS---------------------------
QFrame * fields = new QFrame(this);
QVBoxLayout * fieldsLayout = new QVBoxLayout;
fields->setFixedHeight(250);
fields->setFixedWidth(150);
QLineEdit * userLine_ = new QLineEdit("username", fields);
QLineEdit * passLine_ = new QLineEdit("password", fields);
passLine_->setEchoMode(QLineEdit::Password); // Display bullets instead of char
usernameLine = userLine_;
passLine = passLine_;
//-------------------------------BUTTONS---------------------------
creditsButton = new QPushButton("Credits", fields);
QObject::connect(creditsButton, SIGNAL(clicked()), this, SLOT(showCredits()));
connectButton = new QPushButton("Connect", fields);
QObject::connect(connectButton, SIGNAL(clicked()), this, SLOT(logIn()));
registerButton = new QPushButton("Register", fields);
QObject::connect(registerButton, SIGNAL(clicked()),this, SLOT(registerUser()));
quitButton = new QPushButton("Quit", fields);
QObject::connect(quitButton, SIGNAL(clicked()), this, SLOT(exit()));
//-----------------------CUSTOM SIGNALS CONNECTION--------------------
QObject::connect(parent_,SIGNAL(loginSuccess()),this,SLOT(acceptLogin()));
QObject::connect(parent_, SIGNAL(loginFailure(int)),this,SLOT(refuseLogin(int)));
QObject::connect(parent_, SIGNAL(registerSuccess()),this,SLOT(acceptRegister()));
QObject::connect(parent_, SIGNAL(registerFailure(int)),this,SLOT(refuseRegister(int)));
//--------------------------ADDS THE WIGETS---------------------------
fieldsLayout->addWidget(userLine_);
fieldsLayout->addWidget(passLine_);
fieldsLayout->addWidget(connectButton);
fieldsLayout->addWidget(registerButton);
fieldsLayout->addWidget(creditsButton);
fieldsLayout->addWidget(quitButton);
fields->setLayout(fieldsLayout);
fields->move(this->size().width() / 2 - 75, this->size().height() / 2);
}
void loginScreenWidget::showCredits() {
QMessageBox::information(this, "Credits",
"Application créée par Romain, Nikita et Bruno\nAvec la participation de Tsotne et Cédric\n"
"Librairie graphique utilisée : Qt 5.2.1\n"
"Background : http://fanzone.potterish.com/wp-content/gallery/video-game-hp6-playstation-3/edp_ps3_screencap_02.jpg\n"
"Dans le cadre du cours INFO-F-209\n"
"En fait, Quidditch c'est uidditch fait par Qt");
}
void loginScreenWidget::logIn() {
QString username = usernameLine->text();
QString password = passLine->text();
if ((username.isEmpty() && password.isEmpty())or((username == "username") && (password == "password"))) {
QMessageBox::warning(this, "Champs Vides", "Vous n'avez pas fourni de nom d'utilisateur et de mot de passe");
}
else {
//TODO VERIFY ID/PASSWORD
sviews::login(*parent_->getSocket(), username.toStdString(), password.toStdString());
connectButton->setDisabled(true);
connectButton->setStyleSheet("color : black;");
registerButton->setDisabled(true);
creditsButton->setDisabled(true);
//parent_->setNextScreen(MAINMENUSTATE);
//else {QMessageBox::warning(this, "Identifiants Incorrects", "Veuillez entrer les identifiants d'un compte enregistré");}
}
}
void loginScreenWidget::acceptLogin(){
parent_->setNextScreen(MAINMENUSTATE);
}
void loginScreenWidget::refuseLogin(int errorCode){
if (errorCode == 300){
QMessageBox::warning(this, "Identifiants Incorrects", "Veuillez entrer les identifiants d'un compte enregistré");
}
else if (errorCode == 401){
QMessageBox::warning(this, "Identifiants Incorrects", "Mauvais mot de passe");
}
else{
QMessageBox::warning(this, "Identifiants Incorrects", "Tu n'as pas des projets à terminer?");
}
connectButton->setStyleSheet("color : white;");
}
void loginScreenWidget::acceptRegister(){
parent_->setNextScreen(MAINMENUSTATE);
}
void loginScreenWidget::refuseRegister(int errorCode){
if (errorCode == 402){
QMessageBox::warning(this, "Identifiants Incorrects", "Ce compte est déjà enregistré! Veuillez choisir un nouvel identifiant");
}
else{
QMessageBox::warning(this, "Identifiants Incorrects", "Le serveur ne comprend rien");
}
registerButton->setStyleSheet("color : white;");
}
void loginScreenWidget::registerUser(){
registerButton->setStyleSheet("color : black;");
QDialog* dialog = new QDialog(this);
dialog->setWindowTitle("Nouveau compte");
QFormLayout form(dialog);
QLineEdit* newUserName = new QLineEdit(dialog);
QString label = QString("Nom de compte : ");
form.addRow(label,newUserName);
QLineEdit* newPassword = new QLineEdit(dialog);
newPassword->setEchoMode(QLineEdit::Password);
QString label2 = QString("Mot de passe : ");
form.addRow(label2,newPassword);
// Add some standard buttons (Cancel/Ok) at the bottom of the dialog
QDialogButtonBox buttonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
Qt::Horizontal, dialog);
form.addRow(&buttonBox);
QObject::connect(&buttonBox, SIGNAL(accepted()), dialog, SLOT(accept()));
QObject::connect(&buttonBox, SIGNAL(rejected()), dialog, SLOT(reject()));
registerButton->setStyleSheet("color : white;");
// Show the dialog as modal
QString newID;
QString newPW;
if (dialog->exec() == QDialog::Accepted) {
newID = newUserName->text();
newPW = newPassword->text();
}
}
void loginScreenWidget::exit() {
parent_->close();
}
<commit_msg>use sviews signup.<commit_after>#include "loginscreenwidget.h"
#include <iostream>
#include <QCoreApplication>
#include <QFormLayout>
#include <QPalette>
#include <QDialogButtonBox>
using namespace std;
loginScreenWidget::loginScreenWidget(MainWindow * parent):
QWidget(parent) {
parent_ = parent;
//-------------------------BACKGROUND SETTINGS---------------------------
QVBoxLayout * layout = new QVBoxLayout;
QLabel * image = new QLabel(this);
image->setPixmap(QPixmap(QCoreApplication::applicationDirPath() + "/images/loginScreen2.png"));
layout->addWidget(image);
this->setLayout(layout);
//----------------------------SIZE SETTINGS---------------------------
this->setFixedHeight(720);
this->setFixedWidth(1280);
//----------------------------LINE/BUTTONS---------------------------
QFrame * fields = new QFrame(this);
QVBoxLayout * fieldsLayout = new QVBoxLayout;
fields->setFixedHeight(250);
fields->setFixedWidth(150);
QLineEdit * userLine_ = new QLineEdit("username", fields);
QLineEdit * passLine_ = new QLineEdit("password", fields);
passLine_->setEchoMode(QLineEdit::Password); // Display bullets instead of char
usernameLine = userLine_;
passLine = passLine_;
//-------------------------------BUTTONS---------------------------
creditsButton = new QPushButton("Credits", fields);
QObject::connect(creditsButton, SIGNAL(clicked()), this, SLOT(showCredits()));
connectButton = new QPushButton("Connect", fields);
QObject::connect(connectButton, SIGNAL(clicked()), this, SLOT(logIn()));
registerButton = new QPushButton("Register", fields);
QObject::connect(registerButton, SIGNAL(clicked()),this, SLOT(registerUser()));
quitButton = new QPushButton("Quit", fields);
QObject::connect(quitButton, SIGNAL(clicked()), this, SLOT(exit()));
//-----------------------CUSTOM SIGNALS CONNECTION--------------------
QObject::connect(parent_,SIGNAL(loginSuccess()),this,SLOT(acceptLogin()));
QObject::connect(parent_, SIGNAL(loginFailure(int)),this,SLOT(refuseLogin(int)));
QObject::connect(parent_, SIGNAL(registerSuccess()),this,SLOT(acceptRegister()));
QObject::connect(parent_, SIGNAL(registerFailure(int)),this,SLOT(refuseRegister(int)));
//--------------------------ADDS THE WIGETS---------------------------
fieldsLayout->addWidget(userLine_);
fieldsLayout->addWidget(passLine_);
fieldsLayout->addWidget(connectButton);
fieldsLayout->addWidget(registerButton);
fieldsLayout->addWidget(creditsButton);
fieldsLayout->addWidget(quitButton);
fields->setLayout(fieldsLayout);
fields->move(this->size().width() / 2 - 75, this->size().height() / 2);
}
void loginScreenWidget::showCredits() {
QMessageBox::information(this, "Credits",
"Application créée par Romain, Nikita et Bruno\nAvec la participation de Tsotne et Cédric\n"
"Librairie graphique utilisée : Qt 5.2.1\n"
"Background : http://fanzone.potterish.com/wp-content/gallery/video-game-hp6-playstation-3/edp_ps3_screencap_02.jpg\n"
"Dans le cadre du cours INFO-F-209\n"
"En fait, Quidditch c'est uidditch fait par Qt");
}
void loginScreenWidget::logIn() {
QString username = usernameLine->text();
QString password = passLine->text();
if ((username.isEmpty() && password.isEmpty())or((username == "username") && (password == "password"))) {
QMessageBox::warning(this, "Champs Vides", "Vous n'avez pas fourni de nom d'utilisateur et de mot de passe");
}
else {
//TODO VERIFY ID/PASSWORD
sviews::login(*parent_->getSocket(), username.toStdString(), password.toStdString());
connectButton->setDisabled(true);
connectButton->setStyleSheet("color : black;");
registerButton->setDisabled(true);
creditsButton->setDisabled(true);
//parent_->setNextScreen(MAINMENUSTATE);
//else {QMessageBox::warning(this, "Identifiants Incorrects", "Veuillez entrer les identifiants d'un compte enregistré");}
}
}
void loginScreenWidget::acceptLogin(){
parent_->setNextScreen(MAINMENUSTATE);
}
void loginScreenWidget::refuseLogin(int errorCode){
if (errorCode == 300){
QMessageBox::warning(this, "Identifiants Incorrects", "Veuillez entrer les identifiants d'un compte enregistré");
}
else if (errorCode == 401){
QMessageBox::warning(this, "Identifiants Incorrects", "Mauvais mot de passe");
}
else{
QMessageBox::warning(this, "Identifiants Incorrects", "Tu n'as pas des projets à terminer?");
}
connectButton->setStyleSheet("color : white;");
}
void loginScreenWidget::acceptRegister(){
parent_->setNextScreen(MAINMENUSTATE);
}
void loginScreenWidget::refuseRegister(int errorCode){
if (errorCode == 402){
QMessageBox::warning(this, "Identifiants Incorrects", "Ce compte est déjà enregistré! Veuillez choisir un nouvel identifiant");
}
else{
QMessageBox::warning(this, "Identifiants Incorrects", "Le serveur ne comprend rien");
}
registerButton->setStyleSheet("color : white;");
}
void loginScreenWidget::registerUser(){
registerButton->setStyleSheet("color : black;");
QDialog* dialog = new QDialog(this);
dialog->setWindowTitle("Nouveau compte");
QFormLayout form(dialog);
QLineEdit* newUserName = new QLineEdit(dialog);
QString label = QString("Nom de compte : ");
form.addRow(label,newUserName);
QLineEdit* newPassword = new QLineEdit(dialog);
newPassword->setEchoMode(QLineEdit::Password);
QString label2 = QString("Mot de passe : ");
form.addRow(label2,newPassword);
// Add some standard buttons (Cancel/Ok) at the bottom of the dialog
QDialogButtonBox buttonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
Qt::Horizontal, dialog);
form.addRow(&buttonBox);
QObject::connect(&buttonBox, SIGNAL(accepted()), dialog, SLOT(accept()));
QObject::connect(&buttonBox, SIGNAL(rejected()), dialog, SLOT(reject()));
registerButton->setStyleSheet("color : white;");
// Show the dialog as modal
QString newID;
QString newPW;
if (dialog->exec() == QDialog::Accepted) {
newID = newUserName->text();
newPW = newPassword->text();
sviews::signup(*parent_->getSocket(), newID.toStdString(), newPW.toStdString());
}
}
void loginScreenWidget::exit() {
parent_->close();
}
<|endoftext|>
|
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
// Blueberry
#include <berryISelectionService.h>
#include <berryIWorkbenchWindow.h>
//Mitk
#include <mitkDataNode.h>
#include <mitkNodePredicateNot.h>
#include <mitkNodePredicateProperty.h>
// Qmitk
#include "UltrasoundSupport.h"
#include <QTimer>
// Qt
#include <QMessageBox>
// Ultrasound
#include "mitkUSDevice.h"
#include "QmitkUSAbstractCustomWidget.h"
#include <usModuleContext.h>
#include <usGetModuleContext.h>
#include "usServiceReference.h"
#include "internal/org_mitk_gui_qt_ultrasound_Activator.h"
#include <ctkFlowLayout.h>
#include <ctkDoubleSlider.h>
const std::string UltrasoundSupport::VIEW_ID = "org.mitk.views.ultrasoundsupport";
void UltrasoundSupport::SetFocus()
{
//m_Controls.m_AddDevice->setFocus();
}
void UltrasoundSupport::CreateQtPartControl( QWidget *parent )
{
m_Timer = new QTimer(this);
// create GUI widgets from the Qt Designer's .ui file
m_Controls.setupUi( parent );
connect( m_Controls.m_DeviceManagerWidget, SIGNAL(NewDeviceButtonClicked()), this, SLOT(OnClickedAddNewDevice()) ); // Change Widget Visibilities
connect( m_Controls.m_DeviceManagerWidget, SIGNAL(NewDeviceButtonClicked()), this->m_Controls.m_NewVideoDeviceWidget, SLOT(CreateNewDevice()) ); // Init NewDeviceWidget
connect( m_Controls.m_NewVideoDeviceWidget, SIGNAL(Finished()), this, SLOT(OnNewDeviceWidgetDone()) ); // After NewDeviceWidget finished editing
connect( m_Controls.m_BtnView, SIGNAL(clicked()), this, SLOT(OnClickedViewDevice()) );
connect( m_Timer, SIGNAL(timeout()), this, SLOT(DisplayImage()));
// Initializations
m_Controls.m_NewVideoDeviceWidget->setVisible(false);
std::string filter = "(&(" + us::ServiceConstants::OBJECTCLASS() + "=" + "org.mitk.services.UltrasoundDevice)(" + mitk::USDevice::US_PROPKEY_ISACTIVE + "=true))";
m_Controls.m_ActiveVideoDevices->Initialize<mitk::USDevice>(mitk::USDevice::US_PROPKEY_LABEL ,filter);
m_Node = mitk::DataNode::New();
m_Node->SetName("US Image Stream");
this->GetDataStorage()->Add(m_Node);
m_Controls.tabWidget->setTabEnabled(1, false);
/*ctkFlowLayout* flowLayout = ctkFlowLayout::replaceLayout(m_Controls.m_WidgetDevices);
flowLayout->setAlignItems(true);
flowLayout->setOrientation(Qt::Vertical);*/
}
void UltrasoundSupport::OnClickedAddNewDevice()
{
m_Controls.m_NewVideoDeviceWidget->setVisible(true);
m_Controls.m_DeviceManagerWidget->setVisible(false);
m_Controls.m_Headline->setText("Add New Video Device:");
m_Controls.m_WidgetActiveDevices->setVisible(false);
}
void UltrasoundSupport::DisplayImage()
{
m_Device->UpdateOutputData(0);
mitk::Image::Pointer curOutput = m_Device->GetOutput();
m_Node->SetData(curOutput);
this->RequestRenderWindowUpdate();
if ( curOutput->GetDimension() > 1
&& (curOutput->GetDimension(0) != m_CurrentImageWidth
|| curOutput->GetDimension(1) != m_CurrentImageHeight) )
{
this->GlobalReinit();
m_CurrentImageWidth = curOutput->GetDimension(0);
m_CurrentImageHeight = curOutput->GetDimension(1);
}
m_FrameCounter ++;
if (m_FrameCounter == 10)
{
int nMilliseconds = m_Clock.restart();
int fps = 10000.0f / (nMilliseconds );
m_Controls.m_FramerateLabel->setText("Current Framerate: "+ QString::number(fps) +" FPS");
m_FrameCounter = 0;
}
}
void UltrasoundSupport::OnClickedViewDevice()
{
m_FrameCounter = 0;
// We use the activity state of the timer to determine whether we are currently viewing images
if ( ! m_Timer->isActive() ) // Activate Imaging
{
m_Controls.tabWidget->setTabEnabled(1, true);
m_Controls.tabWidget->setCurrentIndex(1);
//get device & set data node
m_Device = m_Controls.m_ActiveVideoDevices->GetSelectedService<mitk::USDevice>();
if (m_Device.IsNull()){
m_Timer->stop();
return;
}
m_Device->Update();
m_Node->SetData(m_Device->GetOutput());
//start timer
int interval = (1000 / m_Controls.m_FrameRate->value());
m_Timer->setInterval(interval);
m_Timer->start();
//reinit view
//this->GlobalReinit();
//change UI elements
m_Controls.m_BtnView->setText("Stop Viewing");
m_Controls.m_FrameRate->setEnabled(false);
m_ControlProbesWidget = new QmitkUSControlsProbesWidget(m_Device->GetControlInterfaceProbes(), m_Controls.m_ToolBoxControlWidgets);
m_Controls.probesWidgetContainer->addWidget(m_ControlProbesWidget);
// create b mode widget for current device
m_ControlBModeWidget = new QmitkUSControlsBModeWidget(m_Device->GetControlInterfaceBMode(), m_Controls.m_ToolBoxControlWidgets);
m_Controls.m_ToolBoxControlWidgets->addItem(m_ControlBModeWidget, "B Mode Controls");
if ( ! m_Device->GetControlInterfaceBMode() )
{
m_Controls.m_ToolBoxControlWidgets->setItemEnabled(m_Controls.m_ToolBoxControlWidgets->count()-1, false);
}
// create doppler widget for current device
m_ControlDopplerWidget = new QmitkUSControlsDopplerWidget(m_Device->GetControlInterfaceDoppler(), m_Controls.m_ToolBoxControlWidgets);
m_Controls.m_ToolBoxControlWidgets->addItem(m_ControlDopplerWidget, "Doppler Controls");
if ( ! m_Device->GetControlInterfaceDoppler() )
{
m_Controls.m_ToolBoxControlWidgets->setItemEnabled(m_Controls.m_ToolBoxControlWidgets->count()-1, false);
}
ctkPluginContext* pluginContext = mitk::PluginActivator::GetContext();
if ( pluginContext )
{
std::string filter = "(ork.mitk.services.UltrasoundCustomWidget.deviceClass=" + m_Device->GetDeviceClass() + ")";
QString interfaceName ( us_service_interface_iid<QmitkUSAbstractCustomWidget>() );
m_CustomWidgetServiceReference = pluginContext->getServiceReferences(interfaceName, QString::fromStdString(filter));
if (m_CustomWidgetServiceReference.size() > 0)
{
m_ControlCustomWidget = pluginContext->getService<QmitkUSAbstractCustomWidget>
(m_CustomWidgetServiceReference.at(0))->CloneForQt(m_Controls.tab2);
m_ControlCustomWidget->SetDevice(m_Device);
//m_Controls.tab2->layout()->addWidget(m_ControlCustomWidget);
m_Controls.m_ToolBoxControlWidgets->addItem(m_ControlCustomWidget, "Custom Controls");
}
else
{
m_Controls.m_ToolBoxControlWidgets->addItem(new QWidget(m_Controls.m_ToolBoxControlWidgets), "Custom Controls");
m_Controls.m_ToolBoxControlWidgets->setItemEnabled(m_Controls.m_ToolBoxControlWidgets->count()-1, false);
}
}
}
else //deactivate imaging
{
m_Controls.tabWidget->setTabEnabled(1, false);
while (m_Controls.m_ToolBoxControlWidgets->count() > 0)
{
m_Controls.m_ToolBoxControlWidgets->removeItem(0);
}
m_Controls.probesWidgetContainer->removeWidget(m_ControlProbesWidget);
//m_Controls.tab2->layout()->removeWidget(m_ControlProbesWidget);
delete m_ControlProbesWidget;
m_ControlProbesWidget = 0;
//m_Controls.tab2->layout()->removeWidget(m_ControlBModeWidget);
delete m_ControlBModeWidget;
m_ControlBModeWidget = 0;
delete m_ControlDopplerWidget;
m_ControlDopplerWidget = 0;
if ( m_ControlCustomWidget )
{
ctkPluginContext* pluginContext = mitk::PluginActivator::GetContext();
//m_Controls.tab2->layout()->removeWidget(m_ControlCustomWidget);
delete m_ControlCustomWidget; m_ControlCustomWidget = 0;
if ( m_CustomWidgetServiceReference.size() > 0 )
{
pluginContext->ungetService(m_CustomWidgetServiceReference.at(0));
}
}
//stop timer & release data
m_Timer->stop();
m_Node->ReleaseData();
this->RequestRenderWindowUpdate();
//change UI elements
m_Controls.m_BtnView->setText("Start Viewing");
m_Controls.m_FrameRate->setEnabled(true);
}
}
void UltrasoundSupport::OnNewDeviceWidgetDone()
{
m_Controls.m_NewVideoDeviceWidget->setVisible(false);
m_Controls.m_DeviceManagerWidget->setVisible(true);
m_Controls.m_Headline->setText("Ultrasound Devices:");
m_Controls.m_WidgetActiveDevices->setVisible(true);
}
void UltrasoundSupport::GlobalReinit()
{
// get all nodes that have not set "includeInBoundingBox" to false
mitk::NodePredicateNot::Pointer pred = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("includeInBoundingBox", mitk::BoolProperty::New(false)));
mitk::DataStorage::SetOfObjects::ConstPointer rs = this->GetDataStorage()->GetSubset(pred);
// calculate bounding geometry of these nodes
mitk::TimeSlicedGeometry::Pointer bounds = this->GetDataStorage()->ComputeBoundingGeometry3D(rs, "visible");
// initialize the views to the bounding geometry
mitk::RenderingManager::GetInstance()->InitializeViews(bounds);
}
/*void UltrasoundSupport::OnPreferencesChanged(const berry::IBerryPreferences* prefs)
{
std::cout << prefs << std::endl;
}*/
UltrasoundSupport::UltrasoundSupport()
: m_ControlCustomWidget(0),
m_ControlBModeWidget(0),
m_ControlProbesWidget(0),
m_CurrentImageWidth(0),
m_CurrentImageHeight(0)
{
}
UltrasoundSupport::~UltrasoundSupport()
{
}<commit_msg>First available control interface is selected on start viewing.<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
// Blueberry
#include <berryISelectionService.h>
#include <berryIWorkbenchWindow.h>
//Mitk
#include <mitkDataNode.h>
#include <mitkNodePredicateNot.h>
#include <mitkNodePredicateProperty.h>
// Qmitk
#include "UltrasoundSupport.h"
#include <QTimer>
// Qt
#include <QMessageBox>
// Ultrasound
#include "mitkUSDevice.h"
#include "QmitkUSAbstractCustomWidget.h"
#include <usModuleContext.h>
#include <usGetModuleContext.h>
#include "usServiceReference.h"
#include "internal/org_mitk_gui_qt_ultrasound_Activator.h"
#include <ctkFlowLayout.h>
#include <ctkDoubleSlider.h>
const std::string UltrasoundSupport::VIEW_ID = "org.mitk.views.ultrasoundsupport";
void UltrasoundSupport::SetFocus()
{
//m_Controls.m_AddDevice->setFocus();
}
void UltrasoundSupport::CreateQtPartControl( QWidget *parent )
{
m_Timer = new QTimer(this);
// create GUI widgets from the Qt Designer's .ui file
m_Controls.setupUi( parent );
connect( m_Controls.m_DeviceManagerWidget, SIGNAL(NewDeviceButtonClicked()), this, SLOT(OnClickedAddNewDevice()) ); // Change Widget Visibilities
connect( m_Controls.m_DeviceManagerWidget, SIGNAL(NewDeviceButtonClicked()), this->m_Controls.m_NewVideoDeviceWidget, SLOT(CreateNewDevice()) ); // Init NewDeviceWidget
connect( m_Controls.m_NewVideoDeviceWidget, SIGNAL(Finished()), this, SLOT(OnNewDeviceWidgetDone()) ); // After NewDeviceWidget finished editing
connect( m_Controls.m_BtnView, SIGNAL(clicked()), this, SLOT(OnClickedViewDevice()) );
connect( m_Timer, SIGNAL(timeout()), this, SLOT(DisplayImage()));
// Initializations
m_Controls.m_NewVideoDeviceWidget->setVisible(false);
std::string filter = "(&(" + us::ServiceConstants::OBJECTCLASS() + "=" + "org.mitk.services.UltrasoundDevice)(" + mitk::USDevice::US_PROPKEY_ISACTIVE + "=true))";
m_Controls.m_ActiveVideoDevices->Initialize<mitk::USDevice>(mitk::USDevice::US_PROPKEY_LABEL ,filter);
m_Node = mitk::DataNode::New();
m_Node->SetName("US Image Stream");
this->GetDataStorage()->Add(m_Node);
m_Controls.tabWidget->setTabEnabled(1, false);
/*ctkFlowLayout* flowLayout = ctkFlowLayout::replaceLayout(m_Controls.m_WidgetDevices);
flowLayout->setAlignItems(true);
flowLayout->setOrientation(Qt::Vertical);*/
}
void UltrasoundSupport::OnClickedAddNewDevice()
{
m_Controls.m_NewVideoDeviceWidget->setVisible(true);
m_Controls.m_DeviceManagerWidget->setVisible(false);
m_Controls.m_Headline->setText("Add New Video Device:");
m_Controls.m_WidgetActiveDevices->setVisible(false);
}
void UltrasoundSupport::DisplayImage()
{
m_Device->UpdateOutputData(0);
mitk::Image::Pointer curOutput = m_Device->GetOutput();
m_Node->SetData(curOutput);
this->RequestRenderWindowUpdate();
if ( curOutput->GetDimension() > 1
&& (curOutput->GetDimension(0) != m_CurrentImageWidth
|| curOutput->GetDimension(1) != m_CurrentImageHeight) )
{
this->GlobalReinit();
m_CurrentImageWidth = curOutput->GetDimension(0);
m_CurrentImageHeight = curOutput->GetDimension(1);
}
m_FrameCounter ++;
if (m_FrameCounter == 10)
{
int nMilliseconds = m_Clock.restart();
int fps = 10000.0f / (nMilliseconds );
m_Controls.m_FramerateLabel->setText("Current Framerate: "+ QString::number(fps) +" FPS");
m_FrameCounter = 0;
}
}
void UltrasoundSupport::OnClickedViewDevice()
{
m_FrameCounter = 0;
// We use the activity state of the timer to determine whether we are currently viewing images
if ( ! m_Timer->isActive() ) // Activate Imaging
{
m_Controls.tabWidget->setTabEnabled(1, true);
m_Controls.tabWidget->setCurrentIndex(1);
//get device & set data node
m_Device = m_Controls.m_ActiveVideoDevices->GetSelectedService<mitk::USDevice>();
if (m_Device.IsNull()){
m_Timer->stop();
return;
}
m_Device->Update();
m_Node->SetData(m_Device->GetOutput());
//start timer
int interval = (1000 / m_Controls.m_FrameRate->value());
m_Timer->setInterval(interval);
m_Timer->start();
//reinit view
//this->GlobalReinit();
//change UI elements
m_Controls.m_BtnView->setText("Stop Viewing");
m_Controls.m_FrameRate->setEnabled(false);
m_ControlProbesWidget = new QmitkUSControlsProbesWidget(m_Device->GetControlInterfaceProbes(), m_Controls.m_ToolBoxControlWidgets);
m_Controls.probesWidgetContainer->addWidget(m_ControlProbesWidget);
unsigned int firstEnabledControl = -1;
// create b mode widget for current device
m_ControlBModeWidget = new QmitkUSControlsBModeWidget(m_Device->GetControlInterfaceBMode(), m_Controls.m_ToolBoxControlWidgets);
m_Controls.m_ToolBoxControlWidgets->addItem(m_ControlBModeWidget, "B Mode Controls");
if ( ! m_Device->GetControlInterfaceBMode() )
{
m_Controls.m_ToolBoxControlWidgets->setItemEnabled(m_Controls.m_ToolBoxControlWidgets->count()-1, false);
}
else
{
if ( firstEnabledControl == -1 ) { firstEnabledControl = 0; }
}
// create doppler widget for current device
m_ControlDopplerWidget = new QmitkUSControlsDopplerWidget(m_Device->GetControlInterfaceDoppler(), m_Controls.m_ToolBoxControlWidgets);
m_Controls.m_ToolBoxControlWidgets->addItem(m_ControlDopplerWidget, "Doppler Controls");
if ( ! m_Device->GetControlInterfaceDoppler() )
{
m_Controls.m_ToolBoxControlWidgets->setItemEnabled(m_Controls.m_ToolBoxControlWidgets->count()-1, false);
}
else
{
if ( firstEnabledControl == -1 ) { firstEnabledControl = 0; }
}
ctkPluginContext* pluginContext = mitk::PluginActivator::GetContext();
if ( pluginContext )
{
std::string filter = "(ork.mitk.services.UltrasoundCustomWidget.deviceClass=" + m_Device->GetDeviceClass() + ")";
QString interfaceName ( us_service_interface_iid<QmitkUSAbstractCustomWidget>() );
m_CustomWidgetServiceReference = pluginContext->getServiceReferences(interfaceName, QString::fromStdString(filter));
if (m_CustomWidgetServiceReference.size() > 0)
{
m_ControlCustomWidget = pluginContext->getService<QmitkUSAbstractCustomWidget>
(m_CustomWidgetServiceReference.at(0))->CloneForQt(m_Controls.tab2);
m_ControlCustomWidget->SetDevice(m_Device);
//m_Controls.tab2->layout()->addWidget(m_ControlCustomWidget);
m_Controls.m_ToolBoxControlWidgets->addItem(m_ControlCustomWidget, "Custom Controls");
}
else
{
m_Controls.m_ToolBoxControlWidgets->addItem(new QWidget(m_Controls.m_ToolBoxControlWidgets), "Custom Controls");
m_Controls.m_ToolBoxControlWidgets->setItemEnabled(m_Controls.m_ToolBoxControlWidgets->count()-1, false);
}
}
// select first enabled control widget
for ( unsigned int n = 0; n < m_Controls.m_ToolBoxControlWidgets->count(); ++n)
{
if ( m_Controls.m_ToolBoxControlWidgets->isItemEnabled(n) )
{
m_Controls.m_ToolBoxControlWidgets->setCurrentIndex(n);
break;
}
}
}
else //deactivate imaging
{
m_Controls.tabWidget->setTabEnabled(1, false);
while (m_Controls.m_ToolBoxControlWidgets->count() > 0)
{
m_Controls.m_ToolBoxControlWidgets->removeItem(0);
}
m_Controls.probesWidgetContainer->removeWidget(m_ControlProbesWidget);
//m_Controls.tab2->layout()->removeWidget(m_ControlProbesWidget);
delete m_ControlProbesWidget;
m_ControlProbesWidget = 0;
//m_Controls.tab2->layout()->removeWidget(m_ControlBModeWidget);
delete m_ControlBModeWidget;
m_ControlBModeWidget = 0;
delete m_ControlDopplerWidget;
m_ControlDopplerWidget = 0;
if ( m_ControlCustomWidget )
{
ctkPluginContext* pluginContext = mitk::PluginActivator::GetContext();
//m_Controls.tab2->layout()->removeWidget(m_ControlCustomWidget);
delete m_ControlCustomWidget; m_ControlCustomWidget = 0;
if ( m_CustomWidgetServiceReference.size() > 0 )
{
pluginContext->ungetService(m_CustomWidgetServiceReference.at(0));
}
}
//stop timer & release data
m_Timer->stop();
m_Node->ReleaseData();
this->RequestRenderWindowUpdate();
//change UI elements
m_Controls.m_BtnView->setText("Start Viewing");
m_Controls.m_FrameRate->setEnabled(true);
}
}
void UltrasoundSupport::OnNewDeviceWidgetDone()
{
m_Controls.m_NewVideoDeviceWidget->setVisible(false);
m_Controls.m_DeviceManagerWidget->setVisible(true);
m_Controls.m_Headline->setText("Ultrasound Devices:");
m_Controls.m_WidgetActiveDevices->setVisible(true);
}
void UltrasoundSupport::GlobalReinit()
{
// get all nodes that have not set "includeInBoundingBox" to false
mitk::NodePredicateNot::Pointer pred = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("includeInBoundingBox", mitk::BoolProperty::New(false)));
mitk::DataStorage::SetOfObjects::ConstPointer rs = this->GetDataStorage()->GetSubset(pred);
// calculate bounding geometry of these nodes
mitk::TimeSlicedGeometry::Pointer bounds = this->GetDataStorage()->ComputeBoundingGeometry3D(rs, "visible");
// initialize the views to the bounding geometry
mitk::RenderingManager::GetInstance()->InitializeViews(bounds);
}
/*void UltrasoundSupport::OnPreferencesChanged(const berry::IBerryPreferences* prefs)
{
std::cout << prefs << std::endl;
}*/
UltrasoundSupport::UltrasoundSupport()
: m_ControlCustomWidget(0),
m_ControlBModeWidget(0),
m_ControlProbesWidget(0),
m_CurrentImageWidth(0),
m_CurrentImageHeight(0)
{
}
UltrasoundSupport::~UltrasoundSupport()
{
}<|endoftext|>
|
<commit_before>#define BENCHMARK_HAS_CXX11
#include "benchmark/benchmark.h"
#include "serialisation/serialisation.h"
#include <sstream>
#include <chrono>
class Testclass
{
public:
Testclass()
{
std::stringstream ss;
ss << rand();
mValue1 = rand();
while ( ( mValue2 = Util::UInt32ToFloat( rand() ) ) == std::numeric_limits< float >::infinity() );
mValue3 = ss.str();
}
template< typename tT >
void SERIALISATION_CUSTOM_INTERFACE( Message< tT > &message )
{
message.Store( 0, mValue1 );
message.Store( 1, mValue2 );
message.Store( 2, mValue3 );
}
size_t GetMemberSize()
{
return sizeof( uint32_t ) + sizeof( float ) + mValue3.length();
}
private:
uint32_t mValue1;
float mValue2;
std::string mValue3;
};
// class Testclass2
// : public ISerialisable
// {
// public:
// Testclass2()
// {
// std::stringstream ss;
// ss << rand();
// mValue1 = rand();
// while ( ( mValue2 = Util::UInt32ToFloat( rand() ) ) == std::numeric_limits< float >::infinity() );
// mValue3 = ss.str();
// }
// void SERIALISATION_CUSTOM_INTERFACE( Message &message )
// {
// message.Store( 3, mValue4 );
// message.Store( 2, mValue3 );
// message.Store( 1, mValue2 );
// message.Store( 0, mValue1 );
// }
// private:
// uint32_t mValue1;
// float mValue2;
// std::string mValue3;
// Testclass mValue4;
// };
class Testclass3
{
public:
Testclass3()
{
std::stringstream ss;
ss << rand();
mValue1 = rand();
while ( ( mValue2 = Util::UInt32ToFloat( rand() ) ) == std::numeric_limits< float >::infinity() );
mValue3 = ss.str();
}
template<typename tMessage>
void SERIALISATION_CUSTOM_INTERFACE( tMessage &message )
{
message.Store( 3, mValue4 );
message.Store( 2, mValue3 );
message.Store( 1, mValue2 );
message.Store( 0, mValue1 );
}
size_t GetMemberSize()
{
return sizeof( uint32_t ) + sizeof( float ) + mValue3.length() + mValue4.GetMemberSize();
}
private:
uint32_t mValue1;
float mValue2;
std::string mValue3;
Testclass mValue4;
};
class Testclass3Reordered
{
public:
Testclass3Reordered()
{
std::stringstream ss;
ss << rand();
mValue1 = rand();
while ( ( mValue2 = Util::UInt32ToFloat( rand() ) ) == std::numeric_limits< float >::infinity() );
mValue3 = ss.str();
}
template<typename tMessage>
void SERIALISATION_CUSTOM_INTERFACE( tMessage &message )
{
message.Store( 0, mValue1 );
message.Store( 1, mValue2 );
message.Store( 2, mValue3 );
message.Store( 3, mValue4 );
}
size_t GetMemberSize()
{
return sizeof( uint32_t ) + sizeof( float ) + mValue3.length() + mValue4.GetMemberSize();
}
private:
uint32_t mValue1;
float mValue2;
std::string mValue3;
Testclass mValue4;
};
// template< typename tImpl >
// static void BM_OLS( benchmark::State &state )
// {
// double a = Random::GenerateRandomF64( -NUMERICAL_OLS_MAX_SAMPLES, NUMERICAL_OLS_MAX_SAMPLES );
// double b = a + Random::GenerateRandomF64( -NUMERICAL_OLS_MAX_SAMPLES, NUMERICAL_OLS_MAX_SAMPLES );
// double alpha = Random::GenerateRandomF64( -NUMERICAL_OLS_MAX_SAMPLES, NUMERICAL_OLS_MAX_SAMPLES );
// double beta = Random::GenerateRandomF64( -10000, 10000 );
// vec ex = linspace( a, b, state.range_x() );
// vec end = ex * beta + alpha;
// while ( state.KeepRunning() )
// {
// LinReg<tImpl> ols( end, ex );
// ols.Fit();
// }
// state.SetItemsProcessed( state.iterations() );
// state.SetBytesProcessed( state.iterations() * state.range_x() * sizeof( double ) );
// state.SetComplexityN( state.range_x() );
// }
// BENCHMARK_TEMPLATE( BM_OLS, LinealOLSImpl )->Range( 10, 20000 )->Complexity();
// BENCHMARK_TEMPLATE( BM_OLS, QROLSImpl )->Range( 10, 20000 )->Complexity();
// BENCHMARK_TEMPLATE( BM_OLS, SVDOLSImpl )->Range( 10, 20000 )->Complexity();
// BENCHMARK_TEMPLATE( BM_OLS, FGLSImpl )->Range( 10, 20000 )->Complexity();
template< typename tFunc >
static inline void TimeManual( benchmark::State &state, const tFunc &func )
{
auto start = std::chrono::high_resolution_clock::now();
func();
auto end = std::chrono::high_resolution_clock::now();
auto elapsed_seconds =
std::chrono::duration_cast<std::chrono::duration<double>>(
end - start );
state.SetIterationTime( elapsed_seconds.count() );
}
static void BM_VarInt( benchmark::State &state )
{
while ( state.KeepRunning() )
{
benchmark::DoNotOptimize( VarInt<std::numeric_limits<uint64_t>::max()>() );
}
state.SetItemsProcessed( state.iterations() );
state.SetBytesProcessed( state.iterations() * sizeof( uint64_t ) );
}
static void BM_VarIntSize( benchmark::State &state )
{
while ( state.KeepRunning() )
{
benchmark::DoNotOptimize( VarIntSize<std::numeric_limits<uint64_t>::max()>() );
}
state.SetItemsProcessed( state.iterations() );
state.SetBytesProcessed( state.iterations() * sizeof( uint64_t ) );
}
static void BM_StoreU32( benchmark::State &state )
{
uint32_t x = static_cast<uint32_t>( state.range_x() );
{
std::stringstream ss;
Message< BinarySerialisationMessage< BufferedStreamWriter<> > > message( ss );
while ( state.KeepRunning() )
{
message.Store( 0, x );
}
}
state.SetItemsProcessed( state.iterations() );
state.SetBytesProcessed( state.iterations() * sizeof( uint64_t ) );
state.SetComplexityN( static_cast<int>( x ) );
}
static void BM_CreateHeaderCT( benchmark::State &state )
{
while ( state.KeepRunning() )
{
benchmark::DoNotOptimize( Util::CreateHeader<uint32_t>( 0 ) );
}
state.SetItemsProcessed( state.iterations() );
state.SetBytesProcessed( state.iterations() * sizeof( uint64_t ) );
}
static void BM_CreateHeader( benchmark::State &state )
{
volatile uint8_t index = 0;
while ( state.KeepRunning() )
{
benchmark::DoNotOptimize( Util::CreateHeader<uint32_t>( index ) );
}
state.SetItemsProcessed( state.iterations() );
state.SetBytesProcessed( state.iterations() * sizeof( uint64_t ) );
}
static void BM_NormalNestedDeser( benchmark::State &state )
{
Testclass3 tc, tc2;
uint32_t nObj = 200;
std::stringstream ssSource;
{
Serialisation::BinarySerialiser serMessage( ssSource );
for ( uint32_t i = 0; i < nObj; ++i )
{
serMessage.Enter( tc );
}
}
while ( state.KeepRunning() )
{
{
std::stringstream ss( ssSource.str() );
Message< BinaryDeserialisationMessage< BufferedStreamReader<> > > deserMessage( ss );
TimeManual( state, [&]()
{
for ( uint32_t i = 0; i < nObj; ++i )
{
deserMessage.Enter( tc2 );
}
} );
}
}
state.SetItemsProcessed( state.iterations() * nObj );
state.SetBytesProcessed( state.iterations() * nObj * tc.GetMemberSize() );
}
static void BM_ReorderedNestedDeser( benchmark::State &state )
{
Testclass3 tc;
Testclass3Reordered tc2;
uint32_t nObj = 200;
std::stringstream ssSource;
{
Serialisation::BinarySerialiser serMessage( ssSource );
for ( uint32_t i = 0; i < nObj; ++i )
{
serMessage.Enter( tc );
}
}
while ( state.KeepRunning() )
{
{
std::stringstream ss( ssSource.str() );
Message< BinaryDeserialisationMessage< BufferedStreamReader<> > > deserMessage( ss );
TimeManual( state, [&]()
{
for ( uint32_t i = 0; i < nObj; ++i )
{
deserMessage.Enter( tc2 );
}
} );
}
}
state.SetItemsProcessed( state.iterations() * nObj );
state.SetBytesProcessed( state.iterations() * nObj * tc.GetMemberSize() );
}
static void BM_NormalNestedSer( benchmark::State &state )
{
Testclass3 tc;
uint32_t nObj = 200;
while ( state.KeepRunning() )
{
{
std::stringstream ss;
Message< BinarySerialisationMessage<BufferedStreamWriter<> > > serMessage( ss );
TimeManual( state, [&]()
{
for ( uint32_t i = 0; i < nObj; ++i )
{
serMessage.Enter( tc );
}
} );
}
}
state.SetItemsProcessed( state.iterations() * nObj );
state.SetBytesProcessed( state.iterations() * nObj * tc.GetMemberSize() );
}
template< typename tT >
class TestClassArray
{
public:
TestClassArray()
{
mValue1.resize( ( rand() % 8192 ) + 8192 );
for ( auto it = mValue1.begin(); it != mValue1.end(); ++it )
{
*it = static_cast<tT>( rand() );
}
}
template< typename tT >
void OnStore( Message< tT > &message )
{
message.Store( 0, mValue1 );
}
size_t GetMemberSize()
{
return mValue1.size() * sizeof( tT );
}
private:
std::vector<tT> mValue1;
};
static void BM_FloatArraySer( benchmark::State &state )
{
TestClassArray<float> tc;
uint32_t nObj = 1;
while ( state.KeepRunning() )
{
{
std::stringstream ss;
Message< BinarySerialisationMessage<BufferedStreamWriter<> > > serMessage( ss );
TimeManual( state, [&]()
{
for ( uint32_t i = 0; i < nObj; ++i )
{
serMessage.Enter( tc );
}
} );
}
}
state.SetItemsProcessed( state.iterations() * nObj );
state.SetBytesProcessed( state.iterations() * nObj * tc.GetMemberSize() );
}
static void BM_IntArraySer( benchmark::State &state )
{
TestClassArray<uint32_t> tc;
uint32_t nObj = 1;
while ( state.KeepRunning() )
{
{
std::stringstream ss;
Message< BinarySerialisationMessage<BufferedStreamWriter<> > > serMessage( ss );
TimeManual( state, [&]()
{
for ( uint32_t i = 0; i < nObj; ++i )
{
serMessage.Enter( tc );
}
} );
}
}
state.SetItemsProcessed( state.iterations() * nObj );
state.SetBytesProcessed( state.iterations() * nObj * tc.GetMemberSize() );
}
//BENCHMARK( BM_NormalNestedDeser )->MinTime( 5.0 );
//BENCHMARK( BM_NormalNestedSer )->MinTime( 5.0 );
// BENCHMARK( BM_NormalNestedSer )->MinTime( 2.0 );
// BENCHMARK( BM_NormalNestedDeser )->MinTime( 2.0 );
// BENCHMARK( BM_NormalNestedSer )->MinTime( 2.0 );
// BENCHMARK( BM_NormalNestedDeser )->MinTime( 2.0 );
// BENCHMARK( BM_NormalNestedSer )->MinTime( 2.0 );
BENCHMARK( BM_FloatArraySer )->MinTime( 4.0 );
int main( int argc, char **argv )
{
::benchmark::Initialize( &argc, argv );
::benchmark::RunSpecifiedBenchmarks();
}<commit_msg>Resharper fixes for bench-project<commit_after>#define BENCHMARK_HAS_CXX11
#include "benchmark/benchmark.h"
#include "serialisation/serialisation.h"
#include <sstream>
#include <chrono>
class Testclass
{
public:
Testclass()
{
std::stringstream ss;
ss << rand();
mValue1 = rand();
while ( ( mValue2 = Util::UInt32ToFloat( rand() ) ) == std::numeric_limits< float >::infinity() )
{};
mValue3 = ss.str();
}
template< typename tT >
void SERIALISATION_CUSTOM_INTERFACE( Message< tT > &message )
{
message.Store( 0, mValue1 );
message.Store( 1, mValue2 );
message.Store( 2, mValue3 );
}
size_t GetMemberSize() const
{
return sizeof( uint32_t ) + sizeof( float ) + mValue3.length();
}
private:
uint32_t mValue1;
float mValue2;
std::string mValue3;
};
// class Testclass2
// : public ISerialisable
// {
// public:
// Testclass2()
// {
// std::stringstream ss;
// ss << rand();
// mValue1 = rand();
// while ( ( mValue2 = Util::UInt32ToFloat( rand() ) ) == std::numeric_limits< float >::infinity() );
// mValue3 = ss.str();
// }
// void SERIALISATION_CUSTOM_INTERFACE( Message &message )
// {
// message.Store( 3, mValue4 );
// message.Store( 2, mValue3 );
// message.Store( 1, mValue2 );
// message.Store( 0, mValue1 );
// }
// private:
// uint32_t mValue1;
// float mValue2;
// std::string mValue3;
// Testclass mValue4;
// };
class Testclass3
{
public:
Testclass3()
{
std::stringstream ss;
ss << rand();
mValue1 = rand();
while ( ( mValue2 = Util::UInt32ToFloat( rand() ) ) == std::numeric_limits< float >::infinity() )
{};
mValue3 = ss.str();
}
template<typename tMessage>
void SERIALISATION_CUSTOM_INTERFACE( tMessage &message )
{
message.Store( 3, mValue4 );
message.Store( 2, mValue3 );
message.Store( 1, mValue2 );
message.Store( 0, mValue1 );
}
size_t GetMemberSize() const
{
return sizeof( uint32_t ) + sizeof( float ) + mValue3.length() + mValue4.GetMemberSize();
}
private:
uint32_t mValue1;
float mValue2;
std::string mValue3;
Testclass mValue4;
};
class Testclass3Reordered
{
public:
Testclass3Reordered()
{
std::stringstream ss;
ss << rand();
mValue1 = rand();
while ( ( mValue2 = Util::UInt32ToFloat( rand() ) ) == std::numeric_limits< float >::infinity() )
{};
mValue3 = ss.str();
}
template<typename tMessage>
void SERIALISATION_CUSTOM_INTERFACE( tMessage &message )
{
message.Store( 0, mValue1 );
message.Store( 1, mValue2 );
message.Store( 2, mValue3 );
message.Store( 3, mValue4 );
}
size_t GetMemberSize() const
{
return sizeof( uint32_t ) + sizeof( float ) + mValue3.length() + mValue4.GetMemberSize();
}
private:
uint32_t mValue1;
float mValue2;
std::string mValue3;
Testclass mValue4;
};
// template< typename tImpl >
// static void BM_OLS( benchmark::State &state )
// {
// double a = Random::GenerateRandomF64( -NUMERICAL_OLS_MAX_SAMPLES, NUMERICAL_OLS_MAX_SAMPLES );
// double b = a + Random::GenerateRandomF64( -NUMERICAL_OLS_MAX_SAMPLES, NUMERICAL_OLS_MAX_SAMPLES );
// double alpha = Random::GenerateRandomF64( -NUMERICAL_OLS_MAX_SAMPLES, NUMERICAL_OLS_MAX_SAMPLES );
// double beta = Random::GenerateRandomF64( -10000, 10000 );
// vec ex = linspace( a, b, state.range_x() );
// vec end = ex * beta + alpha;
// while ( state.KeepRunning() )
// {
// LinReg<tImpl> ols( end, ex );
// ols.Fit();
// }
// state.SetItemsProcessed( state.iterations() );
// state.SetBytesProcessed( state.iterations() * state.range_x() * sizeof( double ) );
// state.SetComplexityN( state.range_x() );
// }
// BENCHMARK_TEMPLATE( BM_OLS, LinealOLSImpl )->Range( 10, 20000 )->Complexity();
// BENCHMARK_TEMPLATE( BM_OLS, QROLSImpl )->Range( 10, 20000 )->Complexity();
// BENCHMARK_TEMPLATE( BM_OLS, SVDOLSImpl )->Range( 10, 20000 )->Complexity();
// BENCHMARK_TEMPLATE( BM_OLS, FGLSImpl )->Range( 10, 20000 )->Complexity();
template< typename tFunc >
static inline void TimeManual( benchmark::State &state, const tFunc &func )
{
auto start = std::chrono::high_resolution_clock::now();
func();
auto end = std::chrono::high_resolution_clock::now();
auto elapsed_seconds =
std::chrono::duration_cast<std::chrono::duration<double>>(
end - start );
state.SetIterationTime( elapsed_seconds.count() );
}
static void BM_VarInt( benchmark::State &state )
{
while ( state.KeepRunning() )
{
benchmark::DoNotOptimize( VarInt<std::numeric_limits<uint64_t>::max()>() );
}
state.SetItemsProcessed( state.iterations() );
state.SetBytesProcessed( state.iterations() * sizeof( uint64_t ) );
}
static void BM_VarIntSize( benchmark::State &state )
{
while ( state.KeepRunning() )
{
benchmark::DoNotOptimize( VarIntSize<std::numeric_limits<uint64_t>::max()>() );
}
state.SetItemsProcessed( state.iterations() );
state.SetBytesProcessed( state.iterations() * sizeof( uint64_t ) );
}
static void BM_StoreU32( benchmark::State &state )
{
uint32_t x = static_cast<uint32_t>( state.range_x() );
{
std::stringstream ss;
Message< BinarySerialisationMessage< BufferedStreamWriter<> > > message( ss );
while ( state.KeepRunning() )
{
message.Store( 0, x );
}
}
state.SetItemsProcessed( state.iterations() );
state.SetBytesProcessed( state.iterations() * sizeof( uint64_t ) );
state.SetComplexityN( static_cast<int>( x ) );
}
static void BM_CreateHeaderCT( benchmark::State &state )
{
while ( state.KeepRunning() )
{
benchmark::DoNotOptimize( Util::CreateHeader<uint32_t>( 0 ) );
}
state.SetItemsProcessed( state.iterations() );
state.SetBytesProcessed( state.iterations() * sizeof( uint64_t ) );
}
static void BM_CreateHeader( benchmark::State &state )
{
volatile uint8_t index = 0;
while ( state.KeepRunning() )
{
benchmark::DoNotOptimize( Util::CreateHeader<uint32_t>( index ) );
}
state.SetItemsProcessed( state.iterations() );
state.SetBytesProcessed( state.iterations() * sizeof( uint64_t ) );
}
static void BM_NormalNestedDeser( benchmark::State &state )
{
Testclass3 tc, tc2;
uint32_t nObj = 200;
std::stringstream ssSource;
{
Serialisation::BinarySerialiser serMessage( ssSource );
for ( uint32_t i = 0; i < nObj; ++i )
{
serMessage.Enter( tc );
}
}
while ( state.KeepRunning() )
{
{
std::stringstream ss( ssSource.str() );
Message< BinaryDeserialisationMessage< BufferedStreamReader<> > > deserMessage( ss );
TimeManual( state, [&]()
{
for ( uint32_t i = 0; i < nObj; ++i )
{
deserMessage.Enter( tc2 );
}
} );
}
}
state.SetItemsProcessed( state.iterations() * nObj );
state.SetBytesProcessed( state.iterations() * nObj * tc.GetMemberSize() );
}
static void BM_ReorderedNestedDeser( benchmark::State &state )
{
Testclass3 tc;
Testclass3Reordered tc2;
uint32_t nObj = 200;
std::stringstream ssSource;
{
Serialisation::BinarySerialiser serMessage( ssSource );
for ( uint32_t i = 0; i < nObj; ++i )
{
serMessage.Enter( tc );
}
}
while ( state.KeepRunning() )
{
{
std::stringstream ss( ssSource.str() );
Message< BinaryDeserialisationMessage< BufferedStreamReader<> > > deserMessage( ss );
TimeManual( state, [&]()
{
for ( uint32_t i = 0; i < nObj; ++i )
{
deserMessage.Enter( tc2 );
}
} );
}
}
state.SetItemsProcessed( state.iterations() * nObj );
state.SetBytesProcessed( state.iterations() * nObj * tc.GetMemberSize() );
}
static void BM_NormalNestedSer( benchmark::State &state )
{
Testclass3 tc;
uint32_t nObj = 200;
while ( state.KeepRunning() )
{
{
std::stringstream ss;
Message< BinarySerialisationMessage<BufferedStreamWriter<> > > serMessage( ss );
TimeManual( state, [&]()
{
for ( uint32_t i = 0; i < nObj; ++i )
{
serMessage.Enter( tc );
}
} );
}
}
state.SetItemsProcessed( state.iterations() * nObj );
state.SetBytesProcessed( state.iterations() * nObj * tc.GetMemberSize() );
}
template< typename tT >
class TestClassArray
{
public:
TestClassArray()
{
mValue1.resize( ( rand() % 8192 ) + 8192 );
for ( auto it = mValue1.begin(); it != mValue1.end(); ++it )
{
*it = static_cast<tT>( rand() );
}
}
template< typename tM >
void OnStore( Message< tM > &message )
{
message.Store( 0, mValue1 );
}
size_t GetMemberSize()
{
return mValue1.size() * sizeof( tT );
}
private:
std::vector<tT> mValue1;
};
static void BM_FloatArraySer( benchmark::State &state )
{
TestClassArray<float> tc;
uint32_t nObj = 1;
while ( state.KeepRunning() )
{
{
std::stringstream ss;
Message< BinarySerialisationMessage<BufferedStreamWriter<> > > serMessage( ss );
TimeManual( state, [&]()
{
for ( uint32_t i = 0; i < nObj; ++i )
{
serMessage.Enter( tc );
}
} );
}
}
state.SetItemsProcessed( state.iterations() * nObj );
state.SetBytesProcessed( state.iterations() * nObj * tc.GetMemberSize() );
}
static void BM_IntArraySer( benchmark::State &state )
{
TestClassArray<uint32_t> tc;
uint32_t nObj = 1;
while ( state.KeepRunning() )
{
{
std::stringstream ss;
Message< BinarySerialisationMessage<BufferedStreamWriter<> > > serMessage( ss );
TimeManual( state, [&]()
{
for ( uint32_t i = 0; i < nObj; ++i )
{
serMessage.Enter( tc );
}
} );
}
}
state.SetItemsProcessed( state.iterations() * nObj );
state.SetBytesProcessed( state.iterations() * nObj * tc.GetMemberSize() );
}
//BENCHMARK( BM_NormalNestedDeser )->MinTime( 5.0 );
//BENCHMARK( BM_NormalNestedSer )->MinTime( 5.0 );
// BENCHMARK( BM_NormalNestedSer )->MinTime( 2.0 );
// BENCHMARK( BM_NormalNestedDeser )->MinTime( 2.0 );
// BENCHMARK( BM_NormalNestedSer )->MinTime( 2.0 );
// BENCHMARK( BM_NormalNestedDeser )->MinTime( 2.0 );
// BENCHMARK( BM_NormalNestedSer )->MinTime( 2.0 );
BENCHMARK( BM_FloatArraySer )->MinTime( 4.0 );
int main( int argc, char **argv )
{
::benchmark::Initialize( &argc, argv );
::benchmark::RunSpecifiedBenchmarks();
}<|endoftext|>
|
<commit_before>#include <iostream>
#if WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#pragma comment(lib, "Ws2_32.lib")
#else
#include <sys/socket.h>
#include <arpa/inet.h>
#endif
#include <cstring>
#include <string>
#include <chrono>
#include <errno.h>
#include <vector>
#include <mutex>
#include <thread>
#include <fstream>
using namespace std;
using namespace chrono;
int totalConnections = 500000;
unsigned short port = 3000;
#define CONNECTIONS_PER_ADDRESS 28000
#define THREADS 10
int connections, address = 1;
mutex m;
bool nextConnection(int tid)
{
m.lock();
int socketfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (socketfd == -1) {
cout << "FD error, connections: " << connections << endl;
return false;
}
sockaddr_in addr = {};
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(("127.0.0." + to_string(address)).c_str());
addr.sin_port = htons(port);
m.unlock();
// this is a shared upgrade, no need to make it unique
const char *buf = "GET / HTTP/1.1\r\n"
"Host: server.example.com\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\r\n"
"Sec-WebSocket-Protocol: default\r\n"
"Sec-WebSocket-Version: 13\r\n"
"Origin: http://example.com\r\n\r\n";
char message[1024];
int err = connect(socketfd, (sockaddr *)&addr, sizeof(addr));
if (err) {
cout << "Connection error "<< err<< ", connections: " << connections << endl;
return false;
}
send(socketfd, buf, strlen(buf), 0);
memset(message, 0, 1024);
size_t length;
do {
length = recv(socketfd, message, sizeof(message), 0);
} while (strncmp(&message[length - 4], "\r\n\r\n", 4));
m.lock();
if (++connections % CONNECTIONS_PER_ADDRESS == 0) {
address++;
}
if (connections % 1000 == 0 || connections < 1000) {
cout << "Connections: " << connections << endl;
}
if (connections >= totalConnections - THREADS + 1) {
m.unlock();
return false;
}
m.unlock();
return true;
}
int main(int argc, char **argv)
{
#if WIN32
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
#endif
auto startPoint = high_resolution_clock::now();
vector<thread *> threads;
for (int i = 0; i < THREADS; i++) {
threads.push_back(new thread([i] {
while (nextConnection(i));
}));
}
for (thread *t : threads) {
t->join();
}
double connectionsPerMs = double(connections) / duration_cast<milliseconds>(high_resolution_clock::now() - startPoint).count();
cout << "Connection performance: " << connectionsPerMs << " connections/ms" << endl;
#if WIN32
WSACleanup();
#endif
int t;
cin >> t;
return 0;
}<commit_msg>fixing build<commit_after>#include <iostream>
#if WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#pragma comment(lib, "Ws2_32.lib")
#else
#include <sys/socket.h>
#include <arpa/inet.h>
#endif
#include <cstring>
#include <string>
#include <chrono>
#include <errno.h>
#include <vector>
#include <mutex>
#include <thread>
#include <fstream>
using namespace std;
using namespace chrono;
int totalConnections = 500000;
unsigned short port = 3000;
#define CONNECTIONS_PER_ADDRESS 28000
#define THREADS 10
int connections, address = 1;
mutex m;
bool nextConnection(int tid)
{
m.lock();
int socketfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (socketfd == -1) {
cout << "FD error, connections: " << connections << endl;
return false;
}
sockaddr_in addr = {};
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(("127.0.0." + to_string(address)).c_str());
addr.sin_port = htons(port);
m.unlock();
// this is a shared upgrade, no need to make it unique
const char *buf = "GET / HTTP/1.1\r\n"
"Host: server.example.com\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\r\n"
"Sec-WebSocket-Protocol: default\r\n"
"Sec-WebSocket-Version: 13\r\n"
"Origin: http://example.com\r\n\r\n";
char message[1024];
int err = connect(socketfd, (sockaddr *)&addr, sizeof(addr));
if (err) {
cout << "Connection error "<< err<< ", connections: " << connections << endl;
return false;
}
send(socketfd, buf, strlen(buf), 0);
memset(message, 0, 1024);
size_t length;
do {
length = recv(socketfd, message, sizeof(message), 0);
} while (strncmp(&message[length - 4], "\r\n\r\n", 4));
m.lock();
if (++connections % CONNECTIONS_PER_ADDRESS == 0) {
address++;
}
if (connections % 1000 == 0 || connections < 1000) {
cout << "Connections: " << connections << endl;
}
if (connections >= totalConnections - THREADS + 1) {
m.unlock();
return false;
}
m.unlock();
return true;
}
int main(int argc, char **argv)
{
//#if WIN32
// WSADATA wsaData;
// WSAStartup(MAKEWORD(2, 2), &wsaData);
//#endif
//
// auto startPoint = high_resolution_clock::now();
// vector<thread *> threads;
// for (int i = 0; i < THREADS; i++) {
// threads.push_back(new thread([i] {
// while (nextConnection(i));
// }));
// }
//
// for (thread *t : threads) {
// t->join();
// }
//
// double connectionsPerMs = double(connections) / duration_cast<milliseconds>(high_resolution_clock::now() - startPoint).count();
// cout << "Connection performance: " << connectionsPerMs << " connections/ms" << endl;
//#if WIN32
// WSACleanup();
//#endif
return 0;
}<|endoftext|>
|
<commit_before>#if !FEATURE_IPV4
#error [NOT_SUPPORTED] IPV4 not supported for this target
#endif
#include <algorithm>
#include "mbed.h"
#include "EthernetInterface.h"
#include "TCPSocket.h"
#include "greentea-client/test_env.h"
#include "unity/unity.h"
namespace {
// Test connection information
const char *HTTP_SERVER_NAME = "developer.mbed.org";
const char *HTTP_SERVER_FILE_PATH = "/media/uploads/mbed_official/hello.txt";
const int HTTP_SERVER_PORT = 80;
#if defined(TARGET_VK_RZ_A1H)
const int RECV_BUFFER_SIZE = 300;
#else
const int RECV_BUFFER_SIZE = 512;
#endif
// Test related data
const char *HTTP_OK_STR = "200 OK";
const char *HTTP_HELLO_STR = "Hello world!";
// Test buffers
char buffer[RECV_BUFFER_SIZE] = {0};
}
bool find_substring(const char *first, const char *last, const char *s_first, const char *s_last) {
const char *f = std::search(first, last, s_first, s_last);
return (f != last);
}
int main() {
GREENTEA_SETUP(20, "default_auto");
bool result = false;
EthernetInterface eth;
//eth.init(); //Use DHCP
eth.connect();
printf("TCP client IP Address is %s\r\n", eth.get_ip_address());
TCPSocket sock(ð);
printf("HTTP: Connection to %s:%d\r\n", HTTP_SERVER_NAME, HTTP_SERVER_PORT);
if (sock.connect(HTTP_SERVER_NAME, HTTP_SERVER_PORT) == 0) {
printf("HTTP: OK\r\n");
// We are constructing GET command like this:
// GET http://developer.mbed.org/media/uploads/mbed_official/hello.txt HTTP/1.0\n\n
strcpy(buffer, "GET http://");
strcat(buffer, HTTP_SERVER_NAME);
strcat(buffer, HTTP_SERVER_FILE_PATH);
strcat(buffer, " HTTP/1.0\n\n");
// Send GET command
sock.send(buffer, strlen(buffer));
// Server will respond with HTTP GET's success code
const int ret = sock.recv(buffer, sizeof(buffer) - 1);
buffer[ret] = '\0';
// Find 200 OK HTTP status in reply
bool found_200_ok = find_substring(buffer, buffer + ret, HTTP_OK_STR, HTTP_OK_STR + strlen(HTTP_OK_STR));
// Find "Hello World!" string in reply
bool found_hello = find_substring(buffer, buffer + ret, HTTP_HELLO_STR, HTTP_HELLO_STR + strlen(HTTP_HELLO_STR));
TEST_ASSERT_TRUE(found_200_ok);
TEST_ASSERT_TRUE(found_hello);
if (found_200_ok && found_hello) result = true;
printf("HTTP: Received %d chars from server\r\n", ret);
printf("HTTP: Received 200 OK status ... %s\r\n", found_200_ok ? "[OK]" : "[FAIL]");
printf("HTTP: Received '%s' status ... %s\r\n", HTTP_HELLO_STR, found_hello ? "[OK]" : "[FAIL]");
printf("HTTP: Received message:\r\n");
printf("%s", buffer);
sock.close();
}
else {
printf("HTTP: ERROR\r\n");
}
eth.disconnect();
GREENTEA_TESTSUITE_RESULT(result);
}
<commit_msg>tcp_client_hello_world K&R style<commit_after>#if !FEATURE_IPV4
#error [NOT_SUPPORTED] IPV4 not supported for this target
#endif
#include <algorithm>
#include "mbed.h"
#include "EthernetInterface.h"
#include "TCPSocket.h"
#include "greentea-client/test_env.h"
#include "unity/unity.h"
namespace {
// Test connection information
const char *HTTP_SERVER_NAME = "developer.mbed.org";
const char *HTTP_SERVER_FILE_PATH = "/media/uploads/mbed_official/hello.txt";
const int HTTP_SERVER_PORT = 80;
#if defined(TARGET_VK_RZ_A1H)
const int RECV_BUFFER_SIZE = 300;
#else
const int RECV_BUFFER_SIZE = 512;
#endif
// Test related data
const char *HTTP_OK_STR = "200 OK";
const char *HTTP_HELLO_STR = "Hello world!";
// Test buffers
char buffer[RECV_BUFFER_SIZE] = {0};
}
bool find_substring(const char *first, const char *last, const char *s_first, const char *s_last) {
const char *f = std::search(first, last, s_first, s_last);
return (f != last);
}
int main() {
GREENTEA_SETUP(20, "default_auto");
bool result = false;
EthernetInterface eth;
//eth.init(); //Use DHCP
eth.connect();
printf("TCP client IP Address is %s\r\n", eth.get_ip_address());
TCPSocket sock(ð);
printf("HTTP: Connection to %s:%d\r\n", HTTP_SERVER_NAME, HTTP_SERVER_PORT);
if (sock.connect(HTTP_SERVER_NAME, HTTP_SERVER_PORT) == 0) {
printf("HTTP: OK\r\n");
// We are constructing GET command like this:
// GET http://developer.mbed.org/media/uploads/mbed_official/hello.txt HTTP/1.0\n\n
strcpy(buffer, "GET http://");
strcat(buffer, HTTP_SERVER_NAME);
strcat(buffer, HTTP_SERVER_FILE_PATH);
strcat(buffer, " HTTP/1.0\n\n");
// Send GET command
sock.send(buffer, strlen(buffer));
// Server will respond with HTTP GET's success code
const int ret = sock.recv(buffer, sizeof(buffer) - 1);
buffer[ret] = '\0';
// Find 200 OK HTTP status in reply
bool found_200_ok = find_substring(buffer, buffer + ret, HTTP_OK_STR, HTTP_OK_STR + strlen(HTTP_OK_STR));
// Find "Hello World!" string in reply
bool found_hello = find_substring(buffer, buffer + ret, HTTP_HELLO_STR, HTTP_HELLO_STR + strlen(HTTP_HELLO_STR));
TEST_ASSERT_TRUE(found_200_ok);
TEST_ASSERT_TRUE(found_hello);
if (found_200_ok && found_hello) result = true;
printf("HTTP: Received %d chars from server\r\n", ret);
printf("HTTP: Received 200 OK status ... %s\r\n", found_200_ok ? "[OK]" : "[FAIL]");
printf("HTTP: Received '%s' status ... %s\r\n", HTTP_HELLO_STR, found_hello ? "[OK]" : "[FAIL]");
printf("HTTP: Received message:\r\n");
printf("%s", buffer);
sock.close();
} else {
printf("HTTP: ERROR\r\n");
}
eth.disconnect();
GREENTEA_TESTSUITE_RESULT(result);
}
<|endoftext|>
|
<commit_before>/* This file is part of Zanshin
Copyright 2014 Kevin Ottens <ervin@kde.org>
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) version 3 or any later version
accepted by the membership of KDE e.V. (or its successor approved
by the membership of KDE e.V.), which shall act as a proxy
defined in Section 14 of version 3 of the license.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU 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 "availablesourcesview.h"
#include <functional>
#include <QHeaderView>
#include <QSortFilterProxyModel>
#include <QTreeView>
#include <QVBoxLayout>
#include <QItemSelection>
#include <KLineEdit>
#include "presentation/metatypes.h"
#include "presentation/querytreemodelbase.h"
#include "widgets/datasourcedelegate.h"
using namespace Widgets;
AvailableSourcesView::AvailableSourcesView(QWidget *parent)
: QWidget(parent),
m_model(0),
m_sortProxy(new QSortFilterProxyModel(this))
{
m_sortProxy->setDynamicSortFilter(true);
m_sortProxy->sort(0);
auto searchEdit = new KLineEdit(this);
searchEdit->setObjectName("searchEdit");
searchEdit->setClearButtonShown(true);
searchEdit->setClickMessage(tr("Search..."));
connect(searchEdit, SIGNAL(textChanged(QString)),
this, SLOT(onSearchTextChanged(QString)));
auto sourcesView = new QTreeView(this);
sourcesView->setObjectName("sourcesView");
sourcesView->header()->hide();
sourcesView->setModel(m_sortProxy);
connect(sourcesView->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
this, SLOT(onSelectionChanged(const QItemSelection &, const QItemSelection &)));
m_selectionModel = sourcesView->selectionModel();
auto delegate = new DataSourceDelegate(sourcesView);
connect(delegate, SIGNAL(actionTriggered(Domain::DataSource::Ptr,int)),
this, SLOT(onActionTriggered(Domain::DataSource::Ptr,int)));
sourcesView->setItemDelegate(delegate);
auto layout = new QVBoxLayout;
layout->addWidget(searchEdit);
layout->addWidget(sourcesView);
setLayout(layout);
connect(m_sortProxy, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(onRefreshDefaultSource()));
connect(m_sortProxy, SIGNAL(layoutChanged()), this, SLOT(onRefreshDefaultSource()));
connect(m_sortProxy, SIGNAL(modelReset()), this, SLOT(onRefreshDefaultSource()));
connect(m_sortProxy, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(onRefreshDefaultSource()));
connect(m_sortProxy, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(onRefreshDefaultSource()));
onRefreshDefaultSource();
}
QObject *AvailableSourcesView::model() const
{
return m_model;
}
void AvailableSourcesView::setModel(QObject *model)
{
if (model == m_model)
return;
m_sortProxy->setSourceModel(0);
m_model = model;
setSourceModel("sourceListModel");
}
void AvailableSourcesView::onSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
{
const QModelIndexList indexes = selected.indexes();
if (indexes.size() > 1) {
qWarning() << "Selected multiple indexes, no idea what to do with that";
}
if (indexes.size() >= 1) {
const QModelIndex &idx = indexes.first();
const QVariant data = idx.data(Presentation::QueryTreeModelBase::ObjectRole);
const auto source = data.value<Domain::DataSource::Ptr>();
emit sourceActivated(source);
}
}
void AvailableSourcesView::setDefaultSourceProperty(QObject *object, const char *property)
{
m_object = object;
m_property = property;
onRefreshDefaultSource();
}
void AvailableSourcesView::onRefreshDefaultSource()
{
if (!m_object)
return;
const QVariant data = m_object->property(m_property);
const auto defaultSource = data.value<Domain::DataSource::Ptr>();
if (!defaultSource)
return;
selectSource(defaultSource, QModelIndex());
}
void AvailableSourcesView::setDefaultNoteSource(const Domain::DataSource::Ptr &source)
{
selectSource(source, QModelIndex());
}
void AvailableSourcesView::selectSource(Domain::DataSource::Ptr source, const QModelIndex &parentIndex)
{
std::function<void(QAbstractItemModel *, const QModelIndex &, std::function<void(const QModelIndex &)>)> traverseTree;
traverseTree = [&traverseTree](QAbstractItemModel *model, const QModelIndex &parent, std::function<void(const QModelIndex &)> visitor) {
for (int i = 0; i < model->rowCount(parent); i++) {
const auto idx = model->index(i, 0, parent);
visitor(idx);
if (model->hasChildren(idx)) {
traverseTree(model, idx, visitor);
}
}
};
traverseTree(m_sortProxy, QModelIndex(), [this, &source](const QModelIndex &index) {
auto ptr = index.data(Presentation::QueryTreeModelBase::ObjectRole).value<Domain::DataSource::Ptr>();
//FIXME: Comparison of nodes doesn't work because DataSourceQueries::findNotes doesn't yet feed on the tree, and we thus end up with two separate pointers.
if (index.data(Presentation::QueryTreeModelBase::ObjectRole).value<Domain::DataSource::Ptr>()->name() == source->name()) {
m_selectionModel->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect);
}
});
}
void AvailableSourcesView::onActionTriggered(const Domain::DataSource::Ptr &source, int action)
{
switch (action) {
case DataSourceDelegate::AddToList:
QMetaObject::invokeMethod(m_model, "listSource",
Q_ARG(Domain::DataSource::Ptr, source));
break;
case DataSourceDelegate::RemoveFromList:
QMetaObject::invokeMethod(m_model, "unlistSource",
Q_ARG(Domain::DataSource::Ptr, source));
break;
case DataSourceDelegate::Bookmark:
QMetaObject::invokeMethod(m_model, "bookmarkSource",
Q_ARG(Domain::DataSource::Ptr, source));
break;
default:
qFatal("Shouldn't happen");
break;
}
}
void AvailableSourcesView::setSourceModel(const QByteArray &propertyName)
{
QVariant modelProperty = m_model->property(propertyName);
if (modelProperty.canConvert<QAbstractItemModel*>())
m_sortProxy->setSourceModel(modelProperty.value<QAbstractItemModel*>());
}
void AvailableSourcesView::onSearchTextChanged(const QString &text)
{
if (text.size() <= 2) {
m_model->setProperty("searchTerm", QString());
setSourceModel("sourceListModel");
} else {
m_model->setProperty("searchTerm", text);
setSourceModel("searchListModel");
}
}
<commit_msg>fixed build<commit_after>/* This file is part of Zanshin
Copyright 2014 Kevin Ottens <ervin@kde.org>
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) version 3 or any later version
accepted by the membership of KDE e.V. (or its successor approved
by the membership of KDE e.V.), which shall act as a proxy
defined in Section 14 of version 3 of the license.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU 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 "availablesourcesview.h"
#include <functional>
#include <QHeaderView>
#include <QSortFilterProxyModel>
#include <QTreeView>
#include <QVBoxLayout>
#include <QItemSelection>
#include <QDebug>
#include <KLineEdit>
#include "presentation/metatypes.h"
#include "presentation/querytreemodelbase.h"
#include "widgets/datasourcedelegate.h"
using namespace Widgets;
AvailableSourcesView::AvailableSourcesView(QWidget *parent)
: QWidget(parent),
m_model(0),
m_sortProxy(new QSortFilterProxyModel(this))
{
m_sortProxy->setDynamicSortFilter(true);
m_sortProxy->sort(0);
auto searchEdit = new KLineEdit(this);
searchEdit->setObjectName("searchEdit");
searchEdit->setClearButtonShown(true);
searchEdit->setClickMessage(tr("Search..."));
connect(searchEdit, SIGNAL(textChanged(QString)),
this, SLOT(onSearchTextChanged(QString)));
auto sourcesView = new QTreeView(this);
sourcesView->setObjectName("sourcesView");
sourcesView->header()->hide();
sourcesView->setModel(m_sortProxy);
connect(sourcesView->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
this, SLOT(onSelectionChanged(const QItemSelection &, const QItemSelection &)));
m_selectionModel = sourcesView->selectionModel();
auto delegate = new DataSourceDelegate(sourcesView);
connect(delegate, SIGNAL(actionTriggered(Domain::DataSource::Ptr,int)),
this, SLOT(onActionTriggered(Domain::DataSource::Ptr,int)));
sourcesView->setItemDelegate(delegate);
auto layout = new QVBoxLayout;
layout->addWidget(searchEdit);
layout->addWidget(sourcesView);
setLayout(layout);
connect(m_sortProxy, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(onRefreshDefaultSource()));
connect(m_sortProxy, SIGNAL(layoutChanged()), this, SLOT(onRefreshDefaultSource()));
connect(m_sortProxy, SIGNAL(modelReset()), this, SLOT(onRefreshDefaultSource()));
connect(m_sortProxy, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(onRefreshDefaultSource()));
connect(m_sortProxy, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(onRefreshDefaultSource()));
onRefreshDefaultSource();
}
QObject *AvailableSourcesView::model() const
{
return m_model;
}
void AvailableSourcesView::setModel(QObject *model)
{
if (model == m_model)
return;
m_sortProxy->setSourceModel(0);
m_model = model;
setSourceModel("sourceListModel");
}
void AvailableSourcesView::onSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
{
const QModelIndexList indexes = selected.indexes();
if (indexes.size() > 1) {
qWarning() << "Selected multiple indexes, no idea what to do with that";
}
if (indexes.size() >= 1) {
const QModelIndex &idx = indexes.first();
const QVariant data = idx.data(Presentation::QueryTreeModelBase::ObjectRole);
const auto source = data.value<Domain::DataSource::Ptr>();
emit sourceActivated(source);
}
}
void AvailableSourcesView::setDefaultSourceProperty(QObject *object, const char *property)
{
m_object = object;
m_property = property;
onRefreshDefaultSource();
}
void AvailableSourcesView::onRefreshDefaultSource()
{
if (!m_object)
return;
const QVariant data = m_object->property(m_property);
const auto defaultSource = data.value<Domain::DataSource::Ptr>();
if (!defaultSource)
return;
selectSource(defaultSource, QModelIndex());
}
void AvailableSourcesView::setDefaultNoteSource(const Domain::DataSource::Ptr &source)
{
selectSource(source, QModelIndex());
}
void AvailableSourcesView::selectSource(Domain::DataSource::Ptr source, const QModelIndex &parentIndex)
{
std::function<void(QAbstractItemModel *, const QModelIndex &, std::function<void(const QModelIndex &)>)> traverseTree;
traverseTree = [&traverseTree](QAbstractItemModel *model, const QModelIndex &parent, std::function<void(const QModelIndex &)> visitor) {
for (int i = 0; i < model->rowCount(parent); i++) {
const auto idx = model->index(i, 0, parent);
visitor(idx);
if (model->hasChildren(idx)) {
traverseTree(model, idx, visitor);
}
}
};
traverseTree(m_sortProxy, QModelIndex(), [this, &source](const QModelIndex &index) {
auto ptr = index.data(Presentation::QueryTreeModelBase::ObjectRole).value<Domain::DataSource::Ptr>();
//FIXME: Comparison of nodes doesn't work because DataSourceQueries::findNotes doesn't yet feed on the tree, and we thus end up with two separate pointers.
if (index.data(Presentation::QueryTreeModelBase::ObjectRole).value<Domain::DataSource::Ptr>()->name() == source->name()) {
m_selectionModel->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect);
}
});
}
void AvailableSourcesView::onActionTriggered(const Domain::DataSource::Ptr &source, int action)
{
switch (action) {
case DataSourceDelegate::AddToList:
QMetaObject::invokeMethod(m_model, "listSource",
Q_ARG(Domain::DataSource::Ptr, source));
break;
case DataSourceDelegate::RemoveFromList:
QMetaObject::invokeMethod(m_model, "unlistSource",
Q_ARG(Domain::DataSource::Ptr, source));
break;
case DataSourceDelegate::Bookmark:
QMetaObject::invokeMethod(m_model, "bookmarkSource",
Q_ARG(Domain::DataSource::Ptr, source));
break;
default:
qFatal("Shouldn't happen");
break;
}
}
void AvailableSourcesView::setSourceModel(const QByteArray &propertyName)
{
QVariant modelProperty = m_model->property(propertyName);
if (modelProperty.canConvert<QAbstractItemModel*>())
m_sortProxy->setSourceModel(modelProperty.value<QAbstractItemModel*>());
}
void AvailableSourcesView::onSearchTextChanged(const QString &text)
{
if (text.size() <= 2) {
m_model->setProperty("searchTerm", QString());
setSourceModel("sourceListModel");
} else {
m_model->setProperty("searchTerm", text);
setSourceModel("searchListModel");
}
}
<|endoftext|>
|
<commit_before>/* Copyright 2018 Iakov Kirilenko, CyberTech Labs 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 <QProcess>
#include <QsLog.h>
#include <QVector>
#include <trikNetwork/mailboxInterface.h>
#include <trikKernel/paths.h>
#include <trikKernel/exceptions/internalErrorException.h>
#include <trikScriptRunnerInterface.h>
#include "pythonEngineWorker.h"
#include <Python.h>
#include "PythonQtConversion.h"
using namespace trikScriptRunner;
QAtomicInt PythonEngineWorker::initCounter = 0;
static int quitFromPython(void*) {
PyErr_SetInterrupt();
return 0;
}
static void abortPythonInterpreter() {
if(!Py_IsInitialized()) {
return;
}
PythonQtGILScope _;
Py_AddPendingCall(&quitFromPython, nullptr);
}
PythonEngineWorker::PythonEngineWorker(trikControl::BrickInterface &brick
, trikNetwork::MailboxInterface * const mailbox
)
: mBrick(brick)
, mScriptExecutionControl(new ScriptExecutionControl(brick))
, mMailbox(mailbox)
, mState(ready)
{}
PythonEngineWorker::~PythonEngineWorker()
{
stopScript();
{
// In python at least before 3.7 (3.5,3.6)
// we need to make all pending calls before the context
// is destroyed, otherwise python crashes
PythonQtGILScope _;
Py_MakePendingCalls();
mMainContext = nullptr;
if (mPyInterpreter) {
Py_EndInterpreter(mPyInterpreter);
mPyInterpreter = nullptr;
}
}
if (--initCounter == 0) {
Py_Finalize();
PyMem_RawFree(mProgramName);
PyMem_RawFree(mPythonPath);
if (PythonQt::self()) {
PythonQt::cleanup();
}
}
}
void PythonEngineWorker::init()
{
if (initCounter++ == 0) {
mProgramName = Py_DecodeLocale("trikPythonRuntime", nullptr);
Py_SetProgramName(mProgramName);
constexpr auto varName = "TRIK_PYTHONPATH";
auto const &path = QProcessEnvironment::systemEnvironment().value(varName);
if (path.isEmpty()) {
auto const &e = QString("%1 must be set to correct value").arg(varName);
QLOG_FATAL() << e;
throw trikKernel::InternalErrorException(e);
} else {
QLOG_INFO() << varName << ":" << path;
}
/// TODO: Must point to local .zip file
mPythonPath = Py_DecodeLocale(path.toStdString().data(), nullptr);
Py_SetPath(mPythonPath);
/* uncomment for verbosity
Py_VerboseFlag = 3;
Py_InspectFlag = 1;
Py_DebugFlag = 2;
// */
Py_IsolatedFlag = 1;
Py_BytesWarningFlag = 3;
Py_DontWriteBytecodeFlag = 1;
Py_NoSiteFlag = 1;
Py_NoUserSiteDirectory = 1;
Py_Initialize();
PyEval_InitThreads(); // For Python < 3.7
}
if (!mPyInterpreter) {
// mPyInterpreter = Py_NewInterpreter();
}
if (!PythonQt::self()) {
PythonQt::setEnableThreadSupport(true);
PythonQtGILScope _;
PythonQt::init(PythonQt::RedirectStdOut | PythonQt::PythonAlreadyInitialized);
connect(PythonQt::self(), &PythonQt::pythonStdErr, this, &PythonEngineWorker::updateErrorMessage);
connect(PythonQt::self(), &PythonQt::pythonStdOut, this, &PythonEngineWorker::textInStdOut);
PythonQtRegisterListTemplateConverter(QVector, uint8_t)
PythonQt_QtAll::init();
}
if (!mMainContext) {
mMainContext = PythonQt::self()->getMainModule();
recreateContext();
}
emit inited();
}
bool PythonEngineWorker::recreateContext()
{
{
PythonQtGILScope _;
Py_MakePendingCalls();
PyErr_CheckSignals();
PyErr_Clear();
}
PythonQt::self()->clearError();
return initTrik();
}
bool PythonEngineWorker::evalSystemPy()
{
const QString systemPyPath = trikKernel::Paths::systemScriptsPath() + "system.py";
if (!QFileInfo::exists(systemPyPath)) {
QLOG_ERROR() << "system.py not found, path:" << systemPyPath;
return false;
}
mMainContext.evalFile(systemPyPath);
if (PythonQt::self()->hadError()) {
QLOG_ERROR() << "Failed to eval system.py";
return false;
}
return true;
}
bool PythonEngineWorker::initTrik()
{
PythonQt_init_PyTrikControl(mMainContext);
mMainContext.addObject("brick", &mBrick);
mMainContext.addObject("script_cpp", mScriptExecutionControl.data());
return evalSystemPy();
}
void PythonEngineWorker::resetBrick()
{
QLOG_INFO() << "Stopping robot";
if (mMailbox) {
mMailbox->stopWaiting();
mMailbox->clearQueue();
}
mBrick.reset();
}
void PythonEngineWorker::brickBeep()
{
mBrick.playSound(trikKernel::Paths::mediaPath() + "media/beep_soft.wav");
}
void PythonEngineWorker::stopScript()
{
QMutexLocker locker(&mScriptStateMutex);
if (mState == stopping) {
// Already stopping, so we can do nothing.
return;
}
if (mState == ready) {
// Engine is ready for execution.
return;
}
QLOG_INFO() << "PythonEngineWorker: stopping script";
mState = stopping;
if (QThread::currentThread() != thread()) {
abortPythonInterpreter();
} else {
QLOG_FATAL() << "Attempt to abort Python from main thread.";
}
if (mMailbox) {
mMailbox->stopWaiting();
}
mState = ready;
/// @todo: is it actually stopped?
QLOG_INFO() << "PythonEngineWorker: stopping complete";
}
QStringList PythonEngineWorker::knownNames() const
{
QSet<QString> result = {"brick", "script", "threading"};
TrikScriptRunnerInterface::Helper::collectMethodNames(result, &trikControl::BrickInterface::staticMetaObject);
/// TODO: TrikScriptRunnerInterface::Helper::collectMethodNames(result, mScriptControl.metaObject());
if (mMailbox) {
result.insert("mailbox");
TrikScriptRunnerInterface::Helper::collectMethodNames(result, mMailbox->metaObject());
}
/// TODO: TrikScriptRunnerInterface::Helper::collectMethodNames(result, mThreading.metaObject());
return result.toList();
}
void PythonEngineWorker::run(const QString &script, const QFileInfo &scriptFile)
{
QMutexLocker locker(&mScriptStateMutex);
mState = starting;
QMetaObject::invokeMethod(this, [this, script, scriptFile](){this->doRun(script, scriptFile);});
}
void PythonEngineWorker::doRun(const QString &script, const QFileInfo &scriptFile)
{
emit startedScript("", 0);
mErrorMessage.clear();
/// When starting script execution (by any means), clear button states.
mBrick.keys()->reset();
mState = running;
auto ok = recreateContext();
if (!ok) {
emit completed(mErrorMessage,0);
return;
}
if (scriptFile.isFile()) {
mMainContext.evalScript("import sys; (lambda x: sys.path.append(x) if not x in sys.path else None)('"
+ scriptFile.canonicalPath() + "')");
}
mMainContext.evalScript(script);
QLOG_INFO() << "PythonEngineWorker: evaluation ended";
auto wasError = mState != ready && PythonQt::self()->hadError();
mState = ready;
if (wasError) {
emit completed(mErrorMessage, 0);
} else {
emit completed("", 0);
}
}
void PythonEngineWorker::runDirect(const QString &command)
{
QMutexLocker locker(&mScriptStateMutex);
QMetaObject::invokeMethod(this, "doRunDirect", Q_ARG(QString, command));
}
void PythonEngineWorker::doRunDirect(const QString &command)
{
emit startedDirectScript(0);
if (PythonQt::self()->hadError()) {
PythonQt::self()->clearError();
mErrorMessage.clear();
recreateContext();
}
mMainContext.evalScript(command);
emit completed(mErrorMessage, 0);
}
void PythonEngineWorker::updateErrorMessage(const QString &err)
{
mErrorMessage += err;
}
void PythonEngineWorker::onScriptRequestingToQuit()
{
throw std::logic_error("Not implemented");
}
<commit_msg>No twice system.py<commit_after>/* Copyright 2018 Iakov Kirilenko, CyberTech Labs 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 <QProcess>
#include <QsLog.h>
#include <QVector>
#include <trikNetwork/mailboxInterface.h>
#include <trikKernel/paths.h>
#include <trikKernel/exceptions/internalErrorException.h>
#include <trikScriptRunnerInterface.h>
#include "pythonEngineWorker.h"
#include <Python.h>
#include "PythonQtConversion.h"
using namespace trikScriptRunner;
QAtomicInt PythonEngineWorker::initCounter = 0;
static int quitFromPython(void*) {
PyErr_SetInterrupt();
return 0;
}
static void abortPythonInterpreter() {
if(!Py_IsInitialized()) {
return;
}
PythonQtGILScope _;
Py_AddPendingCall(&quitFromPython, nullptr);
}
PythonEngineWorker::PythonEngineWorker(trikControl::BrickInterface &brick
, trikNetwork::MailboxInterface * const mailbox
)
: mBrick(brick)
, mScriptExecutionControl(new ScriptExecutionControl(brick))
, mMailbox(mailbox)
, mState(ready)
{}
PythonEngineWorker::~PythonEngineWorker()
{
stopScript();
{
// In python at least before 3.7 (3.5,3.6)
// we need to make all pending calls before the context
// is destroyed, otherwise python crashes
PythonQtGILScope _;
Py_MakePendingCalls();
mMainContext = nullptr;
if (mPyInterpreter) {
Py_EndInterpreter(mPyInterpreter);
mPyInterpreter = nullptr;
}
}
if (--initCounter == 0) {
Py_Finalize();
PyMem_RawFree(mProgramName);
PyMem_RawFree(mPythonPath);
if (PythonQt::self()) {
PythonQt::cleanup();
}
}
}
void PythonEngineWorker::init()
{
if (initCounter++ == 0) {
mProgramName = Py_DecodeLocale("trikPythonRuntime", nullptr);
Py_SetProgramName(mProgramName);
constexpr auto varName = "TRIK_PYTHONPATH";
auto const &path = QProcessEnvironment::systemEnvironment().value(varName);
if (path.isEmpty()) {
auto const &e = QString("%1 must be set to correct value").arg(varName);
QLOG_FATAL() << e;
throw trikKernel::InternalErrorException(e);
} else {
QLOG_INFO() << varName << ":" << path;
}
/// TODO: Must point to local .zip file
mPythonPath = Py_DecodeLocale(path.toStdString().data(), nullptr);
Py_SetPath(mPythonPath);
/* uncomment for verbosity
Py_VerboseFlag = 3;
Py_InspectFlag = 1;
Py_DebugFlag = 2;
// */
Py_IsolatedFlag = 1;
Py_BytesWarningFlag = 3;
Py_DontWriteBytecodeFlag = 1;
Py_NoSiteFlag = 1;
Py_NoUserSiteDirectory = 1;
Py_Initialize();
PyEval_InitThreads(); // For Python < 3.7
}
if (!mPyInterpreter) {
// mPyInterpreter = Py_NewInterpreter();
}
if (!PythonQt::self()) {
PythonQt::setEnableThreadSupport(true);
PythonQtGILScope _;
PythonQt::init(PythonQt::RedirectStdOut | PythonQt::PythonAlreadyInitialized);
connect(PythonQt::self(), &PythonQt::pythonStdErr, this, &PythonEngineWorker::updateErrorMessage);
connect(PythonQt::self(), &PythonQt::pythonStdOut, this, &PythonEngineWorker::textInStdOut);
PythonQtRegisterListTemplateConverter(QVector, uint8_t)
PythonQt_QtAll::init();
}
if (!mMainContext) {
mMainContext = PythonQt::self()->getMainModule();
recreateContext();
}
emit inited();
}
bool PythonEngineWorker::recreateContext()
{
{
PythonQtGILScope _;
Py_MakePendingCalls();
PyErr_CheckSignals();
PyErr_Clear();
}
PythonQt::self()->clearError();
return initTrik();
}
bool PythonEngineWorker::evalSystemPy()
{
const QString systemPyPath = trikKernel::Paths::systemScriptsPath() + "system.py";
if (!QFileInfo::exists(systemPyPath)) {
QLOG_ERROR() << "system.py not found, path:" << systemPyPath;
return false;
}
mMainContext.evalScript("script.wait(0)");
if (PythonQt::self()->hadError()) {
PythonQt::self()->clearError();
mMainContext.evalFile(systemPyPath);
if (PythonQt::self()->hadError()) {
QLOG_ERROR() << "Failed to eval system.py";
return false;
}
}
return true;
}
bool PythonEngineWorker::initTrik()
{
PythonQt_init_PyTrikControl(mMainContext);
mMainContext.addObject("brick", &mBrick);
mMainContext.addObject("script_cpp", mScriptExecutionControl.data());
return evalSystemPy();
}
void PythonEngineWorker::resetBrick()
{
QLOG_INFO() << "Stopping robot";
if (mMailbox) {
mMailbox->stopWaiting();
mMailbox->clearQueue();
}
mBrick.reset();
}
void PythonEngineWorker::brickBeep()
{
mBrick.playSound(trikKernel::Paths::mediaPath() + "media/beep_soft.wav");
}
void PythonEngineWorker::stopScript()
{
QMutexLocker locker(&mScriptStateMutex);
if (mState == stopping) {
// Already stopping, so we can do nothing.
return;
}
if (mState == ready) {
// Engine is ready for execution.
return;
}
QLOG_INFO() << "PythonEngineWorker: stopping script";
mState = stopping;
if (QThread::currentThread() != thread()) {
abortPythonInterpreter();
} else {
QLOG_FATAL() << "Attempt to abort Python from main thread.";
}
if (mMailbox) {
mMailbox->stopWaiting();
}
mState = ready;
/// @todo: is it actually stopped?
QLOG_INFO() << "PythonEngineWorker: stopping complete";
}
QStringList PythonEngineWorker::knownNames() const
{
QSet<QString> result = {"brick", "script", "threading"};
TrikScriptRunnerInterface::Helper::collectMethodNames(result, &trikControl::BrickInterface::staticMetaObject);
/// TODO: TrikScriptRunnerInterface::Helper::collectMethodNames(result, mScriptControl.metaObject());
if (mMailbox) {
result.insert("mailbox");
TrikScriptRunnerInterface::Helper::collectMethodNames(result, mMailbox->metaObject());
}
/// TODO: TrikScriptRunnerInterface::Helper::collectMethodNames(result, mThreading.metaObject());
return result.toList();
}
void PythonEngineWorker::run(const QString &script, const QFileInfo &scriptFile)
{
QMutexLocker locker(&mScriptStateMutex);
mState = starting;
QMetaObject::invokeMethod(this, [this, script, scriptFile](){this->doRun(script, scriptFile);});
}
void PythonEngineWorker::doRun(const QString &script, const QFileInfo &scriptFile)
{
emit startedScript("", 0);
mErrorMessage.clear();
/// When starting script execution (by any means), clear button states.
mBrick.keys()->reset();
mState = running;
auto ok = recreateContext();
if (!ok) {
emit completed(mErrorMessage,0);
return;
}
if (scriptFile.isFile()) {
mMainContext.evalScript("import sys; (lambda x: sys.path.append(x) if not x in sys.path else None)('"
+ scriptFile.canonicalPath() + "')");
}
mMainContext.evalScript(script);
QLOG_INFO() << "PythonEngineWorker: evaluation ended";
auto wasError = mState != ready && PythonQt::self()->hadError();
mState = ready;
if (wasError) {
emit completed(mErrorMessage, 0);
} else {
emit completed("", 0);
}
}
void PythonEngineWorker::runDirect(const QString &command)
{
QMutexLocker locker(&mScriptStateMutex);
QMetaObject::invokeMethod(this, "doRunDirect", Q_ARG(QString, command));
}
void PythonEngineWorker::doRunDirect(const QString &command)
{
emit startedDirectScript(0);
if (PythonQt::self()->hadError()) {
PythonQt::self()->clearError();
mErrorMessage.clear();
recreateContext();
}
mMainContext.evalScript(command);
emit completed(mErrorMessage, 0);
}
void PythonEngineWorker::updateErrorMessage(const QString &err)
{
mErrorMessage += err;
}
void PythonEngineWorker::onScriptRequestingToQuit()
{
throw std::logic_error("Not implemented");
}
<|endoftext|>
|
<commit_before><commit_msg>make CalcScore Method<commit_after><|endoftext|>
|
<commit_before>//=============================================================================
// ■ VMtest.cxx
//-----------------------------------------------------------------------------
// 虚拟机测试程序。
// 扩展名用了.cxx,意思是“×不要自动编译”。
//=============================================================================
#include <ratio>
#include <chrono>
using namespace std;
#include "ASM76.hpp"
using namespace ASM76;
Instruct test_mem_i[] = {
{LCMM, 0x4000000, 0},
{DATI, 0xABCD1234, 1},
{DATB, 'V', 5},
{DATB, 'M', 6},
{DATB, '7', 7},
{DATB, '6', 8},
{SLLA, 0x2000000, 1},
{SLIA, 0x2500000, 2},
{SLBA, 0x2700000, 3},
{LDLA, 0x2500000, 51},
{LDIA, 0x2500000, 51},
{LDBA, 0x2500000, 61},
{HALT, 0, 0},
};
Program test_mem_p {
.size = sizeof(test_mem_i),
.instruct = test_mem_i
};
Instruct test_basic_algebra_i[] = {
{LCMM, 0x100, 0},
{DATI, 0x1, 1},
// $1 = $1 + $1
// 1, 2, 4, 8, 16, ...
{ADDL, 1, 1},
{ADDL, 1, 1},
{ADDL, 1, 1},
{ADDL, 1, 1},
// Put the result somewhere else
{MVRL, 1, 31},
// Then divide it by 4
{DATI, 0x4, 11},
{DIVL, 1, 11},
{HALT, 0, 0},
};
Program test_basic_algebra_p {
.size = sizeof(test_basic_algebra_i),
.instruct = test_basic_algebra_i
};
Instruct test_flow_control_i[] = {
{DATB, 0x1, 20},
{DATB, 0xA, 10},
{DATB, 0x2, 15},
{ADDL, 15, 15},
{ADDL, 3, 20},
{CMPI, 3, 10},
{PUSH, 15, 1},
{JILA, 3 * sizeof(Instruct), 0},
{HALT, 0, 0},
};
Program test_flow_control_p {
.size = sizeof(test_flow_control_i),
.instruct = test_flow_control_i
};
const char* const test_asm =
"# Comments.\n"
"DATB 0x1 $20\n"
"DATB 0xA $10\n"
"DATB 0x2 $15\n"
"[loop_start]\n"
"ADDL $15 $15\n"
"ADDL $3 $20\n"
"CMPI $3 $10\n"
"PUSH $15 1\n"
"JILA [loop_start]\n"
"HALT\n"
"DD 0x7676 0xEFEF 0xABAB 0xCDCD 0x0000\n"
"# EOF\n";
const char* const test_bios =
"DATI 0x76 $0\n"
"SLIA 0x100 $0\n"
"INTX 0x1 0x100\n"
"DATI 0xAB $0\n"
"SLIA 0x100 $0\n"
"INTX 0x1 0x100\n"
"HALT\n"
"# EOF\n";
static uint32_t test_bios_call(uint8_t* input) {
printf("TEST BIOS CALL: %x\n", *((uint32_t*) input));
return 0x89ABCDEF;
}
Instruct test_speed_i[] = {
{DATI, 0x1, 20},
{DATI, 0x3000000, 60},
{DATI, 0x2, 15},
{ADDL, 3, 20},
{CMPI, 3, 60},
{JILA, 3 * sizeof(Instruct), 0},
{HALT, 0, 0},
};
Program test_speed_p {
.size = sizeof(test_speed_i),
.instruct = test_speed_i
};
const char* const test_tag =
"JMPA [end]\n"
"ADDI $50 $100\n"
"MINI $25 $50\n"
"[end]\n"
"HALT\n"
"# EOF\n";
int main() {
puts("+---------------------+");
puts("| ASM 76 Test Program |");
puts("+---------------------+");
init();
{
puts("===== Memory =====");
VM v(test_mem_p);
v.execute(true);
v.dump_registers();
}
{
puts("===== Basic Algebra =====");
VM v(test_basic_algebra_p);
v.execute(true);
v.dump_registers();
}
{
puts("===== Disassembler =====");
Disassembler d(test_flow_control_p);
char* s = d.disassemble();
puts(s);
free(s);
}
{
puts("===== Assembler =====");
Assembler a(test_asm);
a.scan();
Program p = a.assemble();
// Test assembler DD function
printf("Data DD: %04x%08x%08x\n", p.instruct[9].opcode, p.instruct[9].a, p.instruct[9].b);
// Test disassembler
Disassembler d(p);
char* s = d.disassemble();
puts(s);
free(s);
puts("===== Flow Control & Logistics =====");
VM v(p);
v.execute(false);
v.dump_registers();
free(p.instruct);
}
{
puts("===== Assembler: Tag Test =====");
Assembler a(test_tag);
a.scan();
Program p = a.assemble();
Disassembler d(p);
char* s = d.disassemble();
puts(s);
free(s);
}
{
puts("===== BIOS Test =====");
BIOS* b = new BIOS(5);
b->function_table[1] = &test_bios_call;
Assembler a(test_bios);
a.scan();
Program p = a.assemble();
VM v(p);
v.firmware = b;
v.execute(true);
v.dump_registers();
}
{
puts("===== Object Code =====");
ObjectCode::write_file("test.obj", test_mem_p);
Program p = ObjectCode::read_file("test.obj");
Disassembler d(p);
char* s = d.disassemble();
puts(s);
free(s);
free(p.instruct);
}
{
puts("===== Speed Test: 0x3000000 cycles =====");
VM v(test_speed_p);
// The type is chrono::time_point<chrono::high_resolution_clock>
// and that is why people used auto.
auto t1 = chrono::high_resolution_clock::now();
v.execute(false);
auto t2 = chrono::high_resolution_clock::now();
chrono::duration<double, milli> delay = t2 - t1;
printf("Elapsed time: %lfms\nMIPS: %lf\n",
delay.count(),
((double) 0x3000000) * 3.0 / ((double) delay.count()) / 10000.0
);
}
puts("\n===== TEST END =====");
return 0;
}
<commit_msg>Refine VMtest.cxx × 2<commit_after>//=============================================================================
// ■ VMtest.cxx
//-----------------------------------------------------------------------------
// 虚拟机、汇编器、反汇编器、目标代码的测试程序。
// 扩展名用了.cxx,意思是“× 不要自动编译”。
//=============================================================================
#include <ratio>
#include <chrono>
using namespace std;
#include "ASM76.hpp"
using namespace ASM76;
void test_mem() {
puts("===== Memory =====");
Instruct instruct[] = {
{LCMM, 0x4000000, 0},
{DATI, 0xABCD1234, 1},
{DATB, 'V', 5},
{DATB, 'M', 6},
{DATB, '7', 7},
{DATB, '6', 8},
{SLLA, 0x2000000, 1},
{SLIA, 0x2500000, 2},
{SLBA, 0x2700000, 3},
{LDLA, 0x2500000, 51},
{LDIA, 0x2500000, 51},
{LDBA, 0x2500000, 61},
{HALT, 0, 0},
};
Program p {
.size = sizeof(instruct),
.instruct = instruct
};
VM v(p);
v.execute(true);
v.dump_registers();
}
void test_basic_algebra() {
puts("===== Basic Algebra =====");
Instruct instruct[] = {
{LCMM, 0x100, 0},
{DATI, 0x1, 1},
// $1 = $1 + $1
// 1, 2, 4, 8, 16, ...
{ADDL, 1, 1},
{ADDL, 1, 1},
{ADDL, 1, 1},
{ADDL, 1, 1},
// Put the result somewhere else
{MVRL, 1, 31},
// Then divide it by 4
{DATI, 0x4, 11},
{DIVL, 1, 11},
{HALT, 0, 0},
};
Program p {
.size = sizeof(instruct),
.instruct = instruct
};
VM v(p);
v.execute(true);
v.dump_registers();
}
void test_disassembler_assembler() {
puts("===== Assembler =====");
const char* const s1 =
"# Comments.\n"
"DATB 0x1 $20\n"
"DATB 0xA $10\n"
"DATB 0x2 $15\n"
"[loop_start]\n"
"ADDL $15 $15\n"
"ADDL $3 $20\n"
"CMPI $3 $10\n"
"PUSH $15 1\n"
"JILA [loop_start]\n"
"HALT\n"
"DD 0x7676 0xEFEF 0xABAB 0xCDCD 0x0000\n"
"# EOF\n";
Assembler a(s1);
a.scan();
Program p = a.assemble();
// Test assembler DD function
printf(
"Data DD: %04x%08x%08x\n",
p.instruct[9].opcode,
p.instruct[9].a,
p.instruct[9].b
);
// Test disassembler
Disassembler d(p);
char* s2 = d.disassemble();
puts(s2);
free(s2);
}
void test_tag() {
puts("===== Assembler: Tag Test =====");
const char* const s1 =
"JMPA [end]\n"
"ADDI $50 $100\n"
"MINI $25 $50\n"
"[end]\n"
"HALT\n"
"# EOF\n";
Assembler a(s1);
a.scan();
Program p = a.assemble();
Disassembler d(p);
char* s2 = d.disassemble();
puts(s2);
free(s2);
}
void test_flow_control() {
puts("===== Flow Control & Logistics =====");
Instruct instruct[] = {
{DATB, 0x1, 20},
{DATB, 0xA, 10},
{DATB, 0x2, 15},
{ADDL, 15, 15},
{ADDL, 3, 20},
{CMPI, 3, 10},
{PUSH, 15, 1},
{JILA, 3 * sizeof(Instruct), 0},
{HALT, 0, 0},
};
Program p {
.size = sizeof(instruct),
.instruct = instruct
};
VM v(p);
v.execute(false);
v.dump_registers();
}
static uint32_t test_bios_call(uint8_t* input) {
printf("TEST BIOS CALL: %x\n", *((uint32_t*) input));
return 0x89ABCDEF;
}
void test_bios() {
puts("===== BIOS Test =====");
const char* const s =
"DATI 0x76 $0\n"
"SLIA 0x100 $0\n"
"INTX 0x1 0x100\n"
"DATI 0xAB $0\n"
"SLIA 0x100 $0\n"
"INTX 0x1 0x100\n"
"HALT\n"
"# EOF\n";
BIOS b(5);
b.function_table[1] = &test_bios_call;
Assembler a(s);
a.scan();
Program p = a.assemble();
VM v(p);
v.firmware = &b;
v.execute(true);
v.dump_registers();
}
void test_object_code() {
puts("===== Object Code =====");
Instruct instruct[] = {
{ADDL, 7, 6},
{NOOP, 0, 0},
{HALT, 0, 0},
};
Program p1 {
.size = sizeof(instruct),
.instruct = instruct
};
ObjectCode::write_file("test.obj", p1);
Program p2 = ObjectCode::read_file("test.obj");
Disassembler d(p2);
char* s = d.disassemble();
puts(s);
free(s);
free(p2.instruct);
}
void test_speed() {
puts("===== Speed Test: 0x3000000 cycles =====");
Instruct instruct[] = {
{DATI, 0x1, 20},
{DATI, 0x3000000, 60},
{DATI, 0x2, 15},
{ADDL, 3, 20},
{CMPI, 3, 60},
{JILA, 3 * sizeof(Instruct), 0},
{HALT, 0, 0},
};
Program p {
.size = sizeof(instruct),
.instruct = instruct
};
VM v(p);
// The type is chrono::time_point<chrono::high_resolution_clock>
// and that is why people used auto.
auto t1 = chrono::high_resolution_clock::now();
v.execute(false);
auto t2 = chrono::high_resolution_clock::now();
chrono::duration<double, milli> delay = t2 - t1;
printf("Elapsed time: %lfms\nMIPS: %lf\n",
delay.count(),
((double) 0x3000000) * 3.0 / ((double) delay.count()) / 10000.0
);
}
int main() {
puts("+---------------------+");
puts("| ASM 76 Test Program |");
puts("+---------------------+");
init();
test_mem();
test_basic_algebra();
test_disassembler_assembler();
test_tag();
test_flow_control();
test_bios();
test_object_code();
test_speed();
putchar('\n');
terminate();
puts("# TEST END #");
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2003 The Regents of The University of Michigan
* 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.
*/
/* @file
* Reference counted class containing ethernet packet data
*/
#ifndef __ETHERPKT_HH__
#define __ETHERPKT_HH__
#include <memory>
#include "sim/host.hh"
#include "base/refcnt.hh"
/*
* Reference counted class containing ethernet packet data
*/
class EtherPacket : public RefCounted
{
public:
uint8_t *data;
int length;
public:
EtherPacket() : data(NULL), length(0) {}
EtherPacket(std::auto_ptr<uint8_t> d, int l)
: data(d.release()), length(l) {}
~EtherPacket() { if (data) delete [] data; }
public:
bool IsUnicast() { return data[0] == 0x00; }
bool IsMulticast() { return data[0] == 0x01; }
bool IsBroadcast() { return data[0] == 0xff; }
};
typedef RefCountingPtr<EtherPacket> PacketPtr;
#endif // __ETHERPKT_HH__
<commit_msg>Add serialization for etherdev These changes don't seem to break anything, and may even be correct.<commit_after>/*
* Copyright (c) 2003 The Regents of The University of Michigan
* 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.
*/
/* @file
* Reference counted class containing ethernet packet data
*/
#ifndef __ETHERPKT_HH__
#define __ETHERPKT_HH__
#include <memory>
#include "sim/host.hh"
#include "base/refcnt.hh"
class IniFile;
/*
* Reference counted class containing ethernet packet data
*/
class EtherPacket : public RefCounted
{
public:
uint8_t *data;
int length;
public:
EtherPacket() : data(NULL), length(0) {}
EtherPacket(std::auto_ptr<uint8_t> d, int l)
: data(d.release()), length(l) {}
~EtherPacket() { if (data) delete [] data; }
public:
bool IsUnicast() { return data[0] == 0x00; }
bool IsMulticast() { return data[0] == 0x01; }
bool IsBroadcast() { return data[0] == 0xff; }
virtual void serialize(std::ostream &os);
virtual void unserialize(const IniFile *db, const std::string §ion);
};
typedef RefCountingPtr<EtherPacket> PacketPtr;
#endif // __ETHERPKT_HH__
<|endoftext|>
|
<commit_before>/**
* This file is part of the "tsdb" project
* Copyright (c) 2015 Paul Asmuth, FnordCorp B.V.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <stx/io/fileutil.h>
#include <zbase/core/Partition.h>
#include <zbase/core/LSMPartitionWriter.h>
#include <zbase/core/RecordVersionMap.h>
#include <stx/protobuf/msg.h>
#include <stx/logging.h>
#include <stx/wallclock.h>
#include <stx/logging.h>
#include <sstable/SSTableWriter.h>
#include <stx/protobuf/MessageDecoder.h>
#include <cstable/RecordShredder.h>
#include <cstable/CSTableWriter.h>
#include <sstable/sstablereader.h>
using namespace stx;
namespace zbase {
LSMPartitionWriter::LSMPartitionWriter(
RefPtr<Partition> partition,
PartitionSnapshotRef* head) :
PartitionWriter(head),
partition_(partition),
compaction_strategy_(
new SimpleCompactionStrategy(
partition_->getTable(),
head->getSnapshot()->base_path)),
max_datafile_size_(kDefaultMaxDatafileSize) {}
Set<SHA1Hash> LSMPartitionWriter::insertRecords(const Vector<RecordRef>& records) {
std::unique_lock<std::mutex> lk(mutex_);
if (frozen_) {
RAISE(kIllegalStateError, "partition is frozen");
}
auto snap = head_->getSnapshot();
stx::logTrace(
"tsdb",
"Insert $0 record into partition $1/$2/$3",
records.size(),
snap->state.tsdb_namespace(),
snap->state.table_key(),
snap->key.toString());
HashMap<SHA1Hash, uint64_t> rec_versions;
for (const auto& r : records) {
if (snap->head_arena->fetchRecordVersion(r.record_id) < r.record_version) {
rec_versions.emplace(r.record_id, 0);
}
}
if (snap->compacting_arena.get() != nullptr) {
for (auto& r : rec_versions) {
auto v = snap->compacting_arena->fetchRecordVersion(r.first);
if (v > r.second) {
r.second = v;
}
}
}
const auto& tables = snap->state.lsm_tables();
for (auto tbl = tables.rbegin(); tbl != tables.rend(); ++tbl) {
RecordVersionMap::lookup(
&rec_versions,
FileUtil::joinPaths(snap->base_path, tbl->filename() + ".idx"));
// FIMXE early exit...
}
Set<SHA1Hash> inserted_ids;
if (!rec_versions.empty()) {
for (auto r : records) {
auto headv = rec_versions[r.record_id];
if (headv > 0) {
r.is_update = true;
}
if (r.record_version <= headv) {
continue;
}
if (snap->head_arena->insertRecord(r)) {
inserted_ids.emplace(r.record_id);
}
}
}
return inserted_ids;
}
bool LSMPartitionWriter::needsCommit() {
ScopedLock<std::mutex> write_lk(mutex_);
return head_->getSnapshot()->head_arena->size() > 0;
}
bool LSMPartitionWriter::needsCompaction() {
if (needsCommit() || needsUpgradeFromV1()) {
return true;
}
auto snap = head_->getSnapshot();
return compaction_strategy_->needsCompaction(
Vector<LSMTableRef>(
snap->state.lsm_tables().begin(),
snap->state.lsm_tables().end()));
}
bool LSMPartitionWriter::commit() {
ScopedLock<std::mutex> commit_lk(commit_mutex_);
RefPtr<RecordArena> arena;
// flip arenas if records pending
{
ScopedLock<std::mutex> write_lk(mutex_);
auto snap = head_->getSnapshot()->clone();
if (snap->compacting_arena.get() == nullptr &&
snap->head_arena->size() > 0) {
snap->compacting_arena = snap->head_arena;
snap->head_arena = mkRef(new RecordArena());
head_->setSnapshot(snap);
}
arena = snap->compacting_arena;
}
// flush arena to disk if pending
if (arena.get() && arena->size() > 0) {
auto snap = head_->getSnapshot();
auto filename = Random::singleton()->hex64();
auto filepath = FileUtil::joinPaths(snap->base_path, filename);
auto t0 = WallClock::unixMicros();
writeArenaToDisk(arena, snap->state.lsm_sequence() + 1, filepath);
auto t1 = WallClock::unixMicros();
stx::logDebug(
"z1.core",
"Committing partition $1/$2/$3 ($0 records), took $4s",
arena->size(),
snap->state.tsdb_namespace(),
snap->state.table_key(),
snap->key.toString(),
(double) (t1 - t0) / 1000000.0f);
ScopedLock<std::mutex> write_lk(mutex_);
snap = head_->getSnapshot()->clone();
auto tblref = snap->state.add_lsm_tables();
tblref->set_filename(filename);
tblref->set_first_sequence(snap->state.lsm_sequence() + 1);
tblref->set_last_sequence(snap->state.lsm_sequence() + arena->size());
snap->state.set_lsm_sequence(snap->state.lsm_sequence() + arena->size());
snap->compacting_arena = nullptr;
snap->writeToDisk();
head_->setSnapshot(snap);
return true;
} else {
return false;
}
}
bool LSMPartitionWriter::compact() {
if (needsUpgradeFromV1()) {
upgradeFromV1();
}
auto dirty = commit();
// fetch current table list
auto snap = head_->getSnapshot()->clone();
Vector<LSMTableRef> new_tables;
Vector<LSMTableRef> old_tables(
snap->state.lsm_tables().begin(),
snap->state.lsm_tables().end());
// compact
auto t0 = WallClock::unixMicros();
if (!compaction_strategy_->compact(old_tables, &new_tables)) {
return dirty;
}
auto t1 = WallClock::unixMicros();
stx::logDebug(
"z1.core",
"Compacting partition $0/$1/$2, took $3s",
snap->state.tsdb_namespace(),
snap->state.table_key(),
snap->key.toString(),
(double) (t1 - t0) / 1000000.0f);
// commit table list
ScopedLock<std::mutex> write_lk(mutex_);
snap = head_->getSnapshot()->clone();
if (snap->state.lsm_tables().size() < old_tables.size()) {
RAISE(kConcurrentModificationError, "concurrent compaction");
}
size_t i = 0;
for (const auto& tbl : snap->state.lsm_tables()) {
if (i < old_tables.size()) {
if (old_tables[i].filename() != tbl.filename()) {
RAISE(kConcurrentModificationError, "concurrent compaction");
}
} else {
new_tables.push_back(tbl);
}
++i;
}
snap->state.mutable_lsm_tables()->Clear();
for (const auto& tbl : new_tables) {
*snap->state.add_lsm_tables() = tbl;
}
snap->writeToDisk();
head_->setSnapshot(snap);
write_lk.unlock();
Set<String> delete_filenames;
for (const auto& tbl : old_tables) {
delete_filenames.emplace(tbl.filename());
}
for (const auto& tbl : new_tables) {
delete_filenames.erase(tbl.filename());
}
for (const auto& f : delete_filenames) {
// FIXME: delayed delete
FileUtil::rm(FileUtil::joinPaths(snap->base_path, f + ".cst"));
FileUtil::rm(FileUtil::joinPaths(snap->base_path, f + ".idx"));
}
return true;
}
void LSMPartitionWriter::writeArenaToDisk(
RefPtr<RecordArena> arena,
uint64_t sequence,
const String& filename) {
auto schema = partition_->getTable()->schema();
{
OrderedMap<SHA1Hash, uint64_t> vmap;
auto cstable_schema = cstable::TableSchema::fromProtobuf(*schema);
auto cstable_schema_ext = cstable_schema;
cstable_schema_ext.addBool("__lsm_is_update", false);
cstable_schema_ext.addString("__lsm_id", false);
cstable_schema_ext.addUnsignedInteger("__lsm_version", false);
cstable_schema_ext.addUnsignedInteger("__lsm_sequence", false);
auto cstable = cstable::CSTableWriter::createFile(
filename + ".cst",
cstable::BinaryFormatVersion::v0_1_0,
cstable_schema_ext);
cstable::RecordShredder shredder(cstable.get(), &cstable_schema);
auto is_update_col = cstable->getColumnWriter("__lsm_is_update");
auto id_col = cstable->getColumnWriter("__lsm_id");
auto version_col = cstable->getColumnWriter("__lsm_version");
auto sequence_col = cstable->getColumnWriter("__lsm_sequence");
arena->fetchRecords([&] (const RecordRef& r) {
msg::MessageObject obj;
msg::MessageDecoder::decode(r.record, *schema, &obj);
shredder.addRecordFromProtobuf(obj, *schema);
is_update_col->writeBoolean(0, 0, r.is_update);
String id_str((const char*) r.record_id.data(), r.record_id.size());
id_col->writeString(0, 0, id_str);
version_col->writeUnsignedInt(0, 0, r.record_version);
sequence_col->writeUnsignedInt(0, 0, sequence++);
vmap.emplace(r.record_id, r.record_version);
});
cstable->commit();
RecordVersionMap::write(vmap, filename + ".idx");
}
}
ReplicationState LSMPartitionWriter::fetchReplicationState() const {
auto snap = head_->getSnapshot();
auto repl_state = snap->state.replication_state();
String tbl_uuid((char*) snap->uuid().data(), snap->uuid().size());
if (repl_state.uuid() == tbl_uuid) {
return repl_state;
} else {
ReplicationState state;
state.set_uuid(tbl_uuid);
return state;
}
}
void LSMPartitionWriter::commitReplicationState(const ReplicationState& state) {
ScopedLock<std::mutex> write_lk(mutex_);
auto snap = head_->getSnapshot()->clone();
*snap->state.mutable_replication_state() = state;
snap->writeToDisk();
head_->setSnapshot(snap);
}
void LSMPartitionWriter::upgradeFromV1() {
ScopedLock<std::mutex> upgrade_lk(upgrade_mutex_);
auto snap = head_->getSnapshot();
logNotice(
"z1.core",
"Upgrading partition $0/$1/$2 to LSM storage v0.2.0",
snap->state.tsdb_namespace(),
snap->state.table_key(),
snap->key.toString());
auto cst_filepath = FileUtil::joinPaths(snap->base_path, "_cstable");
if (FileUtil::exists(cst_filepath)) {
FileUtil::rm(cst_filepath);
}
auto cstm_filepath = FileUtil::joinPaths(snap->base_path, "_cstable_state");
if (FileUtil::exists(cstm_filepath)) {
FileUtil::rm(cstm_filepath);
}
auto files = snap->state.sstable_files();
size_t nrecs = 0;
for (const auto& f : files) {
auto fpath = FileUtil::joinPaths(snap->base_path, f);
sstable::SSTableReader reader(fpath);
Vector<RecordRef> records;
auto cursor = reader.getCursor();
while (cursor->valid()) {
void* key;
size_t key_size;
cursor->getKey(&key, &key_size);
if (key_size != SHA1Hash::kSize) {
RAISE(kRuntimeError, "invalid row");
}
void* data;
size_t data_size;
cursor->getData(&data, &data_size);
++nrecs;
auto record_id = SHA1Hash(key, key_size);
records.emplace_back(record_id, 1, Buffer(data, data_size));
if (records.size() == 8192) {
insertRecords(records);
records.clear();
commit();
}
if (!cursor->next()) {
break;
}
}
insertRecords(records);
}
commit();
{
ScopedLock<std::mutex> write_lk(mutex_);
auto snap = head_->getSnapshot()->clone();
snap->state.mutable_sstable_files()->Clear();
snap->writeToDisk();
head_->setSnapshot(snap);
}
for (const auto& f : files) {
auto fpath = FileUtil::joinPaths(snap->base_path, f);
FileUtil::mv(fpath, fpath + ".DELETED_BY_UPGRADE");
}
auto idset_filepath = FileUtil::joinPaths(snap->base_path, "_idset");
if (FileUtil::exists(idset_filepath)) {
FileUtil::mv(idset_filepath, idset_filepath + ".DELETED_BY_UPGRADE");
}
auto repl_filepath = FileUtil::joinPaths(snap->base_path, "_repl");
if (FileUtil::exists(repl_filepath)) {
FileUtil::rm(repl_filepath);
}
logNotice(
"z1.core",
"Upgrade for partition $1/$2/$3 ($0 records) to LSM storage v0.2.0 done",
nrecs,
snap->state.tsdb_namespace(),
snap->state.table_key(),
snap->key.toString());
}
bool LSMPartitionWriter::needsUpgradeFromV1() {
auto snap = head_->getSnapshot();
return
snap->state.sstable_files().size() > 0 ||
FileUtil::exists(FileUtil::joinPaths(snap->base_path, "_idset")) ||
FileUtil::exists(FileUtil::joinPaths(snap->base_path, "_repl")) ||
FileUtil::exists(FileUtil::joinPaths(snap->base_path, "_cstable_state")) ||
FileUtil::exists(FileUtil::joinPaths(snap->base_path, "_cstable"));
}
} // namespace tdsb
<commit_msg>compact after upgrade<commit_after>/**
* This file is part of the "tsdb" project
* Copyright (c) 2015 Paul Asmuth, FnordCorp B.V.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <stx/io/fileutil.h>
#include <zbase/core/Partition.h>
#include <zbase/core/LSMPartitionWriter.h>
#include <zbase/core/RecordVersionMap.h>
#include <stx/protobuf/msg.h>
#include <stx/logging.h>
#include <stx/wallclock.h>
#include <stx/logging.h>
#include <sstable/SSTableWriter.h>
#include <stx/protobuf/MessageDecoder.h>
#include <cstable/RecordShredder.h>
#include <cstable/CSTableWriter.h>
#include <sstable/sstablereader.h>
using namespace stx;
namespace zbase {
LSMPartitionWriter::LSMPartitionWriter(
RefPtr<Partition> partition,
PartitionSnapshotRef* head) :
PartitionWriter(head),
partition_(partition),
compaction_strategy_(
new SimpleCompactionStrategy(
partition_->getTable(),
head->getSnapshot()->base_path)),
max_datafile_size_(kDefaultMaxDatafileSize) {}
Set<SHA1Hash> LSMPartitionWriter::insertRecords(const Vector<RecordRef>& records) {
std::unique_lock<std::mutex> lk(mutex_);
if (frozen_) {
RAISE(kIllegalStateError, "partition is frozen");
}
auto snap = head_->getSnapshot();
stx::logTrace(
"tsdb",
"Insert $0 record into partition $1/$2/$3",
records.size(),
snap->state.tsdb_namespace(),
snap->state.table_key(),
snap->key.toString());
HashMap<SHA1Hash, uint64_t> rec_versions;
for (const auto& r : records) {
if (snap->head_arena->fetchRecordVersion(r.record_id) < r.record_version) {
rec_versions.emplace(r.record_id, 0);
}
}
if (snap->compacting_arena.get() != nullptr) {
for (auto& r : rec_versions) {
auto v = snap->compacting_arena->fetchRecordVersion(r.first);
if (v > r.second) {
r.second = v;
}
}
}
const auto& tables = snap->state.lsm_tables();
for (auto tbl = tables.rbegin(); tbl != tables.rend(); ++tbl) {
RecordVersionMap::lookup(
&rec_versions,
FileUtil::joinPaths(snap->base_path, tbl->filename() + ".idx"));
// FIMXE early exit...
}
Set<SHA1Hash> inserted_ids;
if (!rec_versions.empty()) {
for (auto r : records) {
auto headv = rec_versions[r.record_id];
if (headv > 0) {
r.is_update = true;
}
if (r.record_version <= headv) {
continue;
}
if (snap->head_arena->insertRecord(r)) {
inserted_ids.emplace(r.record_id);
}
}
}
return inserted_ids;
}
bool LSMPartitionWriter::needsCommit() {
ScopedLock<std::mutex> write_lk(mutex_);
return head_->getSnapshot()->head_arena->size() > 0;
}
bool LSMPartitionWriter::needsCompaction() {
if (needsCommit() || needsUpgradeFromV1()) {
return true;
}
auto snap = head_->getSnapshot();
return compaction_strategy_->needsCompaction(
Vector<LSMTableRef>(
snap->state.lsm_tables().begin(),
snap->state.lsm_tables().end()));
}
bool LSMPartitionWriter::commit() {
ScopedLock<std::mutex> commit_lk(commit_mutex_);
RefPtr<RecordArena> arena;
// flip arenas if records pending
{
ScopedLock<std::mutex> write_lk(mutex_);
auto snap = head_->getSnapshot()->clone();
if (snap->compacting_arena.get() == nullptr &&
snap->head_arena->size() > 0) {
snap->compacting_arena = snap->head_arena;
snap->head_arena = mkRef(new RecordArena());
head_->setSnapshot(snap);
}
arena = snap->compacting_arena;
}
// flush arena to disk if pending
if (arena.get() && arena->size() > 0) {
auto snap = head_->getSnapshot();
auto filename = Random::singleton()->hex64();
auto filepath = FileUtil::joinPaths(snap->base_path, filename);
auto t0 = WallClock::unixMicros();
writeArenaToDisk(arena, snap->state.lsm_sequence() + 1, filepath);
auto t1 = WallClock::unixMicros();
stx::logDebug(
"z1.core",
"Committing partition $1/$2/$3 ($0 records), took $4s",
arena->size(),
snap->state.tsdb_namespace(),
snap->state.table_key(),
snap->key.toString(),
(double) (t1 - t0) / 1000000.0f);
ScopedLock<std::mutex> write_lk(mutex_);
snap = head_->getSnapshot()->clone();
auto tblref = snap->state.add_lsm_tables();
tblref->set_filename(filename);
tblref->set_first_sequence(snap->state.lsm_sequence() + 1);
tblref->set_last_sequence(snap->state.lsm_sequence() + arena->size());
snap->state.set_lsm_sequence(snap->state.lsm_sequence() + arena->size());
snap->compacting_arena = nullptr;
snap->writeToDisk();
head_->setSnapshot(snap);
return true;
} else {
return false;
}
}
bool LSMPartitionWriter::compact() {
if (needsUpgradeFromV1()) {
upgradeFromV1();
}
auto dirty = commit();
// fetch current table list
auto snap = head_->getSnapshot()->clone();
Vector<LSMTableRef> new_tables;
Vector<LSMTableRef> old_tables(
snap->state.lsm_tables().begin(),
snap->state.lsm_tables().end());
// compact
auto t0 = WallClock::unixMicros();
if (!compaction_strategy_->compact(old_tables, &new_tables)) {
return dirty;
}
auto t1 = WallClock::unixMicros();
stx::logDebug(
"z1.core",
"Compacting partition $0/$1/$2, took $3s",
snap->state.tsdb_namespace(),
snap->state.table_key(),
snap->key.toString(),
(double) (t1 - t0) / 1000000.0f);
// commit table list
ScopedLock<std::mutex> write_lk(mutex_);
snap = head_->getSnapshot()->clone();
if (snap->state.lsm_tables().size() < old_tables.size()) {
RAISE(kConcurrentModificationError, "concurrent compaction");
}
size_t i = 0;
for (const auto& tbl : snap->state.lsm_tables()) {
if (i < old_tables.size()) {
if (old_tables[i].filename() != tbl.filename()) {
RAISE(kConcurrentModificationError, "concurrent compaction");
}
} else {
new_tables.push_back(tbl);
}
++i;
}
snap->state.mutable_lsm_tables()->Clear();
for (const auto& tbl : new_tables) {
*snap->state.add_lsm_tables() = tbl;
}
snap->writeToDisk();
head_->setSnapshot(snap);
write_lk.unlock();
Set<String> delete_filenames;
for (const auto& tbl : old_tables) {
delete_filenames.emplace(tbl.filename());
}
for (const auto& tbl : new_tables) {
delete_filenames.erase(tbl.filename());
}
for (const auto& f : delete_filenames) {
// FIXME: delayed delete
FileUtil::rm(FileUtil::joinPaths(snap->base_path, f + ".cst"));
FileUtil::rm(FileUtil::joinPaths(snap->base_path, f + ".idx"));
}
return true;
}
void LSMPartitionWriter::writeArenaToDisk(
RefPtr<RecordArena> arena,
uint64_t sequence,
const String& filename) {
auto schema = partition_->getTable()->schema();
{
OrderedMap<SHA1Hash, uint64_t> vmap;
auto cstable_schema = cstable::TableSchema::fromProtobuf(*schema);
auto cstable_schema_ext = cstable_schema;
cstable_schema_ext.addBool("__lsm_is_update", false);
cstable_schema_ext.addString("__lsm_id", false);
cstable_schema_ext.addUnsignedInteger("__lsm_version", false);
cstable_schema_ext.addUnsignedInteger("__lsm_sequence", false);
auto cstable = cstable::CSTableWriter::createFile(
filename + ".cst",
cstable::BinaryFormatVersion::v0_1_0,
cstable_schema_ext);
cstable::RecordShredder shredder(cstable.get(), &cstable_schema);
auto is_update_col = cstable->getColumnWriter("__lsm_is_update");
auto id_col = cstable->getColumnWriter("__lsm_id");
auto version_col = cstable->getColumnWriter("__lsm_version");
auto sequence_col = cstable->getColumnWriter("__lsm_sequence");
arena->fetchRecords([&] (const RecordRef& r) {
msg::MessageObject obj;
msg::MessageDecoder::decode(r.record, *schema, &obj);
shredder.addRecordFromProtobuf(obj, *schema);
is_update_col->writeBoolean(0, 0, r.is_update);
String id_str((const char*) r.record_id.data(), r.record_id.size());
id_col->writeString(0, 0, id_str);
version_col->writeUnsignedInt(0, 0, r.record_version);
sequence_col->writeUnsignedInt(0, 0, sequence++);
vmap.emplace(r.record_id, r.record_version);
});
cstable->commit();
RecordVersionMap::write(vmap, filename + ".idx");
}
}
ReplicationState LSMPartitionWriter::fetchReplicationState() const {
auto snap = head_->getSnapshot();
auto repl_state = snap->state.replication_state();
String tbl_uuid((char*) snap->uuid().data(), snap->uuid().size());
if (repl_state.uuid() == tbl_uuid) {
return repl_state;
} else {
ReplicationState state;
state.set_uuid(tbl_uuid);
return state;
}
}
void LSMPartitionWriter::commitReplicationState(const ReplicationState& state) {
ScopedLock<std::mutex> write_lk(mutex_);
auto snap = head_->getSnapshot()->clone();
*snap->state.mutable_replication_state() = state;
snap->writeToDisk();
head_->setSnapshot(snap);
}
void LSMPartitionWriter::upgradeFromV1() {
ScopedLock<std::mutex> upgrade_lk(upgrade_mutex_);
auto snap = head_->getSnapshot();
logNotice(
"z1.core",
"Upgrading partition $0/$1/$2 to LSM storage v0.2.0",
snap->state.tsdb_namespace(),
snap->state.table_key(),
snap->key.toString());
auto cst_filepath = FileUtil::joinPaths(snap->base_path, "_cstable");
if (FileUtil::exists(cst_filepath)) {
FileUtil::rm(cst_filepath);
}
auto cstm_filepath = FileUtil::joinPaths(snap->base_path, "_cstable_state");
if (FileUtil::exists(cstm_filepath)) {
FileUtil::rm(cstm_filepath);
}
auto files = snap->state.sstable_files();
size_t nrecs = 0;
for (const auto& f : files) {
auto fpath = FileUtil::joinPaths(snap->base_path, f);
sstable::SSTableReader reader(fpath);
Vector<RecordRef> records;
auto cursor = reader.getCursor();
while (cursor->valid()) {
void* key;
size_t key_size;
cursor->getKey(&key, &key_size);
if (key_size != SHA1Hash::kSize) {
RAISE(kRuntimeError, "invalid row");
}
void* data;
size_t data_size;
cursor->getData(&data, &data_size);
++nrecs;
auto record_id = SHA1Hash(key, key_size);
records.emplace_back(record_id, 1, Buffer(data, data_size));
if (records.size() == 8192) {
insertRecords(records);
records.clear();
commit();
}
if (!cursor->next()) {
break;
}
}
insertRecords(records);
}
commit();
{
ScopedLock<std::mutex> write_lk(mutex_);
auto snap = head_->getSnapshot()->clone();
snap->state.mutable_sstable_files()->Clear();
snap->writeToDisk();
head_->setSnapshot(snap);
}
for (const auto& f : files) {
auto fpath = FileUtil::joinPaths(snap->base_path, f);
FileUtil::mv(fpath, fpath + ".DELETED_BY_UPGRADE");
}
auto idset_filepath = FileUtil::joinPaths(snap->base_path, "_idset");
if (FileUtil::exists(idset_filepath)) {
FileUtil::mv(idset_filepath, idset_filepath + ".DELETED_BY_UPGRADE");
}
auto repl_filepath = FileUtil::joinPaths(snap->base_path, "_repl");
if (FileUtil::exists(repl_filepath)) {
FileUtil::rm(repl_filepath);
}
logNotice(
"z1.core",
"Upgrade for partition $1/$2/$3 ($0 records) to LSM storage v0.2.0 done",
nrecs,
snap->state.tsdb_namespace(),
snap->state.table_key(),
snap->key.toString());
compact();
}
bool LSMPartitionWriter::needsUpgradeFromV1() {
auto snap = head_->getSnapshot();
return
snap->state.sstable_files().size() > 0 ||
FileUtil::exists(FileUtil::joinPaths(snap->base_path, "_idset")) ||
FileUtil::exists(FileUtil::joinPaths(snap->base_path, "_repl")) ||
FileUtil::exists(FileUtil::joinPaths(snap->base_path, "_cstable_state")) ||
FileUtil::exists(FileUtil::joinPaths(snap->base_path, "_cstable"));
}
} // namespace tdsb
<|endoftext|>
|
<commit_before>// moderngpu copyright (c) 2016, Sean Baxter http://www.moderngpu.com
#pragma once
#include "kernel_sortedsearch.hxx"
#include "kernel_scan.hxx"
#include "kernel_load_balance.hxx"
BEGIN_MGPU_NAMESPACE
template<typename launch_arg_t = empty_t,
typename a_it, typename b_it, typename comp_t>
mem_t<int2> inner_join(a_it a, int a_count, b_it b, int b_count,
comp_t comp, context_t& context) {
// Compute lower and upper bounds of a into b.
mem_t<int> lower(a_count, context);
mem_t<int> upper(b_count, context);
sorted_search<bounds_lower, launch_arg_t>(a, a_count, b, b_count,
lower.data(), comp, context);
sorted_search<bounds_upper, launch_arg_t>(a, a_count, b, b_count,
upper.data(), comp, context);
// Compute output ranges by scanning upper - lower. Retrieve the reduction
// of the scan, which specifies the size of the output array to allocate.
mem_t<int> scanned_sizes(a_count, context);
const int* lower_data = lower.data();
const int* upper_data = upper.data();
mem_t<int> count(1, context);
transform_scan([=]MGPU_DEVICE(int index) {
return upper_data[index] - lower_data[index];
}, a_count, scanned_sizes.data(), plus_t<int>(), count.data(), context);
// Allocate an int2 output array and use load-balancing search to compute
// the join.
int join_count = from_mem(count)[0];
mem_t<int2> output(join_count, context);
int2* output_data = output.data();
// Use load-balancing search on the segmens. The output is a pair with
// a_index = seg and b_index = lower_data[seg] + rank.
auto k = [=]MGPU_DEVICE(int index, int seg, int rank, tuple<int> lower) {
output_data[index] = make_int2(seg, get<0>(lower) + rank);
};
transform_lbs<launch_arg_t>(k, join_count, scanned_sizes.data(), a_count,
make_tuple(lower_data), context);
return output;
}
END_MGPU_NAMESPACE
<commit_msg>Fixed array sizing bug in inner_join<commit_after>// moderngpu copyright (c) 2016, Sean Baxter http://www.moderngpu.com
#pragma once
#include "kernel_sortedsearch.hxx"
#include "kernel_scan.hxx"
#include "kernel_load_balance.hxx"
BEGIN_MGPU_NAMESPACE
template<typename launch_arg_t = empty_t,
typename a_it, typename b_it, typename comp_t>
mem_t<int2> inner_join(a_it a, int a_count, b_it b, int b_count,
comp_t comp, context_t& context) {
// Compute lower and upper bounds of a into b.
mem_t<int> lower(a_count, context);
mem_t<int> upper(a_count, context);
sorted_search<bounds_lower, launch_arg_t>(a, a_count, b, b_count,
lower.data(), comp, context);
sorted_search<bounds_upper, launch_arg_t>(a, a_count, b, b_count,
upper.data(), comp, context);
// Compute output ranges by scanning upper - lower. Retrieve the reduction
// of the scan, which specifies the size of the output array to allocate.
mem_t<int> scanned_sizes(a_count, context);
const int* lower_data = lower.data();
const int* upper_data = upper.data();
mem_t<int> count(1, context);
transform_scan([=]MGPU_DEVICE(int index) {
return upper_data[index] - lower_data[index];
}, a_count, scanned_sizes.data(), plus_t<int>(), count.data(), context);
// Allocate an int2 output array and use load-balancing search to compute
// the join.
int join_count = from_mem(count)[0];
mem_t<int2> output(join_count, context);
int2* output_data = output.data();
// Use load-balancing search on the segmens. The output is a pair with
// a_index = seg and b_index = lower_data[seg] + rank.
auto k = [=]MGPU_DEVICE(int index, int seg, int rank, tuple<int> lower) {
output_data[index] = make_int2(seg, get<0>(lower) + rank);
};
transform_lbs<launch_arg_t>(k, join_count, scanned_sizes.data(), a_count,
make_tuple(lower_data), context);
return output;
}
END_MGPU_NAMESPACE
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2007 The Hewlett-Packard Development Company
* All rights reserved.
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* 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.
*
* Authors: Gabe Black
*/
#include <string>
#include "arch/x86/pagetable_walker.hh"
#include "arch/x86/tlb.hh"
#include "arch/x86/vtophys.hh"
#include "base/trace.hh"
#include "config/full_system.hh"
#include "cpu/thread_context.hh"
#include "sim/fault.hh"
using namespace std;
namespace X86ISA
{
Addr
vtophys(Addr vaddr)
{
#if FULL_SYSTEM
panic("Need access to page tables\n");
#endif
return vaddr;
}
Addr
vtophys(ThreadContext *tc, Addr vaddr)
{
#if FULL_SYSTEM
Walker *walker = tc->getDTBPtr()->getWalker();
Addr size;
Addr addr = vaddr;
Fault fault = walker->startFunctional(tc, addr, size, BaseTLB::Read);
if (fault != NoFault)
panic("vtophys page walk returned fault\n");
Addr masked_addr = vaddr & (size - 1);
Addr paddr = addr | masked_addr;
DPRINTF(VtoPhys, "vtophys(%#x) -> %#x\n", vaddr, paddr);
return paddr;
#endif
return vaddr;
}
}
<commit_msg>X86: Fix compiling vtophys.cc<commit_after>/*
* Copyright (c) 2007 The Hewlett-Packard Development Company
* All rights reserved.
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* 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.
*
* Authors: Gabe Black
*/
#include <string>
#include "arch/x86/pagetable_walker.hh"
#include "arch/x86/tlb.hh"
#include "arch/x86/vtophys.hh"
#include "base/trace.hh"
#include "config/full_system.hh"
#include "cpu/thread_context.hh"
#include "sim/fault_fwd.hh"
using namespace std;
namespace X86ISA
{
Addr
vtophys(Addr vaddr)
{
#if FULL_SYSTEM
panic("Need access to page tables\n");
#endif
return vaddr;
}
Addr
vtophys(ThreadContext *tc, Addr vaddr)
{
#if FULL_SYSTEM
Walker *walker = tc->getDTBPtr()->getWalker();
Addr size;
Addr addr = vaddr;
Fault fault = walker->startFunctional(tc, addr, size, BaseTLB::Read);
if (fault != NoFault)
panic("vtophys page walk returned fault\n");
Addr masked_addr = vaddr & (size - 1);
Addr paddr = addr | masked_addr;
DPRINTF(VtoPhys, "vtophys(%#x) -> %#x\n", vaddr, paddr);
return paddr;
#endif
return vaddr;
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) [2014-2015] Novell, Inc.
* Copyright (c) [2016-2017] SUSE LLC
*
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, contact Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail, you may
* find current contact information at www.novell.com.
*/
#include <boost/algorithm/string.hpp>
#include "storage/Devices/PartitionableImpl.h"
#include "storage/Devices/PartitionTableImpl.h"
#include "storage/Devices/Msdos.h"
#include "storage/Devices/Gpt.h"
#include "storage/Devices/DasdPt.h"
#include "storage/Devices/ImplicitPt.h"
#include "storage/Holders/User.h"
#include "storage/Devicegraph.h"
#include "storage/Action.h"
#include "storage/Utils/XmlFile.h"
#include "storage/Utils/Enum.h"
#include "storage/Utils/StorageTmpl.h"
#include "storage/Utils/StorageDefines.h"
#include "storage/Utils/SystemCmd.h"
#include "storage/SystemInfo/SystemInfo.h"
#include "storage/StorageImpl.h"
#include "storage/Prober.h"
namespace storage
{
using namespace std;
const char* DeviceTraits<Partitionable>::classname = "Partitionable";
const unsigned int Partitionable::Impl::default_range;
Partitionable::Impl::Impl(const xmlNode* node)
: BlkDevice::Impl(node), topology(), range(0)
{
getChildValue(node, "topology", topology);
getChildValue(node, "range", range);
}
void
Partitionable::Impl::check(const CheckCallbacks* check_callbacks) const
{
BlkDevice::Impl::check(check_callbacks);
if (get_region().get_start() != 0)
ST_THROW(Exception("start of region of partitionable not zero"));
}
void
Partitionable::Impl::save(xmlNode* node) const
{
BlkDevice::Impl::save(node);
setChildValue(node, "topology", topology);
setChildValue(node, "range", range);
}
void
Partitionable::Impl::probe_pass_1a(Prober& prober)
{
BlkDevice::Impl::probe_pass_1a(prober);
const File size_file = prober.get_system_info().getFile(SYSFS_DIR + get_sysfs_path() + "/size");
const File logical_block_size_file = prober.get_system_info().getFile(SYSFS_DIR + get_sysfs_path() +
"/queue/logical_block_size");
// size is always in 512 byte blocks
unsigned long long a = size_file.get<unsigned long long>();
unsigned long long b = logical_block_size_file.get<unsigned long long>();
unsigned long long c = a * 512 / b;
set_region(Region(0, c, b));
const File alignment_offset_file = prober.get_system_info().getFile(SYSFS_DIR + get_sysfs_path() +
"/alignment_offset");
topology.set_alignment_offset(alignment_offset_file.get<int>());
const File optimal_io_size_file = prober.get_system_info().getFile(SYSFS_DIR + get_sysfs_path() +
"/queue/optimal_io_size");
topology.set_optimal_io_size(optimal_io_size_file.get<int>());
if (get_dm_table_name().empty())
{
const File range_file = prober.get_system_info().getFile(SYSFS_DIR + get_sysfs_path() +
"/ext_range");
range = range_file.get<int>();
}
}
void
Partitionable::Impl::probe_pass_1c(Prober& prober)
{
if (has_children() || !is_active() || get_size() == 0)
return;
const Parted& parted = prober.get_system_info().getParted(get_name());
if (parted.get_label() == PtType::MSDOS || parted.get_label() == PtType::GPT ||
parted.get_label() == PtType::DASD)
{
if (get_region().get_block_size() != parted.get_region().get_block_size())
ST_THROW(Exception("different block size reported by kernel and parted"));
if (get_region().get_length() != parted.get_region().get_length())
ST_THROW(Exception("different size reported by kernel and parted"));
PtType label = parted.get_label();
// parted reports DASD partition table for implicit partition
// tables. Convert that to implicit partition table.
if (is_dasd(get_non_impl()))
{
const Dasd* dasd = to_dasd(get_non_impl());
if (dasd->get_type() == DasdType::ECKD && dasd->get_format() == DasdFormat::LDL)
label = PtType::IMPLICIT;
if (dasd->get_type() == DasdType::FBA && parted.is_implicit())
label = PtType::IMPLICIT;
}
PartitionTable* partition_table = create_partition_table(label);
partition_table->get_impl().probe_pass_1c(prober);
}
}
PtType
Partitionable::Impl::get_default_partition_table_type() const
{
vector<PtType> possible = get_possible_partition_table_types();
if (possible.empty())
ST_THROW(Exception("no partition table possible"));
PtType ret = possible.front();
y2mil("ret:" << toString(ret));
return ret;
}
vector<PtType>
Partitionable::Impl::get_possible_partition_table_types() const
{
// ECKD DASDs are handled completely and FBA DASDs partly in Dasd
// class.
unsigned long long int num_sectors = get_region().get_length();
bool size_ok_for_msdos = num_sectors <= UINT32_MAX;
y2mil("num-sectors:" << num_sectors << " size-ok-for-msdos:" << size_ok_for_msdos);
PtType best = PtType::GPT;
vector<PtType> ret = { best };
if (size_ok_for_msdos)
ret.push_back(PtType::MSDOS);
return ret;
}
PartitionTable*
Partitionable::Impl::create_partition_table(PtType pt_type)
{
if (num_children() != 0)
ST_THROW(WrongNumberOfChildren(num_children(), 0));
PartitionTable* ret = nullptr;
switch (pt_type)
{
case PtType::MSDOS:
ret = Msdos::create(get_devicegraph());
break;
case PtType::GPT:
ret = Gpt::create(get_devicegraph());
break;
case PtType::DASD:
ret = DasdPt::create(get_devicegraph());
break;
case PtType::IMPLICIT:
ret = ImplicitPt::create(get_devicegraph());
break;
default:
ST_THROW(UnsupportedException("unsupported partition table type " + toString(pt_type)));
}
User::create(get_devicegraph(), get_non_impl(), ret);
if (pt_type == PtType::IMPLICIT)
{
to_implicit_pt(ret)->create_implicit_partition();
}
return ret;
}
bool
Partitionable::Impl::has_partition_table() const
{
return has_single_child_of_type<const PartitionTable>();
}
PartitionTable*
Partitionable::Impl::get_partition_table()
{
return get_single_child_of_type<PartitionTable>();
}
const PartitionTable*
Partitionable::Impl::get_partition_table() const
{
return get_single_child_of_type<const PartitionTable>();
}
string
Partitionable::Impl::partition_name(int number) const
{
if (boost::starts_with(get_name(), DEV_MAPPER_DIR "/"))
return get_name() + "-part" + to_string(number);
else if (isdigit(get_name().back()))
return get_name() + "p" + to_string(number);
else
return get_name() + to_string(number);
}
bool
Partitionable::Impl::equal(const Device::Impl& rhs_base) const
{
const Impl& rhs = dynamic_cast<const Impl&>(rhs_base);
if (!BlkDevice::Impl::equal(rhs))
return false;
return topology == rhs.topology && range == rhs.range;
}
void
Partitionable::Impl::log_diff(std::ostream& log, const Device::Impl& rhs_base) const
{
const Impl& rhs = dynamic_cast<const Impl&>(rhs_base);
BlkDevice::Impl::log_diff(log, rhs);
storage::log_diff(log, "topology", topology, rhs.topology);
storage::log_diff(log, "range", range, rhs.range);
}
void
Partitionable::Impl::print(std::ostream& out) const
{
BlkDevice::Impl::print(out);
out << " topology:" << topology
<< " range:" << range;
}
}
<commit_msg>- improved error message (see bsc#1089554)<commit_after>/*
* Copyright (c) [2014-2015] Novell, Inc.
* Copyright (c) [2016-2017] SUSE LLC
*
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, contact Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail, you may
* find current contact information at www.novell.com.
*/
#include <boost/algorithm/string.hpp>
#include "storage/Devices/PartitionableImpl.h"
#include "storage/Devices/PartitionTableImpl.h"
#include "storage/Devices/Msdos.h"
#include "storage/Devices/Gpt.h"
#include "storage/Devices/DasdPt.h"
#include "storage/Devices/ImplicitPt.h"
#include "storage/Holders/User.h"
#include "storage/Devicegraph.h"
#include "storage/Action.h"
#include "storage/Utils/XmlFile.h"
#include "storage/Utils/Enum.h"
#include "storage/Utils/StorageTmpl.h"
#include "storage/Utils/StorageDefines.h"
#include "storage/Utils/SystemCmd.h"
#include "storage/SystemInfo/SystemInfo.h"
#include "storage/StorageImpl.h"
#include "storage/Prober.h"
namespace storage
{
using namespace std;
const char* DeviceTraits<Partitionable>::classname = "Partitionable";
const unsigned int Partitionable::Impl::default_range;
Partitionable::Impl::Impl(const xmlNode* node)
: BlkDevice::Impl(node), topology(), range(0)
{
getChildValue(node, "topology", topology);
getChildValue(node, "range", range);
}
void
Partitionable::Impl::check(const CheckCallbacks* check_callbacks) const
{
BlkDevice::Impl::check(check_callbacks);
if (get_region().get_start() != 0)
ST_THROW(Exception("start of region of partitionable not zero"));
}
void
Partitionable::Impl::save(xmlNode* node) const
{
BlkDevice::Impl::save(node);
setChildValue(node, "topology", topology);
setChildValue(node, "range", range);
}
void
Partitionable::Impl::probe_pass_1a(Prober& prober)
{
BlkDevice::Impl::probe_pass_1a(prober);
const File size_file = prober.get_system_info().getFile(SYSFS_DIR + get_sysfs_path() + "/size");
const File logical_block_size_file = prober.get_system_info().getFile(SYSFS_DIR + get_sysfs_path() +
"/queue/logical_block_size");
// size is always in 512 byte blocks
unsigned long long a = size_file.get<unsigned long long>();
unsigned long long b = logical_block_size_file.get<unsigned long long>();
unsigned long long c = a * 512 / b;
set_region(Region(0, c, b));
const File alignment_offset_file = prober.get_system_info().getFile(SYSFS_DIR + get_sysfs_path() +
"/alignment_offset");
topology.set_alignment_offset(alignment_offset_file.get<int>());
const File optimal_io_size_file = prober.get_system_info().getFile(SYSFS_DIR + get_sysfs_path() +
"/queue/optimal_io_size");
topology.set_optimal_io_size(optimal_io_size_file.get<int>());
if (get_dm_table_name().empty())
{
const File range_file = prober.get_system_info().getFile(SYSFS_DIR + get_sysfs_path() +
"/ext_range");
range = range_file.get<int>();
}
}
void
Partitionable::Impl::probe_pass_1c(Prober& prober)
{
if (has_children() || !is_active() || get_size() == 0)
return;
const Parted& parted = prober.get_system_info().getParted(get_name());
if (parted.get_label() == PtType::MSDOS || parted.get_label() == PtType::GPT ||
parted.get_label() == PtType::DASD)
{
if (get_region().get_block_size() != parted.get_region().get_block_size())
ST_THROW(Exception(sformat("different block size reported by kernel and parted for %s",
get_name().c_str())));
if (get_region().get_length() != parted.get_region().get_length())
ST_THROW(Exception(sformat("different size reported by kernel and parted for %s",
get_name().c_str())));
PtType label = parted.get_label();
// parted reports DASD partition table for implicit partition
// tables. Convert that to implicit partition table.
if (is_dasd(get_non_impl()))
{
const Dasd* dasd = to_dasd(get_non_impl());
if (dasd->get_type() == DasdType::ECKD && dasd->get_format() == DasdFormat::LDL)
label = PtType::IMPLICIT;
if (dasd->get_type() == DasdType::FBA && parted.is_implicit())
label = PtType::IMPLICIT;
}
PartitionTable* partition_table = create_partition_table(label);
partition_table->get_impl().probe_pass_1c(prober);
}
}
PtType
Partitionable::Impl::get_default_partition_table_type() const
{
vector<PtType> possible = get_possible_partition_table_types();
if (possible.empty())
ST_THROW(Exception("no partition table possible"));
PtType ret = possible.front();
y2mil("ret:" << toString(ret));
return ret;
}
vector<PtType>
Partitionable::Impl::get_possible_partition_table_types() const
{
// ECKD DASDs are handled completely and FBA DASDs partly in Dasd
// class.
unsigned long long int num_sectors = get_region().get_length();
bool size_ok_for_msdos = num_sectors <= UINT32_MAX;
y2mil("num-sectors:" << num_sectors << " size-ok-for-msdos:" << size_ok_for_msdos);
PtType best = PtType::GPT;
vector<PtType> ret = { best };
if (size_ok_for_msdos)
ret.push_back(PtType::MSDOS);
return ret;
}
PartitionTable*
Partitionable::Impl::create_partition_table(PtType pt_type)
{
if (num_children() != 0)
ST_THROW(WrongNumberOfChildren(num_children(), 0));
PartitionTable* ret = nullptr;
switch (pt_type)
{
case PtType::MSDOS:
ret = Msdos::create(get_devicegraph());
break;
case PtType::GPT:
ret = Gpt::create(get_devicegraph());
break;
case PtType::DASD:
ret = DasdPt::create(get_devicegraph());
break;
case PtType::IMPLICIT:
ret = ImplicitPt::create(get_devicegraph());
break;
default:
ST_THROW(UnsupportedException("unsupported partition table type " + toString(pt_type)));
}
User::create(get_devicegraph(), get_non_impl(), ret);
if (pt_type == PtType::IMPLICIT)
{
to_implicit_pt(ret)->create_implicit_partition();
}
return ret;
}
bool
Partitionable::Impl::has_partition_table() const
{
return has_single_child_of_type<const PartitionTable>();
}
PartitionTable*
Partitionable::Impl::get_partition_table()
{
return get_single_child_of_type<PartitionTable>();
}
const PartitionTable*
Partitionable::Impl::get_partition_table() const
{
return get_single_child_of_type<const PartitionTable>();
}
string
Partitionable::Impl::partition_name(int number) const
{
if (boost::starts_with(get_name(), DEV_MAPPER_DIR "/"))
return get_name() + "-part" + to_string(number);
else if (isdigit(get_name().back()))
return get_name() + "p" + to_string(number);
else
return get_name() + to_string(number);
}
bool
Partitionable::Impl::equal(const Device::Impl& rhs_base) const
{
const Impl& rhs = dynamic_cast<const Impl&>(rhs_base);
if (!BlkDevice::Impl::equal(rhs))
return false;
return topology == rhs.topology && range == rhs.range;
}
void
Partitionable::Impl::log_diff(std::ostream& log, const Device::Impl& rhs_base) const
{
const Impl& rhs = dynamic_cast<const Impl&>(rhs_base);
BlkDevice::Impl::log_diff(log, rhs);
storage::log_diff(log, "topology", topology, rhs.topology);
storage::log_diff(log, "range", range, rhs.range);
}
void
Partitionable::Impl::print(std::ostream& out) const
{
BlkDevice::Impl::print(out);
out << " topology:" << topology
<< " range:" << range;
}
}
<|endoftext|>
|
<commit_before>#include "controller_ros.h"
#include <tf/transform_datatypes.h>
#include <eigen_conversions/eigen_msg.h>
Controller::Controller(ros::NodeHandle nh) : nh(nh)
{
command_sub = nh.subscribe("joystick_motion_command", 10, &Controller::commandCallback, this);
state_sub = nh.subscribe("state_estimate", 10, &Controller::stateCallback, this);
wrench_pub = nh.advertise<geometry_msgs::Wrench>("rov_forces", 10);
control_mode = ControlModes::OPEN_LOOP;
prev_time_valid = false;
position_state.setZero();
orientation_state.setIdentity();
velocity_state.setZero();
position_setpoint.setZero();
orientation_setpoint.setIdentity();
wrench_setpoint.setZero();
getParams();
// Read controller gains from parameter server
std::map<std::string,double> gains;
if (!nh.getParam("/controller/gains", gains))
ROS_ERROR("Failed to read parameter controller gains.");
// Read center of gravity and buoyancy vectors
std::vector<double> r_G_vec, r_B_vec;
if (!nh.getParam("/physical/center_of_mass", r_G_vec))
ROS_ERROR("Failed to read robot center of mass parameter.");
if (!nh.getParam("/physical/center_of_buoyancy", r_B_vec))
ROS_ERROR("Failed to read robot center of buoyancy parameter.");
Eigen::Vector3d r_G(r_G_vec.data());
Eigen::Vector3d r_B(r_B_vec.data());
// Read and calculate ROV weight and buoyancy
double mass, displacement, acceleration_of_gravity, density_of_water;
if (!nh.getParam("/physical/mass_kg", mass))
ROS_ERROR("Failed to read parameter mass.");
if (!nh.getParam("/physical/displacement_m3", displacement))
ROS_ERROR("Failed to read parameter displacement.");
if (!nh.getParam("/gravity/acceleration", acceleration_of_gravity))
ROS_ERROR("Failed to read parameter acceleration of gravity");
if (!nh.getParam("/water/density", density_of_water))
ROS_ERROR("Failed to read parameter density of water");
double W = mass * acceleration_of_gravity;
double B = density_of_water * displacement * acceleration_of_gravity;
position_hold_controller = new QuaternionPdController(gains["a"], gains["b"], gains["c"], W, B, r_G, r_B);
// Set up a dynamic reconfigure server
dynamic_reconfigure::Server<uranus_dp::ControllerConfig>::CallbackType cb;
cb = boost::bind(&Controller::configCallback, this, _1, _2);
dr_srv.setCallback(cb);
ROS_INFO("Controller: Initialized with dynamic reconfigure.");
}
void Controller::commandCallback(const vortex_msgs::JoystickMotionCommand& msg)
{
if (!healthyMessage(msg))
{
ROS_WARN("Controller: Propulsion command message out of range, ignoring...");
return;
}
if (msg.control_mode != control_mode)
{
control_mode = static_cast<ControlMode>(msg.control_mode);
switch (control_mode)
{
case ControlModes::OPEN_LOOP:
ROS_INFO("Controller: Changing mode to OPEN LOOP.");
break;
case ControlModes::POSITION_HOLD:
ROS_INFO("Controller: Changing mode to POSITION HOLD.");
position_setpoint = position_state;
orientation_setpoint = orientation_state;
prev_time_valid = false;
break;
}
}
updateSetpoints(msg);
}
void Controller::stateCallback(const nav_msgs::Odometry &msg)
{
tf::pointMsgToEigen(msg.pose.pose.position, position_state);
tf::quaternionMsgToEigen(msg.pose.pose.orientation, orientation_state);
}
void Controller::configCallback(uranus_dp::ControllerConfig &config, uint32_t level)
{
ROS_INFO_STREAM("Setting quat pd gains: a = " << config.a << ", b = " << config.b << ", c = " << config.c);
position_hold_controller->setGains(config.a, config.b, config.c);
}
void Controller::spin()
{
ros::Rate rate(frequency);
while (ros::ok())
{
Eigen::Vector6d tau;
switch (control_mode)
{
case ControlModes::POSITION_HOLD:
tau = position_hold_controller->compute(position_state,
orientation_state,
velocity_state,
position_setpoint,
orientation_setpoint);
break;
case ControlModes::OPEN_LOOP:
tau = wrench_setpoint;
break;
}
geometry_msgs::Wrench msg;
tf::wrenchEigenToMsg(tau, msg);
wrench_pub.publish(msg);
ros::spinOnce();
rate.sleep();
}
}
void Controller::updateSetpoints(const vortex_msgs::JoystickMotionCommand& msg)
{
// Update wrench setpoints
for (int i = 0; i < 6; ++i) // TODO: Fix magic number
wrench_setpoint(i) = wrench_command_scaling[i] * wrench_command_max[i] * msg.motion[i];
// Update pose setpoints
if (!prev_time_valid)
{
prev_time = msg.header.stamp;
prev_time_valid = true;
return;
}
// Calculate time difference
ros::Time curr_time = msg.header.stamp;
double dt = (curr_time - prev_time).toSec();
prev_time = curr_time;
if (dt == 0)
{
// ROS_WARN("Zero time difference between propulsion command messages.");
return;
}
// Increment position setpoints
for (int i = 0; i < 3; ++i) // TODO: Fix magic number
position_setpoint(i) += pose_command_rate[i] * dt * msg.motion[i];
// Calc euler setpoints
Eigen::Vector3d orientation_setpoint_euler;
orientation_setpoint_euler = orientation_setpoint.toRotationMatrix().eulerAngles(0,1,2);
// Increment euler setpoints
for (int i = 0; i < 3; ++i) // TODO: Fix magic number
orientation_setpoint_euler(i) += pose_command_rate[3+i] * dt * msg.motion[3+i];
// Calc incremented quat setpoints
Eigen::Matrix3d R;
R = Eigen::AngleAxisd(orientation_setpoint_euler(0), Eigen::Vector3d::UnitX())
* Eigen::AngleAxisd(orientation_setpoint_euler(1), Eigen::Vector3d::UnitY())
* Eigen::AngleAxisd(orientation_setpoint_euler(2), Eigen::Vector3d::UnitZ());
Eigen::Quaterniond q(R);
orientation_setpoint = q;
}
void Controller::getParams()
{
// Read control command parameters
if (!nh.getParam("/propulsion/command/wrench/max", wrench_command_max))
ROS_FATAL("Failed to read parameter max wrench command.");
if (!nh.getParam("/propulsion/command/wrench/scaling", wrench_command_scaling))
ROS_FATAL("Failed to read parameter scaling wrench command.");
if (!nh.getParam("/propulsion/command/pose/rate", pose_command_rate))
ROS_FATAL("Failed to read parameter pose command rate.");
if (!nh.getParam("/controller/frequency", frequency))
{
ROS_WARN("Failed to read parameter controller frequency, defaulting to 10 Hz.");
frequency = 10;
}
}
bool Controller::healthyMessage(const vortex_msgs::JoystickMotionCommand& msg)
{
if (abs(msg.forward) > 1)
{
ROS_WARN("controller: Forward motion command out of range");
return false;
}
if (abs(msg.right) > 1)
{
ROS_WARN("controller: Right motion command out of range");
return false;
}
if (abs(msg.down) > 1)
{
ROS_WARN("controller: Down motion command out of range.");
return false;
}
if (abs(msg.tilt_up) > 1)
{
ROS_WARN("controller: Tilt up motion command out of range");
return false;
}
if (abs(msg.turn_right) > 1)
{
ROS_WARN("controller: Turn right motion command out of range");
return false;
}
bool validControlMode = (msg.control_mode == ControlModes::OPEN_LOOP || msg.control_mode == ControlModes::POSITION_HOLD);
if (!validControlMode)
{
ROS_WARN("controller: Invalid control mode.");
return false;
}
return true;
}
<commit_msg>Add logic for control mode list<commit_after>#include "controller_ros.h"
#include "uranus_dp/eigen_helper.h"
#include <tf/transform_datatypes.h>
#include <eigen_conversions/eigen_msg.h>
Controller::Controller(ros::NodeHandle nh) : nh(nh)
{
command_sub = nh.subscribe("joystick_motion_command", 10, &Controller::commandCallback, this);
state_sub = nh.subscribe("state_estimate", 10, &Controller::stateCallback, this);
wrench_pub = nh.advertise<geometry_msgs::Wrench>("rov_forces", 10);
control_mode = ControlModes::OPEN_LOOP;
prev_time_valid = false;
position_state.setZero();
orientation_state.setIdentity();
velocity_state.setZero();
position_setpoint.setZero();
orientation_setpoint.setIdentity();
wrench_setpoint.setZero();
getParams();
// Read controller gains from parameter server
std::map<std::string,double> gains;
if (!nh.getParam("/controller/gains", gains))
ROS_ERROR("Failed to read parameter controller gains.");
// Read center of gravity and buoyancy vectors
std::vector<double> r_G_vec, r_B_vec;
if (!nh.getParam("/physical/center_of_mass", r_G_vec))
ROS_ERROR("Failed to read robot center of mass parameter.");
if (!nh.getParam("/physical/center_of_buoyancy", r_B_vec))
ROS_ERROR("Failed to read robot center of buoyancy parameter.");
Eigen::Vector3d r_G(r_G_vec.data());
Eigen::Vector3d r_B(r_B_vec.data());
// Read and calculate ROV weight and buoyancy
double mass, displacement, acceleration_of_gravity, density_of_water;
if (!nh.getParam("/physical/mass_kg", mass))
ROS_ERROR("Failed to read parameter mass.");
if (!nh.getParam("/physical/displacement_m3", displacement))
ROS_ERROR("Failed to read parameter displacement.");
if (!nh.getParam("/gravity/acceleration", acceleration_of_gravity))
ROS_ERROR("Failed to read parameter acceleration of gravity");
if (!nh.getParam("/water/density", density_of_water))
ROS_ERROR("Failed to read parameter density of water");
double W = mass * acceleration_of_gravity;
double B = density_of_water * displacement * acceleration_of_gravity;
position_hold_controller = new QuaternionPdController(gains["a"], gains["b"], gains["c"], W, B, r_G, r_B);
// Set up a dynamic reconfigure server
dynamic_reconfigure::Server<uranus_dp::ControllerConfig>::CallbackType cb;
cb = boost::bind(&Controller::configCallback, this, _1, _2);
dr_srv.setCallback(cb);
ROS_INFO("Controller: Initialized with dynamic reconfigure.");
}
void Controller::commandCallback(const vortex_msgs::JoystickMotionCommand& msg)
{
if (!healthyMessage(msg))
{
ROS_WARN("Controller: Propulsion command message out of range, ignoring...");
return;
}
ControlMode new_control_mode;
{
int i;
for (i = 0; i < msg.control_mode.size(); ++i)
if (msg.control_mode[i])
break;
new_control_mode = static_cast<ControlMode>(i);
}
if (new_control_mode != control_mode)
{
control_mode = new_control_mode;
switch (control_mode)
{
case ControlModes::OPEN_LOOP:
ROS_INFO("Controller: Changing mode to OPEN LOOP.");
break;
case ControlModes::POSITION_HOLD:
ROS_INFO("Controller: Changing mode to POSITION HOLD.");
position_setpoint = position_state;
orientation_setpoint = orientation_state;
prev_time_valid = false;
break;
}
}
updateSetpoints(msg);
}
void Controller::stateCallback(const nav_msgs::Odometry &msg)
{
tf::pointMsgToEigen(msg.pose.pose.position, position_state);
tf::quaternionMsgToEigen(msg.pose.pose.orientation, orientation_state);
}
void Controller::configCallback(uranus_dp::ControllerConfig &config, uint32_t level)
{
ROS_INFO_STREAM("Setting quat pd gains: a = " << config.a << ", b = " << config.b << ", c = " << config.c);
position_hold_controller->setGains(config.a, config.b, config.c);
}
void Controller::spin()
{
ros::Rate rate(frequency);
while (ros::ok())
{
Eigen::Vector6d tau;
switch (control_mode)
{
case ControlModes::POSITION_HOLD:
tau = position_hold_controller->compute(position_state,
orientation_state,
velocity_state,
position_setpoint,
orientation_setpoint);
break;
case ControlModes::OPEN_LOOP:
tau = wrench_setpoint;
break;
}
geometry_msgs::Wrench msg;
tf::wrenchEigenToMsg(tau, msg);
wrench_pub.publish(msg);
ros::spinOnce();
rate.sleep();
}
}
void Controller::updateSetpoints(const vortex_msgs::JoystickMotionCommand& msg)
{
// Update wrench setpoints
for (int i = 0; i < 6; ++i) // TODO: Fix magic number
wrench_setpoint(i) = wrench_command_scaling[i] * wrench_command_max[i] * msg.motion[i];
// Update pose setpoints
if (!prev_time_valid)
{
prev_time = msg.header.stamp;
prev_time_valid = true;
return;
}
// Calculate time difference
ros::Time curr_time = msg.header.stamp;
double dt = (curr_time - prev_time).toSec();
prev_time = curr_time;
if (dt == 0)
{
// ROS_WARN("Zero time difference between propulsion command messages.");
return;
}
// Increment position setpoints
for (int i = 0; i < 3; ++i) // TODO: Fix magic number
position_setpoint(i) += pose_command_rate[i] * dt * msg.motion[i];
// Calc euler setpoints
Eigen::Vector3d orientation_setpoint_euler;
orientation_setpoint_euler = orientation_setpoint.toRotationMatrix().eulerAngles(0,1,2);
// Increment euler setpoints
for (int i = 0; i < 3; ++i) // TODO: Fix magic number
orientation_setpoint_euler(i) += pose_command_rate[3+i] * dt * msg.motion[3+i];
// Calc incremented quat setpoints
Eigen::Matrix3d R;
R = Eigen::AngleAxisd(orientation_setpoint_euler(0), Eigen::Vector3d::UnitX())
* Eigen::AngleAxisd(orientation_setpoint_euler(1), Eigen::Vector3d::UnitY())
* Eigen::AngleAxisd(orientation_setpoint_euler(2), Eigen::Vector3d::UnitZ());
Eigen::Quaterniond q(R);
orientation_setpoint = q;
}
void Controller::getParams()
{
// Read control command parameters
if (!nh.getParam("/propulsion/command/wrench/max", wrench_command_max))
ROS_FATAL("Failed to read parameter max wrench command.");
if (!nh.getParam("/propulsion/command/wrench/scaling", wrench_command_scaling))
ROS_FATAL("Failed to read parameter scaling wrench command.");
if (!nh.getParam("/propulsion/command/pose/rate", pose_command_rate))
ROS_FATAL("Failed to read parameter pose command rate.");
if (!nh.getParam("/controller/frequency", frequency))
{
ROS_WARN("Failed to read parameter controller frequency, defaulting to 10 Hz.");
frequency = 10;
}
}
bool Controller::healthyMessage(const vortex_msgs::JoystickMotionCommand& msg)
{
// Check that motion commands are in range
for (int i = 0; i < msg.motion.size(); ++i)
{
if (msg.motion[i] > 1 || msg.motion[i] < -1)
{
ROS_WARN("Controller: Motion command out of range.");
return false;
}
}
// Check that exactly one control mode is requested
int num_requested_modes = 0;
for (int i = 0; i < msg.control_mode.size(); ++i)
if (msg.control_mode[i])
num_requested_modes++;
if (num_requested_modes != 1)
{
ROS_WARN("controller: Invalid control mode.");
return false;
}
return true;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
* UrBackup - Client/Server backup system
* Copyright (C) 2011-2016 Martin Raiber
*
* 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/>.
**************************************************************************/
#ifndef CLIENT_ONLY
#include "action_header.h"
#include "../server_status.h"
#include "../database.h"
const size_t max_display=20;
void cleanupLastActs()
{
IDatabase* db = Server->getDatabase(Server->getThreadID(), URBACKUPDB_SERVER);
db->Write("CREATE INDEX IF NOT EXISTS del_stats_del_idx ON del_stats (clientid, created)");
db->Write("DELETE FROM del_stats WHERE (SELECT COUNT(*) FROM del_stats b WHERE del_stats.clientid=b.clientid AND b.created<del_stats.created)>"+convert(max_display));
db->Write("DROP INDEX del_stats_del_idx");
}
void getLastActs(Helper &helper, JSON::Object &ret, std::vector<int> clientids)
{
std::string filter;
if(!clientids.empty())
{
filter=" AND ( ";
for(size_t i=0;i<clientids.size();++i)
{
filter+="clientid=?";
if(i+1<clientids.size())
filter+=" OR ";
}
filter+=" ) ";
}
IDatabase *db=helper.getDatabase();
IQuery *q=db->Prepare("SELECT * FROM ("
"SELECT a.id AS backupid, clientid, name, strftime('"+helper.getTimeFormatString()+"', a.backuptime) AS backuptime, backuptime AS bt,"
"incremental, (strftime('%s',running)-strftime('%s',a.backuptime)) AS duration, size_bytes, 0 AS image, 0 AS del, size_calculated, resumed, 0 AS restore, '' AS details "
"FROM backups a INNER JOIN clients b ON a.clientid=b.id "
"WHERE complete=1 "+filter+
"UNION ALL "
"SELECT c.id AS backupid, clientid, name, strftime('"+helper.getTimeFormatString()+"', c.backuptime) AS backuptime, backuptime AS bt,"
"incremental, (strftime('%s',running)-strftime('%s',c.backuptime)) AS duration, (size_bytes+IFNULL(0,("
"SELECT SUM(size_bytes) FROM backup_images INNER JOIN (SELECT * FROM assoc_images WHERE img_id=c.id) ON assoc_id=id"
")) ) AS size_bytes, 1 AS image, 0 AS del, 1 as size_calculated, 0 AS resumed, 0 AS restore, letter AS details "
"FROM backup_images c INNER JOIN clients d ON c.clientid=d.id "
"WHERE complete=1 AND length(letter)<=2 "+filter+
"UNION ALL "
"SELECT e.backupid AS backupid, clientid, name, strftime('"+helper.getTimeFormatString()+"', e.created) AS backuptime, created AS bt,"
"incremental, (strftime('%s',stoptime)-strftime('%s',e.created)) AS duration, delsize AS size_bytes, image, 1 AS del, 1 AS size_calculated, 0 AS resumed, 0 AS restore, '' AS details "
"FROM del_stats e INNER JOIN clients f ON e.clientid=f.id "
"WHERE 1=1 "+filter+
"UNION ALL "
"SELECT g.id AS backupid, clientid, name, strftime('"+helper.getTimeFormatString()+"', g.created) AS backuptime, g.created as bt,"
"0 AS incremental, (strftime('%s',g.finished)-strftime('%s',g.created)) AS duration, -1 AS size_bytes, image, 0 AS del, 0 AS size_calculated, 0 AS resumed, 1 AS restore,"
" (CASE WHEN image=1 THEN letter ELSE path END) AS details "
"FROM restores g INNER JOIN clients h ON g.clientid=h.id "
"WHERE done=1 "+filter+
") ORDER BY bt DESC LIMIT "+convert(max_display));
for(size_t i=0;i<clientids.size();++i)
{
q->Bind(clientids[i]);
}
for(size_t i=0;i<clientids.size();++i)
{
q->Bind(clientids[i]);
}
db_results res=q->Read();
q->Reset();
JSON::Array lastacts;
for(size_t i=0;i<res.size();++i)
{
JSON::Object obj;
obj.set("id", watoi(res[i]["backupid"]));
obj.set("clientid", watoi(res[i]["clientid"]));
obj.set("name", res[i]["name"]);
obj.set("backuptime", watoi64(res[i]["backuptime"]));
obj.set("incremental", watoi(res[i]["incremental"]));
obj.set("duration", watoi64(res[i]["duration"]));
obj.set("resumed", watoi(res[i]["resumed"]));
obj.set("restore", watoi(res[i]["restore"]));
if(watoi(res[i]["size_calculated"])==1)
{
obj.set("size_bytes", watoi64(res[i]["size_bytes"]));
}
else
{
obj.set("size_bytes", -1);
}
obj.set("image", watoi(res[i]["image"]));
obj.set("del", (res[i]["del"]=="1") );
obj.set("details", res[i]["details"]);
lastacts.add(obj);
}
ret.set("lastacts", lastacts);
}
ACTION_IMPL(lastacts)
{
Helper helper(tid, &POST, &PARAMS);
JSON::Object ret;
SUser *session=helper.getSession();
if(session!=NULL && session->id==SESSION_ID_INVALID) return;
std::vector<int> clientids;
std::string rights=helper.getRights("lastacts");
if(rights!="none" && rights!="all")
{
std::vector<std::string> s_cid;
Tokenize(rights, s_cid, ",");
for(size_t i=0;i<s_cid.size();++i)
{
clientids.push_back(atoi(s_cid[i].c_str()));
}
}
if(session!=NULL && (rights=="all" || clientids.empty()) )
{
getLastActs(helper, ret, clientids);
}
else
{
ret.set("error", 1);
}
helper.Write(ret.stringify(false));
}
#endif //CLIENT_ONLY
<commit_msg>Fix sql<commit_after>/*************************************************************************
* UrBackup - Client/Server backup system
* Copyright (C) 2011-2016 Martin Raiber
*
* 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/>.
**************************************************************************/
#ifndef CLIENT_ONLY
#include "action_header.h"
#include "../server_status.h"
#include "../database.h"
const size_t max_display=20;
void cleanupLastActs()
{
IDatabase* db = Server->getDatabase(Server->getThreadID(), URBACKUPDB_SERVER);
db->Write("CREATE INDEX IF NOT EXISTS del_stats_del_idx ON del_stats (clientid, created)");
db->Write("DELETE FROM del_stats WHERE (SELECT COUNT(*) FROM del_stats b WHERE del_stats.clientid=b.clientid AND b.created<del_stats.created)>"+convert(max_display));
db->Write("DROP INDEX del_stats_del_idx");
}
void getLastActs(Helper &helper, JSON::Object &ret, std::vector<int> clientids)
{
std::string filter;
if(!clientids.empty())
{
filter=" AND ( ";
for(size_t i=0;i<clientids.size();++i)
{
filter+="clientid=?";
if(i+1<clientids.size())
filter+=" OR ";
}
filter+=" ) ";
}
IDatabase *db=helper.getDatabase();
IQuery *q=db->Prepare("SELECT * FROM ("
"SELECT a.id AS backupid, clientid, name, strftime('"+helper.getTimeFormatString()+"', a.backuptime) AS backuptime, backuptime AS bt,"
"incremental, (strftime('%s',running)-strftime('%s',a.backuptime)) AS duration, size_bytes, 0 AS image, 0 AS del, size_calculated, resumed, 0 AS restore, '' AS details "
"FROM backups a INNER JOIN clients b ON a.clientid=b.id "
"WHERE complete=1 "+filter+
"UNION ALL "
"SELECT c.id AS backupid, clientid, name, strftime('"+helper.getTimeFormatString()+"', c.backuptime) AS backuptime, backuptime AS bt,"
"incremental, (strftime('%s',running)-strftime('%s',c.backuptime)) AS duration, (size_bytes+IFNULL(0,("
"SELECT SUM(size_bytes) FROM backup_images INNER JOIN (SELECT * FROM assoc_images WHERE img_id=c.id) ON assoc_id=id"
")) ) AS size_bytes, 1 AS image, 0 AS del, 1 as size_calculated, 0 AS resumed, 0 AS restore, letter AS details "
"FROM backup_images c INNER JOIN clients d ON c.clientid=d.id "
"WHERE complete=1 AND length(letter)<=2 "+filter+
"UNION ALL "
"SELECT e.backupid AS backupid, clientid, name, strftime('"+helper.getTimeFormatString()+"', e.created) AS backuptime, e.created AS bt,"
"incremental, (strftime('%s',stoptime)-strftime('%s',e.created)) AS duration, delsize AS size_bytes, image, 1 AS del, 1 AS size_calculated, 0 AS resumed, 0 AS restore, '' AS details "
"FROM del_stats e INNER JOIN clients f ON e.clientid=f.id "
"WHERE 1=1 "+filter+
"UNION ALL "
"SELECT g.id AS backupid, clientid, name, strftime('"+helper.getTimeFormatString()+"', g.created) AS backuptime, g.created as bt,"
"0 AS incremental, (strftime('%s',g.finished)-strftime('%s',g.created)) AS duration, -1 AS size_bytes, image, 0 AS del, 0 AS size_calculated, 0 AS resumed, 1 AS restore,"
" (CASE WHEN image=1 THEN letter ELSE path END) AS details "
"FROM restores g INNER JOIN clients h ON g.clientid=h.id "
"WHERE done=1 "+filter+
") ORDER BY bt DESC LIMIT "+convert(max_display));
for(size_t i=0;i<clientids.size();++i)
{
q->Bind(clientids[i]);
}
for(size_t i=0;i<clientids.size();++i)
{
q->Bind(clientids[i]);
}
db_results res=q->Read();
q->Reset();
JSON::Array lastacts;
for(size_t i=0;i<res.size();++i)
{
JSON::Object obj;
obj.set("id", watoi(res[i]["backupid"]));
obj.set("clientid", watoi(res[i]["clientid"]));
obj.set("name", res[i]["name"]);
obj.set("backuptime", watoi64(res[i]["backuptime"]));
obj.set("incremental", watoi(res[i]["incremental"]));
obj.set("duration", watoi64(res[i]["duration"]));
obj.set("resumed", watoi(res[i]["resumed"]));
obj.set("restore", watoi(res[i]["restore"]));
if(watoi(res[i]["size_calculated"])==1)
{
obj.set("size_bytes", watoi64(res[i]["size_bytes"]));
}
else
{
obj.set("size_bytes", -1);
}
obj.set("image", watoi(res[i]["image"]));
obj.set("del", (res[i]["del"]=="1") );
obj.set("details", res[i]["details"]);
lastacts.add(obj);
}
ret.set("lastacts", lastacts);
}
ACTION_IMPL(lastacts)
{
Helper helper(tid, &POST, &PARAMS);
JSON::Object ret;
SUser *session=helper.getSession();
if(session!=NULL && session->id==SESSION_ID_INVALID) return;
std::vector<int> clientids;
std::string rights=helper.getRights("lastacts");
if(rights!="none" && rights!="all")
{
std::vector<std::string> s_cid;
Tokenize(rights, s_cid, ",");
for(size_t i=0;i<s_cid.size();++i)
{
clientids.push_back(atoi(s_cid[i].c_str()));
}
}
if(session!=NULL && (rights=="all" || clientids.empty()) )
{
getLastActs(helper, ret, clientids);
}
else
{
ret.set("error", 1);
}
helper.Write(ret.stringify(false));
}
#endif //CLIENT_ONLY
<|endoftext|>
|
<commit_before>/*=========================================================================
*
* Copyright UMC Utrecht and contributors
*
* 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 "itkAdvancedBSplineDeformableTransform.h" // original elastix
#include "itkRecursiveBSplineTransform.h" // recursive version
// Report timings
#include "itkTimeProbe.h"
#include "itkTimeProbesCollectorBase.h"
#include <fstream>
#include <iomanip>
//-------------------------------------------------------------------------------------
int
main( int argc, char * argv[] )
{
/** Some basic type definitions.
* NOTE: don't change the dimension or the spline order, since the
* hard-coded ground truth depends on this.
*/
const unsigned int Dimension = 3;
const unsigned int SplineOrder = 3;
typedef double CoordinateRepresentationType;
/** The number of calls to Evaluate(). Distinguish between
* Debug and Release mode.
*/
#ifndef NDEBUG
unsigned int N = static_cast< unsigned int >( 1e3 );
#else
unsigned int N = static_cast< unsigned int >( 1e5 );
#endif
std::cerr << "N = " << N << std::endl;
/** Check. */
if( argc != 2 )
{
std::cerr << "ERROR: You should specify a text file with the B-spline "
<< "transformation parameters." << std::endl;
return 1;
}
/** Typedefs. */
typedef itk::AdvancedBSplineDeformableTransform<
CoordinateRepresentationType, Dimension, SplineOrder > TransformType;
typedef itk::RecursiveBSplineTransform<
CoordinateRepresentationType, Dimension, SplineOrder > RecursiveTransformType;
typedef TransformType::NumberOfParametersType NumberOfParametersType;
typedef TransformType::InputPointType InputPointType;
typedef TransformType::ParametersType ParametersType;
typedef TransformType::NonZeroJacobianIndicesType NonZeroJacobianIndicesType;
typedef TransformType::DerivativeType DerivativeType;
typedef TransformType::JacobianType JacobianType;
typedef TransformType::MovingImageGradientType MovingImageGradientType;
typedef itk::Image< CoordinateRepresentationType,
Dimension > InputImageType;
typedef InputImageType::RegionType RegionType;
typedef InputImageType::SizeType SizeType;
typedef InputImageType::IndexType IndexType;
typedef InputImageType::SpacingType SpacingType;
typedef InputImageType::PointType OriginType;
typedef InputImageType::DirectionType DirectionType;
/** Create the transform. */
TransformType::Pointer transform = TransformType::New();
RecursiveTransformType::Pointer recursiveTransform = RecursiveTransformType::New();
/** Setup the B-spline transform:
* (GridSize 44 43 35)
* (GridIndex 0 0 0)
* (GridSpacing 10.7832773148 11.2116431394 11.8648235177)
* (GridOrigin -237.6759555555 -239.9488431747 -344.2315805162)
*/
SizeType gridSize;
gridSize[ 0 ] = 44; gridSize[ 1 ] = 43; gridSize[ 2 ] = 35;
IndexType gridIndex;
gridIndex.Fill( 0 );
RegionType gridRegion;
gridRegion.SetSize( gridSize );
gridRegion.SetIndex( gridIndex );
SpacingType gridSpacing;
gridSpacing[ 0 ] = 10.7832773148;
gridSpacing[ 1 ] = 11.2116431394;
gridSpacing[ 2 ] = 11.8648235177;
OriginType gridOrigin;
gridOrigin[ 0 ] = -237.6759555555;
gridOrigin[ 1 ] = -239.9488431747;
gridOrigin[ 2 ] = -344.2315805162;
DirectionType gridDirection;
gridDirection.SetIdentity();
transform->SetGridOrigin( gridOrigin );
transform->SetGridSpacing( gridSpacing );
transform->SetGridRegion( gridRegion );
transform->SetGridDirection( gridDirection );
recursiveTransform->SetGridOrigin( gridOrigin );
recursiveTransform->SetGridSpacing( gridSpacing );
recursiveTransform->SetGridRegion( gridRegion );
recursiveTransform->SetGridDirection( gridDirection );
/** Now read the parameters as defined in the file par.txt. */
ParametersType parameters( transform->GetNumberOfParameters() );
std::ifstream input( argv[ 1 ] );
if( input.is_open() )
{
for( unsigned int i = 0; i < parameters.GetSize(); ++i )
{
input >> parameters[ i ];
}
}
else
{
std::cerr << "ERROR: could not open the text file containing the "
<< "parameter values." << std::endl;
return 1;
}
transform->SetParameters( parameters );
recursiveTransform->SetParameters( parameters );
/** Declare variables. */
InputPointType inputPoint; inputPoint.Fill( 4.1 );
MovingImageGradientType movingImageGradient;
movingImageGradient[ 0 ] = 29.43; movingImageGradient[ 0 ] = 18.21; movingImageGradient[ 0 ] = 1.7;
const NumberOfParametersType nnzji = transform->GetNumberOfNonZeroJacobianIndices();
JacobianType jacobian( Dimension, nnzji );
DerivativeType imageJacobian_old( nnzji );
DerivativeType imageJacobian_new( nnzji );
DerivativeType imageJacobian_recursive( nnzji );
NonZeroJacobianIndicesType nzji( nnzji );
itk::TimeProbesCollectorBase timeCollector;
double sum = 0.0;
/** Time the plain old way. */
timeCollector.Start( "JacobianGradient plain old" );
for( unsigned int i = 0; i < N; ++i )
{
/** Get the TransformJacobian dT/dmu. */
transform->GetJacobian( inputPoint, jacobian, nzji );
/** Compute the inner products (dM/dx)^T (dT/dmu). */
const unsigned int numberOfParametersPerDimension = nnzji / Dimension;
unsigned int counter = 0;
for( unsigned int dim = 0; dim < Dimension; ++dim )
{
const double imDeriv = movingImageGradient[ dim ];
for( unsigned int mu = 0; mu < numberOfParametersPerDimension; ++mu )
{
imageJacobian_old( counter ) = jacobian( dim, counter ) * imDeriv;
++counter;
}
}
sum += imageJacobian_old( 0 ); // just to avoid compiler to optimize away
}
timeCollector.Stop( "JacobianGradient plain old" );
/** Time the plain new way. */
timeCollector.Start( "JacobianGradient plain new" );
for( unsigned int i = 0; i < N; ++i )
{
/** Compute the inner product of the transform Jacobian dT/dmu and the moving image gradient dM/dx. */
transform->EvaluateJacobianWithImageGradientProduct(
inputPoint, movingImageGradient,
imageJacobian_new, nzji );
sum += imageJacobian_new( 0 ); // just to avoid compiler to optimize away
}
timeCollector.Stop( "JacobianGradient plain new" );
/** Time the recursive old way. */
timeCollector.Start( "JacobianGradient recursive old" );
for( unsigned int i = 0; i < N; ++i )
{
/** Compute the inner product of the transform Jacobian dT/dmu and the moving image gradient dM/dx. */
recursiveTransform->GetJacobian( inputPoint, jacobian, nzji );
/** Compute the inner products (dM/dx)^T (dT/dmu). */
const unsigned int numberOfParametersPerDimension = nnzji / Dimension;
unsigned int counter = 0;
for( unsigned int dim = 0; dim < Dimension; ++dim )
{
const double imDeriv = movingImageGradient[ dim ];
for( unsigned int mu = 0; mu < numberOfParametersPerDimension; ++mu )
{
imageJacobian_old( counter ) = jacobian( dim, counter ) * imDeriv;
++counter;
}
}
sum += imageJacobian_old( 0 ); // just to avoid compiler to optimize away
}
timeCollector.Stop( "JacobianGradient recursive old" );
/** Time the recursive new way. */
timeCollector.Start( "JacobianGradient recursive new" );
for( unsigned int i = 0; i < N; ++i )
{
/** Compute the inner product of the transform Jacobian dT/dmu and the moving image gradient dM/dx. */
recursiveTransform->EvaluateJacobianWithImageGradientProduct(
inputPoint, movingImageGradient,
imageJacobian_new, nzji );
sum += imageJacobian_new( 0 ); // just to avoid compiler to optimize away
}
timeCollector.Stop( "JacobianGradient recursive new" );
/** Report timings. */
timeCollector.Report();
// Avoid compiler optimizations, so use sum
std::cerr << sum << std::endl; // works but ugly on screen
/**
*
* Test accuracy
*
*/
transform->EvaluateJacobianWithImageGradientProduct(
inputPoint, movingImageGradient,
imageJacobian_old, nzji );
recursiveTransform->EvaluateJacobianWithImageGradientProduct(
inputPoint, movingImageGradient,
imageJacobian_new, nzji );
double diffNorm = ( imageJacobian_old - imageJacobian_new ).magnitude();
std::cerr << "Recursive B-spline MSD with previous: " << diffNorm << std::endl;
if( diffNorm > 1e-5 )
{
std::cerr << "ERROR: Recursive B-spline EvaluateJacobianWithImageGradientProduct() returning incorrect result." << std::endl;
return EXIT_FAILURE;
}
/** Return a value. */
return EXIT_SUCCESS;
} // end main
<commit_msg>BUG: Ensure all elements of movingImageGradient are initialized to avoid propagating uninitialized values. Makes valgrind happier.<commit_after>/*=========================================================================
*
* Copyright UMC Utrecht and contributors
*
* 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 "itkAdvancedBSplineDeformableTransform.h" // original elastix
#include "itkRecursiveBSplineTransform.h" // recursive version
// Report timings
#include "itkTimeProbe.h"
#include "itkTimeProbesCollectorBase.h"
#include <fstream>
#include <iomanip>
//-------------------------------------------------------------------------------------
int
main( int argc, char * argv[] )
{
/** Some basic type definitions.
* NOTE: don't change the dimension or the spline order, since the
* hard-coded ground truth depends on this.
*/
const unsigned int Dimension = 3;
const unsigned int SplineOrder = 3;
typedef double CoordinateRepresentationType;
/** The number of calls to Evaluate(). Distinguish between
* Debug and Release mode.
*/
#ifndef NDEBUG
unsigned int N = static_cast< unsigned int >( 1e3 );
#else
unsigned int N = static_cast< unsigned int >( 1e5 );
#endif
std::cerr << "N = " << N << std::endl;
/** Check. */
if( argc != 2 )
{
std::cerr << "ERROR: You should specify a text file with the B-spline "
<< "transformation parameters." << std::endl;
return 1;
}
/** Typedefs. */
typedef itk::AdvancedBSplineDeformableTransform<
CoordinateRepresentationType, Dimension, SplineOrder > TransformType;
typedef itk::RecursiveBSplineTransform<
CoordinateRepresentationType, Dimension, SplineOrder > RecursiveTransformType;
typedef TransformType::NumberOfParametersType NumberOfParametersType;
typedef TransformType::InputPointType InputPointType;
typedef TransformType::ParametersType ParametersType;
typedef TransformType::NonZeroJacobianIndicesType NonZeroJacobianIndicesType;
typedef TransformType::DerivativeType DerivativeType;
typedef TransformType::JacobianType JacobianType;
typedef TransformType::MovingImageGradientType MovingImageGradientType;
typedef itk::Image< CoordinateRepresentationType,
Dimension > InputImageType;
typedef InputImageType::RegionType RegionType;
typedef InputImageType::SizeType SizeType;
typedef InputImageType::IndexType IndexType;
typedef InputImageType::SpacingType SpacingType;
typedef InputImageType::PointType OriginType;
typedef InputImageType::DirectionType DirectionType;
/** Create the transform. */
TransformType::Pointer transform = TransformType::New();
RecursiveTransformType::Pointer recursiveTransform = RecursiveTransformType::New();
/** Setup the B-spline transform:
* (GridSize 44 43 35)
* (GridIndex 0 0 0)
* (GridSpacing 10.7832773148 11.2116431394 11.8648235177)
* (GridOrigin -237.6759555555 -239.9488431747 -344.2315805162)
*/
SizeType gridSize;
gridSize[ 0 ] = 44; gridSize[ 1 ] = 43; gridSize[ 2 ] = 35;
IndexType gridIndex;
gridIndex.Fill( 0 );
RegionType gridRegion;
gridRegion.SetSize( gridSize );
gridRegion.SetIndex( gridIndex );
SpacingType gridSpacing;
gridSpacing[ 0 ] = 10.7832773148;
gridSpacing[ 1 ] = 11.2116431394;
gridSpacing[ 2 ] = 11.8648235177;
OriginType gridOrigin;
gridOrigin[ 0 ] = -237.6759555555;
gridOrigin[ 1 ] = -239.9488431747;
gridOrigin[ 2 ] = -344.2315805162;
DirectionType gridDirection;
gridDirection.SetIdentity();
transform->SetGridOrigin( gridOrigin );
transform->SetGridSpacing( gridSpacing );
transform->SetGridRegion( gridRegion );
transform->SetGridDirection( gridDirection );
recursiveTransform->SetGridOrigin( gridOrigin );
recursiveTransform->SetGridSpacing( gridSpacing );
recursiveTransform->SetGridRegion( gridRegion );
recursiveTransform->SetGridDirection( gridDirection );
/** Now read the parameters as defined in the file par.txt. */
ParametersType parameters( transform->GetNumberOfParameters() );
std::ifstream input( argv[ 1 ] );
if( input.is_open() )
{
for( unsigned int i = 0; i < parameters.GetSize(); ++i )
{
input >> parameters[ i ];
}
}
else
{
std::cerr << "ERROR: could not open the text file containing the "
<< "parameter values." << std::endl;
return 1;
}
transform->SetParameters( parameters );
recursiveTransform->SetParameters( parameters );
/** Declare variables. */
InputPointType inputPoint; inputPoint.Fill( 4.1 );
MovingImageGradientType movingImageGradient;
movingImageGradient[ 0 ] = 29.43; movingImageGradient[ 1 ] = 18.21; movingImageGradient[ 2 ] = 1.7;
const NumberOfParametersType nnzji = transform->GetNumberOfNonZeroJacobianIndices();
JacobianType jacobian( Dimension, nnzji );
DerivativeType imageJacobian_old( nnzji );
DerivativeType imageJacobian_new( nnzji );
DerivativeType imageJacobian_recursive( nnzji );
NonZeroJacobianIndicesType nzji( nnzji );
itk::TimeProbesCollectorBase timeCollector;
double sum = 0.0;
/** Time the plain old way. */
timeCollector.Start( "JacobianGradient plain old" );
for( unsigned int i = 0; i < N; ++i )
{
/** Get the TransformJacobian dT/dmu. */
transform->GetJacobian( inputPoint, jacobian, nzji );
/** Compute the inner products (dM/dx)^T (dT/dmu). */
const unsigned int numberOfParametersPerDimension = nnzji / Dimension;
unsigned int counter = 0;
for( unsigned int dim = 0; dim < Dimension; ++dim )
{
const double imDeriv = movingImageGradient[ dim ];
for( unsigned int mu = 0; mu < numberOfParametersPerDimension; ++mu )
{
imageJacobian_old( counter ) = jacobian( dim, counter ) * imDeriv;
++counter;
}
}
sum += imageJacobian_old( 0 ); // just to avoid compiler to optimize away
}
timeCollector.Stop( "JacobianGradient plain old" );
/** Time the plain new way. */
timeCollector.Start( "JacobianGradient plain new" );
for( unsigned int i = 0; i < N; ++i )
{
/** Compute the inner product of the transform Jacobian dT/dmu and the moving image gradient dM/dx. */
transform->EvaluateJacobianWithImageGradientProduct(
inputPoint, movingImageGradient,
imageJacobian_new, nzji );
sum += imageJacobian_new( 0 ); // just to avoid compiler to optimize away
}
timeCollector.Stop( "JacobianGradient plain new" );
/** Time the recursive old way. */
timeCollector.Start( "JacobianGradient recursive old" );
for( unsigned int i = 0; i < N; ++i )
{
/** Compute the inner product of the transform Jacobian dT/dmu and the moving image gradient dM/dx. */
recursiveTransform->GetJacobian( inputPoint, jacobian, nzji );
/** Compute the inner products (dM/dx)^T (dT/dmu). */
const unsigned int numberOfParametersPerDimension = nnzji / Dimension;
unsigned int counter = 0;
for( unsigned int dim = 0; dim < Dimension; ++dim )
{
const double imDeriv = movingImageGradient[ dim ];
for( unsigned int mu = 0; mu < numberOfParametersPerDimension; ++mu )
{
imageJacobian_old( counter ) = jacobian( dim, counter ) * imDeriv;
++counter;
}
}
sum += imageJacobian_old( 0 ); // just to avoid compiler to optimize away
}
timeCollector.Stop( "JacobianGradient recursive old" );
/** Time the recursive new way. */
timeCollector.Start( "JacobianGradient recursive new" );
for( unsigned int i = 0; i < N; ++i )
{
/** Compute the inner product of the transform Jacobian dT/dmu and the moving image gradient dM/dx. */
recursiveTransform->EvaluateJacobianWithImageGradientProduct(
inputPoint, movingImageGradient,
imageJacobian_new, nzji );
sum += imageJacobian_new( 0 ); // just to avoid compiler to optimize away
}
timeCollector.Stop( "JacobianGradient recursive new" );
/** Report timings. */
timeCollector.Report();
// Avoid compiler optimizations, so use sum
std::cerr << sum << std::endl; // works but ugly on screen
/**
*
* Test accuracy
*
*/
transform->EvaluateJacobianWithImageGradientProduct(
inputPoint, movingImageGradient,
imageJacobian_old, nzji );
recursiveTransform->EvaluateJacobianWithImageGradientProduct(
inputPoint, movingImageGradient,
imageJacobian_new, nzji );
double diffNorm = ( imageJacobian_old - imageJacobian_new ).magnitude();
std::cerr << "Recursive B-spline MSD with previous: " << diffNorm << std::endl;
if( diffNorm > 1e-5 )
{
std::cerr << "ERROR: Recursive B-spline EvaluateJacobianWithImageGradientProduct() returning incorrect result." << std::endl;
return EXIT_FAILURE;
}
/** Return a value. */
return EXIT_SUCCESS;
} // end main
<|endoftext|>
|
<commit_before><commit_msg>Update token.cpp<commit_after><|endoftext|>
|
<commit_before>/******************************************************************************
* Main script for the 2017 RoboFishy Scripps AUV
******************************************************************************/
#include "Mapper.h"
// Multithreading
#include <pthread.h>
#include <sched.h>
#include <unistd.h>
// Sampling Values
#define SAMPLE_RATE 200 // sample rate of main control loop (Hz)
#define DT 0.005 // timestep; make sure this is equal to 1/SAMPLE_RATE!
// Conversion Factors
#define UNITS_KPA 0.1 // converts pressure from mbar to kPa
/******************************************************************************
* Controller Gains
******************************************************************************/
// Yaw Controller
#define KP_YAW 0.01
#define KI_YAW 0
#define KD_YAW 1
// Depth Controller
#define KP_DEPTH 0
#define KI_DEPTH 0
#define KD_DEPTH 0
// Saturation Constants
#define YAW_SAT 1 // upper limit of yaw controller
#define DEPTH_SAT 1 // upper limit of depth controller
#define INT_SAT 10 // upper limit of integral windup
#define DINT_SAT 10 // upper limit of depth integral windup
// Filter Values
#define A1 0.3 // for MS5837 pressure sensor
#define A2 0.4 // for MS5837 pressure sensor
// Fluid Densities in kg/m^3
#define DENSITY_FRESHWATER 997
#define DENSITY_SALTWATER 1029
// Acceleration Due to Gravity in m/s^2
#define GRAVITY 9.81
// Depth Start Value
#define DEPTH_START 50 // starting depth (mm)
// Stop Timer
#define STOP_TIME 4 // seconds
// Leak Sensor Inpu and Power Pin
#define LEAKPIN 27 // connected to GPIO 27
#define LEAKPOWERPIN 17 // providing Vcc to leak board
/******************************************************************************
* Declare Threads
******************************************************************************/
void *navigation(void* arg);
void *depth_thread(void* arg);
void *safety_thread(void* arg);
/******************************************************************************
* Global Variables
******************************************************************************/
// Holds the setpoint data structure with current setpoints
//setpoint_t setpoint;
// Holds the system state structure with current system statesystem_state_t sstate;
//system_state_t sstate;
// Holds the calibration values for the MS5837 pressure sensor
pressure_calib_t pressure_calib;
// Holds the latest pressure value from the MS5837 pressure sensor
ms5837_t ms5837;
// Create structure for storing IMU data
//bno055_t bno055;
// Holds the latest temperature value from the DS18B20 temperature sensor
ds18b20_t ds18b20;
// Holds the constants and latest errors of the yaw pid controller
pid_data_t yaw_pid;
// Holds the constants and latest errors of the depth pid controller
pid_data_t depth_pid;
// Motor channels
int motor_channels[] = {CHANNEL_1, CHANNEL_2, CHANNEL_3};
// Ignoring sstate
float depth = 0;
//yaw_controller intialization
float motor_percent = 0;
/******************************************************************************
* Main Function
******************************************************************************/
int main()
{
// Initialize Python interpreter
Py_Initialize();
// Set up RasPi GPIO pins through wiringPi
wiringPiSetupGpio();
// Check if AUV is initialized correctly
if( initialize_sensors() < 0 )
{
return -1;
}
printf("\nAll components are initialized\n");
substate.mode = INITIALIZING;
substate.laserarmed = ARMED;
printf("Starting Threads\n");
initializeTAttr();
// Thread handles
//pthread_t navigationThread;
//pthread_t depthThread;
pthread_t safetyThread;
//pthread_t disarmlaserThread;
// Create threads using modified attributes
/* pthread_create (&navigationThread, &tattrmed, navigation, NULL);
pthread_create (&depthThread, &tattrmed, depth_thread, NULL);
pthread_create (&disarmlaserThread, &tattrlow, disarmLaser, NULL);
*/ pthread_create (&safetyThread, &tattrlow, safety_thread, NULL);
// Destroy the thread attributes
destroyTAttr();
// Start timer!
time_t start = time(0);
// Run main while loop, wait until it's time to stop
while(substate.mode != STOPPED)
{
// Check if we've passed the stop time
if(difftime(time(0),start) > STOP_TIME)
substate.mode = STOPPED;
// Sleep a little
usleep(100000);
}
// Exit cleanly
cleanup_auv();
return 0;
}
/******************************************************************************
* Depth Thread
*
* For Recording Depth & Determining If AUV is in Water or Not
******************************************************************************/
void *depth_thread(void* arg)
{
// Initialize pressure sensor
pressure_calib = init_pressure_sensor();
while(substate.mode!=STOPPED)
{
// Read pressure sensor by passing calibration structure
ms5837 = ms5837_read(pressure_calib);
// Calculate depth (no idea what the magic numbers are)
depth = (ms5837.pressure-1013)*10.197-88.8; // units?
// 1013: ambient pressure (mbar)
// 10.197*p_mbar = p_mmH20
usleep(10000);
}
pthread_exit(NULL);
}//*/
/******************************************************************************
* Navigation Thread
*
* For yaw control
*****************************************************************************/
/*void *navigation(void* arg)
{
initialize_motors(motor_channels, HERTZ);
//float output_port; // port motor output
//float output_starboard; // starboard motor output
float yaw = 0; //Local variable for if statements
//////////////yaw controller initialization////////////////////////////////
yaw_pid.old = 0; // Initialize old imu data
yaw_pid.setpoint = 0; // Initialize setpoint for yaw_controller
yaw_pid.derr = 0;
yaw_pid.ierr = 0; // Initialize yaw_controller error values
yaw_pid.kerr = 0;
yaw_pid.kp = 0.01;
yaw_pid.kd = 1; // Initialize yaw_controller gain values
yaw_pid.ki = .1;
yaw_pid.isat = 1; // Initialize saturation values
yaw_pid.SAT = .2;
yaw_pid.DT = .005; // initialize time step
/////////////depth controller initialization///////////////////////////////
depth_pid.setpoint = 2; // Range-from-bottom setpoint (meters)
depth_pid.old = 0; // Initialize old depth
depth_pid.DT = .005; // Initialize depth controller time step
depth_pid.kp = 0.001;
depth_pid.kd = 1.0; // Depth controller gain initialization
depth_pid.ki = 0.01;
depth_pid.kerr = 0;
depth_pid.ierr = 0; // Initialize depth controller error values
depth_pid.derr = 0;
depth_pid.isat = 1; //Depth controller saturation values
depth_pid.SAT = .4
while(substate.mode!=STOPPED)
{
// read IMU values from fifo file
//bno055 = read_imu_fifo();
substate.imuorientation = read_imu_fifo();
if (substate.imuorientation.yaw < 180) //AUV pointed right
{
yaw = substate.imuorientation.yaw;
}
else //AUV pointed left
{
yaw =(substate.imuorientation.yaw-360);
}
// Write captured values to screen
//printf("\nYaw: %f Roll: %f Pitch: %f p: %f q: %f r: %f Sys: %i Gyro: %i Accel: %i Mag: %i\n ",
bno055.yaw, bno055.pitch, bno055.roll,
bno055.p, bno055.q, bno055.r,
bno055.sys, bno055.gyro, bno055.accel,
bno055.mag);*/
//calculate yaw controller output
/* motor_percent = marchPID(substate.imuorientation, yaw);
// Set port motor
//set_motor(0,motor_percent);
// Set starboard motor
//set_motor(1, motor_percent);
// Sleep for 5 ms //
if (substate.imuorientation.yaw < 180)
{
yaw_pid.err = abs(substate.imuorientation.yaw - yaw_pid.setpoint);
}
else
{
yaw_pid.err =abs((substate.imuorientation.yaw - 360) - yaw_pid.setpoint);
}
// Write captured values to screen
printf("\nYaw: %f Roll: %f Pitch: %f p: %f q: %f r: %f Sys: %i Gyro: %i Accel: %i Mag: %i\n ",
bno055.yaw, bno055.pitch, bno055.roll,
bno055.p, bno055.q, bno055.r,
bno055.sys, bno055.gyro, bno055.accel,
bno055.mag);
//printf("\nYawPID_err: %f Motor Percent: %f ", yaw_pid.err, motor_percent);
// Sanity test: Check if yaw control works
// Call yaw controller function
yaw_controller();
// Set port motor
set_motor(0,motor_percent);
// Set starboard motor
set_motor(1, motor_percent);
// Sleep for 5 ms
usleep(5000);
}
set_motor(0, 0);
set_motor(1, 0);
set_motor(2, 0);
pthread_exit(NULL);
}//*/
/******************************************************************************
* Safety Thread
*
* Shuts down AUV if vehicle goes belows 10m, temperature gets too high, or
* water intrusion is detected
*****************************************************************************/
void *safety_thread(void* arg)
{
// Set up WiringPi for use // (not sure if actually needed)
wiringPiSetup();
// Leak detection pins
pinMode(LEAKPIN, INPUT); // set LEAKPIN as an INPUT
pinMode(LEAKPOWERPIN, OUTPUT); // set as output to provide Vcc
digitalWrite(LEAKPOWERPIN, HIGH); // write high to provide Vcc
// Leak checking variables
int leakState; // holds the state (HIGH or LOW) of the LEAKPIN
// Test if temp sensor reads anything
ds18b20 = read_temp_fifo();
printf("Temperature: %f degC\n", ds18b20.temperature);
while( substate.mode != STOPPED )
{
// Check if depth threshold has been exceeded
/*if( substate.fdepth > DEPTH_STOP )
{
substate.mode = STOPPED;
printf("We're too deep! Shutting down...\n");
continue;
}
else
{
// We're still good
substate.mode = RUNNING;
}
// Check temperature
// Shut down AUV if housing temperature gets too high
if( ds18b20.temperature > TEMP_STOP )
{
substate.mode = STOPPED;
printf("It's too hot! Shutting down...\n");
continue;
}
else
{
// We're still good
substate.mode = RUNNING;
}//*/
// Check for leak
/*leakState = digitalRead(LEAKPIN); // check the state of LEAKPIN
if( leakState == HIGH )
{
substate.mode = STOPPED;
printf("LEAK DETECTED! Shutting down...\n");
continue;
}
else if (leakState == LOW)
{
// We're still good
substate.mode = RUNNING;
}*/
// Check IMU accelerometer for collision (1+ g detected)
if( (float)fabs(substate.imuorientation.x_acc) > 1.0*GRAVITY
|| (float)fabs(substate.imuorientation.y_acc) > 1.0*GRAVITY
|| (float)fabs(substate.imuorientation.z_acc) > 1.0*GRAVITY )
{
substate.mode = STOPPED;
printf("Collision detected. Shutting down...");
continue;
}
else
{
// We're still good
substate.mode = RUNNING;
}
}
pthread_exit(NULL);
}
/******************************************************************************
* Logging Thread
*
* Logs the sensor output data into a file
*****************************************************************************/
/*
PI_THREAD (logging_thread)
{
while(substate.mode!=STOPPED){
FILE *fd = fopen("log.txt", "a");
char buffer[100] = {0};
// add logging values to the next line
sprintf(buffer, "%f %f %f %f %i %i %i %i %f %f %f %f\n",sstate.roll, sstate.pitch[0], sstate.yaw[0], sstate.depth[0],sstate.x[0],
sstate.y[0], sstate.radius[0], setpoint.x - sstate.x[0], sstate.esc_out[0], sstate.esc_out[1], sstate.esc_out[2], sstate.esc_out[3]);
fputs(buffer, fd);
fclose(fd);
//sleep for 100 ms
usleep(100000);
}
return 0;
}
*/
<commit_msg>Changing global variables<commit_after>/******************************************************************************
* Main script for the 2017 RoboFishy Scripps AUV
******************************************************************************/
#include "Mapper.h"
// Multithreading
#include <pthread.h>
#include <sched.h>
#include <unistd.h>
// Sampling Values
#define SAMPLE_RATE 200 // sample rate of main control loop (Hz)
#define DT 0.005 // timestep; make sure this is equal to 1/SAMPLE_RATE!
// Conversion Factors
#define UNITS_KPA 0.1 // converts pressure from mbar to kPa
/******************************************************************************
* Controller Gains
******************************************************************************/
// Yaw Controller
#define KP_YAW 0.01
#define KI_YAW 0
#define KD_YAW 1
// Depth Controller
#define KP_DEPTH 0
#define KI_DEPTH 0
#define KD_DEPTH 0
// Saturation Constants
#define YAW_SAT 1 // upper limit of yaw controller
#define DEPTH_SAT 1 // upper limit of depth controller
#define INT_SAT 10 // upper limit of integral windup
#define DINT_SAT 10 // upper limit of depth integral windup
// Filter Values
#define A1 0.3 // for MS5837 pressure sensor
#define A2 0.4 // for MS5837 pressure sensor
// Fluid Densities in kg/m^3
#define DENSITY_FRESHWATER 997
#define DENSITY_SALTWATER 1029
// Acceleration Due to Gravity in m/s^2
#define GRAVITY 9.81
// Depth Start Value
#define DEPTH_START 50 // starting depth (mm)
// Stop Timer
#define STOP_TIME 4 // seconds
// Leak Sensor Inpu and Power Pin
#define LEAKPIN 27 // connected to GPIO 27
#define LEAKPOWERPIN 17 // providing Vcc to leak board
/******************************************************************************
* Declare Threads
******************************************************************************/
void *navigation(void* arg);
void *depth_thread(void* arg);
void *safety_thread(void* arg);
/******************************************************************************
* Global Variables
******************************************************************************/
// Holds the setpoint data structure with current setpoints
//setpoint_t setpoint;
// Holds the system state structure with current system statesystem_state_t sstate;
//system_state_t sstate;
// Holds the calibration values for the MS5837 pressure sensor
pressure_calib_t pressure_calib;
// Holds the latest pressure value from the MS5837 pressure sensor
ms5837_t ms5837;
// Create structure for storing IMU data
//bno055_t bno055;
// Holds the latest temperature value from the DS18B20 temperature sensor
ds18b20_t ds18b20;
// Holds the constants and latest errors of the yaw pid controller
pid_data_t yaw_pid;
// Holds the constants and latest errors of the depth pid controller
pid_data_t depth_pid;
// Motor channels
int motor_channels[] = {CHANNEL_1, CHANNEL_2, CHANNEL_3};
// Ignoring sstate
float depth = 0;
//yaw_controller intialization
float motor_percent = 0;
/******************************************************************************
* Main Function
******************************************************************************/
int main()
{
// Initialize Python interpreter
Py_Initialize();
// Set up RasPi GPIO pins through wiringPi
wiringPiSetupGpio();
// Check if AUV is initialized correctly
if( initialize_sensors() < 0 )
{
return -1;
}
printf("\nAll components are initialized\n");
substate.mode = INITIALIZING;
substate.laserarmed = ARMED;
printf("Starting Threads\n");
initializeTAttr();
// Thread handles
//pthread_t navigationThread;
//pthread_t depthThread;
pthread_t safetyThread;
//pthread_t disarmlaserThread;
// Create threads using modified attributes
/* pthread_create (&navigationThread, &tattrmed, navigation, NULL);
pthread_create (&depthThread, &tattrmed, depth_thread, NULL);
pthread_create (&disarmlaserThread, &tattrlow, disarmLaser, NULL);
*/ pthread_create (&safetyThread, &tattrlow, safety_thread, NULL);
// Destroy the thread attributes
destroyTAttr();
// Start timer!
time_t start = time(0);
// Run main while loop, wait until it's time to stop
while(substate.mode != STOPPED)
{
// Check if we've passed the stop time
if(difftime(time(0),start) > STOP_TIME)
substate.mode = STOPPED;
// Sleep a little
usleep(100000);
}
// Exit cleanly
cleanup_auv();
return 0;
}
/******************************************************************************
* Depth Thread
*
* For Recording Depth & Determining If AUV is in Water or Not
******************************************************************************/
void *depth_thread(void* arg)
{
// Initialize pressure sensor
pressure_calib = init_pressure_sensor();
while(substate.mode!=STOPPED)
{
// Read pressure sensor by passing calibration structure
ms5837 = ms5837_read(pressure_calib);
// Calculate depth (no idea what the magic numbers are)
depth = (ms5837.pressure-1013)*10.197-88.8; // units?
// 1013: ambient pressure (mbar)
// 10.197*p_mbar = p_mmH20
usleep(10000);
}
pthread_exit(NULL);
}//*/
/******************************************************************************
* Navigation Thread
*
* For yaw control
*****************************************************************************/
/*void *navigation(void* arg)
{
initialize_motors(motor_channels, HERTZ);
//float output_port; // port motor output
//float output_starboard; // starboard motor output
float yaw = 0; //Local variable for if statements
//////////////yaw controller initialization////////////////////////////////
yaw_pid.old = 0; // Initialize old imu data
yaw_pid.setpoint = 0; // Initialize setpoint for yaw_controller
yaw_pid.derr = 0;
yaw_pid.ierr = 0; // Initialize yaw_controller error values
yaw_pid.kerr = 0;
yaw_pid.kp = KP_YAW;
yaw_pid.kd = KD_YAW; // Initialize yaw_controller gain values
yaw_pid.ki = KI_YAW;
yaw_pid.isat = INT_SAT; // Initialize saturation values
yaw_pid.SAT = YAW_SAT;
yaw_pid.DT = DY; // initialize time step
/////////////depth controller initialization///////////////////////////////
depth_pid.setpoint = 2; // Range-from-bottom setpoint (meters)
depth_pid.old = 0; // Initialize old depth
depth_pid.DT = DT; // Initialize depth controller time step
depth_pid.kp = 0.001;
depth_pid.kd = 1.0; // Depth controller gain initialization
depth_pid.ki = 0.01;
depth_pid.kerr = 0;
depth_pid.ierr = 0; // Initialize depth controller error values
depth_pid.derr = 0;
depth_pid.isat = 1; //Depth controller saturation values
depth_pid.SAT = .4
while(substate.mode!=STOPPED)
{
// read IMU values from fifo file
//bno055 = read_imu_fifo();
substate.imuorientation = read_imu_fifo();
if (substate.imuorientation.yaw < 180) //AUV pointed right
{
yaw = substate.imuorientation.yaw;
}
else //AUV pointed left
{
yaw =(substate.imuorientation.yaw-360);
}
// Write captured values to screen
//printf("\nYaw: %f Roll: %f Pitch: %f p: %f q: %f r: %f Sys: %i Gyro: %i Accel: %i Mag: %i\n ",
bno055.yaw, bno055.pitch, bno055.roll,
bno055.p, bno055.q, bno055.r,
bno055.sys, bno055.gyro, bno055.accel,
bno055.mag);*/
//calculate yaw controller output
/* motor_percent = marchPID(substate.imuorientation, yaw);
// Set port motor
//set_motor(0,motor_percent);
// Set starboard motor
//set_motor(1, motor_percent);
// Sleep for 5 ms //
if (substate.imuorientation.yaw < 180)
{
yaw_pid.err = abs(substate.imuorientation.yaw - yaw_pid.setpoint);
}
else
{
yaw_pid.err =abs((substate.imuorientation.yaw - 360) - yaw_pid.setpoint);
}
// Write captured values to screen
printf("\nYaw: %f Roll: %f Pitch: %f p: %f q: %f r: %f Sys: %i Gyro: %i Accel: %i Mag: %i\n ",
bno055.yaw, bno055.pitch, bno055.roll,
bno055.p, bno055.q, bno055.r,
bno055.sys, bno055.gyro, bno055.accel,
bno055.mag);
//printf("\nYawPID_err: %f Motor Percent: %f ", yaw_pid.err, motor_percent);
// Sanity test: Check if yaw control works
// Call yaw controller function
yaw_controller();
// Set port motor
set_motor(0,motor_percent);
// Set starboard motor
set_motor(1, motor_percent);
// Sleep for 5 ms
usleep(5000);
}
set_motor(0, 0);
set_motor(1, 0);
set_motor(2, 0);
pthread_exit(NULL);
}//*/
/******************************************************************************
* Safety Thread
*
* Shuts down AUV if vehicle goes belows 10m, temperature gets too high, or
* water intrusion is detected
*****************************************************************************/
void *safety_thread(void* arg)
{
// Set up WiringPi for use // (not sure if actually needed)
wiringPiSetup();
// Leak detection pins
pinMode(LEAKPIN, INPUT); // set LEAKPIN as an INPUT
pinMode(LEAKPOWERPIN, OUTPUT); // set as output to provide Vcc
digitalWrite(LEAKPOWERPIN, HIGH); // write high to provide Vcc
// Leak checking variables
int leakState; // holds the state (HIGH or LOW) of the LEAKPIN
// Test if temp sensor reads anything
ds18b20 = read_temp_fifo();
printf("Temperature: %f degC\n", ds18b20.temperature);
while( substate.mode != STOPPED )
{
// Check if depth threshold has been exceeded
/*if( substate.fdepth > DEPTH_STOP )
{
substate.mode = STOPPED;
printf("We're too deep! Shutting down...\n");
continue;
}
else
{
// We're still good
substate.mode = RUNNING;
}
// Check temperature
// Shut down AUV if housing temperature gets too high
if( ds18b20.temperature > TEMP_STOP )
{
substate.mode = STOPPED;
printf("It's too hot! Shutting down...\n");
continue;
}
else
{
// We're still good
substate.mode = RUNNING;
}//*/
// Check for leak
/*leakState = digitalRead(LEAKPIN); // check the state of LEAKPIN
if( leakState == HIGH )
{
substate.mode = STOPPED;
printf("LEAK DETECTED! Shutting down...\n");
continue;
}
else if (leakState == LOW)
{
// We're still good
substate.mode = RUNNING;
}*/
// Check IMU accelerometer for collision (1+ g detected)
if( (float)fabs(substate.imuorientation.x_acc) > 1.0*GRAVITY
|| (float)fabs(substate.imuorientation.y_acc) > 1.0*GRAVITY
|| (float)fabs(substate.imuorientation.z_acc) > 1.0*GRAVITY )
{
substate.mode = STOPPED;
printf("Collision detected. Shutting down...");
continue;
}
else
{
// We're still good
substate.mode = RUNNING;
}
}
pthread_exit(NULL);
}
/******************************************************************************
* Logging Thread
*
* Logs the sensor output data into a file
*****************************************************************************/
/*
PI_THREAD (logging_thread)
{
while(substate.mode!=STOPPED){
FILE *fd = fopen("log.txt", "a");
char buffer[100] = {0};
// add logging values to the next line
sprintf(buffer, "%f %f %f %f %i %i %i %i %f %f %f %f\n",sstate.roll, sstate.pitch[0], sstate.yaw[0], sstate.depth[0],sstate.x[0],
sstate.y[0], sstate.radius[0], setpoint.x - sstate.x[0], sstate.esc_out[0], sstate.esc_out[1], sstate.esc_out[2], sstate.esc_out[3]);
fputs(buffer, fd);
fclose(fd);
//sleep for 100 ms
usleep(100000);
}
return 0;
}
*/
<|endoftext|>
|
<commit_before><?hh //strict
/**
* This file is part of hhpack\typesafety package.
*
* (c) Noritaka Horio <holy.shared.design@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace hhpack\typesafety\message;
use hhpack\publisher\Message;
use hhpack\typechecker\check\Result;
final class StoppedMessage implements Message
{
public function __construct(
private Result $result
)
{
}
}
<commit_msg>add methods<commit_after><?hh //strict
/**
* This file is part of hhpack\typesafety package.
*
* (c) Noritaka Horio <holy.shared.design@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace hhpack\typesafety\message;
use hhpack\publisher\Message;
use hhpack\typechecker\check\Result;
use hhpack\typechecker\check\Error;
use Generator;
final class StoppedMessage implements Message
{
public function __construct(
private Result $result
)
{
}
public function isPassed() : bool
{
return $this->result->isPassed();
}
public function isFailed() : bool
{
return $this->result->isPassed() === false;
}
public function errors() : Generator<int, Error, void>
{
foreach ($this->result->getErrors() as $error) {
yield $error;
}
}
}
<|endoftext|>
|
<commit_before>/*
*
* Copyright (c) 2020-2021 Project CHIP 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.
*/
/**
* @file
* This file implements the ExchangeManager class.
*
*/
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
#endif
#include <cstring>
#include <inttypes.h>
#include <stddef.h>
#include <crypto/RandUtils.h>
#include <lib/core/CHIPCore.h>
#include <lib/core/CHIPEncoding.h>
#include <lib/support/CHIPFaultInjection.h>
#include <lib/support/CodeUtils.h>
#include <lib/support/logging/CHIPLogging.h>
#include <messaging/ExchangeContext.h>
#include <messaging/ExchangeMgr.h>
#include <protocols/Protocols.h>
using namespace chip::Encoding;
using namespace chip::Inet;
using namespace chip::System;
namespace chip {
namespace Messaging {
/**
* Constructor for the ExchangeManager class.
* It sets the state to kState_NotInitialized.
*
* @note
* The class must be initialized via ExchangeManager::Init()
* prior to use.
*
*/
ExchangeManager::ExchangeManager() : mReliableMessageMgr(mContextPool)
{
mState = State::kState_NotInitialized;
}
CHIP_ERROR ExchangeManager::Init(SessionManager * sessionManager)
{
CHIP_ERROR err = CHIP_NO_ERROR;
VerifyOrReturnError(mState == State::kState_NotInitialized, err = CHIP_ERROR_INCORRECT_STATE);
mSessionManager = sessionManager;
mNextExchangeId = chip::Crypto::GetRandU16();
mNextKeyId = 0;
for (auto & handler : UMHandlerPool)
{
// Mark all handlers as unallocated. This handles both initial
// initialization and the case when the consumer shuts us down and
// then re-initializes without removing registered handlers.
handler.Reset();
}
sessionManager->RegisterReleaseDelegate(*this);
sessionManager->SetMessageDelegate(this);
mReliableMessageMgr.Init(sessionManager->SystemLayer());
ReturnErrorOnFailure(mDefaultExchangeDispatch.Init(mSessionManager));
mState = State::kState_Initialized;
return err;
}
CHIP_ERROR ExchangeManager::Shutdown()
{
mReliableMessageMgr.Shutdown();
mContextPool.ForEachActiveObject([](auto * ec) {
// There should be no active object in the pool
VerifyOrDie(false);
return Loop::Continue;
});
if (mSessionManager != nullptr)
{
mSessionManager->SetMessageDelegate(nullptr);
mSessionManager->UnregisterReleaseDelegate(*this);
mSessionManager = nullptr;
}
mState = State::kState_NotInitialized;
return CHIP_NO_ERROR;
}
ExchangeContext * ExchangeManager::NewContext(SessionHandle session, ExchangeDelegate * delegate)
{
return mContextPool.CreateObject(this, mNextExchangeId++, session, true, delegate);
}
CHIP_ERROR ExchangeManager::RegisterUnsolicitedMessageHandlerForProtocol(Protocols::Id protocolId, ExchangeDelegate * delegate)
{
return RegisterUMH(protocolId, kAnyMessageType, delegate);
}
CHIP_ERROR ExchangeManager::RegisterUnsolicitedMessageHandlerForType(Protocols::Id protocolId, uint8_t msgType,
ExchangeDelegate * delegate)
{
return RegisterUMH(protocolId, static_cast<int16_t>(msgType), delegate);
}
CHIP_ERROR ExchangeManager::UnregisterUnsolicitedMessageHandlerForProtocol(Protocols::Id protocolId)
{
return UnregisterUMH(protocolId, kAnyMessageType);
}
CHIP_ERROR ExchangeManager::UnregisterUnsolicitedMessageHandlerForType(Protocols::Id protocolId, uint8_t msgType)
{
return UnregisterUMH(protocolId, static_cast<int16_t>(msgType));
}
CHIP_ERROR ExchangeManager::RegisterUMH(Protocols::Id protocolId, int16_t msgType, ExchangeDelegate * delegate)
{
UnsolicitedMessageHandler * selected = nullptr;
for (auto & umh : UMHandlerPool)
{
if (!umh.IsInUse())
{
if (selected == nullptr)
selected = &umh;
}
else if (umh.Matches(protocolId, msgType))
{
umh.Delegate = delegate;
return CHIP_NO_ERROR;
}
}
if (selected == nullptr)
return CHIP_ERROR_TOO_MANY_UNSOLICITED_MESSAGE_HANDLERS;
selected->Delegate = delegate;
selected->ProtocolId = protocolId;
selected->MessageType = msgType;
SYSTEM_STATS_INCREMENT(chip::System::Stats::kExchangeMgr_NumUMHandlers);
return CHIP_NO_ERROR;
}
CHIP_ERROR ExchangeManager::UnregisterUMH(Protocols::Id protocolId, int16_t msgType)
{
for (auto & umh : UMHandlerPool)
{
if (umh.IsInUse() && umh.Matches(protocolId, msgType))
{
umh.Reset();
SYSTEM_STATS_DECREMENT(chip::System::Stats::kExchangeMgr_NumUMHandlers);
return CHIP_NO_ERROR;
}
}
return CHIP_ERROR_NO_UNSOLICITED_MESSAGE_HANDLER;
}
void ExchangeManager::OnMessageReceived(const PacketHeader & packetHeader, const PayloadHeader & payloadHeader,
SessionHandle session, const Transport::PeerAddress & source, DuplicateMessage isDuplicate,
System::PacketBufferHandle && msgBuf)
{
UnsolicitedMessageHandler * matchingUMH = nullptr;
ChipLogProgress(ExchangeManager,
"Received message of type " ChipLogFormatMessageType " with protocolId " ChipLogFormatProtocolId
" and MessageCounter:" ChipLogFormatMessageCounter " on exchange " ChipLogFormatExchangeId,
payloadHeader.GetMessageType(), ChipLogValueProtocolId(payloadHeader.GetProtocolID()),
packetHeader.GetMessageCounter(), ChipLogValueExchangeIdFromReceivedHeader(payloadHeader));
MessageFlags msgFlags;
if (isDuplicate == DuplicateMessage::Yes)
{
msgFlags.Set(MessageFlagValues::kDuplicateMessage);
}
// Skip retrieval of exchange for group message since no exchange is stored
// for group msg (optimization)
if (!packetHeader.IsGroupSession())
{
// Search for an existing exchange that the message applies to. If a match is found...
bool found = false;
mContextPool.ForEachActiveObject([&](auto * ec) {
if (ec->MatchExchange(session, packetHeader, payloadHeader))
{
// Found a matching exchange. Set flag for correct subsequent MRP
// retransmission timeout selection.
if (!ec->HasRcvdMsgFromPeer())
{
ec->SetMsgRcvdFromPeer(true);
}
ChipLogDetail(ExchangeManager, "Found matching exchange: " ChipLogFormatExchange ", Delegate: 0x%p",
ChipLogValueExchange(ec), ec->GetDelegate());
// Matched ExchangeContext; send to message handler.
ec->HandleMessage(packetHeader.GetMessageCounter(), payloadHeader, source, msgFlags, std::move(msgBuf));
found = true;
return Loop::Break;
}
return Loop::Continue;
});
if (found)
{
return;
}
}
// If it's not a duplicate message, search for an unsolicited message handler if it is marked as being sent by an initiator.
// Since we didn't find an existing exchange that matches the message, it must be an unsolicited message. However all
// unsolicited messages must be marked as being from an initiator.
if (!msgFlags.Has(MessageFlagValues::kDuplicateMessage) && payloadHeader.IsInitiator())
{
// Search for an unsolicited message handler that can handle the message. Prefer handlers that can explicitly
// handle the message type over handlers that handle all messages for a profile.
matchingUMH = nullptr;
for (auto & umh : UMHandlerPool)
{
if (umh.IsInUse() && payloadHeader.HasProtocol(umh.ProtocolId))
{
if (umh.MessageType == payloadHeader.GetMessageType())
{
matchingUMH = &umh;
break;
}
if (umh.MessageType == kAnyMessageType)
matchingUMH = &umh;
}
}
}
// Discard the message if it isn't marked as being sent by an initiator and the message does not need to send
// an ack to the peer.
else if (!payloadHeader.NeedsAck())
{
// Using same error message for all errors to reduce code size.
ChipLogError(ExchangeManager, "OnMessageReceived failed, err = %s", ErrorStr(CHIP_ERROR_UNSOLICITED_MSG_NO_ORIGINATOR));
return;
}
// If we found a handler or we need to send an ack, create an exchange to
// handle the message.
if (matchingUMH != nullptr || payloadHeader.NeedsAck())
{
ExchangeDelegate * delegate = matchingUMH ? matchingUMH->Delegate : nullptr;
// If rcvd msg is from initiator then this exchange is created as not Initiator.
// If rcvd msg is not from initiator then this exchange is created as Initiator.
// Note that if matchingUMH is not null then rcvd msg if from initiator.
// TODO: Figure out which channel to use for the received message
ExchangeContext * ec =
mContextPool.CreateObject(this, payloadHeader.GetExchangeID(), session, !payloadHeader.IsInitiator(), delegate);
if (ec == nullptr)
{
// Using same error message for all errors to reduce code size.
ChipLogError(ExchangeManager, "OnMessageReceived failed, err = %s", ErrorStr(CHIP_ERROR_NO_MEMORY));
return;
}
ChipLogDetail(ExchangeManager, "Handling via exchange: " ChipLogFormatExchange ", Delegate: 0x%p", ChipLogValueExchange(ec),
ec->GetDelegate());
if (ec->IsEncryptionRequired() != packetHeader.IsEncrypted())
{
ChipLogError(ExchangeManager, "OnMessageReceived failed, err = %s", ErrorStr(CHIP_ERROR_INVALID_MESSAGE_TYPE));
ec->Close();
return;
}
CHIP_ERROR err = ec->HandleMessage(packetHeader.GetMessageCounter(), payloadHeader, source, msgFlags, std::move(msgBuf));
if (err != CHIP_NO_ERROR)
{
// Using same error message for all errors to reduce code size.
ChipLogError(ExchangeManager, "OnMessageReceived failed, err = %s", ErrorStr(err));
}
}
}
void ExchangeManager::OnSessionReleased(SessionHandle session)
{
ExpireExchangesForSession(session);
}
void ExchangeManager::ExpireExchangesForSession(SessionHandle session)
{
mContextPool.ForEachActiveObject([&](auto * ec) {
if (ec->mSession.HasValue() && ec->mSession.Value() == session)
{
ec->OnConnectionExpired();
// Continue to iterate because there can be multiple exchanges
// associated with the connection.
}
return Loop::Continue;
});
}
void ExchangeManager::CloseAllContextsForDelegate(const ExchangeDelegate * delegate)
{
mContextPool.ForEachActiveObject([&](auto * ec) {
if (ec->GetDelegate() == delegate)
{
// Make sure to null out the delegate before closing the context, so
// we don't notify the delegate that the context is closing. We
// have to do this, because the delegate might be partially
// destroyed by this point.
ec->SetDelegate(nullptr);
ec->Close();
}
return Loop::Continue;
});
}
} // namespace Messaging
} // namespace chip
<commit_msg>Remove redundant 0x from before %p in log formats. (#12519)<commit_after>/*
*
* Copyright (c) 2020-2021 Project CHIP 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.
*/
/**
* @file
* This file implements the ExchangeManager class.
*
*/
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
#endif
#include <cstring>
#include <inttypes.h>
#include <stddef.h>
#include <crypto/RandUtils.h>
#include <lib/core/CHIPCore.h>
#include <lib/core/CHIPEncoding.h>
#include <lib/support/CHIPFaultInjection.h>
#include <lib/support/CodeUtils.h>
#include <lib/support/logging/CHIPLogging.h>
#include <messaging/ExchangeContext.h>
#include <messaging/ExchangeMgr.h>
#include <protocols/Protocols.h>
using namespace chip::Encoding;
using namespace chip::Inet;
using namespace chip::System;
namespace chip {
namespace Messaging {
/**
* Constructor for the ExchangeManager class.
* It sets the state to kState_NotInitialized.
*
* @note
* The class must be initialized via ExchangeManager::Init()
* prior to use.
*
*/
ExchangeManager::ExchangeManager() : mReliableMessageMgr(mContextPool)
{
mState = State::kState_NotInitialized;
}
CHIP_ERROR ExchangeManager::Init(SessionManager * sessionManager)
{
CHIP_ERROR err = CHIP_NO_ERROR;
VerifyOrReturnError(mState == State::kState_NotInitialized, err = CHIP_ERROR_INCORRECT_STATE);
mSessionManager = sessionManager;
mNextExchangeId = chip::Crypto::GetRandU16();
mNextKeyId = 0;
for (auto & handler : UMHandlerPool)
{
// Mark all handlers as unallocated. This handles both initial
// initialization and the case when the consumer shuts us down and
// then re-initializes without removing registered handlers.
handler.Reset();
}
sessionManager->RegisterReleaseDelegate(*this);
sessionManager->SetMessageDelegate(this);
mReliableMessageMgr.Init(sessionManager->SystemLayer());
ReturnErrorOnFailure(mDefaultExchangeDispatch.Init(mSessionManager));
mState = State::kState_Initialized;
return err;
}
CHIP_ERROR ExchangeManager::Shutdown()
{
mReliableMessageMgr.Shutdown();
mContextPool.ForEachActiveObject([](auto * ec) {
// There should be no active object in the pool
VerifyOrDie(false);
return Loop::Continue;
});
if (mSessionManager != nullptr)
{
mSessionManager->SetMessageDelegate(nullptr);
mSessionManager->UnregisterReleaseDelegate(*this);
mSessionManager = nullptr;
}
mState = State::kState_NotInitialized;
return CHIP_NO_ERROR;
}
ExchangeContext * ExchangeManager::NewContext(SessionHandle session, ExchangeDelegate * delegate)
{
return mContextPool.CreateObject(this, mNextExchangeId++, session, true, delegate);
}
CHIP_ERROR ExchangeManager::RegisterUnsolicitedMessageHandlerForProtocol(Protocols::Id protocolId, ExchangeDelegate * delegate)
{
return RegisterUMH(protocolId, kAnyMessageType, delegate);
}
CHIP_ERROR ExchangeManager::RegisterUnsolicitedMessageHandlerForType(Protocols::Id protocolId, uint8_t msgType,
ExchangeDelegate * delegate)
{
return RegisterUMH(protocolId, static_cast<int16_t>(msgType), delegate);
}
CHIP_ERROR ExchangeManager::UnregisterUnsolicitedMessageHandlerForProtocol(Protocols::Id protocolId)
{
return UnregisterUMH(protocolId, kAnyMessageType);
}
CHIP_ERROR ExchangeManager::UnregisterUnsolicitedMessageHandlerForType(Protocols::Id protocolId, uint8_t msgType)
{
return UnregisterUMH(protocolId, static_cast<int16_t>(msgType));
}
CHIP_ERROR ExchangeManager::RegisterUMH(Protocols::Id protocolId, int16_t msgType, ExchangeDelegate * delegate)
{
UnsolicitedMessageHandler * selected = nullptr;
for (auto & umh : UMHandlerPool)
{
if (!umh.IsInUse())
{
if (selected == nullptr)
selected = &umh;
}
else if (umh.Matches(protocolId, msgType))
{
umh.Delegate = delegate;
return CHIP_NO_ERROR;
}
}
if (selected == nullptr)
return CHIP_ERROR_TOO_MANY_UNSOLICITED_MESSAGE_HANDLERS;
selected->Delegate = delegate;
selected->ProtocolId = protocolId;
selected->MessageType = msgType;
SYSTEM_STATS_INCREMENT(chip::System::Stats::kExchangeMgr_NumUMHandlers);
return CHIP_NO_ERROR;
}
CHIP_ERROR ExchangeManager::UnregisterUMH(Protocols::Id protocolId, int16_t msgType)
{
for (auto & umh : UMHandlerPool)
{
if (umh.IsInUse() && umh.Matches(protocolId, msgType))
{
umh.Reset();
SYSTEM_STATS_DECREMENT(chip::System::Stats::kExchangeMgr_NumUMHandlers);
return CHIP_NO_ERROR;
}
}
return CHIP_ERROR_NO_UNSOLICITED_MESSAGE_HANDLER;
}
void ExchangeManager::OnMessageReceived(const PacketHeader & packetHeader, const PayloadHeader & payloadHeader,
SessionHandle session, const Transport::PeerAddress & source, DuplicateMessage isDuplicate,
System::PacketBufferHandle && msgBuf)
{
UnsolicitedMessageHandler * matchingUMH = nullptr;
ChipLogProgress(ExchangeManager,
"Received message of type " ChipLogFormatMessageType " with protocolId " ChipLogFormatProtocolId
" and MessageCounter:" ChipLogFormatMessageCounter " on exchange " ChipLogFormatExchangeId,
payloadHeader.GetMessageType(), ChipLogValueProtocolId(payloadHeader.GetProtocolID()),
packetHeader.GetMessageCounter(), ChipLogValueExchangeIdFromReceivedHeader(payloadHeader));
MessageFlags msgFlags;
if (isDuplicate == DuplicateMessage::Yes)
{
msgFlags.Set(MessageFlagValues::kDuplicateMessage);
}
// Skip retrieval of exchange for group message since no exchange is stored
// for group msg (optimization)
if (!packetHeader.IsGroupSession())
{
// Search for an existing exchange that the message applies to. If a match is found...
bool found = false;
mContextPool.ForEachActiveObject([&](auto * ec) {
if (ec->MatchExchange(session, packetHeader, payloadHeader))
{
// Found a matching exchange. Set flag for correct subsequent MRP
// retransmission timeout selection.
if (!ec->HasRcvdMsgFromPeer())
{
ec->SetMsgRcvdFromPeer(true);
}
ChipLogDetail(ExchangeManager, "Found matching exchange: " ChipLogFormatExchange ", Delegate: %p",
ChipLogValueExchange(ec), ec->GetDelegate());
// Matched ExchangeContext; send to message handler.
ec->HandleMessage(packetHeader.GetMessageCounter(), payloadHeader, source, msgFlags, std::move(msgBuf));
found = true;
return Loop::Break;
}
return Loop::Continue;
});
if (found)
{
return;
}
}
// If it's not a duplicate message, search for an unsolicited message handler if it is marked as being sent by an initiator.
// Since we didn't find an existing exchange that matches the message, it must be an unsolicited message. However all
// unsolicited messages must be marked as being from an initiator.
if (!msgFlags.Has(MessageFlagValues::kDuplicateMessage) && payloadHeader.IsInitiator())
{
// Search for an unsolicited message handler that can handle the message. Prefer handlers that can explicitly
// handle the message type over handlers that handle all messages for a profile.
matchingUMH = nullptr;
for (auto & umh : UMHandlerPool)
{
if (umh.IsInUse() && payloadHeader.HasProtocol(umh.ProtocolId))
{
if (umh.MessageType == payloadHeader.GetMessageType())
{
matchingUMH = &umh;
break;
}
if (umh.MessageType == kAnyMessageType)
matchingUMH = &umh;
}
}
}
// Discard the message if it isn't marked as being sent by an initiator and the message does not need to send
// an ack to the peer.
else if (!payloadHeader.NeedsAck())
{
// Using same error message for all errors to reduce code size.
ChipLogError(ExchangeManager, "OnMessageReceived failed, err = %s", ErrorStr(CHIP_ERROR_UNSOLICITED_MSG_NO_ORIGINATOR));
return;
}
// If we found a handler or we need to send an ack, create an exchange to
// handle the message.
if (matchingUMH != nullptr || payloadHeader.NeedsAck())
{
ExchangeDelegate * delegate = matchingUMH ? matchingUMH->Delegate : nullptr;
// If rcvd msg is from initiator then this exchange is created as not Initiator.
// If rcvd msg is not from initiator then this exchange is created as Initiator.
// Note that if matchingUMH is not null then rcvd msg if from initiator.
// TODO: Figure out which channel to use for the received message
ExchangeContext * ec =
mContextPool.CreateObject(this, payloadHeader.GetExchangeID(), session, !payloadHeader.IsInitiator(), delegate);
if (ec == nullptr)
{
// Using same error message for all errors to reduce code size.
ChipLogError(ExchangeManager, "OnMessageReceived failed, err = %s", ErrorStr(CHIP_ERROR_NO_MEMORY));
return;
}
ChipLogDetail(ExchangeManager, "Handling via exchange: " ChipLogFormatExchange ", Delegate: %p", ChipLogValueExchange(ec),
ec->GetDelegate());
if (ec->IsEncryptionRequired() != packetHeader.IsEncrypted())
{
ChipLogError(ExchangeManager, "OnMessageReceived failed, err = %s", ErrorStr(CHIP_ERROR_INVALID_MESSAGE_TYPE));
ec->Close();
return;
}
CHIP_ERROR err = ec->HandleMessage(packetHeader.GetMessageCounter(), payloadHeader, source, msgFlags, std::move(msgBuf));
if (err != CHIP_NO_ERROR)
{
// Using same error message for all errors to reduce code size.
ChipLogError(ExchangeManager, "OnMessageReceived failed, err = %s", ErrorStr(err));
}
}
}
void ExchangeManager::OnSessionReleased(SessionHandle session)
{
ExpireExchangesForSession(session);
}
void ExchangeManager::ExpireExchangesForSession(SessionHandle session)
{
mContextPool.ForEachActiveObject([&](auto * ec) {
if (ec->mSession.HasValue() && ec->mSession.Value() == session)
{
ec->OnConnectionExpired();
// Continue to iterate because there can be multiple exchanges
// associated with the connection.
}
return Loop::Continue;
});
}
void ExchangeManager::CloseAllContextsForDelegate(const ExchangeDelegate * delegate)
{
mContextPool.ForEachActiveObject([&](auto * ec) {
if (ec->GetDelegate() == delegate)
{
// Make sure to null out the delegate before closing the context, so
// we don't notify the delegate that the context is closing. We
// have to do this, because the delegate might be partially
// destroyed by this point.
ec->SetDelegate(nullptr);
ec->Close();
}
return Loop::Continue;
});
}
} // namespace Messaging
} // namespace chip
<|endoftext|>
|
<commit_before>/*
Copyright 2010, HudsonAlpha Institute for Biotechnology
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.
bam2fastq.cpp
Written by Phillip Dexheimer
*/
#include "sam.h"
#include <getopt.h>
#include <map>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <cctype>
using namespace std;
const char version[] = "1.1.0";
const char shortopts[] = "o:vhfqs";
int save_aligned = 1;
int save_unaligned = 1;
int save_filtered = 1;
int overwrite_files = 0;
int print_msgs = 1;
int strict = 0;
static struct option longopts[] = {
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, 'v' },
{ "output", required_argument, NULL, 'o' },
{ "force", no_argument, NULL, 'f' },
{ "quiet", no_argument, NULL, 'q' },
{ "strict", no_argument, NULL, 's' },
{ "overwrite", no_argument, &overwrite_files,0 },
{ "aligned", no_argument, &save_aligned, 1 },
{ "no-aligned", no_argument, &save_aligned, 0 },
{ "unaligned", no_argument, &save_unaligned, 1 },
{ "no-unaligned", no_argument, &save_unaligned, 0 },
{ "filtered", no_argument, &save_filtered, 1 },
{ "no-filtered", no_argument, &save_filtered, 0 },
{ NULL, 0, NULL, 0 }
};
void usage(int error=1) {
cerr << "bam2fastq v" << version << " - extract sequences from a BAM file" << endl
<< endl
<< "Usage: bam2fastq [options] <bam file>" << endl
<< endl
<< "Options:" << endl
<< " -o FILENAME, --output FILENAME" << endl
<< " Specifies the name of the FASTQ file(s) that will be generated. May" << endl
<< " contain the special characters % (replaced with the lane number) and" << endl
<< " # (replaced with _1 or _2 to distinguish PE reads, removed for SE reads)." << endl
<< " [Default: s_%#_sequence.txt]" << endl
<< " -f, --force, --overwrite" << endl
<< " Create output files specified with --output, overwriting existing" << endl
<< " files if necessary [Default: exit program rather than overwrite files]" << endl
<< " --aligned" << endl
<< " --no-aligned" << endl
<< " Reads in the BAM that are aligned will (will not) be extracted." << endl
<< " [Default: extract aligned reads]" << endl
<< " --unaligned" << endl
<< " --no-unaligned" << endl
<< " Reads in the BAM that are not aligned will (will not) be extracted." << endl
<< " [Default: extract unaligned reads]" << endl
<< " --filtered" << endl
<< " --no-filtered" << endl
<< " Reads that are marked as failing QC checks will (will not) be extracted." << endl
<< " [Default: extract filtered reads]" << endl
<< " -q, --quiet" << endl
<< " Suppress informational messages [Default: print messages]" << endl
<< " -s, --strict" << endl
<< " Keep bam2fastq's processing to a minimum, assuming that the BAM strictly"
<< " meets specifications. [Default: allow some errors in the BAM]" << endl
<< endl;
exit(error);
}
map<int, char> bases;
const string get_pair_name(const bam1_t *b) {
return string(bam1_qname(b));
}
//Returns 0 for read 1 and 1 for read 2.
//Counterintuitive, but good for lookups
const int get_read_idx(const bam1_t *b) {
return !(b->core.flag & BAM_FREAD1);
}
const string get_read_name(const bam1_t *b) {
static const char suffix[2][3] = { "/1", "/2" };
string name = get_pair_name(b);
if (b->core.flag & BAM_FPAIRED)
name += suffix[get_read_idx(b)];
return name;
}
int get_lane_id(const bam1_t *b) {
string name(get_pair_name(b));
size_t start = name.find(":");
if (start == string::npos)
return 0;
start++;
size_t stop = name.find(":", start);
if (stop == string::npos || stop == start)
return 0;
istringstream ist(string(name.begin()+start, name.begin()+stop));
int lane;
ist >> lane;
return lane;
}
const string get_sequence(const bam1_t *b) {
const uint8_t *seq = bam1_seq(b);
size_t len = b->core.l_qseq;
string sequence("");
sequence.reserve(len);
uint8_t offset = (b->core.flag & BAM_FREVERSE) ? 16 : 0;
for (size_t i=0; i<len; i++) {
sequence += bases[bam1_seqi(seq, i) + offset];
}
if (offset)
sequence = string(sequence.rbegin(), sequence.rend());
return sequence;
}
const string get_qualities(const bam1_t *b) {
const uint8_t *qual = bam1_qual(b);
size_t len = b->core.l_qseq;
string quality("");
quality.reserve(len);
for (size_t i=0; i<len; i++) {
quality += char_traits<char>::to_char_type(char_traits<char>::to_int_type(qual[i])+33);
}
if (b->core.flag & BAM_FREVERSE)
quality = string(quality.rbegin(), quality.rend());
return quality;
}
void mangle(string &name) {
if (name.length() < 3)
return;
if (isdigit(name[name.length()-1]) && !isdigit(name[name.length()-2]))
name.erase(name.length()-2);
}
vector<ofstream *> initialize_output(const string &out_template, int lane, bool isPaired) {
vector<ofstream *> files;
string output(out_template);
//First, replace % in the filename with the lane number
size_t laneMarker = output.find('%');
if (laneMarker != string::npos) {
if (lane == 0) {
cerr << "The lane could not be determined from the reads. Specify output files" << endl
<< "(using --output) that do not include the lane number (%)" << endl;
return files;
}
ostringstream laneStr;
laneStr << lane;
output.replace(laneMarker, 1, laneStr.str());
}
//Replace # with read number and open ofstreams
size_t readMarker = output.find('#');
if (isPaired) {
//Replace
if (readMarker == string::npos) {
cerr << "The sequences in the BAM file are marked as Paired, but a single output" << endl
<< "file is specified. Ensure that the output filename (--output) includes" << endl
<< "a # symbol to be replaced with the read number" << endl;
return files;
}
string file1(output);
file1.replace(readMarker, 1, "_1");
string file2(output);
file2.replace(readMarker, 1, "_2");
if (print_msgs)
cerr << "This looks like paired data from lane " << lane << "." << endl
<< "Output will be in " << file1 << " and " << file2 << endl;
//If we're not going to overwrite, check to see if the files exist
if (!overwrite_files) {
ifstream test;
test.open(file1.c_str());
if (test.is_open()) {
cerr << "ERROR: " << file1 << " already exists. Specify --force to overwrite" << endl;
return files;
}
//test is not open, so don't try closing it
test.open(file2.c_str());
if (test.is_open()) {
cerr << "ERROR: " << file2 << " already exists. Specify --force to overwrite" << endl;
return files;
}
}
files.push_back(new ofstream(file1.c_str(), ios_base::out));
files.push_back(new ofstream(file2.c_str(), ios_base::out));
} else {
if (readMarker != string::npos)
output.replace(readMarker, 1, "");
if (print_msgs)
cerr << "This looks like single-end data from lane " << lane << "." << endl
<< "Output will be in " << output << endl;
if (!overwrite_files) {
ifstream test;
test.open(output.c_str());
if (test.is_open()) {
cerr << "ERROR: " << output << " already exists. Specify --force to overwrite" << endl;
return files;
}
}
files.push_back(new ofstream(output.c_str(), ios_base::out));
}
return files;
}
//Effective STL, Item 7
//Except, of course, that I'm not using smart pointers
struct DeleteObject {
template<typename T>
void operator()(const T *ptr) const {
delete ptr;
}
};
void parse_bamfile(const char *bam_filename, const string &output_template) {
samfile_t *sam = samopen(bam_filename, "rb", NULL);
if (sam == NULL) {
cerr << "Could not open " << bam_filename << endl;
return;
}
bam1_t *read = bam_init1();
size_t exported = 0;
size_t all_seen = 0;
bam_read1(sam->x.bam, read);
bool isPaired = (read->core.flag & BAM_FPAIRED);
int lane = get_lane_id(read);
vector<ofstream *> output = initialize_output(output_template, lane, isPaired);
if (output.empty())
return;
map<string, string> unPaired;
map<string, string>::iterator position;
do {
all_seen++;
if (!save_aligned && !(read->core.flag & BAM_FUNMAP))
continue;
if (!save_unaligned && (read->core.flag & BAM_FUNMAP))
continue;
if (!save_filtered && (read->core.flag & BAM_FQCFAIL))
continue;
exported++;
ostringstream ostr;
ostr << "@" << get_read_name(read) << endl
<< get_sequence(read) << endl
<< "+" << endl
<< get_qualities(read) << endl;
if (isPaired) {
//Paired-end is complicated, because both members of the pair
//have to be output at the same position of the two files
string pairName(get_pair_name(read));
if (!strict)
mangle(pairName);
position = unPaired.find(pairName);
if (position == unPaired.end()) {
//I haven't seen the other member of this pair, so just save it
unPaired[pairName] = ostr.str();
} else {
//Aha! This will be the second of the two. Dump them both,
//then clean up
int r_idx = get_read_idx(read);
*output[r_idx] << ostr.str();
r_idx = !r_idx;
*output[r_idx] << position->second;
unPaired.erase(position);
}
} else {
//Single-end? Just dump it
*output[0] << ostr.str();
}
} while (bam_read1(sam->x.bam, read) > 0);
//The documentation for bam_read1 says that it returns the number of
//bytes read - which is true, unless it doesn't read any. It returns
//-1 for normal EOF and -2 for unexpected EOF. So don't just wait for
//it to return 0...
for_each(output.begin(), output.end(), DeleteObject());
bam_destroy1(read);
samclose(sam);
if (print_msgs) {
cerr << all_seen << " sequences in the BAM file" << endl;
cerr << exported << " sequences exported" << endl;
}
if (!unPaired.empty()) {
cerr << "WARNING: " << unPaired.size() << " reads could not be matched "
<< "to a mate and were not exported" << endl;
}
}
int main (int argc, char *argv[]) {
bases[1] = 'A';
bases[2] = 'C';
bases[4] = 'G';
bases[8] = 'T';
bases[15] = 'N';
//Complements (original index + 16)
bases[17] = 'T';
bases[18] = 'G';
bases[20] = 'C';
bases[24] = 'A';
bases[31] = 'N';
string output_template("s_%#_sequence.txt");
int ch;
while ((ch = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1)
switch (ch) {
case 'v':
cerr << "bam2fastq v" << version << endl;
exit(0);
case 'h' :
usage(0);
case 'o' :
output_template = string(optarg);
break;
case 'f' :
overwrite_files = 1;
break;
case 'q' :
print_msgs = 0;
break;
case 's' :
strict = 1;
break;
case '?' : //Unrecognized option
usage(2);
//The remaining options will set the appropriate variable themselves
};
argc -= optind;
argv += optind;
if (argc == 0)
usage(1);
parse_bamfile(argv[0], output_template);
return 0;
}<commit_msg>write unpaired reads to a separate file<commit_after>/*
Copyright 2010, HudsonAlpha Institute for Biotechnology
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.
bam2fastq.cpp
Written by Phillip Dexheimer
*/
#include "sam.h"
#include <getopt.h>
#include <map>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <cctype>
using namespace std;
const char version[] = "1.1.0";
const char shortopts[] = "o:vhfqs";
int save_aligned = 1;
int save_unaligned = 1;
int save_filtered = 1;
int overwrite_files = 0;
int print_msgs = 1;
int strict = 0;
static struct option longopts[] = {
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, 'v' },
{ "output", required_argument, NULL, 'o' },
{ "force", no_argument, NULL, 'f' },
{ "quiet", no_argument, NULL, 'q' },
{ "strict", no_argument, NULL, 's' },
{ "overwrite", no_argument, &overwrite_files,0 },
{ "aligned", no_argument, &save_aligned, 1 },
{ "no-aligned", no_argument, &save_aligned, 0 },
{ "unaligned", no_argument, &save_unaligned, 1 },
{ "no-unaligned", no_argument, &save_unaligned, 0 },
{ "filtered", no_argument, &save_filtered, 1 },
{ "no-filtered", no_argument, &save_filtered, 0 },
{ NULL, 0, NULL, 0 }
};
void usage(int error=1) {
cerr << "bam2fastq v" << version << " - extract sequences from a BAM file" << endl
<< endl
<< "Usage: bam2fastq [options] <bam file>" << endl
<< endl
<< "Options:" << endl
<< " -o FILENAME, --output FILENAME" << endl
<< " Specifies the name of the FASTQ file(s) that will be generated. May" << endl
<< " contain the special characters % (replaced with the lane number) and" << endl
<< " # (replaced with _1 or _2 to distinguish PE reads, removed for SE reads)." << endl
<< " [Default: s_%#_sequence.txt]" << endl
<< " -f, --force, --overwrite" << endl
<< " Create output files specified with --output, overwriting existing" << endl
<< " files if necessary [Default: exit program rather than overwrite files]" << endl
<< " --aligned" << endl
<< " --no-aligned" << endl
<< " Reads in the BAM that are aligned will (will not) be extracted." << endl
<< " [Default: extract aligned reads]" << endl
<< " --unaligned" << endl
<< " --no-unaligned" << endl
<< " Reads in the BAM that are not aligned will (will not) be extracted." << endl
<< " [Default: extract unaligned reads]" << endl
<< " --filtered" << endl
<< " --no-filtered" << endl
<< " Reads that are marked as failing QC checks will (will not) be extracted." << endl
<< " [Default: extract filtered reads]" << endl
<< " -q, --quiet" << endl
<< " Suppress informational messages [Default: print messages]" << endl
<< " -s, --strict" << endl
<< " Keep bam2fastq's processing to a minimum, assuming that the BAM strictly"
<< " meets specifications. [Default: allow some errors in the BAM]" << endl
<< endl;
exit(error);
}
map<int, char> bases;
const string get_pair_name(const bam1_t *b) {
return string(bam1_qname(b));
}
//Returns 0 for read 1 and 1 for read 2.
//Counterintuitive, but good for lookups
const int get_read_idx(const bam1_t *b) {
return !(b->core.flag & BAM_FREAD1);
}
const string get_read_name(const bam1_t *b) {
static const char suffix[2][3] = { "/1", "/2" };
string name = get_pair_name(b);
if (b->core.flag & BAM_FPAIRED)
name += suffix[get_read_idx(b)];
return name;
}
int get_lane_id(const bam1_t *b) {
string name(get_pair_name(b));
size_t start = name.find(":");
if (start == string::npos)
return 0;
start++;
size_t stop = name.find(":", start);
if (stop == string::npos || stop == start)
return 0;
istringstream ist(string(name.begin()+start, name.begin()+stop));
int lane;
ist >> lane;
return lane;
}
const string get_sequence(const bam1_t *b) {
const uint8_t *seq = bam1_seq(b);
size_t len = b->core.l_qseq;
string sequence("");
sequence.reserve(len);
uint8_t offset = (b->core.flag & BAM_FREVERSE) ? 16 : 0;
for (size_t i=0; i<len; i++) {
sequence += bases[bam1_seqi(seq, i) + offset];
}
if (offset)
sequence = string(sequence.rbegin(), sequence.rend());
return sequence;
}
const string get_qualities(const bam1_t *b) {
const uint8_t *qual = bam1_qual(b);
size_t len = b->core.l_qseq;
string quality("");
quality.reserve(len);
for (size_t i=0; i<len; i++) {
quality += char_traits<char>::to_char_type(char_traits<char>::to_int_type(qual[i])+33);
}
if (b->core.flag & BAM_FREVERSE)
quality = string(quality.rbegin(), quality.rend());
return quality;
}
void mangle(string &name) {
if (name.length() < 3)
return;
if (isdigit(name[name.length()-1]) && !isdigit(name[name.length()-2]))
name.erase(name.length()-2);
}
vector<ofstream *> initialize_output(const string &out_template, int lane) {
vector<ofstream *> files;
string output(out_template);
//First, replace % in the filename with the lane number
size_t laneMarker = output.find('%');
if (laneMarker != string::npos) {
if (lane == 0) {
cerr << "The lane could not be determined from the reads. Specify output files" << endl
<< "(using --output) that do not include the lane number (%)" << endl;
return files;
}
ostringstream laneStr;
laneStr << lane;
output.replace(laneMarker, 1, laneStr.str());
}
//Replace # with read number and open ofstreams
size_t readMarker = output.find('#');
//Replace
if (readMarker == string::npos) {
cerr << "The sequences in the BAM file are marked as Paired, but a single output" << endl
<< "file is specified. Ensure that the output filename (--output) includes" << endl
<< "a # symbol to be replaced with the read number" << endl;
return files;
}
string file1(output);
file1.replace(readMarker, 1, "_1");
string file2(output);
file2.replace(readMarker, 1, "_2");
string file3(output);
file3.replace(readMarker, 1, "_M");
if (print_msgs)
cerr << "This looks like paired data from lane " << lane << "." << endl
<< "Output will be in " << file1 << " and " << file2 << endl
<< "Single-end reads will be in " << file3 << endl;
//If we're not going to overwrite, check to see if the files exist
if (!overwrite_files) {
ifstream test;
test.open(file1.c_str());
if (test.is_open()) {
cerr << "ERROR: " << file1 << " already exists. Specify --force to overwrite" << endl;
return files;
}
//test is not open, so don't try closing it
test.open(file2.c_str());
if (test.is_open()) {
cerr << "ERROR: " << file2 << " already exists. Specify --force to overwrite" << endl;
return files;
}
}
files.push_back(new ofstream(file1.c_str(), ios_base::out));
files.push_back(new ofstream(file2.c_str(), ios_base::out));
files.push_back(new ofstream(file3.c_str(), ios_base::out));
return files;
}
//Effective STL, Item 7
//Except, of course, that I'm not using smart pointers
struct DeleteObject {
template<typename T>
void operator()(const T *ptr) const {
delete ptr;
}
};
void parse_bamfile(const char *bam_filename, const string &output_template) {
samfile_t *sam = samopen(bam_filename, "rb", NULL);
if (sam == NULL) {
cerr << "Could not open " << bam_filename << endl;
return;
}
bam1_t *read = bam_init1();
size_t exported = 0;
size_t all_seen = 0;
bam_read1(sam->x.bam, read);
int lane = get_lane_id(read);
vector<ofstream *> output = initialize_output(output_template, lane);
if (output.empty())
return;
map<string, string> unPaired;
map<string, string>::iterator position;
do {
all_seen++;
if (!save_aligned && !(read->core.flag & BAM_FUNMAP))
continue;
if (!save_unaligned && (read->core.flag & BAM_FUNMAP))
continue;
if (!save_filtered && (read->core.flag & BAM_FQCFAIL))
continue;
exported++;
ostringstream ostr;
ostr << "@" << get_read_name(read) << endl
<< get_sequence(read) << endl
<< "+" << endl
<< get_qualities(read) << endl;
//Paired-end is complicated, because both members of the pair
//have to be output at the same position of the two files
// Is this an unpaired read in a BAM with pairs? write to the _M file
if( !(read->core.flag & BAM_FPAIRED) ) {
*output[2] << ostr.str();
} else {
// Search for the pair in the map
string pairName(get_pair_name(read));
if (!strict)
mangle(pairName);
position = unPaired.find(pairName);
if (position == unPaired.end()) {
//I haven't seen the other member of this pair, so just save it
unPaired[pairName] = ostr.str();
} else {
//Aha! This will be the second of the two. Dump them both,
//then clean up
int r_idx = get_read_idx(read);
*output[r_idx] << ostr.str();
r_idx = !r_idx;
*output[r_idx] << position->second;
unPaired.erase(position);
}
}
} while (bam_read1(sam->x.bam, read) > 0);
//The documentation for bam_read1 says that it returns the number of
//bytes read - which is true, unless it doesn't read any. It returns
//-1 for normal EOF and -2 for unexpected EOF. So don't just wait for
//it to return 0...
for_each(output.begin(), output.end(), DeleteObject());
bam_destroy1(read);
samclose(sam);
if (print_msgs) {
cerr << all_seen << " sequences in the BAM file" << endl;
cerr << exported << " sequences exported" << endl;
}
if (!unPaired.empty()) {
cerr << "WARNING: " << unPaired.size() << " reads could not be matched "
<< "to a mate and were not exported" << endl;
}
}
int main (int argc, char *argv[]) {
bases[1] = 'A';
bases[2] = 'C';
bases[4] = 'G';
bases[8] = 'T';
bases[15] = 'N';
//Complements (original index + 16)
bases[17] = 'T';
bases[18] = 'G';
bases[20] = 'C';
bases[24] = 'A';
bases[31] = 'N';
string output_template("s_%#_sequence.txt");
int ch;
while ((ch = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1)
switch (ch) {
case 'v':
cerr << "bam2fastq v" << version << endl;
exit(0);
case 'h' :
usage(0);
case 'o' :
output_template = string(optarg);
break;
case 'f' :
overwrite_files = 1;
break;
case 'q' :
print_msgs = 0;
break;
case 's' :
strict = 1;
break;
case '?' : //Unrecognized option
usage(2);
//The remaining options will set the appropriate variable themselves
};
argc -= optind;
argv += optind;
if (argc == 0)
usage(1);
parse_bamfile(argv[0], output_template);
return 0;
}
<|endoftext|>
|
<commit_before>//@author A0094446X
#include "stdafx.h"
#include <QApplication>
#include <QList>
#include "task_panel_manager.h"
namespace You {
namespace GUI {
using Date = boost::gregorian::date;
const QString MainWindow::TaskPanelManager::TASK_COLUMN_1 = "Hidden ID Column";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_2 = "Index";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_3 = "Description";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_4 = "Deadline";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_5 = "Priority";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_6 = "Dependencies";
MainWindow::TaskPanelManager::TaskPanelManager(MainWindow* const parentGUI)
: BaseManager(parentGUI) {
}
MainWindow::TaskPanelManager::~TaskPanelManager() {
}
void MainWindow::TaskPanelManager::setup() {
QStringList columnHeaders({
TASK_COLUMN_1,
TASK_COLUMN_2,
TASK_COLUMN_3,
TASK_COLUMN_4,
TASK_COLUMN_5,
TASK_COLUMN_6
});
QTreeWidget* taskTreePanel = parentGUI->ui.taskTreePanel;
connect(taskTreePanel, SIGNAL(itemSelectionChanged()),
parentGUI, SLOT(taskSelected()));
taskTreePanel->setColumnCount(columnHeaders.size());
taskTreePanel->setHeaderItem(createItem(columnHeaders).release());
// TODO(angathorion): remove magic constants.
QHeaderView* header = taskTreePanel->header();
header->setStretchLastSection(true);
for (int i = 1; i < columnHeaders.size(); ++i) {
if (i == 2) {
continue;
}
header->resizeSection(i, header->defaultSectionSize());
}
taskTreePanel->header()->setMinimumSectionSize(75);
taskTreePanel->setColumnHidden(0, true);
taskTreePanel->setColumnHidden(5, true);
}
void MainWindow::TaskPanelManager::addTask(const Task& task) {
std::unique_ptr<QTreeWidgetItem> item(createItem(task));
parentGUI->ui.taskTreePanel->addTopLevelItem(item.release());
updateRowNumbers();
}
void MainWindow::TaskPanelManager::addSubtask(QTreeWidgetItem* parent,
const QStringList& rowStrings) {
std::unique_ptr<QTreeWidgetItem> item(createItem(rowStrings));
parent->addChild(item.release());
updateRowNumbers();
}
void MainWindow::TaskPanelManager::editTask(const Task& task) {
QList<QTreeWidgetItem*> items = findItems(task.getID());
assert(items.length() == 1);
QTreeWidgetItem item = *items.at(0);
QStringList wstr = taskToStrVec(task);
*items.at(0) = *createItem(wstr);
updateRowNumbers();
}
void MainWindow::TaskPanelManager::deleteTask(Task::ID taskID) {
QList<QTreeWidgetItem*> items = findItems(taskID);
assert(items.length() == 1);
deleteTask(items.at(0));
updateRowNumbers();
}
void MainWindow::TaskPanelManager::deleteTask(QTreeWidgetItem* task) {
delete task;
}
std::unique_ptr<QTreeWidgetItem> MainWindow::TaskPanelManager::createItem(
const Task& task) {
return createItem(taskToStrVec(task));
}
std::unique_ptr<QTreeWidgetItem> MainWindow::TaskPanelManager::createItem(
const QStringList& rowStrings) {
return std::make_unique<QTreeWidgetItem>(rowStrings);
}
QList<QTreeWidgetItem*> MainWindow::TaskPanelManager::findItems(
You::Controller::Task::ID taskID) const {
return parentGUI->ui.taskTreePanel->findItems(
boost::lexical_cast<QString>(taskID), 0);
}
QStringList MainWindow::TaskPanelManager::taskToStrVec(
const You::Controller::Task& task) {
QStringList result;
// Insert id
result.push_back(boost::lexical_cast<QString>(task.getID()));
// Insert dummy count
result.push_back("0");
// Insert description
result.push_back(QString::fromStdWString(task.getDescription()));
// Insert deadline
if (task.getDeadline() == Task::NEVER) {
result.push_back(QString("Never"));
} else {
result.push_back(boost::lexical_cast<QString>(task.getDeadline()));
task.getDeadline();
}
// Insert priority
QString priority[] { "High", "Normal" };
switch (task.getPriority()) {
case Task::Priority::HIGH:
result.push_back(priority[0]);
case Task::Priority::NORMAL:
result.push_back(priority[1]);
}
// Insert dependencies
std::wstringstream ss;
if (task.getDependencies().size() != 0) {
ss << task.getDependencies().at(0);
for (int i = 1; i < task.getDependencies().size(); i++) {
ss << ", " << task.getDependencies().at(i);
}
result.push_back(QString::fromStdWString(ss.str()));
} else {
result.push_back("None");
}
return result;
}
void MainWindow::TaskPanelManager::updateRowNumbers() {
int rowNum = 0;
for (QTreeWidgetItemIterator it(parentGUI->ui.taskTreePanel); *it; ++it) {
(*it)->setData(1, Qt::DisplayRole, rowNum++);
}
}
bool MainWindow::TaskPanelManager::isPastDue(Task::Time deadline) {
return true;
}
bool MainWindow::TaskPanelManager::isDueAfter(
Task::Time deadline, int daysLeft) {
Date by = Date(deadline.date());
Date today = boost::gregorian::day_clock::universal_day();
if (by.day_of_year() - today.day_of_year() == daysLeft) {
return true;
} else {
return false;
}
}
} // namespace GUI
} // namespace You
<commit_msg>Switched to match to local_time. Previously did not match.<commit_after>//@author A0094446X
#include "stdafx.h"
#include <QApplication>
#include <QList>
#include "task_panel_manager.h"
namespace You {
namespace GUI {
using Date = boost::gregorian::date;
const QString MainWindow::TaskPanelManager::TASK_COLUMN_1 = "Hidden ID Column";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_2 = "Index";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_3 = "Description";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_4 = "Deadline";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_5 = "Priority";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_6 = "Dependencies";
MainWindow::TaskPanelManager::TaskPanelManager(MainWindow* const parentGUI)
: BaseManager(parentGUI) {
}
MainWindow::TaskPanelManager::~TaskPanelManager() {
}
void MainWindow::TaskPanelManager::setup() {
QStringList columnHeaders({
TASK_COLUMN_1,
TASK_COLUMN_2,
TASK_COLUMN_3,
TASK_COLUMN_4,
TASK_COLUMN_5,
TASK_COLUMN_6
});
QTreeWidget* taskTreePanel = parentGUI->ui.taskTreePanel;
connect(taskTreePanel, SIGNAL(itemSelectionChanged()),
parentGUI, SLOT(taskSelected()));
taskTreePanel->setColumnCount(columnHeaders.size());
taskTreePanel->setHeaderItem(createItem(columnHeaders).release());
// TODO(angathorion): remove magic constants.
QHeaderView* header = taskTreePanel->header();
header->setStretchLastSection(true);
for (int i = 1; i < columnHeaders.size(); ++i) {
if (i == 2) {
continue;
}
header->resizeSection(i, header->defaultSectionSize());
}
taskTreePanel->header()->setMinimumSectionSize(75);
taskTreePanel->setColumnHidden(0, true);
taskTreePanel->setColumnHidden(5, true);
}
void MainWindow::TaskPanelManager::addTask(const Task& task) {
std::unique_ptr<QTreeWidgetItem> item(createItem(task));
parentGUI->ui.taskTreePanel->addTopLevelItem(item.release());
updateRowNumbers();
}
void MainWindow::TaskPanelManager::addSubtask(QTreeWidgetItem* parent,
const QStringList& rowStrings) {
std::unique_ptr<QTreeWidgetItem> item(createItem(rowStrings));
parent->addChild(item.release());
updateRowNumbers();
}
void MainWindow::TaskPanelManager::editTask(const Task& task) {
QList<QTreeWidgetItem*> items = findItems(task.getID());
assert(items.length() == 1);
QTreeWidgetItem item = *items.at(0);
QStringList wstr = taskToStrVec(task);
*items.at(0) = *createItem(wstr);
updateRowNumbers();
}
void MainWindow::TaskPanelManager::deleteTask(Task::ID taskID) {
QList<QTreeWidgetItem*> items = findItems(taskID);
assert(items.length() == 1);
deleteTask(items.at(0));
updateRowNumbers();
}
void MainWindow::TaskPanelManager::deleteTask(QTreeWidgetItem* task) {
delete task;
}
std::unique_ptr<QTreeWidgetItem> MainWindow::TaskPanelManager::createItem(
const Task& task) {
return createItem(taskToStrVec(task));
}
std::unique_ptr<QTreeWidgetItem> MainWindow::TaskPanelManager::createItem(
const QStringList& rowStrings) {
return std::make_unique<QTreeWidgetItem>(rowStrings);
}
QList<QTreeWidgetItem*> MainWindow::TaskPanelManager::findItems(
You::Controller::Task::ID taskID) const {
return parentGUI->ui.taskTreePanel->findItems(
boost::lexical_cast<QString>(taskID), 0);
}
QStringList MainWindow::TaskPanelManager::taskToStrVec(
const You::Controller::Task& task) {
QStringList result;
// Insert id
result.push_back(boost::lexical_cast<QString>(task.getID()));
// Insert dummy count
result.push_back("0");
// Insert description
result.push_back(QString::fromStdWString(task.getDescription()));
// Insert deadline
if (task.getDeadline() == Task::NEVER) {
result.push_back(QString("Never"));
} else {
result.push_back(boost::lexical_cast<QString>(task.getDeadline()));
task.getDeadline();
}
// Insert priority
QString priority[] { "High", "Normal" };
switch (task.getPriority()) {
case Task::Priority::HIGH:
result.push_back(priority[0]);
case Task::Priority::NORMAL:
result.push_back(priority[1]);
}
// Insert dependencies
std::wstringstream ss;
if (task.getDependencies().size() != 0) {
ss << task.getDependencies().at(0);
for (int i = 1; i < task.getDependencies().size(); i++) {
ss << ", " << task.getDependencies().at(i);
}
result.push_back(QString::fromStdWString(ss.str()));
} else {
result.push_back("None");
}
return result;
}
void MainWindow::TaskPanelManager::updateRowNumbers() {
int rowNum = 0;
for (QTreeWidgetItemIterator it(parentGUI->ui.taskTreePanel); *it; ++it) {
(*it)->setData(1, Qt::DisplayRole, rowNum++);
}
}
bool MainWindow::TaskPanelManager::isPastDue(Task::Time deadline) {
return true;
}
bool MainWindow::TaskPanelManager::isDueAfter(
Task::Time deadline, int daysLeft) {
Date by = Date(deadline.date());
Date today = boost::gregorian::day_clock::local_day();
if (by.day_of_year() - today.day_of_year() == daysLeft) {
return true;
} else {
return false;
}
}
} // namespace GUI
} // namespace You
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2015 CNRS
// Copyright (c) 2015 Wandercraft, 86 rue de Paris 91400 Orsay, France.
//
// This file is part of Pinocchio
// Pinocchio is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// Pinocchio 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// Pinocchio If not, see
// <http://www.gnu.org/licenses/>.
#ifndef __se3_urdf_hpp__
#define __se3_urdf_hpp__
#include <urdf_model/model.h>
#include <urdf_parser/urdf_parser.h>
#include <iostream>
#include <boost/foreach.hpp>
#include "pinocchio/multibody/model.hpp"
#include <exception>
namespace urdf
{
typedef boost::shared_ptr<ModelInterface> ModelInterfacePtr;
typedef boost::shared_ptr<const Joint> JointConstPtr;
typedef boost::shared_ptr<const Link> LinkConstPtr;
typedef boost::shared_ptr<Link> LinkPtr;
typedef boost::shared_ptr<const Inertial> InertialConstPtr;
}
namespace se3
{
namespace urdf
{
inline Inertia convertFromUrdf( const ::urdf::Inertial& Y )
{
const ::urdf::Vector3 & p = Y.origin.position;
const ::urdf::Rotation & q = Y.origin.rotation;
const Eigen::Vector3d com(p.x,p.y,p.z);
const Eigen::Matrix3d & R = Eigen::Quaterniond(q.w,q.x,q.y,q.z).matrix();
Eigen::Matrix3d I; I << Y.ixx,Y.ixy,Y.ixz
, Y.ixy,Y.iyy,Y.iyz
, Y.ixz,Y.iyz,Y.izz;
return Inertia(Y.mass,com,R*I*R.transpose());
}
inline SE3 convertFromUrdf( const ::urdf::Pose & M )
{
const ::urdf::Vector3 & p = M.position;
const ::urdf::Rotation & q = M.rotation;
return SE3( Eigen::Quaterniond(q.w,q.x,q.y,q.z).matrix(), Eigen::Vector3d(p.x,p.y,p.z));
}
enum AxisCartesian { AXIS_X, AXIS_Y, AXIS_Z, AXIS_UNALIGNED };
inline AxisCartesian extractCartesianAxis( const ::urdf::Vector3 & axis )
{
if( (axis.x==1.0)&&(axis.y==0.0)&&(axis.z==0.0) )
return AXIS_X;
else if( (axis.x==0.0)&&(axis.y==1.0)&&(axis.z==0.0) )
return AXIS_Y;
else if( (axis.x==0.0)&&(axis.y==0.0)&&(axis.z==1.0) )
return AXIS_Z;
else
return AXIS_UNALIGNED;
}
inline void parseTree( ::urdf::LinkConstPtr link, Model & model, const SE3 & placementOffset = SE3::Identity()) throw (std::invalid_argument)
{
::urdf::JointConstPtr joint = link->parent_joint;
SE3 nextPlacementOffset = SE3::Identity(); // OffSet of the next link. In case we encounter a fixed joint, we need to propagate the length of its attached body to next joint.
// std::cout << " *** " << link->name << " < attached by joint ";
// if(joint)
// std::cout << "#" << link->parent_joint->name << std::endl;
// else std::cout << "###ROOT" << std::endl;
// std::cout << "placementOffset: " << placementOffset << std::endl;
if(joint!=NULL)
{
assert(link->getParent()!=NULL);
if (!link->inertial && joint->type != ::urdf::Joint::FIXED)
{
const std::string exception_message (link->name + " - spatial inertia information missing.");
throw std::invalid_argument(exception_message);
}
Model::Index parent = (link->getParent()->parent_joint==NULL) ? (model.existJointName("root_joint") ? model.getJointId("root_joint") : 0) :
model.getJointId( link->getParent()->parent_joint->name );
//std::cout << joint->name << " === " << parent << std::endl;
const SE3 & jointPlacement = placementOffset*convertFromUrdf(joint->parent_to_joint_origin_transform);
const Inertia & Y = (link->inertial) ? convertFromUrdf(*link->inertial) :
Inertia::Identity();
bool visual = (link->visual) ? true : false;
//std::cout << "Parent = " << parent << std::endl;
//std::cout << "Placement = " << (Matrix4)jointPlacement << std::endl;
switch(joint->type)
{
case ::urdf::Joint::REVOLUTE:
case ::urdf::Joint::CONTINUOUS: // Revolute with no joint limits
{
Eigen::VectorXd maxEffort;
Eigen::VectorXd velocity;
Eigen::VectorXd lowerPosition;
Eigen::VectorXd upperPosition;
if (joint->limits)
{
maxEffort.resize(1); maxEffort << joint->limits->effort;
velocity.resize(1); velocity << joint->limits->velocity;
lowerPosition.resize(1); lowerPosition << joint->limits->lower;
upperPosition.resize(1); upperPosition << joint->limits->upper;
}
Eigen::Vector3d jointAxis(Eigen::Vector3d::Zero());
AxisCartesian axis = extractCartesianAxis(joint->axis);
switch(axis)
{
case AXIS_X:
model.addBody( parent, JointModelRX(), jointPlacement, Y,
maxEffort, velocity, lowerPosition, upperPosition,
joint->name,link->name, visual );
break;
case AXIS_Y:
model.addBody( parent, JointModelRY(), jointPlacement, Y,
maxEffort, velocity, lowerPosition, upperPosition,
joint->name,link->name, visual );
break;
case AXIS_Z:
model.addBody( parent, JointModelRZ(), jointPlacement, Y,
maxEffort, velocity, lowerPosition, upperPosition,
joint->name,link->name, visual );
break;
case AXIS_UNALIGNED:
jointAxis= Eigen::Vector3d( joint->axis.x,joint->axis.y,joint->axis.z );
jointAxis.normalize();
model.addBody( parent, JointModelRevoluteUnaligned(jointAxis),
jointPlacement, Y,
maxEffort, velocity, lowerPosition, upperPosition,
joint->name,link->name, visual );
break;
default:
assert( false && "Fatal Error while extracting revolute joint axis");
break;
}
break;
}
case ::urdf::Joint::PRISMATIC:
{
Eigen::VectorXd maxEffort = Eigen::VectorXd(0.);
Eigen::VectorXd velocity = Eigen::VectorXd(0.);
Eigen::VectorXd lowerPosition = Eigen::VectorXd(0.);
Eigen::VectorXd upperPosition = Eigen::VectorXd(0.);
if (joint->limits)
{
maxEffort.resize(1); maxEffort << joint->limits->effort;
velocity.resize(1); velocity << joint->limits->velocity;
lowerPosition.resize(1); lowerPosition << joint->limits->lower;
upperPosition.resize(1); upperPosition << joint->limits->upper;
}
AxisCartesian axis = extractCartesianAxis(joint->axis);
switch(axis)
{
case AXIS_X:
model.addBody( parent, JointModelPX(), jointPlacement, Y,
maxEffort, velocity, lowerPosition, upperPosition,
joint->name,link->name, visual );
break;
case AXIS_Y:
model.addBody( parent, JointModelPY(), jointPlacement, Y,
maxEffort, velocity, lowerPosition, upperPosition,
joint->name,link->name, visual );
break;
case AXIS_Z:
model.addBody( parent, JointModelPZ(), jointPlacement, Y,
maxEffort, velocity, lowerPosition, upperPosition,
joint->name,link->name, visual );
break;
case AXIS_UNALIGNED:
std::cerr << "Bad axis = (" << joint->axis.x <<"," << joint->axis.y << "," << joint->axis.z << ")" << std::endl;
assert(false && "Only X, Y or Z axis are accepted." );
break;
default:
assert( false && "Fatal Error while extracting prismatic joint axis");
break;
}
break;
}
case ::urdf::Joint::FIXED:
{
// In case of fixed joint, if link has inertial tag:
// -add the inertia of the link to his parent in the model
// Otherwise do nothing.
// In all cases:
// -let all the children become children of parent
// -inform the parser of the offset to apply
// -add fixed body in model to display it in gepetto-viewer
if (link->inertial)
{
model.mergeFixedBody(parent, jointPlacement, Y); //Modify the parent inertia in the model
}
SE3 ptjot_se3 = convertFromUrdf(link->parent_joint->parent_to_joint_origin_transform);
//transformation of the current placement offset
nextPlacementOffset = placementOffset*ptjot_se3;
//add the fixed Body in the model for the viewer
model.addFixedBody(parent,nextPlacementOffset,link->name,visual);
BOOST_FOREACH(::urdf::LinkPtr child_link,link->child_links)
{
child_link->setParent(link->getParent() ); //skip the fixed generation
}
break;
}
default:
{
std::cerr << "The joint type " << joint->type << " is not supported." << std::endl;
assert(false && "Only revolute, prismatic and fixed joints are accepted." );
break;
}
}
}
else if (link->getParent() != NULL)
{
const std::string exception_message (link->name + " - joint information missing.");
throw std::invalid_argument(exception_message);
}
BOOST_FOREACH(::urdf::LinkConstPtr child,link->child_links)
{
parseTree(child, model, nextPlacementOffset);
}
}
template <typename D>
void parseTree( ::urdf::LinkConstPtr link, Model & model, const SE3 & placementOffset , const JointModelBase<D> & root_joint )
{
const Inertia & Y = (link->inertial) ?
convertFromUrdf(*link->inertial)
: Inertia::Identity();
model.addBody( 0, root_joint, placementOffset, Y , "root_joint", link->name, true );
BOOST_FOREACH(::urdf::LinkConstPtr child,link->child_links)
{
parseTree(child, model, SE3::Identity());
}
}
template <typename D>
Model buildModel( const std::string & filename, const JointModelBase<D> & root_joint )
{
Model model;
::urdf::ModelInterfacePtr urdfTree = ::urdf::parseURDFFile (filename);
if (urdfTree)
parseTree(urdfTree->getRoot(), model, SE3::Identity(), root_joint);
else
{
std::cerr << "The URDF tree seems to be empty" << std::endl; // In future, raise exception instead
}
return model;
}
inline Model buildModel( const std::string & filename)
{
Model model;
::urdf::ModelInterfacePtr urdfTree = ::urdf::parseURDFFile (filename);
if (urdfTree)
parseTree(urdfTree->getRoot(), model, SE3::Identity());
else
{
std::cerr << "The URDF tree seems to be empty" << std::endl; // In future, raise exception instead
}
return model;
}
} // namespace urdf
} // namespace se3
#endif // ifndef __se3_urdf_hpp__
<commit_msg>[C++] Raise an exception when the urdf tree is badly formated<commit_after>//
// Copyright (c) 2015 CNRS
// Copyright (c) 2015 Wandercraft, 86 rue de Paris 91400 Orsay, France.
//
// This file is part of Pinocchio
// Pinocchio is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// Pinocchio 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// Pinocchio If not, see
// <http://www.gnu.org/licenses/>.
#ifndef __se3_urdf_hpp__
#define __se3_urdf_hpp__
#include <urdf_model/model.h>
#include <urdf_parser/urdf_parser.h>
#include <iostream>
#include <boost/foreach.hpp>
#include "pinocchio/multibody/model.hpp"
#include <exception>
namespace urdf
{
typedef boost::shared_ptr<ModelInterface> ModelInterfacePtr;
typedef boost::shared_ptr<const Joint> JointConstPtr;
typedef boost::shared_ptr<const Link> LinkConstPtr;
typedef boost::shared_ptr<Link> LinkPtr;
typedef boost::shared_ptr<const Inertial> InertialConstPtr;
}
namespace se3
{
namespace urdf
{
inline Inertia convertFromUrdf( const ::urdf::Inertial& Y )
{
const ::urdf::Vector3 & p = Y.origin.position;
const ::urdf::Rotation & q = Y.origin.rotation;
const Eigen::Vector3d com(p.x,p.y,p.z);
const Eigen::Matrix3d & R = Eigen::Quaterniond(q.w,q.x,q.y,q.z).matrix();
Eigen::Matrix3d I; I << Y.ixx,Y.ixy,Y.ixz
, Y.ixy,Y.iyy,Y.iyz
, Y.ixz,Y.iyz,Y.izz;
return Inertia(Y.mass,com,R*I*R.transpose());
}
inline SE3 convertFromUrdf( const ::urdf::Pose & M )
{
const ::urdf::Vector3 & p = M.position;
const ::urdf::Rotation & q = M.rotation;
return SE3( Eigen::Quaterniond(q.w,q.x,q.y,q.z).matrix(), Eigen::Vector3d(p.x,p.y,p.z));
}
enum AxisCartesian { AXIS_X, AXIS_Y, AXIS_Z, AXIS_UNALIGNED };
inline AxisCartesian extractCartesianAxis( const ::urdf::Vector3 & axis )
{
if( (axis.x==1.0)&&(axis.y==0.0)&&(axis.z==0.0) )
return AXIS_X;
else if( (axis.x==0.0)&&(axis.y==1.0)&&(axis.z==0.0) )
return AXIS_Y;
else if( (axis.x==0.0)&&(axis.y==0.0)&&(axis.z==1.0) )
return AXIS_Z;
else
return AXIS_UNALIGNED;
}
inline void parseTree( ::urdf::LinkConstPtr link, Model & model, const SE3 & placementOffset = SE3::Identity()) throw (std::invalid_argument)
{
::urdf::JointConstPtr joint = link->parent_joint;
SE3 nextPlacementOffset = SE3::Identity(); // OffSet of the next link. In case we encounter a fixed joint, we need to propagate the length of its attached body to next joint.
// std::cout << " *** " << link->name << " < attached by joint ";
// if(joint)
// std::cout << "#" << link->parent_joint->name << std::endl;
// else std::cout << "###ROOT" << std::endl;
// std::cout << "placementOffset: " << placementOffset << std::endl;
if(joint!=NULL)
{
assert(link->getParent()!=NULL);
if (!link->inertial && joint->type != ::urdf::Joint::FIXED)
{
const std::string exception_message (link->name + " - spatial inertia information missing.");
throw std::invalid_argument(exception_message);
}
Model::Index parent = (link->getParent()->parent_joint==NULL) ? (model.existJointName("root_joint") ? model.getJointId("root_joint") : 0) :
model.getJointId( link->getParent()->parent_joint->name );
//std::cout << joint->name << " === " << parent << std::endl;
const SE3 & jointPlacement = placementOffset*convertFromUrdf(joint->parent_to_joint_origin_transform);
const Inertia & Y = (link->inertial) ? convertFromUrdf(*link->inertial) :
Inertia::Identity();
bool visual = (link->visual) ? true : false;
//std::cout << "Parent = " << parent << std::endl;
//std::cout << "Placement = " << (Matrix4)jointPlacement << std::endl;
switch(joint->type)
{
case ::urdf::Joint::REVOLUTE:
case ::urdf::Joint::CONTINUOUS: // Revolute with no joint limits
{
Eigen::VectorXd maxEffort;
Eigen::VectorXd velocity;
Eigen::VectorXd lowerPosition;
Eigen::VectorXd upperPosition;
if (joint->limits)
{
maxEffort.resize(1); maxEffort << joint->limits->effort;
velocity.resize(1); velocity << joint->limits->velocity;
lowerPosition.resize(1); lowerPosition << joint->limits->lower;
upperPosition.resize(1); upperPosition << joint->limits->upper;
}
Eigen::Vector3d jointAxis(Eigen::Vector3d::Zero());
AxisCartesian axis = extractCartesianAxis(joint->axis);
switch(axis)
{
case AXIS_X:
model.addBody( parent, JointModelRX(), jointPlacement, Y,
maxEffort, velocity, lowerPosition, upperPosition,
joint->name,link->name, visual );
break;
case AXIS_Y:
model.addBody( parent, JointModelRY(), jointPlacement, Y,
maxEffort, velocity, lowerPosition, upperPosition,
joint->name,link->name, visual );
break;
case AXIS_Z:
model.addBody( parent, JointModelRZ(), jointPlacement, Y,
maxEffort, velocity, lowerPosition, upperPosition,
joint->name,link->name, visual );
break;
case AXIS_UNALIGNED:
jointAxis= Eigen::Vector3d( joint->axis.x,joint->axis.y,joint->axis.z );
jointAxis.normalize();
model.addBody( parent, JointModelRevoluteUnaligned(jointAxis),
jointPlacement, Y,
maxEffort, velocity, lowerPosition, upperPosition,
joint->name,link->name, visual );
break;
default:
assert( false && "Fatal Error while extracting revolute joint axis");
break;
}
break;
}
case ::urdf::Joint::PRISMATIC:
{
Eigen::VectorXd maxEffort = Eigen::VectorXd(0.);
Eigen::VectorXd velocity = Eigen::VectorXd(0.);
Eigen::VectorXd lowerPosition = Eigen::VectorXd(0.);
Eigen::VectorXd upperPosition = Eigen::VectorXd(0.);
if (joint->limits)
{
maxEffort.resize(1); maxEffort << joint->limits->effort;
velocity.resize(1); velocity << joint->limits->velocity;
lowerPosition.resize(1); lowerPosition << joint->limits->lower;
upperPosition.resize(1); upperPosition << joint->limits->upper;
}
AxisCartesian axis = extractCartesianAxis(joint->axis);
switch(axis)
{
case AXIS_X:
model.addBody( parent, JointModelPX(), jointPlacement, Y,
maxEffort, velocity, lowerPosition, upperPosition,
joint->name,link->name, visual );
break;
case AXIS_Y:
model.addBody( parent, JointModelPY(), jointPlacement, Y,
maxEffort, velocity, lowerPosition, upperPosition,
joint->name,link->name, visual );
break;
case AXIS_Z:
model.addBody( parent, JointModelPZ(), jointPlacement, Y,
maxEffort, velocity, lowerPosition, upperPosition,
joint->name,link->name, visual );
break;
case AXIS_UNALIGNED:
std::cerr << "Bad axis = (" << joint->axis.x <<"," << joint->axis.y << "," << joint->axis.z << ")" << std::endl;
assert(false && "Only X, Y or Z axis are accepted." );
break;
default:
assert( false && "Fatal Error while extracting prismatic joint axis");
break;
}
break;
}
case ::urdf::Joint::FIXED:
{
// In case of fixed joint, if link has inertial tag:
// -add the inertia of the link to his parent in the model
// Otherwise do nothing.
// In all cases:
// -let all the children become children of parent
// -inform the parser of the offset to apply
// -add fixed body in model to display it in gepetto-viewer
if (link->inertial)
{
model.mergeFixedBody(parent, jointPlacement, Y); //Modify the parent inertia in the model
}
SE3 ptjot_se3 = convertFromUrdf(link->parent_joint->parent_to_joint_origin_transform);
//transformation of the current placement offset
nextPlacementOffset = placementOffset*ptjot_se3;
//add the fixed Body in the model for the viewer
model.addFixedBody(parent,nextPlacementOffset,link->name,visual);
BOOST_FOREACH(::urdf::LinkPtr child_link,link->child_links)
{
child_link->setParent(link->getParent() ); //skip the fixed generation
}
break;
}
default:
{
std::cerr << "The joint type " << joint->type << " is not supported." << std::endl;
assert(false && "Only revolute, prismatic and fixed joints are accepted." );
break;
}
}
}
else if (link->getParent() != NULL)
{
const std::string exception_message (link->name + " - joint information missing.");
throw std::invalid_argument(exception_message);
}
BOOST_FOREACH(::urdf::LinkConstPtr child,link->child_links)
{
parseTree(child, model, nextPlacementOffset);
}
}
template <typename D>
void parseTree( ::urdf::LinkConstPtr link, Model & model, const SE3 & placementOffset , const JointModelBase<D> & root_joint )
{
const Inertia & Y = (link->inertial) ?
convertFromUrdf(*link->inertial)
: Inertia::Identity();
model.addBody( 0, root_joint, placementOffset, Y , "root_joint", link->name, true );
BOOST_FOREACH(::urdf::LinkConstPtr child,link->child_links)
{
parseTree(child, model, SE3::Identity());
}
}
template <typename D>
Model buildModel( const std::string & filename, const JointModelBase<D> & root_joint )
{
Model model;
::urdf::ModelInterfacePtr urdfTree = ::urdf::parseURDFFile (filename);
if (urdfTree)
parseTree(urdfTree->getRoot(), model, SE3::Identity(), root_joint);
else
{
const std::string exception_message ("The file " + filename + " does not contain a valid URDF model.");
throw std::invalid_argument(exception_message);
}
return model;
}
inline Model buildModel( const std::string & filename)
{
Model model;
::urdf::ModelInterfacePtr urdfTree = ::urdf::parseURDFFile (filename);
if (urdfTree)
parseTree(urdfTree->getRoot(), model, SE3::Identity());
else
{
const std::string exception_message ("The file " + filename + " does not contain a valid URDF model.");
throw std::invalid_argument(exception_message);
}
return model;
}
} // namespace urdf
} // namespace se3
#endif // ifndef __se3_urdf_hpp__
<|endoftext|>
|
<commit_before>//---------------------------------------------------------
// Copyright 2016 Ontario Institute for Cancer Research
// Written by Jared Simpson (jared.simpson@oicr.on.ca)
//---------------------------------------------------------
//
// nanopolish_trainmodel - train a new pore model from
// the FAST5 output of a basecaller
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <vector>
#include <inttypes.h>
#include <assert.h>
#include <math.h>
#include <sys/time.h>
#include <algorithm>
#include <sstream>
#include <set>
#include <omp.h>
#include <getopt.h>
#include "htslib/faidx.h"
#include "nanopolish_poremodel.h"
#include "nanopolish_squiggle_read.h"
#include "nanopolish_methyltrain.h"
#include "training_core.hpp"
#include "profiler.h"
//
// Getopt
//
#define SUBPROGRAM "trainmodel"
static const char *TRAINMODEL_VERSION_MESSAGE =
SUBPROGRAM " Version " PACKAGE_VERSION "\n"
"Written by Jared Simpson.\n"
"\n"
"Copyright 2016 Ontario Institute for Cancer Research\n";
static const char *TRAINMODEL_USAGE_MESSAGE =
"Usage: " PACKAGE_NAME " " SUBPROGRAM " [OPTIONS] input.fofn\n"
"Train a new pore model using the basecalled reads in input.fofn\n"
"\n"
" -v, --verbose display verbose output\n"
" --version display version\n"
" --help display this help and exit\n"
"\nReport bugs to " PACKAGE_BUGREPORT "\n\n";
namespace opt
{
static unsigned int verbose;
static std::string fofn_file;
}
static const char* shortopts = "v";
enum { OPT_HELP = 1, OPT_VERSION };
static const struct option longopts[] = {
{ "verbose", no_argument, NULL, 'v' },
{ "help", no_argument, NULL, OPT_HELP },
{ "version", no_argument, NULL, OPT_VERSION },
{ NULL, 0, NULL, 0 }
};
void parse_trainmodel_options(int argc, char** argv)
{
bool die = false;
for (char c; (c = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1;) {
std::istringstream arg(optarg != NULL ? optarg : "");
switch (c) {
case '?': die = true; break;
case 'v': opt::verbose++; break;
case OPT_HELP:
std::cout << TRAINMODEL_USAGE_MESSAGE;
exit(EXIT_SUCCESS);
case OPT_VERSION:
std::cout << TRAINMODEL_VERSION_MESSAGE;
exit(EXIT_SUCCESS);
}
}
if (argc - optind < 1) {
std::cerr << SUBPROGRAM ": not enough arguments\n";
die = true;
}
if (argc - optind > 1) {
std::cerr << SUBPROGRAM ": too many arguments\n";
die = true;
}
if (die)
{
std::cout << "\n" << TRAINMODEL_USAGE_MESSAGE;
exit(EXIT_FAILURE);
}
opt::fofn_file = argv[optind++];
}
int trainmodel_main(int argc, char** argv)
{
parse_trainmodel_options(argc, argv);
std::ifstream fofn_reader(opt::fofn_file);
std::string fast5_name;
// Read input
std::vector<SquiggleRead*> reads;
while(getline(fofn_reader, fast5_name)) {
fprintf(stderr, "Loading %s\n", fast5_name.c_str());
reads.push_back(new SquiggleRead(fast5_name, fast5_name));
}
fprintf(stderr, "Loaded %zu reads\n", reads.size());
//
unsigned int basecalled_k = 5; // TODO: infer this
size_t num_kmers = gDNAAlphabet.get_num_strings(basecalled_k);
unsigned int training_strand = T_IDX; // template training for now
typedef std::vector<StateTrainingData> TrainingDataVector;
typedef std::vector<TrainingDataVector> KmerTrainingData;
// This vector is indexed by read, then kmer, then event
std::vector<KmerTrainingData> read_training_data;
size_t read_idx = 0;
for(auto* read : reads) {
// Initialize a vector-of-vectors to hold training data for this read
read_training_data.push_back(KmerTrainingData());
KmerTrainingData& kmer_training_data = read_training_data.back();
// Initialize the events-by-kmer vector
kmer_training_data.resize(num_kmers);
printf("KTD: %zu\n", kmer_training_data.size());
const std::string& read_sequence = read->read_sequence;
size_t n_kmers = read_sequence.size() - basecalled_k + 1;
for(size_t ki = 0; ki < n_kmers; ++ki) {
IndexPair event_range_for_kmer = read->base_to_event_map[ki].indices[training_strand];
// skip kmers without events and with multiple events
if(event_range_for_kmer.start == -1 ||
event_range_for_kmer.start != event_range_for_kmer.stop) {
continue;
}
std::string kmer = read_sequence.substr(ki, basecalled_k);
size_t kmer_rank = gDNAAlphabet.kmer_rank(kmer.c_str(), basecalled_k);
assert(kmer_rank < num_kmers);
size_t event_idx = event_range_for_kmer.start;
double level = read->events[training_strand][event_idx].mean;
double stdv = read->events[training_strand][event_idx].stdv;
printf("read: %zu kmer: %s ki: %zu lvl: %.2lf dur: %.5lf\n", read_idx, kmer.c_str(), kmer_rank, level, read->events[training_strand][event_idx].duration);
StateTrainingData std(level, stdv, read->pore_model[training_strand].var);
kmer_training_data[kmer_rank].push_back(std);
}
read_idx++;
/*
std::string kmer(basecalled_k, 'A');
for(size_t ki = 0; ki < num_kmers; ki++) {
size_t num_events = kmer_training_data[ki].size();
printf("%s:", kmer.c_str());
for(size_t ei = 0; ei < num_events; ++ei) {
printf("%.2lf\t", kmer_training_data[ki][ei].level_mean);
}
printf("\n");
gDNAAlphabet.lexicographic_next(kmer);
}
*/
}
// Select the read with the most events as the "baseline" read for generating the model
size_t max_events = 0;
size_t max_events_index = 0;
for(size_t rti = 0; rti < read_training_data.size(); ++rti) {
auto& kmer_training_data = read_training_data[rti];
size_t total_events = 0;
for(size_t ki = 0; ki < kmer_training_data.size(); ++ki) {
total_events += kmer_training_data[ki].size();
}
printf("read %zu has %zu events (max: %zu, %zu)\n", rti, total_events, max_events, max_events_index);
if(total_events > max_events) {
max_events = total_events;
max_events_index = rti;
}
}
// Set the initial pore model based on the read with the most events
PoreModel pore_model(basecalled_k);
pore_model.states.resize(num_kmers);
pore_model.scaled_states.resize(num_kmers);
pore_model.scaled_params.resize(num_kmers);
pore_model.shift = 0.0;
pore_model.scale = 1.0;
pore_model.drift = 0.0;
pore_model.var = 1.0;
pore_model.scale_sd = 1.0;
pore_model.var_sd = 1.0;
auto& kmer_training_data_for_selected = read_training_data[max_events_index];
std::vector<bool> use_kmer(num_kmers, false);
for(size_t ki = 0; ki < kmer_training_data_for_selected.size(); ++ki) {
std::vector<double> values;
std::stringstream ss;
for(size_t ei = 0; ei < kmer_training_data_for_selected[ki].size(); ++ei) {
values.push_back(kmer_training_data_for_selected[ki][ei].level_mean);
ss << values.back() << " ";
}
// Set the kmer's mean parameter to be the median of the recorded values
std::sort(values.begin(), values.end());
size_t n = values.size();
double median;
if(n == 0) {
median = 0.0f;
} else {
if(n % 2 == 0) {
median = (values[n / 2 - 1] + values[n/2]) / 2.0f;
} else {
median = values[n/2];
}
// mark this kmer as valid
use_kmer[ki] = true;
pore_model.states[ki].level_mean = median;
pore_model.states[ki].level_stdv = 1.0;
printf("k: %zu median: %.2lf values: %s\n", ki, median, ss.str().c_str());
}
}
pore_model.bake_gaussian_parameters();
// Apply model to each read
for(auto* read: reads) {
read->pore_model[training_strand] = pore_model;
}
// Recalibrate read
for(auto* read: reads) {
// We generate a vector of event-to-kmer mapping to use the recalibration linear solver
std::vector<EventAlignment> alignment;
const std::string& read_sequence = read->read_sequence;
size_t n_kmers = read_sequence.size() - basecalled_k + 1;
for(size_t ki = 0; ki < n_kmers; ++ki) {
IndexPair event_range_for_kmer = read->base_to_event_map[ki].indices[training_strand];
// skip kmers without events and with multiple events
if(event_range_for_kmer.start == -1 ||
event_range_for_kmer.start != event_range_for_kmer.stop) {
continue;
}
std::string kmer = read_sequence.substr(ki, basecalled_k);
size_t kmer_rank = gDNAAlphabet.kmer_rank(kmer.c_str(), basecalled_k);
assert(kmer_rank < num_kmers);
size_t event_idx = event_range_for_kmer.start;
// Only use this kmer if it is part of the initial model
if(use_kmer[kmer_rank]) {
EventAlignment ea;
// ref data
ea.ref_name = ""; // not needed
ea.ref_kmer = kmer;
ea.ref_position = ki;
ea.read_idx = -1; // not needed
ea.strand_idx = training_strand;
ea.event_idx = event_idx;
ea.rc = false;
ea.model_kmer = kmer;
ea.hmm_state = 'M'; // recalibration code only uses "M" alignments
alignment.push_back(ea);
}
}
recalibrate_model(*read,
training_strand,
alignment,
&gDNAAlphabet,
false);
const PoreModel& read_model = read->pore_model[training_strand];
printf("[recalibration] events: %zu alignment: %zu shift: %.2lf scale: %.2lf drift: %.4lf var: %.2lf\n",
read->events[training_strand].size(),
alignment.size(),
read_model.shift,
read_model.scale,
read_model.drift,
read_model.var);
}
// Deallocate input reads
for(auto* read : reads) {
delete read;
}
return 0;
}
<commit_msg>refactoring<commit_after>//---------------------------------------------------------
// Copyright 2016 Ontario Institute for Cancer Research
// Written by Jared Simpson (jared.simpson@oicr.on.ca)
//---------------------------------------------------------
//
// nanopolish_trainmodel - train a new pore model from
// the FAST5 output of a basecaller
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <vector>
#include <inttypes.h>
#include <assert.h>
#include <math.h>
#include <sys/time.h>
#include <algorithm>
#include <sstream>
#include <set>
#include <omp.h>
#include <getopt.h>
#include "htslib/faidx.h"
#include "nanopolish_poremodel.h"
#include "nanopolish_squiggle_read.h"
#include "nanopolish_methyltrain.h"
#include "training_core.hpp"
#include "profiler.h"
//
// Typedefs
//
typedef std::vector<StateTrainingData> TrainingDataVector;
typedef std::vector<TrainingDataVector> KmerTrainingData;
//
// Getopt
//
#define SUBPROGRAM "trainmodel"
static const char *TRAINMODEL_VERSION_MESSAGE =
SUBPROGRAM " Version " PACKAGE_VERSION "\n"
"Written by Jared Simpson.\n"
"\n"
"Copyright 2016 Ontario Institute for Cancer Research\n";
static const char *TRAINMODEL_USAGE_MESSAGE =
"Usage: " PACKAGE_NAME " " SUBPROGRAM " [OPTIONS] input.fofn\n"
"Train a new pore model using the basecalled reads in input.fofn\n"
"\n"
" -v, --verbose display verbose output\n"
" --version display version\n"
" --help display this help and exit\n"
"\nReport bugs to " PACKAGE_BUGREPORT "\n\n";
namespace opt
{
static unsigned int verbose;
static std::string fofn_file;
}
static const char* shortopts = "v";
enum { OPT_HELP = 1, OPT_VERSION };
static const struct option longopts[] = {
{ "verbose", no_argument, NULL, 'v' },
{ "help", no_argument, NULL, OPT_HELP },
{ "version", no_argument, NULL, OPT_VERSION },
{ NULL, 0, NULL, 0 }
};
void parse_trainmodel_options(int argc, char** argv)
{
bool die = false;
for (char c; (c = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1;) {
std::istringstream arg(optarg != NULL ? optarg : "");
switch (c) {
case '?': die = true; break;
case 'v': opt::verbose++; break;
case OPT_HELP:
std::cout << TRAINMODEL_USAGE_MESSAGE;
exit(EXIT_SUCCESS);
case OPT_VERSION:
std::cout << TRAINMODEL_VERSION_MESSAGE;
exit(EXIT_SUCCESS);
}
}
if (argc - optind < 1) {
std::cerr << SUBPROGRAM ": not enough arguments\n";
die = true;
}
if (argc - optind > 1) {
std::cerr << SUBPROGRAM ": too many arguments\n";
die = true;
}
if (die)
{
std::cout << "\n" << TRAINMODEL_USAGE_MESSAGE;
exit(EXIT_FAILURE);
}
opt::fofn_file = argv[optind++];
}
std::vector<EventAlignment> generate_alignment_to_basecalls(const SquiggleRead* read,
const size_t k,
const size_t strand_idx,
const std::vector<bool>* use_kmer = NULL)
{
size_t num_kmers_in_alphabet = gDNAAlphabet.get_num_strings(k);
std::vector<EventAlignment> alignment;
const std::string& read_sequence = read->read_sequence;
size_t n_kmers = read_sequence.size() - k + 1;
for(size_t ki = 0; ki < n_kmers; ++ki) {
IndexPair event_range_for_kmer = read->base_to_event_map[ki].indices[strand_idx];
// skip kmers without events and with multiple events
if(event_range_for_kmer.start == -1 ||
event_range_for_kmer.start != event_range_for_kmer.stop) {
continue;
}
std::string kmer = read_sequence.substr(ki, k);
size_t kmer_rank = gDNAAlphabet.kmer_rank(kmer.c_str(), k);
assert(kmer_rank < num_kmers_in_alphabet);
size_t event_idx = event_range_for_kmer.start;
// Check if this kmer is marked as being useful
if(use_kmer == NULL || use_kmer->at(kmer_rank)) {
EventAlignment ea;
// ref data
ea.ref_name = ""; // not needed
ea.ref_kmer = kmer;
ea.ref_position = ki;
ea.read_idx = -1; // not needed
ea.strand_idx = strand_idx;
ea.event_idx = event_idx;
ea.rc = false;
ea.model_kmer = kmer;
ea.hmm_state = 'M'; // recalibration code only uses "M" alignments
alignment.push_back(ea);
}
}
return alignment;
}
KmerTrainingData alignment_to_training_data(const SquiggleRead* read,
const std::vector<EventAlignment>& alignment,
const size_t k,
size_t read_idx)
{
size_t num_kmers_in_alphabet = gDNAAlphabet.get_num_strings(k);
KmerTrainingData kmer_training_data(num_kmers_in_alphabet);
for(auto const& a : alignment) {
size_t kmer_rank = gDNAAlphabet.kmer_rank(a.model_kmer.c_str(), k);
assert(kmer_rank < num_kmers_in_alphabet);
double level = read->events[a.strand_idx][a.event_idx].mean;
double stdv = read->events[a.strand_idx][a.event_idx].stdv;
StateTrainingData std(level, stdv, read->pore_model[a.strand_idx].var);
kmer_training_data[kmer_rank].push_back(std);
//fprintf(tsv_writer, "%zu\t%s\t%.2lf\t%.5lf\n", read_idx, kmer.c_str(), level, read->events[training_strand][event_idx].duration);
}
return kmer_training_data;
}
int trainmodel_main(int argc, char** argv)
{
parse_trainmodel_options(argc, argv);
std::ifstream fofn_reader(opt::fofn_file);
std::string fast5_name;
// Read input
std::vector<SquiggleRead*> reads;
while(getline(fofn_reader, fast5_name)) {
fprintf(stderr, "Loading %s\n", fast5_name.c_str());
reads.push_back(new SquiggleRead(fast5_name, fast5_name));
}
fprintf(stderr, "Loaded %zu reads\n", reads.size());
//
unsigned int basecalled_k = 5; // TODO: infer this
size_t num_kmers = gDNAAlphabet.get_num_strings(basecalled_k);
unsigned int training_strand = T_IDX; // template training for now
// This vector is indexed by read, then kmer, then event
std::vector<KmerTrainingData> read_training_data;
FILE* tsv_writer = fopen("trainmodel.tsv", "w");
fprintf(tsv_writer, "read_idx\tkmer\tlevel_mean\tduration\n");
size_t read_idx = 0;
for(auto* read : reads) {
// extract alignment of events to k-mers
std::vector<EventAlignment> alignment =
generate_alignment_to_basecalls(read,
basecalled_k,
training_strand,
NULL);
// convert the alignment into model training data for this read
KmerTrainingData training_data =
alignment_to_training_data(read,
alignment,
basecalled_k,
read_idx);
read_training_data.push_back(training_data);
read_idx++;
}
// Select the read with the most events as the "baseline" read for generating the model
size_t max_events = 0;
size_t max_events_index = 0;
for(size_t rti = 0; rti < read_training_data.size(); ++rti) {
auto& kmer_training_data = read_training_data[rti];
size_t total_events = 0;
for(size_t ki = 0; ki < kmer_training_data.size(); ++ki) {
total_events += kmer_training_data[ki].size();
}
printf("read %zu has %zu events (max: %zu, %zu)\n", rti, total_events, max_events, max_events_index);
if(total_events > max_events) {
max_events = total_events;
max_events_index = rti;
}
}
// Set the initial pore model based on the read with the most events
PoreModel pore_model(basecalled_k);
pore_model.states.resize(num_kmers);
pore_model.scaled_states.resize(num_kmers);
pore_model.scaled_params.resize(num_kmers);
pore_model.shift = 0.0;
pore_model.scale = 1.0;
pore_model.drift = 0.0;
pore_model.var = 1.0;
pore_model.scale_sd = 1.0;
pore_model.var_sd = 1.0;
auto& kmer_training_data_for_selected = read_training_data[max_events_index];
std::vector<bool> use_kmer(num_kmers, false);
for(size_t ki = 0; ki < kmer_training_data_for_selected.size(); ++ki) {
std::vector<double> values;
std::stringstream ss;
for(size_t ei = 0; ei < kmer_training_data_for_selected[ki].size(); ++ei) {
values.push_back(kmer_training_data_for_selected[ki][ei].level_mean);
ss << values.back() << " ";
}
// Set the kmer's mean parameter to be the median of the recorded values
std::sort(values.begin(), values.end());
size_t n = values.size();
double median;
if(n == 0) {
median = 0.0f;
} else {
if(n % 2 == 0) {
median = (values[n / 2 - 1] + values[n/2]) / 2.0f;
} else {
median = values[n/2];
}
// mark this kmer as valid
use_kmer[ki] = true;
pore_model.states[ki].level_mean = median;
pore_model.states[ki].level_stdv = 1.0;
printf("k: %zu median: %.2lf values: %s\n", ki, median, ss.str().c_str());
}
}
pore_model.bake_gaussian_parameters();
// Apply model to each read
for(auto* read: reads) {
read->pore_model[training_strand] = pore_model;
}
// Recalibrate read
for(auto* read: reads) {
// generate an alignment between the RNN output and the basecalled read
std::vector<EventAlignment> alignment =
generate_alignment_to_basecalls(read,
basecalled_k,
training_strand,
&use_kmer);
// recalibrate shift/scale/etc
recalibrate_model(*read,
training_strand,
alignment,
&gDNAAlphabet,
false);
const PoreModel& read_model = read->pore_model[training_strand];
printf("[recalibration] events: %zu alignment: %zu shift: %.2lf scale: %.2lf drift: %.4lf var: %.2lf\n",
read->events[training_strand].size(),
alignment.size(),
read_model.shift,
read_model.scale,
read_model.drift,
read_model.var);
}
// Deallocate input reads
for(auto* read : reads) {
delete read;
}
return 0;
}
<|endoftext|>
|
<commit_before>/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2016, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero Public License for more details.
*
* You should have received a copy of the GNU Affero Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ---------------------------------------------------------------------
*/
/** @file
* Define the ScalarEncoder and PeriodicScalarEncoder
*/
#ifndef NTA_ENCODERS_SCALAR
#define NTA_ENCODERS_SCALAR
#include <nupic/encoders/Base.hpp>
namespace nupic
{
/** Encodes a floating point number as a contiguous block of 1s.
*
* @b Description
* A ScalarEncoder encodes a numeric (floating point) value into an array
* of bits. The output is 0's except for a contiguous block of 1's. The
* location of this contiguous block varies continuously with the input value.
*
* Conceptually, the set of possible outputs is a set of "buckets". If there
* are m buckets, the ScalarEncoder distributes m points along the domain
* [minValue, maxValue], including the endpoints. To figure out the bucket
* index of an input, it rounds the input to the nearest of these points.
*
* This approach is different from the PeriodicScalarEncoder because two
* buckets, the first and last, are half as wide as the rest, since fewer
* numbers in the input domain will round to these endpoints. This behavior
* makes sense because, for example, with the input space [1, 10] and 10
* buckets, 1.49 is in the first bucket and 1.51 is in the second.
*/
class ScalarEncoder : public Encoder
{
public:
/**
* Constructs a ScalarEncoder
*
* @param w The number of bits that are set to encode a single value -- the
* "width" of the output signal
* @param minValue The minimum value of the input signal, inclusive.
* @param maxValue The maximum value of the input signal, inclusive.
* @param clipInput Whether to allow input values outside the [minValue, maxValue]
* range. If true, the input will be clipped to minValue or maxValue.
*
* There are three mutually exclusive parameters that determine the overall
* size of of the output. Only one of these should be nonzero:
*
* @param n The number of bits in the output. Must be greater than or equal to w.
* @param radius Two inputs separated by more than the radius have
* non-overlapping representations. Two inputs separated by less than the
* radius will in general overlap in at least some of their bits. You can
* think of this as the radius of the input.
* @param resolution Two inputs separated by greater than, or equal to the
* resolution are guaranteed to have different representations.
*/
ScalarEncoder(int w, double minValue, double maxValue, int n, double radius,
double resolution, bool clipInput);
~ScalarEncoder() override;
virtual void encodeIntoArray(const ArrayBase & input, UInt output[],
bool learn) override;
virtual int getWidth() const override { return n_; }
private:
int w_;
int n_;
double minValue_;
double maxValue_;
double resolution_;
bool clipInput_;
}; // end class ScalarEncoder
/** Encodes a floating point number as a block of 1s that might wrap around.
*
* @b Description
* A PeriodicScalarEncoder encodes a numeric (floating point) value into an
* array of bits. The output is 0's except for a contiguous block of 1's that
* may wrap around the edge. The location of this contiguous block varies
* continuously with the input value.
*
* Conceptually, the set of possible outputs is a set of "buckets". If there
* are m buckets, the PeriodicScalarEncoder plots m equal-width bands along
* the domain [minValue, maxValue]. The bucket index of an input is simply its
* band index.
*
* Because of the equal-width buckets, the rounding differs from the
* ScalarEncoder. In cases where the ScalarEncoder would put 1.49 in the first
* bucket and 1.51 in the second, the PeriodicScalarEncoder will put 1.99 in
* the first bucket and 2.0 in the second.
*/
class PeriodicScalarEncoder : public Encoder
{
public:
/**
* Constructs a PeriodicScalarEncoder
*
* @param w The number of bits that are set to encode a single value -- the
* "width" of the output signal
* @param minValue The minimum value of the input signal, inclusive.
* @param maxValue The maximum value of the input signal, exclusive. All
* inputs will be strictly less than this value.
*
* There are three mutually exclusive parameters that determine the overall
* size of the output. Only one of these should be nonzero:
*
* @param n The number of bits in the output. Must be greater than or equal
* to w.
* @param radius Two inputs separated by more than the radius have
* non-overlapping representations. Two inputs separated by less than the
* radius will in general overlap in at least some of their bits. You can
* think of this as the radius of the input.
* @param resolution Two inputs separated by greater than, or equal to the
* resolution are guaranteed to have different representations.
*/
PeriodicScalarEncoder(int w, double minValue, double maxValue, int n,
double radius, double resolution);
~PeriodicScalarEncoder() override;
virtual void encodeIntoArray(const ArrayBase & input, UInt output[],
bool learn) override;
virtual int getWidth() const override { return n_; }
private:
int w_;
int n_;
double minValue_;
double maxValue_;
double resolution_;
}; // end class PeriodicScalarEncoder
} // end namespace nupic
#endif // NTA_ENCODERS_SCALAR
<commit_msg>Explicitly mark all derived virtual methods as virtual.<commit_after>/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2016, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero Public License for more details.
*
* You should have received a copy of the GNU Affero Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ---------------------------------------------------------------------
*/
/** @file
* Define the ScalarEncoder and PeriodicScalarEncoder
*/
#ifndef NTA_ENCODERS_SCALAR
#define NTA_ENCODERS_SCALAR
#include <nupic/encoders/Base.hpp>
namespace nupic
{
/** Encodes a floating point number as a contiguous block of 1s.
*
* @b Description
* A ScalarEncoder encodes a numeric (floating point) value into an array
* of bits. The output is 0's except for a contiguous block of 1's. The
* location of this contiguous block varies continuously with the input value.
*
* Conceptually, the set of possible outputs is a set of "buckets". If there
* are m buckets, the ScalarEncoder distributes m points along the domain
* [minValue, maxValue], including the endpoints. To figure out the bucket
* index of an input, it rounds the input to the nearest of these points.
*
* This approach is different from the PeriodicScalarEncoder because two
* buckets, the first and last, are half as wide as the rest, since fewer
* numbers in the input domain will round to these endpoints. This behavior
* makes sense because, for example, with the input space [1, 10] and 10
* buckets, 1.49 is in the first bucket and 1.51 is in the second.
*/
class ScalarEncoder : public Encoder
{
public:
/**
* Constructs a ScalarEncoder
*
* @param w The number of bits that are set to encode a single value -- the
* "width" of the output signal
* @param minValue The minimum value of the input signal, inclusive.
* @param maxValue The maximum value of the input signal, inclusive.
* @param clipInput Whether to allow input values outside the [minValue, maxValue]
* range. If true, the input will be clipped to minValue or maxValue.
*
* There are three mutually exclusive parameters that determine the overall
* size of of the output. Only one of these should be nonzero:
*
* @param n The number of bits in the output. Must be greater than or equal to w.
* @param radius Two inputs separated by more than the radius have
* non-overlapping representations. Two inputs separated by less than the
* radius will in general overlap in at least some of their bits. You can
* think of this as the radius of the input.
* @param resolution Two inputs separated by greater than, or equal to the
* resolution are guaranteed to have different representations.
*/
ScalarEncoder(int w, double minValue, double maxValue, int n, double radius,
double resolution, bool clipInput);
~ScalarEncoder() override;
virtual void encodeIntoArray(const ArrayBase & input, UInt output[],
bool learn) override;
virtual int getWidth() const override { return n_; }
private:
int w_;
int n_;
double minValue_;
double maxValue_;
double resolution_;
bool clipInput_;
}; // end class ScalarEncoder
/** Encodes a floating point number as a block of 1s that might wrap around.
*
* @b Description
* A PeriodicScalarEncoder encodes a numeric (floating point) value into an
* array of bits. The output is 0's except for a contiguous block of 1's that
* may wrap around the edge. The location of this contiguous block varies
* continuously with the input value.
*
* Conceptually, the set of possible outputs is a set of "buckets". If there
* are m buckets, the PeriodicScalarEncoder plots m equal-width bands along
* the domain [minValue, maxValue]. The bucket index of an input is simply its
* band index.
*
* Because of the equal-width buckets, the rounding differs from the
* ScalarEncoder. In cases where the ScalarEncoder would put 1.49 in the first
* bucket and 1.51 in the second, the PeriodicScalarEncoder will put 1.99 in
* the first bucket and 2.0 in the second.
*/
class PeriodicScalarEncoder : public Encoder
{
public:
/**
* Constructs a PeriodicScalarEncoder
*
* @param w The number of bits that are set to encode a single value -- the
* "width" of the output signal
* @param minValue The minimum value of the input signal, inclusive.
* @param maxValue The maximum value of the input signal, exclusive. All
* inputs will be strictly less than this value.
*
* There are three mutually exclusive parameters that determine the overall
* size of the output. Only one of these should be nonzero:
*
* @param n The number of bits in the output. Must be greater than or equal
* to w.
* @param radius Two inputs separated by more than the radius have
* non-overlapping representations. Two inputs separated by less than the
* radius will in general overlap in at least some of their bits. You can
* think of this as the radius of the input.
* @param resolution Two inputs separated by greater than, or equal to the
* resolution are guaranteed to have different representations.
*/
PeriodicScalarEncoder(int w, double minValue, double maxValue, int n,
double radius, double resolution);
virtual ~PeriodicScalarEncoder() override;
virtual void encodeIntoArray(const ArrayBase & input, UInt output[],
bool learn) override;
virtual int getWidth() const override { return n_; }
private:
int w_;
int n_;
double minValue_;
double maxValue_;
double resolution_;
}; // end class PeriodicScalarEncoder
} // end namespace nupic
#endif // NTA_ENCODERS_SCALAR
<|endoftext|>
|
<commit_before>/* bzflag
* Copyright (c) 1993 - 2003 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include <math.h>
#include "common.h"
#include "BaseBuilding.h"
#include "global.h"
#include "Intersect.h"
#include "QuadWallSceneNode.h"
#include "BZDBCache.h"
std::string BaseBuilding::typeName("BaseBuilding");
BaseBuilding::BaseBuilding(const float *p, float rotation,
const float *size, int _team) :
Obstacle(p, rotation, size[0], size[1], size[2]),
team(_team)
{
}
BaseBuilding::~BaseBuilding()
{
// do nothing
}
std::string BaseBuilding::getType() const
{
return typeName;
}
std::string BaseBuilding::getClassName()
{
return typeName;
}
float BaseBuilding::intersect(const Ray &r) const
{
return timeRayHitsBlock(r, getPosition(), getRotation(),
getWidth(), getBreadth(), getHeight());
}
void BaseBuilding::getNormal(const float *p, float *n) const
{
getNormalRect(p, getPosition(), getRotation(), getWidth(), getBreadth(), n);
}
void BaseBuilding::get3DNormal(const float* p, float* n) const
{
// This bit of cruft causes bullets to bounce of buildings in the z direction
if (fabs(p[2] - getPosition()[2]) < Epsilon) {
n[0] = 0.0f;
n[1] = 0.0f;
n[2] = -1.0f;
}
else if (fabs(p[2] - (getPosition()[2] + getHeight())) < Epsilon) {
n[0] = 0.0f;
n[1] = 0.0f;
n[2] = 1.0f;
} // end cruftiness
else
getNormal(p, n);
}
bool BaseBuilding::isInside(const float *p, float radius) const
{
return (p[2] < (getPosition()[2] + getHeight()))
&& ((p[2]+BZDBCache::tankHeight) > getPosition()[2])
&& testRectCircle(getPosition(), getRotation(), getWidth(), getBreadth(), p, radius);
}
bool BaseBuilding::isInside(const float *p, float angle,
float dx, float dy) const
{
return (p[2] < (getPosition()[2] + getHeight()))
&& ((p[2]+BZDBCache::tankHeight) >= getPosition()[2])
&& testRectRect(getPosition(), getRotation(), getWidth(), getBreadth(), p, angle, dx, dy);
}
bool BaseBuilding::isInside(const float* oldP, float,
const float *p, float angle,
float dx, float dy) const
{
float topBaseHeight = getPosition()[2] + getHeight();
float higherZ;
float lowerZ;
// if a base is just the ground (z == 0 && height == 0) no collision
// ground is already handled
if (topBaseHeight <= 0.0)
return false;
if (oldP[2] > p[2]) {
higherZ = oldP[2];
lowerZ = p[2];
} else {
higherZ = p[2];
lowerZ = oldP[2];
}
if (lowerZ >= topBaseHeight)
return false;
if ((higherZ + BZDBCache::tankHeight) < getPosition()[2])
return false;
return testRectRect(getPosition(), getRotation(), getWidth(), getBreadth(),
p, angle, dx, dy);
}
bool BaseBuilding::isCrossing(const float *p, float angle,
float dx, float dy,
float *plane) const
{
// if not inside or contained, then not crossing
if (!isInside(p, angle, dx, dy) ||
testRectInRect(getPosition(), getRotation(),
getWidth(), getBreadth(), p, angle, dx, dy))
return false;
if(!plane) return true;
// it's crossing -- choose which wall is being crossed (this
// is a guestimate, should really do a careful test). Just
// see which wall the point is closest to
const float *p2 = getPosition();
const float a2 = getRotation();
const float c = cosf(-a2), s = sinf(-a2);
const float x = c * (p[0] - p2[0]) - s * (p[1] - p2[1]);
const float y = c * (p[1] - p2[1]) - s * (p[0] - p2[0]);
float pw[2];
if(fabsf(fabsf(x) - getWidth()) < fabsf(fabsf(y) - getBreadth())) {
plane[0] = ((x < 0.0) ? -cosf(a2) : cosf(a2));
plane[1] = ((x < 0.0) ? -sinf(a2) : sinf(a2));
pw[0] = p2[0] + getWidth() * plane[0];
pw[1] = p2[1] + getWidth() * plane[1];
} else {
plane[0] = ((y < 0.0) ? sinf(a2) : -sinf(a2));
plane[1] = ((y < 0.0) ? cosf(a2) : -cosf(a2));
pw[0] = p2[0] + getBreadth() * plane[0];
pw[1] = p2[1] + getBreadth() * plane[1];
}
// now finish off plane equation
plane[2] = 0.0;
plane[3] = -(plane[0] * pw[0] + plane[1] * pw[1]);
return true;
}
bool BaseBuilding::getHitNormal(const float *pos1, float azimuth1,
const float *pos2, float azimuth2,
float halfWidth, float halfBreadth,
float *normal) const
{
return Obstacle::getHitNormal(pos1, azimuth1, pos2, azimuth2, halfWidth, halfBreadth,
getPosition(), getRotation(), getWidth(), getBreadth(),
getHeight(), normal) >= 0.0f;
}
ObstacleSceneNodeGenerator* BaseBuilding::newSceneNodeGenerator() const
{
return new BaseSceneNodeGenerator(this);
}
void BaseBuilding::getCorner(int index, float *pos) const
{
const float *base = getPosition();
const float c = cosf(getRotation());
const float s = sinf(getRotation());
const float w = getWidth();
const float b = getBreadth();
switch(index & 3) {
case 0:
pos[0] = base[0] + c * w - s * b;
pos[1] = base[1] + s * w + c * b;
break;
case 1:
pos[0] = base[0] - c * w - s * b;
pos[1] = base[1] - s * w + c * b;
break;
case 2:
pos[0] = base[0] - c * w + s * b;
pos[1] = base[1] - s * w - c * b;
break;
case 3:
pos[0] = base[0] + c * w + s * b;
pos[1] = base[1] + s * w - c * b;
break;
}
pos[2] = base[2];
if(index >= 4) pos[2] += getHeight();
}
const int BaseBuilding::getTeam() const {
return team;
}
BaseSceneNodeGenerator::BaseSceneNodeGenerator(const BaseBuilding* _base) : base(_base)
{
// do nothing
}
BaseSceneNodeGenerator::~BaseSceneNodeGenerator()
{
// do nothing
}
WallSceneNode* BaseSceneNodeGenerator::getNextNode(float uRepeats, float vRepeats, bool lod)
{
const GLfloat *pos = base->getPosition();
if(getNodeNumber() >= 1 && pos[2] == 0) return NULL;
if(getNodeNumber() >= 6) return NULL;
GLfloat bPoint[3], sCorner[3], tCorner[3];
if(base->getPosition()[2] == 0) {
incNodeNumber();
base->getCorner(0, bPoint);
base->getCorner(3, tCorner);
base->getCorner(1, sCorner);
} else {
switch(incNodeNumber()) {
case 1:
base->getCorner(4, bPoint);
base->getCorner(5, sCorner);
base->getCorner(7, tCorner);
break;
case 2:
base->getCorner(0, bPoint);
base->getCorner(3, sCorner);
base->getCorner(1, tCorner);
break;
case 3:
base->getCorner(0, bPoint);
base->getCorner(1, sCorner);
base->getCorner(4, tCorner);
break;
case 4:
base->getCorner(1, bPoint);
base->getCorner(2, sCorner);
base->getCorner(5, tCorner);
break;
case 5:
base->getCorner(2, bPoint);
base->getCorner(3, sCorner);
base->getCorner(6, tCorner);
break;
case 6:
base->getCorner(3, bPoint);
base->getCorner(0, sCorner);
base->getCorner(7, tCorner);
break;
}
}
GLfloat color[4];
switch(base->getTeam()) {
case 1:
color[0] = 0.7f; color[1] = 0.0f; color[2] = 0.0f;
break;
case 2:
color[0] = 0.0f; color[1] = 0.7f; color[2] = 0.0f;
break;
case 3:
color[0] = 0.0f; color[1] = 0.0f; color[2] = 0.7f;
break;
case 4:
color[0] = 0.7f; color[1] = 0.0f; color[2] = 0.7f;
break;
}
color[3] = 1.0;
GLfloat sEdge[3];
GLfloat tEdge[3];
sEdge[0] = sCorner[0] - bPoint[0];
sEdge[1] = sCorner[1] - bPoint[1];
sEdge[2] = sCorner[2] - bPoint[2];
tEdge[0] = tCorner[0] - bPoint[0];
tEdge[1] = tCorner[1] - bPoint[1];
tEdge[2] = tCorner[2] - bPoint[2];
WallSceneNode *retval = new QuadWallSceneNode(bPoint, sEdge, tEdge, uRepeats, vRepeats, lod);
retval->setColor(color);
return retval;
}
// Local variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>rendering of thick bases at 0 height fixed<commit_after>/* bzflag
* Copyright (c) 1993 - 2003 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include <math.h>
#include "common.h"
#include "BaseBuilding.h"
#include "global.h"
#include "Intersect.h"
#include "QuadWallSceneNode.h"
#include "BZDBCache.h"
std::string BaseBuilding::typeName("BaseBuilding");
BaseBuilding::BaseBuilding(const float *p, float rotation,
const float *size, int _team) :
Obstacle(p, rotation, size[0], size[1], size[2]),
team(_team)
{
}
BaseBuilding::~BaseBuilding()
{
// do nothing
}
std::string BaseBuilding::getType() const
{
return typeName;
}
std::string BaseBuilding::getClassName()
{
return typeName;
}
float BaseBuilding::intersect(const Ray &r) const
{
return timeRayHitsBlock(r, getPosition(), getRotation(),
getWidth(), getBreadth(), getHeight());
}
void BaseBuilding::getNormal(const float *p, float *n) const
{
getNormalRect(p, getPosition(), getRotation(), getWidth(), getBreadth(), n);
}
void BaseBuilding::get3DNormal(const float* p, float* n) const
{
// This bit of cruft causes bullets to bounce of buildings in the z direction
if (fabs(p[2] - getPosition()[2]) < Epsilon) {
n[0] = 0.0f;
n[1] = 0.0f;
n[2] = -1.0f;
}
else if (fabs(p[2] - (getPosition()[2] + getHeight())) < Epsilon) {
n[0] = 0.0f;
n[1] = 0.0f;
n[2] = 1.0f;
} // end cruftiness
else
getNormal(p, n);
}
bool BaseBuilding::isInside(const float *p, float radius) const
{
return (p[2] < (getPosition()[2] + getHeight()))
&& ((p[2]+BZDBCache::tankHeight) > getPosition()[2])
&& testRectCircle(getPosition(), getRotation(), getWidth(), getBreadth(), p, radius);
}
bool BaseBuilding::isInside(const float *p, float angle,
float dx, float dy) const
{
return (p[2] < (getPosition()[2] + getHeight()))
&& ((p[2]+BZDBCache::tankHeight) >= getPosition()[2])
&& testRectRect(getPosition(), getRotation(), getWidth(), getBreadth(), p, angle, dx, dy);
}
bool BaseBuilding::isInside(const float* oldP, float,
const float *p, float angle,
float dx, float dy) const
{
float topBaseHeight = getPosition()[2] + getHeight();
float higherZ;
float lowerZ;
// if a base is just the ground (z == 0 && height == 0) no collision
// ground is already handled
if (topBaseHeight <= 0.0)
return false;
if (oldP[2] > p[2]) {
higherZ = oldP[2];
lowerZ = p[2];
} else {
higherZ = p[2];
lowerZ = oldP[2];
}
if (lowerZ >= topBaseHeight)
return false;
if ((higherZ + BZDBCache::tankHeight) < getPosition()[2])
return false;
return testRectRect(getPosition(), getRotation(), getWidth(), getBreadth(),
p, angle, dx, dy);
}
bool BaseBuilding::isCrossing(const float *p, float angle,
float dx, float dy,
float *plane) const
{
// if not inside or contained, then not crossing
if (!isInside(p, angle, dx, dy) ||
testRectInRect(getPosition(), getRotation(),
getWidth(), getBreadth(), p, angle, dx, dy))
return false;
if(!plane) return true;
// it's crossing -- choose which wall is being crossed (this
// is a guestimate, should really do a careful test). Just
// see which wall the point is closest to
const float *p2 = getPosition();
const float a2 = getRotation();
const float c = cosf(-a2), s = sinf(-a2);
const float x = c * (p[0] - p2[0]) - s * (p[1] - p2[1]);
const float y = c * (p[1] - p2[1]) - s * (p[0] - p2[0]);
float pw[2];
if(fabsf(fabsf(x) - getWidth()) < fabsf(fabsf(y) - getBreadth())) {
plane[0] = ((x < 0.0) ? -cosf(a2) : cosf(a2));
plane[1] = ((x < 0.0) ? -sinf(a2) : sinf(a2));
pw[0] = p2[0] + getWidth() * plane[0];
pw[1] = p2[1] + getWidth() * plane[1];
} else {
plane[0] = ((y < 0.0) ? sinf(a2) : -sinf(a2));
plane[1] = ((y < 0.0) ? cosf(a2) : -cosf(a2));
pw[0] = p2[0] + getBreadth() * plane[0];
pw[1] = p2[1] + getBreadth() * plane[1];
}
// now finish off plane equation
plane[2] = 0.0;
plane[3] = -(plane[0] * pw[0] + plane[1] * pw[1]);
return true;
}
bool BaseBuilding::getHitNormal(const float *pos1, float azimuth1,
const float *pos2, float azimuth2,
float halfWidth, float halfBreadth,
float *normal) const
{
return Obstacle::getHitNormal(pos1, azimuth1, pos2, azimuth2, halfWidth, halfBreadth,
getPosition(), getRotation(), getWidth(), getBreadth(),
getHeight(), normal) >= 0.0f;
}
ObstacleSceneNodeGenerator* BaseBuilding::newSceneNodeGenerator() const
{
return new BaseSceneNodeGenerator(this);
}
void BaseBuilding::getCorner(int index, float *pos) const
{
const float *base = getPosition();
const float c = cosf(getRotation());
const float s = sinf(getRotation());
const float w = getWidth();
const float b = getBreadth();
switch(index & 3) {
case 0:
pos[0] = base[0] + c * w - s * b;
pos[1] = base[1] + s * w + c * b;
break;
case 1:
pos[0] = base[0] - c * w - s * b;
pos[1] = base[1] - s * w + c * b;
break;
case 2:
pos[0] = base[0] - c * w + s * b;
pos[1] = base[1] - s * w - c * b;
break;
case 3:
pos[0] = base[0] + c * w + s * b;
pos[1] = base[1] + s * w - c * b;
break;
}
pos[2] = base[2];
if(index >= 4) pos[2] += getHeight();
}
const int BaseBuilding::getTeam() const {
return team;
}
BaseSceneNodeGenerator::BaseSceneNodeGenerator(const BaseBuilding* _base) : base(_base)
{
// do nothing
}
BaseSceneNodeGenerator::~BaseSceneNodeGenerator()
{
// do nothing
}
WallSceneNode* BaseSceneNodeGenerator::getNextNode(float uRepeats, float vRepeats, bool lod)
{
const GLfloat *pos = base->getPosition();
const float height = base->getHeight();
if(getNodeNumber() >= 1 && height == 0) return NULL;
if(getNodeNumber() >= 6) return NULL;
GLfloat bPoint[3], sCorner[3], tCorner[3];
if (height == 0) {
incNodeNumber();
base->getCorner(0, bPoint);
base->getCorner(3, tCorner);
base->getCorner(1, sCorner);
} else {
switch(incNodeNumber()) {
case 1:
base->getCorner(4, bPoint);
base->getCorner(5, sCorner);
base->getCorner(7, tCorner);
break;
case 2:
base->getCorner(0, bPoint);
base->getCorner(3, sCorner);
base->getCorner(1, tCorner);
break;
case 3:
base->getCorner(0, bPoint);
base->getCorner(1, sCorner);
base->getCorner(4, tCorner);
break;
case 4:
base->getCorner(1, bPoint);
base->getCorner(2, sCorner);
base->getCorner(5, tCorner);
break;
case 5:
base->getCorner(2, bPoint);
base->getCorner(3, sCorner);
base->getCorner(6, tCorner);
break;
case 6:
base->getCorner(3, bPoint);
base->getCorner(0, sCorner);
base->getCorner(7, tCorner);
break;
}
}
GLfloat color[4];
switch(base->getTeam()) {
case 1:
color[0] = 0.7f; color[1] = 0.0f; color[2] = 0.0f;
break;
case 2:
color[0] = 0.0f; color[1] = 0.7f; color[2] = 0.0f;
break;
case 3:
color[0] = 0.0f; color[1] = 0.0f; color[2] = 0.7f;
break;
case 4:
color[0] = 0.7f; color[1] = 0.0f; color[2] = 0.7f;
break;
}
color[3] = 1.0;
GLfloat sEdge[3];
GLfloat tEdge[3];
sEdge[0] = sCorner[0] - bPoint[0];
sEdge[1] = sCorner[1] - bPoint[1];
sEdge[2] = sCorner[2] - bPoint[2];
tEdge[0] = tCorner[0] - bPoint[0];
tEdge[1] = tCorner[1] - bPoint[1];
tEdge[2] = tCorner[2] - bPoint[2];
WallSceneNode *retval = new QuadWallSceneNode(bPoint, sEdge, tEdge, uRepeats, vRepeats, lod);
retval->setColor(color);
return retval;
}
// Local variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>
|
<commit_before>#ifndef CONTAINERS_ARCHIVE_VERSIONED_HPP_
#define CONTAINERS_ARCHIVE_VERSIONED_HPP_
#include "containers/archive/archive.hpp"
#include "version.hpp"
namespace archive_internal {
// This is just used to implement serialize_cluster_version and
// deserialize_cluster_version.
// This defines how to serialize cluster_version_t (which conveniently has a
// contiguous set of valid representation, from v1_13 to v1_13_is_latest).
ARCHIVE_PRIM_MAKE_RANGED_SERIALIZABLE(cluster_version_t, int8_t,
cluster_version_t::v1_13,
cluster_version_t::v1_13_is_latest);
} // namespace archive_details
// These are generally universal. They must not have their behavior change -- except
// if we remove some cluster_version_t value, in which case... maybe would fail on a
// range error with the specific removed values. Or maybe, we would do something
// differently.
inline void serialize_cluster_version(write_message_t *wm, cluster_version_t v) {
archive_internal::serialize<cluster_version_t::LATEST>(wm, v);
}
inline archive_result_t deserialize_cluster_version(read_stream_t *s,
cluster_version_t *thing) {
return archive_internal::deserialize<cluster_version_t::LATEST>(s, thing);
}
// Serializes a value for a given version. DOES NOT SERIALIZE THE VERSION NUMBER!
template <class T>
void serialize_for_version(cluster_version_t version, write_message_t *wm,
const T &value) {
rassert(version == cluster_version_t::ONLY_VERSION);
switch (version) {
case cluster_version_t::v1_13:
serialize<cluster_version_t::v1_13>(wm, value);
}
}
// Deserializes a value, assuming it's serialized for a given version. (This doesn't
// deserialize any version numbers.)
template <class T>
archive_result_t deserialize_for_version(cluster_version_t version,
read_stream_t *s,
T *thing) {
rassert(version == cluster_version_t::ONLY_VERSION);
switch (version) {
case cluster_version_t::v1_13:
return deserialize<cluster_version_t::v1_13>(s, thing);
}
}
// RSI: Remove this, or something.
struct bogus_made_up_struct_t;
template <cluster_version_t W>
size_t serialized_size(const bogus_made_up_struct_t &);
// RSI: This is completely unused right now. (Should it be?)
template <class T>
size_t serialized_size_for_version(cluster_version_t version,
const T &thing) {
rassert(version == cluster_version_t::ONLY_VERSION);
switch (version) {
case cluster_version_t::v1_13:
return serialized_size<cluster_version_t::v1_13>(thing);
}
}
#define INSTANTIATE_SERIALIZE_SINCE_v1_13(typ) \
template void serialize<cluster_version_t::v1_13_is_latest>( \
write_message_t *, const typ &)
#define INSTANTIATE_DESERIALIZE_SINCE_v1_13(typ) \
template archive_result_t deserialize<cluster_version_t::v1_13_is_latest>( \
read_stream_t *, typ *)
#define INSTANTIATE_SERIALIZED_SIZE_SINCE_v1_13(typ) \
template size_t serialized_size<cluster_version_t::v1_13_is_latest>(const typ &)
// RSI: Probably rename this?
#define INSTANTIATE_SINCE_v1_13(typ) \
INSTANTIATE_SERIALIZE_SINCE_v1_13(typ); \
INSTANTIATE_DESERIALIZE_SINCE_v1_13(typ)
#define INSTANTIATE_SELF_SINCE_v1_13(typ) \
template void typ::rdb_serialize<cluster_version_t::v1_13_is_latest>( \
write_message_t *) const; \
template archive_result_t typ::rdb_deserialize<cluster_version_t::v1_13_is_latest>( \
read_stream_t *s)
#endif // CONTAINERS_ARCHIVE_VERSIONED_HPP_
<commit_msg>Removed RSI about removing something.<commit_after>#ifndef CONTAINERS_ARCHIVE_VERSIONED_HPP_
#define CONTAINERS_ARCHIVE_VERSIONED_HPP_
#include "containers/archive/archive.hpp"
#include "version.hpp"
namespace archive_internal {
// This is just used to implement serialize_cluster_version and
// deserialize_cluster_version. (cluster_version_t conveniently has a contiguous set
// of valid representation, from v1_13 to v1_13_is_latest).
ARCHIVE_PRIM_MAKE_RANGED_SERIALIZABLE(cluster_version_t, int8_t,
cluster_version_t::v1_13,
cluster_version_t::v1_13_is_latest);
class bogus_made_up_type_t;
} // namespace archive_details
// These are generally universal. They must not have their behavior change -- except
// if we remove some cluster_version_t value, in which case... maybe would fail on a
// range error with the specific removed values. Or maybe, we would do something
// differently.
inline void serialize_cluster_version(write_message_t *wm, cluster_version_t v) {
archive_internal::serialize<cluster_version_t::LATEST>(wm, v);
}
inline archive_result_t deserialize_cluster_version(read_stream_t *s,
cluster_version_t *thing) {
return archive_internal::deserialize<cluster_version_t::LATEST>(s, thing);
}
// Serializes a value for a given version. DOES NOT SERIALIZE THE VERSION NUMBER!
template <class T>
void serialize_for_version(cluster_version_t version, write_message_t *wm,
const T &value) {
rassert(version == cluster_version_t::ONLY_VERSION);
switch (version) {
case cluster_version_t::v1_13:
serialize<cluster_version_t::v1_13>(wm, value);
}
}
// Deserializes a value, assuming it's serialized for a given version. (This doesn't
// deserialize any version numbers.)
template <class T>
archive_result_t deserialize_for_version(cluster_version_t version,
read_stream_t *s,
T *thing) {
rassert(version == cluster_version_t::ONLY_VERSION);
switch (version) {
case cluster_version_t::v1_13:
return deserialize<cluster_version_t::v1_13>(s, thing);
}
}
// Some serialized_size needs to be visible, apparently, so that
// serialized_size_for_version will actually parse.
template <cluster_version_t W>
size_t serialized_size(const archive_internal::bogus_made_up_type_t &);
// RSI: This is completely unused right now. (Should it be?)
template <class T>
size_t serialized_size_for_version(cluster_version_t version,
const T &thing) {
rassert(version == cluster_version_t::ONLY_VERSION);
switch (version) {
case cluster_version_t::v1_13:
return serialized_size<cluster_version_t::v1_13>(thing);
}
}
#define INSTANTIATE_SERIALIZE_SINCE_v1_13(typ) \
template void serialize<cluster_version_t::v1_13_is_latest>( \
write_message_t *, const typ &)
#define INSTANTIATE_DESERIALIZE_SINCE_v1_13(typ) \
template archive_result_t deserialize<cluster_version_t::v1_13_is_latest>( \
read_stream_t *, typ *)
#define INSTANTIATE_SERIALIZED_SIZE_SINCE_v1_13(typ) \
template size_t serialized_size<cluster_version_t::v1_13_is_latest>(const typ &)
// RSI: Probably rename this?
#define INSTANTIATE_SINCE_v1_13(typ) \
INSTANTIATE_SERIALIZE_SINCE_v1_13(typ); \
INSTANTIATE_DESERIALIZE_SINCE_v1_13(typ)
#define INSTANTIATE_SELF_SINCE_v1_13(typ) \
template void typ::rdb_serialize<cluster_version_t::v1_13_is_latest>( \
write_message_t *) const; \
template archive_result_t typ::rdb_deserialize<cluster_version_t::v1_13_is_latest>( \
read_stream_t *s)
#endif // CONTAINERS_ARCHIVE_VERSIONED_HPP_
<|endoftext|>
|
<commit_before>//
// interpreter.cpp
// SimpleInformationRetrievalTools
//
// Created by ryecao on 6/9/15.
// Copyright (c) 2015 Zhendong Cao. All rights reserved.
//
#include "interpreter.h"
#include <iostream>
#include <sstream>
#include <string>
#include <cctype>
using namespace std;
vector<pair<string,string> > Interpreter::ProcessQuery(const string query){
istringstream query_stream(query);
string word;
vector<int> bool_op_pos;
vector<string> query_vector;
vector<string> parameters;
vector<pair<string,string> > result;
bool search_type_set = false;
bool synonym_set = false;
bool top_k_set = false;
int pos = 0;
while(query_stream >> word){
if (word == "AND" || word == "OR" || word == "NOT" ){
_search_type = BOOL;
search_type_set = true;
bool_op_pos.push_back(pos);
}
if (word[0] == '-') {
parameters.push_back(word);
}
else{
query_vector.push_back(word);
}
pos++;
}
for (auto ¶:parameters){
if(search_type_set == false){
if (para == "-PHRASE_SEARCH"){
_search_type = PHRASE_SEARCH;
search_type_set = true;
}
}
if (synonym_set == false){
if (para == "-SYNONYM_ON"){
_synonym_mode = SYNONYM_ON;
synonym_set = true;
}
else if (para == "-SYNONYM_OFF"){
_synonym_mode = SYNONYM_OFF;
synonym_set = true;
}
}
if (top_k_set == false){
if ( para == "-TOP_K_OFF"){
_top_k_mode = TOP_K_OFF;
top_k_set = true;
}
if ( para == "-TOP_K_HEAP"){
_top_k_mode = TOP_K_HEAP;
top_k_set = true;
}
if ( para == "-TOP_K_CHAMPION_LIST"){
_top_k_mode = TOP_K_CHAMPION_LIST;
top_k_set = true;
}
if ( para == "-TOP_K_STATIC_QUALITY_SCORE"){
_top_k_mode = TOP_K_STATIC_QUALITY_SCORE;
top_k_set = true;
}
if ( para == "-TOP_K_CLUSTER_PRUNING"){
_top_k_mode = TOP_K_CLUSTER_PRUNING;
top_k_set = true;
}
}
}
if (_search_type == BOOL){
string segment = "";
int bool_pos = 0;
for (int i = 0; i < query_vector.size(); ++i){
if(i == bool_op_pos[bool_pos]){
if (segment != ""){
if (bool_pos == 0){
result.push_back(make_pair("AND",segment));
}
else{
result.push_back(make_pair(query_vector[bool_op_pos[bool_pos-1]],segment.substr(0, segment.size()-1)));
}
}
bool_pos++;
segment = "";
continue;
}
segment += query_vector[i] + " ";
}
result.push_back(make_pair(query_vector[bool_op_pos[bool_pos-1]],segment));
}
else{
for (auto &q:query_vector){
result.push_back(make_pair("AND", q));
}
}
return result;
}
<commit_msg>fix filename capitalization problem<commit_after>//
// interpreter.cpp
// SimpleInformationRetrievalTools
//
// Created by ryecao on 6/9/15.
// Copyright (c) 2015 Zhendong Cao. All rights reserved.
//
#include "Interpreter.h"
#include <iostream>
#include <sstream>
#include <string>
#include <cctype>
using namespace std;
vector<pair<string,string> > Interpreter::ProcessQuery(const string query){
istringstream query_stream(query);
string word;
vector<int> bool_op_pos;
vector<string> query_vector;
vector<string> parameters;
vector<pair<string,string> > result;
bool search_type_set = false;
bool synonym_set = false;
bool top_k_set = false;
int pos = 0;
while(query_stream >> word){
if (word == "AND" || word == "OR" || word == "NOT" ){
_search_type = BOOL;
search_type_set = true;
bool_op_pos.push_back(pos);
}
if (word[0] == '-') {
parameters.push_back(word);
}
else{
query_vector.push_back(word);
}
pos++;
}
for (auto ¶:parameters){
if(search_type_set == false){
if (para == "-PHRASE_SEARCH"){
_search_type = PHRASE_SEARCH;
search_type_set = true;
}
}
if (synonym_set == false){
if (para == "-SYNONYM_ON"){
_synonym_mode = SYNONYM_ON;
synonym_set = true;
}
else if (para == "-SYNONYM_OFF"){
_synonym_mode = SYNONYM_OFF;
synonym_set = true;
}
}
if (top_k_set == false){
if ( para == "-TOP_K_OFF"){
_top_k_mode = TOP_K_OFF;
top_k_set = true;
}
if ( para == "-TOP_K_HEAP"){
_top_k_mode = TOP_K_HEAP;
top_k_set = true;
}
if ( para == "-TOP_K_CHAMPION_LIST"){
_top_k_mode = TOP_K_CHAMPION_LIST;
top_k_set = true;
}
if ( para == "-TOP_K_STATIC_QUALITY_SCORE"){
_top_k_mode = TOP_K_STATIC_QUALITY_SCORE;
top_k_set = true;
}
if ( para == "-TOP_K_CLUSTER_PRUNING"){
_top_k_mode = TOP_K_CLUSTER_PRUNING;
top_k_set = true;
}
}
}
if (_search_type == BOOL){
string segment = "";
int bool_pos = 0;
for (int i = 0; i < query_vector.size(); ++i){
if(i == bool_op_pos[bool_pos]){
if (segment != ""){
if (bool_pos == 0){
result.push_back(make_pair("AND",segment));
}
else{
result.push_back(make_pair(query_vector[bool_op_pos[bool_pos-1]],segment.substr(0, segment.size()-1)));
}
}
bool_pos++;
segment = "";
continue;
}
segment += query_vector[i] + " ";
}
result.push_back(make_pair(query_vector[bool_op_pos[bool_pos-1]],segment));
}
else{
for (auto &q:query_vector){
result.push_back(make_pair("AND", q));
}
}
return result;
}
<|endoftext|>
|
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2010 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/**
\file AnalyzeConverter.cpp
\author Tom Fogal
SCI Institute
University of Utah
*/
#include "AnalyzeConverter.h"
AnalyzeConverter::AnalyzeConverter()
{
m_vConverterDesc = "Analyze 7.5";
m_vSupportedExt.push_back("HDR");
}
struct analyze_hdr {
int hdr_size;
char data_type[10];
char db_name[18];
int extents;
short session_err;
char regular;
char hkey_un0;
short dim[8]; // yes, really.
short datatype;
short bpp;
float aspect[3];
float voxel_offset;
};
enum AnalyzeDataTypes {
DT_NONE=0,
DT_BINARY, // 1 bit/voxel
DT_UNSIGNED_CHAR, // 8 bit
DT_SIGNED_SHORT=4,
DT_SIGNED_INT=8,
DT_FLOAT=16,
DT_COMPLEX=32,
DT_DOUBLE=64,
DT_RGB=128,
DT_ALL=255
};
bool AnalyzeConverter::ConvertToRAW(const std::string& strSourceFilename,
const std::string&,
bool,
UINT64& iHeaderSkip,
UINT64& iComponentSize,
UINT64& iComponentCount,
bool& bConvertEndianness,
bool& bSigned, bool& bIsFloat,
UINT64VECTOR3& vVolumeSize,
FLOATVECTOR3& vVolumeAspect,
std::string& strTitle,
UVFTables::ElementSemanticTable& eType,
std::string& strIntermediateFile,
bool& bDeleteIntermediateFile)
{
strTitle = "from analyze converter";
eType = UVFTables::ES_UNDEFINED;
std::ifstream analyze(strSourceFilename.c_str(), std::ios::binary);
if(!analyze) {
T_ERROR("Could not open %s!", strSourceFilename.c_str());
return false;
}
struct analyze_hdr hdr;
analyze.read(reinterpret_cast<char*>(&hdr.hdr_size), 4);
analyze.read(hdr.data_type, 10);
analyze.read(hdr.db_name, 18);
analyze.read(reinterpret_cast<char*>(&hdr.extents), 4);
analyze.read(reinterpret_cast<char*>(&hdr.session_err), 2);
analyze.read(&hdr.regular, 1);
analyze.read(&hdr.hkey_un0, 1);
for(size_t i=0; i < 8; ++i) {
analyze.read(reinterpret_cast<char*>(&hdr.dim[i]), 2);
}
// 14 bytes of unused garbage.
analyze.seekg(14, std::ios_base::cur);
analyze.read(reinterpret_cast<char*>(&hdr.datatype), 2); // DT_xxx ..
analyze.read(reinterpret_cast<char*>(&hdr.bpp), 2);
analyze.seekg(2, std::ios_base::cur); // "dim_un0", unused.
analyze.read(reinterpret_cast<char*>(&hdr.aspect[0]), 4);
analyze.read(reinterpret_cast<char*>(&hdr.aspect[1]), 4);
analyze.read(reinterpret_cast<char*>(&hdr.aspect[2]), 4);
analyze.seekg(16, std::ios_base::cur); // 4 unused aspect values
// 'voxel_offset' really is a float that stores a byte offset. Seriously.
// Maybe some of the same people that wrote DICOM made Analyze as well.
analyze.read(reinterpret_cast<char*>(&hdr.voxel_offset), 4);
// The header size was meant to be used in case the analyze format
// was extended. It never was. Thus the headers are always 348
// bytes. This provides a convenient check for endianness; if the
// size isn't 348, then we need to endian convert everything.
bConvertEndianness = false;
if(hdr.hdr_size != 348) {
MESSAGE("Endianness is wrong, swapping...");
bConvertEndianness = true;
hdr.bpp = EndianConvert::Swap<short>(hdr.bpp);
hdr.dim[0] = EndianConvert::Swap<short>(hdr.dim[0]);
hdr.dim[1] = EndianConvert::Swap<short>(hdr.dim[1]);
hdr.dim[2] = EndianConvert::Swap<short>(hdr.dim[2]);
hdr.aspect[0] = EndianConvert::Swap<float>(hdr.aspect[0]);
hdr.aspect[1] = EndianConvert::Swap<float>(hdr.aspect[1]);
hdr.aspect[2] = EndianConvert::Swap<float>(hdr.aspect[2]);
hdr.voxel_offset = EndianConvert::Swap<float>(hdr.voxel_offset);
hdr.datatype = EndianConvert::Swap<short>(hdr.datatype);
}
iComponentCount = 1; // always, I guess?
iComponentSize = hdr.bpp;
vVolumeSize = UINT64VECTOR3(hdr.dim[0], hdr.dim[1], hdr.dim[2]);
vVolumeAspect = FLOATVECTOR3(hdr.aspect[0], hdr.aspect[1], hdr.aspect[2]);
{
// Check to make sure the aspect ratios make sense. Sometimes analyze
// seems to fill them with zeroes...
for(size_t i=0; i < 3; ++i) {
if(vVolumeAspect[i] == 0.0) {
WARNING("Aspect ratio is 0 for dimension %u, resetting to 1...", i);
vVolumeAspect[i] = 1.0f;
}
}
}
MESSAGE("%gx%gx%g aspect ratio", vVolumeAspect[0], vVolumeAspect[1],
vVolumeAspect[2]);
MESSAGE("%llu-bit %llux%llux%llu data.", iComponentSize,
vVolumeSize[0], vVolumeSize[1], vVolumeSize[2]);
{
UINT64 bits=0;
switch(hdr.datatype) {
case DT_BINARY: bits = 1;
bSigned = false;
bIsFloat = false;
break;
case DT_UNSIGNED_CHAR: bits = 8;
bSigned = false;
bIsFloat = false;
break;
case DT_SIGNED_SHORT: bits = 16;
bSigned = true;
bIsFloat = false;
break;
case DT_SIGNED_INT: bits = 32;
bSigned = true;
bIsFloat = false;
break;
case DT_FLOAT: bits = 32;
bSigned = true;
bIsFloat = true;
break;
case DT_COMPLEX:
T_ERROR("Don't know how to handle complex data.");
return false;
break;
case DT_DOUBLE: bits = 64;
bSigned = true;
bIsFloat = true;
break;
default:
WARNING("Unknown data type.");
bits = 0;
break;
}
if(iComponentSize != bits) {
T_ERROR("Bits per pixel and data type disagree! Broken file?");
analyze.close();
return false;
}
}
// If the voxel offset is negative, then there is padding between every slice
// in the data set. We would need to write an intermediate file to handle
// that; instead, we just don't handle it.
if(hdr.voxel_offset < 0.0) {
analyze.close();
T_ERROR("Analyze voxel offset is negative (%g). Intermediate file "
"required; this converter is broken.");
return false;
}
iHeaderSkip = static_cast<UINT64>(hdr.voxel_offset);
MESSAGE("Skipping %llu bytes.", iHeaderSkip);
strIntermediateFile = SysTools::RemoveExt(strSourceFilename) + ".img";
MESSAGE("Using intermediate file %s", strIntermediateFile.c_str());
bDeleteIntermediateFile = false;
return true;
}
bool AnalyzeConverter::ConvertToNative(const std::string&,
const std::string&,
UINT64,
UINT64,
UINT64, bool,
bool,
UINT64VECTOR3,
FLOATVECTOR3,
bool,
const bool)
{
return false;
}
<commit_msg>analyze: Fix dimension && aspect detection.<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2010 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/**
\file AnalyzeConverter.cpp
\author Tom Fogal
SCI Institute
University of Utah
*/
#include "AnalyzeConverter.h"
AnalyzeConverter::AnalyzeConverter()
{
m_vConverterDesc = "Analyze 7.5";
m_vSupportedExt.push_back("HDR");
}
struct analyze_hdr {
int hdr_size;
char data_type[10];
char db_name[18];
int extents;
short session_err;
char regular;
char hkey_un0;
short dim[8]; // yes, really.
short datatype;
short bpp;
float aspect[3];
float voxel_offset;
};
enum AnalyzeDataTypes {
DT_NONE=0,
DT_BINARY, // 1 bit/voxel
DT_UNSIGNED_CHAR, // 8 bit
DT_SIGNED_SHORT=4,
DT_SIGNED_INT=8,
DT_FLOAT=16,
DT_COMPLEX=32,
DT_DOUBLE=64,
DT_RGB=128,
DT_ALL=255
};
bool AnalyzeConverter::ConvertToRAW(const std::string& strSourceFilename,
const std::string&,
bool,
UINT64& iHeaderSkip,
UINT64& iComponentSize,
UINT64& iComponentCount,
bool& bConvertEndianness,
bool& bSigned, bool& bIsFloat,
UINT64VECTOR3& vVolumeSize,
FLOATVECTOR3& vVolumeAspect,
std::string& strTitle,
UVFTables::ElementSemanticTable& eType,
std::string& strIntermediateFile,
bool& bDeleteIntermediateFile)
{
strTitle = "from analyze converter";
eType = UVFTables::ES_UNDEFINED;
std::ifstream analyze(strSourceFilename.c_str(), std::ios::binary);
if(!analyze) {
T_ERROR("Could not open %s!", strSourceFilename.c_str());
return false;
}
struct analyze_hdr hdr;
analyze.read(reinterpret_cast<char*>(&hdr.hdr_size), 4);
analyze.read(hdr.data_type, 10);
analyze.read(hdr.db_name, 18);
analyze.read(reinterpret_cast<char*>(&hdr.extents), 4);
analyze.read(reinterpret_cast<char*>(&hdr.session_err), 2);
analyze.read(&hdr.regular, 1);
analyze.read(&hdr.hkey_un0, 1);
short num_dimensions;
analyze.read(reinterpret_cast<char*>(&num_dimensions), 2);
if(num_dimensions <= 2) {
T_ERROR("%dd data; must have at least 3 dimensions!");
return false;
}
for(size_t i=0; i < 7; ++i) {
analyze.read(reinterpret_cast<char*>(&hdr.dim[i]), 2);
}
// 14 bytes of unused garbage.
analyze.seekg(14, std::ios_base::cur);
analyze.read(reinterpret_cast<char*>(&hdr.datatype), 2); // DT_xxx ..
analyze.read(reinterpret_cast<char*>(&hdr.bpp), 2);
analyze.seekg(2, std::ios_base::cur); // "dim_un0", unused.
float num_aspect;
analyze.read(reinterpret_cast<char*>(&num_aspect), 4);
analyze.read(reinterpret_cast<char*>(&hdr.aspect[0]), 4);
analyze.read(reinterpret_cast<char*>(&hdr.aspect[1]), 4);
analyze.read(reinterpret_cast<char*>(&hdr.aspect[2]), 4);
analyze.seekg(12, std::ios_base::cur); // 4 unused aspect values
// 'voxel_offset' really is a float that stores a byte offset. Seriously.
// Maybe some of the same people that wrote DICOM made Analyze as well.
analyze.read(reinterpret_cast<char*>(&hdr.voxel_offset), 4);
// The header size was meant to be used in case the analyze format
// was extended. It never was. Thus the headers are always 348
// bytes. This provides a convenient check for endianness; if the
// size isn't 348, then we need to endian convert everything.
bConvertEndianness = false;
if(hdr.hdr_size != 348) {
MESSAGE("Endianness is wrong, swapping...");
bConvertEndianness = true;
hdr.bpp = EndianConvert::Swap<short>(hdr.bpp);
hdr.dim[0] = EndianConvert::Swap<short>(hdr.dim[0]);
hdr.dim[1] = EndianConvert::Swap<short>(hdr.dim[1]);
hdr.dim[2] = EndianConvert::Swap<short>(hdr.dim[2]);
hdr.aspect[0] = EndianConvert::Swap<float>(hdr.aspect[0]);
hdr.aspect[1] = EndianConvert::Swap<float>(hdr.aspect[1]);
hdr.aspect[2] = EndianConvert::Swap<float>(hdr.aspect[2]);
hdr.voxel_offset = EndianConvert::Swap<float>(hdr.voxel_offset);
hdr.datatype = EndianConvert::Swap<short>(hdr.datatype);
}
iComponentCount = 1; // always, I guess?
iComponentSize = hdr.bpp;
vVolumeSize = UINT64VECTOR3(hdr.dim[0], hdr.dim[1], hdr.dim[2]);
vVolumeAspect = FLOATVECTOR3(hdr.aspect[0], hdr.aspect[1], hdr.aspect[2]);
MESSAGE("%gx%gx%g aspect ratio", vVolumeAspect[0], vVolumeAspect[1],
vVolumeAspect[2]);
MESSAGE("%llu-bit %llux%llux%llu data.", iComponentSize,
vVolumeSize[0], vVolumeSize[1], vVolumeSize[2]);
{
UINT64 bits=0;
switch(hdr.datatype) {
case DT_BINARY: bits = 1;
bSigned = false;
bIsFloat = false;
MESSAGE("binary");
break;
case DT_UNSIGNED_CHAR: bits = 8;
bSigned = false;
bIsFloat = false;
MESSAGE("uchar");
break;
case DT_SIGNED_SHORT: bits = 16;
bSigned = true;
bIsFloat = false;
MESSAGE("signed short");
break;
case DT_SIGNED_INT: bits = 32;
bSigned = true;
bIsFloat = false;
MESSAGE("int");
break;
case DT_FLOAT: bits = 32;
bSigned = true;
bIsFloat = true;
MESSAGE("float");
break;
case DT_COMPLEX:
T_ERROR("Don't know how to handle complex data.");
return false;
break;
case DT_DOUBLE: bits = 64;
bSigned = true;
bIsFloat = true;
MESSAGE("double");
break;
default:
WARNING("Unknown data type.");
bits = 0;
break;
}
if(iComponentSize != bits) {
T_ERROR("Bits per pixel and data type disagree! Broken file?");
analyze.close();
return false;
}
}
// If the voxel offset is negative, then there is padding between every slice
// in the data set. We would need to write an intermediate file to handle
// that; instead, we just don't handle it.
if(hdr.voxel_offset < 0.0) {
analyze.close();
T_ERROR("Analyze voxel offset is negative (%g). Intermediate file "
"required; this converter is broken.");
return false;
}
iHeaderSkip = static_cast<UINT64>(hdr.voxel_offset);
MESSAGE("Skipping %llu bytes.", iHeaderSkip);
strIntermediateFile = SysTools::RemoveExt(strSourceFilename) + ".img";
MESSAGE("Using intermediate file %s", strIntermediateFile.c_str());
bDeleteIntermediateFile = false;
return true;
}
bool AnalyzeConverter::ConvertToNative(const std::string&,
const std::string&,
UINT64,
UINT64,
UINT64, bool,
bool,
UINT64VECTOR3,
FLOATVECTOR3,
bool,
const bool)
{
return false;
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <comphelper/random.hxx>
#include <svx/sdrpaintwindow.hxx>
#include <sdr/overlay/overlaymanagerbuffered.hxx>
#include <svx/svdpntv.hxx>
#include <vcl/gdimtf.hxx>
#include <vcl/svapp.hxx>
#include <vcl/settings.hxx>
#include <set>
#include <vector>
//rhbz#1007697 do this in two loops, one to collect the candidates
//and another to update them because updating a candidate can
//trigger the candidate to be deleted, so asking for its
//sibling after that is going to fail hard
class CandidateMgr
{
std::vector<VclPtr<vcl::Window> > m_aCandidates;
std::set<VclPtr<vcl::Window> > m_aDeletedCandidates;
DECL_LINK(WindowEventListener, VclSimpleEvent*);
public:
void PaintTransparentChildren(vcl::Window & rWindow, Rectangle const& rPixelRect);
~CandidateMgr();
};
IMPL_LINK(CandidateMgr, WindowEventListener, VclSimpleEvent*, pEvent)
{
VclWindowEvent* pWinEvent = dynamic_cast< VclWindowEvent* >( pEvent );
if (pWinEvent)
{
vcl::Window* pWindow = pWinEvent->GetWindow();
if (pWinEvent->GetId() == VCLEVENT_OBJECT_DYING)
{
m_aDeletedCandidates.insert(pWindow);
}
}
return 0;
}
CandidateMgr::~CandidateMgr()
{
for (auto aI = m_aCandidates.begin(); aI != m_aCandidates.end(); ++aI)
{
VclPtr<vcl::Window> pCandidate = *aI;
if (m_aDeletedCandidates.find(pCandidate) != m_aDeletedCandidates.end())
continue;
pCandidate->RemoveEventListener(LINK(this, CandidateMgr, WindowEventListener));
}
}
void PaintTransparentChildren(vcl::Window & rWindow, Rectangle const& rPixelRect)
{
if (!rWindow.IsChildTransparentModeEnabled())
return;
CandidateMgr aManager;
aManager.PaintTransparentChildren(rWindow, rPixelRect);
}
void CandidateMgr::PaintTransparentChildren(vcl::Window & rWindow, Rectangle const& rPixelRect)
{
vcl::Window * pCandidate = rWindow.GetWindow( GetWindowType::FirstChild );
while (pCandidate)
{
if (pCandidate->IsPaintTransparent())
{
const Rectangle aCandidatePosSizePixel(
pCandidate->GetPosPixel(),
pCandidate->GetSizePixel());
if (aCandidatePosSizePixel.IsOver(rPixelRect))
{
m_aCandidates.push_back(pCandidate);
pCandidate->AddEventListener(LINK(this, CandidateMgr, WindowEventListener));
}
}
pCandidate = pCandidate->GetWindow( GetWindowType::Next );
}
for (auto aI = m_aCandidates.begin(); aI != m_aCandidates.end(); ++aI)
{
pCandidate = *aI;
if (m_aDeletedCandidates.find(pCandidate) != m_aDeletedCandidates.end())
continue;
//rhbz#1007697 this can cause the window itself to be
//deleted. So we are listening to see if that happens
//and if so, then skip the update
pCandidate->Invalidate(InvalidateFlags::NoTransparent|InvalidateFlags::Children);
// important: actually paint the child here!
if (m_aDeletedCandidates.find(pCandidate) != m_aDeletedCandidates.end())
continue;
pCandidate->Update();
}
}
SdrPreRenderDevice::SdrPreRenderDevice(OutputDevice& rOriginal)
: mrOutputDevice(rOriginal),
mpPreRenderDevice(VclPtr<VirtualDevice>::Create())
{
}
SdrPreRenderDevice::~SdrPreRenderDevice()
{
mpPreRenderDevice.disposeAndClear();
}
void SdrPreRenderDevice::PreparePreRenderDevice()
{
// compare size of mpPreRenderDevice with size of visible area
if(mpPreRenderDevice->GetOutputSizePixel() != mrOutputDevice.GetOutputSizePixel())
{
mpPreRenderDevice->SetOutputSizePixel(mrOutputDevice.GetOutputSizePixel());
}
// Also compare the MapModes for zoom/scroll changes
if(mpPreRenderDevice->GetMapMode() != mrOutputDevice.GetMapMode())
{
mpPreRenderDevice->SetMapMode(mrOutputDevice.GetMapMode());
}
// #i29186#
mpPreRenderDevice->SetDrawMode(mrOutputDevice.GetDrawMode());
mpPreRenderDevice->SetSettings(mrOutputDevice.GetSettings());
}
void SdrPreRenderDevice::OutputPreRenderDevice(const vcl::Region& rExpandedRegion)
{
// region to pixels
const vcl::Region aRegionPixel(mrOutputDevice.LogicToPixel(rExpandedRegion));
//RegionHandle aRegionHandle(aRegionPixel.BeginEnumRects());
//Rectangle aRegionRectanglePixel;
// MapModes off
bool bMapModeWasEnabledDest(mrOutputDevice.IsMapModeEnabled());
bool bMapModeWasEnabledSource(mpPreRenderDevice->IsMapModeEnabled());
mrOutputDevice.EnableMapMode(false);
mpPreRenderDevice->EnableMapMode(false);
RectangleVector aRectangles;
aRegionPixel.GetRegionRectangles(aRectangles);
for(RectangleVector::const_iterator aRectIter(aRectangles.begin()); aRectIter != aRectangles.end(); ++aRectIter)
{
// for each rectangle, copy the area
const Point aTopLeft(aRectIter->TopLeft());
const Size aSize(aRectIter->GetSize());
mrOutputDevice.DrawOutDev(
aTopLeft, aSize,
aTopLeft, aSize,
*mpPreRenderDevice.get());
#ifdef DBG_UTIL
// #i74769#
static bool bDoPaintForVisualControlRegion(false);
if(bDoPaintForVisualControlRegion)
{
int nR = comphelper::rng::uniform_int_distribution(0, 0x7F-1);
int nG = comphelper::rng::uniform_int_distribution(0, 0x7F-1);
int nB = comphelper::rng::uniform_int_distribution(0, 0x7F-1);
const Color aColor(((((nR|0x80)<<8L)|(nG|0x80))<<8L)|(nB|0x80));
mrOutputDevice.SetLineColor(aColor);
mrOutputDevice.SetFillColor();
mrOutputDevice.DrawRect(*aRectIter);
}
#endif
}
mrOutputDevice.EnableMapMode(bMapModeWasEnabledDest);
mpPreRenderDevice->EnableMapMode(bMapModeWasEnabledSource);
}
void SdrPaintWindow::impCreateOverlayManager()
{
// not yet one created?
if(!mxOverlayManager.is())
{
// is it a window?
if(OUTDEV_WINDOW == GetOutputDevice().GetOutDevType())
{
vcl::Window* pWindow = dynamic_cast<vcl::Window*>(&GetOutputDevice());
// decide which OverlayManager to use
if(GetPaintView().IsBufferedOverlayAllowed() && mbUseBuffer && !pWindow->SupportsDoubleBuffering())
{
// buffered OverlayManager, buffers its background and refreshes from there
// for pure overlay changes (no system redraw). The 3rd parameter specifies
// whether that refresh itself will use a 2nd vdev to avoid flickering.
// Also hand over the old OverlayManager if existent; this means to take over
// the registered OverlayObjects from it
mxOverlayManager = sdr::overlay::OverlayManagerBuffered::create(GetOutputDevice(), GetPaintView().GetModel(), true);
}
else
{
// unbuffered OverlayManager, just invalidates places where changes
// take place
// Also hand over the old OverlayManager if existent; this means to take over
// the registered OverlayObjects from it
mxOverlayManager = sdr::overlay::OverlayManager::create(GetOutputDevice(), GetPaintView().GetModel());
}
OSL_ENSURE(mxOverlayManager.is(), "SdrPaintWindow::SdrPaintWindow: Could not allocate an overlayManager (!)");
// Request a repaint so that the buffered overlay manager fills
// its buffer properly. This is a workaround for missing buffer
// updates.
if (pWindow != NULL)
pWindow->Invalidate();
Color aColA(GetPaintView().getOptionsDrawinglayer().GetStripeColorA());
Color aColB(GetPaintView().getOptionsDrawinglayer().GetStripeColorB());
if(Application::GetSettings().GetStyleSettings().GetHighContrastMode())
{
aColA = aColB = Application::GetSettings().GetStyleSettings().GetHighlightColor();
aColB.Invert();
}
mxOverlayManager->setStripeColorA(aColA);
mxOverlayManager->setStripeColorB(aColB);
mxOverlayManager->setStripeLengthPixel(GetPaintView().getOptionsDrawinglayer().GetStripeLength());
}
}
}
SdrPaintWindow::SdrPaintWindow(SdrPaintView& rNewPaintView, OutputDevice& rOut)
: mrOutputDevice(rOut),
mrPaintView(rNewPaintView),
mpPreRenderDevice(0L),
mbTemporaryTarget(false), // #i72889#
mbUseBuffer(true)
{
}
SdrPaintWindow::~SdrPaintWindow()
{
mxOverlayManager.clear();
DestroyPreRenderDevice();
}
rtl::Reference< sdr::overlay::OverlayManager > SdrPaintWindow::GetOverlayManager() const
{
if(!mxOverlayManager.is())
{
// Create buffered overlay manager by default.
const_cast< SdrPaintWindow* >(this)->impCreateOverlayManager();
}
return mxOverlayManager;
}
Rectangle SdrPaintWindow::GetVisibleArea() const
{
Size aVisSizePixel(GetOutputDevice().GetOutputSizePixel());
return Rectangle(GetOutputDevice().PixelToLogic(Rectangle(Point(0,0), aVisSizePixel)));
}
bool SdrPaintWindow::OutputToRecordingMetaFile() const
{
GDIMetaFile* pMetaFile = mrOutputDevice.GetConnectMetaFile();
return (pMetaFile && pMetaFile->IsRecord() && !pMetaFile->IsPause());
}
void SdrPaintWindow::PreparePreRenderDevice()
{
const bool bPrepareBufferedOutput(
mrPaintView.IsBufferedOutputAllowed()
&& !OutputToPrinter()
&& !OutputToVirtualDevice()
&& !OutputToRecordingMetaFile());
if(bPrepareBufferedOutput)
{
if(!mpPreRenderDevice)
{
mpPreRenderDevice = new SdrPreRenderDevice(mrOutputDevice);
}
}
else
{
DestroyPreRenderDevice();
}
if(mpPreRenderDevice)
{
mpPreRenderDevice->PreparePreRenderDevice();
}
}
void SdrPaintWindow::DestroyPreRenderDevice()
{
if(mpPreRenderDevice)
{
delete mpPreRenderDevice;
mpPreRenderDevice = 0L;
}
}
void SdrPaintWindow::OutputPreRenderDevice(const vcl::Region& rExpandedRegion)
{
if(mpPreRenderDevice)
{
mpPreRenderDevice->OutputPreRenderDevice(rExpandedRegion);
}
}
// #i73602# add flag if buffer shall be used
void SdrPaintWindow::DrawOverlay(const vcl::Region& rRegion)
{
// ## force creation of OverlayManager since the first repaint needs to
// save the background to get a controlled start into overlay mechanism
impCreateOverlayManager();
if(mxOverlayManager.is() && !OutputToPrinter())
{
if(mpPreRenderDevice)
{
mxOverlayManager->completeRedraw(rRegion, &mpPreRenderDevice->GetPreRenderDevice());
}
else
{
mxOverlayManager->completeRedraw(rRegion);
}
}
}
void SdrPaintWindow::SetRedrawRegion(const vcl::Region& rNew)
{
maRedrawRegion = rNew;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#1309261 Unchecked dynamic_cast<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <comphelper/random.hxx>
#include <svx/sdrpaintwindow.hxx>
#include <sdr/overlay/overlaymanagerbuffered.hxx>
#include <svx/svdpntv.hxx>
#include <vcl/gdimtf.hxx>
#include <vcl/svapp.hxx>
#include <vcl/settings.hxx>
#include <set>
#include <vector>
//rhbz#1007697 do this in two loops, one to collect the candidates
//and another to update them because updating a candidate can
//trigger the candidate to be deleted, so asking for its
//sibling after that is going to fail hard
class CandidateMgr
{
std::vector<VclPtr<vcl::Window> > m_aCandidates;
std::set<VclPtr<vcl::Window> > m_aDeletedCandidates;
DECL_LINK(WindowEventListener, VclSimpleEvent*);
public:
void PaintTransparentChildren(vcl::Window & rWindow, Rectangle const& rPixelRect);
~CandidateMgr();
};
IMPL_LINK(CandidateMgr, WindowEventListener, VclSimpleEvent*, pEvent)
{
VclWindowEvent* pWinEvent = dynamic_cast< VclWindowEvent* >( pEvent );
if (pWinEvent)
{
vcl::Window* pWindow = pWinEvent->GetWindow();
if (pWinEvent->GetId() == VCLEVENT_OBJECT_DYING)
{
m_aDeletedCandidates.insert(pWindow);
}
}
return 0;
}
CandidateMgr::~CandidateMgr()
{
for (auto aI = m_aCandidates.begin(); aI != m_aCandidates.end(); ++aI)
{
VclPtr<vcl::Window> pCandidate = *aI;
if (m_aDeletedCandidates.find(pCandidate) != m_aDeletedCandidates.end())
continue;
pCandidate->RemoveEventListener(LINK(this, CandidateMgr, WindowEventListener));
}
}
void PaintTransparentChildren(vcl::Window & rWindow, Rectangle const& rPixelRect)
{
if (!rWindow.IsChildTransparentModeEnabled())
return;
CandidateMgr aManager;
aManager.PaintTransparentChildren(rWindow, rPixelRect);
}
void CandidateMgr::PaintTransparentChildren(vcl::Window & rWindow, Rectangle const& rPixelRect)
{
vcl::Window * pCandidate = rWindow.GetWindow( GetWindowType::FirstChild );
while (pCandidate)
{
if (pCandidate->IsPaintTransparent())
{
const Rectangle aCandidatePosSizePixel(
pCandidate->GetPosPixel(),
pCandidate->GetSizePixel());
if (aCandidatePosSizePixel.IsOver(rPixelRect))
{
m_aCandidates.push_back(pCandidate);
pCandidate->AddEventListener(LINK(this, CandidateMgr, WindowEventListener));
}
}
pCandidate = pCandidate->GetWindow( GetWindowType::Next );
}
for (auto aI = m_aCandidates.begin(); aI != m_aCandidates.end(); ++aI)
{
pCandidate = *aI;
if (m_aDeletedCandidates.find(pCandidate) != m_aDeletedCandidates.end())
continue;
//rhbz#1007697 this can cause the window itself to be
//deleted. So we are listening to see if that happens
//and if so, then skip the update
pCandidate->Invalidate(InvalidateFlags::NoTransparent|InvalidateFlags::Children);
// important: actually paint the child here!
if (m_aDeletedCandidates.find(pCandidate) != m_aDeletedCandidates.end())
continue;
pCandidate->Update();
}
}
SdrPreRenderDevice::SdrPreRenderDevice(OutputDevice& rOriginal)
: mrOutputDevice(rOriginal),
mpPreRenderDevice(VclPtr<VirtualDevice>::Create())
{
}
SdrPreRenderDevice::~SdrPreRenderDevice()
{
mpPreRenderDevice.disposeAndClear();
}
void SdrPreRenderDevice::PreparePreRenderDevice()
{
// compare size of mpPreRenderDevice with size of visible area
if(mpPreRenderDevice->GetOutputSizePixel() != mrOutputDevice.GetOutputSizePixel())
{
mpPreRenderDevice->SetOutputSizePixel(mrOutputDevice.GetOutputSizePixel());
}
// Also compare the MapModes for zoom/scroll changes
if(mpPreRenderDevice->GetMapMode() != mrOutputDevice.GetMapMode())
{
mpPreRenderDevice->SetMapMode(mrOutputDevice.GetMapMode());
}
// #i29186#
mpPreRenderDevice->SetDrawMode(mrOutputDevice.GetDrawMode());
mpPreRenderDevice->SetSettings(mrOutputDevice.GetSettings());
}
void SdrPreRenderDevice::OutputPreRenderDevice(const vcl::Region& rExpandedRegion)
{
// region to pixels
const vcl::Region aRegionPixel(mrOutputDevice.LogicToPixel(rExpandedRegion));
//RegionHandle aRegionHandle(aRegionPixel.BeginEnumRects());
//Rectangle aRegionRectanglePixel;
// MapModes off
bool bMapModeWasEnabledDest(mrOutputDevice.IsMapModeEnabled());
bool bMapModeWasEnabledSource(mpPreRenderDevice->IsMapModeEnabled());
mrOutputDevice.EnableMapMode(false);
mpPreRenderDevice->EnableMapMode(false);
RectangleVector aRectangles;
aRegionPixel.GetRegionRectangles(aRectangles);
for(RectangleVector::const_iterator aRectIter(aRectangles.begin()); aRectIter != aRectangles.end(); ++aRectIter)
{
// for each rectangle, copy the area
const Point aTopLeft(aRectIter->TopLeft());
const Size aSize(aRectIter->GetSize());
mrOutputDevice.DrawOutDev(
aTopLeft, aSize,
aTopLeft, aSize,
*mpPreRenderDevice.get());
#ifdef DBG_UTIL
// #i74769#
static bool bDoPaintForVisualControlRegion(false);
if(bDoPaintForVisualControlRegion)
{
int nR = comphelper::rng::uniform_int_distribution(0, 0x7F-1);
int nG = comphelper::rng::uniform_int_distribution(0, 0x7F-1);
int nB = comphelper::rng::uniform_int_distribution(0, 0x7F-1);
const Color aColor(((((nR|0x80)<<8L)|(nG|0x80))<<8L)|(nB|0x80));
mrOutputDevice.SetLineColor(aColor);
mrOutputDevice.SetFillColor();
mrOutputDevice.DrawRect(*aRectIter);
}
#endif
}
mrOutputDevice.EnableMapMode(bMapModeWasEnabledDest);
mpPreRenderDevice->EnableMapMode(bMapModeWasEnabledSource);
}
void SdrPaintWindow::impCreateOverlayManager()
{
// not yet one created?
if(!mxOverlayManager.is())
{
// is it a window?
if(OUTDEV_WINDOW == GetOutputDevice().GetOutDevType())
{
vcl::Window& rWindow = dynamic_cast<vcl::Window&>(GetOutputDevice());
// decide which OverlayManager to use
if(GetPaintView().IsBufferedOverlayAllowed() && mbUseBuffer && !rWindow.SupportsDoubleBuffering())
{
// buffered OverlayManager, buffers its background and refreshes from there
// for pure overlay changes (no system redraw). The 3rd parameter specifies
// whether that refresh itself will use a 2nd vdev to avoid flickering.
// Also hand over the old OverlayManager if existent; this means to take over
// the registered OverlayObjects from it
mxOverlayManager = sdr::overlay::OverlayManagerBuffered::create(GetOutputDevice(), GetPaintView().GetModel(), true);
}
else
{
// unbuffered OverlayManager, just invalidates places where changes
// take place
// Also hand over the old OverlayManager if existent; this means to take over
// the registered OverlayObjects from it
mxOverlayManager = sdr::overlay::OverlayManager::create(GetOutputDevice(), GetPaintView().GetModel());
}
OSL_ENSURE(mxOverlayManager.is(), "SdrPaintWindow::SdrPaintWindow: Could not allocate an overlayManager (!)");
// Request a repaint so that the buffered overlay manager fills
// its buffer properly. This is a workaround for missing buffer
// updates.
rWindow.Invalidate();
Color aColA(GetPaintView().getOptionsDrawinglayer().GetStripeColorA());
Color aColB(GetPaintView().getOptionsDrawinglayer().GetStripeColorB());
if(Application::GetSettings().GetStyleSettings().GetHighContrastMode())
{
aColA = aColB = Application::GetSettings().GetStyleSettings().GetHighlightColor();
aColB.Invert();
}
mxOverlayManager->setStripeColorA(aColA);
mxOverlayManager->setStripeColorB(aColB);
mxOverlayManager->setStripeLengthPixel(GetPaintView().getOptionsDrawinglayer().GetStripeLength());
}
}
}
SdrPaintWindow::SdrPaintWindow(SdrPaintView& rNewPaintView, OutputDevice& rOut)
: mrOutputDevice(rOut),
mrPaintView(rNewPaintView),
mpPreRenderDevice(0L),
mbTemporaryTarget(false), // #i72889#
mbUseBuffer(true)
{
}
SdrPaintWindow::~SdrPaintWindow()
{
mxOverlayManager.clear();
DestroyPreRenderDevice();
}
rtl::Reference< sdr::overlay::OverlayManager > SdrPaintWindow::GetOverlayManager() const
{
if(!mxOverlayManager.is())
{
// Create buffered overlay manager by default.
const_cast< SdrPaintWindow* >(this)->impCreateOverlayManager();
}
return mxOverlayManager;
}
Rectangle SdrPaintWindow::GetVisibleArea() const
{
Size aVisSizePixel(GetOutputDevice().GetOutputSizePixel());
return Rectangle(GetOutputDevice().PixelToLogic(Rectangle(Point(0,0), aVisSizePixel)));
}
bool SdrPaintWindow::OutputToRecordingMetaFile() const
{
GDIMetaFile* pMetaFile = mrOutputDevice.GetConnectMetaFile();
return (pMetaFile && pMetaFile->IsRecord() && !pMetaFile->IsPause());
}
void SdrPaintWindow::PreparePreRenderDevice()
{
const bool bPrepareBufferedOutput(
mrPaintView.IsBufferedOutputAllowed()
&& !OutputToPrinter()
&& !OutputToVirtualDevice()
&& !OutputToRecordingMetaFile());
if(bPrepareBufferedOutput)
{
if(!mpPreRenderDevice)
{
mpPreRenderDevice = new SdrPreRenderDevice(mrOutputDevice);
}
}
else
{
DestroyPreRenderDevice();
}
if(mpPreRenderDevice)
{
mpPreRenderDevice->PreparePreRenderDevice();
}
}
void SdrPaintWindow::DestroyPreRenderDevice()
{
if(mpPreRenderDevice)
{
delete mpPreRenderDevice;
mpPreRenderDevice = 0L;
}
}
void SdrPaintWindow::OutputPreRenderDevice(const vcl::Region& rExpandedRegion)
{
if(mpPreRenderDevice)
{
mpPreRenderDevice->OutputPreRenderDevice(rExpandedRegion);
}
}
// #i73602# add flag if buffer shall be used
void SdrPaintWindow::DrawOverlay(const vcl::Region& rRegion)
{
// ## force creation of OverlayManager since the first repaint needs to
// save the background to get a controlled start into overlay mechanism
impCreateOverlayManager();
if(mxOverlayManager.is() && !OutputToPrinter())
{
if(mpPreRenderDevice)
{
mxOverlayManager->completeRedraw(rRegion, &mpPreRenderDevice->GetPreRenderDevice());
}
else
{
mxOverlayManager->completeRedraw(rRegion);
}
}
}
void SdrPaintWindow::SetRedrawRegion(const vcl::Region& rNew)
{
maRedrawRegion = rNew;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>#include <iostream>
#include <random>
#include <fstream>
#include <cstdlib>
#include <cmath>
#include <algorithm>
int main(int argc, char *argv[]){
int SEED = atoi(argv[1]); // Seed
int N = atoi(argv[2]); // Number of nodes
int M = atoi(argv[3]); // Number of nodes
int m0 = 5; // Initial number of nodes
double alpha = 1.; // Switching probability
// Random generators
std::default_random_engine generator;
std::uniform_real_distribution<double> ureal(0., 1.);
// Connections
std::vector<std::vector<int>> edge_list(N);
// Index variables
int i, j, k;
// Connecting the initial core
for ( j = 0; j < m0; j++ )
{
for ( i = j+1; i < m0; i++ )
{
edge_list[i].push_back(j);
edge_list[j].push_back(i);
}
}
// Growing the network
for ( j = m0; j < N; j++)
{
if ( ureal(generator) <= alpha)
{
// Erdos-Renyi branch
for ( k = 0; k < M; k++ )
{
// Choosing a pair
i = (j-1)*ureal(generator);
edge_list[i].push_back(j);
edge_list[j].push_back(i);
}
}
else {
// Barabasi-Albert branch
}
}
std::ofstream outFile;
outFile.open(argv[4]);
for(int k = 0; k < N; k++)
for(std::vector<int>::iterator it = edge_list[k].begin(); it != edge_list[k].end(); ++it)
outFile << k << " " << *it << std::endl;
outFile.close();
return 0;
}
<commit_msg>Added malloc<commit_after>#include <iostream>
#include <random>
#include <fstream>
#include <cstdlib>
#include <cmath>
#include <algorithm>
int main(int argc, char *argv[]){
int SEED = atoi(argv[1]); // Seed
int N = atoi(argv[2]); // Number of nodes
int M = atoi(argv[3]); // Number of nodes
double *V;
V = (double *) malloc(N*sizeof(double));
int m0 = 5; // Initial number of nodes
double alpha = 1.; // Switching probability
// Random generators
std::default_random_engine generator;
std::uniform_real_distribution<double> ureal(0., 1.);
// Connections
std::vector<std::vector<int>> edge_list(N);
// Index variables
int i, j, k;
// Connecting the initial core
for ( j = 0; j < m0; j++ )
{
for ( i = j+1; i < m0; i++ )
{
edge_list[i].push_back(j);
edge_list[j].push_back(i);
}
}
// Growing the network
for ( j = m0; j < N; j++)
{
if ( ureal(generator) <= alpha)
{
// Erdos-Renyi branch
for ( k = 0; k < M; k++ )
{
// Choosing a pair
i = (j-1)*ureal(generator);
edge_list[i].push_back(j);
edge_list[j].push_back(i);
}
}
else {
// Barabasi-Albert branch
}
}
std::ofstream outFile;
outFile.open(argv[4]);
for(int k = 0; k < N; k++)
for(std::vector<int>::iterator it = edge_list[k].begin(); it != edge_list[k].end(); ++it)
outFile << k << " " << *it << std::endl;
outFile.close();
return 0;
}
<|endoftext|>
|
<commit_before>// Time: O(n)
// Space: O(n)
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param A: Given an integer array with no duplicates.
* @return: The root of max tree.
*/
TreeNode* maxTree(vector<int> A) {
if (A.empty()) {
return NULL;
}
stack<TreeNode *> nodeStack;
nodeStack.push(new TreeNode(A[0]));
for (int i = 1; i < A.size(); ++i) {
// The stack stores nodes in descending order.
if (A[i] <= nodeStack.top()->val) {
TreeNode *node = new TreeNode(A[i]);
nodeStack.push(node);
} else {
// Pop every node which value is less than A[i],
// and let them as right children of
// the last node less than A[i]
TreeNode *smaller_node = nodeStack.top();
nodeStack.pop();
while (!nodeStack.empty() && nodeStack.top()->val < A[i]) {
nodeStack.top()->right = smaller_node;
smaller_node = nodeStack.top();
nodeStack.pop();
}
// Pop the last node which value is less
// than A[i], and let it as right child,
// and push A[i] to the stack.
TreeNode *node = new TreeNode(A[i]);
node->left = smaller_node;
nodeStack.push(node);
}
}
// Pop every node in the stack,
// and let them as right children of the root
TreeNode *root = nodeStack.top();
nodeStack.pop();
while (!nodeStack.empty()) {
nodeStack.top()->right = root;
root = nodeStack.top();
nodeStack.pop();
}
return root;
}
};
<commit_msg>update<commit_after>// Time: O(n)
// Space: O(n)
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param A: Given an integer array with no duplicates.
* @return: The root of max tree.
*/
TreeNode* maxTree(vector<int> A) {
if (A.empty()) {
return nullptr;
}
stack<TreeNode *> nodeStack;
nodeStack.emplace(new TreeNode(A[0]));
for (int i = 1; i < A.size(); ++i) {
// The stack stores nodes in descending order.
if (A[i] <= nodeStack.top()->val) {
TreeNode *node = new TreeNode(A[i]);
nodeStack.emplace(node);
} else {
// Pop every node which value is less than A[i],
// and let them as right children of
// the last node less than A[i]
TreeNode *smaller_node = nodeStack.top();
nodeStack.pop();
while (!nodeStack.empty() && nodeStack.top()->val < A[i]) {
nodeStack.top()->right = smaller_node;
smaller_node = nodeStack.top();
nodeStack.pop();
}
// Pop the last node which value is less
// than A[i], and let it as right child,
// and push A[i] to the stack.
TreeNode *node = new TreeNode(A[i]);
node->left = smaller_node;
nodeStack.emplace(node);
}
}
// Pop every node in the stack,
// and let them as right children of the root
TreeNode *root = nodeStack.top();
nodeStack.pop();
while (!nodeStack.empty()) {
nodeStack.top()->right = root;
root = nodeStack.top();
nodeStack.pop();
}
return root;
}
};
<|endoftext|>
|
<commit_before>// Copyright (c) 2017 The e-Gulden Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "oerushield/oerushield.h"
#include "base58.h"
#include "chainparams.h"
#include "oerushield/oerudb.h"
#include "oerushield/oerutx.h"
#include "oerushield/signaturechecker.h"
#include "primitives/block.h"
#include "primitives/transaction.h"
#include "util.h"
#include "utilstrencodings.h"
#include <string>
#include <vector>
const std::vector<unsigned char> COeruShield::OERU_BYTES = { 0x4f, 0x45, 0x52, 0x55 }; // "OERU"
const uint64_t COeruShield::MAX_HEIGHT_DIFFERENCE = 720;
const std::vector<std::vector<unsigned char>> COeruShield::MASTER_KEYS =
{
ParseHex("1e58eb7273d4ce30e9a961600aaa49871beec551aba5b6f5a5712d6ccd1a8e3a"),
ParseHex("b752e70e9b8343719491edfb524db6599e21d98269c1e720509636a6bb5db7ba"),
ParseHex("f6b2c579d2bc9c86603d0689546ca989c543049d5bdd8486c9b72eee4ccca5b1")
};
COeruShield::COeruShield(COeruDB *oeruDB)
{
this->oeruDB = oeruDB;
}
bool COeruShield::CheckMasterTx(CTransaction tx, int nHeight) const
{
if (tx.IsCoinBase())
return false;
if (tx.vout.size() != 3)
return false;
CTxOut masterOut = tx.vout[0];
CTxOut minerOut = tx.vout[1];
CTxOut signatureOut = tx.vout[2];
CBitcoinAddress master;
if (!GetDestinationAddress(masterOut, master))
return false;
if (!IsMasterKey(master))
return false;
CBitcoinAddress miner;
if (!GetDestinationAddress(minerOut, miner))
return false;
COeruTxOut masterOeruOut(&signatureOut);
COeruMasterData masterData;
if (!masterOeruOut.GetOeruMasterData(masterData))
return false;
if (!masterData.IsValid())
return false;
uint64_t masterHeight;
if (!masterData.GetHeight(masterHeight))
return false;
if (masterHeight < nHeight - COeruShield::MAX_HEIGHT_DIFFERENCE)
return false;
if (!masterData.HasValidSignature(master))
return false;
bool enable;
if (!masterData.GetEnable(enable))
return false;
if (enable)
oeruDB->AddCertifiedAddress(miner);
else
oeruDB->RemoveCertifiedAddress(miner);
return true;
}
bool COeruShield::FindOeruVOut(const CTransaction& coinbaseTx, COeruTxOut& oeruTxOut) const
{
if (!coinbaseTx.IsCoinBase())
return false;
for (auto &vout : coinbaseTx.vout)
{
oeruTxOut = COeruTxOut(&vout);
if (oeruTxOut.HasOeruBytes())
{
return true;
}
}
return false;
}
bool COeruShield::GetCoinbaseAddress(const CTransaction& coinbaseTx, CBitcoinAddress& coinbaseAddress) const
{
if (coinbaseTx.vout.size() < 1)
return false;
return GetDestinationAddress(coinbaseTx.vout[0], coinbaseAddress);
}
bool COeruShield::GetCoinbaseTx(const CBlock& block, CTransaction& coinbaseTx) const
{
if (block.vtx.size() < 1)
return false;
coinbaseTx = block.vtx[0];
if (!coinbaseTx.IsCoinBase())
return false;
return true;
}
bool COeruShield::GetDestinationAddress(const CTxOut txOut, CBitcoinAddress &destination) const
{
CTxDestination txDestination;
if (!ExtractDestination(txOut.scriptPubKey, txDestination))
return false;
destination = CBitcoinAddress(txDestination);
if (!destination.IsValid())
return false;
return true;
}
bool COeruShield::IsActive() const
{
int minAddresses = Params().OeruShieldMinCertifiedAddresses();
return oeruDB->NumCertifiedAddresses() >= minAddresses;
}
bool COeruShield::IsBlockIdentified(const CBlock& block, const int nHeight) const
{
CTransaction coinbaseTx;
if ( ! GetCoinbaseTx(block, coinbaseTx))
return false;
CBitcoinAddress coinbaseAddress;
if ( ! GetCoinbaseAddress(coinbaseTx, coinbaseAddress))
return false;
COeruTxOut oeruTxOut;
if ( ! FindOeruVOut(coinbaseTx, oeruTxOut)) {
LogPrint("OeruShield", "%s: No valid oeru vout found\n", __FUNCTION__);
return false;
}
std::vector<unsigned char> vchData;
if (!oeruTxOut.GetOpReturnData(vchData)) {
LogPrint("OeruShield", "%s: No OP_RETURN data found\n", __FUNCTION__);
return false;
}
std::vector<unsigned char> vchSig(vchData.begin() + COeruShield::OERU_BYTES.size(), vchData.end());
std::string strMessage = std::to_string(nHeight);
CSignatureChecker signatureChecker;
if (signatureChecker.VerifySignature(strMessage, vchSig, coinbaseAddress)) {
LogPrint("OeruShield", "%s: Valid OERU signature\n", __FUNCTION__);
return true;
} else {
LogPrint("OeruShield", "%s: No valid OERU signature\n", __FUNCTION__);
return false;
}
}
bool COeruShield::IsBlockCertified(const CBlock& block, const int nHeight) const
{
if ( ! IsBlockIdentified(block, nHeight))
return false;
CTransaction coinbaseTx;
if ( ! GetCoinbaseTx(block, coinbaseTx) || coinbaseTx.vout.size() < 2)
return false;
CBitcoinAddress coinbaseAddress;
if ( ! GetCoinbaseAddress(coinbaseTx, coinbaseAddress))
return false;
return oeruDB->IsAddressCertified(coinbaseAddress);
}
bool COeruShield::IsMasterKey(std::vector<unsigned char> addrHash) const
{
for (auto it = COeruShield::MASTER_KEYS.begin(); it != COeruShield::MASTER_KEYS.end(); ++it)
{
if (*it == addrHash)
{
return true;
}
}
return false;
}
bool COeruShield::IsMasterKey(CBitcoinAddress addr) const
{
std::string strAddr = addr.ToString();
std::vector<unsigned char> hash;
hash.resize(CSHA256::OUTPUT_SIZE);
CSHA256().Write((unsigned char*) &strAddr[0], strAddr.size())
.Finalize(&hash[0]);
return IsMasterKey(hash);
}
<commit_msg>Switched miner and master out in oeru TX<commit_after>// Copyright (c) 2017 The e-Gulden Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "oerushield/oerushield.h"
#include "base58.h"
#include "chainparams.h"
#include "oerushield/oerudb.h"
#include "oerushield/oerutx.h"
#include "oerushield/signaturechecker.h"
#include "primitives/block.h"
#include "primitives/transaction.h"
#include "util.h"
#include "utilstrencodings.h"
#include <string>
#include <vector>
const std::vector<unsigned char> COeruShield::OERU_BYTES = { 0x4f, 0x45, 0x52, 0x55 }; // "OERU"
const uint64_t COeruShield::MAX_HEIGHT_DIFFERENCE = 720;
const std::vector<std::vector<unsigned char>> COeruShield::MASTER_KEYS =
{
ParseHex("1e58eb7273d4ce30e9a961600aaa49871beec551aba5b6f5a5712d6ccd1a8e3a"),
ParseHex("b752e70e9b8343719491edfb524db6599e21d98269c1e720509636a6bb5db7ba"),
ParseHex("f6b2c579d2bc9c86603d0689546ca989c543049d5bdd8486c9b72eee4ccca5b1")
};
COeruShield::COeruShield(COeruDB *oeruDB)
{
this->oeruDB = oeruDB;
}
bool COeruShield::CheckMasterTx(CTransaction tx, int nHeight) const
{
if (tx.IsCoinBase())
return false;
if (tx.vout.size() != 3)
return false;
CTxOut minerOut = tx.vout[0];
CTxOut masterOut = tx.vout[1];
CTxOut signatureOut = tx.vout[2];
CBitcoinAddress master;
if (!GetDestinationAddress(masterOut, master))
return false;
if (!IsMasterKey(master))
return false;
CBitcoinAddress miner;
if (!GetDestinationAddress(minerOut, miner))
return false;
COeruTxOut masterOeruOut(&signatureOut);
COeruMasterData masterData;
if (!masterOeruOut.GetOeruMasterData(masterData))
return false;
if (!masterData.IsValid())
return false;
uint64_t masterHeight;
if (!masterData.GetHeight(masterHeight))
return false;
if (masterHeight < nHeight - COeruShield::MAX_HEIGHT_DIFFERENCE)
return false;
if (!masterData.HasValidSignature(master))
return false;
bool enable;
if (!masterData.GetEnable(enable))
return false;
if (enable)
oeruDB->AddCertifiedAddress(miner);
else
oeruDB->RemoveCertifiedAddress(miner);
return true;
}
bool COeruShield::FindOeruVOut(const CTransaction& coinbaseTx, COeruTxOut& oeruTxOut) const
{
if (!coinbaseTx.IsCoinBase())
return false;
for (auto &vout : coinbaseTx.vout)
{
oeruTxOut = COeruTxOut(&vout);
if (oeruTxOut.HasOeruBytes())
{
return true;
}
}
return false;
}
bool COeruShield::GetCoinbaseAddress(const CTransaction& coinbaseTx, CBitcoinAddress& coinbaseAddress) const
{
if (coinbaseTx.vout.size() < 1)
return false;
return GetDestinationAddress(coinbaseTx.vout[0], coinbaseAddress);
}
bool COeruShield::GetCoinbaseTx(const CBlock& block, CTransaction& coinbaseTx) const
{
if (block.vtx.size() < 1)
return false;
coinbaseTx = block.vtx[0];
if (!coinbaseTx.IsCoinBase())
return false;
return true;
}
bool COeruShield::GetDestinationAddress(const CTxOut txOut, CBitcoinAddress &destination) const
{
CTxDestination txDestination;
if (!ExtractDestination(txOut.scriptPubKey, txDestination))
return false;
destination = CBitcoinAddress(txDestination);
if (!destination.IsValid())
return false;
return true;
}
bool COeruShield::IsActive() const
{
int minAddresses = Params().OeruShieldMinCertifiedAddresses();
return oeruDB->NumCertifiedAddresses() >= minAddresses;
}
bool COeruShield::IsBlockIdentified(const CBlock& block, const int nHeight) const
{
CTransaction coinbaseTx;
if ( ! GetCoinbaseTx(block, coinbaseTx))
return false;
CBitcoinAddress coinbaseAddress;
if ( ! GetCoinbaseAddress(coinbaseTx, coinbaseAddress))
return false;
COeruTxOut oeruTxOut;
if ( ! FindOeruVOut(coinbaseTx, oeruTxOut)) {
LogPrint("OeruShield", "%s: No valid oeru vout found\n", __FUNCTION__);
return false;
}
std::vector<unsigned char> vchData;
if (!oeruTxOut.GetOpReturnData(vchData)) {
LogPrint("OeruShield", "%s: No OP_RETURN data found\n", __FUNCTION__);
return false;
}
std::vector<unsigned char> vchSig(vchData.begin() + COeruShield::OERU_BYTES.size(), vchData.end());
std::string strMessage = std::to_string(nHeight);
CSignatureChecker signatureChecker;
if (signatureChecker.VerifySignature(strMessage, vchSig, coinbaseAddress)) {
LogPrint("OeruShield", "%s: Valid OERU signature\n", __FUNCTION__);
return true;
} else {
LogPrint("OeruShield", "%s: No valid OERU signature\n", __FUNCTION__);
return false;
}
}
bool COeruShield::IsBlockCertified(const CBlock& block, const int nHeight) const
{
if ( ! IsBlockIdentified(block, nHeight))
return false;
CTransaction coinbaseTx;
if ( ! GetCoinbaseTx(block, coinbaseTx) || coinbaseTx.vout.size() < 2)
return false;
CBitcoinAddress coinbaseAddress;
if ( ! GetCoinbaseAddress(coinbaseTx, coinbaseAddress))
return false;
return oeruDB->IsAddressCertified(coinbaseAddress);
}
bool COeruShield::IsMasterKey(std::vector<unsigned char> addrHash) const
{
for (auto it = COeruShield::MASTER_KEYS.begin(); it != COeruShield::MASTER_KEYS.end(); ++it)
{
if (*it == addrHash)
{
return true;
}
}
return false;
}
bool COeruShield::IsMasterKey(CBitcoinAddress addr) const
{
std::string strAddr = addr.ToString();
std::vector<unsigned char> hash;
hash.resize(CSHA256::OUTPUT_SIZE);
CSHA256().Write((unsigned char*) &strAddr[0], strAddr.size())
.Finalize(&hash[0]);
return IsMasterKey(hash);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2017 The e-Gulden Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "oerushield/oerushield.h"
#include "base58.h"
#include "chainparams.h"
#include "oerushield/oerudb.h"
#include "oerushield/oerutx.h"
#include "oerushield/signaturechecker.h"
#include "primitives/block.h"
#include "primitives/transaction.h"
#include "util.h"
#include "utilstrencodings.h"
#include <string>
#include <vector>
const std::vector<unsigned char> COeruShield::OERU_BYTES = { 0x4f, 0x45, 0x52, 0x55 }; // "OERU"
const uint64_t COeruShield::MAX_HEIGHT_DIFFERENCE = 720;
const std::vector<std::vector<unsigned char>> COeruShield::MASTER_KEYS =
{
ParseHex("1e58eb7273d4ce30e9a961600aaa49871beec551aba5b6f5a5712d6ccd1a8e3a"),
ParseHex("b752e70e9b8343719491edfb524db6599e21d98269c1e720509636a6bb5db7ba"),
ParseHex("f6b2c579d2bc9c86603d0689546ca989c543049d5bdd8486c9b72eee4ccca5b1")
};
COeruShield::COeruShield(COeruDB *oeruDB)
{
this->oeruDB = oeruDB;
}
bool COeruShield::CheckMasterTx(CTransaction tx, int nHeight) const
{
if (tx.IsCoinBase())
return false;
if (tx.vout.size() != 3)
return false;
CTxOut minerOut = tx.vout[0];
CTxOut masterOut = tx.vout[1];
CTxOut signatureOut = tx.vout[2];
CBitcoinAddress master;
if (!GetDestinationAddress(masterOut, master))
return false;
if (!IsMasterKey(master))
return false;
CBitcoinAddress miner;
if (!GetDestinationAddress(minerOut, miner))
return false;
COeruTxOut masterOeruOut(&signatureOut);
COeruMasterData masterData;
if (!masterOeruOut.GetOeruMasterData(masterData))
return false;
if (!masterData.IsValid())
return false;
uint64_t masterHeight;
if (!masterData.GetHeight(masterHeight))
return false;
if (masterHeight < nHeight - COeruShield::MAX_HEIGHT_DIFFERENCE)
return false;
if (!masterData.HasValidSignature(master))
return false;
bool enable;
if (!masterData.GetEnable(enable))
return false;
if (enable)
oeruDB->AddCertifiedAddress(miner);
else
oeruDB->RemoveCertifiedAddress(miner);
return true;
}
bool COeruShield::FindOeruVOut(const CTransaction& coinbaseTx, COeruTxOut& oeruTxOut) const
{
if (!coinbaseTx.IsCoinBase())
return false;
for (auto &vout : coinbaseTx.vout)
{
oeruTxOut = COeruTxOut(&vout);
if (oeruTxOut.HasOeruBytes())
{
return true;
}
}
return false;
}
bool COeruShield::GetCoinbaseAddress(const CTransaction& coinbaseTx, CBitcoinAddress& coinbaseAddress) const
{
if (coinbaseTx.vout.size() < 1)
return false;
return GetDestinationAddress(coinbaseTx.vout[0], coinbaseAddress);
}
bool COeruShield::GetCoinbaseTx(const CBlock& block, CTransaction& coinbaseTx) const
{
if (block.vtx.size() < 1)
return false;
coinbaseTx = block.vtx[0];
if (!coinbaseTx.IsCoinBase())
return false;
return true;
}
bool COeruShield::GetDestinationAddress(const CTxOut txOut, CBitcoinAddress &destination) const
{
CTxDestination txDestination;
if (!ExtractDestination(txOut.scriptPubKey, txDestination))
return false;
destination = CBitcoinAddress(txDestination);
if (!destination.IsValid())
return false;
return true;
}
bool COeruShield::IsActive() const
{
int minAddresses = Params().OeruShieldMinCertifiedAddresses();
return oeruDB->NumCertifiedAddresses() >= minAddresses;
}
bool COeruShield::IsBlockIdentified(const CBlock& block, const int nHeight) const
{
CTransaction coinbaseTx;
if ( ! GetCoinbaseTx(block, coinbaseTx))
return false;
CBitcoinAddress coinbaseAddress;
if ( ! GetCoinbaseAddress(coinbaseTx, coinbaseAddress))
return false;
COeruTxOut oeruTxOut;
if ( ! FindOeruVOut(coinbaseTx, oeruTxOut)) {
LogPrint("OeruShield", "%s: No valid oeru vout found\n", __FUNCTION__);
return false;
}
std::vector<unsigned char> vchData;
if (!oeruTxOut.GetOpReturnData(vchData)) {
LogPrint("OeruShield", "%s: No OP_RETURN data found\n", __FUNCTION__);
return false;
}
std::vector<unsigned char> vchSig(vchData.begin() + COeruShield::OERU_BYTES.size(), vchData.end());
std::string strMessage = std::to_string(nHeight);
CSignatureChecker signatureChecker;
if (signatureChecker.VerifySignature(strMessage, vchSig, coinbaseAddress)) {
LogPrint("OeruShield", "%s: Valid OERU signature\n", __FUNCTION__);
return true;
} else {
LogPrint("OeruShield", "%s: No valid OERU signature\n", __FUNCTION__);
return false;
}
}
bool COeruShield::IsBlockCertified(const CBlock& block, const int nHeight) const
{
if ( ! IsBlockIdentified(block, nHeight))
return false;
CTransaction coinbaseTx;
if ( ! GetCoinbaseTx(block, coinbaseTx) || coinbaseTx.vout.size() < 2)
return false;
CBitcoinAddress coinbaseAddress;
if ( ! GetCoinbaseAddress(coinbaseTx, coinbaseAddress))
return false;
return oeruDB->IsAddressCertified(coinbaseAddress);
}
bool COeruShield::IsMasterKey(std::vector<unsigned char> addrHash) const
{
for (auto it = COeruShield::MASTER_KEYS.begin(); it != COeruShield::MASTER_KEYS.end(); ++it)
{
if (*it == addrHash)
{
return true;
}
}
return false;
}
bool COeruShield::IsMasterKey(CBitcoinAddress addr) const
{
std::string strAddr = addr.ToString();
std::vector<unsigned char> hash;
hash.resize(CSHA256::OUTPUT_SIZE);
CSHA256().Write((unsigned char*) &strAddr[0], strAddr.size())
.Finalize(&hash[0]);
return IsMasterKey(hash);
}
<commit_msg>Write file when any address is certified or decertified<commit_after>// Copyright (c) 2017 The e-Gulden Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "oerushield/oerushield.h"
#include "base58.h"
#include "chainparams.h"
#include "oerushield/oerudb.h"
#include "oerushield/oerutx.h"
#include "oerushield/signaturechecker.h"
#include "primitives/block.h"
#include "primitives/transaction.h"
#include "util.h"
#include "utilstrencodings.h"
#include <string>
#include <vector>
const std::vector<unsigned char> COeruShield::OERU_BYTES = { 0x4f, 0x45, 0x52, 0x55 }; // "OERU"
const uint64_t COeruShield::MAX_HEIGHT_DIFFERENCE = 720;
const std::vector<std::vector<unsigned char>> COeruShield::MASTER_KEYS =
{
ParseHex("1e58eb7273d4ce30e9a961600aaa49871beec551aba5b6f5a5712d6ccd1a8e3a"),
ParseHex("b752e70e9b8343719491edfb524db6599e21d98269c1e720509636a6bb5db7ba"),
ParseHex("f6b2c579d2bc9c86603d0689546ca989c543049d5bdd8486c9b72eee4ccca5b1")
};
COeruShield::COeruShield(COeruDB *oeruDB)
{
this->oeruDB = oeruDB;
}
bool COeruShield::CheckMasterTx(CTransaction tx, int nHeight) const
{
if (tx.IsCoinBase())
return false;
if (tx.vout.size() != 3)
return false;
CTxOut minerOut = tx.vout[0];
CTxOut masterOut = tx.vout[1];
CTxOut signatureOut = tx.vout[2];
CBitcoinAddress master;
if (!GetDestinationAddress(masterOut, master))
return false;
if (!IsMasterKey(master))
return false;
CBitcoinAddress miner;
if (!GetDestinationAddress(minerOut, miner))
return false;
COeruTxOut masterOeruOut(&signatureOut);
COeruMasterData masterData;
if (!masterOeruOut.GetOeruMasterData(masterData))
return false;
if (!masterData.IsValid())
return false;
uint64_t masterHeight;
if (!masterData.GetHeight(masterHeight))
return false;
if (masterHeight < nHeight - COeruShield::MAX_HEIGHT_DIFFERENCE)
return false;
if (!masterData.HasValidSignature(master))
return false;
bool enable;
if (!masterData.GetEnable(enable))
return false;
if (enable)
oeruDB->AddCertifiedAddress(miner);
else
oeruDB->RemoveCertifiedAddress(miner);
oeruDB->WriteFile();
return true;
}
bool COeruShield::FindOeruVOut(const CTransaction& coinbaseTx, COeruTxOut& oeruTxOut) const
{
if (!coinbaseTx.IsCoinBase())
return false;
for (auto &vout : coinbaseTx.vout)
{
oeruTxOut = COeruTxOut(&vout);
if (oeruTxOut.HasOeruBytes())
{
return true;
}
}
return false;
}
bool COeruShield::GetCoinbaseAddress(const CTransaction& coinbaseTx, CBitcoinAddress& coinbaseAddress) const
{
if (coinbaseTx.vout.size() < 1)
return false;
return GetDestinationAddress(coinbaseTx.vout[0], coinbaseAddress);
}
bool COeruShield::GetCoinbaseTx(const CBlock& block, CTransaction& coinbaseTx) const
{
if (block.vtx.size() < 1)
return false;
coinbaseTx = block.vtx[0];
if (!coinbaseTx.IsCoinBase())
return false;
return true;
}
bool COeruShield::GetDestinationAddress(const CTxOut txOut, CBitcoinAddress &destination) const
{
CTxDestination txDestination;
if (!ExtractDestination(txOut.scriptPubKey, txDestination))
return false;
destination = CBitcoinAddress(txDestination);
if (!destination.IsValid())
return false;
return true;
}
bool COeruShield::IsActive() const
{
int minAddresses = Params().OeruShieldMinCertifiedAddresses();
return oeruDB->NumCertifiedAddresses() >= minAddresses;
}
bool COeruShield::IsBlockIdentified(const CBlock& block, const int nHeight) const
{
CTransaction coinbaseTx;
if ( ! GetCoinbaseTx(block, coinbaseTx))
return false;
CBitcoinAddress coinbaseAddress;
if ( ! GetCoinbaseAddress(coinbaseTx, coinbaseAddress))
return false;
COeruTxOut oeruTxOut;
if ( ! FindOeruVOut(coinbaseTx, oeruTxOut)) {
LogPrint("OeruShield", "%s: No valid oeru vout found\n", __FUNCTION__);
return false;
}
std::vector<unsigned char> vchData;
if (!oeruTxOut.GetOpReturnData(vchData)) {
LogPrint("OeruShield", "%s: No OP_RETURN data found\n", __FUNCTION__);
return false;
}
std::vector<unsigned char> vchSig(vchData.begin() + COeruShield::OERU_BYTES.size(), vchData.end());
std::string strMessage = std::to_string(nHeight);
CSignatureChecker signatureChecker;
if (signatureChecker.VerifySignature(strMessage, vchSig, coinbaseAddress)) {
LogPrint("OeruShield", "%s: Valid OERU signature\n", __FUNCTION__);
return true;
} else {
LogPrint("OeruShield", "%s: No valid OERU signature\n", __FUNCTION__);
return false;
}
}
bool COeruShield::IsBlockCertified(const CBlock& block, const int nHeight) const
{
if ( ! IsBlockIdentified(block, nHeight))
return false;
CTransaction coinbaseTx;
if ( ! GetCoinbaseTx(block, coinbaseTx) || coinbaseTx.vout.size() < 2)
return false;
CBitcoinAddress coinbaseAddress;
if ( ! GetCoinbaseAddress(coinbaseTx, coinbaseAddress))
return false;
return oeruDB->IsAddressCertified(coinbaseAddress);
}
bool COeruShield::IsMasterKey(std::vector<unsigned char> addrHash) const
{
for (auto it = COeruShield::MASTER_KEYS.begin(); it != COeruShield::MASTER_KEYS.end(); ++it)
{
if (*it == addrHash)
{
return true;
}
}
return false;
}
bool COeruShield::IsMasterKey(CBitcoinAddress addr) const
{
std::string strAddr = addr.ToString();
std::vector<unsigned char> hash;
hash.resize(CSHA256::OUTPUT_SIZE);
CSHA256().Write((unsigned char*) &strAddr[0], strAddr.size())
.Finalize(&hash[0]);
return IsMasterKey(hash);
}
<|endoftext|>
|
<commit_before>#include "PictureRenderer.h"
#include "SamplePipeControllers.h"
#include "SkCanvas.h"
#include "SkDevice.h"
#include "SkGPipe.h"
#include "SkPicture.h"
#include "SkTDArray.h"
#include "SkTypes.h"
#include "picture_utils.h"
#if SK_SUPPORT_GPU
#include "SkGpuDevice.h"
#endif
namespace sk_tools {
enum {
kDefaultTileWidth = 256,
kDefaultTileHeight = 256
};
void PictureRenderer::init(SkPicture* pict) {
SkASSERT(NULL == fPicture);
SkASSERT(NULL == fCanvas.get());
if (fPicture != NULL || NULL != fCanvas.get()) {
return;
}
SkASSERT(pict != NULL);
if (NULL == pict) {
return;
}
fPicture = pict;
fCanvas.reset(this->setupCanvas());
}
SkCanvas* PictureRenderer::setupCanvas() {
return this->setupCanvas(fPicture->width(), fPicture->height());
}
SkCanvas* PictureRenderer::setupCanvas(int width, int height) {
switch(fDeviceType) {
case kBitmap_DeviceType: {
SkBitmap bitmap;
sk_tools::setup_bitmap(&bitmap, width, height);
return SkNEW_ARGS(SkCanvas, (bitmap));
break;
}
#if SK_SUPPORT_GPU
case kGPU_DeviceType: {
SkAutoTUnref<SkGpuDevice> device(SkNEW_ARGS(SkGpuDevice,
(fGrContext, SkBitmap::kARGB_8888_Config,
width, height)));
return SkNEW_ARGS(SkCanvas, (device.get()));
break;
}
#endif
default:
SkASSERT(0);
}
return NULL;
}
void PictureRenderer::end() {
this->resetState();
fPicture = NULL;
fCanvas.reset(NULL);
}
void PictureRenderer::resetState() {
fCanvas->flush();
if (this->isUsingGpuDevice()) {
SkGLContext* glContext = fGrContextFactory.getGLContext(
GrContextFactory::kNative_GLContextType);
SK_GL(*glContext, Finish());
fGrContext->freeGpuResources();
}
}
void PipePictureRenderer::render() {
SkASSERT(fCanvas.get() != NULL);
SkASSERT(fPicture != NULL);
if (NULL == fCanvas.get() || NULL == fPicture) {
return;
}
PipeController pipeController(fCanvas.get());
SkGPipeWriter writer;
SkCanvas* pipeCanvas = writer.startRecording(&pipeController);
pipeCanvas->drawPicture(*fPicture);
writer.endRecording();
}
void SimplePictureRenderer::render() {
SkASSERT(fCanvas.get() != NULL);
SkASSERT(fPicture != NULL);
if (NULL == fCanvas.get() || NULL == fPicture) {
return;
}
fCanvas->drawPicture(*fPicture);
}
TiledPictureRenderer::TiledPictureRenderer()
: fTileWidth(kDefaultTileWidth)
, fTileHeight(kDefaultTileHeight) {}
void TiledPictureRenderer::init(SkPicture* pict) {
SkASSERT(pict != NULL);
SkASSERT(0 == fTiles.count());
if (NULL == pict || fTiles.count() != 0) {
return;
}
this->INHERITED::init(pict);
if (fTileWidthPercentage > 0) {
fTileWidth = sk_float_ceil2int(float(fTileWidthPercentage * fPicture->width() / 100));
}
if (fTileHeightPercentage > 0) {
fTileHeight = sk_float_ceil2int(float(fTileHeightPercentage * fPicture->height() / 100));
}
this->setupTiles();
}
void TiledPictureRenderer::render() {
SkASSERT(fCanvas.get() != NULL);
SkASSERT(fPicture != NULL);
if (NULL == fCanvas.get() || NULL == fPicture) {
return;
}
this->drawTiles();
this->copyTilesToCanvas();
}
void TiledPictureRenderer::end() {
this->deleteTiles();
this->INHERITED::end();
}
TiledPictureRenderer::~TiledPictureRenderer() {
this->deleteTiles();
}
void TiledPictureRenderer::clipTile(const TileInfo& tile) {
SkRect clip = SkRect::MakeWH(SkIntToScalar(fPicture->width()),
SkIntToScalar(fPicture->height()));
tile.fCanvas->clipRect(clip);
}
void TiledPictureRenderer::addTile(int tile_x_start, int tile_y_start) {
TileInfo* tile = fTiles.push();
tile->fCanvas = this->setupCanvas(fTileWidth, fTileHeight);
tile->fCanvas->translate(SkIntToScalar(-tile_x_start), SkIntToScalar(-tile_y_start));
this->clipTile(*tile);
}
void TiledPictureRenderer::setupTiles() {
for (int tile_y_start = 0; tile_y_start < fPicture->height();
tile_y_start += fTileHeight) {
for (int tile_x_start = 0; tile_x_start < fPicture->width();
tile_x_start += fTileWidth) {
this->addTile(tile_x_start, tile_y_start);
}
}
}
void TiledPictureRenderer::deleteTiles() {
for (int i = 0; i < fTiles.count(); ++i) {
SkDELETE(fTiles[i].fCanvas);
SkDELETE(fTiles[i].fBitmap);
}
fTiles.reset();
}
void TiledPictureRenderer::drawTiles() {
for (int i = 0; i < fTiles.count(); ++i) {
fTiles[i].fCanvas->drawPicture(*(fPicture));
}
}
void TiledPictureRenderer::resetState() {
for (int i = 0; i < fTiles.count(); ++i) {
fTiles[i].fCanvas->flush();
}
this->INHERITED::resetState();
}
void TiledPictureRenderer::copyTilesToCanvas() {
int tile_index = 0;
for (int tile_y_start = 0; tile_y_start < fPicture->height();
tile_y_start += fTileHeight) {
for (int tile_x_start = 0; tile_x_start < fPicture->width();
tile_x_start += fTileWidth) {
SkASSERT(tile_index < fTiles.count());
SkBitmap source = fTiles[tile_index].fCanvas->getDevice()->accessBitmap(false);
fCanvas->drawBitmap(source,
SkIntToScalar(tile_x_start),
SkIntToScalar(tile_y_start));
++tile_index;
}
}
}
}
<commit_msg>Remove fBitmap delete. Tile bitmaps are no longer kept around.<commit_after>#include "PictureRenderer.h"
#include "SamplePipeControllers.h"
#include "SkCanvas.h"
#include "SkDevice.h"
#include "SkGPipe.h"
#include "SkPicture.h"
#include "SkTDArray.h"
#include "SkTypes.h"
#include "picture_utils.h"
#if SK_SUPPORT_GPU
#include "SkGpuDevice.h"
#endif
namespace sk_tools {
enum {
kDefaultTileWidth = 256,
kDefaultTileHeight = 256
};
void PictureRenderer::init(SkPicture* pict) {
SkASSERT(NULL == fPicture);
SkASSERT(NULL == fCanvas.get());
if (fPicture != NULL || NULL != fCanvas.get()) {
return;
}
SkASSERT(pict != NULL);
if (NULL == pict) {
return;
}
fPicture = pict;
fCanvas.reset(this->setupCanvas());
}
SkCanvas* PictureRenderer::setupCanvas() {
return this->setupCanvas(fPicture->width(), fPicture->height());
}
SkCanvas* PictureRenderer::setupCanvas(int width, int height) {
switch(fDeviceType) {
case kBitmap_DeviceType: {
SkBitmap bitmap;
sk_tools::setup_bitmap(&bitmap, width, height);
return SkNEW_ARGS(SkCanvas, (bitmap));
break;
}
#if SK_SUPPORT_GPU
case kGPU_DeviceType: {
SkAutoTUnref<SkGpuDevice> device(SkNEW_ARGS(SkGpuDevice,
(fGrContext, SkBitmap::kARGB_8888_Config,
width, height)));
return SkNEW_ARGS(SkCanvas, (device.get()));
break;
}
#endif
default:
SkASSERT(0);
}
return NULL;
}
void PictureRenderer::end() {
this->resetState();
fPicture = NULL;
fCanvas.reset(NULL);
}
void PictureRenderer::resetState() {
fCanvas->flush();
if (this->isUsingGpuDevice()) {
SkGLContext* glContext = fGrContextFactory.getGLContext(
GrContextFactory::kNative_GLContextType);
SK_GL(*glContext, Finish());
fGrContext->freeGpuResources();
}
}
void PipePictureRenderer::render() {
SkASSERT(fCanvas.get() != NULL);
SkASSERT(fPicture != NULL);
if (NULL == fCanvas.get() || NULL == fPicture) {
return;
}
PipeController pipeController(fCanvas.get());
SkGPipeWriter writer;
SkCanvas* pipeCanvas = writer.startRecording(&pipeController);
pipeCanvas->drawPicture(*fPicture);
writer.endRecording();
}
void SimplePictureRenderer::render() {
SkASSERT(fCanvas.get() != NULL);
SkASSERT(fPicture != NULL);
if (NULL == fCanvas.get() || NULL == fPicture) {
return;
}
fCanvas->drawPicture(*fPicture);
}
TiledPictureRenderer::TiledPictureRenderer()
: fTileWidth(kDefaultTileWidth)
, fTileHeight(kDefaultTileHeight) {}
void TiledPictureRenderer::init(SkPicture* pict) {
SkASSERT(pict != NULL);
SkASSERT(0 == fTiles.count());
if (NULL == pict || fTiles.count() != 0) {
return;
}
this->INHERITED::init(pict);
if (fTileWidthPercentage > 0) {
fTileWidth = sk_float_ceil2int(float(fTileWidthPercentage * fPicture->width() / 100));
}
if (fTileHeightPercentage > 0) {
fTileHeight = sk_float_ceil2int(float(fTileHeightPercentage * fPicture->height() / 100));
}
this->setupTiles();
}
void TiledPictureRenderer::render() {
SkASSERT(fCanvas.get() != NULL);
SkASSERT(fPicture != NULL);
if (NULL == fCanvas.get() || NULL == fPicture) {
return;
}
this->drawTiles();
this->copyTilesToCanvas();
}
void TiledPictureRenderer::end() {
this->deleteTiles();
this->INHERITED::end();
}
TiledPictureRenderer::~TiledPictureRenderer() {
this->deleteTiles();
}
void TiledPictureRenderer::clipTile(const TileInfo& tile) {
SkRect clip = SkRect::MakeWH(SkIntToScalar(fPicture->width()),
SkIntToScalar(fPicture->height()));
tile.fCanvas->clipRect(clip);
}
void TiledPictureRenderer::addTile(int tile_x_start, int tile_y_start) {
TileInfo* tile = fTiles.push();
tile->fCanvas = this->setupCanvas(fTileWidth, fTileHeight);
tile->fCanvas->translate(SkIntToScalar(-tile_x_start), SkIntToScalar(-tile_y_start));
this->clipTile(*tile);
}
void TiledPictureRenderer::setupTiles() {
for (int tile_y_start = 0; tile_y_start < fPicture->height();
tile_y_start += fTileHeight) {
for (int tile_x_start = 0; tile_x_start < fPicture->width();
tile_x_start += fTileWidth) {
this->addTile(tile_x_start, tile_y_start);
}
}
}
void TiledPictureRenderer::deleteTiles() {
for (int i = 0; i < fTiles.count(); ++i) {
SkDELETE(fTiles[i].fCanvas);
}
fTiles.reset();
}
void TiledPictureRenderer::drawTiles() {
for (int i = 0; i < fTiles.count(); ++i) {
fTiles[i].fCanvas->drawPicture(*(fPicture));
}
}
void TiledPictureRenderer::resetState() {
for (int i = 0; i < fTiles.count(); ++i) {
fTiles[i].fCanvas->flush();
}
this->INHERITED::resetState();
}
void TiledPictureRenderer::copyTilesToCanvas() {
int tile_index = 0;
for (int tile_y_start = 0; tile_y_start < fPicture->height();
tile_y_start += fTileHeight) {
for (int tile_x_start = 0; tile_x_start < fPicture->width();
tile_x_start += fTileWidth) {
SkASSERT(tile_index < fTiles.count());
SkBitmap source = fTiles[tile_index].fCanvas->getDevice()->accessBitmap(false);
fCanvas->drawBitmap(source,
SkIntToScalar(tile_x_start),
SkIntToScalar(tile_y_start));
++tile_index;
}
}
}
}
<|endoftext|>
|
<commit_before>//===----------------------------------------------------------------------===//
// The LLVM analyze utility
//
// This utility is designed to print out the results of running various analysis
// passes on a program. This is useful for understanding a program, or for
// debugging an analysis pass.
//
// analyze --help - Output information about command line switches
// analyze --quiet - Do not print analysis name before output
//
//===----------------------------------------------------------------------===//
#include "llvm/Instruction.h"
#include "llvm/Module.h"
#include "llvm/Function.h"
#include "llvm/iPHINode.h"
#include "llvm/Type.h"
#include "llvm/PassManager.h"
#include "llvm/Bytecode/Reader.h"
#include "llvm/Assembly/Parser.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/Assembly/Writer.h"
#include "llvm/Analysis/Writer.h"
#include "llvm/Analysis/InstForest.h"
#include "llvm/Analysis/Dominators.h"
#include "llvm/Analysis/IntervalPartition.h"
#include "llvm/Analysis/Expressions.h"
#include "llvm/Analysis/InductionVariable.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/DataStructure.h"
#include "llvm/Analysis/FindUnsafePointerTypes.h"
#include "llvm/Analysis/FindUsedTypes.h"
#include "llvm/Support/InstIterator.h"
#include "Support/CommandLine.h"
#include <algorithm>
#include <iostream>
using std::ostream;
using std::string;
//===----------------------------------------------------------------------===//
// printPass - Specify how to print out a pass. For most passes, the standard
// way of using operator<< works great, so we use it directly...
//
template<class PassType>
static void printPass(PassType &P, ostream &O, Module *M) {
O << P;
}
template<class PassType>
static void printPass(PassType &P, ostream &O, Function *F) {
O << P;
}
// Other classes require more information to print out information, so we
// specialize the template here for them...
//
template<>
static void printPass(DataStructure &P, ostream &O, Module *M) {
P.print(O, M);
}
template<>
static void printPass(FindUsedTypes &FUT, ostream &O, Module *M) {
FUT.printTypes(O, M);
}
template<>
static void printPass(FindUnsafePointerTypes &FUPT, ostream &O,
Module *M) {
FUPT.printResults(M, O);
}
template <class PassType, class PassName>
class PassPrinter; // Do not implement
template <class PassName>
class PassPrinter<Pass, PassName> : public Pass {
const string Message;
const AnalysisID ID;
public:
PassPrinter(const string &M, AnalysisID id) : Message(M), ID(id) {}
virtual bool run(Module *M) {
std::cout << Message << "\n";
printPass(getAnalysis<PassName>(ID), std::cout, M);
return false;
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired(ID);
}
};
template <class PassName>
class PassPrinter<FunctionPass, PassName> : public FunctionPass {
const string Message;
const AnalysisID ID;
public:
PassPrinter(const string &M, AnalysisID id) : Message(M), ID(id) {}
virtual bool runOnFunction(Function *F) {
std::cout << Message << " on function '" << F->getName() << "'\n";
printPass(getAnalysis<PassName>(ID), std::cout, F);
return false;
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired(ID);
AU.setPreservesAll();
}
};
template <class PassType, class PassName, AnalysisID &ID>
Pass *New(const string &Message) {
return new PassPrinter<PassType, PassName>(Message, ID);
}
template <class PassType, class PassName>
Pass *New(const string &Message) {
return new PassPrinter<PassType, PassName>(Message, PassName::ID);
}
Pass *NewPrintFunction(const string &Message) {
return new PrintFunctionPass(Message, &std::cout);
}
Pass *NewPrintModule(const string &Message) {
return new PrintModulePass(&std::cout);
}
struct InstForest : public FunctionPass {
void doit(Function *F) {
std::cout << analysis::InstForest<char>(F);
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
}
};
struct IndVars : public FunctionPass {
void doit(Function *F) {
LoopInfo &LI = getAnalysis<LoopInfo>();
for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
if (PHINode *PN = dyn_cast<PHINode>(*I)) {
InductionVariable IV(PN, &LI);
if (IV.InductionType != InductionVariable::Unknown)
std::cout << IV;
}
}
void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired(LoopInfo::ID);
AU.setPreservesAll();
}
};
struct Exprs : public FunctionPass {
static void doit(Function *F) {
std::cout << "Classified expressions for: " << F->getName() << "\n";
for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
std::cout << *I;
if ((*I)->getType() == Type::VoidTy) continue;
analysis::ExprType R = analysis::ClassifyExpression(*I);
if (R.Var == *I) continue; // Doesn't tell us anything
std::cout << "\t\tExpr =";
switch (R.ExprTy) {
case analysis::ExprType::ScaledLinear:
WriteAsOperand(std::cout << "(", (Value*)R.Scale) << " ) *";
// fall through
case analysis::ExprType::Linear:
WriteAsOperand(std::cout << "(", R.Var) << " )";
if (R.Offset == 0) break;
else std::cout << " +";
// fall through
case analysis::ExprType::Constant:
if (R.Offset) WriteAsOperand(std::cout, (Value*)R.Offset);
else std::cout << " 0";
break;
}
std::cout << "\n\n";
}
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
}
};
template<class TraitClass>
class PrinterPass : public TraitClass {
const string Message;
public:
PrinterPass(const string &M) : Message(M) {}
virtual bool runOnFunction(Function *F) {
std::cout << Message << " on function '" << F->getName() << "'\n";
TraitClass::doit(F);
return false;
}
};
template<class PassClass>
Pass *Create(const string &Message) {
return new PassClass(Message);
}
enum Ans {
// global analyses
print, intervals, exprs, instforest, loops, indvars,
// ip analyses
printmodule, callgraph, datastructure, printusedtypes, unsafepointertypes,
domset, idom, domtree, domfrontier,
postdomset, postidom, postdomtree, postdomfrontier,
};
cl::String InputFilename ("", "Load <arg> file to analyze", cl::NoFlags, "-");
cl::Flag Quiet ("q", "Don't print analysis pass names");
cl::Alias QuietA ("quiet", "Alias for -q", cl::NoFlags, Quiet);
cl::EnumList<enum Ans> AnalysesList(cl::NoFlags,
clEnumVal(print , "Print each function"),
clEnumVal(intervals , "Print Interval Partitions"),
clEnumVal(exprs , "Classify Expressions"),
clEnumVal(instforest , "Print Instruction Forest"),
clEnumVal(loops , "Print natural loops"),
clEnumVal(indvars , "Print Induction Variables"),
clEnumVal(printmodule , "Print entire module"),
clEnumVal(callgraph , "Print Call Graph"),
clEnumVal(datastructure , "Print data structure information"),
clEnumVal(printusedtypes , "Print types used by module"),
clEnumVal(unsafepointertypes, "Print unsafe pointer types"),
clEnumVal(domset , "Print Dominator Sets"),
clEnumVal(idom , "Print Immediate Dominators"),
clEnumVal(domtree , "Print Dominator Tree"),
clEnumVal(domfrontier , "Print Dominance Frontier"),
clEnumVal(postdomset , "Print Postdominator Sets"),
clEnumVal(postidom , "Print Immediate Postdominators"),
clEnumVal(postdomtree , "Print Post Dominator Tree"),
clEnumVal(postdomfrontier, "Print Postdominance Frontier"),
0);
struct {
enum Ans AnID;
Pass *(*PassConstructor)(const string &Message);
} AnTable[] = {
// Global analyses
{ print , NewPrintFunction },
{ intervals , New<FunctionPass, IntervalPartition> },
{ loops , New<FunctionPass, LoopInfo> },
{ instforest , Create<PrinterPass<InstForest> > },
{ indvars , Create<PrinterPass<IndVars> > },
{ exprs , Create<PrinterPass<Exprs> > },
// IP Analyses...
{ printmodule , NewPrintModule },
{ printusedtypes , New<Pass, FindUsedTypes> },
{ callgraph , New<Pass, CallGraph> },
{ datastructure , New<Pass, DataStructure> },
{ unsafepointertypes, New<Pass, FindUnsafePointerTypes> },
// Dominator analyses
{ domset , New<FunctionPass, DominatorSet> },
{ idom , New<FunctionPass, ImmediateDominators> },
{ domtree , New<FunctionPass, DominatorTree> },
{ domfrontier , New<FunctionPass, DominanceFrontier> },
{ postdomset , New<FunctionPass, DominatorSet, DominatorSet::PostDomID> },
{ postidom , New<FunctionPass, ImmediateDominators, ImmediateDominators::PostDomID> },
{ postdomtree , New<FunctionPass, DominatorTree, DominatorTree::PostDomID> },
{ postdomfrontier , New<FunctionPass, DominanceFrontier, DominanceFrontier::PostDomID> },
};
int main(int argc, char **argv) {
cl::ParseCommandLineOptions(argc, argv, " llvm analysis printer tool\n");
Module *CurMod = 0;
try {
CurMod = ParseBytecodeFile(InputFilename);
if (!CurMod && !(CurMod = ParseAssemblyFile(InputFilename))){
std::cerr << "Input file didn't read correctly.\n";
return 1;
}
} catch (const ParseException &E) {
std::cerr << E.getMessage() << "\n";
return 1;
}
// Create a PassManager to hold and optimize the collection of passes we are
// about to build...
//
PassManager Analyses;
// Loop over all of the analyses looking for analyses to run...
for (unsigned i = 0; i < AnalysesList.size(); ++i) {
enum Ans AnalysisPass = AnalysesList[i];
for (unsigned j = 0; j < sizeof(AnTable)/sizeof(AnTable[0]); ++j) {
if (AnTable[j].AnID == AnalysisPass) {
string Message;
if (!Quiet)
Message = "\nRunning: '" +
string(AnalysesList.getArgDescription(AnalysisPass)) + "' analysis";
Analyses.add(AnTable[j].PassConstructor(Message));
break; // get an error later
}
}
}
Analyses.run(CurMod);
delete CurMod;
return 0;
}
<commit_msg>Rename functions to be more consistend with other pass constructors<commit_after>//===----------------------------------------------------------------------===//
// The LLVM analyze utility
//
// This utility is designed to print out the results of running various analysis
// passes on a program. This is useful for understanding a program, or for
// debugging an analysis pass.
//
// analyze --help - Output information about command line switches
// analyze --quiet - Do not print analysis name before output
//
//===----------------------------------------------------------------------===//
#include "llvm/Instruction.h"
#include "llvm/Module.h"
#include "llvm/Function.h"
#include "llvm/iPHINode.h"
#include "llvm/Type.h"
#include "llvm/PassManager.h"
#include "llvm/Bytecode/Reader.h"
#include "llvm/Assembly/Parser.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/Assembly/Writer.h"
#include "llvm/Analysis/Writer.h"
#include "llvm/Analysis/InstForest.h"
#include "llvm/Analysis/Dominators.h"
#include "llvm/Analysis/IntervalPartition.h"
#include "llvm/Analysis/Expressions.h"
#include "llvm/Analysis/InductionVariable.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/DataStructure.h"
#include "llvm/Analysis/FindUnsafePointerTypes.h"
#include "llvm/Analysis/FindUsedTypes.h"
#include "llvm/Support/InstIterator.h"
#include "Support/CommandLine.h"
#include <algorithm>
#include <iostream>
using std::ostream;
using std::string;
//===----------------------------------------------------------------------===//
// printPass - Specify how to print out a pass. For most passes, the standard
// way of using operator<< works great, so we use it directly...
//
template<class PassType>
static void printPass(PassType &P, ostream &O, Module *M) {
O << P;
}
template<class PassType>
static void printPass(PassType &P, ostream &O, Function *F) {
O << P;
}
// Other classes require more information to print out information, so we
// specialize the template here for them...
//
template<>
static void printPass(DataStructure &P, ostream &O, Module *M) {
P.print(O, M);
}
template<>
static void printPass(FindUsedTypes &FUT, ostream &O, Module *M) {
FUT.printTypes(O, M);
}
template<>
static void printPass(FindUnsafePointerTypes &FUPT, ostream &O,
Module *M) {
FUPT.printResults(M, O);
}
template <class PassType, class PassName>
class PassPrinter; // Do not implement
template <class PassName>
class PassPrinter<Pass, PassName> : public Pass {
const string Message;
const AnalysisID ID;
public:
PassPrinter(const string &M, AnalysisID id) : Message(M), ID(id) {}
virtual bool run(Module *M) {
std::cout << Message << "\n";
printPass(getAnalysis<PassName>(ID), std::cout, M);
return false;
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired(ID);
}
};
template <class PassName>
class PassPrinter<FunctionPass, PassName> : public FunctionPass {
const string Message;
const AnalysisID ID;
public:
PassPrinter(const string &M, AnalysisID id) : Message(M), ID(id) {}
virtual bool runOnFunction(Function *F) {
std::cout << Message << " on function '" << F->getName() << "'\n";
printPass(getAnalysis<PassName>(ID), std::cout, F);
return false;
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired(ID);
AU.setPreservesAll();
}
};
template <class PassType, class PassName, AnalysisID &ID>
Pass *New(const string &Message) {
return new PassPrinter<PassType, PassName>(Message, ID);
}
template <class PassType, class PassName>
Pass *New(const string &Message) {
return new PassPrinter<PassType, PassName>(Message, PassName::ID);
}
Pass *createPrintFunctionPass(const string &Message) {
return new PrintFunctionPass(Message, &std::cout);
}
Pass *createPrintModulePass(const string &Message) {
return new PrintModulePass(&std::cout);
}
struct InstForest : public FunctionPass {
void doit(Function *F) {
std::cout << analysis::InstForest<char>(F);
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
}
};
struct IndVars : public FunctionPass {
void doit(Function *F) {
LoopInfo &LI = getAnalysis<LoopInfo>();
for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
if (PHINode *PN = dyn_cast<PHINode>(*I)) {
InductionVariable IV(PN, &LI);
if (IV.InductionType != InductionVariable::Unknown)
std::cout << IV;
}
}
void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired(LoopInfo::ID);
AU.setPreservesAll();
}
};
struct Exprs : public FunctionPass {
static void doit(Function *F) {
std::cout << "Classified expressions for: " << F->getName() << "\n";
for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
std::cout << *I;
if ((*I)->getType() == Type::VoidTy) continue;
analysis::ExprType R = analysis::ClassifyExpression(*I);
if (R.Var == *I) continue; // Doesn't tell us anything
std::cout << "\t\tExpr =";
switch (R.ExprTy) {
case analysis::ExprType::ScaledLinear:
WriteAsOperand(std::cout << "(", (Value*)R.Scale) << " ) *";
// fall through
case analysis::ExprType::Linear:
WriteAsOperand(std::cout << "(", R.Var) << " )";
if (R.Offset == 0) break;
else std::cout << " +";
// fall through
case analysis::ExprType::Constant:
if (R.Offset) WriteAsOperand(std::cout, (Value*)R.Offset);
else std::cout << " 0";
break;
}
std::cout << "\n\n";
}
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
}
};
template<class TraitClass>
class PrinterPass : public TraitClass {
const string Message;
public:
PrinterPass(const string &M) : Message(M) {}
virtual bool runOnFunction(Function *F) {
std::cout << Message << " on function '" << F->getName() << "'\n";
TraitClass::doit(F);
return false;
}
};
template<class PassClass>
Pass *Create(const string &Message) {
return new PassClass(Message);
}
enum Ans {
// global analyses
print, intervals, exprs, instforest, loops, indvars,
// ip analyses
printmodule, callgraph, datastructure, printusedtypes, unsafepointertypes,
domset, idom, domtree, domfrontier,
postdomset, postidom, postdomtree, postdomfrontier,
};
cl::String InputFilename ("", "Load <arg> file to analyze", cl::NoFlags, "-");
cl::Flag Quiet ("q", "Don't print analysis pass names");
cl::Alias QuietA ("quiet", "Alias for -q", cl::NoFlags, Quiet);
cl::EnumList<enum Ans> AnalysesList(cl::NoFlags,
clEnumVal(print , "Print each function"),
clEnumVal(intervals , "Print Interval Partitions"),
clEnumVal(exprs , "Classify Expressions"),
clEnumVal(instforest , "Print Instruction Forest"),
clEnumVal(loops , "Print natural loops"),
clEnumVal(indvars , "Print Induction Variables"),
clEnumVal(printmodule , "Print entire module"),
clEnumVal(callgraph , "Print Call Graph"),
clEnumVal(datastructure , "Print data structure information"),
clEnumVal(printusedtypes , "Print types used by module"),
clEnumVal(unsafepointertypes, "Print unsafe pointer types"),
clEnumVal(domset , "Print Dominator Sets"),
clEnumVal(idom , "Print Immediate Dominators"),
clEnumVal(domtree , "Print Dominator Tree"),
clEnumVal(domfrontier , "Print Dominance Frontier"),
clEnumVal(postdomset , "Print Postdominator Sets"),
clEnumVal(postidom , "Print Immediate Postdominators"),
clEnumVal(postdomtree , "Print Post Dominator Tree"),
clEnumVal(postdomfrontier, "Print Postdominance Frontier"),
0);
struct {
enum Ans AnID;
Pass *(*PassConstructor)(const string &Message);
} AnTable[] = {
// Global analyses
{ print , createPrintFunctionPass },
{ intervals , New<FunctionPass, IntervalPartition> },
{ loops , New<FunctionPass, LoopInfo> },
{ instforest , Create<PrinterPass<InstForest> > },
{ indvars , Create<PrinterPass<IndVars> > },
{ exprs , Create<PrinterPass<Exprs> > },
// IP Analyses...
{ printmodule , createPrintModulePass },
{ printusedtypes , New<Pass, FindUsedTypes> },
{ callgraph , New<Pass, CallGraph> },
{ datastructure , New<Pass, DataStructure> },
{ unsafepointertypes, New<Pass, FindUnsafePointerTypes> },
// Dominator analyses
{ domset , New<FunctionPass, DominatorSet> },
{ idom , New<FunctionPass, ImmediateDominators> },
{ domtree , New<FunctionPass, DominatorTree> },
{ domfrontier , New<FunctionPass, DominanceFrontier> },
{ postdomset , New<FunctionPass, DominatorSet, DominatorSet::PostDomID> },
{ postidom , New<FunctionPass, ImmediateDominators, ImmediateDominators::PostDomID> },
{ postdomtree , New<FunctionPass, DominatorTree, DominatorTree::PostDomID> },
{ postdomfrontier , New<FunctionPass, DominanceFrontier, DominanceFrontier::PostDomID> },
};
int main(int argc, char **argv) {
cl::ParseCommandLineOptions(argc, argv, " llvm analysis printer tool\n");
Module *CurMod = 0;
try {
CurMod = ParseBytecodeFile(InputFilename);
if (!CurMod && !(CurMod = ParseAssemblyFile(InputFilename))){
std::cerr << "Input file didn't read correctly.\n";
return 1;
}
} catch (const ParseException &E) {
std::cerr << E.getMessage() << "\n";
return 1;
}
// Create a PassManager to hold and optimize the collection of passes we are
// about to build...
//
PassManager Analyses;
// Loop over all of the analyses looking for analyses to run...
for (unsigned i = 0; i < AnalysesList.size(); ++i) {
enum Ans AnalysisPass = AnalysesList[i];
for (unsigned j = 0; j < sizeof(AnTable)/sizeof(AnTable[0]); ++j) {
if (AnTable[j].AnID == AnalysisPass) {
string Message;
if (!Quiet)
Message = "\nRunning: '" +
string(AnalysesList.getArgDescription(AnalysisPass)) + "' analysis";
Analyses.add(AnTable[j].PassConstructor(Message));
break; // get an error later
}
}
}
Analyses.run(CurMod);
delete CurMod;
return 0;
}
<|endoftext|>
|
<commit_before>#include "multiverse.h"
#include "game_window.h"
#include "cosmos.h"
#include "game/types_specification/all_component_includes.h"
multiverse::multiverse()
: main_cosmos_timer(60, 5)
{
main_cosmos = cosmos();
main_cosmos.reserve_storage_for_entities(50000);
main_cosmos.advance_deterministic_schemata(cosmic_entropy(), [this](fixed_step& step) {
main_cosmos_manager.populate_world_with_entities(step);
});
}
void multiverse::control(augs::machine_entropy entropy) {
main_cosmos_player.buffer_entropy_for_next_step(entropy);
for (auto& raw_input : entropy.local) {
if (raw_input.key_event == window::event::PRESSED) {
if (raw_input.key == window::event::keys::_1) {
main_cosmos_timer = augs::fixed_delta_timer(60, 500000);
}
if (raw_input.key == window::event::keys::_2) {
main_cosmos_timer = augs::fixed_delta_timer(128, 500000);
}
if (raw_input.key == window::event::keys::_3) {
main_cosmos_timer = augs::fixed_delta_timer(400, 500000);
}
if (raw_input.key == window::event::keys::_4) {
stepping_speed = 0.1f;
}
if (raw_input.key == window::event::keys::_5) {
stepping_speed = 1.f;
}
if (raw_input.key == window::event::keys::_6) {
stepping_speed = 6.f;
}
if (raw_input.key == window::event::keys::F4) {
LOG_COLOR(console_color::YELLOW, "Separator");
}
}
}
main_cosmos_timer.set_stepping_speed_multiplier(stepping_speed);
}
void multiverse::simulate() {
auto steps_to_perform = main_cosmos_timer.count_logic_steps_to_perform();
while (steps_to_perform--) {
auto machine_entropy_for_this_step = main_cosmos_player.obtain_machine_entropy_for_next_step();
auto cosmic_entropy_for_this_step = main_cosmos_manager.make_cosmic_entropy(machine_entropy_for_this_step, main_cosmos);
renderer::get_current().clear_logic_lines();
main_cosmos.delta = main_cosmos_timer.get_fixed_delta();
main_cosmos.advance_deterministic_schemata(cosmic_entropy_for_this_step,
[this](fixed_step& step) { main_cosmos_manager.pre_solve(step); },
[this](fixed_step& step) { main_cosmos_manager.post_solve(step); }
);
main_cosmos_timer.increment_total_steps_passed();
}
}
void multiverse::view(game_window& window) const {
frame_profiler.fps_counter.new_measurement();
auto& target = renderer::get_current();
target.clear_current_fbo();
target.set_viewport({0, 0, main_cosmos.settings.screen_size.x, main_cosmos.settings.screen_size.y });
basic_viewing_step main_cosmos_viewing_step(main_cosmos, frame_timer.extract_variable_delta(main_cosmos_timer), target);
main_cosmos_manager.view_cosmos(main_cosmos_viewing_step);
frame_profiler.triangles.measure(target.triangles_drawn_total);
target.triangles_drawn_total = 0;
window.window.swap_buffers();
frame_profiler.fps_counter.end_measurement();
}<commit_msg>removed unnecessary cosmic assignment<commit_after>#include "multiverse.h"
#include "game_window.h"
#include "cosmos.h"
#include "game/types_specification/all_component_includes.h"
multiverse::multiverse()
: main_cosmos_timer(60, 5)
{
main_cosmos.reserve_storage_for_entities(50000);
main_cosmos.advance_deterministic_schemata(cosmic_entropy(), [this](fixed_step& step) {
main_cosmos_manager.populate_world_with_entities(step);
});
}
void multiverse::control(augs::machine_entropy entropy) {
main_cosmos_player.buffer_entropy_for_next_step(entropy);
for (auto& raw_input : entropy.local) {
if (raw_input.key_event == window::event::PRESSED) {
if (raw_input.key == window::event::keys::_1) {
main_cosmos_timer = augs::fixed_delta_timer(60, 500000);
}
if (raw_input.key == window::event::keys::_2) {
main_cosmos_timer = augs::fixed_delta_timer(128, 500000);
}
if (raw_input.key == window::event::keys::_3) {
main_cosmos_timer = augs::fixed_delta_timer(400, 500000);
}
if (raw_input.key == window::event::keys::_4) {
stepping_speed = 0.1f;
}
if (raw_input.key == window::event::keys::_5) {
stepping_speed = 1.f;
}
if (raw_input.key == window::event::keys::_6) {
stepping_speed = 6.f;
}
if (raw_input.key == window::event::keys::F4) {
LOG_COLOR(console_color::YELLOW, "Separator");
}
}
}
main_cosmos_timer.set_stepping_speed_multiplier(stepping_speed);
}
void multiverse::simulate() {
auto steps_to_perform = main_cosmos_timer.count_logic_steps_to_perform();
while (steps_to_perform--) {
auto machine_entropy_for_this_step = main_cosmos_player.obtain_machine_entropy_for_next_step();
auto cosmic_entropy_for_this_step = main_cosmos_manager.make_cosmic_entropy(machine_entropy_for_this_step, main_cosmos);
renderer::get_current().clear_logic_lines();
main_cosmos.delta = main_cosmos_timer.get_fixed_delta();
main_cosmos.advance_deterministic_schemata(cosmic_entropy_for_this_step,
[this](fixed_step& step) { main_cosmos_manager.pre_solve(step); },
[this](fixed_step& step) { main_cosmos_manager.post_solve(step); }
);
main_cosmos_timer.increment_total_steps_passed();
}
}
void multiverse::view(game_window& window) const {
frame_profiler.fps_counter.new_measurement();
auto& target = renderer::get_current();
target.clear_current_fbo();
target.set_viewport({0, 0, main_cosmos.settings.screen_size.x, main_cosmos.settings.screen_size.y });
basic_viewing_step main_cosmos_viewing_step(main_cosmos, frame_timer.extract_variable_delta(main_cosmos_timer), target);
main_cosmos_manager.view_cosmos(main_cosmos_viewing_step);
frame_profiler.triangles.measure(target.triangles_drawn_total);
target.triangles_drawn_total = 0;
window.window.swap_buffers();
frame_profiler.fps_counter.end_measurement();
}<|endoftext|>
|
<commit_before>// Copyright 2019 The TCMalloc 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.
//
// Test out of memory handling. Kept in a separate test since running out
// of memory causes other parts of the runtime to behave improperly.
#include <stddef.h>
#include <stdlib.h>
#include <new>
#include "gtest/gtest.h"
#include "tcmalloc/internal/config.h"
#include "tcmalloc/internal/linked_list.h"
#include "tcmalloc/testing/testutil.h"
namespace tcmalloc {
namespace {
class OutOfMemoryTest : public ::testing::Test {
public:
OutOfMemoryTest() { SetTestResourceLimit(); }
};
TEST_F(OutOfMemoryTest, TestUntilFailure) {
// Check that large allocations fail with NULL instead of crashing.
static const size_t kIncrement = 100 << 20;
static const size_t kMaxSize = ~static_cast<size_t>(0);
for (size_t s = kIncrement; s < kMaxSize - kIncrement; s += kIncrement) {
SCOPED_TRACE(s);
void* large_object = ::operator new(s, std::nothrow);
if (large_object == nullptr) {
return;
}
::operator delete(large_object);
}
ASSERT_TRUE(false) << "Did not run out of memory";
}
TEST_F(OutOfMemoryTest, SmallAllocs) {
// Check that large allocations fail with NULL instead of crashing.
static constexpr size_t kSize = tcmalloc_internal::kHugePageSize / 2 - 1;
void* list = nullptr;
bool found = false;
for (int i = 0; i < 8000; i++) {
void* obj = ::operator new(kSize, std::nothrow);
if (obj == nullptr) {
found = true;
break;
}
tcmalloc_internal::SLL_Push(&list, obj);
}
// Cleanup
while (list != nullptr) {
void* obj = tcmalloc_internal::SLL_Pop(&list);
operator delete(obj);
}
ASSERT_TRUE(found) << "Did not run out of memory";
}
} // namespace
} // namespace tcmalloc
<commit_msg>Fix a flakiness issue in outofmemory_test caused by running out of memory while sampling an allocation.<commit_after>// Copyright 2019 The TCMalloc 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.
//
// Test out of memory handling. Kept in a separate test since running out
// of memory causes other parts of the runtime to behave improperly.
#include <stddef.h>
#include <stdlib.h>
#include <new>
#include "gtest/gtest.h"
#include "tcmalloc/internal/config.h"
#include "tcmalloc/internal/linked_list.h"
#include "tcmalloc/testing/testutil.h"
namespace tcmalloc {
namespace {
class OutOfMemoryTest : public ::testing::Test {
public:
OutOfMemoryTest() { SetTestResourceLimit(); }
};
TEST_F(OutOfMemoryTest, TestUntilFailure) {
// Disable sampling.
ScopedGuardedSamplingRate gs(-1);
ScopedProfileSamplingRate s(1);
// Check that large allocations fail with NULL instead of crashing.
static const size_t kIncrement = 100 << 20;
static const size_t kMaxSize = ~static_cast<size_t>(0);
for (size_t s = kIncrement; s < kMaxSize - kIncrement; s += kIncrement) {
SCOPED_TRACE(s);
void* large_object = ::operator new(s, std::nothrow);
if (large_object == nullptr) {
return;
}
::operator delete(large_object);
}
ASSERT_TRUE(false) << "Did not run out of memory";
}
TEST_F(OutOfMemoryTest, SmallAllocs) {
// Disable sampling.
ScopedGuardedSamplingRate gs(-1);
ScopedProfileSamplingRate s(1);
// Check that large allocations fail with NULL instead of crashing.
static constexpr size_t kSize = tcmalloc_internal::kHugePageSize / 2 - 1;
void* list = nullptr;
bool found = false;
for (int i = 0; i < 8000; i++) {
void* obj = ::operator new(kSize, std::nothrow);
if (obj == nullptr) {
found = true;
break;
}
tcmalloc_internal::SLL_Push(&list, obj);
}
// Cleanup
while (list != nullptr) {
void* obj = tcmalloc_internal::SLL_Pop(&list);
operator delete(obj);
}
ASSERT_TRUE(found) << "Did not run out of memory";
}
} // namespace
} // namespace tcmalloc
<|endoftext|>
|
<commit_before>#include "InstructionLexer.hpp"
#include <functional>
#include <iostream>
#include <regex>
#include <utility>
#include <vector>
#include "boost/range/algorithm.hpp"
#include "boost/tokenizer.hpp"
Tokens InstructionLexer::parseInstructions(const std::string& input)
{
boost::tokenizer<boost::char_separator<char>> lineTokenizer{
input, boost::char_separator<char>{"\n"}};
Tokens tokens;
for (const auto& line : lineTokenizer)
{
if (line.at(0) != ' ')
{
throw UnknownInstruction("Invalid line: " + line);
}
boost::copy(parseLine(line), std::back_inserter(tokens));
}
return tokens;
}
Tokens InstructionLexer::parseLine(const std::string& line)
{
boost::tokenizer<boost::char_separator<char>> instructionTokenizer{
line, boost::char_separator<char>{", "}};
Tokens tokens;
for (const auto& token : instructionTokenizer)
{
boost::copy(parseInstruction(token), std::back_inserter(tokens));
}
return tokens;
}
const auto alwaysZeroValue = [](const std::string&) -> Token::ValueType {
return 0;
};
const auto convertToUnsigned = [](const std::string& text) -> Token::ValueType {
try
{
return std::stoi(text);
}
catch (const std::exception&)
{
return 0;
}
};
Tokens InstructionLexer::parseInstruction(const std::string& instruction)
{
const auto trimmedInstruction = trimWhitespacesOnFront(instruction);
if (trimmedInstruction.empty())
{
return {};
}
using TextToTokens = std::vector<
std::tuple<std::regex, TokenType,
std::function<Token::ValueType(const std::string&)>>>;
const TextToTokens acceptableInstructions{
{std::regex{"out"}, TokenType::Out, alwaysZeroValue},
{std::regex{"\\(0\\)"}, TokenType::ZeroWithBrackets, alwaysZeroValue},
{std::regex{"ld"}, TokenType::Ld, alwaysZeroValue},
{std::regex{"a"}, TokenType::A, alwaysZeroValue},
{std::regex{"[0-9]{1,2}|1[0-9]{1,2}|2[0-4][0-9]|25[0-5]"},
TokenType::Number8Bit, convertToUnsigned}};
const auto noArgumentInstructionPosition = std::find_if(
acceptableInstructions.begin(), acceptableInstructions.end(),
[&](const auto& tokenMap) {
return std::regex_match(trimmedInstruction, std::get<0>(tokenMap));
});
if (noArgumentInstructionPosition != acceptableInstructions.end())
{
return {
{std::get<1>(*noArgumentInstructionPosition),
std::get<2>(*noArgumentInstructionPosition)(trimmedInstruction)}};
}
throw UnknownInstruction{"Unknown instruction: " + instruction};
}
std::string
InstructionLexer::trimWhitespacesOnFront(const std::string& instruction)
{
const auto firstRelevantCharPosition = instruction.find_first_not_of(" \t");
if (firstRelevantCharPosition != std::string::npos)
{
return instruction.substr(firstRelevantCharPosition);
}
return {};
}
<commit_msg>Address review issues<commit_after>#include "InstructionLexer.hpp"
#include <functional>
#include <iostream>
#include <regex>
#include <utility>
#include <vector>
#include "boost/algorithm/string/trim.hpp"
#include "boost/range/algorithm.hpp"
#include "boost/tokenizer.hpp"
Tokens InstructionLexer::parseInstructions(const std::string& input)
{
boost::tokenizer<boost::char_separator<char>> lineTokenizer{
input, boost::char_separator<char>{"\n"}};
Tokens tokens;
for (const auto& line : lineTokenizer)
{
if (line.at(0) != ' ')
{
throw UnknownInstruction("Invalid line: " + line);
}
boost::copy(parseLine(line), std::back_inserter(tokens));
}
return tokens;
}
Tokens InstructionLexer::parseLine(const std::string& line)
{
boost::tokenizer<boost::char_separator<char>> instructionTokenizer{
line, boost::char_separator<char>{", "}};
Tokens tokens;
for (const auto& token : instructionTokenizer)
{
boost::copy(parseInstruction(token), std::back_inserter(tokens));
}
return tokens;
}
const auto alwaysZeroValue = [](const std::string&) -> Token::ValueType {
return 0;
};
const auto convertToUnsigned = [](const std::string& text) -> Token::ValueType {
return std::stoi(text);
};
Tokens InstructionLexer::parseInstruction(const std::string& instruction)
{
const auto trimmedInstruction = trimWhitespacesOnFront(instruction);
if (trimmedInstruction.empty())
{
return {};
}
using TextToTokens = std::vector<
std::tuple<std::regex, TokenType,
std::function<Token::ValueType(const std::string&)>>>;
const TextToTokens acceptableInstructions{
{std::regex{"out"}, TokenType::Out, alwaysZeroValue},
{std::regex{"\\(0\\)"}, TokenType::ZeroWithBrackets, alwaysZeroValue},
{std::regex{"ld"}, TokenType::Ld, alwaysZeroValue},
{std::regex{"a"}, TokenType::A, alwaysZeroValue},
{std::regex{"[0-9]{1,2}|1[0-9]{1,2}|2[0-4][0-9]|25[0-5]"},
TokenType::Number8Bit, convertToUnsigned}};
const auto noArgumentInstructionPosition = std::find_if(
acceptableInstructions.begin(), acceptableInstructions.end(),
[&](const auto& tokenMap) {
return std::regex_match(trimmedInstruction, std::get<0>(tokenMap));
});
if (noArgumentInstructionPosition != acceptableInstructions.end())
{
return {
{std::get<1>(*noArgumentInstructionPosition),
std::get<2>(*noArgumentInstructionPosition)(trimmedInstruction)}};
}
throw UnknownInstruction{"Unknown instruction: " + instruction};
}
std::string
InstructionLexer::trimWhitespacesOnFront(const std::string& instruction)
{
return boost::algorithm::trim_left_copy_if(instruction, [](auto character) {
return character == ' ' || character == '\t';
});
}
<|endoftext|>
|
<commit_before>#include <v8.h>
#include <node.h>
#include <node_buffer.h>
#include <cstring>
using namespace v8;
using namespace node;
namespace {
// this is an application of the Curiously Recurring Template Pattern
template <class T> struct UnaryAction {
Handle<Value> apply(Buffer& buffer, const Arguments& args);
Handle<Value> operator()(const Arguments& args) {
if (args[0]->IsObject()) {
Local<Object> object = args[0]->ToObject();
if (Buffer::HasInstance(object)) {
Buffer& buffer = *ObjectWrap::Unwrap<Buffer>(object);
return static_cast<T*>(this)->apply(buffer, args);
}
}
static Persistent<String> illegalArgumentException = Persistent<String>::New(String::New("First argument should be a buffer."));
return ThrowException(Exception::TypeError(illegalArgumentException));
}
};
template <class T> struct BinaryAction {
Handle<Value> apply(Buffer& a, Buffer& b, const Arguments& args);
Handle<Value> operator()(const Arguments& args) {
if (args[0]->IsObject() && args[1]->IsObject()) {
Local<Object> arg0 = args[0]->ToObject();
Local<Object> arg1 = args[0]->ToObject();
if (Buffer::HasInstance(arg0) && Buffer::HasInstance(arg1)) {
Buffer& a = *ObjectWrap::Unwrap<Buffer>(arg0);
Buffer& b = *ObjectWrap::Unwrap<Buffer>(arg1);
return static_cast<T*>(this)->apply(a, b, args);
}
}
static Persistent<String> illegalArgumentException = Persistent<String>::New(String::New("First and second argument should be a buffer."));
return ThrowException(Exception::TypeError(illegalArgumentException));
}
};
//
// helper functions
//
Handle<Value> clear(Buffer& buffer, int c) {
memset(buffer.data(), c, buffer.length());
return buffer.handle_;
}
Handle<Value> fill(Buffer& buffer, void* pattern, size_t size) {
if (size >= buffer.length()) {
memcpy(buffer.data(), pattern, buffer.length());
} else {
const int n_copies = buffer.length() / size;
const int remainder = buffer.length() % size;
for (int i = 0; i < n_copies; i++) {
memcpy(buffer.data() + size * i, pattern, size);
}
memcpy(buffer.data() + size * n_copies, pattern, remainder);
}
return buffer.handle_;
}
int compare(Buffer& a, Buffer& b) {
if (a.length() != b.length()) {
return a.length() > b.length() ? 1 : -1;
}
return memcmp(a.data(), b.data(), a.length());
}
//
// actions
//
struct ClearAction: UnaryAction<ClearAction> {
Handle<Value> apply(Buffer& buffer, const Arguments& args) {
const int c = args[1]->IsInt32() ? args[1]->ToInt32()->Int32Value() : 0;
return clear(buffer, c);
}
};
struct FillAction: UnaryAction<FillAction> {
Handle<Value> apply(Buffer& buffer, const Arguments& args) {
if (args[1]->IsInt32()) {
int c = args[1]->ToInt32()->Int32Value();
return clear(buffer, c);
}
if (args[1]->IsString()) {
String::AsciiValue s(args[1]->ToString());
return fill(buffer, *s, s.length());
}
if (args[1]->IsObject()) {
Local<Object> o = args[1]->ToObject();
if (Buffer::HasInstance(o)) {
Buffer& src = *Buffer::Unwrap<Buffer>(o);
return fill(buffer, src.data(), src.length());
}
}
static Persistent<String> illegalArgumentException = Persistent<String>::New(String::New(
"Second argument should be either a string, a buffer or an integer."));
return ThrowException(Exception::TypeError(illegalArgumentException));
}
};
struct EqualsAction: BinaryAction<EqualsAction> {
Handle<Value> apply(Buffer& a, Buffer& b, const Arguments& args) {
HandleScope scope;
return scope.Close(Boolean::New(compare(a, b)));
}
};
struct CompareAction: BinaryAction<CompareAction> {
Handle<Value> apply(Buffer& a, Buffer& b, const Arguments& args) {
HandleScope scope;
return scope.Close(Integer::New(compare(a, b)));
}
};
//
// V8 function callbacks
//
Handle<Value> Clear(const Arguments& args) {
return ClearAction()(args);
}
Handle<Value> Fill(const Arguments& args) {
return FillAction()(args);
}
Handle<Value> Equals(const Arguments& args) {
return CompareAction()(args);
}
Handle<Value> Compare(const Arguments& args) {
return CompareAction()(args);
}
extern "C" void init(Handle<Object> target) {
HandleScope scope;
target->Set(String::New("fill"), FunctionTemplate::New(Fill)->GetFunction());
target->Set(String::New("clear"), FunctionTemplate::New(Clear)->GetFunction());
target->Set(String::New("equals"), FunctionTemplate::New(Equals)->GetFunction());
target->Set(String::New("compare"), FunctionTemplate::New(Compare)->GetFunction());
}
}
<commit_msg>Fix indentation. It's fine and dandy that the nodejs source uses two spaces but tabs are just easier to read.<commit_after>#include <v8.h>
#include <node.h>
#include <node_buffer.h>
#include <cstring>
using namespace v8;
using namespace node;
namespace {
// this is an application of the Curiously Recurring Template Pattern
template <class T> struct UnaryAction {
Handle<Value> apply(Buffer& buffer, const Arguments& args);
Handle<Value> operator()(const Arguments& args) {
if (args[0]->IsObject()) {
Local<Object> object = args[0]->ToObject();
if (Buffer::HasInstance(object)) {
Buffer& buffer = *ObjectWrap::Unwrap<Buffer>(object);
return static_cast<T*>(this)->apply(buffer, args);
}
}
static Persistent<String> illegalArgumentException = Persistent<String>::New(String::New("First argument should be a buffer."));
return ThrowException(Exception::TypeError(illegalArgumentException));
}
};
template <class T> struct BinaryAction {
Handle<Value> apply(Buffer& a, Buffer& b, const Arguments& args);
Handle<Value> operator()(const Arguments& args) {
if (args[0]->IsObject() && args[1]->IsObject()) {
Local<Object> arg0 = args[0]->ToObject();
Local<Object> arg1 = args[0]->ToObject();
if (Buffer::HasInstance(arg0) && Buffer::HasInstance(arg1)) {
Buffer& a = *ObjectWrap::Unwrap<Buffer>(arg0);
Buffer& b = *ObjectWrap::Unwrap<Buffer>(arg1);
return static_cast<T*>(this)->apply(a, b, args);
}
}
static Persistent<String> illegalArgumentException = Persistent<String>::New(String::New("First and second argument should be a buffer."));
return ThrowException(Exception::TypeError(illegalArgumentException));
}
};
//
// helper functions
//
Handle<Value> clear(Buffer& buffer, int c) {
memset(buffer.data(), c, buffer.length());
return buffer.handle_;
}
Handle<Value> fill(Buffer& buffer, void* pattern, size_t size) {
if (size >= buffer.length()) {
memcpy(buffer.data(), pattern, buffer.length());
} else {
const int n_copies = buffer.length() / size;
const int remainder = buffer.length() % size;
for (int i = 0; i < n_copies; i++) {
memcpy(buffer.data() + size * i, pattern, size);
}
memcpy(buffer.data() + size * n_copies, pattern, remainder);
}
return buffer.handle_;
}
int compare(Buffer& a, Buffer& b) {
if (a.length() != b.length()) {
return a.length() > b.length() ? 1 : -1;
}
return memcmp(a.data(), b.data(), a.length());
}
//
// actions
//
struct ClearAction: UnaryAction<ClearAction> {
Handle<Value> apply(Buffer& buffer, const Arguments& args) {
const int c = args[1]->IsInt32() ? args[1]->ToInt32()->Int32Value() : 0;
return clear(buffer, c);
}
};
struct FillAction: UnaryAction<FillAction> {
Handle<Value> apply(Buffer& buffer, const Arguments& args) {
if (args[1]->IsInt32()) {
int c = args[1]->ToInt32()->Int32Value();
return clear(buffer, c);
}
if (args[1]->IsString()) {
String::AsciiValue s(args[1]->ToString());
return fill(buffer, *s, s.length());
}
if (args[1]->IsObject()) {
Local<Object> o = args[1]->ToObject();
if (Buffer::HasInstance(o)) {
Buffer& src = *Buffer::Unwrap<Buffer>(o);
return fill(buffer, src.data(), src.length());
}
}
static Persistent<String> illegalArgumentException = Persistent<String>::New(String::New(
"Second argument should be either a string, a buffer or an integer."));
return ThrowException(Exception::TypeError(illegalArgumentException));
}
};
struct EqualsAction: BinaryAction<EqualsAction> {
Handle<Value> apply(Buffer& a, Buffer& b, const Arguments& args) {
HandleScope scope;
return scope.Close(Boolean::New(compare(a, b)));
}
};
struct CompareAction: BinaryAction<CompareAction> {
Handle<Value> apply(Buffer& a, Buffer& b, const Arguments& args) {
HandleScope scope;
return scope.Close(Integer::New(compare(a, b)));
}
};
//
// V8 function callbacks
//
Handle<Value> Clear(const Arguments& args) {
return ClearAction()(args);
}
Handle<Value> Fill(const Arguments& args) {
return FillAction()(args);
}
Handle<Value> Equals(const Arguments& args) {
return CompareAction()(args);
}
Handle<Value> Compare(const Arguments& args) {
return CompareAction()(args);
}
extern "C" void init(Handle<Object> target) {
HandleScope scope;
target->Set(String::New("fill"), FunctionTemplate::New(Fill)->GetFunction());
target->Set(String::New("clear"), FunctionTemplate::New(Clear)->GetFunction());
target->Set(String::New("equals"), FunctionTemplate::New(Equals)->GetFunction());
target->Set(String::New("compare"), FunctionTemplate::New(Compare)->GetFunction());
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved
*/
#include "../../StroikaPreComp.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#if qPlatform_Windows
#include <io.h>
#elif qPlatform_POSIX
#include <unistd.h>
#endif
#include "../../Debug/AssertExternallySynchronizedLock.h"
#include "../../Debug/Trace.h"
#include "../../Execution/Common.h"
#include "../../Execution/ErrNoException.h"
#include "../../Execution/Exceptions.h"
#if qPlatform_Windows
#include "../../Execution/Platform/Windows/Exception.h"
#endif
#include "../../IO/FileAccessException.h"
#include "../../Streams/BufferedInputStream.h"
#include "FileInputStream.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::IO;
using namespace Stroika::Foundation::IO::FileSystem;
using Execution::make_unique_lock;
using Streams::InputStream;
using Streams::SeekOffsetType;
#if qPlatform_Windows
using Execution::Platform::Windows::ThrowIfFalseGetLastError;
#endif
// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
/*
********************************************************************************
**************************** FileSystem::FileInputStream ***********************
********************************************************************************
*/
class FileInputStream::Rep_ : public InputStream<Byte>::_IRep, private Debug::AssertExternallySynchronizedLock {
public:
Rep_ () = delete;
Rep_ (const Rep_&) = delete;
Rep_ (const String& fileName, SeekableFlag seekable)
: fFD_ (-1)
, fSeekable_ (seekable)
{
try {
#if qPlatform_Windows
errno_t e = ::_wsopen_s (&fFD_, fileName.c_str (), (O_RDONLY | O_BINARY), _SH_DENYNO, 0);
if (e != 0) {
Execution::errno_ErrorException::Throw (e);
}
ThrowIfFalseGetLastError (fFD_ != -1);
#else
Execution::ThrowErrNoIfNegative (fFD_ = ::open (fileName.AsNarrowSDKString ().c_str (), O_RDONLY));
#endif
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace (L"opened fd: %d", fFD_);
#endif
}
Stroika_Foundation_IO_FileAccessException_CATCH_REBIND_FILENAME_ACCCESS_HELPER(fileName, FileAccessMode::eRead);
}
~Rep_ ()
{
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper ctx (L"FileInputStream::Rep_::~Rep_");
DbgTrace (L"closing %d", fFD_);
#endif
#if qPlatform_Windows
::_close (fFD_);
#else
::close (fFD_);
#endif
}
nonvirtual Rep_& operator= (const Rep_&) = delete;
virtual bool IsSeekable () const override
{
return fSeekable_ == eSeekable;
}
virtual size_t Read (Byte* intoStart, Byte* intoEnd) override
{
RequireNotNull (intoStart);
RequireNotNull (intoEnd);
Require (intoStart < intoEnd);
size_t nRequested = intoEnd - intoStart;
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper ctx (L"FileInputStream::Rep_::Read");
DbgTrace (L"(nRequested: %llu)", static_cast<unsigned long long> (nRequested));
#endif
lock_guard<const AssertExternallySynchronizedLock> critSec { *this };
#if qPlatform_Windows
return static_cast<size_t> (Execution::ThrowErrNoIfNegative (::_read (fFD_, intoStart, Math::PinToMaxForType<unsigned int> (nRequested))));
#else
return static_cast<size_t> (Execution::ThrowErrNoIfNegative (::read (fFD_, intoStart, nRequested)));
#endif
}
virtual Streams::SeekOffsetType GetReadOffset () const override
{
lock_guard<const AssertExternallySynchronizedLock> critSec { *this };
#if qPlatform_Windows
return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::_lseeki64 (fFD_, 0, SEEK_CUR)));
#else
return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::lseek64 (fFD_, 0, SEEK_CUR)));
#endif
}
virtual Streams::SeekOffsetType SeekRead (Streams::Whence whence, Streams::SignedSeekOffsetType offset) override
{
using namespace Streams;
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper ctx (L"FileInputStream::Rep_::SeekRead");
DbgTrace (L"(whence: %d, offset: %lld)", whence, static_cast<long long> (offset));
#endif
lock_guard<const AssertExternallySynchronizedLock> critSec { *this };
switch (whence) {
case Whence::eFromStart: {
if (offset < 0) {
Execution::Throw (std::range_error ("seek"));
}
#if qPlatform_Windows
return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::_lseeki64 (fFD_, offset, SEEK_SET)));
#else
return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::lseek64 (fFD_, offset, SEEK_SET)));
#endif
}
break;
case Whence::eFromCurrent: {
#if qPlatform_Windows
return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::_lseeki64 (fFD_, offset, SEEK_CUR)));
#else
return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::lseek64 (fFD_, offset, SEEK_CUR)));
#endif
}
break;
case Whence::eFromEnd: {
#if qPlatform_Windows
return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::_lseeki64 (fFD_, offset, SEEK_END)));
#else
return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::lseek64 (fFD_, offset, SEEK_END)));
#endif
}
break;
}
RequireNotReached ();
return 0;
}
private:
int fFD_;
SeekableFlag fSeekable_;
};
FileInputStream::FileInputStream (const String& fileName, SeekableFlag seekable)
: FileInputStream (make_shared<Rep_> (fileName, seekable))
{
}
FileInputStream::FileInputStream (const shared_ptr<Rep_>& rep)
: inherited (rep)
{
}
InputStream<Byte> FileInputStream::mk (const String& fileName, SeekableFlag seekable, BufferFlag bufferFlag)
{
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper ctx (L"FileInputStream::mk");
DbgTrace (L"(fileName: %s, seekable: %d, bufferFlag: %d)", fileName.c_str (), seekable, bufferFlag);
#endif
InputStream<Byte> in = FileInputStream (fileName, seekable);
switch (bufferFlag) {
case eBuffered:
return Streams::BufferedInputStream<Byte> (in);
case eUnbuffered:
return in;
default:
AssertNotReached ();
return in;
}
}
<commit_msg>more work - lseek64 - on macos / darwin port<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved
*/
#include "../../StroikaPreComp.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#if qPlatform_Windows
#include <io.h>
#elif qPlatform_POSIX
#include <unistd.h>
#endif
#include "../../Debug/AssertExternallySynchronizedLock.h"
#include "../../Debug/Trace.h"
#include "../../Execution/Common.h"
#include "../../Execution/ErrNoException.h"
#include "../../Execution/Exceptions.h"
#if qPlatform_Windows
#include "../../Execution/Platform/Windows/Exception.h"
#endif
#include "../../IO/FileAccessException.h"
#include "../../Streams/BufferedInputStream.h"
#include "FileInputStream.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::IO;
using namespace Stroika::Foundation::IO::FileSystem;
using Execution::make_unique_lock;
using Streams::InputStream;
using Streams::SeekOffsetType;
#if qPlatform_Windows
using Execution::Platform::Windows::ThrowIfFalseGetLastError;
#endif
// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
/*
********************************************************************************
**************************** FileSystem::FileInputStream ***********************
********************************************************************************
*/
class FileInputStream::Rep_ : public InputStream<Byte>::_IRep, private Debug::AssertExternallySynchronizedLock {
public:
Rep_ () = delete;
Rep_ (const Rep_&) = delete;
Rep_ (const String& fileName, SeekableFlag seekable)
: fFD_ (-1)
, fSeekable_ (seekable)
{
try {
#if qPlatform_Windows
errno_t e = ::_wsopen_s (&fFD_, fileName.c_str (), (O_RDONLY | O_BINARY), _SH_DENYNO, 0);
if (e != 0) {
Execution::errno_ErrorException::Throw (e);
}
ThrowIfFalseGetLastError (fFD_ != -1);
#else
Execution::ThrowErrNoIfNegative (fFD_ = ::open (fileName.AsNarrowSDKString ().c_str (), O_RDONLY));
#endif
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace (L"opened fd: %d", fFD_);
#endif
}
Stroika_Foundation_IO_FileAccessException_CATCH_REBIND_FILENAME_ACCCESS_HELPER(fileName, FileAccessMode::eRead);
}
~Rep_ ()
{
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper ctx (L"FileInputStream::Rep_::~Rep_");
DbgTrace (L"closing %d", fFD_);
#endif
#if qPlatform_Windows
::_close (fFD_);
#else
::close (fFD_);
#endif
}
nonvirtual Rep_& operator= (const Rep_&) = delete;
virtual bool IsSeekable () const override
{
return fSeekable_ == eSeekable;
}
virtual size_t Read (Byte* intoStart, Byte* intoEnd) override
{
RequireNotNull (intoStart);
RequireNotNull (intoEnd);
Require (intoStart < intoEnd);
size_t nRequested = intoEnd - intoStart;
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper ctx (L"FileInputStream::Rep_::Read");
DbgTrace (L"(nRequested: %llu)", static_cast<unsigned long long> (nRequested));
#endif
lock_guard<const AssertExternallySynchronizedLock> critSec { *this };
#if qPlatform_Windows
return static_cast<size_t> (Execution::ThrowErrNoIfNegative (::_read (fFD_, intoStart, Math::PinToMaxForType<unsigned int> (nRequested))));
#else
return static_cast<size_t> (Execution::ThrowErrNoIfNegative (::read (fFD_, intoStart, nRequested)));
#endif
}
virtual Streams::SeekOffsetType GetReadOffset () const override
{
lock_guard<const AssertExternallySynchronizedLock> critSec { *this };
#if qPlatform_Windows
return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::_lseeki64 (fFD_, 0, SEEK_CUR)));
#elif qPlatform_Linux
return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::lseek64 (fFD_, 0, SEEK_CUR)));
#else
return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::lseek (fFD_, 0, SEEK_CUR)));
#endif
}
virtual Streams::SeekOffsetType SeekRead (Streams::Whence whence, Streams::SignedSeekOffsetType offset) override
{
using namespace Streams;
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper ctx (L"FileInputStream::Rep_::SeekRead");
DbgTrace (L"(whence: %d, offset: %lld)", whence, static_cast<long long> (offset));
#endif
lock_guard<const AssertExternallySynchronizedLock> critSec { *this };
switch (whence) {
case Whence::eFromStart: {
if (offset < 0) {
Execution::Throw (std::range_error ("seek"));
}
#if qPlatform_Windows
return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::_lseeki64 (fFD_, offset, SEEK_SET)));
#elif qPlatform_Linux
return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::lseek64 (fFD_, offset, SEEK_SET)));
#else
return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::lseek (fFD_, offset, SEEK_SET)));
#endif
}
break;
case Whence::eFromCurrent: {
#if qPlatform_Windows
return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::_lseeki64 (fFD_, offset, SEEK_CUR)));
#else
return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::lseek64 (fFD_, offset, SEEK_CUR)));
#endif
}
break;
case Whence::eFromEnd: {
#if qPlatform_Windows
return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::_lseeki64 (fFD_, offset, SEEK_END)));
#elif qPlatform_Linux
return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::lseek64 (fFD_, offset, SEEK_END)));
#else
return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::lseek (fFD_, offset, SEEK_END)));
#endif
}
break;
}
RequireNotReached ();
return 0;
}
private:
int fFD_;
SeekableFlag fSeekable_;
};
FileInputStream::FileInputStream (const String& fileName, SeekableFlag seekable)
: FileInputStream (make_shared<Rep_> (fileName, seekable))
{
}
FileInputStream::FileInputStream (const shared_ptr<Rep_>& rep)
: inherited (rep)
{
}
InputStream<Byte> FileInputStream::mk (const String& fileName, SeekableFlag seekable, BufferFlag bufferFlag)
{
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper ctx (L"FileInputStream::mk");
DbgTrace (L"(fileName: %s, seekable: %d, bufferFlag: %d)", fileName.c_str (), seekable, bufferFlag);
#endif
InputStream<Byte> in = FileInputStream (fileName, seekable);
switch (bufferFlag) {
case eBuffered:
return Streams::BufferedInputStream<Byte> (in);
case eUnbuffered:
return in;
default:
AssertNotReached ();
return in;
}
}
<|endoftext|>
|
<commit_before>/*=========================================================================
*
* 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 "itkJoinSeriesImageFilter.h"
#include "itkStreamingImageFilter.h"
#include <iostream>
class ShowProgressObject
{
public:
ShowProgressObject(itk::ProcessObject* o)
{m_Process = o;}
void ShowProgress()
{std::cout << "Progress " << m_Process->GetProgress() << std::endl;}
itk::ProcessObject::Pointer m_Process;
};
int itkJoinSeriesImageFilterTest(int, char* [] )
{
// to write informations to "itkMessageLog.txt" when DebugOn()
// itk::OutputWindow::SetInstance( itk::FileOutputWindow::New() );
const unsigned int streamDivisions = 2;
typedef unsigned char PixelType;
typedef itk::Image< PixelType, 2 > InputImageType;
// typedef itk::Image< PixelType, 3 > OutputImageType;
typedef itk::Image< PixelType, 4 > OutputImageType;
// the expected result
OutputImageType::IndexType expectedIndex = {{1, 2, 0, 0}};
OutputImageType::SizeType expectedSize = {{8, 5, 4, 1}};
OutputImageType::RegionType expectedRegion;
expectedRegion.SetIndex( expectedIndex );
expectedRegion.SetSize( expectedSize );
OutputImageType::SpacingType expectedSpacing;
expectedSpacing[0] = 1.1;
expectedSpacing[1] = 1.2;
expectedSpacing[2] = 1.3;
expectedSpacing[3] = 1.0;
OutputImageType::PointType expectedOrigin;
expectedOrigin[0] = 0.1;
expectedOrigin[1] = 0.2;
expectedOrigin[2] = 0.3;
expectedOrigin[3] = 0.0;
// make the input images
int numInputs = 4;
InputImageType::IndexType index = {{1, 2}};
InputImageType::SizeType size = {{8, 5}};
InputImageType::RegionType region;
region.SetIndex( index );
region.SetSize( size );
const double spacingValue = 1.3;
InputImageType::SpacingType spacing;
spacing[0] = 1.1;
spacing[1] = 1.2;
const double originValue = 0.3;
InputImageType::PointType origin;
origin[0] = 0.1;
origin[1] = 0.2;
std::vector<InputImageType::Pointer> inputs;
PixelType counter1 = 0;
for ( int i = 0; i < numInputs; i++ )
{
inputs.push_back( InputImageType::New() );
inputs[i]->SetLargestPossibleRegion( region );
inputs[i]->SetBufferedRegion( region );
inputs[i]->Allocate();
itk::ImageRegionIterator<InputImageType>
inputIter( inputs[i], inputs[i]->GetBufferedRegion() );
while ( !inputIter.IsAtEnd() )
{
inputIter.Set( counter1 );
++counter1;
++inputIter;
}
inputs[i]->SetSpacing( spacing );
inputs[i]->SetOrigin( origin );
// inputs[i]->DebugOn();
}
// create the filter
typedef itk::JoinSeriesImageFilter< InputImageType, OutputImageType >
JoinSeriesImageType;
JoinSeriesImageType::Pointer joinSeriesImage = JoinSeriesImageType::New();
// check the default values
if ( joinSeriesImage->GetSpacing() != 1.0 )
{
std::cout << "Default spacing is not 1.0" << std::endl;
return EXIT_FAILURE;
}
if ( joinSeriesImage->GetOrigin() != 0.0 )
{
std::cout << "Default origin is not 0.0" << std::endl;
return EXIT_FAILURE;
}
// setup the filter
joinSeriesImage->SetSpacing( spacingValue );
joinSeriesImage->SetOrigin( originValue );
for ( int i = 0; i < numInputs; i++ )
{
joinSeriesImage->SetInput( i, inputs[i] );
}
// to test ProgressReporter
ShowProgressObject progressWatch( joinSeriesImage );
typedef itk::SimpleMemberCommand< ShowProgressObject > CommandType;
CommandType::Pointer command = CommandType::New();
command->SetCallbackFunction( &progressWatch,
&ShowProgressObject::ShowProgress );
joinSeriesImage->AddObserver( itk::ProgressEvent(), command );
// to test streaming
typedef itk::StreamingImageFilter< OutputImageType, OutputImageType >
StreamingImageType;
StreamingImageType::Pointer streamingImage = StreamingImageType::New();
streamingImage->SetInput( joinSeriesImage->GetOutput() );
streamingImage->SetNumberOfStreamDivisions( streamDivisions );
// run
try
{
streamingImage->Update();
}
catch( itk::ExceptionObject & err )
{
std::cout << err << std::endl;
//for InvalidRequestedRegionError
itk::DataObjectError * errp = dynamic_cast<itk::DataObjectError *>( &err );
if ( errp )
{
errp->GetDataObject()->Print( std::cout );
}
return EXIT_FAILURE;
}
OutputImageType::Pointer output = streamingImage->GetOutput();
// check the informations
if ( output->GetLargestPossibleRegion() != expectedRegion )
{
std::cout << "LargestPossibleRegion mismatch" << std::endl;
return EXIT_FAILURE;
}
if ( output->GetSpacing() != expectedSpacing )
{
std::cout << "Spacing mismatch" << std::endl;
return EXIT_FAILURE;
}
if ( output->GetOrigin() != expectedOrigin )
{
std::cout << "Origin mismatch" << std::endl;
return EXIT_FAILURE;
}
// check the contents
bool passed = true;
PixelType counter2 = 0;
itk::ImageRegionIterator<OutputImageType>
outputIter( output, output->GetBufferedRegion() );
while ( !outputIter.IsAtEnd() )
{
if ( outputIter.Get() != counter2 )
{
passed = false;
std::cout << "Mismatch at index: " << outputIter.GetIndex() << std::endl;
}
++counter2;
++outputIter;
}
if ( !passed || counter1 != counter2 )
{
std::cout << "Test failed." << std::endl;
return EXIT_FAILURE;
}
// An exception is raised when an input is missing.
passed = false;
// set the 2nd input null
joinSeriesImage->SetInput( 1, ITK_NULLPTR );
try
{
joinSeriesImage->Update();
}
catch( itk::InvalidRequestedRegionError & err )
{
std::cout << err << std::endl;
passed = true;
}
catch( itk::ExceptionObject & err )
{
std::cout << err << std::endl;
return EXIT_FAILURE;
}
if ( !passed )
{
std::cout << "Expected exception is missing" << std::endl;
return EXIT_FAILURE;
}
std::cout << "Test passed." << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>ENH: Improve itkJoinSeriesImageFilter coverage.<commit_after>/*=========================================================================
*
* 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 "itkJoinSeriesImageFilter.h"
#include "itkStreamingImageFilter.h"
#include "itkTestingMacros.h"
#include <iostream>
class ShowProgressObject
{
public:
ShowProgressObject(itk::ProcessObject* o)
{m_Process = o;}
void ShowProgress()
{std::cout << "Progress " << m_Process->GetProgress() << std::endl;}
itk::ProcessObject::Pointer m_Process;
};
int itkJoinSeriesImageFilterTest( int, char* [] )
{
const unsigned int streamDivisions = 2;
typedef unsigned char PixelType;
typedef itk::Image< PixelType, 2 > InputImageType;
typedef itk::Image< PixelType, 4 > OutputImageType;
// Expected result
OutputImageType::IndexType expectedIndex = {{1, 2, 0, 0}};
OutputImageType::SizeType expectedSize = {{8, 5, 4, 1}};
OutputImageType::RegionType expectedRegion;
expectedRegion.SetIndex( expectedIndex );
expectedRegion.SetSize( expectedSize );
OutputImageType::SpacingType expectedSpacing;
expectedSpacing[0] = 1.1;
expectedSpacing[1] = 1.2;
expectedSpacing[2] = 1.3;
expectedSpacing[3] = 1.0;
OutputImageType::PointType expectedOrigin;
expectedOrigin[0] = 0.1;
expectedOrigin[1] = 0.2;
expectedOrigin[2] = 0.3;
expectedOrigin[3] = 0.0;
// Create the input images
int numInputs = 4;
InputImageType::IndexType index = {{1, 2}};
InputImageType::SizeType size = {{8, 5}};
InputImageType::RegionType region;
region.SetIndex( index );
region.SetSize( size );
const double spacingValue = 1.3;
InputImageType::SpacingType spacing;
spacing[0] = 1.1;
spacing[1] = 1.2;
const double originValue = 0.3;
InputImageType::PointType origin;
origin[0] = 0.1;
origin[1] = 0.2;
std::vector<InputImageType::Pointer> inputs;
PixelType counter1 = 0;
for ( int i = 0; i < numInputs; i++ )
{
inputs.push_back( InputImageType::New() );
inputs[i]->SetLargestPossibleRegion( region );
inputs[i]->SetBufferedRegion( region );
inputs[i]->Allocate();
itk::ImageRegionIterator<InputImageType>
inputIter( inputs[i], inputs[i]->GetBufferedRegion() );
while ( !inputIter.IsAtEnd() )
{
inputIter.Set( counter1 );
++counter1;
++inputIter;
}
inputs[i]->SetSpacing( spacing );
inputs[i]->SetOrigin( origin );
}
// Create the filter
typedef itk::JoinSeriesImageFilter< InputImageType, OutputImageType >
JoinSeriesImageType;
JoinSeriesImageType::Pointer joinSeriesImage = JoinSeriesImageType::New();
EXERCISE_BASIC_OBJECT_METHODS( joinSeriesImage, JoinSeriesImageFilter,
ImageToImageFilter );
// Check the default values
if ( joinSeriesImage->GetSpacing() != 1.0 )
{
std::cout << "Default spacing is not 1.0" << std::endl;
return EXIT_FAILURE;
}
if ( joinSeriesImage->GetOrigin() != 0.0 )
{
std::cout << "Default origin is not 0.0" << std::endl;
return EXIT_FAILURE;
}
// Setup the filter
joinSeriesImage->SetSpacing( spacingValue );
TEST_SET_GET_VALUE( spacingValue, joinSeriesImage->GetSpacing() );
joinSeriesImage->SetOrigin( originValue );
TEST_SET_GET_VALUE( originValue, joinSeriesImage->GetOrigin() );
for ( int i = 0; i < numInputs; i++ )
{
joinSeriesImage->SetInput( i, inputs[i] );
}
// Test the ProgressReporter
ShowProgressObject progressWatch( joinSeriesImage );
typedef itk::SimpleMemberCommand< ShowProgressObject > CommandType;
CommandType::Pointer command = CommandType::New();
command->SetCallbackFunction( &progressWatch,
&ShowProgressObject::ShowProgress );
joinSeriesImage->AddObserver( itk::ProgressEvent(), command );
// Test streaming
typedef itk::StreamingImageFilter< OutputImageType, OutputImageType >
StreamingImageType;
StreamingImageType::Pointer streamingImage = StreamingImageType::New();
streamingImage->SetInput( joinSeriesImage->GetOutput() );
streamingImage->SetNumberOfStreamDivisions( streamDivisions );
try
{
streamingImage->Update();
}
catch( itk::ExceptionObject & err )
{
std::cout << err << std::endl;
itk::DataObjectError * errp = dynamic_cast<itk::DataObjectError *>( &err );
if ( errp )
{
errp->GetDataObject()->Print( std::cout );
}
return EXIT_FAILURE;
}
OutputImageType::Pointer output = streamingImage->GetOutput();
// Check the informations
if ( output->GetLargestPossibleRegion() != expectedRegion )
{
std::cout << "LargestPossibleRegion mismatch" << std::endl;
return EXIT_FAILURE;
}
if ( output->GetSpacing() != expectedSpacing )
{
std::cout << "Spacing mismatch" << std::endl;
return EXIT_FAILURE;
}
if ( output->GetOrigin() != expectedOrigin )
{
std::cout << "Origin mismatch" << std::endl;
return EXIT_FAILURE;
}
// Check the contents
bool passed = true;
PixelType counter2 = 0;
itk::ImageRegionIterator<OutputImageType>
outputIter( output, output->GetBufferedRegion() );
while ( !outputIter.IsAtEnd() )
{
if ( outputIter.Get() != counter2 )
{
passed = false;
std::cout << "Mismatch at index: " << outputIter.GetIndex() << std::endl;
}
++counter2;
++outputIter;
}
if ( !passed || counter1 != counter2 )
{
std::cout << "Test failed." << std::endl;
return EXIT_FAILURE;
}
// An exception is raised when an input is missing.
passed = false;
// Set the 2nd input null
joinSeriesImage->SetInput( 1, ITK_NULLPTR );
try
{
joinSeriesImage->Update();
}
catch( itk::InvalidRequestedRegionError & err )
{
std::cout << err << std::endl;
passed = true;
}
catch( itk::ExceptionObject & err )
{
std::cout << err << std::endl;
return EXIT_FAILURE;
}
if ( !passed )
{
std::cout << "Expected exception is missing" << std::endl;
return EXIT_FAILURE;
}
std::cout << "Test passed." << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "mcommonpixmaps.h"
#include "mthemedaemon.h"
#include "mdebug.h"
#include <QFile>
#include <QDir>
using namespace M::MThemeDaemonProtocol;
#define VERSION(major, minor) ((major << 16) | minor)
const unsigned int PRELOAD_FILE_VERSION = VERSION(0, 1);
MCommonPixmaps::MCommonPixmaps(MThemeDaemon *daemon) :
minRequestsForCache(0),
daemon(daemon)
{
connect(&cpuMonitor, SIGNAL(newCpuFrameAvailable()), SLOT(loadOne()));
connect(this, SIGNAL(mostUsedPixmapsChanged(M::MThemeDaemonProtocol::MostUsedPixmaps)), SLOT(considerSaving()));
}
MCommonPixmaps::~MCommonPixmaps()
{
// please call clear before destroying this object
Q_ASSERT(mostUsedPixmaps.count() == 0);
}
void MCommonPixmaps::clear()
{
// release all most used pixmaps
foreach(const PixmapIdentifier & id, mostUsedPixmaps) {
if (toLoadList.contains(id))
continue;
ImageResource *resource = daemon->findImageResource(id.imageId);
resource->releasePixmap(id.size);
}
cpuMonitor.stop();
mostUsedPixmaps.clear();
toLoadList.clear();
requestCounts.clear();
minRequestsForCache = 0;
}
void MCommonPixmaps::load()
{
// clear the old ones.
clear();
if (!QFile::exists(cacheFilename())) {
return;
}
QFile file(cacheFilename());
if (!file.open(QIODevice::ReadOnly)) {
mWarning("MCommonPixmaps") << "Could not load most used pixmaps from" << cacheFilename();
return;
}
QDataStream stream(&file);
unsigned int version;
stream >> version;
if (version != PRELOAD_FILE_VERSION)
return;
while (file.bytesAvailable()) {
QString imageId;
QSize size;
quint32 requestCount;
bool isMostUsed;
stream >> imageId >> size >> requestCount >> isMostUsed;
PixmapIdentifier id(imageId, size);
requestCounts.insert(id, requestCount);
if (isMostUsed) {
toLoadList.insert(PixmapIdentifier(imageId, size));
mostUsedPixmaps.insert(PixmapIdentifier(imageId, size));
}
}
if (!toLoadList.isEmpty()) {
cpuMonitor.start(2000);
}
file.close();
}
void MCommonPixmaps::save() const
{
QFile file(cacheFilename());
if (!file.open(QIODevice::WriteOnly)) {
mWarning("MCommonPixmaps") << "Could not save most used pixmaps to" << cacheFilename();
return;
}
QDataStream stream(&file);
stream << PRELOAD_FILE_VERSION;
QHash<PixmapIdentifier, quint32>::const_iterator i = requestCounts.begin();
for (; i != requestCounts.end(); ++i) {
const PixmapIdentifier& id = i.key();
bool isMostUsed = mostUsedPixmaps.contains(id);
stream << id.imageId << id.size << i.value() << isMostUsed;
}
file.close();
}
void MCommonPixmaps::loadOne()
{
// stop the timer, so we can adjust the frequency depending on the usage
cpuMonitor.stop();
if (0 <= cpuMonitor.usage() || cpuMonitor.usage() < 10) {
//check if there really is something to load
if (!toLoadList.isEmpty()) {
PixmapIdentifier id = *toLoadList.begin();
toLoadList.erase(toLoadList.begin());
ImageResource *resource = daemon->findImageResource(id.imageId);
if (resource) {
resource->fetchPixmap(id.size);
} else {
mWarning("MCommonPixmaps") << QString("Themedaemon could not find resource %1 while loading most used pixmaps. Removing from list.").arg(id.imageId);
requestCounts.remove(id);
mostUsedPixmaps.remove(id);
}
if (!toLoadList.isEmpty()) {
// there's still items in the list, so start the timer with small delay
cpuMonitor.start(250);
} else {
// all common pixmaps loaded - notify clients
MostUsedPixmaps mostUsed;
mostUsed.addedHandles = mostUsedPixmapHandles();
emit mostUsedPixmapsChanged(mostUsed);
}
}
} else {
// the cpu usage was too high, so start start the timer with longer delay
cpuMonitor.start(2000);
}
}
void MCommonPixmaps::increaseRequestCount(const M::MThemeDaemonProtocol::PixmapIdentifier &id, ImageResource *resource)
{
QHash<PixmapIdentifier, quint32>::iterator requestCount = requestCounts.find(id);
if (requestCount == requestCounts.end()) {
requestCount = requestCounts.insert(id, 0);
}
++requestCount.value();
// does this pixmap has higher request count value than the current minimum for cache?
if (requestCount.value() > minRequestsForCache && !mostUsedPixmaps.contains(id)) {
// this pixmap might end up to mostUsedPixmaps list
// check if there's still room for this pixmap
if (mostUsedPixmaps.count() < MCommonPixmaps::CacheSize) {
// yep, just add this pixmap and return
Qt::HANDLE handle = resource->fetchPixmap(id.size);
mostUsedPixmaps.insert(id);
MostUsedPixmaps packet;
packet.addedHandles.append(PixmapHandle(id, handle));
if (toLoadList.isEmpty()) {
emit mostUsedPixmapsChanged(packet);
}
return;
}
// there was no room, so we'll check if we can make it
QSet<PixmapIdentifier>::iterator i = mostUsedPixmaps.begin();
QSet<PixmapIdentifier>::iterator leastUsed = i;
quint32 leastUsedRequests = requestCounts[*leastUsed];
quint32 secondlyLeastUsedRequests = leastUsedRequests;
++i;
// find the least used pixmap from most used list
for (; i != mostUsedPixmaps.end(); ++i) {
const PixmapIdentifier &curId = *i;
quint32 count = requestCounts[curId];
if (count < leastUsedRequests) {
secondlyLeastUsedRequests = leastUsedRequests;
leastUsedRequests = count;
leastUsed = i;
}
}
// if the least used is still above the current, we'll just update the limit
if (leastUsedRequests >= requestCount.value()) {
minRequestsForCache = leastUsedRequests;
return;
}
// otherwise we have a new pixmap for the list
// update the limit, there may be duplicate request counts in the most used list
minRequestsForCache = (secondlyLeastUsedRequests > requestCount.value()) ? requestCount.value() : secondlyLeastUsedRequests;
// allocate one pixmap for the list
Qt::HANDLE handle = resource->fetchPixmap(id.size);
MostUsedPixmaps packet;
packet.addedHandles.append(PixmapHandle(id, handle));
// release the old one from the list
if (!toLoadList.remove(*leastUsed)) {
packet.removedIdentifiers.append(id);
}
if (toLoadList.isEmpty()) {
emit mostUsedPixmapsChanged(packet);
}
mostUsedPixmaps.remove(*leastUsed);
mostUsedPixmaps.insert(id);
}
}
void MCommonPixmaps::reload(const PixmapIdentifier &id, ImageResource *oldResource)
{
if (toLoadList.contains(id) || !mostUsedPixmaps.contains(id)) {
// no need to do anything
return;
}
oldResource->releasePixmap(id.size);
toLoadList.insert(id);
}
QList<M::MThemeDaemonProtocol::PixmapHandle> MCommonPixmaps::mostUsedPixmapHandles()
{
if (!toLoadList.isEmpty()) {
// not all pixmaps loaded/valid - return empty list
return QList<M::MThemeDaemonProtocol::PixmapHandle>();
}
// we could also save the handles earlier but it is cheap to do the query
QList<PixmapHandle> pixmapHandles;
foreach(const M::MThemeDaemonProtocol::PixmapIdentifier& id, mostUsedPixmaps) {
Qt::HANDLE handle = daemon->findImageResource(id.imageId)->pixmapHandle(id.size);
pixmapHandles.append(M::MThemeDaemonProtocol::PixmapHandle(id, handle));
}
return pixmapHandles;
}
QString MCommonPixmaps::cacheFilename() const
{
return daemon->systemThemeCacheDirectory() + QDir::separator() + daemon->currentTheme() + QDir::separator() + QLatin1String("preload.list");
}
void MCommonPixmaps::considerSaving()
{
// we do not allow more than one update in 10 seconds
const int delay = 10000;
if (!timerSinceLastSave.isValid() || timerSinceLastSave.hasExpired(delay)) {
save();
timerSinceLastSave.start();
}
}
<commit_msg>Changes: make valgrind happy<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "mcommonpixmaps.h"
#include "mthemedaemon.h"
#include "mdebug.h"
#include <QFile>
#include <QDir>
using namespace M::MThemeDaemonProtocol;
#define VERSION(major, minor) ((major << 16) | minor)
const unsigned int PRELOAD_FILE_VERSION = VERSION(0, 1);
MCommonPixmaps::MCommonPixmaps(MThemeDaemon *daemon) :
minRequestsForCache(0),
daemon(daemon)
{
connect(&cpuMonitor, SIGNAL(newCpuFrameAvailable()), SLOT(loadOne()));
connect(this, SIGNAL(mostUsedPixmapsChanged(M::MThemeDaemonProtocol::MostUsedPixmaps)), SLOT(considerSaving()));
timerSinceLastSave.invalidate();
}
MCommonPixmaps::~MCommonPixmaps()
{
// please call clear before destroying this object
Q_ASSERT(mostUsedPixmaps.count() == 0);
}
void MCommonPixmaps::clear()
{
// release all most used pixmaps
foreach(const PixmapIdentifier & id, mostUsedPixmaps) {
if (toLoadList.contains(id))
continue;
ImageResource *resource = daemon->findImageResource(id.imageId);
resource->releasePixmap(id.size);
}
cpuMonitor.stop();
mostUsedPixmaps.clear();
toLoadList.clear();
requestCounts.clear();
minRequestsForCache = 0;
}
void MCommonPixmaps::load()
{
// clear the old ones.
clear();
if (!QFile::exists(cacheFilename())) {
return;
}
QFile file(cacheFilename());
if (!file.open(QIODevice::ReadOnly)) {
mWarning("MCommonPixmaps") << "Could not load most used pixmaps from" << cacheFilename();
return;
}
QDataStream stream(&file);
unsigned int version;
stream >> version;
if (version != PRELOAD_FILE_VERSION)
return;
while (file.bytesAvailable()) {
QString imageId;
QSize size;
quint32 requestCount;
bool isMostUsed;
stream >> imageId >> size >> requestCount >> isMostUsed;
PixmapIdentifier id(imageId, size);
requestCounts.insert(id, requestCount);
if (isMostUsed) {
toLoadList.insert(PixmapIdentifier(imageId, size));
mostUsedPixmaps.insert(PixmapIdentifier(imageId, size));
}
}
if (!toLoadList.isEmpty()) {
cpuMonitor.start(2000);
}
file.close();
}
void MCommonPixmaps::save() const
{
QFile file(cacheFilename());
if (!file.open(QIODevice::WriteOnly)) {
mWarning("MCommonPixmaps") << "Could not save most used pixmaps to" << cacheFilename();
return;
}
QDataStream stream(&file);
stream << PRELOAD_FILE_VERSION;
QHash<PixmapIdentifier, quint32>::const_iterator i = requestCounts.begin();
for (; i != requestCounts.end(); ++i) {
const PixmapIdentifier& id = i.key();
bool isMostUsed = mostUsedPixmaps.contains(id);
stream << id.imageId << id.size << i.value() << isMostUsed;
}
file.close();
}
void MCommonPixmaps::loadOne()
{
// stop the timer, so we can adjust the frequency depending on the usage
cpuMonitor.stop();
if (0 <= cpuMonitor.usage() || cpuMonitor.usage() < 10) {
//check if there really is something to load
if (!toLoadList.isEmpty()) {
PixmapIdentifier id = *toLoadList.begin();
toLoadList.erase(toLoadList.begin());
ImageResource *resource = daemon->findImageResource(id.imageId);
if (resource) {
resource->fetchPixmap(id.size);
} else {
mWarning("MCommonPixmaps") << QString("Themedaemon could not find resource %1 while loading most used pixmaps. Removing from list.").arg(id.imageId);
requestCounts.remove(id);
mostUsedPixmaps.remove(id);
}
if (!toLoadList.isEmpty()) {
// there's still items in the list, so start the timer with small delay
cpuMonitor.start(250);
} else {
// all common pixmaps loaded - notify clients
MostUsedPixmaps mostUsed;
mostUsed.addedHandles = mostUsedPixmapHandles();
emit mostUsedPixmapsChanged(mostUsed);
}
}
} else {
// the cpu usage was too high, so start start the timer with longer delay
cpuMonitor.start(2000);
}
}
void MCommonPixmaps::increaseRequestCount(const M::MThemeDaemonProtocol::PixmapIdentifier &id, ImageResource *resource)
{
QHash<PixmapIdentifier, quint32>::iterator requestCount = requestCounts.find(id);
if (requestCount == requestCounts.end()) {
requestCount = requestCounts.insert(id, 0);
}
++requestCount.value();
// does this pixmap has higher request count value than the current minimum for cache?
if (requestCount.value() > minRequestsForCache && !mostUsedPixmaps.contains(id)) {
// this pixmap might end up to mostUsedPixmaps list
// check if there's still room for this pixmap
if (mostUsedPixmaps.count() < MCommonPixmaps::CacheSize) {
// yep, just add this pixmap and return
Qt::HANDLE handle = resource->fetchPixmap(id.size);
mostUsedPixmaps.insert(id);
MostUsedPixmaps packet;
packet.addedHandles.append(PixmapHandle(id, handle));
if (toLoadList.isEmpty()) {
emit mostUsedPixmapsChanged(packet);
}
return;
}
// there was no room, so we'll check if we can make it
QSet<PixmapIdentifier>::iterator i = mostUsedPixmaps.begin();
QSet<PixmapIdentifier>::iterator leastUsed = i;
quint32 leastUsedRequests = requestCounts[*leastUsed];
quint32 secondlyLeastUsedRequests = leastUsedRequests;
++i;
// find the least used pixmap from most used list
for (; i != mostUsedPixmaps.end(); ++i) {
const PixmapIdentifier &curId = *i;
quint32 count = requestCounts[curId];
if (count < leastUsedRequests) {
secondlyLeastUsedRequests = leastUsedRequests;
leastUsedRequests = count;
leastUsed = i;
}
}
// if the least used is still above the current, we'll just update the limit
if (leastUsedRequests >= requestCount.value()) {
minRequestsForCache = leastUsedRequests;
return;
}
// otherwise we have a new pixmap for the list
// update the limit, there may be duplicate request counts in the most used list
minRequestsForCache = (secondlyLeastUsedRequests > requestCount.value()) ? requestCount.value() : secondlyLeastUsedRequests;
// allocate one pixmap for the list
Qt::HANDLE handle = resource->fetchPixmap(id.size);
MostUsedPixmaps packet;
packet.addedHandles.append(PixmapHandle(id, handle));
// release the old one from the list
if (!toLoadList.remove(*leastUsed)) {
packet.removedIdentifiers.append(id);
}
if (toLoadList.isEmpty()) {
emit mostUsedPixmapsChanged(packet);
}
mostUsedPixmaps.remove(*leastUsed);
mostUsedPixmaps.insert(id);
}
}
void MCommonPixmaps::reload(const PixmapIdentifier &id, ImageResource *oldResource)
{
if (toLoadList.contains(id) || !mostUsedPixmaps.contains(id)) {
// no need to do anything
return;
}
oldResource->releasePixmap(id.size);
toLoadList.insert(id);
}
QList<M::MThemeDaemonProtocol::PixmapHandle> MCommonPixmaps::mostUsedPixmapHandles()
{
if (!toLoadList.isEmpty()) {
// not all pixmaps loaded/valid - return empty list
return QList<M::MThemeDaemonProtocol::PixmapHandle>();
}
// we could also save the handles earlier but it is cheap to do the query
QList<PixmapHandle> pixmapHandles;
foreach(const M::MThemeDaemonProtocol::PixmapIdentifier& id, mostUsedPixmaps) {
Qt::HANDLE handle = daemon->findImageResource(id.imageId)->pixmapHandle(id.size);
pixmapHandles.append(M::MThemeDaemonProtocol::PixmapHandle(id, handle));
}
return pixmapHandles;
}
QString MCommonPixmaps::cacheFilename() const
{
return daemon->systemThemeCacheDirectory() + QDir::separator() + daemon->currentTheme() + QDir::separator() + QLatin1String("preload.list");
}
void MCommonPixmaps::considerSaving()
{
// we do not allow more than one update in 10 seconds
const int delay = 10000;
if (!timerSinceLastSave.isValid() || timerSinceLastSave.hasExpired(delay)) {
save();
timerSinceLastSave.start();
}
}
<|endoftext|>
|
<commit_before>/*
* Thread.hpp
*
* Copyright (C) 2020 by RStudio, PBC
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* 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.
*
*/
#ifndef CORE_THREAD_HPP
#define CORE_THREAD_HPP
#include <queue>
#include <boost/utility.hpp>
#include <boost/function.hpp>
#include <core/BoostErrors.hpp>
#include <core/BoostThread.hpp>
#include <shared_core/Error.hpp>
#include <core/Log.hpp>
#define LOCK_MUTEX(m) \
try \
{ \
boost::lock_guard<boost::mutex> lock(m);
#define RECURSIVE_LOCK_MUTEX(m) \
try \
{ \
boost::lock_guard<boost::recursive_mutex> lock(m);
#define UNIQUE_LOCK_MUTEX(m, lockvar) \
try \
{ \
boost::unique_lock<boost::mutex> lockvar(m); \
#define END_LOCK_MUTEX \
} \
catch (const boost::thread_resource_error& e) \
{ \
core::Error threadError(boost::thread_error::ec_from_exception(e), \
ERROR_LOCATION); \
LOG_ERROR(threadError); \
} \
CATCH_UNEXPECTED_EXCEPTION
namespace rstudio {
namespace core {
namespace thread {
template <typename T>
class ThreadsafeValue : boost::noncopyable
{
public:
explicit ThreadsafeValue(const T& value = T()) : value_(value) {}
virtual ~ThreadsafeValue() {}
T get()
{
LOCK_MUTEX(mutex_)
{
return value_;
}
END_LOCK_MUTEX
// keep compiler happy
return T();
}
void set(const T& value)
{
LOCK_MUTEX(mutex_)
{
value_ = value;
}
END_LOCK_MUTEX
}
private:
boost::mutex mutex_;
T value_;
};
template <typename K, typename V>
class ThreadsafeMap : boost::noncopyable
{
public:
ThreadsafeMap() {}
virtual ~ThreadsafeMap() {}
bool contains(const K& key)
{
LOCK_MUTEX(mutex_)
{
return map_.find(key) != map_.end();
}
END_LOCK_MUTEX
// keep compiler happy
return false;
}
V get(const K& key, const V& defaultValue = V())
{
LOCK_MUTEX(mutex_)
{
typename std::map<K,V>::const_iterator it = map_.find(key);
if (it != map_.end())
return it->second;
else
return defaultValue;
}
END_LOCK_MUTEX
// keep compiler happy
return defaultValue;
}
V collect(const K& key)
{
LOCK_MUTEX(mutex_)
{
typename std::map<K,V>::const_iterator it = map_.find(key);
if (it != map_.end())
{
V val = it->second;
map_.erase(key);
return val;
}
}
END_LOCK_MUTEX
return V();
}
void set(const K& key, const V& val)
{
LOCK_MUTEX(mutex_)
{
map_[key] = val;
}
END_LOCK_MUTEX
}
void remove(const K& key)
{
LOCK_MUTEX(mutex_)
{
map_.erase(key);
}
END_LOCK_MUTEX
}
void clear()
{
LOCK_MUTEX(mutex_)
{
map_.clear();
}
END_LOCK_MUTEX
}
private:
boost::mutex mutex_;
std::map<K,V> map_;
};
template <typename T>
class ThreadsafeQueue : boost::noncopyable
{
public:
explicit ThreadsafeQueue(bool freeSyncObjects = false)
: pMutex_(new boost::mutex()),
pWaitCondition_(new boost::condition()),
freeSyncObjects_(freeSyncObjects)
{
}
virtual ~ThreadsafeQueue()
{
try
{
if (freeSyncObjects_)
{
delete pMutex_;
delete pWaitCondition_;
}
}
catch(...)
{
}
}
// COPYING: boost::noncopyable
public:
void enque(const T& val)
{
LOCK_MUTEX(*pMutex_)
{
// enque
queue_.push(val);
}
END_LOCK_MUTEX
pWaitCondition_->notify_all();
}
bool deque(T* pVal)
{
LOCK_MUTEX(*pMutex_)
{
if (!queue_.empty())
{
// remove it
*pVal = queue_.front();
queue_.pop();
// return true
return true;
}
else
{
return false;
}
}
END_LOCK_MUTEX
// keep compiler happy
return false;
}
bool isEmpty()
{
LOCK_MUTEX(*pMutex_)
{
return queue_.empty();
}
END_LOCK_MUTEX
// keep compiler happy
return true;
}
bool deque(T* pVal, const boost::posix_time::time_duration& waitDuration)
{
// first see if we already have one
if (deque(pVal))
return true;
// now wait the specified interval for one to materialize
if (wait(waitDuration))
return deque(pVal);
else
return false;
}
bool wait(const boost::posix_time::time_duration& waitDuration =
boost::posix_time::time_duration(boost::posix_time::not_a_date_time))
{
using namespace boost;
try
{
unique_lock<mutex> lock(*pMutex_);
if (waitDuration.is_not_a_date_time())
{
pWaitCondition_->wait(lock);
return true;
}
else
{
system_time timeoutTime = get_system_time() + waitDuration;
return pWaitCondition_->timed_wait(lock, timeoutTime);
}
}
catch(const thread_resource_error& e)
{
Error waitError(boost::thread_error::ec_from_exception(e), ERROR_LOCATION);
LOG_ERROR(waitError);
return false;
}
}
private:
// synchronization objects. heap based so that we can control whether
// they are destroyed or not (boost has been known to crash if a mutex
// is being destroyed while it is being waited on so sometimes it is
// better to simply never delete these objects
boost::mutex* pMutex_;
boost::condition* pWaitCondition_;
// instance data
const bool freeSyncObjects_;
std::queue<T> queue_;
};
template <typename T>
class ThreadsafeSet
{
public:
bool contains(const T& value) const
{
LOCK_MUTEX(mutex_)
{
return set_.find(value) != set_.end();
}
END_LOCK_MUTEX
// This will only be hit if we had a problem acquiring the lock, which likely means we have bigger problems.
return false;
}
void insert(const T& value)
{
LOCK_MUTEX(mutex_)
{
set_.insert(value);
}
END_LOCK_MUTEX
}
void insert(T&& value)
{
LOCK_MUTEX(mutex_)
{
set_.insert(value);
}
END_LOCK_MUTEX
}
void remove(const T& value)
{
std::set<std::string> test;
LOCK_MUTEX(mutex_)
{
auto itr = set_.find(value);
if (itr != set_.end())
set_.erase(value);
}
END_LOCK_MUTEX
}
private:
// We need to supply the default std::set template argument values because there's a compiler bug pre MSVC 2019 16.6:
// https://developercommunity.visualstudio.com/content/problem/910615/c2976-during-function-template-argument-deduction.html
std::set<T, std::less<T>, std::allocator<T> > set_;
mutable boost::mutex mutex_;
};
void safeLaunchThread(boost::function<void()> threadMain,
boost::thread* pThread = nullptr);
} // namespace thread
} // namespace core
} // namespace rstudio
#endif // CORE_THREAD_HPP
<commit_msg>Remove debugging code from Thread.hpp (std::set<std::string> test)<commit_after>/*
* Thread.hpp
*
* Copyright (C) 2020 by RStudio, PBC
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* 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.
*
*/
#ifndef CORE_THREAD_HPP
#define CORE_THREAD_HPP
#include <queue>
#include <boost/utility.hpp>
#include <boost/function.hpp>
#include <core/BoostErrors.hpp>
#include <core/BoostThread.hpp>
#include <shared_core/Error.hpp>
#include <core/Log.hpp>
#define LOCK_MUTEX(m) \
try \
{ \
boost::lock_guard<boost::mutex> lock(m);
#define RECURSIVE_LOCK_MUTEX(m) \
try \
{ \
boost::lock_guard<boost::recursive_mutex> lock(m);
#define UNIQUE_LOCK_MUTEX(m, lockvar) \
try \
{ \
boost::unique_lock<boost::mutex> lockvar(m); \
#define END_LOCK_MUTEX \
} \
catch (const boost::thread_resource_error& e) \
{ \
core::Error threadError(boost::thread_error::ec_from_exception(e), \
ERROR_LOCATION); \
LOG_ERROR(threadError); \
} \
CATCH_UNEXPECTED_EXCEPTION
namespace rstudio {
namespace core {
namespace thread {
template <typename T>
class ThreadsafeValue : boost::noncopyable
{
public:
explicit ThreadsafeValue(const T& value = T()) : value_(value) {}
virtual ~ThreadsafeValue() {}
T get()
{
LOCK_MUTEX(mutex_)
{
return value_;
}
END_LOCK_MUTEX
// keep compiler happy
return T();
}
void set(const T& value)
{
LOCK_MUTEX(mutex_)
{
value_ = value;
}
END_LOCK_MUTEX
}
private:
boost::mutex mutex_;
T value_;
};
template <typename K, typename V>
class ThreadsafeMap : boost::noncopyable
{
public:
ThreadsafeMap() {}
virtual ~ThreadsafeMap() {}
bool contains(const K& key)
{
LOCK_MUTEX(mutex_)
{
return map_.find(key) != map_.end();
}
END_LOCK_MUTEX
// keep compiler happy
return false;
}
V get(const K& key, const V& defaultValue = V())
{
LOCK_MUTEX(mutex_)
{
typename std::map<K,V>::const_iterator it = map_.find(key);
if (it != map_.end())
return it->second;
else
return defaultValue;
}
END_LOCK_MUTEX
// keep compiler happy
return defaultValue;
}
V collect(const K& key)
{
LOCK_MUTEX(mutex_)
{
typename std::map<K,V>::const_iterator it = map_.find(key);
if (it != map_.end())
{
V val = it->second;
map_.erase(key);
return val;
}
}
END_LOCK_MUTEX
return V();
}
void set(const K& key, const V& val)
{
LOCK_MUTEX(mutex_)
{
map_[key] = val;
}
END_LOCK_MUTEX
}
void remove(const K& key)
{
LOCK_MUTEX(mutex_)
{
map_.erase(key);
}
END_LOCK_MUTEX
}
void clear()
{
LOCK_MUTEX(mutex_)
{
map_.clear();
}
END_LOCK_MUTEX
}
private:
boost::mutex mutex_;
std::map<K,V> map_;
};
template <typename T>
class ThreadsafeQueue : boost::noncopyable
{
public:
explicit ThreadsafeQueue(bool freeSyncObjects = false)
: pMutex_(new boost::mutex()),
pWaitCondition_(new boost::condition()),
freeSyncObjects_(freeSyncObjects)
{
}
virtual ~ThreadsafeQueue()
{
try
{
if (freeSyncObjects_)
{
delete pMutex_;
delete pWaitCondition_;
}
}
catch(...)
{
}
}
// COPYING: boost::noncopyable
public:
void enque(const T& val)
{
LOCK_MUTEX(*pMutex_)
{
// enque
queue_.push(val);
}
END_LOCK_MUTEX
pWaitCondition_->notify_all();
}
bool deque(T* pVal)
{
LOCK_MUTEX(*pMutex_)
{
if (!queue_.empty())
{
// remove it
*pVal = queue_.front();
queue_.pop();
// return true
return true;
}
else
{
return false;
}
}
END_LOCK_MUTEX
// keep compiler happy
return false;
}
bool isEmpty()
{
LOCK_MUTEX(*pMutex_)
{
return queue_.empty();
}
END_LOCK_MUTEX
// keep compiler happy
return true;
}
bool deque(T* pVal, const boost::posix_time::time_duration& waitDuration)
{
// first see if we already have one
if (deque(pVal))
return true;
// now wait the specified interval for one to materialize
if (wait(waitDuration))
return deque(pVal);
else
return false;
}
bool wait(const boost::posix_time::time_duration& waitDuration =
boost::posix_time::time_duration(boost::posix_time::not_a_date_time))
{
using namespace boost;
try
{
unique_lock<mutex> lock(*pMutex_);
if (waitDuration.is_not_a_date_time())
{
pWaitCondition_->wait(lock);
return true;
}
else
{
system_time timeoutTime = get_system_time() + waitDuration;
return pWaitCondition_->timed_wait(lock, timeoutTime);
}
}
catch(const thread_resource_error& e)
{
Error waitError(boost::thread_error::ec_from_exception(e), ERROR_LOCATION);
LOG_ERROR(waitError);
return false;
}
}
private:
// synchronization objects. heap based so that we can control whether
// they are destroyed or not (boost has been known to crash if a mutex
// is being destroyed while it is being waited on so sometimes it is
// better to simply never delete these objects
boost::mutex* pMutex_;
boost::condition* pWaitCondition_;
// instance data
const bool freeSyncObjects_;
std::queue<T> queue_;
};
template <typename T>
class ThreadsafeSet
{
public:
bool contains(const T& value) const
{
LOCK_MUTEX(mutex_)
{
return set_.find(value) != set_.end();
}
END_LOCK_MUTEX
// This will only be hit if we had a problem acquiring the lock, which likely means we have bigger problems.
return false;
}
void insert(const T& value)
{
LOCK_MUTEX(mutex_)
{
set_.insert(value);
}
END_LOCK_MUTEX
}
void insert(T&& value)
{
LOCK_MUTEX(mutex_)
{
set_.insert(value);
}
END_LOCK_MUTEX
}
void remove(const T& value)
{
LOCK_MUTEX(mutex_)
{
auto itr = set_.find(value);
if (itr != set_.end())
set_.erase(value);
}
END_LOCK_MUTEX
}
private:
// We need to supply the default std::set template argument values because there's a compiler bug pre MSVC 2019 16.6:
// https://developercommunity.visualstudio.com/content/problem/910615/c2976-during-function-template-argument-deduction.html
std::set<T, std::less<T>, std::allocator<T> > set_;
mutable boost::mutex mutex_;
};
void safeLaunchThread(boost::function<void()> threadMain,
boost::thread* pThread = nullptr);
} // namespace thread
} // namespace core
} // namespace rstudio
#endif // CORE_THREAD_HPP
<|endoftext|>
|
<commit_before>// ROOT6 modifications
#ifdef __CLING__
#include <AliAnalysisManager.h>
#include <AliAODInputHandler.h>
#include <AliDielectronVarCuts.h>
// Tell ROOT where to find AliPhysics headers
R__ADD_INCLUDE_PATH($ALICE_PHYSICS)
#include <PWGDQ/dielectron/macrosLMEE/Config_miweber_LMEE_PbPb_woCutLib.C>
#endif
AliAnalysisTask *AddTask_miweber_LMEE_PbPb_woCutLib(Int_t cutDefinition = 0,
TString outputFileName = "AnalysisResult.root",
TString directoryBaseName = "miweber_LMEE_PbPb",
Bool_t isNano = kFALSE,
Bool_t bCutQA = kTRUE,
Bool_t useTPCCorr=kFALSE,
Bool_t useRotation=kFALSE,
Bool_t useMixing=kTRUE,
Bool_t noPairing=kFALSE,
Bool_t bUsePileUpCutsTPCClusters = kFALSE,
Float_t pileUpCutsTPCClustersMin = 0.,
Float_t pileUpCutsTPCClustersMax = 0.
){
//get the current analysis manager
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("AddTask_miweber_LMEE_PbPb_woCutLib", "No analysis manager found.");
return 0;
}
Bool_t bESDANA=kFALSE; //Autodetect via InputHandler
// ROOT6 modifications
#ifndef __CLING__
TString configBasePath("$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/");
TString configFile("Config_miweber_LMEE_PbPb_woCutLib.C");
TString configFilePath(configBasePath+configFile);
//load dielectron configuration files
if (!gROOT->GetListOfGlobalFunctions()->FindObject(configFile.Data()))
gROOT->LoadMacro(configFilePath.Data());
#endif
//Do we have an MC handler?
Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0);
//AOD Usage currently tested with Input handler
if (mgr->GetInputEventHandler()->IsA()==AliAODInputHandler::Class()){
::Info("AddTask_miweber_LMEE_PbPb_woCutLib", "no dedicated AOD configuration");
}
else if (mgr->GetInputEventHandler()->IsA()==AliESDInputHandler::Class()){
::Info("AddTask_miweber_LMEE_PbPb_woCutLib","switching on ESD specific code");
bESDANA=kTRUE;
}
//create task and add it to the manager
AliAnalysisTaskMultiDielectron *task=new AliAnalysisTaskMultiDielectron("MultiDiEData_miweber_PbPb_woCutLib");
// for MC no need for physics selection and for Nano AODs this has been done already
if (!hasMC && !isNano) task->UsePhysicsSelection();
//Add event filter
Int_t triggerNames = AliVEvent::kINT7;//PbPb Min Bias, can be set also from outside
// for Nano AODs this has been done already
if(!isNano){
task->SelectCollisionCandidates(triggerNames);
task->SetTriggerMask(triggerNames);
// task->SetRejectPileup(); // to be done differently (too strong cuts at the moment in dielectron framework)
}
// Note: event cuts are identical for all analysis 'cutDefinition's that run together!
//Add event filter
task->SetEventFilter( GetEventCuts() );
// Add the task to the manager
mgr->AddTask(task);
//add dielectron analysis with selected cut to the task
AliDielectron *diel_low = Config_miweber_LMEE_PbPb_woCutLib(cutDefinition,bESDANA,bCutQA,kFALSE,useTPCCorr,useRotation,useMixing,noPairing,hasMC);
if(diel_low){
AliDielectronVarCuts *eventplaneCuts = new AliDielectronVarCuts("eventplaneCuts","eventplaneCuts");
// use event plane cuts only for this cut set
if(cutDefinition==671){
eventplaneCuts->AddCut(AliDielectronVarManager::kQnTPCrpH2,-999.,kTRUE); // makes sure that the event has an eventplane
eventplaneCuts->Print();
diel_low->GetEventFilter().AddCuts(eventplaneCuts);
}
// use pile-up rejection cuts based on TPC clusters/event
if(bUsePileUpCutsTPCClusters){
Printf("Using TPC cluster based pile-up cuts with parameter 0 from %f to %f",pileUpCutsTPCClustersMin,pileUpCutsTPCClustersMax);
TF1* fFitMin = new TF1("fFit","pol4",0,90);
fFitMin->SetParameters(pileUpCutsTPCClustersMin,-109555,2309.01,-27.2048,0.129126);
TF1* fFitMax = new TF1("fFit","pol4",0,90);
fFitMax->SetParameters(pileUpCutsTPCClustersMax,-109555,2309.01,-27.2048,0.129126);
AliDielectronEventCuts *pileUpCuts = new AliDielectronEventCuts("pileUpCuts","pileUpCuts");
pileUpCuts->SetMinCorrCutFunction(fFitMin, AliDielectronVarManager::kCentralityNew, AliDielectronVarManager::kNTPCclsEvent);
pileUpCuts->SetMaxCorrCutFunction(fFitMax, AliDielectronVarManager::kCentralityNew, AliDielectronVarManager::kNTPCclsEvent);
pileUpCuts->Print();
diel_low->GetEventFilter().AddCuts(pileUpCuts);
}
task->AddDielectron(diel_low);
printf("successfully added AliDielectron: %s\n",diel_low->GetName());
}
else{
Printf("=======================================");
Printf("No AliDielectron object loaded -> EXIT ");
Printf("=======================================");
return NULL;
}
//create output container
AliAnalysisDataContainer *coutput1 =
mgr->CreateContainer(Form("%s_tree",directoryBaseName.Data()),
TTree::Class(),
AliAnalysisManager::kExchangeContainer,
outputFileName.Data());
AliAnalysisDataContainer *cOutputHist1 =
mgr->CreateContainer(Form("%s_out",directoryBaseName.Data()),
TList::Class(),
AliAnalysisManager::kOutputContainer,
outputFileName.Data());
AliAnalysisDataContainer *cOutputHist2 =
mgr->CreateContainer(Form("%s_CF",directoryBaseName.Data()),
TList::Class(),
AliAnalysisManager::kOutputContainer,
outputFileName.Data());
// "miweber_LMEE_PbPb_CF.root");
AliAnalysisDataContainer *cOutputHist3 =
mgr->CreateContainer(Form("%s_EventStat",directoryBaseName.Data()),
TH1D::Class(),
AliAnalysisManager::kOutputContainer,
outputFileName.Data());
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
if((AliAnalysisDataContainer*)mgr->GetContainers()->FindObject("ZDCEPExchangeContainer"))
mgr->ConnectInput(task, 1,(AliAnalysisDataContainer*)mgr->GetContainers()->FindObject("ZDCEPExchangeContainer"));
mgr->ConnectOutput(task, 0, coutput1 );
mgr->ConnectOutput(task, 1, cOutputHist1);
mgr->ConnectOutput(task, 2, cOutputHist2);
mgr->ConnectOutput(task, 3, cOutputHist3);
return task;
}
<commit_msg>TPC cluster fit for pile-up: pol4 -> pol6<commit_after>// ROOT6 modifications
#ifdef __CLING__
#include <AliAnalysisManager.h>
#include <AliAODInputHandler.h>
#include <AliDielectronVarCuts.h>
// Tell ROOT where to find AliPhysics headers
R__ADD_INCLUDE_PATH($ALICE_PHYSICS)
#include <PWGDQ/dielectron/macrosLMEE/Config_miweber_LMEE_PbPb_woCutLib.C>
#endif
AliAnalysisTask *AddTask_miweber_LMEE_PbPb_woCutLib(Int_t cutDefinition = 0,
TString outputFileName = "AnalysisResult.root",
TString directoryBaseName = "miweber_LMEE_PbPb",
Bool_t isNano = kFALSE,
Bool_t bCutQA = kTRUE,
Bool_t useTPCCorr=kFALSE,
Bool_t useRotation=kFALSE,
Bool_t useMixing=kTRUE,
Bool_t noPairing=kFALSE,
Bool_t bUsePileUpCutsTPCClusters = kFALSE,
Float_t pileUpCutsTPCClustersMin = 0.,
Float_t pileUpCutsTPCClustersMax = 0.
){
//get the current analysis manager
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("AddTask_miweber_LMEE_PbPb_woCutLib", "No analysis manager found.");
return 0;
}
Bool_t bESDANA=kFALSE; //Autodetect via InputHandler
// ROOT6 modifications
#ifndef __CLING__
TString configBasePath("$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/");
TString configFile("Config_miweber_LMEE_PbPb_woCutLib.C");
TString configFilePath(configBasePath+configFile);
//load dielectron configuration files
if (!gROOT->GetListOfGlobalFunctions()->FindObject(configFile.Data()))
gROOT->LoadMacro(configFilePath.Data());
#endif
//Do we have an MC handler?
Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0);
//AOD Usage currently tested with Input handler
if (mgr->GetInputEventHandler()->IsA()==AliAODInputHandler::Class()){
::Info("AddTask_miweber_LMEE_PbPb_woCutLib", "no dedicated AOD configuration");
}
else if (mgr->GetInputEventHandler()->IsA()==AliESDInputHandler::Class()){
::Info("AddTask_miweber_LMEE_PbPb_woCutLib","switching on ESD specific code");
bESDANA=kTRUE;
}
//create task and add it to the manager
AliAnalysisTaskMultiDielectron *task=new AliAnalysisTaskMultiDielectron("MultiDiEData_miweber_PbPb_woCutLib");
// for MC no need for physics selection and for Nano AODs this has been done already
if (!hasMC && !isNano) task->UsePhysicsSelection();
//Add event filter
Int_t triggerNames = AliVEvent::kINT7;//PbPb Min Bias, can be set also from outside
// for Nano AODs this has been done already
if(!isNano){
task->SelectCollisionCandidates(triggerNames);
task->SetTriggerMask(triggerNames);
// task->SetRejectPileup(); // to be done differently (too strong cuts at the moment in dielectron framework)
}
// Note: event cuts are identical for all analysis 'cutDefinition's that run together!
//Add event filter
task->SetEventFilter( GetEventCuts() );
// Add the task to the manager
mgr->AddTask(task);
//add dielectron analysis with selected cut to the task
AliDielectron *diel_low = Config_miweber_LMEE_PbPb_woCutLib(cutDefinition,bESDANA,bCutQA,kFALSE,useTPCCorr,useRotation,useMixing,noPairing,hasMC);
if(diel_low){
AliDielectronVarCuts *eventplaneCuts = new AliDielectronVarCuts("eventplaneCuts","eventplaneCuts");
// use event plane cuts only for this cut set
if(cutDefinition==671){
eventplaneCuts->AddCut(AliDielectronVarManager::kQnTPCrpH2,-999.,kTRUE); // makes sure that the event has an eventplane
eventplaneCuts->Print();
diel_low->GetEventFilter().AddCuts(eventplaneCuts);
}
// use pile-up rejection cuts based on TPC clusters/event
if(bUsePileUpCutsTPCClusters){
Printf("Using TPC cluster based pile-up cuts with parameter 0 from %f to %f",pileUpCutsTPCClustersMin,pileUpCutsTPCClustersMax);
TF1* fFitMin = new TF1("fFit","pol6",0,90);
TF1* fFitMax = new TF1("fFit","pol6",0,90);
fFitMin->SetParameters(pileUpCutsTPCClustersMin,-95678.946999,2152.010478,-50.119000,0.780528,-0.006150,0.000019);
fFitMax->SetParameters(pileUpCutsTPCClustersMax,-95678.946999,2152.010478,-50.119000,0.780528,-0.006150,0.000019);
AliDielectronEventCuts *pileUpCuts = new AliDielectronEventCuts("pileUpCuts","pileUpCuts");
pileUpCuts->SetMinCorrCutFunction(fFitMin, AliDielectronVarManager::kCentralityNew, AliDielectronVarManager::kNTPCclsEvent);
pileUpCuts->SetMaxCorrCutFunction(fFitMax, AliDielectronVarManager::kCentralityNew, AliDielectronVarManager::kNTPCclsEvent);
pileUpCuts->Print();
diel_low->GetEventFilter().AddCuts(pileUpCuts);
}
task->AddDielectron(diel_low);
printf("successfully added AliDielectron: %s\n",diel_low->GetName());
}
else{
Printf("=======================================");
Printf("No AliDielectron object loaded -> EXIT ");
Printf("=======================================");
return NULL;
}
//create output container
AliAnalysisDataContainer *coutput1 =
mgr->CreateContainer(Form("%s_tree",directoryBaseName.Data()),
TTree::Class(),
AliAnalysisManager::kExchangeContainer,
outputFileName.Data());
AliAnalysisDataContainer *cOutputHist1 =
mgr->CreateContainer(Form("%s_out",directoryBaseName.Data()),
TList::Class(),
AliAnalysisManager::kOutputContainer,
outputFileName.Data());
AliAnalysisDataContainer *cOutputHist2 =
mgr->CreateContainer(Form("%s_CF",directoryBaseName.Data()),
TList::Class(),
AliAnalysisManager::kOutputContainer,
outputFileName.Data());
// "miweber_LMEE_PbPb_CF.root");
AliAnalysisDataContainer *cOutputHist3 =
mgr->CreateContainer(Form("%s_EventStat",directoryBaseName.Data()),
TH1D::Class(),
AliAnalysisManager::kOutputContainer,
outputFileName.Data());
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
if((AliAnalysisDataContainer*)mgr->GetContainers()->FindObject("ZDCEPExchangeContainer"))
mgr->ConnectInput(task, 1,(AliAnalysisDataContainer*)mgr->GetContainers()->FindObject("ZDCEPExchangeContainer"));
mgr->ConnectOutput(task, 0, coutput1 );
mgr->ConnectOutput(task, 1, cOutputHist1);
mgr->ConnectOutput(task, 2, cOutputHist2);
mgr->ConnectOutput(task, 3, cOutputHist3);
return task;
}
<|endoftext|>
|
<commit_before>/****************************************************************************
*
* Copyright (c) 2019 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
#pragma once
#include <stdint.h>
namespace px4
{
class WorkQueue; // forward declaration
struct wq_config_t {
const char *name;
uint16_t stacksize;
int8_t relative_priority; // relative to max
};
namespace wq_configurations
{
static constexpr wq_config_t rate_ctrl{"wq:rate_ctrl", 1600, 0}; // PX4 inner loop highest priority
static constexpr wq_config_t SPI0{"wq:SPI0", 1900, -1};
static constexpr wq_config_t SPI1{"wq:SPI1", 1900, -2};
static constexpr wq_config_t SPI2{"wq:SPI2", 1900, -3};
static constexpr wq_config_t SPI3{"wq:SPI3", 1900, -4};
static constexpr wq_config_t SPI4{"wq:SPI4", 1900, -5};
static constexpr wq_config_t SPI5{"wq:SPI5", 1900, -6};
static constexpr wq_config_t SPI6{"wq:SPI6", 1900, -7};
static constexpr wq_config_t I2C0{"wq:I2C0", 1400, -8};
static constexpr wq_config_t I2C1{"wq:I2C1", 1400, -9};
static constexpr wq_config_t I2C2{"wq:I2C2", 1400, -10};
static constexpr wq_config_t I2C3{"wq:I2C3", 1400, -11};
static constexpr wq_config_t I2C4{"wq:I2C4", 1400, -12};
static constexpr wq_config_t att_pos_ctrl{"wq:att_pos_ctrl", 6600, -13}; // PX4 att/pos controllers, highest priority after sensors
static constexpr wq_config_t hp_default{"wq:hp_default", 1900, -14};
static constexpr wq_config_t uavcan{"wq:uavcan", 2400, -15};
static constexpr wq_config_t UART0{"wq:UART0", 1400, -16};
static constexpr wq_config_t UART1{"wq:UART1", 1400, -17};
static constexpr wq_config_t UART2{"wq:UART2", 1400, -18};
static constexpr wq_config_t UART3{"wq:UART3", 1400, -19};
static constexpr wq_config_t UART4{"wq:UART4", 1400, -20};
static constexpr wq_config_t UART5{"wq:UART5", 1400, -21};
static constexpr wq_config_t UART6{"wq:UART6", 1400, -22};
static constexpr wq_config_t UART7{"wq:UART7", 1400, -23};
static constexpr wq_config_t UART8{"wq:UART8", 1400, -24};
static constexpr wq_config_t UART_UNKNOWN{"wq:UART_UNKNOWN", 1400, -25};
static constexpr wq_config_t lp_default{"wq:lp_default", 1700, -50};
static constexpr wq_config_t test1{"wq:test1", 800, 0};
static constexpr wq_config_t test2{"wq:test2", 800, 0};
} // namespace wq_configurations
/**
* Start the work queue manager task.
*/
int WorkQueueManagerStart();
/**
* Stop the work queue manager task.
*/
int WorkQueueManagerStop();
/**
* Work queue manager status.
*/
int WorkQueueManagerStatus();
/**
* Create (or find) a work queue with a particular configuration.
*
* @param new_wq The work queue configuration (see WorkQueueManager.hpp).
* @return A pointer to the WorkQueue, or nullptr on failure.
*/
WorkQueue *WorkQueueFindOrCreate(const wq_config_t &new_wq);
/**
* Map a PX4 driver device id to a work queue (by sensor bus).
*
* @param device_id The PX4 driver's device id.
* @return A work queue configuration.
*/
const wq_config_t &device_bus_to_wq(uint32_t device_id);
/**
* Map a serial device path (eg /dev/ttyS1) to a work queue.
*
* @param device_id The device path.
* @return A work queue configuration.
*/
const wq_config_t &serial_port_to_wq(const char *serial);
} // namespace px4
<commit_msg>platforms: prevent stackoverflow for ekf2 sideslip<commit_after>/****************************************************************************
*
* Copyright (c) 2019 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
#pragma once
#include <stdint.h>
namespace px4
{
class WorkQueue; // forward declaration
struct wq_config_t {
const char *name;
uint16_t stacksize;
int8_t relative_priority; // relative to max
};
namespace wq_configurations
{
static constexpr wq_config_t rate_ctrl{"wq:rate_ctrl", 1600, 0}; // PX4 inner loop highest priority
static constexpr wq_config_t SPI0{"wq:SPI0", 1900, -1};
static constexpr wq_config_t SPI1{"wq:SPI1", 1900, -2};
static constexpr wq_config_t SPI2{"wq:SPI2", 1900, -3};
static constexpr wq_config_t SPI3{"wq:SPI3", 1900, -4};
static constexpr wq_config_t SPI4{"wq:SPI4", 1900, -5};
static constexpr wq_config_t SPI5{"wq:SPI5", 1900, -6};
static constexpr wq_config_t SPI6{"wq:SPI6", 1900, -7};
static constexpr wq_config_t I2C0{"wq:I2C0", 1400, -8};
static constexpr wq_config_t I2C1{"wq:I2C1", 1400, -9};
static constexpr wq_config_t I2C2{"wq:I2C2", 1400, -10};
static constexpr wq_config_t I2C3{"wq:I2C3", 1400, -11};
static constexpr wq_config_t I2C4{"wq:I2C4", 1400, -12};
// PX4 att/pos controllers, highest priority after sensors.
static constexpr wq_config_t att_pos_ctrl{"wq:att_pos_ctrl", 7200, -13};
static constexpr wq_config_t hp_default{"wq:hp_default", 1900, -14};
static constexpr wq_config_t uavcan{"wq:uavcan", 2400, -15};
static constexpr wq_config_t UART0{"wq:UART0", 1400, -16};
static constexpr wq_config_t UART1{"wq:UART1", 1400, -17};
static constexpr wq_config_t UART2{"wq:UART2", 1400, -18};
static constexpr wq_config_t UART3{"wq:UART3", 1400, -19};
static constexpr wq_config_t UART4{"wq:UART4", 1400, -20};
static constexpr wq_config_t UART5{"wq:UART5", 1400, -21};
static constexpr wq_config_t UART6{"wq:UART6", 1400, -22};
static constexpr wq_config_t UART7{"wq:UART7", 1400, -23};
static constexpr wq_config_t UART8{"wq:UART8", 1400, -24};
static constexpr wq_config_t UART_UNKNOWN{"wq:UART_UNKNOWN", 1400, -25};
static constexpr wq_config_t lp_default{"wq:lp_default", 1700, -50};
static constexpr wq_config_t test1{"wq:test1", 800, 0};
static constexpr wq_config_t test2{"wq:test2", 800, 0};
} // namespace wq_configurations
/**
* Start the work queue manager task.
*/
int WorkQueueManagerStart();
/**
* Stop the work queue manager task.
*/
int WorkQueueManagerStop();
/**
* Work queue manager status.
*/
int WorkQueueManagerStatus();
/**
* Create (or find) a work queue with a particular configuration.
*
* @param new_wq The work queue configuration (see WorkQueueManager.hpp).
* @return A pointer to the WorkQueue, or nullptr on failure.
*/
WorkQueue *WorkQueueFindOrCreate(const wq_config_t &new_wq);
/**
* Map a PX4 driver device id to a work queue (by sensor bus).
*
* @param device_id The PX4 driver's device id.
* @return A work queue configuration.
*/
const wq_config_t &device_bus_to_wq(uint32_t device_id);
/**
* Map a serial device path (eg /dev/ttyS1) to a work queue.
*
* @param device_id The device path.
* @return A work queue configuration.
*/
const wq_config_t &serial_port_to_wq(const char *serial);
} // namespace px4
<|endoftext|>
|
<commit_before>/*
* Copyright 2007-2020 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "file_enotdir.hxx"
#include "Request.hxx"
#include "translation/Response.hxx"
#include "file_address.hxx"
#include "cgi/Address.hxx"
#include "lhttp_address.hxx"
#include "http/IncomingRequest.hxx"
#include "pool/pool.hxx"
#include "io/StatAt.hxx"
#include "AllocatorPtr.hxx"
#include <assert.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>
#include <errno.h>
gcc_pure
static bool
IsEnotdir(const char *base, const char *path) noexcept
{
struct statx st;
return !StatAt(base, path, AT_STATX_DONT_SYNC, STATX_TYPE, &st) &&
errno == ENOTDIR;
}
gcc_pure
static const char *
get_file_path(const TranslateResponse &response)
{
if (response.test_path != nullptr)
return response.test_path;
const auto &address = response.address;
switch (address.type) {
case ResourceAddress::Type::NONE:
case ResourceAddress::Type::HTTP:
case ResourceAddress::Type::PIPE:
case ResourceAddress::Type::NFS:
return nullptr;
case ResourceAddress::Type::CGI:
case ResourceAddress::Type::FASTCGI:
case ResourceAddress::Type::WAS:
return address.GetCgi().path;
case ResourceAddress::Type::LHTTP:
return address.GetLhttp().path;
case ResourceAddress::Type::LOCAL:
return address.GetFile().path;
// TODO: implement NFS
}
assert(false);
gcc_unreachable();
}
gcc_pure
static const char *
get_file_base(const TranslateResponse &response) noexcept
{
if (response.test_path != nullptr)
return nullptr;
const auto &address = response.address;
switch (address.type) {
case ResourceAddress::Type::NONE:
case ResourceAddress::Type::HTTP:
case ResourceAddress::Type::PIPE:
case ResourceAddress::Type::NFS:
case ResourceAddress::Type::CGI:
case ResourceAddress::Type::FASTCGI:
case ResourceAddress::Type::WAS:
case ResourceAddress::Type::LHTTP:
return nullptr;
case ResourceAddress::Type::LOCAL:
return address.GetFile().base;
}
assert(false);
gcc_unreachable();
}
static bool
submit_enotdir(Request &request, const TranslateResponse &response)
{
request.translate.request.enotdir = response.enotdir;
const char *const uri = request.request.uri;
if (request.translate.enotdir_uri == nullptr) {
request.translate.request.uri = request.translate.enotdir_uri =
p_strdup(&request.pool, uri);
request.translate.enotdir_path_info = uri + strlen(uri);
}
const char *slash = (const char *)
memrchr(uri, '/', request.translate.enotdir_path_info - uri);
if (slash == nullptr || slash == uri)
return true;
request.translate.enotdir_uri[slash - uri] = 0;
request.translate.enotdir_path_info = slash;
request.SubmitTranslateRequest();
return false;
}
bool
check_file_enotdir(Request &request,
const TranslateResponse &response)
{
assert(!response.enotdir.IsNull());
const char *path = get_file_path(response);
if (path == nullptr) {
request.LogDispatchError(HTTP_STATUS_BAD_GATEWAY,
"Resource address not compatible with ENOTDIR",
1);
return false;
}
if (IsEnotdir(get_file_base(response), path))
return submit_enotdir(request, response);
return true;
}
void
apply_file_enotdir(Request &request)
{
if (request.translate.enotdir_path_info != nullptr) {
/* append the path_info to the resource address */
auto address =
request.translate.address.Apply(request.pool,
request.translate.enotdir_path_info);
if (address.IsDefined())
request.translate.address = {ShallowCopy(), address};
}
}
<commit_msg>bp/file_enotdir: use move operator instead of ShallowCopy<commit_after>/*
* Copyright 2007-2020 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "file_enotdir.hxx"
#include "Request.hxx"
#include "translation/Response.hxx"
#include "file_address.hxx"
#include "cgi/Address.hxx"
#include "lhttp_address.hxx"
#include "http/IncomingRequest.hxx"
#include "pool/pool.hxx"
#include "io/StatAt.hxx"
#include "AllocatorPtr.hxx"
#include <assert.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>
#include <errno.h>
gcc_pure
static bool
IsEnotdir(const char *base, const char *path) noexcept
{
struct statx st;
return !StatAt(base, path, AT_STATX_DONT_SYNC, STATX_TYPE, &st) &&
errno == ENOTDIR;
}
gcc_pure
static const char *
get_file_path(const TranslateResponse &response)
{
if (response.test_path != nullptr)
return response.test_path;
const auto &address = response.address;
switch (address.type) {
case ResourceAddress::Type::NONE:
case ResourceAddress::Type::HTTP:
case ResourceAddress::Type::PIPE:
case ResourceAddress::Type::NFS:
return nullptr;
case ResourceAddress::Type::CGI:
case ResourceAddress::Type::FASTCGI:
case ResourceAddress::Type::WAS:
return address.GetCgi().path;
case ResourceAddress::Type::LHTTP:
return address.GetLhttp().path;
case ResourceAddress::Type::LOCAL:
return address.GetFile().path;
// TODO: implement NFS
}
assert(false);
gcc_unreachable();
}
gcc_pure
static const char *
get_file_base(const TranslateResponse &response) noexcept
{
if (response.test_path != nullptr)
return nullptr;
const auto &address = response.address;
switch (address.type) {
case ResourceAddress::Type::NONE:
case ResourceAddress::Type::HTTP:
case ResourceAddress::Type::PIPE:
case ResourceAddress::Type::NFS:
case ResourceAddress::Type::CGI:
case ResourceAddress::Type::FASTCGI:
case ResourceAddress::Type::WAS:
case ResourceAddress::Type::LHTTP:
return nullptr;
case ResourceAddress::Type::LOCAL:
return address.GetFile().base;
}
assert(false);
gcc_unreachable();
}
static bool
submit_enotdir(Request &request, const TranslateResponse &response)
{
request.translate.request.enotdir = response.enotdir;
const char *const uri = request.request.uri;
if (request.translate.enotdir_uri == nullptr) {
request.translate.request.uri = request.translate.enotdir_uri =
p_strdup(&request.pool, uri);
request.translate.enotdir_path_info = uri + strlen(uri);
}
const char *slash = (const char *)
memrchr(uri, '/', request.translate.enotdir_path_info - uri);
if (slash == nullptr || slash == uri)
return true;
request.translate.enotdir_uri[slash - uri] = 0;
request.translate.enotdir_path_info = slash;
request.SubmitTranslateRequest();
return false;
}
bool
check_file_enotdir(Request &request,
const TranslateResponse &response)
{
assert(!response.enotdir.IsNull());
const char *path = get_file_path(response);
if (path == nullptr) {
request.LogDispatchError(HTTP_STATUS_BAD_GATEWAY,
"Resource address not compatible with ENOTDIR",
1);
return false;
}
if (IsEnotdir(get_file_base(response), path))
return submit_enotdir(request, response);
return true;
}
void
apply_file_enotdir(Request &request)
{
if (request.translate.enotdir_path_info != nullptr) {
/* append the path_info to the resource address */
auto address =
request.translate.address.Apply(request.pool,
request.translate.enotdir_path_info);
if (address.IsDefined())
request.translate.address = std::move(address);
}
}
<|endoftext|>
|
<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#ifdef _MSC_VER
#pragma warning( 4: 4786)
#endif
#include <stdio.h>
#include <iostream>
#include <map>
#include <string>
#include "BZAdminClient.h"
#include "BZAdminUI.h"
#include "OptionParser.h"
#include "UIMap.h"
// causes persistent rebuilding to obtain build versioning
#include "version.h"
int debugLevel = 0;
#ifdef _WIN32
void Player::setDeadReckoning()
{
}
#endif
/** @file
This is the main file for bzadmin, the bzflag text client.
*/
int main(int argc, char** argv) {
#ifdef _WIN32
// startup winsock
{
static const int major = 2, minor = 2;
WSADATA wsaData;
if (WSAStartup(MAKEWORD(major, minor), &wsaData)) {
return 1;
}
if (LOBYTE(wsaData.wVersion) != major ||
HIBYTE(wsaData.wVersion) != minor) {
WSACleanup();
return 1;
}
}
#endif
// command line options
std::string uiName("curses");
std::vector<std::string> visibleMsgs;
std::vector<std::string> invisibleMsgs;
// no curses, use stdboth as default instead
const UIMap& interfaces = UIMap::instance();
if (interfaces.find("curses") == interfaces.end())
uiName = "stdboth";
// build a usage string with all interfaces
UIMap::const_iterator uiIter;
std::string uiUsage;
for (uiIter = interfaces.begin(); uiIter != interfaces.end(); ++uiIter)
uiUsage += uiIter->first + '|';
uiUsage = std::string("[-ui ") + uiUsage.substr(0, uiUsage.size() - 1) + ']';
// register and parse command line arguments
OptionParser op(std::string("bzadmin ") + getAppVersion(),
"CALLSIGN@HOST[:PORT] [COMMAND] [COMMAND] ...");
const std::string uiOption("ui");
const std::string uiMsg = "choose a user interface";
op.registerVariable(uiOption, uiName, uiUsage, uiMsg);
op.registerVector("show", visibleMsgs, "[-show msgtype{,msgtype}*]",
"tell bzadmin to show these message types");
op.registerVector("hide", invisibleMsgs, "[-hide msgtype{,msgtype}*]",
"tell bzadmin not to show these message types");
if (!op.parse(argc, argv))
return 1;
// check that we have callsign and host in the right format and extract them
int atPos;
std::string name = "", host = "";
if (!(op.getParameters().size() > 0 &&
(atPos = op.getParameters()[0].find('@')) > 0)) {
// input callsign and host interactively
std::cout << "No callsign@host specified. Please input them" << std::endl;
std::cout << "Callsign: ";
std::cin >> name;
if (name.size() <= 1) {
std::cerr << "You must specify a callsign. Exiting." << std::endl;
return 1;
}
std::cout << "Server to connect to: ";
std::cin >> host;
if (host.size() <= 1) {
std::cerr << "You must specify a host name to connect to. Exiting." << std::endl;
return 1;
}
} else { // callsign/host on command line
name = op.getParameters()[0].substr(0, atPos);
host = op.getParameters()[0].substr(atPos + 1);
}
int port = ServerPort;
int cPos = host.find(':');
if (cPos != -1) {
port = atoi(host.substr(cPos + 1).c_str());
host = host.substr(0, cPos);
}
// check that the ui is valid
uiIter = UIMap::instance().find(uiName);
if (uiIter == UIMap::instance().end()) {
std::cerr<<"There is no interface called \""<<uiName<<"\"."<<std::endl;
return 1;
}
// try to connect
BZAdminClient client(name, host, port);
if (!client.isValid())
return 1;
unsigned int i;
for (i = 0; i < visibleMsgs.size(); ++i)
client.showMessageType(visibleMsgs[i]);
for (i = 0; i < invisibleMsgs.size(); ++i)
client.ignoreMessageType(invisibleMsgs[i]);
// if we got commands as arguments, send them and exit
if (op.getParameters().size() > 1) {
for (unsigned int i = 1; i < op.getParameters().size(); ++i)
client.sendMessage(op.getParameters()[i], AllPlayers);
client.waitForServer();
return 0;
}
// create UI and run the main loop
BZAdminUI* ui = uiIter->second(client);
client.setUI(ui);
client.runLoop();
delete ui;
return 0;
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>don't quit bzadmin automatically if there are commands as arguments<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#ifdef _MSC_VER
#pragma warning( 4: 4786)
#endif
#include <stdio.h>
#include <iostream>
#include <map>
#include <string>
#include "BZAdminClient.h"
#include "BZAdminUI.h"
#include "OptionParser.h"
#include "UIMap.h"
// causes persistent rebuilding to obtain build versioning
#include "version.h"
int debugLevel = 0;
#ifdef _WIN32
void Player::setDeadReckoning()
{
}
#endif
/** @file
This is the main file for bzadmin, the bzflag text client.
*/
int main(int argc, char** argv) {
bool earlyQuit = false;
// FIXME - build this into OptionParser (VariableSimple parser?)
if ((argc > 1) && (strcmp (argv[1], "-q") == 0)) {
earlyQuit = true;
argv[1] = argv[0]; // eat the option
argv++;
argc--;
}
#ifdef _WIN32
// startup winsock
{
static const int major = 2, minor = 2;
WSADATA wsaData;
if (WSAStartup(MAKEWORD(major, minor), &wsaData)) {
return 1;
}
if (LOBYTE(wsaData.wVersion) != major ||
HIBYTE(wsaData.wVersion) != minor) {
WSACleanup();
return 1;
}
}
#endif
// command line options
std::string uiName("curses");
std::vector<std::string> visibleMsgs;
std::vector<std::string> invisibleMsgs;
// no curses, use stdboth as default instead
const UIMap& interfaces = UIMap::instance();
if (interfaces.find("curses") == interfaces.end())
uiName = "stdboth";
// build a usage string with all interfaces
UIMap::const_iterator uiIter;
std::string uiUsage;
for (uiIter = interfaces.begin(); uiIter != interfaces.end(); ++uiIter)
uiUsage += uiIter->first + '|';
uiUsage = std::string("[-ui ") + uiUsage.substr(0, uiUsage.size() - 1) + ']';
// register and parse command line arguments
OptionParser op(std::string("bzadmin ") + getAppVersion(),
"CALLSIGN@HOST[:PORT] [COMMAND] [COMMAND] ...");
const std::string uiOption("ui");
const std::string uiMsg = "choose a user interface";
op.registerVariable(uiOption, uiName, uiUsage, uiMsg);
op.registerVector("show", visibleMsgs, "[-show msgtype{,msgtype}*]",
"tell bzadmin to show these message types");
op.registerVector("hide", invisibleMsgs, "[-hide msgtype{,msgtype}*]",
"tell bzadmin not to show these message types");
if (!op.parse(argc, argv))
return 1;
// check that we have callsign and host in the right format and extract them
int atPos;
std::string name = "", host = "";
if (!(op.getParameters().size() > 0 &&
(atPos = op.getParameters()[0].find('@')) > 0)) {
// input callsign and host interactively
std::cout << "No callsign@host specified. Please input them" << std::endl;
std::cout << "Callsign: ";
std::cin >> name;
if (name.size() <= 1) {
std::cerr << "You must specify a callsign. Exiting." << std::endl;
return 1;
}
std::cout << "Server to connect to: ";
std::cin >> host;
if (host.size() <= 1) {
std::cerr << "You must specify a host name to connect to. Exiting." << std::endl;
return 1;
}
} else { // callsign/host on command line
name = op.getParameters()[0].substr(0, atPos);
host = op.getParameters()[0].substr(atPos + 1);
}
int port = ServerPort;
int cPos = host.find(':');
if (cPos != -1) {
port = atoi(host.substr(cPos + 1).c_str());
host = host.substr(0, cPos);
}
// check that the ui is valid
uiIter = UIMap::instance().find(uiName);
if (uiIter == UIMap::instance().end()) {
std::cerr<<"There is no interface called \""<<uiName<<"\"."<<std::endl;
return 1;
}
// try to connect
BZAdminClient client(name, host, port);
if (!client.isValid())
return 1;
unsigned int i;
for (i = 0; i < visibleMsgs.size(); ++i)
client.showMessageType(visibleMsgs[i]);
for (i = 0; i < invisibleMsgs.size(); ++i)
client.ignoreMessageType(invisibleMsgs[i]);
// if we got commands as arguments, send them and exit
if (op.getParameters().size() > 1) {
for (unsigned int i = 1; i < op.getParameters().size(); ++i)
client.sendMessage(op.getParameters()[i], AllPlayers);
if (earlyQuit) {
client.waitForServer();
return 0;
}
}
// Print a friendly warning
if (earlyQuit)
std::cout << "WARNING: didn't quit early, no command line commands" << std::endl;
// create UI and run the main loop
BZAdminUI* ui = uiIter->second(client);
client.setUI(ui);
client.runLoop();
delete ui;
return 0;
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>
|
<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// interface header
#include "RejoinList.h"
// common headers
#include "TimeKeeper.h"
#include "PlayerInfo.h"
#include "StateDatabase.h" // for StateDatabase::BZDB_REJOINTIME
// bzfs specific headers
#include "CmdLineOptions.h" // for MaxPlayers & ReplayObservers
#include "RecordReplay.h"
#include "GameKeeper.h"
// it's loathsome to expose private structure in a header
typedef struct RejoinNode {
char callsign[CallSignLen];
TimeKeeper joinTime;
} RejoinNode;
RejoinList::RejoinList ()
{
queue.clear(); // call me paranoid
}
RejoinList::~RejoinList ()
{
std::list<struct RejoinNode*>::iterator it;
for (it = queue.begin(); it != queue.end(); it++) {
RejoinNode *rn = *it;
delete rn;
}
queue.clear();
}
bool RejoinList::add (int playerIndex)
{
GameKeeper::Player *playerData
= GameKeeper::Player::getPlayerByIndex(playerIndex);
if (!playerData)
return true;
RejoinNode* rn = new RejoinNode;
strcpy (rn->callsign, playerData->player.getCallSign());
rn->joinTime = TimeKeeper::getCurrent();
queue.push_back (rn);
return true;
}
float RejoinList::waitTime (int playerIndex)
{
GameKeeper::Player *playerData
= GameKeeper::Player::getPlayerByIndex(playerIndex);
if (!playerData)
return true;
std::list<struct RejoinNode*>::iterator it;
TimeKeeper thenTime = TimeKeeper::getCurrent();
thenTime += -BZDB.eval(StateDatabase::BZDB_REJOINTIME);
// remove old entries
it = queue.begin();
while (it != queue.end()) {
RejoinNode *rn = *it;
if (rn->joinTime <= thenTime) {
delete rn;
it = queue.erase(it);
continue;
}
it++;
}
const char *callsign = playerData->player.getCallSign();
float value = 0.0f;
it = queue.begin();
while (it != queue.end()) {
RejoinNode *rn = *it;
if (strcasecmp (rn->callsign, callsign) == 0) {
value = rn->joinTime - thenTime;
}
it++;
}
return value;
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>float(true) == ?<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// interface header
#include "RejoinList.h"
// common headers
#include "TimeKeeper.h"
#include "PlayerInfo.h"
#include "StateDatabase.h" // for StateDatabase::BZDB_REJOINTIME
// bzfs specific headers
#include "CmdLineOptions.h" // for MaxPlayers & ReplayObservers
#include "RecordReplay.h"
#include "GameKeeper.h"
// it's loathsome to expose private structure in a header
typedef struct RejoinNode {
char callsign[CallSignLen];
TimeKeeper joinTime;
} RejoinNode;
RejoinList::RejoinList ()
{
queue.clear(); // call me paranoid
}
RejoinList::~RejoinList ()
{
std::list<struct RejoinNode*>::iterator it;
for (it = queue.begin(); it != queue.end(); it++) {
RejoinNode *rn = *it;
delete rn;
}
queue.clear();
}
bool RejoinList::add (int playerIndex)
{
GameKeeper::Player *playerData
= GameKeeper::Player::getPlayerByIndex(playerIndex);
if (playerData == NULL) {
return false;
}
RejoinNode* rn = new RejoinNode;
strcpy (rn->callsign, playerData->player.getCallSign());
rn->joinTime = TimeKeeper::getCurrent();
queue.push_back (rn);
return true;
}
float RejoinList::waitTime (int playerIndex)
{
GameKeeper::Player *playerData
= GameKeeper::Player::getPlayerByIndex(playerIndex);
if (playerData == NULL) {
return 0.0f;
}
std::list<struct RejoinNode*>::iterator it;
TimeKeeper thenTime = TimeKeeper::getCurrent();
thenTime += -BZDB.eval(StateDatabase::BZDB_REJOINTIME);
// remove old entries
it = queue.begin();
while (it != queue.end()) {
RejoinNode *rn = *it;
if (rn->joinTime <= thenTime) {
delete rn;
it = queue.erase(it);
continue;
}
it++;
}
const char *callsign = playerData->player.getCallSign();
float value = 0.0f;
it = queue.begin();
while (it != queue.end()) {
RejoinNode *rn = *it;
if (strcasecmp (rn->callsign, callsign) == 0) {
value = rn->joinTime - thenTime;
}
it++;
}
return value;
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>
|
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright (C) 2017 ScyllaDB
*
* Modified by ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/range/algorithm/transform.hpp>
#include <boost/range/adaptors.hpp>
#include "clustering_bounds_comparator.hh"
#include "cql3/statements/select_statement.hh"
#include "cql3/util.hh"
#include "db/view/view.hh"
namespace db {
namespace view {
cql3::statements::select_statement& view::select_statement() const {
if (!_select_statement) {
std::vector<sstring_view> included;
if (!_schema->view_info()->include_all_columns()) {
included.reserve(_schema->all_columns_in_select_order().size());
boost::transform(_schema->all_columns_in_select_order(), std::back_inserter(included), std::mem_fn(&column_definition::name_as_text));
}
auto raw = cql3::util::build_select_statement(_schema->view_info()->base_name(), _schema->view_info()->where_clause(), std::move(included));
raw->prepare_keyspace(_schema->ks_name());
raw->set_bound_variables({});
cql3::cql_stats ignored;
auto prepared = raw->prepare(service::get_local_storage_proxy().get_db().local(), ignored, true);
_select_statement = static_pointer_cast<cql3::statements::select_statement>(prepared->statement);
}
return *_select_statement;
}
const query::partition_slice& view::partition_slice() const {
if (!_partition_slice) {
_partition_slice = select_statement().make_partition_slice(cql3::query_options({ }));
}
return *_partition_slice;
}
const dht::partition_range_vector& view::partition_ranges() const {
if (!_partition_ranges) {
_partition_ranges = select_statement().get_restrictions()->get_partition_key_ranges(cql3::query_options({ }));
}
return *_partition_ranges;
}
bool view::partition_key_matches(const ::schema& base, const dht::decorated_key& key) const {
dht::ring_position rp(key);
auto& ranges = partition_ranges();
return std::any_of(ranges.begin(), ranges.end(), [&] (auto&& range) {
return range.contains(rp, dht::ring_position_comparator(base));
});
}
bool view::clustering_prefix_matches(const ::schema& base, const partition_key& key, const clustering_key_prefix& ck) const {
bound_view::compare less(base);
auto& ranges = partition_slice().row_ranges(base, key);
return std::any_of(ranges.begin(), ranges.end(), [&] (auto&& range) {
auto bounds = bound_view::from_range(range);
return !less(ck, bounds.first) && !less(bounds.second, ck);
});
}
bool view::may_be_affected_by(const ::schema& base, const dht::decorated_key& key, const rows_entry& update) const {
// We can guarantee that the view won't be affected if:
// - the primary key is excluded by the view filter (note that this isn't true of the filter on regular columns:
// even if an update don't match a view condition on a regular column, that update can still invalidate a
// pre-existing entry);
// - the update doesn't modify any of the columns impacting the view (where "impacting" the view means that column
// is neither included in the view, nor used by the view filter).
if (!partition_key_matches(base, key) && !clustering_prefix_matches(base, key.key(), update.key())) {
return false;
}
// We want to check if the update modifies any of the columns that are part of the view (in which case the view is
// affected). But iff the view includes all the base table columns, or the update has either a row deletion or a
// row marker, we know the view is affected right away.
if (_schema->view_info()->include_all_columns() || update.row().deleted_at() || update.row().marker().is_live()) {
return true;
}
bool affected = false;
update.row().cells().for_each_cell_until([&] (column_id id, const atomic_cell_or_collection& cell) {
affected = _schema->get_column_definition(base.column_at(column_kind::regular_column, id).name());
return stop_iteration(affected);
});
return affected;
}
bool view::matches_view_filter(const ::schema& base, const partition_key& key, const clustering_row& update, gc_clock::time_point now) const {
return clustering_prefix_matches(base, key, update.key()) &&
boost::algorithm::all_of(
select_statement().get_restrictions()->get_non_pk_restriction() | boost::adaptors::map_values,
[&] (auto&& r) {
return r->is_satisfied_by(base, key, update.key(), update.cells(), cql3::query_options({ }), now);
});
}
void view::set_base_non_pk_column_in_view_pk(const ::schema& base) {
for (auto&& base_col : base.regular_columns()) {
auto view_col = _schema->get_column_definition(base_col.name());
if (view_col && view_col->is_primary_key()) {
_base_non_pk_column_in_view_pk = view_col;
return;
}
}
_base_non_pk_column_in_view_pk = nullptr;
}
class view_updates final {
lw_shared_ptr<const db::view::view> _view;
schema_ptr _base;
std::unordered_map<partition_key, mutation_partition, partition_key::hashing, partition_key::equality> _updates;
public:
explicit view_updates(lw_shared_ptr<const db::view::view> view, schema_ptr base)
: _view(std::move(view))
, _base(std::move(base))
, _updates(8, partition_key::hashing(*_base), partition_key::equality(*_base)) {
}
void move_to(std::vector<mutation>& mutations) && {
auto& partitioner = dht::global_partitioner();
std::transform(_updates.begin(), _updates.end(), std::back_inserter(mutations), [&, this] (auto&& m) {
return mutation(_view->schema(), partitioner.decorate_key(*_base, std::move(m.first)), std::move(m.second));
});
}
private:
mutation_partition& partition_for(partition_key&& key) {
auto it = _updates.find(key);
if (it != _updates.end()) {
return it->second;
}
return _updates.emplace(std::move(key), mutation_partition(_view->schema())).first->second;
}
row_marker compute_row_marker(const clustering_row& base_row) const;
deletable_row& get_view_row(const partition_key& base_key, const clustering_row& update);
void create_entry(const partition_key& base_key, const clustering_row& update, gc_clock::time_point now);
};
row_marker view_updates::compute_row_marker(const clustering_row& base_row) const {
/*
* We need to compute both the timestamp and expiration.
*
* For the timestamp, it makes sense to use the bigger timestamp for all view PK columns.
*
* This is more complex for the expiration. We want to maintain consistency between the base and the view, so the
* entry should only exist as long as the base row exists _and_ has non-null values for all the columns that are part
* of the view PK.
* Which means we really have 2 cases:
* 1) There is a column that is not in the base PK but is in the view PK. In that case, as long as that column
* lives, the view entry does too, but as soon as it expires (or is deleted for that matter) the entry also
* should expire. So the expiration for the view is the one of that column, regardless of any other expiration.
* To take an example of that case, if you have:
* CREATE TABLE t (a int, b int, c int, PRIMARY KEY (a, b))
* CREATE MATERIALIZED VIEW mv AS SELECT * FROM t WHERE c IS NOT NULL AND a IS NOT NULL AND b IS NOT NULL PRIMARY KEY (c, a, b)
* INSERT INTO t(a, b) VALUES (0, 0) USING TTL 3;
* UPDATE t SET c = 0 WHERE a = 0 AND b = 0;
* then even after 3 seconds elapsed, the row will still exist (it just won't have a "row marker" anymore) and so
* the MV should still have a corresponding entry.
* 2) The columns for the base and view PKs are exactly the same. In that case, the view entry should live
* as long as the base row lives. This means the view entry should only expire once *everything* in the
* base row has expired. So, the row TTL should be the max of any other TTL. This is particularly important
* in the case where the base row has a TTL, but a column *absent* from the view holds a greater TTL.
*/
auto marker = base_row.marker();
auto* col = _view->base_non_pk_column_in_view_pk();
if (col) {
// Note: multi-cell columns can't be part of the primary key.
auto cell = base_row.cells().cell_at(col->id).as_atomic_cell();
auto timestamp = std::max(marker.timestamp(), cell.timestamp());
return cell.is_live_and_has_ttl() ? row_marker(timestamp, cell.ttl(), cell.expiry()) : row_marker(timestamp);
}
if (!marker.is_expiring()) {
return marker;
}
auto ttl = marker.ttl();
auto expiry = marker.expiry();
auto maybe_update_expiry_and_ttl = [&] (atomic_cell_view&& cell) {
// Note: Cassandra compares cell.ttl() here, but that seems very wrong.
// See CASSANDRA-13127.
if (cell.is_live_and_has_ttl() && cell.expiry() > expiry) {
expiry = cell.expiry();
ttl = cell.ttl();
}
};
base_row.cells().for_each_cell([&] (column_id id, const atomic_cell_or_collection& c) {
auto& def = _base->regular_column_at(id);
if (def.is_atomic()) {
maybe_update_expiry_and_ttl(c.as_atomic_cell());
} else {
static_pointer_cast<const collection_type_impl>(def.type)->for_each_cell(c.as_collection_mutation(), maybe_update_expiry_and_ttl);
}
});
return row_marker(marker.timestamp(), ttl, expiry);
}
deletable_row& view_updates::get_view_row(const partition_key& base_key, const clustering_row& update) {
auto get_value = boost::adaptors::transformed([&, this] (const column_definition& cdef) {
auto* base_col = _base->get_column_definition(cdef.name());
assert(base_col);
switch (base_col->kind) {
case column_kind::partition_key:
return base_key.get_component(*_base, base_col->position());
case column_kind::clustering_key:
return update.key().get_component(*_base, base_col->position());
default:
auto& c = update.cells().cell_at(base_col->id);
if (base_col->is_atomic()) {
return c.as_atomic_cell().value();
}
return c.as_collection_mutation().data;
}
});
auto& view_schema = *_view->schema();
auto& partition = partition_for(partition_key::from_range(view_schema.partition_key_columns() | get_value));
auto ckey = clustering_key::from_range(view_schema.clustering_key_columns() | get_value);
return partition.clustered_row(view_schema, std::move(ckey));
}
static const column_definition* view_column(const schema& base, const schema& view, column_id base_id) {
// FIXME: Map base column_ids to view_column_ids, which can be something like
// a boost::small_vector where the position is the base column_id, and the
// value is either empty or the view's column_id.
return view.get_column_definition(base.regular_column_at(base_id).name());
}
static void add_cells_to_view(const schema& base, const schema& view, const row& base_cells, row& view_cells) {
base_cells.for_each_cell([&] (column_id id, const atomic_cell_or_collection& c) {
auto* view_col = view_column(base, view, id);
if (view_col && !view_col->is_primary_key()) {
view_cells.append_cell(view_col->id, c);
}
});
}
/**
* Creates a view entry corresponding to the provided base row.
* This method checks that the base row does match the view filter before applying anything.
*/
void view_updates::create_entry(const partition_key& base_key, const clustering_row& update, gc_clock::time_point now) {
if (!_view->matches_view_filter(*_base, base_key, update, now)) {
return;
}
deletable_row& r = get_view_row(base_key, update);
r.apply(compute_row_marker(update));
r.apply(update.tomb());
add_cells_to_view(*_base, *_view->schema(), update.cells(), r.cells());
}
} // namespace view
} // namespace db
<commit_msg>view_updates: Delete old view entry<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright (C) 2017 ScyllaDB
*
* Modified by ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/range/algorithm/transform.hpp>
#include <boost/range/adaptors.hpp>
#include "clustering_bounds_comparator.hh"
#include "cql3/statements/select_statement.hh"
#include "cql3/util.hh"
#include "db/view/view.hh"
namespace db {
namespace view {
cql3::statements::select_statement& view::select_statement() const {
if (!_select_statement) {
std::vector<sstring_view> included;
if (!_schema->view_info()->include_all_columns()) {
included.reserve(_schema->all_columns_in_select_order().size());
boost::transform(_schema->all_columns_in_select_order(), std::back_inserter(included), std::mem_fn(&column_definition::name_as_text));
}
auto raw = cql3::util::build_select_statement(_schema->view_info()->base_name(), _schema->view_info()->where_clause(), std::move(included));
raw->prepare_keyspace(_schema->ks_name());
raw->set_bound_variables({});
cql3::cql_stats ignored;
auto prepared = raw->prepare(service::get_local_storage_proxy().get_db().local(), ignored, true);
_select_statement = static_pointer_cast<cql3::statements::select_statement>(prepared->statement);
}
return *_select_statement;
}
const query::partition_slice& view::partition_slice() const {
if (!_partition_slice) {
_partition_slice = select_statement().make_partition_slice(cql3::query_options({ }));
}
return *_partition_slice;
}
const dht::partition_range_vector& view::partition_ranges() const {
if (!_partition_ranges) {
_partition_ranges = select_statement().get_restrictions()->get_partition_key_ranges(cql3::query_options({ }));
}
return *_partition_ranges;
}
bool view::partition_key_matches(const ::schema& base, const dht::decorated_key& key) const {
dht::ring_position rp(key);
auto& ranges = partition_ranges();
return std::any_of(ranges.begin(), ranges.end(), [&] (auto&& range) {
return range.contains(rp, dht::ring_position_comparator(base));
});
}
bool view::clustering_prefix_matches(const ::schema& base, const partition_key& key, const clustering_key_prefix& ck) const {
bound_view::compare less(base);
auto& ranges = partition_slice().row_ranges(base, key);
return std::any_of(ranges.begin(), ranges.end(), [&] (auto&& range) {
auto bounds = bound_view::from_range(range);
return !less(ck, bounds.first) && !less(bounds.second, ck);
});
}
bool view::may_be_affected_by(const ::schema& base, const dht::decorated_key& key, const rows_entry& update) const {
// We can guarantee that the view won't be affected if:
// - the primary key is excluded by the view filter (note that this isn't true of the filter on regular columns:
// even if an update don't match a view condition on a regular column, that update can still invalidate a
// pre-existing entry);
// - the update doesn't modify any of the columns impacting the view (where "impacting" the view means that column
// is neither included in the view, nor used by the view filter).
if (!partition_key_matches(base, key) && !clustering_prefix_matches(base, key.key(), update.key())) {
return false;
}
// We want to check if the update modifies any of the columns that are part of the view (in which case the view is
// affected). But iff the view includes all the base table columns, or the update has either a row deletion or a
// row marker, we know the view is affected right away.
if (_schema->view_info()->include_all_columns() || update.row().deleted_at() || update.row().marker().is_live()) {
return true;
}
bool affected = false;
update.row().cells().for_each_cell_until([&] (column_id id, const atomic_cell_or_collection& cell) {
affected = _schema->get_column_definition(base.column_at(column_kind::regular_column, id).name());
return stop_iteration(affected);
});
return affected;
}
bool view::matches_view_filter(const ::schema& base, const partition_key& key, const clustering_row& update, gc_clock::time_point now) const {
return clustering_prefix_matches(base, key, update.key()) &&
boost::algorithm::all_of(
select_statement().get_restrictions()->get_non_pk_restriction() | boost::adaptors::map_values,
[&] (auto&& r) {
return r->is_satisfied_by(base, key, update.key(), update.cells(), cql3::query_options({ }), now);
});
}
void view::set_base_non_pk_column_in_view_pk(const ::schema& base) {
for (auto&& base_col : base.regular_columns()) {
auto view_col = _schema->get_column_definition(base_col.name());
if (view_col && view_col->is_primary_key()) {
_base_non_pk_column_in_view_pk = view_col;
return;
}
}
_base_non_pk_column_in_view_pk = nullptr;
}
class view_updates final {
lw_shared_ptr<const db::view::view> _view;
schema_ptr _base;
std::unordered_map<partition_key, mutation_partition, partition_key::hashing, partition_key::equality> _updates;
public:
explicit view_updates(lw_shared_ptr<const db::view::view> view, schema_ptr base)
: _view(std::move(view))
, _base(std::move(base))
, _updates(8, partition_key::hashing(*_base), partition_key::equality(*_base)) {
}
void move_to(std::vector<mutation>& mutations) && {
auto& partitioner = dht::global_partitioner();
std::transform(_updates.begin(), _updates.end(), std::back_inserter(mutations), [&, this] (auto&& m) {
return mutation(_view->schema(), partitioner.decorate_key(*_base, std::move(m.first)), std::move(m.second));
});
}
private:
mutation_partition& partition_for(partition_key&& key) {
auto it = _updates.find(key);
if (it != _updates.end()) {
return it->second;
}
return _updates.emplace(std::move(key), mutation_partition(_view->schema())).first->second;
}
row_marker compute_row_marker(const clustering_row& base_row) const;
deletable_row& get_view_row(const partition_key& base_key, const clustering_row& update);
void create_entry(const partition_key& base_key, const clustering_row& update, gc_clock::time_point now);
void delete_old_entry(const partition_key& base_key, const clustering_row& existing, gc_clock::time_point now);
void do_delete_old_entry(const partition_key& base_key, const clustering_row& existing, gc_clock::time_point now);
};
row_marker view_updates::compute_row_marker(const clustering_row& base_row) const {
/*
* We need to compute both the timestamp and expiration.
*
* For the timestamp, it makes sense to use the bigger timestamp for all view PK columns.
*
* This is more complex for the expiration. We want to maintain consistency between the base and the view, so the
* entry should only exist as long as the base row exists _and_ has non-null values for all the columns that are part
* of the view PK.
* Which means we really have 2 cases:
* 1) There is a column that is not in the base PK but is in the view PK. In that case, as long as that column
* lives, the view entry does too, but as soon as it expires (or is deleted for that matter) the entry also
* should expire. So the expiration for the view is the one of that column, regardless of any other expiration.
* To take an example of that case, if you have:
* CREATE TABLE t (a int, b int, c int, PRIMARY KEY (a, b))
* CREATE MATERIALIZED VIEW mv AS SELECT * FROM t WHERE c IS NOT NULL AND a IS NOT NULL AND b IS NOT NULL PRIMARY KEY (c, a, b)
* INSERT INTO t(a, b) VALUES (0, 0) USING TTL 3;
* UPDATE t SET c = 0 WHERE a = 0 AND b = 0;
* then even after 3 seconds elapsed, the row will still exist (it just won't have a "row marker" anymore) and so
* the MV should still have a corresponding entry.
* 2) The columns for the base and view PKs are exactly the same. In that case, the view entry should live
* as long as the base row lives. This means the view entry should only expire once *everything* in the
* base row has expired. So, the row TTL should be the max of any other TTL. This is particularly important
* in the case where the base row has a TTL, but a column *absent* from the view holds a greater TTL.
*/
auto marker = base_row.marker();
auto* col = _view->base_non_pk_column_in_view_pk();
if (col) {
// Note: multi-cell columns can't be part of the primary key.
auto cell = base_row.cells().cell_at(col->id).as_atomic_cell();
auto timestamp = std::max(marker.timestamp(), cell.timestamp());
return cell.is_live_and_has_ttl() ? row_marker(timestamp, cell.ttl(), cell.expiry()) : row_marker(timestamp);
}
if (!marker.is_expiring()) {
return marker;
}
auto ttl = marker.ttl();
auto expiry = marker.expiry();
auto maybe_update_expiry_and_ttl = [&] (atomic_cell_view&& cell) {
// Note: Cassandra compares cell.ttl() here, but that seems very wrong.
// See CASSANDRA-13127.
if (cell.is_live_and_has_ttl() && cell.expiry() > expiry) {
expiry = cell.expiry();
ttl = cell.ttl();
}
};
base_row.cells().for_each_cell([&] (column_id id, const atomic_cell_or_collection& c) {
auto& def = _base->regular_column_at(id);
if (def.is_atomic()) {
maybe_update_expiry_and_ttl(c.as_atomic_cell());
} else {
static_pointer_cast<const collection_type_impl>(def.type)->for_each_cell(c.as_collection_mutation(), maybe_update_expiry_and_ttl);
}
});
return row_marker(marker.timestamp(), ttl, expiry);
}
deletable_row& view_updates::get_view_row(const partition_key& base_key, const clustering_row& update) {
auto get_value = boost::adaptors::transformed([&, this] (const column_definition& cdef) {
auto* base_col = _base->get_column_definition(cdef.name());
assert(base_col);
switch (base_col->kind) {
case column_kind::partition_key:
return base_key.get_component(*_base, base_col->position());
case column_kind::clustering_key:
return update.key().get_component(*_base, base_col->position());
default:
auto& c = update.cells().cell_at(base_col->id);
if (base_col->is_atomic()) {
return c.as_atomic_cell().value();
}
return c.as_collection_mutation().data;
}
});
auto& view_schema = *_view->schema();
auto& partition = partition_for(partition_key::from_range(view_schema.partition_key_columns() | get_value));
auto ckey = clustering_key::from_range(view_schema.clustering_key_columns() | get_value);
return partition.clustered_row(view_schema, std::move(ckey));
}
static const column_definition* view_column(const schema& base, const schema& view, column_id base_id) {
// FIXME: Map base column_ids to view_column_ids, which can be something like
// a boost::small_vector where the position is the base column_id, and the
// value is either empty or the view's column_id.
return view.get_column_definition(base.regular_column_at(base_id).name());
}
static void add_cells_to_view(const schema& base, const schema& view, const row& base_cells, row& view_cells) {
base_cells.for_each_cell([&] (column_id id, const atomic_cell_or_collection& c) {
auto* view_col = view_column(base, view, id);
if (view_col && !view_col->is_primary_key()) {
view_cells.append_cell(view_col->id, c);
}
});
}
/**
* Creates a view entry corresponding to the provided base row.
* This method checks that the base row does match the view filter before applying anything.
*/
void view_updates::create_entry(const partition_key& base_key, const clustering_row& update, gc_clock::time_point now) {
if (!_view->matches_view_filter(*_base, base_key, update, now)) {
return;
}
deletable_row& r = get_view_row(base_key, update);
r.apply(compute_row_marker(update));
r.apply(update.tomb());
add_cells_to_view(*_base, *_view->schema(), update.cells(), r.cells());
}
/**
* Deletes the view entry corresponding to the provided base row.
* This method checks that the base row does match the view filter before bothering.
*/
void view_updates::delete_old_entry(const partition_key& base_key, const clustering_row& existing, gc_clock::time_point now) {
// Before deleting an old entry, make sure it was matching the view filter
// (otherwise there is nothing to delete)
if (_view->matches_view_filter(*_base, base_key, existing, now)) {
do_delete_old_entry(base_key, existing, now);
}
}
void view_updates::do_delete_old_entry(const partition_key& base_key, const clustering_row& existing, gc_clock::time_point now) {
// We delete the old row using a shadowable row tombstone, making sure that
// the tombstone deletes everything in the row (or it might still show up).
// FIXME: If the entry is "resurrected" by a later update, we would need to
// ensure that the timestamp for the entry then is bigger than the tombstone
// we're just inserting, which is not currently guaranteed. See CASSANDRA-11500
// for details.
auto& view_schema = *_view->schema();
auto ts = existing.marker().timestamp();
auto set_max_ts = [&ts] (atomic_cell_view&& cell) {
ts = std::max(ts, cell.timestamp());
};
existing.cells().for_each_cell([&, this] (column_id id, const atomic_cell_or_collection& cell) {
auto* def = view_column(*_base, view_schema, id);
if (!def) {
return;
}
if (def->is_atomic()) {
set_max_ts(cell.as_atomic_cell());
} else {
static_pointer_cast<const collection_type_impl>(def->type)->for_each_cell(cell.as_collection_mutation(), set_max_ts);
}
});
get_view_row(base_key, existing).apply(tombstone(ts, now));
}
} // namespace view
} // namespace db
<|endoftext|>
|
<commit_before>#include "robot_diagrams_0.0.hpp"
#include <iostream>
#include <fstream>
#include <iterator>
#include <string>
#include <vector>
#include <cstdlib>
std::vector<std::string> split(std::string s)
{
std::stringstream ss(s);
std::istream_iterator<std::string> begin(ss);
std::istream_iterator<std::string> end;
std::vector<std::string> vstrings(begin, end);
return vstrings;
}
// TODO: delete copy constructor of robot!
bool add_element(rob_diag::Robot& robot, std::string line)
{
// TODO: do float parsing better...std::stof is only C++11...std::strtod sucks for error conditions.
try
{
std::vector<std::string> words = split(line);
if (words.size() == 0)
{
std::cerr << "No arguments on line!" << std::endl;
return false;
}
if (words[0] == "base" || words[0] == "invisible_base")
{
if (words.size() == 1)
{
rob_diag::RobotElement* base = (rob_diag::RobotElement*)new rob_diag::Base();
if (words[0] == "invisible_base")
((rob_diag::Base*)base)->visible_ = false;
robot.elements_.push_back(base);
return true;
}
else if (words.size() == 2)
{
double width = std::strtod (words[1].c_str(), NULL);
rob_diag::RobotElement* base = (rob_diag::RobotElement*)new rob_diag::Base(width);
if (words[0] == "invisible_base")
((rob_diag::Base*)base)->visible_ = false;
robot.elements_.push_back(base);
return true;
}
std::cerr << "Invalid arguments for " << words[0] << std::endl;
return false;
}
else if (words[0] == "link" || words[0] == "vector") // TODO: remove me! hack to workaround gmail blocking an attachment!
{
if (words.size() == 2)
{
double length = std::strtod (words[1].c_str(), NULL);
rob_diag::RobotElement* link = (rob_diag::RobotElement*)new rob_diag::Link(length);
robot.elements_.push_back(link);
return true;
}
else if (words.size() == 3)
{
double length = std::strtod (words[1].c_str(), NULL);
rob_diag::RobotElement* link = (rob_diag::RobotElement*)new rob_diag::Link(length, words[2]);
robot.elements_.push_back(link);
return true;
}
std::cerr << "Invalid arguments for " << words[0] << std::endl;
return false;
}
else if (words[0] == "invisible_link")
{
if (words.size() == 2)
{
double length = std::strtod (words[1].c_str(), NULL);
rob_diag::Link* tmp = new rob_diag::Link(length);
tmp->visible_ = false;
rob_diag::RobotElement* link = (rob_diag::RobotElement*)tmp;
robot.elements_.push_back(link);
return true;
}
std::cerr << "Invalid arguments for " << words[0] << std::endl;
return false;
}
else if (words[0] == "frames")
{
if (words.size() == 1)
{
rob_diag::RobotElement* link = (rob_diag::RobotElement*)new rob_diag::Frames();
robot.elements_.push_back(link);
return true;
}
std::cerr << "Invalid (or not yet supported) arguments for " << words[0] << std::endl;
return false;
}
else if (words[0] == "point") // NOTE: this is a hack to work around missed gmail attachment!
{
if (words.size() == 1 || words.size() == 2)
{
rob_diag::RobotElement* rjoint = (rob_diag::RobotElement*)new rob_diag::RJoint(0);
robot.elements_.push_back(rjoint);
return true;
}
std::cerr << "Invalid arguments for " << words[0] << std::endl;
return false;
}
else if (words[0] == "rjoint" || words[0] == "invisible_rjoint")
{
if (words.size() == 2)
{
double theta = std::strtod (words[1].c_str(), NULL);
rob_diag::RobotElement* rjoint = (rob_diag::RobotElement*)new rob_diag::RJoint(theta);
if (words[0] == "invisible_rjoint")
((rob_diag::RJoint*)rjoint)->visible_ = false;
robot.elements_.push_back(rjoint);
return true;
}
std::cerr << "Invalid arguments for " << words[0] << std::endl;
return false;
}
else if (words[0] == "pjoint")
{
if (words.size() == 1)
{
rob_diag::RobotElement* pjoint = (rob_diag::RobotElement*)new rob_diag::PJoint();
robot.elements_.push_back(pjoint);
return true;
}
std::cerr << "Invalid arguments for " << words[0] << std::endl;
return false;
}
else if (words[0] == "effector")
{
if (words.size() == 1)
{
rob_diag::RobotElement* ee = (rob_diag::RobotElement*)new rob_diag::EndEffector();
robot.elements_.push_back(ee);
return true;
}
std::cerr << "Invalid (or not yet supported) arguments for " << words[0] << std::endl;
return false;
}
else if (words[0] == "vector")
{
if (words.size() == 2)
{
double length = std::strtod (words[1].c_str(), NULL);
rob_diag::RobotElement* vec = (rob_diag::RobotElement*)new rob_diag::Vector(length);
robot.elements_.push_back(vec);
return true;
}
else if (words.size() == 3)
{
double length = std::strtod (words[1].c_str(), NULL);
rob_diag::RobotElement* vec = (rob_diag::RobotElement*)new rob_diag::Vector(length, words[2]);
robot.elements_.push_back(vec);
return true;
}
std::cerr << "Invalid arguments for " << words[0] << std::endl;
return false;
}
else if (words[0] == "point")
{
if (words.size() == 1)
{
rob_diag::RobotElement* pt = (rob_diag::RobotElement*)new rob_diag::RobPoint();
robot.elements_.push_back(pt);
return true;
}
else if (words.size() == 2)
{
rob_diag::RobotElement* pt = (rob_diag::RobotElement*)new rob_diag::RobPoint(2, words[1]);
robot.elements_.push_back(pt);
return true;
}
std::cerr << "Invalid arguments for " << words[0] << std::endl;
return false;
}
else
{
std::cerr << words[0] << " not recognized!" << std::endl;
return false;
}
}
catch (...)
{
return false;
}
return false;
}
void draw_robot(rob_diag::Robot& robot, std::string filename)
{
// Compute dimensions
rob_diag::Rect bounds = robot.compute_dimensions();
double width = bounds.right_ - bounds.left_;
double height = bounds.top_ - bounds.bottom_;
double margin = 10;
svg::Dimensions dimensions(width + margin * 2.0, height + margin * 2.0);
// Draw to file:
Document doc(filename, svg::Layout(dimensions, svg::Layout::BottomLeft));
rob_diag::Pose origin(-bounds.left_ + margin, -bounds.bottom_ + margin, 0);
robot.draw_at(doc, origin);
// Save and quit
doc.save();
}
void delete_robot(rob_diag::Robot& robot)
{
// TODO: move to a destructor? Don't store pointers?
for (int i = 0; i < robot.elements_.size(); ++i)
delete robot.elements_[i];
robot.elements_.clear();
// TODO! NOTE: ensure this is called on any failure, even after a bad 'add element'
}
bool draw_robot(const char* filename)
{
std::string file_string(filename);
if (file_string.size() < 6 || file_string.substr(file_string.size() - 6, 6) != ".robot")
{
std::cerr << filename << " is not a valid .robot filename." << std::endl;
return false;
}
std::string file_base = file_string.substr(0, file_string.size() - 6);
std::string file_ext = file_string.substr(0, file_string.size() - 6);
std::string line;
std::ifstream robot_config (filename);
if (robot_config.is_open())
{
rob_diag::Robot robot;
while ( getline (robot_config,line) )
{
if (!add_element(robot, line))
{
std::cerr << "Bad configuration line for " << filename << ":" << std::endl << line << std::endl;
robot_config.close();
delete_robot(robot);
return false;
}
}
robot_config.close();
draw_robot(robot, file_base + ".svg");
delete_robot(robot);
return true;
}
else
{
std::cout << "Unable to open " << filename << std::endl;
return false;
}
std::cout << "Unknown error with " << filename << std::endl;
return false;
}
int main(int argc, char** argv)
{
if (argc < 2)
{
std::cout << "Usage: ./generate_robots <list of .robot files>" << std::endl;
return -1;
}
int num_good = 0;
std::cout << "Converting files..." << std::endl;
for (int i = 1; i < argc; i++)
{
if (draw_robot(argv[i]))
{
++num_good;
std::cout << argv[i] << ": success" << std::endl;
}
// NOTE: error from failure will be displayed in the 'draw_robot' function.
}
std::cout << "Converted " << num_good << "/" << argc - 1 << " files." << std::endl;
return 0;
}
<commit_msg>Removed unnecessary changes to generate robots.<commit_after>#include "robot_diagrams_0.0.hpp"
#include <iostream>
#include <fstream>
#include <iterator>
#include <string>
#include <vector>
#include <cstdlib>
std::vector<std::string> split(std::string s)
{
std::stringstream ss(s);
std::istream_iterator<std::string> begin(ss);
std::istream_iterator<std::string> end;
std::vector<std::string> vstrings(begin, end);
return vstrings;
}
// TODO: delete copy constructor of robot!
bool add_element(rob_diag::Robot& robot, std::string line)
{
// TODO: do float parsing better...std::stof is only C++11...std::strtod sucks for error conditions.
try
{
std::vector<std::string> words = split(line);
if (words.size() == 0)
{
std::cerr << "No arguments on line!" << std::endl;
return false;
}
if (words[0] == "base" || words[0] == "invisible_base")
{
if (words.size() == 1)
{
rob_diag::RobotElement* base = (rob_diag::RobotElement*)new rob_diag::Base();
if (words[0] == "invisible_base")
((rob_diag::Base*)base)->visible_ = false;
robot.elements_.push_back(base);
return true;
}
else if (words.size() == 2)
{
double width = std::strtod (words[1].c_str(), NULL);
rob_diag::RobotElement* base = (rob_diag::RobotElement*)new rob_diag::Base(width);
if (words[0] == "invisible_base")
((rob_diag::Base*)base)->visible_ = false;
robot.elements_.push_back(base);
return true;
}
std::cerr << "Invalid arguments for " << words[0] << std::endl;
return false;
}
else if (words[0] == "link")
{
if (words.size() == 2)
{
double length = std::strtod (words[1].c_str(), NULL);
rob_diag::RobotElement* link = (rob_diag::RobotElement*)new rob_diag::Link(length);
robot.elements_.push_back(link);
return true;
}
else if (words.size() == 3)
{
double length = std::strtod (words[1].c_str(), NULL);
rob_diag::RobotElement* link = (rob_diag::RobotElement*)new rob_diag::Link(length, words[2]);
robot.elements_.push_back(link);
return true;
}
std::cerr << "Invalid arguments for " << words[0] << std::endl;
return false;
}
else if (words[0] == "invisible_link")
{
if (words.size() == 2)
{
double length = std::strtod (words[1].c_str(), NULL);
rob_diag::Link* tmp = new rob_diag::Link(length);
tmp->visible_ = false;
rob_diag::RobotElement* link = (rob_diag::RobotElement*)tmp;
robot.elements_.push_back(link);
return true;
}
std::cerr << "Invalid arguments for " << words[0] << std::endl;
return false;
}
else if (words[0] == "frames")
{
if (words.size() == 1)
{
rob_diag::RobotElement* link = (rob_diag::RobotElement*)new rob_diag::Frames();
robot.elements_.push_back(link);
return true;
}
std::cerr << "Invalid (or not yet supported) arguments for " << words[0] << std::endl;
return false;
}
else if (words[0] == "rjoint" || words[0] == "invisible_rjoint")
{
if (words.size() == 2)
{
double theta = std::strtod (words[1].c_str(), NULL);
rob_diag::RobotElement* rjoint = (rob_diag::RobotElement*)new rob_diag::RJoint(theta);
if (words[0] == "invisible_rjoint")
((rob_diag::RJoint*)rjoint)->visible_ = false;
robot.elements_.push_back(rjoint);
return true;
}
std::cerr << "Invalid arguments for " << words[0] << std::endl;
return false;
}
else if (words[0] == "pjoint")
{
if (words.size() == 1)
{
rob_diag::RobotElement* pjoint = (rob_diag::RobotElement*)new rob_diag::PJoint();
robot.elements_.push_back(pjoint);
return true;
}
std::cerr << "Invalid arguments for " << words[0] << std::endl;
return false;
}
else if (words[0] == "effector")
{
if (words.size() == 1)
{
rob_diag::RobotElement* ee = (rob_diag::RobotElement*)new rob_diag::EndEffector();
robot.elements_.push_back(ee);
return true;
}
std::cerr << "Invalid (or not yet supported) arguments for " << words[0] << std::endl;
return false;
}
else if (words[0] == "vector")
{
if (words.size() == 2)
{
double length = std::strtod (words[1].c_str(), NULL);
rob_diag::RobotElement* vec = (rob_diag::RobotElement*)new rob_diag::Vector(length);
robot.elements_.push_back(vec);
return true;
}
else if (words.size() == 3)
{
double length = std::strtod (words[1].c_str(), NULL);
rob_diag::RobotElement* vec = (rob_diag::RobotElement*)new rob_diag::Vector(length, words[2]);
robot.elements_.push_back(vec);
return true;
}
std::cerr << "Invalid arguments for " << words[0] << std::endl;
return false;
}
else if (words[0] == "point")
{
if (words.size() == 1)
{
rob_diag::RobotElement* pt = (rob_diag::RobotElement*)new rob_diag::RobPoint();
robot.elements_.push_back(pt);
return true;
}
else if (words.size() == 2)
{
rob_diag::RobotElement* pt = (rob_diag::RobotElement*)new rob_diag::RobPoint(2, words[1]);
robot.elements_.push_back(pt);
return true;
}
std::cerr << "Invalid arguments for " << words[0] << std::endl;
return false;
}
else
{
std::cerr << words[0] << " not recognized!" << std::endl;
return false;
}
}
catch (...)
{
return false;
}
return false;
}
void draw_robot(rob_diag::Robot& robot, std::string filename)
{
// Compute dimensions
rob_diag::Rect bounds = robot.compute_dimensions();
double width = bounds.right_ - bounds.left_;
double height = bounds.top_ - bounds.bottom_;
double margin = 10;
svg::Dimensions dimensions(width + margin * 2.0, height + margin * 2.0);
// Draw to file:
Document doc(filename, svg::Layout(dimensions, svg::Layout::BottomLeft));
rob_diag::Pose origin(-bounds.left_ + margin, -bounds.bottom_ + margin, 0);
robot.draw_at(doc, origin);
// Save and quit
doc.save();
}
void delete_robot(rob_diag::Robot& robot)
{
// TODO: move to a destructor? Don't store pointers?
for (int i = 0; i < robot.elements_.size(); ++i)
delete robot.elements_[i];
robot.elements_.clear();
// TODO! NOTE: ensure this is called on any failure, even after a bad 'add element'
}
bool draw_robot(const char* filename)
{
std::string file_string(filename);
if (file_string.size() < 6 || file_string.substr(file_string.size() - 6, 6) != ".robot")
{
std::cerr << filename << " is not a valid .robot filename." << std::endl;
return false;
}
std::string file_base = file_string.substr(0, file_string.size() - 6);
std::string file_ext = file_string.substr(0, file_string.size() - 6);
std::string line;
std::ifstream robot_config (filename);
if (robot_config.is_open())
{
rob_diag::Robot robot;
while ( getline (robot_config,line) )
{
if (!add_element(robot, line))
{
std::cerr << "Bad configuration line for " << filename << ":" << std::endl << line << std::endl;
robot_config.close();
delete_robot(robot);
return false;
}
}
robot_config.close();
draw_robot(robot, file_base + ".svg");
delete_robot(robot);
return true;
}
else
{
std::cout << "Unable to open " << filename << std::endl;
return false;
}
std::cout << "Unknown error with " << filename << std::endl;
return false;
}
int main(int argc, char** argv)
{
if (argc < 2)
{
std::cout << "Usage: ./generate_robots <list of .robot files>" << std::endl;
return -1;
}
int num_good = 0;
std::cout << "Converting files..." << std::endl;
for (int i = 1; i < argc; i++)
{
if (draw_robot(argv[i]))
{
++num_good;
std::cout << argv[i] << ": success" << std::endl;
}
// NOTE: error from failure will be displayed in the 'draw_robot' function.
}
std::cout << "Converted " << num_good << "/" << argc - 1 << " files." << std::endl;
return 0;
}
<|endoftext|>
|
<commit_before>#include "mocca/base/CommandLineParser.h"
#include "mocca/base/Containers.h"
#include "mocca/base/Error.h"
#include "mocca/base/StringTools.h"
#include <iostream>
#include <sstream>
using namespace mocca;
CommandLineParser::CommandLineParser() {
Option usage;
usage.key = "--usage";
usage.help = "prints usage";
usage.callback = std::bind(&CommandLineParser::printUsage, this, std::placeholders::_1);
options_.push_back(usage);
}
void CommandLineParser::addOption(const Option& option) {
options_.push_back(option);
}
void mocca::CommandLineParser::printUsage(const std::string&) const {
std::stringstream stream;
for (const auto& opt : options_) {
stream << opt.key << ": " << opt.help << std::endl;
if (!opt.allowedValues.empty()) {
for (const auto& val : opt.allowedValues) {
stream << "\t" << val.value << ": " << val.help << std::endl;
}
}
}
std::cout << stream.str();
std::exit(0);
}
void CommandLineParser::parse(int argc, const char** argv) {
for (int i = 1; i < argc; ++i) { // skip first arg because it contains the program name
auto arg = std::string(argv[i]);
auto separatorIndex = arg.find_first_of("=");
auto argKey = arg.substr(0, separatorIndex);
if (findMemberEqual(options_, &Option::key, argKey) == end(options_)) {
throw Error(formatString("Unknown option '%%'", argKey), __FILE__, __LINE__);
}
std::string argValue;
if (separatorIndex != std::string::npos) {
argValue = arg.substr(separatorIndex + 1, std::string::npos);
}
for (const auto& opt : options_) {
if (opt.key == argKey) {
if (!opt.allowedValues.empty()) {
if (findMemberEqual(opt.allowedValues, &OptionValue::value, argValue) == end(opt.allowedValues)) {
auto allowedValues = collectMembers(begin(opt.allowedValues), end(opt.allowedValues), &OptionValue::value);
auto allowedValuesStr = makeString(begin(allowedValues), end(allowedValues));
throw Error(
formatString("Invalid value '%%' for option '%%'. Allowed values are: %%", argValue, opt.key, allowedValuesStr),
__FILE__, __LINE__);
}
}
opt.callback(argValue);
break;
}
}
}
}<commit_msg>nicer format for usage text in CommandLineParser<commit_after>#include "mocca/base/CommandLineParser.h"
#include "mocca/base/Containers.h"
#include "mocca/base/Error.h"
#include "mocca/base/StringTools.h"
#include <iostream>
#include <sstream>
using namespace mocca;
CommandLineParser::CommandLineParser() {
Option usage;
usage.key = "--usage";
usage.help = "prints usage";
usage.callback = std::bind(&CommandLineParser::printUsage, this, std::placeholders::_1);
options_.push_back(usage);
}
void CommandLineParser::addOption(const Option& option) {
options_.push_back(option);
}
void mocca::CommandLineParser::printUsage(const std::string&) const {
std::stringstream stream;
for (const auto& opt : options_) {
stream << opt.key << ": " << opt.help << std::endl;
if (!opt.allowedValues.empty()) {
for (const auto& val : opt.allowedValues) {
stream << "\t" << val.value << ": " << val.help << std::endl;
}
}
stream << std::endl;
}
std::cout << stream.str();
std::exit(0);
}
void CommandLineParser::parse(int argc, const char** argv) {
for (int i = 1; i < argc; ++i) { // skip first arg because it contains the program name
auto arg = std::string(argv[i]);
auto separatorIndex = arg.find_first_of("=");
auto argKey = arg.substr(0, separatorIndex);
if (findMemberEqual(options_, &Option::key, argKey) == end(options_)) {
throw Error(formatString("Unknown option '%%'", argKey), __FILE__, __LINE__);
}
std::string argValue;
if (separatorIndex != std::string::npos) {
argValue = arg.substr(separatorIndex + 1, std::string::npos);
}
for (const auto& opt : options_) {
if (opt.key == argKey) {
if (!opt.allowedValues.empty()) {
if (findMemberEqual(opt.allowedValues, &OptionValue::value, argValue) == end(opt.allowedValues)) {
auto allowedValues = collectMembers(begin(opt.allowedValues), end(opt.allowedValues), &OptionValue::value);
auto allowedValuesStr = makeString(begin(allowedValues), end(allowedValues));
throw Error(
formatString("Invalid value '%%' for option '%%'. Allowed values are: %%", argValue, opt.key, allowedValuesStr),
__FILE__, __LINE__);
}
}
opt.callback(argValue);
break;
}
}
}
}<|endoftext|>
|
<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2012-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
/// Render Tests for the OsgCapsuleRepresentation class.
#include <SurgSim/Graphics/OsgManager.h>
#include <SurgSim/Graphics/OsgCapsuleRepresentation.h>
#include <SurgSim/Graphics/OsgViewElement.h>
#include <SurgSim/Framework/Scene.h>
#include <SurgSim/Framework/SceneElement.h>
#include <SurgSim/Framework/Runtime.h>
#include <SurgSim/Math/Vector.h>
#include <SurgSim/Testing/MathUtilities.h>
#include <gtest/gtest.h>
using SurgSim::Framework::Runtime;
using SurgSim::Framework::Scene;
using SurgSim::Framework::SceneElement;
using SurgSim::Math::RigidTransform3d;
using SurgSim::Math::Vector2d;
using SurgSim::Math::Vector3d;
using SurgSim::Math::makeRigidTransform;
using SurgSim::Math::makeRotationQuaternion;
using SurgSim::Testing::interpolate;
namespace SurgSim
{
namespace Graphics
{
TEST(OsgCapsuleRepresentationRenderTests, MovingCapsuleTest)
{
/// Initial positoin of capsule 1
Vector3d startPosition1(-0.1, 0.0, -0.2);
/// Final position of capsule 1
Vector3d endPosition1(0.1, 0.0, -0.2);
/// Initial size (radius, hegiht) of capsule 1
Vector2d startSize1(0.001, 0.011);
/// Final size (radius, hegiht) of capsule 1
Vector2d endSize1(0.01, 0.02);
/// Initial angles (X, Y, Z) of the capsule 1
Vector3d startAngles1(0.0, 0.0, 0.0);
/// Final angles (X, Y, Z) of the capsule 1
Vector3d endAngles1(-M_PI / 4.0, -M_PI / 4.0, -M_PI / 4.0);
/// Initial position capsule 2
Vector3d startPosition2(0.0, -0.1, -0.2);
/// Final position capsule 2
Vector3d endPosition2(0.0, 0.1, -0.2);
/// Initial size (radius, hegiht) of capsule 2
Vector2d startSize2(0.001, 0.01);
/// Final size (radius, hegiht) of capsule 2
Vector2d endSize2(0.011, 0.02);
/// Initial angles (X, Y, Z) of the capsule 2
Vector3d startAngles2(-M_PI / 2.0, -M_PI / 2.0, -M_PI / 2.0);
/// Final angles (X, Y, Z) of the capsule 2
Vector3d endAngles2(M_PI, M_PI, M_PI);
/// Number of times to step the capsule position and radius from start to end.
/// This number of steps will be done in 1 second.
int numSteps = 100;
std::shared_ptr<Runtime> runtime = std::make_shared<Runtime>();
std::shared_ptr<OsgManager> manager = std::make_shared<OsgManager>();
runtime->addManager(manager);
std::shared_ptr<Scene> scene = std::make_shared<Scene>();
runtime->setScene(scene);
/// Add a graphics view element to the scene
std::shared_ptr<OsgViewElement> viewElement = std::make_shared<OsgViewElement>("view element");
scene->addSceneElement(viewElement);
/// Add the two capsule representation to the view element so we don't need to make another concrete scene element
std::shared_ptr<CapsuleRepresentation> capsuleRepresentation1 =
std::make_shared<OsgCapsuleRepresentation>("capsule representation 1");
viewElement->addComponent(capsuleRepresentation1);
std::shared_ptr<CapsuleRepresentation> capsuleRepresentation2 =
std::make_shared<OsgCapsuleRepresentation>("capsule representation 2");
viewElement->addComponent(capsuleRepresentation2);
/// Run the thread
runtime->start();
EXPECT_TRUE(manager->isInitialized());
boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
enum SetterType {SetterTypeIndividual,
SetterTypeTogether,
SetterTypeVector2d,
// Add more setter types above this line.
BoxSetterTypeCount};
int setterType = 0;
Vector2d capsule1Size, capsule2Size;
for (int i = 0; i < numSteps; ++i)
{
/// Calculate t in [0.0, 1.0]
double t = static_cast<double>(i) / numSteps;
/// Interpolate position and angle
capsuleRepresentation1->setPose(makeRigidTransform(
makeRotationQuaternion(interpolate(startAngles1.x(), endAngles1.x(), t), Vector3d(1.0, 0.0, 0.0)) *
makeRotationQuaternion(interpolate(startAngles1.y(), endAngles1.y(), t), Vector3d(0.0, 1.0, 0.0)) *
makeRotationQuaternion(interpolate(startAngles1.z(), endAngles1.z(), t), Vector3d(0.0, 0.0, 1.0)),
interpolate(startPosition1, endPosition1, t)));
capsuleRepresentation2->setPose(makeRigidTransform(
makeRotationQuaternion(interpolate(startAngles2.x(), endAngles2.x(), t), Vector3d(1.0, 0.0, 0.0)) *
makeRotationQuaternion(interpolate(startAngles2.y(), endAngles2.y(), t), Vector3d(0.0, 1.0, 0.0)) *
makeRotationQuaternion(interpolate(startAngles2.z(), endAngles2.z(), t), Vector3d(0.0, 0.0, 1.0)),
interpolate(startPosition2, endPosition2, t)));
/// Test different ways to set the size of capsule
if(setterType == static_cast<int>(SetterTypeIndividual))
{
capsuleRepresentation1->setRadius(interpolate(startSize1.x(), endSize1.x(), t));
capsuleRepresentation1->setHeight(interpolate(startSize1.y(), endSize1.y(), t));
capsuleRepresentation2->setRadius(interpolate(startSize2.x(), endSize2.x(), t));
capsuleRepresentation2->setHeight(interpolate(startSize2.y(), endSize2.y(), t));
}
else if(setterType == static_cast<int>(SetterTypeTogether))
{
capsuleRepresentation1->setSize(interpolate(startSize1.x(), endSize1.x(), t),
interpolate(startSize1.y(), endSize1.y(), t));
capsuleRepresentation2->setSize(interpolate(startSize2.x(), endSize2.x(), t),
interpolate(startSize2.y(), endSize2.y(), t));
}
else if(setterType == static_cast<int>(SetterTypeVector2d))
{
capsule1Size.x() = interpolate(startSize1.x(), endSize1.x(), t);
capsule1Size.y() = interpolate(startSize1.y(), endSize1.y(), t);
capsuleRepresentation1->setSize(capsule1Size);
capsule2Size.x() = interpolate(startSize2.x(), endSize2.x(), t);
capsule2Size.y() = interpolate(startSize2.y(), endSize2.y(), t);
capsuleRepresentation2->setSize(capsule2Size);
}
setterType = (setterType + 1) % BoxSetterTypeCount;
/// The total number of steps should complete in 1 second
boost::this_thread::sleep(boost::posix_time::milliseconds(1000 / numSteps));
}
runtime->stop();
}
}; // namespace Graphics
}; // namespace SurgSim<commit_msg>Added a test fixture to OsgCapsuleRepresentationRenderTests.<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2012-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
/// Render Tests for the OsgCapsuleRepresentation class.
#include <SurgSim/Graphics/OsgManager.h>
#include <SurgSim/Graphics/OsgCapsuleRepresentation.h>
#include <SurgSim/Graphics/OsgViewElement.h>
#include <SurgSim/Framework/Scene.h>
#include <SurgSim/Framework/SceneElement.h>
#include <SurgSim/Framework/Runtime.h>
#include <SurgSim/Math/Vector.h>
#include <SurgSim/Testing/MathUtilities.h>
#include <gtest/gtest.h>
using SurgSim::Framework::Runtime;
using SurgSim::Framework::Scene;
using SurgSim::Framework::SceneElement;
using SurgSim::Math::RigidTransform3d;
using SurgSim::Math::Vector2d;
using SurgSim::Math::Vector3d;
using SurgSim::Math::makeRigidTransform;
using SurgSim::Math::makeRotationQuaternion;
using SurgSim::Testing::interpolate;
namespace SurgSim
{
namespace Graphics
{
struct OsgCapsuleRepresentationRenderTests : public ::testing::Test
{
virtual void SetUp()
{
runtime = std::make_shared<SurgSim::Framework::Runtime>();
manager = std::make_shared<SurgSim::Graphics::OsgManager>();
runtime->addManager(manager);
scene = std::make_shared<SurgSim::Framework::Scene>();
runtime->setScene(scene);
viewElement = std::make_shared<OsgViewElement>("view element");
scene->addSceneElement(viewElement);
}
virtual void TearDown()
{
runtime->stop();
}
std::shared_ptr<SurgSim::Framework::Runtime> runtime;
std::shared_ptr<SurgSim::Graphics::OsgManager> manager;
std::shared_ptr<SurgSim::Framework::Scene> scene;
std::shared_ptr<OsgViewElement> viewElement;
protected:
};
TEST_F(OsgCapsuleRepresentationRenderTests, MovingCapsuleTest)
{
/// Add the two capsule representation to the view element
std::shared_ptr<CapsuleRepresentation> capsuleRepresentation1 =
std::make_shared<OsgCapsuleRepresentation>("capsule representation 1");
viewElement->addComponent(capsuleRepresentation1);
std::shared_ptr<CapsuleRepresentation> capsuleRepresentation2 =
std::make_shared<OsgCapsuleRepresentation>("capsule representation 2");
viewElement->addComponent(capsuleRepresentation2);
/// Run the thread
runtime->start();
EXPECT_TRUE(manager->isInitialized());
boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
enum SetterType {SetterTypeIndividual,
SetterTypeTogether,
SetterTypeVector2d,
// Add more setter types above this line.
BoxSetterTypeCount};
int setterType = 0;
Vector2d capsule1Size, capsule2Size;
/// Initial positoin of capsule 1
Vector3d startPosition1(-0.1, 0.0, -0.2);
/// Final position of capsule 1
Vector3d endPosition1(0.1, 0.0, -0.2);
/// Initial size (radius, hegiht) of capsule 1
Vector2d startSize1(0.001, 0.011);
/// Final size (radius, hegiht) of capsule 1
Vector2d endSize1(0.01, 0.02);
/// Initial angles (X, Y, Z) of the capsule 1
Vector3d startAngles1(0.0, 0.0, 0.0);
/// Final angles (X, Y, Z) of the capsule 1
Vector3d endAngles1(-M_PI_4, -M_PI_4, -M_PI_4);
/// Initial position capsule 2
Vector3d startPosition2(0.0, -0.1, -0.2);
/// Final position capsule 2
Vector3d endPosition2(0.0, 0.1, -0.2);
/// Initial size (radius, hegiht) of capsule 2
Vector2d startSize2(0.001, 0.01);
/// Final size (radius, hegiht) of capsule 2
Vector2d endSize2(0.011, 0.02);
/// Initial angles (X, Y, Z) of the capsule 2
Vector3d startAngles2(-M_PI_2, -M_PI_2, -M_PI_2);
/// Final angles (X, Y, Z) of the capsule 2
Vector3d endAngles2(M_PI, M_PI, M_PI);
/// Number of times to step the capsule position and radius from start to end.
/// This number of steps will be done in 1 second.
int numSteps = 100;
for (int i = 0; i < numSteps; ++i)
{
/// Calculate t in [0.0, 1.0]
double t = static_cast<double>(i) / numSteps;
/// Interpolate position and angle
capsuleRepresentation1->setPose(makeRigidTransform(
makeRotationQuaternion(interpolate(startAngles1.x(), endAngles1.x(), t), Vector3d(1.0, 0.0, 0.0)) *
makeRotationQuaternion(interpolate(startAngles1.y(), endAngles1.y(), t), Vector3d(0.0, 1.0, 0.0)) *
makeRotationQuaternion(interpolate(startAngles1.z(), endAngles1.z(), t), Vector3d(0.0, 0.0, 1.0)),
interpolate(startPosition1, endPosition1, t)));
capsuleRepresentation2->setPose(makeRigidTransform(
makeRotationQuaternion(interpolate(startAngles2.x(), endAngles2.x(), t), Vector3d(1.0, 0.0, 0.0)) *
makeRotationQuaternion(interpolate(startAngles2.y(), endAngles2.y(), t), Vector3d(0.0, 1.0, 0.0)) *
makeRotationQuaternion(interpolate(startAngles2.z(), endAngles2.z(), t), Vector3d(0.0, 0.0, 1.0)),
interpolate(startPosition2, endPosition2, t)));
/// Test different ways to set the size of capsule
if(setterType == static_cast<int>(SetterTypeIndividual))
{
capsuleRepresentation1->setRadius(interpolate(startSize1.x(), endSize1.x(), t));
capsuleRepresentation1->setHeight(interpolate(startSize1.y(), endSize1.y(), t));
capsuleRepresentation2->setRadius(interpolate(startSize2.x(), endSize2.x(), t));
capsuleRepresentation2->setHeight(interpolate(startSize2.y(), endSize2.y(), t));
}
else if(setterType == static_cast<int>(SetterTypeTogether))
{
capsuleRepresentation1->setSize(interpolate(startSize1.x(), endSize1.x(), t),
interpolate(startSize1.y(), endSize1.y(), t));
capsuleRepresentation2->setSize(interpolate(startSize2.x(), endSize2.x(), t),
interpolate(startSize2.y(), endSize2.y(), t));
}
else if(setterType == static_cast<int>(SetterTypeVector2d))
{
capsule1Size.x() = interpolate(startSize1.x(), endSize1.x(), t);
capsule1Size.y() = interpolate(startSize1.y(), endSize1.y(), t);
capsuleRepresentation1->setSize(capsule1Size);
capsule2Size.x() = interpolate(startSize2.x(), endSize2.x(), t);
capsule2Size.y() = interpolate(startSize2.y(), endSize2.y(), t);
capsuleRepresentation2->setSize(capsule2Size);
}
setterType = (setterType + 1) % BoxSetterTypeCount;
/// The total number of steps should complete in 1 second
boost::this_thread::sleep(boost::posix_time::milliseconds(1000 / numSteps));
}
}
}; // namespace Graphics
}; // namespace SurgSim<|endoftext|>
|
<commit_before>/******************************************************************************\
* File: header.cpp
* Purpose: Implementation of wxExHeader class
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/extension/header.h>
#include <wx/extension/configdialog.h>
#include <wx/extension/file.h>
#include <wx/extension/util.h>
wxExHeader::wxExHeader(wxExConfig* config)
: m_Config(config)
{
}
const wxString wxExHeader::Get(const wxExFileName* filename) const
{
const wxString h_name = "Name: ";
const wxString h_purpose = "Purpose: ";
const wxString h_author = "Author: ";
const wxString h_created = "Created: ";
const wxString h_rcs = "RCS-ID: $";
const wxString h_copyright = "Copyright: ";
const wxString h_license = "License: ";
const wxString author = m_Config->Get(_("Author"));
const wxString company = m_Config->Get(_("Company"));
const wxString license = m_Config->Get(_("License"));
const wxString email = m_Config->Get(_("Email"));
const wxString purpose = m_Config->Get(_("Purpose"));
const wxString email_field = (!email.empty() ? " < " + email + ">": email);
wxString header;
const wxExLexer l = filename->GetLexer();
if (!l.GetCommentEnd().empty())
{
header << l.GetCommentBegin() << "\n";
header << h_name << filename->GetFullName() << "\n";
header << wxExAlignText(purpose, h_purpose) << "\n";
header << h_author << author << "\n";
header << h_created << wxDateTime::Now().FormatISODate() << "\n";
if (m_Config->GetBool("SVN"))
// Prevent the Id to be expanded by SVN itself here.
header << h_rcs << wxString("Id$") << "\n";
header << h_copyright << "(c) " << wxDateTime::Now().Format("%Y") << " " <<
(!company.empty() ? company: author) << email_field << "\n";
if (!license.empty())
header << h_license << license << "\n";
header << l.GetCommentEnd() << "\n";
}
else
{
header << l.MakeComment(wxEmptyString, false) << "\n";
header << l.MakeComment(h_name, filename->GetFullName()) << "\n";
header << l.MakeComment(h_purpose, purpose) << "\n";
header << l.MakeComment(h_author, author) << "\n";
header << l.MakeComment(h_created, wxDateTime::Now().FormatISODate()) << "\n";
if (m_Config->GetBool("SVN"))
// Prevent the Id to be expanded by SVN itself here.
header << l.MakeComment(h_rcs, wxString("Id$")) << "\n";
header << l.MakeComment(h_copyright, "(c) " + wxDateTime::Now().Format("%Y") + " " +
(!company.empty() ? company: author) + email_field) << "\n";
if (!license.empty())
header << l.MakeComment(h_license, license) << "\n";
header << l.MakeComment(wxEmptyString, false) << "\n";
}
header << "\n";
if (filename->GetExt() == "h" &&
filename->GetStat().st_size == 0)
{
wxString argument = "__" + filename->GetName() + "_h";
header << "\n";
header << "#if !defined (" << argument << ")" << "\n";
header << "#define " << argument << "\n";
header << "#endif" << "\n";
}
return header;
}
int wxExHeader::ShowDialog(wxWindow* parent, const wxString& title) const
{
std::vector<wxExConfigItem> v;
// Purpose is required.
v.push_back(wxExConfigItem(_("Purpose"), wxEmptyString, wxTE_MULTILINE, true));
// Author is required, but only presented if empty.
// Email and License also are only presented if Author empty.
if (m_Config->Get(_("Author")).empty())
{
v.push_back(wxExConfigItem(_("Author"), wxEmptyString, 0, true));
if (m_Config->Get(_("Email")).empty())
{
v.push_back(wxExConfigItem(_("Email")));
}
if (m_Config->Get(_("License")).empty())
{
v.push_back(wxExConfigItem(_("License")));
}
}
return wxExConfigDialog(
parent,
m_Config, v, title).ShowModal();
}
<commit_msg>removed company field<commit_after>/******************************************************************************\
* File: header.cpp
* Purpose: Implementation of wxExHeader class
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/extension/header.h>
#include <wx/extension/configdialog.h>
#include <wx/extension/file.h>
#include <wx/extension/util.h>
wxExHeader::wxExHeader(wxExConfig* config)
: m_Config(config)
{
}
const wxString wxExHeader::Get(const wxExFileName* filename) const
{
const wxString h_name = "Name: ";
const wxString h_purpose = "Purpose: ";
const wxString h_author = "Author: ";
const wxString h_created = "Created: ";
const wxString h_rcs = "RCS-ID: $";
const wxString h_copyright = "Copyright: ";
const wxString h_license = "License: ";
const wxString author = m_Config->Get(_("Author"));
const wxString license = m_Config->Get(_("License"));
const wxString email = m_Config->Get(_("Email"));
const wxString purpose = m_Config->Get(_("Purpose"));
const wxString email_field = (!email.empty() ? " < " + email + ">": email);
wxString header;
const wxExLexer l = filename->GetLexer();
if (!l.GetCommentEnd().empty())
{
header << l.GetCommentBegin() << "\n";
header << h_name << filename->GetFullName() << "\n";
header << wxExAlignText(purpose, h_purpose) << "\n";
header << h_author << author << "\n";
header << h_created << wxDateTime::Now().FormatISODate() << "\n";
if (m_Config->GetBool("SVN"))
// Prevent the Id to be expanded by SVN itself here.
header << h_rcs << wxString("Id$") << "\n";
header << h_copyright << "(c) " << wxDateTime::Now().Format("%Y") << " " <<
author << email_field << "\n";
if (!license.empty())
header << h_license << license << "\n";
header << l.GetCommentEnd() << "\n";
}
else
{
header << l.MakeComment(wxEmptyString, false) << "\n";
header << l.MakeComment(h_name, filename->GetFullName()) << "\n";
header << l.MakeComment(h_purpose, purpose) << "\n";
header << l.MakeComment(h_author, author) << "\n";
header << l.MakeComment(h_created, wxDateTime::Now().FormatISODate()) << "\n";
if (m_Config->GetBool("SVN"))
// Prevent the Id to be expanded by SVN itself here.
header << l.MakeComment(h_rcs, wxString("Id$")) << "\n";
header << l.MakeComment(h_copyright, "(c) " + wxDateTime::Now().Format("%Y") + " " +
author + email_field) << "\n";
if (!license.empty())
header << l.MakeComment(h_license, license) << "\n";
header << l.MakeComment(wxEmptyString, false) << "\n";
}
header << "\n";
if (filename->GetExt() == "h" &&
filename->GetStat().st_size == 0)
{
wxString argument = "__" + filename->GetName() + "_h";
header << "\n";
header << "#if !defined (" << argument << ")" << "\n";
header << "#define " << argument << "\n";
header << "#endif" << "\n";
}
return header;
}
int wxExHeader::ShowDialog(wxWindow* parent, const wxString& title) const
{
std::vector<wxExConfigItem> v;
// Purpose is required.
v.push_back(wxExConfigItem(_("Purpose"), wxEmptyString, wxTE_MULTILINE, true));
// Author is required, but only presented if empty.
// Email and License also are only presented if Author empty.
if (m_Config->Get(_("Author")).empty())
{
v.push_back(wxExConfigItem(_("Author"), wxEmptyString, 0, true));
if (m_Config->Get(_("Email")).empty())
{
v.push_back(wxExConfigItem(_("Email")));
}
if (m_Config->Get(_("License")).empty())
{
v.push_back(wxExConfigItem(_("License")));
}
}
return wxExConfigDialog(
parent,
m_Config, v, title).ShowModal();
}
<|endoftext|>
|
<commit_before>/******************************************************************************\
* File: lexers.cpp
* Purpose: Implementation of wxExLexers classes
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 2008-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/config.h>
#include <wx/stdpaths.h>
#include <wx/tokenzr.h>
#include <wx/stc/stc.h>
#include <wx/textfile.h>
#include <wx/extension/lexers.h>
#include <wx/extension/frd.h>
#include <wx/extension/util.h> // for wxExMatchesOneOf
wxExLexers* wxExLexers::m_Self = NULL;
wxExLexers::wxExLexers(const wxFileName& filename)
: m_FileName(filename)
{
}
const wxString wxExLexers::ApplyMacro(const wxString& text) const
{
if (text.IsNumber() || text.Contains(","))
{
return text;
}
std::map<wxString, wxString>::const_iterator it = m_Macros.find(text);
if (it != m_Macros.end())
{
return it->second;
}
else
{
wxLogError(_("Undefined macro: %s"), text.c_str());
return text;
}
}
const wxString wxExLexers::BuildWildCards(const wxFileName& filename) const
{
const wxString allfiles_wildcard =
_("All Files") + wxString::Format(" (%s)|%s",
wxFileSelectorDefaultWildcardStr,
wxFileSelectorDefaultWildcardStr);
wxString wildcards = allfiles_wildcard;
// Build the wildcard string using all available lexers.
for (
std::map<wxString, wxExLexer>::const_iterator it = m_Lexers.begin();
it != m_Lexers.end();
++it)
{
if (!it->second.m_Extensions.empty())
{
const wxString wildcard =
it->second.GetScintillaLexer() +
" (" + it->second.m_Extensions + ") |" +
it->second.m_Extensions;
if (wxExMatchesOneOf(filename, it->second.m_Extensions))
{
wildcards = wildcard + "|" + wildcards;
}
else
{
wildcards = wildcards + "|" + wildcard;
}
}
}
return wildcards;
}
const wxExLexer wxExLexers::FindByFileName(const wxFileName& filename) const
{
if (!filename.IsOk())
{
return wxExLexer();
}
for (
std::map<wxString, wxExLexer>::const_iterator it = m_Lexers.begin();
it != m_Lexers.end();
++it)
{
if (wxExMatchesOneOf(filename, it->second.m_Extensions))
{
return it->second;
}
}
return wxExLexer();
}
const wxExLexer wxExLexers::FindByName(
const wxString& name,
bool fail_if_not_found) const
{
std::map<wxString, wxExLexer>::const_iterator it = m_Lexers.find(name);
if (it != m_Lexers.end())
{
return it->second;
}
if (!m_Lexers.empty() && fail_if_not_found)
{
wxFAIL;
}
return wxExLexer();
}
const wxExLexer wxExLexers::FindByText(const wxString& text) const
{
// Add automatic lexers if text starts with some special tokens.
const wxString text_lowercase = text.Lower();
if (text_lowercase.StartsWith("#") ||
// .po files that do not have comment headers, start with msgid, so set them
text_lowercase.StartsWith("msgid"))
{
return FindByName("bash", false); // don't show error
}
else if (text_lowercase.StartsWith("<html>") ||
text_lowercase.StartsWith("<?php"))
{
return FindByName("hypertext", false); // don't show error
}
else if (text_lowercase.StartsWith("<?xml"))
{
return FindByName("xml", false); // don't show error
}
// cpp files like #include <map> really do not have a .h extension (e.g. /usr/include/c++/3.3.5/map)
// so add here.
else if (text_lowercase.StartsWith("//"))
{
return FindByName("cpp", false); // don't show error
}
return wxExLexer();
}
wxExLexers* wxExLexers::Get(bool createOnDemand)
{
if (m_Self == NULL && createOnDemand)
{
m_Self = new wxExLexers(wxFileName(
#ifdef wxExUSE_PORTABLE
wxPathOnly(wxStandardPaths::Get().GetExecutablePath())
#else
wxStandardPaths::Get().GetUserDataDir()
#endif
+ wxFileName::GetPathSeparator() + "lexers.xml")
);
m_Self->Read();
}
return m_Self;
}
const wxString wxExLexers::GetLexerExtensions() const
{
wxString text;
for (
std::map<wxString, wxExLexer>::const_iterator it = m_Lexers.begin();
it != m_Lexers.end();
++it)
{
if (!it->second.m_Extensions.empty() &&
it->second.m_Extensions != "*." + it->second.m_ScintillaLexer)
{
if (!text.empty())
{
text += wxExFindReplaceData::Get()->GetFieldSeparator();
}
text += it->second.m_Extensions;
}
}
return text;
}
const wxString wxExLexers::ParseTagColourings(const wxXmlNode* node) const
{
wxString text;
wxXmlNode* child = node->GetChildren();
while (child)
{
if (child->GetName() == "colouring")
{
wxString content = child->GetNodeContent().Strip(wxString::both);
std::map<wxString, wxString>::const_iterator it = m_Macros.find(content);
if (it != m_Macros.end())
{
content = it->second;
}
text +=
ApplyMacro(
child->GetAttribute("no", "0"))
+ "=" + content + wxTextFile::GetEOL();
}
else if (child->GetName() == "comment")
{
// Ignore comments.
}
else
{
wxLogError(_("Undefined colourings tag: %s on: %d"),
child->GetName().c_str(), child->GetLineNumber());
}
child = child->GetNext();
}
return text;
}
void wxExLexers::ParseTagGlobal(const wxXmlNode* node)
{
wxXmlNode* child = node->GetChildren();
while (child)
{
if (child->GetName() == "comment")
{
// Ignore comments.
}
else if (child->GetName() == "hex")
{
m_StylesHex.push_back(
ApplyMacro(child->GetAttribute("no", "0")) + "=" +
child->GetNodeContent().Strip(wxString::both));
}
else if (child->GetName() == "indicator")
{
m_Indicators.insert(std::make_pair(
atoi(ApplyMacro(child->GetAttribute("no", "0")).c_str()),
atoi(child->GetNodeContent().Strip(wxString::both).c_str())));
}
else if (child->GetName() == "marker")
{
const wxExMarker marker(ParseTagMarker(
ApplyMacro(child->GetAttribute("no", "0")),
child->GetNodeContent().Strip(wxString::both)));
if (marker.GetMarkerNumber() < wxSTC_STYLE_MAX &&
marker.GetMarkerSymbol() < wxSTC_STYLE_MAX)
{
m_Markers.push_back(marker);
}
else
{
wxLogError(_("Illegal marker number: %d or symbol: %d on: %d"),
marker.GetMarkerNumber(),
marker.GetMarkerSymbol(),
child->GetLineNumber());
}
}
else if (child->GetName() == "properties")
{
m_GlobalProperties = ParseTagProperties(child);
}
else if (child->GetName() == "style")
{
const wxString attrib = ApplyMacro(child->GetAttribute("no", "0"));
const wxString content = child->GetNodeContent().Strip(wxString::both);
int attrib_no = atoi(attrib.c_str());
if (attrib_no == wxSTC_STYLE_DEFAULT)
{
m_DefaultStyle = attrib + "=" + content;
}
else
{
m_Styles.push_back(attrib + "=" + content);
}
}
else
{
wxLogError(_("Undefined global tag: %s on: %d"),
child->GetName().c_str(), child->GetLineNumber());
}
child = child->GetNext();
}
}
const wxExLexer wxExLexers::ParseTagLexer(const wxXmlNode* node) const
{
wxExLexer lexer(node->GetAttribute("name", ""));
lexer.m_Extensions = node->GetAttribute(
"extensions",
"*." + lexer.m_ScintillaLexer);
wxXmlNode *child = node->GetChildren();
while (child)
{
if (child->GetName() == "colourings")
{
lexer.m_Colourings = ParseTagColourings(child);
}
else if (child->GetName() == "keywords")
{
if (!lexer.SetKeywords(child->GetNodeContent().Strip(wxString::both)))
{
wxLogError(_("Keywords could not be set on: %d"), child->GetLineNumber());
}
}
else if (child->GetName() == "properties")
{
lexer.m_Properties = ParseTagProperties(child);
}
else if (child->GetName() == "comments")
{
lexer.m_CommentBegin = child->GetAttribute("begin1", "");
lexer.m_CommentEnd = child->GetAttribute("end1", "");
lexer.m_CommentBegin2 = child->GetAttribute("begin2", "");
lexer.m_CommentEnd2 = child->GetAttribute("end2", "");
}
else if (child->GetName() == "comment")
{
// Ignore comments.
}
else
{
wxLogError(_("Undefined lexer tag: %s on: %d"),
child->GetName().c_str(), child->GetLineNumber());
}
child = child->GetNext();
}
return lexer;
}
void wxExLexers::ParseTagMacro(const wxXmlNode* node)
{
wxXmlNode* child = node->GetChildren();
while (child)
{
if (child->GetName() == "comment")
{
// Ignore comments.
}
else if (child->GetName() == "def")
{
const wxString attrib = child->GetAttribute("no", "0");
const wxString content = child->GetNodeContent().Strip(wxString::both);
m_Macros[attrib] = content;
}
else
{
wxLogError(_("Undefined macro tag: %s on: %d"),
child->GetName().c_str(), child->GetLineNumber());
}
child = child->GetNext();
}
}
const wxExMarker wxExLexers::ParseTagMarker(
const wxString& number,
const wxString& props) const
{
wxStringTokenizer prop_fields(props, ",");
const wxString symbol = ApplyMacro(prop_fields.GetNextToken());
wxColour foreground;
wxColour background;
if (prop_fields.HasMoreTokens())
{
foreground = ApplyMacro(
prop_fields.GetNextToken().Strip(wxString::both));
if (prop_fields.HasMoreTokens())
{
background = ApplyMacro(
prop_fields.GetNextToken().Strip(wxString::both));
}
}
const int no = atoi(number.c_str());
const int symbol_no = atoi(symbol.c_str());
if (no <= wxSTC_MARKER_MAX && symbol_no <= wxSTC_MARKER_MAX)
{
return wxExMarker(no, symbol_no, foreground, background);
}
else
{
wxLogError(_("Illegal marker number: %d or symbol: %d"), no, symbol_no);
return wxExMarker(0, 0, foreground, background);
}
}
const wxString wxExLexers::ParseTagProperties(const wxXmlNode* node) const
{
wxString text;
wxXmlNode *child = node->GetChildren();
while (child)
{
if (child->GetName() == "property")
{
text +=
child->GetAttribute("name", "0") + "=" +
child->GetNodeContent().Strip(wxString::both) + wxTextFile::GetEOL();
}
else if (child->GetName() == "comment")
{
// Ignore comments.
}
else
{
wxLogError(_("Undefined properties tag: %s on %d"),
child->GetName().c_str(), child->GetLineNumber());
}
child = child->GetNext();
}
return text;
}
void wxExLexers::Read()
{
// This test is to prevent showing an error if the lexers file does not exist,
// as this is not required.
if (!m_FileName.FileExists())
{
return;
}
wxXmlDocument doc;
if (!doc.Load(m_FileName.GetFullPath()))
{
return;
}
// Initialize members.
m_Indicators.clear();
m_Lexers.clear();
m_Markers.clear();
m_SortedLexerNames.clear();
m_Styles.clear();
m_StylesHex.clear();
wxXmlNode* child = doc.GetRoot()->GetChildren();
while (child)
{
if (child->GetName() == "macro")
{
ParseTagMacro(child);
}
else if (child->GetName() == "global")
{
ParseTagGlobal(child);
}
else if (child->GetName() == "lexer")
{
const wxExLexer& lexer = ParseTagLexer(child);
if (!lexer.GetScintillaLexer().empty())
{
if (lexer.GetScintillaLexer() == "hypertext")
{
// As our lexers.xml files cannot use xml comments,
// add them here.
wxExLexer l(lexer);
l.m_CommentBegin = "<!--";
l.m_CommentEnd = "-->";
m_Lexers.insert(std::make_pair(lexer.GetScintillaLexer(), l));
}
else
{
m_Lexers.insert(std::make_pair(lexer.GetScintillaLexer(), lexer));
m_SortedLexerNames.Add(lexer.GetScintillaLexer());
}
}
}
child = child->GetNext();
}
// Add the <none> lexer.
m_SortedLexerNames.Add(_("<none>"));
if (!wxConfigBase::Get()->Exists(_("In files")))
{
wxConfigBase::Get()->Write(_("In files"), GetLexerExtensions());
}
if (!wxConfigBase::Get()->Exists(_("Add what")))
{
wxConfigBase::Get()->Write(_("Add what"), GetLexerExtensions());
}
}
wxExLexers* wxExLexers::Set(wxExLexers* lexers)
{
wxExLexers* old = m_Self;
m_Self = lexers;
return old;
}
bool wxExLexers::ShowDialog(
wxWindow* parent,
wxString& lexer,
const wxString& caption) const
{
wxSingleChoiceDialog dlg(
parent,
_("Input") + ":",
caption,
m_SortedLexerNames);
dlg.SetSelection(lexer.empty() ?
m_SortedLexerNames.Index(_("<none>")):
m_SortedLexerNames.Index(lexer));
if (dlg.ShowModal() == wxID_CANCEL)
{
return false;
}
lexer = (dlg.GetSelection() == m_SortedLexerNames.Index(_("<none>")) ?
wxEmptyString:
FindByName(dlg.GetStringSelection()).GetScintillaLexer());
return true;
}
<commit_msg>give error if macro already exists<commit_after>/******************************************************************************\
* File: lexers.cpp
* Purpose: Implementation of wxExLexers classes
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 2008-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/config.h>
#include <wx/stdpaths.h>
#include <wx/tokenzr.h>
#include <wx/stc/stc.h>
#include <wx/textfile.h>
#include <wx/extension/lexers.h>
#include <wx/extension/frd.h>
#include <wx/extension/util.h> // for wxExMatchesOneOf
wxExLexers* wxExLexers::m_Self = NULL;
wxExLexers::wxExLexers(const wxFileName& filename)
: m_FileName(filename)
{
}
const wxString wxExLexers::ApplyMacro(const wxString& text) const
{
if (text.IsNumber() || text.Contains(","))
{
return text;
}
std::map<wxString, wxString>::const_iterator it = m_Macros.find(text);
if (it != m_Macros.end())
{
return it->second;
}
else
{
wxLogError(_("Undefined macro: %s"), text.c_str());
return text;
}
}
const wxString wxExLexers::BuildWildCards(const wxFileName& filename) const
{
const wxString allfiles_wildcard =
_("All Files") + wxString::Format(" (%s)|%s",
wxFileSelectorDefaultWildcardStr,
wxFileSelectorDefaultWildcardStr);
wxString wildcards = allfiles_wildcard;
// Build the wildcard string using all available lexers.
for (
std::map<wxString, wxExLexer>::const_iterator it = m_Lexers.begin();
it != m_Lexers.end();
++it)
{
if (!it->second.m_Extensions.empty())
{
const wxString wildcard =
it->second.GetScintillaLexer() +
" (" + it->second.m_Extensions + ") |" +
it->second.m_Extensions;
if (wxExMatchesOneOf(filename, it->second.m_Extensions))
{
wildcards = wildcard + "|" + wildcards;
}
else
{
wildcards = wildcards + "|" + wildcard;
}
}
}
return wildcards;
}
const wxExLexer wxExLexers::FindByFileName(const wxFileName& filename) const
{
if (!filename.IsOk())
{
return wxExLexer();
}
for (
std::map<wxString, wxExLexer>::const_iterator it = m_Lexers.begin();
it != m_Lexers.end();
++it)
{
if (wxExMatchesOneOf(filename, it->second.m_Extensions))
{
return it->second;
}
}
return wxExLexer();
}
const wxExLexer wxExLexers::FindByName(
const wxString& name,
bool fail_if_not_found) const
{
std::map<wxString, wxExLexer>::const_iterator it = m_Lexers.find(name);
if (it != m_Lexers.end())
{
return it->second;
}
if (!m_Lexers.empty() && fail_if_not_found)
{
wxFAIL;
}
return wxExLexer();
}
const wxExLexer wxExLexers::FindByText(const wxString& text) const
{
// Add automatic lexers if text starts with some special tokens.
const wxString text_lowercase = text.Lower();
if (text_lowercase.StartsWith("#") ||
// .po files that do not have comment headers, start with msgid, so set them
text_lowercase.StartsWith("msgid"))
{
return FindByName("bash", false); // don't show error
}
else if (text_lowercase.StartsWith("<html>") ||
text_lowercase.StartsWith("<?php"))
{
return FindByName("hypertext", false); // don't show error
}
else if (text_lowercase.StartsWith("<?xml"))
{
return FindByName("xml", false); // don't show error
}
// cpp files like #include <map> really do not have a .h extension (e.g. /usr/include/c++/3.3.5/map)
// so add here.
else if (text_lowercase.StartsWith("//"))
{
return FindByName("cpp", false); // don't show error
}
return wxExLexer();
}
wxExLexers* wxExLexers::Get(bool createOnDemand)
{
if (m_Self == NULL && createOnDemand)
{
m_Self = new wxExLexers(wxFileName(
#ifdef wxExUSE_PORTABLE
wxPathOnly(wxStandardPaths::Get().GetExecutablePath())
#else
wxStandardPaths::Get().GetUserDataDir()
#endif
+ wxFileName::GetPathSeparator() + "lexers.xml")
);
m_Self->Read();
}
return m_Self;
}
const wxString wxExLexers::GetLexerExtensions() const
{
wxString text;
for (
std::map<wxString, wxExLexer>::const_iterator it = m_Lexers.begin();
it != m_Lexers.end();
++it)
{
if (!it->second.m_Extensions.empty() &&
it->second.m_Extensions != "*." + it->second.m_ScintillaLexer)
{
if (!text.empty())
{
text += wxExFindReplaceData::Get()->GetFieldSeparator();
}
text += it->second.m_Extensions;
}
}
return text;
}
const wxString wxExLexers::ParseTagColourings(const wxXmlNode* node) const
{
wxString text;
wxXmlNode* child = node->GetChildren();
while (child)
{
if (child->GetName() == "colouring")
{
wxString content = child->GetNodeContent().Strip(wxString::both);
std::map<wxString, wxString>::const_iterator it = m_Macros.find(content);
if (it != m_Macros.end())
{
content = it->second;
}
text +=
ApplyMacro(
child->GetAttribute("no", "0"))
+ "=" + content + wxTextFile::GetEOL();
}
else if (child->GetName() == "comment")
{
// Ignore comments.
}
else
{
wxLogError(_("Undefined colourings tag: %s on: %d"),
child->GetName().c_str(), child->GetLineNumber());
}
child = child->GetNext();
}
return text;
}
void wxExLexers::ParseTagGlobal(const wxXmlNode* node)
{
wxXmlNode* child = node->GetChildren();
while (child)
{
if (child->GetName() == "comment")
{
// Ignore comments.
}
else if (child->GetName() == "hex")
{
m_StylesHex.push_back(
ApplyMacro(child->GetAttribute("no", "0")) + "=" +
child->GetNodeContent().Strip(wxString::both));
}
else if (child->GetName() == "indicator")
{
m_Indicators.insert(std::make_pair(
atoi(ApplyMacro(child->GetAttribute("no", "0")).c_str()),
atoi(child->GetNodeContent().Strip(wxString::both).c_str())));
}
else if (child->GetName() == "marker")
{
const wxExMarker marker(ParseTagMarker(
ApplyMacro(child->GetAttribute("no", "0")),
child->GetNodeContent().Strip(wxString::both)));
if (marker.GetMarkerNumber() < wxSTC_STYLE_MAX &&
marker.GetMarkerSymbol() < wxSTC_STYLE_MAX)
{
m_Markers.push_back(marker);
}
else
{
wxLogError(_("Illegal marker number: %d or symbol: %d on: %d"),
marker.GetMarkerNumber(),
marker.GetMarkerSymbol(),
child->GetLineNumber());
}
}
else if (child->GetName() == "properties")
{
m_GlobalProperties = ParseTagProperties(child);
}
else if (child->GetName() == "style")
{
const wxString attrib = ApplyMacro(child->GetAttribute("no", "0"));
const wxString content = child->GetNodeContent().Strip(wxString::both);
int attrib_no = atoi(attrib.c_str());
if (attrib_no == wxSTC_STYLE_DEFAULT)
{
m_DefaultStyle = attrib + "=" + content;
}
else
{
m_Styles.push_back(attrib + "=" + content);
}
}
else
{
wxLogError(_("Undefined global tag: %s on: %d"),
child->GetName().c_str(), child->GetLineNumber());
}
child = child->GetNext();
}
}
const wxExLexer wxExLexers::ParseTagLexer(const wxXmlNode* node) const
{
wxExLexer lexer(node->GetAttribute("name", ""));
lexer.m_Extensions = node->GetAttribute(
"extensions",
"*." + lexer.m_ScintillaLexer);
wxXmlNode *child = node->GetChildren();
while (child)
{
if (child->GetName() == "colourings")
{
lexer.m_Colourings = ParseTagColourings(child);
}
else if (child->GetName() == "keywords")
{
if (!lexer.SetKeywords(child->GetNodeContent().Strip(wxString::both)))
{
wxLogError(_("Keywords could not be set on: %d"), child->GetLineNumber());
}
}
else if (child->GetName() == "properties")
{
lexer.m_Properties = ParseTagProperties(child);
}
else if (child->GetName() == "comments")
{
lexer.m_CommentBegin = child->GetAttribute("begin1", "");
lexer.m_CommentEnd = child->GetAttribute("end1", "");
lexer.m_CommentBegin2 = child->GetAttribute("begin2", "");
lexer.m_CommentEnd2 = child->GetAttribute("end2", "");
}
else if (child->GetName() == "comment")
{
// Ignore comments.
}
else
{
wxLogError(_("Undefined lexer tag: %s on: %d"),
child->GetName().c_str(), child->GetLineNumber());
}
child = child->GetNext();
}
return lexer;
}
void wxExLexers::ParseTagMacro(const wxXmlNode* node)
{
wxXmlNode* child = node->GetChildren();
while (child)
{
if (child->GetName() == "comment")
{
// Ignore comments.
}
else if (child->GetName() == "def")
{
const wxString attrib = child->GetAttribute("no", "0");
const wxString content = child->GetNodeContent().Strip(wxString::both);
std::map<wxString, wxString>::const_iterator it = m_Macros.find(attrib);
if (it != m_Macros.end())
{
wxLogError(_("Macro: %s on line: already exists: %d"),
attrib.c_str(), child->GetLineNumber());
}
else
{
m_Macros[attrib] = content;
}
}
else
{
wxLogError(_("Undefined macro tag: %s on: %d"),
child->GetName().c_str(), child->GetLineNumber());
}
child = child->GetNext();
}
}
const wxExMarker wxExLexers::ParseTagMarker(
const wxString& number,
const wxString& props) const
{
wxStringTokenizer prop_fields(props, ",");
const wxString symbol = ApplyMacro(prop_fields.GetNextToken());
wxColour foreground;
wxColour background;
if (prop_fields.HasMoreTokens())
{
foreground = ApplyMacro(
prop_fields.GetNextToken().Strip(wxString::both));
if (prop_fields.HasMoreTokens())
{
background = ApplyMacro(
prop_fields.GetNextToken().Strip(wxString::both));
}
}
const int no = atoi(number.c_str());
const int symbol_no = atoi(symbol.c_str());
if (no <= wxSTC_MARKER_MAX && symbol_no <= wxSTC_MARKER_MAX)
{
return wxExMarker(no, symbol_no, foreground, background);
}
else
{
wxLogError(_("Illegal marker number: %d or symbol: %d"), no, symbol_no);
return wxExMarker(0, 0, foreground, background);
}
}
const wxString wxExLexers::ParseTagProperties(const wxXmlNode* node) const
{
wxString text;
wxXmlNode *child = node->GetChildren();
while (child)
{
if (child->GetName() == "property")
{
text +=
child->GetAttribute("name", "0") + "=" +
child->GetNodeContent().Strip(wxString::both) + wxTextFile::GetEOL();
}
else if (child->GetName() == "comment")
{
// Ignore comments.
}
else
{
wxLogError(_("Undefined properties tag: %s on %d"),
child->GetName().c_str(), child->GetLineNumber());
}
child = child->GetNext();
}
return text;
}
void wxExLexers::Read()
{
// This test is to prevent showing an error if the lexers file does not exist,
// as this is not required.
if (!m_FileName.FileExists())
{
return;
}
wxXmlDocument doc;
if (!doc.Load(m_FileName.GetFullPath()))
{
return;
}
// Initialize members.
m_Indicators.clear();
m_Lexers.clear();
m_Markers.clear();
m_SortedLexerNames.clear();
m_Styles.clear();
m_StylesHex.clear();
wxXmlNode* child = doc.GetRoot()->GetChildren();
while (child)
{
if (child->GetName() == "macro")
{
ParseTagMacro(child);
}
else if (child->GetName() == "global")
{
ParseTagGlobal(child);
}
else if (child->GetName() == "lexer")
{
const wxExLexer& lexer = ParseTagLexer(child);
if (!lexer.GetScintillaLexer().empty())
{
if (lexer.GetScintillaLexer() == "hypertext")
{
// As our lexers.xml files cannot use xml comments,
// add them here.
wxExLexer l(lexer);
l.m_CommentBegin = "<!--";
l.m_CommentEnd = "-->";
m_Lexers.insert(std::make_pair(lexer.GetScintillaLexer(), l));
}
else
{
m_Lexers.insert(std::make_pair(lexer.GetScintillaLexer(), lexer));
m_SortedLexerNames.Add(lexer.GetScintillaLexer());
}
}
}
child = child->GetNext();
}
// Add the <none> lexer.
m_SortedLexerNames.Add(_("<none>"));
if (!wxConfigBase::Get()->Exists(_("In files")))
{
wxConfigBase::Get()->Write(_("In files"), GetLexerExtensions());
}
if (!wxConfigBase::Get()->Exists(_("Add what")))
{
wxConfigBase::Get()->Write(_("Add what"), GetLexerExtensions());
}
}
wxExLexers* wxExLexers::Set(wxExLexers* lexers)
{
wxExLexers* old = m_Self;
m_Self = lexers;
return old;
}
bool wxExLexers::ShowDialog(
wxWindow* parent,
wxString& lexer,
const wxString& caption) const
{
wxSingleChoiceDialog dlg(
parent,
_("Input") + ":",
caption,
m_SortedLexerNames);
dlg.SetSelection(lexer.empty() ?
m_SortedLexerNames.Index(_("<none>")):
m_SortedLexerNames.Index(lexer));
if (dlg.ShowModal() == wxID_CANCEL)
{
return false;
}
lexer = (dlg.GetSelection() == m_SortedLexerNames.Index(_("<none>")) ?
wxEmptyString:
FindByName(dlg.GetStringSelection()).GetScintillaLexer());
return true;
}
<|endoftext|>
|
<commit_before>/**
* Script.cpp
*
* Implementation file for the script class
*
* @author Emiel Bruijntjes <emiel.bruijntjes@copernica.com>
* @copyright 2014 Copernica BV
*/
/**
* Dependencies
*/
#include "includes.h"
#include <mutex>
/**
* Open PHP namespace
*/
namespace Php {
/**
* Helper class to temporarily set compiler options
*
* When an object is destructed, it automatically restored the previous compiler settings
*/
class CompilerOptions
{
private:
/**
* The original compiler options
* @var int
*/
zend_uint _original;
public:
/**
* Constructor
* @param options
*/
CompilerOptions(zend_uint options)
{
// remember the old compiler options before we set temporary compile options
_original = CG(compiler_options);
// we're going to evaluate only once
CG(compiler_options) = options;
}
/**
* Destructor
*/
virtual ~CompilerOptions()
{
// restore original options
CG(compiler_options) = _original;
}
};
/**
* Helper class to store and restore the current opcode state
*
* When we're going to execute a set of instructions, we need to store the
* current state of the Zend engine. After the instructions have been processed,
* we can switch back to the original instructions
*/
class ExecuteState
{
private:
/**
* All the original settings
*/
zend_op_array *_active_op_array;
zval **_return_value_ptr_ptr;
zend_op **_opline_ptr;
int _interactive;
public:
/**
* Constructor
*/
ExecuteState()
{
// store all the original stuff
_active_op_array = EG(active_op_array);
_return_value_ptr_ptr = EG(return_value_ptr_ptr);
_opline_ptr = EG(opline_ptr);
_interactive = CG(interactive);
}
/**
* Destructor
*/
virtual ~ExecuteState()
{
// restore all settings
CG(interactive) = _interactive;
EG(no_extensions) = 0;
EG(opline_ptr) = _opline_ptr;
EG(active_op_array) = _active_op_array;
EG(return_value_ptr_ptr) = _return_value_ptr_ptr;
}
};
/**
* Constructor
* @param name name of the script
* @param script actual PHP code
* @param size length of the string
*/
Script::Script(const char *name, const char *phpcode, size_t size)
{
// Sadly, there is not a simple Zend function to compile a string into opcodes,
// so we basically copy the code that we found in zend_execute_API.c inside
// the zend_eval_stringl() function into this file here. However, the code
// found there is full of zval manipulation, for which we can use the much
// simpler Php::Value object
Php::Value source(phpcode, size);
// remember the old compiler options, and set new compiler options
CompilerOptions options(ZEND_COMPILE_DEFAULT_FOR_EVAL);
// we need the tsrm_ls variable
TSRMLS_FETCH();
// compile the string
_opcodes = zend_compile_string(source._val, (char *)name TSRMLS_CC);
}
/**
* Destructor
*/
Script::~Script()
{
// do nothing if there are no opcodes
if (!_opcodes) return;
// clean up opcodes
destroy_op_array(_opcodes TSRMLS_CC);
efree(_opcodes);
}
/**
* Execute a script
* @return Value
*/
Value Script::execute() const
{
// if the script could not be compiled, we return null
if (!_opcodes) return nullptr;
// pointer that is going to hold the return value of the script
zval *retval_ptr = nullptr;
// the zend engine is probably already busy processing opcodes, so we store
// the current execute state before we're going to switch the runtime to
// our own set of opcodes
ExecuteState oldstate;
// old execute state has been saved (and will automatically be restured when
// the oldstate is destructed), so we can now safely overwrite all the settings
EG(return_value_ptr_ptr) = &retval_ptr;
EG(active_op_array) = _opcodes;
EG(no_extensions) = 1;
if (!EG(active_symbol_table)) zend_rebuild_symbol_table(TSRMLS_C);
CG(interactive) = 0;
// this code was copied from zend_execute_API.c. this is what I think it does:
// the zend_execute() call could result in all sort of disastrous things, one
// of them is a full crash of the executing script. if that happens, the zend
// engine does a long jump right up to some other point in the code. the
// 'zend_try' and 'zend_catch' macros prevent this: they install a new
// destination for the long jump, so that we can catch a failure
zend_try
{
// execute the code
zend_execute(_opcodes TSRMLS_CC);
}
zend_catch
{
// the code could not be executed, and the zend engine is in big
// trouble now, in the original code the _opcodes are efree'd, but here
// we can just as well continue with the real bailout (the zend_try/
// zend_catch pair was maybe not even necessary???)
zend_bailout();
}
zend_end_try();
// we're ready if there is no return value
if (!retval_ptr) return nullptr;
// copy the pointer into a value object, and return that
return retval_ptr;
}
/**
* End of namespace
*/
}
<commit_msg>exception support for the Script class<commit_after>/**
* Script.cpp
*
* Implementation file for the script class
*
* @author Emiel Bruijntjes <emiel.bruijntjes@copernica.com>
* @copyright 2014 Copernica BV
*/
/**
* Dependencies
*/
#include "includes.h"
#include <mutex>
/**
* Open PHP namespace
*/
namespace Php {
/**
* Helper class to temporarily set compiler options
*
* When an object is destructed, it automatically restored the previous compiler settings
*/
class CompilerOptions
{
private:
/**
* The original compiler options
* @var int
*/
zend_uint _original;
public:
/**
* Constructor
* @param options
*/
CompilerOptions(zend_uint options)
{
// remember the old compiler options before we set temporary compile options
_original = CG(compiler_options);
// we're going to evaluate only once
CG(compiler_options) = options;
}
/**
* Destructor
*/
virtual ~CompilerOptions()
{
// restore original options
CG(compiler_options) = _original;
}
};
/**
* Helper class to store and restore the current opcode state
*
* When we're going to execute a set of instructions, we need to store the
* current state of the Zend engine. After the instructions have been processed,
* we can switch back to the original instructions
*/
class ExecuteState
{
private:
/**
* All the original settings
*/
zend_op_array *_active_op_array;
zval **_return_value_ptr_ptr;
zend_op **_opline_ptr;
int _interactive;
public:
/**
* Constructor
*/
ExecuteState()
{
// store all the original stuff
_active_op_array = EG(active_op_array);
_return_value_ptr_ptr = EG(return_value_ptr_ptr);
_opline_ptr = EG(opline_ptr);
_interactive = CG(interactive);
}
/**
* Destructor
*/
virtual ~ExecuteState()
{
// restore all settings
CG(interactive) = _interactive;
EG(no_extensions) = 0;
EG(opline_ptr) = _opline_ptr;
EG(active_op_array) = _active_op_array;
EG(return_value_ptr_ptr) = _return_value_ptr_ptr;
}
};
/**
* Constructor
* @param name name of the script
* @param script actual PHP code
* @param size length of the string
*/
Script::Script(const char *name, const char *phpcode, size_t size)
{
// Sadly, there is not a simple Zend function to compile a string into opcodes,
// so we basically copy the code that we found in zend_execute_API.c inside
// the zend_eval_stringl() function into this file here. However, the code
// found there is full of zval manipulation, for which we can use the much
// simpler Php::Value object
Php::Value source(phpcode, size);
// remember the old compiler options, and set new compiler options
CompilerOptions options(ZEND_COMPILE_DEFAULT_FOR_EVAL);
// we need the tsrm_ls variable
TSRMLS_FETCH();
// compile the string
_opcodes = zend_compile_string(source._val, (char *)name TSRMLS_CC);
}
/**
* Destructor
*/
Script::~Script()
{
// do nothing if there are no opcodes
if (!_opcodes) return;
// clean up opcodes
destroy_op_array(_opcodes TSRMLS_CC);
efree(_opcodes);
}
/**
* Execute a script
* @return Value
*/
Value Script::execute() const
{
// if the script could not be compiled, we return null
if (!_opcodes) return nullptr;
// pointer that is going to hold the return value of the script
zval *retval_ptr = nullptr;
// the zend engine is probably already busy processing opcodes, so we store
// the current execute state before we're going to switch the runtime to
// our own set of opcodes
ExecuteState oldstate;
// old execute state has been saved (and will automatically be restured when
// the oldstate is destructed), so we can now safely overwrite all the settings
EG(return_value_ptr_ptr) = &retval_ptr;
EG(active_op_array) = _opcodes;
EG(no_extensions) = 1;
if (!EG(active_symbol_table)) zend_rebuild_symbol_table(TSRMLS_C);
CG(interactive) = 0;
// this code was copied from zend_execute_API.c. this is what I think it does:
// the zend_execute() call could result in all sort of disastrous things, one
// of them is a full crash of the executing script. if that happens, the zend
// engine does a long jump right up to some other point in the code. the
// 'zend_try' and 'zend_catch' macros prevent this: they install a new
// destination for the long jump, so that we can catch a failure
zend_try
{
// the current exception
zval* oldException = EG(exception);
// execute the code
zend_execute(_opcodes TSRMLS_CC);
// was an exception thrown inside the eval()'ed code? In that case we
// throw a C++ new exception to give the C++ code the chance to catch it
if (oldException != EG(exception) && EG(exception)) throw OrigException(EG(exception) TSRMLS_CC);
}
zend_catch
{
// the code could not be executed, and the zend engine is in big
// trouble now, in the original code the _opcodes are efree'd, but here
// we can just as well continue with the real bailout (the zend_try/
// zend_catch pair was maybe not even necessary???)
zend_bailout();
}
zend_end_try();
// we're ready if there is no return value
if (!retval_ptr) return nullptr;
// copy the pointer into a value object, and return that
return retval_ptr;
}
/**
* End of namespace
*/
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkMinimumMaximumImageCalculatorTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2001 Insight Consortium
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.
* The name of the Insight Consortium, nor the names of any consortium members,
nor of any contributors, may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 AUTHORS 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 "itkImage.h"
#include "itkMinimumMaximumImageCalculator.h"
#include "itkSize.h"
typedef itk::Size<3> SizeType;
typedef itk::Image<short, 3> ImageType;
typedef itk::MinimumMaximumImageCalculator<ImageType> MinMaxCalculatorType;
/* Define the image size and physical coordinates */
SizeType size = {{20, 20, 20}};
double origin [3] = { 0.0, 0.0, 0.0};
double spacing[3] = { 1, 1 , 1};
int
main(int argc,char *argv[])
{
int flag = 0; /* Did this test program work? */
std::cout << "Testing Minimum and Maximum Image Calulator:\n";
/* Allocate a simple test image */
ImageType::Pointer image = ImageType::New();
ImageType::RegionType region;
region.SetSize(size);
image->SetLargestPossibleRegion(region);
image->SetRequestedRegion(region);
image->SetBufferedRegion(region);
image->Allocate();
/* Set origin and spacing of physical coordinates */
image->SetOrigin(origin);
image->SetSpacing(spacing);
short minimum = -52;
short maximum = 103;
/* Initialize the image contents with the minimum value*/
itk::Index<3> index;
for (int slice = 0; slice < 20; slice++) {
index[2] = slice;
for (int row = 0; row <20; row++) {
index[1] = row;
for (int col = 0; col < 20; col++) {
index[0] = col;
image->SetPixel(index, minimum);
}
}
}
/* Set voxel (10,10,10) to maximum value*/
index[0] = 10;
index[1] = 10;
index[2] = 10;
image->SetPixel(index, maximum);
/* Create and initialize the calculator */
MinMaxCalculatorType::Pointer calculator = MinMaxCalculatorType::New();
calculator->SetImage(image);
calculator->Compute();
/* Return minimum of intensity */
short minimumResult = calculator->GetMinimum();
std::cout << "The Minimum intensity value is : " << minimumResult << std::endl;
if(minimumResult != minimum)
{
std::cout << "Minimum Value is wrong : " << minimumResult ;
std::cout << " != " << minimum << std::endl;
flag = 1;
}
/* Return maximum of intensity */
short maximumResult = calculator->GetMaximum();
std::cout << "The Maximum intensity value is : " << maximumResult << std::endl;
if(maximumResult != maximum)
{
std::cout << "Maximum Value is wrong : " << maximumResult ;
std::cout << " != " << maximum << std::endl;
flag = 2;
}
/* Return results of test */
if (flag != 0) {
std::cout << "*** Some tests failed" << std::endl;
return flag; }
else {
std::cout << "All tests successfully passed" << std::endl;
return 0; }
}
<commit_msg>ENH: added print.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkMinimumMaximumImageCalculatorTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2001 Insight Consortium
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.
* The name of the Insight Consortium, nor the names of any consortium members,
nor of any contributors, may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 AUTHORS 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 "itkImage.h"
#include "itkMinimumMaximumImageCalculator.h"
#include "itkSize.h"
typedef itk::Size<3> SizeType;
typedef itk::Image<short, 3> ImageType;
typedef itk::MinimumMaximumImageCalculator<ImageType> MinMaxCalculatorType;
/* Define the image size and physical coordinates */
SizeType size = {{20, 20, 20}};
double origin [3] = { 0.0, 0.0, 0.0};
double spacing[3] = { 1, 1 , 1};
int
main(int argc,char *argv[])
{
int flag = 0; /* Did this test program work? */
std::cout << "Testing Minimum and Maximum Image Calulator:\n";
/* Allocate a simple test image */
ImageType::Pointer image = ImageType::New();
ImageType::RegionType region;
region.SetSize(size);
image->SetLargestPossibleRegion(region);
image->SetRequestedRegion(region);
image->SetBufferedRegion(region);
image->Allocate();
/* Set origin and spacing of physical coordinates */
image->SetOrigin(origin);
image->SetSpacing(spacing);
short minimum = -52;
short maximum = 103;
/* Initialize the image contents with the minimum value*/
itk::Index<3> index;
for (int slice = 0; slice < 20; slice++) {
index[2] = slice;
for (int row = 0; row <20; row++) {
index[1] = row;
for (int col = 0; col < 20; col++) {
index[0] = col;
image->SetPixel(index, minimum);
}
}
}
/* Set voxel (10,10,10) to maximum value*/
index[0] = 10;
index[1] = 10;
index[2] = 10;
image->SetPixel(index, maximum);
/* Create and initialize the calculator */
MinMaxCalculatorType::Pointer calculator = MinMaxCalculatorType::New();
calculator->SetImage(image);
calculator->Compute();
std::cout << "calculator: " << calculator;
/* Return minimum of intensity */
short minimumResult = calculator->GetMinimum();
std::cout << "The Minimum intensity value is : " << minimumResult << std::endl;
if(minimumResult != minimum)
{
std::cout << "Minimum Value is wrong : " << minimumResult ;
std::cout << " != " << minimum << std::endl;
flag = 1;
}
/* Return maximum of intensity */
short maximumResult = calculator->GetMaximum();
std::cout << "The Maximum intensity value is : " << maximumResult << std::endl;
if(maximumResult != maximum)
{
std::cout << "Maximum Value is wrong : " << maximumResult ;
std::cout << " != " << maximum << std::endl;
flag = 2;
}
/* Return results of test */
if (flag != 0) {
std::cout << "*** Some tests failed" << std::endl;
return flag; }
else {
std::cout << "All tests successfully passed" << std::endl;
return 0; }
}
<|endoftext|>
|
<commit_before>// Test the mmap_limit_mb flag.
//
// RUN: %clangxx_asan -O2 %s -o %t
// RUN: %run %t 100 16
// RUN: %run %t 100 1000000
// RUN: env ASAN_OPTIONS=mmap_limit_mb=500 %run %t 50 16
// RUN: env ASAN_OPTIONS=mmap_limit_mb=500 %run %t 50 1000000
// RUN: env ASAN_OPTIONS=mmap_limit_mb=500 not %run %t 500 16 2>&1 | FileCheck %s
// RUN: env ASAN_OPTIONS=mmap_limit_mb=500 not %run %t 500 1000000 2>&1 | FileCheck %s
// XFAIL: arm-linux-gnueabi
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <algorithm>
#include <vector>
int main(int argc, char **argv) {
assert(argc == 3);
long total_mb = atoi(argv[1]);
long allocation_size = atoi(argv[2]);
fprintf(stderr, "total_mb: %zd allocation_size: %zd\n", total_mb,
allocation_size);
std::vector<char *> v;
for (long total = total_mb << 20; total > 0; total -= allocation_size)
v.push_back(new char[allocation_size]);
for (std::vector<char *>::const_iterator it = v.begin(); it != v.end(); ++it)
delete[](*it);
fprintf(stderr, "PASS\n");
// CHECK: total_mmaped{{.*}}mmap_limit_mb
return 0;
}
<commit_msg>[asan] Tune down mmap_limit_mb test.<commit_after>// Test the mmap_limit_mb flag.
//
// RUN: %clangxx_asan -O2 %s -o %t
// RUN: %run %t 20 16
// RUN: %run %t 30 1000000
// RUN: env ASAN_OPTIONS=mmap_limit_mb=150 %run %t 20 16
// RUN: env ASAN_OPTIONS=mmap_limit_mb=150 %run %t 20 1000000
// RUN: env ASAN_OPTIONS=mmap_limit_mb=150 not %run %t 500 16 2>&1 | FileCheck %s
// RUN: env ASAN_OPTIONS=mmap_limit_mb=150 not %run %t 500 1000000 2>&1 | FileCheck %s
// XFAIL: arm-linux-gnueabi
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <algorithm>
#include <vector>
int main(int argc, char **argv) {
assert(argc == 3);
long total_mb = atoi(argv[1]);
long allocation_size = atoi(argv[2]);
fprintf(stderr, "total_mb: %zd allocation_size: %zd\n", total_mb,
allocation_size);
std::vector<char *> v;
for (long total = total_mb << 20; total > 0; total -= allocation_size)
v.push_back(new char[allocation_size]);
for (std::vector<char *>::const_iterator it = v.begin(); it != v.end(); ++it)
delete[](*it);
fprintf(stderr, "PASS\n");
// CHECK: total_mmaped{{.*}}mmap_limit_mb
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Native Client Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "native_client/tests/ppapi_test_lib/get_browser_interface.h"
#include "native_client/tests/ppapi_test_lib/test_interface.h"
#include "native_client/src/shared/platform/nacl_check.h"
#include "ppapi/c/ppb_core.h"
#include "ppapi/c/ppb_file_system.h"
#include "ppapi/c/ppb_url_request_info.h"
#include "ppapi/c/pp_errors.h"
namespace {
void OpenCallback(void* /*data*/, int32_t /*result*/) {
}
const PP_FileSystemType kFileSystemTypes[] = {
PP_FILESYSTEMTYPE_EXTERNAL,
PP_FILESYSTEMTYPE_LOCALPERSISTENT,
PP_FILESYSTEMTYPE_LOCALTEMPORARY
};
const size_t kNumFileSystemTypes =
sizeof(kFileSystemTypes) / sizeof(kFileSystemTypes[0]);
void TestCreate() {
PP_Resource file_system = kInvalidResource;
const PPB_FileSystem* ppb_file_system = PPBFileSystem();
// Test to see if PPB_FileSystem::Create returns PP_Resource value of 0
// if the instance parameter is invalid.
file_system = ppb_file_system->Create(kInvalidInstance,
PP_FILESYSTEMTYPE_EXTERNAL);
EXPECT(file_system == kInvalidResource);
file_system = ppb_file_system->Create(kInvalidInstance,
PP_FILESYSTEMTYPE_LOCALPERSISTENT);
EXPECT(file_system == kInvalidResource);
file_system = ppb_file_system->Create(kInvalidInstance,
PP_FILESYSTEMTYPE_LOCALTEMPORARY);
EXPECT(file_system == kInvalidResource);
// Test for failure when an invalid file system type is requested.
file_system = ppb_file_system->Create(pp_instance(),
PP_FILESYSTEMTYPE_INVALID);
EXPECT(file_system == kInvalidResource);
// Test to see if PPB_FileSystem::Create returns a valid PP_Resource
// value when given a valid PP_Instance value parameter. Test for all
// three file system types PPB_FileSystem supports.
for (size_t i = 0; i < kNumFileSystemTypes; ++i) {
file_system = ppb_file_system->Create(pp_instance(), kFileSystemTypes[i]);
EXPECT(file_system != kInvalidResource);
PPBCore()->ReleaseResource(file_system);
}
TEST_PASSED;
}
void TestIsFileSystem() {
const PPB_Core* ppb_core = PPBCore();
const PPB_FileSystem* ppb_file_system = PPBFileSystem();
PP_Resource file_system = kInvalidResource;
PP_Bool is_file_system = PP_FALSE;
// Test fail for invalid resource.
EXPECT(ppb_file_system->IsFileSystem(kInvalidResource) != PP_TRUE);
// Test pass for the different valid system types, and test fail against a
// resource that has been released.
for (size_t i = 0; i < kNumFileSystemTypes; ++i) {
file_system = ppb_file_system->Create(pp_instance(), kFileSystemTypes[i]);
CHECK(file_system != kInvalidResource);
is_file_system = ppb_file_system->IsFileSystem(file_system);
ppb_core->ReleaseResource(file_system);
EXPECT(is_file_system == PP_TRUE);
is_file_system = ppb_file_system->IsFileSystem(file_system);
EXPECT(is_file_system == PP_FALSE);
}
// Test fail against a non-filesystem resource.
PP_Resource url_request_info = PPBURLRequestInfo()->Create(pp_instance());
CHECK(url_request_info != kInvalidResource);
is_file_system = ppb_file_system->IsFileSystem(url_request_info);
ppb_core->ReleaseResource(url_request_info);
EXPECT(is_file_system == PP_FALSE);
TEST_PASSED;
}
void TestOpen() {
const PPB_Core* ppb_core = PPBCore();
const PPB_FileSystem* ppb_file_system = PPBFileSystem();
PP_Resource file_system = kInvalidResource;
PP_CompletionCallback nop_callback =
MakeTestableCompletionCallback("NopCallback", OpenCallback);
PP_CompletionCallback open_callback =
MakeTestableCompletionCallback("OpenCallback", OpenCallback, NULL);
int32_t pp_error = PP_ERROR_FAILED;
int64_t kSize = 1024; // Dummy value.
// Test to make sure opening an invalid file system fails.
pp_error = ppb_file_system->Open(kInvalidResource, kSize, nop_callback);
EXPECT(pp_error == PP_ERROR_BADRESOURCE);
// Test to make sure external file system is not supported.
// TODO(sanga): Once Chrome supports external file systems, change this test
// to reflect the change.
file_system = ppb_file_system->Create(pp_instance(),
PP_FILESYSTEMTYPE_EXTERNAL);
pp_error = ppb_file_system->Open(file_system, kSize, nop_callback);
ppb_core->ReleaseResource(file_system);
EXPECT(pp_error == PP_ERROR_FAILED);
// Test local temporary and local persistant file systems.
for (size_t i = 1; i < kNumFileSystemTypes; ++i) {
#ifdef __native_client__
// Test fail for blocking open.
//
// Only conduct this test with nexe. Trusted ppapi plugin does not work
// with synchronous Open call.
// See http://code.google.com/p/chromium/issues/detail?id=78449
file_system = ppb_file_system->Create(pp_instance(), kFileSystemTypes[i]);
pp_error = ppb_file_system->Open(file_system, kSize,
PP_BlockUntilComplete());
ppb_core->ReleaseResource(file_system);
EXPECT(pp_error == PP_ERROR_BADARGUMENT);
#endif
// Test success for asynchronous open.
file_system = ppb_file_system->Create(pp_instance(), kFileSystemTypes[i]);
pp_error = ppb_file_system->Open(file_system, kSize, open_callback);
ppb_core->ReleaseResource(file_system);
EXPECT(pp_error == PP_OK_COMPLETIONPENDING);
open_callback =
MakeTestableCompletionCallback("OpenCallback", OpenCallback);
// Test fail for multiple opens.
file_system = ppb_file_system->Create(pp_instance(), kFileSystemTypes[i]);
pp_error = ppb_file_system->Open(file_system, kSize, open_callback);
CHECK(pp_error == PP_OK_COMPLETIONPENDING); // Previously tested.
pp_error = ppb_file_system->Open(file_system, kSize, nop_callback);
ppb_core->ReleaseResource(file_system);
// TODO(polina, sanga): take out PP_ERROR_FAILED when chrome is fixed.
EXPECT(pp_error == PP_ERROR_FAILED || pp_error == PP_ERROR_INPROGRESS);
}
TEST_PASSED;
}
void TestGetType() {
const PPB_Core* ppb_core = PPBCore();
const PPB_FileSystem* ppb_file_system = PPBFileSystem();
PP_Resource file_system = kInvalidResource;
PP_FileSystemType type = PP_FILESYSTEMTYPE_INVALID;
// Test for invalid resource.
EXPECT(PP_FILESYSTEMTYPE_INVALID == ppb_file_system->GetType(0));
// Test pass for the different valid system types.
for (size_t i = 0; i < kNumFileSystemTypes; ++i) {
file_system = ppb_file_system->Create(pp_instance(), kFileSystemTypes[i]);
CHECK(file_system != kInvalidResource);
type = ppb_file_system->GetType(file_system);
ppb_core->ReleaseResource(file_system);
EXPECT(type == kFileSystemTypes[i]);
}
// Test fail against a non-filesystem resource.
PP_Resource url_request_info = PPBURLRequestInfo()->Create(pp_instance());
CHECK(url_request_info != kInvalidResource);
type = ppb_file_system->GetType(url_request_info);
ppb_core->ReleaseResource(url_request_info);
EXPECT(type == PP_FILESYSTEMTYPE_INVALID);
TEST_PASSED;
}
} // namespace
void SetupTests() {
RegisterTest("TestCreate", TestCreate);
RegisterTest("TestIsFileSystem", TestIsFileSystem);
RegisterTest("TestOpen", TestOpen);
RegisterTest("TestGetType", TestGetType);
}
void SetupPluginInterfaces() {
/* No PPP interface to test. */
}
<commit_msg>Made a fix so TestOpen does not release the file system right after calling Open, instead passing the resource as user data to the open callback to be released.<commit_after>// Copyright (c) 2011 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 "native_client/tests/ppapi_test_lib/get_browser_interface.h"
#include "native_client/tests/ppapi_test_lib/test_interface.h"
#include "native_client/src/shared/platform/nacl_check.h"
#include "ppapi/c/ppb_core.h"
#include "ppapi/c/ppb_file_system.h"
#include "ppapi/c/ppb_url_request_info.h"
#include "ppapi/c/pp_errors.h"
namespace {
struct OpenCallbackData {
explicit OpenCallbackData(PP_Resource file_system)
: file_system(file_system) {}
PP_Resource file_system;
};
void OpenCallback(void* data, int32_t result) {
EXPECT(result == PP_OK);
OpenCallbackData* callback_data = reinterpret_cast<OpenCallbackData*>(data);
PPBCore()->ReleaseResource(callback_data->file_system);
delete callback_data;
}
const PP_FileSystemType kFileSystemTypes[] = {
PP_FILESYSTEMTYPE_EXTERNAL,
PP_FILESYSTEMTYPE_LOCALPERSISTENT,
PP_FILESYSTEMTYPE_LOCALTEMPORARY
};
const size_t kNumFileSystemTypes =
sizeof(kFileSystemTypes) / sizeof(kFileSystemTypes[0]);
void TestCreate() {
PP_Resource file_system = kInvalidResource;
const PPB_FileSystem* ppb_file_system = PPBFileSystem();
// Test to see if PPB_FileSystem::Create returns PP_Resource value of 0
// if the instance parameter is invalid.
file_system = ppb_file_system->Create(kInvalidInstance,
PP_FILESYSTEMTYPE_EXTERNAL);
EXPECT(file_system == kInvalidResource);
file_system = ppb_file_system->Create(kInvalidInstance,
PP_FILESYSTEMTYPE_LOCALPERSISTENT);
EXPECT(file_system == kInvalidResource);
file_system = ppb_file_system->Create(kInvalidInstance,
PP_FILESYSTEMTYPE_LOCALTEMPORARY);
EXPECT(file_system == kInvalidResource);
// Test for failure when an invalid file system type is requested.
file_system = ppb_file_system->Create(pp_instance(),
PP_FILESYSTEMTYPE_INVALID);
EXPECT(file_system == kInvalidResource);
// Test to see if PPB_FileSystem::Create returns a valid PP_Resource
// value when given a valid PP_Instance value parameter. Test for all
// three file system types PPB_FileSystem supports.
for (size_t i = 0; i < kNumFileSystemTypes; ++i) {
file_system = ppb_file_system->Create(pp_instance(), kFileSystemTypes[i]);
EXPECT(file_system != kInvalidResource);
PPBCore()->ReleaseResource(file_system);
}
TEST_PASSED;
}
void TestIsFileSystem() {
const PPB_Core* ppb_core = PPBCore();
const PPB_FileSystem* ppb_file_system = PPBFileSystem();
PP_Resource file_system = kInvalidResource;
PP_Bool is_file_system = PP_FALSE;
// Test fail for invalid resource.
EXPECT(ppb_file_system->IsFileSystem(kInvalidResource) != PP_TRUE);
// Test pass for the different valid system types, and test fail against a
// resource that has been released.
for (size_t i = 0; i < kNumFileSystemTypes; ++i) {
file_system = ppb_file_system->Create(pp_instance(), kFileSystemTypes[i]);
CHECK(file_system != kInvalidResource);
is_file_system = ppb_file_system->IsFileSystem(file_system);
ppb_core->ReleaseResource(file_system);
EXPECT(is_file_system == PP_TRUE);
is_file_system = ppb_file_system->IsFileSystem(file_system);
EXPECT(is_file_system == PP_FALSE);
}
// Test fail against a non-filesystem resource.
PP_Resource url_request_info = PPBURLRequestInfo()->Create(pp_instance());
CHECK(url_request_info != kInvalidResource);
is_file_system = ppb_file_system->IsFileSystem(url_request_info);
ppb_core->ReleaseResource(url_request_info);
EXPECT(is_file_system == PP_FALSE);
TEST_PASSED;
}
void TestOpen() {
const PPB_Core* ppb_core = PPBCore();
const PPB_FileSystem* ppb_file_system = PPBFileSystem();
static PP_Resource file_system = kInvalidResource;
PP_CompletionCallback nop_callback =
MakeTestableCompletionCallback("NopCallback", OpenCallback);
int32_t pp_error = PP_ERROR_FAILED;
int64_t kSize = 1024; // Dummy value.
// Test to make sure opening an invalid file system fails.
pp_error = ppb_file_system->Open(kInvalidResource, kSize, nop_callback);
EXPECT(pp_error == PP_ERROR_BADRESOURCE);
// Test to make sure external file system is not supported.
// TODO(sanga): Once Chrome supports external file systems, change this test
// to reflect the change.
file_system = ppb_file_system->Create(pp_instance(),
PP_FILESYSTEMTYPE_EXTERNAL);
pp_error = ppb_file_system->Open(file_system, kSize, nop_callback);
ppb_core->ReleaseResource(file_system);
EXPECT(pp_error == PP_ERROR_FAILED);
// Test local temporary and local persistant file systems.
for (size_t i = 1; i < kNumFileSystemTypes; ++i) {
#ifdef __native_client__
// Test fail for blocking open.
//
// Only conduct this test with nexe. Trusted ppapi plugin does not work
// with synchronous Open call.
// See http://code.google.com/p/chromium/issues/detail?id=78449
file_system = ppb_file_system->Create(pp_instance(), kFileSystemTypes[i]);
pp_error = ppb_file_system->Open(file_system, kSize,
PP_BlockUntilComplete());
ppb_core->ReleaseResource(file_system);
EXPECT(pp_error == PP_ERROR_BADARGUMENT);
#endif
// Test success for asynchronous open.
file_system = ppb_file_system->Create(pp_instance(), kFileSystemTypes[i]);
OpenCallbackData* callback_data = new OpenCallbackData(file_system);
PP_CompletionCallback open_callback = MakeTestableCompletionCallback(
"OpenCallback", OpenCallback, callback_data);
pp_error = ppb_file_system->Open(file_system, kSize, open_callback);
EXPECT(pp_error == PP_OK_COMPLETIONPENDING);
// Test fail for multiple opens.
file_system = ppb_file_system->Create(pp_instance(), kFileSystemTypes[i]);
callback_data = new OpenCallbackData(file_system);
open_callback = MakeTestableCompletionCallback(
"OpenCallback", OpenCallback, callback_data);
pp_error = ppb_file_system->Open(file_system, kSize, open_callback);
CHECK(pp_error == PP_OK_COMPLETIONPENDING); // Previously tested.
pp_error = ppb_file_system->Open(file_system, kSize, nop_callback);
EXPECT(pp_error == PP_ERROR_INPROGRESS);
}
TEST_PASSED;
}
void TestGetType() {
const PPB_Core* ppb_core = PPBCore();
const PPB_FileSystem* ppb_file_system = PPBFileSystem();
PP_Resource file_system = kInvalidResource;
PP_FileSystemType type = PP_FILESYSTEMTYPE_INVALID;
// Test for invalid resource.
EXPECT(PP_FILESYSTEMTYPE_INVALID == ppb_file_system->GetType(0));
// Test pass for the different valid system types.
for (size_t i = 0; i < kNumFileSystemTypes; ++i) {
file_system = ppb_file_system->Create(pp_instance(), kFileSystemTypes[i]);
CHECK(file_system != kInvalidResource);
type = ppb_file_system->GetType(file_system);
ppb_core->ReleaseResource(file_system);
EXPECT(type == kFileSystemTypes[i]);
}
// Test fail against a non-filesystem resource.
PP_Resource url_request_info = PPBURLRequestInfo()->Create(pp_instance());
CHECK(url_request_info != kInvalidResource);
type = ppb_file_system->GetType(url_request_info);
ppb_core->ReleaseResource(url_request_info);
EXPECT(type == PP_FILESYSTEMTYPE_INVALID);
TEST_PASSED;
}
} // namespace
void SetupTests() {
RegisterTest("TestCreate", TestCreate);
RegisterTest("TestIsFileSystem", TestIsFileSystem);
RegisterTest("TestOpen", TestOpen);
RegisterTest("TestGetType", TestGetType);
}
void SetupPluginInterfaces() {
/* No PPP interface to test. */
}
<|endoftext|>
|
<commit_before>/**********************************************************************
* File: serialis.cpp (Formerly serialmac.h)
* Description: Inline routines and macros for serialisation functions
* Author: Phil Cheatle
*
* (C) Copyright 1990, Hewlett-Packard 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 "errcode.h"
#include <tesseract/helpers.h> // for ReverseN
#include "serialis.h"
#include <cstdio>
namespace tesseract {
// The default FileReader loads the whole file into the vector of char,
// returning false on error.
bool LoadDataFromFile(const char* filename, std::vector<char>* data) {
bool result = false;
FILE* fp = fopen(filename, "rb");
if (fp != nullptr) {
fseek(fp, 0, SEEK_END);
auto size = std::ftell(fp);
fseek(fp, 0, SEEK_SET);
// Trying to open a directory on Linux sets size to LONG_MAX. Catch it here.
if (size > 0 && size < LONG_MAX) {
// reserve an extra byte in case caller wants to append a '\0' character
data->reserve(size + 1);
data->resize(size); // TODO: optimize no init
result = static_cast<long>(fread(&(*data)[0], 1, size, fp)) == size;
}
fclose(fp);
}
return result;
}
// The default FileWriter writes the vector of char to the filename file,
// returning false on error.
bool SaveDataToFile(const std::vector<char>& data, const char* filename) {
FILE* fp = fopen(filename, "wb");
if (fp == nullptr) {
return false;
}
bool result =
static_cast<int>(fwrite(&data[0], 1, data.size(), fp)) == data.size();
fclose(fp);
return result;
}
bool DeSerialize(FILE* fp, char* data, size_t n) {
return fread(data, sizeof(*data), n, fp) == n;
}
bool DeSerialize(FILE* fp, float* data, size_t n) {
return fread(data, sizeof(*data), n, fp) == n;
}
bool DeSerialize(FILE* fp, int8_t* data, size_t n) {
return fread(data, sizeof(*data), n, fp) == n;
}
bool DeSerialize(FILE* fp, int16_t* data, size_t n) {
return fread(data, sizeof(*data), n, fp) == n;
}
bool DeSerialize(FILE* fp, int32_t* data, size_t n) {
return fread(data, sizeof(*data), n, fp) == n;
}
bool DeSerialize(FILE* fp, uint8_t* data, size_t n) {
return fread(data, sizeof(*data), n, fp) == n;
}
bool DeSerialize(FILE* fp, uint16_t* data, size_t n) {
return fread(data, sizeof(*data), n, fp) == n;
}
bool DeSerialize(FILE* fp, uint32_t* data, size_t n) {
return fread(data, sizeof(*data), n, fp) == n;
}
bool Serialize(FILE* fp, const char* data, size_t n) {
return fwrite(data, sizeof(*data), n, fp) == n;
}
bool Serialize(FILE* fp, const float* data, size_t n) {
return fwrite(data, sizeof(*data), n, fp) == n;
}
bool Serialize(FILE* fp, const int8_t* data, size_t n) {
return fwrite(data, sizeof(*data), n, fp) == n;
}
bool Serialize(FILE* fp, const int16_t* data, size_t n) {
return fwrite(data, sizeof(*data), n, fp) == n;
}
bool Serialize(FILE* fp, const int32_t* data, size_t n) {
return fwrite(data, sizeof(*data), n, fp) == n;
}
bool Serialize(FILE* fp, const uint8_t* data, size_t n) {
return fwrite(data, sizeof(*data), n, fp) == n;
}
bool Serialize(FILE* fp, const uint16_t* data, size_t n) {
return fwrite(data, sizeof(*data), n, fp) == n;
}
bool Serialize(FILE* fp, const uint32_t* data, size_t n) {
return fwrite(data, sizeof(*data), n, fp) == n;
}
TFile::TFile()
: data_(nullptr),
offset_(0),
data_is_owned_(false),
is_writing_(false),
swap_(false) {}
TFile::~TFile() {
if (data_is_owned_)
delete data_;
}
bool TFile::DeSerialize(std::vector<char>& data) {
uint32_t size;
if (!DeSerialize(&size)) {
return false;
}
// TODO: optimize.
data.resize(size);
return DeSerialize(&data[0], data.size());
}
bool TFile::DeSerialize(char* buffer, size_t count) {
return FRead(buffer, sizeof(*buffer), count) == count;
}
bool TFile::DeSerialize(double* buffer, size_t count) {
return FReadEndian(buffer, sizeof(*buffer), count) == count;
}
bool TFile::DeSerialize(float* buffer, size_t count) {
return FReadEndian(buffer, sizeof(*buffer), count) == count;
}
bool TFile::DeSerialize(int8_t* buffer, size_t count) {
return FRead(buffer, sizeof(*buffer), count) == count;
}
bool TFile::DeSerialize(int16_t* buffer, size_t count) {
return FReadEndian(buffer, sizeof(*buffer), count) == count;
}
bool TFile::DeSerialize(int32_t* buffer, size_t count) {
return FReadEndian(buffer, sizeof(*buffer), count) == count;
}
bool TFile::DeSerialize(int64_t* buffer, size_t count) {
return FReadEndian(buffer, sizeof(*buffer), count) == count;
}
bool TFile::DeSerialize(uint8_t* buffer, size_t count) {
return FRead(buffer, sizeof(*buffer), count) == count;
}
bool TFile::DeSerialize(uint16_t* buffer, size_t count) {
return FReadEndian(buffer, sizeof(*buffer), count) == count;
}
bool TFile::DeSerialize(uint32_t* buffer, size_t count) {
return FReadEndian(buffer, sizeof(*buffer), count) == count;
}
bool TFile::DeSerialize(uint64_t* buffer, size_t count) {
return FReadEndian(buffer, sizeof(*buffer), count) == count;
}
bool TFile::Serialize(const std::vector<char>& data) {
uint32_t size = data.size();
if (!Serialize(&size)) {
return false;
}
return Serialize(&data[0], size);
}
bool TFile::Serialize(const char* buffer, size_t count) {
return FWrite(buffer, sizeof(*buffer), count) == count;
}
bool TFile::Serialize(const double* buffer, size_t count) {
return FWrite(buffer, sizeof(*buffer), count) == count;
}
bool TFile::Serialize(const float* buffer, size_t count) {
return FWrite(buffer, sizeof(*buffer), count) == count;
}
bool TFile::Serialize(const int8_t* buffer, size_t count) {
return FWrite(buffer, sizeof(*buffer), count) == count;
}
bool TFile::Serialize(const int16_t* buffer, size_t count) {
return FWrite(buffer, sizeof(*buffer), count) == count;
}
bool TFile::Serialize(const int32_t* buffer, size_t count) {
return FWrite(buffer, sizeof(*buffer), count) == count;
}
bool TFile::Serialize(const int64_t* buffer, size_t count) {
return FWrite(buffer, sizeof(*buffer), count) == count;
}
bool TFile::Serialize(const uint8_t* buffer, size_t count) {
return FWrite(buffer, sizeof(*buffer), count) == count;
}
bool TFile::Serialize(const uint16_t* buffer, size_t count) {
return FWrite(buffer, sizeof(*buffer), count) == count;
}
bool TFile::Serialize(const uint32_t* buffer, size_t count) {
return FWrite(buffer, sizeof(*buffer), count) == count;
}
bool TFile::Serialize(const uint64_t* buffer, size_t count) {
return FWrite(buffer, sizeof(*buffer), count) == count;
}
bool TFile::Skip(size_t count) {
offset_ += count;
return true;
}
bool TFile::Open(const char* filename, FileReader reader) {
if (!data_is_owned_) {
data_ = new std::vector<char>;
data_is_owned_ = true;
}
offset_ = 0;
is_writing_ = false;
swap_ = false;
if (reader == nullptr)
return LoadDataFromFile(filename, data_);
else
return (*reader)(filename, data_);
}
bool TFile::Open(const char* data, int size) {
offset_ = 0;
if (!data_is_owned_) {
data_ = new std::vector<char>;
data_is_owned_ = true;
}
is_writing_ = false;
swap_ = false;
data_->resize(size); // TODO: optimize no init
memcpy(&(*data_)[0], data, size);
return true;
}
bool TFile::Open(FILE* fp, int64_t end_offset) {
offset_ = 0;
auto current_pos = std::ftell(fp);
if (current_pos < 0) {
// ftell failed.
return false;
}
if (end_offset < 0) {
if (fseek(fp, 0, SEEK_END))
return false;
end_offset = ftell(fp);
if (fseek(fp, current_pos, SEEK_SET))
return false;
}
int size = end_offset - current_pos;
is_writing_ = false;
swap_ = false;
if (!data_is_owned_) {
data_ = new std::vector<char>;
data_is_owned_ = true;
}
data_->resize(size); // TODO: optimize no init
return static_cast<int>(fread(&(*data_)[0], 1, size, fp)) == size;
}
char* TFile::FGets(char* buffer, int buffer_size) {
ASSERT_HOST(!is_writing_);
int size = 0;
while (size + 1 < buffer_size && offset_ < data_->size()) {
buffer[size++] = (*data_)[offset_++];
if ((*data_)[offset_ - 1] == '\n') break;
}
if (size < buffer_size) buffer[size] = '\0';
return size > 0 ? buffer : nullptr;
}
int TFile::FReadEndian(void* buffer, size_t size, int count) {
int num_read = FRead(buffer, size, count);
if (swap_) {
char* char_buffer = static_cast<char*>(buffer);
for (int i = 0; i < num_read; ++i, char_buffer += size) {
ReverseN(char_buffer, size);
}
}
return num_read;
}
int TFile::FRead(void* buffer, size_t size, int count) {
ASSERT_HOST(!is_writing_);
ASSERT_HOST(size > 0);
ASSERT_HOST(count >= 0);
size_t required_size;
if (SIZE_MAX / size <= count) {
// Avoid integer overflow.
required_size = data_->size() - offset_;
} else {
required_size = size * count;
if (data_->size() - offset_ < required_size) {
required_size = data_->size() - offset_;
}
}
if (required_size > 0 && buffer != nullptr)
memcpy(buffer, &(*data_)[offset_], required_size);
offset_ += required_size;
return required_size / size;
}
void TFile::Rewind() {
ASSERT_HOST(!is_writing_);
offset_ = 0;
}
void TFile::OpenWrite(std::vector<char>* data) {
offset_ = 0;
if (data != nullptr) {
if (data_is_owned_) delete data_;
data_ = data;
data_is_owned_ = false;
} else if (!data_is_owned_) {
data_ = new std::vector<char>;
data_is_owned_ = true;
}
is_writing_ = true;
swap_ = false;
data_->resize(0);
}
bool TFile::CloseWrite(const char* filename, FileWriter writer) {
ASSERT_HOST(is_writing_);
if (writer == nullptr)
return SaveDataToFile(*data_, filename);
else
return (*writer)(*data_, filename);
}
int TFile::FWrite(const void* buffer, size_t size, int count) {
ASSERT_HOST(is_writing_);
ASSERT_HOST(size > 0);
ASSERT_HOST(count >= 0);
ASSERT_HOST(SIZE_MAX / size > count);
size_t total = size * count;
const char* buf = static_cast<const char*>(buffer);
// This isn't very efficient, but memory is so fast compared to disk
// that it is relatively unimportant, and very simple.
for (size_t i = 0; i < total; ++i)
data_->push_back(buf[i]);
return count;
}
} // namespace tesseract.
<commit_msg>Fix TFile::DeSerialize, TFile::Serialize for empty vectors<commit_after>/**********************************************************************
* File: serialis.cpp (Formerly serialmac.h)
* Description: Inline routines and macros for serialisation functions
* Author: Phil Cheatle
*
* (C) Copyright 1990, Hewlett-Packard 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 "errcode.h"
#include <tesseract/helpers.h> // for ReverseN
#include "serialis.h"
#include <cstdio>
namespace tesseract {
// The default FileReader loads the whole file into the vector of char,
// returning false on error.
bool LoadDataFromFile(const char* filename, std::vector<char>* data) {
bool result = false;
FILE* fp = fopen(filename, "rb");
if (fp != nullptr) {
fseek(fp, 0, SEEK_END);
auto size = std::ftell(fp);
fseek(fp, 0, SEEK_SET);
// Trying to open a directory on Linux sets size to LONG_MAX. Catch it here.
if (size > 0 && size < LONG_MAX) {
// reserve an extra byte in case caller wants to append a '\0' character
data->reserve(size + 1);
data->resize(size); // TODO: optimize no init
result = static_cast<long>(fread(&(*data)[0], 1, size, fp)) == size;
}
fclose(fp);
}
return result;
}
// The default FileWriter writes the vector of char to the filename file,
// returning false on error.
bool SaveDataToFile(const std::vector<char>& data, const char* filename) {
FILE* fp = fopen(filename, "wb");
if (fp == nullptr) {
return false;
}
bool result =
static_cast<int>(fwrite(&data[0], 1, data.size(), fp)) == data.size();
fclose(fp);
return result;
}
bool DeSerialize(FILE* fp, char* data, size_t n) {
return fread(data, sizeof(*data), n, fp) == n;
}
bool DeSerialize(FILE* fp, float* data, size_t n) {
return fread(data, sizeof(*data), n, fp) == n;
}
bool DeSerialize(FILE* fp, int8_t* data, size_t n) {
return fread(data, sizeof(*data), n, fp) == n;
}
bool DeSerialize(FILE* fp, int16_t* data, size_t n) {
return fread(data, sizeof(*data), n, fp) == n;
}
bool DeSerialize(FILE* fp, int32_t* data, size_t n) {
return fread(data, sizeof(*data), n, fp) == n;
}
bool DeSerialize(FILE* fp, uint8_t* data, size_t n) {
return fread(data, sizeof(*data), n, fp) == n;
}
bool DeSerialize(FILE* fp, uint16_t* data, size_t n) {
return fread(data, sizeof(*data), n, fp) == n;
}
bool DeSerialize(FILE* fp, uint32_t* data, size_t n) {
return fread(data, sizeof(*data), n, fp) == n;
}
bool Serialize(FILE* fp, const char* data, size_t n) {
return fwrite(data, sizeof(*data), n, fp) == n;
}
bool Serialize(FILE* fp, const float* data, size_t n) {
return fwrite(data, sizeof(*data), n, fp) == n;
}
bool Serialize(FILE* fp, const int8_t* data, size_t n) {
return fwrite(data, sizeof(*data), n, fp) == n;
}
bool Serialize(FILE* fp, const int16_t* data, size_t n) {
return fwrite(data, sizeof(*data), n, fp) == n;
}
bool Serialize(FILE* fp, const int32_t* data, size_t n) {
return fwrite(data, sizeof(*data), n, fp) == n;
}
bool Serialize(FILE* fp, const uint8_t* data, size_t n) {
return fwrite(data, sizeof(*data), n, fp) == n;
}
bool Serialize(FILE* fp, const uint16_t* data, size_t n) {
return fwrite(data, sizeof(*data), n, fp) == n;
}
bool Serialize(FILE* fp, const uint32_t* data, size_t n) {
return fwrite(data, sizeof(*data), n, fp) == n;
}
TFile::TFile()
: data_(nullptr),
offset_(0),
data_is_owned_(false),
is_writing_(false),
swap_(false) {}
TFile::~TFile() {
if (data_is_owned_)
delete data_;
}
bool TFile::DeSerialize(std::vector<char>& data) {
uint32_t size;
if (!DeSerialize(&size)) {
return false;
} else if (size > 0) {
// TODO: optimize.
data.resize(size);
return DeSerialize(&data[0], data.size());
}
data.clear();
return true;
}
bool TFile::DeSerialize(char* buffer, size_t count) {
return FRead(buffer, sizeof(*buffer), count) == count;
}
bool TFile::DeSerialize(double* buffer, size_t count) {
return FReadEndian(buffer, sizeof(*buffer), count) == count;
}
bool TFile::DeSerialize(float* buffer, size_t count) {
return FReadEndian(buffer, sizeof(*buffer), count) == count;
}
bool TFile::DeSerialize(int8_t* buffer, size_t count) {
return FRead(buffer, sizeof(*buffer), count) == count;
}
bool TFile::DeSerialize(int16_t* buffer, size_t count) {
return FReadEndian(buffer, sizeof(*buffer), count) == count;
}
bool TFile::DeSerialize(int32_t* buffer, size_t count) {
return FReadEndian(buffer, sizeof(*buffer), count) == count;
}
bool TFile::DeSerialize(int64_t* buffer, size_t count) {
return FReadEndian(buffer, sizeof(*buffer), count) == count;
}
bool TFile::DeSerialize(uint8_t* buffer, size_t count) {
return FRead(buffer, sizeof(*buffer), count) == count;
}
bool TFile::DeSerialize(uint16_t* buffer, size_t count) {
return FReadEndian(buffer, sizeof(*buffer), count) == count;
}
bool TFile::DeSerialize(uint32_t* buffer, size_t count) {
return FReadEndian(buffer, sizeof(*buffer), count) == count;
}
bool TFile::DeSerialize(uint64_t* buffer, size_t count) {
return FReadEndian(buffer, sizeof(*buffer), count) == count;
}
bool TFile::Serialize(const std::vector<char>& data) {
uint32_t size = data.size();
if (!Serialize(&size)) {
return false;
} else if (size > 0) {
return Serialize(&data[0], size);
}
return true;
}
bool TFile::Serialize(const char* buffer, size_t count) {
return FWrite(buffer, sizeof(*buffer), count) == count;
}
bool TFile::Serialize(const double* buffer, size_t count) {
return FWrite(buffer, sizeof(*buffer), count) == count;
}
bool TFile::Serialize(const float* buffer, size_t count) {
return FWrite(buffer, sizeof(*buffer), count) == count;
}
bool TFile::Serialize(const int8_t* buffer, size_t count) {
return FWrite(buffer, sizeof(*buffer), count) == count;
}
bool TFile::Serialize(const int16_t* buffer, size_t count) {
return FWrite(buffer, sizeof(*buffer), count) == count;
}
bool TFile::Serialize(const int32_t* buffer, size_t count) {
return FWrite(buffer, sizeof(*buffer), count) == count;
}
bool TFile::Serialize(const int64_t* buffer, size_t count) {
return FWrite(buffer, sizeof(*buffer), count) == count;
}
bool TFile::Serialize(const uint8_t* buffer, size_t count) {
return FWrite(buffer, sizeof(*buffer), count) == count;
}
bool TFile::Serialize(const uint16_t* buffer, size_t count) {
return FWrite(buffer, sizeof(*buffer), count) == count;
}
bool TFile::Serialize(const uint32_t* buffer, size_t count) {
return FWrite(buffer, sizeof(*buffer), count) == count;
}
bool TFile::Serialize(const uint64_t* buffer, size_t count) {
return FWrite(buffer, sizeof(*buffer), count) == count;
}
bool TFile::Skip(size_t count) {
offset_ += count;
return true;
}
bool TFile::Open(const char* filename, FileReader reader) {
if (!data_is_owned_) {
data_ = new std::vector<char>;
data_is_owned_ = true;
}
offset_ = 0;
is_writing_ = false;
swap_ = false;
if (reader == nullptr)
return LoadDataFromFile(filename, data_);
else
return (*reader)(filename, data_);
}
bool TFile::Open(const char* data, int size) {
offset_ = 0;
if (!data_is_owned_) {
data_ = new std::vector<char>;
data_is_owned_ = true;
}
is_writing_ = false;
swap_ = false;
data_->resize(size); // TODO: optimize no init
memcpy(&(*data_)[0], data, size);
return true;
}
bool TFile::Open(FILE* fp, int64_t end_offset) {
offset_ = 0;
auto current_pos = std::ftell(fp);
if (current_pos < 0) {
// ftell failed.
return false;
}
if (end_offset < 0) {
if (fseek(fp, 0, SEEK_END))
return false;
end_offset = ftell(fp);
if (fseek(fp, current_pos, SEEK_SET))
return false;
}
int size = end_offset - current_pos;
is_writing_ = false;
swap_ = false;
if (!data_is_owned_) {
data_ = new std::vector<char>;
data_is_owned_ = true;
}
data_->resize(size); // TODO: optimize no init
return static_cast<int>(fread(&(*data_)[0], 1, size, fp)) == size;
}
char* TFile::FGets(char* buffer, int buffer_size) {
ASSERT_HOST(!is_writing_);
int size = 0;
while (size + 1 < buffer_size && offset_ < data_->size()) {
buffer[size++] = (*data_)[offset_++];
if ((*data_)[offset_ - 1] == '\n') break;
}
if (size < buffer_size) buffer[size] = '\0';
return size > 0 ? buffer : nullptr;
}
int TFile::FReadEndian(void* buffer, size_t size, int count) {
int num_read = FRead(buffer, size, count);
if (swap_) {
char* char_buffer = static_cast<char*>(buffer);
for (int i = 0; i < num_read; ++i, char_buffer += size) {
ReverseN(char_buffer, size);
}
}
return num_read;
}
int TFile::FRead(void* buffer, size_t size, int count) {
ASSERT_HOST(!is_writing_);
ASSERT_HOST(size > 0);
ASSERT_HOST(count >= 0);
size_t required_size;
if (SIZE_MAX / size <= count) {
// Avoid integer overflow.
required_size = data_->size() - offset_;
} else {
required_size = size * count;
if (data_->size() - offset_ < required_size) {
required_size = data_->size() - offset_;
}
}
if (required_size > 0 && buffer != nullptr)
memcpy(buffer, &(*data_)[offset_], required_size);
offset_ += required_size;
return required_size / size;
}
void TFile::Rewind() {
ASSERT_HOST(!is_writing_);
offset_ = 0;
}
void TFile::OpenWrite(std::vector<char>* data) {
offset_ = 0;
if (data != nullptr) {
if (data_is_owned_) delete data_;
data_ = data;
data_is_owned_ = false;
} else if (!data_is_owned_) {
data_ = new std::vector<char>;
data_is_owned_ = true;
}
is_writing_ = true;
swap_ = false;
data_->resize(0);
}
bool TFile::CloseWrite(const char* filename, FileWriter writer) {
ASSERT_HOST(is_writing_);
if (writer == nullptr)
return SaveDataToFile(*data_, filename);
else
return (*writer)(*data_, filename);
}
int TFile::FWrite(const void* buffer, size_t size, int count) {
ASSERT_HOST(is_writing_);
ASSERT_HOST(size > 0);
ASSERT_HOST(count >= 0);
ASSERT_HOST(SIZE_MAX / size > count);
size_t total = size * count;
const char* buf = static_cast<const char*>(buffer);
// This isn't very efficient, but memory is so fast compared to disk
// that it is relatively unimportant, and very simple.
for (size_t i = 0; i < total; ++i)
data_->push_back(buf[i]);
return count;
}
} // namespace tesseract.
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** 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 "id.h"
#include "coreconstants.h"
#include <utils/qtcassert.h>
#include <QByteArray>
#include <QHash>
#include <QVector>
#include <string.h>
namespace Core {
/*!
\class Core::Id
\brief The class Id encapsulates an identifier that is unique
within a specific running Qt Creator process.
\c{Core::Id} is used as facility to identify objects of interest
in a more typesafe and faster manner than a plain \c QString or
\c QByteArray would provide.
An id is internally represented as a 32 bit integer (its \c UID)
and associated with a be plain 7-bit-clean ASCII name used
for display and persistency.
Each plugin that is distributed as part of Qt Creator has a
private range of 10000 UIDs that are guaranteed to be unique.
Third party plugins are advised to construct ids from their
string representation.
*/
class StringHolder
{
public:
StringHolder()
: n(0), str(0)
{}
StringHolder(const char *s, int length)
: n(length), str(s)
{
if (!n)
length = n = strlen(s);
h = 0;
while (length--) {
h = (h << 4) + *s++;
h ^= (h & 0xf0000000) >> 23;
h &= 0x0fffffff;
}
}
int n;
const char *str;
uint h;
};
static bool operator==(const StringHolder &sh1, const StringHolder &sh2)
{
// sh.n is unlikely to discriminate better than the hash.
return sh1.h == sh2.h && sh1.str && sh2.str && strcmp(sh1.str, sh2.str) == 0;
}
static uint qHash(const StringHolder &sh)
{
return sh.h;
}
struct IdCache : public QHash<StringHolder, int>
{
#ifndef QTC_ALLOW_STATIC_LEAKS
~IdCache()
{
for (IdCache::iterator it = begin(); it != end(); ++it)
delete[](const_cast<char *>(it.key().str));
}
#endif
};
static int firstUnusedId = Id::IdsPerPlugin * Id::ReservedPlugins;
static QHash<int, StringHolder> stringFromId;
static IdCache idFromString;
static int theId(const char *str, int n = 0)
{
QTC_ASSERT(str && *str, return 0);
StringHolder sh(str, n);
int res = idFromString.value(sh, 0);
if (res == 0) {
res = firstUnusedId++;
sh.str = qstrdup(sh.str);
idFromString[sh] = res;
stringFromId[res] = sh;
}
return res;
}
static int theId(const QByteArray &ba)
{
return theId(ba.constData(), ba.size());
}
/*!
\fn Core::Id(int uid)
\brief Constructs an id given a UID.
The UID is an integer value that is unique within the running
Qt Creator process.
It is the callers responsibility to ensure the uniqueness of
the passed integer. The recommended approach is to use
\c{registerId()} with an value taken from the plugin's
private range.
\sa registerId()
*/
/*!
Constructs an id given its associated name. The internal
representation will be unspecified, but consistent within a
Qt Creator process.
*/
Id::Id(const char *name)
: m_id(theId(name, 0))
{}
/*!
\overload
*/
Id::Id(const QByteArray &name)
: m_id(theId(name))
{}
/*!
\overload
\deprecated
*/
Id::Id(const QString &name)
: m_id(theId(name.toUtf8()))
{}
/*!
Returns an internal representation of the id.
*/
QByteArray Id::name() const
{
return stringFromId.value(m_id).str;
}
/*!
Returns a string representation of the id suitable
for UI display.
This should not be used to create a persistent version
of the Id, use \c{toSetting()} instead.
\sa fromString(), toSetting()
*/
QString Id::toString() const
{
return QString::fromUtf8(stringFromId.value(m_id).str);
}
/*!
Creates an id from a string representation.
This should not be used to handle a persistent version
of the Id, use \c{fromSetting()} instead.
\deprecated
\sa toString(), fromSetting()
*/
Id Id::fromString(const QString &name)
{
return Id(theId(name.toUtf8()));
}
/*!
Creates an id from a string representation.
This should not be used to handle a persistent version
of the Id, use \c{fromSetting()} instead.
\deprecated
\sa toString(), fromSetting()
*/
Id Id::fromName(const QByteArray &name)
{
return Id(theId(name));
}
/*!
Returns a persistent value representing the id which is
suitable to be stored in QSettings.
\sa fromSetting()
*/
QVariant Id::toSetting() const
{
return QVariant(QString::fromUtf8(stringFromId.value(m_id).str));
}
/*!
Reconstructs an id from a persistent value.
\sa toSetting()
*/
Id Id::fromSetting(const QVariant &variant)
{
const QByteArray ba = variant.toString().toUtf8();
if (ba.isEmpty())
return Id();
return Id(theId(ba));
}
/*!
Constructs a derived id.
This can be used to construct groups of ids logically
belonging together. The associated internal name
will be generated by appending \c{suffix}.
*/
Id Id::withSuffix(int suffix) const
{
const QByteArray ba = name() + QByteArray::number(suffix);
return Id(ba.constData());
}
/*!
\overload
*/
Id Id::withSuffix(const char *suffix) const
{
const QByteArray ba = name() + suffix;
return Id(ba.constData());
}
/*!
Constructs a derived id.
This can be used to construct groups of ids logically
belonging together. The associated internal name
will be generated by prepending \c{prefix}.
*/
Id Id::withPrefix(const char *prefix) const
{
const QByteArray ba = prefix + name();
return Id(ba.constData());
}
/*!
Associates a id with its uid and its string
representation.
The uid should be taken from the plugin's private range.
\sa fromSetting()
*/
void Id::registerId(int uid, const char *name)
{
StringHolder sh(name, 0);
idFromString[sh] = uid;
stringFromId[uid] = sh;
}
bool Id::operator==(const char *name) const
{
const char *string = stringFromId.value(m_id).str;
if (string && name)
return strcmp(string, name) == 0;
else
return false;
}
// For debugging purposes
CORE_EXPORT const char *nameForId(int id)
{
return stringFromId.value(id).str;
}
bool Id::alphabeticallyBefore(Id other) const
{
return toString().compare(other.toString(), Qt::CaseInsensitive) < 0;
}
} // namespace Core
<commit_msg>fix typo in Core::Id documentation<commit_after>/****************************************************************************
**
** 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 "id.h"
#include "coreconstants.h"
#include <utils/qtcassert.h>
#include <QByteArray>
#include <QHash>
#include <QVector>
#include <string.h>
namespace Core {
/*!
\class Core::Id
\brief The class Id encapsulates an identifier that is unique
within a specific running Qt Creator process.
\c{Core::Id} is used as facility to identify objects of interest
in a more typesafe and faster manner than a plain \c QString or
\c QByteArray would provide.
An id is internally represented as a 32 bit integer (its \c UID)
and associated with a plain 7-bit-clean ASCII name used
for display and persistency.
Each plugin that is distributed as part of Qt Creator has a
private range of 10000 UIDs that are guaranteed to be unique.
Third party plugins are advised to construct ids from their
string representation.
*/
class StringHolder
{
public:
StringHolder()
: n(0), str(0)
{}
StringHolder(const char *s, int length)
: n(length), str(s)
{
if (!n)
length = n = strlen(s);
h = 0;
while (length--) {
h = (h << 4) + *s++;
h ^= (h & 0xf0000000) >> 23;
h &= 0x0fffffff;
}
}
int n;
const char *str;
uint h;
};
static bool operator==(const StringHolder &sh1, const StringHolder &sh2)
{
// sh.n is unlikely to discriminate better than the hash.
return sh1.h == sh2.h && sh1.str && sh2.str && strcmp(sh1.str, sh2.str) == 0;
}
static uint qHash(const StringHolder &sh)
{
return sh.h;
}
struct IdCache : public QHash<StringHolder, int>
{
#ifndef QTC_ALLOW_STATIC_LEAKS
~IdCache()
{
for (IdCache::iterator it = begin(); it != end(); ++it)
delete[](const_cast<char *>(it.key().str));
}
#endif
};
static int firstUnusedId = Id::IdsPerPlugin * Id::ReservedPlugins;
static QHash<int, StringHolder> stringFromId;
static IdCache idFromString;
static int theId(const char *str, int n = 0)
{
QTC_ASSERT(str && *str, return 0);
StringHolder sh(str, n);
int res = idFromString.value(sh, 0);
if (res == 0) {
res = firstUnusedId++;
sh.str = qstrdup(sh.str);
idFromString[sh] = res;
stringFromId[res] = sh;
}
return res;
}
static int theId(const QByteArray &ba)
{
return theId(ba.constData(), ba.size());
}
/*!
\fn Core::Id(int uid)
\brief Constructs an id given a UID.
The UID is an integer value that is unique within the running
Qt Creator process.
It is the callers responsibility to ensure the uniqueness of
the passed integer. The recommended approach is to use
\c{registerId()} with an value taken from the plugin's
private range.
\sa registerId()
*/
/*!
Constructs an id given its associated name. The internal
representation will be unspecified, but consistent within a
Qt Creator process.
*/
Id::Id(const char *name)
: m_id(theId(name, 0))
{}
/*!
\overload
*/
Id::Id(const QByteArray &name)
: m_id(theId(name))
{}
/*!
\overload
\deprecated
*/
Id::Id(const QString &name)
: m_id(theId(name.toUtf8()))
{}
/*!
Returns an internal representation of the id.
*/
QByteArray Id::name() const
{
return stringFromId.value(m_id).str;
}
/*!
Returns a string representation of the id suitable
for UI display.
This should not be used to create a persistent version
of the Id, use \c{toSetting()} instead.
\sa fromString(), toSetting()
*/
QString Id::toString() const
{
return QString::fromUtf8(stringFromId.value(m_id).str);
}
/*!
Creates an id from a string representation.
This should not be used to handle a persistent version
of the Id, use \c{fromSetting()} instead.
\deprecated
\sa toString(), fromSetting()
*/
Id Id::fromString(const QString &name)
{
return Id(theId(name.toUtf8()));
}
/*!
Creates an id from a string representation.
This should not be used to handle a persistent version
of the Id, use \c{fromSetting()} instead.
\deprecated
\sa toString(), fromSetting()
*/
Id Id::fromName(const QByteArray &name)
{
return Id(theId(name));
}
/*!
Returns a persistent value representing the id which is
suitable to be stored in QSettings.
\sa fromSetting()
*/
QVariant Id::toSetting() const
{
return QVariant(QString::fromUtf8(stringFromId.value(m_id).str));
}
/*!
Reconstructs an id from a persistent value.
\sa toSetting()
*/
Id Id::fromSetting(const QVariant &variant)
{
const QByteArray ba = variant.toString().toUtf8();
if (ba.isEmpty())
return Id();
return Id(theId(ba));
}
/*!
Constructs a derived id.
This can be used to construct groups of ids logically
belonging together. The associated internal name
will be generated by appending \c{suffix}.
*/
Id Id::withSuffix(int suffix) const
{
const QByteArray ba = name() + QByteArray::number(suffix);
return Id(ba.constData());
}
/*!
\overload
*/
Id Id::withSuffix(const char *suffix) const
{
const QByteArray ba = name() + suffix;
return Id(ba.constData());
}
/*!
Constructs a derived id.
This can be used to construct groups of ids logically
belonging together. The associated internal name
will be generated by prepending \c{prefix}.
*/
Id Id::withPrefix(const char *prefix) const
{
const QByteArray ba = prefix + name();
return Id(ba.constData());
}
/*!
Associates a id with its uid and its string
representation.
The uid should be taken from the plugin's private range.
\sa fromSetting()
*/
void Id::registerId(int uid, const char *name)
{
StringHolder sh(name, 0);
idFromString[sh] = uid;
stringFromId[uid] = sh;
}
bool Id::operator==(const char *name) const
{
const char *string = stringFromId.value(m_id).str;
if (string && name)
return strcmp(string, name) == 0;
else
return false;
}
// For debugging purposes
CORE_EXPORT const char *nameForId(int id)
{
return stringFromId.value(id).str;
}
bool Id::alphabeticallyBefore(Id other) const
{
return toString().compare(other.toString(), Qt::CaseInsensitive) < 0;
}
} // namespace Core
<|endoftext|>
|
<commit_before>/* This file is part of VoltDB.
* Copyright (C) 2008-2013 VoltDB Inc.
*
* This file contains original code and/or modifications of original code.
* Any modifications made by VoltDB Inc. are licensed under the following
* terms and conditions:
*
* 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 VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
/* Copyright (C) 2008 by H-Store Project
* Brown University
* Massachusetts Institute of Technology
* Yale University
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include <iostream>
#include "seqscanexecutor.h"
#include "common/debuglog.h"
#include "common/common.h"
#include "common/tabletuple.h"
#include "common/FatalException.hpp"
#include "expressions/abstractexpression.h"
#include "plannodes/seqscannode.h"
#include "plannodes/projectionnode.h"
#include "plannodes/limitnode.h"
#include "storage/table.h"
#include "storage/temptable.h"
#include "storage/tablefactory.h"
#include "storage/tableiterator.h"
using namespace voltdb;
bool SeqScanExecutor::p_init(AbstractPlanNode* abstract_node,
TempTableLimits* limits)
{
VOLT_TRACE("init SeqScan Executor");
SeqScanPlanNode* node = dynamic_cast<SeqScanPlanNode*>(abstract_node);
assert(node);
assert(node->getTargetTable());
//
// OPTIMIZATION: If there is no predicate for this SeqScan,
// then we want to just set our OutputTable pointer to be the
// pointer of our TargetTable. This prevents us from just
// reading through the entire TargetTable and copying all of
// the tuples. We are guarenteed that no Executor will ever
// modify an input table, so this operation is safe
//
if (!this->needsOutputTableClear())
{
node->setOutputTable(node->getTargetTable());
}
//
// Otherwise create a new temp table that mirrors the
// output schema specified in the plan (which should mirror
// the output schema for any inlined projection)
//
else
{
// Create output table based on output schema from the plan
setTempOutputTable(limits, node->getTargetTable()->name());
}
return true;
}
bool SeqScanExecutor::needsOutputTableClear() {
// clear the temporary output table only when it has a predicate.
// if it doesn't have a predicate, it's the original persistent table
// and we don't have to (and must not) clear it.
SeqScanPlanNode* node = dynamic_cast<SeqScanPlanNode*>(m_abstractNode);
assert(node);
return node->needsOutputTableClear();
}
bool SeqScanExecutor::p_execute(const NValueArray ¶ms) {
SeqScanPlanNode* node = dynamic_cast<SeqScanPlanNode*>(m_abstractNode);
assert(node);
Table* output_table = node->getOutputTable();
assert(output_table);
Table* target_table = dynamic_cast<Table*>(node->getTargetTable());
assert(target_table);
//cout << "SeqScanExecutor: node id" << node->getPlanNodeId() << endl;
VOLT_TRACE("Sequential Scanning table :\n %s",
target_table->debug().c_str());
VOLT_DEBUG("Sequential Scanning table : %s which has %d active, %d"
" allocated",
target_table->name().c_str(),
(int)target_table->activeTupleCount(),
(int)target_table->allocatedTupleCount());
//
// OPTIMIZATION: NESTED PROJECTION
//
// Since we have the input params, we need to call substitute to
// change any nodes in our expression tree to be ready for the
// projection operations in execute
//
int num_of_columns = (int)output_table->columnCount();
ProjectionPlanNode* projection_node = dynamic_cast<ProjectionPlanNode*>(node->getInlinePlanNode(PLAN_NODE_TYPE_PROJECTION));
if (projection_node != NULL) {
for (int ctr = 0; ctr < num_of_columns; ctr++) {
assert(projection_node->getOutputColumnExpressions()[ctr]);
projection_node->getOutputColumnExpressions()[ctr]->substitute(params);
}
}
//
// OPTIMIZATION: NESTED LIMIT
// How nice! We can also cut off our scanning with a nested limit!
//
LimitPlanNode* limit_node = dynamic_cast<LimitPlanNode*>(node->getInlinePlanNode(PLAN_NODE_TYPE_LIMIT));
//
// OPTIMIZATION:
//
// If there is no predicate and no Projection for this SeqScan,
// then we have already set the node's OutputTable to just point
// at the TargetTable. Therefore, there is nothing we more we need
// to do here
//
if (node->getPredicate() != NULL || projection_node != NULL ||
limit_node != NULL)
{
//
// Just walk through the table using our iterator and apply
// the predicate to each tuple. For each tuple that satisfies
// our expression, we'll insert them into the output table.
//
TableTuple tuple(target_table->schema());
TableIterator iterator = target_table->iterator();
AbstractExpression *predicate = node->getPredicate();
if (predicate)
{
VOLT_TRACE("SCAN PREDICATE A:\n%s\n", predicate->debug(true).c_str());
predicate->substitute(params);
assert(predicate != NULL);
VOLT_DEBUG("SCAN PREDICATE B:\n%s\n",
predicate->debug(true).c_str());
}
int limit = -1;
int offset = -1;
if (limit_node) {
limit_node->getLimitAndOffsetByReference(params, limit, offset);
}
int tuple_ctr = 0;
int tuple_skipped = 0;
m_engine->setLastAccessedTable(target_table);
while ((limit == -1 || tuple_ctr < limit) && iterator.next(tuple))
{
VOLT_TRACE("INPUT TUPLE: %s, %d/%d\n",
tuple.debug(target_table->name()).c_str(), tuple_ctr,
(int)target_table->activeTupleCount());
m_engine->noteTuplesProcessedForProgressMonitoring(1);
//
// For each tuple we need to evaluate it against our predicate
//
if (predicate == NULL || predicate->eval(&tuple, NULL).isTrue())
{
// Check if we have to skip this tuple because of offset
if (tuple_skipped < offset) {
tuple_skipped++;
continue;
}
++tuple_ctr;
//
// Nested Projection
// Project (or replace) values from input tuple
//
if (projection_node != NULL)
{
TableTuple &temp_tuple = output_table->tempTuple();
for (int ctr = 0; ctr < num_of_columns; ctr++)
{
NValue value =
projection_node->
getOutputColumnExpressions()[ctr]->eval(&tuple, NULL);
temp_tuple.setNValue(ctr, value);
}
if (!output_table->insertTuple(temp_tuple))
{
VOLT_ERROR("Failed to insert tuple from table '%s' into"
" output table '%s'",
target_table->name().c_str(),
output_table->name().c_str());
return false;
}
}
else
{
//
// Insert the tuple into our output table
//
if (!output_table->insertTuple(tuple)) {
VOLT_ERROR("Failed to insert tuple from table '%s' into"
" output table '%s'",
target_table->name().c_str(),
output_table->name().c_str());
return false;
}
}
}
}
}
VOLT_TRACE("\n%s\n", output_table->debug().c_str());
VOLT_DEBUG("Finished Seq scanning");
return true;
}
<commit_msg>Experimentally turning off some accounting to check performance impact. (cherry picked from commit 2b8478d9e1dc333b01f83358eaf826a7aa442226)<commit_after>/* This file is part of VoltDB.
* Copyright (C) 2008-2013 VoltDB Inc.
*
* This file contains original code and/or modifications of original code.
* Any modifications made by VoltDB Inc. are licensed under the following
* terms and conditions:
*
* 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 VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
/* Copyright (C) 2008 by H-Store Project
* Brown University
* Massachusetts Institute of Technology
* Yale University
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include <iostream>
#include "seqscanexecutor.h"
#include "common/debuglog.h"
#include "common/common.h"
#include "common/tabletuple.h"
#include "common/FatalException.hpp"
#include "expressions/abstractexpression.h"
#include "plannodes/seqscannode.h"
#include "plannodes/projectionnode.h"
#include "plannodes/limitnode.h"
#include "storage/table.h"
#include "storage/temptable.h"
#include "storage/tablefactory.h"
#include "storage/tableiterator.h"
using namespace voltdb;
bool SeqScanExecutor::p_init(AbstractPlanNode* abstract_node,
TempTableLimits* limits)
{
VOLT_TRACE("init SeqScan Executor");
SeqScanPlanNode* node = dynamic_cast<SeqScanPlanNode*>(abstract_node);
assert(node);
assert(node->getTargetTable());
//
// OPTIMIZATION: If there is no predicate for this SeqScan,
// then we want to just set our OutputTable pointer to be the
// pointer of our TargetTable. This prevents us from just
// reading through the entire TargetTable and copying all of
// the tuples. We are guarenteed that no Executor will ever
// modify an input table, so this operation is safe
//
if (!this->needsOutputTableClear())
{
node->setOutputTable(node->getTargetTable());
}
//
// Otherwise create a new temp table that mirrors the
// output schema specified in the plan (which should mirror
// the output schema for any inlined projection)
//
else
{
// Create output table based on output schema from the plan
setTempOutputTable(limits, node->getTargetTable()->name());
}
return true;
}
bool SeqScanExecutor::needsOutputTableClear() {
// clear the temporary output table only when it has a predicate.
// if it doesn't have a predicate, it's the original persistent table
// and we don't have to (and must not) clear it.
SeqScanPlanNode* node = dynamic_cast<SeqScanPlanNode*>(m_abstractNode);
assert(node);
return node->needsOutputTableClear();
}
bool SeqScanExecutor::p_execute(const NValueArray ¶ms) {
SeqScanPlanNode* node = dynamic_cast<SeqScanPlanNode*>(m_abstractNode);
assert(node);
Table* output_table = node->getOutputTable();
assert(output_table);
Table* target_table = dynamic_cast<Table*>(node->getTargetTable());
assert(target_table);
//cout << "SeqScanExecutor: node id" << node->getPlanNodeId() << endl;
VOLT_TRACE("Sequential Scanning table :\n %s",
target_table->debug().c_str());
VOLT_DEBUG("Sequential Scanning table : %s which has %d active, %d"
" allocated",
target_table->name().c_str(),
(int)target_table->activeTupleCount(),
(int)target_table->allocatedTupleCount());
//
// OPTIMIZATION: NESTED PROJECTION
//
// Since we have the input params, we need to call substitute to
// change any nodes in our expression tree to be ready for the
// projection operations in execute
//
int num_of_columns = (int)output_table->columnCount();
ProjectionPlanNode* projection_node = dynamic_cast<ProjectionPlanNode*>(node->getInlinePlanNode(PLAN_NODE_TYPE_PROJECTION));
if (projection_node != NULL) {
for (int ctr = 0; ctr < num_of_columns; ctr++) {
assert(projection_node->getOutputColumnExpressions()[ctr]);
projection_node->getOutputColumnExpressions()[ctr]->substitute(params);
}
}
//
// OPTIMIZATION: NESTED LIMIT
// How nice! We can also cut off our scanning with a nested limit!
//
LimitPlanNode* limit_node = dynamic_cast<LimitPlanNode*>(node->getInlinePlanNode(PLAN_NODE_TYPE_LIMIT));
//
// OPTIMIZATION:
//
// If there is no predicate and no Projection for this SeqScan,
// then we have already set the node's OutputTable to just point
// at the TargetTable. Therefore, there is nothing we more we need
// to do here
//
if (node->getPredicate() != NULL || projection_node != NULL ||
limit_node != NULL)
{
//
// Just walk through the table using our iterator and apply
// the predicate to each tuple. For each tuple that satisfies
// our expression, we'll insert them into the output table.
//
TableTuple tuple(target_table->schema());
TableIterator iterator = target_table->iterator();
AbstractExpression *predicate = node->getPredicate();
if (predicate)
{
VOLT_TRACE("SCAN PREDICATE A:\n%s\n", predicate->debug(true).c_str());
predicate->substitute(params);
assert(predicate != NULL);
VOLT_DEBUG("SCAN PREDICATE B:\n%s\n",
predicate->debug(true).c_str());
}
int limit = -1;
int offset = -1;
if (limit_node) {
limit_node->getLimitAndOffsetByReference(params, limit, offset);
}
int tuple_ctr = 0;
int tuple_skipped = 0;
m_engine->setLastAccessedTable(target_table);
while ((limit == -1 || tuple_ctr < limit) && iterator.next(tuple))
{
VOLT_TRACE("INPUT TUPLE: %s, %d/%d\n",
tuple.debug(target_table->name()).c_str(), tuple_ctr,
(int)target_table->activeTupleCount());
// Experimentally turning off accounting to check performance impact.
// m_engine->noteTuplesProcessedForProgressMonitoring(1);
//
// For each tuple we need to evaluate it against our predicate
//
if (predicate == NULL || predicate->eval(&tuple, NULL).isTrue())
{
// Check if we have to skip this tuple because of offset
if (tuple_skipped < offset) {
tuple_skipped++;
continue;
}
++tuple_ctr;
//
// Nested Projection
// Project (or replace) values from input tuple
//
if (projection_node != NULL)
{
TableTuple &temp_tuple = output_table->tempTuple();
for (int ctr = 0; ctr < num_of_columns; ctr++)
{
NValue value =
projection_node->
getOutputColumnExpressions()[ctr]->eval(&tuple, NULL);
temp_tuple.setNValue(ctr, value);
}
if (!output_table->insertTuple(temp_tuple))
{
VOLT_ERROR("Failed to insert tuple from table '%s' into"
" output table '%s'",
target_table->name().c_str(),
output_table->name().c_str());
return false;
}
}
else
{
//
// Insert the tuple into our output table
//
if (!output_table->insertTuple(tuple)) {
VOLT_ERROR("Failed to insert tuple from table '%s' into"
" output table '%s'",
target_table->name().c_str(),
output_table->name().c_str());
return false;
}
}
}
}
}
VOLT_TRACE("\n%s\n", output_table->debug().c_str());
VOLT_DEBUG("Finished Seq scanning");
return true;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2006 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkDiscretePathEffect.h"
#include "SkFixed.h"
#include "SkPathMeasure.h"
#include "SkPointPriv.h"
#include "SkReadBuffer.h"
#include "SkStrokeRec.h"
#include "SkWriteBuffer.h"
sk_sp<SkPathEffect> SkDiscretePathEffect::Make(SkScalar segLength, SkScalar deviation,
uint32_t seedAssist) {
if (!SkScalarIsFinite(segLength) || !SkScalarIsFinite(deviation)) {
return nullptr;
}
if (segLength <= SK_ScalarNearlyZero) {
return nullptr;
}
return sk_sp<SkPathEffect>(new SkDiscretePathEffect(segLength, deviation, seedAssist));
}
static void Perterb(SkPoint* p, const SkVector& tangent, SkScalar scale) {
SkVector normal = tangent;
SkPointPriv::RotateCCW(&normal);
normal.setLength(scale);
*p += normal;
}
SkDiscretePathEffect::SkDiscretePathEffect(SkScalar segLength,
SkScalar deviation,
uint32_t seedAssist)
: fSegLength(segLength), fPerterb(deviation), fSeedAssist(seedAssist)
{
}
/** \class LCGRandom
Utility class that implements pseudo random 32bit numbers using a fast
linear equation. Unlike rand(), this class holds its own seed (initially
set to 0), so that multiple instances can be used with no side-effects.
Copied from the original implementation of SkRandom. Only contains the
methods used by SkDiscretePathEffect::filterPath, with methods that were
not called directly moved to private.
*/
class LCGRandom {
public:
LCGRandom(uint32_t seed) : fSeed(seed) {}
/** Return the next pseudo random number expressed as a SkScalar
in the range [-SK_Scalar1..SK_Scalar1).
*/
SkScalar nextSScalar1() { return SkFixedToScalar(this->nextSFixed1()); }
private:
/** Return the next pseudo random number as an unsigned 32bit value.
*/
uint32_t nextU() { uint32_t r = fSeed * kMul + kAdd; fSeed = r; return r; }
/** Return the next pseudo random number as a signed 32bit value.
*/
int32_t nextS() { return (int32_t)this->nextU(); }
/** Return the next pseudo random number expressed as a signed SkFixed
in the range [-SK_Fixed1..SK_Fixed1).
*/
SkFixed nextSFixed1() { return this->nextS() >> 15; }
// See "Numerical Recipes in C", 1992 page 284 for these constants
enum {
kMul = 1664525,
kAdd = 1013904223
};
uint32_t fSeed;
};
bool SkDiscretePathEffect::filterPath(SkPath* dst, const SkPath& src,
SkStrokeRec* rec, const SkRect*) const {
bool doFill = rec->isFillStyle();
SkPathMeasure meas(src, doFill);
/* Caller may supply their own seed assist, which by default is 0 */
uint32_t seed = fSeedAssist ^ SkScalarRoundToInt(meas.getLength());
LCGRandom rand(seed ^ ((seed << 16) | (seed >> 16)));
SkScalar scale = fPerterb;
SkPoint p;
SkVector v;
do {
SkScalar length = meas.getLength();
if (fSegLength * (2 + doFill) > length) {
meas.getSegment(0, length, dst, true); // to short for us to mangle
} else {
int n = SkScalarRoundToInt(length / fSegLength);
SkScalar delta = length / n;
SkScalar distance = 0;
if (meas.isClosed()) {
n -= 1;
distance += delta/2;
}
if (meas.getPosTan(distance, &p, &v)) {
Perterb(&p, v, rand.nextSScalar1() * scale);
dst->moveTo(p);
}
while (--n >= 0) {
distance += delta;
if (meas.getPosTan(distance, &p, &v)) {
Perterb(&p, v, rand.nextSScalar1() * scale);
dst->lineTo(p);
}
}
if (meas.isClosed()) {
dst->close();
}
}
} while (meas.nextContour());
return true;
}
sk_sp<SkFlattenable> SkDiscretePathEffect::CreateProc(SkReadBuffer& buffer) {
SkScalar segLength = buffer.readScalar();
SkScalar perterb = buffer.readScalar();
uint32_t seed = buffer.readUInt();
return Make(segLength, perterb, seed);
}
void SkDiscretePathEffect::flatten(SkWriteBuffer& buffer) const {
buffer.writeScalar(fSegLength);
buffer.writeScalar(fPerterb);
buffer.writeUInt(fSeedAssist);
}
#ifndef SK_IGNORE_TO_STRING
void SkDiscretePathEffect::toString(SkString* str) const {
str->appendf("SkDiscretePathEffect: (");
str->appendf("segLength: %.2f deviation: %.2f seed %d", fSegLength, fPerterb, fSeedAssist);
str->append(")");
}
#endif
<commit_msg>limit discrete path effect iterations<commit_after>/*
* Copyright 2006 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkDiscretePathEffect.h"
#include "SkFixed.h"
#include "SkPathMeasure.h"
#include "SkPointPriv.h"
#include "SkReadBuffer.h"
#include "SkStrokeRec.h"
#include "SkWriteBuffer.h"
sk_sp<SkPathEffect> SkDiscretePathEffect::Make(SkScalar segLength, SkScalar deviation,
uint32_t seedAssist) {
if (!SkScalarIsFinite(segLength) || !SkScalarIsFinite(deviation)) {
return nullptr;
}
if (segLength <= SK_ScalarNearlyZero) {
return nullptr;
}
return sk_sp<SkPathEffect>(new SkDiscretePathEffect(segLength, deviation, seedAssist));
}
static void Perterb(SkPoint* p, const SkVector& tangent, SkScalar scale) {
SkVector normal = tangent;
SkPointPriv::RotateCCW(&normal);
normal.setLength(scale);
*p += normal;
}
SkDiscretePathEffect::SkDiscretePathEffect(SkScalar segLength,
SkScalar deviation,
uint32_t seedAssist)
: fSegLength(segLength), fPerterb(deviation), fSeedAssist(seedAssist)
{
}
/** \class LCGRandom
Utility class that implements pseudo random 32bit numbers using a fast
linear equation. Unlike rand(), this class holds its own seed (initially
set to 0), so that multiple instances can be used with no side-effects.
Copied from the original implementation of SkRandom. Only contains the
methods used by SkDiscretePathEffect::filterPath, with methods that were
not called directly moved to private.
*/
class LCGRandom {
public:
LCGRandom(uint32_t seed) : fSeed(seed) {}
/** Return the next pseudo random number expressed as a SkScalar
in the range [-SK_Scalar1..SK_Scalar1).
*/
SkScalar nextSScalar1() { return SkFixedToScalar(this->nextSFixed1()); }
private:
/** Return the next pseudo random number as an unsigned 32bit value.
*/
uint32_t nextU() { uint32_t r = fSeed * kMul + kAdd; fSeed = r; return r; }
/** Return the next pseudo random number as a signed 32bit value.
*/
int32_t nextS() { return (int32_t)this->nextU(); }
/** Return the next pseudo random number expressed as a signed SkFixed
in the range [-SK_Fixed1..SK_Fixed1).
*/
SkFixed nextSFixed1() { return this->nextS() >> 15; }
// See "Numerical Recipes in C", 1992 page 284 for these constants
enum {
kMul = 1664525,
kAdd = 1013904223
};
uint32_t fSeed;
};
bool SkDiscretePathEffect::filterPath(SkPath* dst, const SkPath& src,
SkStrokeRec* rec, const SkRect*) const {
bool doFill = rec->isFillStyle();
SkPathMeasure meas(src, doFill);
/* Caller may supply their own seed assist, which by default is 0 */
uint32_t seed = fSeedAssist ^ SkScalarRoundToInt(meas.getLength());
LCGRandom rand(seed ^ ((seed << 16) | (seed >> 16)));
SkScalar scale = fPerterb;
SkPoint p;
SkVector v;
do {
SkScalar length = meas.getLength();
if (fSegLength * (2 + doFill) > length) {
meas.getSegment(0, length, dst, true); // to short for us to mangle
} else {
int n = SkScalarRoundToInt(length / fSegLength);
constexpr int kMaxReasonableIterations = 100000;
n = SkTMin(n, kMaxReasonableIterations);
SkScalar delta = length / n;
SkScalar distance = 0;
if (meas.isClosed()) {
n -= 1;
distance += delta/2;
}
if (meas.getPosTan(distance, &p, &v)) {
Perterb(&p, v, rand.nextSScalar1() * scale);
dst->moveTo(p);
}
while (--n >= 0) {
distance += delta;
if (meas.getPosTan(distance, &p, &v)) {
Perterb(&p, v, rand.nextSScalar1() * scale);
dst->lineTo(p);
}
}
if (meas.isClosed()) {
dst->close();
}
}
} while (meas.nextContour());
return true;
}
sk_sp<SkFlattenable> SkDiscretePathEffect::CreateProc(SkReadBuffer& buffer) {
SkScalar segLength = buffer.readScalar();
SkScalar perterb = buffer.readScalar();
uint32_t seed = buffer.readUInt();
return Make(segLength, perterb, seed);
}
void SkDiscretePathEffect::flatten(SkWriteBuffer& buffer) const {
buffer.writeScalar(fSegLength);
buffer.writeScalar(fPerterb);
buffer.writeUInt(fSeedAssist);
}
#ifndef SK_IGNORE_TO_STRING
void SkDiscretePathEffect::toString(SkString* str) const {
str->appendf("SkDiscretePathEffect: (");
str->appendf("segLength: %.2f deviation: %.2f seed %d", fSegLength, fPerterb, fSeedAssist);
str->append(")");
}
#endif
<|endoftext|>
|
<commit_before>
/*
* Copyright 2006 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkTypes.h"
static const size_t kBufferSize = 256;
#define LOG_TAG "skia"
#include <android/log.h>
void SkDebugf(const char format[], ...) {
va_list args;
va_start(args, format);
__android_log_vprint(ANDROID_LOG_DEBUG, LOG_TAG, format, args);
va_end(args);
}
<commit_msg>Enable Android executables (like skia_launcher) to redirect SkDebugf output to stdout as well as the system logs.<commit_after>
/*
* Copyright 2006 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkTypes.h"
static const size_t kBufferSize = 256;
#define LOG_TAG "skia"
#include <android/log.h>
static bool gSkDebugToStdOut = false;
extern "C" void AndroidSkDebugToStdOut(bool debugToStdOut) {
gSkDebugToStdOut = debugToStdOut;
}
void SkDebugf(const char format[], ...) {
va_list args;
va_start(args, format);
__android_log_vprint(ANDROID_LOG_DEBUG, LOG_TAG, format, args);
// Print debug output to stdout as well. This is useful for command
// line applications (e.g. skia_launcher)
if (gSkDebugToStdOut) {
vprintf(format, args);
}
va_end(args);
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <fstream>
#include "pin.H"
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <cstdlib>
#include <cstring>
#include <sched.h>
#include <sys/time.h>
#include <sys/resource.h>
#include "IPCBase.h"
#include "shmem.h"
#define COUNT (1000)
#define locQ (50)
#define QSIZE (locQ*sizeof(packet))
// if 64 bit machine change this to 0xffffffffffffffff
#define MASK 0x00000000ffffffff
// Defining command line arguments
KNOB<UINT64> KnobLong(KNOB_MODE_WRITEONCE, "pintool",
"map", "1", "Maps");
PIN_LOCK lock;
INT32 numThreads = 0;
UINT64 checkSum = 0;
IPC::IPCBase *tst;
VOID ThreadStart(THREADID threadid, CONTEXT *ctxt, INT32 flags, VOID *v)
{
GetLock(&lock, threadid+1);
numThreads++;
printf("threads till now %d\n",numThreads);
fflush(stdout);
ReleaseLock(&lock);
ASSERT(numThreads <= MaxNumThreads, "Maximum number of threads exceeded\n");
tst->onThread_start(threadid);
}
VOID ThreadFini(THREADID tid,const CONTEXT *ctxt, INT32 flags, VOID *v)
{
while (tst->onThread_finish(tid)==-1) {
PIN_Yield();
}
}
// Pass a memory read record
VOID RecordMemRead(THREADID tid,VOID * ip, VOID * addr)
{
checkSum+=2;
uint64_t nip = MASK & (uint64_t)ip;
uint64_t naddr = MASK & (uint64_t)addr;
while (tst->analysisFn(tid,nip,2,naddr)== -1) {
PIN_Yield();
}
}
// Pass a memory write record
VOID RecordMemWrite(THREADID tid,VOID * ip, VOID * addr)
{
checkSum+=3;
uint64_t nip = MASK & (uint64_t)ip;
uint64_t naddr = MASK & (uint64_t)addr;
while(tst->analysisFn(tid,nip,3,naddr)== -1) {
PIN_Yield();
}
}
VOID BrnFun(THREADID tid,ADDRINT tadr,BOOL taken,VOID *ip)
{
uint64_t nip = MASK & (uint64_t)ip;
uint64_t ntadr = MASK & (uint64_t)tadr;
if (taken) {
checkSum+=4;
while (tst->analysisFn(tid,nip,4,ntadr)==-1) {
PIN_Yield();
}
}
else {
checkSum+=5;
while (tst->analysisFn(tid,nip,5,ntadr)==-1) {
PIN_Yield();
}
}
}
VOID RegValRead(THREADID tid,VOID * ip,REG* _reg)
{
checkSum+=6;
uint64_t nip = MASK & (uint64_t)ip;
uint64_t _nreg = MASK & (uint64_t)_reg;
while (tst->analysisFn(tid,nip,6,_nreg)== -1) {
PIN_Yield();
}
}
VOID RegValWrite(THREADID tid,VOID * ip,REG* _reg)
{
checkSum+=7;
uint64_t nip = MASK & (uint64_t)ip;
uint64_t _nreg = MASK & (uint64_t)_reg;
while (tst->analysisFn(tid,nip,7,_nreg)== -1) {
PIN_Yield();
}
}
// Pin calls this function every time a new instruction is encountered
VOID Instruction(INS ins, VOID *v)
{
UINT32 memOperands = INS_MemoryOperandCount(ins);
UINT32 maxWregs = INS_MaxNumWRegs(ins);
UINT32 maxRregs = INS_MaxNumRRegs(ins);
for(UINT32 i=0; i< maxWregs; i++) {
REG x = REG_FullRegName(INS_RegW(ins, i));
if (REG_is_gr(x) || x == REG_EFLAGS)
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)RegValWrite,IARG_THREAD_ID, IARG_INST_PTR, IARG_REG_VALUE,x,IARG_END);
}
for(UINT32 i=0; i< maxRregs; i++) {
REG x = REG_FullRegName(INS_RegR(ins, i));
if (REG_is_gr(x) || x == REG_EFLAGS)
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)RegValRead,IARG_THREAD_ID, IARG_INST_PTR, IARG_REG_VALUE,x,IARG_END);
}
if (INS_IsBranchOrCall(ins))//INS_IsIndirectBranchOrCall(ins))
{
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)BrnFun, IARG_THREAD_ID, IARG_BRANCH_TARGET_ADDR, IARG_BRANCH_TAKEN, IARG_INST_PTR, IARG_END);
}
/* if (INS_HasFallThrough(ins))//INS_IsIndirectBranchOrCall(ins))
{
INS_InsertCall(ins, IPOINT_AFTER, (AFUNPTR)BrnFun, IARG_BRANCH_TARGET_ADDR, IARG_BRANCH_TAKEN, IARG_INST_PTR, IARG_END);
} */
// Iterate over each memory operand of the instruction.
for (UINT32 memOp = 0; memOp < memOperands; memOp++)
{
if (INS_MemoryOperandIsRead(ins, memOp))
{
INS_InsertPredicatedCall(
ins, IPOINT_BEFORE, (AFUNPTR)RecordMemRead,
IARG_THREAD_ID,
IARG_INST_PTR,
IARG_MEMORYOP_EA, memOp,
IARG_END);
}
// Note that in some architectures a single memory operand can be
// both read and written (for instance incl (%eax) on IA-32)
// In that case we instrument it once for read and once for write.
if (INS_MemoryOperandIsWritten(ins, memOp))
{
INS_InsertPredicatedCall(
ins, IPOINT_BEFORE, (AFUNPTR)RecordMemWrite,
IARG_THREAD_ID,
IARG_INST_PTR,
IARG_MEMORYOP_EA, memOp,
IARG_END);
}
}
}
// This function is called when the application exits
VOID Fini(INT32 code, VOID *v)
{
//printf("checkSum is %lld\n",checkSum);
tst->unload();
}
/* ===================================================================== */
/* Print Help Message */
/* ===================================================================== */
INT32 Usage()
{
cerr << "This tool instruments the benchmarks" << endl;
cerr << endl << KNOB_BASE::StringKnobSummary() << endl;
return -1;
}
/* ===================================================================== */
/* Main */
/* ===================================================================== */
// argc, argv are the entire command line, including pin -t <toolname> -- ...
int main(int argc, char * argv[])
{
UINT64 mask = KnobLong;
printf("mask for pin %lld\n", mask);
fflush(stdout);
if (sched_setaffinity(0, sizeof(mask), (cpu_set_t *)&mask) <0) {
perror("sched_setaffinity");
}
// Initialize pin
if (PIN_Init(argc, argv)) return Usage();
tst = new IPC::Shm ();
PIN_AddThreadStartFunction(ThreadStart, 0);
// Register Instruction to be called to instrument instructions
INS_AddInstrumentFunction(Instruction, 0);
PIN_AddThreadFiniFunction(ThreadFini, 0);
// Register Fini to be called when the application exits
PIN_AddFiniFunction(Fini, 0);
// Start the program, never returns
PIN_StartProgram();
return 0;
}
<commit_msg>committing _LP64 for 32/64 bit identification<commit_after>#include <iostream>
#include <fstream>
#include "pin.H"
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <cstdlib>
#include <cstring>
#include <sched.h>
#include <sys/time.h>
#include <sys/resource.h>
#include "IPCBase.h"
#include "shmem.h"
#define COUNT (1000)
#define locQ (50)
#define QSIZE (locQ*sizeof(packet))
#ifdef _LP64
#define MASK 0xffffffffffffffff
#else
#define MASK 0x00000000ffffffff
#endif
// Defining command line arguments
KNOB<UINT64> KnobLong(KNOB_MODE_WRITEONCE, "pintool",
"map", "1", "Maps");
PIN_LOCK lock;
INT32 numThreads = 0;
UINT64 checkSum = 0;
IPC::IPCBase *tst;
VOID ThreadStart(THREADID threadid, CONTEXT *ctxt, INT32 flags, VOID *v)
{
GetLock(&lock, threadid+1);
numThreads++;
printf("threads till now %d\n",numThreads);
fflush(stdout);
ReleaseLock(&lock);
ASSERT(numThreads <= MaxNumThreads, "Maximum number of threads exceeded\n");
tst->onThread_start(threadid);
}
VOID ThreadFini(THREADID tid,const CONTEXT *ctxt, INT32 flags, VOID *v)
{
while (tst->onThread_finish(tid)==-1) {
PIN_Yield();
}
}
// Pass a memory read record
VOID RecordMemRead(THREADID tid,VOID * ip, VOID * addr)
{
checkSum+=2;
uint64_t nip = MASK & (uint64_t)ip;
uint64_t naddr = MASK & (uint64_t)addr;
while (tst->analysisFn(tid,nip,2,naddr)== -1) {
PIN_Yield();
}
}
// Pass a memory write record
VOID RecordMemWrite(THREADID tid,VOID * ip, VOID * addr)
{
checkSum+=3;
uint64_t nip = MASK & (uint64_t)ip;
uint64_t naddr = MASK & (uint64_t)addr;
while(tst->analysisFn(tid,nip,3,naddr)== -1) {
PIN_Yield();
}
}
VOID BrnFun(THREADID tid,ADDRINT tadr,BOOL taken,VOID *ip)
{
uint64_t nip = MASK & (uint64_t)ip;
uint64_t ntadr = MASK & (uint64_t)tadr;
if (taken) {
checkSum+=4;
while (tst->analysisFn(tid,nip,4,ntadr)==-1) {
PIN_Yield();
}
}
else {
checkSum+=5;
while (tst->analysisFn(tid,nip,5,ntadr)==-1) {
PIN_Yield();
}
}
}
VOID RegValRead(THREADID tid,VOID * ip,REG* _reg)
{
checkSum+=6;
uint64_t nip = MASK & (uint64_t)ip;
uint64_t _nreg = MASK & (uint64_t)_reg;
while (tst->analysisFn(tid,nip,6,_nreg)== -1) {
PIN_Yield();
}
}
VOID RegValWrite(THREADID tid,VOID * ip,REG* _reg)
{
checkSum+=7;
uint64_t nip = MASK & (uint64_t)ip;
uint64_t _nreg = MASK & (uint64_t)_reg;
while (tst->analysisFn(tid,nip,7,_nreg)== -1) {
PIN_Yield();
}
}
// Pin calls this function every time a new instruction is encountered
VOID Instruction(INS ins, VOID *v)
{
UINT32 memOperands = INS_MemoryOperandCount(ins);
UINT32 maxWregs = INS_MaxNumWRegs(ins);
UINT32 maxRregs = INS_MaxNumRRegs(ins);
for(UINT32 i=0; i< maxWregs; i++) {
REG x = REG_FullRegName(INS_RegW(ins, i));
if (REG_is_gr(x) || x == REG_EFLAGS)
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)RegValWrite,IARG_THREAD_ID, IARG_INST_PTR, IARG_REG_VALUE,x,IARG_END);
}
for(UINT32 i=0; i< maxRregs; i++) {
REG x = REG_FullRegName(INS_RegR(ins, i));
if (REG_is_gr(x) || x == REG_EFLAGS)
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)RegValRead,IARG_THREAD_ID, IARG_INST_PTR, IARG_REG_VALUE,x,IARG_END);
}
if (INS_IsBranchOrCall(ins))//INS_IsIndirectBranchOrCall(ins))
{
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)BrnFun, IARG_THREAD_ID, IARG_BRANCH_TARGET_ADDR, IARG_BRANCH_TAKEN, IARG_INST_PTR, IARG_END);
}
/* if (INS_HasFallThrough(ins))//INS_IsIndirectBranchOrCall(ins))
{
INS_InsertCall(ins, IPOINT_AFTER, (AFUNPTR)BrnFun, IARG_BRANCH_TARGET_ADDR, IARG_BRANCH_TAKEN, IARG_INST_PTR, IARG_END);
} */
// Iterate over each memory operand of the instruction.
for (UINT32 memOp = 0; memOp < memOperands; memOp++)
{
if (INS_MemoryOperandIsRead(ins, memOp))
{
INS_InsertPredicatedCall(
ins, IPOINT_BEFORE, (AFUNPTR)RecordMemRead,
IARG_THREAD_ID,
IARG_INST_PTR,
IARG_MEMORYOP_EA, memOp,
IARG_END);
}
// Note that in some architectures a single memory operand can be
// both read and written (for instance incl (%eax) on IA-32)
// In that case we instrument it once for read and once for write.
if (INS_MemoryOperandIsWritten(ins, memOp))
{
INS_InsertPredicatedCall(
ins, IPOINT_BEFORE, (AFUNPTR)RecordMemWrite,
IARG_THREAD_ID,
IARG_INST_PTR,
IARG_MEMORYOP_EA, memOp,
IARG_END);
}
}
}
// This function is called when the application exits
VOID Fini(INT32 code, VOID *v)
{
//printf("checkSum is %lld\n",checkSum);
tst->unload();
}
/* ===================================================================== */
/* Print Help Message */
/* ===================================================================== */
INT32 Usage()
{
cerr << "This tool instruments the benchmarks" << endl;
cerr << endl << KNOB_BASE::StringKnobSummary() << endl;
return -1;
}
/* ===================================================================== */
/* Main */
/* ===================================================================== */
// argc, argv are the entire command line, including pin -t <toolname> -- ...
int main(int argc, char * argv[])
{
UINT64 mask = KnobLong;
printf("mask for pin %lld\n", mask);
fflush(stdout);
if (sched_setaffinity(0, sizeof(mask), (cpu_set_t *)&mask) <0) {
perror("sched_setaffinity");
}
// Initialize pin
if (PIN_Init(argc, argv)) return Usage();
tst = new IPC::Shm ();
PIN_AddThreadStartFunction(ThreadStart, 0);
// Register Instruction to be called to instrument instructions
INS_AddInstrumentFunction(Instruction, 0);
PIN_AddThreadFiniFunction(ThreadFini, 0);
// Register Fini to be called when the application exits
PIN_AddFiniFunction(Fini, 0);
// Start the program, never returns
PIN_StartProgram();
return 0;
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** 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, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qdeclarativeitemsmodule_p.h"
#include <QtGui/qaction.h>
#include <QtGui/qvalidator.h>
#include <QtGui/qgraphicseffect.h>
#include "qdeclarativeevents_p_p.h"
#include "qdeclarativeeffects_p.h"
#include "qdeclarativescalegrid_p_p.h"
#include "qdeclarativeanimatedimage_p.h"
#include "qdeclarativeborderimage_p.h"
#include "qdeclarativepositioners_p.h"
#include "qdeclarativemousearea_p.h"
#include "qdeclarativeflickable_p.h"
#include "qdeclarativeflickable_p_p.h"
#include "qdeclarativeflipable_p.h"
#include "qdeclarativefocuspanel_p.h"
#include "qdeclarativefocusscope_p.h"
#include "qdeclarativegraphicsobjectcontainer_p.h"
#include "qdeclarativegridview_p.h"
#include "qdeclarativeimage_p.h"
#include "qdeclarativeitem_p.h"
#include "qdeclarativelayoutitem_p.h"
#include "qdeclarativelistview_p.h"
#include "qdeclarativeloader_p.h"
#include "qdeclarativemousearea_p.h"
#include "qdeclarativepath_p.h"
#include "qdeclarativepathview_p.h"
#include "qdeclarativerectangle_p.h"
#include "qdeclarativerepeater_p.h"
#include "qdeclarativetext_p.h"
#include "qdeclarativetextedit_p.h"
#include "qdeclarativetextinput_p.h"
#include "qdeclarativevisualitemmodel_p.h"
#ifdef QT_WEBKIT_LIB
#include "qdeclarativewebview_p.h"
#include "qdeclarativewebview_p_p.h"
#endif
#include "qdeclarativeanchors_p.h"
void QDeclarativeItemModule::defineModule()
{
qmlRegisterType<QDeclarativeAnimatedImage>("Qt",4,6,"AnimatedImage");
qmlRegisterType<QGraphicsBlurEffect>("Qt",4,6,"Blur");
qmlRegisterType<QDeclarativeBorderImage>("Qt",4,6,"BorderImage");
qmlRegisterType<QGraphicsColorizeEffect>("Qt",4,6,"Colorize");
qmlRegisterType<QDeclarativeColumn>("Qt",4,6,"Column");
qmlRegisterType<QDeclarativeDrag>("Qt",4,6,"Drag");
qmlRegisterType<QGraphicsDropShadowEffect>("Qt",4,6,"DropShadow");
qmlRegisterType<QDeclarativeFlickable>("Qt",4,6,"Flickable");
qmlRegisterType<QDeclarativeFlipable>("Qt",4,6,"Flipable");
qmlRegisterType<QDeclarativeFlow>("Qt",4,6,"Flow");
qmlRegisterType<QDeclarativeFocusPanel>("Qt",4,6,"FocusPanel");
qmlRegisterType<QDeclarativeFocusScope>("Qt",4,6,"FocusScope");
qmlRegisterType<QDeclarativeGradient>("Qt",4,6,"Gradient");
qmlRegisterType<QDeclarativeGradientStop>("Qt",4,6,"GradientStop");
qmlRegisterType<QDeclarativeGraphicsObjectContainer>("Qt",4,6,"GraphicsObjectContainer");
qmlRegisterType<QDeclarativeGrid>("Qt",4,6,"Grid");
qmlRegisterType<QDeclarativeGridView>("Qt",4,6,"GridView");
qmlRegisterType<QDeclarativeImage>("Qt",4,6,"Image");
qmlRegisterType<QDeclarativeItem>("Qt",4,6,"Item");
qmlRegisterType<QDeclarativeKeyNavigationAttached>("Qt",4,6,"KeyNavigation");
qmlRegisterType<QDeclarativeKeysAttached>("Qt",4,6,"Keys");
qmlRegisterType<QDeclarativeLayoutItem>("Qt",4,6,"LayoutItem");
qmlRegisterType<QDeclarativeListView>("Qt",4,6,"ListView");
qmlRegisterType<QDeclarativeLoader>("Qt",4,6,"Loader");
qmlRegisterType<QDeclarativeMouseArea>("Qt",4,6,"MouseArea");
qmlRegisterType<QGraphicsOpacityEffect>("Qt",4,6,"Opacity");
qmlRegisterType<QDeclarativePath>("Qt",4,6,"Path");
qmlRegisterType<QDeclarativePathAttribute>("Qt",4,6,"PathAttribute");
qmlRegisterType<QDeclarativePathCubic>("Qt",4,6,"PathCubic");
qmlRegisterType<QDeclarativePathLine>("Qt",4,6,"PathLine");
qmlRegisterType<QDeclarativePathPercent>("Qt",4,6,"PathPercent");
qmlRegisterType<QDeclarativePathQuad>("Qt",4,6,"PathQuad");
qmlRegisterType<QDeclarativePathView>("Qt",4,6,"PathView");
qmlRegisterType<QDeclarativePen>("Qt",4,6,"Pen");
qmlRegisterType<QIntValidator>("Qt",4,6,"QIntValidator");
#if (QT_VERSION >= QT_VERSION_CHECK(4,7,0))
qmlRegisterType<QDoubleValidator>("Qt",4,7,"QDoubleValidator");
qmlRegisterType<QRegExpValidator>("Qt",4,7,"QRegExpValidator");
#endif
qmlRegisterType<QDeclarativeRectangle>("Qt",4,6,"Rectangle");
qmlRegisterType<QDeclarativeRepeater>("Qt",4,6,"Repeater");
qmlRegisterType<QGraphicsRotation>("Qt",4,6,"Rotation");
qmlRegisterType<QDeclarativeRow>("Qt",4,6,"Row");
qmlRegisterType<QGraphicsScale>("Qt",4,6,"Scale");
qmlRegisterType<QDeclarativeText>("Qt",4,6,"Text");
qmlRegisterType<QDeclarativeTextEdit>("Qt",4,6,"TextEdit");
qmlRegisterType<QDeclarativeTextInput>("Qt",4,6,"TextInput");
qmlRegisterType<QDeclarativeViewSection>("Qt",4,6,"ViewSection");
qmlRegisterType<QDeclarativeFlickableVisibleArea>("Qt",4,6,"VisibleArea");
qmlRegisterType<QDeclarativeVisualDataModel>("Qt",4,6,"VisualDataModel");
qmlRegisterType<QDeclarativeVisualItemModel>("Qt",4,6,"VisualItemModel");
qmlRegisterType<QDeclarativeAnchors>();
qmlRegisterType<QGraphicsEffect>();
qmlRegisterType<QDeclarativeKeyEvent>();
qmlRegisterType<QDeclarativeMouseEvent>();
qmlRegisterType<QGraphicsObject>();
qmlRegisterType<QGraphicsWidget>();
qmlRegisterType<QGraphicsTransform>();
qmlRegisterType<QDeclarativePathElement>();
qmlRegisterType<QDeclarativeCurve>();
qmlRegisterType<QDeclarativeScaleGrid>();
qmlRegisterType<QValidator>();
qmlRegisterType<QDeclarativeVisualModel>();
qmlRegisterType<QAction>();
#ifdef QT_WEBKIT_LIB
qmlRegisterType<QDeclarativeWebSettings>();
#endif
}
<commit_msg>Pen is not a creatable type.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** 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, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qdeclarativeitemsmodule_p.h"
#include <QtGui/qaction.h>
#include <QtGui/qvalidator.h>
#include <QtGui/qgraphicseffect.h>
#include "qdeclarativeevents_p_p.h"
#include "qdeclarativeeffects_p.h"
#include "qdeclarativescalegrid_p_p.h"
#include "qdeclarativeanimatedimage_p.h"
#include "qdeclarativeborderimage_p.h"
#include "qdeclarativepositioners_p.h"
#include "qdeclarativemousearea_p.h"
#include "qdeclarativeflickable_p.h"
#include "qdeclarativeflickable_p_p.h"
#include "qdeclarativeflipable_p.h"
#include "qdeclarativefocuspanel_p.h"
#include "qdeclarativefocusscope_p.h"
#include "qdeclarativegraphicsobjectcontainer_p.h"
#include "qdeclarativegridview_p.h"
#include "qdeclarativeimage_p.h"
#include "qdeclarativeitem_p.h"
#include "qdeclarativelayoutitem_p.h"
#include "qdeclarativelistview_p.h"
#include "qdeclarativeloader_p.h"
#include "qdeclarativemousearea_p.h"
#include "qdeclarativepath_p.h"
#include "qdeclarativepathview_p.h"
#include "qdeclarativerectangle_p.h"
#include "qdeclarativerepeater_p.h"
#include "qdeclarativetext_p.h"
#include "qdeclarativetextedit_p.h"
#include "qdeclarativetextinput_p.h"
#include "qdeclarativevisualitemmodel_p.h"
#ifdef QT_WEBKIT_LIB
#include "qdeclarativewebview_p.h"
#include "qdeclarativewebview_p_p.h"
#endif
#include "qdeclarativeanchors_p.h"
void QDeclarativeItemModule::defineModule()
{
qmlRegisterType<QDeclarativeAnimatedImage>("Qt",4,6,"AnimatedImage");
qmlRegisterType<QGraphicsBlurEffect>("Qt",4,6,"Blur");
qmlRegisterType<QDeclarativeBorderImage>("Qt",4,6,"BorderImage");
qmlRegisterType<QGraphicsColorizeEffect>("Qt",4,6,"Colorize");
qmlRegisterType<QDeclarativeColumn>("Qt",4,6,"Column");
qmlRegisterType<QDeclarativeDrag>("Qt",4,6,"Drag");
qmlRegisterType<QGraphicsDropShadowEffect>("Qt",4,6,"DropShadow");
qmlRegisterType<QDeclarativeFlickable>("Qt",4,6,"Flickable");
qmlRegisterType<QDeclarativeFlipable>("Qt",4,6,"Flipable");
qmlRegisterType<QDeclarativeFlow>("Qt",4,6,"Flow");
qmlRegisterType<QDeclarativeFocusPanel>("Qt",4,6,"FocusPanel");
qmlRegisterType<QDeclarativeFocusScope>("Qt",4,6,"FocusScope");
qmlRegisterType<QDeclarativeGradient>("Qt",4,6,"Gradient");
qmlRegisterType<QDeclarativeGradientStop>("Qt",4,6,"GradientStop");
qmlRegisterType<QDeclarativeGraphicsObjectContainer>("Qt",4,6,"GraphicsObjectContainer");
qmlRegisterType<QDeclarativeGrid>("Qt",4,6,"Grid");
qmlRegisterType<QDeclarativeGridView>("Qt",4,6,"GridView");
qmlRegisterType<QDeclarativeImage>("Qt",4,6,"Image");
qmlRegisterType<QDeclarativeItem>("Qt",4,6,"Item");
qmlRegisterType<QDeclarativeKeyNavigationAttached>("Qt",4,6,"KeyNavigation");
qmlRegisterType<QDeclarativeKeysAttached>("Qt",4,6,"Keys");
qmlRegisterType<QDeclarativeLayoutItem>("Qt",4,6,"LayoutItem");
qmlRegisterType<QDeclarativeListView>("Qt",4,6,"ListView");
qmlRegisterType<QDeclarativeLoader>("Qt",4,6,"Loader");
qmlRegisterType<QDeclarativeMouseArea>("Qt",4,6,"MouseArea");
qmlRegisterType<QGraphicsOpacityEffect>("Qt",4,6,"Opacity");
qmlRegisterType<QDeclarativePath>("Qt",4,6,"Path");
qmlRegisterType<QDeclarativePathAttribute>("Qt",4,6,"PathAttribute");
qmlRegisterType<QDeclarativePathCubic>("Qt",4,6,"PathCubic");
qmlRegisterType<QDeclarativePathLine>("Qt",4,6,"PathLine");
qmlRegisterType<QDeclarativePathPercent>("Qt",4,6,"PathPercent");
qmlRegisterType<QDeclarativePathQuad>("Qt",4,6,"PathQuad");
qmlRegisterType<QDeclarativePathView>("Qt",4,6,"PathView");
qmlRegisterType<QIntValidator>("Qt",4,6,"QIntValidator");
#if (QT_VERSION >= QT_VERSION_CHECK(4,7,0))
qmlRegisterType<QDoubleValidator>("Qt",4,7,"QDoubleValidator");
qmlRegisterType<QRegExpValidator>("Qt",4,7,"QRegExpValidator");
#endif
qmlRegisterType<QDeclarativeRectangle>("Qt",4,6,"Rectangle");
qmlRegisterType<QDeclarativeRepeater>("Qt",4,6,"Repeater");
qmlRegisterType<QGraphicsRotation>("Qt",4,6,"Rotation");
qmlRegisterType<QDeclarativeRow>("Qt",4,6,"Row");
qmlRegisterType<QGraphicsScale>("Qt",4,6,"Scale");
qmlRegisterType<QDeclarativeText>("Qt",4,6,"Text");
qmlRegisterType<QDeclarativeTextEdit>("Qt",4,6,"TextEdit");
qmlRegisterType<QDeclarativeTextInput>("Qt",4,6,"TextInput");
qmlRegisterType<QDeclarativeViewSection>("Qt",4,6,"ViewSection");
qmlRegisterType<QDeclarativeFlickableVisibleArea>("Qt",4,6,"VisibleArea");
qmlRegisterType<QDeclarativeVisualDataModel>("Qt",4,6,"VisualDataModel");
qmlRegisterType<QDeclarativeVisualItemModel>("Qt",4,6,"VisualItemModel");
qmlRegisterType<QDeclarativeAnchors>();
qmlRegisterType<QGraphicsEffect>();
qmlRegisterType<QDeclarativeKeyEvent>();
qmlRegisterType<QDeclarativeMouseEvent>();
qmlRegisterType<QGraphicsObject>();
qmlRegisterType<QGraphicsWidget>();
qmlRegisterType<QGraphicsTransform>();
qmlRegisterType<QDeclarativePathElement>();
qmlRegisterType<QDeclarativeCurve>();
qmlRegisterType<QDeclarativeScaleGrid>();
qmlRegisterType<QValidator>();
qmlRegisterType<QDeclarativeVisualModel>();
qmlRegisterType<QAction>();
qmlRegisterType<QDeclarativePen>();
#ifdef QT_WEBKIT_LIB
qmlRegisterType<QDeclarativeWebSettings>();
#endif
}
<|endoftext|>
|
<commit_before>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2018 Intel Corporation. All Rights Reserved.
#include "../include/librealsense2/rs.hpp"
#include "../include/librealsense2/rsutil.h"
#include "proc/synthetic-stream.h"
#include "proc/occlusion-filter.h"
//#include "../../common/tiny-profiler.h"
#include <vector>
#include <cmath>
namespace librealsense
{
occlusion_filter::occlusion_filter() : _occlusion_filter(occlusion_monotonic_scan) , _occlusion_scanning(horizontal)
{
}
void occlusion_filter::set_texel_intrinsics(const rs2_intrinsics& in)
{
_texels_intrinsics = in;
_texels_depth.resize(_texels_intrinsics.value().width*_texels_intrinsics.value().height);
}
void occlusion_filter::process(float3* points, float2* uv_map, const std::vector<float2> & pix_coord, const rs2::depth_frame& depth) const
{
switch (_occlusion_filter)
{
case occlusion_none:
break;
case occlusion_monotonic_scan:
monotonic_heuristic_invalidation(points, uv_map, pix_coord, depth);
break;
default:
throw std::runtime_error(to_string() << "Unsupported occlusion filter type " << _occlusion_filter << " requested");
break;
}
}
int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
// Return the gretest common divisor of a
// and b which lie in the given range.
int maxDivisorRange(int a, int b, int l, int h)
{
int g = gcd(a, b);
int res = g;
// Loop from 1 to sqrt(GCD(a, b).
for (int i = l; i * i <= g && i <= h; i++)
if ((g % i == 0) && (g / i) < h)
{
res = g / i;
break;
}
return res;
}
template<size_t SIZE>
void rotate_image_optimized(byte* dest[], const byte* source, int width, int height)
{
auto width_out = height;
auto height_out = width;
auto out = dest[0];
auto buffer_size = maxDivisorRange(height, width, 1, ROTATION_BUFFER_SIZE);
byte *buffer = new byte[buffer_size * buffer_size * SIZE];
for (int i = 0; i < height; i = i + buffer_size)
{
for (int j = 0; j < width; j = j + buffer_size)
{
for (int ii = 0; ii < buffer_size; ii++) {
for (int jj = 0; jj < buffer_size; jj++) {
auto source_index = (j + jj + (width * (i + ii))) * SIZE; // capture a buffer from source
memcpy((void*)(buffer + buffer_size* (buffer_size - jj - 1) + (buffer_size - ii - 1) * SIZE), &source[source_index], SIZE);
}
}
for (int ii = 0; ii < buffer_size; ii++) { // copy buffer to out
auto out_index = ((height - (i + buffer_size - 1) - 1) + (width - (j + buffer_size - 1) - 1 + ii) * height) * SIZE;
memcpy(&out[out_index], (buffer + ii), SIZE * buffer_size);
}
}
}
}
// IMPORTANT! This implementation is based on the assumption that the RGB sensor is positioned strictly to the left of the depth sensor.
// namely D415/D435 and SR300. The implementation WILL NOT work properly for different setups
// Heuristic occlusion invalidation algorithm:
// - Use the uv texels calculated when projecting depth to color
// - Scan each line from left to right and check the the U coordinate in the mapping is raising monotonically.
// - The occlusion is designated as U coordinate for a given pixel is less than the U coordinate of the predecessing pixel.
// - The UV mapping for the occluded pixel is reset to (0,0). Later on the (0,0) coordinate in the texture map is overwritten
// with a invalidation color such as black/magenta according to the purpose (production/debugging)
void occlusion_filter::monotonic_heuristic_invalidation(float3* points, float2* uv_map, const std::vector<float2>& pix_coord, const rs2::depth_frame& depth) const
{
float occZTh = 0.1f; //meters
int occDilationSz = 1;
auto points_width = _depth_intrinsics->width;
auto points_height = _depth_intrinsics->height;
auto pixels_ptr = pix_coord.data();
auto points_ptr = points;
auto uv_map_ptr = uv_map;
float maxInLine = -1;
float maxZ = 0;
if (_occlusion_scanning == horizontal)
{
for( size_t y = 0; y < points_height; ++y )
{
maxInLine = -1;
maxZ = 0;
int occDilationLeft = 0;
for( size_t x = 0; x < points_width; ++x )
{
if( points_ptr->z )
{
// Occlusion detection
if( pixels_ptr->x < maxInLine
|| ( pixels_ptr->x == maxInLine && ( points_ptr->z - maxZ ) > occZTh ) )
{
*points_ptr = { 0, 0, 0 };
occDilationLeft = occDilationSz;
}
else
{
maxInLine = pixels_ptr->x;
maxZ = points_ptr->z;
if( occDilationLeft > 0 )
{
*points_ptr = { 0, 0, 0 };
occDilationLeft--;
}
}
}
++points_ptr;
++uv_map_ptr;
++pixels_ptr;
}
}
}
else if (_occlusion_scanning == vertical)
{
auto rotated_depth_width = _depth_intrinsics->height;
auto rotated_depth_height = _depth_intrinsics->width;
auto depth_ptr = (byte*)(depth.get_data());
std::vector< byte > alloc( depth.get_bytes_per_pixel() * points_width * points_height );
byte* depth_planes[1];
depth_planes[0] = alloc.data();
rotate_image_optimized<2>(depth_planes, (const byte*)(depth.get_data()), points_width, points_height);
// scan depth frame after rotation: check if there is a noticed jump between adjacen pixels in Z-axis (depth), it means there could be occlusion.
// save suspected points and run occlusion-invalidation vertical scan only on them
// after rotation : height = points_width , width = points_height
for (int i = 0; i < rotated_depth_height; i++)
{
for (int j = 0; j < rotated_depth_width; j++)
{
// before depth frame rotation: occlusion detected in the positive direction of Y
// after rotation : scan from right to left (positive direction of X) to detect occlusion
// compare depth each pixel only with the pixel on its right (i,j+1)
auto index = (j + (rotated_depth_width * i));
auto uv_index = ((rotated_depth_height - i - 1) + (rotated_depth_width - j - 1) * rotated_depth_height);
auto index_right = index + 1;
uint16_t* diff_depth_ptr = (uint16_t*)depth_planes[0];
uint16_t diff_right = abs((uint16_t)(*(diff_depth_ptr + index)) - (uint16_t)(*(diff_depth_ptr + index_right)));
float scaled_threshold = DEPTH_OCCLUSION_THRESHOLD / _depth_units;
if (diff_right > scaled_threshold)
{
points_ptr = points + uv_index;
uv_map_ptr = uv_map + uv_index;
if (j >= VERTICAL_SCAN_WINDOW_SIZE) {
maxInLine = (uv_map_ptr - 1 * points_width)->y;
for (size_t y = 0; y <= VERTICAL_SCAN_WINDOW_SIZE; ++y)
{
if (((uv_map_ptr + y * points_width)->y < maxInLine))
{
*(points_ptr + y * points_width) = { 0.f, 0.f };
}
else
{
break;
}
}
}
}
}
}
}
}
// Prepare texture map without occlusion that for every texture coordinate there no more than one depth point that is mapped to it
// i.e. for every (u,v) map coordinate we select the depth point with minimum Z. all other points that are mapped to this texel will be invalidated
// Algo input data:
// Vector of 3D [xyz] coordinates of depth_width*depth_height size
// Vector of 2D [i,j] coordinates where the val[i,j] stores the texture coordinate (s,t) for the corresponding (i,j) pixel in depth frame
// Algo intermediate data:
// Vector of depth values (floats) in size of the mapped texture (different from depth width*height) where
// each (i,j) cell holds the minimal Z among all the depth pixels that are mapped to the specific texel
void occlusion_filter::comprehensive_invalidation(float3* points, float2* uv_map, const std::vector<float2> & pix_coord) const
{
auto depth_points = points;
auto mapped_pix = pix_coord.data();
size_t mapped_tex_width = _texels_intrinsics->width;
size_t mapped_tex_height = _texels_intrinsics->height;
size_t points_width = _depth_intrinsics->width;
size_t points_height = _depth_intrinsics->height;
static const float z_threshold = 0.05f; // Compensate for temporal noise when comparing Z values
// Clear previous data
memset((void*)(_texels_depth.data()), 0, _texels_depth.size() * sizeof(float));
// Pass1 -generate texels mapping with minimal depth for each texel involved
for (size_t i = 0; i < points_height; i++)
{
for (size_t j = 0; j < points_width; j++)
{
if ((depth_points->z > 0.0001f) &&
(mapped_pix->x > 0.f) && (mapped_pix->x < mapped_tex_width) &&
(mapped_pix->y > 0.f) && (mapped_pix->y < mapped_tex_height))
{
size_t texel_index = (size_t)(mapped_pix->y)*mapped_tex_width + (size_t)(mapped_pix->x);
if ((_texels_depth[texel_index] < 0.0001f) || ((_texels_depth[texel_index] + z_threshold) > depth_points->z))
{
_texels_depth[texel_index] = depth_points->z;
}
}
++depth_points;
++mapped_pix;
}
}
mapped_pix = pix_coord.data();
depth_points = points;
auto uv_ptr = uv_map;
// Pass2 -invalidate depth texels with occlusion traits
for (size_t i = 0; i < points_height; i++)
{
for (size_t j = 0; j < points_width; j++)
{
if ((depth_points->z > 0.0001f) &&
(mapped_pix->x > 0.f) && (mapped_pix->x < mapped_tex_width) &&
(mapped_pix->y > 0.f) && (mapped_pix->y < mapped_tex_height))
{
size_t texel_index = (size_t)(mapped_pix->y)*mapped_tex_width + (size_t)(mapped_pix->x);
if ((_texels_depth[texel_index] > 0.0001f) && ((_texels_depth[texel_index] + z_threshold) < depth_points->z))
{
*uv_ptr = { 0.f, 0.f };
}
}
++depth_points;
++mapped_pix;
++uv_ptr;
}
}
}
}
<commit_msg>L515 occlusion filter fix<commit_after>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2018 Intel Corporation. All Rights Reserved.
#include "../include/librealsense2/rs.hpp"
#include "../include/librealsense2/rsutil.h"
#include "proc/synthetic-stream.h"
#include "proc/occlusion-filter.h"
//#include "../../common/tiny-profiler.h"
#include <vector>
#include <cmath>
namespace librealsense
{
occlusion_filter::occlusion_filter() : _occlusion_filter(occlusion_monotonic_scan) , _occlusion_scanning(horizontal)
{
}
void occlusion_filter::set_texel_intrinsics(const rs2_intrinsics& in)
{
_texels_intrinsics = in;
_texels_depth.resize(_texels_intrinsics.value().width*_texels_intrinsics.value().height);
}
void occlusion_filter::process(float3* points, float2* uv_map, const std::vector<float2> & pix_coord, const rs2::depth_frame& depth) const
{
switch (_occlusion_filter)
{
case occlusion_none:
break;
case occlusion_monotonic_scan:
monotonic_heuristic_invalidation(points, uv_map, pix_coord, depth);
break;
default:
throw std::runtime_error(to_string() << "Unsupported occlusion filter type " << _occlusion_filter << " requested");
break;
}
}
int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
// Return the greatest common divisor of a
// and b which lie in the given range.
int maxDivisorRange(int a, int b, int lo, int hi)
{
if (lo > hi)
{
int tmp = lo;
lo = hi;
hi = tmp;
}
int g = gcd(a, b);
int res = g;
// Loop from 1 to sqrt(GCD(a, b).
for (int i = lo; i * i <= g && i <= hi; i++)
if ((g % i == 0) && (g / i) < hi)
{
res = g / i;
break;
}
return res;
}
template<size_t SIZE>
void rotate_image_optimized(byte* dest[], const byte* source, int width, int height)
{
auto width_out = height;
auto height_out = width;
auto out = dest[0];
auto buffer_size = maxDivisorRange(height, width, 1, ROTATION_BUFFER_SIZE);
std::vector<byte> buffer(buffer_size * buffer_size * SIZE);
for (int i = 0; i < height; i = i + buffer_size)
{
for (int j = 0; j < width; j = j + buffer_size)
{
for (int ii = 0; ii < buffer_size; ii++) {
for (int jj = 0; jj < buffer_size; jj++) {
auto source_index = (j + jj + (width * (i + ii))) * SIZE; // capture a buffer from source
memcpy((void*)&(buffer[buffer_size * (buffer_size - jj - 1) + (buffer_size - ii - 1) * SIZE]), &source[source_index], SIZE);
}
}
for (int ii = 0; ii < buffer_size; ii++) { // copy buffer to out
auto out_index = ((height - (i + buffer_size - 1) - 1) + (width - (j + buffer_size - 1) - 1 + ii) * height) * SIZE;
memcpy(&out[out_index], &(buffer[ii]), SIZE * buffer_size);
}
}
}
}
// IMPORTANT! This implementation is based on the assumption that the RGB sensor is positioned strictly to the left of the depth sensor.
// namely D415/D435 and SR300. The implementation WILL NOT work properly for different setups
// Heuristic occlusion invalidation algorithm:
// - Use the uv texels calculated when projecting depth to color
// - Scan each line from left to right and check the the U coordinate in the mapping is raising monotonically.
// - The occlusion is designated as U coordinate for a given pixel is less than the U coordinate of the predecessing pixel.
// - The UV mapping for the occluded pixel is reset to (0,0). Later on the (0,0) coordinate in the texture map is overwritten
// with a invalidation color such as black/magenta according to the purpose (production/debugging)
void occlusion_filter::monotonic_heuristic_invalidation(float3* points, float2* uv_map, const std::vector<float2>& pix_coord, const rs2::depth_frame& depth) const
{
float occZTh = 0.1f; //meters
int occDilationSz = 1;
auto points_width = _depth_intrinsics->width;
auto points_height = _depth_intrinsics->height;
auto pixels_ptr = pix_coord.data();
auto points_ptr = points;
auto uv_map_ptr = uv_map;
float maxInLine = -1;
float maxZ = 0;
if (_occlusion_scanning == horizontal)
{
for( size_t y = 0; y < points_height; ++y )
{
maxInLine = -1;
maxZ = 0;
int occDilationLeft = 0;
for( size_t x = 0; x < points_width; ++x )
{
if( points_ptr->z )
{
// Occlusion detection
if( pixels_ptr->x < maxInLine
|| ( pixels_ptr->x == maxInLine && ( points_ptr->z - maxZ ) > occZTh ) )
{
*points_ptr = { 0, 0, 0 };
occDilationLeft = occDilationSz;
}
else
{
maxInLine = pixels_ptr->x;
maxZ = points_ptr->z;
if( occDilationLeft > 0 )
{
*points_ptr = { 0, 0, 0 };
occDilationLeft--;
}
}
}
++points_ptr;
++uv_map_ptr;
++pixels_ptr;
}
}
}
else if (_occlusion_scanning == vertical)
{
auto rotated_depth_width = _depth_intrinsics->height;
auto rotated_depth_height = _depth_intrinsics->width;
auto depth_ptr = (byte*)(depth.get_data());
std::vector< byte > alloc( depth.get_bytes_per_pixel() * points_width * points_height );
byte* depth_planes[1];
depth_planes[0] = alloc.data();
rotate_image_optimized<2>(depth_planes, (const byte*)(depth.get_data()), points_width, points_height);
// scan depth frame after rotation: check if there is a noticed jump between adjacen pixels in Z-axis (depth), it means there could be occlusion.
// save suspected points and run occlusion-invalidation vertical scan only on them
// after rotation : height = points_width , width = points_height
for (int i = 0; i < rotated_depth_height; i++)
{
for (int j = 0; j < rotated_depth_width; j++)
{
// before depth frame rotation: occlusion detected in the positive direction of Y
// after rotation : scan from right to left (positive direction of X) to detect occlusion
// compare depth each pixel only with the pixel on its right (i,j+1)
auto index = (j + (rotated_depth_width * i));
auto uv_index = ((rotated_depth_height - i - 1) + (rotated_depth_width - j - 1) * rotated_depth_height);
auto index_right = index + 1;
uint16_t* diff_depth_ptr = (uint16_t*)depth_planes[0];
uint16_t diff_right = abs((uint16_t)(*(diff_depth_ptr + index)) - (uint16_t)(*(diff_depth_ptr + index_right)));
float scaled_threshold = DEPTH_OCCLUSION_THRESHOLD / _depth_units;
if (diff_right > scaled_threshold)
{
points_ptr = points + uv_index;
uv_map_ptr = uv_map + uv_index;
if (j >= VERTICAL_SCAN_WINDOW_SIZE) {
maxInLine = (uv_map_ptr - 1 * points_width)->y;
for (size_t y = 0; y <= VERTICAL_SCAN_WINDOW_SIZE; ++y)
{
if (((uv_map_ptr + y * points_width)->y < maxInLine))
{
*(points_ptr + y * points_width) = { 0.f, 0.f };
}
else
{
break;
}
}
}
}
}
}
}
}
// Prepare texture map without occlusion that for every texture coordinate there no more than one depth point that is mapped to it
// i.e. for every (u,v) map coordinate we select the depth point with minimum Z. all other points that are mapped to this texel will be invalidated
// Algo input data:
// Vector of 3D [xyz] coordinates of depth_width*depth_height size
// Vector of 2D [i,j] coordinates where the val[i,j] stores the texture coordinate (s,t) for the corresponding (i,j) pixel in depth frame
// Algo intermediate data:
// Vector of depth values (floats) in size of the mapped texture (different from depth width*height) where
// each (i,j) cell holds the minimal Z among all the depth pixels that are mapped to the specific texel
void occlusion_filter::comprehensive_invalidation(float3* points, float2* uv_map, const std::vector<float2> & pix_coord) const
{
auto depth_points = points;
auto mapped_pix = pix_coord.data();
size_t mapped_tex_width = _texels_intrinsics->width;
size_t mapped_tex_height = _texels_intrinsics->height;
size_t points_width = _depth_intrinsics->width;
size_t points_height = _depth_intrinsics->height;
static const float z_threshold = 0.05f; // Compensate for temporal noise when comparing Z values
// Clear previous data
memset((void*)(_texels_depth.data()), 0, _texels_depth.size() * sizeof(float));
// Pass1 -generate texels mapping with minimal depth for each texel involved
for (size_t i = 0; i < points_height; i++)
{
for (size_t j = 0; j < points_width; j++)
{
if ((depth_points->z > 0.0001f) &&
(mapped_pix->x > 0.f) && (mapped_pix->x < mapped_tex_width) &&
(mapped_pix->y > 0.f) && (mapped_pix->y < mapped_tex_height))
{
size_t texel_index = (size_t)(mapped_pix->y)*mapped_tex_width + (size_t)(mapped_pix->x);
if ((_texels_depth[texel_index] < 0.0001f) || ((_texels_depth[texel_index] + z_threshold) > depth_points->z))
{
_texels_depth[texel_index] = depth_points->z;
}
}
++depth_points;
++mapped_pix;
}
}
mapped_pix = pix_coord.data();
depth_points = points;
auto uv_ptr = uv_map;
// Pass2 -invalidate depth texels with occlusion traits
for (size_t i = 0; i < points_height; i++)
{
for (size_t j = 0; j < points_width; j++)
{
if ((depth_points->z > 0.0001f) &&
(mapped_pix->x > 0.f) && (mapped_pix->x < mapped_tex_width) &&
(mapped_pix->y > 0.f) && (mapped_pix->y < mapped_tex_height))
{
size_t texel_index = (size_t)(mapped_pix->y)*mapped_tex_width + (size_t)(mapped_pix->x);
if ((_texels_depth[texel_index] > 0.0001f) && ((_texels_depth[texel_index] + z_threshold) < depth_points->z))
{
*uv_ptr = { 0.f, 0.f };
}
}
++depth_points;
++mapped_pix;
++uv_ptr;
}
}
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************/
/* register_types.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* 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 "register_types.h"
#include "gdnative/gdnative.h"
#include "gdnative.h"
#include "io/resource_loader.h"
#include "io/resource_saver.h"
#include "arvr/register_types.h"
#include "nativescript/register_types.h"
#include "pluginscript/register_types.h"
#include "core/engine.h"
#include "core/os/os.h"
#include "core/project_settings.h"
#ifdef TOOLS_ENABLED
#include "editor/editor_node.h"
#include "gd_native_library_editor.h"
// Class used to discover singleton gdnative files
static void actual_discoverer_handler();
class GDNativeSingletonDiscover : public Object {
// GDCLASS(GDNativeSingletonDiscover, Object)
virtual String get_class() const {
// okay, this is a really dirty hack.
// We're overriding get_class so we can connect it to a signal
// This works because get_class is a virtual method, so we don't
// need to register a new class to ClassDB just for this one
// little signal.
actual_discoverer_handler();
return "Object";
}
};
static Set<String> get_gdnative_singletons(EditorFileSystemDirectory *p_dir) {
Set<String> file_paths;
// check children
for (int i = 0; i < p_dir->get_file_count(); i++) {
String file_name = p_dir->get_file(i);
String file_type = p_dir->get_file_type(i);
if (file_type != "GDNativeLibrary") {
continue;
}
Ref<GDNativeLibrary> lib = ResourceLoader::load(p_dir->get_file_path(i));
if (lib.is_valid() && lib->is_singleton()) {
file_paths.insert(p_dir->get_file_path(i));
}
}
// check subdirectories
for (int i = 0; i < p_dir->get_subdir_count(); i++) {
Set<String> paths = get_gdnative_singletons(p_dir->get_subdir(i));
for (Set<String>::Element *E = paths.front(); E; E = E->next()) {
file_paths.insert(E->get());
}
}
return file_paths;
}
static void actual_discoverer_handler() {
EditorFileSystemDirectory *dir = EditorFileSystem::get_singleton()->get_filesystem();
Set<String> file_paths = get_gdnative_singletons(dir);
Array files;
files.resize(file_paths.size());
int i = 0;
for (Set<String>::Element *E = file_paths.front(); E; i++, E = E->next()) {
files.set(i, E->get());
}
ProjectSettings::get_singleton()->set("gdnative/singletons", files);
ProjectSettings::get_singleton()->save();
}
static GDNativeSingletonDiscover *discoverer = NULL;
class GDNativeExportPlugin : public EditorExportPlugin {
protected:
virtual void _export_file(const String &p_path, const String &p_type, const Set<String> &p_features);
};
struct LibrarySymbol {
char *name;
bool is_required;
};
void GDNativeExportPlugin::_export_file(const String &p_path, const String &p_type, const Set<String> &p_features) {
if (p_type != "GDNativeLibrary") {
return;
}
Ref<GDNativeLibrary> lib = ResourceLoader::load(p_path);
if (lib.is_null()) {
return;
}
Ref<ConfigFile> config = lib->get_config_file();
{
List<String> entry_keys;
config->get_section_keys("entry", &entry_keys);
for (List<String>::Element *E = entry_keys.front(); E; E = E->next()) {
String key = E->get();
Vector<String> tags = key.split(".");
bool skip = false;
for (int i = 0; i < tags.size(); i++) {
bool has_feature = p_features.has(tags[i]);
if (!has_feature) {
skip = true;
break;
}
}
if (skip) {
continue;
}
String entry_lib_path = config->get_value("entry", key);
add_shared_object(entry_lib_path, tags);
}
}
{
List<String> dependency_keys;
config->get_section_keys("dependencies", &dependency_keys);
for (List<String>::Element *E = dependency_keys.front(); E; E = E->next()) {
String key = E->get();
Vector<String> tags = key.split(".");
bool skip = false;
for (int i = 0; i < tags.size(); i++) {
bool has_feature = p_features.has(tags[i]);
if (!has_feature) {
skip = true;
break;
}
}
if (skip) {
continue;
}
Vector<String> dependency_paths = config->get_value("dependencies", key);
for (int i = 0; i < dependency_paths.size(); i++) {
add_shared_object(dependency_paths[i], tags);
}
}
}
if (p_features.has("iOS")) {
// Register symbols in the "fake" dynamic lookup table, because dlsym does not work well on iOS.
LibrarySymbol expected_symbols[] = {
{ "gdnative_init", true },
{ "gdnative_terminate", false },
{ "nativescript_init", false },
{ "nativescript_frame", false },
{ "nativescript_thread_enter", false },
{ "nativescript_thread_exit", false },
{ "gdnative_singleton", false }
};
String declare_pattern = "extern \"C\" void $name(void)$weak;\n";
String additional_code = "extern void register_dynamic_symbol(char *name, void *address);\n"
"extern void add_ios_init_callback(void (*cb)());\n";
String linker_flags = "";
for (int i = 0; i < sizeof(expected_symbols) / sizeof(expected_symbols[0]); ++i) {
String full_name = lib->get_symbol_prefix() + expected_symbols[i].name;
String code = declare_pattern.replace("$name", full_name);
code = code.replace("$weak", expected_symbols[i].is_required ? "" : " __attribute__((weak))");
additional_code += code;
if (!expected_symbols[i].is_required) {
if (linker_flags.length() > 0) {
linker_flags += " ";
}
linker_flags += "-Wl,-U,_" + full_name;
}
}
additional_code += String("void $prefixinit() {\n").replace("$prefix", lib->get_symbol_prefix());
String register_pattern = " if (&$name) register_dynamic_symbol((char *)\"$name\", (void *)$name);\n";
for (int i = 0; i < sizeof(expected_symbols) / sizeof(expected_symbols[0]); ++i) {
String full_name = lib->get_symbol_prefix() + expected_symbols[i].name;
additional_code += register_pattern.replace("$name", full_name);
}
additional_code += "}\n";
additional_code += String("struct $prefixstruct {$prefixstruct() {add_ios_init_callback($prefixinit);}};\n").replace("$prefix", lib->get_symbol_prefix());
additional_code += String("$prefixstruct $prefixstruct_instance;\n").replace("$prefix", lib->get_symbol_prefix());
add_ios_cpp_code(additional_code);
add_ios_linker_flags(linker_flags);
}
}
static void editor_init_callback() {
GDNativeLibraryEditor *library_editor = memnew(GDNativeLibraryEditor);
library_editor->set_name(TTR("GDNative"));
ProjectSettingsEditor::get_singleton()->get_tabs()->add_child(library_editor);
discoverer = memnew(GDNativeSingletonDiscover);
EditorFileSystem::get_singleton()->connect("filesystem_changed", discoverer, "get_class");
Ref<GDNativeExportPlugin> export_plugin;
export_plugin.instance();
EditorExport::get_singleton()->add_export_plugin(export_plugin);
}
#endif
static godot_variant cb_standard_varcall(void *p_procedure_handle, godot_array *p_args) {
godot_gdnative_procedure_fn proc;
proc = (godot_gdnative_procedure_fn)p_procedure_handle;
return proc(p_args);
}
GDNativeCallRegistry *GDNativeCallRegistry::singleton;
Vector<Ref<GDNative> > singleton_gdnatives;
GDNativeLibraryResourceLoader *resource_loader_gdnlib = NULL;
GDNativeLibraryResourceSaver *resource_saver_gdnlib = NULL;
void register_gdnative_types() {
#ifdef TOOLS_ENABLED
EditorNode::add_init_callback(editor_init_callback);
#endif
ClassDB::register_class<GDNativeLibrary>();
ClassDB::register_class<GDNative>();
resource_loader_gdnlib = memnew(GDNativeLibraryResourceLoader);
resource_saver_gdnlib = memnew(GDNativeLibraryResourceSaver);
ResourceLoader::add_resource_format_loader(resource_loader_gdnlib);
ResourceSaver::add_resource_format_saver(resource_saver_gdnlib);
GDNativeCallRegistry::singleton = memnew(GDNativeCallRegistry);
GDNativeCallRegistry::singleton->register_native_call_type("standard_varcall", cb_standard_varcall);
register_arvr_types();
register_nativescript_types();
register_pluginscript_types();
// run singletons
Array singletons = Array();
if (ProjectSettings::get_singleton()->has_setting("gdnative/singletons")) {
singletons = ProjectSettings::get_singleton()->get("gdnative/singletons");
}
singleton_gdnatives.resize(singletons.size());
for (int i = 0; i < singletons.size(); i++) {
String path = singletons[i];
Ref<GDNativeLibrary> lib = ResourceLoader::load(path);
singleton_gdnatives[i].instance();
singleton_gdnatives[i]->set_library(lib);
if (!singleton_gdnatives[i]->initialize()) {
// Can't initialize. Don't make a native_call then
continue;
}
void *proc_ptr;
Error err = singleton_gdnatives[i]->get_symbol(
lib->get_symbol_prefix() + "gdnative_singleton",
proc_ptr);
if (err != OK) {
ERR_PRINT((String("No godot_gdnative_singleton in \"" + singleton_gdnatives[i]->get_library()->get_current_library_path()) + "\" found").utf8().get_data());
} else {
((void (*)())proc_ptr)();
}
}
}
void unregister_gdnative_types() {
for (int i = 0; i < singleton_gdnatives.size(); i++) {
if (singleton_gdnatives[i].is_null()) {
continue;
}
if (!singleton_gdnatives[i]->is_initialized()) {
continue;
}
singleton_gdnatives[i]->terminate();
}
singleton_gdnatives.clear();
unregister_pluginscript_types();
unregister_nativescript_types();
unregister_arvr_types();
memdelete(GDNativeCallRegistry::singleton);
#ifdef TOOLS_ENABLED
if (Engine::get_singleton()->is_editor_hint() && discoverer != NULL) {
memdelete(discoverer);
}
#endif
memdelete(resource_loader_gdnlib);
memdelete(resource_saver_gdnlib);
// This is for printing out the sizes of the core types
/*
print_line(String("array:\t") + itos(sizeof(Array)));
print_line(String("basis:\t") + itos(sizeof(Basis)));
print_line(String("color:\t") + itos(sizeof(Color)));
print_line(String("dict:\t" ) + itos(sizeof(Dictionary)));
print_line(String("node_path:\t") + itos(sizeof(NodePath)));
print_line(String("plane:\t") + itos(sizeof(Plane)));
print_line(String("poolarray:\t") + itos(sizeof(PoolByteArray)));
print_line(String("quat:\t") + itos(sizeof(Quat)));
print_line(String("rect2:\t") + itos(sizeof(Rect2)));
print_line(String("aabb:\t") + itos(sizeof(AABB)));
print_line(String("rid:\t") + itos(sizeof(RID)));
print_line(String("string:\t") + itos(sizeof(String)));
print_line(String("transform:\t") + itos(sizeof(Transform)));
print_line(String("transfo2D:\t") + itos(sizeof(Transform2D)));
print_line(String("variant:\t") + itos(sizeof(Variant)));
print_line(String("vector2:\t") + itos(sizeof(Vector2)));
print_line(String("vector3:\t") + itos(sizeof(Vector3)));
*/
}
<commit_msg>GDNative: Save singletons only if there's a change<commit_after>/*************************************************************************/
/* register_types.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* 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 "register_types.h"
#include "gdnative/gdnative.h"
#include "gdnative.h"
#include "io/resource_loader.h"
#include "io/resource_saver.h"
#include "arvr/register_types.h"
#include "nativescript/register_types.h"
#include "pluginscript/register_types.h"
#include "core/engine.h"
#include "core/os/os.h"
#include "core/project_settings.h"
#ifdef TOOLS_ENABLED
#include "editor/editor_node.h"
#include "gd_native_library_editor.h"
// Class used to discover singleton gdnative files
static void actual_discoverer_handler();
class GDNativeSingletonDiscover : public Object {
// GDCLASS(GDNativeSingletonDiscover, Object)
virtual String get_class() const {
// okay, this is a really dirty hack.
// We're overriding get_class so we can connect it to a signal
// This works because get_class is a virtual method, so we don't
// need to register a new class to ClassDB just for this one
// little signal.
actual_discoverer_handler();
return "Object";
}
};
static Set<String> get_gdnative_singletons(EditorFileSystemDirectory *p_dir) {
Set<String> file_paths;
// check children
for (int i = 0; i < p_dir->get_file_count(); i++) {
String file_name = p_dir->get_file(i);
String file_type = p_dir->get_file_type(i);
if (file_type != "GDNativeLibrary") {
continue;
}
Ref<GDNativeLibrary> lib = ResourceLoader::load(p_dir->get_file_path(i));
if (lib.is_valid() && lib->is_singleton()) {
file_paths.insert(p_dir->get_file_path(i));
}
}
// check subdirectories
for (int i = 0; i < p_dir->get_subdir_count(); i++) {
Set<String> paths = get_gdnative_singletons(p_dir->get_subdir(i));
for (Set<String>::Element *E = paths.front(); E; E = E->next()) {
file_paths.insert(E->get());
}
}
return file_paths;
}
static void actual_discoverer_handler() {
EditorFileSystemDirectory *dir = EditorFileSystem::get_singleton()->get_filesystem();
Set<String> file_paths = get_gdnative_singletons(dir);
bool changed = false;
Array current_files = ProjectSettings::get_singleton()->get("gdnative/singletons");
Array files;
files.resize(file_paths.size());
int i = 0;
for (Set<String>::Element *E = file_paths.front(); E; i++, E = E->next()) {
if (!current_files.has(E->get())) {
changed = true;
}
files.set(i, E->get());
}
// Check for removed files
if (!changed) {
for (int i = 0; i < current_files.size(); i++) {
if (!file_paths.has(current_files[i])) {
changed = true;
break;
}
}
}
if (changed) {
ProjectSettings::get_singleton()->set("gdnative/singletons", files);
ProjectSettings::get_singleton()->save();
}
}
static GDNativeSingletonDiscover *discoverer = NULL;
class GDNativeExportPlugin : public EditorExportPlugin {
protected:
virtual void _export_file(const String &p_path, const String &p_type, const Set<String> &p_features);
};
struct LibrarySymbol {
char *name;
bool is_required;
};
void GDNativeExportPlugin::_export_file(const String &p_path, const String &p_type, const Set<String> &p_features) {
if (p_type != "GDNativeLibrary") {
return;
}
Ref<GDNativeLibrary> lib = ResourceLoader::load(p_path);
if (lib.is_null()) {
return;
}
Ref<ConfigFile> config = lib->get_config_file();
{
List<String> entry_keys;
config->get_section_keys("entry", &entry_keys);
for (List<String>::Element *E = entry_keys.front(); E; E = E->next()) {
String key = E->get();
Vector<String> tags = key.split(".");
bool skip = false;
for (int i = 0; i < tags.size(); i++) {
bool has_feature = p_features.has(tags[i]);
if (!has_feature) {
skip = true;
break;
}
}
if (skip) {
continue;
}
String entry_lib_path = config->get_value("entry", key);
add_shared_object(entry_lib_path, tags);
}
}
{
List<String> dependency_keys;
config->get_section_keys("dependencies", &dependency_keys);
for (List<String>::Element *E = dependency_keys.front(); E; E = E->next()) {
String key = E->get();
Vector<String> tags = key.split(".");
bool skip = false;
for (int i = 0; i < tags.size(); i++) {
bool has_feature = p_features.has(tags[i]);
if (!has_feature) {
skip = true;
break;
}
}
if (skip) {
continue;
}
Vector<String> dependency_paths = config->get_value("dependencies", key);
for (int i = 0; i < dependency_paths.size(); i++) {
add_shared_object(dependency_paths[i], tags);
}
}
}
if (p_features.has("iOS")) {
// Register symbols in the "fake" dynamic lookup table, because dlsym does not work well on iOS.
LibrarySymbol expected_symbols[] = {
{ "gdnative_init", true },
{ "gdnative_terminate", false },
{ "nativescript_init", false },
{ "nativescript_frame", false },
{ "nativescript_thread_enter", false },
{ "nativescript_thread_exit", false },
{ "gdnative_singleton", false }
};
String declare_pattern = "extern \"C\" void $name(void)$weak;\n";
String additional_code = "extern void register_dynamic_symbol(char *name, void *address);\n"
"extern void add_ios_init_callback(void (*cb)());\n";
String linker_flags = "";
for (int i = 0; i < sizeof(expected_symbols) / sizeof(expected_symbols[0]); ++i) {
String full_name = lib->get_symbol_prefix() + expected_symbols[i].name;
String code = declare_pattern.replace("$name", full_name);
code = code.replace("$weak", expected_symbols[i].is_required ? "" : " __attribute__((weak))");
additional_code += code;
if (!expected_symbols[i].is_required) {
if (linker_flags.length() > 0) {
linker_flags += " ";
}
linker_flags += "-Wl,-U,_" + full_name;
}
}
additional_code += String("void $prefixinit() {\n").replace("$prefix", lib->get_symbol_prefix());
String register_pattern = " if (&$name) register_dynamic_symbol((char *)\"$name\", (void *)$name);\n";
for (int i = 0; i < sizeof(expected_symbols) / sizeof(expected_symbols[0]); ++i) {
String full_name = lib->get_symbol_prefix() + expected_symbols[i].name;
additional_code += register_pattern.replace("$name", full_name);
}
additional_code += "}\n";
additional_code += String("struct $prefixstruct {$prefixstruct() {add_ios_init_callback($prefixinit);}};\n").replace("$prefix", lib->get_symbol_prefix());
additional_code += String("$prefixstruct $prefixstruct_instance;\n").replace("$prefix", lib->get_symbol_prefix());
add_ios_cpp_code(additional_code);
add_ios_linker_flags(linker_flags);
}
}
static void editor_init_callback() {
GDNativeLibraryEditor *library_editor = memnew(GDNativeLibraryEditor);
library_editor->set_name(TTR("GDNative"));
ProjectSettingsEditor::get_singleton()->get_tabs()->add_child(library_editor);
discoverer = memnew(GDNativeSingletonDiscover);
EditorFileSystem::get_singleton()->connect("filesystem_changed", discoverer, "get_class");
Ref<GDNativeExportPlugin> export_plugin;
export_plugin.instance();
EditorExport::get_singleton()->add_export_plugin(export_plugin);
}
#endif
static godot_variant cb_standard_varcall(void *p_procedure_handle, godot_array *p_args) {
godot_gdnative_procedure_fn proc;
proc = (godot_gdnative_procedure_fn)p_procedure_handle;
return proc(p_args);
}
GDNativeCallRegistry *GDNativeCallRegistry::singleton;
Vector<Ref<GDNative> > singleton_gdnatives;
GDNativeLibraryResourceLoader *resource_loader_gdnlib = NULL;
GDNativeLibraryResourceSaver *resource_saver_gdnlib = NULL;
void register_gdnative_types() {
#ifdef TOOLS_ENABLED
EditorNode::add_init_callback(editor_init_callback);
#endif
ClassDB::register_class<GDNativeLibrary>();
ClassDB::register_class<GDNative>();
resource_loader_gdnlib = memnew(GDNativeLibraryResourceLoader);
resource_saver_gdnlib = memnew(GDNativeLibraryResourceSaver);
ResourceLoader::add_resource_format_loader(resource_loader_gdnlib);
ResourceSaver::add_resource_format_saver(resource_saver_gdnlib);
GDNativeCallRegistry::singleton = memnew(GDNativeCallRegistry);
GDNativeCallRegistry::singleton->register_native_call_type("standard_varcall", cb_standard_varcall);
register_arvr_types();
register_nativescript_types();
register_pluginscript_types();
// run singletons
Array singletons = Array();
if (ProjectSettings::get_singleton()->has_setting("gdnative/singletons")) {
singletons = ProjectSettings::get_singleton()->get("gdnative/singletons");
}
singleton_gdnatives.resize(singletons.size());
for (int i = 0; i < singletons.size(); i++) {
String path = singletons[i];
Ref<GDNativeLibrary> lib = ResourceLoader::load(path);
singleton_gdnatives[i].instance();
singleton_gdnatives[i]->set_library(lib);
if (!singleton_gdnatives[i]->initialize()) {
// Can't initialize. Don't make a native_call then
continue;
}
void *proc_ptr;
Error err = singleton_gdnatives[i]->get_symbol(
lib->get_symbol_prefix() + "gdnative_singleton",
proc_ptr);
if (err != OK) {
ERR_PRINT((String("No godot_gdnative_singleton in \"" + singleton_gdnatives[i]->get_library()->get_current_library_path()) + "\" found").utf8().get_data());
} else {
((void (*)())proc_ptr)();
}
}
}
void unregister_gdnative_types() {
for (int i = 0; i < singleton_gdnatives.size(); i++) {
if (singleton_gdnatives[i].is_null()) {
continue;
}
if (!singleton_gdnatives[i]->is_initialized()) {
continue;
}
singleton_gdnatives[i]->terminate();
}
singleton_gdnatives.clear();
unregister_pluginscript_types();
unregister_nativescript_types();
unregister_arvr_types();
memdelete(GDNativeCallRegistry::singleton);
#ifdef TOOLS_ENABLED
if (Engine::get_singleton()->is_editor_hint() && discoverer != NULL) {
memdelete(discoverer);
}
#endif
memdelete(resource_loader_gdnlib);
memdelete(resource_saver_gdnlib);
// This is for printing out the sizes of the core types
/*
print_line(String("array:\t") + itos(sizeof(Array)));
print_line(String("basis:\t") + itos(sizeof(Basis)));
print_line(String("color:\t") + itos(sizeof(Color)));
print_line(String("dict:\t" ) + itos(sizeof(Dictionary)));
print_line(String("node_path:\t") + itos(sizeof(NodePath)));
print_line(String("plane:\t") + itos(sizeof(Plane)));
print_line(String("poolarray:\t") + itos(sizeof(PoolByteArray)));
print_line(String("quat:\t") + itos(sizeof(Quat)));
print_line(String("rect2:\t") + itos(sizeof(Rect2)));
print_line(String("aabb:\t") + itos(sizeof(AABB)));
print_line(String("rid:\t") + itos(sizeof(RID)));
print_line(String("string:\t") + itos(sizeof(String)));
print_line(String("transform:\t") + itos(sizeof(Transform)));
print_line(String("transfo2D:\t") + itos(sizeof(Transform2D)));
print_line(String("variant:\t") + itos(sizeof(Variant)));
print_line(String("vector2:\t") + itos(sizeof(Vector2)));
print_line(String("vector3:\t") + itos(sizeof(Vector3)));
*/
}
<|endoftext|>
|
<commit_before>#include "partition/partitioner.hpp"
#include "partition/annotated_partition.hpp"
#include "partition/bisection_graph.hpp"
#include "partition/compressed_node_based_graph_reader.hpp"
#include "partition/edge_based_graph_reader.hpp"
#include "partition/node_based_graph_to_edge_based_graph_mapping_reader.hpp"
#include "partition/recursive_bisection.hpp"
#include "util/coordinate.hpp"
#include "util/geojson_debug_logger.hpp"
#include "util/geojson_debug_policies.hpp"
#include "util/integer_range.hpp"
#include "util/json_container.hpp"
#include "util/log.hpp"
#include <algorithm>
#include <iterator>
#include <vector>
#include <boost/assert.hpp>
#include "util/geojson_debug_logger.hpp"
#include "util/geojson_debug_policies.hpp"
#include "util/json_container.hpp"
#include "util/timing_util.hpp"
namespace osrm
{
namespace partition
{
void LogStatistics(const std::string &filename, std::vector<std::uint32_t> bisection_ids)
{
auto compressed_node_based_graph = LoadCompressedNodeBasedGraph(filename);
util::Log() << "Loaded compressed node based graph: "
<< compressed_node_based_graph.edges.size() << " edges, "
<< compressed_node_based_graph.coordinates.size() << " nodes";
groupEdgesBySource(begin(compressed_node_based_graph.edges),
end(compressed_node_based_graph.edges));
auto graph =
makeBisectionGraph(compressed_node_based_graph.coordinates,
adaptToBisectionEdge(std::move(compressed_node_based_graph.edges)));
TIMER_START(annotation);
AnnotatedPartition partition(graph, bisection_ids);
TIMER_STOP(annotation);
std::cout << "Annotation took " << TIMER_SEC(annotation) << " seconds" << std::endl;
}
void LogGeojson(const std::string &filename, const std::vector<std::uint32_t> &bisection_ids)
{
// reload graph, since we destroyed the old one
auto compressed_node_based_graph = LoadCompressedNodeBasedGraph(filename);
util::Log() << "Loaded compressed node based graph: "
<< compressed_node_based_graph.edges.size() << " edges, "
<< compressed_node_based_graph.coordinates.size() << " nodes";
groupEdgesBySource(begin(compressed_node_based_graph.edges),
end(compressed_node_based_graph.edges));
auto graph =
makeBisectionGraph(compressed_node_based_graph.coordinates,
adaptToBisectionEdge(std::move(compressed_node_based_graph.edges)));
const auto get_level = [](const std::uint32_t lhs, const std::uint32_t rhs) {
auto xored = lhs ^ rhs;
std::uint32_t level = log(xored) / log(2.0);
return level;
};
std::vector<std::vector<util::Coordinate>> border_vertices(33);
for (NodeID nid = 0; nid < graph.NumberOfNodes(); ++nid)
{
const auto source_id = bisection_ids[nid];
for (const auto &edge : graph.Edges(nid))
{
const auto target_id = bisection_ids[edge.target];
if (source_id != target_id)
{
auto level = get_level(source_id, target_id);
border_vertices[level].push_back(graph.Node(nid).coordinate);
border_vertices[level].push_back(graph.Node(edge.target).coordinate);
}
}
}
util::ScopedGeojsonLoggerGuard<util::CoordinateVectorToMultiPoint> guard(
"border_vertices.geojson");
std::size_t level = 0;
for (auto &bv : border_vertices)
{
if (!bv.empty())
{
std::sort(bv.begin(), bv.end(), [](const auto lhs, const auto rhs) {
return std::tie(lhs.lon, lhs.lat) < std::tie(rhs.lon, rhs.lat);
});
bv.erase(std::unique(bv.begin(), bv.end()), bv.end());
util::json::Object jslevel;
jslevel.values["level"] = util::json::Number(level++);
guard.Write(bv, jslevel);
}
}
}
int Partitioner::Run(const PartitionConfig &config)
{
auto compressed_node_based_graph =
LoadCompressedNodeBasedGraph(config.compressed_node_based_graph_path.string());
util::Log() << "Loaded compressed node based graph: "
<< compressed_node_based_graph.edges.size() << " edges, "
<< compressed_node_based_graph.coordinates.size() << " nodes";
groupEdgesBySource(begin(compressed_node_based_graph.edges),
end(compressed_node_based_graph.edges));
auto graph =
makeBisectionGraph(compressed_node_based_graph.coordinates,
adaptToBisectionEdge(std::move(compressed_node_based_graph.edges)));
util::Log() << " running partition: " << config.maximum_cell_size << " " << config.balance
<< " " << config.boundary_factor << " " << config.num_optimizing_cuts << " "
<< config.small_component_size
<< " # max_cell_size balance boundary cuts small_component_size";
RecursiveBisection recursive_bisection(graph,
config.maximum_cell_size,
config.balance,
config.boundary_factor,
config.num_optimizing_cuts,
config.small_component_size);
LogStatistics(config.compressed_node_based_graph_path.string(),
recursive_bisection.BisectionIDs());
// Up until now we worked on the compressed node based graph.
// But what we actually need is a partition for the edge based graph to work on.
// The following loads a mapping from node based graph to edge based graph.
// Then loads the edge based graph tanslates the partition and modifies it.
// For details see #3205
auto mapping = LoadNodeBasedGraphToEdgeBasedGraphMapping(config.nbg_ebg_mapping_path.string());
util::Log() << "Loaded node based graph to edge based graph mapping";
auto edge_based_graph = LoadEdgeBasedGraph(config.edge_based_graph_path.string());
util::Log() << "Loaded edge based graph for mapping partition ids: "
<< edge_based_graph->GetNumberOfEdges() << " edges, "
<< edge_based_graph->GetNumberOfNodes() << " nodes";
// TODO: put translation into own function / file
const auto &partition_ids = recursive_bisection.BisectionIDs();
std::vector<NodeID> edge_based_border_nodes;
// Extract edge based border nodes, based on node based partition and mapping.
for (const auto node_id : util::irange(0u, edge_based_graph->GetNumberOfNodes()))
{
const auto node_based_nodes = mapping.Lookup(node_id);
const auto u = node_based_nodes.u;
const auto v = node_based_nodes.v;
if (partition_ids[u] == partition_ids[v])
{
// Can use partition_ids[u/v] as partition for edge based graph `node_id`
}
else
{
// Border nodes u,v - need to be resolved.
edge_based_border_nodes.push_back(node_id);
}
}
util::Log() << "Fixing " << edge_based_border_nodes.size() << " edge based graph border nodes";
std::vector<std::pair<NodeID, EdgeBasedGraphEdgeData>> incoming_edges;
for (const auto border_node : edge_based_border_nodes)
{
for (const auto edge : edge_based_graph->GetAdjacentEdgeRange(border_node))
{
const auto &data = edge_based_graph->GetEdgeData(edge);
if (data.backward)
{
incoming_edges.emplace_back(edge_based_graph->GetTarget(edge), data);
edge_based_graph->DeleteEdge(border_node, edge);
}
}
const auto artificial = edge_based_graph->InsertNode();
EdgeBasedGraphEdgeData dummy{SPECIAL_EDGEID, /*is_boundary_arc=*/true, 0, 0, false, false};
for (const auto edge : incoming_edges)
{
edge_based_graph->InsertEdge(edge.first, artificial, edge.second);
}
incoming_edges.clear();
}
return 0;
}
} // namespace partition
} // namespace osrm
<commit_msg>Sigh. Just randomly pick a side for border nodes for now..<commit_after>#include "partition/partitioner.hpp"
#include "partition/annotated_partition.hpp"
#include "partition/bisection_graph.hpp"
#include "partition/compressed_node_based_graph_reader.hpp"
#include "partition/edge_based_graph_reader.hpp"
#include "partition/node_based_graph_to_edge_based_graph_mapping_reader.hpp"
#include "partition/recursive_bisection.hpp"
#include "util/coordinate.hpp"
#include "util/geojson_debug_logger.hpp"
#include "util/geojson_debug_policies.hpp"
#include "util/integer_range.hpp"
#include "util/json_container.hpp"
#include "util/log.hpp"
#include <algorithm>
#include <iterator>
#include <vector>
#include <boost/assert.hpp>
#include "util/geojson_debug_logger.hpp"
#include "util/geojson_debug_policies.hpp"
#include "util/json_container.hpp"
#include "util/timing_util.hpp"
namespace osrm
{
namespace partition
{
void LogStatistics(const std::string &filename, std::vector<std::uint32_t> bisection_ids)
{
auto compressed_node_based_graph = LoadCompressedNodeBasedGraph(filename);
util::Log() << "Loaded compressed node based graph: "
<< compressed_node_based_graph.edges.size() << " edges, "
<< compressed_node_based_graph.coordinates.size() << " nodes";
groupEdgesBySource(begin(compressed_node_based_graph.edges),
end(compressed_node_based_graph.edges));
auto graph =
makeBisectionGraph(compressed_node_based_graph.coordinates,
adaptToBisectionEdge(std::move(compressed_node_based_graph.edges)));
TIMER_START(annotation);
AnnotatedPartition partition(graph, bisection_ids);
TIMER_STOP(annotation);
std::cout << "Annotation took " << TIMER_SEC(annotation) << " seconds" << std::endl;
}
void LogGeojson(const std::string &filename, const std::vector<std::uint32_t> &bisection_ids)
{
// reload graph, since we destroyed the old one
auto compressed_node_based_graph = LoadCompressedNodeBasedGraph(filename);
util::Log() << "Loaded compressed node based graph: "
<< compressed_node_based_graph.edges.size() << " edges, "
<< compressed_node_based_graph.coordinates.size() << " nodes";
groupEdgesBySource(begin(compressed_node_based_graph.edges),
end(compressed_node_based_graph.edges));
auto graph =
makeBisectionGraph(compressed_node_based_graph.coordinates,
adaptToBisectionEdge(std::move(compressed_node_based_graph.edges)));
const auto get_level = [](const std::uint32_t lhs, const std::uint32_t rhs) {
auto xored = lhs ^ rhs;
std::uint32_t level = log(xored) / log(2.0);
return level;
};
std::vector<std::vector<util::Coordinate>> border_vertices(33);
for (NodeID nid = 0; nid < graph.NumberOfNodes(); ++nid)
{
const auto source_id = bisection_ids[nid];
for (const auto &edge : graph.Edges(nid))
{
const auto target_id = bisection_ids[edge.target];
if (source_id != target_id)
{
auto level = get_level(source_id, target_id);
border_vertices[level].push_back(graph.Node(nid).coordinate);
border_vertices[level].push_back(graph.Node(edge.target).coordinate);
}
}
}
util::ScopedGeojsonLoggerGuard<util::CoordinateVectorToMultiPoint> guard(
"border_vertices.geojson");
std::size_t level = 0;
for (auto &bv : border_vertices)
{
if (!bv.empty())
{
std::sort(bv.begin(), bv.end(), [](const auto lhs, const auto rhs) {
return std::tie(lhs.lon, lhs.lat) < std::tie(rhs.lon, rhs.lat);
});
bv.erase(std::unique(bv.begin(), bv.end()), bv.end());
util::json::Object jslevel;
jslevel.values["level"] = util::json::Number(level++);
guard.Write(bv, jslevel);
}
}
}
int Partitioner::Run(const PartitionConfig &config)
{
auto compressed_node_based_graph =
LoadCompressedNodeBasedGraph(config.compressed_node_based_graph_path.string());
util::Log() << "Loaded compressed node based graph: "
<< compressed_node_based_graph.edges.size() << " edges, "
<< compressed_node_based_graph.coordinates.size() << " nodes";
groupEdgesBySource(begin(compressed_node_based_graph.edges),
end(compressed_node_based_graph.edges));
auto graph =
makeBisectionGraph(compressed_node_based_graph.coordinates,
adaptToBisectionEdge(std::move(compressed_node_based_graph.edges)));
util::Log() << " running partition: " << config.maximum_cell_size << " " << config.balance
<< " " << config.boundary_factor << " " << config.num_optimizing_cuts << " "
<< config.small_component_size
<< " # max_cell_size balance boundary cuts small_component_size";
RecursiveBisection recursive_bisection(graph,
config.maximum_cell_size,
config.balance,
config.boundary_factor,
config.num_optimizing_cuts,
config.small_component_size);
LogStatistics(config.compressed_node_based_graph_path.string(),
recursive_bisection.BisectionIDs());
// Up until now we worked on the compressed node based graph.
// But what we actually need is a partition for the edge based graph to work on.
// The following loads a mapping from node based graph to edge based graph.
// Then loads the edge based graph tanslates the partition and modifies it.
// For details see #3205
auto mapping = LoadNodeBasedGraphToEdgeBasedGraphMapping(config.nbg_ebg_mapping_path.string());
util::Log() << "Loaded node based graph to edge based graph mapping";
auto edge_based_graph = LoadEdgeBasedGraph(config.edge_based_graph_path.string());
util::Log() << "Loaded edge based graph for mapping partition ids: "
<< edge_based_graph->GetNumberOfEdges() << " edges, "
<< edge_based_graph->GetNumberOfNodes() << " nodes";
// TODO: node based graph to edge based graph partition id mapping should be done split off.
// Partition ids, keyed by node based graph nodes
const auto &node_based_partition_ids = recursive_bisection.BisectionIDs();
// Partition ids, keyed by edge based graph nodes
std::vector<NodeID> edge_based_partition_ids(edge_based_graph->GetNumberOfNodes());
// Extract edge based border nodes, based on node based partition and mapping.
for (const auto node : util::irange(0u, edge_based_graph->GetNumberOfNodes()))
{
const auto node_based_nodes = mapping.Lookup(node);
const auto u = node_based_nodes.u;
const auto v = node_based_nodes.v;
if (node_based_partition_ids[u] == node_based_partition_ids[v])
{
// Can use partition_ids[u/v] as partition for edge based graph `node_id`
edge_based_partition_ids[node] = node_based_partition_ids[u];
}
else
{
// Border nodes u,v - need to be resolved.
// FIXME: just pick one side for now. See #3205.
edge_based_partition_ids[node] = node_based_partition_ids[u];
}
}
return 0;
}
} // namespace partition
} // namespace osrm
<|endoftext|>
|
<commit_before>// This header intentionally has no include guards.
// Preparing ConfigIndex, etc for remapclasses_initialize_vector_loader.
// And, it's a valuable opportunity to traverse checkbox.xml. (it takes very long time!)
// We handle other data at this time.
//
// Targets:
// - ConfigIndex (for <only>,<not> filter)
// - KeyCode::VK_CONFIG_*
// - essential_configurations
// - preferences_node_tree
//
template <class preferences_node_tree_t>
class remapclasses_initialize_vector_prepare_loader final {
public:
remapclasses_initialize_vector_prepare_loader(const xml_compiler& xml_compiler,
symbol_map& symbol_map,
std::vector<std::shared_ptr<essential_configuration>>& essential_configurations,
preferences_node_tree_t* preferences_node_tree) : xml_compiler_(xml_compiler),
symbol_map_(symbol_map),
essential_configurations_(essential_configurations),
preferences_node_tree_(preferences_node_tree),
root_preferences_node_tree_(preferences_node_tree) {}
void traverse(const extracted_ptree& pt) {
for (const auto& it : pt) {
// Hack for speed improvement.
// We can stop traversing when we met <autogen>.
if (it.get_tag_name() == "autogen") {
continue;
}
// traverse
{
if (it.get_tag_name() != "item") {
if (!it.children_empty()) {
traverse(it.children_extracted_ptree());
}
} else {
// preferences_node_tree
assert(preferences_node_tree_);
std::shared_ptr<preferences_node_tree_t> ptr(new preferences_node_tree_t(preferences_node_tree_->get_node()));
assert(ptr);
for (const auto& child : it.children_extracted_ptree()) {
ptr->handle_item_child(child);
if (child.get_tag_name() == "identifier") {
auto raw_identifier = boost::trim_copy(child.get_data());
if (xml_compiler_.valid_identifier_(raw_identifier, it.get_tag_name())) {
auto identifier = raw_identifier;
normalize_identifier_(identifier);
// ----------------------------------------
auto attr_essential = child.get_optional("<xmlattr>.essential");
if (attr_essential) {
essential_configurations_.push_back(std::shared_ptr<essential_configuration>(new essential_configuration(ptr->get_node())));
// Do not treat essentials anymore.
continue;
}
// ----------------------------------------
auto attr_vk_config = child.get_optional("<xmlattr>.vk_config");
if (attr_vk_config) {
const char* names[] = {
"VK_CONFIG_TOGGLE_",
"VK_CONFIG_FORCE_ON_",
"VK_CONFIG_FORCE_OFF_",
"VK_CONFIG_SYNC_KEYDOWNUP_",
};
for (const auto& n : names) {
symbol_map_.add("KeyCode", std::string(n) + identifier);
}
}
// ----------------------------------------
if (boost::starts_with(identifier, "notsave_")) {
identifiers_notsave_.push_back(identifier);
} else {
identifiers_except_notsave_.push_back(identifier);
}
}
}
}
auto saved_preferences_node_tree = preferences_node_tree_;
preferences_node_tree_ = ptr.get();
{
if (!it.children_empty()) {
traverse(it.children_extracted_ptree());
}
}
preferences_node_tree_ = saved_preferences_node_tree;
auto attr_hidden = it.get_optional("<xmlattr>.hidden");
if (!attr_hidden) {
preferences_node_tree_->push_back(ptr);
}
}
}
}
}
// call "fixup" at traversing each file.
void fixup(void) {
preferences_node_tree_ = root_preferences_node_tree_;
}
// call "cleanup" at finished traversing all files.
void cleanup(void) {
fixup();
// "notsave" has higher priority.
for (const auto& it : identifiers_notsave_) {
symbol_map_.add("ConfigIndex", it);
}
identifiers_notsave_.clear();
for (const auto& it : identifiers_except_notsave_) {
symbol_map_.add("ConfigIndex", it);
}
identifiers_except_notsave_.clear();
}
private:
const xml_compiler& xml_compiler_;
symbol_map& symbol_map_;
std::vector<std::shared_ptr<essential_configuration>>& essential_configurations_;
preferences_node_tree_t* preferences_node_tree_;
preferences_node_tree_t* const root_preferences_node_tree_;
std::vector<std::string> identifiers_notsave_;
std::vector<std::string> identifiers_except_notsave_;
};
<commit_msg>add high_priority attribute<commit_after>// This header intentionally has no include guards.
// Preparing ConfigIndex, etc for remapclasses_initialize_vector_loader.
// And, it's a valuable opportunity to traverse checkbox.xml. (it takes very long time!)
// We handle other data at this time.
//
// Targets:
// - ConfigIndex (for <only>,<not> filter)
// - KeyCode::VK_CONFIG_*
// - essential_configurations
// - preferences_node_tree
//
template <class preferences_node_tree_t>
class remapclasses_initialize_vector_prepare_loader final {
public:
remapclasses_initialize_vector_prepare_loader(const xml_compiler& xml_compiler,
symbol_map& symbol_map,
std::vector<std::shared_ptr<essential_configuration>>& essential_configurations,
preferences_node_tree_t* preferences_node_tree) : xml_compiler_(xml_compiler),
symbol_map_(symbol_map),
essential_configurations_(essential_configurations),
preferences_node_tree_(preferences_node_tree),
root_preferences_node_tree_(preferences_node_tree) {}
void traverse(const extracted_ptree& pt) {
for (const auto& it : pt) {
// Hack for speed improvement.
// We can stop traversing when we met <autogen>.
if (it.get_tag_name() == "autogen") {
continue;
}
// traverse
{
if (it.get_tag_name() != "item") {
if (!it.children_empty()) {
traverse(it.children_extracted_ptree());
}
} else {
// preferences_node_tree
assert(preferences_node_tree_);
std::shared_ptr<preferences_node_tree_t> ptr(new preferences_node_tree_t(preferences_node_tree_->get_node()));
assert(ptr);
for (const auto& child : it.children_extracted_ptree()) {
ptr->handle_item_child(child);
if (child.get_tag_name() == "identifier") {
auto raw_identifier = boost::trim_copy(child.get_data());
if (xml_compiler_.valid_identifier_(raw_identifier, it.get_tag_name())) {
auto identifier = raw_identifier;
normalize_identifier_(identifier);
// ----------------------------------------
auto attr_essential = child.get_optional("<xmlattr>.essential");
if (attr_essential) {
essential_configurations_.push_back(std::shared_ptr<essential_configuration>(new essential_configuration(ptr->get_node())));
// Do not treat essentials anymore.
continue;
}
// ----------------------------------------
auto attr_vk_config = child.get_optional("<xmlattr>.vk_config");
if (attr_vk_config) {
const char* names[] = {
"VK_CONFIG_TOGGLE_",
"VK_CONFIG_FORCE_ON_",
"VK_CONFIG_FORCE_OFF_",
"VK_CONFIG_SYNC_KEYDOWNUP_",
};
for (const auto& n : names) {
symbol_map_.add("KeyCode", std::string(n) + identifier);
}
}
// ----------------------------------------
auto attr_high_priority = child.get_optional("<xmlattr>.high_priority");
if (boost::starts_with(identifier, "notsave_") ||
attr_high_priority) {
identifiers_high_priority_.push_back(identifier);
} else {
identifiers_normal_priority_.push_back(identifier);
}
}
}
}
auto saved_preferences_node_tree = preferences_node_tree_;
preferences_node_tree_ = ptr.get();
{
if (!it.children_empty()) {
traverse(it.children_extracted_ptree());
}
}
preferences_node_tree_ = saved_preferences_node_tree;
auto attr_hidden = it.get_optional("<xmlattr>.hidden");
if (!attr_hidden) {
preferences_node_tree_->push_back(ptr);
}
}
}
}
}
// call "fixup" at traversing each file.
void fixup(void) {
preferences_node_tree_ = root_preferences_node_tree_;
}
// call "cleanup" at finished traversing all files.
void cleanup(void) {
fixup();
// "notsave" has higher priority.
for (const auto& it : identifiers_high_priority_) {
symbol_map_.add("ConfigIndex", it);
}
identifiers_high_priority_.clear();
for (const auto& it : identifiers_normal_priority_) {
symbol_map_.add("ConfigIndex", it);
}
identifiers_normal_priority_.clear();
}
private:
const xml_compiler& xml_compiler_;
symbol_map& symbol_map_;
std::vector<std::shared_ptr<essential_configuration>>& essential_configurations_;
preferences_node_tree_t* preferences_node_tree_;
preferences_node_tree_t* const root_preferences_node_tree_;
std::vector<std::string> identifiers_high_priority_;
std::vector<std::string> identifiers_normal_priority_;
};
<|endoftext|>
|
<commit_before>#include <iostream>
#include <fstream>
#include <codecvt>
//#include <cstddef>
#include <locale>
#include <clocale>
#include <string>
#include <iomanip>
#include <ctime>
#include "cp-neural.h"
using std::wcout; using std::wstring;
using std::cerr; using std::vector;
class Text {
private:
bool isinit=false;
bool readDataFile(string inputfile) {
std::wifstream txtfile(inputfile, std::ios::binary);
if (!txtfile.is_open()) {
return false;
}
txtfile.imbue(std::locale("en_US.UTF-8"));
wstring ttext((std::istreambuf_iterator<wchar_t>(txtfile)),
std::istreambuf_iterator<wchar_t>());
txtfile.close();
text=ttext;
filename=inputfile;
return true;
}
public:
wstring text;
string filename;
std::map<wchar_t,int> freq;
std::map<wchar_t,int> w2v;
std::map<int,wchar_t> v2w;
Text(string filename) {
if (readDataFile(filename)) {
for (auto wc : text) {
freq[wc]++;
}
int it=0;
for (auto wc : freq) {
w2v[wc.first]=it;
v2w[it]=wc.first;
++it;
}
isinit=true;
cerr << "Freq:" << freq.size() << ", w2v:" << w2v.size() << ", v2w:" << v2w.size() << endl;
}
}
~Text() {
}
bool isInit() {
return isinit;
}
int vocsize() {
if (!isinit) return 0;
return (int)v2w.size();
}
wstring sample(int len) {
int p=std::rand()%(text.size()-len);
return text.substr(p,len);
}
};
void currentDateTime(wstring& timestr) {
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
// Visit http://en.cppreference.com/w/cpp/chrono/c/strftime
// for more information about date/time format
strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct);
timestr=std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes(buf);
}
int main(int argc, char *argv[]) {
#ifndef __APPLE__
std::setlocale(LC_ALL, "");
#else
setlocale(LC_ALL, "");
std::wcout.imbue(std::locale("en_US.UTF-8"));
#endif
wcout << L"Rnn-Readär" << std::endl;
bool allOk=true;
if (argc!=2) {
cerr << L"rnnreader <path-to-text-file>" << endl;
exit(-1);
}
Text txt(argv[1]);
if (!txt.isInit()) {
cerr << "Cannot initialize Text object from inputfile: " << argv[1] << endl;
exit(-1);
}
wcout << L"Text size: " << txt.text.size() << endl;
wcout << L"Size of vocabulary:" << txt.freq.size() << std::endl;
/* for (auto f : txt.freq) {
int c=(int)f.first;
wstring wc(1,f.first);
wcout << wc << L"|" << wchar_t(f.first) << L"(0x" << std::hex << c << L")" ": " << std::dec << f.second << endl;
}
*/
Color::Modifier red(Color::FG_RED);
Color::Modifier green(Color::FG_GREEN);
Color::Modifier def(Color::FG_DEFAULT);
int T=80;
int N=(int)txt.text.size() / (T+1);
cerr << N << " Max datasets" << endl;
MatrixN Xr(N,T);
MatrixN yr(N,T);
wstring chunk,chunky;
int n=0;
for (int i=0; i<N; i++) {
wstring smp = txt.sample(T+1);
chunk=smp.substr(0,T);
chunky=smp.substr(1,T);
for (int t=0; t<T; t++) {
Xr(i,t)=txt.w2v[chunk[t]];
yr(i,t)=txt.w2v[chunky[t]];
}
++n;
}
int maxN = 100000;
if (n>maxN) n=maxN;
int n1=n*0.9;
int dn=(n-n1)/2;
if (n1+2*dn > n) {
cerr << "Math doesn't work out." << endl;
}
cerr << n1 << " datasets, " << dn << " test-sets, " << dn << " validation-sets" << endl;
/* MatrixN X(n1,T);
MatrixN y(n1,T);
MatrixN Xv(dn,T);
MatrixN yv(dn,T);
MatrixN Xt(dn,T);
MatrixN yt(dn,T);
*/
MatrixN X=Xr.block(0,0,n1,T);
MatrixN y=yr.block(0,0,n1,T);
MatrixN Xv=Xr.block(n1,0,dn,T);
MatrixN yv=yr.block(n1,0,dn,T);
MatrixN Xt=Xr.block(n1+dn,0,dn,T);
MatrixN yt=yr.block(n1+dn,0,dn,T);
unsigned int ctm=(unsigned int)std::time(0);
std::srand(ctm);
cpInitCompute("Rnnreader");
registerLayers();
LayerBlock lb(R"({"name":"rnnreader","init":"orthonormal","initfactor":0.03})"_json);
int VS=txt.vocsize();
int H=512;
int BS=128;
float clip=5.0;
//int D=64;
// CpParams cp0;
// cp0.setPar("inputShape",vector<int>{T});
// cp0.setPar("V",VS);
// cp0.setPar("D",D);
// cp0.setPar("clip",clip);
// cp0.setPar("init",(string)"orthonormal");
// lb.addLayer("WordEmbedding","WE0",cp0,{"input"});
string rnntype="LSTM"; // or "RNN"
cerr << "RNN-type: " << rnntype << endl;
json j0;
string oName{"OH0"};
j0["inputShape"]=vector<int>{T};
j0["V"]=VS;
lb.addLayer("OneHot",oName,j0,{"input"});
string nName;
json j1;
j1["inputShape"]=vector<int>{VS,T};
j1["N"]=BS;
j1["H"]=H;
j1["forgetgateinitones"]=true;
j1["forgetbias"]=0.30;
j1["clip"]=clip;
int layer_depth1=4;
j1["H"]=H;
for (auto l=0; l<layer_depth1; l++) {
if (l>0) j1["inputShape"]=vector<int>{H,T};
nName="lstm"+std::to_string(l);
lb.addLayer(rnntype,nName,j1,{oName});
oName=nName;
}
json j10;
j10["inputShape"]=vector<int>{H,T};
j10["M"]=VS;
lb.addLayer("TemporalAffine","af1",j10,{oName});
json j11;
j11["inputShape"]=vector<int>{VS,T};
lb.addLayer("TemporalSoftmax","sm1",j11,{"af1"});
if (!lb.checkTopology(true)) {
allOk=false;
cerr << red << "Topology-check for LayerBlock: ERROR." << def << endl;
} else {
cerr << green << "Topology-check for LayerBlock: ok." << def << endl;
}
//json jc;
//lb.getLayerConfiguration(jc);
//cerr << jc.dump(4) << endl;
// preseverstates no longer necessary for training!
json jo(R"({"verbose":true,"shuffle":false,"preservestates":false,"notests":false,"nofragmentbatches":true,"epsilon":1e-8})"_json);
jo["lossfactor"]=1.0/(floatN)T; // Allows to normalize the loss with T.
jo["learning_rate"]=(floatN)2e-2; //2.2e-2);
floatN dep=25.0;
floatN sep=0.0;
jo["epochs"]=(floatN)dep;
jo["batch_size"]=BS;
for (int i=0; i<10000; i++) {
jo["startepoch"]=(floatN)sep;
t_cppl states;
t_cppl statesv;
states["y"] = new MatrixN(y);
statesv["y"] = new MatrixN(yv);
lb.train(X, &states, Xv, &statesv, "Adam", jo);
cppl_delete(&states);
cppl_delete(&statesv);
sep+=dep;
int pos=rand() % 1000 + 5000;
wstring instr=txt.text.substr(pos,T);
MatrixN xg(1,T);
for (int i=0; i<T; i++) {
xg(0,i)=txt.w2v[instr[i]];
}
wstring sout{};
Layer* plstm0=lb.layerMap["lstm0"];
t_cppl statesg{};
plstm0->genZeroStates(&statesg, 1);
int g,t,v;
for (g=0; g<500; g++) {
t_cppl cache{};
MatrixN probst=lb.forward(xg,&cache, &statesg);
MatrixN probsd=MatrixN(T,VS);
for (t=0; t<T; t++) {
for (v=0; v<VS; v++) {
probsd(t,v)=probst(0,t*VS+v);
}
}
int li=-1;
for (t=0; t<T; t++) {
vector<floatN> probs(VS);
vector<floatN> index(VS);
for (v=0; v<VS; v++) {
probs[v]=probsd(t,v);
index[v]=v;
}
li=(int)index[randomChoice(index, probs)];
}
cppl_delete(&cache);
for (int t=0; t<T-1; t++) {
xg(0,t)=xg(0,t+1);
}
xg(0,T-1)=li;
sout += txt.v2w[li];
}
wcout << "output: " << sout << endl;
wstring timestr;
currentDateTime(timestr);
std::wofstream fl("rnnreader.txt", std::ios_base::app);
fl << "---- " << timestr << ", ep:" << sep << " ---" << endl;
fl << sout << endl;
fl.close();
cppl_delete(&statesg);
}
cpExitCompute();
}
<commit_msg>smaller for M1<commit_after>#include <iostream>
#include <fstream>
#include <codecvt>
//#include <cstddef>
#include <locale>
#include <clocale>
#include <string>
#include <iomanip>
#include <ctime>
#include "cp-neural.h"
using std::wcout; using std::wstring;
using std::cerr; using std::vector;
class Text {
private:
bool isinit=false;
bool readDataFile(string inputfile) {
std::wifstream txtfile(inputfile, std::ios::binary);
if (!txtfile.is_open()) {
return false;
}
txtfile.imbue(std::locale("en_US.UTF-8"));
wstring ttext((std::istreambuf_iterator<wchar_t>(txtfile)),
std::istreambuf_iterator<wchar_t>());
txtfile.close();
text=ttext;
filename=inputfile;
return true;
}
public:
wstring text;
string filename;
std::map<wchar_t,int> freq;
std::map<wchar_t,int> w2v;
std::map<int,wchar_t> v2w;
Text(string filename) {
if (readDataFile(filename)) {
for (auto wc : text) {
freq[wc]++;
}
int it=0;
for (auto wc : freq) {
w2v[wc.first]=it;
v2w[it]=wc.first;
++it;
}
isinit=true;
cerr << "Freq:" << freq.size() << ", w2v:" << w2v.size() << ", v2w:" << v2w.size() << endl;
}
}
~Text() {
}
bool isInit() {
return isinit;
}
int vocsize() {
if (!isinit) return 0;
return (int)v2w.size();
}
wstring sample(int len) {
int p=std::rand()%(text.size()-len);
return text.substr(p,len);
}
};
void currentDateTime(wstring& timestr) {
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
// Visit http://en.cppreference.com/w/cpp/chrono/c/strftime
// for more information about date/time format
strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct);
timestr=std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes(buf);
}
int main(int argc, char *argv[]) {
#ifndef __APPLE__
std::setlocale(LC_ALL, "");
#else
setlocale(LC_ALL, "");
std::wcout.imbue(std::locale("en_US.UTF-8"));
#endif
wcout << L"Rnn-Readär" << std::endl;
bool allOk=true;
if (argc!=2) {
cerr << L"rnnreader <path-to-text-file>" << endl;
exit(-1);
}
Text txt(argv[1]);
if (!txt.isInit()) {
cerr << "Cannot initialize Text object from inputfile: " << argv[1] << endl;
exit(-1);
}
wcout << L"Text size: " << txt.text.size() << endl;
wcout << L"Size of vocabulary:" << txt.freq.size() << std::endl;
/* for (auto f : txt.freq) {
int c=(int)f.first;
wstring wc(1,f.first);
wcout << wc << L"|" << wchar_t(f.first) << L"(0x" << std::hex << c << L")" ": " << std::dec << f.second << endl;
}
*/
Color::Modifier red(Color::FG_RED);
Color::Modifier green(Color::FG_GREEN);
Color::Modifier def(Color::FG_DEFAULT);
int T=64;
int N=(int)txt.text.size() / (T+1);
cerr << N << " Max datasets" << endl;
MatrixN Xr(N,T);
MatrixN yr(N,T);
wstring chunk,chunky;
int n=0;
for (int i=0; i<N; i++) {
wstring smp = txt.sample(T+1);
chunk=smp.substr(0,T);
chunky=smp.substr(1,T);
for (int t=0; t<T; t++) {
Xr(i,t)=txt.w2v[chunk[t]];
yr(i,t)=txt.w2v[chunky[t]];
}
++n;
}
int maxN = 100000;
if (n>maxN) n=maxN;
int n1=n*0.9;
int dn=(n-n1)/2;
if (n1+2*dn > n) {
cerr << "Math doesn't work out." << endl;
}
cerr << n1 << " datasets, " << dn << " test-sets, " << dn << " validation-sets" << endl;
/* MatrixN X(n1,T);
MatrixN y(n1,T);
MatrixN Xv(dn,T);
MatrixN yv(dn,T);
MatrixN Xt(dn,T);
MatrixN yt(dn,T);
*/
MatrixN X=Xr.block(0,0,n1,T);
MatrixN y=yr.block(0,0,n1,T);
MatrixN Xv=Xr.block(n1,0,dn,T);
MatrixN yv=yr.block(n1,0,dn,T);
MatrixN Xt=Xr.block(n1+dn,0,dn,T);
MatrixN yt=yr.block(n1+dn,0,dn,T);
unsigned int ctm=(unsigned int)std::time(0);
std::srand(ctm);
cpInitCompute("Rnnreader");
registerLayers();
LayerBlock lb(R"({"name":"rnnreader","init":"orthonormal","initfactor":0.03})"_json);
int VS=txt.vocsize();
int H=384;
int BS=128;
float clip=5.0;
//int D=64;
// CpParams cp0;
// cp0.setPar("inputShape",vector<int>{T});
// cp0.setPar("V",VS);
// cp0.setPar("D",D);
// cp0.setPar("clip",clip);
// cp0.setPar("init",(string)"orthonormal");
// lb.addLayer("WordEmbedding","WE0",cp0,{"input"});
string rnntype="LSTM"; // or "RNN"
cerr << "RNN-type: " << rnntype << endl;
json j0;
string oName{"OH0"};
j0["inputShape"]=vector<int>{T};
j0["V"]=VS;
lb.addLayer("OneHot",oName,j0,{"input"});
string nName;
json j1;
j1["inputShape"]=vector<int>{VS,T};
j1["N"]=BS;
j1["H"]=H;
j1["forgetgateinitones"]=true;
j1["forgetbias"]=0.30;
j1["clip"]=clip;
int layer_depth1=4;
j1["H"]=H;
for (auto l=0; l<layer_depth1; l++) {
if (l>0) j1["inputShape"]=vector<int>{H,T};
nName="lstm"+std::to_string(l);
lb.addLayer(rnntype,nName,j1,{oName});
oName=nName;
}
json j10;
j10["inputShape"]=vector<int>{H,T};
j10["M"]=VS;
lb.addLayer("TemporalAffine","af1",j10,{oName});
json j11;
j11["inputShape"]=vector<int>{VS,T};
lb.addLayer("TemporalSoftmax","sm1",j11,{"af1"});
if (!lb.checkTopology(true)) {
allOk=false;
cerr << red << "Topology-check for LayerBlock: ERROR." << def << endl;
} else {
cerr << green << "Topology-check for LayerBlock: ok." << def << endl;
}
//json jc;
//lb.getLayerConfiguration(jc);
//cerr << jc.dump(4) << endl;
// preseverstates no longer necessary for training!
json jo(R"({"verbose":true,"shuffle":false,"preservestates":false,"notests":false,"nofragmentbatches":true,"epsilon":1e-8})"_json);
jo["lossfactor"]=1.0/(floatN)T; // Allows to normalize the loss with T.
jo["learning_rate"]=(floatN)2e-2; //2.2e-2);
floatN dep=25.0;
floatN sep=0.0;
jo["epochs"]=(floatN)dep;
jo["batch_size"]=BS;
for (int i=0; i<10000; i++) {
jo["startepoch"]=(floatN)sep;
t_cppl states;
t_cppl statesv;
states["y"] = new MatrixN(y);
statesv["y"] = new MatrixN(yv);
lb.train(X, &states, Xv, &statesv, "Adam", jo);
cppl_delete(&states);
cppl_delete(&statesv);
sep+=dep;
int pos=rand() % 1000 + 5000;
wstring instr=txt.text.substr(pos,T);
MatrixN xg(1,T);
for (int i=0; i<T; i++) {
xg(0,i)=txt.w2v[instr[i]];
}
wstring sout{};
Layer* plstm0=lb.layerMap["lstm0"];
t_cppl statesg{};
plstm0->genZeroStates(&statesg, 1);
int g,t,v;
for (g=0; g<500; g++) {
t_cppl cache{};
MatrixN probst=lb.forward(xg,&cache, &statesg);
MatrixN probsd=MatrixN(T,VS);
for (t=0; t<T; t++) {
for (v=0; v<VS; v++) {
probsd(t,v)=probst(0,t*VS+v);
}
}
int li=-1;
for (t=0; t<T; t++) {
vector<floatN> probs(VS);
vector<floatN> index(VS);
for (v=0; v<VS; v++) {
probs[v]=probsd(t,v);
index[v]=v;
}
li=(int)index[randomChoice(index, probs)];
}
cppl_delete(&cache);
for (int t=0; t<T-1; t++) {
xg(0,t)=xg(0,t+1);
}
xg(0,T-1)=li;
sout += txt.v2w[li];
}
wcout << "output: " << sout << endl;
wstring timestr;
currentDateTime(timestr);
std::wofstream fl("rnnreader.txt", std::ios_base::app);
fl << "---- " << timestr << ", ep:" << sep << " ---" << endl;
fl << sout << endl;
fl.close();
cppl_delete(&statesg);
}
cpExitCompute();
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
* Project: RooFit *
* Package: RooFitCore *
* File: $Id: RooProdPdf.cc,v 1.32 2002/11/18 19:57:44 wverkerke Exp $
* Authors: *
* WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu *
* DK, David Kirkby, UC Irvine, dkirkby@uci.edu *
* *
* Copyright (c) 2000-2002, Regents of the University of California *
* and Stanford University. All rights reserved. *
* *
* Redistribution and use in source and binary forms, *
* with or without modification, are permitted according to the terms *
* listed in LICENSE (http://roofit.sourceforge.net/license.txt) *
*****************************************************************************/
// -- CLASS DESCRIPTION [PDF] --
// RooProdPdf is an efficient implementation of a product of PDFs of the form
//
// PDF_1 * PDF_2 * ... * PDF_N
//
// RooProdPdf relies on each component PDF to be normalized and will perform no
// explicit normalization itself. No PDF may share any dependents with any other PDF.
//
// If exactly one of the component PDFs supports extended likelihood fits, the
// product will also be usable in extended mode, returning the number of expected
// events from the extendable component PDF. The extendable component does not
// have to appear in any specific place in the list.
//
// To construct a product of PDFs that share dependents, and thus require explicit
// normalization of the product, use RooGenericPdf.
#include "TIterator.h"
#include "RooFitCore/RooProdPdf.hh"
#include "RooFitCore/RooRealProxy.hh"
#include "RooFitCore/RooProdGenContext.hh"
ClassImp(RooProdPdf)
;
RooProdPdf::RooProdPdf(const char *name, const char *title, Double_t cutOff) :
RooAbsPdf(name,title),
_pdfList("_pdfList","List of PDFs",this),
_cutOff(cutOff),
_codeReg(10),
_extendedIndex(-1),
_partListMgr(10)
{
// Dummy constructor
}
RooProdPdf::RooProdPdf(const char *name, const char *title,
RooAbsPdf& pdf1, RooAbsPdf& pdf2, Double_t cutOff) :
RooAbsPdf(name,title),
_pdfList("_pdfList","List of PDFs",this),
_pdfIter(_pdfList.createIterator()),
_cutOff(cutOff),
_codeReg(10),
_extendedIndex(-1),
_partListMgr(10)
{
// Constructor with 2 PDFs (most frequent use case).
//
// The optional cutOff parameter can be used as a speed optimization if
// one or more of the PDF have sizable regions with very small values,
// which would pull the entire product of PDFs to zero in those regions.
//
// After each PDF multiplication, the running product is compared with
// the cutOff parameter. If the running product is smaller than the
// cutOff value, the product series is terminated and remaining PDFs
// are not evaluated.
//
// There is no magic value of the cutOff, the user should experiment
// to find the appropriate balance between speed and precision.
// If a cutoff is specified, the PDFs most likely to be small should
// be put first in the product. The default cutOff value is zero.
_pdfList.add(pdf1) ;
if (pdf1.canBeExtended()) {
_extendedIndex = _pdfList.index(&pdf1) ;
}
_pdfList.add(pdf2) ;
if (pdf2.canBeExtended()) {
if (_extendedIndex>=0) {
// Protect against multiple extended terms
cout << "RooProdPdf::RooProdPdf(" << GetName()
<< ") multiple components with extended terms detected,"
<< " product will not be extendible." << endl ;
_extendedIndex=-1 ;
} else {
_extendedIndex=_pdfList.index(&pdf2) ;
}
}
}
RooProdPdf::RooProdPdf(const char* name, const char* title, const RooArgList& pdfList, Double_t cutOff) :
RooAbsPdf(name,title),
_pdfList("_pdfList","List of PDFs",this),
_pdfIter(_pdfList.createIterator()),
_cutOff(cutOff),
_codeReg(10),
_extendedIndex(-1),
_partListMgr(10)
{
// Constructor from a list of PDFs
//
// The optional cutOff parameter can be used as a speed optimization if
// one or more of the PDF have sizable regions with very small values,
// which would pull the entire product of PDFs to zero in those regions.
//
// After each PDF multiplication, the running product is compared with
// the cutOff parameter. If the running product is smaller than the
// cutOff value, the product series is terminated and remaining PDFs
// are not evaluated.
//
// There is no magic value of the cutOff, the user should experiment
// to find the appropriate balance between speed and precision.
// If a cutoff is specified, the PDFs most likely to be small should
// be put first in the product. The default cutOff value is zero.
TIterator* iter = pdfList.createIterator() ;
RooAbsPdf* pdf ;
Int_t numExtended(0) ;
while(pdf=(RooAbsPdf*)iter->Next()) {
if (!dynamic_cast<RooAbsPdf*>(pdf)) {
cout << "RooProdPdf::RooProdPdf(" << GetName() << ") list arg "
<< pdf->GetName() << " is not a PDF, ignored" << endl ;
continue ;
}
_pdfList.add(*pdf) ;
if (pdf->canBeExtended()) {
_extendedIndex = _pdfList.index(pdf) ;
numExtended++ ;
}
}
// Protect against multiple extended terms
if (numExtended>1) {
cout << "RooProdPdf::RooProdPdf(" << GetName()
<< ") WARNING: multiple components with extended terms detected,"
<< " product will not be extendible." << endl ;
_extendedIndex = -1 ;
}
delete iter ;
}
RooProdPdf::RooProdPdf(const RooProdPdf& other, const char* name) :
RooAbsPdf(other,name),
_pdfList("_pdfList",this,other._pdfList),
_pdfIter(_pdfList.createIterator()),
_cutOff(other._cutOff),
_codeReg(other._codeReg),
_extendedIndex(other._extendedIndex),
_partListMgr(other._partListMgr)
{
// Copy constructor
}
RooProdPdf::~RooProdPdf()
{
// Destructor
delete _pdfIter ;
}
Double_t RooProdPdf::evaluate() const
{
// Calculate current unnormalized value of object
const RooArgSet* nset = _pdfList.nset() ;
Int_t code ;
RooArgList* plist = getPartIntList(nset,0,code) ;
return calculate(plist,nset) ;
}
Double_t RooProdPdf::calculate(const RooArgList* partIntList, const RooArgSet* normSet) const
{
// Calculate running product of pdfs, skipping factorized components
RooAbsReal* partInt ;
Double_t value(1.0) ;
Int_t n = partIntList->getSize() ;
Int_t i ;
for (i=0 ; i<n ; i++) {
partInt = ((RooAbsReal*)partIntList->at(i)) ;
Double_t piVal = partInt->getVal(normSet) ;
value *= piVal ;
// if (_verboseEval<0) {
// cout << "RPP:calc(" << GetName() << "): value *= " << piVal << " (" << partInt->GetName() << ")" << endl ;
// }
if (value<_cutOff) {
//cout << "RooProdPdf::calculate(" << GetName() << ") calculation cut off after " << partInt->GetName() << endl ;
break ;
}
}
return value ;
}
RooArgList* RooProdPdf::getPartIntList(const RooArgSet* nset, const RooArgSet* iset, Int_t& code) const
{
// Check if this configuration was created before
RooArgList* partIntList = _partListMgr.getNormList(this,nset,iset) ;
if (partIntList) {
code = _partListMgr.lastIndex() ;
return partIntList ;
}
// Create the partial integral set for this request
_pdfIter->Reset() ;
partIntList = new RooArgList("partIntList") ;
RooAbsPdf* pdf ;
while(pdf=(RooAbsPdf*)_pdfIter->Next()) {
// Check if all dependents of this PDF component appear in the normalization set
Bool_t fact(kFALSE) ;
RooArgSet *pdfDepList = pdf->getDependents(nset) ;
if (pdfDepList->getSize()>0) {
fact=kTRUE ;
TIterator* depIter = pdfDepList->createIterator() ;
RooAbsArg* dep ;
while(dep=(RooAbsArg*)depIter->Next()) {
if (!iset || !iset->find(dep->GetName())) {
fact=kFALSE ;
}
}
delete depIter ;
}
// fact=true -> all integrated pdf dependents are in normalization set
if (fact) {
// This product term factorizes, no partial integral needs to be created
} else if (nset && pdfDepList->getSize()==0) {
} else {
if (iset && iset->getSize()>0) {
RooArgSet* iSet = pdf->getDependents(iset) ;
RooAbsReal* partInt = pdf->createIntegral(*iSet,*pdfDepList) ;
partInt->setOperMode(operMode()) ;
partIntList->addOwned(*partInt) ;
delete iSet ;
} else {
partIntList->add(*pdf) ;
}
}
delete pdfDepList ;
}
// Store the partial integral list and return the assigned code ;
code = _partListMgr.setNormList(this,nset,iset,partIntList) ;
// cout << "RooProdPdf::getPIL(" << GetName() << ") creating new configuration with code " << code << endl
// << " nset = " ; if (nset) nset->Print("1") ; else cout << "<none>" << endl ;
// cout << " iset = " ; if (iset) iset->Print("1") ; else cout << "<none>" << endl ;
// cout << " Partial Integral List:" << endl ;
// partIntList->Print("1") ;
return partIntList ;
}
Int_t RooProdPdf::getAnalyticalIntegralWN(RooArgSet& allVars, RooArgSet& analVars, const RooArgSet* normSet) const
{
// Determine which part (if any) of given integral can be performed analytically.
// If any analytical integration is possible, return integration scenario code.
//
// RooProdPdf implements two strategies in implementing analytical integrals
//
// First, PDF components whose entire set of dependents are requested to be integrated
// can be dropped from the product, as they will integrate out to 1 by construction
//
// Second, RooProdPdf queries each remaining component PDF for its analytical integration
// capability of the requested set ('allVars'). It finds the largest common set of variables
// that can be integrated by all remaining components. If such a set exists, it reconfirms that
// each component is capable of analytically integrating the common set, and combines the components
// individual integration codes into a single integration code valid for RooProdPdf.
if (_forceNumInt) return 0 ;
// Declare that we can analytically integrate all requested observables
analVars.add(allVars) ;
// Retrieve (or create) the required partial integral list
Int_t code ;
getPartIntList(normSet,&allVars,code) ;
return code+1 ;
}
Double_t RooProdPdf::analyticalIntegralWN(Int_t code, const RooArgSet* normSet) const
{
// Return analytical integral defined by given scenario code
// No integration scenario
if (code==0) {
return getVal(normSet) ;
}
// Partial integration scenarios
RooArgList* partIntList = _partListMgr.getNormListByIndex(code-1) ;
return calculate(partIntList,normSet) ;
}
Bool_t RooProdPdf::checkDependents(const RooArgSet* nset) const
{
// Check that none of the PDFs have overlapping dependents
Bool_t ret(kFALSE) ;
_pdfIter->Reset() ;
RooAbsPdf* pdf, *pdf2 ;
TIterator* iter2 = _pdfList.createIterator() ;
while(pdf = (RooAbsPdf*)_pdfIter->Next()) {
*iter2 = *_pdfIter ;
while(pdf2 = (RooAbsPdf*)iter2->Next()) {
if (pdf->dependentOverlaps(nset,*pdf2)) {
cout << "RooProdPdf::checkDependents(" << GetName() << "): ERROR: PDFs " << pdf->GetName()
<< " and " << pdf2->GetName() << " have one or more dependents in common" << endl ;
ret = kTRUE ;
}
}
}
delete iter2 ;
return ret ;
}
RooAbsPdf::ExtendMode RooProdPdf::extendMode() const
{
return (_extendedIndex>=0) ? ((RooAbsPdf*)_pdfList.at(_extendedIndex))->extendMode() : CanNotBeExtended ;
}
Double_t RooProdPdf::expectedEvents() const
{
assert(_extendedIndex>=0) ;
return ((RooAbsPdf*)_pdfList.at(_extendedIndex))->expectedEvents() ;
}
RooAbsGenContext* RooProdPdf::genContext(const RooArgSet &vars, const RooDataSet *prototype, Bool_t verbose) const
{
return new RooProdGenContext(*this,vars,prototype,verbose) ;
}
void RooProdPdf::operModeHook()
{
Int_t i ;
for (i=0 ; i<_partListMgr.cacheSize() ; i++) {
RooArgList* plist = _partListMgr.getNormListByIndex(i) ;
if (plist->isOwning()) {
TIterator* iter = plist->createIterator() ;
RooAbsArg* arg ;
while(arg=(RooAbsArg*)iter->Next()) {
arg->setOperMode(_operMode) ;
}
delete iter ;
}
}
return ;
}
Bool_t RooProdPdf::redirectServersHook(const RooAbsCollection& newServerList, Bool_t mustReplaceAll, Bool_t nameChange, Bool_t isRecursive)
{
Bool_t ret(kFALSE) ;
Int_t i ;
for (i=0 ; i<_partListMgr.cacheSize() ; i++) {
RooArgList* plist = _partListMgr.getNormListByIndex(i) ;
// Only redirect owned lists in recursive mode
if (!isRecursive && !plist->isOwning()) continue ;
TIterator* iter = plist->createIterator() ;
RooAbsArg* arg ;
while(arg=(RooAbsArg*)iter->Next()) {
ret |= arg->recursiveRedirectServers(newServerList,mustReplaceAll,nameChange) ;
}
delete iter ;
}
return ret ;
}
<commit_msg><commit_after>/*****************************************************************************
* Project: RooFit *
* Package: RooFitCore *
* File: $Id: RooProdPdf.cc,v 1.33 2003/01/14 00:07:54 wverkerke Exp $
* Authors: *
* WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu *
* DK, David Kirkby, UC Irvine, dkirkby@uci.edu *
* *
* Copyright (c) 2000-2002, Regents of the University of California *
* and Stanford University. All rights reserved. *
* *
* Redistribution and use in source and binary forms, *
* with or without modification, are permitted according to the terms *
* listed in LICENSE (http://roofit.sourceforge.net/license.txt) *
*****************************************************************************/
// -- CLASS DESCRIPTION [PDF] --
// RooProdPdf is an efficient implementation of a product of PDFs of the form
//
// PDF_1 * PDF_2 * ... * PDF_N
//
// RooProdPdf relies on each component PDF to be normalized and will perform no
// explicit normalization itself. No PDF may share any dependents with any other PDF.
//
// If exactly one of the component PDFs supports extended likelihood fits, the
// product will also be usable in extended mode, returning the number of expected
// events from the extendable component PDF. The extendable component does not
// have to appear in any specific place in the list.
//
// To construct a product of PDFs that share dependents, and thus require explicit
// normalization of the product, use RooGenericPdf.
#include "TIterator.h"
#include "RooFitCore/RooProdPdf.hh"
#include "RooFitCore/RooRealProxy.hh"
#include "RooFitCore/RooProdGenContext.hh"
ClassImp(RooProdPdf)
;
RooProdPdf::RooProdPdf(const char *name, const char *title, Double_t cutOff) :
RooAbsPdf(name,title),
_pdfList("_pdfList","List of PDFs",this),
_cutOff(cutOff),
_codeReg(10),
_extendedIndex(-1),
_partListMgr(10)
{
// Dummy constructor
}
RooProdPdf::RooProdPdf(const char *name, const char *title,
RooAbsPdf& pdf1, RooAbsPdf& pdf2, Double_t cutOff) :
RooAbsPdf(name,title),
_pdfList("_pdfList","List of PDFs",this),
_pdfIter(_pdfList.createIterator()),
_cutOff(cutOff),
_codeReg(10),
_extendedIndex(-1),
_partListMgr(10)
{
// Constructor with 2 PDFs (most frequent use case).
//
// The optional cutOff parameter can be used as a speed optimization if
// one or more of the PDF have sizable regions with very small values,
// which would pull the entire product of PDFs to zero in those regions.
//
// After each PDF multiplication, the running product is compared with
// the cutOff parameter. If the running product is smaller than the
// cutOff value, the product series is terminated and remaining PDFs
// are not evaluated.
//
// There is no magic value of the cutOff, the user should experiment
// to find the appropriate balance between speed and precision.
// If a cutoff is specified, the PDFs most likely to be small should
// be put first in the product. The default cutOff value is zero.
_pdfList.add(pdf1) ;
if (pdf1.canBeExtended()) {
_extendedIndex = _pdfList.index(&pdf1) ;
}
_pdfList.add(pdf2) ;
if (pdf2.canBeExtended()) {
if (_extendedIndex>=0) {
// Protect against multiple extended terms
cout << "RooProdPdf::RooProdPdf(" << GetName()
<< ") multiple components with extended terms detected,"
<< " product will not be extendible." << endl ;
_extendedIndex=-1 ;
} else {
_extendedIndex=_pdfList.index(&pdf2) ;
}
}
}
RooProdPdf::RooProdPdf(const char* name, const char* title, const RooArgList& pdfList, Double_t cutOff) :
RooAbsPdf(name,title),
_pdfList("_pdfList","List of PDFs",this),
_pdfIter(_pdfList.createIterator()),
_cutOff(cutOff),
_codeReg(10),
_extendedIndex(-1),
_partListMgr(10)
{
// Constructor from a list of PDFs
//
// The optional cutOff parameter can be used as a speed optimization if
// one or more of the PDF have sizable regions with very small values,
// which would pull the entire product of PDFs to zero in those regions.
//
// After each PDF multiplication, the running product is compared with
// the cutOff parameter. If the running product is smaller than the
// cutOff value, the product series is terminated and remaining PDFs
// are not evaluated.
//
// There is no magic value of the cutOff, the user should experiment
// to find the appropriate balance between speed and precision.
// If a cutoff is specified, the PDFs most likely to be small should
// be put first in the product. The default cutOff value is zero.
TIterator* iter = pdfList.createIterator() ;
RooAbsPdf* pdf ;
Int_t numExtended(0) ;
while(pdf=(RooAbsPdf*)iter->Next()) {
if (!dynamic_cast<RooAbsPdf*>(pdf)) {
cout << "RooProdPdf::RooProdPdf(" << GetName() << ") list arg "
<< pdf->GetName() << " is not a PDF, ignored" << endl ;
continue ;
}
_pdfList.add(*pdf) ;
if (pdf->canBeExtended()) {
_extendedIndex = _pdfList.index(pdf) ;
numExtended++ ;
}
}
// Protect against multiple extended terms
if (numExtended>1) {
cout << "RooProdPdf::RooProdPdf(" << GetName()
<< ") WARNING: multiple components with extended terms detected,"
<< " product will not be extendible." << endl ;
_extendedIndex = -1 ;
}
delete iter ;
}
RooProdPdf::RooProdPdf(const RooProdPdf& other, const char* name) :
RooAbsPdf(other,name),
_pdfList("_pdfList",this,other._pdfList),
_pdfIter(_pdfList.createIterator()),
_cutOff(other._cutOff),
_codeReg(other._codeReg),
_extendedIndex(other._extendedIndex),
_partListMgr(other._partListMgr)
{
// Copy constructor
}
RooProdPdf::~RooProdPdf()
{
// Destructor
delete _pdfIter ;
}
Double_t RooProdPdf::evaluate() const
{
// Calculate current unnormalized value of object
const RooArgSet* nset = _pdfList.nset() ;
Int_t code ;
RooArgList* plist = getPartIntList(nset,0,code) ;
return calculate(plist,nset) ;
}
Double_t RooProdPdf::calculate(const RooArgList* partIntList, const RooArgSet* normSet) const
{
// Calculate running product of pdfs, skipping factorized components
RooAbsReal* partInt ;
Double_t value(1.0) ;
Int_t n = partIntList->getSize() ;
Int_t i ;
for (i=0 ; i<n ; i++) {
partInt = ((RooAbsReal*)partIntList->at(i)) ;
Double_t piVal = partInt->getVal(normSet) ;
value *= piVal ;
// if (_verboseEval<0) {
// cout << "RPP:calc(" << GetName() << "): value *= " << piVal << " (" << partInt->GetName() << ")" << endl ;
// }
if (value<_cutOff) {
//cout << "RooProdPdf::calculate(" << GetName() << ") calculation cut off after " << partInt->GetName() << endl ;
break ;
}
}
return value ;
}
RooArgList* RooProdPdf::getPartIntList(const RooArgSet* nset, const RooArgSet* iset, Int_t& code) const
{
// Check if this configuration was created before
RooArgList* partIntList = _partListMgr.getNormList(this,nset,iset) ;
if (partIntList) {
code = _partListMgr.lastIndex() ;
return partIntList ;
}
// Create the partial integral set for this request
_pdfIter->Reset() ;
partIntList = new RooArgList("partIntList") ;
RooAbsPdf* pdf ;
while(pdf=(RooAbsPdf*)_pdfIter->Next()) {
// Check if all dependents of this PDF component appear in the normalization set
Bool_t fact(kFALSE) ;
RooArgSet *pdfDepList = pdf->getDependents(nset) ;
if (pdfDepList->getSize()>0) {
fact=kTRUE ;
TIterator* depIter = pdfDepList->createIterator() ;
RooAbsArg* dep ;
while(dep=(RooAbsArg*)depIter->Next()) {
if (!iset || !iset->find(dep->GetName())) {
fact=kFALSE ;
}
}
delete depIter ;
}
// fact=true -> all integrated pdf dependents are in normalization set
if (fact) {
// This product term factorizes, no partial integral needs to be created
} else if (nset && pdfDepList->getSize()==0) {
} else {
if (iset && iset->getSize()>0) {
RooArgSet* iSet = pdf->getDependents(iset) ;
RooAbsReal* partInt = pdf->createIntegral(*iSet,*pdfDepList) ;
partInt->setOperMode(operMode()) ;
partIntList->addOwned(*partInt) ;
delete iSet ;
} else {
partIntList->add(*pdf) ;
}
}
delete pdfDepList ;
}
// Store the partial integral list and return the assigned code ;
code = _partListMgr.setNormList(this,nset,iset,partIntList) ;
// cout << "RooProdPdf::getPIL(" << GetName() << ") creating new configuration with code " << code << endl
// << " nset = " ; if (nset) nset->Print("1") ; else cout << "<none>" << endl ;
// cout << " iset = " ; if (iset) iset->Print("1") ; else cout << "<none>" << endl ;
// cout << " Partial Integral List:" << endl ;
// partIntList->Print("1") ;
return partIntList ;
}
Int_t RooProdPdf::getAnalyticalIntegralWN(RooArgSet& allVars, RooArgSet& analVars, const RooArgSet* normSet) const
{
// Determine which part (if any) of given integral can be performed analytically.
// If any analytical integration is possible, return integration scenario code.
//
// RooProdPdf implements two strategies in implementing analytical integrals
//
// First, PDF components whose entire set of dependents are requested to be integrated
// can be dropped from the product, as they will integrate out to 1 by construction
//
// Second, RooProdPdf queries each remaining component PDF for its analytical integration
// capability of the requested set ('allVars'). It finds the largest common set of variables
// that can be integrated by all remaining components. If such a set exists, it reconfirms that
// each component is capable of analytically integrating the common set, and combines the components
// individual integration codes into a single integration code valid for RooProdPdf.
if (_forceNumInt) return 0 ;
// Declare that we can analytically integrate all requested observables
analVars.add(allVars) ;
// Retrieve (or create) the required partial integral list
Int_t code ;
getPartIntList(normSet,&allVars,code) ;
return code+1 ;
}
Double_t RooProdPdf::analyticalIntegralWN(Int_t code, const RooArgSet* normSet) const
{
// Return analytical integral defined by given scenario code
// No integration scenario
if (code==0) {
return getVal(normSet) ;
}
// Partial integration scenarios
RooArgList* partIntList = _partListMgr.getNormListByIndex(code-1) ;
return calculate(partIntList,normSet) ;
}
Bool_t RooProdPdf::checkDependents(const RooArgSet* nset) const
{
// Check that none of the PDFs have overlapping dependents
Bool_t ret(kFALSE) ;
_pdfIter->Reset() ;
RooAbsPdf* pdf, *pdf2 ;
TIterator* iter2 = _pdfList.createIterator() ;
while(pdf = (RooAbsPdf*)_pdfIter->Next()) {
*iter2 = *_pdfIter ;
while(pdf2 = (RooAbsPdf*)iter2->Next()) {
if (pdf->dependentOverlaps(nset,*pdf2)) {
cout << "RooProdPdf::checkDependents(" << GetName() << "): ERROR: PDFs " << pdf->GetName()
<< " and " << pdf2->GetName() << " have one or more dependents in common" << endl ;
ret = kTRUE ;
}
}
}
delete iter2 ;
return ret ;
}
RooAbsPdf::ExtendMode RooProdPdf::extendMode() const
{
return (_extendedIndex>=0) ? ((RooAbsPdf*)_pdfList.at(_extendedIndex))->extendMode() : CanNotBeExtended ;
}
Double_t RooProdPdf::expectedEvents() const
{
assert(_extendedIndex>=0) ;
return ((RooAbsPdf*)_pdfList.at(_extendedIndex))->expectedEvents() ;
}
RooAbsGenContext* RooProdPdf::genContext(const RooArgSet &vars, const RooDataSet *prototype, Bool_t verbose) const
{
return new RooProdGenContext(*this,vars,prototype,verbose) ;
}
void RooProdPdf::operModeHook()
{
Int_t i ;
for (i=0 ; i<_partListMgr.cacheSize() ; i++) {
RooArgList* plist = _partListMgr.getNormListByIndex(i) ;
if (plist->isOwning()) {
TIterator* iter = plist->createIterator() ;
RooAbsArg* arg ;
while(arg=(RooAbsArg*)iter->Next()) {
arg->setOperMode(_operMode) ;
}
delete iter ;
}
}
return ;
}
Bool_t RooProdPdf::redirectServersHook(const RooAbsCollection& newServerList, Bool_t mustReplaceAll, Bool_t nameChange, Bool_t isRecursive)
{
Bool_t ret(kFALSE) ;
Int_t i ;
for (i=0 ; i<_partListMgr.cacheSize() ; i++) {
RooArgList* plist = _partListMgr.getNormListByIndex(i) ;
// Only redirect owned lists in recursive mode
if (!isRecursive || !plist->isOwning()) continue ;
TIterator* iter = plist->createIterator() ;
RooAbsArg* arg ;
while(arg=(RooAbsArg*)iter->Next()) {
ret |= arg->recursiveRedirectServers(newServerList,mustReplaceAll,nameChange) ;
}
delete iter ;
}
return ret ;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2002 - present, H. Hernan Saez
* 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 holder 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 COPYRIGHT HOLDER BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CRIMILD_MATHEMATICS_ORTHO_
#define CRIMILD_MATHEMATICS_ORTHO_
#include "Foundation/Macros.hpp"
#include "Mathematics/Matrix4.hpp"
namespace crimild {
[[nodiscard]] constexpr Matrix4 ortho( Real l, Real r, Real b, Real t, Real n, Real f ) noexcept
{
#if CRIMILD_USE_DEPTH_RANGE_ZERO_TO_ONE
return Matrix4 {
{ Real( 2 ) / ( r - l ), 0, 0, 0 },
{ 0, Real( 2 ) / ( t - b ), 0, 0 },
{ 0, 0, Real( 1 ) / ( f - n ), 0 },
{ -( r + l ) / ( r - l ), -( t + b ) / ( t - b ), -n / ( f - n ), 1 },
};
#else
return Matrix4 {
{ Real( 2 ) / ( r - l ), 0, 0, 0 },
{ 0, Real( 2 ) / ( t - b ), 0, 0 },
{ 0, 0, Real( 2 ) / ( f - n ), 0 },
{ -( r + l ) / ( r - l ), -( t + b ) / ( t - b ), -( f + n ) / ( f - n ), 1 },
};
#endif
}
}
#endif
<commit_msg>Fix orthographic projection<commit_after>/*
* Copyright (c) 2002 - present, H. Hernan Saez
* 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 holder 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 COPYRIGHT HOLDER BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CRIMILD_MATHEMATICS_ORTHO_
#define CRIMILD_MATHEMATICS_ORTHO_
#include "Foundation/Macros.hpp"
#include "Mathematics/Matrix4.hpp"
namespace crimild {
[[nodiscard]] constexpr Matrix4 ortho( Real l, Real r, Real b, Real t, Real n, Real f ) noexcept
{
#if CRIMILD_USE_DEPTH_RANGE_ZERO_TO_ONE
return Matrix4 {
{ Real( 2 ) / ( r - l ), 0, 0, 0 },
{ 0, Real( 2 ) / ( t - b ), 0, 0 },
{ 0, 0, -Real( 1 ) / ( f - n ), 0 },
{ -( r + l ) / ( r - l ), -( t + b ) / ( t - b ), -n / ( f - n ), 1 },
};
#else
return Matrix4 {
{ Real( 2 ) / ( r - l ), 0, 0, 0 },
{ 0, Real( 2 ) / ( t - b ), 0, 0 },
{ 0, 0, -Real( 2 ) / ( f - n ), 0 },
{ -( r + l ) / ( r - l ), -( t + b ) / ( t - b ), -( f + n ) / ( f - n ), 1 },
};
#endif
}
}
#endif
<|endoftext|>
|
<commit_before><commit_msg>Move IBL settings in their own category<commit_after><|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/control/control_component.h"
#include "cyber/common/file.h"
#include "cyber/common/log.h"
#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/time/time.h"
#include "modules/common/vehicle_state/vehicle_state_provider.h"
#include "modules/control/common/control_gflags.h"
namespace apollo {
namespace control {
using apollo::canbus::Chassis;
using apollo::common::ErrorCode;
using apollo::common::Status;
using apollo::common::VehicleStateProvider;
using apollo::common::time::Clock;
using apollo::localization::LocalizationEstimate;
using apollo::planning::ADCTrajectory;
ControlComponent::ControlComponent()
: monitor_logger_buffer_(common::monitor::MonitorMessageItem::CONTROL) {}
bool ControlComponent::Init() {
// init_time_ = Clock::NowInSeconds();
AINFO << "Control init, starting ...";
CHECK(
cyber::common::GetProtoFromFile(FLAGS_control_conf_file, &control_conf_))
<< "Unable to load control conf file: " + FLAGS_control_conf_file;
AINFO << "Conf file: " << FLAGS_control_conf_file << " is loaded.";
AINFO << "Conf file: " << ConfigFilePath() << " is loaded.";
// set controller
if (!controller_agent_.Init(&control_conf_).ok()) {
monitor_logger_buffer_.ERROR("Control init controller failed! Stopping...");
return false;
}
cyber::ReaderConfig chassis_reader_config;
chassis_reader_config.channel_name = FLAGS_chassis_topic;
chassis_reader_config.pending_queue_size = FLAGS_chassis_pending_queue_size;
chassis_reader_ =
node_->CreateReader<Chassis>(chassis_reader_config, nullptr);
CHECK(chassis_reader_ != nullptr);
cyber::ReaderConfig planning_reader_config;
planning_reader_config.channel_name = FLAGS_planning_trajectory_topic;
planning_reader_config.pending_queue_size = FLAGS_planning_pending_queue_size;
trajectory_reader_ =
node_->CreateReader<ADCTrajectory>(planning_reader_config, nullptr);
CHECK(trajectory_reader_ != nullptr);
cyber::ReaderConfig localization_reader_config;
localization_reader_config.channel_name = FLAGS_localization_topic;
localization_reader_config.pending_queue_size =
FLAGS_localization_pending_queue_size;
localization_reader_ = node_->CreateReader<LocalizationEstimate>(
localization_reader_config, nullptr);
CHECK(localization_reader_ != nullptr);
cyber::ReaderConfig pad_msg_reader_config;
pad_msg_reader_config.channel_name = FLAGS_pad_topic;
pad_msg_reader_config.pending_queue_size = FLAGS_pad_msg_pending_queue_size;
pad_msg_reader_ =
node_->CreateReader<PadMessage>(pad_msg_reader_config, nullptr);
CHECK(pad_msg_reader_ != nullptr);
control_cmd_writer_ =
node_->CreateWriter<ControlCommand>(FLAGS_control_command_topic);
CHECK(control_cmd_writer_ != nullptr);
// set initial vehicle state by cmd
// need to sleep, because advertised channel is not ready immediately
// simple test shows a short delay of 80 ms or so
AINFO << "Control resetting vehicle state, sleeping for 1000 ms ...";
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
// should init_vehicle first, let car enter work status, then use status msg
// trigger control
AINFO << "Control default driving action is "
<< DrivingAction_Name(control_conf_.action());
pad_msg_.set_action(control_conf_.action());
return true;
}
void ControlComponent::OnPad(const std::shared_ptr<PadMessage> &pad) {
pad_msg_.CopyFrom(*pad);
ADEBUG << "Received Pad Msg:" << pad_msg_.DebugString();
AERROR_IF(!pad_msg_.has_action()) << "pad message check failed!";
// do something according to pad message
if (pad_msg_.action() == DrivingAction::RESET) {
AINFO << "Control received RESET action!";
estop_ = false;
estop_reason_.clear();
}
pad_received_ = true;
}
void ControlComponent::OnChassis(const std::shared_ptr<Chassis> &chassis) {
ADEBUG << "Received chassis data: run chassis callback.";
std::lock_guard<std::mutex> lock(mutex_);
latest_chassis_.CopyFrom(*chassis);
}
void ControlComponent::OnPlanning(
const std::shared_ptr<ADCTrajectory> &trajectory) {
ADEBUG << "Received chassis data: run trajectory callback.";
std::lock_guard<std::mutex> lock(mutex_);
latest_trajectory_.CopyFrom(*trajectory);
}
void ControlComponent::OnLocalization(
const std::shared_ptr<LocalizationEstimate> &localization) {
ADEBUG << "Received control data: run localization message callback.";
std::lock_guard<std::mutex> lock(mutex_);
latest_localization_.CopyFrom(*localization);
}
void ControlComponent::OnMonitor(
const common::monitor::MonitorMessage &monitor_message) {
for (const auto &item : monitor_message.item()) {
if (item.log_level() == common::monitor::MonitorMessageItem::FATAL) {
estop_ = true;
return;
}
}
}
Status ControlComponent::ProduceControlCommand(
ControlCommand *control_command) {
{
std::lock_guard<std::mutex> lock(mutex_);
local_view_.chassis = latest_chassis_;
local_view_.trajectory = latest_trajectory_;
local_view_.localization = latest_localization_;
}
Status status = CheckInput(&local_view_);
// check data
if (!status.ok()) {
AERROR_EVERY(100) << "Control input data failed: "
<< status.error_message();
control_command->mutable_engage_advice()->set_advice(
apollo::common::EngageAdvice::DISALLOW_ENGAGE);
control_command->mutable_engage_advice()->set_reason(
status.error_message());
estop_ = true;
estop_reason_ = status.error_message();
} else {
Status status_ts = CheckTimestamp(local_view_);
if (!status_ts.ok()) {
AERROR << "Input messages timeout";
// estop_ = true;
status = status_ts;
if (local_view_.chassis.driving_mode() !=
apollo::canbus::Chassis::COMPLETE_AUTO_DRIVE) {
control_command->mutable_engage_advice()->set_advice(
apollo::common::EngageAdvice::DISALLOW_ENGAGE);
control_command->mutable_engage_advice()->set_reason(
status.error_message());
}
} else {
control_command->mutable_engage_advice()->set_advice(
apollo::common::EngageAdvice::READY_TO_ENGAGE);
}
}
// check estop
estop_ = control_conf_.enable_persistent_estop()
? estop_ || local_view_.trajectory.estop().is_estop()
: local_view_.trajectory.estop().is_estop();
if (local_view_.trajectory.estop().is_estop()) {
estop_reason_ = "estop from planning";
}
if (local_view_.trajectory.trajectory_point_size() == 0) {
AWARN_EVERY(100) << "planning has no trajectory point. ";
estop_ = true;
estop_reason_ = "estop for empty planning trajectory";
}
// if planning set estop, then no control process triggered
if (!estop_) {
if (local_view_.chassis.driving_mode() == Chassis::COMPLETE_MANUAL) {
controller_agent_.Reset();
AINFO_EVERY(100) << "Reset Controllers in Manual Mode";
}
auto debug = control_command->mutable_debug()->mutable_input_debug();
debug->mutable_localization_header()->CopyFrom(
local_view_.localization.header());
debug->mutable_canbus_header()->CopyFrom(local_view_.chassis.header());
debug->mutable_trajectory_header()->CopyFrom(
local_view_.trajectory.header());
Status status_compute = controller_agent_.ComputeControlCommand(
&local_view_.localization, &local_view_.chassis,
&local_view_.trajectory, control_command);
if (!status_compute.ok()) {
AERROR << "Control main function failed"
<< " with localization: "
<< local_view_.localization.ShortDebugString()
<< " with chassis: " << local_view_.chassis.ShortDebugString()
<< " with trajectory: "
<< local_view_.trajectory.ShortDebugString()
<< " with cmd: " << control_command->ShortDebugString()
<< " status:" << status_compute.error_message();
estop_ = true;
estop_reason_ = status_compute.error_message();
status = status_compute;
}
}
if (estop_) {
AWARN_EVERY(100) << "Estop triggered! No control core method executed!";
// set Estop command
control_command->set_speed(0);
control_command->set_throttle(0);
control_command->set_brake(control_conf_.soft_estop_brake());
control_command->set_gear_location(Chassis::GEAR_DRIVE);
}
// check signal
if (local_view_.trajectory.decision().has_vehicle_signal()) {
control_command->mutable_signal()->CopyFrom(
local_view_.trajectory.decision().vehicle_signal());
}
return status;
}
bool ControlComponent::Proc() {
double start_timestamp = Clock::NowInSeconds();
chassis_reader_->Observe();
const auto &chassis_msg = chassis_reader_->GetLatestObserved();
if (chassis_msg == nullptr) {
AERROR << "Chassis msg is not ready!";
return false;
}
OnChassis(chassis_msg);
trajectory_reader_->Observe();
const auto &trajectory_msg = trajectory_reader_->GetLatestObserved();
if (trajectory_msg == nullptr) {
AERROR << "planning msg is not ready!";
return false;
}
OnPlanning(trajectory_msg);
localization_reader_->Observe();
const auto &localization_msg = localization_reader_->GetLatestObserved();
if (localization_msg == nullptr) {
AERROR << "localization msg is not ready!";
return false;
}
OnLocalization(localization_msg);
pad_msg_reader_->Observe();
const auto &pad_msg = pad_msg_reader_->GetLatestObserved();
if (pad_msg != nullptr) {
OnPad(pad_msg);
}
if (control_conf_.is_control_test_mode() &&
control_conf_.control_test_duration() > 0 &&
(start_timestamp - init_time_) > control_conf_.control_test_duration()) {
AERROR << "Control finished testing. exit";
return false;
}
ControlCommand control_command;
Status status = ProduceControlCommand(&control_command);
AERROR_IF(!status.ok()) << "Failed to produce control command:"
<< status.error_message();
double end_timestamp = Clock::NowInSeconds();
if (pad_received_) {
control_command.mutable_pad_msg()->CopyFrom(pad_msg_);
pad_received_ = false;
}
const double time_diff_ms = (end_timestamp - start_timestamp) * 1000;
control_command.mutable_latency_stats()->set_total_time_ms(time_diff_ms);
control_command.mutable_latency_stats()->set_total_time_exceeded(
time_diff_ms < control_conf_.control_period());
ADEBUG << "control cycle time is: " << time_diff_ms << " ms.";
status.Save(control_command.mutable_header()->mutable_status());
// forward estop reason among following control frames.
if (estop_) {
control_command.mutable_header()->mutable_status()->set_msg(estop_reason_);
}
// set header
control_command.mutable_header()->set_lidar_timestamp(
local_view_.trajectory.header().lidar_timestamp());
control_command.mutable_header()->set_camera_timestamp(
local_view_.trajectory.header().camera_timestamp());
control_command.mutable_header()->set_radar_timestamp(
local_view_.trajectory.header().radar_timestamp());
common::util::FillHeader(node_->Name(), &control_command);
ADEBUG << control_command.ShortDebugString();
if (control_conf_.is_control_test_mode()) {
ADEBUG << "Skip publish control command in test mode";
return true;
}
control_cmd_writer_->Write(std::make_shared<ControlCommand>(control_command));
return true;
}
Status ControlComponent::CheckInput(LocalView *local_view) {
ADEBUG << "Received localization:"
<< local_view->localization.ShortDebugString();
ADEBUG << "Received chassis:" << local_view->chassis.ShortDebugString();
if (!local_view->trajectory.estop().is_estop() &&
local_view->trajectory.trajectory_point_size() == 0) {
AWARN_EVERY(100) << "planning has no trajectory point. ";
std::string msg("planning has no trajectory point. planning_seq_num:");
msg += std::to_string(local_view->trajectory.header().sequence_num());
return Status(ErrorCode::CONTROL_COMPUTE_ERROR, msg);
}
for (auto &trajectory_point :
*local_view->trajectory.mutable_trajectory_point()) {
if (std::abs(trajectory_point.v()) <
control_conf_.minimum_speed_resolution()) {
trajectory_point.set_v(0.0);
trajectory_point.set_a(0.0);
}
}
VehicleStateProvider::Instance()->Update(local_view->localization,
local_view->chassis);
return Status::OK();
}
Status ControlComponent::CheckTimestamp(const LocalView &local_view) {
if (!control_conf_.enable_input_timestamp_check() ||
control_conf_.is_control_test_mode()) {
ADEBUG << "Skip input timestamp check by gflags.";
return Status::OK();
}
double current_timestamp = Clock::NowInSeconds();
double localization_diff =
current_timestamp - local_view.localization.header().timestamp_sec();
if (localization_diff > (control_conf_.max_localization_miss_num() *
control_conf_.localization_period())) {
AERROR << "Localization msg lost for " << std::setprecision(6)
<< localization_diff << "s";
monitor_logger_buffer_.ERROR("Localization msg lost");
return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "Localization msg timeout");
}
double chassis_diff =
current_timestamp - local_view.chassis.header().timestamp_sec();
if (chassis_diff >
(control_conf_.max_chassis_miss_num() * control_conf_.chassis_period())) {
AERROR << "Chassis msg lost for " << std::setprecision(6) << chassis_diff
<< "s";
monitor_logger_buffer_.ERROR("Chassis msg lost");
return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "Chassis msg timeout");
}
double trajectory_diff =
current_timestamp - local_view.trajectory.header().timestamp_sec();
if (trajectory_diff > (control_conf_.max_planning_miss_num() *
control_conf_.trajectory_period())) {
AERROR << "Trajectory msg lost for " << std::setprecision(6)
<< trajectory_diff << "s";
monitor_logger_buffer_.ERROR("Trajectory msg lost");
return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "Trajectory msg timeout");
}
return Status::OK();
}
} // namespace control
} // namespace apollo
<commit_msg>Control: fix time_exceeded judgement error<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/control/control_component.h"
#include "cyber/common/file.h"
#include "cyber/common/log.h"
#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/time/time.h"
#include "modules/common/vehicle_state/vehicle_state_provider.h"
#include "modules/control/common/control_gflags.h"
namespace apollo {
namespace control {
using apollo::canbus::Chassis;
using apollo::common::ErrorCode;
using apollo::common::Status;
using apollo::common::VehicleStateProvider;
using apollo::common::time::Clock;
using apollo::localization::LocalizationEstimate;
using apollo::planning::ADCTrajectory;
ControlComponent::ControlComponent()
: monitor_logger_buffer_(common::monitor::MonitorMessageItem::CONTROL) {}
bool ControlComponent::Init() {
// init_time_ = Clock::NowInSeconds();
AINFO << "Control init, starting ...";
CHECK(
cyber::common::GetProtoFromFile(FLAGS_control_conf_file, &control_conf_))
<< "Unable to load control conf file: " + FLAGS_control_conf_file;
AINFO << "Conf file: " << FLAGS_control_conf_file << " is loaded.";
AINFO << "Conf file: " << ConfigFilePath() << " is loaded.";
// set controller
if (!controller_agent_.Init(&control_conf_).ok()) {
monitor_logger_buffer_.ERROR("Control init controller failed! Stopping...");
return false;
}
cyber::ReaderConfig chassis_reader_config;
chassis_reader_config.channel_name = FLAGS_chassis_topic;
chassis_reader_config.pending_queue_size = FLAGS_chassis_pending_queue_size;
chassis_reader_ =
node_->CreateReader<Chassis>(chassis_reader_config, nullptr);
CHECK(chassis_reader_ != nullptr);
cyber::ReaderConfig planning_reader_config;
planning_reader_config.channel_name = FLAGS_planning_trajectory_topic;
planning_reader_config.pending_queue_size = FLAGS_planning_pending_queue_size;
trajectory_reader_ =
node_->CreateReader<ADCTrajectory>(planning_reader_config, nullptr);
CHECK(trajectory_reader_ != nullptr);
cyber::ReaderConfig localization_reader_config;
localization_reader_config.channel_name = FLAGS_localization_topic;
localization_reader_config.pending_queue_size =
FLAGS_localization_pending_queue_size;
localization_reader_ = node_->CreateReader<LocalizationEstimate>(
localization_reader_config, nullptr);
CHECK(localization_reader_ != nullptr);
cyber::ReaderConfig pad_msg_reader_config;
pad_msg_reader_config.channel_name = FLAGS_pad_topic;
pad_msg_reader_config.pending_queue_size = FLAGS_pad_msg_pending_queue_size;
pad_msg_reader_ =
node_->CreateReader<PadMessage>(pad_msg_reader_config, nullptr);
CHECK(pad_msg_reader_ != nullptr);
control_cmd_writer_ =
node_->CreateWriter<ControlCommand>(FLAGS_control_command_topic);
CHECK(control_cmd_writer_ != nullptr);
// set initial vehicle state by cmd
// need to sleep, because advertised channel is not ready immediately
// simple test shows a short delay of 80 ms or so
AINFO << "Control resetting vehicle state, sleeping for 1000 ms ...";
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
// should init_vehicle first, let car enter work status, then use status msg
// trigger control
AINFO << "Control default driving action is "
<< DrivingAction_Name(control_conf_.action());
pad_msg_.set_action(control_conf_.action());
return true;
}
void ControlComponent::OnPad(const std::shared_ptr<PadMessage> &pad) {
pad_msg_.CopyFrom(*pad);
ADEBUG << "Received Pad Msg:" << pad_msg_.DebugString();
AERROR_IF(!pad_msg_.has_action()) << "pad message check failed!";
// do something according to pad message
if (pad_msg_.action() == DrivingAction::RESET) {
AINFO << "Control received RESET action!";
estop_ = false;
estop_reason_.clear();
}
pad_received_ = true;
}
void ControlComponent::OnChassis(const std::shared_ptr<Chassis> &chassis) {
ADEBUG << "Received chassis data: run chassis callback.";
std::lock_guard<std::mutex> lock(mutex_);
latest_chassis_.CopyFrom(*chassis);
}
void ControlComponent::OnPlanning(
const std::shared_ptr<ADCTrajectory> &trajectory) {
ADEBUG << "Received chassis data: run trajectory callback.";
std::lock_guard<std::mutex> lock(mutex_);
latest_trajectory_.CopyFrom(*trajectory);
}
void ControlComponent::OnLocalization(
const std::shared_ptr<LocalizationEstimate> &localization) {
ADEBUG << "Received control data: run localization message callback.";
std::lock_guard<std::mutex> lock(mutex_);
latest_localization_.CopyFrom(*localization);
}
void ControlComponent::OnMonitor(
const common::monitor::MonitorMessage &monitor_message) {
for (const auto &item : monitor_message.item()) {
if (item.log_level() == common::monitor::MonitorMessageItem::FATAL) {
estop_ = true;
return;
}
}
}
Status ControlComponent::ProduceControlCommand(
ControlCommand *control_command) {
{
std::lock_guard<std::mutex> lock(mutex_);
local_view_.chassis = latest_chassis_;
local_view_.trajectory = latest_trajectory_;
local_view_.localization = latest_localization_;
}
Status status = CheckInput(&local_view_);
// check data
if (!status.ok()) {
AERROR_EVERY(100) << "Control input data failed: "
<< status.error_message();
control_command->mutable_engage_advice()->set_advice(
apollo::common::EngageAdvice::DISALLOW_ENGAGE);
control_command->mutable_engage_advice()->set_reason(
status.error_message());
estop_ = true;
estop_reason_ = status.error_message();
} else {
Status status_ts = CheckTimestamp(local_view_);
if (!status_ts.ok()) {
AERROR << "Input messages timeout";
// estop_ = true;
status = status_ts;
if (local_view_.chassis.driving_mode() !=
apollo::canbus::Chassis::COMPLETE_AUTO_DRIVE) {
control_command->mutable_engage_advice()->set_advice(
apollo::common::EngageAdvice::DISALLOW_ENGAGE);
control_command->mutable_engage_advice()->set_reason(
status.error_message());
}
} else {
control_command->mutable_engage_advice()->set_advice(
apollo::common::EngageAdvice::READY_TO_ENGAGE);
}
}
// check estop
estop_ = control_conf_.enable_persistent_estop()
? estop_ || local_view_.trajectory.estop().is_estop()
: local_view_.trajectory.estop().is_estop();
if (local_view_.trajectory.estop().is_estop()) {
estop_reason_ = "estop from planning";
}
if (local_view_.trajectory.trajectory_point_size() == 0) {
AWARN_EVERY(100) << "planning has no trajectory point. ";
estop_ = true;
estop_reason_ = "estop for empty planning trajectory";
}
// if planning set estop, then no control process triggered
if (!estop_) {
if (local_view_.chassis.driving_mode() == Chassis::COMPLETE_MANUAL) {
controller_agent_.Reset();
AINFO_EVERY(100) << "Reset Controllers in Manual Mode";
}
auto debug = control_command->mutable_debug()->mutable_input_debug();
debug->mutable_localization_header()->CopyFrom(
local_view_.localization.header());
debug->mutable_canbus_header()->CopyFrom(local_view_.chassis.header());
debug->mutable_trajectory_header()->CopyFrom(
local_view_.trajectory.header());
Status status_compute = controller_agent_.ComputeControlCommand(
&local_view_.localization, &local_view_.chassis,
&local_view_.trajectory, control_command);
if (!status_compute.ok()) {
AERROR << "Control main function failed"
<< " with localization: "
<< local_view_.localization.ShortDebugString()
<< " with chassis: " << local_view_.chassis.ShortDebugString()
<< " with trajectory: "
<< local_view_.trajectory.ShortDebugString()
<< " with cmd: " << control_command->ShortDebugString()
<< " status:" << status_compute.error_message();
estop_ = true;
estop_reason_ = status_compute.error_message();
status = status_compute;
}
}
if (estop_) {
AWARN_EVERY(100) << "Estop triggered! No control core method executed!";
// set Estop command
control_command->set_speed(0);
control_command->set_throttle(0);
control_command->set_brake(control_conf_.soft_estop_brake());
control_command->set_gear_location(Chassis::GEAR_DRIVE);
}
// check signal
if (local_view_.trajectory.decision().has_vehicle_signal()) {
control_command->mutable_signal()->CopyFrom(
local_view_.trajectory.decision().vehicle_signal());
}
return status;
}
bool ControlComponent::Proc() {
double start_timestamp = Clock::NowInSeconds();
chassis_reader_->Observe();
const auto &chassis_msg = chassis_reader_->GetLatestObserved();
if (chassis_msg == nullptr) {
AERROR << "Chassis msg is not ready!";
return false;
}
OnChassis(chassis_msg);
trajectory_reader_->Observe();
const auto &trajectory_msg = trajectory_reader_->GetLatestObserved();
if (trajectory_msg == nullptr) {
AERROR << "planning msg is not ready!";
return false;
}
OnPlanning(trajectory_msg);
localization_reader_->Observe();
const auto &localization_msg = localization_reader_->GetLatestObserved();
if (localization_msg == nullptr) {
AERROR << "localization msg is not ready!";
return false;
}
OnLocalization(localization_msg);
pad_msg_reader_->Observe();
const auto &pad_msg = pad_msg_reader_->GetLatestObserved();
if (pad_msg != nullptr) {
OnPad(pad_msg);
}
if (control_conf_.is_control_test_mode() &&
control_conf_.control_test_duration() > 0 &&
(start_timestamp - init_time_) > control_conf_.control_test_duration()) {
AERROR << "Control finished testing. exit";
return false;
}
ControlCommand control_command;
Status status = ProduceControlCommand(&control_command);
AERROR_IF(!status.ok()) << "Failed to produce control command:"
<< status.error_message();
double end_timestamp = Clock::NowInSeconds();
if (pad_received_) {
control_command.mutable_pad_msg()->CopyFrom(pad_msg_);
pad_received_ = false;
}
const double time_diff_ms = (end_timestamp - start_timestamp) * 1000;
control_command.mutable_latency_stats()->set_total_time_ms(time_diff_ms);
control_command.mutable_latency_stats()->set_total_time_exceeded(
time_diff_ms > control_conf_.control_period());
ADEBUG << "control cycle time is: " << time_diff_ms << " ms.";
status.Save(control_command.mutable_header()->mutable_status());
// forward estop reason among following control frames.
if (estop_) {
control_command.mutable_header()->mutable_status()->set_msg(estop_reason_);
}
// set header
control_command.mutable_header()->set_lidar_timestamp(
local_view_.trajectory.header().lidar_timestamp());
control_command.mutable_header()->set_camera_timestamp(
local_view_.trajectory.header().camera_timestamp());
control_command.mutable_header()->set_radar_timestamp(
local_view_.trajectory.header().radar_timestamp());
common::util::FillHeader(node_->Name(), &control_command);
ADEBUG << control_command.ShortDebugString();
if (control_conf_.is_control_test_mode()) {
ADEBUG << "Skip publish control command in test mode";
return true;
}
control_cmd_writer_->Write(std::make_shared<ControlCommand>(control_command));
return true;
}
Status ControlComponent::CheckInput(LocalView *local_view) {
ADEBUG << "Received localization:"
<< local_view->localization.ShortDebugString();
ADEBUG << "Received chassis:" << local_view->chassis.ShortDebugString();
if (!local_view->trajectory.estop().is_estop() &&
local_view->trajectory.trajectory_point_size() == 0) {
AWARN_EVERY(100) << "planning has no trajectory point. ";
std::string msg("planning has no trajectory point. planning_seq_num:");
msg += std::to_string(local_view->trajectory.header().sequence_num());
return Status(ErrorCode::CONTROL_COMPUTE_ERROR, msg);
}
for (auto &trajectory_point :
*local_view->trajectory.mutable_trajectory_point()) {
if (std::abs(trajectory_point.v()) <
control_conf_.minimum_speed_resolution()) {
trajectory_point.set_v(0.0);
trajectory_point.set_a(0.0);
}
}
VehicleStateProvider::Instance()->Update(local_view->localization,
local_view->chassis);
return Status::OK();
}
Status ControlComponent::CheckTimestamp(const LocalView &local_view) {
if (!control_conf_.enable_input_timestamp_check() ||
control_conf_.is_control_test_mode()) {
ADEBUG << "Skip input timestamp check by gflags.";
return Status::OK();
}
double current_timestamp = Clock::NowInSeconds();
double localization_diff =
current_timestamp - local_view.localization.header().timestamp_sec();
if (localization_diff > (control_conf_.max_localization_miss_num() *
control_conf_.localization_period())) {
AERROR << "Localization msg lost for " << std::setprecision(6)
<< localization_diff << "s";
monitor_logger_buffer_.ERROR("Localization msg lost");
return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "Localization msg timeout");
}
double chassis_diff =
current_timestamp - local_view.chassis.header().timestamp_sec();
if (chassis_diff >
(control_conf_.max_chassis_miss_num() * control_conf_.chassis_period())) {
AERROR << "Chassis msg lost for " << std::setprecision(6) << chassis_diff
<< "s";
monitor_logger_buffer_.ERROR("Chassis msg lost");
return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "Chassis msg timeout");
}
double trajectory_diff =
current_timestamp - local_view.trajectory.header().timestamp_sec();
if (trajectory_diff > (control_conf_.max_planning_miss_num() *
control_conf_.trajectory_period())) {
AERROR << "Trajectory msg lost for " << std::setprecision(6)
<< trajectory_diff << "s";
monitor_logger_buffer_.ERROR("Trajectory msg lost");
return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "Trajectory msg timeout");
}
return Status::OK();
}
} // namespace control
} // namespace apollo
<|endoftext|>
|
<commit_before><commit_msg>Added onObjLoad function<commit_after><|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/routing/routing_component.h"
#include "modules/common/adapters/adapter_gflags.h"
#include "modules/routing/common/routing_gflags.h"
DECLARE_string(flagfile);
namespace apollo {
namespace routing {
bool RoutingComponent::Init() {
AINFO << "Loading gflag from file: " << ConfigFilePath();
google::SetCommandLineOption("flagfile", ConfigFilePath().c_str());
response_writer_ =
node_->CreateWriter<RoutingResponse>(FLAGS_routing_response_topic);
return routing_.Init().ok() && routing_.Start().ok();
}
bool RoutingComponent::Proc(const std::shared_ptr<RoutingRequest>& request) {
auto response = std::make_shared<RoutingResponse>();
if (!routing_.Process(request, response.get())) {
return false;
}
response_writer_->Write(response);
return true;
}
} // namespace routing
} // namespace apollo
<commit_msg>routing: add pb header into routing response.<commit_after>/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/routing/routing_component.h"
#include "modules/common/adapters/adapter_gflags.h"
#include "modules/routing/common/routing_gflags.h"
DECLARE_string(flagfile);
namespace apollo {
namespace routing {
bool RoutingComponent::Init() {
AINFO << "Loading gflag from file: " << ConfigFilePath();
google::SetCommandLineOption("flagfile", ConfigFilePath().c_str());
response_writer_ =
node_->CreateWriter<RoutingResponse>(FLAGS_routing_response_topic);
return routing_.Init().ok() && routing_.Start().ok();
}
bool RoutingComponent::Proc(const std::shared_ptr<RoutingRequest>& request) {
auto response = std::make_shared<RoutingResponse>();
if (!routing_.Process(request, response.get())) {
return false;
}
common::util::FillHeader(node_->Name(), response.get());
response_writer_->Write(response);
return true;
}
} // namespace routing
} // namespace apollo
<|endoftext|>
|
<commit_before>#include "glesplash.h"
#include "shaders.h"
#include <EGL/egl.h>
const float vertexArray[] = {
-1.0, 1.0, 0.0,
-1.0, -1.0, 0.0,
1.0, -1.0, 0.0,
1.0, 1.0, 0.0,
-1.0, 1.0, 0.0
};
const float textureArray[] = {
0.0, 1.0,
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
0.0, 1.0
};
EGLDisplay egl_display;
EGLContext egl_context;
EGLSurface egl_surface;
GLint
position_loc,
texCoord_loc,
texSampl_loc;
void render()
{
static int init = 0;
if(!init) {
#ifdef X11
XWindowAttributes gwa;
XGetWindowAttributes(x_display, win, &gwa);
glViewport(0, 0, gwa.width, gwa.height);
#else
glViewport(0, 0, 854, 480);
#endif
glClearColor(0.0, 0.0, 0.0, 1.0);
init = 1;
}
glClear(GL_COLOR_BUFFER_BIT);
glVertexAttribPointer(position_loc, 3, GL_FLOAT, false, 0, vertexArray);
glVertexAttribPointer(texCoord_loc, 2, GL_FLOAT, false, 0, textureArray);
glEnableVertexAttribArray(position_loc);
glEnableVertexAttribArray(texCoord_loc);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 5);
eglSwapBuffers(egl_display, egl_surface);
}
int create_egl_context()
{
EGLConfig egl_config;
EGLint num_config;
EGLint attr[] = {
EGL_BUFFER_SIZE, 16,
EGL_RENDERABLE_TYPE,
EGL_OPENGL_ES2_BIT,
EGL_NONE
};
EGLint ctx_attr[] = {
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE
};
#ifdef X11
egl_display = eglGetDisplay((EGLNativeDisplayType)x_display);
#else
egl_display = eglGetDisplay(NULL);
#endif
if(egl_display == EGL_NO_DISPLAY)
{
cerr << "Could not get EGL display" << endl;
return EXIT_FAILURE;
}
if(!eglInitialize(egl_display, NULL, NULL))
{
cerr << "Unable to initialize EGL" << endl;
return EXIT_FAILURE;
}
if(!eglChooseConfig(egl_display, attr, &egl_config, 1, &num_config))
{
cerr << "Failed to configure EGL context" << endl;
return EXIT_FAILURE;
}
if(num_config != 1)
{
cerr << "Multiple configurations returned, got " << num_config << " configurations" << endl;
return EXIT_FAILURE;
}
#ifdef X11
egl_surface = eglCreateWindowSurface(egl_display, egl_config, (EGLNativeWindowType)win, NULL);
#else
egl_surface = eglCreateWindowSurface(egl_display, egl_config, (EGLNativeWindowType)NULL, NULL);
#endif
if(egl_surface == EGL_NO_SURFACE)
{
cerr << "Unable to create EGL surface: " << eglGetError() << endl;
return EXIT_FAILURE;
}
egl_context = eglCreateContext(egl_display, egl_config, EGL_NO_CONTEXT, ctx_attr);
if(egl_context == EGL_NO_CONTEXT)
{
cerr << "Unable to create EGL context: " << eglGetError() << endl;
return EXIT_FAILURE;
}
eglMakeCurrent(egl_display, egl_surface, egl_surface, egl_context);
return EXIT_SUCCESS;
}
int init_gl_context()
{
/////// the openGL part ///////////////////////////////////////////////////////////////
GLuint shaderProgram = glCreateProgram();
GLuint vertexShader = load_shader(vertex_src, GL_VERTEX_SHADER);
GLuint fragmentShader = load_shader(fragment_src, GL_FRAGMENT_SHADER);
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
glUseProgram(shaderProgram);
//// now get the locations (kind of handle) of the shaders variables
position_loc = glGetAttribLocation(shaderProgram, "aPosition");
texCoord_loc = glGetAttribLocation(shaderProgram, "aTexCoord");
texSampl_loc = glGetUniformLocation(shaderProgram, "tex");
if(position_loc < 0) {
cerr << "Unable to get position attribute" << endl;
return EXIT_FAILURE;
}
if(texCoord_loc < 0) {
cerr << "Unable to get texCoord attribute" << endl;
return EXIT_FAILURE;
}
if(texSampl_loc < 0) {
cerr << "Unable to get texSampl uniform" << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>Viewport offset fix when running in framebuffer mode.<commit_after>#include "glesplash.h"
#include "shaders.h"
#include <EGL/egl.h>
const float vertexArray[] = {
-1.0, 1.0, 0.0,
-1.0, -1.0, 0.0,
1.0, -1.0, 0.0,
1.0, 1.0, 0.0,
-1.0, 1.0, 0.0
};
const float textureArray[] = {
0.0, 1.0,
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
0.0, 1.0
};
EGLDisplay egl_display;
EGLContext egl_context;
EGLSurface egl_surface;
GLint
position_loc,
texCoord_loc,
texSampl_loc;
void render()
{
static int init = 0;
if(!init) {
#ifdef X11
XWindowAttributes gwa;
XGetWindowAttributes(x_display, win, &gwa);
glViewport(0, 0, gwa.width, gwa.height);
#else
glViewport(0, 288, 854, 480);
#endif
glClearColor(1.0, 0.0, 1.0, 1.0);
init = 1;
}
glClear(GL_COLOR_BUFFER_BIT);
glVertexAttribPointer(position_loc, 3, GL_FLOAT, false, 0, vertexArray);
glVertexAttribPointer(texCoord_loc, 2, GL_FLOAT, false, 0, textureArray);
glEnableVertexAttribArray(position_loc);
glEnableVertexAttribArray(texCoord_loc);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 5);
eglSwapBuffers(egl_display, egl_surface);
}
int create_egl_context()
{
EGLConfig egl_config;
EGLint num_config;
EGLint attr[] = {
EGL_BUFFER_SIZE, 16,
EGL_RENDERABLE_TYPE,
EGL_OPENGL_ES2_BIT,
EGL_NONE
};
EGLint ctx_attr[] = {
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE
};
#ifdef X11
egl_display = eglGetDisplay((EGLNativeDisplayType)x_display);
#else
egl_display = eglGetDisplay(NULL);
#endif
if(egl_display == EGL_NO_DISPLAY)
{
cerr << "Could not get EGL display" << endl;
return EXIT_FAILURE;
}
if(!eglInitialize(egl_display, NULL, NULL))
{
cerr << "Unable to initialize EGL" << endl;
return EXIT_FAILURE;
}
if(!eglChooseConfig(egl_display, attr, &egl_config, 1, &num_config))
{
cerr << "Failed to configure EGL context" << endl;
return EXIT_FAILURE;
}
if(num_config < 1)
{
cerr << "No EGL configurations found" << endl;
return EXIT_FAILURE;
}
#ifdef X11
egl_surface = eglCreateWindowSurface(egl_display, egl_config, (EGLNativeWindowType)win, NULL);
#else
egl_surface = eglCreateWindowSurface(egl_display, egl_config, (EGLNativeWindowType)NULL, NULL);
#endif
if(egl_surface == EGL_NO_SURFACE)
{
cerr << "Unable to create EGL surface: " << eglGetError() << endl;
return EXIT_FAILURE;
}
egl_context = eglCreateContext(egl_display, egl_config, EGL_NO_CONTEXT, ctx_attr);
if(egl_context == EGL_NO_CONTEXT)
{
cerr << "Unable to create EGL context: " << eglGetError() << endl;
return EXIT_FAILURE;
}
eglMakeCurrent(egl_display, egl_surface, egl_surface, egl_context);
return EXIT_SUCCESS;
}
int init_gl_context()
{
/////// the openGL part ///////////////////////////////////////////////////////////////
GLuint shaderProgram = glCreateProgram();
GLuint vertexShader = load_shader(vertex_src, GL_VERTEX_SHADER);
GLuint fragmentShader = load_shader(fragment_src, GL_FRAGMENT_SHADER);
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
glUseProgram(shaderProgram);
//// now get the locations (kind of handle) of the shaders variables
position_loc = glGetAttribLocation(shaderProgram, "aPosition");
texCoord_loc = glGetAttribLocation(shaderProgram, "aTexCoord");
texSampl_loc = glGetUniformLocation(shaderProgram, "tex");
if(position_loc < 0) {
cerr << "Unable to get position attribute" << endl;
return EXIT_FAILURE;
}
if(texCoord_loc < 0) {
cerr << "Unable to get texCoord attribute" << endl;
return EXIT_FAILURE;
}
if(texSampl_loc < 0) {
cerr << "Unable to get texSampl uniform" << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include "rdb_protocol/terms/terms.hpp"
#include "rdb_protocol/error.hpp"
#include "rdb_protocol/op.hpp"
namespace ql {
class pend_term_t : public op_term_t {
public:
pend_term_t(env_t *env, protob_t<const Term> term) : op_term_t(env, term, argspec_t(2)) { }
protected:
enum which_pend_t {PRE, AP};
counted_t<val_t> pend(which_pend_t which_pend) {
counted_t<const datum_t> arr = arg(0)->as_datum();
counted_t<const datum_t> new_el = arg(1)->as_datum();
arr->check_type(datum_t::R_ARRAY);
scoped_ptr_t<datum_t> out(new datum_t(datum_t::R_ARRAY));
if (which_pend == PRE) {
// TODO: this is horrendously inefficient.
out->add(new_el);
for (size_t i = 0; i < arr->size(); ++i) out->add(arr->get(i));
} else {
// TODO: this is horrendously inefficient.
for (size_t i = 0; i < arr->size(); ++i) out->add(arr->get(i));
out->add(new_el);
}
return new_val(counted_t<const datum_t>(out.release()));
}
};
class append_term_t : public pend_term_t {
public:
append_term_t(env_t *env, protob_t<const Term> term) : pend_term_t(env, term) { }
private:
virtual counted_t<val_t> eval_impl() {
return pend(AP);
}
virtual const char *name() const { return "append"; }
};
class prepend_term_t : public pend_term_t {
public:
prepend_term_t(env_t *env, protob_t<const Term> term) : pend_term_t(env, term) { }
private:
virtual counted_t<val_t> eval_impl() {
return pend(PRE);
}
virtual const char *name() const { return "prepend"; }
};
// This gets the literal index of a (possibly negative) index relative to a
// fixed size.
size_t canonicalize(const term_t *t, int32_t index, size_t size, bool *oob_out = 0) {
CT_ASSERT(sizeof(size_t) >= sizeof(int32_t));
if (index >= 0) return index;
if (size_t(index * -1) > size) {
if (oob_out) {
*oob_out = true;
} else {
rfail_target(t, "Index out of bounds: %d", index);
}
return 0;
}
return size + index;
}
class nth_term_t : public op_term_t {
public:
nth_term_t(env_t *env, protob_t<const Term> term) : op_term_t(env, term, argspec_t(2)) { }
private:
virtual counted_t<val_t> eval_impl() {
counted_t<val_t> v = arg(0);
int32_t n = arg(1)->as_int<int32_t>();
if (v->get_type().is_convertible(val_t::type_t::DATUM)) {
counted_t<const datum_t> arr = v->as_datum();
size_t real_n = canonicalize(this, n, arr->size());
return new_val(arr->get(real_n));
} else {
counted_t<datum_stream_t> s = v->as_seq();
rcheck(n >= -1, strprintf("Cannot use an index < -1 (%d) on a stream.", n));
counted_t<const datum_t> last_d;
for (int32_t i = 0; ; ++i) {
counted_t<const datum_t> d = s->next();
if (!d.has()) {
rcheck(n == -1 && last_d.has(),
strprintf("Index out of bounds: %d", n));
return new_val(last_d);
}
if (i == n) return new_val(d);
last_d = d;
r_sanity_check(n == -1 || i < n);
}
}
}
virtual const char *name() const { return "nth"; }
};
// TODO: this kinda sucks.
class slice_term_t : public op_term_t {
public:
slice_term_t(env_t *env, protob_t<const Term> term)
: op_term_t(env, term, argspec_t(3)) { }
private:
virtual counted_t<val_t> eval_impl() {
counted_t<val_t> v = arg(0);
int32_t fake_l = arg(1)->as_int<int32_t>();
int32_t fake_r = arg(2)->as_int<int32_t>();
if (v->get_type().is_convertible(val_t::type_t::DATUM)) {
counted_t<const datum_t> arr = v->as_datum();
rcheck(arr->get_type() == datum_t::R_ARRAY, "Cannot slice non-sequences.");
bool l_oob = false;
size_t real_l = canonicalize(this, fake_l, arr->size(), &l_oob);
if (l_oob) real_l = 0;
bool r_oob = false;
size_t real_r = canonicalize(this, fake_r, arr->size(), &r_oob);
scoped_ptr_t<datum_t> out(new datum_t(datum_t::R_ARRAY));
if (!r_oob) {
for (size_t i = real_l; i <= real_r; ++i) {
if (i >= arr->size()) break;
out->add(arr->get(i));
}
}
return new_val(counted_t<const datum_t>(out.release()));
} else if (v->get_type().is_convertible(val_t::type_t::SEQUENCE)) {
counted_t<table_t> t;
counted_t<datum_stream_t> seq;
if (v->get_type().is_convertible(val_t::type_t::SELECTION)) {
std::pair<counted_t<table_t>, counted_t<datum_stream_t> > t_seq
= v->as_selection();
t = t_seq.first;
seq = t_seq.second;
} else {
seq = v->as_seq();
}
rcheck(fake_l >= 0, "Cannot use a negative left index on a stream.");
rcheck(fake_r >= -1, "Cannot use a right index < -1 on a stream");
counted_t<datum_stream_t> new_ds = seq->slice(fake_l, fake_r);
return t.has() ? new_val(new_ds, t) : new_val(new_ds);
}
rfail("Cannot slice non-sequences.");
unreachable();
}
virtual const char *name() const { return "slice"; }
};
class limit_term_t : public op_term_t {
public:
limit_term_t(env_t *env, protob_t<const Term> term)
: op_term_t(env, term, argspec_t(2)) { }
private:
virtual counted_t<val_t> eval_impl() {
counted_t<val_t> v = arg(0);
counted_t<table_t> t;
if (v->get_type().is_convertible(val_t::type_t::SELECTION)) {
t = v->as_selection().first;
}
counted_t<datum_stream_t> ds = v->as_seq();
int32_t r = arg(1)->as_int<int32_t>();
rcheck(r >= 0, strprintf("LIMIT takes a non-negative argument (got %d)", r));
counted_t<datum_stream_t> new_ds;
if (r == 0) {
new_ds = ds->slice(1, 0); // (0, -1) has a different meaning
} else {
new_ds = ds->slice(0, r-1); // note that both bounds are inclusive
}
return t.has() ? new_val(new_ds, t) : new_val(new_ds);
}
virtual const char *name() const { return "limit"; }
};
class set_insert_term_t : public op_term_t {
public:
set_insert_term_t(env_t *env, protob_t<const Term> term)
: op_term_t(env, term, argspec_t(2)) { }
private:
virtual counted_t<val_t> eval_impl() {
counted_t<const datum_t> arr = arg(0)->as_datum();
counted_t<const datum_t> new_el = arg(1)->as_datum();
arr->check_type(datum_t::R_ARRAY);
std::set<counted_t<const datum_t> > el_set;
scoped_ptr_t<datum_t> out(new datum_t(datum_t::R_ARRAY));
for (size_t i = 0; i < arr->size(); ++i) {
if(el_set.insert(arr->get(i)).second) {
out->add(arr->get(i));
}
}
if (!std_contains(el_set, new_el)) {
out->add(new_el);
}
return new_val(counted_t<const datum_t>(out.release()));
}
virtual const char *name() const { return "set_insert"; }
};
class set_union_term_t : public op_term_t {
public:
set_union_term_t(env_t *env, protob_t<const Term> term)
: op_term_t(env, term, argspec_t(2)) { }
private:
virtual counted_t<val_t> eval_impl() {
counted_t<const datum_t> arr1 = arg(0)->as_datum();
counted_t<const datum_t> arr2 = arg(1)->as_datum();
arr1->check_type(datum_t::R_ARRAY);
arr2->check_type(datum_t::R_ARRAY);
std::set<counted_t<const datum_t> > el_set;
scoped_ptr_t<datum_t> out(new datum_t(datum_t::R_ARRAY));
for (size_t i = 0; i < arr1->size(); ++i) {
if(el_set.insert(arr1->get(i)).second) {
out->add(arr1->get(i));
}
}
for (size_t i = 0; i < arr2->size(); ++i) {
if(el_set.insert(arr2->get(i)).second) {
out->add(arr2->get(i));
}
}
return new_val(counted_t<const datum_t>(out.release()));
}
virtual const char *name() const { return "set_union"; }
};
class set_intersection_term_t : public op_term_t {
public:
set_intersection_term_t(env_t *env, protob_t<const Term> term)
: op_term_t(env, term, argspec_t(2)) { }
private:
virtual counted_t<val_t> eval_impl() {
counted_t<const datum_t> arr1 = arg(0)->as_datum();
counted_t<const datum_t> arr2 = arg(1)->as_datum();
arr1->check_type(datum_t::R_ARRAY);
arr2->check_type(datum_t::R_ARRAY);
std::set<counted_t<const datum_t> > el_set;
scoped_ptr_t<datum_t> out(new datum_t(datum_t::R_ARRAY));
for (size_t i = 0; i < arr1->size(); ++i) {
el_set.insert(arr1->get(i));
}
for (size_t i = 0; i < arr2->size(); ++i) {
if (std_contains(el_set, arr2->get(i))) {
out->add(arr2->get(i));
el_set.erase(arr2->get(i));
}
}
return new_val(counted_t<const datum_t>(out.release()));
}
virtual const char *name() const { return "set_intersection"; }
};
class set_difference_term_t : public op_term_t {
public:
set_difference_term_t(env_t *env, protob_t<const Term> term)
: op_term_t(env, term, argspec_t(2)) { }
private:
virtual counted_t<val_t> eval_impl() {
counted_t<const datum_t> arr1 = arg(0)->as_datum();
counted_t<const datum_t> arr2 = arg(1)->as_datum();
arr1->check_type(datum_t::R_ARRAY);
arr2->check_type(datum_t::R_ARRAY);
std::set<counted_t<const datum_t> > el_set;
scoped_ptr_t<datum_t> out(new datum_t(datum_t::R_ARRAY));
for (size_t i = 0; i < arr2->size(); ++i) {
el_set.insert(arr2->get(i));
}
for (size_t i = 0; i < arr1->size(); ++i) {
if (!std_contains(el_set, arr1->get(i))) {
out->add(arr1->get(i));
el_set.insert(arr1->get(i));
}
}
return new_val(counted_t<const datum_t>(out.release()));
}
virtual const char *name() const { return "set_difference"; }
};
counted_t<term_t> make_append_term(env_t *env, protob_t<const Term> term) {
return make_counted<append_term_t>(env, term);
}
counted_t<term_t> make_prepend_term(env_t *env, protob_t<const Term> term) {
return make_counted<prepend_term_t>(env, term);
}
counted_t<term_t> make_nth_term(env_t *env, protob_t<const Term> term) {
return make_counted<nth_term_t>(env, term);
}
counted_t<term_t> make_slice_term(env_t *env, protob_t<const Term> term) {
return make_counted<slice_term_t>(env, term);
}
counted_t<term_t> make_limit_term(env_t *env, protob_t<const Term> term) {
return make_counted<limit_term_t>(env, term);
}
counted_t<term_t> make_set_insert_term(env_t *env, protob_t<const Term> term) {
return make_counted<set_insert_term_t>(env, term);
}
counted_t<term_t> make_set_union_term(env_t *env, protob_t<const Term> term) {
return make_counted<set_union_term_t>(env, term);
}
counted_t<term_t> make_set_intersection_term(env_t *env, protob_t<const Term> term) {
return make_counted<set_intersection_term_t>(env, term);
}
counted_t<term_t> make_set_difference_term(env_t *env, protob_t<const Term> term) {
return make_counted<set_difference_term_t>(env, term);
}
} // namespace ql
<commit_msg>Remove some unneeded calls to `check_type`.<commit_after>#include "rdb_protocol/terms/terms.hpp"
#include "rdb_protocol/error.hpp"
#include "rdb_protocol/op.hpp"
namespace ql {
class pend_term_t : public op_term_t {
public:
pend_term_t(env_t *env, protob_t<const Term> term) : op_term_t(env, term, argspec_t(2)) { }
protected:
enum which_pend_t {PRE, AP};
counted_t<val_t> pend(which_pend_t which_pend) {
counted_t<const datum_t> arr = arg(0)->as_datum();
counted_t<const datum_t> new_el = arg(1)->as_datum();
scoped_ptr_t<datum_t> out(new datum_t(datum_t::R_ARRAY));
if (which_pend == PRE) {
// TODO: this is horrendously inefficient.
out->add(new_el);
for (size_t i = 0; i < arr->size(); ++i) out->add(arr->get(i));
} else {
// TODO: this is horrendously inefficient.
for (size_t i = 0; i < arr->size(); ++i) out->add(arr->get(i));
out->add(new_el);
}
return new_val(counted_t<const datum_t>(out.release()));
}
};
class append_term_t : public pend_term_t {
public:
append_term_t(env_t *env, protob_t<const Term> term) : pend_term_t(env, term) { }
private:
virtual counted_t<val_t> eval_impl() {
return pend(AP);
}
virtual const char *name() const { return "append"; }
};
class prepend_term_t : public pend_term_t {
public:
prepend_term_t(env_t *env, protob_t<const Term> term) : pend_term_t(env, term) { }
private:
virtual counted_t<val_t> eval_impl() {
return pend(PRE);
}
virtual const char *name() const { return "prepend"; }
};
// This gets the literal index of a (possibly negative) index relative to a
// fixed size.
size_t canonicalize(const term_t *t, int32_t index, size_t size, bool *oob_out = 0) {
CT_ASSERT(sizeof(size_t) >= sizeof(int32_t));
if (index >= 0) return index;
if (size_t(index * -1) > size) {
if (oob_out) {
*oob_out = true;
} else {
rfail_target(t, "Index out of bounds: %d", index);
}
return 0;
}
return size + index;
}
class nth_term_t : public op_term_t {
public:
nth_term_t(env_t *env, protob_t<const Term> term) : op_term_t(env, term, argspec_t(2)) { }
private:
virtual counted_t<val_t> eval_impl() {
counted_t<val_t> v = arg(0);
int32_t n = arg(1)->as_int<int32_t>();
if (v->get_type().is_convertible(val_t::type_t::DATUM)) {
counted_t<const datum_t> arr = v->as_datum();
size_t real_n = canonicalize(this, n, arr->size());
return new_val(arr->get(real_n));
} else {
counted_t<datum_stream_t> s = v->as_seq();
rcheck(n >= -1, strprintf("Cannot use an index < -1 (%d) on a stream.", n));
counted_t<const datum_t> last_d;
for (int32_t i = 0; ; ++i) {
counted_t<const datum_t> d = s->next();
if (!d.has()) {
rcheck(n == -1 && last_d.has(),
strprintf("Index out of bounds: %d", n));
return new_val(last_d);
}
if (i == n) return new_val(d);
last_d = d;
r_sanity_check(n == -1 || i < n);
}
}
}
virtual const char *name() const { return "nth"; }
};
// TODO: this kinda sucks.
class slice_term_t : public op_term_t {
public:
slice_term_t(env_t *env, protob_t<const Term> term)
: op_term_t(env, term, argspec_t(3)) { }
private:
virtual counted_t<val_t> eval_impl() {
counted_t<val_t> v = arg(0);
int32_t fake_l = arg(1)->as_int<int32_t>();
int32_t fake_r = arg(2)->as_int<int32_t>();
if (v->get_type().is_convertible(val_t::type_t::DATUM)) {
counted_t<const datum_t> arr = v->as_datum();
rcheck(arr->get_type() == datum_t::R_ARRAY, "Cannot slice non-sequences.");
bool l_oob = false;
size_t real_l = canonicalize(this, fake_l, arr->size(), &l_oob);
if (l_oob) real_l = 0;
bool r_oob = false;
size_t real_r = canonicalize(this, fake_r, arr->size(), &r_oob);
scoped_ptr_t<datum_t> out(new datum_t(datum_t::R_ARRAY));
if (!r_oob) {
for (size_t i = real_l; i <= real_r; ++i) {
if (i >= arr->size()) break;
out->add(arr->get(i));
}
}
return new_val(counted_t<const datum_t>(out.release()));
} else if (v->get_type().is_convertible(val_t::type_t::SEQUENCE)) {
counted_t<table_t> t;
counted_t<datum_stream_t> seq;
if (v->get_type().is_convertible(val_t::type_t::SELECTION)) {
std::pair<counted_t<table_t>, counted_t<datum_stream_t> > t_seq
= v->as_selection();
t = t_seq.first;
seq = t_seq.second;
} else {
seq = v->as_seq();
}
rcheck(fake_l >= 0, "Cannot use a negative left index on a stream.");
rcheck(fake_r >= -1, "Cannot use a right index < -1 on a stream");
counted_t<datum_stream_t> new_ds = seq->slice(fake_l, fake_r);
return t.has() ? new_val(new_ds, t) : new_val(new_ds);
}
rfail("Cannot slice non-sequences.");
unreachable();
}
virtual const char *name() const { return "slice"; }
};
class limit_term_t : public op_term_t {
public:
limit_term_t(env_t *env, protob_t<const Term> term)
: op_term_t(env, term, argspec_t(2)) { }
private:
virtual counted_t<val_t> eval_impl() {
counted_t<val_t> v = arg(0);
counted_t<table_t> t;
if (v->get_type().is_convertible(val_t::type_t::SELECTION)) {
t = v->as_selection().first;
}
counted_t<datum_stream_t> ds = v->as_seq();
int32_t r = arg(1)->as_int<int32_t>();
rcheck(r >= 0, strprintf("LIMIT takes a non-negative argument (got %d)", r));
counted_t<datum_stream_t> new_ds;
if (r == 0) {
new_ds = ds->slice(1, 0); // (0, -1) has a different meaning
} else {
new_ds = ds->slice(0, r-1); // note that both bounds are inclusive
}
return t.has() ? new_val(new_ds, t) : new_val(new_ds);
}
virtual const char *name() const { return "limit"; }
};
class set_insert_term_t : public op_term_t {
public:
set_insert_term_t(env_t *env, protob_t<const Term> term)
: op_term_t(env, term, argspec_t(2)) { }
private:
virtual counted_t<val_t> eval_impl() {
counted_t<const datum_t> arr = arg(0)->as_datum();
counted_t<const datum_t> new_el = arg(1)->as_datum();
std::set<counted_t<const datum_t> > el_set;
scoped_ptr_t<datum_t> out(new datum_t(datum_t::R_ARRAY));
for (size_t i = 0; i < arr->size(); ++i) {
if(el_set.insert(arr->get(i)).second) {
out->add(arr->get(i));
}
}
if (!std_contains(el_set, new_el)) {
out->add(new_el);
}
return new_val(counted_t<const datum_t>(out.release()));
}
virtual const char *name() const { return "set_insert"; }
};
class set_union_term_t : public op_term_t {
public:
set_union_term_t(env_t *env, protob_t<const Term> term)
: op_term_t(env, term, argspec_t(2)) { }
private:
virtual counted_t<val_t> eval_impl() {
counted_t<const datum_t> arr1 = arg(0)->as_datum();
counted_t<const datum_t> arr2 = arg(1)->as_datum();
std::set<counted_t<const datum_t> > el_set;
scoped_ptr_t<datum_t> out(new datum_t(datum_t::R_ARRAY));
for (size_t i = 0; i < arr1->size(); ++i) {
if(el_set.insert(arr1->get(i)).second) {
out->add(arr1->get(i));
}
}
for (size_t i = 0; i < arr2->size(); ++i) {
if(el_set.insert(arr2->get(i)).second) {
out->add(arr2->get(i));
}
}
return new_val(counted_t<const datum_t>(out.release()));
}
virtual const char *name() const { return "set_union"; }
};
class set_intersection_term_t : public op_term_t {
public:
set_intersection_term_t(env_t *env, protob_t<const Term> term)
: op_term_t(env, term, argspec_t(2)) { }
private:
virtual counted_t<val_t> eval_impl() {
counted_t<const datum_t> arr1 = arg(0)->as_datum();
counted_t<const datum_t> arr2 = arg(1)->as_datum();
std::set<counted_t<const datum_t> > el_set;
scoped_ptr_t<datum_t> out(new datum_t(datum_t::R_ARRAY));
for (size_t i = 0; i < arr1->size(); ++i) {
el_set.insert(arr1->get(i));
}
for (size_t i = 0; i < arr2->size(); ++i) {
if (std_contains(el_set, arr2->get(i))) {
out->add(arr2->get(i));
el_set.erase(arr2->get(i));
}
}
return new_val(counted_t<const datum_t>(out.release()));
}
virtual const char *name() const { return "set_intersection"; }
};
class set_difference_term_t : public op_term_t {
public:
set_difference_term_t(env_t *env, protob_t<const Term> term)
: op_term_t(env, term, argspec_t(2)) { }
private:
virtual counted_t<val_t> eval_impl() {
counted_t<const datum_t> arr1 = arg(0)->as_datum();
counted_t<const datum_t> arr2 = arg(1)->as_datum();
std::set<counted_t<const datum_t> > el_set;
scoped_ptr_t<datum_t> out(new datum_t(datum_t::R_ARRAY));
for (size_t i = 0; i < arr2->size(); ++i) {
el_set.insert(arr2->get(i));
}
for (size_t i = 0; i < arr1->size(); ++i) {
if (!std_contains(el_set, arr1->get(i))) {
out->add(arr1->get(i));
el_set.insert(arr1->get(i));
}
}
return new_val(counted_t<const datum_t>(out.release()));
}
virtual const char *name() const { return "set_difference"; }
};
counted_t<term_t> make_append_term(env_t *env, protob_t<const Term> term) {
return make_counted<append_term_t>(env, term);
}
counted_t<term_t> make_prepend_term(env_t *env, protob_t<const Term> term) {
return make_counted<prepend_term_t>(env, term);
}
counted_t<term_t> make_nth_term(env_t *env, protob_t<const Term> term) {
return make_counted<nth_term_t>(env, term);
}
counted_t<term_t> make_slice_term(env_t *env, protob_t<const Term> term) {
return make_counted<slice_term_t>(env, term);
}
counted_t<term_t> make_limit_term(env_t *env, protob_t<const Term> term) {
return make_counted<limit_term_t>(env, term);
}
counted_t<term_t> make_set_insert_term(env_t *env, protob_t<const Term> term) {
return make_counted<set_insert_term_t>(env, term);
}
counted_t<term_t> make_set_union_term(env_t *env, protob_t<const Term> term) {
return make_counted<set_union_term_t>(env, term);
}
counted_t<term_t> make_set_intersection_term(env_t *env, protob_t<const Term> term) {
return make_counted<set_intersection_term_t>(env, term);
}
counted_t<term_t> make_set_difference_term(env_t *env, protob_t<const Term> term) {
return make_counted<set_difference_term_t>(env, term);
}
} // namespace ql
<|endoftext|>
|
<commit_before><commit_msg>more tests for ScRangeList::DeleteArea<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: servobj.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-08 21:49:48 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SC_SERVOBJ_HXX
#define SC_SERVOBJ_HXX
#ifndef _SFXLSTNER_HXX //autogen
#include <svtools/lstner.hxx>
#endif
#ifndef _SVT_LISTENER_HXX
#include <svtools/listener.hxx>
#endif
#ifndef _LINKSRC_HXX //autogen
#include <sfx2/linksrc.hxx>
#endif
#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif
#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif
class ScDocShell;
class ScServerObject;
class ScServerObjectSvtListenerForwarder : public SvtListener
{
ScServerObject* pObj;
SfxBroadcaster aBroadcaster;
public:
ScServerObjectSvtListenerForwarder( ScServerObject* pObjP);
virtual ~ScServerObjectSvtListenerForwarder();
virtual void Notify( SvtBroadcaster& rBC, const SfxHint& rHint);
};
class ScServerObject : public ::sfx2::SvLinkSource, public SfxListener
{
private:
ScServerObjectSvtListenerForwarder aForwarder;
ScDocShell* pDocSh;
ScRange aRange;
String aItemStr;
BOOL bRefreshListener;
void Clear();
public:
ScServerObject( ScDocShell* pShell, const String& rItem );
virtual ~ScServerObject();
virtual BOOL GetData( ::com::sun::star::uno::Any & rData /*out param*/,
const String & rMimeType,
BOOL bSynchron = FALSE );
virtual void SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType,
const SfxHint& rHint, const TypeId& rHintType );
void EndListeningAll();
};
//SO2_DECL_REF( ScServerObject )
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.5.700); FILE MERGED 2008/04/01 15:31:00 thb 1.5.700.3: #i85898# Stripping all external header guards 2008/04/01 12:36:49 thb 1.5.700.2: #i85898# Stripping all external header guards 2008/03/31 17:15:47 rt 1.5.700.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: servobj.hxx,v $
* $Revision: 1.6 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef SC_SERVOBJ_HXX
#define SC_SERVOBJ_HXX
#include <svtools/lstner.hxx>
#include <svtools/listener.hxx>
#include <sfx2/linksrc.hxx>
#include "global.hxx"
#include "address.hxx"
class ScDocShell;
class ScServerObject;
class ScServerObjectSvtListenerForwarder : public SvtListener
{
ScServerObject* pObj;
SfxBroadcaster aBroadcaster;
public:
ScServerObjectSvtListenerForwarder( ScServerObject* pObjP);
virtual ~ScServerObjectSvtListenerForwarder();
virtual void Notify( SvtBroadcaster& rBC, const SfxHint& rHint);
};
class ScServerObject : public ::sfx2::SvLinkSource, public SfxListener
{
private:
ScServerObjectSvtListenerForwarder aForwarder;
ScDocShell* pDocSh;
ScRange aRange;
String aItemStr;
BOOL bRefreshListener;
void Clear();
public:
ScServerObject( ScDocShell* pShell, const String& rItem );
virtual ~ScServerObject();
virtual BOOL GetData( ::com::sun::star::uno::Any & rData /*out param*/,
const String & rMimeType,
BOOL bSynchron = FALSE );
virtual void SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType,
const SfxHint& rHint, const TypeId& rHintType );
void EndListeningAll();
};
//SO2_DECL_REF( ScServerObject )
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: olkact.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: nn $ $Date: 2000-09-22 18:37:37 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef PCH
#include "ui_pch.hxx"
#endif
#pragma hdrstop
//------------------------------------------------------------------
#define _BIGINT_HXX
#define _CACHESTR_HXX
#define _CONFIG_HXX
#define _CURSOR_HXX
#define _CTRLTOOL_HXX
#define _DLGCFG_HXX
#define _DYNARR_HXX
#define _EXTATTR_HXX
#define _FILDLG_HXX
#define _FONTDLG_HXX
#define _FRM3D_HXX
#define _INTRO_HXX
#define _ISETBWR_HXX
#define _NO_SVRTF_PARSER_HXX
#define _MACRODLG_HXX
#define _MODALDLG_HXX
#define _MOREBUTTON_HXX
#define _OUTLINER_HXX
#define _PASSWD_HXX
#define _PRNDLG_HXX
//#define _POLY_HXX
#define _PVRWIN_HXX
#define _QUEUE_HXX
#define _RULER_HXX
#define _SCRWIN_HXX
#define _SETBRW_HXX
#define _STACK_HXX
//#define _STATUS_HXX ***
#define _STDMENU_HXX
#define _TABBAR_HXX
//#define _VCBRW_HXX
#define _VCTRLS_HXX
//#define _VCSBX_HXX
#define _VCONT_HXX
#define _VDRWOBJ_HXX
//sfx
#define _SFXAPPWIN_HXX
#define _SFXCTRLITEM
#define _SFXDISPATCH_HXX
#define _SFXFILEDLG_HXX
#define _SFXIMGMGR_HXX
#define _SFXIPFRM_HXX
#define _SFX_MACRO_HXX
#define _SFXMULTISEL_HXX
#define _SFX_MINFITEM_HXX
//sfxcore.hxx
//#define _SFXINIMGR_HXX ***
//#define _SFXCFGITEM_HXX
//#define _SFX_PRINTER_HXX
#define _SFXGENLINK_HXX
#define _SFXHINTPOST_HXX
#define _SFXDOCINF_HXX
#define _SFXLINKHDL_HXX
//#define _SFX_PROGRESS_HXX
//sfxsh.hxx
//#define _SFX_SHELL_HXX
//#define _SFXAPP_HXX
//#define _SFXDISPATCH_HXX
//#define _SFXMSG_HXX ***
//#define _SFXOBJFACE_HXX ***
//#define _SFXREQUEST_HXX
#define _SFXMACRO_HXX
// SFX
//#define _SFXAPPWIN_HXX ***
#define _SFX_SAVEOPT_HXX
//#define _SFX_CHILDWIN_HXX
//#define _SFXCTRLITEM_HXX
#define _SFXPRNMON_HXX
#define _INTRO_HXX
#define _SFXMSGDESCR_HXX
#define _SFXMSGPOOL_HXX
#define _SFXFILEDLG_HXX
#define _PASSWD_HXX
#define _SFXTBXCTRL_HXX
#define _SFXSTBITEM_HXX
#define _SFXMNUITEM_HXX
#define _SFXIMGMGR_HXX
#define _SFXTBXMGR_HXX
#define _SFXSTBMGR_HXX
#define _SFX_MINFITEM_HXX
#define _SFXEVENT_HXX
//sfxdoc.hxx
//#define _SFX_OBJSH_HXX
//#define _SFX_CLIENTSH_HXX
//#define _SFXDOCINF_HXX
//#define _SFX_OBJFAC_HXX
#define _SFX_DOCFILT_HXX
//#define _SFXDOCFILE_HXX ***
//define _VIEWFAC_HXX
//#define _SFXVIEWFRM_HXX
//#define _SFXVIEWSH_HXX
//#define _MDIFRM_HXX ***
#define _SFX_IPFRM_HXX
//#define _SFX_INTERNO_HXX
//sfxdlg.hxx
//#define _SFXTABDLG_HXX
//#define _BASEDLGS_HXX ***
#define _SFX_DINFDLG_HXX
#define _SFXDINFEDT_HXX
#define _SFX_MGETEMPL_HXX
#define _SFX_TPLPITEM_HXX
//#define _SFX_STYLEDLG_HXX
#define _NEWSTYLE_HXX
//#define _SFXDOCTEMPL_HXX ***
//#define _SFXDOCTDLG_HXX ***
//#define _SFX_TEMPLDLG_HXX ***
//#define _SFXNEW_HXX ***
#define _SFXDOCMAN_HXX
//#define _SFXDOCKWIN_HXX
//sfxitems.hxx
#define _SFX_WHMAP_HXX
#define _ARGS_HXX
//#define _SFXPOOLITEM_HXX
//#define _SFXINTITEM_HXX
//#define _SFXENUMITEM_HXX
#define _SFXFLAGITEM_HXX
//#define _SFXSTRITEM_HXX
#define _SFXPTITEM_HXX
#define _SFXRECTITEM_HXX
//#define _SFXITEMPOOL_HXX
//#define _SFXITEMSET_HXX
#define _SFXITEMITER_HXX
#define _SFX_WHITER_HXX
#define _SFXPOOLCACH_HXX
//#define _AEITEM_HXX
#define _SFXRNGITEM_HXX
//#define _SFXSLSTITM_HXX
//#define _SFXSTYLE_HXX
//xout.hxx
//#define _XENUM_HXX
//#define _XPOLY_HXX
//#define _XATTR_HXX
//#define _XOUTX_HXX
//#define _XPOOL_HXX
//#define _XTABLE_HXX
//svdraw.hxx
#define _SDR_NOITEMS
#define _SDR_NOTOUCH
#define _SDR_NOTRANSFORM
//#define _SDR_NOOBJECTS
//#define _SDR_NOVIEWS
#define _SFXBASIC_HXX
#define _SFX_DOCFILE_HXX
#define _SFX_DOCFILT_HXX
#define _SFX_DOCINF_HXX
#define _SFX_DOCSH_HXX
#define _SFX_TEMPLDLG_HXX
#define _SFXSTBMGR_HXX
#define _SFXTBXMGR_HXX
#define _SFXIMGMGR_HXX
#define _SFXMNUITEM_HXX
#define _SFXMNUMGR_HXX
#define _SFXSTBITEM_HXX
#define _SFXTBXCTRL_HXX
#define _SFXFILEDLG_HXX
#define _SFXREQUEST_HXX
#define _SFXOBJFACE_HXX
#define _SFXMSGPOOL_HXX
#define _SFXMSGDESCR_HXX
#define _SFXMSG_HXX
#define _SFX_PRNMON_HXX
//si
#define _SI_NOSBXCONTROLS
#define _SI_NOCONTROL
//#define SI_NOITEMS
//#define SI_NODRW
//#define SI_NOOTHERFORMS
#define _SIDLL_HXX
//#define _VCSBX_HXX
//#define _VCBRW_HXX
//#define _SVDATTR_HXX <--- der wars
#define _SVDXOUT_HXX
#define _SVDEC_HXX
//#define _SVDIO_HXX
//#define _SVDLAYER_HXX
//#define _SVDRAG_HXX
#define _SVINCVW_HXX
#define _SV_MULTISEL_HXX
#define _SVRTV_HXX
#define _SVTABBX_HXX
#define _SVX_DAILDLL_HXX
#define _SVX_HYPHEN_HXX
#define _SVX_IMPGRF_HXX
#define _SVX_OPTITEMS_HXX
#define _SVX_OPTGERL_HXX
#define _SVX_OPTSAVE_HXX
#define _SVX_OPTSPELL_HXX
#define _SVX_OPTPATH_HXX
#define _SVX_OPTLINGU_HXX
#define _SVX_RULER_HXX
#define _SVX_RULRITEM_HXX
#define _SVX_SPLWRAP_HXX
#define _SVX_SPLDLG_HXX
#define _SVX_THESDLG_HXX
// INCLUDE ---------------------------------------------------------------
#include <sfx2/childwin.hxx>
#include <sfx2/objsh.hxx>
#include "document.hxx"
#include "viewdata.hxx"
#include "drawview.hxx"
#include "drawpage.hxx"
#include "drwlayer.hxx"
// STATIC DATA -----------------------------------------------------------
// -----------------------------------------------------------------------
void ActivateOlk( ScViewData* pViewData )
{
// Browser fuer Virtual Controls fuellen
// VC's und den Browser dazu gibts nicht mehr...
// GetSbxForm gibt's nicht mehr, muss auch nichts mehr angemeldet werden
}
void DeActivateOlk( ScViewData* pViewData )
{
// Browser fuer Virtual Controls fuellen
// VC's und den Browser dazu gibts nicht mehr...
// GetSbxForm gibt's nicht mehr, muss auch nichts mehr angemeldet werden
}
<commit_msg>del: old stuff<commit_after>/*************************************************************************
*
* $RCSfile: olkact.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: mh $ $Date: 2002-01-16 11:26:47 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef PCH
#include "ui_pch.hxx"
#endif
#pragma hdrstop
// INCLUDE ---------------------------------------------------------------
class ScViewData;
// -----------------------------------------------------------------------
void ActivateOlk( ScViewData* pViewData )
{
// Browser fuer Virtual Controls fuellen
// VC's und den Browser dazu gibts nicht mehr...
// GetSbxForm gibt's nicht mehr, muss auch nichts mehr angemeldet werden
}
void DeActivateOlk( ScViewData* pViewData )
{
// Browser fuer Virtual Controls fuellen
// VC's und den Browser dazu gibts nicht mehr...
// GetSbxForm gibt's nicht mehr, muss auch nichts mehr angemeldet werden
}
<|endoftext|>
|
<commit_before>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "lid_space_compaction_job_take2.h"
#include "i_document_scan_iterator.h"
#include "i_lid_space_compaction_handler.h"
#include "i_operation_storer.h"
#include <vespa/searchcore/proton/feedoperation/moveoperation.h>
#include <vespa/searchcorespi/index/i_thread_service.h>
#include <vespa/persistence/spi/bucket_tasks.h>
#include <vespa/document/fieldvalue/document.h>
#include <vespa/vespalib/util/destructor_callbacks.h>
#include <vespa/vespalib/util/lambdatask.h>
#include <cassert>
#include <thread>
using search::DocumentMetaData;
using search::LidUsageStats;
using storage::spi::makeBucketTask;
using storage::spi::Bucket;
using vespalib::makeLambdaTask;
namespace proton::lidspace {
namespace {
class IncOnDestruct {
public:
IncOnDestruct(std::atomic<size_t> & count) : _count(count) {}
~IncOnDestruct() {
_count.fetch_add(1, std::memory_order_relaxed);
}
private:
std::atomic<size_t> & _count;
};
bool
isSameDocument(const search::DocumentMetaData & a, const search::DocumentMetaData & b) {
return (a.lid == b.lid) &&
(a.bucketId == b.bucketId) &&
(a.gid == b.gid) &&
(a.timestamp == b.timestamp); // Timestamp check can be removed once logic has proved itself in large scale.
}
}
void
CompactionJob::failOperation() {
IncOnDestruct countGuard(_executedCount);
_master.execute(makeLambdaTask([this] { _scanItr.reset(); }
}
bool
CompactionJob::scanDocuments(const LidUsageStats &stats)
{
if (_scanItr->valid()) {
DocumentMetaData document = getNextDocument(stats, false);
if (document.valid()) {
Bucket metaBucket(document::Bucket(_bucketSpace, document.bucketId));
IDestructorCallback::SP context = getLimiter().beginOperation();
auto bucketTask = makeBucketTask([this, meta=document, opsTracker=std::move(context)]
(const Bucket & bucket, std::shared_ptr<IDestructorCallback> onDone) {
assert(bucket.getBucketId() == meta.bucketId);
using DoneContext = vespalib::KeepAlive<std::pair<IDestructorCallback::SP, IDestructorCallback::SP>>;
moveDocument(meta, std::make_shared<DoneContext>(std::make_pair(std::move(opsTracker), std::move(onDone))));
}, [this](const Bucket &) { failOperation(); });
_startedCount.fetch_add(1, std::memory_order_relaxed);
_bucketExecutor.execute(metaBucket, std::move(bucketTask));
if (isBlocked(BlockedReason::OUTSTANDING_OPS)) {
return true;
}
}
}
return false;
}
void
CompactionJob::moveDocument(const search::DocumentMetaData & metaThen, std::shared_ptr<IDestructorCallback> context) {
IncOnDestruct countGuard(_executedCount);
if (_stopped.load(std::memory_order_relaxed)) return;
// The real lid must be sampled in the master thread.
//TODO remove target lid from createMoveOperation interface
auto op = _handler->createMoveOperation(metaThen, 0);
if (!op || !op->getDocument()) return;
// Early detection and force md5 calculation outside of master thread
if (metaThen.gid != op->getDocument()->getId().getGlobalId()) return;
_master.execute(makeLambdaTask([this, meta=metaThen, moveOp=std::move(op), onDone=std::move(context)]() mutable {
if (_stopped.load(std::memory_order_relaxed)) return;
completeMove(meta, std::move(moveOp), std::move(onDone));
}));
}
void
CompactionJob::completeMove(const search::DocumentMetaData & metaThen, std::unique_ptr<MoveOperation> moveOp,
std::shared_ptr<IDestructorCallback> onDone)
{
// Reread meta data as document might have been altered after move was initiated
// If so it will fail the timestamp sanity check later on.
search::DocumentMetaData metaNow = _handler->getMetaData(metaThen.lid);
// This should be impossible and should probably be an assert
if ( ! isSameDocument(metaThen, metaNow)) return;
if (metaNow.gid != moveOp->getDocument()->getId().getGlobalId()) return;
uint32_t lowestLid = _handler->getLidStatus().getLowestFreeLid();
if (lowestLid >= metaNow.lid) return;
moveOp->setTargetLid(lowestLid);
_opStorer.appendOperation(*moveOp, onDone);
_handler->handleMove(*moveOp, std::move(onDone));
}
CompactionJob::CompactionJob(const DocumentDBLidSpaceCompactionConfig &config,
std::shared_ptr<ILidSpaceCompactionHandler> handler,
IOperationStorer &opStorer,
IThreadService & master,
BucketExecutor & bucketExecutor,
IDiskMemUsageNotifier &diskMemUsageNotifier,
const BlockableMaintenanceJobConfig &blockableConfig,
IClusterStateChangedNotifier &clusterStateChangedNotifier,
bool nodeRetired,
document::BucketSpace bucketSpace)
: LidSpaceCompactionJobBase(config, std::move(handler), opStorer, diskMemUsageNotifier,
blockableConfig, clusterStateChangedNotifier, nodeRetired),
_master(master),
_bucketExecutor(bucketExecutor),
_bucketSpace(bucketSpace),
_stopped(false),
_startedCount(0),
_executedCount(0)
{ }
CompactionJob::~CompactionJob() = default;
bool
CompactionJob::inSync() const {
return _executedCount == _startedCount;
}
void
CompactionJob::onStop() {
_stopped = true;
while ( ! inSync() ) {
std::this_thread::sleep_for(1ms);
}
}
} // namespace proton
<commit_msg>Fix typo.<commit_after>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "lid_space_compaction_job_take2.h"
#include "i_document_scan_iterator.h"
#include "i_lid_space_compaction_handler.h"
#include "i_operation_storer.h"
#include <vespa/searchcore/proton/feedoperation/moveoperation.h>
#include <vespa/searchcorespi/index/i_thread_service.h>
#include <vespa/persistence/spi/bucket_tasks.h>
#include <vespa/document/fieldvalue/document.h>
#include <vespa/vespalib/util/destructor_callbacks.h>
#include <vespa/vespalib/util/lambdatask.h>
#include <cassert>
#include <thread>
using search::DocumentMetaData;
using search::LidUsageStats;
using storage::spi::makeBucketTask;
using storage::spi::Bucket;
using vespalib::makeLambdaTask;
namespace proton::lidspace {
namespace {
class IncOnDestruct {
public:
IncOnDestruct(std::atomic<size_t> & count) : _count(count) {}
~IncOnDestruct() {
_count.fetch_add(1, std::memory_order_relaxed);
}
private:
std::atomic<size_t> & _count;
};
bool
isSameDocument(const search::DocumentMetaData & a, const search::DocumentMetaData & b) {
return (a.lid == b.lid) &&
(a.bucketId == b.bucketId) &&
(a.gid == b.gid) &&
(a.timestamp == b.timestamp); // Timestamp check can be removed once logic has proved itself in large scale.
}
}
void
CompactionJob::failOperation() {
IncOnDestruct countGuard(_executedCount);
_master.execute(makeLambdaTask([this] { _scanItr.reset(); }));
}
bool
CompactionJob::scanDocuments(const LidUsageStats &stats)
{
if (_scanItr->valid()) {
DocumentMetaData document = getNextDocument(stats, false);
if (document.valid()) {
Bucket metaBucket(document::Bucket(_bucketSpace, document.bucketId));
IDestructorCallback::SP context = getLimiter().beginOperation();
auto bucketTask = makeBucketTask([this, meta=document, opsTracker=std::move(context)]
(const Bucket & bucket, std::shared_ptr<IDestructorCallback> onDone) {
assert(bucket.getBucketId() == meta.bucketId);
using DoneContext = vespalib::KeepAlive<std::pair<IDestructorCallback::SP, IDestructorCallback::SP>>;
moveDocument(meta, std::make_shared<DoneContext>(std::make_pair(std::move(opsTracker), std::move(onDone))));
}, [this](const Bucket &) { failOperation(); });
_startedCount.fetch_add(1, std::memory_order_relaxed);
_bucketExecutor.execute(metaBucket, std::move(bucketTask));
if (isBlocked(BlockedReason::OUTSTANDING_OPS)) {
return true;
}
}
}
return false;
}
void
CompactionJob::moveDocument(const search::DocumentMetaData & metaThen, std::shared_ptr<IDestructorCallback> context) {
IncOnDestruct countGuard(_executedCount);
if (_stopped.load(std::memory_order_relaxed)) return;
// The real lid must be sampled in the master thread.
//TODO remove target lid from createMoveOperation interface
auto op = _handler->createMoveOperation(metaThen, 0);
if (!op || !op->getDocument()) return;
// Early detection and force md5 calculation outside of master thread
if (metaThen.gid != op->getDocument()->getId().getGlobalId()) return;
_master.execute(makeLambdaTask([this, meta=metaThen, moveOp=std::move(op), onDone=std::move(context)]() mutable {
if (_stopped.load(std::memory_order_relaxed)) return;
completeMove(meta, std::move(moveOp), std::move(onDone));
}));
}
void
CompactionJob::completeMove(const search::DocumentMetaData & metaThen, std::unique_ptr<MoveOperation> moveOp,
std::shared_ptr<IDestructorCallback> onDone)
{
// Reread meta data as document might have been altered after move was initiated
// If so it will fail the timestamp sanity check later on.
search::DocumentMetaData metaNow = _handler->getMetaData(metaThen.lid);
// This should be impossible and should probably be an assert
if ( ! isSameDocument(metaThen, metaNow)) return;
if (metaNow.gid != moveOp->getDocument()->getId().getGlobalId()) return;
uint32_t lowestLid = _handler->getLidStatus().getLowestFreeLid();
if (lowestLid >= metaNow.lid) return;
moveOp->setTargetLid(lowestLid);
_opStorer.appendOperation(*moveOp, onDone);
_handler->handleMove(*moveOp, std::move(onDone));
}
CompactionJob::CompactionJob(const DocumentDBLidSpaceCompactionConfig &config,
std::shared_ptr<ILidSpaceCompactionHandler> handler,
IOperationStorer &opStorer,
IThreadService & master,
BucketExecutor & bucketExecutor,
IDiskMemUsageNotifier &diskMemUsageNotifier,
const BlockableMaintenanceJobConfig &blockableConfig,
IClusterStateChangedNotifier &clusterStateChangedNotifier,
bool nodeRetired,
document::BucketSpace bucketSpace)
: LidSpaceCompactionJobBase(config, std::move(handler), opStorer, diskMemUsageNotifier,
blockableConfig, clusterStateChangedNotifier, nodeRetired),
_master(master),
_bucketExecutor(bucketExecutor),
_bucketSpace(bucketSpace),
_stopped(false),
_startedCount(0),
_executedCount(0)
{ }
CompactionJob::~CompactionJob() = default;
bool
CompactionJob::inSync() const {
return _executedCount == _startedCount;
}
void
CompactionJob::onStop() {
_stopped = true;
while ( ! inSync() ) {
std::this_thread::sleep_for(1ms);
}
}
} // namespace proton
<|endoftext|>
|
<commit_before>//! Copyright (c) 2013 ASMlover. 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 ofconditions 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 materialsprovided with the
//! distribution.
//!
//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//! "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//! LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//! FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//! COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//! INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//! BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//! LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//! CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//! ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//! POSSIBILITY OF SUCH DAMAGE.
#include "select_ev.h"
#include "thread.h"
#include "address.h"
#include "socket.h"
#include "connector_mgr.h"
#include "listener.h"
Listener::Listener(void)
: running_(false)
, listener_(NULL)
, thread_(NULL)
, conn_mgr_(NULL)
{
}
Listener::~Listener(void)
{
}
bool
Listener::Start(const char* ip, unsigned short port)
{
listener_ = new Socket();
if (NULL == listener_)
return false;
listener_->Open();
listener_->SetReuseAddr();
listener_->Bind(ip, port);
listener_->Listen();
do {
conn_mgr_ = new ConnectorMgr();
if (NULL == conn_mgr_)
break;
thread_ = new Thread();
if (NULL == thread_)
break;
running_ = true;
thread_->Start(&Listener::Routine, this);
return true;
} while (0);
Stop();
return false;
}
void
Listener::Stop(void)
{
running_ = false;
if (NULL != thread_) {
thread_->Stop();
delete thread_;
thread_ = NULL;
}
if (NULL != conn_mgr_) {
conn_mgr_->CloseAll();
delete conn_mgr_;
conn_mgr_ = NULL;
}
if (NULL != listener_) {
listener_->Close();
delete listener_;
listener_ = NULL;
}
}
void
Listener::Routine(void* argument)
{
Listener* self = static_cast<Listener*>(argument);
if (NULL == self)
return;
Socket s;
Address addr;
while (self->running_) {
if (!self->listener_->Accept(&s, &addr)) {
Sleep(1);
continue;
}
else {
}
}
}
<commit_msg>improved listener module<commit_after>//! Copyright (c) 2013 ASMlover. 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 ofconditions 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 materialsprovided with the
//! distribution.
//!
//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//! "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//! LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//! FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//! COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//! INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//! BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//! LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//! CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//! ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//! POSSIBILITY OF SUCH DAMAGE.
#include "select_ev.h"
#include "thread.h"
#include "address.h"
#include "socket.h"
#include "connector_mgr.h"
#include "listener.h"
Listener::Listener(void)
: running_(false)
, listener_(NULL)
, thread_(NULL)
, conn_mgr_(NULL)
{
}
Listener::~Listener(void)
{
}
bool
Listener::Start(const char* ip, unsigned short port)
{
listener_ = new Socket();
if (NULL == listener_)
return false;
listener_->Open();
listener_->SetReuseAddr();
listener_->Bind(ip, port);
listener_->Listen();
do {
conn_mgr_ = new ConnectorMgr();
if (NULL == conn_mgr_)
break;
thread_ = new Thread();
if (NULL == thread_)
break;
running_ = true;
thread_->Start(&Listener::Routine, this);
return true;
} while (0);
Stop();
return false;
}
void
Listener::Stop(void)
{
running_ = false;
if (NULL != thread_) {
thread_->Stop();
delete thread_;
thread_ = NULL;
}
if (NULL != conn_mgr_) {
conn_mgr_->CloseAll();
delete conn_mgr_;
conn_mgr_ = NULL;
}
if (NULL != listener_) {
listener_->Close();
delete listener_;
listener_ = NULL;
}
}
void
Listener::Routine(void* argument)
{
Listener* self = static_cast<Listener*>(argument);
if (NULL == self || NULL == self->conn_mgr_)
return;
Socket s;
Address addr;
while (self->running_) {
if (!self->listener_->Accept(&s, &addr)) {
Sleep(1);
continue;
}
else {
int fd = s.fd();
int worker_id = self->conn_mgr_->SuitableWorker();
Connector* conn = self->conn_mgr_->Insert(fd, worker_id);
if (NULL != conn) {
//! TODO:
//! add event
}
else {
s.Close();
}
s.Detach();
addr.Detach();
}
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2011-2015, Intel Corporation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "AlsaCtlPortConfig.hpp"
#include "MappingContext.h"
#include "AlsaMappingKeys.hpp"
#include <string.h>
#include <string>
#include <assert.h>
#include <sstream>
#include <limits>
using std::string;
#define base AlsaSubsystemObject
AlsaCtlPortConfig::AlsaCtlPortConfig(const string &mappingValue,
CInstanceConfigurableElement *instanceConfigurableElement,
const CMappingContext &context,
core::log::Logger& logger,
const PortConfig &defaultPortConfig)
: base(mappingValue,
instanceConfigurableElement,
context,
logger),
_device(context.getItemAsInteger(AlsaCtlDevice)),
_portConfig(defaultPortConfig)
{
}
bool AlsaCtlPortConfig::receiveFromHW(string &error)
{
blackboardWrite(&_portConfig, sizeof(_portConfig));
return true;
}
bool AlsaCtlPortConfig::sendToHW(string &error)
{
PortConfig portConfig;
blackboardRead(&portConfig, sizeof(portConfig));
// If device update is needed, close all the stream
if (isDeviceUpdateNeeded(portConfig)) {
// Close playback and capture
closeStream(Playback);
closeStream(Capture);
// Save new configuration
_portConfig.channelNumber = portConfig.channelNumber;
_portConfig.format = portConfig.format;
_portConfig.sampleRate = portConfig.sampleRate;
} else {
// Close playback/capture streams if asked for
if (!portConfig.isStreamEnabled[Playback]) {
closeStream(Playback);
}
if (!portConfig.isStreamEnabled[Capture]) {
closeStream(Capture);
}
}
// Open and configure required streams
if (portConfig.isStreamEnabled[Playback]) {
if (!openStream(Playback, error)) {
return false;
}
}
if (portConfig.isStreamEnabled[Capture]) {
if (!openStream(Capture, error)) {
return false;
}
}
// Check port configuration has been considered
assert(!memcmp(&_portConfig, &portConfig, sizeof(_portConfig)));
return true;
}
bool AlsaCtlPortConfig::openStream(StreamDirection streamDirection, string &error)
{
// Stream needs to be opened only if it was closed previously
if (!_portConfig.isStreamEnabled[streamDirection]) {
if (!doOpenStream(streamDirection, error)) {
return false;
}
// Stream has to be opened
_portConfig.isStreamEnabled[streamDirection] = true;
}
return true;
}
void AlsaCtlPortConfig::closeStream(StreamDirection streamDirection)
{
// Stream needs to be closed only if it was opened previously
if (_portConfig.isStreamEnabled[streamDirection]) {
// Stream has to be closed
doCloseStream(streamDirection);
_portConfig.isStreamEnabled[streamDirection] = false;
}
}
string AlsaCtlPortConfig::formatAlsaError(StreamDirection streamDirection,
const string &functionName,
const string &error)
{
std::ostringstream stringStream;
stringStream << (streamDirection ? "Capture" : "Playback") << " " <<
functionName << " error: " << error;
return stringStream.str();
}
bool AlsaCtlPortConfig::isStreamEnabled(StreamDirection streamDirection) const
{
return _portConfig.isStreamEnabled[streamDirection] != 0;
}
bool AlsaCtlPortConfig::isDeviceUpdateNeeded(const PortConfig &portConfig) const
{
return (_portConfig.channelNumber != portConfig.channelNumber) ||
(_portConfig.format != portConfig.format) ||
(_portConfig.sampleRate != portConfig.sampleRate);
}
<commit_msg>Fix compilation error when using CLANG<commit_after>/*
* Copyright (c) 2011-2015, Intel Corporation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "AlsaCtlPortConfig.hpp"
#include "MappingContext.h"
#include "AlsaMappingKeys.hpp"
#include <string.h>
#include <string>
#include <assert.h>
#include <sstream>
#include <limits>
using std::string;
#define base AlsaSubsystemObject
AlsaCtlPortConfig::AlsaCtlPortConfig(const string &mappingValue,
CInstanceConfigurableElement *instanceConfigurableElement,
const CMappingContext &context,
core::log::Logger& logger,
const PortConfig &defaultPortConfig)
: base(mappingValue,
instanceConfigurableElement,
context,
logger),
_device(context.getItemAsInteger(AlsaCtlDevice)),
_portConfig(defaultPortConfig)
{
}
bool AlsaCtlPortConfig::receiveFromHW(string &/*error*/)
{
blackboardWrite(&_portConfig, sizeof(_portConfig));
return true;
}
bool AlsaCtlPortConfig::sendToHW(string &error)
{
PortConfig portConfig;
blackboardRead(&portConfig, sizeof(portConfig));
// If device update is needed, close all the stream
if (isDeviceUpdateNeeded(portConfig)) {
// Close playback and capture
closeStream(Playback);
closeStream(Capture);
// Save new configuration
_portConfig.channelNumber = portConfig.channelNumber;
_portConfig.format = portConfig.format;
_portConfig.sampleRate = portConfig.sampleRate;
} else {
// Close playback/capture streams if asked for
if (!portConfig.isStreamEnabled[Playback]) {
closeStream(Playback);
}
if (!portConfig.isStreamEnabled[Capture]) {
closeStream(Capture);
}
}
// Open and configure required streams
if (portConfig.isStreamEnabled[Playback]) {
if (!openStream(Playback, error)) {
return false;
}
}
if (portConfig.isStreamEnabled[Capture]) {
if (!openStream(Capture, error)) {
return false;
}
}
// Check port configuration has been considered
assert(!memcmp(&_portConfig, &portConfig, sizeof(_portConfig)));
return true;
}
bool AlsaCtlPortConfig::openStream(StreamDirection streamDirection, string &error)
{
// Stream needs to be opened only if it was closed previously
if (!_portConfig.isStreamEnabled[streamDirection]) {
if (!doOpenStream(streamDirection, error)) {
return false;
}
// Stream has to be opened
_portConfig.isStreamEnabled[streamDirection] = true;
}
return true;
}
void AlsaCtlPortConfig::closeStream(StreamDirection streamDirection)
{
// Stream needs to be closed only if it was opened previously
if (_portConfig.isStreamEnabled[streamDirection]) {
// Stream has to be closed
doCloseStream(streamDirection);
_portConfig.isStreamEnabled[streamDirection] = false;
}
}
string AlsaCtlPortConfig::formatAlsaError(StreamDirection streamDirection,
const string &functionName,
const string &error)
{
std::ostringstream stringStream;
stringStream << (streamDirection ? "Capture" : "Playback") << " " <<
functionName << " error: " << error;
return stringStream.str();
}
bool AlsaCtlPortConfig::isStreamEnabled(StreamDirection streamDirection) const
{
return _portConfig.isStreamEnabled[streamDirection] != 0;
}
bool AlsaCtlPortConfig::isDeviceUpdateNeeded(const PortConfig &portConfig) const
{
return (_portConfig.channelNumber != portConfig.channelNumber) ||
(_portConfig.format != portConfig.format) ||
(_portConfig.sampleRate != portConfig.sampleRate);
}
<|endoftext|>
|
<commit_before>#pragma once
#include "singleton.hpp"
#include "restag.hpp"
#include "optional.hpp"
#include <unordered_map>
namespace spi {
//! 名前付きリソースマネージャ
/*!
中身の保持はすべてスマートポインタで行う
シングルスレッド動作
*/
template <
class T,
class K = std::string,
class Allocator = std::allocator<T>
>
class ResMgrName {
public:
using value_t = T;
using shared_t = std::shared_ptr<value_t>;
using key_t = K;
private:
using this_t = ResMgrName<T,K>;
using tag_t = ResTag<value_t>;
using Map = std::unordered_map<key_t, tag_t>;
using Val2Key = std::unordered_map<const value_t*, key_t>;
struct Resource {
Map map;
Val2Key v2k;
};
using Resource_SP = std::shared_ptr<Resource>;
template <bool B>
class _iterator : public Map::iterator {
public:
using base_t = typename Map::iterator;
using base_t::base_t;
using v_t = std::conditional_t<B, const value_t, value_t>;
using s_t = std::shared_ptr<v_t>;
s_t operator *() const {
return base_t::operator*().second.weak.lock();
}
s_t operator ->() const {
return base_t::operator*().second.weak.lock();
}
};
using iterator = _iterator<false>;
using const_iterator = _iterator<true>;
Resource_SP _resource;
template <class T2>
static void _Release(const Resource_SP& r, T2* p) noexcept {
auto& m = r->map;
auto& v2k = r->v2k;
typename Allocator::template rebind<T2>::other alc;
const auto itr = v2k.find(p);
try {
Assert0(itr != v2k.end());
const auto itr2 = m.find(itr->second);
Assert0(itr2 != m.end());
v2k.erase(itr);
m.erase(itr2);
alc.destroy(p);
alc.deallocate(p, 1);
} catch(...) {}
}
const static key_t s_anonymousPrefix;
// 無名リソースを作成する際の通し番号
uint64_t _acounter;
key_t _makeAKey() {
key_t key(s_anonymousPrefix);
key += std::to_string(_acounter++);
return key;
}
template <class Ar, class T2, class K2>
friend void save(Ar&, const ResMgrName<T2,K2>&);
template <class Ar, class T2, class K2>
friend void load(Ar&, ResMgrName<T2,K2>&);
static bool _HasAnonymousPrefix(const key_t& s) {
if(s.length() >= s_anonymousPrefix.length()) {
auto itr0 = s.cbegin(),
itr1 = s_anonymousPrefix.cbegin();
do {
if(*itr0 != *itr1)
return false;
++itr0;
++itr1;
} while(itr1 != s_anonymousPrefix.cend());
return true;
}
return false;
}
template <class T2>
auto _getDeleter() {
return [r=_resource](T2 *const p){ _Release(r, p); };
}
protected:
//! 継承先のクラスでキーの改変をする必要があればこれをオーバーライドする
virtual void _modifyResourceName(key_t& /*key*/) const {}
public:
ResMgrName():
_resource(std::make_shared<Resource>()),
_acounter(0)
{}
iterator begin() noexcept { return _resource->map.begin(); }
iterator end() noexcept { return _resource->map.end(); }
const_iterator begin() const noexcept { return _resource->map.begin(); }
const_iterator cbegin() const noexcept { return _resource->map.cbegin(); }
const_iterator end() const noexcept { return _resource->map.end(); }
const_iterator cend() const noexcept { return _resource->map.cend(); }
// (主にデバッグ用)
bool operator == (const ResMgrName& m) const noexcept {
auto &m0 = _resource->map,
&m1 = m._resource->map;
if(m0.size() == m1.size()) {
auto itr0 = m0.begin(),
itr1 = m1.begin();
while(itr0 != m0.end()) {
if(*itr0 != *itr1)
return false;
++itr0;
++itr1;
}
return _acounter == m._acounter;
}
return false;
}
bool operator != (const ResMgrName& m) const noexcept {
return !(this->operator == (m));
}
template <class T2>
struct Constructor {
using Alc = typename Allocator::template rebind<T2>::other;
Alc alc;
T2* pointer;
Constructor():
pointer(alc.allocate(1))
{}
template <class... Ts>
void operator()(Ts&&... ts) {
alc.construct(pointer, std::forward<Ts>(ts)...);
}
};
// ---- 名前付きリソース作成 ----
template <class T2, class Make>
auto acquireWithMake(const key_t& k, Make&& make) {
key_t tk(k);
if(!_HasAnonymousPrefix(tk))
_modifyResourceName(tk);
// 既に同じ名前でリソースを確保済みならばそれを返す
if(auto ret = get(tk))
return std::make_pair(std::static_pointer_cast<T2>(ret), false);
// 新しくリソースを作成
Constructor<T2> ctor;
make(tk, ctor);
auto& res = *_resource;
std::shared_ptr<T2> sp(
ctor.pointer,
_getDeleter<T2>()
);
res.map.emplace(tk, sp);
res.v2k.emplace(sp.get(), tk);
return std::make_pair(sp, true);
}
template <class T2, class... Ts>
auto emplaceWithType(const key_t& k, Ts&&... ts) {
return acquireWithMake<T2>(k, [&ts...](auto& /*key*/, auto&& mk){
mk(std::forward<Ts>(ts)...);
});
}
template <class... Ts>
auto emplace(const key_t& k, Ts&&... ts) {
return emplaceWithType<value_t>(k, std::forward<Ts>(ts)...);
}
// ---- 無名リソース作成 ----
template <class P, class... Ts>
auto acquireA(Ts&&... ts) {
for(;;) {
// 適当にリソース名を生成して、ダブりがなければOK
const auto key = _makeAKey();
auto ret = acquireWithMake<P>(key,
[&ts...](auto& /*key*/, auto&& mk){
mk(std::forward<Ts>(ts)...);
});
if(ret.second)
return ret.first;
}
}
template <class T2, class... Ts>
auto emplaceA_WithType(Ts&&... ts) {
return acquireA<T2>(std::forward<Ts>(ts)...);
}
template <class... Ts>
auto emplaceA(Ts&&... ts) {
return emplaceA_WithType<value_t>(std::forward<Ts>(ts)...);
}
Optional<const key_t&> getKey(const shared_t& p) const {
return getKey(p.get());
}
Optional<const key_t&> getKey(const value_t* p) const {
auto& v2k = _resource->v2k;
const auto itr = v2k.find(p);
if(itr != v2k.end())
return itr->second;
return none;
}
shared_t get(const key_t& k) {
key_t tk(k);
auto& map = _resource->map;
const auto itr = map.find(tk);
if(itr != map.end()) {
shared_t ret(itr->second.weak.lock());
D_Assert0(ret);
return ret;
}
return nullptr;
}
std::size_t size() const noexcept {
return _resource->map.size();
}
};
template <class T, class K, class A>
const typename ResMgrName<T,K,A>::key_t ResMgrName<T,K,A>::s_anonymousPrefix("__anonymous__");
}
<commit_msg>ResMgrName: 名前付きリソースの置き換え<commit_after>#pragma once
#include "singleton.hpp"
#include "restag.hpp"
#include "optional.hpp"
#include <unordered_map>
namespace spi {
//! 名前付きリソースマネージャ
/*!
中身の保持はすべてスマートポインタで行う
シングルスレッド動作
*/
template <
class T,
class K = std::string,
class Allocator = std::allocator<T>
>
class ResMgrName {
public:
using value_t = T;
using shared_t = std::shared_ptr<value_t>;
using key_t = K;
private:
using this_t = ResMgrName<T,K>;
using tag_t = ResTag<value_t>;
using Map = std::unordered_map<key_t, tag_t>;
using Val2Key = std::unordered_map<const value_t*, key_t>;
struct Resource {
Map map;
Val2Key v2k;
};
using Resource_SP = std::shared_ptr<Resource>;
template <bool B>
class _iterator : public Map::iterator {
public:
using base_t = typename Map::iterator;
using base_t::base_t;
using v_t = std::conditional_t<B, const value_t, value_t>;
using s_t = std::shared_ptr<v_t>;
s_t operator *() const {
return base_t::operator*().second.weak.lock();
}
s_t operator ->() const {
return base_t::operator*().second.weak.lock();
}
};
using iterator = _iterator<false>;
using const_iterator = _iterator<true>;
Resource_SP _resource;
template <class T2>
static void _Release(const Resource_SP& r, T2* p) noexcept {
auto& m = r->map;
auto& v2k = r->v2k;
typename Allocator::template rebind<T2>::other alc;
const auto itr = v2k.find(p);
try {
Assert0(itr != v2k.end());
const auto itr2 = m.find(itr->second);
Assert0(itr2 != m.end());
v2k.erase(itr);
m.erase(itr2);
alc.destroy(p);
alc.deallocate(p, 1);
} catch(...) {}
}
const static key_t s_anonymousPrefix;
// 無名リソースを作成する際の通し番号
uint64_t _acounter;
key_t _makeAKey() {
// 適当にリソース名を生成して、ダブりがなければOK
for(;;) {
key_t key(s_anonymousPrefix);
key += std::to_string(_acounter++);
if(_resource->map.count(key) == 0)
return key;
}
}
template <class Ar, class T2, class K2>
friend void save(Ar&, const ResMgrName<T2,K2>&);
template <class Ar, class T2, class K2>
friend void load(Ar&, ResMgrName<T2,K2>&);
key_t _convertKey(const key_t& s) {
key_t tk(s);
if(!_HasAnonymousPrefix(tk))
_modifyResourceName(tk);
return tk;
}
static bool _HasAnonymousPrefix(const key_t& s) {
if(s.size() >= s_anonymousPrefix.size()) {
auto itr0 = s.cbegin(),
itr1 = s_anonymousPrefix.cbegin();
do {
if(*itr0 != *itr1)
return false;
++itr0;
++itr1;
} while(itr1 != s_anonymousPrefix.cend());
return true;
}
return false;
}
template <class T2>
auto _getDeleter() {
return [r=_resource](T2 *const p){ _Release(r, p); };
}
//! key->resource の関連付けを解除
tag_t _eraseKey2Tag(const key_t& k_from) {
auto& m = _resource->map;
const auto itr = m.find(k_from);
D_Assert0(itr != m.end());
tag_t tag = itr->second;
m.erase(itr);
return tag;
}
//! resource -> key の関連付けを解除
void _eraseV2K(const value_t* ptr) {
auto& v2k = _resource->v2k;
const auto itr = v2k.find(ptr);
D_Assert0(itr != v2k.end());
v2k.erase(itr);
}
//! あるキーに関連付けられているリソースを別の名前と関連付けしなおす
void _renameEntry(const key_t& k_from, const key_t& k_to) {
tag_t tag = _eraseKey2Tag(k_from);
_eraseV2K(tag.ptr);
_resource->map.emplace(k_to, tag);
_resource->v2k.emplace(tag.ptr, k_to);
}
template <class T2, class Make>
auto _addEntry(const key_t& k, const Make& make) {
// 新しくリソースを作成
Constructor<T2> ctor;
make(k, ctor);
std::shared_ptr<T2> sp(
ctor.pointer,
_getDeleter<T2>()
);
auto& res = *_resource;
res.map.emplace(k, sp);
res.v2k.emplace(sp.get(), k);
return sp;
}
protected:
//! 継承先のクラスでキーの改変をする必要があればこれをオーバーライドする
virtual void _modifyResourceName(key_t& /*key*/) const {}
public:
ResMgrName():
_resource(std::make_shared<Resource>()),
_acounter(0)
{}
iterator begin() noexcept { return _resource->map.begin(); }
iterator end() noexcept { return _resource->map.end(); }
const_iterator begin() const noexcept { return _resource->map.begin(); }
const_iterator cbegin() const noexcept { return _resource->map.cbegin(); }
const_iterator end() const noexcept { return _resource->map.end(); }
const_iterator cend() const noexcept { return _resource->map.cend(); }
// (主にデバッグ用)
bool operator == (const ResMgrName& m) const noexcept {
auto &m0 = _resource->map,
&m1 = m._resource->map;
if(m0.size() == m1.size()) {
auto itr0 = m0.begin(),
itr1 = m1.begin();
while(itr0 != m0.end()) {
if(*itr0 != *itr1)
return false;
++itr0;
++itr1;
}
return _acounter == m._acounter;
}
return false;
}
bool operator != (const ResMgrName& m) const noexcept {
return !(this->operator == (m));
}
template <class T2>
struct Constructor {
using Alc = typename Allocator::template rebind<T2>::other;
Alc alc;
T2* pointer;
Constructor():
pointer(alc.allocate(1))
{}
template <class... Ts>
void operator()(Ts&&... ts) {
alc.construct(pointer, std::forward<Ts>(ts)...);
}
};
// ---- 名前付きリソース作成 ----
template <class T2, class Make>
auto acquireWithMake(const key_t& k, Make&& make) {
const key_t tk = _convertKey(k);
// 既に同じ名前でリソースを確保済みならばそれを返す
if(auto ret = get(tk))
return std::make_pair(std::static_pointer_cast<T2>(ret), false);
return std::make_pair(_addEntry<T2>(tk, make), true);
}
//! 型を指定してのリソース確保
template <class T2, class... Ts>
auto emplaceWithType(const key_t& k, Ts&&... ts) {
return acquireWithMake<T2>(k, [&ts...](auto& /*key*/, auto&& mk){
mk(std::forward<Ts>(ts)...);
});
}
template <class... Ts>
auto emplace(const key_t& k, Ts&&... ts) {
return emplaceWithType<value_t>(k, std::forward<Ts>(ts)...);
}
bool setAnonymous(const key_t& k, key_t* oldKey=nullptr) {
auto& m = _resource->map;
const auto itr = m.find(k);
if(itr != m.end()) {
const auto nk = _makeAKey();
if(oldKey)
*oldKey = nk;
_renameEntry(k, nk);
return true;
}
return false;
}
/*!
\param[in] oldKey 有効なポインタを指定すれば上書きされたリソースの新しいキー名がセットされる
\return std::pair(first=置き換えられた後のリソースハンドル, second=古いリソースが置き換えられたかのフラグ)
*/
template <class T2, class Make>
auto replaceWithMake(const key_t& k, const Make& make, key_t* oldKey=nullptr) {
const key_t tk = _convertKey(k);
// 既に同じ名前でリソースを確保済みならばキーを無名リソースキーに書き換え
const bool hasOld = setAnonymous(tk, oldKey);
return std::make_pair(_addEntry<T2>(tk, make), hasOld);
}
template <class T2, class... Ts>
auto replaceEmplaceWithType(const key_t& k, key_t* oldKey, Ts&&... ts) {
return replaceWithMake<T2>(k, [&ts...](auto& /*key*/, auto&& mk){
mk(std::forward<Ts>(ts)...);
}, oldKey);
}
template <class... Ts>
auto replaceEmplace(const key_t& k, key_t* oldKey, Ts&&... ts) {
return replaceEmplaceWithType<value_t>(k, oldKey, std::forward<Ts>(ts)...);
}
// ---- 無名リソース作成 ----
template <class P, class... Ts>
auto acquireA(Ts&&... ts) {
const auto key = _makeAKey();
auto ret = acquireWithMake<P>(key,
[&ts...](auto& /*key*/, auto&& mk){
mk(std::forward<Ts>(ts)...);
});
D_Assert0(ret.second);
return ret.first;
}
//! データ型を指定しての無名リソース確保
template <class T2, class... Ts>
auto emplaceA_WithType(Ts&&... ts) {
return acquireA<T2>(std::forward<Ts>(ts)...);
}
//! 無名リソース確保(データ型 = value_t>
template <class... Ts>
auto emplaceA(Ts&&... ts) {
return emplaceA_WithType<value_t>(std::forward<Ts>(ts)...);
}
//! リソースに対応するキーを取得(from shared_ptr)
Optional<const key_t&> getKey(const shared_t& p) const {
return getKey(p.get());
}
//! リソースに対応するキーを取得(from pointer)
/*! 管轄外のリソースや不正なポインタを入力した場合、noneが返る */
Optional<const key_t&> getKey(const value_t* p) const {
auto& v2k = _resource->v2k;
const auto itr = v2k.find(p);
if(itr != v2k.end())
return itr->second;
return none;
}
//! キーに対応するリソースを取り出す(ない場合はnullptrを返す)
shared_t get(const key_t& k) {
const key_t tk = _convertKey(k);
auto& map = _resource->map;
const auto itr = map.find(tk);
if(itr != map.end()) {
shared_t ret(itr->second.weak.lock());
D_Assert0(ret);
return ret;
}
return nullptr;
}
//! 確保されたリソース数
std::size_t size() const noexcept {
return _resource->map.size();
}
};
template <class T>
const char* GetAnonymousPrefix(T*) { return u8"__anonymous__"; }
inline const char16_t* GetAnonymousPrefix(std::u16string*) { return u"__anonymous__"; }
inline const char32_t* GetAnonymousPrefix(std::u32string*) { return U"__anonymous__"; }
template <class T, class K, class A>
const typename ResMgrName<T,K,A>::key_t ResMgrName<T,K,A>::s_anonymousPrefix(GetAnonymousPrefix((K*)nullptr));
}
<|endoftext|>
|
<commit_before>/*!
* Copyright (c) 2018 by Contributors
* \file alter_op_layout.cc
* \brief Alter the operator layouts. Keep inferred layouts (if any) from previous stages.
* e.g., convolution may calculates faster with NCHW16c layout.
*/
#include <nnvm/pass.h>
#include <nnvm/op_attr_types.h>
#include <nnvm/layout.h>
#include <nnvm/compiler/op_attr_types.h>
#include <nnvm/pass_functions.h>
#include <tvm/tvm.h>
#include <algorithm>
#include <functional>
#include "./compile_engine.h"
#include "./graph_transform.h"
namespace nnvm {
namespace compiler {
namespace {
tvm::Array<tvm::Tensor> GetTensorInfo(const IndexedGraph& idx_graph,
const uint32_t nid,
const ShapeVector& shape_vec,
const DTypeVector& dtype_vec) {
tvm::Array<tvm::Tensor> vec;
for (uint32_t i = 0; i < idx_graph[nid].source->num_outputs(); ++i) {
tvm::Array<tvm::Expr> shape;
for (int64_t x : shape_vec[idx_graph.entry_id(nid, i)]) {
CHECK_LE(x, static_cast<int64_t>(std::numeric_limits<int>::max()));
shape.push_back(tvm::make_const(tvm::Int(32), x));
}
vec.push_back(tvm::placeholder(
shape, GetTVMType(dtype_vec[idx_graph.entry_id(nid, i)])));
}
return vec;
}
Graph AlterOpLayout(const Graph& src) {
static auto& falter_op_layout =
Op::GetAttr<nnvm::compiler::FTVMAlterOpLayout >("FTVMAlterOpLayout");
const ShapeVector& shape_vec = src.GetAttr<ShapeVector>("shape");
const DTypeVector& dtype_vec = src.GetAttr<DTypeVector>("dtype");
const IndexedGraph& idx_graph = src.indexed_graph();
std::vector<std::vector<Layout> > in_layouts_of_node(idx_graph.num_nodes());
std::vector<std::vector<Layout> > out_layouts_of_node(idx_graph.num_nodes());
std::unordered_map<const Node*, uint32_t> new_nodes;
if (src.HasAttr("layout")) {
// record layouts so that LayoutTransform pass can fix layouts correctly,
// e.g., conv2d can be replaced by some contrib implement
// whose layout is different from the original one
// (which was imported from a model file).
const auto& layouts = src.GetAttr<std::vector<Layout> >("layout");
for (uint32_t nid = 0; nid < idx_graph.num_nodes(); ++nid) {
const auto &inode = idx_graph[nid];
if (falter_op_layout.count(inode.source->op())) {
// do not record input layouts of nodes that will be replaced.
continue;
}
std::vector<Layout> in_layout;
for (const auto& e : inode.inputs) {
in_layout.emplace_back(layouts[idx_graph.entry_id(e)]);
}
in_layouts_of_node[nid] = in_layout;
std::vector<Layout> out_layout;
for (uint i = 0; i < inode.source->num_outputs(); ++i) {
out_layout.emplace_back(layouts[idx_graph.entry_id(nid, i)]);
}
out_layouts_of_node[nid] = out_layout;
}
}
auto transform = [&](uint32_t nid,
const NodePtr& n,
std::vector<NodeEntry>* ret) {
nnvm::compiler::FTVMAlterOpLayout fn_alter_op_layout =
falter_op_layout.get(n->op(), nullptr);
if (fn_alter_op_layout == nullptr) {
new_nodes[n.get()] = nid;
return false;
}
// construct parameters for registered function
std::vector<Symbol> op_inputs;
tvm::Array<tvm::Tensor> tensor_infos;
CHECK_EQ(n->num_inputs(), idx_graph[nid].inputs.size());
for (uint32_t i = 0; i < n->num_inputs(); ++i) {
const nnvm::NodeEntry& input = n->inputs[i];
// input operator
Symbol op_input;
op_input.outputs.push_back(input);
op_inputs.push_back(op_input);
// input tinfo, extract from the original graph
// because it was where infer_shape & infer_type applied.
tvm::Array<tvm::Tensor> op_output_tinfos =
GetTensorInfo(idx_graph, idx_graph[nid].inputs[i].node_id,
shape_vec, dtype_vec);
tensor_infos.push_back(op_output_tinfos[input.index]);
}
// callback registered function to get a new operator.
auto op = fn_alter_op_layout(n->attrs, Symbol::CreateGroup(op_inputs), tensor_infos);
*ret = op.outputs;
return true;
};
Graph ret = nnvm::compiler::GraphTransform(src, transform);
if (src.HasAttr("layout")) {
// restore the layouts to return graph
const auto& ret_idx = ret.indexed_graph();
std::vector<Layout> ret_layouts(ret_idx.num_node_entries(), Layout::Undef());
for (uint32_t nid = 0; nid < ret_idx.num_nodes(); ++nid) {
const auto& inode = ret_idx[nid];
if (new_nodes.count(inode.source)) {
const std::vector<Layout>& in_layouts =
in_layouts_of_node[new_nodes[inode.source]];
for (uint32_t i = 0; i < inode.inputs.size(); ++i) {
const auto& e = inode.inputs[i];
ret_layouts[ret_idx.entry_id(e)] = in_layouts[i];
}
const std::vector<Layout>& out_layouts =
out_layouts_of_node[new_nodes[inode.source]];
for (uint32_t i = 0; i < inode.source->num_outputs(); ++i) {
ret_layouts[ret_idx.entry_id(nid, i)] = out_layouts[i];
}
}
}
// cannot call indexed_graph() before return the origin Graph,
// thus create a new one.
nnvm::Graph new_ret;
new_ret.outputs = ret.outputs;
new_ret.attrs["layout"] = std::make_shared<any>(std::move(ret_layouts));
return new_ret;
}
return ret;
}
// register pass
NNVM_REGISTER_PASS(AlterOpLayout)
.set_body(AlterOpLayout)
.set_change_graph(true);
} // namespace
} // namespace compiler
} // namespace nnvm
<commit_msg>use uint32_t (#478)<commit_after>/*!
* Copyright (c) 2018 by Contributors
* \file alter_op_layout.cc
* \brief Alter the operator layouts. Keep inferred layouts (if any) from previous stages.
* e.g., convolution may calculates faster with NCHW16c layout.
*/
#include <nnvm/pass.h>
#include <nnvm/op_attr_types.h>
#include <nnvm/layout.h>
#include <nnvm/compiler/op_attr_types.h>
#include <nnvm/pass_functions.h>
#include <tvm/tvm.h>
#include <algorithm>
#include <functional>
#include "./compile_engine.h"
#include "./graph_transform.h"
namespace nnvm {
namespace compiler {
namespace {
tvm::Array<tvm::Tensor> GetTensorInfo(const IndexedGraph& idx_graph,
const uint32_t nid,
const ShapeVector& shape_vec,
const DTypeVector& dtype_vec) {
tvm::Array<tvm::Tensor> vec;
for (uint32_t i = 0; i < idx_graph[nid].source->num_outputs(); ++i) {
tvm::Array<tvm::Expr> shape;
for (int64_t x : shape_vec[idx_graph.entry_id(nid, i)]) {
CHECK_LE(x, static_cast<int64_t>(std::numeric_limits<int>::max()));
shape.push_back(tvm::make_const(tvm::Int(32), x));
}
vec.push_back(tvm::placeholder(
shape, GetTVMType(dtype_vec[idx_graph.entry_id(nid, i)])));
}
return vec;
}
Graph AlterOpLayout(const Graph& src) {
static auto& falter_op_layout =
Op::GetAttr<nnvm::compiler::FTVMAlterOpLayout >("FTVMAlterOpLayout");
const ShapeVector& shape_vec = src.GetAttr<ShapeVector>("shape");
const DTypeVector& dtype_vec = src.GetAttr<DTypeVector>("dtype");
const IndexedGraph& idx_graph = src.indexed_graph();
std::vector<std::vector<Layout> > in_layouts_of_node(idx_graph.num_nodes());
std::vector<std::vector<Layout> > out_layouts_of_node(idx_graph.num_nodes());
std::unordered_map<const Node*, uint32_t> new_nodes;
if (src.HasAttr("layout")) {
// record layouts so that LayoutTransform pass can fix layouts correctly,
// e.g., conv2d can be replaced by some contrib implement
// whose layout is different from the original one
// (which was imported from a model file).
const auto& layouts = src.GetAttr<std::vector<Layout> >("layout");
for (uint32_t nid = 0; nid < idx_graph.num_nodes(); ++nid) {
const auto &inode = idx_graph[nid];
if (falter_op_layout.count(inode.source->op())) {
// do not record input layouts of nodes that will be replaced.
continue;
}
std::vector<Layout> in_layout;
for (const auto& e : inode.inputs) {
in_layout.emplace_back(layouts[idx_graph.entry_id(e)]);
}
in_layouts_of_node[nid] = in_layout;
std::vector<Layout> out_layout;
for (uint32_t i = 0; i < inode.source->num_outputs(); ++i) {
out_layout.emplace_back(layouts[idx_graph.entry_id(nid, i)]);
}
out_layouts_of_node[nid] = out_layout;
}
}
auto transform = [&](uint32_t nid,
const NodePtr& n,
std::vector<NodeEntry>* ret) {
nnvm::compiler::FTVMAlterOpLayout fn_alter_op_layout =
falter_op_layout.get(n->op(), nullptr);
if (fn_alter_op_layout == nullptr) {
new_nodes[n.get()] = nid;
return false;
}
// construct parameters for registered function
std::vector<Symbol> op_inputs;
tvm::Array<tvm::Tensor> tensor_infos;
CHECK_EQ(n->num_inputs(), idx_graph[nid].inputs.size());
for (uint32_t i = 0; i < n->num_inputs(); ++i) {
const nnvm::NodeEntry& input = n->inputs[i];
// input operator
Symbol op_input;
op_input.outputs.push_back(input);
op_inputs.push_back(op_input);
// input tinfo, extract from the original graph
// because it was where infer_shape & infer_type applied.
tvm::Array<tvm::Tensor> op_output_tinfos =
GetTensorInfo(idx_graph, idx_graph[nid].inputs[i].node_id,
shape_vec, dtype_vec);
tensor_infos.push_back(op_output_tinfos[input.index]);
}
// callback registered function to get a new operator.
auto op = fn_alter_op_layout(n->attrs, Symbol::CreateGroup(op_inputs), tensor_infos);
*ret = op.outputs;
return true;
};
Graph ret = nnvm::compiler::GraphTransform(src, transform);
if (src.HasAttr("layout")) {
// restore the layouts to return graph
const auto& ret_idx = ret.indexed_graph();
std::vector<Layout> ret_layouts(ret_idx.num_node_entries(), Layout::Undef());
for (uint32_t nid = 0; nid < ret_idx.num_nodes(); ++nid) {
const auto& inode = ret_idx[nid];
if (new_nodes.count(inode.source)) {
const std::vector<Layout>& in_layouts =
in_layouts_of_node[new_nodes[inode.source]];
for (uint32_t i = 0; i < inode.inputs.size(); ++i) {
const auto& e = inode.inputs[i];
ret_layouts[ret_idx.entry_id(e)] = in_layouts[i];
}
const std::vector<Layout>& out_layouts =
out_layouts_of_node[new_nodes[inode.source]];
for (uint32_t i = 0; i < inode.source->num_outputs(); ++i) {
ret_layouts[ret_idx.entry_id(nid, i)] = out_layouts[i];
}
}
}
// cannot call indexed_graph() before return the origin Graph,
// thus create a new one.
nnvm::Graph new_ret;
new_ret.outputs = ret.outputs;
new_ret.attrs["layout"] = std::make_shared<any>(std::move(ret_layouts));
return new_ret;
}
return ret;
}
// register pass
NNVM_REGISTER_PASS(AlterOpLayout)
.set_body(AlterOpLayout)
.set_change_graph(true);
} // namespace
} // namespace compiler
} // namespace nnvm
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2007 Till Adam <adam@kde.org>
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 "maildirresource.h"
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtDBus/QDBusConnection>
#include <kdebug.h>
#include <kurl.h>
#include <kfiledialog.h>
#include <klocale.h>
#include <libakonadi/collectionlistjob.h>
#include <libakonadi/collectionmodifyjob.h>
#include <libakonadi/itemappendjob.h>
#include <libakonadi/itemfetchjob.h>
#include <libakonadi/itemstorejob.h>
#include <libakonadi/session.h>
#include <maildir/maildir.h>
#include <kmime/kmime_message.h>
#include <boost/shared_ptr.hpp>
typedef boost::shared_ptr<KMime::Message> MessagePtr;
using namespace Akonadi;
using KPIM::Maildir;
MaildirResource::MaildirResource( const QString &id )
:ResourceBase( id )
{
}
MaildirResource::~ MaildirResource()
{
}
bool MaildirResource::requestItemDelivery( const Akonadi::DataReference &ref, const QStringList &parts, const QDBusMessage &msg )
{
const QString rid = ref.remoteId();
const QString dir = rid.left( rid.lastIndexOf( QDir::separator() ) );
const QString entry = rid.mid( rid.lastIndexOf( QDir::separator() ) + 1 );
Maildir md( dir );
if ( !md.isValid() )
return false;
const QByteArray data = md.readEntry( entry );
KMime::Message *mail = new KMime::Message();
mail->setContent( data );
mail->parse();
Item item( ref );
item.setMimeType( "message/rfc822" );
item.setPayload( MessagePtr( mail ) );
ItemStoreJob *job = new ItemStoreJob( item, session() );
job->storePayload();
return deliverItem( job, msg );
}
void MaildirResource::aboutToQuit()
{
kDebug() << "Implement me: " << k_funcinfo << endl;
}
void MaildirResource::configure()
{
QString oldDir = settings()->value( "General/Path" ).toString();
KUrl url;
if ( !oldDir.isEmpty() )
url = KUrl::fromPath( oldDir );
else
url = KUrl::fromPath( QDir::homePath() );
QString newDir = KFileDialog::getExistingDirectory( url, 0, i18n("Select Mail Directory") );
if ( newDir.isEmpty() )
return;
if ( oldDir == newDir )
return;
settings()->setValue( "General/Path", newDir );
synchronize();
}
void MaildirResource::itemAdded( const Akonadi::Item & item, const Akonadi::Collection& collection )
{
Maildir dir( collection.remoteId() );
QString errMsg;
if ( !dir.isValid( errMsg ) ) {
error( errMsg );
return;
}
// we can only deal with mail
if ( item.mimeType() != "message/rfc822" ) {
error( i18n("Only email messages can be added to the Maildir resource!") );
return;
}
const MessagePtr mail = item.payload<MessagePtr>();
dir.addEntry( mail->encodedContent() );
}
void MaildirResource::itemChanged( const Akonadi::Item& item, const QStringList& parts )
{
if ( !parts.contains( Item::PartBody ) ) return;
const QString rid = item.reference().remoteId();
const QString path = rid.left( rid.lastIndexOf( QDir::separator() ) );
const QString entry = rid.mid( rid.lastIndexOf( QDir::separator() ) + 1 );
Maildir dir( path );
QString errMsg;
if ( !dir.isValid( errMsg ) ) {
error( errMsg );
return;
}
// we can only deal with mail
if ( item.mimeType() != "message/rfc822" ) {
error( i18n("Only email messages can be added to the Maildir resource!") );
return;
}
const MessagePtr mail = item.payload<MessagePtr>();
dir.writeEntry( entry, mail->encodedContent() );
}
void MaildirResource::itemRemoved(const Akonadi::DataReference & ref)
{
kDebug() << "Implement me: " << k_funcinfo << endl;
}
void MaildirResource::retrieveCollections()
{
Maildir dir( settings()->value( "General/Path" ).toString() );
QString errMsg;
if ( !dir.isValid( errMsg ) ) {
error( errMsg );
collectionsRetrieved( Collection::List() );
}
Collection root;
root.setParent( Collection::root() );
root.setRemoteId( settings()->value( "General/Path" ).toString() );
root.setName( name() );
QStringList mimeTypes;
mimeTypes << "message/rfc822" << Collection::collectionMimeType();
root.setContentTypes( mimeTypes );
root.setCachePolicyId( 1 ); // ### just for testing
Collection::List list;
list << root;
foreach ( const QString sub, dir.subFolderList() ) {
Collection c;
c.setRemoteId( sub );
c.setParent( root );
c.setContentTypes( mimeTypes );
list << c;
}
collectionsRetrieved( list );
}
void MaildirResource::synchronizeCollection(const Akonadi::Collection & col)
{
ItemFetchJob *fetch = new ItemFetchJob( col, session() );
if ( !fetch->exec() ) {
changeStatus( Error, i18n("Unable to fetch listing of collection '%1': %2", col.name(), fetch->errorString()) );
return;
}
Item::List items = fetch->items();
changeProgress( 0 );
Maildir md( col.remoteId() );
if ( !md.isValid() ) {
error( i18n("Invalid maildir" ) );
return;
}
QStringList entryList = md.entryList();
int counter = 0;
foreach ( const QString entry, entryList ) {
const QString rid = col.remoteId() + QDir::separator() + entry;
bool found = false;
foreach ( Item item, items ) {
if ( item.reference().remoteId() == rid ) {
found = true;
break;
}
}
if ( found )
continue;
Item item( DataReference( -1, rid ) );
item.setMimeType( "message/rfc822" );
ItemAppendJob *append = new ItemAppendJob( item, col, session() );
if ( !append->exec() ) {
changeProgress( 0 );
changeStatus( Error, i18n("Appending new message failed: %1", append->errorString()) );
return;
}
counter++;
int percentage = (counter * 100) / entryList.count();
changeProgress( percentage );
}
collectionSynchronized();
}
#include "maildirresource.moc"
<commit_msg>And finally implement removing entries in teh resource too.<commit_after>/*
Copyright (c) 2007 Till Adam <adam@kde.org>
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 "maildirresource.h"
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtDBus/QDBusConnection>
#include <kdebug.h>
#include <kurl.h>
#include <kfiledialog.h>
#include <klocale.h>
#include <libakonadi/collectionlistjob.h>
#include <libakonadi/collectionmodifyjob.h>
#include <libakonadi/itemappendjob.h>
#include <libakonadi/itemfetchjob.h>
#include <libakonadi/itemstorejob.h>
#include <libakonadi/session.h>
#include <maildir/maildir.h>
#include <kmime/kmime_message.h>
#include <boost/shared_ptr.hpp>
typedef boost::shared_ptr<KMime::Message> MessagePtr;
using namespace Akonadi;
using KPIM::Maildir;
MaildirResource::MaildirResource( const QString &id )
:ResourceBase( id )
{
}
MaildirResource::~ MaildirResource()
{
}
bool MaildirResource::requestItemDelivery( const Akonadi::DataReference &ref, const QStringList &parts, const QDBusMessage &msg )
{
const QString rid = ref.remoteId();
const QString dir = rid.left( rid.lastIndexOf( QDir::separator() ) );
const QString entry = rid.mid( rid.lastIndexOf( QDir::separator() ) + 1 );
Maildir md( dir );
if ( !md.isValid() )
return false;
const QByteArray data = md.readEntry( entry );
KMime::Message *mail = new KMime::Message();
mail->setContent( data );
mail->parse();
Item item( ref );
item.setMimeType( "message/rfc822" );
item.setPayload( MessagePtr( mail ) );
ItemStoreJob *job = new ItemStoreJob( item, session() );
job->storePayload();
return deliverItem( job, msg );
}
void MaildirResource::aboutToQuit()
{
kDebug() << "Implement me: " << k_funcinfo << endl;
}
void MaildirResource::configure()
{
QString oldDir = settings()->value( "General/Path" ).toString();
KUrl url;
if ( !oldDir.isEmpty() )
url = KUrl::fromPath( oldDir );
else
url = KUrl::fromPath( QDir::homePath() );
QString newDir = KFileDialog::getExistingDirectory( url, 0, i18n("Select Mail Directory") );
if ( newDir.isEmpty() )
return;
if ( oldDir == newDir )
return;
settings()->setValue( "General/Path", newDir );
synchronize();
}
void MaildirResource::itemAdded( const Akonadi::Item & item, const Akonadi::Collection& collection )
{
Maildir dir( collection.remoteId() );
QString errMsg;
if ( !dir.isValid( errMsg ) ) {
error( errMsg );
return;
}
// we can only deal with mail
if ( item.mimeType() != "message/rfc822" ) {
error( i18n("Only email messages can be added to the Maildir resource!") );
return;
}
const MessagePtr mail = item.payload<MessagePtr>();
dir.addEntry( mail->encodedContent() );
}
void MaildirResource::itemChanged( const Akonadi::Item& item, const QStringList& parts )
{
if ( !parts.contains( Item::PartBody ) ) return;
const QString rid = item.reference().remoteId();
const QString path = rid.left( rid.lastIndexOf( QDir::separator() ) );
const QString entry = rid.mid( rid.lastIndexOf( QDir::separator() ) + 1 );
Maildir dir( path );
QString errMsg;
if ( !dir.isValid( errMsg ) ) {
error( errMsg );
return;
}
// we can only deal with mail
if ( item.mimeType() != "message/rfc822" ) {
error( i18n("Only email messages can be added to the Maildir resource!") );
return;
}
const MessagePtr mail = item.payload<MessagePtr>();
dir.writeEntry( entry, mail->encodedContent() );
}
void MaildirResource::itemRemoved(const Akonadi::DataReference & ref)
{
const QString rid = ref.remoteId();
const QString path = rid.left( rid.lastIndexOf( QDir::separator() ) );
const QString entry = rid.mid( rid.lastIndexOf( QDir::separator() ) + 1 );
Maildir dir( path );
QString errMsg;
if ( !dir.isValid( errMsg ) ) {
error( errMsg );
return;
}
if ( !dir.removeEntry( entry ) ) {
error( i18n("Failed to delete item: %1", rid) );
}
}
void MaildirResource::retrieveCollections()
{
Maildir dir( settings()->value( "General/Path" ).toString() );
QString errMsg;
if ( !dir.isValid( errMsg ) ) {
error( errMsg );
collectionsRetrieved( Collection::List() );
}
Collection root;
root.setParent( Collection::root() );
root.setRemoteId( settings()->value( "General/Path" ).toString() );
root.setName( name() );
QStringList mimeTypes;
mimeTypes << "message/rfc822" << Collection::collectionMimeType();
root.setContentTypes( mimeTypes );
root.setCachePolicyId( 1 ); // ### just for testing
Collection::List list;
list << root;
foreach ( const QString sub, dir.subFolderList() ) {
Collection c;
c.setRemoteId( sub );
c.setParent( root );
c.setContentTypes( mimeTypes );
list << c;
}
collectionsRetrieved( list );
}
void MaildirResource::synchronizeCollection(const Akonadi::Collection & col)
{
ItemFetchJob *fetch = new ItemFetchJob( col, session() );
if ( !fetch->exec() ) {
changeStatus( Error, i18n("Unable to fetch listing of collection '%1': %2", col.name(), fetch->errorString()) );
return;
}
Item::List items = fetch->items();
changeProgress( 0 );
Maildir md( col.remoteId() );
if ( !md.isValid() ) {
error( i18n("Invalid maildir" ) );
return;
}
QStringList entryList = md.entryList();
int counter = 0;
foreach ( const QString entry, entryList ) {
const QString rid = col.remoteId() + QDir::separator() + entry;
bool found = false;
foreach ( Item item, items ) {
if ( item.reference().remoteId() == rid ) {
found = true;
break;
}
}
if ( found )
continue;
Item item( DataReference( -1, rid ) );
item.setMimeType( "message/rfc822" );
ItemAppendJob *append = new ItemAppendJob( item, col, session() );
if ( !append->exec() ) {
changeProgress( 0 );
changeStatus( Error, i18n("Appending new message failed: %1", append->errorString()) );
return;
}
counter++;
int percentage = (counter * 100) / entryList.count();
changeProgress( percentage );
}
collectionSynchronized();
}
#include "maildirresource.moc"
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.