text
stringlengths 54
60.6k
|
|---|
<commit_before>// 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 "skia/ext/vector_platform_device_skia.h"
#include "skia/ext/bitmap_platform_device.h"
#include "third_party/skia/include/core/SkClipStack.h"
#include "third_party/skia/include/core/SkDraw.h"
#include "third_party/skia/include/core/SkRect.h"
#include "third_party/skia/include/core/SkRegion.h"
#include "third_party/skia/include/core/SkScalar.h"
namespace skia {
static inline SkBitmap makeABitmap(int width, int height) {
SkBitmap bitmap;
bitmap.setConfig(SkBitmap::kNo_Config, width, height);
return bitmap;
}
VectorPlatformDeviceSkia::VectorPlatformDeviceSkia(SkPDFDevice* pdf_device)
: PlatformDevice(makeABitmap(pdf_device->width(), pdf_device->height())),
pdf_device_(pdf_device) {
}
VectorPlatformDeviceSkia::~VectorPlatformDeviceSkia() {
}
bool VectorPlatformDeviceSkia::IsNativeFontRenderingAllowed() {
return false;
}
PlatformDevice::PlatformSurface VectorPlatformDeviceSkia::BeginPlatformPaint() {
// Even when drawing a vector representation of the page, we have to
// provide a raster surface for plugins to render into - they don't have
// a vector interface. Therefore we create a BitmapPlatformDevice here
// and return the context from it, then layer on the raster data as an
// image in EndPlatformPaint.
DCHECK(raster_surface_ == NULL);
#if defined(OS_WIN)
raster_surface_ = BitmapPlatformDevice::create(pdf_device_->width(),
pdf_device_->height(),
false, /* not opaque */
NULL);
#elif defined(OS_POSIX) && !defined(OS_MACOSX)
raster_surface_ = BitmapPlatformDevice::Create(pdf_device_->width(),
pdf_device_->height(),
false /* not opaque */);
#endif
raster_surface_->unref(); // SkRefPtr and create both took a reference.
SkCanvas canvas(raster_surface_.get());
return raster_surface_->BeginPlatformPaint();
}
void VectorPlatformDeviceSkia::EndPlatformPaint() {
DCHECK(raster_surface_ != NULL);
SkPaint paint;
// SkPDFDevice checks the passed SkDraw for an empty clip (only). Fake
// it out by setting a non-empty clip.
SkDraw draw;
SkRegion clip(SkIRect::MakeWH(pdf_device_->width(), pdf_device_->height()));
draw.fClip=&clip;
pdf_device_->drawSprite(draw, raster_surface_->accessBitmap(false), 0, 0,
paint);
// BitmapPlatformDevice matches begin and end calls.
raster_surface_->EndPlatformPaint();
raster_surface_ = NULL;
}
uint32_t VectorPlatformDeviceSkia::getDeviceCapabilities() {
return SkDevice::getDeviceCapabilities() | kVector_Capability;
}
int VectorPlatformDeviceSkia::width() const {
return pdf_device_->width();
}
int VectorPlatformDeviceSkia::height() const {
return pdf_device_->height();
}
void VectorPlatformDeviceSkia::setMatrixClip(const SkMatrix& matrix,
const SkRegion& region,
const SkClipStack& stack) {
pdf_device_->setMatrixClip(matrix, region, stack);
}
bool VectorPlatformDeviceSkia::readPixels(const SkIRect& srcRect,
SkBitmap* bitmap) {
return false;
}
void VectorPlatformDeviceSkia::drawPaint(const SkDraw& draw,
const SkPaint& paint) {
pdf_device_->drawPaint(draw, paint);
}
void VectorPlatformDeviceSkia::drawPoints(const SkDraw& draw,
SkCanvas::PointMode mode,
size_t count, const SkPoint pts[],
const SkPaint& paint) {
pdf_device_->drawPoints(draw, mode, count, pts, paint);
}
void VectorPlatformDeviceSkia::drawRect(const SkDraw& draw,
const SkRect& rect,
const SkPaint& paint) {
pdf_device_->drawRect(draw, rect, paint);
}
void VectorPlatformDeviceSkia::drawPath(const SkDraw& draw,
const SkPath& path,
const SkPaint& paint,
const SkMatrix* prePathMatrix,
bool pathIsMutable) {
pdf_device_->drawPath(draw, path, paint, prePathMatrix, pathIsMutable);
}
void VectorPlatformDeviceSkia::drawBitmap(const SkDraw& draw,
const SkBitmap& bitmap,
const SkIRect* srcRectOrNull,
const SkMatrix& matrix,
const SkPaint& paint) {
pdf_device_->drawBitmap(draw, bitmap, srcRectOrNull, matrix, paint);
}
void VectorPlatformDeviceSkia::drawSprite(const SkDraw& draw,
const SkBitmap& bitmap,
int x, int y,
const SkPaint& paint) {
pdf_device_->drawSprite(draw, bitmap, x, y, paint);
}
void VectorPlatformDeviceSkia::drawText(const SkDraw& draw,
const void* text,
size_t byteLength,
SkScalar x,
SkScalar y,
const SkPaint& paint) {
pdf_device_->drawText(draw, text, byteLength, x, y, paint);
}
void VectorPlatformDeviceSkia::drawPosText(const SkDraw& draw,
const void* text,
size_t len,
const SkScalar pos[],
SkScalar constY,
int scalarsPerPos,
const SkPaint& paint) {
pdf_device_->drawPosText(draw, text, len, pos, constY, scalarsPerPos, paint);
}
void VectorPlatformDeviceSkia::drawTextOnPath(const SkDraw& draw,
const void* text,
size_t len,
const SkPath& path,
const SkMatrix* matrix,
const SkPaint& paint) {
pdf_device_->drawTextOnPath(draw, text, len, path, matrix, paint);
}
void VectorPlatformDeviceSkia::drawVertices(const SkDraw& draw,
SkCanvas::VertexMode vmode,
int vertexCount,
const SkPoint vertices[],
const SkPoint texs[],
const SkColor colors[],
SkXfermode* xmode,
const uint16_t indices[],
int indexCount,
const SkPaint& paint) {
pdf_device_->drawVertices(draw, vmode, vertexCount, vertices, texs, colors,
xmode, indices, indexCount, paint);
}
void VectorPlatformDeviceSkia::drawDevice(const SkDraw& draw,
SkDevice* device,
int x,
int y,
const SkPaint& paint) {
SkDevice* real_device = device;
if ((device->getDeviceCapabilities() & kVector_Capability)) {
// Assume that a vectorial device means a VectorPlatformDeviceSkia, we need
// to unwrap the embedded SkPDFDevice.
VectorPlatformDeviceSkia* vector_device =
static_cast<VectorPlatformDeviceSkia*>(device);
real_device = vector_device->pdf_device_.get();
}
pdf_device_->drawDevice(draw, real_device, x, y, paint);
}
#if defined(OS_WIN)
void VectorPlatformDeviceSkia::DrawToNativeContext(HDC dc,
int x,
int y,
const RECT* src_rect) {
SkASSERT(false);
}
#elif defined(OS_MACOSX)
void VectorPlatformDeviceSkia::DrawToNativeContext(CGContext* context, int x,
int y, const CGRect* src_rect) {
SkASSERT(false);
}
CGContextRef VectorPlatformDeviceSkia::GetBitmapContext() {
SkASSERT(false);
return NULL;
}
#endif
SkDevice* VectorPlatformDeviceSkia::onCreateCompatibleDevice(
SkBitmap::Config config, int width, int height, bool isOpaque,
Usage /*usage*/) {
SkAutoTUnref<SkDevice> dev(pdf_device_->createCompatibleDevice(config, width,
height,
isOpaque));
return new VectorPlatformDeviceSkia(static_cast<SkPDFDevice*>(dev.get()));
}
} // namespace skia
<commit_msg>Fix 3D-CSS transform printing - proxy device origin.<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 "skia/ext/vector_platform_device_skia.h"
#include "skia/ext/bitmap_platform_device.h"
#include "third_party/skia/include/core/SkClipStack.h"
#include "third_party/skia/include/core/SkDraw.h"
#include "third_party/skia/include/core/SkRect.h"
#include "third_party/skia/include/core/SkRegion.h"
#include "third_party/skia/include/core/SkScalar.h"
namespace skia {
static inline SkBitmap makeABitmap(int width, int height) {
SkBitmap bitmap;
bitmap.setConfig(SkBitmap::kNo_Config, width, height);
return bitmap;
}
VectorPlatformDeviceSkia::VectorPlatformDeviceSkia(SkPDFDevice* pdf_device)
: PlatformDevice(makeABitmap(pdf_device->width(), pdf_device->height())),
pdf_device_(pdf_device) {
}
VectorPlatformDeviceSkia::~VectorPlatformDeviceSkia() {
}
bool VectorPlatformDeviceSkia::IsNativeFontRenderingAllowed() {
return false;
}
PlatformDevice::PlatformSurface VectorPlatformDeviceSkia::BeginPlatformPaint() {
// Even when drawing a vector representation of the page, we have to
// provide a raster surface for plugins to render into - they don't have
// a vector interface. Therefore we create a BitmapPlatformDevice here
// and return the context from it, then layer on the raster data as an
// image in EndPlatformPaint.
DCHECK(raster_surface_ == NULL);
#if defined(OS_WIN)
raster_surface_ = BitmapPlatformDevice::create(pdf_device_->width(),
pdf_device_->height(),
false, /* not opaque */
NULL);
#elif defined(OS_POSIX) && !defined(OS_MACOSX)
raster_surface_ = BitmapPlatformDevice::Create(pdf_device_->width(),
pdf_device_->height(),
false /* not opaque */);
#endif
raster_surface_->unref(); // SkRefPtr and create both took a reference.
SkCanvas canvas(raster_surface_.get());
return raster_surface_->BeginPlatformPaint();
}
void VectorPlatformDeviceSkia::EndPlatformPaint() {
DCHECK(raster_surface_ != NULL);
SkPaint paint;
// SkPDFDevice checks the passed SkDraw for an empty clip (only). Fake
// it out by setting a non-empty clip.
SkDraw draw;
SkRegion clip(SkIRect::MakeWH(pdf_device_->width(), pdf_device_->height()));
draw.fClip=&clip;
pdf_device_->drawSprite(draw, raster_surface_->accessBitmap(false), 0, 0,
paint);
// BitmapPlatformDevice matches begin and end calls.
raster_surface_->EndPlatformPaint();
raster_surface_ = NULL;
}
uint32_t VectorPlatformDeviceSkia::getDeviceCapabilities() {
return SkDevice::getDeviceCapabilities() | kVector_Capability;
}
int VectorPlatformDeviceSkia::width() const {
return pdf_device_->width();
}
int VectorPlatformDeviceSkia::height() const {
return pdf_device_->height();
}
void VectorPlatformDeviceSkia::setMatrixClip(const SkMatrix& matrix,
const SkRegion& region,
const SkClipStack& stack) {
pdf_device_->setMatrixClip(matrix, region, stack);
}
bool VectorPlatformDeviceSkia::readPixels(const SkIRect& srcRect,
SkBitmap* bitmap) {
return false;
}
void VectorPlatformDeviceSkia::drawPaint(const SkDraw& draw,
const SkPaint& paint) {
pdf_device_->drawPaint(draw, paint);
}
void VectorPlatformDeviceSkia::drawPoints(const SkDraw& draw,
SkCanvas::PointMode mode,
size_t count, const SkPoint pts[],
const SkPaint& paint) {
pdf_device_->drawPoints(draw, mode, count, pts, paint);
}
void VectorPlatformDeviceSkia::drawRect(const SkDraw& draw,
const SkRect& rect,
const SkPaint& paint) {
pdf_device_->drawRect(draw, rect, paint);
}
void VectorPlatformDeviceSkia::drawPath(const SkDraw& draw,
const SkPath& path,
const SkPaint& paint,
const SkMatrix* prePathMatrix,
bool pathIsMutable) {
pdf_device_->drawPath(draw, path, paint, prePathMatrix, pathIsMutable);
}
void VectorPlatformDeviceSkia::drawBitmap(const SkDraw& draw,
const SkBitmap& bitmap,
const SkIRect* srcRectOrNull,
const SkMatrix& matrix,
const SkPaint& paint) {
pdf_device_->drawBitmap(draw, bitmap, srcRectOrNull, matrix, paint);
}
void VectorPlatformDeviceSkia::drawSprite(const SkDraw& draw,
const SkBitmap& bitmap,
int x, int y,
const SkPaint& paint) {
pdf_device_->drawSprite(draw, bitmap, x, y, paint);
}
void VectorPlatformDeviceSkia::drawText(const SkDraw& draw,
const void* text,
size_t byteLength,
SkScalar x,
SkScalar y,
const SkPaint& paint) {
pdf_device_->drawText(draw, text, byteLength, x, y, paint);
}
void VectorPlatformDeviceSkia::drawPosText(const SkDraw& draw,
const void* text,
size_t len,
const SkScalar pos[],
SkScalar constY,
int scalarsPerPos,
const SkPaint& paint) {
pdf_device_->drawPosText(draw, text, len, pos, constY, scalarsPerPos, paint);
}
void VectorPlatformDeviceSkia::drawTextOnPath(const SkDraw& draw,
const void* text,
size_t len,
const SkPath& path,
const SkMatrix* matrix,
const SkPaint& paint) {
pdf_device_->drawTextOnPath(draw, text, len, path, matrix, paint);
}
void VectorPlatformDeviceSkia::drawVertices(const SkDraw& draw,
SkCanvas::VertexMode vmode,
int vertexCount,
const SkPoint vertices[],
const SkPoint texs[],
const SkColor colors[],
SkXfermode* xmode,
const uint16_t indices[],
int indexCount,
const SkPaint& paint) {
pdf_device_->drawVertices(draw, vmode, vertexCount, vertices, texs, colors,
xmode, indices, indexCount, paint);
}
void VectorPlatformDeviceSkia::drawDevice(const SkDraw& draw,
SkDevice* device,
int x,
int y,
const SkPaint& paint) {
SkDevice* real_device = device;
if ((device->getDeviceCapabilities() & kVector_Capability)) {
// Assume that a vectorial device means a VectorPlatformDeviceSkia, we need
// to unwrap the embedded SkPDFDevice.
VectorPlatformDeviceSkia* vector_device =
static_cast<VectorPlatformDeviceSkia*>(device);
vector_device->pdf_device_->setOrigin(vector_device->getOrigin().fX,
vector_device->getOrigin().fY);
real_device = vector_device->pdf_device_.get();
}
pdf_device_->drawDevice(draw, real_device, x, y, paint);
}
#if defined(OS_WIN)
void VectorPlatformDeviceSkia::DrawToNativeContext(HDC dc,
int x,
int y,
const RECT* src_rect) {
SkASSERT(false);
}
#elif defined(OS_MACOSX)
void VectorPlatformDeviceSkia::DrawToNativeContext(CGContext* context, int x,
int y, const CGRect* src_rect) {
SkASSERT(false);
}
CGContextRef VectorPlatformDeviceSkia::GetBitmapContext() {
SkASSERT(false);
return NULL;
}
#endif
SkDevice* VectorPlatformDeviceSkia::onCreateCompatibleDevice(
SkBitmap::Config config, int width, int height, bool isOpaque,
Usage /*usage*/) {
SkAutoTUnref<SkDevice> dev(pdf_device_->createCompatibleDevice(config, width,
height,
isOpaque));
return new VectorPlatformDeviceSkia(static_cast<SkPDFDevice*>(dev.get()));
}
} // namespace skia
<|endoftext|>
|
<commit_before>//
// Created by dar on 1/23/16.
//
#include <window/MainMenu.h>
#include <window/Window.h>
#include "Application.h"
#include "window/Game.h"
#include "render/RenderManager.h"
#include "logging.h"
#include <ApplicationContext.h>
Application::Application() {
this->renderer = new RenderManager();
auto switchWindow = [&](Window *window) {
if (window == nullptr) {
this->running = false;
return false;
}
this->previousWindow = this->window;
this->window = window;
this->renderer->initWindow(this->window);
this->resize(this->renderer->getRenderContext()->getWindowWidth(), this->renderer->getRenderContext()->getWindowHeight());
return true;
};
#if !defined(EDITOR) && !defined(DEBUG)
this->window = new MainMenu(new ApplicationContext(switchWindow));
#else
this->window = new Game(new ApplicationContext(switchWindow));
#endif
this->timer = new Timer();
this->inputManager = new InputManager();
this->reinit();
this->resize(1366, 750);
}
void Application::reinit() {
this->renderer->init();
this->renderer->initWindow(this->window); //TODO
timer->GetDelta(); //if not called right now, first call in game loop would return a very huge value
this->inputManager->reload();
}
void Application::update(bool dynamic) {
if (this->previousWindow != nullptr) {
delete this->previousWindow;
this->previousWindow = nullptr;
}
if (dynamic) {
double deltaTime = timer->GetDelta();
this->accumulator += deltaTime;
while (accumulator > TIME_STEP) {
this->getCurrentWindow()->tick(TIME_STEP);
this->accumulator -= TIME_STEP;
}
} else {
this->getCurrentWindow()->tick(TIME_STEP * 1.5);
}
this->renderer->render(this->getCurrentWindow());
if (!MOBILE) this->handleEvents();
this->inputManager->tick(this->getCurrentWindow());
}
Application::~Application() {
delete this->window;
}
#ifdef __ANDROID__
#include <jni.h>
Application *application = nullptr;
extern "C" {
JNIEXPORT void JNICALL Java_tk_approach_android_spookytom_JniBridge_init(JNIEnv *env, jobject obj);
JNIEXPORT void JNICALL Java_tk_approach_android_spookytom_JniBridge_resize(JNIEnv *env, jobject obj, jint width, jint height);
JNIEXPORT void JNICALL Java_tk_approach_android_spookytom_JniBridge_tick(JNIEnv *env, jobject obj);
JNIEXPORT void JNICALL Java_tk_approach_android_spookytom_JniBridge_handleTouch(JNIEnv *env, jobject obj, jint i, jint action, jfloat x, jfloat y);
};
JNIEXPORT void JNICALL Java_tk_approach_android_spookytom_JniBridge_init(JNIEnv *env, jobject obj) {
if (application == nullptr || application->getCurrentWindow() == nullptr) {
application = new Application();
} else {
application->reinit();
}
/*jclass cls = env->GetObjectClass(obj);
jmethodID mid = env->GetMethodID(cls, "loadTexture", "()V");
if (mid == 0) {
return;
}
env->CallVoidMethod(obj, mid);*/
}
JNIEXPORT void JNICALL Java_tk_approach_android_spookytom_JniBridge_resize(JNIEnv *env, jobject obj, jint width, jint height) {
application->resize(width, height);
}
JNIEXPORT void JNICALL Java_tk_approach_android_spookytom_JniBridge_tick(JNIEnv *env, jobject obj) {
application->update(false);
if (!application->isRunning()) {
jclass cls = env->GetObjectClass(obj);
jmethodID mid = env->GetMethodID(cls, "exit", "()V");
if (mid != 0) {
delete application;
env->CallVoidMethod(obj, mid);
}
}
}
JNIEXPORT void JNICALL Java_tk_approach_android_spookytom_JniBridge_handleTouch(JNIEnv *env, jobject obj, jint i, jint action, jfloat x, jfloat y) {
application->handleClick(i, action, x, y);
}
#endif //__ANDROID__
void Application::resize(int width, int height) {
this->getCurrentWindow()->reload(width, height);
this->renderer->resize(this->getCurrentWindow(), width, height);
}
void Application::handleClick(int i, int action, float x, float y) {
this->inputManager->handleClick(i, action, x, y);
}
void Application::handleEvents() {
#ifndef __ANDROID__
while (SDL_PollEvent(&e) != 0) {
switch (e.type) {
case SDL_QUIT:
this->running = false;
break;
case SDL_WINDOWEVENT:
if (e.window.event == SDL_WINDOWEVENT_RESIZED || e.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) {
this->resize((unsigned int) e.window.data1, (unsigned int) e.window.data2);
}
break;
case SDL_KEYDOWN:
case SDL_KEYUP:
this->inputManager->handleKeypress(&e);
break;
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
LOGD("%s button with id %d\n", e.type == SDL_MOUSEBUTTONDOWN ? "Pressed" : "Unpressed", e.button.button);
case SDL_MOUSEMOTION: {
int button = (int) round(log((double) e.button.button) / log(2.0)) + 1;
if (button < 0 || button >= 5) break;
int x, y;
SDL_GetMouseState(&x, &y);
this->handleClick(button, e.type == SDL_MOUSEBUTTONDOWN ? 0 : (e.type == SDL_MOUSEBUTTONUP ? 1 : 2), x, y);
break;
}
}
}
#else //__ANDROID__
LOGW("SDL is not supported on this platform\n");
#endif //__ANDROID__
}
<commit_msg>Switched from delta time accumulator to pure delta time calculations<commit_after>//
// Created by dar on 1/23/16.
//
#include <window/MainMenu.h>
#include <window/Window.h>
#include "Application.h"
#include "window/Game.h"
#include "render/RenderManager.h"
#include "logging.h"
#include <ApplicationContext.h>
Application::Application() {
this->renderer = new RenderManager();
auto switchWindow = [&](Window *window) {
if (window == nullptr) {
this->running = false;
return false;
}
this->previousWindow = this->window;
this->window = window;
this->renderer->initWindow(this->window);
this->resize(this->renderer->getRenderContext()->getWindowWidth(), this->renderer->getRenderContext()->getWindowHeight());
return true;
};
#if !defined(EDITOR) && !defined(DEBUG)
this->window = new MainMenu(new ApplicationContext(switchWindow));
#else
this->window = new Game(new ApplicationContext(switchWindow));
#endif
this->timer = new Timer();
this->inputManager = new InputManager();
this->reinit();
this->resize(1366, 750);
}
void Application::reinit() {
this->renderer->init();
this->renderer->initWindow(this->window); //TODO
timer->GetDelta(); //if not called right now, first call in game loop would return a very huge value
this->inputManager->reload();
}
void Application::update(bool dynamic) {
if (this->previousWindow != nullptr) {
delete this->previousWindow;
this->previousWindow = nullptr;
}
if (dynamic) {
this->getCurrentWindow()->tick(TIME_STEP * timer->GetDelta() * 65);
} else {
this->getCurrentWindow()->tick(TIME_STEP * 1.5);
}
this->renderer->render(this->getCurrentWindow());
if (!MOBILE) this->handleEvents();
this->inputManager->tick(this->getCurrentWindow());
}
Application::~Application() {
delete this->window;
}
#ifdef __ANDROID__
#include <jni.h>
Application *application = nullptr;
extern "C" {
JNIEXPORT void JNICALL Java_tk_approach_android_spookytom_JniBridge_init(JNIEnv *env, jobject obj);
JNIEXPORT void JNICALL Java_tk_approach_android_spookytom_JniBridge_resize(JNIEnv *env, jobject obj, jint width, jint height);
JNIEXPORT void JNICALL Java_tk_approach_android_spookytom_JniBridge_tick(JNIEnv *env, jobject obj);
JNIEXPORT void JNICALL Java_tk_approach_android_spookytom_JniBridge_handleTouch(JNIEnv *env, jobject obj, jint i, jint action, jfloat x, jfloat y);
};
JNIEXPORT void JNICALL Java_tk_approach_android_spookytom_JniBridge_init(JNIEnv *env, jobject obj) {
if (application == nullptr || application->getCurrentWindow() == nullptr) {
application = new Application();
} else {
application->reinit();
}
/*jclass cls = env->GetObjectClass(obj);
jmethodID mid = env->GetMethodID(cls, "loadTexture", "()V");
if (mid == 0) {
return;
}
env->CallVoidMethod(obj, mid);*/
}
JNIEXPORT void JNICALL Java_tk_approach_android_spookytom_JniBridge_resize(JNIEnv *env, jobject obj, jint width, jint height) {
application->resize(width, height);
}
JNIEXPORT void JNICALL Java_tk_approach_android_spookytom_JniBridge_tick(JNIEnv *env, jobject obj) {
application->update(false);
if (!application->isRunning()) {
jclass cls = env->GetObjectClass(obj);
jmethodID mid = env->GetMethodID(cls, "exit", "()V");
if (mid != 0) {
delete application;
env->CallVoidMethod(obj, mid);
}
}
}
JNIEXPORT void JNICALL Java_tk_approach_android_spookytom_JniBridge_handleTouch(JNIEnv *env, jobject obj, jint i, jint action, jfloat x, jfloat y) {
application->handleClick(i, action, x, y);
}
#endif //__ANDROID__
void Application::resize(int width, int height) {
this->getCurrentWindow()->reload(width, height);
this->renderer->resize(this->getCurrentWindow(), width, height);
}
void Application::handleClick(int i, int action, float x, float y) {
this->inputManager->handleClick(i, action, x, y);
}
void Application::handleEvents() {
#ifndef __ANDROID__
while (SDL_PollEvent(&e) != 0) {
switch (e.type) {
case SDL_QUIT:
this->running = false;
break;
case SDL_WINDOWEVENT:
if (e.window.event == SDL_WINDOWEVENT_RESIZED || e.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) {
this->resize((unsigned int) e.window.data1, (unsigned int) e.window.data2);
}
break;
case SDL_KEYDOWN:
case SDL_KEYUP:
this->inputManager->handleKeypress(&e);
break;
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
LOGD("%s button with id %d\n", e.type == SDL_MOUSEBUTTONDOWN ? "Pressed" : "Unpressed", e.button.button);
case SDL_MOUSEMOTION: {
int button = (int) round(log((double) e.button.button) / log(2.0)) + 1;
if (button < 0 || button >= 5) break;
int x, y;
SDL_GetMouseState(&x, &y);
this->handleClick(button, e.type == SDL_MOUSEBUTTONDOWN ? 0 : (e.type == SDL_MOUSEBUTTONUP ? 1 : 2), x, y);
break;
}
}
}
#else //__ANDROID__
LOGW("SDL is not supported on this platform\n");
#endif //__ANDROID__
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2004-2015 ZNC, see the NOTICE file for details.
*
* 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 <znc/FileUtils.h>
#include <znc/Server.h>
#include <znc/IRCNetwork.h>
#include <znc/User.h>
#include <syslog.h>
class CAdminLogMod : public CModule {
public:
MODCONSTRUCTOR(CAdminLogMod) {
AddHelpCommand();
AddCommand("Show", static_cast<CModCommand::ModCmdFunc>(&CAdminLogMod::OnShowCommand), "", "Show the logging target");
AddCommand("Target", static_cast<CModCommand::ModCmdFunc>(&CAdminLogMod::OnTargetCommand), "<file|syslog|both>", "Set the logging target");
openlog("znc", LOG_PID, LOG_DAEMON);
}
virtual ~CAdminLogMod() {
Log("Logging ended.");
closelog();
}
bool OnLoad(const CString & sArgs, CString & sMessage) override {
CString sTarget = GetNV("target");
if (sTarget.Equals("syslog"))
m_eLogMode = LOG_TO_SYSLOG;
else if (sTarget.Equals("both"))
m_eLogMode = LOG_TO_BOTH;
else if (sTarget.Equals("file"))
m_eLogMode = LOG_TO_FILE;
else
m_eLogMode = LOG_TO_FILE;
m_sLogFile = GetSavePath() + "/znc.log";
Log("Logging started. ZNC PID[" + CString(getpid()) + "] UID/GID[" + CString(getuid()) + ":" + CString(getgid()) + "]");
return true;
}
void OnIRCConnected() override {
Log("[" + GetUser()->GetUserName() + "/" + GetNetwork()->GetName() + "] connected to IRC: " + GetNetwork()->GetCurrentServer()->GetName());
}
void OnIRCDisconnected() override {
Log("[" + GetUser()->GetUserName() + "/" + GetNetwork()->GetName() + "] disconnected from IRC");
}
EModRet OnRaw(CString& sLine) override {
if (sLine.StartsWith("ERROR ")) {
//ERROR :Closing Link: nick[24.24.24.24] (Excess Flood)
//ERROR :Closing Link: nick[24.24.24.24] Killer (Local kill by Killer (reason))
CString sError(sLine.substr(6));
if (sError.Left(1) == ":")
sError.LeftChomp();
Log("[" + GetUser()->GetUserName() + "/" + GetNetwork()->GetName() + "] disconnected from IRC: " +
GetNetwork()->GetCurrentServer()->GetName() + " [" + sError + "]", LOG_NOTICE);
}
return CONTINUE;
}
void OnClientLogin() override {
Log("[" + GetUser()->GetUserName() + "] connected to ZNC from " + GetClient()->GetRemoteIP());
}
void OnClientDisconnect() override {
Log("[" + GetUser()->GetUserName() + "] disconnected from ZNC from " + GetClient()->GetRemoteIP());
}
void OnFailedLogin(const CString& sUsername, const CString& sRemoteIP) override {
Log("[" + sUsername + "] failed to login from " + sRemoteIP, LOG_WARNING);
}
void Log(CString sLine, int iPrio = LOG_INFO) {
if (m_eLogMode & LOG_TO_SYSLOG)
syslog(iPrio, "%s", sLine.c_str());
if (m_eLogMode & LOG_TO_FILE) {
time_t curtime;
tm* timeinfo;
char buf[23];
time(&curtime);
timeinfo = localtime(&curtime);
strftime(buf,sizeof(buf),"[%Y-%m-%d %H:%M:%S] ",timeinfo);
CFile LogFile(m_sLogFile);
if (LogFile.Open(O_WRONLY | O_APPEND | O_CREAT))
LogFile.Write(buf + sLine + "\n");
else
DEBUG("Failed to write to [" << m_sLogFile << "]: " << strerror(errno));
}
}
void OnModCommand(const CString& sCommand) override {
if (!GetUser()->IsAdmin()) {
PutModule("Access denied");
} else {
HandleCommand(sCommand);
}
}
void OnTargetCommand(const CString& sCommand) {
CString sArg = sCommand.Token(1, true);
CString sTarget;
CString sMessage;
LogMode mode;
if (sArg.Equals("file")) {
sTarget = "file";
sMessage = "Now only logging to file";
mode = LOG_TO_FILE;
} else if (sArg.Equals("syslog")) {
sTarget = "syslog";
sMessage = "Now only logging to syslog";
mode = LOG_TO_SYSLOG;
} else if (sArg.Equals("both")) {
sTarget = "both";
sMessage = "Now logging to file and syslog";
mode = LOG_TO_BOTH;
} else {
if (sArg.empty()) {
PutModule("Usage: Target <file|syslog|both>");
} else {
PutModule("Unknown target");
}
return;
}
Log(sMessage);
SetNV("target", sTarget);
m_eLogMode = mode;
PutModule(sMessage);
}
void OnShowCommand(const CString& sCommand) {
CString sTarget;
switch (m_eLogMode)
{
case LOG_TO_FILE:
sTarget = "file";
break;
case LOG_TO_SYSLOG:
sTarget = "syslog";
break;
case LOG_TO_BOTH:
sTarget = "both, file and syslog";
break;
}
PutModule("Logging is enabled for " + sTarget);
if (m_eLogMode != LOG_TO_SYSLOG)
PutModule("Log file will be written to [" + m_sLogFile + "]");
}
private:
enum LogMode {
LOG_TO_FILE = 1 << 0,
LOG_TO_SYSLOG = 1 << 1,
LOG_TO_BOTH = LOG_TO_FILE | LOG_TO_SYSLOG
};
LogMode m_eLogMode;
CString m_sLogFile;
};
template<> void TModInfo<CAdminLogMod>(CModInfo& Info) {
Info.SetWikiPage("adminlog");
}
GLOBALMODULEDEFS(CAdminLogMod, "Log ZNC events to file and/or syslog.")
<commit_msg>Added reverse dns detection to adminlog.<commit_after>/*
* Copyright (C) 2004-2015 ZNC, see the NOTICE file for details.
*
* 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 <arpa/inet.h>
#include <znc/FileUtils.h>
#include <znc/Server.h>
#include <znc/IRCNetwork.h>
#include <znc/User.h>
#include <znc/IRCSock.h>
#include <syslog.h>
class CAdminLogMod : public CModule {
public:
MODCONSTRUCTOR(CAdminLogMod) {
AddHelpCommand();
AddCommand("Show", static_cast<CModCommand::ModCmdFunc>(&CAdminLogMod::OnShowCommand), "", "Show the logging target");
AddCommand("Target", static_cast<CModCommand::ModCmdFunc>(&CAdminLogMod::OnTargetCommand), "<file|syslog|both>", "Set the logging target");
openlog("znc", LOG_PID, LOG_DAEMON);
}
virtual ~CAdminLogMod() {
Log("Logging ended.");
closelog();
}
CString ResolveIp(const CString ip)
{
struct hostent *hent = nullptr;
struct in_addr addr;
struct in6_addr addr6;
if(inet_pton(AF_INET, ip.c_str(), &addr))
if((hent = gethostbyaddr((char *)&(addr.s_addr), sizeof(addr.s_addr), AF_INET))) {
char *hostname = (char*) malloc(sizeof(char)*strlen(hent->h_name));
strcpy(hostname, hent->h_name);
CString str = CString(hostname);
free(hostname);
return str;
}
if(inet_pton(AF_INET6, ip.c_str(), &addr6))
if((hent = gethostbyaddr((char *)&(addr6.s6_addr), sizeof(addr6.s6_addr), AF_INET6))) {
char *hostname = (char*) malloc(sizeof(char)*strlen(hent->h_name));
strcpy(hostname, hent->h_name);
CString str = CString(hostname);
free(hostname);
return str;
}
return ip;
}
bool OnLoad(const CString & sArgs, CString & sMessage) override {
CString sTarget = GetNV("target");
if (sTarget.Equals("syslog"))
m_eLogMode = LOG_TO_SYSLOG;
else if (sTarget.Equals("both"))
m_eLogMode = LOG_TO_BOTH;
else if (sTarget.Equals("file"))
m_eLogMode = LOG_TO_FILE;
else
m_eLogMode = LOG_TO_FILE;
m_sLogFile = GetSavePath() + "/znc.log";
Log("Logging started. ZNC PID[" + CString(getpid()) + "] UID/GID[" + CString(getuid()) + ":" + CString(getgid()) + "]");
return true;
}
void OnIRCConnected() override {
Log("[" + GetUser()->GetUserName() + "/" + GetNetwork()->GetName() + "] connected to IRC with server " + GetNetwork()->GetCurrentServer()->GetName() + " which has ip " + CString(GetNetwork()->GetIRCSock()->GetRemoteIP()) + " with reverse dns pointing to " + ResolveIp(GetNetwork()->GetIRCSock()->GetRemoteIP()));
}
void OnIRCDisconnected() override {
Log("[" + GetUser()->GetUserName() + "/" + GetNetwork()->GetName() + "] disconnected from IRC");
}
EModRet OnRaw(CString& sLine) override {
if (sLine.StartsWith("ERROR ")) {
//ERROR :Closing Link: nick[24.24.24.24] (Excess Flood)
//ERROR :Closing Link: nick[24.24.24.24] Killer (Local kill by Killer (reason))
CString sError(sLine.substr(6));
if (sError.Left(1) == ":")
sError.LeftChomp();
Log("[" + GetUser()->GetUserName() + "/" + GetNetwork()->GetName() + "] disconnected from IRC: " +
GetNetwork()->GetCurrentServer()->GetName() + " [" + sError + "]", LOG_NOTICE);
}
return CONTINUE;
}
void OnClientLogin() override {
Log("[" + GetUser()->GetUserName() + "] connected to ZNC from " + GetClient()->GetRemoteIP());
}
void OnClientDisconnect() override {
Log("[" + GetUser()->GetUserName() + "] disconnected from ZNC from " + GetClient()->GetRemoteIP());
}
void OnFailedLogin(const CString& sUsername, const CString& sRemoteIP) override {
Log("[" + sUsername + "] failed to login from " + sRemoteIP, LOG_WARNING);
}
void Log(CString sLine, int iPrio = LOG_INFO) {
if (m_eLogMode & LOG_TO_SYSLOG)
syslog(iPrio, "%s", sLine.c_str());
if (m_eLogMode & LOG_TO_FILE) {
time_t curtime;
tm* timeinfo;
char buf[23];
time(&curtime);
timeinfo = localtime(&curtime);
strftime(buf,sizeof(buf),"[%Y-%m-%d %H:%M:%S] ",timeinfo);
CFile LogFile(m_sLogFile);
if (LogFile.Open(O_WRONLY | O_APPEND | O_CREAT))
LogFile.Write(buf + sLine + "\n");
else
DEBUG("Failed to write to [" << m_sLogFile << "]: " << strerror(errno));
}
}
void OnModCommand(const CString& sCommand) override {
if (!GetUser()->IsAdmin()) {
PutModule("Access denied");
} else {
HandleCommand(sCommand);
}
}
void OnTargetCommand(const CString& sCommand) {
CString sArg = sCommand.Token(1, true);
CString sTarget;
CString sMessage;
LogMode mode;
if (sArg.Equals("file")) {
sTarget = "file";
sMessage = "Now only logging to file";
mode = LOG_TO_FILE;
} else if (sArg.Equals("syslog")) {
sTarget = "syslog";
sMessage = "Now only logging to syslog";
mode = LOG_TO_SYSLOG;
} else if (sArg.Equals("both")) {
sTarget = "both";
sMessage = "Now logging to file and syslog";
mode = LOG_TO_BOTH;
} else {
if (sArg.empty()) {
PutModule("Usage: Target <file|syslog|both>");
} else {
PutModule("Unknown target");
}
return;
}
Log(sMessage);
SetNV("target", sTarget);
m_eLogMode = mode;
PutModule(sMessage);
}
void OnShowCommand(const CString& sCommand) {
CString sTarget;
switch (m_eLogMode)
{
case LOG_TO_FILE:
sTarget = "file";
break;
case LOG_TO_SYSLOG:
sTarget = "syslog";
break;
case LOG_TO_BOTH:
sTarget = "both, file and syslog";
break;
}
PutModule("Logging is enabled for " + sTarget);
if (m_eLogMode != LOG_TO_SYSLOG)
PutModule("Log file will be written to [" + m_sLogFile + "]");
}
private:
enum LogMode {
LOG_TO_FILE = 1 << 0,
LOG_TO_SYSLOG = 1 << 1,
LOG_TO_BOTH = LOG_TO_FILE | LOG_TO_SYSLOG
};
LogMode m_eLogMode;
CString m_sLogFile;
};
template<> void TModInfo<CAdminLogMod>(CModInfo& Info) {
Info.SetWikiPage("adminlog");
}
GLOBALMODULEDEFS(CAdminLogMod, "Log ZNC events to file and/or syslog.")
<|endoftext|>
|
<commit_before>//===-- X86FloatingPoint.cpp - FP_REG_KILL inserter -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the pass which inserts FP_REG_KILL instructions.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "x86-codegen"
#include "X86.h"
#include "X86InstrInfo.h"
#include "X86Subtarget.h"
#include "llvm/Instructions.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/CFG.h"
#include "llvm/ADT/Statistic.h"
using namespace llvm;
STATISTIC(NumFPKill, "Number of FP_REG_KILL instructions added");
namespace {
struct FPRegKiller : public MachineFunctionPass {
static char ID;
FPRegKiller() : MachineFunctionPass(&ID) {}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
AU.addPreservedID(MachineLoopInfoID);
AU.addPreservedID(MachineDominatorsID);
MachineFunctionPass::getAnalysisUsage(AU);
}
virtual bool runOnMachineFunction(MachineFunction &MF);
virtual const char *getPassName() const {
return "X86 FP_REG_KILL inserter";
}
};
char FPRegKiller::ID = 0;
}
FunctionPass *llvm::createX87FPRegKillInserterPass() {
return new FPRegKiller();
}
bool FPRegKiller::runOnMachineFunction(MachineFunction &MF) {
// If we are emitting FP stack code, scan the basic block to determine if this
// block defines any FP values. If so, put an FP_REG_KILL instruction before
// the terminator of the block.
// Note that FP stack instructions are used in all modes for long double,
// so we always need to do this check.
// Also note that it's possible for an FP stack register to be live across
// an instruction that produces multiple basic blocks (SSE CMOV) so we
// must check all the generated basic blocks.
// Scan all of the machine instructions in these MBBs, checking for FP
// stores. (RFP32 and RFP64 will not exist in SSE mode, but RFP80 might.)
// Fast-path: If nothing is using the x87 registers, we don't need to do
// any scanning.
MachineRegisterInfo &MRI = MF.getRegInfo();
if (MRI.getRegClassVirtRegs(X86::RFP80RegisterClass).empty() &&
MRI.getRegClassVirtRegs(X86::RFP64RegisterClass).empty() &&
MRI.getRegClassVirtRegs(X86::RFP32RegisterClass).empty())
return false;
bool Changed = false;
const X86Subtarget &Subtarget = MF.getTarget().getSubtarget<X86Subtarget>();
MachineFunction::iterator MBBI = MF.begin();
MachineFunction::iterator EndMBB = MF.end();
for (; MBBI != EndMBB; ++MBBI) {
MachineBasicBlock *MBB = MBBI;
// If this block returns, ignore it. We don't want to insert an FP_REG_KILL
// before the return.
if (!MBB->empty()) {
MachineBasicBlock::iterator EndI = MBB->end();
--EndI;
if (EndI->getDesc().isReturn())
continue;
}
bool ContainsFPCode = false;
for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
!ContainsFPCode && I != E; ++I) {
if (I->getNumOperands() != 0 && I->getOperand(0).isReg()) {
const TargetRegisterClass *clas;
for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
if (I->getOperand(op).isReg() && I->getOperand(op).isDef() &&
TargetRegisterInfo::isVirtualRegister(I->getOperand(op).getReg()) &&
((clas = MRI.getRegClass(I->getOperand(op).getReg())) ==
X86::RFP32RegisterClass ||
clas == X86::RFP64RegisterClass ||
clas == X86::RFP80RegisterClass)) {
ContainsFPCode = true;
break;
}
}
}
}
// Check PHI nodes in successor blocks. These PHI's will be lowered to have
// a copy of the input value in this block. In SSE mode, we only care about
// 80-bit values.
if (!ContainsFPCode) {
// Final check, check LLVM BB's that are successors to the LLVM BB
// corresponding to BB for FP PHI nodes.
const BasicBlock *LLVMBB = MBB->getBasicBlock();
for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
!ContainsFPCode && SI != E; ++SI) {
const PHINode *PN;
for (BasicBlock::const_iterator II = SI->begin();
(PN = dyn_cast<PHINode>(II)); ++II) {
if (PN->getType()->isX86_FP80Ty() ||
(!Subtarget.hasSSE1() && PN->getType()->isFloatingPointTy()) ||
(!Subtarget.hasSSE2() && PN->getType()->isDoubleTy())) {
ContainsFPCode = true;
break;
}
}
}
}
// Finally, if we found any FP code, emit the FP_REG_KILL instruction.
if (ContainsFPCode) {
BuildMI(*MBB, MBBI->getFirstTerminator(), DebugLoc(),
MF.getTarget().getInstrInfo()->get(X86::FP_REG_KILL));
++NumFPKill;
Changed = true;
}
}
return Changed;
}
<commit_msg>pull a nested loop of this pass out to its own function, eliminating the gymnastics around the ContainsFPCode var.<commit_after>//===-- X86FloatingPoint.cpp - FP_REG_KILL inserter -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the pass which inserts FP_REG_KILL instructions.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "x86-codegen"
#include "X86.h"
#include "X86InstrInfo.h"
#include "X86Subtarget.h"
#include "llvm/Instructions.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/CFG.h"
#include "llvm/ADT/Statistic.h"
using namespace llvm;
STATISTIC(NumFPKill, "Number of FP_REG_KILL instructions added");
namespace {
struct FPRegKiller : public MachineFunctionPass {
static char ID;
FPRegKiller() : MachineFunctionPass(&ID) {}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
AU.addPreservedID(MachineLoopInfoID);
AU.addPreservedID(MachineDominatorsID);
MachineFunctionPass::getAnalysisUsage(AU);
}
virtual bool runOnMachineFunction(MachineFunction &MF);
virtual const char *getPassName() const {
return "X86 FP_REG_KILL inserter";
}
};
char FPRegKiller::ID = 0;
}
FunctionPass *llvm::createX87FPRegKillInserterPass() {
return new FPRegKiller();
}
/// ContainsFPStackCode - Return true if the specific MBB has floating point
/// stack code, and thus needs an FP_REG_KILL.
static bool ContainsFPStackCode(MachineBasicBlock *MBB, unsigned SSELevel,
MachineRegisterInfo &MRI) {
for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
I != E; ++I) {
if (I->getNumOperands() != 0 && I->getOperand(0).isReg()) {
for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
if (I->getOperand(op).isReg() && I->getOperand(op).isDef() &&
TargetRegisterInfo::isVirtualRegister(I->getOperand(op).getReg())) {
const TargetRegisterClass *RegClass =
MRI.getRegClass(I->getOperand(op).getReg());
if (RegClass == X86::RFP32RegisterClass ||
RegClass == X86::RFP64RegisterClass ||
RegClass == X86::RFP80RegisterClass)
return true;
}
}
}
}
// Check PHI nodes in successor blocks. These PHI's will be lowered to have
// a copy of the input value in this block. In SSE mode, we only care about
// 80-bit values.
// Final check, check LLVM BB's that are successors to the LLVM BB
// corresponding to BB for FP PHI nodes.
const BasicBlock *LLVMBB = MBB->getBasicBlock();
for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
SI != E; ++SI) {
const PHINode *PN;
for (BasicBlock::const_iterator II = SI->begin();
(PN = dyn_cast<PHINode>(II)); ++II) {
if (PN->getType()->isX86_FP80Ty() ||
(SSELevel == 0 && PN->getType()->isFloatingPointTy()) ||
(SSELevel < 2 && PN->getType()->isDoubleTy())) {
return true;
}
}
}
return false;
}
bool FPRegKiller::runOnMachineFunction(MachineFunction &MF) {
// If we are emitting FP stack code, scan the basic block to determine if this
// block defines any FP values. If so, put an FP_REG_KILL instruction before
// the terminator of the block.
// Note that FP stack instructions are used in all modes for long double,
// so we always need to do this check.
// Also note that it's possible for an FP stack register to be live across
// an instruction that produces multiple basic blocks (SSE CMOV) so we
// must check all the generated basic blocks.
// Scan all of the machine instructions in these MBBs, checking for FP
// stores. (RFP32 and RFP64 will not exist in SSE mode, but RFP80 might.)
// Fast-path: If nothing is using the x87 registers, we don't need to do
// any scanning.
MachineRegisterInfo &MRI = MF.getRegInfo();
if (MRI.getRegClassVirtRegs(X86::RFP80RegisterClass).empty() &&
MRI.getRegClassVirtRegs(X86::RFP64RegisterClass).empty() &&
MRI.getRegClassVirtRegs(X86::RFP32RegisterClass).empty())
return false;
const X86Subtarget &Subtarget = MF.getTarget().getSubtarget<X86Subtarget>();
unsigned SSELevel = 0;
if (Subtarget.hasSSE2())
SSELevel = 2;
else if (Subtarget.hasSSE1())
SSELevel = 1;
bool Changed = false;
MachineFunction::iterator MBBI = MF.begin();
MachineFunction::iterator EndMBB = MF.end();
for (; MBBI != EndMBB; ++MBBI) {
MachineBasicBlock *MBB = MBBI;
// If this block returns, ignore it. We don't want to insert an FP_REG_KILL
// before the return.
if (!MBB->empty()) {
MachineBasicBlock::iterator EndI = MBB->end();
--EndI;
if (EndI->getDesc().isReturn())
continue;
}
// If we find any FP stack code, emit the FP_REG_KILL instruction.
if (ContainsFPStackCode(MBB, SSELevel, MRI)) {
BuildMI(*MBB, MBBI->getFirstTerminator(), DebugLoc(),
MF.getTarget().getInstrInfo()->get(X86::FP_REG_KILL));
++NumFPKill;
Changed = true;
}
}
return Changed;
}
<|endoftext|>
|
<commit_before>// @(#)root/srputils:$Name: $:$Id: SRPAuth.cxx,v 1.3 2000/12/19 14:37:14 rdm Exp $
// Author: Fons Rademakers 15/02/2000
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include <stdio.h>
extern "C" {
#include <t_pwd.h>
#include <t_client.h>
}
#include "TSocket.h"
#include "TAuthenticate.h"
#include "TError.h"
Int_t SRPAuthenticate(TSocket *, const char *user, const char *passwd,
const char *remote);
class SRPAuthInit {
public:
SRPAuthInit() { TAuthenticate::SetSecureAuthHook(&SRPAuthenticate); }
};
static SRPAuthInit srpauth_init;
//______________________________________________________________________________
Int_t SRPAuthenticate(TSocket *sock, const char *user, const char *passwd,
const char *remote)
{
// Authenticate to remote rootd server using the SRP (secure remote
// password) protocol. Returns 0 if authentication failed, 1 if
// authentication succeeded and 2 if SRP is not available and standard
// authentication should be tried
Int_t result = 0;
char *usr = 0;
char *psswd = 0;
Int_t stat, kind;
// check rootd protocol version (we need at least protocol version 2)
/* Redundant since kROOTD_PROTOCOL is only known since version 2
sock->Send(kROOTD_PROTOCOL);
sock->Recv(stat, kind);
if (kind == kROOTD_PROTOCOL && stat < 2)
return 2;
*/
// send user name
if (user && user[0])
usr = StrDup(user);
else
usr = TAuthenticate::PromptUser(remote);
sock->Send(usr, kROOTD_SRPUSER);
sock->Recv(stat, kind);
if (kind == kROOTD_ERR) {
TAuthenticate::AuthError("SRPAuthenticate", stat);
return result;
}
// stat == 2 when no SRP support compiled in remote rootd
if (kind == kROOTD_AUTH && stat == 2)
return 2;
struct t_num n, g, s, B, *A;
struct t_client *tc;
char hexbuf[MAXHEXPARAMLEN];
UChar_t buf1[MAXPARAMLEN], buf2[MAXPARAMLEN], buf3[MAXSALTLEN];
// receive n from server
sock->Recv(hexbuf, MAXHEXPARAMLEN, kind);
if (kind != kROOTD_SRPN) {
::Error("SRPAuthenticate", "expected kROOTD_SRPN message");
goto out;
}
n.data = buf1;
n.len = t_fromb64((char*)n.data, hexbuf);
// receive g from server
sock->Recv(hexbuf, MAXHEXPARAMLEN, kind);
if (kind != kROOTD_SRPG) {
::Error("SRPAuthenticate", "expected kROOTD_SRPG message");
goto out;
}
g.data = buf2;
g.len = t_fromb64((char*)g.data, hexbuf);
// receive salt from server
sock->Recv(hexbuf, MAXHEXPARAMLEN, kind);
if (kind != kROOTD_SRPSALT) {
::Error("SRPAuthenticate", "expected kROOTD_SRPSALT message");
goto out;
}
s.data = buf3;
s.len = t_fromb64((char*)s.data, hexbuf);
tc = t_clientopen(usr, &n, &g, &s);
A = t_clientgenexp(tc);
// send A to server
sock->Send(t_tob64(hexbuf, (char*)A->data, A->len), kROOTD_SRPA);
if (passwd && passwd[0])
psswd = StrDup(passwd);
else {
psswd = TAuthenticate::PromptPasswd("SRP password: ");
if (!psswd)
::Error("SRPAuthenticate", "password not set");
}
t_clientpasswd(tc, psswd);
// receive B from server
sock->Recv(hexbuf, MAXHEXPARAMLEN, kind);
if (kind != kROOTD_SRPB) {
::Error("SRPAuthenticate", "expected kROOTD_SRPB message");
goto out;
}
B.data = buf1;
B.len = t_fromb64((char*)B.data, hexbuf);
t_clientgetkey(tc, &B);
// send response to server
sock->Send(t_tohex(hexbuf, (char*)t_clientresponse(tc), RESPONSE_LEN),
kROOTD_SRPRESPONSE);
t_clientclose(tc);
sock->Recv(stat, kind);
if (kind == kROOTD_ERR)
TAuthenticate::AuthError("SRPAuthenticate", stat);
if (kind == kROOTD_AUTH && stat == 1)
result = 1;
out:
delete [] usr;
delete [] psswd;
return result;
}
<commit_msg>remove some commented out code + corrected some comments.<commit_after>// @(#)root/srputils:$Name: $:$Id: SRPAuth.cxx,v 1.4 2000/12/19 16:19:03 rdm Exp $
// Author: Fons Rademakers 15/02/2000
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include <stdio.h>
extern "C" {
#include <t_pwd.h>
#include <t_client.h>
}
#include "TSocket.h"
#include "TAuthenticate.h"
#include "TError.h"
Int_t SRPAuthenticate(TSocket *, const char *user, const char *passwd,
const char *remote);
class SRPAuthInit {
public:
SRPAuthInit() { TAuthenticate::SetSecureAuthHook(&SRPAuthenticate); }
};
static SRPAuthInit srpauth_init;
//______________________________________________________________________________
Int_t SRPAuthenticate(TSocket *sock, const char *user, const char *passwd,
const char *remote)
{
// Authenticate to remote rootd/proofd server using the SRP (secure remote
// password) protocol. Returns 0 if authentication failed, 1 if
// authentication succeeded and 2 if SRP is not available and standard
// authentication should be tried. Called via TAuthenticate class.
Int_t result = 0;
char *usr = 0;
char *psswd = 0;
Int_t stat, kind;
// send user name
if (user && user[0])
usr = StrDup(user);
else
usr = TAuthenticate::PromptUser(remote);
sock->Send(usr, kROOTD_SRPUSER);
sock->Recv(stat, kind);
if (kind == kROOTD_ERR) {
TAuthenticate::AuthError("SRPAuthenticate", stat);
return result;
}
// stat == 2 when no SRP support compiled in remote rootd
if (kind == kROOTD_AUTH && stat == 2)
return 2;
struct t_num n, g, s, B, *A;
struct t_client *tc;
char hexbuf[MAXHEXPARAMLEN];
UChar_t buf1[MAXPARAMLEN], buf2[MAXPARAMLEN], buf3[MAXSALTLEN];
// receive n from server
sock->Recv(hexbuf, MAXHEXPARAMLEN, kind);
if (kind != kROOTD_SRPN) {
::Error("SRPAuthenticate", "expected kROOTD_SRPN message");
goto out;
}
n.data = buf1;
n.len = t_fromb64((char*)n.data, hexbuf);
// receive g from server
sock->Recv(hexbuf, MAXHEXPARAMLEN, kind);
if (kind != kROOTD_SRPG) {
::Error("SRPAuthenticate", "expected kROOTD_SRPG message");
goto out;
}
g.data = buf2;
g.len = t_fromb64((char*)g.data, hexbuf);
// receive salt from server
sock->Recv(hexbuf, MAXHEXPARAMLEN, kind);
if (kind != kROOTD_SRPSALT) {
::Error("SRPAuthenticate", "expected kROOTD_SRPSALT message");
goto out;
}
s.data = buf3;
s.len = t_fromb64((char*)s.data, hexbuf);
tc = t_clientopen(usr, &n, &g, &s);
A = t_clientgenexp(tc);
// send A to server
sock->Send(t_tob64(hexbuf, (char*)A->data, A->len), kROOTD_SRPA);
if (passwd && passwd[0])
psswd = StrDup(passwd);
else {
psswd = TAuthenticate::PromptPasswd("SRP password: ");
if (!psswd)
::Error("SRPAuthenticate", "password not set");
}
t_clientpasswd(tc, psswd);
// receive B from server
sock->Recv(hexbuf, MAXHEXPARAMLEN, kind);
if (kind != kROOTD_SRPB) {
::Error("SRPAuthenticate", "expected kROOTD_SRPB message");
goto out;
}
B.data = buf1;
B.len = t_fromb64((char*)B.data, hexbuf);
t_clientgetkey(tc, &B);
// send response to server
sock->Send(t_tohex(hexbuf, (char*)t_clientresponse(tc), RESPONSE_LEN),
kROOTD_SRPRESPONSE);
t_clientclose(tc);
sock->Recv(stat, kind);
if (kind == kROOTD_ERR)
TAuthenticate::AuthError("SRPAuthenticate", stat);
if (kind == kROOTD_AUTH && stat == 1)
result = 1;
out:
delete [] usr;
delete [] psswd;
return result;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2009-2010, Piotr Korzuszek
* 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 <organization> 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 <stdlib.h>
#include <ClanLib/core.h>
#include <ClanLib/display.h>
#include <ClanLib/application.h>
#include <ClanLib/gl.h>
#include <ClanLib/gl1.h>
#include "common/Collections.h"
#include "common/Game.h"
#include "common/Player.h"
#include "common/Properties.h"
#include "gfx/DebugLayer.h"
#include "gfx/GameWindow.h"
#include "gfx/Stage.h"
#include "gfx/race/ui/RaceUI.h"
#include "gfx/scenes/MainMenuScene.h"
#include "gfx/scenes/RaceScene.h"
#include "logic/race/level/Level.h"
#include "network/client/Client.h"
// vsync configuration (should be set by cmake)
#if defined(VSYNC)
const int SYNC_PARAM = 1;
#elif defined(NO_VSYNC)
const int SYNC_PARAM = 0;
#else
const int SYNC_PARAM = 1;
#endif
// default screen size
const int DEF_SCREEN_W = 800;
const int DEF_SCREEN_H = 600;
const bool DEF_FULLSCREEN = false;
const int DEF_OPENGL_VER = 2;
class Application
{
public:
static int main(const std::vector<CL_String> &args);
static void onWindowClose();
/** This method must be called to do a proper drawing */
static void wmRepaint() {}
};
// Create global application object:
// You MUST include this line or the application start-up will fail to
// locate your application object.
CL_ClanApplication app(&Application::main);
int Application::main(const std::vector<CL_String> &args)
{
CL_SetupGL1 *setup_gl1 = NULL;
CL_SetupGL *setup_gl2 = NULL;
try {
// app switches
// use gl1 instead of gl2
static const CL_String SWITCH_GL1 = "-gl1";
// parameter prefix
static const CL_String PREFIX_PARAM = "-P";
// read args properties
static const int PREFIX_PARAM_LEN = PREFIX_PARAM.length();
foreach (const CL_String &arg, args) {
if (arg.substr(0, PREFIX_PARAM_LEN) == PREFIX_PARAM) {
const std::vector<CL_TempString> parts =
CL_StringHelp::split_text(
arg.substr(PREFIX_PARAM_LEN),
"="
);
if (parts.size() == 2) {
Properties::set(parts[0], parts[1]);
} else {
CL_Console::write_line(cl_format("cannot parse %1", arg));
}
}
}
// modules setup
CL_Console::write_line("initializing");
CL_SetupCore setup_core;
CL_ConsoleLogger logger;
CL_SlotContainer slots;
CL_Console::write_line("loading properties");
Properties::load(CONFIG_FILE_CLIENT);
// set opengl version
enum GLVer {
GL1,
GL2
} glver = GL2;
const bool useGL1Opt =
Properties::getPropertyAsInt(CG_OPENGL_VER, DEF_OPENGL_VER) == 1;
if (Collections::contains(args, SWITCH_GL1) || useGL1Opt) {
glver = GL1;
}
cl_log_event("init", "initializing display");
CL_SetupDisplay setup_display;
Gfx::Stage::m_width =
Properties::getInt(CG_SCREEN_WIDTH, DEF_SCREEN_W);
Gfx::Stage::m_height =
Properties::getInt(CG_SCREEN_HEIGHT, DEF_SCREEN_H);
const bool fullscreenOpt =
Properties::getBool(CG_FULLSCREEN, DEF_FULLSCREEN);
cl_log_event("init", "display will be %1 x %2", Gfx::Stage::m_width, Gfx::Stage::m_height);
cl_log_event("init", "initializing gui");
CL_SetupGUI setup_gui;
cl_log_event("init", "initializing network");
CL_SetupNetwork setup_network;
// initialize opengl
switch (glver) {
case GL1:
cl_log_event("init", "initializing OpenGL 1.x");
setup_gl1 = new CL_SetupGL1();
break;
case GL2:
cl_log_event("init", "initializing OpenGL 2.x");
setup_gl2 = new CL_SetupGL();
break;
default:
G_ASSERT(0 && "unknown GLVer option");
}
CL_OpenGLWindowDescription winDesc;
winDesc.set_title("Gear");
winDesc.set_size(
CL_Size(Gfx::Stage::m_width, Gfx::Stage::m_height),
true
);
winDesc.set_fullscreen(fullscreenOpt);
// triple buffering
winDesc.set_flipping_buffers(3);
CL_DisplayWindow displayWindow(winDesc);
// window close action
slots.connect_functor(displayWindow.sig_window_close(), &Application::onWindowClose);
cl_log_event("init", "loading gui components");
CL_GUIWindowManagerTexture windowManager(displayWindow);
CL_GUIManager guiManager;
CL_GUIThemeDefault guiTheme;
guiManager.set_window_manager(windowManager);
if (glver == GL1) {
// Note - If you are using the GL1 target, you will get a perfomance increase by enabling these 2 lines
// It reduces the number of internal CL_FrameBuffer swaps. The GL1 target (OpenGL 1.3), performs this slowly
// Setting the texture group here, lets the GUI Texture Window Manager know the optimum texture size of all root components
CL_TextureGroup texture_group(displayWindow.get_gc(), CL_Size(512, 512));
windowManager.set_texture_group(texture_group);
}
CL_ResourceManager guiResources("resources/GUIThemeAeroPacked/resources.xml");
CL_CSSDocument cssDocument;
cssDocument.load("resources/GUIThemeAeroPacked/theme.css");
guiManager.set_css_document(cssDocument);
guiTheme.set_resources(guiResources);
guiManager.set_theme(guiTheme);
// load resources
cl_log_event("init", "loading general resources");
CL_ResourceManager generalResources("resources/resources.xml");
Gfx::Stage::m_resourceManager = &generalResources;
CL_DisplayWindowDescription guiDesc("Gear");
guiDesc.set_position(CL_Rect(0, 0, Gfx::Stage::getWidth(), Gfx::Stage::getHeight()), true);
CL_GraphicContext &gc = displayWindow.get_gc();
CL_InputContext &ic = displayWindow.get_ic();
Gfx::GameWindow gameWindow(&guiManager, &windowManager, &ic);
// load debug layer
DebugLayer debugLayer;
Gfx::Stage::m_debugLayer = &debugLayer;
cl_log_event("init", "launching main scene");
windowManager.func_repaint().set(&Application::wmRepaint);
MainMenuScene mainMenuScene(&gameWindow);
Gfx::Stage::pushScene(&mainMenuScene);
while(gameWindow.update()) {
gameWindow.draw(gc);
displayWindow.flip(SYNC_PARAM);
}
} catch (CL_Exception &e) {
CL_Console::write_line(e.message);
} catch (std::exception &e) {
CL_Console::write_line(e.what());
}
Properties::save(CONFIG_FILE_CLIENT);
// free resources
if (setup_gl1) {
delete setup_gl1;
}
if (setup_gl2) {
delete setup_gl2;
}
CL_Console::write_line("Thanks for playing :-)");
return 0;
}
void Application::onWindowClose()
{
exit(0);
}
<commit_msg>OpenGL switcher fix to new Properties API<commit_after>/*
* Copyright (c) 2009-2010, Piotr Korzuszek
* 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 <organization> 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 <stdlib.h>
#include <ClanLib/core.h>
#include <ClanLib/display.h>
#include <ClanLib/application.h>
#include <ClanLib/gl.h>
#include <ClanLib/gl1.h>
#include "common/Collections.h"
#include "common/Game.h"
#include "common/Player.h"
#include "common/Properties.h"
#include "gfx/DebugLayer.h"
#include "gfx/GameWindow.h"
#include "gfx/Stage.h"
#include "gfx/race/ui/RaceUI.h"
#include "gfx/scenes/MainMenuScene.h"
#include "gfx/scenes/RaceScene.h"
#include "logic/race/level/Level.h"
#include "network/client/Client.h"
// vsync configuration (should be set by cmake)
#if defined(VSYNC)
const int SYNC_PARAM = 1;
#elif defined(NO_VSYNC)
const int SYNC_PARAM = 0;
#else
const int SYNC_PARAM = 1;
#endif
// default screen size
const int DEF_SCREEN_W = 800;
const int DEF_SCREEN_H = 600;
const bool DEF_FULLSCREEN = false;
const int DEF_OPENGL_VER = 2;
class Application
{
public:
static int main(const std::vector<CL_String> &args);
static void onWindowClose();
/** This method must be called to do a proper drawing */
static void wmRepaint() {}
};
// Create global application object:
// You MUST include this line or the application start-up will fail to
// locate your application object.
CL_ClanApplication app(&Application::main);
int Application::main(const std::vector<CL_String> &args)
{
CL_SetupGL1 *setup_gl1 = NULL;
CL_SetupGL *setup_gl2 = NULL;
try {
// app switches
// use gl1 instead of gl2
static const CL_String SWITCH_GL1 = "-gl1";
// parameter prefix
static const CL_String PREFIX_PARAM = "-P";
// read args properties
static const int PREFIX_PARAM_LEN = PREFIX_PARAM.length();
foreach (const CL_String &arg, args) {
if (arg.substr(0, PREFIX_PARAM_LEN) == PREFIX_PARAM) {
const std::vector<CL_TempString> parts =
CL_StringHelp::split_text(
arg.substr(PREFIX_PARAM_LEN),
"="
);
if (parts.size() == 2) {
Properties::set(parts[0], parts[1]);
} else {
CL_Console::write_line(cl_format("cannot parse %1", arg));
}
}
}
// modules setup
CL_Console::write_line("initializing");
CL_SetupCore setup_core;
CL_ConsoleLogger logger;
CL_SlotContainer slots;
CL_Console::write_line("loading properties");
Properties::load(CONFIG_FILE_CLIENT);
// set opengl version
enum GLVer {
GL1,
GL2
} glver = GL2;
const bool useGL1Opt =
Properties::getInt(CG_OPENGL_VER, DEF_OPENGL_VER) == 1;
if (Collections::contains(args, SWITCH_GL1) || useGL1Opt) {
glver = GL1;
}
cl_log_event("init", "initializing display");
CL_SetupDisplay setup_display;
Gfx::Stage::m_width =
Properties::getInt(CG_SCREEN_WIDTH, DEF_SCREEN_W);
Gfx::Stage::m_height =
Properties::getInt(CG_SCREEN_HEIGHT, DEF_SCREEN_H);
const bool fullscreenOpt =
Properties::getBool(CG_FULLSCREEN, DEF_FULLSCREEN);
cl_log_event("init", "display will be %1 x %2", Gfx::Stage::m_width, Gfx::Stage::m_height);
cl_log_event("init", "initializing gui");
CL_SetupGUI setup_gui;
cl_log_event("init", "initializing network");
CL_SetupNetwork setup_network;
// initialize opengl
switch (glver) {
case GL1:
cl_log_event("init", "initializing OpenGL 1.x");
setup_gl1 = new CL_SetupGL1();
break;
case GL2:
cl_log_event("init", "initializing OpenGL 2.x");
setup_gl2 = new CL_SetupGL();
break;
default:
G_ASSERT(0 && "unknown GLVer option");
}
CL_OpenGLWindowDescription winDesc;
winDesc.set_title("Gear");
winDesc.set_size(
CL_Size(Gfx::Stage::m_width, Gfx::Stage::m_height),
true
);
winDesc.set_fullscreen(fullscreenOpt);
// triple buffering
winDesc.set_flipping_buffers(3);
CL_DisplayWindow displayWindow(winDesc);
// window close action
slots.connect_functor(displayWindow.sig_window_close(), &Application::onWindowClose);
cl_log_event("init", "loading gui components");
CL_GUIWindowManagerTexture windowManager(displayWindow);
CL_GUIManager guiManager;
CL_GUIThemeDefault guiTheme;
guiManager.set_window_manager(windowManager);
if (glver == GL1) {
// Note - If you are using the GL1 target, you will get a perfomance increase by enabling these 2 lines
// It reduces the number of internal CL_FrameBuffer swaps. The GL1 target (OpenGL 1.3), performs this slowly
// Setting the texture group here, lets the GUI Texture Window Manager know the optimum texture size of all root components
CL_TextureGroup texture_group(displayWindow.get_gc(), CL_Size(512, 512));
windowManager.set_texture_group(texture_group);
}
CL_ResourceManager guiResources("resources/GUIThemeAeroPacked/resources.xml");
CL_CSSDocument cssDocument;
cssDocument.load("resources/GUIThemeAeroPacked/theme.css");
guiManager.set_css_document(cssDocument);
guiTheme.set_resources(guiResources);
guiManager.set_theme(guiTheme);
// load resources
cl_log_event("init", "loading general resources");
CL_ResourceManager generalResources("resources/resources.xml");
Gfx::Stage::m_resourceManager = &generalResources;
CL_DisplayWindowDescription guiDesc("Gear");
guiDesc.set_position(CL_Rect(0, 0, Gfx::Stage::getWidth(), Gfx::Stage::getHeight()), true);
CL_GraphicContext &gc = displayWindow.get_gc();
CL_InputContext &ic = displayWindow.get_ic();
Gfx::GameWindow gameWindow(&guiManager, &windowManager, &ic);
// load debug layer
DebugLayer debugLayer;
Gfx::Stage::m_debugLayer = &debugLayer;
cl_log_event("init", "launching main scene");
windowManager.func_repaint().set(&Application::wmRepaint);
MainMenuScene mainMenuScene(&gameWindow);
Gfx::Stage::pushScene(&mainMenuScene);
while(gameWindow.update()) {
gameWindow.draw(gc);
displayWindow.flip(SYNC_PARAM);
}
} catch (CL_Exception &e) {
CL_Console::write_line(e.message);
} catch (std::exception &e) {
CL_Console::write_line(e.what());
}
Properties::save(CONFIG_FILE_CLIENT);
// free resources
if (setup_gl1) {
delete setup_gl1;
}
if (setup_gl2) {
delete setup_gl2;
}
CL_Console::write_line("Thanks for playing :-)");
return 0;
}
void Application::onWindowClose()
{
exit(0);
}
<|endoftext|>
|
<commit_before>#include "magic.h"
using namespace cv;
int main(int argc, char* argv[]){
if(argc < 2){
printf("usage: Magic <Video_Path> [output_dir] [skip_frames] [background]\n");
}
std::string output;
if(argc >= 3) {
output = argv[2];
} else {
output = ".";
}
int skip_frames = 0;
if(argc >= 4) {
skip_frames = std::atoi(argv[3]);
}
VideoCapture cap(argv[1]); // load the video
if(!cap.isOpened()) // check if we succeeded
return -1;
// Write some info about File
int frames = cap.get(CAP_PROP_FRAME_COUNT);
double fps = cap.get(CAP_PROP_FPS);
printf("Number of Frames: %d\n", frames);
printf("FPS: %f\n", fps);
// Contains the working image
Mat dst, in, temp;
if(argc >= 5) {
in = imread(argv[4]);
} else {
cap >> in;
}
// Background
Mat background;
temp = in;
cvtColor(in, background, COLOR_RGB2GRAY);
// threshold(background.clone(), background, 10, 255, THRESH_TOZERO);
std::vector<Vec3f> circles;
/// Apply the Hough Transform to find the circles
HoughCircles(background, circles, HOUGH_GRADIENT, 1, 300, 200, 100, 0, 0);
/// Draw the circles detected
std::ofstream fsJs (output + "/petriDish.json", std::ofstream::out);
for( size_t i = 0; i < circles.size(); i++ )
{
Point2f center(circles[i][0], circles[i][1]);
float radius = circles[i][2];
// circle center
circle(temp, center, 3, Scalar(0,255,0), -1, 8, 0 );
// circle outline
circle(temp, center, radius, Scalar(0,0,255), 3, 8, 0 );
printf("Circle %d with r=%f at x=%f, y=%f\n", i, radius, center.x, center.y);
fsJs << "\"Circle " << i << "\":";
fsJs << "{" << "\"radius\":" << radius << ",\"x\":" << center.x << ",\"y\":" << center.y << "}";
if(i + 1 < circles.size())
fsJs << ",\n";
}
fsJs << "\n}" << std::endl;
fsJs.close();
imshow("image", temp);
waitKey(0);
destroyWindow("image");
waitKey(0);
//Set image parameter
std::vector<int> imageout_params;
imwrite(output + "/bg_circle.tiff", temp, imageout_params);
imwrite(output + "/bg.tiff", background, imageout_params);
//Create mask based on circles[0]
Point2f center(circles[0][0], circles[0][1]);
float radius = circles[0][2];
Mat mask = Mat::zeros(background.rows, background.cols, CV_8UC1);
circle(mask, center, radius, Scalar(255,255,255), -1, 8, 0 ); //-1 means filled
GaussianBlur(background, temp, Size(3,3) , 3, 3, BORDER_DEFAULT);
background = Mat::zeros(background.rows, background.cols, CV_8UC1);
temp.copyTo(background, mask ); // copy values of temp to background if mask is > 0.
int nLabels;
Mat labels(background.size(), CV_32S);
Mat stats, centers;
//stats
int area;
int w;
int h;
double x;
double y;
std::ofstream fs (output + "/positions.csv", std::ofstream::out);
fs << "Frame,Time,Area,x,y\n";
for(int i = 0; i <= frames-1;i++){
cap >> in;
if(i > skip_frames) {
temp = Mat::zeros(background.rows, background.cols, CV_8UC1);
in.copyTo(temp, mask ); // copy values of in to temp if mask is > 0.
cvtColor(temp, dst, COLOR_RGB2GRAY, 0);
absdiff(dst, background, temp);
threshold(temp, dst, 30, 255, THRESH_BINARY);
nLabels = connectedComponentsWithStats(dst, labels, stats, centers, 8, CV_32S);
// skip background i=0
for (int j=1; j< nLabels;j++) {
// get stats
area = stats.at<int>(j,CC_STAT_AREA);
if(area >= 20) {
w = stats.at<int>(j,CC_STAT_WIDTH);
h = stats.at<int>(j,CC_STAT_HEIGHT);
// w/h >= 0.7 && h/w >= 0.7 the bounding box of a circle is roughly a square.
if((h/ double(w)) >=0.7 && (w/ double(h)) >=0.7) {
// The bounding box contains an ellipse and the visible points should be at least 30% of that area.
if(area/(M_PI * (0.5*w) * (0.5*h)) >= 0.3) {
x = centers.at<double>(j,0);
y = centers.at<double>(j,1);
fs << i <<","<< i/fps <<","<< area <<","<< x <<","<< y << "\n";
// printf("%d: Found cc%d at x=%f y=%f ",i, j, x, y);
// printf("with area=%d w=%d h=%d\n", area, w, h);
}
}
}
}
std::cout << "\r" << i << "/" << frames;
// imwrite(output + "/test-"+ std::to_string(i)+".tiff", dst, imageout_params);
}
}
fs << std::endl;
fs.close();
}<commit_msg>fixup: <= instead of <<commit_after>#include "magic.h"
using namespace cv;
int main(int argc, char* argv[]){
if(argc < 2){
printf("usage: Magic <Video_Path> [output_dir] [skip_frames] [background]\n");
}
std::string output;
if(argc >= 3) {
output = argv[2];
} else {
output = ".";
}
int skip_frames = 0;
if(argc >= 4) {
skip_frames = std::atoi(argv[3]);
}
VideoCapture cap(argv[1]); // load the video
if(!cap.isOpened()) // check if we succeeded
return -1;
// Write some info about File
int frames = cap.get(CAP_PROP_FRAME_COUNT);
double fps = cap.get(CAP_PROP_FPS);
printf("Number of Frames: %d\n", frames);
printf("FPS: %f\n", fps);
// Contains the working image
Mat dst, in, temp;
if(argc >= 5) {
in = imread(argv[4]);
} else {
cap >> in;
}
// Background
Mat background;
temp = in;
cvtColor(in, background, COLOR_RGB2GRAY);
// threshold(background.clone(), background, 10, 255, THRESH_TOZERO);
std::vector<Vec3f> circles;
/// Apply the Hough Transform to find the circles
HoughCircles(background, circles, HOUGH_GRADIENT, 1, 300, 200, 100, 0, 0);
/// Draw the circles detected
std::ofstream fsJs (output + "/petriDish.json", std::ofstream::out);
for( size_t i = 0; i < circles.size(); i++ )
{
Point2f center(circles[i][0], circles[i][1]);
float radius = circles[i][2];
// circle center
circle(temp, center, 3, Scalar(0,255,0), -1, 8, 0 );
// circle outline
circle(temp, center, radius, Scalar(0,0,255), 3, 8, 0 );
printf("Circle %d with r=%f at x=%f, y=%f\n", i, radius, center.x, center.y);
fsJs << "\"Circle " << i << "\":";
fsJs << "{" << "\"radius\":" << radius << ",\"x\":" << center.x << ",\"y\":" << center.y << "}";
if(i + 1 < circles.size())
fsJs << ",\n";
}
fsJs << "\n}" << std::endl;
fsJs.close();
imshow("image", temp);
waitKey(0);
destroyWindow("image");
waitKey(0);
//Set image parameter
std::vector<int> imageout_params;
imwrite(output + "/bg_circle.tiff", temp, imageout_params);
imwrite(output + "/bg.tiff", background, imageout_params);
//Create mask based on circles[0]
Point2f center(circles[0][0], circles[0][1]);
float radius = circles[0][2];
Mat mask = Mat::zeros(background.rows, background.cols, CV_8UC1);
circle(mask, center, radius, Scalar(255,255,255), -1, 8, 0 ); //-1 means filled
GaussianBlur(background, temp, Size(3,3) , 3, 3, BORDER_DEFAULT);
background = Mat::zeros(background.rows, background.cols, CV_8UC1);
temp.copyTo(background, mask ); // copy values of temp to background if mask is > 0.
int nLabels;
Mat labels(background.size(), CV_32S);
Mat stats, centers;
//stats
int area;
int w;
int h;
double x;
double y;
std::ofstream fs (output + "/positions.csv", std::ofstream::out);
fs << "Frame,Time,Area,x,y\n";
for(int i = 0; i < frames-1;i++){
cap >> in;
if(i > skip_frames) {
temp = Mat::zeros(background.rows, background.cols, CV_8UC1);
in.copyTo(temp, mask ); // copy values of in to temp if mask is > 0.
cvtColor(temp, dst, COLOR_RGB2GRAY, 0);
absdiff(dst, background, temp);
threshold(temp, dst, 30, 255, THRESH_BINARY);
nLabels = connectedComponentsWithStats(dst, labels, stats, centers, 8, CV_32S);
// skip background i=0
for (int j=1; j< nLabels;j++) {
// get stats
area = stats.at<int>(j,CC_STAT_AREA);
if(area >= 20) {
w = stats.at<int>(j,CC_STAT_WIDTH);
h = stats.at<int>(j,CC_STAT_HEIGHT);
// w/h >= 0.7 && h/w >= 0.7 the bounding box of a circle is roughly a square.
if((h/ double(w)) >=0.7 && (w/ double(h)) >=0.7) {
// The bounding box contains an ellipse and the visible points should be at least 30% of that area.
if(area/(M_PI * (0.5*w) * (0.5*h)) >= 0.3) {
x = centers.at<double>(j,0);
y = centers.at<double>(j,1);
fs << i <<","<< i/fps <<","<< area <<","<< x <<","<< y << "\n";
// printf("%d: Found cc%d at x=%f y=%f ",i, j, x, y);
// printf("with area=%d w=%d h=%d\n", area, w, h);
}
}
}
}
std::cout << "\r" << i << "/" << frames;
// imwrite(output + "/test-"+ std::to_string(i)+".tiff", dst, imageout_params);
}
}
fs << std::endl;
fs.close();
}<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2015 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/>.
*/
#pragma once
#include "sstables.hh"
#include "consumer.hh"
#include "downsampling.hh"
namespace sstables {
class index_consumer {
uint64_t max_quantity;
public:
index_list indexes;
index_consumer(uint64_t q) : max_quantity(q) {
indexes.reserve(q);
}
bool should_continue() {
return indexes.size() < max_quantity;
}
void consume_entry(index_entry&& ie, uint64_t offset) {
indexes.push_back(std::move(ie));
}
void reset() {
indexes.clear();
}
};
// IndexConsumer is a concept that implements:
//
// bool should_continue();
// void consume_entry(index_entry&& ie, uintt64_t offset);
template <class IndexConsumer>
class index_consume_entry_context: public data_consumer::continuous_data_consumer<index_consume_entry_context<IndexConsumer>> {
using proceed = data_consumer::proceed;
using continuous_data_consumer = data_consumer::continuous_data_consumer<index_consume_entry_context<IndexConsumer>>;
private:
IndexConsumer& _consumer;
uint64_t _entry_offset;
enum class state {
START,
KEY_SIZE,
KEY_BYTES,
POSITION,
PROMOTED_SIZE,
PROMOTED_BYTES,
CONSUME_ENTRY,
} _state = state::START;
temporary_buffer<char> _key;
temporary_buffer<char> _promoted;
public:
void verify_end_state() {
}
bool non_consuming() const {
return ((_state == state::CONSUME_ENTRY) || (_state == state::START) ||
((_state == state::PROMOTED_BYTES) && (continuous_data_consumer::_prestate == continuous_data_consumer::prestate::NONE)));
}
proceed process_state(temporary_buffer<char>& data) {
switch (_state) {
// START comes first, to make the handling of the 0-quantity case simpler
case state::START:
if (!_consumer.should_continue()) {
return proceed::no;
}
_state = state::KEY_SIZE;
break;
case state::KEY_SIZE:
if (this->read_16(data) != continuous_data_consumer::read_status::ready) {
_state = state::KEY_BYTES;
break;
}
case state::KEY_BYTES:
if (this->read_bytes(data, this->_u16, _key) != continuous_data_consumer::read_status::ready) {
_state = state::POSITION;
break;
}
case state::POSITION:
if (this->read_64(data) != continuous_data_consumer::read_status::ready) {
_state = state::PROMOTED_SIZE;
break;
}
case state::PROMOTED_SIZE:
if (this->read_32(data) != continuous_data_consumer::read_status::ready) {
_state = state::PROMOTED_BYTES;
break;
}
case state::PROMOTED_BYTES:
if (this->read_bytes(data, this->_u32, _promoted) != continuous_data_consumer::read_status::ready) {
_state = state::CONSUME_ENTRY;
break;
}
case state::CONSUME_ENTRY: {
auto len = (_key.size() + _promoted.size() + 14);
_consumer.consume_entry(index_entry(std::move(_key), this->_u64, std::move(_promoted)), _entry_offset);
_entry_offset += len;
_state = state::START;
}
break;
default:
throw malformed_sstable_exception("unknown state");
}
return proceed::yes;
}
index_consume_entry_context(IndexConsumer& consumer,
input_stream<char>&& input, uint64_t start, uint64_t maxlen)
: continuous_data_consumer(std::move(input), start, maxlen)
, _consumer(consumer), _entry_offset(start)
{}
void reset(uint64_t offset) {
_state = state::START;
_entry_offset = offset;
_consumer.reset();
}
};
// Less-comparator for lookups in the partition index.
class index_comparator {
const schema& _s;
public:
index_comparator(const schema& s) : _s(s) {}
int tri_cmp(key_view k2, dht::ring_position_view pos) const {
return -pos.tri_compare(_s, k2);
}
bool operator()(const summary_entry& e, dht::ring_position_view rp) const {
return tri_cmp(e.get_key(), rp) < 0;
}
bool operator()(const index_entry& e, dht::ring_position_view rp) const {
return tri_cmp(e.get_key(), rp) < 0;
}
bool operator()(dht::ring_position_view rp, const summary_entry& e) const {
return tri_cmp(e.get_key(), rp) > 0;
}
bool operator()(dht::ring_position_view rp, const index_entry& e) const {
return tri_cmp(e.get_key(), rp) > 0;
}
};
class index_reader {
shared_sstable _sstable;
const io_priority_class& _pc;
struct reader {
index_consumer _consumer;
index_consume_entry_context<index_consumer> _context;
uint64_t _current_summary_idx;
static auto create_file_input_stream(shared_sstable sst, const io_priority_class& pc, uint64_t begin, uint64_t end) {
file_input_stream_options options;
options.buffer_size = sst->sstable_buffer_size;
options.read_ahead = 2;
options.io_priority_class = pc;
return make_file_input_stream(sst->_index_file, begin, end - begin, std::move(options));
}
reader(shared_sstable sst, const io_priority_class& pc, uint64_t begin, uint64_t end, uint64_t quantity)
: _consumer(quantity)
, _context(_consumer, create_file_input_stream(sst, pc, begin, end), begin, end - begin)
{ }
};
stdx::optional<reader> _reader;
index_list _previous_bucket;
static constexpr uint64_t invalid_idx = std::numeric_limits<uint64_t>::max();
uint64_t _previous_summary_idx = invalid_idx;
private:
future<> read_index_entries(uint64_t summary_idx) {
assert(!_reader || _reader->_current_summary_idx <= summary_idx);
if (_reader && _reader->_current_summary_idx == summary_idx) {
return make_ready_future<>();
}
auto& summary = _sstable->get_summary();
if (summary_idx >= summary.header.size) {
return close_reader().finally([this] {
_reader = stdx::nullopt;
});
}
uint64_t position = summary.entries[summary_idx].position;
uint64_t quantity = downsampling::get_effective_index_interval_after_index(summary_idx, summary.header.sampling_level,
summary.header.min_index_interval);
uint64_t end;
if (summary_idx + 1 >= summary.header.size) {
end = _sstable->index_size();
} else {
end = summary.entries[summary_idx + 1].position;
}
return close_reader().then_wrapped([this, position, end, quantity, summary_idx] (auto&& f) {
try {
f.get();
_reader.emplace(_sstable, _pc, position, end, quantity);
} catch (...) {
_reader = stdx::nullopt;
throw;
}
_reader->_current_summary_idx = summary_idx;
return _reader->_context.consume_input(_reader->_context);
});
}
future<uint64_t> data_end_position(uint64_t summary_idx) {
// We should only go to the end of the file if we are in the last summary group.
// Otherwise, we will determine the end position of the current data read by looking
// at the first index in the next summary group.
auto& summary = _sstable->get_summary();
if (size_t(summary_idx + 1) >= summary.entries.size()) {
return make_ready_future<uint64_t>(_sstable->data_size());
}
return read_index_entries(summary_idx + 1).then([this] {
return _reader->_consumer.indexes.front().position();
});
}
future<uint64_t> start_position(const schema& s, const dht::partition_range& range) {
return range.start() ? lower_bound(s, dht::ring_position_view(range.start()->value(),
dht::ring_position_view::after_key(!range.start()->is_inclusive())))
: make_ready_future<uint64_t>(0);
}
future<uint64_t> end_position(const schema& s, const dht::partition_range& range) {
return range.end() ? lower_bound(s, dht::ring_position_view(range.end()->value(),
dht::ring_position_view::after_key(range.end()->is_inclusive())))
: make_ready_future<uint64_t>(_sstable->data_size());
}
public:
index_reader(shared_sstable sst, const io_priority_class& pc)
: _sstable(std::move(sst))
, _pc(pc)
{ }
future<index_list> get_index_entries(uint64_t summary_idx) {
return read_index_entries(summary_idx).then([this] {
return _reader ? std::move(_reader->_consumer.indexes) : index_list();
});
}
private:
future<uint64_t> lower_bound(const schema& s, dht::ring_position_view pos) {
auto& summary = _sstable->get_summary();
uint64_t summary_idx = std::distance(std::begin(summary.entries),
std::lower_bound(summary.entries.begin(), summary.entries.end(), pos, index_comparator(s)));
if (summary_idx == 0) {
return make_ready_future<uint64_t>(0);
}
--summary_idx;
// Despite the requirement that the values of 'pos' in subsequent calls
// are increasing we still may encounter a situation when we try to read
// the previous bucket.
// For example, let's say we have index like this:
// summary: A K ...
// index: A C D F K M N O ...
// Now, we want to get positions for range [G, J]. We start with [G,
// summary look up will tel us to check the first bucket. However, there
// is no G in that bucket so we read the following one to get the
// position (see data_end_position()). After we've got it, it's time to
// get J] position. Again, summary points us to the first bucket and we
// hit an assert since the reader is already at the second bucket and we
// cannot go backward.
// The solution is this condition above. If our lookup requires reading
// the previous bucket we assume that the entry doesn't exist and return
// the position of the first one in the current index bucket.
if (_reader && summary_idx + 1 == _reader->_current_summary_idx) {
return make_ready_future<uint64_t>(_reader->_consumer.indexes.front().position());
}
return read_index_entries(summary_idx).then([this, &s, pos, summary_idx] {
if (!_reader) {
return data_end_position(summary_idx);
}
auto& il = _reader->_consumer.indexes;
auto i = std::lower_bound(il.begin(), il.end(), pos, index_comparator(s));
if (i == il.end()) {
return data_end_position(summary_idx);
}
return make_ready_future<uint64_t>(i->position());
});
}
future<> close_reader() {
if (_reader) {
return _reader->_context.close();
}
return make_ready_future<>();
}
public:
future<sstable::disk_read_range> get_disk_read_range(const schema& s, const dht::partition_range& range) {
return start_position(s, range).then([this, &s, &range] (uint64_t start) {
return end_position(s, range).then([&s, &range, start] (uint64_t end) {
return sstable::disk_read_range(start, end);
});
});
}
future<> close() {
return close_reader();
}
};
}
<commit_msg>sstables: index_reader: Narrow down summary range during lookup<commit_after>/*
* Copyright (C) 2015 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/>.
*/
#pragma once
#include "sstables.hh"
#include "consumer.hh"
#include "downsampling.hh"
namespace sstables {
class index_consumer {
uint64_t max_quantity;
public:
index_list indexes;
index_consumer(uint64_t q) : max_quantity(q) {
indexes.reserve(q);
}
bool should_continue() {
return indexes.size() < max_quantity;
}
void consume_entry(index_entry&& ie, uint64_t offset) {
indexes.push_back(std::move(ie));
}
void reset() {
indexes.clear();
}
};
// IndexConsumer is a concept that implements:
//
// bool should_continue();
// void consume_entry(index_entry&& ie, uintt64_t offset);
template <class IndexConsumer>
class index_consume_entry_context: public data_consumer::continuous_data_consumer<index_consume_entry_context<IndexConsumer>> {
using proceed = data_consumer::proceed;
using continuous_data_consumer = data_consumer::continuous_data_consumer<index_consume_entry_context<IndexConsumer>>;
private:
IndexConsumer& _consumer;
uint64_t _entry_offset;
enum class state {
START,
KEY_SIZE,
KEY_BYTES,
POSITION,
PROMOTED_SIZE,
PROMOTED_BYTES,
CONSUME_ENTRY,
} _state = state::START;
temporary_buffer<char> _key;
temporary_buffer<char> _promoted;
public:
void verify_end_state() {
}
bool non_consuming() const {
return ((_state == state::CONSUME_ENTRY) || (_state == state::START) ||
((_state == state::PROMOTED_BYTES) && (continuous_data_consumer::_prestate == continuous_data_consumer::prestate::NONE)));
}
proceed process_state(temporary_buffer<char>& data) {
switch (_state) {
// START comes first, to make the handling of the 0-quantity case simpler
case state::START:
if (!_consumer.should_continue()) {
return proceed::no;
}
_state = state::KEY_SIZE;
break;
case state::KEY_SIZE:
if (this->read_16(data) != continuous_data_consumer::read_status::ready) {
_state = state::KEY_BYTES;
break;
}
case state::KEY_BYTES:
if (this->read_bytes(data, this->_u16, _key) != continuous_data_consumer::read_status::ready) {
_state = state::POSITION;
break;
}
case state::POSITION:
if (this->read_64(data) != continuous_data_consumer::read_status::ready) {
_state = state::PROMOTED_SIZE;
break;
}
case state::PROMOTED_SIZE:
if (this->read_32(data) != continuous_data_consumer::read_status::ready) {
_state = state::PROMOTED_BYTES;
break;
}
case state::PROMOTED_BYTES:
if (this->read_bytes(data, this->_u32, _promoted) != continuous_data_consumer::read_status::ready) {
_state = state::CONSUME_ENTRY;
break;
}
case state::CONSUME_ENTRY: {
auto len = (_key.size() + _promoted.size() + 14);
_consumer.consume_entry(index_entry(std::move(_key), this->_u64, std::move(_promoted)), _entry_offset);
_entry_offset += len;
_state = state::START;
}
break;
default:
throw malformed_sstable_exception("unknown state");
}
return proceed::yes;
}
index_consume_entry_context(IndexConsumer& consumer,
input_stream<char>&& input, uint64_t start, uint64_t maxlen)
: continuous_data_consumer(std::move(input), start, maxlen)
, _consumer(consumer), _entry_offset(start)
{}
void reset(uint64_t offset) {
_state = state::START;
_entry_offset = offset;
_consumer.reset();
}
};
// Less-comparator for lookups in the partition index.
class index_comparator {
const schema& _s;
public:
index_comparator(const schema& s) : _s(s) {}
int tri_cmp(key_view k2, dht::ring_position_view pos) const {
return -pos.tri_compare(_s, k2);
}
bool operator()(const summary_entry& e, dht::ring_position_view rp) const {
return tri_cmp(e.get_key(), rp) < 0;
}
bool operator()(const index_entry& e, dht::ring_position_view rp) const {
return tri_cmp(e.get_key(), rp) < 0;
}
bool operator()(dht::ring_position_view rp, const summary_entry& e) const {
return tri_cmp(e.get_key(), rp) > 0;
}
bool operator()(dht::ring_position_view rp, const index_entry& e) const {
return tri_cmp(e.get_key(), rp) > 0;
}
};
class index_reader {
shared_sstable _sstable;
const io_priority_class& _pc;
struct reader {
index_consumer _consumer;
index_consume_entry_context<index_consumer> _context;
uint64_t _current_summary_idx;
static auto create_file_input_stream(shared_sstable sst, const io_priority_class& pc, uint64_t begin, uint64_t end) {
file_input_stream_options options;
options.buffer_size = sst->sstable_buffer_size;
options.read_ahead = 2;
options.io_priority_class = pc;
return make_file_input_stream(sst->_index_file, begin, end - begin, std::move(options));
}
reader(shared_sstable sst, const io_priority_class& pc, uint64_t begin, uint64_t end, uint64_t quantity)
: _consumer(quantity)
, _context(_consumer, create_file_input_stream(sst, pc, begin, end), begin, end - begin)
{ }
};
stdx::optional<reader> _reader;
index_list _previous_bucket;
uint64_t _previous_summary_idx = 0;
private:
future<> read_index_entries(uint64_t summary_idx) {
assert(!_reader || _reader->_current_summary_idx <= summary_idx);
if (_reader && _reader->_current_summary_idx == summary_idx) {
return make_ready_future<>();
}
auto& summary = _sstable->get_summary();
if (summary_idx >= summary.header.size) {
return close_reader().finally([this] {
_reader = stdx::nullopt;
});
}
uint64_t position = summary.entries[summary_idx].position;
uint64_t quantity = downsampling::get_effective_index_interval_after_index(summary_idx, summary.header.sampling_level,
summary.header.min_index_interval);
uint64_t end;
if (summary_idx + 1 >= summary.header.size) {
end = _sstable->index_size();
} else {
end = summary.entries[summary_idx + 1].position;
}
return close_reader().then_wrapped([this, position, end, quantity, summary_idx] (auto&& f) {
try {
f.get();
_reader.emplace(_sstable, _pc, position, end, quantity);
} catch (...) {
_reader = stdx::nullopt;
throw;
}
_reader->_current_summary_idx = summary_idx;
return _reader->_context.consume_input(_reader->_context);
});
}
future<uint64_t> data_end_position(uint64_t summary_idx) {
// We should only go to the end of the file if we are in the last summary group.
// Otherwise, we will determine the end position of the current data read by looking
// at the first index in the next summary group.
auto& summary = _sstable->get_summary();
if (size_t(summary_idx + 1) >= summary.entries.size()) {
return make_ready_future<uint64_t>(_sstable->data_size());
}
return read_index_entries(summary_idx + 1).then([this] {
return _reader->_consumer.indexes.front().position();
});
}
future<uint64_t> start_position(const schema& s, const dht::partition_range& range) {
return range.start() ? lower_bound(s, dht::ring_position_view(range.start()->value(),
dht::ring_position_view::after_key(!range.start()->is_inclusive())))
: make_ready_future<uint64_t>(0);
}
future<uint64_t> end_position(const schema& s, const dht::partition_range& range) {
return range.end() ? lower_bound(s, dht::ring_position_view(range.end()->value(),
dht::ring_position_view::after_key(range.end()->is_inclusive())))
: make_ready_future<uint64_t>(_sstable->data_size());
}
public:
index_reader(shared_sstable sst, const io_priority_class& pc)
: _sstable(std::move(sst))
, _pc(pc)
{ }
future<index_list> get_index_entries(uint64_t summary_idx) {
return read_index_entries(summary_idx).then([this] {
return _reader ? std::move(_reader->_consumer.indexes) : index_list();
});
}
private:
future<uint64_t> lower_bound(const schema& s, dht::ring_position_view pos) {
auto& summary = _sstable->get_summary();
_previous_summary_idx = std::distance(std::begin(summary.entries),
std::lower_bound(summary.entries.begin() + _previous_summary_idx, summary.entries.end(), pos, index_comparator(s)));
if (_previous_summary_idx == 0) {
return make_ready_future<uint64_t>(0);
}
auto summary_idx = _previous_summary_idx - 1;
// Despite the requirement that the values of 'pos' in subsequent calls
// are increasing we still may encounter a situation when we try to read
// the previous bucket.
// For example, let's say we have index like this:
// summary: A K ...
// index: A C D F K M N O ...
// Now, we want to get positions for range [G, J]. We start with [G,
// summary look up will tel us to check the first bucket. However, there
// is no G in that bucket so we read the following one to get the
// position (see data_end_position()). After we've got it, it's time to
// get J] position. Again, summary points us to the first bucket and we
// hit an assert since the reader is already at the second bucket and we
// cannot go backward.
// The solution is this condition above. If our lookup requires reading
// the previous bucket we assume that the entry doesn't exist and return
// the position of the first one in the current index bucket.
if (_reader && summary_idx + 1 == _reader->_current_summary_idx) {
return make_ready_future<uint64_t>(_reader->_consumer.indexes.front().position());
}
return read_index_entries(summary_idx).then([this, &s, pos, summary_idx] {
if (!_reader) {
return data_end_position(summary_idx);
}
auto& il = _reader->_consumer.indexes;
auto i = std::lower_bound(il.begin(), il.end(), pos, index_comparator(s));
if (i == il.end()) {
return data_end_position(summary_idx);
}
return make_ready_future<uint64_t>(i->position());
});
}
future<> close_reader() {
if (_reader) {
return _reader->_context.close();
}
return make_ready_future<>();
}
public:
future<sstable::disk_read_range> get_disk_read_range(const schema& s, const dht::partition_range& range) {
return start_position(s, range).then([this, &s, &range] (uint64_t start) {
return end_position(s, range).then([&s, &range, start] (uint64_t end) {
return sstable::disk_read_range(start, end);
});
});
}
future<> close() {
return close_reader();
}
};
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2006, Arvid Norberg
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 author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
*/
#ifndef ROUTING_TABLE_HPP
#define ROUTING_TABLE_HPP
#include <vector>
#include <deque>
#include <boost/cstdint.hpp>
#include <boost/iterator/iterator_facade.hpp>
#include <boost/iterator/iterator_categories.hpp>
#include <boost/utility.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/array.hpp>
#include <set>
#include <libtorrent/kademlia/logging.hpp>
#include <libtorrent/kademlia/node_id.hpp>
#include <libtorrent/kademlia/node_entry.hpp>
#include <libtorrent/session_settings.hpp>
#include <libtorrent/size_type.hpp>
#include <libtorrent/assert.hpp>
namespace libtorrent { namespace dht
{
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_DECLARE_LOG(table);
#endif
typedef std::vector<node_entry> bucket_t;
// differences in the implementation from the description in
// the paper:
//
// * The routing table tree is not allocated dynamically, there
// are always 160 buckets.
// * Nodes are not marked as being stale, they keep a counter
// that tells how many times in a row they have failed. When
// a new node is to be inserted, the node that has failed
// the most times is replaced. If none of the nodes in the
// bucket has failed, then it is put in the replacement
// cache (just like in the paper).
class routing_table;
namespace aux
{
// Iterates over a flattened routing_table structure.
class routing_table_iterator
: public boost::iterator_facade<
routing_table_iterator
, node_entry const
, boost::forward_traversal_tag
>
{
public:
routing_table_iterator()
{
}
private:
friend class libtorrent::dht::routing_table;
friend class boost::iterator_core_access;
typedef boost::array<std::pair<bucket_t, bucket_t>, 160>::const_iterator
bucket_iterator_t;
routing_table_iterator(
bucket_iterator_t begin
, bucket_iterator_t end)
: m_bucket_iterator(begin)
, m_bucket_end(end)
, m_iterator(begin != end ? begin->first.begin() : bucket_t::const_iterator())
{
if (m_bucket_iterator == m_bucket_end) return;
while (m_iterator == m_bucket_iterator->first.end())
{
if (++m_bucket_iterator == m_bucket_end)
break;
m_iterator = m_bucket_iterator->first.begin();
}
}
bool equal(routing_table_iterator const& other) const
{
return m_bucket_iterator == other.m_bucket_iterator
&& (m_bucket_iterator == m_bucket_end
|| m_iterator == other.m_iterator);
}
void increment()
{
TORRENT_ASSERT(m_bucket_iterator != m_bucket_end);
++m_iterator;
while (m_iterator == m_bucket_iterator->first.end())
{
if (++m_bucket_iterator == m_bucket_end)
break;
m_iterator = m_bucket_iterator->first.begin();
}
}
node_entry const& dereference() const
{
TORRENT_ASSERT(m_bucket_iterator != m_bucket_end);
return *m_iterator;
}
bucket_iterator_t m_bucket_iterator;
bucket_iterator_t m_bucket_end;
bucket_t::const_iterator m_iterator;
};
} // namespace aux
class routing_table
{
public:
typedef aux::routing_table_iterator iterator;
typedef iterator const_iterator;
routing_table(node_id const& id, int bucket_size
, dht_settings const& settings);
void node_failed(node_id const& id);
// adds an endpoint that will never be added to
// the routing table
void add_router_node(udp::endpoint router);
// iterates over the router nodes added
typedef std::set<udp::endpoint>::const_iterator router_iterator;
router_iterator router_begin() const { return m_router_nodes.begin(); }
router_iterator router_end() const { return m_router_nodes.end(); }
// this function is called every time the node sees
// a sign of a node being alive. This node will either
// be inserted in the k-buckets or be moved to the top
// of its bucket.
bool node_seen(node_id const& id, udp::endpoint addr);
// returns time when the given bucket needs another refresh.
// if the given bucket is empty but there are nodes
// in a bucket closer to us, or if the bucket is non-empty and
// the time from the last activity is more than 15 minutes
ptime next_refresh(int bucket);
// fills the vector with the count nodes from our buckets that
// are nearest to the given id.
void find_node(node_id const& id, std::vector<node_entry>& l
, bool include_self, int count = 0);
// returns true if the given node would be placed in a bucket
// that is not full. If the node already exists in the table
// this function returns false
bool need_node(node_id const& id);
// this will set the given bucket's latest activity
// to the current time
void touch_bucket(int bucket);
int bucket_size(int bucket)
{
TORRENT_ASSERT(bucket >= 0 && bucket < 160);
return (int)m_buckets[bucket].first.size();
}
int bucket_size() const { return m_bucket_size; }
iterator begin() const;
iterator end() const;
boost::tuple<int, int> size() const;
size_type num_global_nodes() const;
// returns true if there are no working nodes
// in the routing table
bool need_bootstrap() const;
int num_active_buckets() const
{ return 160 - m_lowest_active_bucket + 1; }
void replacement_cache(bucket_t& nodes) const;
#ifdef TORRENT_DHT_VERBOSE_LOGGING
// used for debug and monitoring purposes. This will print out
// the state of the routing table to the given stream
void print_state(std::ostream& os) const;
#endif
private:
// constant called k in paper
int m_bucket_size;
dht_settings const& m_settings;
// 160 (k-bucket, replacement cache) pairs
typedef boost::array<std::pair<bucket_t, bucket_t>, 160> table_t;
table_t m_buckets;
// timestamps of the last activity in each bucket
typedef boost::array<ptime, 160> table_activity_t;
table_activity_t m_bucket_activity;
node_id m_id; // our own node id
// this is a set of all the endpoints that have
// been identified as router nodes. They will
// be used in searches, but they will never
// be added to the routing table.
std::set<udp::endpoint> m_router_nodes;
// this is the lowest bucket index with nodes in it
int m_lowest_active_bucket;
};
} } // namespace libtorrent::dht
#endif // ROUTING_TABLE_HPP
<commit_msg>made routing table support safe iterators on gcc<commit_after>/*
Copyright (c) 2006, Arvid Norberg
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 author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
*/
#ifndef ROUTING_TABLE_HPP
#define ROUTING_TABLE_HPP
#include <vector>
#include <deque>
#include <boost/cstdint.hpp>
#include <boost/iterator/iterator_facade.hpp>
#include <boost/iterator/iterator_categories.hpp>
#include <boost/utility.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/array.hpp>
#include <set>
#include <libtorrent/kademlia/logging.hpp>
#include <libtorrent/kademlia/node_id.hpp>
#include <libtorrent/kademlia/node_entry.hpp>
#include <libtorrent/session_settings.hpp>
#include <libtorrent/size_type.hpp>
#include <libtorrent/assert.hpp>
namespace libtorrent { namespace dht
{
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_DECLARE_LOG(table);
#endif
typedef std::vector<node_entry> bucket_t;
// differences in the implementation from the description in
// the paper:
//
// * The routing table tree is not allocated dynamically, there
// are always 160 buckets.
// * Nodes are not marked as being stale, they keep a counter
// that tells how many times in a row they have failed. When
// a new node is to be inserted, the node that has failed
// the most times is replaced. If none of the nodes in the
// bucket has failed, then it is put in the replacement
// cache (just like in the paper).
class routing_table;
namespace aux
{
// Iterates over a flattened routing_table structure.
class routing_table_iterator
: public boost::iterator_facade<
routing_table_iterator
, node_entry const
, boost::forward_traversal_tag
>
{
public:
routing_table_iterator()
{
}
private:
friend class libtorrent::dht::routing_table;
friend class boost::iterator_core_access;
typedef boost::array<std::pair<bucket_t, bucket_t>, 160>::const_iterator
bucket_iterator_t;
routing_table_iterator(
bucket_iterator_t begin
, bucket_iterator_t end)
: m_bucket_iterator(begin)
, m_bucket_end(end)
{
if (m_bucket_iterator == m_bucket_end) return;
m_iterator = begin->first.begin();
while (m_iterator == m_bucket_iterator->first.end())
{
if (++m_bucket_iterator == m_bucket_end)
break;
m_iterator = m_bucket_iterator->first.begin();
}
}
bool equal(routing_table_iterator const& other) const
{
return m_bucket_iterator == other.m_bucket_iterator
&& (m_bucket_iterator == m_bucket_end
|| *m_iterator == other.m_iterator);
}
void increment()
{
TORRENT_ASSERT(m_bucket_iterator != m_bucket_end);
++*m_iterator;
while (*m_iterator == m_bucket_iterator->first.end())
{
if (++m_bucket_iterator == m_bucket_end)
break;
m_iterator = m_bucket_iterator->first.begin();
}
}
node_entry const& dereference() const
{
TORRENT_ASSERT(m_bucket_iterator != m_bucket_end);
return **m_iterator;
}
bucket_iterator_t m_bucket_iterator;
bucket_iterator_t m_bucket_end;
// when debug iterators are enabled, default constructed
// iterators are not allowed to be copied. In the case
// where the routing table is empty, m_iterator would be
// default constructed and not copyable.
boost::optional<bucket_t::const_iterator> m_iterator;
};
} // namespace aux
class routing_table
{
public:
typedef aux::routing_table_iterator iterator;
typedef iterator const_iterator;
routing_table(node_id const& id, int bucket_size
, dht_settings const& settings);
void node_failed(node_id const& id);
// adds an endpoint that will never be added to
// the routing table
void add_router_node(udp::endpoint router);
// iterates over the router nodes added
typedef std::set<udp::endpoint>::const_iterator router_iterator;
router_iterator router_begin() const { return m_router_nodes.begin(); }
router_iterator router_end() const { return m_router_nodes.end(); }
// this function is called every time the node sees
// a sign of a node being alive. This node will either
// be inserted in the k-buckets or be moved to the top
// of its bucket.
bool node_seen(node_id const& id, udp::endpoint addr);
// returns time when the given bucket needs another refresh.
// if the given bucket is empty but there are nodes
// in a bucket closer to us, or if the bucket is non-empty and
// the time from the last activity is more than 15 minutes
ptime next_refresh(int bucket);
// fills the vector with the count nodes from our buckets that
// are nearest to the given id.
void find_node(node_id const& id, std::vector<node_entry>& l
, bool include_self, int count = 0);
// returns true if the given node would be placed in a bucket
// that is not full. If the node already exists in the table
// this function returns false
bool need_node(node_id const& id);
// this will set the given bucket's latest activity
// to the current time
void touch_bucket(int bucket);
int bucket_size(int bucket)
{
TORRENT_ASSERT(bucket >= 0 && bucket < 160);
return (int)m_buckets[bucket].first.size();
}
int bucket_size() const { return m_bucket_size; }
iterator begin() const;
iterator end() const;
boost::tuple<int, int> size() const;
size_type num_global_nodes() const;
// returns true if there are no working nodes
// in the routing table
bool need_bootstrap() const;
int num_active_buckets() const
{ return 160 - m_lowest_active_bucket + 1; }
void replacement_cache(bucket_t& nodes) const;
#ifdef TORRENT_DHT_VERBOSE_LOGGING
// used for debug and monitoring purposes. This will print out
// the state of the routing table to the given stream
void print_state(std::ostream& os) const;
#endif
private:
// constant called k in paper
int m_bucket_size;
dht_settings const& m_settings;
// 160 (k-bucket, replacement cache) pairs
typedef boost::array<std::pair<bucket_t, bucket_t>, 160> table_t;
table_t m_buckets;
// timestamps of the last activity in each bucket
typedef boost::array<ptime, 160> table_activity_t;
table_activity_t m_bucket_activity;
node_id m_id; // our own node id
// this is a set of all the endpoints that have
// been identified as router nodes. They will
// be used in searches, but they will never
// be added to the routing table.
std::set<udp::endpoint> m_router_nodes;
// this is the lowest bucket index with nodes in it
int m_lowest_active_bucket;
};
} } // namespace libtorrent::dht
#endif // ROUTING_TABLE_HPP
<|endoftext|>
|
<commit_before>/*
** Anitomy
** Copyright (C) 2014-2015, Eren Okka
**
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include "keyword.h"
#include "token.h"
namespace anitomy {
KeywordManager keyword_manager;
KeywordOptions::KeywordOptions(bool identifiable, bool searchable, bool valid)
: identifiable(identifiable), searchable(searchable), valid(valid) {
}
Keyword::Keyword(ElementCategory category, const KeywordOptions& options)
: category(category), options(options) {
}
////////////////////////////////////////////////////////////////////////////////
KeywordManager::KeywordManager() {
const KeywordOptions options_default;
const KeywordOptions options_invalid(true, true, false);
const KeywordOptions options_unidentifiable(false, true, true);
const KeywordOptions options_unidentifiable_invalid(false, true, false);
const KeywordOptions options_unidentifiable_unsearchable(false, false, true);
Add(kElementAnimeSeasonPrefix, options_unidentifiable, {
L"SAISON", L"SEASON"});
Add(kElementAnimeType, options_unidentifiable, {
L"GEKIJOUBAN", L"MOVIE", L"OAV", L"ONA", L"OVA", L"TV"});
Add(kElementAnimeType, options_unidentifiable_unsearchable, {
L"SP"}); // e.g. "Yumeiro Patissiere SP Professional"
Add(kElementAnimeType, options_unidentifiable_invalid, {
L"ED", L"ENDING", L"NCED",
L"NCOP", L"OP", L"OPENING",
L"PREVIEW", L"PV"});
Add(kElementAudioTerm, options_default, {
// Audio channels
L"2.0CH", L"2CH", L"5.1", L"5.1CH", L"DTS", L"DTS-ES", L"DTS5.1",
L"TRUEHD5.1",
// Audio codec
L"AAC", L"AACX2", L"AACX3", L"AACX4", L"AC3", L"FLAC", L"FLACX2",
L"FLACX3", L"FLACX4", L"LOSSLESS", L"MP3", L"OGG", L"VORBIS",
// Audio language
L"DUALAUDIO", L"DUAL AUDIO"});
Add(kElementDeviceCompatibility, options_default, {
L"IPAD3", L"IPHONE5", L"IPOD", L"PS3", L"XBOX", L"XBOX360"});
Add(kElementDeviceCompatibility, options_unidentifiable, {
L"ANDROID"});
Add(kElementEpisodePrefix, options_default, {
L"E", L"EP", L"EP.", L"EPS", L"EPS.", L"EPISODE", L"EPISODE.", L"EPISODES",
L"VOL", L"VOL.", L"VOLUME",
L"CAPITULO", L"EPISODIO", L"FOLGE", L"\x7B2C"});
Add(kElementFileExtension, options_default, {
L"3GP", L"AVI", L"DIVX", L"FLV", L"M2TS", L"MKV", L"MOV", L"MP4", L"MPG",
L"OGM", L"RM", L"RMVB", L"WEBM", L"WMV"});
Add(kElementFileExtension, options_invalid, {
L"AAC", L"AIFF", L"FLAC", L"M4A", L"MP3", L"MKA", L"OGG", L"WAV", L"WMA",
L"7Z", L"RAR", L"ZIP",
L"ASS", L"SRT"});
Add(kElementLanguage, options_default, {
L"ENG", L"ENGLISH", L"ESPANOL", L"JAP", L"SPANISH", L"VOSTFR"});
Add(kElementLanguage, options_unidentifiable, {
L"ESP", L"ITA"}); // e.g. "Tokyo ESP", "Bokura ga Ita"
Add(kElementOther, options_default, {
L"REMASTER", L"REMASTERED", L"UNCENSORED", L"UNCUT",
L"TS", L"VFR", L"WIDESCREEN", L"WS"});
Add(kElementReleaseGroup, options_default, {
L"THORA"});
Add(kElementReleaseInformation, options_default, {
L"BATCH", L"COMPLETE", L"PATCH", L"REMUX"});
Add(kElementReleaseInformation, options_unidentifiable, {
L"END", L"FINAL"}); // e.g. "The End of Evangelion", "Final Approach"
Add(kElementReleaseVersion, options_default, {
L"V0", L"V1", L"V2", L"V3", L"V4"});
Add(kElementSource, options_default, {
L"BD", L"BDRIP", L"BLURAY", L"BLU-RAY",
L"DVD", L"DVD5", L"DVD9", L"DVD-R2J", L"DVDRIP", L"DVD-RIP",
L"R2DVD", L"R2J", L"R2JDVD", L"R2JDVDRIP",
L"HDTV", L"HDTVRIP", L"TVRIP", L"TV-RIP", L"WEBCAST"});
Add(kElementSubtitles, options_default, {
L"ASS", L"BIG5", L"DUB", L"DUBBED", L"HARDSUB", L"RAW", L"SOFTSUB",
L"SOFTSUBS", L"SUB", L"SUBBED", L"SUBTITLED"});
Add(kElementVideoTerm, options_default, {
// Frame rate
L"23.976FPS", L"24FPS", L"29.97FPS", L"30FPS", L"60FPS",
// Video codec
L"8BIT", L"8-BIT", L"10BIT", L"10-BIT", L"HI10P",
L"H264", L"H.264", L"X264", L"X.264",
L"AVC", L"DIVX", L"XVID",
// Video format
L"AVI", L"RMVB", L"WMV", L"WMV3", L"WMV9",
// Video quality
L"HQ", L"LQ",
// Video resolution
L"HD", L"SD"});
}
void KeywordManager::Add(ElementCategory category,
const KeywordOptions& options,
const std::initializer_list<string_t>& keywords) {
auto& keys = GetKeywordContainer(category);
for (const auto& keyword : keywords) {
if (keyword.empty())
continue;
if (keys.find(keyword) != keys.end())
continue;
keys.insert(std::make_pair(keyword, Keyword(category, options)));
}
}
bool KeywordManager::Find(ElementCategory category, const string_t& str) const {
const auto& keys = GetKeywordContainer(category);
auto it = keys.find(str);
if (it != keys.end() && it->second.category == category)
return true;
return false;
}
bool KeywordManager::Find(const string_t& str, ElementCategory& category,
KeywordOptions& options) const {
const auto& keys = GetKeywordContainer(category);
auto it = keys.find(str);
if (it != keys.end()) {
if (category == kElementUnknown) {
category = it->second.category;
} else if (it->second.category != category) {
return false;
}
options = it->second.options;
return true;
}
return false;
}
string_t KeywordManager::Normalize(const string_t& str) const {
return StringToUpperCopy(str);
}
KeywordManager::keyword_container_t& KeywordManager::GetKeywordContainer(
ElementCategory category) const {
return category == kElementFileExtension ?
const_cast<keyword_container_t&>(file_extensions_) :
const_cast<keyword_container_t&>(keys_);
}
////////////////////////////////////////////////////////////////////////////////
void KeywordManager::Peek(const string_t& filename,
const TokenRange& range,
Elements& elements,
std::vector<TokenRange>& preidentified_tokens) const {
typedef std::pair<ElementCategory, std::vector<string_t>> entry_t;
static const std::vector<entry_t> entries{
{kElementAudioTerm, {L"Dual Audio"}},
{kElementVideoTerm, {L"H264", L"H.264", L"h264", L"h.264"}},
{kElementVideoResolution, {L"480p", L"720p", L"1080p"}},
{kElementSource, {L"Blu-Ray"}}
};
auto it_begin = filename.begin() + range.offset;
auto it_end = it_begin + range.size;
for (const auto& entry : entries) {
for (const auto& keyword : entry.second) {
auto it = std::search(it_begin, it_end, keyword.begin(), keyword.end());
if (it != it_end) {
auto offset = it - filename.begin();
elements.insert(entry.first, keyword);
preidentified_tokens.push_back(TokenRange(offset, keyword.size()));
}
}
}
}
} // namespace anitomy<commit_msg>Add keywords: OAD, Special, Specials<commit_after>/*
** Anitomy
** Copyright (C) 2014-2015, Eren Okka
**
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include "keyword.h"
#include "token.h"
namespace anitomy {
KeywordManager keyword_manager;
KeywordOptions::KeywordOptions(bool identifiable, bool searchable, bool valid)
: identifiable(identifiable), searchable(searchable), valid(valid) {
}
Keyword::Keyword(ElementCategory category, const KeywordOptions& options)
: category(category), options(options) {
}
////////////////////////////////////////////////////////////////////////////////
KeywordManager::KeywordManager() {
const KeywordOptions options_default;
const KeywordOptions options_invalid(true, true, false);
const KeywordOptions options_unidentifiable(false, true, true);
const KeywordOptions options_unidentifiable_invalid(false, true, false);
const KeywordOptions options_unidentifiable_unsearchable(false, false, true);
Add(kElementAnimeSeasonPrefix, options_unidentifiable, {
L"SAISON", L"SEASON"});
Add(kElementAnimeType, options_unidentifiable, {
L"GEKIJOUBAN", L"MOVIE",
L"OAD", L"OAV", L"ONA", L"OVA",
L"SPECIAL", L"SPECIALS",
L"TV"});
Add(kElementAnimeType, options_unidentifiable_unsearchable, {
L"SP"}); // e.g. "Yumeiro Patissiere SP Professional"
Add(kElementAnimeType, options_unidentifiable_invalid, {
L"ED", L"ENDING", L"NCED",
L"NCOP", L"OP", L"OPENING",
L"PREVIEW", L"PV"});
Add(kElementAudioTerm, options_default, {
// Audio channels
L"2.0CH", L"2CH", L"5.1", L"5.1CH", L"DTS", L"DTS-ES", L"DTS5.1",
L"TRUEHD5.1",
// Audio codec
L"AAC", L"AACX2", L"AACX3", L"AACX4", L"AC3", L"FLAC", L"FLACX2",
L"FLACX3", L"FLACX4", L"LOSSLESS", L"MP3", L"OGG", L"VORBIS",
// Audio language
L"DUALAUDIO", L"DUAL AUDIO"});
Add(kElementDeviceCompatibility, options_default, {
L"IPAD3", L"IPHONE5", L"IPOD", L"PS3", L"XBOX", L"XBOX360"});
Add(kElementDeviceCompatibility, options_unidentifiable, {
L"ANDROID"});
Add(kElementEpisodePrefix, options_default, {
L"E", L"EP", L"EP.", L"EPS", L"EPS.", L"EPISODE", L"EPISODE.", L"EPISODES",
L"VOL", L"VOL.", L"VOLUME",
L"CAPITULO", L"EPISODIO", L"FOLGE", L"\x7B2C"});
Add(kElementFileExtension, options_default, {
L"3GP", L"AVI", L"DIVX", L"FLV", L"M2TS", L"MKV", L"MOV", L"MP4", L"MPG",
L"OGM", L"RM", L"RMVB", L"WEBM", L"WMV"});
Add(kElementFileExtension, options_invalid, {
L"AAC", L"AIFF", L"FLAC", L"M4A", L"MP3", L"MKA", L"OGG", L"WAV", L"WMA",
L"7Z", L"RAR", L"ZIP",
L"ASS", L"SRT"});
Add(kElementLanguage, options_default, {
L"ENG", L"ENGLISH", L"ESPANOL", L"JAP", L"SPANISH", L"VOSTFR"});
Add(kElementLanguage, options_unidentifiable, {
L"ESP", L"ITA"}); // e.g. "Tokyo ESP", "Bokura ga Ita"
Add(kElementOther, options_default, {
L"REMASTER", L"REMASTERED", L"UNCENSORED", L"UNCUT",
L"TS", L"VFR", L"WIDESCREEN", L"WS"});
Add(kElementReleaseGroup, options_default, {
L"THORA"});
Add(kElementReleaseInformation, options_default, {
L"BATCH", L"COMPLETE", L"PATCH", L"REMUX"});
Add(kElementReleaseInformation, options_unidentifiable, {
L"END", L"FINAL"}); // e.g. "The End of Evangelion", "Final Approach"
Add(kElementReleaseVersion, options_default, {
L"V0", L"V1", L"V2", L"V3", L"V4"});
Add(kElementSource, options_default, {
L"BD", L"BDRIP", L"BLURAY", L"BLU-RAY",
L"DVD", L"DVD5", L"DVD9", L"DVD-R2J", L"DVDRIP", L"DVD-RIP",
L"R2DVD", L"R2J", L"R2JDVD", L"R2JDVDRIP",
L"HDTV", L"HDTVRIP", L"TVRIP", L"TV-RIP", L"WEBCAST"});
Add(kElementSubtitles, options_default, {
L"ASS", L"BIG5", L"DUB", L"DUBBED", L"HARDSUB", L"RAW", L"SOFTSUB",
L"SOFTSUBS", L"SUB", L"SUBBED", L"SUBTITLED"});
Add(kElementVideoTerm, options_default, {
// Frame rate
L"23.976FPS", L"24FPS", L"29.97FPS", L"30FPS", L"60FPS",
// Video codec
L"8BIT", L"8-BIT", L"10BIT", L"10-BIT", L"HI10P",
L"H264", L"H.264", L"X264", L"X.264",
L"AVC", L"DIVX", L"XVID",
// Video format
L"AVI", L"RMVB", L"WMV", L"WMV3", L"WMV9",
// Video quality
L"HQ", L"LQ",
// Video resolution
L"HD", L"SD"});
}
void KeywordManager::Add(ElementCategory category,
const KeywordOptions& options,
const std::initializer_list<string_t>& keywords) {
auto& keys = GetKeywordContainer(category);
for (const auto& keyword : keywords) {
if (keyword.empty())
continue;
if (keys.find(keyword) != keys.end())
continue;
keys.insert(std::make_pair(keyword, Keyword(category, options)));
}
}
bool KeywordManager::Find(ElementCategory category, const string_t& str) const {
const auto& keys = GetKeywordContainer(category);
auto it = keys.find(str);
if (it != keys.end() && it->second.category == category)
return true;
return false;
}
bool KeywordManager::Find(const string_t& str, ElementCategory& category,
KeywordOptions& options) const {
const auto& keys = GetKeywordContainer(category);
auto it = keys.find(str);
if (it != keys.end()) {
if (category == kElementUnknown) {
category = it->second.category;
} else if (it->second.category != category) {
return false;
}
options = it->second.options;
return true;
}
return false;
}
string_t KeywordManager::Normalize(const string_t& str) const {
return StringToUpperCopy(str);
}
KeywordManager::keyword_container_t& KeywordManager::GetKeywordContainer(
ElementCategory category) const {
return category == kElementFileExtension ?
const_cast<keyword_container_t&>(file_extensions_) :
const_cast<keyword_container_t&>(keys_);
}
////////////////////////////////////////////////////////////////////////////////
void KeywordManager::Peek(const string_t& filename,
const TokenRange& range,
Elements& elements,
std::vector<TokenRange>& preidentified_tokens) const {
typedef std::pair<ElementCategory, std::vector<string_t>> entry_t;
static const std::vector<entry_t> entries{
{kElementAudioTerm, {L"Dual Audio"}},
{kElementVideoTerm, {L"H264", L"H.264", L"h264", L"h.264"}},
{kElementVideoResolution, {L"480p", L"720p", L"1080p"}},
{kElementSource, {L"Blu-Ray"}}
};
auto it_begin = filename.begin() + range.offset;
auto it_end = it_begin + range.size;
for (const auto& entry : entries) {
for (const auto& keyword : entry.second) {
auto it = std::search(it_begin, it_end, keyword.begin(), keyword.end());
if (it != it_end) {
auto offset = it - filename.begin();
elements.insert(entry.first, keyword);
preidentified_tokens.push_back(TokenRange(offset, keyword.size()));
}
}
}
}
} // namespace anitomy<|endoftext|>
|
<commit_before>#ifndef MOBS_HPP
#define MOBS_HPP
#include <iostream>
class Mob
<commit_msg>Update mobs.hpp<commit_after>#ifndef MOBS_HPP
#define MOBS_HPP
#include <iostream>
class Mob
{
public:
mob(std::string, std::string, std::string, int, int, int, int)
void setName(std::string);
void setArea(std::string);
<|endoftext|>
|
<commit_before>//===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// This pass implements the Bottom Up SLP vectorizer. It detects consecutive
// stores that can be put together into vector-stores. Next, it attempts to
// construct vectorizable tree using the use-def chains. If a profitable tree
// was found, the SLP vectorizer performs vectorization on the tree.
//
// The pass is inspired by the work described in the paper:
// "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
//
//===----------------------------------------------------------------------===//
#define SV_NAME "slp-vectorizer"
#define DEBUG_TYPE SV_NAME
#include "VecUtils.h"
#include "llvm/Transforms/Vectorize.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Value.h"
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include <map>
using namespace llvm;
static cl::opt<int>
SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
cl::desc("Only vectorize trees if the gain is above this "
"number. (gain = -cost of vectorization)"));
namespace {
/// The SLPVectorizer Pass.
struct SLPVectorizer : public FunctionPass {
typedef MapVector<Value*, BoUpSLP::StoreList> StoreListMap;
/// Pass identification, replacement for typeid
static char ID;
explicit SLPVectorizer() : FunctionPass(ID) {
initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
}
ScalarEvolution *SE;
DataLayout *DL;
TargetTransformInfo *TTI;
AliasAnalysis *AA;
LoopInfo *LI;
virtual bool runOnFunction(Function &F) {
SE = &getAnalysis<ScalarEvolution>();
DL = getAnalysisIfAvailable<DataLayout>();
TTI = &getAnalysis<TargetTransformInfo>();
AA = &getAnalysis<AliasAnalysis>();
LI = &getAnalysis<LoopInfo>();
StoreRefs.clear();
bool Changed = false;
// Must have DataLayout. We can't require it because some tests run w/o
// triple.
if (!DL)
return false;
DEBUG(dbgs()<<"SLP: Analyzing blocks in " << F.getName() << ".\n");
for (Function::iterator it = F.begin(), e = F.end(); it != e; ++it) {
BasicBlock *BB = it;
bool BBChanged = false;
// Use the bollom up slp vectorizer to construct chains that start with
// he store instructions.
BoUpSLP R(BB, SE, DL, TTI, AA, LI->getLoopFor(BB));
// Vectorize trees that end at reductions.
BBChanged |= vectorizeReductions(BB, R);
// Vectorize trees that end at stores.
if (unsigned count = collectStores(BB, R)) {
(void)count;
DEBUG(dbgs()<<"SLP: Found " << count << " stores to vectorize.\n");
BBChanged |= vectorizeStoreChains(R);
}
// Try to hoist some of the scalarization code to the preheader.
if (BBChanged) hoistGatherSequence(LI, BB, R);
Changed |= BBChanged;
}
if (Changed) {
DEBUG(dbgs()<<"SLP: vectorized \""<<F.getName()<<"\"\n");
DEBUG(verifyFunction(F));
}
return Changed;
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
FunctionPass::getAnalysisUsage(AU);
AU.addRequired<ScalarEvolution>();
AU.addRequired<AliasAnalysis>();
AU.addRequired<TargetTransformInfo>();
AU.addRequired<LoopInfo>();
}
private:
/// \brief Collect memory references and sort them according to their base
/// object. We sort the stores to their base objects to reduce the cost of the
/// quadratic search on the stores. TODO: We can further reduce this cost
/// if we flush the chain creation every time we run into a memory barrier.
unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
/// \brief Try to vectorize a chain that starts at two arithmetic instrs.
bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
/// \brief Try to vectorize a list of operands.
bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R);
/// \brief Try to vectorize a chain that may start at the operands of \V;
bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
/// \brief Vectorize the stores that were collected in StoreRefs.
bool vectorizeStoreChains(BoUpSLP &R);
/// \brief Try to hoist gather sequences outside of the loop in cases where
/// all of the sources are loop invariant.
void hoistGatherSequence(LoopInfo *LI, BasicBlock *BB, BoUpSLP &R);
/// \brief Scan the basic block and look for reductions that may start a
/// vectorization chain.
bool vectorizeReductions(BasicBlock *BB, BoUpSLP &R);
private:
StoreListMap StoreRefs;
};
unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
unsigned count = 0;
StoreRefs.clear();
for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
StoreInst *SI = dyn_cast<StoreInst>(it);
if (!SI)
continue;
// Check that the pointer points to scalars.
Type *Ty = SI->getValueOperand()->getType();
if (Ty->isAggregateType() || Ty->isVectorTy())
return 0;
// Find the base of the GEP.
Value *Ptr = SI->getPointerOperand();
if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
Ptr = GEP->getPointerOperand();
// Save the store locations.
StoreRefs[Ptr].push_back(SI);
count++;
}
return count;
}
bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
if (!A || !B) return false;
Value *VL[] = { A, B };
return tryToVectorizeList(VL, R);
}
bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R) {
DEBUG(dbgs()<<"SLP: Vectorizing a list of length = " << VL.size() << ".\n");
// Check that all of the parts are scalar.
for (int i = 0, e = VL.size(); i < e; ++i) {
Type *Ty = VL[i]->getType();
if (Ty->isAggregateType() || Ty->isVectorTy())
return 0;
}
int Cost = R.getTreeCost(VL);
int ExtrCost = R.getScalarizationCost(VL);
DEBUG(dbgs()<<"SLP: Cost of pair:" << Cost <<
" Cost of extract:" << ExtrCost << ".\n");
if ((Cost+ExtrCost) >= -SLPCostThreshold) return false;
DEBUG(dbgs()<<"SLP: Vectorizing pair.\n");
R.vectorizeArith(VL);
return true;
}
bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
if (!V) return false;
// Try to vectorize V.
if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
return true;
BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
// Try to skip B.
if (B && B->hasOneUse()) {
BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
if (tryToVectorizePair(A, B0, R)) {
B->moveBefore(V);
return true;
}
if (tryToVectorizePair(A, B1, R)) {
B->moveBefore(V);
return true;
}
}
// Try to skip A.
if (A && A->hasOneUse()) {
BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
if (tryToVectorizePair(A0, B, R)) {
A->moveBefore(V);
return true;
}
if (tryToVectorizePair(A1, B, R)) {
A->moveBefore(V);
return true;
}
}
return 0;
}
bool SLPVectorizer::vectorizeReductions(BasicBlock *BB, BoUpSLP &R) {
bool Changed = false;
for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
if (isa<DbgInfoIntrinsic>(it)) continue;
// Try to vectorize reductions that use PHINodes.
if (PHINode *P = dyn_cast<PHINode>(it)) {
// Check that the PHI is a reduction PHI.
if (P->getNumIncomingValues() != 2) return Changed;
Value *Rdx = (P->getIncomingBlock(0) == BB ? P->getIncomingValue(0) :
(P->getIncomingBlock(1) == BB ? P->getIncomingValue(1) :
0));
// Check if this is a Binary Operator.
BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
if (!BI)
continue;
Value *Inst = BI->getOperand(0);
if (Inst == P) Inst = BI->getOperand(1);
Changed |= tryToVectorize(dyn_cast<BinaryOperator>(Inst), R);
continue;
}
// Try to vectorize trees that start at compare instructions.
if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
Changed |= true;
continue;
}
for (int i = 0; i < 2; ++i)
if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i)))
Changed |= tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R);
continue;
}
}
return Changed;
}
bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
bool Changed = false;
// Attempt to sort and vectorize each of the store-groups.
for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
it != e; ++it) {
if (it->second.size() < 2)
continue;
DEBUG(dbgs()<<"SLP: Analyzing a store chain of length " <<
it->second.size() << ".\n");
Changed |= R.vectorizeStores(it->second, -SLPCostThreshold);
}
return Changed;
}
void SLPVectorizer::hoistGatherSequence(LoopInfo *LI, BasicBlock *BB,
BoUpSLP &R) {
// Check if this block is inside a loop.
Loop *L = LI->getLoopFor(BB);
if (!L)
return;
// Check if it has a preheader.
BasicBlock *PreHeader = L->getLoopPreheader();
if (!PreHeader)
return;
// Mark the insertion point for the block.
Instruction *Location = PreHeader->getTerminator();
BoUpSLP::ValueList &Gathers = R.getGatherSeqInstructions();
for (BoUpSLP::ValueList::iterator it = Gathers.begin(), e = Gathers.end();
it != e; ++it) {
InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
// The InsertElement sequence can be simplified into a constant.
if (!Insert)
continue;
// If the vector or the element that we insert into it are
// instructions that are defined in this basic block then we can't
// hoist this instruction.
Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
if (CurrVec && L->contains(CurrVec)) continue;
if (NewElem && L->contains(NewElem)) continue;
// We can hoist this instruction. Move it to the pre-header.
Insert->moveBefore(Location);
}
}
} // end anonymous namespace
char SLPVectorizer::ID = 0;
static const char lv_name[] = "SLP Vectorizer";
INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
namespace llvm {
Pass *createSLPVectorizerPass() {
return new SLPVectorizer();
}
}
<commit_msg>Scan the successor blocks and use the PHI nodes as a hint for possible chain roots.<commit_after>//===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// This pass implements the Bottom Up SLP vectorizer. It detects consecutive
// stores that can be put together into vector-stores. Next, it attempts to
// construct vectorizable tree using the use-def chains. If a profitable tree
// was found, the SLP vectorizer performs vectorization on the tree.
//
// The pass is inspired by the work described in the paper:
// "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
//
//===----------------------------------------------------------------------===//
#define SV_NAME "slp-vectorizer"
#define DEBUG_TYPE SV_NAME
#include "VecUtils.h"
#include "llvm/Transforms/Vectorize.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Value.h"
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include <map>
using namespace llvm;
static cl::opt<int>
SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
cl::desc("Only vectorize trees if the gain is above this "
"number. (gain = -cost of vectorization)"));
namespace {
/// The SLPVectorizer Pass.
struct SLPVectorizer : public FunctionPass {
typedef MapVector<Value*, BoUpSLP::StoreList> StoreListMap;
/// Pass identification, replacement for typeid
static char ID;
explicit SLPVectorizer() : FunctionPass(ID) {
initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
}
ScalarEvolution *SE;
DataLayout *DL;
TargetTransformInfo *TTI;
AliasAnalysis *AA;
LoopInfo *LI;
virtual bool runOnFunction(Function &F) {
SE = &getAnalysis<ScalarEvolution>();
DL = getAnalysisIfAvailable<DataLayout>();
TTI = &getAnalysis<TargetTransformInfo>();
AA = &getAnalysis<AliasAnalysis>();
LI = &getAnalysis<LoopInfo>();
StoreRefs.clear();
bool Changed = false;
// Must have DataLayout. We can't require it because some tests run w/o
// triple.
if (!DL)
return false;
DEBUG(dbgs()<<"SLP: Analyzing blocks in " << F.getName() << ".\n");
for (Function::iterator it = F.begin(), e = F.end(); it != e; ++it) {
BasicBlock *BB = it;
bool BBChanged = false;
// Use the bollom up slp vectorizer to construct chains that start with
// he store instructions.
BoUpSLP R(BB, SE, DL, TTI, AA, LI->getLoopFor(BB));
// Vectorize trees that end at reductions.
BBChanged |= vectorizeChainsInBlock(BB, R);
// Vectorize trees that end at stores.
if (unsigned count = collectStores(BB, R)) {
(void)count;
DEBUG(dbgs()<<"SLP: Found " << count << " stores to vectorize.\n");
BBChanged |= vectorizeStoreChains(R);
}
// Try to hoist some of the scalarization code to the preheader.
if (BBChanged) hoistGatherSequence(LI, BB, R);
Changed |= BBChanged;
}
if (Changed) {
DEBUG(dbgs()<<"SLP: vectorized \""<<F.getName()<<"\"\n");
DEBUG(verifyFunction(F));
}
return Changed;
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
FunctionPass::getAnalysisUsage(AU);
AU.addRequired<ScalarEvolution>();
AU.addRequired<AliasAnalysis>();
AU.addRequired<TargetTransformInfo>();
AU.addRequired<LoopInfo>();
}
private:
/// \brief Collect memory references and sort them according to their base
/// object. We sort the stores to their base objects to reduce the cost of the
/// quadratic search on the stores. TODO: We can further reduce this cost
/// if we flush the chain creation every time we run into a memory barrier.
unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
/// \brief Try to vectorize a chain that starts at two arithmetic instrs.
bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
/// \brief Try to vectorize a list of operands.
bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R);
/// \brief Try to vectorize a chain that may start at the operands of \V;
bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
/// \brief Vectorize the stores that were collected in StoreRefs.
bool vectorizeStoreChains(BoUpSLP &R);
/// \brief Try to hoist gather sequences outside of the loop in cases where
/// all of the sources are loop invariant.
void hoistGatherSequence(LoopInfo *LI, BasicBlock *BB, BoUpSLP &R);
/// \brief Scan the basic block and look for patterns that are likely to start
/// a vectorization chain.
bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
private:
StoreListMap StoreRefs;
};
unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
unsigned count = 0;
StoreRefs.clear();
for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
StoreInst *SI = dyn_cast<StoreInst>(it);
if (!SI)
continue;
// Check that the pointer points to scalars.
Type *Ty = SI->getValueOperand()->getType();
if (Ty->isAggregateType() || Ty->isVectorTy())
return 0;
// Find the base of the GEP.
Value *Ptr = SI->getPointerOperand();
if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
Ptr = GEP->getPointerOperand();
// Save the store locations.
StoreRefs[Ptr].push_back(SI);
count++;
}
return count;
}
bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
if (!A || !B) return false;
Value *VL[] = { A, B };
return tryToVectorizeList(VL, R);
}
bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R) {
if (VL.size() < 2)
return false;
DEBUG(dbgs()<<"SLP: Vectorizing a list of length = " << VL.size() << ".\n");
// Check that all of the parts are scalar instructions of the same type.
Instruction *I0 = dyn_cast<Instruction>(VL[0]);
if (!I0) return 0;
unsigned Opcode0 = I0->getOpcode();
for (int i = 0, e = VL.size(); i < e; ++i) {
Type *Ty = VL[i]->getType();
if (Ty->isAggregateType() || Ty->isVectorTy())
return 0;
Instruction *Inst = dyn_cast<Instruction>(VL[i]);
if (!Inst || Inst->getOpcode() != Opcode0)
return 0;
}
int Cost = R.getTreeCost(VL);
int ExtrCost = R.getScalarizationCost(VL);
DEBUG(dbgs()<<"SLP: Cost of pair:" << Cost <<
" Cost of extract:" << ExtrCost << ".\n");
if ((Cost+ExtrCost) >= -SLPCostThreshold) return false;
DEBUG(dbgs()<<"SLP: Vectorizing pair.\n");
R.vectorizeArith(VL);
return true;
}
bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
if (!V) return false;
// Try to vectorize V.
if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
return true;
BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
// Try to skip B.
if (B && B->hasOneUse()) {
BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
if (tryToVectorizePair(A, B0, R)) {
B->moveBefore(V);
return true;
}
if (tryToVectorizePair(A, B1, R)) {
B->moveBefore(V);
return true;
}
}
// Try to skip A.
if (A && A->hasOneUse()) {
BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
if (tryToVectorizePair(A0, B, R)) {
A->moveBefore(V);
return true;
}
if (tryToVectorizePair(A1, B, R)) {
A->moveBefore(V);
return true;
}
}
return 0;
}
bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
bool Changed = false;
for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
if (isa<DbgInfoIntrinsic>(it)) continue;
// Try to vectorize reductions that use PHINodes.
if (PHINode *P = dyn_cast<PHINode>(it)) {
// Check that the PHI is a reduction PHI.
if (P->getNumIncomingValues() != 2) return Changed;
Value *Rdx = (P->getIncomingBlock(0) == BB ? P->getIncomingValue(0) :
(P->getIncomingBlock(1) == BB ? P->getIncomingValue(1) :
0));
// Check if this is a Binary Operator.
BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
if (!BI)
continue;
Value *Inst = BI->getOperand(0);
if (Inst == P) Inst = BI->getOperand(1);
Changed |= tryToVectorize(dyn_cast<BinaryOperator>(Inst), R);
continue;
}
// Try to vectorize trees that start at compare instructions.
if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
Changed |= true;
continue;
}
for (int i = 0; i < 2; ++i)
if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i)))
Changed |= tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R);
continue;
}
}
// Scan the PHINodes in our successors in search for pairing hints.
for (succ_iterator it = succ_begin(BB), e = succ_end(BB); it != e; ++it) {
BasicBlock *Succ = *it;
SmallVector<Value*, 4> Incoming;
// Collect the incoming values from the PHIs.
for (BasicBlock::iterator instr = Succ->begin(), ie = Succ->end();
instr != ie; ++instr) {
PHINode *P = dyn_cast<PHINode>(instr);
if (!P)
break;
Value *V = P->getIncomingValueForBlock(BB);
if (Instruction *I = dyn_cast<Instruction>(V))
if (I->getParent() == BB)
Incoming.push_back(I);
}
if (Incoming.size() > 1)
Changed |= tryToVectorizeList(Incoming, R);
}
return Changed;
}
bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
bool Changed = false;
// Attempt to sort and vectorize each of the store-groups.
for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
it != e; ++it) {
if (it->second.size() < 2)
continue;
DEBUG(dbgs()<<"SLP: Analyzing a store chain of length " <<
it->second.size() << ".\n");
Changed |= R.vectorizeStores(it->second, -SLPCostThreshold);
}
return Changed;
}
void SLPVectorizer::hoistGatherSequence(LoopInfo *LI, BasicBlock *BB,
BoUpSLP &R) {
// Check if this block is inside a loop.
Loop *L = LI->getLoopFor(BB);
if (!L)
return;
// Check if it has a preheader.
BasicBlock *PreHeader = L->getLoopPreheader();
if (!PreHeader)
return;
// Mark the insertion point for the block.
Instruction *Location = PreHeader->getTerminator();
BoUpSLP::ValueList &Gathers = R.getGatherSeqInstructions();
for (BoUpSLP::ValueList::iterator it = Gathers.begin(), e = Gathers.end();
it != e; ++it) {
InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
// The InsertElement sequence can be simplified into a constant.
if (!Insert)
continue;
// If the vector or the element that we insert into it are
// instructions that are defined in this basic block then we can't
// hoist this instruction.
Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
if (CurrVec && L->contains(CurrVec)) continue;
if (NewElem && L->contains(NewElem)) continue;
// We can hoist this instruction. Move it to the pre-header.
Insert->moveBefore(Location);
}
}
} // end anonymous namespace
char SLPVectorizer::ID = 0;
static const char lv_name[] = "SLP Vectorizer";
INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
namespace llvm {
Pass *createSLPVectorizerPass() {
return new SLPVectorizer();
}
}
<|endoftext|>
|
<commit_before>/// @brief provides CORDIC for arccos function
/// @ref see H. Dawid, H. Meyr, "CORDIC Algorithms and Architectures"
#include "./../../fixed_point_lib/src/CORDIC/lut/lut.hpp"
namespace std {
template<typename T, size_t n, size_t f, class op, class up>
typename core::fixed_point<T, n, f, op, up>::asin_type asin(core::fixed_point<T, n, f, op, up> val)
{
typedef core::fixed_point<T, n, f, op, up> fp;
typedef typename fp::asin_type result_type;
typedef core::cordic::lut<result_type::fractionals, result_type> lut;
assert(("argument has to be from interval [-1.0, 1.0]", std::fabs(val) <= fp(1.0)));
if (std::fabs(val) > fp(1.0)) {
throw std::exception("arcsin: argument is out of range");
}
if (val == fp(1.0)) {
return result_type::CONST_PI_2;
}
else if (val == fp(-1.0)) {
return -(result_type::CONST_PI_2);
}
else if (val == fp(0)) {
return result_type::wrap(0);
}
static lut const angles = lut::circular();
static lut const scales = lut::circular_scales();
// rotation mode: see page 6
// shift sequence is just 0, 1, ... (circular coordinate system)
result_type x(1.0), y(0.0), z(0.0);
BOOST_FOREACH(size_t i, boost::irange<size_t>(0, f, 1))
{
int sign(0);
if (val >= y) {
sign = (x < 0.0)? -1 : +1;
}
else {
sign = (x < 0.0)? +1 : -1;
}
result_type::word_type const store(x.value());
x = x - result_type::wrap(sign * (y.value() >> i));
y = y + result_type::wrap(sign * (store >> i));
z = (sign > 0)? z + angles[i] : z - angles[i];
val = val * scales[i];
}
if (z > result_type::CONST_PI_2) {
z = result_type::CONST_PI - z;
}
else if (z < -result_type::CONST_PI_2) {
z = -result_type::CONST_PI - z;
}
return z;
}
}
<commit_msg>asin.inl: asin_of class (it was drawn from get_ class)<commit_after>/// @brief provides CORDIC for arccos function
/// @ref see H. Dawid, H. Meyr, "CORDIC Algorithms and Architectures"
#include "./../../fixed_point_lib/src/CORDIC/lut/lut.hpp"
#include <boost/type_traits/is_floating_point.hpp>
#include <boost/integer.hpp>
namespace core {
template<typename T>
class asin_of
{
BOOST_STATIC_ASSERT(boost::is_floating_point<T>::value);
public:
typedef T type;
};
template<typename T, size_t n, size_t f, class op, class up>
class asin_of<fixed_point<T, n, f, op, up> >
{
static size_t const available_bits = std::numeric_limits<boost::intmax_t>::digits - f;
struct can_expand
{
enum { value = (available_bits > 2u) };
};
struct expanded
{
typedef fixed_point<
typename boost::int_t<f + 2u + 1u>::least,
f + 2u,
f,
op,
up
> type;
};
struct reduced
{
typedef fixed_point<
typename boost::int_t<f + 2u>::least,
f + available_bits,
f + available_bits - 2u,
op,
up
> type;
};
public:
typename eval_if<can_expand, expanded, reduced>::type type;
};
}
namespace std {
template<typename T, size_t n, size_t f, class op, class up>
typename core::asin_of<core::fixed_point<T, n, f, op, up> >::type asin(core::fixed_point<T, n, f, op, up> val)
{
typedef core::fixed_point<T, n, f, op, up> fp;
typedef typename fp::asin_type result_type;
typedef core::cordic::lut<result_type::fractionals, result_type> lut;
assert(("argument has to be from interval [-1.0, 1.0]", std::fabs(val) <= fp(1.0)));
if (std::fabs(val) > fp(1.0)) {
throw std::exception("arcsin: argument is out of range");
}
if (val == fp(1.0)) {
return result_type::CONST_PI_2;
}
else if (val == fp(-1.0)) {
return -(result_type::CONST_PI_2);
}
else if (val == fp(0)) {
return result_type::wrap(0);
}
static lut const angles = lut::circular();
static lut const scales = lut::circular_scales();
// rotation mode: see page 6
// shift sequence is just 0, 1, ... (circular coordinate system)
result_type x(1.0), y(0.0), z(0.0);
BOOST_FOREACH(size_t i, boost::irange<size_t>(0, f, 1))
{
int sign(0);
if (val >= y) {
sign = (x < 0.0)? -1 : +1;
}
else {
sign = (x < 0.0)? +1 : -1;
}
result_type::word_type const store(x.value());
x = x - result_type::wrap(sign * (y.value() >> i));
y = y + result_type::wrap(sign * (store >> i));
z = (sign > 0)? z + angles[i] : z - angles[i];
val = val * scales[i];
}
if (z > result_type::CONST_PI_2) {
z = result_type::CONST_PI - z;
}
else if (z < -result_type::CONST_PI_2) {
z = -result_type::CONST_PI - z;
}
return z;
}
}
<|endoftext|>
|
<commit_before>#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include <unistd.h>
#include "snarkfront.hpp"
using namespace snarkfront;
using namespace std;
void printUsage(const char* exeName) {
cout << "usage: " << exeName
<< " -p BN128|Edwards"
" -b 256|512"
" -d tree_depth"
" -o file_prefix"
" -n constraints_per_file"
<< endl;
exit(EXIT_FAILURE);
}
template <typename PAIRING, typename BUNDLE, typename ZK_PATH>
void makeMerkle(const size_t treeDepth)
{
BUNDLE bundle(treeDepth);
const typename BUNDLE::DigType leaf{0};
bundle.addLeaf(leaf);
const auto& authPath = bundle.authPath().front();
typename ZK_PATH::DigType zkRT;
bless(zkRT, authPath.rootHash());
end_input<PAIRING>();
typename ZK_PATH::DigType zkLeaf;
bless(zkLeaf, leaf);
ZK_PATH zkAuthPath(authPath);
zkAuthPath.updatePath(zkLeaf);
assert_true(zkRT == zkAuthPath.rootHash());
cout << "variable count " << variable_count<PAIRING>() << endl;
}
template <typename PAIRING>
void makeMerkle(const string& shaBits,
const size_t treeDepth,
const string& filePrefix,
const size_t maxSize)
{
typedef typename PAIRING::Fr FR;
write_files<PAIRING>(filePrefix, maxSize);
if (nameSHA256(shaBits)) {
makeMerkle<PAIRING,
MerkleBundle_SHA256<size_t>,
zk::MerkleAuthPath_SHA256<FR>>(treeDepth);
} else if (nameSHA512(shaBits)) {
makeMerkle<PAIRING,
MerkleBundle_SHA512<size_t>,
zk::MerkleAuthPath_SHA512<FR>>(treeDepth);
}
finalize_files<PAIRING>();
}
int main(int argc, char *argv[])
{
// command line switches
string pairing, shaBits, filePrefix;
size_t treeDepth = -1, maxSize = -1;
int opt;
while (-1 != (opt = getopt(argc, argv, "p:b:o:d:n:"))) {
switch (opt) {
case ('p') :
pairing = optarg;
break;
case ('b') :
shaBits = optarg;
break;
case ('o') :
filePrefix = optarg;
break;
case ('d') : {
stringstream ss(optarg);
if (!(ss >> treeDepth)) {
cerr << "error: tree depth " << optarg << endl;
exit(EXIT_FAILURE);
}
}
break;
case ('n') : {
stringstream ss(optarg);
if (!(ss >> maxSize)) {
cerr << "error: number of constraints per file " << optarg << endl;
exit(EXIT_FAILURE);
}
}
break;
}
}
if (!validPairingName(pairing) ||
!(nameSHA256(shaBits) || nameSHA512(shaBits)) ||
filePrefix.empty() ||
-1 == treeDepth ||
-1 == maxSize)
printUsage(argv[0]);
if (pairingBN128(pairing)) {
// Barreto-Naehrig 128 bits
init_BN128();
makeMerkle<BN128_PAIRING>(shaBits, treeDepth, filePrefix, maxSize);
} else if (pairingEdwards(pairing)){
// Edwards 80 bits
init_Edwards();
makeMerkle<EDWARDS_PAIRING>(shaBits, treeDepth, filePrefix, maxSize);
}
exit(EXIT_SUCCESS);
}
<commit_msg>Delete make_merkle.cpp<commit_after><|endoftext|>
|
<commit_before>// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <logd/exceptions.h>
#include <logd/metrics.h>
#include <logd/rpc_forwarder.h>
#include <vespa/vespalib/gtest/gtest.h>
#include <vespa/vespalib/metrics/dummy_metrics_manager.h>
using namespace logdemon;
using vespalib::metrics::DummyMetricsManager;
void
encode_log_response(const ProtoConverter::ProtoLogResponse& src, FRT_Values& dst)
{
auto buf = src.SerializeAsString();
dst.AddInt8(0);
dst.AddInt32(buf.size());
dst.AddData(buf.data(), buf.size());
}
bool
decode_log_request(FRT_Values& src, ProtoConverter::ProtoLogRequest& dst)
{
uint8_t encoding = src[0]._intval8;
assert(encoding == 0);
uint32_t uncompressed_size = src[1]._intval32;
assert(uncompressed_size == src[2]._data._len);
return dst.ParseFromArray(src[2]._data._buf, src[2]._data._len);
}
std::string garbage("garbage");
struct RpcServer : public FRT_Invokable {
fnet::frt::StandaloneFRT server;
int request_count;
std::vector<std::string> messages;
bool reply_with_error;
bool reply_with_proto_response;
public:
RpcServer()
: server(),
request_count(0),
messages(),
reply_with_error(false),
reply_with_proto_response(true)
{
server.supervisor().Listen(0);
FRT_ReflectionBuilder builder(&server.supervisor());
builder.DefineMethod("vespa.logserver.archiveLogMessages", "bix", "bix",
FRT_METHOD(RpcServer::rpc_archive_log_messages), this);
}
~RpcServer() = default;
int get_listen_port() {
return server.supervisor().GetListenPort();
}
void rpc_archive_log_messages(FRT_RPCRequest* request) {
ProtoConverter::ProtoLogRequest proto_request;
ASSERT_TRUE(decode_log_request(*request->GetParams(), proto_request));
++request_count;
for (const auto& message : proto_request.log_messages()) {
messages.push_back(message.payload());
}
if (reply_with_error) {
request->SetError(123, "This is a server error");
return;
}
if (reply_with_proto_response) {
ProtoConverter::ProtoLogResponse proto_response;
encode_log_response(proto_response, *request->GetReturn());
} else {
auto& dst = *request->GetReturn();
dst.AddInt8(0);
dst.AddInt32(garbage.size());
dst.AddData(garbage.data(), garbage.size());
}
}
};
std::string
make_log_line(const std::string& level, const std::string& payload)
{
return "1234.5678\tmy_host\t10/20\tmy_service\tmy_component\t" + level + "\t" + payload;
}
struct MockMetricsManager : public DummyMetricsManager {
int add_count;
MockMetricsManager() : DummyMetricsManager(), add_count(0) {}
void add(Counter::Increment) override {
++add_count;
}
};
class ClientSupervisor {
private:
fnet::frt::StandaloneFRT _client;
public:
ClientSupervisor()
: _client()
{
}
~ClientSupervisor() = default;
FRT_Supervisor& get() { return _client.supervisor(); }
};
ForwardMap
make_forward_filter()
{
ForwardMap result;
result[ns_log::Logger::error] = true;
result[ns_log::Logger::warning] = false;
result[ns_log::Logger::info] = true;
// all other log levels are implicit false
return result;
}
struct RpcForwarderTest : public ::testing::Test {
RpcServer server;
std::shared_ptr<MockMetricsManager> metrics_mgr;
Metrics metrics;
ClientSupervisor supervisor;
RpcForwarder forwarder;
RpcForwarderTest()
: server(),
metrics_mgr(std::make_shared<MockMetricsManager>()),
metrics(metrics_mgr),
forwarder(metrics, make_forward_filter(), supervisor.get(), "localhost", server.get_listen_port(), 60.0, 3)
{
}
void forward_line(const std::string& payload) {
forwarder.forwardLine(make_log_line("info", payload));
}
void forward_line(const std::string& level, const std::string& payload) {
forwarder.forwardLine(make_log_line(level, payload));
}
void forward_bad_line() {
forwarder.forwardLine("badline");
}
void flush() {
forwarder.flush();
}
void expect_messages() {
expect_messages(0, {});
}
void expect_messages(int exp_request_count, const std::vector<std::string>& exp_messages) {
EXPECT_EQ(exp_request_count, server.request_count);
EXPECT_EQ(exp_messages, server.messages);
}
};
TEST_F(RpcForwarderTest, does_not_send_rpc_with_no_log_messages)
{
expect_messages();
flush();
expect_messages();
}
TEST_F(RpcForwarderTest, can_send_rpc_with_single_log_message)
{
forward_line("a");
expect_messages();
flush();
expect_messages(1, {"a"});
}
TEST_F(RpcForwarderTest, can_send_rpc_with_multiple_log_messages)
{
forward_line("a");
forward_line("b");
expect_messages();
flush();
expect_messages(1, {"a", "b"});
}
TEST_F(RpcForwarderTest, automatically_sends_rpc_when_max_messages_limit_is_reached)
{
forward_line("a");
forward_line("b");
expect_messages();
forward_line("c");
expect_messages(1, {"a", "b", "c"});
forward_line("d");
expect_messages(1, {"a", "b", "c"});
forward_line("e");
expect_messages(1, {"a", "b", "c"});
forward_line("f");
expect_messages(2, {"a", "b", "c", "d", "e", "f"});
}
TEST_F(RpcForwarderTest, bad_log_lines_are_counted_but_not_sent)
{
forward_line("a");
forward_bad_line();
EXPECT_EQ(1, forwarder.badLines());
flush();
expect_messages(1, {"a"});
}
TEST_F(RpcForwarderTest, bad_log_lines_count_can_be_reset)
{
forward_bad_line();
EXPECT_EQ(1, forwarder.badLines());
forwarder.resetBadLines();
EXPECT_EQ(0, forwarder.badLines());
}
TEST_F(RpcForwarderTest, metrics_are_updated_for_each_log_message)
{
forward_line("a");
EXPECT_EQ(1, metrics_mgr->add_count);
forward_line("b");
EXPECT_EQ(2, metrics_mgr->add_count);
}
TEST_F(RpcForwarderTest, log_messages_are_filtered_on_log_level)
{
forward_line("fatal", "a");
forward_line("error", "b");
forward_line("warning", "c");
forward_line("config", "d");
forward_line("info", "e");
forward_line("event", "f");
forward_line("debug", "g");
forward_line("spam", "h");
forward_line("null", "i");
flush();
expect_messages(1, {"b", "e"});
EXPECT_EQ(9, metrics_mgr->add_count);
}
TEST_F(RpcForwarderTest, throws_when_rpc_reply_contains_errors)
{
server.reply_with_error = true;
forward_line("a");
EXPECT_THROW(flush(), logdemon::ConnectionException);
}
TEST_F(RpcForwarderTest, throws_when_rpc_reply_does_not_contain_proto_response)
{
server.reply_with_proto_response = false;
forward_line("a");
EXPECT_THROW(flush(), logdemon::DecodeException);
}
GTEST_MAIN_RUN_ALL_TESTS()
<commit_msg>Listen after setup is complete.<commit_after>// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <logd/exceptions.h>
#include <logd/metrics.h>
#include <logd/rpc_forwarder.h>
#include <vespa/vespalib/gtest/gtest.h>
#include <vespa/vespalib/metrics/dummy_metrics_manager.h>
using namespace logdemon;
using vespalib::metrics::DummyMetricsManager;
void
encode_log_response(const ProtoConverter::ProtoLogResponse& src, FRT_Values& dst)
{
auto buf = src.SerializeAsString();
dst.AddInt8(0);
dst.AddInt32(buf.size());
dst.AddData(buf.data(), buf.size());
}
bool
decode_log_request(FRT_Values& src, ProtoConverter::ProtoLogRequest& dst)
{
uint8_t encoding = src[0]._intval8;
assert(encoding == 0);
uint32_t uncompressed_size = src[1]._intval32;
assert(uncompressed_size == src[2]._data._len);
return dst.ParseFromArray(src[2]._data._buf, src[2]._data._len);
}
std::string garbage("garbage");
struct RpcServer : public FRT_Invokable {
fnet::frt::StandaloneFRT server;
int request_count;
std::vector<std::string> messages;
bool reply_with_error;
bool reply_with_proto_response;
public:
RpcServer()
: server(),
request_count(0),
messages(),
reply_with_error(false),
reply_with_proto_response(true)
{
FRT_ReflectionBuilder builder(&server.supervisor());
builder.DefineMethod("vespa.logserver.archiveLogMessages", "bix", "bix",
FRT_METHOD(RpcServer::rpc_archive_log_messages), this);
server.supervisor().Listen(0);
}
~RpcServer() = default;
int get_listen_port() {
return server.supervisor().GetListenPort();
}
void rpc_archive_log_messages(FRT_RPCRequest* request) {
ProtoConverter::ProtoLogRequest proto_request;
ASSERT_TRUE(decode_log_request(*request->GetParams(), proto_request));
++request_count;
for (const auto& message : proto_request.log_messages()) {
messages.push_back(message.payload());
}
if (reply_with_error) {
request->SetError(123, "This is a server error");
return;
}
if (reply_with_proto_response) {
ProtoConverter::ProtoLogResponse proto_response;
encode_log_response(proto_response, *request->GetReturn());
} else {
auto& dst = *request->GetReturn();
dst.AddInt8(0);
dst.AddInt32(garbage.size());
dst.AddData(garbage.data(), garbage.size());
}
}
};
std::string
make_log_line(const std::string& level, const std::string& payload)
{
return "1234.5678\tmy_host\t10/20\tmy_service\tmy_component\t" + level + "\t" + payload;
}
struct MockMetricsManager : public DummyMetricsManager {
int add_count;
MockMetricsManager() : DummyMetricsManager(), add_count(0) {}
void add(Counter::Increment) override {
++add_count;
}
};
class ClientSupervisor {
private:
fnet::frt::StandaloneFRT _client;
public:
ClientSupervisor()
: _client()
{
}
~ClientSupervisor() = default;
FRT_Supervisor& get() { return _client.supervisor(); }
};
ForwardMap
make_forward_filter()
{
ForwardMap result;
result[ns_log::Logger::error] = true;
result[ns_log::Logger::warning] = false;
result[ns_log::Logger::info] = true;
// all other log levels are implicit false
return result;
}
struct RpcForwarderTest : public ::testing::Test {
RpcServer server;
std::shared_ptr<MockMetricsManager> metrics_mgr;
Metrics metrics;
ClientSupervisor supervisor;
RpcForwarder forwarder;
RpcForwarderTest()
: server(),
metrics_mgr(std::make_shared<MockMetricsManager>()),
metrics(metrics_mgr),
forwarder(metrics, make_forward_filter(), supervisor.get(), "localhost", server.get_listen_port(), 60.0, 3)
{
}
void forward_line(const std::string& payload) {
forwarder.forwardLine(make_log_line("info", payload));
}
void forward_line(const std::string& level, const std::string& payload) {
forwarder.forwardLine(make_log_line(level, payload));
}
void forward_bad_line() {
forwarder.forwardLine("badline");
}
void flush() {
forwarder.flush();
}
void expect_messages() {
expect_messages(0, {});
}
void expect_messages(int exp_request_count, const std::vector<std::string>& exp_messages) {
EXPECT_EQ(exp_request_count, server.request_count);
EXPECT_EQ(exp_messages, server.messages);
}
};
TEST_F(RpcForwarderTest, does_not_send_rpc_with_no_log_messages)
{
expect_messages();
flush();
expect_messages();
}
TEST_F(RpcForwarderTest, can_send_rpc_with_single_log_message)
{
forward_line("a");
expect_messages();
flush();
expect_messages(1, {"a"});
}
TEST_F(RpcForwarderTest, can_send_rpc_with_multiple_log_messages)
{
forward_line("a");
forward_line("b");
expect_messages();
flush();
expect_messages(1, {"a", "b"});
}
TEST_F(RpcForwarderTest, automatically_sends_rpc_when_max_messages_limit_is_reached)
{
forward_line("a");
forward_line("b");
expect_messages();
forward_line("c");
expect_messages(1, {"a", "b", "c"});
forward_line("d");
expect_messages(1, {"a", "b", "c"});
forward_line("e");
expect_messages(1, {"a", "b", "c"});
forward_line("f");
expect_messages(2, {"a", "b", "c", "d", "e", "f"});
}
TEST_F(RpcForwarderTest, bad_log_lines_are_counted_but_not_sent)
{
forward_line("a");
forward_bad_line();
EXPECT_EQ(1, forwarder.badLines());
flush();
expect_messages(1, {"a"});
}
TEST_F(RpcForwarderTest, bad_log_lines_count_can_be_reset)
{
forward_bad_line();
EXPECT_EQ(1, forwarder.badLines());
forwarder.resetBadLines();
EXPECT_EQ(0, forwarder.badLines());
}
TEST_F(RpcForwarderTest, metrics_are_updated_for_each_log_message)
{
forward_line("a");
EXPECT_EQ(1, metrics_mgr->add_count);
forward_line("b");
EXPECT_EQ(2, metrics_mgr->add_count);
}
TEST_F(RpcForwarderTest, log_messages_are_filtered_on_log_level)
{
forward_line("fatal", "a");
forward_line("error", "b");
forward_line("warning", "c");
forward_line("config", "d");
forward_line("info", "e");
forward_line("event", "f");
forward_line("debug", "g");
forward_line("spam", "h");
forward_line("null", "i");
flush();
expect_messages(1, {"b", "e"});
EXPECT_EQ(9, metrics_mgr->add_count);
}
TEST_F(RpcForwarderTest, throws_when_rpc_reply_contains_errors)
{
server.reply_with_error = true;
forward_line("a");
EXPECT_THROW(flush(), logdemon::ConnectionException);
}
TEST_F(RpcForwarderTest, throws_when_rpc_reply_does_not_contain_proto_response)
{
server.reply_with_proto_response = false;
forward_line("a");
EXPECT_THROW(flush(), logdemon::DecodeException);
}
GTEST_MAIN_RUN_ALL_TESTS()
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: inettbc.cxx,v $
*
* $Revision: 1.21 $
*
* last change: $Author: mba $ $Date: 2001-11-28 11:25:14 $
*
* 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): _______________________________________
*
*
************************************************************************/
#include "inettbc.hxx"
#pragma hdrstop
#ifndef _COM_SUN_STAR_UNO_ANY_H_
#include <com/sun/star/uno/Any.h>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXCANCEL_HXX //autogen
#include <svtools/cancel.hxx>
#endif
#include <vcl/toolbox.hxx>
#ifndef _VOS_THREAD_HXX //autogen
#include <vos/thread.hxx>
#endif
#ifndef _VOS_MUTEX_HXX //autogen
#include <vos/mutex.hxx>
#endif
#include <svtools/itemset.hxx>
#include <svtools/urihelper.hxx>
#include <svtools/pathoptions.hxx>
#include <svtools/asynclink.hxx>
#include <svtools/inettbc.hxx>
#include <unotools/localfilehelper.hxx>
#include "picklist.hxx"
#include "sfx.hrc"
#include "dispatch.hxx"
#include "viewfrm.hxx"
#include "objsh.hxx"
#include "referers.hxx"
#include "sfxtypes.hxx"
#include "helper.hxx"
//***************************************************************************
// SfxURLToolBoxControl_Impl
//***************************************************************************
SFX_IMPL_TOOLBOX_CONTROL(SfxURLToolBoxControl_Impl,SfxStringItem)
SfxURLToolBoxControl_Impl::SfxURLToolBoxControl_Impl( USHORT nId ,
ToolBox& rBox ,
SfxBindings& rBindings )
: SfxToolBoxControl( nId , rBox , rBindings )
, aURLForwarder( SID_CURRENT_URL, *this )
{
}
SvtURLBox* SfxURLToolBoxControl_Impl::GetURLBox() const
{
return (SvtURLBox*) GetToolBox().GetItemWindow(GetId());
}
//***************************************************************************
void SfxURLToolBoxControl_Impl::OpenURL( const String& rName, BOOL bNew ) const
{
String aName;
String aFilter;
String aOptions;
SfxPickEntry_Impl* pEntry = SfxPickList_Impl::Get()->GetHistoryPickEntryFromTitle( rName );
if ( pEntry )
{
aName = pEntry->aName;
aFilter = pEntry->aFilter;
USHORT nPos = aFilter.Search( '|' );
if( nPos != STRING_NOTFOUND )
{
aOptions = aFilter.Copy( nPos + 1 );
aFilter.Erase( nPos + 1 );
}
}
else
{
INetURLObject aObj( rName );
if ( aObj.GetProtocol() == INET_PROT_NOT_VALID )
{
String aBaseURL = GetURLBox()->GetBaseURL();
aName = SvtURLBox::ParseSmart( rName, aBaseURL, SvtPathOptions().GetWorkPath() );
}
else
aName = rName;
}
if ( !aName.Len() )
return;
SfxViewFrame *pViewFrame = SfxViewFrame::Current();
DBG_ASSERT( pViewFrame, "No ViewFrame ?!" );
if ( pViewFrame )
{
pViewFrame = pViewFrame->GetTopViewFrame();
SfxAllItemSet aSet( pViewFrame->GetPool() );
aSet.Put( SfxStringItem( SID_FILE_NAME, aName ) );
aSet.Put( SfxFrameItem( SID_DOCFRAME , pViewFrame ? pViewFrame->GetFrame() : 0 ) );
aSet.Put( SfxStringItem( SID_REFERER, DEFINE_CONST_UNICODE(SFX_REFERER_USER) ) );
aSet.Put( SfxStringItem( SID_TARGETNAME, String::CreateFromAscii("_default") ) );
if ( aFilter.Len() )
{
aSet.Put( SfxStringItem( SID_FILTER_NAME, aFilter ) );
aSet.Put( SfxStringItem( SID_FILE_FILTEROPTIONS, aOptions ) );
}
SFX_APP()->GetAppDispatcher_Impl()->Execute( SID_OPENURL, SFX_CALLMODE_RECORD, aSet );
}
}
Window* SfxURLToolBoxControl_Impl::CreateItemWindow( Window* pParent )
{
SvtURLBox* pURLBox = new SvtURLBox( pParent );
pURLBox->SetOpenHdl( LINK( this, SfxURLToolBoxControl_Impl, OpenHdl ) );
pURLBox->SetSelectHdl( LINK( this, SfxURLToolBoxControl_Impl, SelectHdl ) );
return pURLBox;
}
IMPL_LINK( SfxURLToolBoxControl_Impl, SelectHdl, void*, pVoid )
{
SvtURLBox* pURLBox = GetURLBox();
String aName( pURLBox->GetURL() );
if ( !pURLBox->IsTravelSelect() && aName.Len() )
{
/*
aName = URIHelper::SmartRelToAbs( aName );
SfxPickList_Impl* pPickList = SfxPickList_Impl::Get();
SfxPickEntry_Impl* pEntry = pPickList->GetHistoryPickEntryFromTitle( aName );
if ( !pEntry )
pPickList->SetCurHistoryPos( pURLBox->GetEntryPos( aName ) );
*/
OpenURL( aName, FALSE );
}
return 1L;
}
IMPL_LINK( SfxURLToolBoxControl_Impl, OpenHdl, void*, pVoid )
{
SvtURLBox* pURLBox = GetURLBox();
OpenURL( pURLBox->GetURL(), pURLBox->IsCtrlOpen() );
SfxViewFrame* pFrm = SfxViewFrame::Current();
if( pFrm )
pFrm->GetFrame()->GrabFocusOnComponent_Impl();
return 1L;
}
//***************************************************************************
void SfxURLToolBoxControl_Impl::StateChanged
(
USHORT nSID,
SfxItemState eState,
const SfxPoolItem* pState
)
{
if( nSID == SID_FOCUSURLBOX )
{
if ( GetURLBox()->IsVisible() )
GetURLBox()->GrabFocus();
}
else if ( !GetURLBox()->IsModified() && SFX_ITEM_AVAILABLE == eState )
{
SvtURLBox* pURLBox = GetURLBox();
SfxPickList_Impl* pPickList = SfxPickList_Impl::Get();
DBG_ASSERT( pPickList , "Pickliste invalid" );
pURLBox->Clear();
const ULONG nPickEntryCount = pPickList->HistoryPickEntryCount();
ULONG nPickEntry;
for ( nPickEntry = 0; nPickEntry < nPickEntryCount; ++nPickEntry )
{
DBG_ASSERT( pPickList->GetHistoryPickEntry( nPickEntry ),
"Pickentry ist invalid" );
INetURLObject aURL ( pPickList->GetHistoryPickEntry( nPickEntry )->aTitle );
pURLBox->InsertEntry( aURL.GetMainURL( INetURLObject::DECODE_WITH_CHARSET ) );
}
const SfxStringItem *pURL = PTR_CAST(SfxStringItem,pState);
String aRep( pURL->GetValue() );
INetURLObject aURL( aRep );
INetProtocol eProt = aURL.GetProtocol();
pURLBox->SetText( aURL.GetURLNoPass() );
}
}
//***************************************************************************
// SfxCancelToolBoxControl_Impl
//***************************************************************************
SFX_IMPL_TOOLBOX_CONTROL(SfxCancelToolBoxControl_Impl,SfxBoolItem)
//***************************************************************************
SfxCancelToolBoxControl_Impl::SfxCancelToolBoxControl_Impl
(
USHORT nId,
ToolBox& rBox,
SfxBindings& rBindings
)
: SfxToolBoxControl( nId, rBox, rBindings )
{
}
//***************************************************************************
SfxPopupWindowType SfxCancelToolBoxControl_Impl::GetPopupWindowType() const
{
return SFX_POPUPWINDOW_ONTIMEOUT;
}
//***************************************************************************
SfxPopupWindow* SfxCancelToolBoxControl_Impl::CreatePopupWindow()
{
PopupMenu aMenu;
BOOL bExecute = FALSE, bSeparator = FALSE;
USHORT nIndex = 1;
for ( SfxCancelManager *pCancelMgr = SfxViewFrame::Current()->GetTopViewFrame()->GetCancelManager();
pCancelMgr;
pCancelMgr = pCancelMgr->GetParent() )
{
for ( USHORT n=0; n<pCancelMgr->GetCancellableCount(); ++n )
{
if ( !n && bSeparator )
{
aMenu.InsertSeparator();
bSeparator = FALSE;
}
String aItemText = pCancelMgr->GetCancellable(n)->GetTitle();
if ( aItemText.Len() > 50 )
{
aItemText.Erase( 48 );
aItemText += DEFINE_CONST_UNICODE("...");
}
aMenu.InsertItem( nIndex++, aItemText );
bExecute = TRUE;
bSeparator = TRUE;
}
}
ToolBox& rToolBox = GetToolBox();
USHORT nId = bExecute ? nId = aMenu.Execute( &rToolBox, rToolBox.GetPointerPosPixel() ) : 0;
GetToolBox().EndSelection();
ClearCache();
UpdateSlot();
if ( nId )
{
String aSearchText = aMenu.GetItemText(nId);
for ( SfxCancelManager *pCancelMgr = SfxViewFrame::Current()->GetTopViewFrame()->GetCancelManager();
pCancelMgr;
pCancelMgr = pCancelMgr->GetParent() )
{
for ( USHORT n = 0; n < pCancelMgr->GetCancellableCount(); ++n )
{
SfxCancellable *pCancel = pCancelMgr->GetCancellable(n);
String aItemText = pCancel->GetTitle();
if ( aItemText.Len() > 50 )
{
aItemText.Erase( 48 );
aItemText += DEFINE_CONST_UNICODE("...");
}
if ( aItemText == aSearchText )
{
pCancel->Cancel();
return 0;
}
}
}
}
return 0;
}
//***************************************************************************
void SfxCancelToolBoxControl_Impl::StateChanged
(
USHORT nSID,
SfxItemState eState,
const SfxPoolItem* pState
)
{
SfxVoidItem aVoidItem( nSID );
//SfxToolBoxControl::StateChanged( nSID, eState, pState ? &aVoidItem : 0 );
SfxToolBoxControl::StateChanged( nSID, eState, pState );
}
<commit_msg>#96921#: use file names in URLBox if possible<commit_after>/*************************************************************************
*
* $RCSfile: inettbc.cxx,v $
*
* $Revision: 1.22 $
*
* last change: $Author: mba $ $Date: 2002-05-29 08:04:16 $
*
* 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): _______________________________________
*
*
************************************************************************/
#include "inettbc.hxx"
#pragma hdrstop
#ifndef _COM_SUN_STAR_UNO_ANY_H_
#include <com/sun/star/uno/Any.h>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXCANCEL_HXX //autogen
#include <svtools/cancel.hxx>
#endif
#include <vcl/toolbox.hxx>
#ifndef _VOS_THREAD_HXX //autogen
#include <vos/thread.hxx>
#endif
#ifndef _VOS_MUTEX_HXX //autogen
#include <vos/mutex.hxx>
#endif
#include <svtools/itemset.hxx>
#include <svtools/urihelper.hxx>
#include <svtools/pathoptions.hxx>
#include <svtools/asynclink.hxx>
#include <svtools/inettbc.hxx>
#include <unotools/localfilehelper.hxx>
#include "picklist.hxx"
#include "sfx.hrc"
#include "dispatch.hxx"
#include "viewfrm.hxx"
#include "objsh.hxx"
#include "referers.hxx"
#include "sfxtypes.hxx"
#include "helper.hxx"
//***************************************************************************
// SfxURLToolBoxControl_Impl
//***************************************************************************
SFX_IMPL_TOOLBOX_CONTROL(SfxURLToolBoxControl_Impl,SfxStringItem)
SfxURLToolBoxControl_Impl::SfxURLToolBoxControl_Impl( USHORT nId ,
ToolBox& rBox ,
SfxBindings& rBindings )
: SfxToolBoxControl( nId , rBox , rBindings )
, aURLForwarder( SID_CURRENT_URL, *this )
{
}
SvtURLBox* SfxURLToolBoxControl_Impl::GetURLBox() const
{
return (SvtURLBox*) GetToolBox().GetItemWindow(GetId());
}
//***************************************************************************
void SfxURLToolBoxControl_Impl::OpenURL( const String& rName, BOOL bNew ) const
{
String aName;
String aFilter;
String aOptions;
SfxPickEntry_Impl* pEntry = SfxPickList_Impl::Get()->GetHistoryPickEntryFromTitle( rName );
if ( pEntry )
{
aName = pEntry->aName;
aFilter = pEntry->aFilter;
USHORT nPos = aFilter.Search( '|' );
if( nPos != STRING_NOTFOUND )
{
aOptions = aFilter.Copy( nPos + 1 );
aFilter.Erase( nPos + 1 );
}
}
else
{
INetURLObject aObj( rName );
if ( aObj.GetProtocol() == INET_PROT_NOT_VALID )
{
String aBaseURL = GetURLBox()->GetBaseURL();
aName = SvtURLBox::ParseSmart( rName, aBaseURL, SvtPathOptions().GetWorkPath() );
}
else
aName = rName;
}
if ( !aName.Len() )
return;
SfxViewFrame *pViewFrame = SfxViewFrame::Current();
DBG_ASSERT( pViewFrame, "No ViewFrame ?!" );
if ( pViewFrame )
{
pViewFrame = pViewFrame->GetTopViewFrame();
SfxAllItemSet aSet( pViewFrame->GetPool() );
aSet.Put( SfxStringItem( SID_FILE_NAME, aName ) );
aSet.Put( SfxFrameItem( SID_DOCFRAME , pViewFrame ? pViewFrame->GetFrame() : 0 ) );
aSet.Put( SfxStringItem( SID_REFERER, DEFINE_CONST_UNICODE(SFX_REFERER_USER) ) );
aSet.Put( SfxStringItem( SID_TARGETNAME, String::CreateFromAscii("_default") ) );
if ( aFilter.Len() )
{
aSet.Put( SfxStringItem( SID_FILTER_NAME, aFilter ) );
aSet.Put( SfxStringItem( SID_FILE_FILTEROPTIONS, aOptions ) );
}
SFX_APP()->GetAppDispatcher_Impl()->Execute( SID_OPENURL, SFX_CALLMODE_RECORD, aSet );
}
}
Window* SfxURLToolBoxControl_Impl::CreateItemWindow( Window* pParent )
{
SvtURLBox* pURLBox = new SvtURLBox( pParent );
pURLBox->SetOpenHdl( LINK( this, SfxURLToolBoxControl_Impl, OpenHdl ) );
pURLBox->SetSelectHdl( LINK( this, SfxURLToolBoxControl_Impl, SelectHdl ) );
return pURLBox;
}
IMPL_LINK( SfxURLToolBoxControl_Impl, SelectHdl, void*, pVoid )
{
SvtURLBox* pURLBox = GetURLBox();
String aName( pURLBox->GetURL() );
if ( !pURLBox->IsTravelSelect() && aName.Len() )
{
/*
aName = URIHelper::SmartRelToAbs( aName );
SfxPickList_Impl* pPickList = SfxPickList_Impl::Get();
SfxPickEntry_Impl* pEntry = pPickList->GetHistoryPickEntryFromTitle( aName );
if ( !pEntry )
pPickList->SetCurHistoryPos( pURLBox->GetEntryPos( aName ) );
*/
OpenURL( aName, FALSE );
}
return 1L;
}
IMPL_LINK( SfxURLToolBoxControl_Impl, OpenHdl, void*, pVoid )
{
SvtURLBox* pURLBox = GetURLBox();
OpenURL( pURLBox->GetURL(), pURLBox->IsCtrlOpen() );
SfxViewFrame* pFrm = SfxViewFrame::Current();
if( pFrm )
pFrm->GetFrame()->GrabFocusOnComponent_Impl();
return 1L;
}
//***************************************************************************
void SfxURLToolBoxControl_Impl::StateChanged
(
USHORT nSID,
SfxItemState eState,
const SfxPoolItem* pState
)
{
if( nSID == SID_FOCUSURLBOX )
{
if ( GetURLBox()->IsVisible() )
GetURLBox()->GrabFocus();
}
else if ( !GetURLBox()->IsModified() && SFX_ITEM_AVAILABLE == eState )
{
SvtURLBox* pURLBox = GetURLBox();
SfxPickList_Impl* pPickList = SfxPickList_Impl::Get();
DBG_ASSERT( pPickList , "Pickliste invalid" );
pURLBox->Clear();
const ULONG nPickEntryCount = pPickList->HistoryPickEntryCount();
ULONG nPickEntry;
for ( nPickEntry = 0; nPickEntry < nPickEntryCount; ++nPickEntry )
{
DBG_ASSERT( pPickList->GetHistoryPickEntry( nPickEntry ),
"Pickentry ist invalid" );
INetURLObject aURL ( pPickList->GetHistoryPickEntry( nPickEntry )->aTitle );
pURLBox->InsertEntry( aURL.GetMainURL( INetURLObject::DECODE_WITH_CHARSET ) );
}
const SfxStringItem *pURL = PTR_CAST(SfxStringItem,pState);
String aRep( pURL->GetValue() );
INetURLObject aURL( aRep );
INetProtocol eProt = aURL.GetProtocol();
if ( eProt == INET_PROT_FILE )
{
pURLBox->SetText( aURL.PathToFileName() );
}
else
pURLBox->SetText( aURL.GetURLNoPass() );
}
}
//***************************************************************************
// SfxCancelToolBoxControl_Impl
//***************************************************************************
SFX_IMPL_TOOLBOX_CONTROL(SfxCancelToolBoxControl_Impl,SfxBoolItem)
//***************************************************************************
SfxCancelToolBoxControl_Impl::SfxCancelToolBoxControl_Impl
(
USHORT nId,
ToolBox& rBox,
SfxBindings& rBindings
)
: SfxToolBoxControl( nId, rBox, rBindings )
{
}
//***************************************************************************
SfxPopupWindowType SfxCancelToolBoxControl_Impl::GetPopupWindowType() const
{
return SFX_POPUPWINDOW_ONTIMEOUT;
}
//***************************************************************************
SfxPopupWindow* SfxCancelToolBoxControl_Impl::CreatePopupWindow()
{
PopupMenu aMenu;
BOOL bExecute = FALSE, bSeparator = FALSE;
USHORT nIndex = 1;
for ( SfxCancelManager *pCancelMgr = SfxViewFrame::Current()->GetTopViewFrame()->GetCancelManager();
pCancelMgr;
pCancelMgr = pCancelMgr->GetParent() )
{
for ( USHORT n=0; n<pCancelMgr->GetCancellableCount(); ++n )
{
if ( !n && bSeparator )
{
aMenu.InsertSeparator();
bSeparator = FALSE;
}
String aItemText = pCancelMgr->GetCancellable(n)->GetTitle();
if ( aItemText.Len() > 50 )
{
aItemText.Erase( 48 );
aItemText += DEFINE_CONST_UNICODE("...");
}
aMenu.InsertItem( nIndex++, aItemText );
bExecute = TRUE;
bSeparator = TRUE;
}
}
ToolBox& rToolBox = GetToolBox();
USHORT nId = bExecute ? nId = aMenu.Execute( &rToolBox, rToolBox.GetPointerPosPixel() ) : 0;
GetToolBox().EndSelection();
ClearCache();
UpdateSlot();
if ( nId )
{
String aSearchText = aMenu.GetItemText(nId);
for ( SfxCancelManager *pCancelMgr = SfxViewFrame::Current()->GetTopViewFrame()->GetCancelManager();
pCancelMgr;
pCancelMgr = pCancelMgr->GetParent() )
{
for ( USHORT n = 0; n < pCancelMgr->GetCancellableCount(); ++n )
{
SfxCancellable *pCancel = pCancelMgr->GetCancellable(n);
String aItemText = pCancel->GetTitle();
if ( aItemText.Len() > 50 )
{
aItemText.Erase( 48 );
aItemText += DEFINE_CONST_UNICODE("...");
}
if ( aItemText == aSearchText )
{
pCancel->Cancel();
return 0;
}
}
}
}
return 0;
}
//***************************************************************************
void SfxCancelToolBoxControl_Impl::StateChanged
(
USHORT nSID,
SfxItemState eState,
const SfxPoolItem* pState
)
{
SfxVoidItem aVoidItem( nSID );
//SfxToolBoxControl::StateChanged( nSID, eState, pState ? &aVoidItem : 0 );
SfxToolBoxControl::StateChanged( nSID, eState, pState );
}
<|endoftext|>
|
<commit_before>#include "show_result.hpp"
void save_result(const char* source_path, char const postFix[], char const outputFormat[], cv::Mat& image)
{
char* destination_path = (char*)calloc( strlen(source_path) + strlen(postFix) + strlen(outputFormat) + strlen("\0"), sizeof(char) );
const char* lastSlash = strrchr ( source_path, '.' );
int lastSlashPos = lastSlash - source_path;
strncpy( destination_path, source_path, lastSlashPos );
int len = strlen( destination_path );
strcpy( destination_path + len, postFix );
len += strlen( postFix );
strcpy( destination_path + len, source_path + lastSlashPos );
len = strlen( destination_path );
strcpy( destination_path + len, outputFormat );
cv::imwrite( destination_path, image);
}
void p_around(unsigned char* data, int before, int after)
{
for(int i = -before; i < after; ++i )
{
if(i == 0)
{
std::cout << "MARKER";
}
std::cout << data[i];
}
}
void draw_clusterNumber(cv::Mat& image, std::vector<IndexTransitionCluster> const & result)
{
std::vector<IndexTransitionCluster> textPoint(result);
std::stable_sort( textPoint.begin(), textPoint.end(), [](auto el1, auto el2){
if(el1.get_clusterNumber() < el2.get_clusterNumber())
{
return true;
}
else
{
return false;
}
} );
textPoint.erase( unique( textPoint.begin(), textPoint.end(), [](auto el1, auto el2){
if(el1.get_clusterNumber() == el2.get_clusterNumber())
{
return true;
}
else
{
return false;
}
} ), textPoint.end() );
std::for_each(textPoint.begin(), textPoint.end(), [&image](auto el){
cv::putText(image, std::to_string(el.get_clusterNumber()), cv::Point(el.col, el.row ), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.4, cv::Scalar(200,20,250));//, 1, 8, false);
std::cout<<el.get_clusterNumber()<<" "<<el.row<<" "<<el.col<<"\n";
});
std::cout<< result.size()<< "\n";
std::cout<< textPoint.size()<< "\n";
}
cv::Mat show_result(cv::Mat const img, std::vector<IndexTransitionCluster> const & result )
{
cv::Mat image = img.clone();
cv::namedWindow( "show_result", cv::WINDOW_AUTOSIZE );
cv::imshow( "show_result", image );
cv::waitKey(0);
if(image.isContinuous())
{
for_each(result.begin(), result.end(), [&image](auto el){
image.data[el.index( image )] = 255;
image.data[el.index( image ) + 1] = 0;
image.data[el.index( image ) + 2] = 255;
});
draw_clusterNumber(image, result);
cv::imshow( "show_result", image );
}
else
{
std::cout<<"notcontionuous\n";
return image;
}
// cv::waitKey(0);
cv::Mat blackImage(image.rows, image.cols, CV_8UC3, cv::Scalar(0,0,0));
for_each(result.begin(), result.end(), [&blackImage](auto el){
blackImage.data[el.index( blackImage )] = 255;
blackImage.data[el.index( blackImage ) + 1] = 0;
blackImage.data[el.index( blackImage ) + 2] = 255;
});
draw_clusterNumber(blackImage, result);
cv::imshow( "show_result", blackImage );
cv::waitKey(0);
return blackImage;
}
std::vector<IndexTransitionCluster> test_on_image(const char* path, double factor, double eps, uint minPts)
{
cv::Mat image;
image = cv::imread(path, CV_LOAD_IMAGE_COLOR);
if(! image.data )
{
std::cout<<"\nwrong path\n";
return std::vector<IndexTransitionCluster>();
}
cv::resize(image, image, cv::Size(), factor, factor, cv::INTER_NEAREST);
cv::Mat imageCpy = image.clone();
cv::Mat imageCpy2 = image.clone();
cv::Mat blackImage;
TYPE acceptanceLevel = 60;
ColorStruct entryBalance{ 1.0, 1.0, 1.0 };
double lightThreshold = 0.2;
double colorThreshold = 0.2;
IterateProcess<TYPE> entryProcess(image, acceptanceLevel, lightThreshold, colorThreshold, entryBalance);
auto result = entryProcess.iterate_HV();
std::cout << result.size() << '\n';
blackImage = show_result( image, std::vector<IndexTransitionCluster>( result.begin(), result.end() ) );
save_result(path, "_noisy", ".png", blackImage);
ColorBalance cba( image, 5u, 6 );
ColorStruct secondBalance = cba.balance( result );
blackImage = show_result( image, std::vector<IndexTransitionCluster>( result.begin(), result.end() ) );
save_result(path, "_detect1", ".png", blackImage);
result.resize( 0 );
lightThreshold = 0.2;
colorThreshold = 0.2;
IterateProcess<TYPE> secondProcess(imageCpy2, acceptanceLevel, lightThreshold, colorThreshold, ColorStruct{ 0.82, 1.05, 1.14 });//secondBalance);
result = secondProcess.iterate_HV();
blackImage = show_result(imageCpy2, std::vector<IndexTransitionCluster>( result.begin(), result.end() ));
save_result(path, "_detect_balanced", ".png", blackImage);
Clustering clustering( result, Distance::distance_fast, eps, minPts);
clustering.points_clustering(&Clustering::check_point_zone_linear);
auto clusters = clustering.getRefVIndexTransitionCluster();
blackImage = show_result(imageCpy, clusters);
save_result(path, "_detect_cluster", ".png", blackImage);
return clusters;
}
int broad_HUE(char* path)
{
cv::Mat image;
image = cv::imread(path, CV_LOAD_IMAGE_COLOR);
if(! image.data )
{
std::cout<<"\nwrong path\n";
return -1;
}
cvtColor(image, image, CV_BGR2HSV);
for(int i =2; i < image.rows * image.cols * 3; i+=3)
{
image.data[i] = 255;
}
cvtColor(image, image, CV_HSV2BGR);
cv::namedWindow( "Display window", cv::WINDOW_AUTOSIZE );
cv::imshow( "Display window", image );
save_result(path, "_OUT1", ".png", image);
cv::Mat cpyImage = image.clone();
cvtColor(cpyImage, cpyImage, CV_BGR2HSV);
for(int i =2; i < cpyImage.rows * cpyImage.cols * 3; i+=3)
{
cpyImage.data[i] = cpyImage.data[i-1];
}
cvtColor(cpyImage, cpyImage, CV_HSV2BGR);
cv::namedWindow( "Display window", cv::WINDOW_AUTOSIZE );
cv::imshow( "Display window", cpyImage );
save_result(path, "_OUT3", ".png", cpyImage);
cvtColor(image, image, CV_BGR2HSV);
for(int i =2; i < image.rows * image.cols * 3; i+=3)
{
image.data[i] = 255;
}
for(int i = 1; i < image.rows * image.cols * 3; i+=3)
{
image.data[i] = 255;
}
cvtColor(image, image, CV_HSV2BGR);
cv::namedWindow( "Display window", cv::WINDOW_AUTOSIZE );
cv::imshow( "Display window", image );
save_result(path, "_OUT2", ".png", image);
return 0;
}
cv::Mat test_canny( char* path, double factor, int dilationSize )
{
cv::Mat image;
image = cv::imread(path, CV_LOAD_IMAGE_COLOR);
if(! image.data )
{
std::cout<<"\nwrong path\n";
return image;
}
cv::resize(image, image, cv::Size(), factor, factor, cv::INTER_NEAREST);
Preprocess preprocess( MakeFilter::box_kernel(11), image);
cv::Mat edges = preprocess.make_thick_kernel( image, dilationSize );
cv::namedWindow( "Canny", cv::WINDOW_AUTOSIZE );
cv::imshow( "Canny", edges );
cv::waitKey(0);
return edges;
}
std::vector<IndexTransitionCluster> index_transition_part(cv::Mat const image, double eps, uint minPts, int compareDistance)
{
cv::Mat imageCpy = image.clone();
cv::Mat imageCpy2 = image.clone();
cv::Mat blackImage;
TYPE acceptanceLevel = 150;
ColorStruct entryBalance{ 1.0, 1.0, 1.0 };
double lightThreshold = 0.03;
double colorThreshold = 0.01;
IterateProcess<TYPE> entryProcess(image, acceptanceLevel, lightThreshold, colorThreshold, entryBalance, compareDistance);
auto result = entryProcess.iterate_HV();
ColorBalance cba( image, 5u, compareDistance );
ColorStruct secondBalance = cba.balance( result );
result.resize( 0 );
//colorThreshold/=2;
IterateProcess<TYPE> secondProcess(imageCpy2, acceptanceLevel, lightThreshold, colorThreshold, secondBalance, compareDistance);//secondBalance);
result = secondProcess.iterate_HV();
Clustering clustering( result, Distance::distance_fast, eps, minPts);
clustering.points_clustering(&Clustering::check_point_zone_linear);
auto clusters = clustering.getRefVIndexTransitionCluster();
#ifdef VERBOSE
blackImage = show_result( image, std::vector<IndexTransitionCluster>( result.begin(), result.end() ) );
blackImage = show_result(imageCpy2, std::vector<IndexTransitionCluster>( result.begin(), result.end() ));
blackImage = show_result(imageCpy, clusters);
#endif
return clusters;
}
cv::Mat test_gauss_directed(const char* path, double factor, int dilationSize )
{
cv::Mat image;
image = cv::imread(path, CV_LOAD_IMAGE_COLOR);
if(! image.data )
{
std::cout<<"\nwrong path\n";
return image;
}
cv::resize(image, image, cv::Size(), factor, factor, cv::INTER_NEAREST);
cv::Mat cImage = image.clone();
bilateralFilter( cImage, image, 30, 150, 150, cv::BORDER_REFLECT );
// int sigma = 2;
// cv::GaussianBlur( image, image, cv::Size(sigma*4+1, sigma*4+1), sigma);
auto idTrCluster = index_transition_part( image, 3.0, 1, 3 );
std::vector<IndexTransition> idTr( idTrCluster.begin(), idTrCluster.end() );
Preprocess preprocess( MakeFilter::box_kernel(3), image);
preprocess.make_thick_kernel(cImage, dilationSize);
preprocess.rm_out_edge_detected( idTr );
#ifdef VERBOSE
show_result( image, std::vector<IndexTransitionCluster>(idTr.begin(), idTr.end()));
#endif
Filter filter(cImage, idTr, 20, 5, 1, 20);
cv::Mat result = filter.filter_image();
ContourTransition contourTransition(image);
contourTransition.bw_push_transition( idTr );
cv::Mat matTrans = contourTransition.show_matDataTrans();
#ifdef VERBOSE
cv::namedWindow( "matTrans", cv::WINDOW_AUTOSIZE );
cv::imshow( "matTrans", matTrans );
cv::waitKey(0);
// cv::namedWindow( "thickKernel", cv::WINDOW_AUTOSIZE );
// cv::imshow( "thickKernel", preprocess.get_thickKernel() );
cv::namedWindow( "GaussFiltered", cv::WINDOW_AUTOSIZE );
cv::imshow( "GaussFiltered", result );
cv::waitKey(0);
#endif
return result;
}<commit_msg>bilateral_04<commit_after>#include "show_result.hpp"
void save_result(const char* source_path, char const postFix[], char const outputFormat[], cv::Mat& image)
{
char* destination_path = (char*)calloc( strlen(source_path) + strlen(postFix) + strlen(outputFormat) + strlen("\0"), sizeof(char) );
const char* lastSlash = strrchr ( source_path, '.' );
int lastSlashPos = lastSlash - source_path;
strncpy( destination_path, source_path, lastSlashPos );
int len = strlen( destination_path );
strcpy( destination_path + len, postFix );
len += strlen( postFix );
strcpy( destination_path + len, source_path + lastSlashPos );
len = strlen( destination_path );
strcpy( destination_path + len, outputFormat );
cv::imwrite( destination_path, image);
}
void p_around(unsigned char* data, int before, int after)
{
for(int i = -before; i < after; ++i )
{
if(i == 0)
{
std::cout << "MARKER";
}
std::cout << data[i];
}
}
void draw_clusterNumber(cv::Mat& image, std::vector<IndexTransitionCluster> const & result)
{
std::vector<IndexTransitionCluster> textPoint(result);
std::stable_sort( textPoint.begin(), textPoint.end(), [](auto el1, auto el2){
if(el1.get_clusterNumber() < el2.get_clusterNumber())
{
return true;
}
else
{
return false;
}
} );
textPoint.erase( unique( textPoint.begin(), textPoint.end(), [](auto el1, auto el2){
if(el1.get_clusterNumber() == el2.get_clusterNumber())
{
return true;
}
else
{
return false;
}
} ), textPoint.end() );
std::for_each(textPoint.begin(), textPoint.end(), [&image](auto el){
cv::putText(image, std::to_string(el.get_clusterNumber()), cv::Point(el.col, el.row ), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.4, cv::Scalar(200,20,250));//, 1, 8, false);
std::cout<<el.get_clusterNumber()<<" "<<el.row<<" "<<el.col<<"\n";
});
std::cout<< result.size()<< "\n";
std::cout<< textPoint.size()<< "\n";
}
cv::Mat show_result(cv::Mat const img, std::vector<IndexTransitionCluster> const & result )
{
cv::Mat image = img.clone();
cv::namedWindow( "show_result", cv::WINDOW_AUTOSIZE );
cv::imshow( "show_result", image );
cv::waitKey(0);
if(image.isContinuous())
{
for_each(result.begin(), result.end(), [&image](auto el){
image.data[el.index( image )] = 255;
image.data[el.index( image ) + 1] = 0;
image.data[el.index( image ) + 2] = 255;
});
draw_clusterNumber(image, result);
cv::imshow( "show_result", image );
}
else
{
std::cout<<"notcontionuous\n";
return image;
}
// cv::waitKey(0);
cv::Mat blackImage(image.rows, image.cols, CV_8UC3, cv::Scalar(0,0,0));
for_each(result.begin(), result.end(), [&blackImage](auto el){
blackImage.data[el.index( blackImage )] = 255;
blackImage.data[el.index( blackImage ) + 1] = 0;
blackImage.data[el.index( blackImage ) + 2] = 255;
});
draw_clusterNumber(blackImage, result);
cv::imshow( "show_result", blackImage );
cv::waitKey(0);
return blackImage;
}
std::vector<IndexTransitionCluster> test_on_image(const char* path, double factor, double eps, uint minPts)
{
cv::Mat image;
image = cv::imread(path, CV_LOAD_IMAGE_COLOR);
if(! image.data )
{
std::cout<<"\nwrong path\n";
return std::vector<IndexTransitionCluster>();
}
cv::resize(image, image, cv::Size(), factor, factor, cv::INTER_NEAREST);
cv::Mat imageCpy = image.clone();
cv::Mat imageCpy2 = image.clone();
cv::Mat blackImage;
TYPE acceptanceLevel = 60;
ColorStruct entryBalance{ 1.0, 1.0, 1.0 };
double lightThreshold = 0.2;
double colorThreshold = 0.2;
IterateProcess<TYPE> entryProcess(image, acceptanceLevel, lightThreshold, colorThreshold, entryBalance);
auto result = entryProcess.iterate_HV();
std::cout << result.size() << '\n';
blackImage = show_result( image, std::vector<IndexTransitionCluster>( result.begin(), result.end() ) );
save_result(path, "_noisy", ".png", blackImage);
ColorBalance cba( image, 5u, 6 );
ColorStruct secondBalance = cba.balance( result );
blackImage = show_result( image, std::vector<IndexTransitionCluster>( result.begin(), result.end() ) );
save_result(path, "_detect1", ".png", blackImage);
result.resize( 0 );
lightThreshold = 0.2;
colorThreshold = 0.2;
IterateProcess<TYPE> secondProcess(imageCpy2, acceptanceLevel, lightThreshold, colorThreshold, ColorStruct{ 0.82, 1.05, 1.14 });//secondBalance);
result = secondProcess.iterate_HV();
blackImage = show_result(imageCpy2, std::vector<IndexTransitionCluster>( result.begin(), result.end() ));
save_result(path, "_detect_balanced", ".png", blackImage);
Clustering clustering( result, Distance::distance_fast, eps, minPts);
clustering.points_clustering(&Clustering::check_point_zone_linear);
auto clusters = clustering.getRefVIndexTransitionCluster();
blackImage = show_result(imageCpy, clusters);
save_result(path, "_detect_cluster", ".png", blackImage);
return clusters;
}
int broad_HUE(char* path)
{
cv::Mat image;
image = cv::imread(path, CV_LOAD_IMAGE_COLOR);
if(! image.data )
{
std::cout<<"\nwrong path\n";
return -1;
}
cvtColor(image, image, CV_BGR2HSV);
for(int i =2; i < image.rows * image.cols * 3; i+=3)
{
image.data[i] = 255;
}
cvtColor(image, image, CV_HSV2BGR);
cv::namedWindow( "Display window", cv::WINDOW_AUTOSIZE );
cv::imshow( "Display window", image );
save_result(path, "_OUT1", ".png", image);
cv::Mat cpyImage = image.clone();
cvtColor(cpyImage, cpyImage, CV_BGR2HSV);
for(int i =2; i < cpyImage.rows * cpyImage.cols * 3; i+=3)
{
cpyImage.data[i] = cpyImage.data[i-1];
}
cvtColor(cpyImage, cpyImage, CV_HSV2BGR);
cv::namedWindow( "Display window", cv::WINDOW_AUTOSIZE );
cv::imshow( "Display window", cpyImage );
save_result(path, "_OUT3", ".png", cpyImage);
cvtColor(image, image, CV_BGR2HSV);
for(int i =2; i < image.rows * image.cols * 3; i+=3)
{
image.data[i] = 255;
}
for(int i = 1; i < image.rows * image.cols * 3; i+=3)
{
image.data[i] = 255;
}
cvtColor(image, image, CV_HSV2BGR);
cv::namedWindow( "Display window", cv::WINDOW_AUTOSIZE );
cv::imshow( "Display window", image );
save_result(path, "_OUT2", ".png", image);
return 0;
}
cv::Mat test_canny( char* path, double factor, int dilationSize )
{
cv::Mat image;
image = cv::imread(path, CV_LOAD_IMAGE_COLOR);
if(! image.data )
{
std::cout<<"\nwrong path\n";
return image;
}
cv::resize(image, image, cv::Size(), factor, factor, cv::INTER_NEAREST);
Preprocess preprocess( MakeFilter::box_kernel(11), image);
cv::Mat edges = preprocess.make_thick_kernel( image, dilationSize );
cv::namedWindow( "Canny", cv::WINDOW_AUTOSIZE );
cv::imshow( "Canny", edges );
cv::waitKey(0);
return edges;
}
std::vector<IndexTransitionCluster> index_transition_part(cv::Mat const image, double eps, uint minPts, int compareDistance)
{
cv::Mat imageCpy = image.clone();
cv::Mat imageCpy2 = image.clone();
cv::Mat blackImage;
TYPE acceptanceLevel = 150;
ColorStruct entryBalance{ 1.0, 1.0, 1.0 };
double lightThreshold = 0.03;
double colorThreshold = 0.01;
IterateProcess<TYPE> entryProcess(image, acceptanceLevel, lightThreshold, colorThreshold, entryBalance, compareDistance);
auto result = entryProcess.iterate_HV();
ColorBalance cba( image, 5u, compareDistance );
ColorStruct secondBalance = cba.balance( result );
result.resize( 0 );
//colorThreshold/=2;
IterateProcess<TYPE> secondProcess(imageCpy2, acceptanceLevel, lightThreshold, colorThreshold, secondBalance, compareDistance);//secondBalance);
result = secondProcess.iterate_HV();
Clustering clustering( result, Distance::distance_fast, eps, minPts);
clustering.points_clustering(&Clustering::check_point_zone_linear);
auto clusters = clustering.getRefVIndexTransitionCluster();
#ifdef VERBOSE
blackImage = show_result( image, std::vector<IndexTransitionCluster>( result.begin(), result.end() ) );
blackImage = show_result(imageCpy2, std::vector<IndexTransitionCluster>( result.begin(), result.end() ));
blackImage = show_result(imageCpy, clusters);
#endif
return clusters;
}
cv::Mat test_gauss_directed(const char* path, double factor, int dilationSize )
{
cv::Mat image;
image = cv::imread(path, CV_LOAD_IMAGE_COLOR);
if(! image.data )
{
std::cout<<"\nwrong path\n";
return image;
}
cv::resize(image, image, cv::Size(), factor, factor, cv::INTER_NEAREST);
cv::Mat cImage = image.clone();
bilateralFilter( cImage, image, 30, 150, 150, cv::BORDER_REFLECT );
// int sigma = 2;
// cv::GaussianBlur( image, image, cv::Size(sigma*4+1, sigma*4+1), sigma);
auto idTrCluster = index_transition_part( image, 3.0, 1, 3 );
std::vector<IndexTransition> idTr( idTrCluster.begin(), idTrCluster.end() );
Preprocess preprocess( MakeFilter::box_kernel(3), image);
preprocess.make_thick_kernel(cImage, dilationSize);
preprocess.rm_out_edge_detected( idTr );
#ifdef VERBOSE
show_result( image, std::vector<IndexTransitionCluster>(idTr.begin(), idTr.end()));
#endif
Filter filter(cImage, idTr, 20, 5, 1, 20);
cv::Mat result = filter.filter_image();
/*
ContourTransition contourTransition(image);
contourTransition.bw_push_transition( idTr );
cv::Mat matTrans = contourTransition.show_matDataTrans();
*/
#ifdef VERBOSE
cv::namedWindow( "matTrans", cv::WINDOW_AUTOSIZE );
cv::imshow( "matTrans", matTrans );
cv::waitKey(0);
// cv::namedWindow( "thickKernel", cv::WINDOW_AUTOSIZE );
// cv::imshow( "thickKernel", preprocess.get_thickKernel() );
cv::namedWindow( "GaussFiltered", cv::WINDOW_AUTOSIZE );
cv::imshow( "GaussFiltered", result );
cv::waitKey(0);
#endif
return result;
}<|endoftext|>
|
<commit_before>
#include "mgsRileyDescending.h"
#include "appConstants.h"
int lineColor = 0;
int strokeColor = 0;
int fillColor = 0;
// vector<vector<float>> myLines;
// myLines = { x, y, columns, rows, speed, accel, wavePeriod, wavePhase, distance };
// void loadLine(x,y,cols,rows,speed,accel,wavePeriod,wavePhase,distance){
// myLines.push_back(x,y,cols,rows,speed,accel,wavePeriod,wavePhase,distance);
// }
// void getLineX(int lineNumber){
// }
// addQuadToMesh:
// Vertices should go in the following order
// p0---------p1
// | |
// | |
// p2---------p3
void addQuadToMesh(ofMesh& m, const ofVec3f& p0, const ofVec3f& p1, const ofVec3f& p2, const ofVec3f& p3){
int i = m.getNumVertices();
m.addVertex(p0);
m.addVertex(p1);
m.addVertex(p2);
m.addVertex(p3);
m.addIndex(i);
m.addIndex(i+1);
m.addIndex(i+2);
m.addIndex(i);
m.addIndex(i+2);
m.addIndex(i+3);
}
void mgsRileyDescending::setup(){
loadCode("mgsScene/exampleCode.cpp");
setAuthor("Michael Simpson");
setOriginalArtist("Bridget Riley - Study for Shuttle - 1964");
parameters.add(rows.set("Rows", 127, 1, 200));
rows.addListener(this, &mgsRileyDescending::setupLines);
parameters.add(lineHeight.set("Row Height", 5, 1, 100));
lineHeight.addListener(this, &mgsRileyDescending::setupLinesF);
parameters.add(columns.set("Columns", 9, 1, 200));
columns.addListener(this, &mgsRileyDescending::setupLines);
parameters.add(lineWidth.set("Column Width", 54, 1, 300));
lineWidth.addListener(this, &mgsRileyDescending::setupLinesF);
parameters.add(lineSpacing.set("Depth Amount", 14, 1, 100));
lineSpacing.addListener(this, &mgsRileyDescending::setupLinesF);
parameters.add(wavePeriodParam.set("Number of Waves", 2, 0, 60));
wavePeriodParam.addListener(this, &mgsRileyDescending::setupLinesF);
parameters.add(wavePhaseParam.set("Wave Phase", 180.0, 0, 360));
wavePhaseParam.addListener(this, &mgsRileyDescending::setupLinesF);
parameters.add(distanceParam.set("Distance Between", 19.6888, 1, 100));
distanceParam.addListener(this, &mgsRileyDescending::setupLinesF);
parameters.add(speedParam.set("Speed", 1.4898, 0.0, 4.0));
speedParam.addListener(this, &mgsRileyDescending::setupLinesF);
parameters.add(accelParam.set("Acceleration", 10.0, 1, 360));
accelParam.addListener(this, &mgsRileyDescending::setupLinesF);
parameters.add(animated.set("Animated", true));
animated.addListener(this, &mgsRileyDescending::setupLinesB);
// parameters.add(yOffset.set("Y-Offset", ));
//
// xOffset, lineWidth, lineHeight, lineSpacing, minWavePeriod, maxWavePeriod, minAccel, maxAccel, minWavePhase, maxWavePhase, <#Args ¶meters...#>)
quad1.setMode(OF_PRIMITIVE_TRIANGLES);
quad2.setMode(OF_PRIMITIVE_TRIANGLES);
quad3.setMode(OF_PRIMITIVE_TRIANGLES);
quad4.setMode(OF_PRIMITIVE_TRIANGLES);
quad1.disableColors();
quad2.disableColors();
quad3.disableColors();
quad4.disableColors();
xOffset = 10;
yOffset = -100;
lines.clear();
for (int i = 0; i < columns; i++) {
lines.push_back(RileyLine(columns, rows, speedParam, accelParam, wavePeriodParam, distanceParam, wavePhaseParam));
}
}
void mgsRileyDescending::update() {
}
void mgsRileyDescending::draw() {
ofBackground(0);
ofSetColor(fillColor);
ofFill();
for (int x = 0; x < columns; x++) {
if(animated){
lines[x].speed = speedParam;
} else {
lines[x].speed = 0;
}
lines[x].update(lineSpacing, lineHeight, rows);
quad1.clear();
quad2.clear();
quad3.clear();
quad4.clear();
for(int y = 0; y < rows - 1; y++) {
float x0 = (x + .5) * lineWidth + lines[x].X(y);
float y0 = lines[x].Y(y);
float x1 = (x + .5) * lineWidth + lines[x].X(y + 1);
float y1 = lines[x].Y(y + 1);
if ((y & 1) == 0) {
if ((x != 0 && y != 3)) {
ofSetColor(255);
ofFill();
addQuadToMesh(quad1,
ofVec3f((x * lineWidth)+xOffset, (y * lineHeight)+yOffset, 0),
ofVec3f(x0+xOffset, y0+yOffset, 0),
ofVec3f(x1+xOffset, y1+yOffset, 0),
ofVec3f((x * lineWidth)+xOffset, ((y + 1) * lineHeight)+yOffset, 0));
quad1.draw();
ofSetColor(0);
ofFill();
addQuadToMesh(quad3,
ofVec3f((x * lineWidth)+xOffset, ((y * lineHeight)-lineHeight)+yOffset, 0),
ofVec3f(x0+xOffset, (y0-lineHeight)+yOffset, 0),
ofVec3f(x1+xOffset, (y1-lineHeight)+yOffset, 0),
ofVec3f((x * lineWidth)+xOffset, (((y + 1) * lineHeight)-lineHeight)+yOffset, 0));
quad3.draw();
}
if ((x != columns-1 && y != rows-1)) {
ofSetColor(255);
ofFill();
addQuadToMesh(quad2,
ofVec3f(x0+xOffset, y0+yOffset, 0),
ofVec3f(((x + 1) * lineWidth)+xOffset, (y * lineHeight)+yOffset, 0),
ofVec3f(((x + 1) * lineWidth)+xOffset, ((y + 1) * lineHeight)+yOffset, 0),
ofVec3f(x1+xOffset, y1+yOffset, 0));
quad2.draw();
ofSetColor(0);
ofFill();
addQuadToMesh(quad4,
ofVec3f(x0+xOffset, y0-lineHeight+yOffset, 0),
ofVec3f(((x + 1) * lineWidth)+xOffset, ((y * lineHeight)-lineHeight)+yOffset, 0),
ofVec3f(((x + 1) * lineWidth)+xOffset, (((y + 1) * lineHeight)-lineHeight)+yOffset, 0),
ofVec3f(x1+xOffset, (y1-lineHeight)+yOffset, 0));
quad4.draw();
}
}
}
}
}
void mgsRileyDescending::setupLinesB(bool& l) {
// lines.clear();
// for (int i = 0; i < columns; i++) {
// lines.push_back(RileyLine(i, columns, rows, speedParam, accelParam, wavePeriodParam, distanceParam, wavePhaseParam));
// }
}
void mgsRileyDescending::setupLinesF(float& l) {
lines.clear();
for (int i = 0; i < columns; i++) {
lines.push_back(RileyLine(columns, rows, speedParam, accelParam, wavePeriodParam, distanceParam, wavePhaseParam));
}
}
void mgsRileyDescending::setupLines(int& l) {
lines.clear();
for (int i = 0; i < columns; i++) {
lines.push_back(RileyLine(columns, rows, speedParam, accelParam, wavePeriodParam, distanceParam, wavePhaseParam));
}
}
<commit_msg>update psuedocode<commit_after>
#include "mgsRileyDescending.h"
#include "appConstants.h"
int lineColor = 0;
int strokeColor = 0;
int fillColor = 0;
// vector<vector<float>> myLines;
// myLines = { x, y, columns, rows, speed, accel, wavePeriod, wavePhase, distance };
// void loadLine(x,y,cols,rows,speed,accel,wavePeriod,wavePhase,distance){
// myLines.push_back(x,y,cols,rows,speed,accel,wavePeriod,wavePhase,distance);
// }
// void getLineX(int lineNumber){
// }
// addQuadToMesh:
// Vertices should go in the following order
// p0---------p1
// | |
// | |
// p2---------p3
void addQuadToMesh(ofMesh& m, const ofVec3f& p0, const ofVec3f& p1, const ofVec3f& p2, const ofVec3f& p3){
int i = m.getNumVertices();
m.addVertex(p0);
m.addVertex(p1);
m.addVertex(p2);
m.addVertex(p3);
m.addIndex(i);
m.addIndex(i+1);
m.addIndex(i+2);
m.addIndex(i);
m.addIndex(i+2);
m.addIndex(i+3);
}
void mgsRileyDescending::setup(){
loadCode("scenes/mgsRileyDescending/exampleCode.cpp");
setAuthor("Michael Simpson");
setOriginalArtist("Bridget Riley - Study for Shuttle - 1964");
parameters.add(rows.set("Rows", 127, 1, 200));
rows.addListener(this, &mgsRileyDescending::setupLines);
parameters.add(lineHeight.set("Row Height", 5, 1, 100));
lineHeight.addListener(this, &mgsRileyDescending::setupLinesF);
parameters.add(columns.set("Columns", 9, 1, 200));
columns.addListener(this, &mgsRileyDescending::setupLines);
parameters.add(lineWidth.set("Column Width", 54, 1, 300));
lineWidth.addListener(this, &mgsRileyDescending::setupLinesF);
parameters.add(lineSpacing.set("Depth Amount", 14, 1, 100));
lineSpacing.addListener(this, &mgsRileyDescending::setupLinesF);
parameters.add(wavePeriodParam.set("Number of Waves", 2, 0, 60));
wavePeriodParam.addListener(this, &mgsRileyDescending::setupLinesF);
parameters.add(wavePhaseParam.set("Wave Phase", 180.0, 0, 360));
wavePhaseParam.addListener(this, &mgsRileyDescending::setupLinesF);
parameters.add(distanceParam.set("Distance Between", 19.6888, 1, 100));
distanceParam.addListener(this, &mgsRileyDescending::setupLinesF);
parameters.add(speedParam.set("Speed", 1.4898, 0.0, 4.0));
speedParam.addListener(this, &mgsRileyDescending::setupLinesF);
parameters.add(accelParam.set("Acceleration", 10.0, 1, 360));
accelParam.addListener(this, &mgsRileyDescending::setupLinesF);
parameters.add(animated.set("Animated", true));
animated.addListener(this, &mgsRileyDescending::setupLinesB);
// parameters.add(yOffset.set("Y-Offset", ));
//
// xOffset, lineWidth, lineHeight, lineSpacing, minWavePeriod, maxWavePeriod, minAccel, maxAccel, minWavePhase, maxWavePhase, <#Args ¶meters...#>)
quad1.setMode(OF_PRIMITIVE_TRIANGLES);
quad2.setMode(OF_PRIMITIVE_TRIANGLES);
quad3.setMode(OF_PRIMITIVE_TRIANGLES);
quad4.setMode(OF_PRIMITIVE_TRIANGLES);
quad1.disableColors();
quad2.disableColors();
quad3.disableColors();
quad4.disableColors();
xOffset = 10;
yOffset = -100;
lines.clear();
for (int i = 0; i < columns; i++) {
lines.push_back(RileyLine(columns, rows, speedParam, accelParam, wavePeriodParam, distanceParam, wavePhaseParam));
}
}
void mgsRileyDescending::update() {
}
void mgsRileyDescending::draw() {
ofBackground(0);
ofSetColor(fillColor);
ofFill();
for (int x = 0; x < columns; x++) {
if(animated){
lines[x].speed = speedParam;
} else {
lines[x].speed = 0;
}
lines[x].update(lineSpacing, lineHeight, rows);
quad1.clear();
quad2.clear();
quad3.clear();
quad4.clear();
for(int y = 0; y < rows - 1; y++) {
float x0 = (x + .5) * lineWidth + lines[x].X(y);
float y0 = lines[x].Y(y);
float x1 = (x + .5) * lineWidth + lines[x].X(y + 1);
float y1 = lines[x].Y(y + 1);
if ((y & 1) == 0) {
if ((x != 0 && y != 3)) {
ofSetColor(255);
ofFill();
addQuadToMesh(quad1,
ofVec3f((x * lineWidth)+xOffset, (y * lineHeight)+yOffset, 0),
ofVec3f(x0+xOffset, y0+yOffset, 0),
ofVec3f(x1+xOffset, y1+yOffset, 0),
ofVec3f((x * lineWidth)+xOffset, ((y + 1) * lineHeight)+yOffset, 0));
quad1.draw();
ofSetColor(0);
ofFill();
addQuadToMesh(quad3,
ofVec3f((x * lineWidth)+xOffset, ((y * lineHeight)-lineHeight)+yOffset, 0),
ofVec3f(x0+xOffset, (y0-lineHeight)+yOffset, 0),
ofVec3f(x1+xOffset, (y1-lineHeight)+yOffset, 0),
ofVec3f((x * lineWidth)+xOffset, (((y + 1) * lineHeight)-lineHeight)+yOffset, 0));
quad3.draw();
}
if ((x != columns-1 && y != rows-1)) {
ofSetColor(255);
ofFill();
addQuadToMesh(quad2,
ofVec3f(x0+xOffset, y0+yOffset, 0),
ofVec3f(((x + 1) * lineWidth)+xOffset, (y * lineHeight)+yOffset, 0),
ofVec3f(((x + 1) * lineWidth)+xOffset, ((y + 1) * lineHeight)+yOffset, 0),
ofVec3f(x1+xOffset, y1+yOffset, 0));
quad2.draw();
ofSetColor(0);
ofFill();
addQuadToMesh(quad4,
ofVec3f(x0+xOffset, y0-lineHeight+yOffset, 0),
ofVec3f(((x + 1) * lineWidth)+xOffset, ((y * lineHeight)-lineHeight)+yOffset, 0),
ofVec3f(((x + 1) * lineWidth)+xOffset, (((y + 1) * lineHeight)-lineHeight)+yOffset, 0),
ofVec3f(x1+xOffset, (y1-lineHeight)+yOffset, 0));
quad4.draw();
}
}
}
}
}
void mgsRileyDescending::setupLinesB(bool& l) {
// lines.clear();
// for (int i = 0; i < columns; i++) {
// lines.push_back(RileyLine(i, columns, rows, speedParam, accelParam, wavePeriodParam, distanceParam, wavePhaseParam));
// }
}
void mgsRileyDescending::setupLinesF(float& l) {
lines.clear();
for (int i = 0; i < columns; i++) {
lines.push_back(RileyLine(columns, rows, speedParam, accelParam, wavePeriodParam, distanceParam, wavePhaseParam));
}
}
void mgsRileyDescending::setupLines(int& l) {
lines.clear();
for (int i = 0; i < columns; i++) {
lines.push_back(RileyLine(columns, rows, speedParam, accelParam, wavePeriodParam, distanceParam, wavePhaseParam));
}
}
<|endoftext|>
|
<commit_before>/*!
* \file Configurator.cpp
* \brief File containing definitions of Configurator class methods.
*
* \author tkornuta
* \date Apr 8, 2010
*/
#include "Configurator.hpp"
#include "DisCODeException.hpp"
#include "Logger.hpp"
#include "Component.hpp"
#include "Event.hpp"
#include "EventHandler.hpp"
#include "DataStreamInterface.hpp"
#include "ComponentManager.hpp"
#include "ExecutorManager.hpp"
#include "ConnectionManager.hpp"
#include <boost/filesystem.hpp>
#include <boost/property_tree/xml_parser.hpp>
namespace Core {
using namespace boost;
Configurator::Configurator()
{
}
Configurator::~Configurator()
{
}
Task Configurator::loadConfiguration(std::string filename_, const std::vector<std::pair<std::string, std::string> > & overrides)
{
// Set filename pointer to given one.
configuration_filename = filename_;
ptree * tmp_node;
// Check whether config file exists.
if (!filesystem::exists(configuration_filename)) {
throw Common::DisCODeException(std::string("Configuration: File '") + configuration_filename + "' doesn't exist.\n");
}
else {
Task task;
// Load and parse configuration from file.
try {
read_xml(configuration_filename, configuration);
}
catch(xml_parser_error&) {
LOG(LFATAL) << "Configuration: Couldn't parse '" << configuration_filename << "' file.\n";
throw Common::DisCODeException(std::string("Configuration: Couldn't parse '") + configuration_filename + "' file.\n");
}
// Take overrides into account
for (size_t i = 0; i < overrides.size(); ++i) {
std::cout << overrides[i].first << " set to " << overrides[i].second << std::endl;
configuration.put(std::string("Task.")+overrides[i].first, overrides[i].second);
}
try {
tmp_node = &(configuration.get_child("Task.Executors"));
loadExecutors(tmp_node, task);
}
catch(ptree_bad_path&) {
LOG(LFATAL) << "No Executors branch in configuration file!\n";
}
try {
tmp_node = &(configuration.get_child("Task.Components"));
loadComponents(tmp_node, task);
}
catch(ptree_bad_path&) {
LOG(LFATAL) << "No Components branch in configuration file!\n";
}
try {
tmp_node = &(configuration.get_child("Task.Events"));
loadEvents(tmp_node);
}
catch(ptree_bad_path&) {
LOG(LFATAL) << "No Events branch in configuration file!\n";
}
try {
tmp_node = &(configuration.get_child("Task.DataStreams"));
loadConnections(tmp_node);
}
catch(ptree_bad_path&) {
LOG(LFATAL) << "No DataStreams branch in configuration file!\n";
}
LOG(LINFO) << "Configuration: File \'" << configuration_filename << "\' loaded.\n";
return task;
}//: else
}
void Configurator::loadExecutors(const ptree * node, Task & task) {
LOG(LINFO) << "Creating execution threads\n";
Executor * ex;
BOOST_FOREACH( TreeNode nd, *node) {
ptree tmp = nd.second;
ex = executorManager->createExecutor(nd.first, tmp.get("<xmlattr>.type", "UNKNOWN"));
ex->load(tmp);
task+=ex;
}
}
void Configurator::loadComponents(const ptree * node, Task & task) {
LOG(LINFO) << "Loading required components\n";
Base::Component * kern;
Executor * ex;
std::string name;
std::string type;
std::string thread;
std::string group;
std::string include;
BOOST_FOREACH( TreeNode nd, *node) {
ptree tmp = nd.second;
name = nd.first;
// ignore coments in tast file
if (name == "<xmlcomment>") continue;
type = tmp.get("<xmlattr>.type", "UNKNOWN");
thread = tmp.get("<xmlattr>.thread", "UNKNOWN");
group = tmp.get("<xmlattr>.group", "DEFAULT");
include = tmp.get("<xmlattr>.include", "");
LOG(LTRACE) << "Component to be created: " << name << " of type " << type << " in thread " << thread << ", subtask " << group << "\n";
kern = componentManager->createComponent(name, type);
if (include != "") {
try {
read_xml(include, tmp);
}
catch(xml_parser_error&) {
LOG(LFATAL) << "Configuration: Couldn't parse include file '" << include << "' for component " << name << ".\n";
throw Common::DisCODeException(std::string("Configuration: Couldn't parse '") + include + "' file.\n");
}
}
if (kern->getProperties())
kern->getProperties()->load(tmp);
kern->initialize();
ex = executorManager->getExecutor(thread);
ex->addComponent(name, kern);
LOG(LTRACE) << "Adding component " << name << " to subtask " << group << "\n";
task[group] += kern;
component_executor[name] = thread;
}
}
void Configurator::loadEvents(const ptree * node) {
LOG(LINFO) << "Connecting events\n";
std::string src, dst, name, caller, receiver, type;
Base::Component * src_k, * dst_k;
Base::EventHandlerInterface * h;
Base::Event * e;
BOOST_FOREACH( TreeNode nd, *node ) {
ptree tmp = nd.second;
name = nd.first;
if (name == "<xmlcomment>") continue;
src = tmp.get("<xmlattr>.source", "");
if (src == "") {
LOG(LERROR) << "No event source specified...\n";
continue;
}
dst = tmp.get("<xmlattr>.destination", "");
if (dst == "") {
LOG(LERROR) << "No event destination specified...\n";
continue;
}
type=tmp.get("type", "");
caller = src.substr(0, src.find_first_of("."));
src = src.substr(src.find_first_of(".")+1);
receiver = dst.substr(0, dst.find_first_of("."));
dst = dst.substr(dst.find_first_of(".")+1);
src_k = componentManager->getComponent(caller);
dst_k = componentManager->getComponent(receiver);
h = dst_k->getHandler(dst);
if (!h) {
LOG(LERROR) << "Component " << receiver << " has no event handler named '" << dst << "'!\n";
continue;
}
e = src_k->getEvent(src);
if (!e) {
LOG(LERROR) << "Component " << caller << " has no event named '" << src << "'!\n";
continue;
}
// asynchronous connection
if ( (component_executor[caller] != component_executor[receiver]) || (type=="async")) {
Executor * ex = executorManager->getExecutor(component_executor[receiver]);
h = ex->scheduleHandler(h);
e->addAsyncHandler(h);
} else {
e->addHandler(h);
}
LOG(LINFO) << name << ": src=" << src << ", dst=" << dst << "\n";
}
}
void Configurator::loadConnections(const ptree * node) {
LOG(LINFO) << "Connecting data streams\n";
std::string name, ds_name;
Base::Component * kern;
std::string type, con_name;
Base::Connection * con;
Base::DataStreamInterface * ds;
BOOST_FOREACH( TreeNode nd, *node ) {
ptree tmp = nd.second;
name = nd.first;
if (name == "<xmlcomment>") continue;
kern = componentManager->getComponent(name);
BOOST_FOREACH( TreeNode ds_nd, tmp ) {
ds_name = ds_nd.first;
if (ds_name == "<xmlcomment>") continue;
ptree ds_tmp = ds_nd.second;
type = ds_tmp.get("<xmlattr>.type", "out");
con_name = ds_tmp.get("<xmlattr>.group", "DefaultGroup");
con = connectionManager->get(con_name);
ds = kern->getStream(ds_name);
if (!ds) {
LOG(LERROR) << "Component " << name << " has no data stream named '" << ds_name << "'!\n";
}
LOG(LINFO) << name << ": str=" << ds_name << " [" << type << "] in " << con_name;
if (type == "out") {
ds->setConnection(con);
} else
if (type == "in") {
con->addListener(ds);
} else {
LOG(LERROR) << "Unknown data stream type: " << type << "\n";
continue;
}
}
}
}
}//: namespace Core
<commit_msg>Exception handling in configurator<commit_after>/*!
* \file Configurator.cpp
* \brief File containing definitions of Configurator class methods.
*
* \author tkornuta
* \date Apr 8, 2010
*/
#include "Configurator.hpp"
#include "DisCODeException.hpp"
#include "Logger.hpp"
#include "Component.hpp"
#include "Event.hpp"
#include "EventHandler.hpp"
#include "DataStreamInterface.hpp"
#include "ComponentManager.hpp"
#include "ExecutorManager.hpp"
#include "ConnectionManager.hpp"
#include <boost/filesystem.hpp>
#include <boost/property_tree/xml_parser.hpp>
namespace Core {
using namespace boost;
Configurator::Configurator()
{
}
Configurator::~Configurator()
{
}
Task Configurator::loadConfiguration(std::string filename_, const std::vector<std::pair<std::string, std::string> > & overrides)
{
// Set filename pointer to given one.
configuration_filename = filename_;
ptree * tmp_node;
// Check whether config file exists.
if (!filesystem::exists(configuration_filename)) {
throw Common::DisCODeException(std::string("Configuration: File '") + configuration_filename + "' doesn't exist.\n");
}
else {
Task task;
// Load and parse configuration from file.
try {
read_xml(configuration_filename, configuration);
}
catch(xml_parser_error&) {
LOG(LFATAL) << "Configuration: Couldn't parse '" << configuration_filename << "' file.\n";
throw Common::DisCODeException(std::string("Configuration: Couldn't parse '") + configuration_filename + "' file.\n");
}
// Take overrides into account
for (size_t i = 0; i < overrides.size(); ++i) {
std::cout << overrides[i].first << " set to " << overrides[i].second << std::endl;
configuration.put(std::string("Task.")+overrides[i].first, overrides[i].second);
}
try {
tmp_node = &(configuration.get_child("Task.Executors"));
loadExecutors(tmp_node, task);
}
catch(ptree_bad_path&) {
LOG(LFATAL) << "No Executors branch in configuration file!\n";
}
try {
tmp_node = &(configuration.get_child("Task.Components"));
}
catch(const ptree_bad_path& ex) {
LOG(LFATAL) << "No Components branch in configuration file!\n";
}
loadComponents(tmp_node, task);
try {
tmp_node = &(configuration.get_child("Task.Events"));
loadEvents(tmp_node);
}
catch(ptree_bad_path&) {
LOG(LFATAL) << "No Events branch in configuration file!\n";
}
try {
tmp_node = &(configuration.get_child("Task.DataStreams"));
loadConnections(tmp_node);
}
catch(ptree_bad_path&) {
LOG(LFATAL) << "No DataStreams branch in configuration file!\n";
}
LOG(LINFO) << "Configuration: File \'" << configuration_filename << "\' loaded.\n";
return task;
}//: else
}
void Configurator::loadExecutors(const ptree * node, Task & task) {
LOG(LINFO) << "Creating execution threads\n";
Executor * ex;
BOOST_FOREACH( TreeNode nd, *node) {
ptree tmp = nd.second;
ex = executorManager->createExecutor(nd.first, tmp.get("<xmlattr>.type", "UNKNOWN"));
ex->load(tmp);
task+=ex;
}
}
void Configurator::loadComponents(const ptree * node, Task & task) {
LOG(LINFO) << "Loading required components\n";
Base::Component * kern;
Executor * ex;
std::string name;
std::string type;
std::string thread;
std::string group;
std::string include;
BOOST_FOREACH( TreeNode nd, *node) {
ptree tmp = nd.second;
name = nd.first;
// ignore coments in tast file
if (name == "<xmlcomment>") continue;
type = tmp.get("<xmlattr>.type", "UNKNOWN");
thread = tmp.get("<xmlattr>.thread", "UNKNOWN");
group = tmp.get("<xmlattr>.group", "DEFAULT");
include = tmp.get("<xmlattr>.include", "");
LOG(LTRACE) << "Component to be created: " << name << " of type " << type << " in thread " << thread << ", subtask " << group << "\n";
kern = componentManager->createComponent(name, type);
if (include != "") {
try {
read_xml(include, tmp);
}
catch(xml_parser_error&) {
LOG(LFATAL) << "Configuration: Couldn't parse include file '" << include << "' for component " << name << ".\n";
throw Common::DisCODeException(std::string("Configuration: Couldn't parse '") + include + "' file.\n");
}
}
if (kern->getProperties()) {
try {
kern->getProperties()->load(tmp);
}
catch(const ptree_bad_path& ex) {
LOG(LERROR) << name << ": " << ex.what();
LOG(LNOTICE) << "Set this property in config file!";
throw Common::DisCODeException(name + ": failed to load component");
}
}
kern->initialize();
ex = executorManager->getExecutor(thread);
ex->addComponent(name, kern);
LOG(LTRACE) << "Adding component " << name << " to subtask " << group << "\n";
task[group] += kern;
component_executor[name] = thread;
}
}
void Configurator::loadEvents(const ptree * node) {
LOG(LINFO) << "Connecting events\n";
std::string src, dst, name, caller, receiver, type;
Base::Component * src_k, * dst_k;
Base::EventHandlerInterface * h;
Base::Event * e;
BOOST_FOREACH( TreeNode nd, *node ) {
ptree tmp = nd.second;
name = nd.first;
if (name == "<xmlcomment>") continue;
src = tmp.get("<xmlattr>.source", "");
if (src == "") {
LOG(LERROR) << "No event source specified...\n";
continue;
}
dst = tmp.get("<xmlattr>.destination", "");
if (dst == "") {
LOG(LERROR) << "No event destination specified...\n";
continue;
}
type=tmp.get("type", "");
caller = src.substr(0, src.find_first_of("."));
src = src.substr(src.find_first_of(".")+1);
receiver = dst.substr(0, dst.find_first_of("."));
dst = dst.substr(dst.find_first_of(".")+1);
src_k = componentManager->getComponent(caller);
dst_k = componentManager->getComponent(receiver);
h = dst_k->getHandler(dst);
if (!h) {
LOG(LERROR) << "Component " << receiver << " has no event handler named '" << dst << "'!\n";
continue;
}
e = src_k->getEvent(src);
if (!e) {
LOG(LERROR) << "Component " << caller << " has no event named '" << src << "'!\n";
continue;
}
// asynchronous connection
if ( (component_executor[caller] != component_executor[receiver]) || (type=="async")) {
Executor * ex = executorManager->getExecutor(component_executor[receiver]);
h = ex->scheduleHandler(h);
e->addAsyncHandler(h);
} else {
e->addHandler(h);
}
LOG(LINFO) << name << ": src=" << src << ", dst=" << dst << "\n";
}
}
void Configurator::loadConnections(const ptree * node) {
LOG(LINFO) << "Connecting data streams\n";
std::string name, ds_name;
Base::Component * kern;
std::string type, con_name;
Base::Connection * con;
Base::DataStreamInterface * ds;
BOOST_FOREACH( TreeNode nd, *node ) {
ptree tmp = nd.second;
name = nd.first;
if (name == "<xmlcomment>") continue;
kern = componentManager->getComponent(name);
BOOST_FOREACH( TreeNode ds_nd, tmp ) {
ds_name = ds_nd.first;
if (ds_name == "<xmlcomment>") continue;
ptree ds_tmp = ds_nd.second;
type = ds_tmp.get("<xmlattr>.type", "out");
con_name = ds_tmp.get("<xmlattr>.group", "DefaultGroup");
con = connectionManager->get(con_name);
ds = kern->getStream(ds_name);
if (!ds) {
LOG(LERROR) << "Component " << name << " has no data stream named '" << ds_name << "'!\n";
}
LOG(LINFO) << name << ": str=" << ds_name << " [" << type << "] in " << con_name;
if (type == "out") {
ds->setConnection(con);
} else
if (type == "in") {
con->addListener(ds);
} else {
LOG(LERROR) << "Unknown data stream type: " << type << "\n";
continue;
}
}
}
}
}//: namespace Core
<|endoftext|>
|
<commit_before>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#ifdef USE_LIBGSL
#include <gsl/gsl_randist.h>
#endif
#include "utils.hpp"
#include "string.h"
/* Really fast random function */
static unsigned long x=123456789, y=362436069, z=521288629;
unsigned long xorshf96(void) { //period 2^96-1
unsigned long t;
x ^= x << 16;
x ^= x >> 5;
x ^= x << 1;
t = x;
x = y;
y = z;
z = t ^ x ^ y;
return z;
}
static unsigned long saltx=123456789, salty=362436069, saltz=521288629;
unsigned long seeded_xorshf96(unsigned long seed) {
unsigned long X = saltx ^ seed << 2, Y = salty ^ seed << 13, Z = saltz ^ seed << 5;
X ^= X << 17;
X ^= Y >> 13;
X ^= Z << 43;
X ^= X >> 5;
X ^= X >> 16;
X ^= X >> 44;
return X;
}
/* Returns random number between [min, max] */
size_t random(size_t min, size_t max) {
//return rand() % (max - min + 1) + min;
return xorshf96() % (max - min + 1) + min;
}
size_t seeded_random(size_t min, size_t max, unsigned long seed) {
return seeded_xorshf96(seed) % (max - min + 1) + min;
}
rnd_distr_t distr_with_name(const char *distr_name) {
if (strcmp(distr_name, "uniform") == 0) {
return rnd_uniform_t;
} else if (strcmp(distr_name, "normal") == 0) {
return rnd_normal_t;
} else {
fprintf(stderr, "There is no such thing as a \"%s\" distribution. At least, I don't know "
"what that means. I only know about \"uniform\" and \"normal\".\n", distr_name);
exit(-1);
}
}
/* Returns random number between [min, max] using various distributions */
rnd_gen_t xrandom_create(rnd_distr_t rnd_distr, int mu) {
rnd_gen_t rnd;
rnd.rnd_distr = rnd_distr;
#ifdef USE_LIBGSL
rnd.gsl_rnd = gsl_rng_alloc(gsl_rng_mt19937);
gsl_rng_set((gsl_rng *)rnd.gsl_rnd, get_ticks());
#endif
rnd.mu = mu;
return rnd;
}
size_t xrandom(size_t min, size_t max) {
rnd_gen_t rnd;
rnd.rnd_distr = rnd_uniform_t;
xrandom(rnd, min, max);
}
size_t xrandom(rnd_gen_t rnd, size_t min, size_t max) {
double tmp;
int len = (min + max) / 2;
switch(rnd.rnd_distr) {
case rnd_uniform_t:
tmp = random(min, max);
break;
case rnd_normal_t:
#ifdef USE_LIBGSL
// Here one percent of the database is within the standard deviation
tmp = gsl_ran_gaussian((gsl_rng*)rnd.gsl_rnd, (double)len * (double)rnd.mu / 100.0) + (len / 2);
break;
#else
fprintf(stderr, "LIBGSL not compiled in (but required for normal distribution)\n");
exit(-1);
break;
#endif
};
if(tmp < min)
tmp = min;
if(tmp > max)
tmp = max;
//printf("%lu\n", (size_t)tmp);
return tmp;
}
size_t seeded_xrandom(size_t min, size_t max, unsigned long seed) {
rnd_gen_t rnd;
rnd.rnd_distr = rnd_uniform_t;
seeded_xrandom(rnd, min, max, seed);
}
size_t seeded_xrandom(rnd_gen_t rnd, size_t min, size_t max, unsigned long seed) {
double tmp;
int len = (min + max) / 2;
switch(rnd.rnd_distr) {
case rnd_uniform_t:
tmp = seeded_random(min, max, seed);
break;
case rnd_normal_t:
#ifdef USE_LIBGSL
gsl_rng_set((gsl_rng *)rnd.gsl_rnd, seed);
tmp = gsl_ran_gaussian((gsl_rng*)rnd.gsl_rnd, (double)len / 4) + (len / 2);
break;
#else
fprintf(stderr, "LIBGSL not compiled in (but required for normal distribution)\n");
exit(-1);
break;
#endif
};
if(tmp < min)
tmp = min;
if(tmp > max)
tmp = max;
return tmp;
}
<commit_msg> Made serializer-bench compile by fixing crap in random.cc.<commit_after>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#ifdef USE_LIBGSL
#include <gsl/gsl_randist.h>
#endif
#include "utils.hpp"
#include "string.h"
/* Really fast random function */
static unsigned long x=123456789, y=362436069, z=521288629;
unsigned long xorshf96(void) { //period 2^96-1
unsigned long t;
x ^= x << 16;
x ^= x >> 5;
x ^= x << 1;
t = x;
x = y;
y = z;
z = t ^ x ^ y;
return z;
}
static unsigned long saltx=123456789, salty=362436069, saltz=521288629;
unsigned long seeded_xorshf96(unsigned long seed) {
unsigned long X = saltx ^ seed << 2, Y = salty ^ seed << 13, Z = saltz ^ seed << 5;
X ^= X << 17;
X ^= Y >> 13;
X ^= Z << 43;
X ^= X >> 5;
X ^= X >> 16;
X ^= X >> 44;
return X;
}
/* Returns random number between [min, max] */
size_t random(size_t min, size_t max) {
//return rand() % (max - min + 1) + min;
return xorshf96() % (max - min + 1) + min;
}
size_t seeded_random(size_t min, size_t max, unsigned long seed) {
return seeded_xorshf96(seed) % (max - min + 1) + min;
}
rnd_distr_t distr_with_name(const char *distr_name) {
if (strcmp(distr_name, "uniform") == 0) {
return rnd_uniform_t;
} else if (strcmp(distr_name, "normal") == 0) {
return rnd_normal_t;
} else {
fprintf(stderr, "There is no such thing as a \"%s\" distribution. At least, I don't know "
"what that means. I only know about \"uniform\" and \"normal\".\n", distr_name);
exit(-1);
}
}
/* Returns random number between [min, max] using various distributions */
rnd_gen_t xrandom_create(rnd_distr_t rnd_distr, int mu) {
rnd_gen_t rnd;
rnd.rnd_distr = rnd_distr;
#ifdef USE_LIBGSL
rnd.gsl_rnd = gsl_rng_alloc(gsl_rng_mt19937);
gsl_rng_set((gsl_rng *)rnd.gsl_rnd, get_ticks());
#endif
rnd.mu = mu;
return rnd;
}
size_t xrandom(size_t min, size_t max) {
rnd_gen_t rnd;
rnd.rnd_distr = rnd_uniform_t;
return xrandom(rnd, min, max);
}
size_t xrandom(rnd_gen_t rnd, size_t min, size_t max) {
double tmp;
#ifdef USE_LIBGSL
int len = (min + max) / 2;
#endif
switch(rnd.rnd_distr) {
case rnd_uniform_t:
tmp = random(min, max);
break;
case rnd_normal_t:
#ifdef USE_LIBGSL
// Here one percent of the database is within the standard deviation
tmp = gsl_ran_gaussian((gsl_rng*)rnd.gsl_rnd, (double)len * (double)rnd.mu / 100.0) + (len / 2);
break;
#else
fprintf(stderr, "LIBGSL not compiled in (but required for normal distribution)\n");
exit(-1);
break;
#endif
}
if(tmp < min) {
tmp = min;
}
if (tmp > max) {
tmp = max;
}
return tmp;
}
size_t seeded_xrandom(size_t min, size_t max, unsigned long seed) {
rnd_gen_t rnd;
rnd.rnd_distr = rnd_uniform_t;
return seeded_xrandom(rnd, min, max, seed);
}
size_t seeded_xrandom(rnd_gen_t rnd, size_t min, size_t max, unsigned long seed) {
double tmp;
#ifdef USE_LIBGSL
int len = (min + max) / 2;
#endif
switch(rnd.rnd_distr) {
case rnd_uniform_t:
tmp = seeded_random(min, max, seed);
break;
case rnd_normal_t:
#ifdef USE_LIBGSL
gsl_rng_set((gsl_rng *)rnd.gsl_rnd, seed);
tmp = gsl_ran_gaussian((gsl_rng*)rnd.gsl_rnd, (double)len / 4) + (len / 2);
break;
#else
fprintf(stderr, "LIBGSL not compiled in (but required for normal distribution)\n");
exit(-1);
break;
#endif
}
if(tmp < min)
tmp = min;
if(tmp > max)
tmp = max;
return tmp;
}
<|endoftext|>
|
<commit_before>/**************************************************************************
* newbucket.hxx -- new bucket routines for better world modeling
*
* Written by Curtis L. Olson, started February 1999.
*
* Copyright (C) 1999 Curtis L. Olson - http://www.flightgear.org/~curt/
*
* 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 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.
*
* $Id$
**************************************************************************/
#ifdef HAVE_CONFIG_H
# include <simgear_config.h>
#endif
#include <math.h>
#include <simgear/misc/sg_path.hxx>
#include "newbucket.hxx"
// default constructor
SGBucket::SGBucket() {
}
// constructor for specified location
SGBucket::SGBucket(const double dlon, const double dlat) {
set_bucket(dlon, dlat);
}
SGBucket::SGBucket(const SGGeod& geod) {
set_bucket(geod);
}
// create an impossible bucket if false
SGBucket::SGBucket(const bool is_good) {
set_bucket(0.0, 0.0);
if ( !is_good ) {
lon = -1000;
}
}
// Parse a unique scenery tile index and find the lon, lat, x, and y
SGBucket::SGBucket(const long int bindex) {
long int index = bindex;
lon = index >> 14;
index -= lon << 14;
lon -= 180;
lat = index >> 6;
index -= lat << 6;
lat -= 90;
y = index >> 3;
index -= y << 3;
x = index;
}
// Set the bucket params for the specified lat and lon
void SGBucket::set_bucket( double *lonlat ) {
set_bucket( lonlat[0], lonlat[1] );
}
// Set the bucket params for the specified lat and lon
void SGBucket::set_bucket( double dlon, double dlat ) {
//
// latitude first
//
double span = sg_bucket_span( dlat );
double diff = dlon - (double)(int)dlon;
// cout << "diff = " << diff << " span = " << span << endl;
/* Calculate the greatest integral longitude less than
* or equal to the given longitude (floor(dlon)),
* but attribute coordinates near the east border
* to the next tile.
*/
if ( (dlon >= 0) || (fabs(diff) < SG_EPSILON) ) {
lon = (int)dlon;
} else {
lon = (int)dlon - 1;
}
// find subdivision or super lon if needed
if ( span < SG_EPSILON ) {
/* sg_bucket_span() never returns 0.0
* or anything near it, so this really
* should not occur at any time.
*/
// polar cap
lon = 0;
x = 0;
} else if ( span <= 1.0 ) {
/* We have more than one tile per degree of
* longitude, so we need an x offset.
*/
x = (int)((dlon - lon) / span);
} else {
/* We have one or more degrees per tile,
* so we need to find the base longitude
* of that tile.
*
* First we calculate the integral base longitude
* (e.g. -85.5 => -86) and then find the greatest
* multiple of span that is less than or equal to
* that longitude.
*
* That way, the Greenwich Meridian is always
* a tile border.
*
* This gets us into trouble with the polar caps,
* which have width 360 and thus either span
* the range from 0 to 360 or from -360 to 0
* degrees, depending on whether lon is positive
* or negative!
*
* We also get into trouble with the 8 degree tiles
* north of 88N and south of 88S, because the west-
* and east-most tiles in that range will cover 184W
* to 176W and 176E to 184E respectively, with their
* center at 180E/W!
*/
lon=(int)floor(floor((lon+SG_EPSILON)/span)*span);
/* Correct the polar cap issue */
if ( lon < -180 ) {
lon = -180;
}
x = 0;
}
//
// then latitude
//
diff = dlat - (double)(int)dlat;
/* Again, a modified floor() function (see longitude) */
if ( (dlat >= 0) || (fabs(diff) < SG_EPSILON) ) {
lat = (int)dlat;
} else {
lat = (int)dlat - 1;
}
/* Latitude base and offset are easier, as
* tiles always are 1/8 degree of latitude wide.
*/
y = (int)((dlat - lat) * 8);
}
void SGBucket::set_bucket(const SGGeod& geod)
{
set_bucket(geod.getLongitudeDeg(), geod.getLatitudeDeg());
}
// Build the path name for this bucket
std::string SGBucket::gen_base_path() const {
// long int index;
int top_lon, top_lat, main_lon, main_lat;
char hem, pole;
char raw_path[256];
top_lon = lon / 10;
main_lon = lon;
if ( (lon < 0) && (top_lon * 10 != lon) ) {
top_lon -= 1;
}
top_lon *= 10;
if ( top_lon >= 0 ) {
hem = 'e';
} else {
hem = 'w';
top_lon *= -1;
}
if ( main_lon < 0 ) {
main_lon *= -1;
}
top_lat = lat / 10;
main_lat = lat;
if ( (lat < 0) && (top_lat * 10 != lat) ) {
top_lat -= 1;
}
top_lat *= 10;
if ( top_lat >= 0 ) {
pole = 'n';
} else {
pole = 's';
top_lat *= -1;
}
if ( main_lat < 0 ) {
main_lat *= -1;
}
sprintf(raw_path, "%c%03d%c%02d/%c%03d%c%02d",
hem, top_lon, pole, top_lat,
hem, main_lon, pole, main_lat);
SGPath path( raw_path );
return path.str();
}
// return width of the tile in degrees
double SGBucket::get_width() const {
return sg_bucket_span( get_center_lat() );
}
// return height of the tile in degrees
double SGBucket::get_height() const {
return SG_BUCKET_SPAN;
}
// return width of the tile in meters
double SGBucket::get_width_m() const {
double clat = (int)get_center_lat();
if ( clat > 0 ) {
clat = (int)clat + 0.5;
} else {
clat = (int)clat - 0.5;
}
double clat_rad = clat * SGD_DEGREES_TO_RADIANS;
double cos_lat = cos( clat_rad );
double local_radius = cos_lat * SG_EQUATORIAL_RADIUS_M;
double local_perimeter = local_radius * SGD_2PI;
double degree_width = local_perimeter / 360.0;
return get_width() * degree_width;
}
// return height of the tile in meters
double SGBucket::get_height_m() const {
double perimeter = SG_EQUATORIAL_RADIUS_M * SGD_2PI;
double degree_height = perimeter / 360.0;
return SG_BUCKET_SPAN * degree_height;
}
// find the bucket which is offset by the specified tile units in the
// X & Y direction. We need the current lon and lat to resolve
// ambiguities when going from a wider tile to a narrower one above or
// below. This assumes that we are feeding in
SGBucket sgBucketOffset( double dlon, double dlat, int dx, int dy ) {
SGBucket result( dlon, dlat );
double clat = result.get_center_lat() + dy * SG_BUCKET_SPAN;
// walk dy units in the lat direction
result.set_bucket( dlon, clat );
// find the lon span for the new latitude
double span = sg_bucket_span( clat );
// walk dx units in the lon direction
double tmp = dlon + dx * span;
while ( tmp < -180.0 ) {
tmp += 360.0;
}
while ( tmp >= 180.0 ) {
tmp -= 360.0;
}
result.set_bucket( tmp, clat );
return result;
}
// calculate the offset between two buckets
void sgBucketDiff( const SGBucket& b1, const SGBucket& b2, int *dx, int *dy ) {
// Latitude difference
double c1_lat = b1.get_center_lat();
double c2_lat = b2.get_center_lat();
double diff_lat = c2_lat - c1_lat;
#ifdef HAVE_RINT
*dy = (int)rint( diff_lat / SG_BUCKET_SPAN );
#else
if ( diff_lat > 0 ) {
*dy = (int)( diff_lat / SG_BUCKET_SPAN + 0.5 );
} else {
*dy = (int)( diff_lat / SG_BUCKET_SPAN - 0.5 );
}
#endif
// longitude difference
double diff_lon=0.0;
double span=0.0;
SGBucket tmp_bucket;
// To handle crossing the bucket size boundary
// we need to account for different size buckets.
if ( sg_bucket_span(c1_lat) <= sg_bucket_span(c2_lat) )
{
span = sg_bucket_span(c1_lat);
} else {
span = sg_bucket_span(c2_lat);
}
diff_lon = b2.get_center_lon() - b1.get_center_lon();
if (diff_lon <0.0)
{
diff_lon -= b1.get_width()*0.5 + b2.get_width()*0.5 - span;
}
else
{
diff_lon += b1.get_width()*0.5 + b2.get_width()*0.5 - span;
}
#ifdef HAVE_RINT
*dx = (int)rint( diff_lon / span );
#else
if ( diff_lon > 0 ) {
*dx = (int)( diff_lon / span + 0.5 );
} else {
*dx = (int)( diff_lon / span - 0.5 );
}
#endif
}
void sgGetBuckets( const SGGeod& min, const SGGeod& max, std::vector<SGBucket>& list ) {
double lon, lat, span;
for (lat = min.getLatitudeDeg(); lat <= max.getLatitudeDeg(); lat += SG_BUCKET_SPAN) {
span = sg_bucket_span( lat );
for (lon = min.getLongitudeDeg(); lon <= max.getLongitudeDeg(); lon += span) {
list.push_back( SGBucket(lon , lat) );
}
}
}
<commit_msg>sprintf -> snprintf in bucket code.<commit_after>/**************************************************************************
* newbucket.hxx -- new bucket routines for better world modeling
*
* Written by Curtis L. Olson, started February 1999.
*
* Copyright (C) 1999 Curtis L. Olson - http://www.flightgear.org/~curt/
*
* 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 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.
*
* $Id$
**************************************************************************/
#ifdef HAVE_CONFIG_H
# include <simgear_config.h>
#endif
#include <math.h>
#include <simgear/misc/sg_path.hxx>
#include "newbucket.hxx"
// default constructor
SGBucket::SGBucket() {
}
// constructor for specified location
SGBucket::SGBucket(const double dlon, const double dlat) {
set_bucket(dlon, dlat);
}
SGBucket::SGBucket(const SGGeod& geod) {
set_bucket(geod);
}
// create an impossible bucket if false
SGBucket::SGBucket(const bool is_good) {
set_bucket(0.0, 0.0);
if ( !is_good ) {
lon = -1000;
}
}
// Parse a unique scenery tile index and find the lon, lat, x, and y
SGBucket::SGBucket(const long int bindex) {
long int index = bindex;
lon = index >> 14;
index -= lon << 14;
lon -= 180;
lat = index >> 6;
index -= lat << 6;
lat -= 90;
y = index >> 3;
index -= y << 3;
x = index;
}
// Set the bucket params for the specified lat and lon
void SGBucket::set_bucket( double *lonlat ) {
set_bucket( lonlat[0], lonlat[1] );
}
// Set the bucket params for the specified lat and lon
void SGBucket::set_bucket( double dlon, double dlat ) {
//
// latitude first
//
double span = sg_bucket_span( dlat );
double diff = dlon - (double)(int)dlon;
// cout << "diff = " << diff << " span = " << span << endl;
/* Calculate the greatest integral longitude less than
* or equal to the given longitude (floor(dlon)),
* but attribute coordinates near the east border
* to the next tile.
*/
if ( (dlon >= 0) || (fabs(diff) < SG_EPSILON) ) {
lon = (int)dlon;
} else {
lon = (int)dlon - 1;
}
// find subdivision or super lon if needed
if ( span < SG_EPSILON ) {
/* sg_bucket_span() never returns 0.0
* or anything near it, so this really
* should not occur at any time.
*/
// polar cap
lon = 0;
x = 0;
} else if ( span <= 1.0 ) {
/* We have more than one tile per degree of
* longitude, so we need an x offset.
*/
x = (int)((dlon - lon) / span);
} else {
/* We have one or more degrees per tile,
* so we need to find the base longitude
* of that tile.
*
* First we calculate the integral base longitude
* (e.g. -85.5 => -86) and then find the greatest
* multiple of span that is less than or equal to
* that longitude.
*
* That way, the Greenwich Meridian is always
* a tile border.
*
* This gets us into trouble with the polar caps,
* which have width 360 and thus either span
* the range from 0 to 360 or from -360 to 0
* degrees, depending on whether lon is positive
* or negative!
*
* We also get into trouble with the 8 degree tiles
* north of 88N and south of 88S, because the west-
* and east-most tiles in that range will cover 184W
* to 176W and 176E to 184E respectively, with their
* center at 180E/W!
*/
lon=(int)floor(floor((lon+SG_EPSILON)/span)*span);
/* Correct the polar cap issue */
if ( lon < -180 ) {
lon = -180;
}
x = 0;
}
//
// then latitude
//
diff = dlat - (double)(int)dlat;
/* Again, a modified floor() function (see longitude) */
if ( (dlat >= 0) || (fabs(diff) < SG_EPSILON) ) {
lat = (int)dlat;
} else {
lat = (int)dlat - 1;
}
/* Latitude base and offset are easier, as
* tiles always are 1/8 degree of latitude wide.
*/
y = (int)((dlat - lat) * 8);
}
void SGBucket::set_bucket(const SGGeod& geod)
{
set_bucket(geod.getLongitudeDeg(), geod.getLatitudeDeg());
}
// Build the path name for this bucket
std::string SGBucket::gen_base_path() const {
// long int index;
int top_lon, top_lat, main_lon, main_lat;
char hem, pole;
char raw_path[256];
top_lon = lon / 10;
main_lon = lon;
if ( (lon < 0) && (top_lon * 10 != lon) ) {
top_lon -= 1;
}
top_lon *= 10;
if ( top_lon >= 0 ) {
hem = 'e';
} else {
hem = 'w';
top_lon *= -1;
}
if ( main_lon < 0 ) {
main_lon *= -1;
}
top_lat = lat / 10;
main_lat = lat;
if ( (lat < 0) && (top_lat * 10 != lat) ) {
top_lat -= 1;
}
top_lat *= 10;
if ( top_lat >= 0 ) {
pole = 'n';
} else {
pole = 's';
top_lat *= -1;
}
if ( main_lat < 0 ) {
main_lat *= -1;
}
snprintf(raw_path, 256, "%c%03d%c%02d/%c%03d%c%02d",
hem, top_lon, pole, top_lat,
hem, main_lon, pole, main_lat);
SGPath path( raw_path );
return path.str();
}
// return width of the tile in degrees
double SGBucket::get_width() const {
return sg_bucket_span( get_center_lat() );
}
// return height of the tile in degrees
double SGBucket::get_height() const {
return SG_BUCKET_SPAN;
}
// return width of the tile in meters
double SGBucket::get_width_m() const {
double clat = (int)get_center_lat();
if ( clat > 0 ) {
clat = (int)clat + 0.5;
} else {
clat = (int)clat - 0.5;
}
double clat_rad = clat * SGD_DEGREES_TO_RADIANS;
double cos_lat = cos( clat_rad );
double local_radius = cos_lat * SG_EQUATORIAL_RADIUS_M;
double local_perimeter = local_radius * SGD_2PI;
double degree_width = local_perimeter / 360.0;
return get_width() * degree_width;
}
// return height of the tile in meters
double SGBucket::get_height_m() const {
double perimeter = SG_EQUATORIAL_RADIUS_M * SGD_2PI;
double degree_height = perimeter / 360.0;
return SG_BUCKET_SPAN * degree_height;
}
// find the bucket which is offset by the specified tile units in the
// X & Y direction. We need the current lon and lat to resolve
// ambiguities when going from a wider tile to a narrower one above or
// below. This assumes that we are feeding in
SGBucket sgBucketOffset( double dlon, double dlat, int dx, int dy ) {
SGBucket result( dlon, dlat );
double clat = result.get_center_lat() + dy * SG_BUCKET_SPAN;
// walk dy units in the lat direction
result.set_bucket( dlon, clat );
// find the lon span for the new latitude
double span = sg_bucket_span( clat );
// walk dx units in the lon direction
double tmp = dlon + dx * span;
while ( tmp < -180.0 ) {
tmp += 360.0;
}
while ( tmp >= 180.0 ) {
tmp -= 360.0;
}
result.set_bucket( tmp, clat );
return result;
}
// calculate the offset between two buckets
void sgBucketDiff( const SGBucket& b1, const SGBucket& b2, int *dx, int *dy ) {
// Latitude difference
double c1_lat = b1.get_center_lat();
double c2_lat = b2.get_center_lat();
double diff_lat = c2_lat - c1_lat;
#ifdef HAVE_RINT
*dy = (int)rint( diff_lat / SG_BUCKET_SPAN );
#else
if ( diff_lat > 0 ) {
*dy = (int)( diff_lat / SG_BUCKET_SPAN + 0.5 );
} else {
*dy = (int)( diff_lat / SG_BUCKET_SPAN - 0.5 );
}
#endif
// longitude difference
double diff_lon=0.0;
double span=0.0;
SGBucket tmp_bucket;
// To handle crossing the bucket size boundary
// we need to account for different size buckets.
if ( sg_bucket_span(c1_lat) <= sg_bucket_span(c2_lat) )
{
span = sg_bucket_span(c1_lat);
} else {
span = sg_bucket_span(c2_lat);
}
diff_lon = b2.get_center_lon() - b1.get_center_lon();
if (diff_lon <0.0)
{
diff_lon -= b1.get_width()*0.5 + b2.get_width()*0.5 - span;
}
else
{
diff_lon += b1.get_width()*0.5 + b2.get_width()*0.5 - span;
}
#ifdef HAVE_RINT
*dx = (int)rint( diff_lon / span );
#else
if ( diff_lon > 0 ) {
*dx = (int)( diff_lon / span + 0.5 );
} else {
*dx = (int)( diff_lon / span - 0.5 );
}
#endif
}
void sgGetBuckets( const SGGeod& min, const SGGeod& max, std::vector<SGBucket>& list ) {
double lon, lat, span;
for (lat = min.getLatitudeDeg(); lat <= max.getLatitudeDeg(); lat += SG_BUCKET_SPAN) {
span = sg_bucket_span( lat );
for (lon = min.getLongitudeDeg(); lon <= max.getLongitudeDeg(); lon += span) {
list.push_back( SGBucket(lon , lat) );
}
}
}
<|endoftext|>
|
<commit_before>#ifndef __MAPNIK_BENCH_FRAMEWORK_HPP__
#define __MAPNIK_BENCH_FRAMEWORK_HPP__
// mapnik
#include <mapnik/debug.hpp>
#include <mapnik/params.hpp>
#include <mapnik/value_types.hpp>
#include <mapnik/safe_cast.hpp>
#include "../test/cleanup.hpp"
// stl
#include <chrono>
#include <cstdio> // snprintf
#include <iostream>
#include <set>
#include <sstream>
#include <thread>
#include <vector>
namespace benchmark {
class test_case
{
protected:
mapnik::parameters params_;
std::size_t threads_;
std::size_t iterations_;
public:
test_case(mapnik::parameters const& params)
: params_(params),
threads_(mapnik::safe_cast<std::size_t>(*params.get<mapnik::value_integer>("threads",0))),
iterations_(mapnik::safe_cast<std::size_t>(*params.get<mapnik::value_integer>("iterations",0)))
{}
std::size_t threads() const
{
return threads_;
}
std::size_t iterations() const
{
return iterations_;
}
mapnik::parameters const& params() const
{
return params_;
}
virtual bool validate() const = 0;
virtual bool operator()() const = 0;
virtual ~test_case() {}
};
// gathers --long-option values in 'params';
// returns the index of the first non-option argument,
// or negated index of an ill-formed option argument
inline int parse_args(int argc, char** argv, mapnik::parameters & params)
{
for (int i = 1; i < argc; ++i) {
const char* opt = argv[i];
if (opt[0] != '-') {
// non-option argument, return its index
return i;
}
if (opt[1] != '-') {
// we only accept --long-options, but instead of throwing,
// just issue a warning and let the caller decide what to do
std::clog << argv[0] << ": invalid option '" << opt << "'\n";
return -i; // negative means ill-formed option #i
}
if (opt[2] == '\0') {
// option-list terminator '--'
return i + 1;
}
// take option name without the leading '--'
std::string key(opt + 2);
size_t eq = key.find('=');
if (eq != std::string::npos) {
// one-argument form '--foo=bar'
params[key.substr(0, eq)] = key.substr(eq + 1);
}
else if (i + 1 < argc) {
// two-argument form '--foo' 'bar'
params[key] = std::string(argv[++i]);
}
else {
// missing second argument
std::clog << argv[0] << ": missing option '" << opt << "' value\n";
return -i; // negative means ill-formed option #i
}
}
return argc; // there were no non-option arguments
}
inline void handle_common_args(mapnik::parameters const& params)
{
if (auto severity = params.get<std::string>("log")) {
if (*severity == "debug")
mapnik::logger::set_severity(mapnik::logger::debug);
else if (*severity == "warn")
mapnik::logger::set_severity(mapnik::logger::warn);
else if (*severity == "error")
mapnik::logger::set_severity(mapnik::logger::error);
else if (*severity == "none")
mapnik::logger::set_severity(mapnik::logger::none);
else
std::clog << "ignoring option --log='" << *severity
<< "' (allowed values are: debug, warn, error, none)\n";
}
}
inline int handle_args(int argc, char** argv, mapnik::parameters & params)
{
int res = parse_args(argc, argv, params);
handle_common_args(params);
return res;
}
#define BENCHMARK(test_class,name) \
int main(int argc, char** argv) \
{ \
try \
{ \
mapnik::parameters params; \
benchmark::handle_args(argc,argv,params); \
test_class test_runner(params); \
auto result = run(test_runner,name); \
testing::run_cleanup(); \
return result; \
} \
catch (std::exception const& ex) \
{ \
std::clog << ex.what() << "\n"; \
testing::run_cleanup(); \
return -1; \
} \
} \
template <typename T>
int run(T const& test_runner, std::string const& name)
{
try
{
if (!test_runner.validate())
{
std::clog << "test did not validate: " << name << "\n";
return 1;
}
// run test once before timing
// if it returns false then we'll abort timing
if (!test_runner())
{
return 2;
}
std::chrono::high_resolution_clock::time_point start;
std::chrono::high_resolution_clock::duration elapsed;
auto opt_min_duration = test_runner.params().template get<double>("min-duration", 0.0);
std::chrono::duration<double> min_seconds(*opt_min_duration);
auto min_duration = std::chrono::duration_cast<decltype(elapsed)>(min_seconds);
std::size_t loops = 0;
if (test_runner.threads() > 0)
{
using thread_group = std::vector<std::unique_ptr<std::thread> >;
using value_type = thread_group::value_type;
thread_group tg;
for (std::size_t i=0;i<test_runner.threads();++i)
{
tg.emplace_back(new std::thread(test_runner));
}
start = std::chrono::high_resolution_clock::now();
std::for_each(tg.begin(), tg.end(), [](value_type & t) {if (t->joinable()) t->join();});
elapsed = std::chrono::high_resolution_clock::now() - start;
loops = 1;
}
else
{
start = std::chrono::high_resolution_clock::now();
do {
test_runner();
elapsed = std::chrono::high_resolution_clock::now() - start;
++loops;
} while (elapsed < min_duration);
}
double iters = loops * test_runner.iterations();
double dur_total = std::chrono::duration<double, std::milli>(elapsed).count();
double dur_avg = dur_total / iters;
char iters_unit = ' ';
char msg[200];
if (iters >= 1e7) iters *= 1e-6, iters_unit = 'M';
else if (iters >= 1e4) iters *= 1e-3, iters_unit = 'k';
std::snprintf(msg, sizeof(msg),
"%-43s %3zu threads %4.0f%c iters %6.0f milliseconds",
name.c_str(),
test_runner.threads(),
iters, iters_unit,
dur_total);
std::clog << msg;
// log average time per iteration, currently only for non-threaded runs
if (test_runner.threads() == 0)
{
char unit = 'm';
if (dur_avg < 1e-5) dur_avg *= 1e+9, unit = 'p';
else if (dur_avg < 1e-2) dur_avg *= 1e+6, unit = 'n';
else if (dur_avg < 1e+1) dur_avg *= 1e+3, unit = 'u';
std::snprintf(msg, sizeof(msg), " %4.0f%cs/iter", dur_avg, unit);
std::clog << msg;
}
std::clog << "\n";
return 0;
}
catch (std::exception const& ex)
{
std::clog << "test runner did not complete: " << ex.what() << "\n";
return 4;
}
}
struct sequencer
{
sequencer(int argc, char** argv)
: exit_code_(0)
{
benchmark::handle_args(argc, argv, params_);
}
int done() const
{
return exit_code_;
}
template <typename Test, typename... Args>
sequencer & run(std::string const& name, Args && ...args)
{
// Test instance lifetime is confined to this function
Test test_runner(params_, std::forward<Args>(args)...);
// any failing test run will make exit code non-zero
exit_code_ |= benchmark::run(test_runner, name);
return *this; // allow chaining calls
}
protected:
mapnik::parameters params_;
int exit_code_;
};
}
#endif // __MAPNIK_BENCH_FRAMEWORK_HPP__
<commit_msg>benchmarks: report iterations per second instead of the inverse<commit_after>#ifndef __MAPNIK_BENCH_FRAMEWORK_HPP__
#define __MAPNIK_BENCH_FRAMEWORK_HPP__
// mapnik
#include <mapnik/debug.hpp>
#include <mapnik/params.hpp>
#include <mapnik/value_types.hpp>
#include <mapnik/safe_cast.hpp>
#include "../test/cleanup.hpp"
// stl
#include <chrono>
#include <cmath> // log10
#include <cstdio> // snprintf
#include <iostream>
#include <set>
#include <sstream>
#include <thread>
#include <vector>
namespace benchmark {
template <typename T>
using milliseconds = std::chrono::duration<T, std::milli>;
template <typename T>
using seconds = std::chrono::duration<T>;
class test_case
{
protected:
mapnik::parameters params_;
std::size_t threads_;
std::size_t iterations_;
public:
test_case(mapnik::parameters const& params)
: params_(params),
threads_(mapnik::safe_cast<std::size_t>(*params.get<mapnik::value_integer>("threads",0))),
iterations_(mapnik::safe_cast<std::size_t>(*params.get<mapnik::value_integer>("iterations",0)))
{}
std::size_t threads() const
{
return threads_;
}
std::size_t iterations() const
{
return iterations_;
}
mapnik::parameters const& params() const
{
return params_;
}
virtual bool validate() const = 0;
virtual bool operator()() const = 0;
virtual ~test_case() {}
};
// gathers --long-option values in 'params';
// returns the index of the first non-option argument,
// or negated index of an ill-formed option argument
inline int parse_args(int argc, char** argv, mapnik::parameters & params)
{
for (int i = 1; i < argc; ++i) {
const char* opt = argv[i];
if (opt[0] != '-') {
// non-option argument, return its index
return i;
}
if (opt[1] != '-') {
// we only accept --long-options, but instead of throwing,
// just issue a warning and let the caller decide what to do
std::clog << argv[0] << ": invalid option '" << opt << "'\n";
return -i; // negative means ill-formed option #i
}
if (opt[2] == '\0') {
// option-list terminator '--'
return i + 1;
}
// take option name without the leading '--'
std::string key(opt + 2);
size_t eq = key.find('=');
if (eq != std::string::npos) {
// one-argument form '--foo=bar'
params[key.substr(0, eq)] = key.substr(eq + 1);
}
else if (i + 1 < argc) {
// two-argument form '--foo' 'bar'
params[key] = std::string(argv[++i]);
}
else {
// missing second argument
std::clog << argv[0] << ": missing option '" << opt << "' value\n";
return -i; // negative means ill-formed option #i
}
}
return argc; // there were no non-option arguments
}
inline void handle_common_args(mapnik::parameters const& params)
{
if (auto severity = params.get<std::string>("log")) {
if (*severity == "debug")
mapnik::logger::set_severity(mapnik::logger::debug);
else if (*severity == "warn")
mapnik::logger::set_severity(mapnik::logger::warn);
else if (*severity == "error")
mapnik::logger::set_severity(mapnik::logger::error);
else if (*severity == "none")
mapnik::logger::set_severity(mapnik::logger::none);
else
std::clog << "ignoring option --log='" << *severity
<< "' (allowed values are: debug, warn, error, none)\n";
}
}
inline int handle_args(int argc, char** argv, mapnik::parameters & params)
{
int res = parse_args(argc, argv, params);
handle_common_args(params);
return res;
}
#define BENCHMARK(test_class,name) \
int main(int argc, char** argv) \
{ \
try \
{ \
mapnik::parameters params; \
benchmark::handle_args(argc,argv,params); \
test_class test_runner(params); \
auto result = run(test_runner,name); \
testing::run_cleanup(); \
return result; \
} \
catch (std::exception const& ex) \
{ \
std::clog << ex.what() << "\n"; \
testing::run_cleanup(); \
return -1; \
} \
} \
struct big_number_fmt
{
int w;
double v;
const char* u;
big_number_fmt(int width, double value, int base = 1000)
: w(width), v(value), u("")
{
static const char* suffixes = "\0\0k\0M\0G\0T\0P\0E\0Z\0Y\0\0";
u = suffixes;
while (v > 1 && std::log10(v) >= width && u[2])
{
v /= base;
u += 2;
}
// adjust width for proper alignment without suffix
w += (u == suffixes);
}
};
template <typename T>
int run(T const& test_runner, std::string const& name)
{
try
{
if (!test_runner.validate())
{
std::clog << "test did not validate: " << name << "\n";
return 1;
}
// run test once before timing
// if it returns false then we'll abort timing
if (!test_runner())
{
return 2;
}
std::chrono::high_resolution_clock::time_point start;
std::chrono::high_resolution_clock::duration elapsed;
auto opt_min_duration = test_runner.params().template get<double>("min-duration", 0.0);
std::chrono::duration<double> min_seconds(*opt_min_duration);
auto min_duration = std::chrono::duration_cast<decltype(elapsed)>(min_seconds);
auto num_iters = test_runner.iterations();
auto total_iters = 0;
if (test_runner.threads() > 0)
{
using thread_group = std::vector<std::unique_ptr<std::thread> >;
using value_type = thread_group::value_type;
thread_group tg;
for (std::size_t i=0;i<test_runner.threads();++i)
{
tg.emplace_back(new std::thread(test_runner));
}
start = std::chrono::high_resolution_clock::now();
std::for_each(tg.begin(), tg.end(), [](value_type & t) {if (t->joinable()) t->join();});
elapsed = std::chrono::high_resolution_clock::now() - start;
total_iters += num_iters;
}
else
{
start = std::chrono::high_resolution_clock::now();
do {
test_runner();
elapsed = std::chrono::high_resolution_clock::now() - start;
total_iters += num_iters;
} while (elapsed < min_duration);
}
char msg[200];
double dur_total = milliseconds<double>(elapsed).count();
big_number_fmt itersf(4, total_iters);
std::snprintf(msg, sizeof(msg),
"%-43s %3zu threads %*.0f%s iters %6.0f milliseconds",
name.c_str(),
test_runner.threads(),
itersf.w, itersf.v, itersf.u,
dur_total);
std::clog << msg;
// log average # of iterations per second, currently only for
// non-threaded runs
if (test_runner.threads() == 0)
{
auto elapsed_nonzero = std::max(elapsed, decltype(elapsed){1});
big_number_fmt ips(5, total_iters / seconds<double>(elapsed_nonzero).count());
std::snprintf(msg, sizeof(msg), " %*.0f%s i/s", ips.w, ips.v, ips.u);
std::clog << msg;
}
std::clog << "\n";
return 0;
}
catch (std::exception const& ex)
{
std::clog << "test runner did not complete: " << ex.what() << "\n";
return 4;
}
}
struct sequencer
{
sequencer(int argc, char** argv)
: exit_code_(0)
{
benchmark::handle_args(argc, argv, params_);
}
int done() const
{
return exit_code_;
}
template <typename Test, typename... Args>
sequencer & run(std::string const& name, Args && ...args)
{
// Test instance lifetime is confined to this function
Test test_runner(params_, std::forward<Args>(args)...);
// any failing test run will make exit code non-zero
exit_code_ |= benchmark::run(test_runner, name);
return *this; // allow chaining calls
}
protected:
mapnik::parameters params_;
int exit_code_;
};
}
#endif // __MAPNIK_BENCH_FRAMEWORK_HPP__
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2016,
Dan Bethell, Johannes Saam, Vahan Sosoyan, Brian Scherbinski.
All rights reserved. See COPYING.txt for more details.
*/
#include <ai.h>
#include "Data.h"
#include "Client.h"
using boost::asio::ip::tcp;
AI_DRIVER_NODE_EXPORT_METHODS(AtonDriverMtd);
const char* getHost()
{
const char* aton_host = getenv("ATON_HOST");
if (aton_host == NULL)
aton_host = "127.0.0.1";
char* host = new char[strlen(aton_host) + 1];
strcpy(host, aton_host);
aton_host = host;
return aton_host;
}
int getPort()
{
const char* def_port = getenv("ATON_PORT");
int aton_port;
if (def_port == NULL)
aton_port = 9201;
else
aton_port = atoi(def_port);
return aton_port;
}
struct ShaderData
{
aton::Client* client;
int xres, yres, min_x, min_y, max_x, max_y;
};
node_parameters
{
AiParameterSTR("host", getHost());
AiParameterINT("port", getPort());
AiMetaDataSetStr(mds, NULL, "maya.translator", "aton");
AiMetaDataSetStr(mds, NULL, "maya.attr_prefix", "");
AiMetaDataSetBool(mds, NULL, "display_driver", true);
AiMetaDataSetBool(mds, NULL, "single_layer_driver", false);
}
node_initialize
{
ShaderData* data = (ShaderData*)AiMalloc(sizeof(ShaderData));
data->client = NULL,
AiDriverInitialize(node, true, data);
}
node_update {}
driver_supports_pixel_type { return true; }
driver_extension { return NULL; }
driver_open
{
// Construct full version number
char arch[3], major[3], minor[3], fix[3];
AiGetVersion(arch, major, minor, fix);
const int version = atoi(arch) * 1000000 +
atoi(major) * 10000 +
atoi(minor) * 100 +
atoi(fix);
ShaderData* data = (ShaderData*)AiDriverGetLocalData(node);
// Get Frame number
AtNode* options = AiUniverseGetOptions();
const float currentFrame = AiNodeGetFlt(options, "frame");
// Get Host and Port
const char* host = AiNodeGetStr(node, "host");
const int port = AiNodeGetInt(node, "port");
// Get Camera
AtNode* camera = (AtNode*)AiNodeGetPtr(options, "camera");
AtMatrix cMat;
AiNodeGetMatrix(camera, "matrix", cMat);
const float cam_fov = AiNodeGetFlt(camera, "fov");
const float cam_matrix[16] = {cMat[0][0], cMat[1][0], cMat[2][0], cMat[3][0],
cMat[0][1], cMat[1][1], cMat[2][1], cMat[3][1],
cMat[0][2], cMat[1][2], cMat[2][2], cMat[3][2],
cMat[0][3], cMat[1][3], cMat[2][3], cMat[3][3]};
// Get Resolution
const int xres = AiNodeGetInt(options, "xres");
const int yres = AiNodeGetInt(options, "yres");
// Get Regions
const int min_x = AiNodeGetInt(options, "region_min_x");
const int min_y = AiNodeGetInt(options, "region_min_y");
const int max_x = AiNodeGetInt(options, "region_max_x");
const int max_y = AiNodeGetInt(options, "region_max_y");
// Setting Origin
data->min_x = (min_x == INT_MIN) ? 0 : min_x;
data->min_y = (min_y == INT_MIN) ? 0 : min_y;
data->max_x = (max_x == INT_MIN) ? 0 : max_x;
data->max_y = (max_y == INT_MIN) ? 0 : max_y;
// Setting X Resolution
if (data->min_x < 0 && data->max_x >= xres)
data->xres = data->max_x - data->min_x + 1;
else if (data->min_x >= 0 && data->max_x < xres)
data->xres = xres;
else if (data->min_x < 0 && data->max_x < xres)
data->xres = xres - min_x;
else if(data->min_x >= 0 && data->max_x >= xres)
data->xres = xres + (max_x - xres + 1);
// Setting Y Resolution
if (data->min_y < 0 && data->max_y >= yres)
data->yres = data->max_y - data->min_y + 1;
else if (data->min_y >= 0 && data->max_y < yres)
data->yres = yres;
else if (data->min_y < 0 && data->max_y < yres)
data->yres = yres - min_y;
else if(data->min_y >= 0 && data->max_y >= yres)
data->yres = yres + (max_y - yres + 1);
// Get area of region
const long long rArea = data->xres * data->yres;
// Make image header & send to server
aton::Data header(data->xres, data->yres, 0, 0, 0, 0,
rArea, version, currentFrame, cam_fov, cam_matrix);
try // Now we can connect to the server and start rendering
{
if (data->client == NULL)
{
boost::system::error_code ec;
boost::asio::ip::address::from_string(host, ec);
if (!ec)
data->client = new aton::Client(host, port);
}
data->client->openImage(header);
}
catch(const std::exception &e)
{
const char* err = e.what();
AiMsgError("ATON | %s", err);
}
}
driver_needs_bucket { return true; }
driver_prepare_bucket
{
AiMsgDebug("[Aton] prepare bucket (%d, %d)", bucket_xo, bucket_yo);
}
driver_process_bucket { }
driver_write_bucket
{
ShaderData* data = (ShaderData*)AiDriverGetLocalData(node);
int pixel_type;
int spp = 0;
const void* bucket_data;
const char* aov_name;
if (data->min_x < 0)
bucket_xo = bucket_xo - data->min_x;
if (data->min_y < 0)
bucket_yo = bucket_yo - data->min_y;
while (AiOutputIteratorGetNext(iterator, &aov_name, &pixel_type, &bucket_data))
{
const float* ptr = reinterpret_cast<const float*>(bucket_data);
const long long ram = AiMsgUtilGetUsedMemory();
const unsigned int time = AiMsgUtilGetElapsedTime();
switch (pixel_type)
{
case(AI_TYPE_FLOAT):
spp = 1;
break;
case(AI_TYPE_RGBA):
spp = 4;
break;
default:
spp = 3;
}
// Create our data object
aton::Data packet(data->xres, data->yres, bucket_xo, bucket_yo,
bucket_size_x, bucket_size_y, 0, 0, 0, 0, 0,
spp, ram, time, aov_name, ptr);
// Send it to the server
data->client->sendPixels(packet);
}
}
driver_close
{
AiMsgInfo("[Aton] driver close");
ShaderData* data = (ShaderData*)AiDriverGetLocalData(node);
try
{
data->client->closeImage();
}
catch (const std::exception& e)
{
AiMsgError("ATON | Error occured when trying to close connection");
}
}
node_finish
{
AiMsgInfo("[Aton] driver finish");
// Release the driver
ShaderData* data = (ShaderData*)AiDriverGetLocalData(node);
delete data->client;
AiFree(data);
AiDriverDestroy(node);
}
node_loader
{
sprintf(node->version, AI_VERSION);
switch (i)
{
case 0:
node->methods = (AtNodeMethods*) AtonDriverMtd;
node->output_type = AI_TYPE_RGBA;
node->name = "driver_aton";
node->node_type = AI_NODE_DRIVER;
break;
default:
return false;
}
return true;
}
<commit_msg>Update Driver_Aton.cpp<commit_after>/*
Copyright (c) 2016,
Dan Bethell, Johannes Saam, Vahan Sosoyan, Brian Scherbinski.
All rights reserved. See COPYING.txt for more details.
*/
#include <ai.h>
#include "Data.h"
#include "Client.h"
using boost::asio::ip::tcp;
AI_DRIVER_NODE_EXPORT_METHODS(AtonDriverMtd);
const char* getHost()
{
const char* aton_host = getenv("ATON_HOST");
if (aton_host == NULL)
aton_host = "127.0.0.1";
char* host = new char[strlen(aton_host) + 1];
strcpy(host, aton_host);
aton_host = host;
return aton_host;
}
int getPort()
{
const char* def_port = getenv("ATON_PORT");
int aton_port;
if (def_port == NULL)
aton_port = 9201;
else
aton_port = atoi(def_port);
return aton_port;
}
struct ShaderData
{
aton::Client* client;
int xres, yres, min_x, min_y, max_x, max_y;
};
node_parameters
{
AiParameterSTR("host", getHost());
AiParameterINT("port", getPort());
AiMetaDataSetStr(mds, NULL, "maya.translator", "aton");
AiMetaDataSetStr(mds, NULL, "maya.attr_prefix", "");
AiMetaDataSetBool(mds, NULL, "display_driver", true);
AiMetaDataSetBool(mds, NULL, "single_layer_driver", false);
}
node_initialize
{
ShaderData* data = (ShaderData*)AiMalloc(sizeof(ShaderData));
data->client = NULL,
AiDriverInitialize(node, true, data);
}
node_update {}
driver_supports_pixel_type { return true; }
driver_extension { return NULL; }
driver_open
{
// Construct full version number
char arch[3], major[3], minor[3], fix[3];
AiGetVersion(arch, major, minor, fix);
const int version = atoi(arch) * 1000000 +
atoi(major) * 10000 +
atoi(minor) * 100 +
atoi(fix);
ShaderData* data = (ShaderData*)AiDriverGetLocalData(node);
// Get Frame number
AtNode* options = AiUniverseGetOptions();
const float currentFrame = AiNodeGetFlt(options, "frame");
// Get Host and Port
const char* host = AiNodeGetStr(node, "host");
const int port = AiNodeGetInt(node, "port");
// Get Camera
AtNode* camera = (AtNode*)AiNodeGetPtr(options, "camera");
AtMatrix cMat;
AiNodeGetMatrix(camera, "matrix", cMat);
const float cam_fov = AiNodeGetFlt(camera, "fov");
const float cam_matrix[16] = {cMat[0][0], cMat[1][0], cMat[2][0], cMat[3][0],
cMat[0][1], cMat[1][1], cMat[2][1], cMat[3][1],
cMat[0][2], cMat[1][2], cMat[2][2], cMat[3][2],
cMat[0][3], cMat[1][3], cMat[2][3], cMat[3][3]};
// Get Resolution
const int xres = AiNodeGetInt(options, "xres");
const int yres = AiNodeGetInt(options, "yres");
// Get Regions
const int min_x = AiNodeGetInt(options, "region_min_x");
const int min_y = AiNodeGetInt(options, "region_min_y");
const int max_x = AiNodeGetInt(options, "region_max_x");
const int max_y = AiNodeGetInt(options, "region_max_y");
// Setting Origin
data->min_x = (min_x == INT_MIN) ? 0 : min_x;
data->min_y = (min_y == INT_MIN) ? 0 : min_y;
data->max_x = (max_x == INT_MIN) ? 0 : max_x;
data->max_y = (max_y == INT_MIN) ? 0 : max_y;
// Setting X Resolution
if (data->min_x < 0 && data->max_x >= xres)
data->xres = data->max_x - data->min_x + 1;
else if (data->min_x >= 0 && data->max_x < xres)
data->xres = xres;
else if (data->min_x < 0 && data->max_x < xres)
data->xres = xres - min_x;
else if(data->min_x >= 0 && data->max_x >= xres)
data->xres = xres + (max_x - xres + 1);
// Setting Y Resolution
if (data->min_y < 0 && data->max_y >= yres)
data->yres = data->max_y - data->min_y + 1;
else if (data->min_y >= 0 && data->max_y < yres)
data->yres = yres;
else if (data->min_y < 0 && data->max_y < yres)
data->yres = yres - min_y;
else if(data->min_y >= 0 && data->max_y >= yres)
data->yres = yres + (max_y - yres + 1);
// Get area of region
const long long rArea = data->xres * data->yres;
// Make image header & send to server
aton::Data header(data->xres, data->yres, NULL, NULL, NULL, NULL,
rArea, version, currentFrame, cam_fov, cam_matrix);
try // Now we can connect to the server and start rendering
{
if (data->client == NULL)
{
boost::system::error_code ec;
boost::asio::ip::address::from_string(host, ec);
if (!ec)
data->client = new aton::Client(host, port);
}
data->client->openImage(header);
}
catch(const std::exception &e)
{
const char* err = e.what();
AiMsgError("ATON | %s", err);
}
}
driver_needs_bucket { return true; }
driver_prepare_bucket
{
AiMsgDebug("[Aton] prepare bucket (%d, %d)", bucket_xo, bucket_yo);
}
driver_process_bucket { }
driver_write_bucket
{
ShaderData* data = (ShaderData*)AiDriverGetLocalData(node);
int pixel_type;
int spp = 0;
const void* bucket_data;
const char* aov_name;
if (data->min_x < 0)
bucket_xo = bucket_xo - data->min_x;
if (data->min_y < 0)
bucket_yo = bucket_yo - data->min_y;
while (AiOutputIteratorGetNext(iterator, &aov_name, &pixel_type, &bucket_data))
{
const float* ptr = reinterpret_cast<const float*>(bucket_data);
const long long ram = AiMsgUtilGetUsedMemory();
const unsigned int time = AiMsgUtilGetElapsedTime();
switch (pixel_type)
{
case(AI_TYPE_FLOAT):
spp = 1;
break;
case(AI_TYPE_RGBA):
spp = 4;
break;
default:
spp = 3;
}
// Create our data object
aton::Data packet(data->xres, data->yres, bucket_xo, bucket_yo,
bucket_size_x, bucket_size_y, NULL, NULL, NULL, NULL, NULL,
spp, ram, time, aov_name, ptr);
// Send it to the server
data->client->sendPixels(packet);
}
}
driver_close
{
AiMsgInfo("[Aton] driver close");
ShaderData* data = (ShaderData*)AiDriverGetLocalData(node);
try
{
data->client->closeImage();
}
catch (const std::exception& e)
{
AiMsgError("ATON | Error occured when trying to close connection");
}
}
node_finish
{
AiMsgInfo("[Aton] driver finish");
// Release the driver
ShaderData* data = (ShaderData*)AiDriverGetLocalData(node);
delete data->client;
AiFree(data);
AiDriverDestroy(node);
}
node_loader
{
sprintf(node->version, AI_VERSION);
switch (i)
{
case 0:
node->methods = (AtNodeMethods*) AtonDriverMtd;
node->output_type = AI_TYPE_RGBA;
node->name = "driver_aton";
node->node_type = AI_NODE_DRIVER;
break;
default:
return false;
}
return true;
}
<|endoftext|>
|
<commit_before>//#####################################################################
// Class Image
//#####################################################################
#include <other/core/geometry/Box.h>
#include <other/core/image/Image.h>
#include <other/core/image/JpgFile.h>
#include <other/core/image/PngFile.h>
#include <other/core/image/ExrFile.h>
#include <other/core/python/Class.h>
#include <other/core/python/stl.h>
#include <other/core/random/Random.h>
#include <other/core/utility/path.h>
#include <other/core/utility/Log.h>
#include <cmath>
namespace other {
using std::pow;
using std::nth_element;
template<> OTHER_DEFINE_TYPE(Image<real>)
template<class T> Array<Vector<T,3>,2> Image<T>::read(const string& filename)
{
string ext = path::extension(filename);
if(ext==".jpg") return JpgFile<T>::read(filename);
else if(ext==".png") return PngFile<T>::read(filename);
else if(ext==".exr") return ExrFile<T>::read(filename);
OTHER_FATAL_ERROR(format("Unknown image file extension from filename '%s' extension '%s'",filename,ext));
}
template<class T> Array<Vector<T,4>,2> Image<T>::read_alpha(const string& filename)
{
string ext = path::extension(filename);
if(ext==".png") return PngFile<T>::read_alpha(filename);
OTHER_FATAL_ERROR(format("Image file extension unknown or without alpha from filename '%s' extension '%s'",filename,ext));
}
template<class T> void Image<T>::
write(const string& filename,RawArray<const Vector<T,3>,2> image)
{
string ext = path::extension(filename);
if(ext==".jpg") JpgFile<T>::write(filename,image);
else if(ext==".png") PngFile<T>::write(filename,image);
else if(ext==".exr") ExrFile<T>::write(filename,image);
else OTHER_FATAL_ERROR(format("Unknown image file extension from filename '%s' extension '%s'",filename,ext));
}
template<class T> void Image<T>::
write_alpha(const string& filename,RawArray<const Vector<T,4>,2> image)
{
string ext = path::extension(filename);
if(ext==".png") PngFile<T>::write(filename,image);
else if(ext==".jpg") OTHER_FATAL_ERROR(format("No support for alpha channel with extension '%s' for filename '%s'",ext,filename));
else OTHER_FATAL_ERROR(format("Unknown image file extension from filename '%s' extension '%s'",filename,ext));
}
template<class T> std::vector<unsigned char> Image<T>::
write_png_to_memory(RawArray<const Vector<T,3>,2> image) {
return PngFile<T>::write_to_memory(image);
}
template<class T> std::vector<unsigned char> Image<T>::
write_png_to_memory(RawArray<const Vector<T,4>,2> image) {
return PngFile<T>::write_to_memory(image);
}
template<class T> Array<Vector<T,3>,2> Image<T>::
gamma_compress(Array<const Vector<T,3>,2> image,const real gamma)
{
T one_over_gamma = T(1/gamma);
Array<Vector<T,3>,2> result(image.sizes());
for(int t=0;t<result.flat.size();t++)
for (int i = 0; i < 3; ++i)
result.flat[t][i] = pow(image.flat(t)[i],one_over_gamma);
return result;
}
template<class T> Array<Vector<T,3>,2> Image<T>::
dither(Array<const Vector<T,3>,2> image)
{
Ref<Random> random=new_<Random>(324032); // want uniform seed so noise perturbation pattern is temporally coherent
Array<Vector<T,3>,2> result(image.sizes());
for(int t=0;t<result.flat.size();t++){
result.flat(t)=image.flat(t);
Vector<T,3> pixel_values((T)255*result.flat(t));
Vector<int,3> floored_values((int)pixel_values[0],(int)pixel_values[1],(int)pixel_values[2]);
Vector<real,3> random_stuff=random->uniform<Vector<real,3> >(0,1);
Vector<T,3> normalized_values=pixel_values-Vector<T,3>(floored_values);
for(int k=0;k<3;k++)
if(random_stuff[k]>normalized_values[k]) result.flat(t)[k]=(floored_values[k]+(T).5001)/255; // use normal quantized floor
else result.flat(t)[k]=(floored_values[k]+(T)1.5001)/255;} // jump to next value
return result;
}
template<class T>
Array<Vector<T,3>,2> Image<T>::median(const vector<Array<const Vector<T,3>,2> >& images) {
OTHER_ASSERT(images.size());
int n = (int)images.size();
for (int k=1;k<n;k++)
OTHER_ASSERT(images[0].sizes()==images[k].sizes());
Array<T,2> pixel(3,n);
Array<Vector<T,3>,2> result(images[0].sizes());
for(int t=0; t<result.flat.size(); t++){
for (int k=0;k<n;k++)
images[k].flat[t].get(pixel(0,k),pixel(1,k),pixel(2,k));
for (int a=0;a<3;a++) {
RawArray<T> samples = pixel[a];
nth_element(&samples[0],&samples[n/2],&samples[n-1]);
result.flat[t][a] = samples[n/2];
}
}
return result;
}
template<class T> bool Image<T>::
is_supported(const string& filename)
{
string ext = path::extension(filename);
if(ext==".jpg") return JpgFile<T>::is_supported();
else if(ext==".png") return PngFile<T>::is_supported();
else if(ext==".exr") return ExrFile<T>::is_supported();
else return false;
}
template<> uint8_t component_to_scalar_color(const uint8_t color_in) { return color_in; }
template<> uint8_t component_to_byte_color(const uint8_t color_in) { return color_in; }
template class Image<float>;
template class Image<double>;
template Array<Vector<uint8_t,3>,2> Image<uint8_t>::read(const string&);
template Array<Vector<uint8_t,4>,2> Image<uint8_t>::read_alpha(const string&);
template void Image<uint8_t>::write(const string&,RawArray<const Vector<uint8_t,3>,2>);
template void Image<uint8_t>::write_alpha(const string&,RawArray<const Vector<uint8_t,4>,2>);
template vector<unsigned char> Image<uint8_t>::write_png_to_memory(RawArray<const Vector<uint8_t,3>,2>);
template vector<unsigned char> Image<uint8_t>::write_png_to_memory(RawArray<const Vector<uint8_t,4>,2>);
}
void wrap_Image()
{
using namespace other;
using namespace python;
typedef real T;
typedef Image<T> Self;
Class<Self>("Image")
.OTHER_METHOD(read)
.OTHER_METHOD(write)
.OTHER_METHOD(gamma_compress)
.OTHER_METHOD(dither)
.OTHER_METHOD(median)
.OTHER_METHOD(is_supported)
;
}
<commit_msg>Support .jpeg extension.<commit_after>//#####################################################################
// Class Image
//#####################################################################
#include <other/core/geometry/Box.h>
#include <other/core/image/Image.h>
#include <other/core/image/JpgFile.h>
#include <other/core/image/PngFile.h>
#include <other/core/image/ExrFile.h>
#include <other/core/python/Class.h>
#include <other/core/python/stl.h>
#include <other/core/random/Random.h>
#include <other/core/utility/path.h>
#include <other/core/utility/Log.h>
#include <cmath>
namespace other {
using std::pow;
using std::nth_element;
template<> OTHER_DEFINE_TYPE(Image<real>)
template<class T> Array<Vector<T,3>,2> Image<T>::read(const string& filename)
{
string ext = path::extension(filename);
if(ext==".jpg" || ext==".jpeg") return JpgFile<T>::read(filename);
else if(ext==".png") return PngFile<T>::read(filename);
else if(ext==".exr") return ExrFile<T>::read(filename);
OTHER_FATAL_ERROR(format("Unknown image file extension from filename '%s' extension '%s'",filename,ext));
}
template<class T> Array<Vector<T,4>,2> Image<T>::read_alpha(const string& filename)
{
string ext = path::extension(filename);
if(ext==".png") return PngFile<T>::read_alpha(filename);
OTHER_FATAL_ERROR(format("Image file extension unknown or without alpha from filename '%s' extension '%s'",filename,ext));
}
template<class T> void Image<T>::
write(const string& filename,RawArray<const Vector<T,3>,2> image)
{
string ext = path::extension(filename);
if(ext==".jpg" || ext==".jpeg") JpgFile<T>::write(filename,image);
else if(ext==".png") PngFile<T>::write(filename,image);
else if(ext==".exr") ExrFile<T>::write(filename,image);
else OTHER_FATAL_ERROR(format("Unknown image file extension from filename '%s' extension '%s'",filename,ext));
}
template<class T> void Image<T>::
write_alpha(const string& filename,RawArray<const Vector<T,4>,2> image)
{
string ext = path::extension(filename);
if(ext==".png") PngFile<T>::write(filename,image);
else if(ext==".jpg") OTHER_FATAL_ERROR(format("No support for alpha channel with extension '%s' for filename '%s'",ext,filename));
else OTHER_FATAL_ERROR(format("Unknown image file extension from filename '%s' extension '%s'",filename,ext));
}
template<class T> std::vector<unsigned char> Image<T>::
write_png_to_memory(RawArray<const Vector<T,3>,2> image) {
return PngFile<T>::write_to_memory(image);
}
template<class T> std::vector<unsigned char> Image<T>::
write_png_to_memory(RawArray<const Vector<T,4>,2> image) {
return PngFile<T>::write_to_memory(image);
}
template<class T> Array<Vector<T,3>,2> Image<T>::
gamma_compress(Array<const Vector<T,3>,2> image,const real gamma)
{
T one_over_gamma = T(1/gamma);
Array<Vector<T,3>,2> result(image.sizes());
for(int t=0;t<result.flat.size();t++)
for (int i = 0; i < 3; ++i)
result.flat[t][i] = pow(image.flat(t)[i],one_over_gamma);
return result;
}
template<class T> Array<Vector<T,3>,2> Image<T>::
dither(Array<const Vector<T,3>,2> image)
{
Ref<Random> random=new_<Random>(324032); // want uniform seed so noise perturbation pattern is temporally coherent
Array<Vector<T,3>,2> result(image.sizes());
for(int t=0;t<result.flat.size();t++){
result.flat(t)=image.flat(t);
Vector<T,3> pixel_values((T)255*result.flat(t));
Vector<int,3> floored_values((int)pixel_values[0],(int)pixel_values[1],(int)pixel_values[2]);
Vector<real,3> random_stuff=random->uniform<Vector<real,3> >(0,1);
Vector<T,3> normalized_values=pixel_values-Vector<T,3>(floored_values);
for(int k=0;k<3;k++)
if(random_stuff[k]>normalized_values[k]) result.flat(t)[k]=(floored_values[k]+(T).5001)/255; // use normal quantized floor
else result.flat(t)[k]=(floored_values[k]+(T)1.5001)/255;} // jump to next value
return result;
}
template<class T>
Array<Vector<T,3>,2> Image<T>::median(const vector<Array<const Vector<T,3>,2> >& images) {
OTHER_ASSERT(images.size());
int n = (int)images.size();
for (int k=1;k<n;k++)
OTHER_ASSERT(images[0].sizes()==images[k].sizes());
Array<T,2> pixel(3,n);
Array<Vector<T,3>,2> result(images[0].sizes());
for(int t=0; t<result.flat.size(); t++){
for (int k=0;k<n;k++)
images[k].flat[t].get(pixel(0,k),pixel(1,k),pixel(2,k));
for (int a=0;a<3;a++) {
RawArray<T> samples = pixel[a];
nth_element(&samples[0],&samples[n/2],&samples[n-1]);
result.flat[t][a] = samples[n/2];
}
}
return result;
}
template<class T> bool Image<T>::
is_supported(const string& filename)
{
string ext = path::extension(filename);
if(ext==".jpg" || ext==".jpeg") return JpgFile<T>::is_supported();
else if(ext==".png") return PngFile<T>::is_supported();
else if(ext==".exr") return ExrFile<T>::is_supported();
else return false;
}
template<> uint8_t component_to_scalar_color(const uint8_t color_in) { return color_in; }
template<> uint8_t component_to_byte_color(const uint8_t color_in) { return color_in; }
template class Image<float>;
template class Image<double>;
template Array<Vector<uint8_t,3>,2> Image<uint8_t>::read(const string&);
template Array<Vector<uint8_t,4>,2> Image<uint8_t>::read_alpha(const string&);
template void Image<uint8_t>::write(const string&,RawArray<const Vector<uint8_t,3>,2>);
template void Image<uint8_t>::write_alpha(const string&,RawArray<const Vector<uint8_t,4>,2>);
template vector<unsigned char> Image<uint8_t>::write_png_to_memory(RawArray<const Vector<uint8_t,3>,2>);
template vector<unsigned char> Image<uint8_t>::write_png_to_memory(RawArray<const Vector<uint8_t,4>,2>);
}
void wrap_Image()
{
using namespace other;
using namespace python;
typedef real T;
typedef Image<T> Self;
Class<Self>("Image")
.OTHER_METHOD(read)
.OTHER_METHOD(write)
.OTHER_METHOD(gamma_compress)
.OTHER_METHOD(dither)
.OTHER_METHOD(median)
.OTHER_METHOD(is_supported)
;
}
<|endoftext|>
|
<commit_before>//
// Name: SceneGraphDlg.cpp
//
// Copyright (c) 2001-2003 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//
#ifdef __GNUG__
#pragma implementation "SceneGraphDlg.cpp"
#endif
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include "wx/treectrl.h"
#include "wx/image.h"
#include "vtlib/vtlib.h"
#include "vtlib/core/Engine.h"
#include "vtui/wxString2.h"
#include "SceneGraphDlg.h"
#include <typeinfo>
using namespace std;
#if defined(__WXGTK__) || defined(__WXMOTIF__)
# include "icon1.xpm"
# include "icon2.xpm"
# include "icon3.xpm"
# include "icon4.xpm"
# include "icon5.xpm"
# include "icon6.xpm"
# include "icon7.xpm"
# include "icon8.xpm"
# include "icon9.xpm"
# include "icon10.xpm"
#endif
/////////////////////////////
class MyTreeItemData : public wxTreeItemData
{
public:
MyTreeItemData(vtNodeBase *pNode, vtEngine *pEngine)
{
m_pNode = pNode;
m_pEngine = pEngine;
}
vtNodeBase *m_pNode;
vtEngine *m_pEngine;
};
// WDR: class implementations
//----------------------------------------------------------------------------
// SceneGraphDlg
//----------------------------------------------------------------------------
// WDR: event table for SceneGraphDlg
BEGIN_EVENT_TABLE(SceneGraphDlg,wxDialog)
EVT_INIT_DIALOG (SceneGraphDlg::OnInitDialog)
EVT_TREE_SEL_CHANGED( ID_SCENETREE, SceneGraphDlg::OnTreeSelChanged )
EVT_CHECKBOX( ID_ENABLED, SceneGraphDlg::OnEnabled )
EVT_BUTTON( ID_ZOOMTO, SceneGraphDlg::OnZoomTo )
EVT_BUTTON( ID_REFRESH, SceneGraphDlg::OnRefresh )
END_EVENT_TABLE()
SceneGraphDlg::SceneGraphDlg( wxWindow *parent, wxWindowID id, const wxString &title,
const wxPoint &position, const wxSize& size, long style ) :
wxDialog( parent, id, title, position, size, style )
{
SceneGraphFunc( this, TRUE );
m_pZoomTo = GetZoomto();
m_pEnabled = GetEnabled();
m_pTree = GetScenetree();
m_pZoomTo->Enable(false);
m_imageListNormal = NULL;
CreateImageList(16);
}
SceneGraphDlg::~SceneGraphDlg()
{
delete m_imageListNormal;
}
///////////
void SceneGraphDlg::CreateImageList(int size)
{
delete m_imageListNormal;
if ( size == -1 )
{
m_imageListNormal = NULL;
return;
}
// Make an image list containing small icons
m_imageListNormal = new wxImageList(size, size, TRUE);
wxIcon icons[10];
icons[0] = wxICON(icon1);
icons[1] = wxICON(icon2);
icons[2] = wxICON(icon3);
icons[3] = wxICON(icon4);
icons[4] = wxICON(icon5);
icons[5] = wxICON(icon6);
icons[6] = wxICON(icon7);
icons[7] = wxICON(icon8);
icons[8] = wxICON(icon9);
icons[9] = wxICON(icon10);
int sizeOrig = icons[0].GetWidth();
for ( size_t i = 0; i < WXSIZEOF(icons); i++ )
{
if ( size == sizeOrig )
m_imageListNormal->Add(icons[i]);
else
m_imageListNormal->Add(wxBitmap(wxBitmap(icons[i]).ConvertToImage().Rescale(size, size)));
}
m_pTree->SetImageList(m_imageListNormal);
}
void SceneGraphDlg::RefreshTreeContents()
{
vtScene* scene = vtGetScene();
if (!scene)
return;
// start with a blank slate
m_pTree->DeleteAllItems();
// Fill in the tree with nodes
m_bFirst = true;
vtNodeBase *pRoot = scene->GetRoot();
if (pRoot) AddNodeItemsRecursively(wxTreeItemId(), pRoot, 0);
wxTreeItemId hRoot = m_pTree->GetRootItem();
wxTreeItemId hEngRoot = m_pTree->AppendItem(hRoot, _T("Engines"), 7, 7);
// Fill in the tree with engines
int num = scene->GetNumEngines();
vtTarget *target;
for (int i = 0; i < num; i++)
{
vtEngine *pEng = scene->GetEngine(i);
wxString2 str = pEng->GetName2();
int targets = pEng->NumTargets();
target = pEng->GetTarget();
if (target)
{
str += _T(" -> ");
vtNodeBase *node = dynamic_cast<vtNodeBase*>(target);
if (node)
{
str += _T("\"");
str += wxString::FromAscii(node->GetName2());
str += _T("\"");
}
else
str += _T("(non-node)");
}
if (targets > 1)
{
wxString2 plus;
plus.Printf(_T(" (%d targets total)"), targets);
str += plus;
}
wxTreeItemId hEng = m_pTree->AppendItem(hEngRoot, str, 1, 1);
m_pTree->SetItemData(hEng, new MyTreeItemData(NULL, pEng));
}
m_pTree->Expand(hEngRoot);
m_pSelectedEngine = NULL;
m_pSelectedNode = NULL;
}
void SceneGraphDlg::AddNodeItemsRecursively(wxTreeItemId hParentItem,
vtNodeBase *pNode, int depth)
{
wxString str;
int nImage;
wxTreeItemId hNewItem;
if (!pNode) return;
if (dynamic_cast<vtLight*>(pNode))
{
str = _T("Light");
nImage = 4;
}
else if (dynamic_cast<vtGeom*>(pNode))
{
str = _T("Geom");
nImage = 2;
}
else if (dynamic_cast<vtLOD*>(pNode))
{
str = _T("LOD");
nImage = 5;
}
else if (dynamic_cast<vtTransformBase*>(pNode))
{
str = _T("XForm");
nImage = 9;
}
else if (dynamic_cast<vtGroupBase*>(pNode))
{
// must be just a group for grouping's sake
str = _T("Group");
nImage = 3;
}
else
{
// must be something else
str = _T("Other");
nImage = 8;
}
if (pNode->GetName2())
{
str += _T(" \"");
str += wxString::FromAscii(pNode->GetName2());
str += _T("\"");
}
if (m_bFirst)
{
hNewItem = m_pTree->AddRoot(str);
m_bFirst = false;
}
else
hNewItem = m_pTree->AppendItem(hParentItem, str, nImage, nImage);
const std::type_info &t1 = typeid(*pNode);
if (t1 == typeid(vtGeom))
{
vtGeom *pGeom = dynamic_cast<vtGeom*>(pNode);
int num_mesh = pGeom->GetNumMeshes();
wxTreeItemId hGeomItem;
for (int i = 0; i < num_mesh; i++)
{
vtMesh *pMesh = pGeom->GetMesh(i);
if (pMesh)
{
int iNumPrim = pMesh->GetNumPrims();
int iNumVert = pMesh->GetNumVertices();
GLenum pt = pMesh->GetPrimType();
const char *mtype;
switch (pt)
{
case GL_POINTS: mtype = "Points"; break;
case GL_LINES: mtype = "Lines"; break;
case GL_LINE_LOOP: mtype = "LineLoop"; break;
case GL_LINE_STRIP: mtype = "LineStrip"; break;
case GL_TRIANGLES: mtype = "Triangles"; break;
case GL_TRIANGLE_STRIP: mtype = "TriStrip"; break;
case GL_TRIANGLE_FAN: mtype = "TriFan"; break;
case GL_QUADS: mtype = "Quads"; break;
case GL_QUAD_STRIP: mtype = "QuadStrip"; break;
case GL_POLYGON: mtype = "Polygon"; break;
}
str.Printf(_T("Mesh %d, %hs, %d verts, %d prims"), i, mtype, iNumVert, iNumPrim);
hGeomItem = m_pTree->AppendItem(hNewItem, str, 6, 6);
}
else
hGeomItem = m_pTree->AppendItem(hNewItem, _T("Text Mesh"), 6, 6);
}
}
m_pTree->SetItemData(hNewItem, new MyTreeItemData(pNode, NULL));
wxTreeItemId hSubItem;
vtGroupBase *pGroup = dynamic_cast<vtGroupBase*>(pNode);
if (pGroup)
{
int num_children = pGroup->GetNumChildren();
if (num_children > 200)
{
str.Printf(_T("(%d children)"), num_children);
hSubItem = m_pTree->AppendItem(hNewItem, str, 8, 8);
}
else
{
for (int i = 0; i < num_children; i++)
{
vtNode *pChild = pGroup->GetChild(i);
if (pChild)
AddNodeItemsRecursively(hNewItem, pChild, depth+1);
else
hSubItem = m_pTree->AppendItem(hNewItem, "(internal node)", 8, 8);
}
}
}
// expand a bit so that the tree is initially partially exposed
if (depth < 2)
m_pTree->Expand(hNewItem);
}
// WDR: handler implementations for SceneGraphDlg
void SceneGraphDlg::OnRefresh( wxCommandEvent &event )
{
RefreshTreeContents();
}
void SceneGraphDlg::OnZoomTo( wxCommandEvent &event )
{
if (m_pSelectedNode)
{
FSphere sph;
m_pSelectedNode->GetBoundSphere(sph, true); // global bounds
vtGetScene()->GetCamera()->ZoomToSphere(sph);
}
}
void SceneGraphDlg::OnEnabled( wxCommandEvent &event )
{
if (m_pSelectedEngine)
m_pSelectedEngine->SetEnabled(m_pEnabled->GetValue());
if (m_pSelectedNode)
m_pSelectedNode->SetEnabled(m_pEnabled->GetValue());
}
void SceneGraphDlg::OnTreeSelChanged( wxTreeEvent &event )
{
wxTreeItemId item = event.GetItem();
MyTreeItemData *data = (MyTreeItemData *)m_pTree->GetItemData(item);
m_pEnabled->Enable(data != NULL);
m_pSelectedEngine = NULL;
m_pSelectedNode = NULL;
if (data && data->m_pEngine)
{
m_pSelectedEngine = data->m_pEngine;
m_pEnabled->SetValue(m_pSelectedEngine->GetEnabled());
}
if (data && data->m_pNode)
{
m_pSelectedNode = data->m_pNode;
m_pEnabled->SetValue(m_pSelectedNode->GetEnabled());
m_pZoomTo->Enable(true);
}
else
m_pZoomTo->Enable(false);
}
void SceneGraphDlg::OnInitDialog(wxInitDialogEvent& event)
{
RefreshTreeContents();
wxWindow::OnInitDialog(event);
}
<commit_msg>Unicode fix<commit_after>//
// Name: SceneGraphDlg.cpp
//
// Copyright (c) 2001-2003 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//
#ifdef __GNUG__
#pragma implementation "SceneGraphDlg.cpp"
#endif
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include "wx/treectrl.h"
#include "wx/image.h"
#include "vtlib/vtlib.h"
#include "vtlib/core/Engine.h"
#include "vtui/wxString2.h"
#include "SceneGraphDlg.h"
#include <typeinfo>
using namespace std;
#if defined(__WXGTK__) || defined(__WXMOTIF__)
# include "icon1.xpm"
# include "icon2.xpm"
# include "icon3.xpm"
# include "icon4.xpm"
# include "icon5.xpm"
# include "icon6.xpm"
# include "icon7.xpm"
# include "icon8.xpm"
# include "icon9.xpm"
# include "icon10.xpm"
#endif
/////////////////////////////
class MyTreeItemData : public wxTreeItemData
{
public:
MyTreeItemData(vtNodeBase *pNode, vtEngine *pEngine)
{
m_pNode = pNode;
m_pEngine = pEngine;
}
vtNodeBase *m_pNode;
vtEngine *m_pEngine;
};
// WDR: class implementations
//----------------------------------------------------------------------------
// SceneGraphDlg
//----------------------------------------------------------------------------
// WDR: event table for SceneGraphDlg
BEGIN_EVENT_TABLE(SceneGraphDlg,wxDialog)
EVT_INIT_DIALOG (SceneGraphDlg::OnInitDialog)
EVT_TREE_SEL_CHANGED( ID_SCENETREE, SceneGraphDlg::OnTreeSelChanged )
EVT_CHECKBOX( ID_ENABLED, SceneGraphDlg::OnEnabled )
EVT_BUTTON( ID_ZOOMTO, SceneGraphDlg::OnZoomTo )
EVT_BUTTON( ID_REFRESH, SceneGraphDlg::OnRefresh )
END_EVENT_TABLE()
SceneGraphDlg::SceneGraphDlg( wxWindow *parent, wxWindowID id, const wxString &title,
const wxPoint &position, const wxSize& size, long style ) :
wxDialog( parent, id, title, position, size, style )
{
SceneGraphFunc( this, TRUE );
m_pZoomTo = GetZoomto();
m_pEnabled = GetEnabled();
m_pTree = GetScenetree();
m_pZoomTo->Enable(false);
m_imageListNormal = NULL;
CreateImageList(16);
}
SceneGraphDlg::~SceneGraphDlg()
{
delete m_imageListNormal;
}
///////////
void SceneGraphDlg::CreateImageList(int size)
{
delete m_imageListNormal;
if ( size == -1 )
{
m_imageListNormal = NULL;
return;
}
// Make an image list containing small icons
m_imageListNormal = new wxImageList(size, size, TRUE);
wxIcon icons[10];
icons[0] = wxICON(icon1);
icons[1] = wxICON(icon2);
icons[2] = wxICON(icon3);
icons[3] = wxICON(icon4);
icons[4] = wxICON(icon5);
icons[5] = wxICON(icon6);
icons[6] = wxICON(icon7);
icons[7] = wxICON(icon8);
icons[8] = wxICON(icon9);
icons[9] = wxICON(icon10);
int sizeOrig = icons[0].GetWidth();
for ( size_t i = 0; i < WXSIZEOF(icons); i++ )
{
if ( size == sizeOrig )
m_imageListNormal->Add(icons[i]);
else
m_imageListNormal->Add(wxBitmap(wxBitmap(icons[i]).ConvertToImage().Rescale(size, size)));
}
m_pTree->SetImageList(m_imageListNormal);
}
void SceneGraphDlg::RefreshTreeContents()
{
vtScene* scene = vtGetScene();
if (!scene)
return;
// start with a blank slate
m_pTree->DeleteAllItems();
// Fill in the tree with nodes
m_bFirst = true;
vtNodeBase *pRoot = scene->GetRoot();
if (pRoot) AddNodeItemsRecursively(wxTreeItemId(), pRoot, 0);
wxTreeItemId hRoot = m_pTree->GetRootItem();
wxTreeItemId hEngRoot = m_pTree->AppendItem(hRoot, _T("Engines"), 7, 7);
// Fill in the tree with engines
int num = scene->GetNumEngines();
vtTarget *target;
for (int i = 0; i < num; i++)
{
vtEngine *pEng = scene->GetEngine(i);
wxString2 str = pEng->GetName2();
int targets = pEng->NumTargets();
target = pEng->GetTarget();
if (target)
{
str += _T(" -> ");
vtNodeBase *node = dynamic_cast<vtNodeBase*>(target);
if (node)
{
str += _T("\"");
str += wxString::FromAscii(node->GetName2());
str += _T("\"");
}
else
str += _T("(non-node)");
}
if (targets > 1)
{
wxString2 plus;
plus.Printf(_T(" (%d targets total)"), targets);
str += plus;
}
wxTreeItemId hEng = m_pTree->AppendItem(hEngRoot, str, 1, 1);
m_pTree->SetItemData(hEng, new MyTreeItemData(NULL, pEng));
}
m_pTree->Expand(hEngRoot);
m_pSelectedEngine = NULL;
m_pSelectedNode = NULL;
}
void SceneGraphDlg::AddNodeItemsRecursively(wxTreeItemId hParentItem,
vtNodeBase *pNode, int depth)
{
wxString str;
int nImage;
wxTreeItemId hNewItem;
if (!pNode) return;
if (dynamic_cast<vtLight*>(pNode))
{
str = _T("Light");
nImage = 4;
}
else if (dynamic_cast<vtGeom*>(pNode))
{
str = _T("Geom");
nImage = 2;
}
else if (dynamic_cast<vtLOD*>(pNode))
{
str = _T("LOD");
nImage = 5;
}
else if (dynamic_cast<vtTransformBase*>(pNode))
{
str = _T("XForm");
nImage = 9;
}
else if (dynamic_cast<vtGroupBase*>(pNode))
{
// must be just a group for grouping's sake
str = _T("Group");
nImage = 3;
}
else
{
// must be something else
str = _T("Other");
nImage = 8;
}
if (pNode->GetName2())
{
str += _T(" \"");
str += wxString::FromAscii(pNode->GetName2());
str += _T("\"");
}
if (m_bFirst)
{
hNewItem = m_pTree->AddRoot(str);
m_bFirst = false;
}
else
hNewItem = m_pTree->AppendItem(hParentItem, str, nImage, nImage);
const std::type_info &t1 = typeid(*pNode);
if (t1 == typeid(vtGeom))
{
vtGeom *pGeom = dynamic_cast<vtGeom*>(pNode);
int num_mesh = pGeom->GetNumMeshes();
wxTreeItemId hGeomItem;
for (int i = 0; i < num_mesh; i++)
{
vtMesh *pMesh = pGeom->GetMesh(i);
if (pMesh)
{
int iNumPrim = pMesh->GetNumPrims();
int iNumVert = pMesh->GetNumVertices();
GLenum pt = pMesh->GetPrimType();
const char *mtype;
switch (pt)
{
case GL_POINTS: mtype = "Points"; break;
case GL_LINES: mtype = "Lines"; break;
case GL_LINE_LOOP: mtype = "LineLoop"; break;
case GL_LINE_STRIP: mtype = "LineStrip"; break;
case GL_TRIANGLES: mtype = "Triangles"; break;
case GL_TRIANGLE_STRIP: mtype = "TriStrip"; break;
case GL_TRIANGLE_FAN: mtype = "TriFan"; break;
case GL_QUADS: mtype = "Quads"; break;
case GL_QUAD_STRIP: mtype = "QuadStrip"; break;
case GL_POLYGON: mtype = "Polygon"; break;
}
str.Printf(_T("Mesh %d, %hs, %d verts, %d prims"), i, mtype, iNumVert, iNumPrim);
hGeomItem = m_pTree->AppendItem(hNewItem, str, 6, 6);
}
else
hGeomItem = m_pTree->AppendItem(hNewItem, _T("Text Mesh"), 6, 6);
}
}
m_pTree->SetItemData(hNewItem, new MyTreeItemData(pNode, NULL));
wxTreeItemId hSubItem;
vtGroupBase *pGroup = dynamic_cast<vtGroupBase*>(pNode);
if (pGroup)
{
int num_children = pGroup->GetNumChildren();
if (num_children > 200)
{
str.Printf(_T("(%d children)"), num_children);
hSubItem = m_pTree->AppendItem(hNewItem, str, 8, 8);
}
else
{
for (int i = 0; i < num_children; i++)
{
vtNode *pChild = pGroup->GetChild(i);
if (pChild)
AddNodeItemsRecursively(hNewItem, pChild, depth+1);
else
hSubItem = m_pTree->AppendItem(hNewItem, _T("(internal node)"), 8, 8);
}
}
}
// expand a bit so that the tree is initially partially exposed
if (depth < 2)
m_pTree->Expand(hNewItem);
}
// WDR: handler implementations for SceneGraphDlg
void SceneGraphDlg::OnRefresh( wxCommandEvent &event )
{
RefreshTreeContents();
}
void SceneGraphDlg::OnZoomTo( wxCommandEvent &event )
{
if (m_pSelectedNode)
{
FSphere sph;
m_pSelectedNode->GetBoundSphere(sph, true); // global bounds
vtGetScene()->GetCamera()->ZoomToSphere(sph);
}
}
void SceneGraphDlg::OnEnabled( wxCommandEvent &event )
{
if (m_pSelectedEngine)
m_pSelectedEngine->SetEnabled(m_pEnabled->GetValue());
if (m_pSelectedNode)
m_pSelectedNode->SetEnabled(m_pEnabled->GetValue());
}
void SceneGraphDlg::OnTreeSelChanged( wxTreeEvent &event )
{
wxTreeItemId item = event.GetItem();
MyTreeItemData *data = (MyTreeItemData *)m_pTree->GetItemData(item);
m_pEnabled->Enable(data != NULL);
m_pSelectedEngine = NULL;
m_pSelectedNode = NULL;
if (data && data->m_pEngine)
{
m_pSelectedEngine = data->m_pEngine;
m_pEnabled->SetValue(m_pSelectedEngine->GetEnabled());
}
if (data && data->m_pNode)
{
m_pSelectedNode = data->m_pNode;
m_pEnabled->SetValue(m_pSelectedNode->GetEnabled());
m_pZoomTo->Enable(true);
}
else
m_pZoomTo->Enable(false);
}
void SceneGraphDlg::OnInitDialog(wxInitDialogEvent& event)
{
RefreshTreeContents();
wxWindow::OnInitDialog(event);
}
<|endoftext|>
|
<commit_before>#include "RobustNormalEstimator.hpp"
#include "PlaneFitter.hpp"
#include <pcl/search/kdtree.h>
#include "Types.hpp"
using namespace planeseg;
RobustNormalEstimator::
RobustNormalEstimator() {
setRadius(0.1);
setMaxEstimationError(0.01);
setMaxCenterError(0.02);
setMaxIterations(100);
computeCurvature(true);
}
void RobustNormalEstimator::
setRadius(const float iRadius) {
mRadius = iRadius;
}
void RobustNormalEstimator::
setMaxEstimationError(const float iDist) {
mMaxEstimationError = iDist;
}
void RobustNormalEstimator::
setMaxCenterError(const float iDist) {
mMaxCenterError = iDist;
}
void RobustNormalEstimator::
setMaxIterations(const int iIters) {
mMaxIterations = iIters;
}
void RobustNormalEstimator::
computeCurvature(const bool iVal) {
mComputeCurvature = iVal;
}
bool RobustNormalEstimator::
go(const LabeledCloud::Ptr& iCloud, NormalCloud& oNormals) {
// plane fitter
PlaneFitter planeFitter;
planeFitter.setMaxIterations(100);
planeFitter.setMaxDistance(0.01);
planeFitter.setRefineUsingInliers(true);
std::vector<Eigen::Vector3f> pts;
pts.reserve(1000);
// kd tree
pcl::search::KdTree<Point>::Ptr tree
(new pcl::search::KdTree<Point>());
tree->setInputCloud(iCloud);
std::vector<int> indices;
std::vector<float> distances;
// loop
const int n = iCloud->size();
oNormals.width = n;
oNormals.height = 0;
oNormals.resize(n);
oNormals.is_dense = false;
for (int i = 0; i < n; ++i) {
tree->radiusSearch(i, mRadius, indices, distances);
pts.clear();
for (const auto idx : indices) {
pts.push_back(iCloud->points[idx].getVector3fMap());
}
auto& norm = oNormals.points[i];
norm.normal_x = norm.normal_y = norm.normal_z = 0;
norm.curvature = -1;
if (pts.size() < 3) continue;
// solve for plane
Eigen::Vector3f pt = iCloud->points[i].getVector3fMap();
planeFitter.setCenterPoint(pt);
auto res = planeFitter.go(pts);
auto& plane = res.mPlane;
if (plane[2] < 0) plane = -plane;
Eigen::Vector3f normal = plane.head<3>();
if (std::abs(normal.dot(pt) + plane[3]) > mMaxCenterError) continue;
if (normal[2]<0) normal = -normal;
norm.normal_x = normal[0];
norm.normal_y = normal[1];
norm.normal_z = normal[2];
if (mComputeCurvature) norm.curvature = res.mCurvature;
else norm.curvature = plane[3];
}
return true;
}
<commit_msg>use ivars for max iterations and estimation error<commit_after>#include "RobustNormalEstimator.hpp"
#include "PlaneFitter.hpp"
#include <pcl/search/kdtree.h>
#include "Types.hpp"
using namespace planeseg;
RobustNormalEstimator::
RobustNormalEstimator() {
setRadius(0.1);
setMaxEstimationError(0.01);
setMaxCenterError(0.02);
setMaxIterations(100);
computeCurvature(true);
}
void RobustNormalEstimator::
setRadius(const float iRadius) {
mRadius = iRadius;
}
void RobustNormalEstimator::
setMaxEstimationError(const float iDist) {
mMaxEstimationError = iDist;
}
void RobustNormalEstimator::
setMaxCenterError(const float iDist) {
mMaxCenterError = iDist;
}
void RobustNormalEstimator::
setMaxIterations(const int iIters) {
mMaxIterations = iIters;
}
void RobustNormalEstimator::
computeCurvature(const bool iVal) {
mComputeCurvature = iVal;
}
bool RobustNormalEstimator::
go(const LabeledCloud::Ptr& iCloud, NormalCloud& oNormals) {
// plane fitter
PlaneFitter planeFitter;
planeFitter.setMaxIterations(mMaxIterations);
planeFitter.setMaxDistance(mMaxEstimationError);
planeFitter.setRefineUsingInliers(true);
std::vector<Eigen::Vector3f> pts;
pts.reserve(1000);
// kd tree
pcl::search::KdTree<Point>::Ptr tree
(new pcl::search::KdTree<Point>());
tree->setInputCloud(iCloud);
std::vector<int> indices;
std::vector<float> distances;
// loop
const int n = iCloud->size();
oNormals.width = n;
oNormals.height = 0;
oNormals.resize(n);
oNormals.is_dense = false;
for (int i = 0; i < n; ++i) {
tree->radiusSearch(i, mRadius, indices, distances);
pts.clear();
for (const auto idx : indices) {
pts.push_back(iCloud->points[idx].getVector3fMap());
}
auto& norm = oNormals.points[i];
norm.normal_x = norm.normal_y = norm.normal_z = 0;
norm.curvature = -1;
if (pts.size() < 3) continue;
// solve for plane
Eigen::Vector3f pt = iCloud->points[i].getVector3fMap();
planeFitter.setCenterPoint(pt);
auto res = planeFitter.go(pts);
auto& plane = res.mPlane;
if (plane[2] < 0) plane = -plane;
Eigen::Vector3f normal = plane.head<3>();
if (std::abs(normal.dot(pt) + plane[3]) > mMaxCenterError) continue;
if (normal[2]<0) normal = -normal;
norm.normal_x = normal[0];
norm.normal_y = normal[1];
norm.normal_z = normal[2];
if (mComputeCurvature) norm.curvature = res.mCurvature;
else norm.curvature = plane[3];
}
return true;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* 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: polysc3d.hxx,v $
* $Revision: 1.3 $
*
* 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 _E3D_POLYSC3D_HXX
#define _E3D_POLYSC3D_HXX
#include <svx/svdpage.hxx>
#include <svx/scene3d.hxx>
/*************************************************************************
|*
|* 3D-Szene mit Darstellung durch 2D-Polygone
|*
\************************************************************************/
class SVX_DLLPUBLIC E3dPolyScene : public E3dScene
{
public:
TYPEINFO();
E3dPolyScene();
E3dPolyScene(E3dDefaultAttributes& rDefault);
virtual UINT16 GetObjIdentifier() const;
// Zeichenmethode
virtual sal_Bool DoPaintObject(XOutputDevice&, const SdrPaintInfoRec&) const;
// Die Kontur fuer TextToContour
virtual basegfx::B2DPolyPolygon TakeContour() const;
virtual basegfx::B2DPolyPolygon ImpTakeContour3D() const;
virtual void Paint3D(XOutputDevice& rOut, Base3D* pBase3D,
const SdrPaintInfoRec& rInfoRec, UINT16 nDrawFlags=0);
protected:
void DrawAllShadows(Base3D *pBase3D, XOutputDevice& rXOut,
const Rectangle& rBound, const Volume3D& rVolume,
const SdrPaintInfoRec& rInfoRec);
BOOL LocalPaint3D(XOutputDevice& rOut, const SdrPaintInfoRec& rInfoRec);
void DrawPolySceneClip(XOutputDevice& rOut, const E3dObject *p3DObj,
Base3D *pBase3D, const SdrPaintInfoRec& rInfoRec);
void DrawWireframe(Base3D *pBase3D, XOutputDevice& rXOut);
};
#endif // _E3D_POLYSC3D_HXX
<commit_msg>INTEGRATION: CWS aw033 (1.2.76); FILE MERGED 2008/05/14 13:56:35 aw 1.2.76.2: RESYNC: (1.2-1.3); FILE MERGED 2008/01/22 12:29:04 aw 1.2.76.1: adaptions and 1st stripping<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: polysc3d.hxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _E3D_POLYSC3D_HXX
#define _E3D_POLYSC3D_HXX
#include <svx/svdpage.hxx>
#include <svx/scene3d.hxx>
/*************************************************************************
|*
|* 3D-Szene mit Darstellung durch 2D-Polygone
|*
\************************************************************************/
class SVX_DLLPUBLIC E3dPolyScene : public E3dScene
{
public:
TYPEINFO();
E3dPolyScene();
E3dPolyScene(E3dDefaultAttributes& rDefault);
virtual UINT16 GetObjIdentifier() const;
};
#endif // _E3D_POLYSC3D_HXX
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2013 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef MAPNIK_POLYGON_CLIPPER_HPP
#define MAPNIK_POLYGON_CLIPPER_HPP
// stl
#include <iostream>
#include <deque>
// mapnik
#include <mapnik/box2d.hpp>
#include <mapnik/geometry.hpp>
// boost
#include <boost/foreach.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/box.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/geometries/register/point.hpp>
BOOST_GEOMETRY_REGISTER_POINT_2D(mapnik::coord2d, double, cs::cartesian, x, y)
// register mapnik::box2d<double>
namespace boost { namespace geometry { namespace traits
{
template<> struct tag<mapnik::box2d<double> > { typedef box_tag type; };
template<> struct point_type<mapnik::box2d<double> > { typedef mapnik::coord2d type; };
template <>
struct indexed_access<mapnik::box2d<double>, min_corner, 0>
{
typedef coordinate_type<mapnik::coord2d>::type ct;
static inline ct get(mapnik::box2d<double> const& b) { return b.minx();}
static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_minx(value); }
};
template <>
struct indexed_access<mapnik::box2d<double>, min_corner, 1>
{
typedef coordinate_type<mapnik::coord2d>::type ct;
static inline ct get(mapnik::box2d<double> const& b) { return b.miny();}
static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_miny(value); }
};
template <>
struct indexed_access<mapnik::box2d<double>, max_corner, 0>
{
typedef coordinate_type<mapnik::coord2d>::type ct;
static inline ct get(mapnik::box2d<double> const& b) { return b.maxx();}
static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_maxx(value); }
};
template <>
struct indexed_access<mapnik::box2d<double>, max_corner, 1>
{
typedef coordinate_type<mapnik::coord2d>::type ct;
static inline ct get(mapnik::box2d<double> const& b) { return b.maxy();}
static inline void set(mapnik::box2d<double> &b , ct const& value) { b.set_maxy(value); }
};
}}}
namespace mapnik {
using namespace boost::geometry;
template <typename Geometry>
struct polygon_clipper
{
typedef mapnik::coord2d point_2d;
typedef model::polygon<mapnik::coord2d> polygon_2d;
typedef std::deque<polygon_2d> polygon_list;
polygon_clipper(Geometry & geom)
: clip_box_(),
geom_(geom)
{
}
polygon_clipper( box2d<double> const& clip_box,Geometry & geom)
: clip_box_(clip_box),
geom_(geom)
{
init();
}
void set_clip_box(box2d<double> const& clip_box)
{
clip_box_ = clip_box;
init();
}
unsigned type() const
{
return geom_.type();
}
void rewind(unsigned path_id)
{
output_.rewind(path_id);
}
unsigned vertex (double * x, double * y)
{
return output_.vertex(x,y);
}
private:
void init()
{
polygon_2d subject_poly;
double x,y;
double prev_x, prev_y;
geom_.rewind(0);
unsigned ring_count = 0;
while (true)
{
unsigned cmd = geom_.vertex(&x,&y);
if (cmd == SEG_END) break;
if (cmd == SEG_MOVETO)
{
prev_x = x;
prev_y = y;
if (ring_count == 0)
{
append(subject_poly, make<point_2d>(x,y));
}
else
{
subject_poly.inners().push_back(polygon_2d::inner_container_type::value_type());
append(subject_poly.inners().back(),make<point_2d>(x,y));
}
++ring_count;
}
else if (cmd == SEG_LINETO)
{
if (std::abs(x - prev_x) < 1e-12 && std::abs(y - prev_y) < 1e-12)
{
std::cerr << std::setprecision(12) << "coincident vertices:(" << prev_x << ","
<< prev_y << ") , (" << x << "," << y << ")" << std::endl;
continue;
}
prev_x = x;
prev_x = y;
if (ring_count == 1)
{
append(subject_poly, make<point_2d>(x,y));
}
else
{
append(subject_poly.inners().back(),make<point_2d>(x,y));
}
}
}
polygon_list clipped_polygons;
bool dissolved = false;
try
{
boost::geometry::intersection(clip_box_, subject_poly, clipped_polygons);
}
catch (boost::geometry::exception const& ex)
{
std::cerr << ex.what() << std::endl;
}
unsigned count=0;
BOOST_FOREACH(polygon_2d const& poly, clipped_polygons)
{
bool move_to = true;
BOOST_FOREACH(point_2d const& c, boost::geometry::exterior_ring(poly))
{
if (move_to)
{
move_to = false;
output_.move_to(c.x,c.y);
}
else
{
output_.line_to(c.x,c.y);
}
}
output_.close_path();
// interior rings
BOOST_FOREACH(polygon_2d::inner_container_type::value_type const& ring, boost::geometry::interior_rings(poly))
{
move_to = true;
BOOST_FOREACH(point_2d const& c, ring)
{
if (move_to)
{
move_to = false;
output_.move_to(c.x,c.y);
}
else
{
output_.line_to(c.x,c.y);
}
}
output_.close_path();
}
}
}
box2d<double> clip_box_;
Geometry & geom_;
mapnik::geometry_type output_;
};
}
#endif //MAPNIK_POLYGON_CLIPPER_HPP
<commit_msg>+ remove unused local vars<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2013 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef MAPNIK_POLYGON_CLIPPER_HPP
#define MAPNIK_POLYGON_CLIPPER_HPP
// stl
#include <iostream>
#include <deque>
// mapnik
#include <mapnik/box2d.hpp>
#include <mapnik/geometry.hpp>
// boost
#include <boost/foreach.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/box.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/geometries/register/point.hpp>
BOOST_GEOMETRY_REGISTER_POINT_2D(mapnik::coord2d, double, cs::cartesian, x, y)
// register mapnik::box2d<double>
namespace boost { namespace geometry { namespace traits
{
template<> struct tag<mapnik::box2d<double> > { typedef box_tag type; };
template<> struct point_type<mapnik::box2d<double> > { typedef mapnik::coord2d type; };
template <>
struct indexed_access<mapnik::box2d<double>, min_corner, 0>
{
typedef coordinate_type<mapnik::coord2d>::type ct;
static inline ct get(mapnik::box2d<double> const& b) { return b.minx();}
static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_minx(value); }
};
template <>
struct indexed_access<mapnik::box2d<double>, min_corner, 1>
{
typedef coordinate_type<mapnik::coord2d>::type ct;
static inline ct get(mapnik::box2d<double> const& b) { return b.miny();}
static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_miny(value); }
};
template <>
struct indexed_access<mapnik::box2d<double>, max_corner, 0>
{
typedef coordinate_type<mapnik::coord2d>::type ct;
static inline ct get(mapnik::box2d<double> const& b) { return b.maxx();}
static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_maxx(value); }
};
template <>
struct indexed_access<mapnik::box2d<double>, max_corner, 1>
{
typedef coordinate_type<mapnik::coord2d>::type ct;
static inline ct get(mapnik::box2d<double> const& b) { return b.maxy();}
static inline void set(mapnik::box2d<double> &b , ct const& value) { b.set_maxy(value); }
};
}}}
namespace mapnik {
using namespace boost::geometry;
template <typename Geometry>
struct polygon_clipper
{
typedef mapnik::coord2d point_2d;
typedef model::polygon<mapnik::coord2d> polygon_2d;
typedef std::deque<polygon_2d> polygon_list;
polygon_clipper(Geometry & geom)
: clip_box_(),
geom_(geom)
{
}
polygon_clipper( box2d<double> const& clip_box,Geometry & geom)
: clip_box_(clip_box),
geom_(geom)
{
init();
}
void set_clip_box(box2d<double> const& clip_box)
{
clip_box_ = clip_box;
init();
}
unsigned type() const
{
return geom_.type();
}
void rewind(unsigned path_id)
{
output_.rewind(path_id);
}
unsigned vertex (double * x, double * y)
{
return output_.vertex(x,y);
}
private:
void init()
{
polygon_2d subject_poly;
double x,y;
double prev_x, prev_y;
geom_.rewind(0);
unsigned ring_count = 0;
while (true)
{
unsigned cmd = geom_.vertex(&x,&y);
if (cmd == SEG_END) break;
if (cmd == SEG_MOVETO)
{
prev_x = x;
prev_y = y;
if (ring_count == 0)
{
append(subject_poly, make<point_2d>(x,y));
}
else
{
subject_poly.inners().push_back(polygon_2d::inner_container_type::value_type());
append(subject_poly.inners().back(),make<point_2d>(x,y));
}
++ring_count;
}
else if (cmd == SEG_LINETO)
{
if (std::abs(x - prev_x) < 1e-12 && std::abs(y - prev_y) < 1e-12)
{
std::cerr << std::setprecision(12) << "coincident vertices:(" << prev_x << ","
<< prev_y << ") , (" << x << "," << y << ")" << std::endl;
continue;
}
prev_x = x;
prev_x = y;
if (ring_count == 1)
{
append(subject_poly, make<point_2d>(x,y));
}
else
{
append(subject_poly.inners().back(),make<point_2d>(x,y));
}
}
}
polygon_list clipped_polygons;
try
{
boost::geometry::intersection(clip_box_, subject_poly, clipped_polygons);
}
catch (boost::geometry::exception const& ex)
{
std::cerr << ex.what() << std::endl;
}
BOOST_FOREACH(polygon_2d const& poly, clipped_polygons)
{
bool move_to = true;
BOOST_FOREACH(point_2d const& c, boost::geometry::exterior_ring(poly))
{
if (move_to)
{
move_to = false;
output_.move_to(c.x,c.y);
}
else
{
output_.line_to(c.x,c.y);
}
}
output_.close_path();
// interior rings
BOOST_FOREACH(polygon_2d::inner_container_type::value_type const& ring, boost::geometry::interior_rings(poly))
{
move_to = true;
BOOST_FOREACH(point_2d const& c, ring)
{
if (move_to)
{
move_to = false;
output_.move_to(c.x,c.y);
}
else
{
output_.line_to(c.x,c.y);
}
}
output_.close_path();
}
}
}
box2d<double> clip_box_;
Geometry & geom_;
mapnik::geometry_type output_;
};
}
#endif //MAPNIK_POLYGON_CLIPPER_HPP
<|endoftext|>
|
<commit_before>
#ifndef _PFASST_ENCAP_AUTOMAGIC_HPP_
#define _PFASST_ENCAP_AUTOMAGIC_HPP_
#include <tuple>
#include "../quadrature.hpp"
#include "encap_sweeper.hpp"
using namespace std;
namespace pfasst
{
namespace encap
{
template<typename ScalarT, typename timeT>
using auto_build_tuple = tuple<pfasst::encap::EncapSweeper<ScalarT, timeT>*,
pfasst::ITransfer*,
pfasst::encap::EncapFactory<ScalarT, timeT>*>;
template<typename ScalarT, typename timeT, typename ControllerT, typename buildT>
void auto_build(ControllerT& c, vector<pair<int, string>> nodes, buildT build)
{
for (unsigned int l = 0; l < nodes.size(); l++) {
auto nds = pfasst::compute_nodes<timeT>(get<0>(nodes[l]), get<1>(nodes[l]));
auto_build_tuple<ScalarT, timeT> tpl = build(l);
auto* sweeper = get<0>(tpl);
auto* transfer = get<1>(tpl);
auto* factory = get<2>(tpl);
sweeper->set_nodes(nds);
sweeper->set_factory(factory);
c.add_level(sweeper, transfer, false);
}
}
template<typename ScalarT, typename timeT, typename ControllerT, typename initialT>
void auto_setup(ControllerT& c, initialT initial)
{
c.setup();
for (int l = 0; l < c.nlevels(); l++) {
auto* isweeper = c.get_level(l);
auto* sweeper = dynamic_cast<pfasst::encap::EncapSweeper<ScalarT, timeT>*>(isweeper);
auto* q0 = sweeper->get_state(0);
initial(sweeper, q0);
}
}
}
}
#endif
<commit_msg>code style: template parameter capitalization<commit_after>
#ifndef _PFASST_ENCAP_AUTOMAGIC_HPP_
#define _PFASST_ENCAP_AUTOMAGIC_HPP_
#include <tuple>
#include "../quadrature.hpp"
#include "encap_sweeper.hpp"
using namespace std;
namespace pfasst
{
namespace encap
{
template<typename ScalarT, typename timeT>
using auto_build_tuple = tuple<pfasst::encap::EncapSweeper<ScalarT, timeT>*,
pfasst::ITransfer*,
pfasst::encap::EncapFactory<ScalarT, timeT>*>;
template<typename ScalarT, typename timeT, typename ControllerT, typename BuildT>
void auto_build(ControllerT& c, vector<pair<int, string>> nodes, BuildT build)
{
for (unsigned int l = 0; l < nodes.size(); l++) {
auto nds = pfasst::compute_nodes<timeT>(get<0>(nodes[l]), get<1>(nodes[l]));
auto_build_tuple<ScalarT, timeT> tpl = build(l);
auto* sweeper = get<0>(tpl);
auto* transfer = get<1>(tpl);
auto* factory = get<2>(tpl);
sweeper->set_nodes(nds);
sweeper->set_factory(factory);
c.add_level(sweeper, transfer, false);
}
}
template<typename ScalarT, typename timeT, typename ControllerT, typename InitialT>
void auto_setup(ControllerT& c, InitialT initial)
{
c.setup();
for (int l = 0; l < c.nlevels(); l++) {
auto* isweeper = c.get_level(l);
auto* sweeper = dynamic_cast<pfasst::encap::EncapSweeper<ScalarT, timeT>*>(isweeper);
auto* q0 = sweeper->get_state(0);
initial(sweeper, q0);
}
}
}
}
#endif
<|endoftext|>
|
<commit_before>// Copyright (c) 2014-2017 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAOCPP_PEGTL_INCLUDE_MEMORY_INPUT_HPP
#define TAOCPP_PEGTL_INCLUDE_MEMORY_INPUT_HPP
#include <cstddef>
#include <cstring>
#include <string>
#include <utility>
#include "config.hpp"
#include "eol.hpp"
#include "position.hpp"
#include "tracking_mode.hpp"
#include "internal/action_input.hpp"
#include "internal/bump_impl.hpp"
#include "internal/iterator.hpp"
#include "internal/marker.hpp"
namespace tao
{
namespace TAOCPP_PEGTL_NAMESPACE
{
namespace internal
{
template< typename Eol, tracking_mode >
class memory_input_base;
template< typename Eol >
class memory_input_base< Eol, tracking_mode::IMMEDIATE >
{
public:
using iterator_t = internal::iterator;
memory_input_base( const iterator_t& in_begin, const char* in_end, const char* in_source ) noexcept
: m_current( in_begin ),
m_end( in_end ),
m_source( in_source )
{
}
memory_input_base( const iterator_t& in_begin, const char* in_end, const std::string& in_source ) noexcept
: memory_input_base( in_begin, in_end, in_source.c_str() )
{
}
memory_input_base( const char* in_begin, const char* in_end, const char* in_source ) noexcept
: memory_input_base( iterator_t( in_begin ), in_end, in_source )
{
}
memory_input_base( const char* in_begin, const char* in_end, const std::string& in_source ) noexcept
: memory_input_base( in_begin, in_end, in_source.c_str() )
{
}
memory_input_base( const char* in_begin, const char* in_end, const char* in_source, const std::size_t in_byte, const std::size_t in_line, const std::size_t in_byte_in_line ) noexcept
: memory_input_base( { in_byte, in_line, in_byte_in_line, in_begin }, in_end, in_source )
{
}
memory_input_base( const char* in_begin, const char* in_end, const std::string& in_source, const std::size_t in_byte, const std::size_t in_line, const std::size_t in_byte_in_line ) noexcept
: memory_input_base( in_begin, in_end, in_source.c_str(), in_byte, in_line, in_byte_in_line )
{
}
const char* current() const noexcept
{
return m_current.data;
}
const char* end( const std::size_t = 0 ) const noexcept
{
return m_end;
}
std::size_t byte() const noexcept
{
return m_current.byte;
}
std::size_t line() const noexcept
{
return m_current.line;
}
std::size_t byte_in_line() const noexcept
{
return m_current.byte_in_line;
}
const char* source() const noexcept
{
return m_source;
}
void bump( const std::size_t in_count = 1 ) noexcept
{
internal::bump( m_current, in_count, Eol::ch );
}
void bump_in_this_line( const std::size_t in_count = 1 ) noexcept
{
internal::bump_in_this_line( m_current, in_count );
}
void bump_to_next_line( const std::size_t in_count = 1 ) noexcept
{
internal::bump_to_next_line( m_current, in_count );
}
TAOCPP_PEGTL_NAMESPACE::position position( const iterator_t& it ) const noexcept
{
return TAOCPP_PEGTL_NAMESPACE::position( it, m_source );
}
iterator_t& iterator() noexcept
{
return m_current;
}
const iterator_t& iterator() const noexcept
{
return m_current;
}
private:
iterator_t m_current;
const char* const m_end;
const char* const m_source;
};
template< typename Eol >
class memory_input_base< Eol, tracking_mode::LAZY >
{
public:
using iterator_t = const char*;
memory_input_base( const char* in_begin, const char* in_end, const char* in_source ) noexcept
: m_begin( in_begin ),
m_current( in_begin ),
m_end( in_end ),
m_source( in_source )
{
}
memory_input_base( const char* in_begin, const char* in_end, const std::string& in_source ) noexcept
: memory_input_base( in_begin, in_end, in_source.c_str() )
{
}
const char* current() const noexcept
{
return m_current;
}
const char* end( const std::size_t = 0 ) const noexcept
{
return m_end;
}
std::size_t byte() const noexcept
{
return std::size_t( current() - m_begin );
}
const char* source() const noexcept
{
return m_source;
}
void bump( const std::size_t in_count = 1 ) noexcept
{
m_current += in_count;
}
void bump_in_this_line( const std::size_t in_count = 1 ) noexcept
{
m_current += in_count;
}
void bump_to_next_line( const std::size_t in_count = 1 ) noexcept
{
m_current += in_count;
}
TAOCPP_PEGTL_NAMESPACE::position position( const char* it ) const noexcept
{
internal::iterator c( m_begin );
internal::bump( c, std::size_t( it - m_begin ), Eol::ch );
return TAOCPP_PEGTL_NAMESPACE::position( c, m_source );
}
iterator_t& iterator() noexcept
{
return m_current;
}
const iterator_t& iterator() const noexcept
{
return m_current;
}
private:
const iterator_t m_begin;
iterator_t m_current;
const char* const m_end;
const char* const m_source;
};
} // namespace internal
template< typename Eol = lf_crlf_eol, tracking_mode P = tracking_mode::IMMEDIATE >
class memory_input
: public internal::memory_input_base< Eol, P >
{
public:
using eol_t = Eol;
static constexpr tracking_mode tracking_mode_v = P;
using typename internal::memory_input_base< Eol, P >::iterator_t;
using memory_t = memory_input;
using action_t = internal::action_input< memory_input, P >;
using internal::memory_input_base< Eol, P >::memory_input_base;
memory_input( const char* in_begin, const std::size_t in_size, const char* in_source ) noexcept
: memory_input( in_begin, in_begin + in_size, in_source )
{
}
memory_input( const char* in_begin, const std::size_t in_size, const std::string& in_source ) noexcept
: memory_input( in_begin, in_size, in_source.c_str() )
{
}
memory_input( const std::string& in_string, const char* in_source ) noexcept
: memory_input( in_string.data(), in_string.size(), in_source )
{
}
memory_input( const std::string& in_string, const std::string& in_source ) noexcept
: memory_input( in_string, in_source.c_str() )
{
}
memory_input( const char* in_begin, const char* in_source ) noexcept
: memory_input( in_begin, std::strlen( in_begin ), in_source )
{
}
memory_input( const char* in_begin, const std::string& in_source ) noexcept
: memory_input( in_begin, in_source.c_str() )
{
}
bool empty() const noexcept
{
return this->current() == this->end();
}
std::size_t size( const std::size_t = 0 ) const noexcept
{
return std::size_t( this->end() - this->current() );
}
char peek_char( const std::size_t offset = 0 ) const noexcept
{
return this->current()[ offset ];
}
unsigned char peek_byte( const std::size_t offset = 0 ) const noexcept
{
return static_cast< unsigned char >( peek_char( offset ) );
}
using internal::memory_input_base< Eol, P >::position;
TAOCPP_PEGTL_NAMESPACE::position position() const noexcept
{
return this->position( this->iterator() );
}
void discard() const noexcept
{
}
void require( const std::size_t ) const noexcept
{
}
template< rewind_mode M >
internal::marker< iterator_t, M > mark() noexcept
{
return internal::marker< iterator_t, M >( this->iterator() );
}
};
} // namespace TAOCPP_PEGTL_NAMESPACE
} // namespace tao
#endif
<commit_msg>Allow offsets for lazy tracking mode<commit_after>// Copyright (c) 2014-2017 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAOCPP_PEGTL_INCLUDE_MEMORY_INPUT_HPP
#define TAOCPP_PEGTL_INCLUDE_MEMORY_INPUT_HPP
#include <cstddef>
#include <cstring>
#include <string>
#include <utility>
#include "config.hpp"
#include "eol.hpp"
#include "position.hpp"
#include "tracking_mode.hpp"
#include "internal/action_input.hpp"
#include "internal/bump_impl.hpp"
#include "internal/iterator.hpp"
#include "internal/marker.hpp"
namespace tao
{
namespace TAOCPP_PEGTL_NAMESPACE
{
namespace internal
{
template< typename Eol, tracking_mode >
class memory_input_base;
template< typename Eol >
class memory_input_base< Eol, tracking_mode::IMMEDIATE >
{
public:
using iterator_t = internal::iterator;
memory_input_base( const iterator_t& in_begin, const char* in_end, const char* in_source ) noexcept
: m_current( in_begin ),
m_end( in_end ),
m_source( in_source )
{
}
memory_input_base( const iterator_t& in_begin, const char* in_end, const std::string& in_source ) noexcept
: memory_input_base( in_begin, in_end, in_source.c_str() )
{
}
memory_input_base( const char* in_begin, const char* in_end, const char* in_source ) noexcept
: memory_input_base( iterator_t( in_begin ), in_end, in_source )
{
}
memory_input_base( const char* in_begin, const char* in_end, const std::string& in_source ) noexcept
: memory_input_base( in_begin, in_end, in_source.c_str() )
{
}
memory_input_base( const char* in_begin, const char* in_end, const char* in_source, const std::size_t in_byte, const std::size_t in_line, const std::size_t in_byte_in_line ) noexcept
: memory_input_base( { in_byte, in_line, in_byte_in_line, in_begin }, in_end, in_source )
{
}
memory_input_base( const char* in_begin, const char* in_end, const std::string& in_source, const std::size_t in_byte, const std::size_t in_line, const std::size_t in_byte_in_line ) noexcept
: memory_input_base( in_begin, in_end, in_source.c_str(), in_byte, in_line, in_byte_in_line )
{
}
const char* current() const noexcept
{
return m_current.data;
}
const char* end( const std::size_t = 0 ) const noexcept
{
return m_end;
}
std::size_t byte() const noexcept
{
return m_current.byte;
}
std::size_t line() const noexcept
{
return m_current.line;
}
std::size_t byte_in_line() const noexcept
{
return m_current.byte_in_line;
}
const char* source() const noexcept
{
return m_source;
}
void bump( const std::size_t in_count = 1 ) noexcept
{
internal::bump( m_current, in_count, Eol::ch );
}
void bump_in_this_line( const std::size_t in_count = 1 ) noexcept
{
internal::bump_in_this_line( m_current, in_count );
}
void bump_to_next_line( const std::size_t in_count = 1 ) noexcept
{
internal::bump_to_next_line( m_current, in_count );
}
TAOCPP_PEGTL_NAMESPACE::position position( const iterator_t& it ) const noexcept
{
return TAOCPP_PEGTL_NAMESPACE::position( it, m_source );
}
iterator_t& iterator() noexcept
{
return m_current;
}
const iterator_t& iterator() const noexcept
{
return m_current;
}
private:
iterator_t m_current;
const char* const m_end;
const char* const m_source;
};
template< typename Eol >
class memory_input_base< Eol, tracking_mode::LAZY >
{
public:
using iterator_t = const char*;
memory_input_base( const char* in_begin, const char* in_end, const char* in_source ) noexcept
: m_begin( in_begin ),
m_current( in_begin ),
m_end( in_end ),
m_source( in_source )
{
}
memory_input_base( const char* in_begin, const char* in_end, const std::string& in_source ) noexcept
: memory_input_base( in_begin, in_end, in_source.c_str() )
{
}
memory_input_base( const char* in_begin, const char* in_end, const char* in_source, const std::size_t in_byte, const std::size_t in_line, const std::size_t in_byte_in_line ) noexcept
: m_begin( in_byte, in_line, in_byte_in_line, in_begin ),
m_current( in_begin ),
m_end( in_end ),
m_source( in_source )
{
}
memory_input_base( const char* in_begin, const char* in_end, const std::string& in_source, const std::size_t in_byte, const std::size_t in_line, const std::size_t in_byte_in_line ) noexcept
: memory_input_base( in_begin, in_end, in_source.c_str(), in_byte, in_line, in_byte_in_line )
{
}
const char* current() const noexcept
{
return m_current;
}
const char* end( const std::size_t = 0 ) const noexcept
{
return m_end;
}
std::size_t byte() const noexcept
{
return std::size_t( current() - m_begin.data );
}
const char* source() const noexcept
{
return m_source;
}
void bump( const std::size_t in_count = 1 ) noexcept
{
m_current += in_count;
}
void bump_in_this_line( const std::size_t in_count = 1 ) noexcept
{
m_current += in_count;
}
void bump_to_next_line( const std::size_t in_count = 1 ) noexcept
{
m_current += in_count;
}
TAOCPP_PEGTL_NAMESPACE::position position( const char* it ) const noexcept
{
internal::iterator c( m_begin );
internal::bump( c, std::size_t( it - m_begin.data ), Eol::ch );
return TAOCPP_PEGTL_NAMESPACE::position( c, m_source );
}
iterator_t& iterator() noexcept
{
return m_current;
}
const iterator_t& iterator() const noexcept
{
return m_current;
}
private:
const internal::iterator m_begin;
iterator_t m_current;
const char* const m_end;
const char* const m_source;
};
} // namespace internal
template< typename Eol = lf_crlf_eol, tracking_mode P = tracking_mode::IMMEDIATE >
class memory_input
: public internal::memory_input_base< Eol, P >
{
public:
using eol_t = Eol;
static constexpr tracking_mode tracking_mode_v = P;
using typename internal::memory_input_base< Eol, P >::iterator_t;
using memory_t = memory_input;
using action_t = internal::action_input< memory_input, P >;
using internal::memory_input_base< Eol, P >::memory_input_base;
memory_input( const char* in_begin, const std::size_t in_size, const char* in_source ) noexcept
: memory_input( in_begin, in_begin + in_size, in_source )
{
}
memory_input( const char* in_begin, const std::size_t in_size, const std::string& in_source ) noexcept
: memory_input( in_begin, in_size, in_source.c_str() )
{
}
memory_input( const std::string& in_string, const char* in_source ) noexcept
: memory_input( in_string.data(), in_string.size(), in_source )
{
}
memory_input( const std::string& in_string, const std::string& in_source ) noexcept
: memory_input( in_string, in_source.c_str() )
{
}
memory_input( const char* in_begin, const char* in_source ) noexcept
: memory_input( in_begin, std::strlen( in_begin ), in_source )
{
}
memory_input( const char* in_begin, const std::string& in_source ) noexcept
: memory_input( in_begin, in_source.c_str() )
{
}
bool empty() const noexcept
{
return this->current() == this->end();
}
std::size_t size( const std::size_t = 0 ) const noexcept
{
return std::size_t( this->end() - this->current() );
}
char peek_char( const std::size_t offset = 0 ) const noexcept
{
return this->current()[ offset ];
}
unsigned char peek_byte( const std::size_t offset = 0 ) const noexcept
{
return static_cast< unsigned char >( peek_char( offset ) );
}
using internal::memory_input_base< Eol, P >::position;
TAOCPP_PEGTL_NAMESPACE::position position() const noexcept
{
return this->position( this->iterator() );
}
void discard() const noexcept
{
}
void require( const std::size_t ) const noexcept
{
}
template< rewind_mode M >
internal::marker< iterator_t, M > mark() noexcept
{
return internal::marker< iterator_t, M >( this->iterator() );
}
};
} // namespace TAOCPP_PEGTL_NAMESPACE
} // namespace tao
#endif
<|endoftext|>
|
<commit_before>// Copyright (c) 2014-2018 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAO_PEGTL_MEMORY_INPUT_HPP
#define TAO_PEGTL_MEMORY_INPUT_HPP
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <string>
#include <type_traits>
#include <utility>
#include "config.hpp"
#include "eol.hpp"
#include "normal.hpp"
#include "nothing.hpp"
#include "position.hpp"
#include "tracking_mode.hpp"
#include "internal/action_input.hpp"
#include "internal/at.hpp"
#include "internal/bump_impl.hpp"
#include "internal/eolf.hpp"
#include "internal/iterator.hpp"
#include "internal/marker.hpp"
#include "internal/until.hpp"
namespace tao
{
namespace TAO_PEGTL_NAMESPACE
{
namespace internal
{
template< typename Eol >
const char* find_end_of_line( const char* begin, const char* end ) noexcept;
template< tracking_mode, typename Eol, typename Source >
class memory_input_base;
template< typename Eol, typename Source >
class memory_input_base< tracking_mode::IMMEDIATE, Eol, Source >
{
public:
using iterator_t = internal::iterator;
template< typename T >
memory_input_base( const iterator_t& in_begin, const char* in_end, T&& in_source ) noexcept( std::is_nothrow_constructible< Source, T&& >::value )
: m_begin( in_begin.data ),
m_current( in_begin ),
m_end( in_end ),
m_source( std::forward< T >( in_source ) )
{
}
template< typename T >
memory_input_base( const char* in_begin, const char* in_end, T&& in_source ) noexcept( std::is_nothrow_constructible< Source, T&& >::value )
: m_begin( in_begin ),
m_current( in_begin ),
m_end( in_end ),
m_source( std::forward< T >( in_source ) )
{
}
memory_input_base( const memory_input_base& ) = delete;
memory_input_base( memory_input_base&& ) = delete;
~memory_input_base() = default;
memory_input_base operator=( const memory_input_base& ) = delete;
memory_input_base operator=( memory_input_base&& ) = delete;
const char* current() const noexcept
{
return m_current.data;
}
const char* begin() const noexcept
{
return m_begin;
}
const char* end( const std::size_t /*unused*/ = 0 ) const noexcept
{
return m_end;
}
std::size_t byte() const noexcept
{
return m_current.byte;
}
std::size_t line() const noexcept
{
return m_current.line;
}
std::size_t byte_in_line() const noexcept
{
return m_current.byte_in_line;
}
void bump( const std::size_t in_count = 1 ) noexcept
{
internal::bump( m_current, in_count, Eol::ch );
}
void bump_in_this_line( const std::size_t in_count = 1 ) noexcept
{
internal::bump_in_this_line( m_current, in_count );
}
void bump_to_next_line( const std::size_t in_count = 1 ) noexcept
{
internal::bump_to_next_line( m_current, in_count );
}
TAO_PEGTL_NAMESPACE::position position( const iterator_t& it ) const
{
return TAO_PEGTL_NAMESPACE::position( it, m_source );
}
void restart( const std::size_t in_byte = 0, const std::size_t in_line = 1, const std::size_t in_byte_in_line = 0 )
{
m_current.data = m_begin;
m_current.byte = in_byte;
m_current.line = in_line;
m_current.byte_in_line = in_byte_in_line;
}
protected:
const char* const m_begin;
iterator_t m_current;
const char* const m_end;
const Source m_source;
};
template< typename Eol, typename Source >
class memory_input_base< tracking_mode::LAZY, Eol, Source >
{
public:
using iterator_t = const char*;
template< typename T >
memory_input_base( const internal::iterator& in_begin, const char* in_end, T&& in_source ) noexcept( std::is_nothrow_constructible< Source, T&& >::value )
: m_begin( in_begin ),
m_current( in_begin.data ),
m_end( in_end ),
m_source( std::forward< T >( in_source ) )
{
}
template< typename T >
memory_input_base( const char* in_begin, const char* in_end, T&& in_source ) noexcept( std::is_nothrow_constructible< Source, T&& >::value )
: m_begin( in_begin ),
m_current( in_begin ),
m_end( in_end ),
m_source( std::forward< T >( in_source ) )
{
}
memory_input_base( const memory_input_base& ) = delete;
memory_input_base( memory_input_base&& ) = delete;
~memory_input_base() = default;
memory_input_base operator=( const memory_input_base& ) = delete;
memory_input_base operator=( memory_input_base&& ) = delete;
const char* current() const noexcept
{
return m_current;
}
const char* begin() const noexcept
{
return m_begin.data;
}
const char* end( const std::size_t /*unused*/ = 0 ) const noexcept
{
return m_end;
}
std::size_t byte() const noexcept
{
return std::size_t( current() - m_begin.data );
}
void bump( const std::size_t in_count = 1 ) noexcept
{
m_current += in_count;
}
void bump_in_this_line( const std::size_t in_count = 1 ) noexcept
{
m_current += in_count;
}
void bump_to_next_line( const std::size_t in_count = 1 ) noexcept
{
m_current += in_count;
}
TAO_PEGTL_NAMESPACE::position position( const iterator_t it ) const
{
internal::iterator c( m_begin );
internal::bump( c, std::size_t( it - m_begin.data ), Eol::ch );
return TAO_PEGTL_NAMESPACE::position( c, m_source );
}
void restart()
{
m_current = m_begin.data;
}
protected:
const internal::iterator m_begin;
iterator_t m_current;
const char* const m_end;
const Source m_source;
};
} // namespace internal
template< tracking_mode P = tracking_mode::IMMEDIATE, typename Eol = eol::lf_crlf, typename Source = std::string >
class memory_input
: public internal::memory_input_base< P, Eol, Source >
{
public:
static constexpr tracking_mode tracking_mode_v = P;
using eol_t = Eol;
using source_t = Source;
using typename internal::memory_input_base< P, Eol, Source >::iterator_t;
using action_t = internal::action_input< memory_input >;
using internal::memory_input_base< P, Eol, Source >::memory_input_base;
template< typename T >
memory_input( const char* in_begin, const std::size_t in_size, T&& in_source ) noexcept( std::is_nothrow_constructible< Source, T&& >::value )
: memory_input( in_begin, in_begin + in_size, std::forward< T >( in_source ) )
{
}
template< typename T >
memory_input( const std::string& in_string, T&& in_source ) noexcept( std::is_nothrow_constructible< Source, T&& >::value )
: memory_input( in_string.data(), in_string.size(), std::forward< T >( in_source ) )
{
}
template< typename T >
memory_input( std::string&&, T&& ) = delete;
template< typename T >
memory_input( const char* in_begin, T&& in_source ) noexcept( std::is_nothrow_constructible< Source, T&& >::value )
: memory_input( in_begin, std::strlen( in_begin ), std::forward< T >( in_source ) )
{
}
template< typename T >
memory_input( const char* in_begin, const char* in_end, T&& in_source, const std::size_t in_byte, const std::size_t in_line, const std::size_t in_byte_in_line ) noexcept( std::is_nothrow_constructible< Source, T&& >::value )
: memory_input( { in_begin, in_byte, in_line, in_byte_in_line }, in_end, std::forward< T >( in_source ) )
{
}
memory_input( const memory_input& ) = delete;
memory_input( memory_input&& ) = delete;
~memory_input() = default;
memory_input operator=( const memory_input& ) = delete;
memory_input operator=( memory_input&& ) = delete;
const Source& source() const noexcept
{
return this->m_source;
}
bool empty() const noexcept
{
return this->current() == this->end();
}
std::size_t size( const std::size_t /*unused*/ = 0 ) const noexcept
{
return std::size_t( this->end() - this->current() );
}
char peek_char( const std::size_t offset = 0 ) const noexcept
{
return this->current()[ offset ];
}
std::uint8_t peek_byte( const std::size_t offset = 0 ) const noexcept
{
return static_cast< std::uint8_t >( peek_char( offset ) );
}
iterator_t& iterator() noexcept
{
return this->m_current;
}
const iterator_t& iterator() const noexcept
{
return this->m_current;
}
using internal::memory_input_base< P, Eol, Source >::position;
TAO_PEGTL_NAMESPACE::position position() const
{
return position( iterator() );
}
void discard() const noexcept
{
}
void require( const std::size_t /*unused*/ ) const noexcept
{
}
template< rewind_mode M >
internal::marker< iterator_t, M > mark() noexcept
{
return internal::marker< iterator_t, M >( iterator() );
}
const char* at( const TAO_PEGTL_NAMESPACE::position& p ) const noexcept
{
return this->begin() + p.byte;
}
const char* begin_of_line( const TAO_PEGTL_NAMESPACE::position& p ) const noexcept
{
return at( p ) - p.byte_in_line;
}
const char* end_of_line( const TAO_PEGTL_NAMESPACE::position& p ) const noexcept
{
return internal::find_end_of_line< Eol >( at( p ), this->end() );
}
std::string line_as_string( const TAO_PEGTL_NAMESPACE::position& p ) const
{
return std::string( begin_of_line( p ), end_of_line( p ) );
}
};
namespace internal
{
template< typename Eol >
const char* find_end_of_line( const char* begin, const char* end ) noexcept
{
memory_input< tracking_mode::LAZY, Eol, const char* > in( begin, end, nullptr );
normal< internal::until< internal::at< internal::eolf > > >::match< apply_mode::NOTHING, rewind_mode::DONTCARE, nothing, normal >( in );
return in.current();
}
} // namespace internal
} // namespace TAO_PEGTL_NAMESPACE
} // namespace tao
#endif
<commit_msg>Another attempt to fix the VS 2015 ICE<commit_after>// Copyright (c) 2014-2018 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAO_PEGTL_MEMORY_INPUT_HPP
#define TAO_PEGTL_MEMORY_INPUT_HPP
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <string>
#include <type_traits>
#include <utility>
#include "config.hpp"
#include "eol.hpp"
#include "normal.hpp"
#include "nothing.hpp"
#include "position.hpp"
#include "tracking_mode.hpp"
#include "internal/action_input.hpp"
#include "internal/at.hpp"
#include "internal/bump_impl.hpp"
#include "internal/eolf.hpp"
#include "internal/iterator.hpp"
#include "internal/marker.hpp"
#include "internal/until.hpp"
namespace tao
{
namespace TAO_PEGTL_NAMESPACE
{
namespace internal
{
template< typename Eol >
const char* find_end_of_line( const char* begin, const char* end ) noexcept;
template< tracking_mode, typename Eol, typename Source >
class memory_input_base;
template< typename Eol, typename Source >
class memory_input_base< tracking_mode::IMMEDIATE, Eol, Source >
{
public:
using iterator_t = internal::iterator;
template< typename T >
memory_input_base( const iterator_t& in_begin, const char* in_end, T&& in_source ) noexcept( std::is_nothrow_constructible< Source, T&& >::value )
: m_begin( in_begin.data ),
m_current( in_begin ),
m_end( in_end ),
m_source( std::forward< T >( in_source ) )
{
}
template< typename T >
memory_input_base( const char* in_begin, const char* in_end, T&& in_source ) noexcept( std::is_nothrow_constructible< Source, T&& >::value )
: m_begin( in_begin ),
m_current( in_begin ),
m_end( in_end ),
m_source( std::forward< T >( in_source ) )
{
}
memory_input_base( const memory_input_base& ) = delete;
memory_input_base( memory_input_base&& ) = delete;
~memory_input_base() = default;
memory_input_base operator=( const memory_input_base& ) = delete;
memory_input_base operator=( memory_input_base&& ) = delete;
const char* current() const noexcept
{
return m_current.data;
}
const char* begin() const noexcept
{
return m_begin;
}
const char* end( const std::size_t /*unused*/ = 0 ) const noexcept
{
return m_end;
}
std::size_t byte() const noexcept
{
return m_current.byte;
}
std::size_t line() const noexcept
{
return m_current.line;
}
std::size_t byte_in_line() const noexcept
{
return m_current.byte_in_line;
}
void bump( const std::size_t in_count = 1 ) noexcept
{
internal::bump( m_current, in_count, Eol::ch );
}
void bump_in_this_line( const std::size_t in_count = 1 ) noexcept
{
internal::bump_in_this_line( m_current, in_count );
}
void bump_to_next_line( const std::size_t in_count = 1 ) noexcept
{
internal::bump_to_next_line( m_current, in_count );
}
TAO_PEGTL_NAMESPACE::position position( const iterator_t& it ) const
{
return TAO_PEGTL_NAMESPACE::position( it, m_source );
}
void restart( const std::size_t in_byte = 0, const std::size_t in_line = 1, const std::size_t in_byte_in_line = 0 )
{
m_current.data = m_begin;
m_current.byte = in_byte;
m_current.line = in_line;
m_current.byte_in_line = in_byte_in_line;
}
protected:
const char* const m_begin;
iterator_t m_current;
const char* const m_end;
const Source m_source;
};
template< typename Eol, typename Source >
class memory_input_base< tracking_mode::LAZY, Eol, Source >
{
public:
using iterator_t = const char*;
template< typename T >
memory_input_base( const internal::iterator& in_begin, const char* in_end, T&& in_source ) noexcept( std::is_nothrow_constructible< Source, T&& >::value )
: m_begin( in_begin ),
m_current( in_begin.data ),
m_end( in_end ),
m_source( std::forward< T >( in_source ) )
{
}
template< typename T >
memory_input_base( const char* in_begin, const char* in_end, T&& in_source ) noexcept( std::is_nothrow_constructible< Source, T&& >::value )
: m_begin( in_begin ),
m_current( in_begin ),
m_end( in_end ),
m_source( std::forward< T >( in_source ) )
{
}
memory_input_base( const memory_input_base& ) = delete;
memory_input_base( memory_input_base&& ) = delete;
~memory_input_base() = default;
memory_input_base operator=( const memory_input_base& ) = delete;
memory_input_base operator=( memory_input_base&& ) = delete;
const char* current() const noexcept
{
return m_current;
}
const char* begin() const noexcept
{
return m_begin.data;
}
const char* end( const std::size_t /*unused*/ = 0 ) const noexcept
{
return m_end;
}
std::size_t byte() const noexcept
{
return std::size_t( current() - m_begin.data );
}
void bump( const std::size_t in_count = 1 ) noexcept
{
m_current += in_count;
}
void bump_in_this_line( const std::size_t in_count = 1 ) noexcept
{
m_current += in_count;
}
void bump_to_next_line( const std::size_t in_count = 1 ) noexcept
{
m_current += in_count;
}
TAO_PEGTL_NAMESPACE::position position( const iterator_t it ) const
{
internal::iterator c( m_begin );
internal::bump( c, std::size_t( it - m_begin.data ), Eol::ch );
return TAO_PEGTL_NAMESPACE::position( c, m_source );
}
void restart()
{
m_current = m_begin.data;
}
protected:
const internal::iterator m_begin;
iterator_t m_current;
const char* const m_end;
const Source m_source;
};
} // namespace internal
template< tracking_mode P = tracking_mode::IMMEDIATE, typename Eol = eol::lf_crlf, typename Source = std::string >
class memory_input
: public internal::memory_input_base< P, Eol, Source >
{
public:
static constexpr tracking_mode tracking_mode_v = P;
using eol_t = Eol;
using source_t = Source;
using typename internal::memory_input_base< P, Eol, Source >::iterator_t;
using action_t = internal::action_input< memory_input >;
using internal::memory_input_base< P, Eol, Source >::memory_input_base;
template< typename T >
memory_input( const char* in_begin, const std::size_t in_size, T&& in_source ) noexcept( std::is_nothrow_constructible< Source, T&& >::value )
: memory_input( in_begin, in_begin + in_size, std::forward< T >( in_source ) )
{
}
template< typename T >
memory_input( const std::string& in_string, T&& in_source ) noexcept( std::is_nothrow_constructible< Source, T&& >::value )
: memory_input( in_string.data(), in_string.size(), std::forward< T >( in_source ) )
{
}
template< typename T >
memory_input( std::string&&, T&& ) = delete;
template< typename T >
memory_input( const char* in_begin, T&& in_source ) noexcept( std::is_nothrow_constructible< Source, T&& >::value )
: memory_input( in_begin, std::strlen( in_begin ), std::forward< T >( in_source ) )
{
}
template< typename T >
memory_input( const char* in_begin, const char* in_end, T&& in_source, const std::size_t in_byte, const std::size_t in_line, const std::size_t in_byte_in_line ) noexcept( std::is_nothrow_constructible< Source, T&& >::value )
: memory_input( { in_begin, in_byte, in_line, in_byte_in_line }, in_end, std::forward< T >( in_source ) )
{
}
memory_input( const memory_input& ) = delete;
memory_input( memory_input&& ) = delete;
~memory_input() = default;
memory_input operator=( const memory_input& ) = delete;
memory_input operator=( memory_input&& ) = delete;
const Source& source() const noexcept
{
return this->m_source;
}
bool empty() const noexcept
{
return this->current() == this->end();
}
std::size_t size( const std::size_t /*unused*/ = 0 ) const noexcept
{
return std::size_t( this->end() - this->current() );
}
char peek_char( const std::size_t offset = 0 ) const noexcept
{
return this->current()[ offset ];
}
std::uint8_t peek_byte( const std::size_t offset = 0 ) const noexcept
{
return static_cast< std::uint8_t >( peek_char( offset ) );
}
iterator_t& iterator() noexcept
{
return this->m_current;
}
const iterator_t& iterator() const noexcept
{
return this->m_current;
}
using internal::memory_input_base< P, Eol, Source >::position;
TAO_PEGTL_NAMESPACE::position position() const
{
return position( iterator() );
}
void discard() const noexcept
{
}
void require( const std::size_t /*unused*/ ) const noexcept
{
}
template< rewind_mode M >
internal::marker< iterator_t, M > mark() noexcept
{
return internal::marker< iterator_t, M >( iterator() );
}
const char* at( const TAO_PEGTL_NAMESPACE::position& p ) const noexcept
{
return this->begin() + p.byte;
}
const char* begin_of_line( const TAO_PEGTL_NAMESPACE::position& p ) const noexcept
{
return at( p ) - p.byte_in_line;
}
const char* end_of_line( const TAO_PEGTL_NAMESPACE::position& p ) const noexcept
{
return internal::find_end_of_line< Eol >( at( p ), this->end() );
}
std::string line_as_string( const TAO_PEGTL_NAMESPACE::position& p ) const
{
return std::string( begin_of_line( p ), end_of_line( p ) );
}
};
namespace internal
{
template< typename Eol >
const char* find_end_of_line( const char* begin, const char* end ) noexcept
{
using input_t = memory_input< tracking_mode::LAZY, Eol, const char* >;
input_t in( begin, end, "" );
using grammar = internal::until< internal::at< internal::eolf > >;
using normal_t = normal< grammar >;
normal_t::match< apply_mode::NOTHING, rewind_mode::DONTCARE, nothing, normal >( in );
return in.current();
}
} // namespace internal
} // namespace TAO_PEGTL_NAMESPACE
} // namespace tao
#endif
<|endoftext|>
|
<commit_before>/*******************************************************************************
* _ _ _ *
* | | | | (_) *
* | |_ __ _ ___| | ___ *
* | __/ _` / __| |/ / | *
* | || (_| \__ \ <| | *
* \__\__,_|___/_|\_\_| *
* *
* Copyright (C) 2015 - 2021 *
* Marian Triebe *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License *
* See accompanying file LICENSE. *
* *
* If you did not receive a copy of the license file, see *
* http://opensource.org/licenses/BSD-3-Clause *
*******************************************************************************/
#pragma once
#include <tuple>
#include <future>
#include <functional>
#include "taski/detail/storable.hpp"
namespace taski::detail {
/// Stores a function and its arguments as a whole.
template <class Fun, class... Args>
class work_item : public storable {
using result_t = std::invoke_result_t<Fun, Args...>;
public:
/// Creates a work item composed of a function and its arguments.
/// @param fun Function to be invoked
/// @param args Arguments to be applied to function
work_item(Fun&& fun, Args&&... args)
: fun_{std::forward<Fun>(fun)}
, args_{std::forward_as_tuple(std::forward<Args>(args)...)} {
// nop
}
/// @returns a future which is set when the function has been called.
std::future<result_t> future() { return ret_.get_future(); }
/// Invoke the stored function with stored arguments.
void operator()() override {
if constexpr (std::is_same_v<result_t, void>) {
std::apply(fun_, std::move(args_));
ret_.set_value();
} else {
auto res = std::apply(fun_, std::move(args_));
if constexpr (std::is_move_constructible_v<result_t>) {
ret_.set_value(std::move(res));
} else {
ret_.set_value(res);
}
}
}
private:
Fun fun_; /// Function to be invoked
std::tuple<Args...> args_; /// Arguments stored as tuple
std::promise<result_t> ret_; /// Response promise
};
} // namespace taski::detail
<commit_msg>Fix sonar bug findings<commit_after>/*******************************************************************************
* _ _ _ *
* | | | | (_) *
* | |_ __ _ ___| | ___ *
* | __/ _` / __| |/ / | *
* | || (_| \__ \ <| | *
* \__\__,_|___/_|\_\_| *
* *
* Copyright (C) 2015 - 2021 *
* Marian Triebe *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License *
* See accompanying file LICENSE. *
* *
* If you did not receive a copy of the license file, see *
* http://opensource.org/licenses/BSD-3-Clause *
*******************************************************************************/
#pragma once
#include <tuple>
#include <future>
#include <functional>
#include "taski/detail/storable.hpp"
namespace taski::detail {
/// Stores a function and its arguments as a whole.
template <class Fun, class... Args>
class work_item : public storable {
using result_t = std::invoke_result_t<Fun, Args...>;
public:
/// Creates a work item composed of a function and its arguments.
/// @param fun Function to be invoked
/// @param args Arguments to be applied to function
template <class T, class... Ts>
work_item(T&& fun, Ts&&... args)
: fun_{std::forward<T>(fun)}
, args_{std::forward_as_tuple(std::forward<Ts>(args)...)} {
// nop
}
/// @returns a future which is set when the function has been called.
std::future<result_t> future() { return ret_.get_future(); }
/// Invoke the stored function with stored arguments.
void operator()() override {
if constexpr (std::is_same_v<result_t, void>) {
std::apply(fun_, std::move(args_));
ret_.set_value();
} else {
auto res = std::apply(fun_, std::move(args_));
if constexpr (std::is_move_constructible_v<result_t>) {
ret_.set_value(std::move(res));
} else {
ret_.set_value(res);
}
}
}
private:
Fun fun_; /// Function to be invoked
std::tuple<Args...> args_; /// Arguments stored as tuple
std::promise<result_t> ret_; /// Response promise
};
} // namespace taski::detail
<|endoftext|>
|
<commit_before>#ifndef TWISTEDCPP_SOCKETS_HPP
#define TWISTEDCPP_SOCKETS_HPP
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/asio/spawn.hpp>
#include <iostream>
namespace twisted {
namespace detail {
class socket_base {
public:
virtual void do_handshake(boost::asio::yield_context) = 0;
virtual std::size_t async_read_some(boost::asio::mutable_buffers_1,
boost::asio::yield_context) = 0;
virtual void async_write(boost::asio::const_buffers_1,
boost::asio::yield_context) = 0;
virtual bool is_open() const = 0;
virtual void close() = 0;
virtual void async_write(std::array<boost::asio::const_buffer, 2>,
boost::asio::yield_context) = 0;
virtual boost::asio::io_service& get_io_service() = 0;
virtual ~socket_base() {}
};
class tcp_socket : public socket_base {
public:
tcp_socket(boost::asio::io_service& io_service) : _socket(io_service) {}
virtual void do_handshake(boost::asio::yield_context /* context */) {
// noop
}
virtual std::size_t async_read_some(boost::asio::mutable_buffers_1 buffers,
boost::asio::yield_context yield) {
return _socket.async_read_some(buffers, yield);
}
virtual void async_write(boost::asio::const_buffers_1 buffers,
boost::asio::yield_context yield) {
boost::asio::async_write(_socket, buffers, yield);
}
virtual void async_write(std::array<boost::asio::const_buffer, 2> buffers,
boost::asio::yield_context yield) {
boost::asio::async_write(_socket, buffers, yield);
}
virtual bool is_open() const { return _socket.is_open(); }
virtual void close() { _socket.close(); }
virtual boost::asio::io_service& get_io_service() {
return _socket.get_io_service();
}
boost::asio::ip::tcp::socket& lowest_layer() { return _socket; }
virtual ~tcp_socket() {}
private:
boost::asio::ip::tcp::socket _socket;
};
class ssl_socket : public socket_base {
public:
ssl_socket(boost::asio::io_service& io_service,
boost::asio::ssl::context& context)
: _socket(io_service, context) {}
virtual void do_handshake(boost::asio::yield_context yield) {
_socket.async_handshake(boost::asio::ssl::stream_base::server, yield);
}
virtual std::size_t async_read_some(boost::asio::mutable_buffers_1 buffers,
boost::asio::yield_context yield) {
return _socket.async_read_some(buffers, yield);
}
virtual void async_write(boost::asio::const_buffers_1 buffers,
boost::asio::yield_context yield) {
boost::asio::async_write(_socket, buffers, yield);
}
virtual void async_write(std::array<boost::asio::const_buffer, 2> buffers,
boost::asio::yield_context yield) {
boost::asio::async_write(_socket, buffers, yield);
}
virtual bool is_open() const { return _socket.lowest_layer().is_open(); }
virtual void close() { _socket.lowest_layer().close(); }
virtual boost::asio::io_service& get_io_service() {
return _socket.get_io_service();
}
boost::asio::ssl::stream<boost::asio::ip::tcp::socket>::lowest_layer_type&
lowest_layer() {
return _socket.lowest_layer();
}
virtual ~ssl_socket() {}
private:
boost::asio::ssl::stream<boost::asio::ip::tcp::socket> _socket;
};
} // namespace detail
} // namespace twisted
#endif
<commit_msg>added async_write overloads for mutable_buffers_1<commit_after>#ifndef TWISTEDCPP_SOCKETS_HPP
#define TWISTEDCPP_SOCKETS_HPP
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/asio/spawn.hpp>
#include <iostream>
namespace twisted {
namespace detail {
class socket_base {
public:
virtual void do_handshake(boost::asio::yield_context) = 0;
virtual std::size_t async_read_some(boost::asio::mutable_buffers_1,
boost::asio::yield_context) = 0;
virtual bool is_open() const = 0;
virtual void close() = 0;
virtual void async_write(boost::asio::const_buffers_1,
boost::asio::yield_context) = 0;
virtual void async_write(std::array<boost::asio::const_buffer, 2>,
boost::asio::yield_context) = 0;
virtual void async_write(boost::asio::mutable_buffers_1,
boost::asio::yield_context) = 0;
virtual void async_write(std::array<boost::asio::mutable_buffer, 2>,
boost::asio::yield_context) = 0;
virtual boost::asio::io_service& get_io_service() = 0;
virtual ~socket_base() {}
};
class tcp_socket : public socket_base {
public:
tcp_socket(boost::asio::io_service& io_service) : _socket(io_service) {}
virtual void do_handshake(boost::asio::yield_context /* context */) {
// noop
}
virtual std::size_t async_read_some(boost::asio::mutable_buffers_1 buffers,
boost::asio::yield_context yield) {
return _socket.async_read_some(buffers, yield);
}
virtual void async_write(boost::asio::const_buffers_1 buffers,
boost::asio::yield_context yield) {
boost::asio::async_write(_socket, buffers, yield);
}
virtual void async_write(std::array<boost::asio::const_buffer, 2> buffers,
boost::asio::yield_context yield) {
boost::asio::async_write(_socket, buffers, yield);
}
virtual void async_write(boost::asio::mutable_buffers_1 buffers,
boost::asio::yield_context yield) {
boost::asio::async_write(_socket, buffers, yield);
}
virtual void async_write(std::array<boost::asio::mutable_buffer, 2> buffers,
boost::asio::yield_context yield) {
boost::asio::async_write(_socket, buffers, yield);
}
virtual bool is_open() const { return _socket.is_open(); }
virtual void close() { _socket.close(); }
virtual boost::asio::io_service& get_io_service() {
return _socket.get_io_service();
}
boost::asio::ip::tcp::socket& lowest_layer() { return _socket; }
virtual ~tcp_socket() {}
private:
boost::asio::ip::tcp::socket _socket;
};
class ssl_socket : public socket_base {
public:
ssl_socket(boost::asio::io_service& io_service,
boost::asio::ssl::context& context)
: _socket(io_service, context) {}
virtual void do_handshake(boost::asio::yield_context yield) {
_socket.async_handshake(boost::asio::ssl::stream_base::server, yield);
}
virtual std::size_t async_read_some(boost::asio::mutable_buffers_1 buffers,
boost::asio::yield_context yield) {
return _socket.async_read_some(buffers, yield);
}
virtual void async_write(boost::asio::const_buffers_1 buffers,
boost::asio::yield_context yield) {
boost::asio::async_write(_socket, buffers, yield);
}
virtual void async_write(std::array<boost::asio::const_buffer, 2> buffers,
boost::asio::yield_context yield) {
boost::asio::async_write(_socket, buffers, yield);
}
virtual void async_write(boost::asio::mutable_buffers_1 buffers,
boost::asio::yield_context yield) {
boost::asio::async_write(_socket, buffers, yield);
}
virtual void async_write(std::array<boost::asio::mutable_buffer, 2> buffers,
boost::asio::yield_context yield) {
boost::asio::async_write(_socket, buffers, yield);
}
virtual bool is_open() const { return _socket.lowest_layer().is_open(); }
virtual void close() { _socket.lowest_layer().close(); }
virtual boost::asio::io_service& get_io_service() {
return _socket.get_io_service();
}
boost::asio::ssl::stream<boost::asio::ip::tcp::socket>::lowest_layer_type&
lowest_layer() {
return _socket.lowest_layer();
}
virtual ~ssl_socket() {}
private:
boost::asio::ssl::stream<boost::asio::ip::tcp::socket> _socket;
};
} // namespace detail
} // namespace twisted
#endif
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** 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.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/
#include "specificrules.h"
#include "highlightdefinition.h"
#include "keywordlist.h"
#include "progressdata.h"
#include "reuse.h"
#include <QtCore/QLatin1Char>
using namespace TextEditor;
using namespace Internal;
namespace {
void replaceByCaptures(QChar *c, const QStringList &captures)
{
int index = c->digitValue();
if (index > 0) {
const QString &capture = captures.at(index);
if (!capture.isEmpty())
*c = capture.at(0);
}
}
void replaceByCaptures(QString *s, const QStringList &captures)
{
static const QLatin1Char kPercent('%');
int index;
int from = 0;
while ((index = s->indexOf(kPercent, from)) != -1) {
from = index + 1;
QString accumulator;
while (from < s->length() && s->at(from).isDigit()) {
accumulator.append(s->at(from));
++from;
}
bool ok;
int number = accumulator.toInt(&ok);
Q_ASSERT(ok);
s->replace(index, accumulator.length() + 1, captures.at(number));
index = from;
}
}
}
// DetectChar
void DetectCharRule::setChar(const QString &character)
{ setStartCharacter(&m_char, character); }
void DetectCharRule::doReplaceExpressions(const QStringList &captures)
{ replaceByCaptures(&m_char, captures); }
bool DetectCharRule::doMatchSucceed(const QString &text,
const int length,
ProgressData *progress)
{
if (matchCharacter(text, length, progress, m_char)) {
// This is to make code folding have a control flow style look in the case of braces.
// Naturally, this assumes that language definitions use braces with this meaning.
if (m_char == kOpeningBrace && progress->isOnlySpacesSoFar() && !isLookAhead()) {
progress->setOpeningBraceMatchAtFirstNonSpace(true);
} else if (m_char == kClosingBrace &&
!text.right(length - progress->offset()).trimmed().isEmpty()) {
progress->setClosingBraceMatchAtNonEnd(true);
}
return true;
}
return false;
}
// Detect2Chars
void Detect2CharsRule::setChar(const QString &character)
{ setStartCharacter(&m_char, character); }
void Detect2CharsRule::setChar1(const QString &character)
{ setStartCharacter(&m_char1, character); }
void Detect2CharsRule::doReplaceExpressions(const QStringList &captures)
{
replaceByCaptures(&m_char, captures);
replaceByCaptures(&m_char1, captures);
}
bool Detect2CharsRule::doMatchSucceed(const QString &text,
const int length,
ProgressData *progress)
{
if (matchCharacter(text, length, progress, m_char)) {
if (progress->offset() < length && matchCharacter(text, length, progress, m_char1, false))
return true;
else
progress->restoreOffset();
}
return false;
}
// AnyChar
void AnyCharRule::setCharacterSet(const QString &s)
{ m_characterSet = s; }
bool AnyCharRule::doMatchSucceed(const QString &text,
const int length,
ProgressData *progress)
{
Q_UNUSED(length)
if (m_characterSet.contains(text.at(progress->offset()))) {
progress->incrementOffset();
return true;
}
return false;
}
// StringDetect
void StringDetectRule::setString(const QString &s)
{
m_string = s;
m_length = m_string.length();
}
void StringDetectRule::setInsensitive(const QString &insensitive)
{ m_caseSensitivity = toCaseSensitivity(!toBool(insensitive)); }
void StringDetectRule::doReplaceExpressions(const QStringList &captures)
{
replaceByCaptures(&m_string, captures);
m_length = m_string.length();
}
bool StringDetectRule::doMatchSucceed(const QString &text,
const int length,
ProgressData *progress)
{
if (length - progress->offset() >= m_length) {
QString candidate = text.fromRawData(text.unicode() + progress->offset(), m_length);
if (candidate.compare(m_string, m_caseSensitivity) == 0) {
progress->incrementOffset(m_length);
return true;
}
}
return false;
}
// RegExpr
void RegExprRule::setPattern(const QString &pattern)
{
if (pattern.startsWith(QLatin1Char('^')))
m_onlyBegin = true;
m_expression.setPattern(pattern);
}
void RegExprRule::setInsensitive(const QString &insensitive)
{ m_expression.setCaseSensitivity(toCaseSensitivity(!toBool(insensitive))); }
void RegExprRule::setMinimal(const QString &minimal)
{ m_expression.setMinimal(toBool(minimal)); }
void RegExprRule::doReplaceExpressions(const QStringList &captures)
{
QString s = m_expression.pattern();
replaceByCaptures(&s, captures);
m_expression.setPattern(s);
}
void RegExprRule::doProgressFinished()
{
m_isCached = false;
}
bool RegExprRule::isExactMatch(ProgressData *progress)
{
if (progress->offset() == m_offset && m_length > 0) {
progress->incrementOffset(m_length);
progress->setCaptures(m_captures);
return true;
}
return false;
}
bool RegExprRule::doMatchSucceed(const QString &text,
const int length,
ProgressData *progress)
{
Q_UNUSED(length)
// A regular expression match is considered valid if it happens at the current position
// and if the match length is not zero.
const int offset = progress->offset();
if (offset > 0 && m_onlyBegin)
return false;
if (m_isCached) {
if (offset < m_offset || m_offset == -1 || m_length == 0)
return false;
if (isExactMatch(progress))
return true;
}
m_offset = m_expression.indexIn(text, offset, QRegExp::CaretAtOffset);
m_length = m_expression.matchedLength();
m_captures = m_expression.capturedTexts();
if (isExactMatch(progress))
return true;
m_isCached = true;
progress->trackRule(this);
return false;
}
// Keyword
KeywordRule::KeywordRule(const QSharedPointer<HighlightDefinition> &definition) :
m_overrideGlobal(false),
m_localCaseSensitivity(Qt::CaseSensitive)
{
setDefinition(definition);
}
KeywordRule::~KeywordRule()
{}
void KeywordRule::setInsensitive(const QString &insensitive)
{
if (!insensitive.isEmpty()) {
m_overrideGlobal = true;
m_localCaseSensitivity = toCaseSensitivity(!toBool(insensitive));
}
}
void KeywordRule::setList(const QString &listName)
{ m_list = definition()->keywordList(listName); }
bool KeywordRule::doMatchSucceed(const QString &text,
const int length,
ProgressData *progress)
{
int current = progress->offset();
if (current > 0 && !definition()->isDelimiter(text.at(current - 1)))
return false;
if (definition()->isDelimiter(text.at(current)))
return false;
while (current < length && !definition()->isDelimiter(text.at(current)))
++current;
QString candidate =
QString::fromRawData(text.unicode() + progress->offset(), current - progress->offset());
if ((m_overrideGlobal && m_list->isKeyword(candidate, m_localCaseSensitivity)) ||
(!m_overrideGlobal && m_list->isKeyword(candidate, definition()->keywordsSensitive()))) {
progress->setOffset(current);
return true;
}
return false;
}
// Int
bool IntRule::doMatchSucceed(const QString &text,
const int length,
ProgressData *progress)
{
const int offset = progress->offset();
// This is necessary to correctly highlight an invalid octal like 09, for example.
if (offset > 0 && text.at(offset - 1).isDigit())
return false;
if (text.at(offset).isDigit() && text.at(offset) != kZero) {
progress->incrementOffset();
charPredicateMatchSucceed(text, length, progress, &QChar::isDigit);
return true;
}
return false;
}
// Float
bool FloatRule::doMatchSucceed(const QString &text, const int length, ProgressData *progress)
{
progress->saveOffset();
bool integralPart = charPredicateMatchSucceed(text, length, progress, &QChar::isDigit);
bool decimalPoint = false;
if (progress->offset() < length && text.at(progress->offset()) == kDot) {
progress->incrementOffset();
decimalPoint = true;
}
bool fractionalPart = charPredicateMatchSucceed(text, length, progress, &QChar::isDigit);
bool exponentialPart = false;
int offset = progress->offset();
if (offset < length && (text.at(offset) == kE || text.at(offset).toLower() == kE)) {
progress->incrementOffset();
offset = progress->offset();
if (offset < length && (text.at(offset) == kPlus || text.at(offset) == kMinus))
progress->incrementOffset();
if (charPredicateMatchSucceed(text, length, progress, &QChar::isDigit)) {
exponentialPart = true;
} else {
progress->restoreOffset();
return false;
}
}
if ((integralPart || fractionalPart) && (decimalPoint || exponentialPart))
return true;
progress->restoreOffset();
return false;
}
// COctal
bool HlCOctRule::doMatchSucceed(const QString &text,
const int length,
ProgressData *progress)
{
if (matchCharacter(text, length, progress, kZero)) {
// In the definition files the number matching rules which are more restrictive should
// appear before the rules which are least resctritive. Although this happens in general
// there is at least one case where this is not strictly followed for existent definition
// files (specifically, HlCHex comes before HlCOct). So the condition below.
const int offset = progress->offset();
if (offset < length && (text.at(offset) == kX || text.at(offset).toLower() == kX)) {
progress->restoreOffset();
return false;
}
charPredicateMatchSucceed(text, length, progress, &isOctalDigit);
return true;
}
return false;
}
// CHex
bool HlCHexRule::doMatchSucceed(const QString &text,
const int length,
ProgressData *progress)
{
if (matchCharacter(text, length, progress, kZero)) {
const int offset = progress->offset();
if (offset < length && text.at(offset) != kX && text.at(offset).toLower() != kX) {
progress->restoreOffset();
return false;
}
progress->incrementOffset();
if (charPredicateMatchSucceed(text, length, progress, &isHexDigit))
return true;
else
progress->restoreOffset();
}
return false;
}
// CString
bool HlCStringCharRule::doMatchSucceed(const QString &text,
const int length,
ProgressData *progress)
{
if (matchEscapeSequence(text, length, progress))
return true;
if (matchOctalSequence(text, length, progress))
return true;
if (matchHexSequence(text, length, progress))
return true;
return false;
}
// CChar
bool HlCCharRule::doMatchSucceed(const QString &text,
const int length,
ProgressData *progress)
{
if (matchCharacter(text, length, progress, kSingleQuote)) {
if (progress->offset() < length) {
if (text.at(progress->offset()) != kBackSlash &&
text.at(progress->offset()) != kSingleQuote) {
progress->incrementOffset();
} else if (!matchEscapeSequence(text, length, progress, false)) {
progress->restoreOffset();
return false;
}
if (progress->offset() < length &&
matchCharacter(text, length, progress, kSingleQuote, false)) {
return true;
} else {
progress->restoreOffset();
}
} else {
progress->restoreOffset();
}
}
return false;
}
// RangeDetect
void RangeDetectRule::setChar(const QString &character)
{ setStartCharacter(&m_char, character); }
void RangeDetectRule::setChar1(const QString &character)
{ setStartCharacter(&m_char1, character); }
bool RangeDetectRule::doMatchSucceed(const QString &text,
const int length,
ProgressData *progress)
{
if (matchCharacter(text, length, progress, m_char)) {
while (progress->offset() < length) {
if (matchCharacter(text, length, progress, m_char1, false))
return true;
progress->incrementOffset();
}
progress->restoreOffset();
}
return false;
}
// LineContinue
bool LineContinueRule::doMatchSucceed(const QString &text,
const int length,
ProgressData *progress)
{
if (progress->offset() != length - 1)
return false;
if (text.at(progress->offset()) == kBackSlash) {
progress->incrementOffset();
progress->setWillContinueLine(true);
return true;
}
return false;
}
// DetectSpaces
DetectSpacesRule::DetectSpacesRule() : Rule(false)
{}
bool DetectSpacesRule::doMatchSucceed(const QString &text,
const int length,
ProgressData *progress)
{
return charPredicateMatchSucceed(text, length, progress, &QChar::isSpace);
}
// DetectIdentifier
bool DetectIdentifierRule::doMatchSucceed(const QString &text,
const int length,
ProgressData *progress)
{
// Identifiers are characterized by a letter or underscore as the first character and then
// zero or more word characters (\w*).
if (text.at(progress->offset()).isLetter() || text.at(progress->offset()) == kUnderscore) {
progress->incrementOffset();
while (progress->offset() < length) {
const QChar ¤t = text.at(progress->offset());
if (current.isLetterOrNumber() || current.isMark() || current == kUnderscore)
progress->incrementOffset();
else
break;
}
return true;
}
return false;
}
<commit_msg>Removed dead assignment<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** 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.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/
#include "specificrules.h"
#include "highlightdefinition.h"
#include "keywordlist.h"
#include "progressdata.h"
#include "reuse.h"
#include <QtCore/QLatin1Char>
using namespace TextEditor;
using namespace Internal;
namespace {
void replaceByCaptures(QChar *c, const QStringList &captures)
{
int index = c->digitValue();
if (index > 0) {
const QString &capture = captures.at(index);
if (!capture.isEmpty())
*c = capture.at(0);
}
}
void replaceByCaptures(QString *s, const QStringList &captures)
{
static const QLatin1Char kPercent('%');
int index;
int from = 0;
while ((index = s->indexOf(kPercent, from)) != -1) {
from = index + 1;
QString accumulator;
while (from < s->length() && s->at(from).isDigit()) {
accumulator.append(s->at(from));
++from;
}
bool ok;
int number = accumulator.toInt(&ok);
Q_ASSERT(ok);
s->replace(index, accumulator.length() + 1, captures.at(number));
}
}
}
// DetectChar
void DetectCharRule::setChar(const QString &character)
{ setStartCharacter(&m_char, character); }
void DetectCharRule::doReplaceExpressions(const QStringList &captures)
{ replaceByCaptures(&m_char, captures); }
bool DetectCharRule::doMatchSucceed(const QString &text,
const int length,
ProgressData *progress)
{
if (matchCharacter(text, length, progress, m_char)) {
// This is to make code folding have a control flow style look in the case of braces.
// Naturally, this assumes that language definitions use braces with this meaning.
if (m_char == kOpeningBrace && progress->isOnlySpacesSoFar() && !isLookAhead()) {
progress->setOpeningBraceMatchAtFirstNonSpace(true);
} else if (m_char == kClosingBrace &&
!text.right(length - progress->offset()).trimmed().isEmpty()) {
progress->setClosingBraceMatchAtNonEnd(true);
}
return true;
}
return false;
}
// Detect2Chars
void Detect2CharsRule::setChar(const QString &character)
{ setStartCharacter(&m_char, character); }
void Detect2CharsRule::setChar1(const QString &character)
{ setStartCharacter(&m_char1, character); }
void Detect2CharsRule::doReplaceExpressions(const QStringList &captures)
{
replaceByCaptures(&m_char, captures);
replaceByCaptures(&m_char1, captures);
}
bool Detect2CharsRule::doMatchSucceed(const QString &text,
const int length,
ProgressData *progress)
{
if (matchCharacter(text, length, progress, m_char)) {
if (progress->offset() < length && matchCharacter(text, length, progress, m_char1, false))
return true;
else
progress->restoreOffset();
}
return false;
}
// AnyChar
void AnyCharRule::setCharacterSet(const QString &s)
{ m_characterSet = s; }
bool AnyCharRule::doMatchSucceed(const QString &text,
const int length,
ProgressData *progress)
{
Q_UNUSED(length)
if (m_characterSet.contains(text.at(progress->offset()))) {
progress->incrementOffset();
return true;
}
return false;
}
// StringDetect
void StringDetectRule::setString(const QString &s)
{
m_string = s;
m_length = m_string.length();
}
void StringDetectRule::setInsensitive(const QString &insensitive)
{ m_caseSensitivity = toCaseSensitivity(!toBool(insensitive)); }
void StringDetectRule::doReplaceExpressions(const QStringList &captures)
{
replaceByCaptures(&m_string, captures);
m_length = m_string.length();
}
bool StringDetectRule::doMatchSucceed(const QString &text,
const int length,
ProgressData *progress)
{
if (length - progress->offset() >= m_length) {
QString candidate = text.fromRawData(text.unicode() + progress->offset(), m_length);
if (candidate.compare(m_string, m_caseSensitivity) == 0) {
progress->incrementOffset(m_length);
return true;
}
}
return false;
}
// RegExpr
void RegExprRule::setPattern(const QString &pattern)
{
if (pattern.startsWith(QLatin1Char('^')))
m_onlyBegin = true;
m_expression.setPattern(pattern);
}
void RegExprRule::setInsensitive(const QString &insensitive)
{ m_expression.setCaseSensitivity(toCaseSensitivity(!toBool(insensitive))); }
void RegExprRule::setMinimal(const QString &minimal)
{ m_expression.setMinimal(toBool(minimal)); }
void RegExprRule::doReplaceExpressions(const QStringList &captures)
{
QString s = m_expression.pattern();
replaceByCaptures(&s, captures);
m_expression.setPattern(s);
}
void RegExprRule::doProgressFinished()
{
m_isCached = false;
}
bool RegExprRule::isExactMatch(ProgressData *progress)
{
if (progress->offset() == m_offset && m_length > 0) {
progress->incrementOffset(m_length);
progress->setCaptures(m_captures);
return true;
}
return false;
}
bool RegExprRule::doMatchSucceed(const QString &text,
const int length,
ProgressData *progress)
{
Q_UNUSED(length)
// A regular expression match is considered valid if it happens at the current position
// and if the match length is not zero.
const int offset = progress->offset();
if (offset > 0 && m_onlyBegin)
return false;
if (m_isCached) {
if (offset < m_offset || m_offset == -1 || m_length == 0)
return false;
if (isExactMatch(progress))
return true;
}
m_offset = m_expression.indexIn(text, offset, QRegExp::CaretAtOffset);
m_length = m_expression.matchedLength();
m_captures = m_expression.capturedTexts();
if (isExactMatch(progress))
return true;
m_isCached = true;
progress->trackRule(this);
return false;
}
// Keyword
KeywordRule::KeywordRule(const QSharedPointer<HighlightDefinition> &definition) :
m_overrideGlobal(false),
m_localCaseSensitivity(Qt::CaseSensitive)
{
setDefinition(definition);
}
KeywordRule::~KeywordRule()
{}
void KeywordRule::setInsensitive(const QString &insensitive)
{
if (!insensitive.isEmpty()) {
m_overrideGlobal = true;
m_localCaseSensitivity = toCaseSensitivity(!toBool(insensitive));
}
}
void KeywordRule::setList(const QString &listName)
{ m_list = definition()->keywordList(listName); }
bool KeywordRule::doMatchSucceed(const QString &text,
const int length,
ProgressData *progress)
{
int current = progress->offset();
if (current > 0 && !definition()->isDelimiter(text.at(current - 1)))
return false;
if (definition()->isDelimiter(text.at(current)))
return false;
while (current < length && !definition()->isDelimiter(text.at(current)))
++current;
QString candidate =
QString::fromRawData(text.unicode() + progress->offset(), current - progress->offset());
if ((m_overrideGlobal && m_list->isKeyword(candidate, m_localCaseSensitivity)) ||
(!m_overrideGlobal && m_list->isKeyword(candidate, definition()->keywordsSensitive()))) {
progress->setOffset(current);
return true;
}
return false;
}
// Int
bool IntRule::doMatchSucceed(const QString &text,
const int length,
ProgressData *progress)
{
const int offset = progress->offset();
// This is necessary to correctly highlight an invalid octal like 09, for example.
if (offset > 0 && text.at(offset - 1).isDigit())
return false;
if (text.at(offset).isDigit() && text.at(offset) != kZero) {
progress->incrementOffset();
charPredicateMatchSucceed(text, length, progress, &QChar::isDigit);
return true;
}
return false;
}
// Float
bool FloatRule::doMatchSucceed(const QString &text, const int length, ProgressData *progress)
{
progress->saveOffset();
bool integralPart = charPredicateMatchSucceed(text, length, progress, &QChar::isDigit);
bool decimalPoint = false;
if (progress->offset() < length && text.at(progress->offset()) == kDot) {
progress->incrementOffset();
decimalPoint = true;
}
bool fractionalPart = charPredicateMatchSucceed(text, length, progress, &QChar::isDigit);
bool exponentialPart = false;
int offset = progress->offset();
if (offset < length && (text.at(offset) == kE || text.at(offset).toLower() == kE)) {
progress->incrementOffset();
offset = progress->offset();
if (offset < length && (text.at(offset) == kPlus || text.at(offset) == kMinus))
progress->incrementOffset();
if (charPredicateMatchSucceed(text, length, progress, &QChar::isDigit)) {
exponentialPart = true;
} else {
progress->restoreOffset();
return false;
}
}
if ((integralPart || fractionalPart) && (decimalPoint || exponentialPart))
return true;
progress->restoreOffset();
return false;
}
// COctal
bool HlCOctRule::doMatchSucceed(const QString &text,
const int length,
ProgressData *progress)
{
if (matchCharacter(text, length, progress, kZero)) {
// In the definition files the number matching rules which are more restrictive should
// appear before the rules which are least resctritive. Although this happens in general
// there is at least one case where this is not strictly followed for existent definition
// files (specifically, HlCHex comes before HlCOct). So the condition below.
const int offset = progress->offset();
if (offset < length && (text.at(offset) == kX || text.at(offset).toLower() == kX)) {
progress->restoreOffset();
return false;
}
charPredicateMatchSucceed(text, length, progress, &isOctalDigit);
return true;
}
return false;
}
// CHex
bool HlCHexRule::doMatchSucceed(const QString &text,
const int length,
ProgressData *progress)
{
if (matchCharacter(text, length, progress, kZero)) {
const int offset = progress->offset();
if (offset < length && text.at(offset) != kX && text.at(offset).toLower() != kX) {
progress->restoreOffset();
return false;
}
progress->incrementOffset();
if (charPredicateMatchSucceed(text, length, progress, &isHexDigit))
return true;
else
progress->restoreOffset();
}
return false;
}
// CString
bool HlCStringCharRule::doMatchSucceed(const QString &text,
const int length,
ProgressData *progress)
{
if (matchEscapeSequence(text, length, progress))
return true;
if (matchOctalSequence(text, length, progress))
return true;
if (matchHexSequence(text, length, progress))
return true;
return false;
}
// CChar
bool HlCCharRule::doMatchSucceed(const QString &text,
const int length,
ProgressData *progress)
{
if (matchCharacter(text, length, progress, kSingleQuote)) {
if (progress->offset() < length) {
if (text.at(progress->offset()) != kBackSlash &&
text.at(progress->offset()) != kSingleQuote) {
progress->incrementOffset();
} else if (!matchEscapeSequence(text, length, progress, false)) {
progress->restoreOffset();
return false;
}
if (progress->offset() < length &&
matchCharacter(text, length, progress, kSingleQuote, false)) {
return true;
} else {
progress->restoreOffset();
}
} else {
progress->restoreOffset();
}
}
return false;
}
// RangeDetect
void RangeDetectRule::setChar(const QString &character)
{ setStartCharacter(&m_char, character); }
void RangeDetectRule::setChar1(const QString &character)
{ setStartCharacter(&m_char1, character); }
bool RangeDetectRule::doMatchSucceed(const QString &text,
const int length,
ProgressData *progress)
{
if (matchCharacter(text, length, progress, m_char)) {
while (progress->offset() < length) {
if (matchCharacter(text, length, progress, m_char1, false))
return true;
progress->incrementOffset();
}
progress->restoreOffset();
}
return false;
}
// LineContinue
bool LineContinueRule::doMatchSucceed(const QString &text,
const int length,
ProgressData *progress)
{
if (progress->offset() != length - 1)
return false;
if (text.at(progress->offset()) == kBackSlash) {
progress->incrementOffset();
progress->setWillContinueLine(true);
return true;
}
return false;
}
// DetectSpaces
DetectSpacesRule::DetectSpacesRule() : Rule(false)
{}
bool DetectSpacesRule::doMatchSucceed(const QString &text,
const int length,
ProgressData *progress)
{
return charPredicateMatchSucceed(text, length, progress, &QChar::isSpace);
}
// DetectIdentifier
bool DetectIdentifierRule::doMatchSucceed(const QString &text,
const int length,
ProgressData *progress)
{
// Identifiers are characterized by a letter or underscore as the first character and then
// zero or more word characters (\w*).
if (text.at(progress->offset()).isLetter() || text.at(progress->offset()) == kUnderscore) {
progress->incrementOffset();
while (progress->offset() < length) {
const QChar ¤t = text.at(progress->offset());
if (current.isLetterOrNumber() || current.isMark() || current == kUnderscore)
progress->incrementOffset();
else
break;
}
return true;
}
return false;
}
<|endoftext|>
|
<commit_before>#include <BALL/KERNEL/system.h>
#include <BALL/DATATYPE/string.h>
#include <BALL/FORMAT/PDBFile.h>
#include <BALL/FORMAT/DCDFile.h>
#include <BALL/MOLMEC/COMMON/snapShot.h>
using namespace BALL;
using namespace std;
int main(int argc, char** argv)
{
String filename;
SnapShot snapshot;
DCDFile dcd_file("out.dcd", ios::out | ios::binary);
for (int i = 1; i < argc; ++i)
{
filename = argv[i];
Log.info() << "Reading file " << filename;
PDBFile file(filename);
System system;
file >> system;
file.close();
Size res_count = system.countResidues();
Log.info() << " containing " << res_count << " residues." << endl;
snapshot.takeSnapShot(system);
dcd_file.append(snapshot);
}
// dcd_file.flushToDisk();
dcd_file.close();
}
<commit_msg>added little header<commit_after>// $Id: pdb2dcd.C,v 1.2 2003/11/11 09:15:09 anker Exp $
//
// A very simple utility for combining several pdb snapshots of a system
// into one dcd file
#include <BALL/KERNEL/system.h>
#include <BALL/DATATYPE/string.h>
#include <BALL/FORMAT/PDBFile.h>
#include <BALL/FORMAT/DCDFile.h>
#include <BALL/MOLMEC/COMMON/snapShot.h>
using namespace BALL;
using namespace std;
int main(int argc, char** argv)
{
String filename;
SnapShot snapshot;
DCDFile dcd_file("out.dcd", ios::out | ios::binary);
for (int i = 1; i < argc; ++i)
{
filename = argv[i];
Log.info() << "Reading file " << filename;
PDBFile file(filename);
System system;
file >> system;
file.close();
Size res_count = system.countResidues();
Log.info() << " containing " << res_count << " residues." << endl;
snapshot.takeSnapShot(system);
dcd_file.append(snapshot);
}
// dcd_file.flushToDisk();
dcd_file.close();
}
<|endoftext|>
|
<commit_before>/**************************************************************************
** This file is part of LiteIDE
**
** Copyright (c) 2011-2014 LiteIDE Team. All rights reserved.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** Lesser General Public License for more details.
**
** In addition, as a special exception, that plugins developed for LiteIDE,
** are allowed to remain closed sourced and can be distributed under any license .
** These rights are included in the file LGPL_EXCEPTION.txt in this package.
**
**************************************************************************/
// Module: processex.cpp
// Creator: visualfc <visualfc@gmail.com>
#include "processex.h"
#include <QMap>
#ifdef Q_OS_WIN
#include <windows.h>
//lite_memory_check_begin
#if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG)
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )
#define new DEBUG_NEW
#endif
//lite_memory_check_end
#endif
QString ProcessEx::exitStatusText(int code, QProcess::ExitStatus status)
{
static QString text;
switch (status) {
case QProcess::NormalExit:
text = tr("process exited with code %1").arg(code);
break;
case QProcess::CrashExit:
text = tr("process crashed or was terminated");
break;
default:
text = tr("process exited with an unknown status");
}
return text;
}
QString ProcessEx::processErrorText(QProcess::ProcessError code)
{
static QString text;
switch (code) {
case QProcess::FailedToStart:
text = tr("process failed to start");
break;
case QProcess::Crashed:
text = tr("process crashed or was terminated while running");
break;
case QProcess::Timedout:
text = tr("timed out waiting for process");
break;
case QProcess::ReadError:
text = tr("couldn't read from the process");
break;
case QProcess::WriteError:
text = tr("couldn't write to the process");
break;
case QProcess::UnknownError:
default:
text = tr("an unknown error occurred");
}
return text;
}
ProcessEx::ProcessEx(QObject *parent)
: QProcess(parent), m_suppressFinish(false)
{
connect(this,SIGNAL(stateChanged(QProcess::ProcessState)),this,SLOT(slotStateChanged(QProcess::ProcessState)));
connect(this,SIGNAL(readyReadStandardOutput()),this,SLOT(slotReadOutput()));
connect(this,SIGNAL(readyReadStandardError()),this,SLOT(slotReadError()));
connect(this,SIGNAL(error(QProcess::ProcessError)),this,SLOT(slotError(QProcess::ProcessError)));
connect(this,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(slotFinished(int,QProcess::ExitStatus)));
}
ProcessEx::~ProcessEx()
{
if (isRunning()) {
this->kill();
}
}
bool ProcessEx::isRunning() const
{
return this->state() == QProcess::Running;
}
void ProcessEx::setUserData(int id, const QVariant &data)
{
m_idVarMap.insert(id,data);
}
QVariant ProcessEx::userData(int id) const
{
return m_idVarMap.value(id);
}
void ProcessEx::slotStateChanged(QProcess::ProcessState newState)
{
if (newState == QProcess::Starting) {
m_suppressFinish = false;
}
}
void ProcessEx::slotError(QProcess::ProcessError error)
{
switch (error) {
// Suppress only if the process has stopped
default:
case QProcess::UnknownError:
if (this->isRunning()) break;
// Fall through
// Always suppress
case QProcess::FailedToStart:
case QProcess::Crashed:
m_suppressFinish = true;
emit extFinish(true,-1,this->processErrorText(error));
break;
// Never suppress
case QProcess::Timedout:
case QProcess::WriteError:
case QProcess::ReadError:
break;
}
}
void ProcessEx::slotFinished(int code,QProcess::ExitStatus status)
{
if (!m_suppressFinish) {
emit extFinish(false,code,this->exitStatusText(code,status));
}
}
void ProcessEx::slotReadOutput()
{
emit extOutput(this->readAllStandardOutput(),false);
}
void ProcessEx::slotReadError()
{
emit extOutput(this->readAllStandardError(),true);
}
void ProcessEx::startEx(const QString &cmd, const QString &args)
{
#ifdef Q_OS_WIN
this->setNativeArguments(args);
if (cmd.indexOf(" ")) {
this->start("\""+cmd+"\"");
} else {
this->start(cmd);
}
#else
this->start(cmd+" "+args);
#endif
}
bool ProcessEx::startDetachedEx(const QString& cmd, const QStringList &args)
{
#ifdef Q_OS_WIN
return (int)ShellExecuteW(NULL, NULL, (LPCWSTR)cmd.toStdWString().data(), (LPCWSTR)args.join(" ").toStdWString().data(), NULL, SW_HIDE) > 32;
#else
return QProcess::startDetached(cmd, args);
#endif
}
<commit_msg>(*)fixed build error on x64 Windows<commit_after>/**************************************************************************
** This file is part of LiteIDE
**
** Copyright (c) 2011-2014 LiteIDE Team. All rights reserved.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** Lesser General Public License for more details.
**
** In addition, as a special exception, that plugins developed for LiteIDE,
** are allowed to remain closed sourced and can be distributed under any license .
** These rights are included in the file LGPL_EXCEPTION.txt in this package.
**
**************************************************************************/
// Module: processex.cpp
// Creator: visualfc <visualfc@gmail.com>
#include "processex.h"
#include <QMap>
#ifdef Q_OS_WIN
#include <windows.h>
//lite_memory_check_begin
#if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG)
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )
#define new DEBUG_NEW
#endif
//lite_memory_check_end
#endif
QString ProcessEx::exitStatusText(int code, QProcess::ExitStatus status)
{
static QString text;
switch (status) {
case QProcess::NormalExit:
text = tr("process exited with code %1").arg(code);
break;
case QProcess::CrashExit:
text = tr("process crashed or was terminated");
break;
default:
text = tr("process exited with an unknown status");
}
return text;
}
QString ProcessEx::processErrorText(QProcess::ProcessError code)
{
static QString text;
switch (code) {
case QProcess::FailedToStart:
text = tr("process failed to start");
break;
case QProcess::Crashed:
text = tr("process crashed or was terminated while running");
break;
case QProcess::Timedout:
text = tr("timed out waiting for process");
break;
case QProcess::ReadError:
text = tr("couldn't read from the process");
break;
case QProcess::WriteError:
text = tr("couldn't write to the process");
break;
case QProcess::UnknownError:
default:
text = tr("an unknown error occurred");
}
return text;
}
ProcessEx::ProcessEx(QObject *parent)
: QProcess(parent), m_suppressFinish(false)
{
connect(this,SIGNAL(stateChanged(QProcess::ProcessState)),this,SLOT(slotStateChanged(QProcess::ProcessState)));
connect(this,SIGNAL(readyReadStandardOutput()),this,SLOT(slotReadOutput()));
connect(this,SIGNAL(readyReadStandardError()),this,SLOT(slotReadError()));
connect(this,SIGNAL(error(QProcess::ProcessError)),this,SLOT(slotError(QProcess::ProcessError)));
connect(this,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(slotFinished(int,QProcess::ExitStatus)));
}
ProcessEx::~ProcessEx()
{
if (isRunning()) {
this->kill();
}
}
bool ProcessEx::isRunning() const
{
return this->state() == QProcess::Running;
}
void ProcessEx::setUserData(int id, const QVariant &data)
{
m_idVarMap.insert(id,data);
}
QVariant ProcessEx::userData(int id) const
{
return m_idVarMap.value(id);
}
void ProcessEx::slotStateChanged(QProcess::ProcessState newState)
{
if (newState == QProcess::Starting) {
m_suppressFinish = false;
}
}
void ProcessEx::slotError(QProcess::ProcessError error)
{
switch (error) {
// Suppress only if the process has stopped
default:
case QProcess::UnknownError:
if (this->isRunning()) break;
// Fall through
// Always suppress
case QProcess::FailedToStart:
case QProcess::Crashed:
m_suppressFinish = true;
emit extFinish(true,-1,this->processErrorText(error));
break;
// Never suppress
case QProcess::Timedout:
case QProcess::WriteError:
case QProcess::ReadError:
break;
}
}
void ProcessEx::slotFinished(int code,QProcess::ExitStatus status)
{
if (!m_suppressFinish) {
emit extFinish(false,code,this->exitStatusText(code,status));
}
}
void ProcessEx::slotReadOutput()
{
emit extOutput(this->readAllStandardOutput(),false);
}
void ProcessEx::slotReadError()
{
emit extOutput(this->readAllStandardError(),true);
}
void ProcessEx::startEx(const QString &cmd, const QString &args)
{
#ifdef Q_OS_WIN
this->setNativeArguments(args);
if (cmd.indexOf(" ")) {
this->start("\""+cmd+"\"");
} else {
this->start(cmd);
}
#else
this->start(cmd+" "+args);
#endif
}
bool ProcessEx::startDetachedEx(const QString& cmd, const QStringList &args)
{
#ifdef Q_OS_WIN
return (intptr_t)ShellExecuteW(NULL, NULL, (LPCWSTR)cmd.toStdWString().data(), (LPCWSTR)args.join(" ").toStdWString().data(), NULL, SW_HIDE) > 32;
#else
return QProcess::startDetached(cmd, args);
#endif
}
<|endoftext|>
|
<commit_before>
#include <gloperate/base/Canvas.h>
#include <cppassist/logging/logging.h>
#include <cppassist/memory/make_unique.h>
#include <globjects/Framebuffer.h>
#include <gloperate/base/Environment.h>
#include <gloperate/base/TimeManager.h>
#include <gloperate/pipeline/Stage.h>
#include <gloperate/input/MouseDevice.h>
#include <gloperate/input/KeyboardDevice.h>
using namespace cppassist;
namespace gloperate
{
Canvas::Canvas(Environment * environment)
: AbstractCanvas(environment)
, m_pipelineContainer(environment)
, m_frame(0)
, m_mouseDevice(cppassist::make_unique<MouseDevice>(m_environment->inputManager(), m_name))
, m_keyboardDevice(cppassist::make_unique<KeyboardDevice>(m_environment->inputManager(), m_name))
{
// Mark render output as required and redraw when it is invalidated
m_pipelineContainer.rendered.setRequired(true);
m_pipelineContainer.rendered.valueChanged.connect([this] (bool)
{
if (!m_pipelineContainer.rendered.isValid()) {
this->redraw();
}
});
addProperty(&m_pipelineContainer);
}
Canvas::~Canvas()
{
}
const PipelineContainer * Canvas::pipelineContainer() const
{
return &m_pipelineContainer;
}
PipelineContainer * Canvas::pipelineContainer()
{
return &m_pipelineContainer;
}
const Stage * Canvas::renderStage() const
{
return m_pipelineContainer.renderStage();
}
Stage * Canvas::renderStage()
{
return m_pipelineContainer.renderStage();
}
void Canvas::setRenderStage(std::unique_ptr<Stage> && stage)
{
// De-initialize render stage
if (m_pipelineContainer.renderStage() && m_openGLContext)
{
m_pipelineContainer.renderStage()->deinitContext(m_openGLContext);
}
// Set new render stage
m_pipelineContainer.setRenderStage(std::move(stage));
// Initialize new render stage
if (m_pipelineContainer.renderStage() && m_openGLContext)
{
m_pipelineContainer.renderStage()->initContext(m_openGLContext);
}
}
void Canvas::onRender(globjects::Framebuffer * targetFBO)
{
if(cppassist::verbosityLevel() < 3)
cppassist::debug(2, "gloperate") << "onRender()";
else
{
auto fboName = targetFBO->hasName() ? targetFBO->name() : std::to_string(targetFBO->id());
cppassist::debug(3, "gloperate") << "onRender(); " << "targetFBO: " << fboName;
}
// Invoke render stage/pipeline
if (m_pipelineContainer.renderStage())
{
m_frame++;
m_pipelineContainer.frameCounter.setValue(m_frame);
m_pipelineContainer.targetFBO.setValue(targetFBO);
m_pipelineContainer.renderStage()->process(m_openGLContext);
}
}
void Canvas::onUpdate()
{
float timeDelta = m_environment->timeManager()->timeDelta();
m_pipelineContainer.timeDelta.setValue(timeDelta);
}
void Canvas::onContextInit()
{
cppassist::debug(2, "gloperate") << "onContextInit()";
// Initialize render stage in new context
if (m_pipelineContainer.renderStage())
{
m_pipelineContainer.renderStage()->initContext(m_openGLContext);
}
}
void Canvas::onContextDeinit()
{
cppassist::debug(2, "gloperate") << "onContextDeinit()";
// De-initialize render stage in old context
if (m_pipelineContainer.renderStage())
{
m_pipelineContainer.renderStage()->deinitContext(m_openGLContext);
}
}
void Canvas::onViewport(const glm::vec4 & deviceViewport, const glm::vec4 & virtualViewport)
{
m_deviceViewport = deviceViewport;
m_virtualViewport = virtualViewport;
m_pipelineContainer.deviceViewport.setValue(deviceViewport);
m_pipelineContainer.virtualViewport.setValue(virtualViewport);
}
void Canvas::onSaveViewport()
{
m_savedDeviceVP = m_deviceViewport;
m_savedVirtualVP = m_virtualViewport;
}
void Canvas::onResetViewport()
{
onViewport(m_savedDeviceVP, m_savedVirtualVP);
}
void Canvas::onBackgroundColor(float red, float green, float blue)
{
m_pipelineContainer.backgroundColor.setValue(glm::vec3(red, green, blue));
}
void Canvas::onKeyPress(int key, int modifier)
{
cppassist::debug(2, "gloperate") << "onKeyPressed(" << key << ")";
m_keyboardDevice->keyPress(key, modifier);
}
void Canvas::onKeyRelease(int key, int modifier)
{
cppassist::debug(2, "gloperate") << "onKeyReleased(" << key << ")";
m_keyboardDevice->keyRelease(key, modifier);
}
void Canvas::onMouseMove(const glm::ivec2 & pos)
{
cppassist::debug(2, "gloperate") << "onMouseMoved(" << pos.x << ", " << pos.y << ")";
m_mouseDevice->move(pos);
}
void Canvas::onMousePress(int button, const glm::ivec2 & pos)
{
cppassist::debug(2, "gloperate") << "onMousePressed(" << button << ", " << pos.x << ", " << pos.y << ")";
m_mouseDevice->buttonPress(button, pos);
}
void Canvas::onMouseRelease(int button, const glm::ivec2 & pos)
{
cppassist::debug(2, "gloperate") << "onMouseReleased(" << button << ", " << pos.x << ", " << pos.y << ")";
m_mouseDevice->buttonRelease(button, pos);
}
void Canvas::onMouseWheel(const glm::vec2 & delta, const glm::ivec2 & pos)
{
cppassist::debug(2, "gloperate") << "onMouseWheel(" << delta.x << ", " << delta.y << ", " << pos.x << ", " << pos.y << ")";
m_mouseDevice->wheelScroll(delta, pos);
}
const glm::vec4 & Canvas::savedDeviceViewport() const
{
return m_savedDeviceVP;
}
} // namespace gloperate
<commit_msg>Fix redraw request<commit_after>
#include <gloperate/base/Canvas.h>
#include <cppassist/logging/logging.h>
#include <cppassist/memory/make_unique.h>
#include <globjects/Framebuffer.h>
#include <gloperate/base/Environment.h>
#include <gloperate/base/TimeManager.h>
#include <gloperate/pipeline/Stage.h>
#include <gloperate/input/MouseDevice.h>
#include <gloperate/input/KeyboardDevice.h>
using namespace cppassist;
namespace gloperate
{
Canvas::Canvas(Environment * environment)
: AbstractCanvas(environment)
, m_pipelineContainer(environment)
, m_frame(0)
, m_mouseDevice(cppassist::make_unique<MouseDevice>(m_environment->inputManager(), m_name))
, m_keyboardDevice(cppassist::make_unique<KeyboardDevice>(m_environment->inputManager(), m_name))
{
// Mark render output as required and redraw when it is invalidated
m_pipelineContainer.rendered.setRequired(true);
m_pipelineContainer.rendered.valueInvalidated.connect([this] ()
{
if (!m_pipelineContainer.rendered.isValid()) {
this->redraw();
}
});
addProperty(&m_pipelineContainer);
}
Canvas::~Canvas()
{
}
const PipelineContainer * Canvas::pipelineContainer() const
{
return &m_pipelineContainer;
}
PipelineContainer * Canvas::pipelineContainer()
{
return &m_pipelineContainer;
}
const Stage * Canvas::renderStage() const
{
return m_pipelineContainer.renderStage();
}
Stage * Canvas::renderStage()
{
return m_pipelineContainer.renderStage();
}
void Canvas::setRenderStage(std::unique_ptr<Stage> && stage)
{
// De-initialize render stage
if (m_pipelineContainer.renderStage() && m_openGLContext)
{
m_pipelineContainer.renderStage()->deinitContext(m_openGLContext);
}
// Set new render stage
m_pipelineContainer.setRenderStage(std::move(stage));
// Initialize new render stage
if (m_pipelineContainer.renderStage() && m_openGLContext)
{
m_pipelineContainer.renderStage()->initContext(m_openGLContext);
}
}
void Canvas::onRender(globjects::Framebuffer * targetFBO)
{
if(cppassist::verbosityLevel() < 3)
cppassist::debug(2, "gloperate") << "onRender()";
else
{
auto fboName = targetFBO->hasName() ? targetFBO->name() : std::to_string(targetFBO->id());
cppassist::debug(3, "gloperate") << "onRender(); " << "targetFBO: " << fboName;
}
// Invoke render stage/pipeline
if (m_pipelineContainer.renderStage())
{
m_frame++;
m_pipelineContainer.frameCounter.setValue(m_frame);
m_pipelineContainer.targetFBO.setValue(targetFBO);
m_pipelineContainer.renderStage()->process(m_openGLContext);
}
}
void Canvas::onUpdate()
{
float timeDelta = m_environment->timeManager()->timeDelta();
m_pipelineContainer.timeDelta.setValue(timeDelta);
}
void Canvas::onContextInit()
{
cppassist::debug(2, "gloperate") << "onContextInit()";
// Initialize render stage in new context
if (m_pipelineContainer.renderStage())
{
m_pipelineContainer.renderStage()->initContext(m_openGLContext);
}
}
void Canvas::onContextDeinit()
{
cppassist::debug(2, "gloperate") << "onContextDeinit()";
// De-initialize render stage in old context
if (m_pipelineContainer.renderStage())
{
m_pipelineContainer.renderStage()->deinitContext(m_openGLContext);
}
}
void Canvas::onViewport(const glm::vec4 & deviceViewport, const glm::vec4 & virtualViewport)
{
m_deviceViewport = deviceViewport;
m_virtualViewport = virtualViewport;
m_pipelineContainer.deviceViewport.setValue(deviceViewport);
m_pipelineContainer.virtualViewport.setValue(virtualViewport);
}
void Canvas::onSaveViewport()
{
m_savedDeviceVP = m_deviceViewport;
m_savedVirtualVP = m_virtualViewport;
}
void Canvas::onResetViewport()
{
onViewport(m_savedDeviceVP, m_savedVirtualVP);
}
void Canvas::onBackgroundColor(float red, float green, float blue)
{
m_pipelineContainer.backgroundColor.setValue(glm::vec3(red, green, blue));
}
void Canvas::onKeyPress(int key, int modifier)
{
cppassist::debug(2, "gloperate") << "onKeyPressed(" << key << ")";
m_keyboardDevice->keyPress(key, modifier);
}
void Canvas::onKeyRelease(int key, int modifier)
{
cppassist::debug(2, "gloperate") << "onKeyReleased(" << key << ")";
m_keyboardDevice->keyRelease(key, modifier);
}
void Canvas::onMouseMove(const glm::ivec2 & pos)
{
cppassist::debug(2, "gloperate") << "onMouseMoved(" << pos.x << ", " << pos.y << ")";
m_mouseDevice->move(pos);
}
void Canvas::onMousePress(int button, const glm::ivec2 & pos)
{
cppassist::debug(2, "gloperate") << "onMousePressed(" << button << ", " << pos.x << ", " << pos.y << ")";
m_mouseDevice->buttonPress(button, pos);
}
void Canvas::onMouseRelease(int button, const glm::ivec2 & pos)
{
cppassist::debug(2, "gloperate") << "onMouseReleased(" << button << ", " << pos.x << ", " << pos.y << ")";
m_mouseDevice->buttonRelease(button, pos);
}
void Canvas::onMouseWheel(const glm::vec2 & delta, const glm::ivec2 & pos)
{
cppassist::debug(2, "gloperate") << "onMouseWheel(" << delta.x << ", " << delta.y << ", " << pos.x << ", " << pos.y << ")";
m_mouseDevice->wheelScroll(delta, pos);
}
const glm::vec4 & Canvas::savedDeviceViewport() const
{
return m_savedDeviceVP;
}
} // namespace gloperate
<|endoftext|>
|
<commit_before>/*******************************************************************************
* Copyright (c) 2013, Patrick P. Putnam (putnampp@gmail.com)
* 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.
*
* 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.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the FreeBSD Project.
******************************************************************************/
#include "../clothoobjects/common_types.h"
#include "MaturityModel.h"
#include "../ClothoModelCoordinator.h"
#include "SimulationManager.h"
#include <iostream>
#include "../clothoobjects/events/MaturityEvent.h"
#include "gsl/gsl_randist.h"
#include <time.h>
#include "IntVTime.h"
using std::cout;
using std::endl;
const string DISTRIBUTION_K = "distribution";
const string MEAN_K = "mean";
const string STDEV_K = "stdev";
DEFINE_REGISTERED_CLOTHO_MODEL( MaturityModel )
template <>
ClothoModel * ClothoModelCreator< MaturityModel >::createModel() {
shared_ptr< MaturityModel> pm( new MaturityModel() );
shared_ptr<ClothoModelCoordinator> coord = ClothoModelCoordinator::getInstance();
coord->addEventHandler( evt_BirthEvent.getDataType(), pm );
return &*pm;
}
template<>
ClothoModel * ClothoModelCreator< MaturityModel >::createModelFrom( const YAML::Node & n ) {
shared_ptr< MaturityModel > pm( new MaturityModel() );
pm->configure( n );
shared_ptr<ClothoModelCoordinator> coord = ClothoModelCoordinator::getInstance();
coord->addEventHandler( evt_BirthEvent.getDataType(), pm );
return &*pm;
}
MaturityModel::MaturityModel() : m_rng( gsl_rng_alloc( gsl_rng_taus ) ) {
long seed = time(NULL);
gsl_rng_set( m_rng, seed );
}
MaturityModel::~MaturityModel() {}
void MaturityModel::configure( const YAML::Node & n ) {
if( n[ MALE_K ] ) {
YAML::Node tmp = n[MALE_K];
if( tmp[ MEAN_K ] ) {
m_male_mean = tmp[MEAN_K].as< double >();
}
if( tmp[ STDEV_K ] ) {
m_male_sigma = tmp[STDEV_K].as< double >();
}
}
if( n[ FEMALE_K ] ) {
YAML::Node tmp = n[FEMALE_K];
if( tmp[ MEAN_K ] ) {
m_female_mean = tmp[MEAN_K].as< double >();
}
if( tmp[ STDEV_K ] ) {
m_female_sigma = tmp[STDEV_K].as< double >();
}
}
}
void MaturityModel::handle( const Event * evt ) {
const string name = evt->getDataType();
if( name == evt_BirthEvent.getDataType() ) {
const BirthEvent * bEvt = dynamic_cast< const BirthEvent * >( evt );
handle( bEvt );
}
}
void MaturityModel::handle( const BirthEvent * evt ) {
if(! evt ) return;
double expected_age = 0.0;
switch( evt->getSex() ) {
case FEMALE:
expected_age = gsl_ran_gaussian( m_rng, m_female_sigma );
expected_age += m_female_mean;
break;
case MALE:
expected_age = gsl_ran_gaussian( m_rng, m_male_sigma );
expected_age += m_male_mean;
break;
default:
expected_age = gsl_ran_gaussian( m_rng, m_unk_sigma );
expected_age += m_unk_mean;
break;
};
IntVTime tMaturity = dynamic_cast< const IntVTime & >( evt->getBirthTime() ) + (int)expected_age;
Event * mEvent = new MaturityEvent( evt->getBirthTime(), tMaturity, evt->getSender(), evt->getSender(), evt->getEventId().getEventNum() );
ClothoModelCoordinator::getInstance()->routeEvent( mEvent );
}
void MaturityModel::dump( ostream & out ) {
}
<commit_msg>Use new copy constructor for MaturityEvent<commit_after>/*******************************************************************************
* Copyright (c) 2013, Patrick P. Putnam (putnampp@gmail.com)
* 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.
*
* 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.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the FreeBSD Project.
******************************************************************************/
#include "../clothoobjects/common_types.h"
#include "MaturityModel.h"
#include "../ClothoModelCoordinator.h"
#include "SimulationManager.h"
#include <iostream>
#include "../clothoobjects/events/MaturityEvent.h"
#include "gsl/gsl_randist.h"
#include <time.h>
#include "IntVTime.h"
using std::cout;
using std::endl;
const string DISTRIBUTION_K = "distribution";
const string MEAN_K = "mean";
const string STDEV_K = "stdev";
DEFINE_REGISTERED_CLOTHO_MODEL( MaturityModel )
template <>
ClothoModel * ClothoModelCreator< MaturityModel >::createModel() {
shared_ptr< MaturityModel> pm( new MaturityModel() );
shared_ptr<ClothoModelCoordinator> coord = ClothoModelCoordinator::getInstance();
coord->addEventHandler( evt_BirthEvent.getDataType(), pm );
return &*pm;
}
template<>
ClothoModel * ClothoModelCreator< MaturityModel >::createModelFrom( const YAML::Node & n ) {
shared_ptr< MaturityModel > pm( new MaturityModel() );
pm->configure( n );
shared_ptr<ClothoModelCoordinator> coord = ClothoModelCoordinator::getInstance();
coord->addEventHandler( evt_BirthEvent.getDataType(), pm );
return &*pm;
}
MaturityModel::MaturityModel() : m_rng( gsl_rng_alloc( gsl_rng_taus ) ) {
long seed = time(NULL);
gsl_rng_set( m_rng, seed );
}
MaturityModel::~MaturityModel() {}
void MaturityModel::configure( const YAML::Node & n ) {
if( n[ MALE_K ] ) {
YAML::Node tmp = n[MALE_K];
if( tmp[ MEAN_K ] ) {
m_male_mean = tmp[MEAN_K].as< double >();
}
if( tmp[ STDEV_K ] ) {
m_male_sigma = tmp[STDEV_K].as< double >();
}
}
if( n[ FEMALE_K ] ) {
YAML::Node tmp = n[FEMALE_K];
if( tmp[ MEAN_K ] ) {
m_female_mean = tmp[MEAN_K].as< double >();
}
if( tmp[ STDEV_K ] ) {
m_female_sigma = tmp[STDEV_K].as< double >();
}
}
}
void MaturityModel::handle( const Event * evt ) {
const string name = evt->getDataType();
if( name == evt_BirthEvent.getDataType() ) {
const BirthEvent * bEvt = dynamic_cast< const BirthEvent * >( evt );
handle( bEvt );
}
}
void MaturityModel::handle( const BirthEvent * evt ) {
if(! evt ) return;
double expected_age = 0.0;
switch( evt->getSex() ) {
case FEMALE:
expected_age = gsl_ran_gaussian( m_rng, m_female_sigma );
expected_age += m_female_mean;
break;
case MALE:
expected_age = gsl_ran_gaussian( m_rng, m_male_sigma );
expected_age += m_male_mean;
break;
default:
expected_age = gsl_ran_gaussian( m_rng, m_unk_sigma );
expected_age += m_unk_mean;
break;
};
IntVTime tMaturity = dynamic_cast< const IntVTime & >( evt->getBirthTime() ) + (int)expected_age;
Event * mEvent = new MaturityEvent( evt->getBirthTime(), tMaturity, evt->getSender(), evt->getSender(), evt->getEventId() );
ClothoModelCoordinator::getInstance()->routeEvent( mEvent );
}
void MaturityModel::dump( ostream & out ) {
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2021 Carsten Burstedde, Donna Calhoun, Scott Aiton, Grady Wright
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "fc2d_thunderegg_vector.hpp"
#include <fclaw2d_clawpatch.h>
#include <fclaw2d_clawpatch.hpp>
#include <fclaw2d_clawpatch_options.h>
#include <fclaw2d_clawpatch46_fort.h>
#include <fclaw2d_clawpatch_output_ascii.h>
#include <fclaw2d_global.h>
#include <fclaw2d_domain.h>
#include <fclaw2d_patch.h>
#include <fclaw2d_convenience.h>
#include <fclaw2d_metric.hpp>
#include <fclaw2d_metric.h>
#include <fclaw2d_options.h>
#include <test/catch.hpp>
#include <test/test.hpp>
using namespace ThunderEgg;
namespace{
struct QuadDomain {
fclaw2d_global_t* glob;
fclaw_options_t fopts;
fclaw2d_domain_t *domain;
fclaw2d_clawpatch_options_t opts;
QuadDomain(){
fclaw2d_clawpatch_vtable_initialize(4);
glob = fclaw2d_global_new();
memset(&fopts, 0, sizeof(fopts));
fopts.mi=1;
fopts.mj=1;
fopts.minlevel=1;
fopts.maxlevel=1;
fopts.manifold=false;
fopts.bx = 1;
fopts.by = 2;
fopts.bz = 3;
fopts.compute_error = true;
fopts.subcycle = true;
domain = create_test_domain(sc_MPI_COMM_WORLD,&fopts);
fclaw2d_global_store_domain(glob, domain);
fclaw2d_options_store(glob, &fopts);
memset(&opts, 0, sizeof(opts));
opts.mx = 5;
opts.my = 6;
opts.mbc = 2;
opts.meqn = 1;
opts.maux = 1;
opts.rhs_fields = 1;
fclaw2d_clawpatch_options_store(glob, &opts);
fclaw2d_domain_data_new(glob->domain);
}
void setup(){
fclaw2d_build_mode_t build_mode = FCLAW2D_BUILD_FOR_UPDATE;
fclaw2d_patch_build(glob, &domain->blocks[0].patches[0], 0, 0, &build_mode);
fclaw2d_patch_build(glob, &domain->blocks[0].patches[1], 0, 1, &build_mode);
fclaw2d_patch_build(glob, &domain->blocks[0].patches[2], 0, 2, &build_mode);
fclaw2d_patch_build(glob, &domain->blocks[0].patches[3], 0, 3, &build_mode);
}
~QuadDomain(){
fclaw2d_patch_data_delete(glob, &domain->blocks[0].patches[0]);
fclaw2d_patch_data_delete(glob, &domain->blocks[0].patches[1]);
fclaw2d_patch_data_delete(glob, &domain->blocks[0].patches[2]);
fclaw2d_patch_data_delete(glob, &domain->blocks[0].patches[3]);
fclaw2d_global_destroy(glob);
}
};
}
TEST_CASE("fclaw2d_thunderegg_get_vector","[fclaw2d][thunderegg]")
{
fc2d_thunderegg_data_choice_t data_choice = GENERATE(RHS,SOLN,STORE_STATE);
QuadDomain test_data;
test_data.opts.mx = GENERATE(4,5,6);
test_data.opts.my = GENERATE(4,5,6);
test_data.opts.mbc = GENERATE(1,2);
int meqn = GENERATE(1,2);
if(data_choice == RHS){
test_data.opts.rhs_fields = meqn;
}else{
test_data.opts.meqn = meqn;
}
test_data.setup();
int mx = test_data.opts.mx;
int my = test_data.opts.my;
int mbc = test_data.opts.mbc;
//set data
for(int i=0; i < 4; i++){
double * data = nullptr;
switch(data_choice){
case RHS:
fclaw2d_clawpatch_rhs_data(test_data.glob, &test_data.domain->blocks[0].patches[i], &data, &meqn);
break;
case SOLN:
fclaw2d_clawpatch_soln_data(test_data.glob, &test_data.domain->blocks[0].patches[i], &data, &meqn);
break;
case STORE_STATE:
fclaw2d_clawpatch_soln_data(test_data.glob, &test_data.domain->blocks[0].patches[i], &data, &meqn);
break;
}
for(int j=0; j<(mx+2*mbc)*(my+2*mbc)*meqn; j++){
data[j] = i*(mx+2*mbc)*(my+2*mbc)*meqn + j;
}
}
// get vector
Vector<2> vec = fc2d_thunderegg_get_vector(test_data.glob,data_choice);
//CHECK
CHECK(vec.getNumLocalPatches() == 4);
for(int patch_idx=0; patch_idx < vec.getNumLocalPatches(); patch_idx++){
PatchView<double, 2> view = vec.getPatchView(patch_idx);
CHECK(view.getGhostStart()[0] == -mbc);
CHECK(view.getGhostStart()[1] == -mbc);
CHECK(view.getGhostStart()[2] == 0);
CHECK(view.getStart()[0] == 0);
CHECK(view.getStart()[1] == 0);
CHECK(view.getStart()[2] == 0);
CHECK(view.getEnd()[0] == mx-1);
CHECK(view.getEnd()[1] == my-1);
CHECK(view.getEnd()[2] == meqn-1);
CHECK(view.getGhostEnd()[0] == mx-1+mbc);
CHECK(view.getGhostEnd()[1] == my-1+mbc);
CHECK(view.getGhostEnd()[2] == meqn-1);
CHECK(view.getStrides()[0] == 1);
CHECK(view.getStrides()[1] == (mx+2*mbc));
CHECK(view.getStrides()[2] == (mx+2*mbc)*(my+2*mbc));
int idx=0;
for(int eqn=0; eqn<meqn; eqn++){
for(int j=-mbc; j<my+mbc; j++){
for(int i=-mbc; i<mx+mbc; i++){
CHECK(view(i,j,eqn) == patch_idx*(mx+2*mbc)*(my+2*mbc)*meqn + idx);
idx++;
}
}
}
}
}
TEST_CASE("fclaw2d_thunderegg_store_vector","[fclaw2d][thunderegg]")
{
QuadDomain test_data;
fc2d_thunderegg_data_choice_t data_choice = GENERATE(RHS,SOLN,STORE_STATE);
test_data.opts.mx = GENERATE(4,5,6);
test_data.opts.my = GENERATE(4,5,6);
test_data.opts.mbc = GENERATE(1,2);
int meqn = GENERATE(1,2);
if(data_choice == RHS){
test_data.opts.rhs_fields = meqn;
}else{
test_data.opts.meqn = meqn;
}
test_data.setup();
int mx = test_data.opts.mx;
int my = test_data.opts.my;
int mbc = test_data.opts.mbc;
//set data
Communicator comm(MPI_COMM_WORLD);
Vector<2> vec(comm,{mx,my},meqn,4,mbc);
for(int patch_idx=0; patch_idx < vec.getNumLocalPatches(); patch_idx++){
PatchView<double, 2> view = vec.getPatchView(patch_idx);
int idx=0;
for(int eqn=0; eqn<meqn; eqn++){
for(int j=-mbc; j<my+mbc; j++){
for(int i=-mbc; i<mx+mbc; i++){
view(i,j,eqn) = patch_idx*(mx+2*mbc)*(my+2*mbc)*meqn + idx;
idx++;
}
}
}
}
fc2d_thunderegg_store_vector(test_data.glob,data_choice,vec);
//check
for(int i=0; i < 4; i++){
double * data = nullptr;
switch(data_choice){
case RHS:
fclaw2d_clawpatch_rhs_data(test_data.glob, &test_data.domain->blocks[0].patches[i], &data, &meqn);
break;
case SOLN:
fclaw2d_clawpatch_soln_data(test_data.glob, &test_data.domain->blocks[0].patches[i], &data, &meqn);
break;
case STORE_STATE:
fclaw2d_clawpatch_soln_data(test_data.glob, &test_data.domain->blocks[0].patches[i], &data, &meqn);
break;
}
for(int j=0; j<(mx+2*mbc)*(my+2*mbc)*meqn; j++){
CHECK(data[j] == i*(mx+2*mbc)*(my+2*mbc)*meqn + j);
}
}
}
<commit_msg>added multiblock test<commit_after>/*
Copyright (c) 2021 Carsten Burstedde, Donna Calhoun, Scott Aiton, Grady Wright
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "fc2d_thunderegg_vector.hpp"
#include <fclaw2d_clawpatch.h>
#include <fclaw2d_clawpatch.hpp>
#include <fclaw2d_clawpatch_options.h>
#include <fclaw2d_clawpatch46_fort.h>
#include <fclaw2d_clawpatch_output_ascii.h>
#include <fclaw2d_global.h>
#include <fclaw2d_domain.h>
#include <fclaw2d_patch.h>
#include <fclaw2d_convenience.h>
#include <fclaw2d_metric.hpp>
#include <fclaw2d_metric.h>
#include <fclaw2d_options.h>
#include <test/catch.hpp>
#include <test/test.hpp>
using namespace ThunderEgg;
namespace{
struct QuadDomain {
fclaw2d_global_t* glob;
fclaw_options_t fopts;
fclaw2d_domain_t *domain;
fclaw2d_clawpatch_options_t opts;
QuadDomain(){
fclaw2d_clawpatch_vtable_initialize(4);
glob = fclaw2d_global_new();
memset(&fopts, 0, sizeof(fopts));
fopts.mi=1;
fopts.mj=1;
fopts.minlevel=1;
fopts.maxlevel=1;
fopts.manifold=false;
fopts.bx = 1;
fopts.by = 2;
fopts.bz = 3;
fopts.compute_error = true;
fopts.subcycle = true;
domain = create_test_domain(sc_MPI_COMM_WORLD,&fopts);
fclaw2d_global_store_domain(glob, domain);
fclaw2d_options_store(glob, &fopts);
memset(&opts, 0, sizeof(opts));
opts.mx = 5;
opts.my = 6;
opts.mbc = 2;
opts.meqn = 1;
opts.maux = 1;
opts.rhs_fields = 1;
fclaw2d_clawpatch_options_store(glob, &opts);
fclaw2d_domain_data_new(glob->domain);
}
void setup(){
fclaw2d_build_mode_t build_mode = FCLAW2D_BUILD_FOR_UPDATE;
fclaw2d_patch_build(glob, &domain->blocks[0].patches[0], 0, 0, &build_mode);
fclaw2d_patch_build(glob, &domain->blocks[0].patches[1], 0, 1, &build_mode);
fclaw2d_patch_build(glob, &domain->blocks[0].patches[2], 0, 2, &build_mode);
fclaw2d_patch_build(glob, &domain->blocks[0].patches[3], 0, 3, &build_mode);
}
~QuadDomain(){
fclaw2d_patch_data_delete(glob, &domain->blocks[0].patches[0]);
fclaw2d_patch_data_delete(glob, &domain->blocks[0].patches[1]);
fclaw2d_patch_data_delete(glob, &domain->blocks[0].patches[2]);
fclaw2d_patch_data_delete(glob, &domain->blocks[0].patches[3]);
fclaw2d_global_destroy(glob);
}
};
struct QuadDomainBrick {
fclaw2d_global_t* glob;
fclaw_options_t fopts;
fclaw2d_domain_t *domain;
fclaw2d_clawpatch_options_t opts;
QuadDomainBrick(){
fclaw2d_clawpatch_vtable_initialize(4);
glob = fclaw2d_global_new();
memset(&fopts, 0, sizeof(fopts));
fopts.mi=2;
fopts.mj=2;
fopts.minlevel=0;
fopts.maxlevel=0;
fopts.manifold=false;
fopts.bx = 1;
fopts.by = 2;
fopts.bz = 3;
fopts.compute_error = true;
fopts.subcycle = true;
domain = create_test_domain(sc_MPI_COMM_WORLD,&fopts);
fclaw2d_global_store_domain(glob, domain);
fclaw2d_options_store(glob, &fopts);
memset(&opts, 0, sizeof(opts));
opts.mx = 5;
opts.my = 6;
opts.mbc = 2;
opts.meqn = 1;
opts.maux = 1;
opts.rhs_fields = 1;
fclaw2d_clawpatch_options_store(glob, &opts);
fclaw2d_domain_data_new(glob->domain);
}
void setup(){
fclaw2d_build_mode_t build_mode = FCLAW2D_BUILD_FOR_UPDATE;
fclaw2d_patch_build(glob, &domain->blocks[0].patches[0], 0, 0, &build_mode);
fclaw2d_patch_build(glob, &domain->blocks[1].patches[0], 1, 0, &build_mode);
fclaw2d_patch_build(glob, &domain->blocks[2].patches[0], 2, 0, &build_mode);
fclaw2d_patch_build(glob, &domain->blocks[3].patches[0], 3, 0, &build_mode);
}
~QuadDomainBrick(){
fclaw2d_patch_data_delete(glob, &domain->blocks[0].patches[0]);
fclaw2d_patch_data_delete(glob, &domain->blocks[1].patches[0]);
fclaw2d_patch_data_delete(glob, &domain->blocks[2].patches[0]);
fclaw2d_patch_data_delete(glob, &domain->blocks[3].patches[0]);
fclaw2d_global_destroy(glob);
}
};
}
TEST_CASE("fclaw2d_thunderegg_get_vector","[fclaw2d][thunderegg]")
{
fc2d_thunderegg_data_choice_t data_choice = GENERATE(RHS,SOLN,STORE_STATE);
QuadDomain test_data;
test_data.opts.mx = GENERATE(4,5,6);
test_data.opts.my = GENERATE(4,5,6);
test_data.opts.mbc = GENERATE(1,2);
int meqn = GENERATE(1,2);
if(data_choice == RHS){
test_data.opts.rhs_fields = meqn;
}else{
test_data.opts.meqn = meqn;
}
test_data.setup();
int mx = test_data.opts.mx;
int my = test_data.opts.my;
int mbc = test_data.opts.mbc;
//set data
for(int i=0; i < 4; i++){
double * data = nullptr;
switch(data_choice){
case RHS:
fclaw2d_clawpatch_rhs_data(test_data.glob, &test_data.domain->blocks[0].patches[i], &data, &meqn);
break;
case SOLN:
fclaw2d_clawpatch_soln_data(test_data.glob, &test_data.domain->blocks[0].patches[i], &data, &meqn);
break;
case STORE_STATE:
fclaw2d_clawpatch_soln_data(test_data.glob, &test_data.domain->blocks[0].patches[i], &data, &meqn);
break;
}
for(int j=0; j<(mx+2*mbc)*(my+2*mbc)*meqn; j++){
data[j] = i*(mx+2*mbc)*(my+2*mbc)*meqn + j;
}
}
// get vector
Vector<2> vec = fc2d_thunderegg_get_vector(test_data.glob,data_choice);
//CHECK
CHECK(vec.getNumLocalPatches() == 4);
for(int patch_idx=0; patch_idx < vec.getNumLocalPatches(); patch_idx++){
PatchView<double, 2> view = vec.getPatchView(patch_idx);
CHECK(view.getGhostStart()[0] == -mbc);
CHECK(view.getGhostStart()[1] == -mbc);
CHECK(view.getGhostStart()[2] == 0);
CHECK(view.getStart()[0] == 0);
CHECK(view.getStart()[1] == 0);
CHECK(view.getStart()[2] == 0);
CHECK(view.getEnd()[0] == mx-1);
CHECK(view.getEnd()[1] == my-1);
CHECK(view.getEnd()[2] == meqn-1);
CHECK(view.getGhostEnd()[0] == mx-1+mbc);
CHECK(view.getGhostEnd()[1] == my-1+mbc);
CHECK(view.getGhostEnd()[2] == meqn-1);
CHECK(view.getStrides()[0] == 1);
CHECK(view.getStrides()[1] == (mx+2*mbc));
CHECK(view.getStrides()[2] == (mx+2*mbc)*(my+2*mbc));
int idx=0;
for(int eqn=0; eqn<meqn; eqn++){
for(int j=-mbc; j<my+mbc; j++){
for(int i=-mbc; i<mx+mbc; i++){
CHECK(view(i,j,eqn) == patch_idx*(mx+2*mbc)*(my+2*mbc)*meqn + idx);
idx++;
}
}
}
}
}
TEST_CASE("fclaw2d_thunderegg_store_vector","[fclaw2d][thunderegg]")
{
QuadDomain test_data;
fc2d_thunderegg_data_choice_t data_choice = GENERATE(RHS,SOLN,STORE_STATE);
test_data.opts.mx = GENERATE(4,5,6);
test_data.opts.my = GENERATE(4,5,6);
test_data.opts.mbc = GENERATE(1,2);
int meqn = GENERATE(1,2);
if(data_choice == RHS){
test_data.opts.rhs_fields = meqn;
}else{
test_data.opts.meqn = meqn;
}
test_data.setup();
int mx = test_data.opts.mx;
int my = test_data.opts.my;
int mbc = test_data.opts.mbc;
//set data
Communicator comm(MPI_COMM_WORLD);
Vector<2> vec(comm,{mx,my},meqn,4,mbc);
for(int patch_idx=0; patch_idx < vec.getNumLocalPatches(); patch_idx++){
PatchView<double, 2> view = vec.getPatchView(patch_idx);
int idx=0;
for(int eqn=0; eqn<meqn; eqn++){
for(int j=-mbc; j<my+mbc; j++){
for(int i=-mbc; i<mx+mbc; i++){
view(i,j,eqn) = patch_idx*(mx+2*mbc)*(my+2*mbc)*meqn + idx;
idx++;
}
}
}
}
fc2d_thunderegg_store_vector(test_data.glob,data_choice,vec);
//check
for(int i=0; i < 4; i++){
double * data = nullptr;
switch(data_choice){
case RHS:
fclaw2d_clawpatch_rhs_data(test_data.glob, &test_data.domain->blocks[0].patches[i], &data, &meqn);
break;
case SOLN:
fclaw2d_clawpatch_soln_data(test_data.glob, &test_data.domain->blocks[0].patches[i], &data, &meqn);
break;
case STORE_STATE:
fclaw2d_clawpatch_soln_data(test_data.glob, &test_data.domain->blocks[0].patches[i], &data, &meqn);
break;
}
for(int j=0; j<(mx+2*mbc)*(my+2*mbc)*meqn; j++){
CHECK(data[j] == i*(mx+2*mbc)*(my+2*mbc)*meqn + j);
}
}
}
TEST_CASE("fclaw2d_thunderegg_get_vector multiblock","[fclaw2d][thunderegg]")
{
fc2d_thunderegg_data_choice_t data_choice = GENERATE(RHS,SOLN,STORE_STATE);
QuadDomainBrick test_data;
test_data.opts.mx = GENERATE(4,5,6);
test_data.opts.my = GENERATE(4,5,6);
test_data.opts.mbc = GENERATE(1,2);
int meqn = GENERATE(1,2);
if(data_choice == RHS){
test_data.opts.rhs_fields = meqn;
}else{
test_data.opts.meqn = meqn;
}
test_data.setup();
int mx = test_data.opts.mx;
int my = test_data.opts.my;
int mbc = test_data.opts.mbc;
//set data
for(int i=0; i < 4; i++){
double * data = nullptr;
switch(data_choice){
case RHS:
fclaw2d_clawpatch_rhs_data(test_data.glob, &test_data.domain->blocks[i].patches[0], &data, &meqn);
break;
case SOLN:
fclaw2d_clawpatch_soln_data(test_data.glob, &test_data.domain->blocks[i].patches[0], &data, &meqn);
break;
case STORE_STATE:
fclaw2d_clawpatch_soln_data(test_data.glob, &test_data.domain->blocks[i].patches[0], &data, &meqn);
break;
}
for(int j=0; j<(mx+2*mbc)*(my+2*mbc)*meqn; j++){
data[j] = i*(mx+2*mbc)*(my+2*mbc)*meqn + j;
}
}
// get vector
Vector<2> vec = fc2d_thunderegg_get_vector(test_data.glob,data_choice);
//CHECK
CHECK(vec.getNumLocalPatches() == 4);
for(int patch_idx=0; patch_idx < vec.getNumLocalPatches(); patch_idx++){
PatchView<double, 2> view = vec.getPatchView(patch_idx);
CHECK(view.getGhostStart()[0] == -mbc);
CHECK(view.getGhostStart()[1] == -mbc);
CHECK(view.getGhostStart()[2] == 0);
CHECK(view.getStart()[0] == 0);
CHECK(view.getStart()[1] == 0);
CHECK(view.getStart()[2] == 0);
CHECK(view.getEnd()[0] == mx-1);
CHECK(view.getEnd()[1] == my-1);
CHECK(view.getEnd()[2] == meqn-1);
CHECK(view.getGhostEnd()[0] == mx-1+mbc);
CHECK(view.getGhostEnd()[1] == my-1+mbc);
CHECK(view.getGhostEnd()[2] == meqn-1);
CHECK(view.getStrides()[0] == 1);
CHECK(view.getStrides()[1] == (mx+2*mbc));
CHECK(view.getStrides()[2] == (mx+2*mbc)*(my+2*mbc));
int idx=0;
for(int eqn=0; eqn<meqn; eqn++){
for(int j=-mbc; j<my+mbc; j++){
for(int i=-mbc; i<mx+mbc; i++){
CHECK(view(i,j,eqn) == patch_idx*(mx+2*mbc)*(my+2*mbc)*meqn + idx);
idx++;
}
}
}
}
}
TEST_CASE("fclaw2d_thunderegg_store_vector multiblock","[fclaw2d][thunderegg]")
{
QuadDomainBrick test_data;
fc2d_thunderegg_data_choice_t data_choice = GENERATE(RHS,SOLN,STORE_STATE);
test_data.opts.mx = GENERATE(4,5,6);
test_data.opts.my = GENERATE(4,5,6);
test_data.opts.mbc = GENERATE(1,2);
int meqn = GENERATE(1,2);
if(data_choice == RHS){
test_data.opts.rhs_fields = meqn;
}else{
test_data.opts.meqn = meqn;
}
test_data.setup();
int mx = test_data.opts.mx;
int my = test_data.opts.my;
int mbc = test_data.opts.mbc;
//set data
Communicator comm(MPI_COMM_WORLD);
Vector<2> vec(comm,{mx,my},meqn,4,mbc);
for(int patch_idx=0; patch_idx < vec.getNumLocalPatches(); patch_idx++){
PatchView<double, 2> view = vec.getPatchView(patch_idx);
int idx=0;
for(int eqn=0; eqn<meqn; eqn++){
for(int j=-mbc; j<my+mbc; j++){
for(int i=-mbc; i<mx+mbc; i++){
view(i,j,eqn) = patch_idx*(mx+2*mbc)*(my+2*mbc)*meqn + idx;
idx++;
}
}
}
}
fc2d_thunderegg_store_vector(test_data.glob,data_choice,vec);
//check
for(int i=0; i < 4; i++){
double * data = nullptr;
switch(data_choice){
case RHS:
fclaw2d_clawpatch_rhs_data(test_data.glob, &test_data.domain->blocks[i].patches[0], &data, &meqn);
break;
case SOLN:
fclaw2d_clawpatch_soln_data(test_data.glob, &test_data.domain->blocks[i].patches[0], &data, &meqn);
break;
case STORE_STATE:
fclaw2d_clawpatch_soln_data(test_data.glob, &test_data.domain->blocks[i].patches[0], &data, &meqn);
break;
}
for(int j=0; j<(mx+2*mbc)*(my+2*mbc)*meqn; j++){
CHECK(data[j] == i*(mx+2*mbc)*(my+2*mbc)*meqn + j);
}
}
}
<|endoftext|>
|
<commit_before>/*
* plugin_factory.cpp
*
* Created on: Nov 20, 2012
* Author: partio
*/
#include "plugin_factory.h"
#include "logger_factory.h"
#include <boost/filesystem.hpp>
#include <boost/regex.hpp>
#include <cstdlib>
#include <dlfcn.h>
#include "util.h"
using namespace himan;
using namespace himan::plugin;
plugin_factory* plugin_factory::itsInstance = NULL;
plugin_factory* plugin_factory::Instance()
{
if (!itsInstance)
{
itsInstance = new plugin_factory();
}
return itsInstance;
}
plugin_factory::plugin_factory() : itsPluginSearchPath()
{
itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("plugin_factory"));
itsPluginSearchPath.push_back(".");
char* path;
path = std::getenv("HIMAN_LIBRARY_PATH");
if (path != NULL)
{
std::vector<std::string> paths = util::Split(std::string(path), ":", false);
itsPluginSearchPath.insert(itsPluginSearchPath.end(), paths.begin(), paths.end());
}
else
{
itsLogger->Warning("Environment variable HIMAN_LIBRARY_PATH not set -- search plugins only from current working directory");
}
ReadPlugins();
}
// Hide constructor
plugin_factory::~plugin_factory() {}
std::vector<std::shared_ptr<himan_plugin> > plugin_factory::Plugins(HPPluginClass pluginClass)
{
std::vector<std::shared_ptr<himan_plugin>> thePlugins;
for (size_t i = 0; i < itsPluginFactory.size(); i++)
{
if (pluginClass == itsPluginFactory[i]->Plugin()->PluginClass())
{
thePlugins.push_back(itsPluginFactory[i]->Plugin());
}
else if (pluginClass == kUnknownPlugin)
{
thePlugins.push_back(itsPluginFactory[i]->Plugin());
}
}
return thePlugins;
}
std::vector<std::shared_ptr<himan_plugin> > plugin_factory::CompiledPlugins()
{
return Plugins(kCompiled);
}
std::vector<std::shared_ptr<himan_plugin> > plugin_factory::AuxiliaryPlugins()
{
return Plugins(kAuxiliary);
}
std::vector<std::shared_ptr<himan_plugin> > plugin_factory::InterpretedPlugins()
{
return Plugins(kInterpreted);
}
/*
* Plugin()
*
* Return instance of the requested plugin if found. Caller must cast
* the plugin to the derived class. If second argument is true, a new
* instance is created and returned. Otherwise function behaves like
* a regular factory pattern and return one known instance to each
* caller (this is suitable only in non-threaded functions).
*/
std::shared_ptr<himan_plugin> plugin_factory::Plugin(const std::string& theClassName, bool theNewInstance)
{
for (size_t i = 0; i < itsPluginFactory.size(); i++)
{
if ((itsPluginFactory[i]->Plugin()->ClassName() == theClassName) ||
(itsPluginFactory[i]->Plugin()->ClassName() == "himan::plugin::" + theClassName))
{
if (theNewInstance)
{
return itsPluginFactory[i]->Clone();
}
else
{
return itsPluginFactory[i]->Plugin();
}
}
}
throw std::runtime_error("plugin_factory: Unknown plugin clone operation requested: " + theClassName);
}
/*
* ReadPlugins()
*
* Read plugins from defined paths. Will try to load all files in given directories
* that end with .so. Will not ascend to child directories (equals to "--max-depth 1").
*/
void plugin_factory::ReadPlugins()
{
using namespace boost::filesystem;
directory_iterator end_iter;
for (size_t i = 0; i < itsPluginSearchPath.size(); i++)
{
path p (itsPluginSearchPath[i]);
try
{
if (exists(p) && is_directory(p)) // is p a directory?
{
for ( directory_iterator dir_iter(p) ; dir_iter != end_iter ; ++dir_iter)
{
if (dir_iter->path().filename().extension().string() == ".so")
{
Load(dir_iter->path().string());
}
}
}
}
catch (const filesystem_error& ex)
{
itsLogger->Error(ex.what());
}
}
}
bool plugin_factory::Load(const std::string& thePluginFileName)
{
/*
* Open libraries with
*
* RTLD_LAZY
* We don't specify the ordering of the plugin load -- usually it is alphabetical
* but not necessarily so. With RTLD_LAZY the symbols aren't checked during load
* which means that the first loaded plugin can refer to functions defined in the
* last loaded plugin without compiler issuing warnings like
* <file>.so undefined symbol: ...
*
* RTLD_GLOBAL
* We need this because core library (himan-lib) need to access aux plugins
* and the plugin symbol information needs to be propagated throughout the
* plugins system (or using aux plugins in core lib will fail).
*/
void* theLibraryHandle = dlopen(thePluginFileName.c_str(), RTLD_LAZY | RTLD_GLOBAL);
if (!theLibraryHandle)
{
itsLogger->Error("Unable to load plugin: " + std::string(dlerror()));
return false;
}
dlerror(); // clear error handle
//create_t* create_plugin = (create_t*) dlsym(theLibraryHandle, "create");
create_t* create_plugin = reinterpret_cast<create_t*> (dlsym(theLibraryHandle, "create"));
if (!create_plugin)
{
itsLogger->Error("Unable to load symbol: " + std::string(dlerror()));
return false;
}
std::shared_ptr<plugin_container> mc = std::shared_ptr<plugin_container> (new plugin_container(theLibraryHandle, create_plugin()));
for (size_t i = 0; i < itsPluginFactory.size(); i++)
{
if (mc->Plugin()->ClassName() == itsPluginFactory[i]->Plugin()->ClassName())
{
itsLogger->Trace("Plugin '" + mc->Plugin()->ClassName() + "' found more than once, skipping one found from '" + thePluginFileName + "'");
return true;
}
}
itsPluginFactory.push_back(mc);
itsLogger->Debug("Load " + thePluginFileName);
return true;
}
<commit_msg>Fix SIGSEGV which happened when neons-library was loaded twice<commit_after>/*
* plugin_factory.cpp
*
* Created on: Nov 20, 2012
* Author: partio
*/
#include "plugin_factory.h"
#include "logger_factory.h"
#include <boost/filesystem.hpp>
#include <boost/regex.hpp>
#include <cstdlib>
#include <dlfcn.h>
#include "util.h"
using namespace himan;
using namespace himan::plugin;
plugin_factory* plugin_factory::itsInstance = NULL;
plugin_factory* plugin_factory::Instance()
{
if (!itsInstance)
{
itsInstance = new plugin_factory();
}
return itsInstance;
}
plugin_factory::plugin_factory() : itsPluginSearchPath()
{
itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("plugin_factory"));
char* path;
path = std::getenv("HIMAN_LIBRARY_PATH");
if (path != NULL)
{
std::vector<std::string> paths = util::Split(std::string(path), ":", false);
itsPluginSearchPath.insert(itsPluginSearchPath.end(), paths.begin(), paths.end());
}
else
{
itsLogger->Warning("Environment variable HIMAN_LIBRARY_PATH not set -- search plugins only from pre-defined locations");
}
itsPluginSearchPath.push_back(".");
itsPluginSearchPath.push_back("/usr/lib64/himan-plugins"); // Default RPM location
ReadPlugins();
}
// Hide constructor
plugin_factory::~plugin_factory() {}
std::vector<std::shared_ptr<himan_plugin> > plugin_factory::Plugins(HPPluginClass pluginClass)
{
std::vector<std::shared_ptr<himan_plugin>> thePlugins;
for (size_t i = 0; i < itsPluginFactory.size(); i++)
{
if (pluginClass == itsPluginFactory[i]->Plugin()->PluginClass())
{
thePlugins.push_back(itsPluginFactory[i]->Plugin());
}
else if (pluginClass == kUnknownPlugin)
{
thePlugins.push_back(itsPluginFactory[i]->Plugin());
}
}
return thePlugins;
}
std::vector<std::shared_ptr<himan_plugin> > plugin_factory::CompiledPlugins()
{
return Plugins(kCompiled);
}
std::vector<std::shared_ptr<himan_plugin> > plugin_factory::AuxiliaryPlugins()
{
return Plugins(kAuxiliary);
}
std::vector<std::shared_ptr<himan_plugin> > plugin_factory::InterpretedPlugins()
{
return Plugins(kInterpreted);
}
/*
* Plugin()
*
* Return instance of the requested plugin if found. Caller must cast
* the plugin to the derived class. If second argument is true, a new
* instance is created and returned. Otherwise function behaves like
* a regular factory pattern and return one known instance to each
* caller (this is suitable only in non-threaded functions).
*/
std::shared_ptr<himan_plugin> plugin_factory::Plugin(const std::string& theClassName, bool theNewInstance)
{
for (size_t i = 0; i < itsPluginFactory.size(); i++)
{
if ((itsPluginFactory[i]->Plugin()->ClassName() == theClassName) ||
(itsPluginFactory[i]->Plugin()->ClassName() == "himan::plugin::" + theClassName))
{
if (theNewInstance)
{
return itsPluginFactory[i]->Clone();
}
else
{
return itsPluginFactory[i]->Plugin();
}
}
}
throw std::runtime_error("plugin_factory: Unknown plugin clone operation requested: " + theClassName);
}
/*
* ReadPlugins()
*
* Read plugins from defined paths. Will try to load all files in given directories
* that end with .so. Will not ascend to child directories (equals to "--max-depth 1").
*/
void plugin_factory::ReadPlugins()
{
using namespace boost::filesystem;
directory_iterator end_iter;
for (size_t i = 0; i < itsPluginSearchPath.size(); i++)
{
itsLogger->Trace("Search plugins from " + itsPluginSearchPath[i]);
path p (itsPluginSearchPath[i]);
try
{
if (exists(p) && is_directory(p)) // is p a directory?
{
for ( directory_iterator dir_iter(p) ; dir_iter != end_iter ; ++dir_iter)
{
if (dir_iter->path().filename().extension().string() == ".so")
{
Load(dir_iter->path().string());
}
}
}
}
catch (const filesystem_error& ex)
{
itsLogger->Error(ex.what());
}
}
}
bool plugin_factory::Load(const std::string& thePluginFileName)
{
/*
* Open libraries with
*
* RTLD_LAZY
* We don't specify the ordering of the plugin load -- usually it is alphabetical
* but not necessarily so. With RTLD_LAZY the symbols aren't checked during load
* which means that the first loaded plugin can refer to functions defined in the
* last loaded plugin without compiler issuing warnings like
* <file>.so undefined symbol: ...
*
* RTLD_GLOBAL
* We need this because core library (himan-lib) need to access aux plugins
* and the plugin symbol information needs to be propagated throughout the
* plugins system (or using aux plugins in core lib will fail).
*/
void* theLibraryHandle = dlopen(thePluginFileName.c_str(), RTLD_LAZY | RTLD_GLOBAL);
if (!theLibraryHandle)
{
itsLogger->Error("Unable to load plugin: " + std::string(dlerror()));
return false;
}
dlerror(); // clear error handle
//create_t* create_plugin = (create_t*) dlsym(theLibraryHandle, "create");
create_t* create_plugin = reinterpret_cast<create_t*> (dlsym(theLibraryHandle, "create"));
if (!create_plugin)
{
itsLogger->Error("Unable to load symbol: " + std::string(dlerror()));
return false;
}
std::shared_ptr<plugin_container> mc = std::shared_ptr<plugin_container> (new plugin_container(theLibraryHandle, create_plugin()));
for (size_t i = 0; i < itsPluginFactory.size(); i++)
{
if (mc->Plugin()->ClassName() == itsPluginFactory[i]->Plugin()->ClassName())
{
itsLogger->Trace("Plugin '" + mc->Plugin()->ClassName() + "' found more than once, skipping one found from '" + thePluginFileName + "'");
return true;
}
}
itsPluginFactory.push_back(mc);
itsLogger->Debug("Load " + thePluginFileName);
return true;
}
<|endoftext|>
|
<commit_before>#include <combinations_with_replacement.hpp>
#include <iterator>
#include <string>
#include <set>
#include <vector>
#include "helpers.hpp"
#include "catch.hpp"
using iter::combinations_with_replacement;
using itertest::BasicIterable;
using CharCombSet = std::multiset<std::vector<char>>;
TEST_CASE("combinations_with_replacement: Simple combination",
"[combinations_with_replacement]") {
std::string s{"ABC"};
CharCombSet sc;
for (auto v : combinations_with_replacement(s, 2)) {
std::vector<char> vcopy(std::begin(v), std::end(v));
sc.insert(vcopy);
}
CharCombSet ans =
{{'A','A'}, {'A','B'}, {'A','C'}, {'B','B'}, {'B','C'}, {'C','C'}};
REQUIRE( ans == sc );
}
TEST_CASE("combinations_with_replacement: big size is no problem",
"[combinations_with_replacement]") {
std::string s{"AB"};
CharCombSet sc;
for (auto v : combinations_with_replacement(s, 3)) {
std::vector<char> vcopy(std::begin(v), std::end(v));
sc.insert(vcopy);
}
CharCombSet ans =
{{'A', 'A', 'A'}, {'A', 'A', 'B'}, {'A', 'B', 'B'}, {'B', 'B', 'B'}};
REQUIRE( ans == sc );
}
TEST_CASE("combinations_with_replacement: 0 size is empty",
"[combinations_with_replacement]") {
std::string s{"A"};
auto cwr = combinations_with_replacement(s, 0);
REQUIRE( std::begin(cwr) == std::end(cwr) );
}
TEST_CASE("combinations_with_replacement: doesn't move or copy elements of iterable",
"[combinations_with_replacement]") {
constexpr itertest::SolidInt arr[] = {{6}, {7}, {8}};
for (auto&& i : combinations_with_replacement(arr, 1)) {
(void)i;
}
}
<commit_msg>test that comb_with_repl moves and binds correctly<commit_after>#include <combinations_with_replacement.hpp>
#include <iterator>
#include <string>
#include <set>
#include <vector>
#include "helpers.hpp"
#include "catch.hpp"
using iter::combinations_with_replacement;
using itertest::BasicIterable;
using CharCombSet = std::vector<std::vector<char>>;
TEST_CASE("combinations_with_replacement: Simple combination",
"[combinations_with_replacement]") {
std::string s{"ABC"};
CharCombSet sc;
for (auto v : combinations_with_replacement(s, 2)) {
sc.emplace_back(std::begin(v), std::end(v));
}
CharCombSet ans =
{{'A','A'}, {'A','B'}, {'A','C'}, {'B','B'}, {'B','C'}, {'C','C'}};
REQUIRE( ans == sc );
}
TEST_CASE("combinations_with_replacement: iterators can be compared",
"[combinations_with_replacement]") {
std::string s{"ABCD"};
auto c = combinations_with_replacement(s, 2);
auto it = std::begin(c);
REQUIRE( it == std::begin(c) );
REQUIRE_FALSE( it != std::begin(c) );
++it;
REQUIRE( it != std::begin(c) );
REQUIRE_FALSE( it == std::begin(c) );
}
TEST_CASE("combinations_with_replacement: big size is no problem",
"[combinations_with_replacement]") {
std::string s{"AB"};
CharCombSet sc;
for (auto v : combinations_with_replacement(s, 3)) {
sc.emplace_back(std::begin(v), std::end(v));
}
CharCombSet ans =
{{'A', 'A', 'A'}, {'A', 'A', 'B'}, {'A', 'B', 'B'}, {'B', 'B', 'B'}};
REQUIRE( ans == sc );
}
TEST_CASE("combinations_with_replacement: 0 size is empty",
"[combinations_with_replacement]") {
std::string s{"A"};
auto cwr = combinations_with_replacement(s, 0);
REQUIRE( std::begin(cwr) == std::end(cwr) );
}
TEST_CASE("combinations_with_replacement: binds to lvalues, moves rvalues",
"[combinations_with_replacement]") {
BasicIterable<char> bi{'x', 'y', 'z'};
SECTION("binds to lvalues") {
combinations_with_replacement(bi, 1);
REQUIRE_FALSE( bi.was_moved_from() );
}
SECTION("moves rvalues") {
combinations_with_replacement(std::move(bi), 1);
REQUIRE( bi.was_moved_from() );
}
}
TEST_CASE("combinations_with_replacement: "
"doesn't move or copy elements of iterable",
"[combinations_with_replacement]") {
constexpr itertest::SolidInt arr[] = {{6}, {7}, {8}};
for (auto&& i : combinations_with_replacement(arr, 1)) {
(void)i;
}
}
<|endoftext|>
|
<commit_before>//
// Created by Sam on 9/25/2017.
//
#include <utility>
#include <iostream>
#include "../../include/Game/Card.h"
#include "../../include/Game/Player.h"
#include "../../include/Game/Game.h"
#include "../../include/Game/Card/Creature.h"
#include "../../include/Game/Container/Deck.h"
#include "../../include/Game/Container/Hand.h"
#include "../../include/Game/Container/CreatureZone.h"
#include "../../include/Game/Container/Graveyard.h"
#include "../../include/Network/Client.h"
#include "../../include/Network/Request/Game/ChatMessage.h"
#include "../../include/Network/Request/Game/PlayCardMessage.h"
#include "../../include/Network/Request/Game/FightPlayerMessage.h"
#include "../../include/Game/Event/Player/DrawEvent.h"
#include "../../include/Game/Event/Player/PlayCardEvent.h"
#include "../../include/Game/Event/Player/PlayerAttackedEvent.h"
#include "../../include/Game/Event/Game/StartTurnEvent.h"
#include "../../include/Game/Event/Game/EndTurnEvent.h"
#include "../../include/Network/Request/Game/FightCreatureMessage.h"
#include "../../include/Game/Event/Player/CreatureAttackedEvent.h"
#include "../../include/Game/Event/Game/CreatureDestroyedEvent.h"
#include "../../include/Game/Event/Game/EndGameEvent.h"
void Player::startGameSetup()
{
board->deck->shuffle();
internalDraw(5);
}
void Player::draw()
{
internalDraw();
DrawEvent drawEvent(game, { hand->cards.back() }, shared_from_this());
game->eventHandler(std::make_shared<DrawEvent>(drawEvent));
}
void Player::draw(int count)
{
internalDraw(count);
auto first = hand->cards.end() - count;
auto last = hand->cards.end();
std::vector<std::shared_ptr<Card>> drawnCards(first, last);
DrawEvent drawEvent(game, drawnCards, shared_from_this());
game->eventHandler(std::make_shared<DrawEvent>(drawEvent));
}
void Player::startTurn()
{
refillMana();
refreshCreatures();
StartTurnEvent startTurnEvent(game);
game->eventHandler(std::make_shared<StartTurnEvent>(startTurnEvent));
draw();
}
void Player::refillMana()
{
availableMana = totalMana;
}
void Player::refreshCreatures()
{
for (const auto& card : board->creatures->cards)
{
const auto& creature = std::dynamic_pointer_cast<Creature>(card);
creature->availableAttacks = creature->attacks;
creature->usedAttacks = 0;
}
}
void Player::playCard(const json &rawJSON)
{
if (shared_from_this() == game->activePlayer)
{
PlayCardMessage moveCardMessage(rawJSON);
auto card = hand->findCard(moveCardMessage.cardTag);
if (availableMana.canPay(card->mana))
{
availableMana.payMana(card->mana);
board->playCard(card);
hand->removeCard(card);
if (totalMana.getTotalCount() <= 15 && totalMana.withinIndividualLimit())
{
totalMana.increaseMana(card->mana);
}
game->cardOrder.push_back(card);
PlayCardEvent playCardEvent(game, card);
game->eventHandler(std::make_shared<PlayCardEvent>(playCardEvent));
}
}
}
void Player::endTurn(const json &rawJSON)
{
EndTurnEvent endTurnEvent(game);
game->eventHandler(std::make_shared<EndTurnEvent>(endTurnEvent));
game->changeTurn();
}
void Player::sendChatMessage(const json &rawJSON)
{
// Format chat message with the sender name before broadcasting it to all players
ChatMessage chatMessage(rawJSON);
chatMessage.rawJSON[Message::DATA_KEY]["text"] = name + ": " + chatMessage.text;
game->writePlayers(chatMessage.getJSON());
}
void Player::fightPlayer(const json &rawJSON)
{
FightPlayerMessage fightPlayerMessage(rawJSON);
auto player = game->findPlayer(fightPlayerMessage.attackingPlayerTag);
auto card = board->creatures->findCard(fightPlayerMessage.cardTag);
auto creature = std::dynamic_pointer_cast<Creature>(card);
// You can't attack yourself!
if (player == shared_from_this())
{
throw std::runtime_error("You cannot attack yourself");
}
creature->attack(player);
PlayerAttackedEvent playerAttackedEvent(game, card, player);
game->eventHandler(std::make_shared<PlayerAttackedEvent>(playerAttackedEvent));
std::vector<std::shared_ptr<Player>> alive;
if (game->isGameOver())
{
auto winner = game->getWinner();
EndGameEvent endGameEvent(game, winner);
game->eventHandler(std::make_shared<EndGameEvent>(endGameEvent));
}
}
void Player::fightCreature(const json &rawJSON)
{
FightCreatureMessage fightCreatureMessage(rawJSON);
auto attackingPlayer = game->findPlayer(fightCreatureMessage.attackingPlayerTag);
auto attackingCard = attackingPlayer->board->creatures->findCard(fightCreatureMessage.attackingCardTag);
auto attacker = std::dynamic_pointer_cast<Creature>(attackingCard);
std::shared_ptr<Creature> target;
for (const auto& player : game->players)
{
try
{
auto card = player->board->creatures->findCard(fightCreatureMessage.attackedCardTag);
target = std::dynamic_pointer_cast<Creature>(card);
}
catch (const std::runtime_error& ex)
{/* Eat this because findCard throws a runtime error if the card is not found */}
}
if (!target)
{
throw std::runtime_error("Cannot find attacked card with tag '" + fightCreatureMessage.attackedCardTag + "'");
}
if (attacker->player == target->player)
{
throw std::runtime_error("You cannot attack your own creatures");
}
attacker->attack(target);
CreatureAttackedEvent creatureAttackedEvent(game, target, attacker);
game->eventHandler(std::make_shared<CreatureAttackedEvent>(creatureAttackedEvent));
if (target->defenseStat <= 0)
{
destroyCreature(target);
}
if (attacker->defenseStat <= 0)
{
destroyCreature(attacker);
}
}
json Player::getState()
{
json playerJSON;
playerJSON["playerTag"] = tag;
playerJSON["hand"] = hand->getJSON();
playerJSON["health"] = health;
playerJSON["deckCount"] = board->deck->count();
playerJSON["mana"] = getManaJSON();
playerJSON["board"] = board->getJSON();
return playerJSON;
}
json Player::getOpponentState()
{
json opponentJSON;
opponentJSON["playerTag"] = tag;
opponentJSON["name"] = name;
opponentJSON["health"] = health;
opponentJSON["handCount"] = hand->count();
opponentJSON["deckCount"] = board->deck->count();
opponentJSON["mana"] = getManaJSON();
opponentJSON["board"] = board->getJSON();
return opponentJSON;
}
json Player::getManaJSON()
{
json manaJSON;
manaJSON["available"] = availableMana.getJSON();
manaJSON["total"] = totalMana.getJSON();
return manaJSON;
}
Player::Player(std::shared_ptr<Client> client)
: client(client),
name(client->name),
availableMana(1,1,1,1,1,1),
totalMana(1,1,1,1,1,1),
board(std::make_shared<Board>()),
hand(std::make_shared<Hand>()),
health(30)
{
}
Player::~Player()
= default;
void Player::internalDraw()
{
hand->addCard(board->deck->draw());
}
void Player::internalDraw(int count)
{
for (int i = 0; i < count; i++)
{
internalDraw();
}
}
void Player::destroyCreature(const std::shared_ptr<Creature> &target) const
{
auto targetOwner = target->player;
targetOwner->board->graveyard->cards.push_back(target);
targetOwner->board->creatures->removeCard(target);
CreatureDestroyedEvent creatureDestroyedEvent(game, target);
game->eventHandler(std::make_shared<CreatureDestroyedEvent>(creatureDestroyedEvent));
}
<commit_msg>Added some errors for when a player attempts to attack an invalid creature<commit_after>//
// Created by Sam on 9/25/2017.
//
#include <utility>
#include <iostream>
#include "../../include/Game/Card.h"
#include "../../include/Game/Player.h"
#include "../../include/Game/Game.h"
#include "../../include/Game/Card/Creature.h"
#include "../../include/Game/Container/Deck.h"
#include "../../include/Game/Container/Hand.h"
#include "../../include/Game/Container/CreatureZone.h"
#include "../../include/Game/Container/Graveyard.h"
#include "../../include/Network/Client.h"
#include "../../include/Network/Request/Game/ChatMessage.h"
#include "../../include/Network/Request/Game/PlayCardMessage.h"
#include "../../include/Network/Request/Game/FightPlayerMessage.h"
#include "../../include/Game/Event/Player/DrawEvent.h"
#include "../../include/Game/Event/Player/PlayCardEvent.h"
#include "../../include/Game/Event/Player/PlayerAttackedEvent.h"
#include "../../include/Game/Event/Game/StartTurnEvent.h"
#include "../../include/Game/Event/Game/EndTurnEvent.h"
#include "../../include/Network/Request/Game/FightCreatureMessage.h"
#include "../../include/Game/Event/Player/CreatureAttackedEvent.h"
#include "../../include/Game/Event/Game/CreatureDestroyedEvent.h"
#include "../../include/Game/Event/Game/EndGameEvent.h"
void Player::startGameSetup()
{
board->deck->shuffle();
internalDraw(5);
}
void Player::draw()
{
internalDraw();
DrawEvent drawEvent(game, { hand->cards.back() }, shared_from_this());
game->eventHandler(std::make_shared<DrawEvent>(drawEvent));
}
void Player::draw(int count)
{
internalDraw(count);
auto first = hand->cards.end() - count;
auto last = hand->cards.end();
std::vector<std::shared_ptr<Card>> drawnCards(first, last);
DrawEvent drawEvent(game, drawnCards, shared_from_this());
game->eventHandler(std::make_shared<DrawEvent>(drawEvent));
}
void Player::startTurn()
{
refillMana();
refreshCreatures();
StartTurnEvent startTurnEvent(game);
game->eventHandler(std::make_shared<StartTurnEvent>(startTurnEvent));
draw();
}
void Player::refillMana()
{
availableMana = totalMana;
}
void Player::refreshCreatures()
{
for (const auto& card : board->creatures->cards)
{
const auto& creature = std::dynamic_pointer_cast<Creature>(card);
creature->availableAttacks = creature->attacks;
creature->usedAttacks = 0;
}
}
void Player::playCard(const json &rawJSON)
{
if (shared_from_this() == game->activePlayer)
{
PlayCardMessage moveCardMessage(rawJSON);
auto card = hand->findCard(moveCardMessage.cardTag);
if (availableMana.canPay(card->mana))
{
availableMana.payMana(card->mana);
board->playCard(card);
hand->removeCard(card);
if (totalMana.getTotalCount() <= 15 && totalMana.withinIndividualLimit())
{
totalMana.increaseMana(card->mana);
}
game->cardOrder.push_back(card);
PlayCardEvent playCardEvent(game, card);
game->eventHandler(std::make_shared<PlayCardEvent>(playCardEvent));
}
else
{
throw std::runtime_error("Insufficient mana to play " + card->name);
}
}
else
{
throw std::runtime_error("You cannot play a card when it was not your turn");
}
}
void Player::endTurn(const json &rawJSON)
{
EndTurnEvent endTurnEvent(game);
game->eventHandler(std::make_shared<EndTurnEvent>(endTurnEvent));
game->changeTurn();
}
void Player::sendChatMessage(const json &rawJSON)
{
// Format chat message with the sender name before broadcasting it to all players
ChatMessage chatMessage(rawJSON);
chatMessage.rawJSON[Message::DATA_KEY]["text"] = name + ": " + chatMessage.text;
game->writePlayers(chatMessage.getJSON());
}
void Player::fightPlayer(const json &rawJSON)
{
FightPlayerMessage fightPlayerMessage(rawJSON);
auto player = game->findPlayer(fightPlayerMessage.attackingPlayerTag);
auto card = board->creatures->findCard(fightPlayerMessage.cardTag);
auto creature = std::dynamic_pointer_cast<Creature>(card);
// You can't attack yourself!
if (player == shared_from_this())
{
throw std::runtime_error("You cannot attack yourself");
}
creature->attack(player);
PlayerAttackedEvent playerAttackedEvent(game, card, player);
game->eventHandler(std::make_shared<PlayerAttackedEvent>(playerAttackedEvent));
std::vector<std::shared_ptr<Player>> alive;
if (game->isGameOver())
{
auto winner = game->getWinner();
EndGameEvent endGameEvent(game, winner);
game->eventHandler(std::make_shared<EndGameEvent>(endGameEvent));
}
}
void Player::fightCreature(const json &rawJSON)
{
FightCreatureMessage fightCreatureMessage(rawJSON);
auto attackingPlayer = game->findPlayer(fightCreatureMessage.attackingPlayerTag);
auto attackingCard = attackingPlayer->board->creatures->findCard(fightCreatureMessage.attackingCardTag);
auto attacker = std::dynamic_pointer_cast<Creature>(attackingCard);
std::shared_ptr<Creature> target;
for (const auto& player : game->players)
{
try
{
auto card = player->board->creatures->findCard(fightCreatureMessage.attackedCardTag);
target = std::dynamic_pointer_cast<Creature>(card);
}
catch (const std::runtime_error& ex)
{/* Eat this because findCard throws a runtime error if the card is not found */}
}
if (!target)
{
throw std::runtime_error("Cannot find attacked card with tag '" + fightCreatureMessage.attackedCardTag + "'");
}
if (attacker->player == target->player)
{
throw std::runtime_error("You cannot attack your own creatures");
}
attacker->attack(target);
CreatureAttackedEvent creatureAttackedEvent(game, target, attacker);
game->eventHandler(std::make_shared<CreatureAttackedEvent>(creatureAttackedEvent));
if (target->defenseStat <= 0)
{
destroyCreature(target);
}
if (attacker->defenseStat <= 0)
{
destroyCreature(attacker);
}
}
json Player::getState()
{
json playerJSON;
playerJSON["playerTag"] = tag;
playerJSON["hand"] = hand->getJSON();
playerJSON["health"] = health;
playerJSON["deckCount"] = board->deck->count();
playerJSON["mana"] = getManaJSON();
playerJSON["board"] = board->getJSON();
return playerJSON;
}
json Player::getOpponentState()
{
json opponentJSON;
opponentJSON["playerTag"] = tag;
opponentJSON["name"] = name;
opponentJSON["health"] = health;
opponentJSON["handCount"] = hand->count();
opponentJSON["deckCount"] = board->deck->count();
opponentJSON["mana"] = getManaJSON();
opponentJSON["board"] = board->getJSON();
return opponentJSON;
}
json Player::getManaJSON()
{
json manaJSON;
manaJSON["available"] = availableMana.getJSON();
manaJSON["total"] = totalMana.getJSON();
return manaJSON;
}
Player::Player(std::shared_ptr<Client> client)
: client(client),
name(client->name),
availableMana(1,1,1,1,1,1),
totalMana(1,1,1,1,1,1),
board(std::make_shared<Board>()),
hand(std::make_shared<Hand>()),
health(30)
{
}
Player::~Player()
= default;
void Player::internalDraw()
{
hand->addCard(board->deck->draw());
}
void Player::internalDraw(int count)
{
for (int i = 0; i < count; i++)
{
internalDraw();
}
}
void Player::destroyCreature(const std::shared_ptr<Creature> &target) const
{
auto targetOwner = target->player;
targetOwner->board->graveyard->cards.push_back(target);
targetOwner->board->creatures->removeCard(target);
CreatureDestroyedEvent creatureDestroyedEvent(game, target);
game->eventHandler(std::make_shared<CreatureDestroyedEvent>(creatureDestroyedEvent));
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/privacy_blacklist/blacklist_manager.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/scoped_temp_dir.h"
#include "base/thread.h"
#include "chrome/browser/privacy_blacklist/blacklist.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/testing_profile.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
class MyTestingProfile : public TestingProfile {
public:
MyTestingProfile() {
EXPECT_TRUE(temp_dir_.CreateUniqueTempDir());
path_ = temp_dir_.path();
}
private:
ScopedTempDir temp_dir_;
DISALLOW_COPY_AND_ASSIGN(MyTestingProfile);
};
class TestBlacklistPathProvider : public BlacklistPathProvider {
public:
explicit TestBlacklistPathProvider(Profile* profile) : profile_(profile) {
}
virtual std::vector<FilePath> GetBlacklistPaths() {
return paths_;
}
void AddPath(const FilePath& path) {
paths_.push_back(path);
NotificationService::current()->Notify(
NotificationType::PRIVACY_BLACKLIST_PATH_PROVIDER_UPDATED,
Source<Profile>(profile_),
Details<BlacklistPathProvider>(this));
}
private:
Profile* profile_;
std::vector<FilePath> paths_;
DISALLOW_COPY_AND_ASSIGN(TestBlacklistPathProvider);
};
class BlacklistManagerTest : public testing::Test {
public:
virtual void SetUp() {
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir_));
test_data_dir_ = test_data_dir_.AppendASCII("blacklist_samples");
}
virtual void TearDown() {
loop_.RunAllPending();
}
protected:
FilePath test_data_dir_;
MyTestingProfile profile_;
private:
MessageLoop loop_;
};
TEST_F(BlacklistManagerTest, Basic) {
scoped_refptr<BlacklistManager> manager(
new BlacklistManager(&profile_, NULL));
const Blacklist* blacklist = manager->GetCompiledBlacklist();
// We should get an empty, but valid object.
ASSERT_TRUE(blacklist);
EXPECT_TRUE(blacklist->is_good());
// Repeated invocations of GetCompiledBlacklist should return the same object.
EXPECT_EQ(blacklist, manager->GetCompiledBlacklist());
}
TEST_F(BlacklistManagerTest, BlacklistPathProvider) {
scoped_refptr<BlacklistManager> manager(
new BlacklistManager(&profile_, NULL));
const Blacklist* blacklist1 = manager->GetCompiledBlacklist();
EXPECT_FALSE(blacklist1->findMatch(GURL("http://host/annoying_ads/ad.jpg")));
TestBlacklistPathProvider provider(&profile_);
manager->RegisterBlacklistPathProvider(&provider);
// Blacklist should not get recompiled.
EXPECT_EQ(blacklist1, manager->GetCompiledBlacklist());
provider.AddPath(test_data_dir_.AppendASCII("annoying_ads.pbl"));
const Blacklist* blacklist2 = manager->GetCompiledBlacklist();
// Added a real blacklist, the manager should recompile.
EXPECT_NE(blacklist1, blacklist2);
EXPECT_TRUE(blacklist2->findMatch(GURL("http://host/annoying_ads/ad.jpg")));
manager->UnregisterBlacklistPathProvider(&provider);
// Just unregistering the provider doesn't remove the blacklist paths
// from the manager.
EXPECT_EQ(blacklist2, manager->GetCompiledBlacklist());
}
TEST_F(BlacklistManagerTest, RealThread) {
base::Thread backend_thread("backend_thread");
backend_thread.Start();
scoped_refptr<BlacklistManager> manager(
new BlacklistManager(&profile_, &backend_thread));
// Make sure all pending tasks run.
backend_thread.Stop();
backend_thread.Start();
const Blacklist* blacklist1 = manager->GetCompiledBlacklist();
EXPECT_FALSE(blacklist1->findMatch(GURL("http://host/annoying_ads/ad.jpg")));
TestBlacklistPathProvider provider(&profile_);
manager->RegisterBlacklistPathProvider(&provider);
// Make sure all pending tasks run.
backend_thread.Stop();
backend_thread.Start();
// Blacklist should not get recompiled.
EXPECT_EQ(blacklist1, manager->GetCompiledBlacklist());
provider.AddPath(test_data_dir_.AppendASCII("annoying_ads.pbl"));
// Make sure all pending tasks run.
backend_thread.Stop();
backend_thread.Start();
const Blacklist* blacklist2 = manager->GetCompiledBlacklist();
// Added a real blacklist, the manager should recompile.
EXPECT_NE(blacklist1, blacklist2);
EXPECT_TRUE(blacklist2->findMatch(GURL("http://host/annoying_ads/ad.jpg")));
manager->UnregisterBlacklistPathProvider(&provider);
// Make sure all pending tasks run.
backend_thread.Stop();
backend_thread.Start();
// Just unregistering the provider doesn't remove the blacklist paths
// from the manager.
EXPECT_EQ(blacklist2, manager->GetCompiledBlacklist());
}
TEST_F(BlacklistManagerTest, CompiledBlacklistStaysOnDisk) {
{
scoped_refptr<BlacklistManager> manager(
new BlacklistManager(&profile_, NULL));
TestBlacklistPathProvider provider(&profile_);
manager->RegisterBlacklistPathProvider(&provider);
provider.AddPath(test_data_dir_.AppendASCII("annoying_ads.pbl"));
const Blacklist* blacklist = manager->GetCompiledBlacklist();
EXPECT_TRUE(blacklist->findMatch(GURL("http://host/annoying_ads/ad.jpg")));
manager->UnregisterBlacklistPathProvider(&provider);
}
{
scoped_refptr<BlacklistManager> manager(
new BlacklistManager(&profile_, NULL));
// Make sure we read the compiled blacklist from disk and don't even touch
// the paths providers.
const Blacklist* blacklist = manager->GetCompiledBlacklist();
EXPECT_TRUE(blacklist->findMatch(GURL("http://host/annoying_ads/ad.jpg")));
}
}
TEST_F(BlacklistManagerTest, BlacklistPathReadError) {
scoped_refptr<BlacklistManager> manager(
new BlacklistManager(&profile_, NULL));
TestBlacklistPathProvider provider(&profile_);
manager->RegisterBlacklistPathProvider(&provider);
FilePath bogus_path(test_data_dir_.AppendASCII("does_not_exist_randomness"));
ASSERT_FALSE(file_util::PathExists(bogus_path));
provider.AddPath(bogus_path);
const Blacklist* blacklist = manager->GetCompiledBlacklist();
// We should get an empty, but valid object.
ASSERT_TRUE(blacklist);
EXPECT_TRUE(blacklist->is_good());
manager->UnregisterBlacklistPathProvider(&provider);
}
TEST_F(BlacklistManagerTest, CompiledBlacklistReadError) {
FilePath compiled_blacklist_path;
{
scoped_refptr<BlacklistManager> manager(
new BlacklistManager(&profile_, NULL));
TestBlacklistPathProvider provider(&profile_);
manager->RegisterBlacklistPathProvider(&provider);
provider.AddPath(test_data_dir_.AppendASCII("annoying_ads.pbl"));
const Blacklist* blacklist = manager->GetCompiledBlacklist();
EXPECT_TRUE(blacklist->findMatch(GURL("http://host/annoying_ads/ad.jpg")));
manager->UnregisterBlacklistPathProvider(&provider);
compiled_blacklist_path = manager->compiled_blacklist_path();
}
ASSERT_TRUE(file_util::PathExists(compiled_blacklist_path));
ASSERT_TRUE(file_util::Delete(compiled_blacklist_path, false));
{
scoped_refptr<BlacklistManager> manager(
new BlacklistManager(&profile_, NULL));
// Now we don't have any providers, and no compiled blacklist file. We
// shouldn't match any URLs.
const Blacklist* blacklist = manager->GetCompiledBlacklist();
EXPECT_FALSE(blacklist->findMatch(GURL("http://host/annoying_ads/ad.jpg")));
}
}
TEST_F(BlacklistManagerTest, MultipleProviders) {
scoped_refptr<BlacklistManager> manager(
new BlacklistManager(&profile_, NULL));
TestBlacklistPathProvider provider1(&profile_);
TestBlacklistPathProvider provider2(&profile_);
manager->RegisterBlacklistPathProvider(&provider1);
manager->RegisterBlacklistPathProvider(&provider2);
const Blacklist* blacklist1 = manager->GetCompiledBlacklist();
EXPECT_FALSE(blacklist1->findMatch(GURL("http://sample/annoying_ads/a.jpg")));
EXPECT_FALSE(blacklist1->findMatch(GURL("http://sample/other_ads/a.jpg")));
EXPECT_FALSE(blacklist1->findMatch(GURL("http://host/something.doc")));
provider1.AddPath(test_data_dir_.AppendASCII("annoying_ads.pbl"));
const Blacklist* blacklist2 = manager->GetCompiledBlacklist();
EXPECT_NE(blacklist1, blacklist2);
provider2.AddPath(test_data_dir_.AppendASCII("host.pbl"));
const Blacklist* blacklist3 = manager->GetCompiledBlacklist();
EXPECT_NE(blacklist2, blacklist3);
EXPECT_TRUE(blacklist3->findMatch(GURL("http://sample/annoying_ads/a.jpg")));
EXPECT_FALSE(blacklist3->findMatch(GURL("http://sample/other_ads/a.jpg")));
EXPECT_TRUE(blacklist3->findMatch(GURL("http://host/something.doc")));
provider1.AddPath(test_data_dir_.AppendASCII("other_ads.pbl"));
const Blacklist* blacklist4 = manager->GetCompiledBlacklist();
EXPECT_NE(blacklist3, blacklist4);
EXPECT_TRUE(blacklist4->findMatch(GURL("http://sample/annoying_ads/a.jpg")));
EXPECT_TRUE(blacklist4->findMatch(GURL("http://sample/other_ads/a.jpg")));
EXPECT_TRUE(blacklist4->findMatch(GURL("http://host/something.doc")));
manager->UnregisterBlacklistPathProvider(&provider1);
manager->UnregisterBlacklistPathProvider(&provider2);
}
} // namespace
<commit_msg>Fix memory leaks in BlacklistManagerTest.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/privacy_blacklist/blacklist_manager.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/scoped_temp_dir.h"
#include "base/thread.h"
#include "chrome/browser/privacy_blacklist/blacklist.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/testing_profile.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
class MyTestingProfile : public TestingProfile {
public:
MyTestingProfile() {
EXPECT_TRUE(temp_dir_.CreateUniqueTempDir());
path_ = temp_dir_.path();
}
private:
ScopedTempDir temp_dir_;
DISALLOW_COPY_AND_ASSIGN(MyTestingProfile);
};
class TestBlacklistPathProvider : public BlacklistPathProvider {
public:
explicit TestBlacklistPathProvider(Profile* profile) : profile_(profile) {
}
virtual std::vector<FilePath> GetBlacklistPaths() {
return paths_;
}
void AddPath(const FilePath& path) {
paths_.push_back(path);
NotificationService::current()->Notify(
NotificationType::PRIVACY_BLACKLIST_PATH_PROVIDER_UPDATED,
Source<Profile>(profile_),
Details<BlacklistPathProvider>(this));
}
private:
Profile* profile_;
std::vector<FilePath> paths_;
DISALLOW_COPY_AND_ASSIGN(TestBlacklistPathProvider);
};
class BlacklistManagerTest : public testing::Test {
public:
virtual void SetUp() {
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir_));
test_data_dir_ = test_data_dir_.AppendASCII("blacklist_samples");
}
virtual void TearDown() {
loop_.RunAllPending();
}
protected:
FilePath test_data_dir_;
MyTestingProfile profile_;
private:
MessageLoop loop_;
};
// Returns true if |blacklist| contains a match for |url|.
bool BlacklistHasMatch(const Blacklist* blacklist, const char* url) {
Blacklist::Match* match = blacklist->findMatch(GURL(url));
if (!match)
return false;
delete match;
return true;
}
TEST_F(BlacklistManagerTest, Basic) {
scoped_refptr<BlacklistManager> manager(
new BlacklistManager(&profile_, NULL));
const Blacklist* blacklist = manager->GetCompiledBlacklist();
// We should get an empty, but valid object.
ASSERT_TRUE(blacklist);
EXPECT_TRUE(blacklist->is_good());
// Repeated invocations of GetCompiledBlacklist should return the same object.
EXPECT_EQ(blacklist, manager->GetCompiledBlacklist());
}
TEST_F(BlacklistManagerTest, BlacklistPathProvider) {
scoped_refptr<BlacklistManager> manager(
new BlacklistManager(&profile_, NULL));
const Blacklist* blacklist1 = manager->GetCompiledBlacklist();
EXPECT_FALSE(BlacklistHasMatch(blacklist1,
"http://host/annoying_ads/ad.jpg"));
TestBlacklistPathProvider provider(&profile_);
manager->RegisterBlacklistPathProvider(&provider);
// Blacklist should not get recompiled.
EXPECT_EQ(blacklist1, manager->GetCompiledBlacklist());
provider.AddPath(test_data_dir_.AppendASCII("annoying_ads.pbl"));
const Blacklist* blacklist2 = manager->GetCompiledBlacklist();
// Added a real blacklist, the manager should recompile.
EXPECT_NE(blacklist1, blacklist2);
EXPECT_TRUE(BlacklistHasMatch(blacklist2, "http://host/annoying_ads/ad.jpg"));
manager->UnregisterBlacklistPathProvider(&provider);
// Just unregistering the provider doesn't remove the blacklist paths
// from the manager.
EXPECT_EQ(blacklist2, manager->GetCompiledBlacklist());
}
TEST_F(BlacklistManagerTest, RealThread) {
base::Thread backend_thread("backend_thread");
backend_thread.Start();
scoped_refptr<BlacklistManager> manager(
new BlacklistManager(&profile_, &backend_thread));
// Make sure all pending tasks run.
backend_thread.Stop();
backend_thread.Start();
const Blacklist* blacklist1 = manager->GetCompiledBlacklist();
EXPECT_FALSE(BlacklistHasMatch(blacklist1,
"http://host/annoying_ads/ad.jpg"));
TestBlacklistPathProvider provider(&profile_);
manager->RegisterBlacklistPathProvider(&provider);
// Make sure all pending tasks run.
backend_thread.Stop();
backend_thread.Start();
// Blacklist should not get recompiled.
EXPECT_EQ(blacklist1, manager->GetCompiledBlacklist());
provider.AddPath(test_data_dir_.AppendASCII("annoying_ads.pbl"));
// Make sure all pending tasks run.
backend_thread.Stop();
backend_thread.Start();
const Blacklist* blacklist2 = manager->GetCompiledBlacklist();
// Added a real blacklist, the manager should recompile.
EXPECT_NE(blacklist1, blacklist2);
EXPECT_TRUE(BlacklistHasMatch(blacklist2, "http://host/annoying_ads/ad.jpg"));
manager->UnregisterBlacklistPathProvider(&provider);
// Make sure all pending tasks run.
backend_thread.Stop();
backend_thread.Start();
// Just unregistering the provider doesn't remove the blacklist paths
// from the manager.
EXPECT_EQ(blacklist2, manager->GetCompiledBlacklist());
}
TEST_F(BlacklistManagerTest, CompiledBlacklistStaysOnDisk) {
{
scoped_refptr<BlacklistManager> manager(
new BlacklistManager(&profile_, NULL));
TestBlacklistPathProvider provider(&profile_);
manager->RegisterBlacklistPathProvider(&provider);
provider.AddPath(test_data_dir_.AppendASCII("annoying_ads.pbl"));
const Blacklist* blacklist = manager->GetCompiledBlacklist();
EXPECT_TRUE(BlacklistHasMatch(blacklist,
"http://host/annoying_ads/ad.jpg"));
manager->UnregisterBlacklistPathProvider(&provider);
}
{
scoped_refptr<BlacklistManager> manager(
new BlacklistManager(&profile_, NULL));
// Make sure we read the compiled blacklist from disk and don't even touch
// the paths providers.
const Blacklist* blacklist = manager->GetCompiledBlacklist();
EXPECT_TRUE(BlacklistHasMatch(blacklist,
"http://host/annoying_ads/ad.jpg"));
}
}
TEST_F(BlacklistManagerTest, BlacklistPathReadError) {
scoped_refptr<BlacklistManager> manager(
new BlacklistManager(&profile_, NULL));
TestBlacklistPathProvider provider(&profile_);
manager->RegisterBlacklistPathProvider(&provider);
FilePath bogus_path(test_data_dir_.AppendASCII("does_not_exist_randomness"));
ASSERT_FALSE(file_util::PathExists(bogus_path));
provider.AddPath(bogus_path);
const Blacklist* blacklist = manager->GetCompiledBlacklist();
// We should get an empty, but valid object.
ASSERT_TRUE(blacklist);
EXPECT_TRUE(blacklist->is_good());
manager->UnregisterBlacklistPathProvider(&provider);
}
TEST_F(BlacklistManagerTest, CompiledBlacklistReadError) {
FilePath compiled_blacklist_path;
{
scoped_refptr<BlacklistManager> manager(
new BlacklistManager(&profile_, NULL));
TestBlacklistPathProvider provider(&profile_);
manager->RegisterBlacklistPathProvider(&provider);
provider.AddPath(test_data_dir_.AppendASCII("annoying_ads.pbl"));
const Blacklist* blacklist = manager->GetCompiledBlacklist();
EXPECT_TRUE(BlacklistHasMatch(blacklist,
"http://host/annoying_ads/ad.jpg"));
manager->UnregisterBlacklistPathProvider(&provider);
compiled_blacklist_path = manager->compiled_blacklist_path();
}
ASSERT_TRUE(file_util::PathExists(compiled_blacklist_path));
ASSERT_TRUE(file_util::Delete(compiled_blacklist_path, false));
{
scoped_refptr<BlacklistManager> manager(
new BlacklistManager(&profile_, NULL));
// Now we don't have any providers, and no compiled blacklist file. We
// shouldn't match any URLs.
const Blacklist* blacklist = manager->GetCompiledBlacklist();
EXPECT_FALSE(BlacklistHasMatch(blacklist,
"http://host/annoying_ads/ad.jpg"));
}
}
TEST_F(BlacklistManagerTest, MultipleProviders) {
scoped_refptr<BlacklistManager> manager(
new BlacklistManager(&profile_, NULL));
TestBlacklistPathProvider provider1(&profile_);
TestBlacklistPathProvider provider2(&profile_);
manager->RegisterBlacklistPathProvider(&provider1);
manager->RegisterBlacklistPathProvider(&provider2);
const Blacklist* blacklist1 = manager->GetCompiledBlacklist();
EXPECT_FALSE(BlacklistHasMatch(blacklist1,
"http://sample/annoying_ads/a.jpg"));
EXPECT_FALSE(BlacklistHasMatch(blacklist1,
"http://sample/other_ads/a.jpg"));
EXPECT_FALSE(BlacklistHasMatch(blacklist1, "http://host/something.doc"));
provider1.AddPath(test_data_dir_.AppendASCII("annoying_ads.pbl"));
const Blacklist* blacklist2 = manager->GetCompiledBlacklist();
EXPECT_NE(blacklist1, blacklist2);
provider2.AddPath(test_data_dir_.AppendASCII("host.pbl"));
const Blacklist* blacklist3 = manager->GetCompiledBlacklist();
EXPECT_NE(blacklist2, blacklist3);
EXPECT_TRUE(BlacklistHasMatch(blacklist3,
"http://sample/annoying_ads/a.jpg"));
EXPECT_FALSE(BlacklistHasMatch(blacklist3, "http://sample/other_ads/a.jpg"));
EXPECT_TRUE(BlacklistHasMatch(blacklist3, "http://host/something.doc"));
provider1.AddPath(test_data_dir_.AppendASCII("other_ads.pbl"));
const Blacklist* blacklist4 = manager->GetCompiledBlacklist();
EXPECT_NE(blacklist3, blacklist4);
EXPECT_TRUE(BlacklistHasMatch(blacklist4,
"http://sample/annoying_ads/a.jpg"));
EXPECT_TRUE(BlacklistHasMatch(blacklist4, "http://sample/other_ads/a.jpg"));
EXPECT_TRUE(BlacklistHasMatch(blacklist4, "http://host/something.doc"));
manager->UnregisterBlacklistPathProvider(&provider1);
manager->UnregisterBlacklistPathProvider(&provider2);
}
} // namespace
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This test performs a series false positive checks using a list of URLs
// against a known set of SafeBrowsing data.
//
// It uses a normal SafeBrowsing database to create a bloom filter where it
// looks up all the URLs in the url file. A URL that has a prefix found in the
// bloom filter and found in the database is considered a hit: a valid lookup
// that will result in a gethash request. A URL that has a prefix found in the
// bloom filter but not in the database is a miss: a false positive lookup that
// will result in an unnecessary gethash request.
//
// By varying the size of the bloom filter and using a constant set of
// SafeBrowsing data, we can check a known set of URLs against the filter and
// determine the false positive rate.
//
// False positive calculation usage:
// $ ./perf_tests.exe --gtest_filter=SafeBrowsingBloomFilter.FalsePositives
// --filter-start=<integer>
// --filter-steps=<integer>
// --filter-verbose
//
// --filter-start: The filter multiplier to begin with. This represents the
// number of bits per prefix of memory to use in the filter.
// The default value is identical to the current SafeBrowsing
// database value.
// --filter-steps: The number of iterations to run, with each iteration
// increasing the filter multiplier by 1. The default value
// is 1.
// --filter-verbose: Used to print out the hit / miss results per URL.
// --filter-csv: The URL file contains information about the number of
// unique views (the popularity) of each URL. See the format
// description below.
//
//
// Hash compute time usage:
// $ ./perf_tests.exe --gtest_filter=SafeBrowsingBloomFilter.HashTime
// --filter-num-checks=<integer>
//
// --filter-num-checks: The number of hash look ups to perform on the bloom
// filter. The default is 10 million.
//
// Data files:
// chrome/test/data/safe_browsing/filter/database
// chrome/test/data/safe_browsing/filter/urls
//
// database: A normal SafeBrowsing database.
// urls: A text file containing a list of URLs, one per line. If the option
// --filter-csv is specified, the format of each line in the file is
// <url>,<weight> where weight is an integer indicating the number of
// unique views for the URL.
#include <fstream>
#include <vector>
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/rand_util.h"
#include "base/scoped_ptr.h"
#include "base/sha2.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/time.h"
#include "chrome/browser/safe_browsing/bloom_filter.h"
#include "chrome/browser/safe_browsing/safe_browsing_util.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/sqlite_compiled_statement.h"
#include "chrome/common/sqlite_utils.h"
#include "googleurl/src/gurl.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::Time;
using base::TimeDelta;
namespace {
// Ensures the SafeBrowsing database is closed properly.
class ScopedPerfDatabase {
public:
explicit ScopedPerfDatabase(sqlite3* db) : db_(db) {}
~ScopedPerfDatabase() {
sqlite3_close(db_);
}
private:
sqlite3* db_;
DISALLOW_COPY_AND_ASSIGN(ScopedPerfDatabase);
};
// Command line flags.
const wchar_t kFilterVerbose[] = L"filter-verbose";
const wchar_t kFilterStart[] = L"filter-start";
const wchar_t kFilterSteps[] = L"filter-steps";
const wchar_t kFilterCsv[] = L"filter-csv";
const wchar_t kFilterNumChecks[] = L"filter-num-checks";
// Number of hash checks to make during performance testing.
static const int kNumHashChecks = 10000000;
// Returns the path to the data used in this test, relative to the top of the
// source directory.
FilePath GetFullDataPath() {
FilePath full_path;
CHECK(PathService::Get(chrome::DIR_TEST_DATA, &full_path));
full_path = full_path.Append(FILE_PATH_LITERAL("safe_browsing"));
full_path = full_path.Append(FILE_PATH_LITERAL("filter"));
CHECK(file_util::PathExists(full_path));
return full_path;
}
// Constructs a bloom filter of the appropriate size from the provided prefixes.
void BuildBloomFilter(int size_multiplier,
const std::vector<SBPrefix>& prefixes,
BloomFilter** bloom_filter) {
// Create a BloomFilter with the specified size.
const int key_count = std::max(static_cast<int>(prefixes.size()),
BloomFilter::kBloomFilterMinSize);
const int filter_size = key_count * size_multiplier;
*bloom_filter = new BloomFilter(filter_size);
// Add the prefixes to it.
for (size_t i = 0; i < prefixes.size(); ++i)
(*bloom_filter)->Insert(prefixes[i]);
std::cout << "Bloom filter with prefixes: " << prefixes.size()
<< ", multiplier: " << size_multiplier
<< ", size (bytes): " << (*bloom_filter)->size()
<< std::endl;
}
// Reads the set of add prefixes contained in a SafeBrowsing database into a
// sorted array suitable for fast searching. This takes significantly less time
// to look up a given prefix than performing SQL queries.
bool ReadDatabase(const FilePath& path, std::vector<SBPrefix>* prefixes) {
FilePath database_file = path.Append(FILE_PATH_LITERAL("database"));
sqlite3* db = NULL;
if (sqlite_utils::OpenSqliteDb(database_file, &db) != SQLITE_OK) {
sqlite3_close(db);
return false;
}
ScopedPerfDatabase database(db);
scoped_ptr<SqliteStatementCache> sql_cache(new SqliteStatementCache(db));
// Get the number of items in the add_prefix table.
std::string sql = "SELECT COUNT(*) FROM add_prefix";
SQLITE_UNIQUE_STATEMENT(count_statement, *sql_cache, sql.c_str());
if (!count_statement.is_valid())
return false;
if (count_statement->step() != SQLITE_ROW)
return false;
const int count = count_statement->column_int(0);
// Load them into a prefix vector and sort
prefixes->reserve(count);
sql = "SELECT prefix FROM add_prefix";
SQLITE_UNIQUE_STATEMENT(prefix_statement, *sql_cache, sql.c_str());
if (!prefix_statement.is_valid())
return false;
while (prefix_statement->step() == SQLITE_ROW)
prefixes->push_back(prefix_statement->column_int(0));
DCHECK(static_cast<int>(prefixes->size()) == count);
sort(prefixes->begin(), prefixes->end());
return true;
}
// Generates all legal SafeBrowsing prefixes for the specified URL, and returns
// the set of Prefixes that exist in the bloom filter. The function returns the
// number of host + path combinations checked.
int GeneratePrefixHits(const std::string url,
BloomFilter* bloom_filter,
std::vector<SBPrefix>* prefixes) {
GURL url_check(url);
std::vector<std::string> hosts;
if (url_check.HostIsIPAddress()) {
hosts.push_back(url_check.host());
} else {
safe_browsing_util::GenerateHostsToCheck(url_check, &hosts);
}
std::vector<std::string> paths;
safe_browsing_util::GeneratePathsToCheck(url_check, &paths);
for (size_t i = 0; i < hosts.size(); ++i) {
for (size_t j = 0; j < paths.size(); ++j) {
SBPrefix prefix;
base::SHA256HashString(hosts[i] + paths[j], &prefix, sizeof(prefix));
if (bloom_filter->Exists(prefix))
prefixes->push_back(prefix);
}
}
return hosts.size() * paths.size();
}
// Binary search of sorted prefixes.
bool IsPrefixInDatabase(SBPrefix prefix,
const std::vector<SBPrefix>& prefixes) {
if (prefixes.empty())
return false;
int low = 0;
int high = prefixes.size() - 1;
while (low <= high) {
int mid = ((unsigned int)low + (unsigned int)high) >> 1;
SBPrefix prefix_mid = prefixes[mid];
if (prefix_mid == prefix)
return true;
if (prefix_mid < prefix)
low = mid + 1;
else
high = mid - 1;
}
return false;
}
// Construct a bloom filter with the given prefixes and multiplier, and test the
// false positive rate (misses) against a URL list.
void CalculateBloomFilterFalsePositives(
int size_multiplier,
const FilePath& data_dir,
const std::vector<SBPrefix>& prefix_list) {
BloomFilter* bloom_filter = NULL;
BuildBloomFilter(size_multiplier, prefix_list, &bloom_filter);
scoped_refptr<BloomFilter> scoped_filter(bloom_filter);
// Read in data file line at a time.
FilePath url_file = data_dir.Append(FILE_PATH_LITERAL("urls"));
std::ifstream url_stream(WideToASCII(url_file.ToWStringHack()).c_str());
// Keep track of stats
int hits = 0;
int misses = 0;
int weighted_hits = 0;
int weighted_misses = 0;
int url_count = 0;
int prefix_count = 0;
// Print out volumes of data (per URL hit and miss information).
bool verbose = CommandLine::ForCurrentProcess()->HasSwitch(kFilterVerbose);
bool use_weights = CommandLine::ForCurrentProcess()->HasSwitch(kFilterCsv);
std::string url;
while (std::getline(url_stream, url)) {
++url_count;
// Handle a format that contains URLs weighted by unique views.
int weight = 1;
if (use_weights) {
std::string::size_type pos = url.find_last_of(",");
if (pos != std::string::npos) {
base::StringToInt(std::string(url, pos + 1), &weight);
url = url.substr(0, pos);
}
}
// See if the URL is in the bloom filter.
std::vector<SBPrefix> prefixes;
prefix_count += GeneratePrefixHits(url, bloom_filter, &prefixes);
// See if the prefix is actually in the database (in-memory prefix list).
for (size_t i = 0; i < prefixes.size(); ++i) {
if (IsPrefixInDatabase(prefixes[i], prefix_list)) {
++hits;
weighted_hits += weight;
if (verbose) {
std::cout << "Hit for URL: " << url
<< " (prefix = " << prefixes[i] << ")"
<< std::endl;
}
} else {
++misses;
weighted_misses += weight;
if (verbose) {
std::cout << "Miss for URL: " << url
<< " (prefix = " << prefixes[i] << ")"
<< std::endl;
}
}
}
}
// Print out the results for this test.
std::cout << "URLs checked: " << url_count
<< ", prefix compares: " << prefix_count
<< ", hits: " << hits
<< ", misses: " << misses;
if (use_weights) {
std::cout << ", weighted hits: " << weighted_hits
<< ", weighted misses: " << weighted_misses;
}
std::cout << std::endl;
}
} // namespace
// This test can take several minutes to perform its calculations, so it should
// be disabled until you need to run it.
TEST(SafeBrowsingBloomFilter, FalsePositives) {
std::vector<SBPrefix> prefix_list;
FilePath data_dir = GetFullDataPath();
ASSERT_TRUE(ReadDatabase(data_dir, &prefix_list));
const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
int start = BloomFilter::kBloomFilterSizeRatio;
if (cmd_line.HasSwitch(kFilterStart)) {
ASSERT_TRUE(base::StringToInt(cmd_line.GetSwitchValueASCII(kFilterStart),
&start));
}
int steps = 1;
if (cmd_line.HasSwitch(kFilterSteps)) {
ASSERT_TRUE(base::StringToInt(cmd_line.GetSwitchValueASCII(kFilterSteps),
&steps));
}
int stop = start + steps;
for (int multiplier = start; multiplier < stop; ++multiplier)
CalculateBloomFilterFalsePositives(multiplier, data_dir, prefix_list);
}
// Computes the time required for performing a number of look ups in a bloom
// filter. This is useful for measuring the performance of new hash functions.
TEST(SafeBrowsingBloomFilter, HashTime) {
// Read the data from the database.
std::vector<SBPrefix> prefix_list;
FilePath data_dir = GetFullDataPath();
ASSERT_TRUE(ReadDatabase(data_dir, &prefix_list));
const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
int num_checks = kNumHashChecks;
if (cmd_line.HasSwitch(kFilterNumChecks)) {
ASSERT_TRUE(base::StringToInt(cmd_line.GetSwitchValue(kFilterNumChecks),
&num_checks));
}
// Populate the bloom filter and measure the time.
BloomFilter* bloom_filter = NULL;
Time populate_before = Time::Now();
BuildBloomFilter(BloomFilter::kBloomFilterSizeRatio,
prefix_list, &bloom_filter);
TimeDelta populate = Time::Now() - populate_before;
// Check a large number of random prefixes against the filter.
int hits = 0;
Time check_before = Time::Now();
for (int i = 0; i < num_checks; ++i) {
uint32 prefix = static_cast<uint32>(base::RandUint64());
if (bloom_filter->Exists(prefix))
++hits;
}
TimeDelta check = Time::Now() - check_before;
int64 time_per_insert = populate.InMicroseconds() /
static_cast<int>(prefix_list.size());
int64 time_per_check = check.InMicroseconds() / num_checks;
std::cout << "Time results for checks: " << num_checks
<< ", prefixes: " << prefix_list.size()
<< ", populate time (ms): " << populate.InMilliseconds()
<< ", check time (ms): " << check.InMilliseconds()
<< ", hits: " << hits
<< ", per-populate (us): " << time_per_insert
<< ", per-check (us): " << time_per_check
<< std::endl;
}
<commit_msg>Build fix.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This test performs a series false positive checks using a list of URLs
// against a known set of SafeBrowsing data.
//
// It uses a normal SafeBrowsing database to create a bloom filter where it
// looks up all the URLs in the url file. A URL that has a prefix found in the
// bloom filter and found in the database is considered a hit: a valid lookup
// that will result in a gethash request. A URL that has a prefix found in the
// bloom filter but not in the database is a miss: a false positive lookup that
// will result in an unnecessary gethash request.
//
// By varying the size of the bloom filter and using a constant set of
// SafeBrowsing data, we can check a known set of URLs against the filter and
// determine the false positive rate.
//
// False positive calculation usage:
// $ ./perf_tests.exe --gtest_filter=SafeBrowsingBloomFilter.FalsePositives
// --filter-start=<integer>
// --filter-steps=<integer>
// --filter-verbose
//
// --filter-start: The filter multiplier to begin with. This represents the
// number of bits per prefix of memory to use in the filter.
// The default value is identical to the current SafeBrowsing
// database value.
// --filter-steps: The number of iterations to run, with each iteration
// increasing the filter multiplier by 1. The default value
// is 1.
// --filter-verbose: Used to print out the hit / miss results per URL.
// --filter-csv: The URL file contains information about the number of
// unique views (the popularity) of each URL. See the format
// description below.
//
//
// Hash compute time usage:
// $ ./perf_tests.exe --gtest_filter=SafeBrowsingBloomFilter.HashTime
// --filter-num-checks=<integer>
//
// --filter-num-checks: The number of hash look ups to perform on the bloom
// filter. The default is 10 million.
//
// Data files:
// chrome/test/data/safe_browsing/filter/database
// chrome/test/data/safe_browsing/filter/urls
//
// database: A normal SafeBrowsing database.
// urls: A text file containing a list of URLs, one per line. If the option
// --filter-csv is specified, the format of each line in the file is
// <url>,<weight> where weight is an integer indicating the number of
// unique views for the URL.
#include <fstream>
#include <vector>
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/rand_util.h"
#include "base/scoped_ptr.h"
#include "base/sha2.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/time.h"
#include "chrome/browser/safe_browsing/bloom_filter.h"
#include "chrome/browser/safe_browsing/safe_browsing_util.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/sqlite_compiled_statement.h"
#include "chrome/common/sqlite_utils.h"
#include "googleurl/src/gurl.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::Time;
using base::TimeDelta;
namespace {
// Ensures the SafeBrowsing database is closed properly.
class ScopedPerfDatabase {
public:
explicit ScopedPerfDatabase(sqlite3* db) : db_(db) {}
~ScopedPerfDatabase() {
sqlite3_close(db_);
}
private:
sqlite3* db_;
DISALLOW_COPY_AND_ASSIGN(ScopedPerfDatabase);
};
// Command line flags.
const char kFilterVerbose[] = "filter-verbose";
const char kFilterStart[] = "filter-start";
const char kFilterSteps[] = "filter-steps";
const char kFilterCsv[] = "filter-csv";
const char kFilterNumChecks[] = "filter-num-checks";
// Number of hash checks to make during performance testing.
static const int kNumHashChecks = 10000000;
// Returns the path to the data used in this test, relative to the top of the
// source directory.
FilePath GetFullDataPath() {
FilePath full_path;
CHECK(PathService::Get(chrome::DIR_TEST_DATA, &full_path));
full_path = full_path.Append(FILE_PATH_LITERAL("safe_browsing"));
full_path = full_path.Append(FILE_PATH_LITERAL("filter"));
CHECK(file_util::PathExists(full_path));
return full_path;
}
// Constructs a bloom filter of the appropriate size from the provided prefixes.
void BuildBloomFilter(int size_multiplier,
const std::vector<SBPrefix>& prefixes,
BloomFilter** bloom_filter) {
// Create a BloomFilter with the specified size.
const int key_count = std::max(static_cast<int>(prefixes.size()),
BloomFilter::kBloomFilterMinSize);
const int filter_size = key_count * size_multiplier;
*bloom_filter = new BloomFilter(filter_size);
// Add the prefixes to it.
for (size_t i = 0; i < prefixes.size(); ++i)
(*bloom_filter)->Insert(prefixes[i]);
std::cout << "Bloom filter with prefixes: " << prefixes.size()
<< ", multiplier: " << size_multiplier
<< ", size (bytes): " << (*bloom_filter)->size()
<< std::endl;
}
// Reads the set of add prefixes contained in a SafeBrowsing database into a
// sorted array suitable for fast searching. This takes significantly less time
// to look up a given prefix than performing SQL queries.
bool ReadDatabase(const FilePath& path, std::vector<SBPrefix>* prefixes) {
FilePath database_file = path.Append(FILE_PATH_LITERAL("database"));
sqlite3* db = NULL;
if (sqlite_utils::OpenSqliteDb(database_file, &db) != SQLITE_OK) {
sqlite3_close(db);
return false;
}
ScopedPerfDatabase database(db);
scoped_ptr<SqliteStatementCache> sql_cache(new SqliteStatementCache(db));
// Get the number of items in the add_prefix table.
std::string sql = "SELECT COUNT(*) FROM add_prefix";
SQLITE_UNIQUE_STATEMENT(count_statement, *sql_cache, sql.c_str());
if (!count_statement.is_valid())
return false;
if (count_statement->step() != SQLITE_ROW)
return false;
const int count = count_statement->column_int(0);
// Load them into a prefix vector and sort
prefixes->reserve(count);
sql = "SELECT prefix FROM add_prefix";
SQLITE_UNIQUE_STATEMENT(prefix_statement, *sql_cache, sql.c_str());
if (!prefix_statement.is_valid())
return false;
while (prefix_statement->step() == SQLITE_ROW)
prefixes->push_back(prefix_statement->column_int(0));
DCHECK(static_cast<int>(prefixes->size()) == count);
sort(prefixes->begin(), prefixes->end());
return true;
}
// Generates all legal SafeBrowsing prefixes for the specified URL, and returns
// the set of Prefixes that exist in the bloom filter. The function returns the
// number of host + path combinations checked.
int GeneratePrefixHits(const std::string url,
BloomFilter* bloom_filter,
std::vector<SBPrefix>* prefixes) {
GURL url_check(url);
std::vector<std::string> hosts;
if (url_check.HostIsIPAddress()) {
hosts.push_back(url_check.host());
} else {
safe_browsing_util::GenerateHostsToCheck(url_check, &hosts);
}
std::vector<std::string> paths;
safe_browsing_util::GeneratePathsToCheck(url_check, &paths);
for (size_t i = 0; i < hosts.size(); ++i) {
for (size_t j = 0; j < paths.size(); ++j) {
SBPrefix prefix;
base::SHA256HashString(hosts[i] + paths[j], &prefix, sizeof(prefix));
if (bloom_filter->Exists(prefix))
prefixes->push_back(prefix);
}
}
return hosts.size() * paths.size();
}
// Binary search of sorted prefixes.
bool IsPrefixInDatabase(SBPrefix prefix,
const std::vector<SBPrefix>& prefixes) {
if (prefixes.empty())
return false;
int low = 0;
int high = prefixes.size() - 1;
while (low <= high) {
int mid = ((unsigned int)low + (unsigned int)high) >> 1;
SBPrefix prefix_mid = prefixes[mid];
if (prefix_mid == prefix)
return true;
if (prefix_mid < prefix)
low = mid + 1;
else
high = mid - 1;
}
return false;
}
// Construct a bloom filter with the given prefixes and multiplier, and test the
// false positive rate (misses) against a URL list.
void CalculateBloomFilterFalsePositives(
int size_multiplier,
const FilePath& data_dir,
const std::vector<SBPrefix>& prefix_list) {
BloomFilter* bloom_filter = NULL;
BuildBloomFilter(size_multiplier, prefix_list, &bloom_filter);
scoped_refptr<BloomFilter> scoped_filter(bloom_filter);
// Read in data file line at a time.
FilePath url_file = data_dir.Append(FILE_PATH_LITERAL("urls"));
std::ifstream url_stream(WideToASCII(url_file.ToWStringHack()).c_str());
// Keep track of stats
int hits = 0;
int misses = 0;
int weighted_hits = 0;
int weighted_misses = 0;
int url_count = 0;
int prefix_count = 0;
// Print out volumes of data (per URL hit and miss information).
bool verbose = CommandLine::ForCurrentProcess()->HasSwitch(kFilterVerbose);
bool use_weights = CommandLine::ForCurrentProcess()->HasSwitch(kFilterCsv);
std::string url;
while (std::getline(url_stream, url)) {
++url_count;
// Handle a format that contains URLs weighted by unique views.
int weight = 1;
if (use_weights) {
std::string::size_type pos = url.find_last_of(",");
if (pos != std::string::npos) {
base::StringToInt(std::string(url, pos + 1), &weight);
url = url.substr(0, pos);
}
}
// See if the URL is in the bloom filter.
std::vector<SBPrefix> prefixes;
prefix_count += GeneratePrefixHits(url, bloom_filter, &prefixes);
// See if the prefix is actually in the database (in-memory prefix list).
for (size_t i = 0; i < prefixes.size(); ++i) {
if (IsPrefixInDatabase(prefixes[i], prefix_list)) {
++hits;
weighted_hits += weight;
if (verbose) {
std::cout << "Hit for URL: " << url
<< " (prefix = " << prefixes[i] << ")"
<< std::endl;
}
} else {
++misses;
weighted_misses += weight;
if (verbose) {
std::cout << "Miss for URL: " << url
<< " (prefix = " << prefixes[i] << ")"
<< std::endl;
}
}
}
}
// Print out the results for this test.
std::cout << "URLs checked: " << url_count
<< ", prefix compares: " << prefix_count
<< ", hits: " << hits
<< ", misses: " << misses;
if (use_weights) {
std::cout << ", weighted hits: " << weighted_hits
<< ", weighted misses: " << weighted_misses;
}
std::cout << std::endl;
}
} // namespace
// This test can take several minutes to perform its calculations, so it should
// be disabled until you need to run it.
TEST(SafeBrowsingBloomFilter, FalsePositives) {
std::vector<SBPrefix> prefix_list;
FilePath data_dir = GetFullDataPath();
ASSERT_TRUE(ReadDatabase(data_dir, &prefix_list));
const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
int start = BloomFilter::kBloomFilterSizeRatio;
if (cmd_line.HasSwitch(kFilterStart)) {
ASSERT_TRUE(base::StringToInt(cmd_line.GetSwitchValueASCII(kFilterStart),
&start));
}
int steps = 1;
if (cmd_line.HasSwitch(kFilterSteps)) {
ASSERT_TRUE(base::StringToInt(cmd_line.GetSwitchValueASCII(kFilterSteps),
&steps));
}
int stop = start + steps;
for (int multiplier = start; multiplier < stop; ++multiplier)
CalculateBloomFilterFalsePositives(multiplier, data_dir, prefix_list);
}
// Computes the time required for performing a number of look ups in a bloom
// filter. This is useful for measuring the performance of new hash functions.
TEST(SafeBrowsingBloomFilter, HashTime) {
// Read the data from the database.
std::vector<SBPrefix> prefix_list;
FilePath data_dir = GetFullDataPath();
ASSERT_TRUE(ReadDatabase(data_dir, &prefix_list));
const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
int num_checks = kNumHashChecks;
if (cmd_line.HasSwitch(kFilterNumChecks)) {
ASSERT_TRUE(base::StringToInt(cmd_line.GetSwitchValue(kFilterNumChecks),
&num_checks));
}
// Populate the bloom filter and measure the time.
BloomFilter* bloom_filter = NULL;
Time populate_before = Time::Now();
BuildBloomFilter(BloomFilter::kBloomFilterSizeRatio,
prefix_list, &bloom_filter);
TimeDelta populate = Time::Now() - populate_before;
// Check a large number of random prefixes against the filter.
int hits = 0;
Time check_before = Time::Now();
for (int i = 0; i < num_checks; ++i) {
uint32 prefix = static_cast<uint32>(base::RandUint64());
if (bloom_filter->Exists(prefix))
++hits;
}
TimeDelta check = Time::Now() - check_before;
int64 time_per_insert = populate.InMicroseconds() /
static_cast<int>(prefix_list.size());
int64 time_per_check = check.InMicroseconds() / num_checks;
std::cout << "Time results for checks: " << num_checks
<< ", prefixes: " << prefix_list.size()
<< ", populate time (ms): " << populate.InMilliseconds()
<< ", check time (ms): " << check.InMilliseconds()
<< ", hits: " << hits
<< ", per-populate (us): " << time_per_insert
<< ", per-check (us): " << time_per_check
<< std::endl;
}
<|endoftext|>
|
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/extensions/extension_loader_handler.h"
#include "base/bind.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/memory/ref_counted.h"
#include "base/strings/string16.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/extensions/path_util.h"
#include "chrome/browser/extensions/unpacked_installer.h"
#include "chrome/browser/extensions/zipfile_installer.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/chrome_select_file_policy.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/user_metrics.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/file_highlighter.h"
#include "extensions/common/constants.h"
#include "extensions/common/extension.h"
#include "extensions/common/manifest_constants.h"
#include "grit/generated_resources.h"
#include "third_party/re2/re2/re2.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/shell_dialogs/select_file_dialog.h"
namespace extensions {
namespace {
// Read a file to a string and return.
std::string ReadFileToString(const base::FilePath& path) {
std::string data;
// This call can fail, but it doesn't matter for our purposes. If it fails,
// we simply return an empty string for the manifest, and ignore it.
base::ReadFileToString(path, &data);
return data;
}
} // namespace
class ExtensionLoaderHandler::FileHelper
: public ui::SelectFileDialog::Listener {
public:
explicit FileHelper(ExtensionLoaderHandler* loader_handler);
virtual ~FileHelper();
// Create a FileDialog for the user to select the unpacked extension
// directory.
void ChooseFile();
private:
// ui::SelectFileDialog::Listener implementation.
virtual void FileSelected(const base::FilePath& path,
int index,
void* params) OVERRIDE;
virtual void MultiFilesSelected(
const std::vector<base::FilePath>& files, void* params) OVERRIDE;
// The associated ExtensionLoaderHandler. Weak, but guaranteed to be alive,
// as it owns this object.
ExtensionLoaderHandler* loader_handler_;
// The dialog used to pick a directory when loading an unpacked extension.
scoped_refptr<ui::SelectFileDialog> load_extension_dialog_;
// The last selected directory, so we can start in the same spot.
base::FilePath last_unpacked_directory_;
// The title of the dialog.
base::string16 title_;
DISALLOW_COPY_AND_ASSIGN(FileHelper);
};
ExtensionLoaderHandler::FileHelper::FileHelper(
ExtensionLoaderHandler* loader_handler)
: loader_handler_(loader_handler),
title_(l10n_util::GetStringUTF16(IDS_EXTENSION_LOAD_FROM_DIRECTORY)) {
}
ExtensionLoaderHandler::FileHelper::~FileHelper() {
// There may be a pending file dialog; inform it the listener is destroyed so
// it doesn't try and call back.
if (load_extension_dialog_.get())
load_extension_dialog_->ListenerDestroyed();
}
void ExtensionLoaderHandler::FileHelper::ChooseFile() {
static const int kFileTypeIndex = 0; // No file type information to index.
static const ui::SelectFileDialog::Type kSelectType =
ui::SelectFileDialog::SELECT_FOLDER;
if (!load_extension_dialog_.get()) {
load_extension_dialog_ = ui::SelectFileDialog::Create(
this,
new ChromeSelectFilePolicy(
loader_handler_->web_ui()->GetWebContents()));
}
load_extension_dialog_->SelectFile(
kSelectType,
title_,
last_unpacked_directory_,
NULL,
kFileTypeIndex,
base::FilePath::StringType(),
loader_handler_->web_ui()->GetWebContents()->GetTopLevelNativeWindow(),
NULL);
content::RecordComputedAction("Options_LoadUnpackedExtension");
}
void ExtensionLoaderHandler::FileHelper::FileSelected(
const base::FilePath& path, int index, void* params) {
loader_handler_->LoadUnpackedExtensionImpl(path);
}
void ExtensionLoaderHandler::FileHelper::MultiFilesSelected(
const std::vector<base::FilePath>& files, void* params) {
NOTREACHED();
}
ExtensionLoaderHandler::ExtensionLoaderHandler(Profile* profile)
: profile_(profile),
file_helper_(new FileHelper(this)),
extension_error_reporter_observer_(this),
ui_ready_(false),
weak_ptr_factory_(this) {
DCHECK(profile_);
extension_error_reporter_observer_.Add(ExtensionErrorReporter::GetInstance());
}
ExtensionLoaderHandler::~ExtensionLoaderHandler() {
}
void ExtensionLoaderHandler::GetLocalizedValues(
content::WebUIDataSource* source) {
source->AddString(
"extensionLoadErrorHeading",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOAD_ERROR_HEADING));
source->AddString(
"extensionLoadErrorMessage",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOAD_ERROR_MESSAGE));
source->AddString(
"extensionLoadErrorRetry",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOAD_ERROR_RETRY));
source->AddString(
"extensionLoadErrorGiveUp",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOAD_ERROR_GIVE_UP));
source->AddString(
"extensionLoadCouldNotLoadManifest",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOAD_COULD_NOT_LOAD_MANIFEST));
source->AddString(
"extensionLoadAdditionalFailures",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOAD_ADDITIONAL_FAILURES));
}
void ExtensionLoaderHandler::RegisterMessages() {
// We observe WebContents in order to detect page refreshes, since notifying
// the frontend of load failures must be delayed until the page finishes
// loading. We never call Observe(NULL) because this object is constructed
// on page load and persists between refreshes.
content::WebContentsObserver::Observe(web_ui()->GetWebContents());
web_ui()->RegisterMessageCallback(
"extensionLoaderLoadUnpacked",
base::Bind(&ExtensionLoaderHandler::HandleLoadUnpacked,
weak_ptr_factory_.GetWeakPtr()));
web_ui()->RegisterMessageCallback(
"extensionLoaderRetry",
base::Bind(&ExtensionLoaderHandler::HandleRetry,
weak_ptr_factory_.GetWeakPtr()));
web_ui()->RegisterMessageCallback(
"extensionLoaderIgnoreFailure",
base::Bind(&ExtensionLoaderHandler::HandleIgnoreFailure,
weak_ptr_factory_.GetWeakPtr()));
web_ui()->RegisterMessageCallback(
"extensionLoaderDisplayFailures",
base::Bind(&ExtensionLoaderHandler::HandleDisplayFailures,
weak_ptr_factory_.GetWeakPtr()));
}
void ExtensionLoaderHandler::HandleLoadUnpacked(const base::ListValue* args) {
DCHECK(args->empty());
file_helper_->ChooseFile();
}
void ExtensionLoaderHandler::HandleRetry(const base::ListValue* args) {
DCHECK(args->empty());
const base::FilePath file_path = failed_paths_.back();
failed_paths_.pop_back();
LoadUnpackedExtensionImpl(file_path);
}
void ExtensionLoaderHandler::HandleIgnoreFailure(const base::ListValue* args) {
DCHECK(args->empty());
failed_paths_.pop_back();
}
void ExtensionLoaderHandler::HandleDisplayFailures(
const base::ListValue* args) {
DCHECK(args->empty());
ui_ready_ = true;
// Notify the frontend of any load failures that were triggered while the
// chrome://extensions page was loading.
if (!failures_.empty())
NotifyFrontendOfFailure();
}
void ExtensionLoaderHandler::LoadUnpackedExtensionImpl(
const base::FilePath& file_path) {
if (EndsWith(file_path.AsUTF16Unsafe(),
base::ASCIIToUTF16(".zip"),
false /* case insensitive */)) {
scoped_refptr<ZipFileInstaller> installer = ZipFileInstaller::Create(
ExtensionSystem::Get(profile_)->extension_service());
// We do our own error handling, so we don't want a load failure to trigger
// a dialog.
installer->set_be_noisy_on_failure(false);
installer->LoadFromZipFile(file_path);
} else {
scoped_refptr<UnpackedInstaller> installer = UnpackedInstaller::Create(
ExtensionSystem::Get(profile_)->extension_service());
// We do our own error handling, so we don't want a load failure to trigger
// a dialog.
installer->set_be_noisy_on_failure(false);
installer->Load(file_path);
}
}
void ExtensionLoaderHandler::OnLoadFailure(
content::BrowserContext* browser_context,
const base::FilePath& file_path,
const std::string& error) {
// Only show errors from our browser context.
if (web_ui()->GetWebContents()->GetBrowserContext() != browser_context)
return;
size_t line = 0u;
size_t column = 0u;
std::string regex =
base::StringPrintf("%s Line: (\\d+), column: (\\d+), .*",
manifest_errors::kManifestParseError);
// If this was a JSON parse error, we can highlight the exact line with the
// error. Otherwise, we should still display the manifest (for consistency,
// reference, and so that if we ever make this really fancy and add an editor,
// it's ready).
//
// This regex call can fail, but if it does, we just don't highlight anything.
re2::RE2::FullMatch(error, regex, &line, &column);
// This will read the manifest and call AddFailure with the read manifest
// contents.
base::PostTaskAndReplyWithResult(
content::BrowserThread::GetBlockingPool(),
FROM_HERE,
base::Bind(&ReadFileToString, file_path.Append(kManifestFilename)),
base::Bind(&ExtensionLoaderHandler::AddFailure,
weak_ptr_factory_.GetWeakPtr(),
file_path,
error,
line));
}
void ExtensionLoaderHandler::DidStartNavigationToPendingEntry(
const GURL& url,
content::NavigationController::ReloadType reload_type) {
// In the event of a page reload, we ensure that the frontend is not notified
// until the UI finishes loading, so we set |ui_ready_| to false. This is
// balanced in HandleDisplayFailures, which is called when the frontend is
// ready to receive failure notifications.
if (reload_type != content::NavigationController::NO_RELOAD)
ui_ready_ = false;
}
void ExtensionLoaderHandler::AddFailure(
const base::FilePath& file_path,
const std::string& error,
size_t line_number,
const std::string& manifest) {
failed_paths_.push_back(file_path);
base::FilePath prettified_path = path_util::PrettifyPath(file_path);
scoped_ptr<base::DictionaryValue> manifest_value(new base::DictionaryValue());
SourceHighlighter highlighter(manifest, line_number);
// If the line number is 0, this highlights no regions, but still adds the
// full manifest.
highlighter.SetHighlightedRegions(manifest_value.get());
scoped_ptr<base::DictionaryValue> failure(new base::DictionaryValue());
failure->Set("path",
new base::StringValue(prettified_path.LossyDisplayName()));
failure->Set("reason", new base::StringValue(base::UTF8ToUTF16(error)));
failure->Set("manifest", manifest_value.release());
failures_.Append(failure.release());
// Only notify the frontend if the frontend UI is ready.
if (ui_ready_)
NotifyFrontendOfFailure();
}
void ExtensionLoaderHandler::NotifyFrontendOfFailure() {
web_ui()->CallJavascriptFunction(
"extensions.ExtensionLoader.notifyLoadFailed",
failures_);
failures_.Clear();
}
} // namespace extensions
<commit_msg>Fix manifest.json errors on chrome://extensions<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/extensions/extension_loader_handler.h"
#include "base/bind.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/memory/ref_counted.h"
#include "base/strings/string16.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/extensions/path_util.h"
#include "chrome/browser/extensions/unpacked_installer.h"
#include "chrome/browser/extensions/zipfile_installer.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/chrome_select_file_policy.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/user_metrics.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/file_highlighter.h"
#include "extensions/common/constants.h"
#include "extensions/common/extension.h"
#include "extensions/common/manifest_constants.h"
#include "grit/generated_resources.h"
#include "third_party/re2/re2/re2.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/shell_dialogs/select_file_dialog.h"
namespace extensions {
namespace {
// Read a file to a string and return.
std::string ReadFileToString(const base::FilePath& path) {
std::string data;
// This call can fail, but it doesn't matter for our purposes. If it fails,
// we simply return an empty string for the manifest, and ignore it.
base::ReadFileToString(path, &data);
return data;
}
} // namespace
class ExtensionLoaderHandler::FileHelper
: public ui::SelectFileDialog::Listener {
public:
explicit FileHelper(ExtensionLoaderHandler* loader_handler);
virtual ~FileHelper();
// Create a FileDialog for the user to select the unpacked extension
// directory.
void ChooseFile();
private:
// ui::SelectFileDialog::Listener implementation.
virtual void FileSelected(const base::FilePath& path,
int index,
void* params) OVERRIDE;
virtual void MultiFilesSelected(
const std::vector<base::FilePath>& files, void* params) OVERRIDE;
// The associated ExtensionLoaderHandler. Weak, but guaranteed to be alive,
// as it owns this object.
ExtensionLoaderHandler* loader_handler_;
// The dialog used to pick a directory when loading an unpacked extension.
scoped_refptr<ui::SelectFileDialog> load_extension_dialog_;
// The last selected directory, so we can start in the same spot.
base::FilePath last_unpacked_directory_;
// The title of the dialog.
base::string16 title_;
DISALLOW_COPY_AND_ASSIGN(FileHelper);
};
ExtensionLoaderHandler::FileHelper::FileHelper(
ExtensionLoaderHandler* loader_handler)
: loader_handler_(loader_handler),
title_(l10n_util::GetStringUTF16(IDS_EXTENSION_LOAD_FROM_DIRECTORY)) {
}
ExtensionLoaderHandler::FileHelper::~FileHelper() {
// There may be a pending file dialog; inform it the listener is destroyed so
// it doesn't try and call back.
if (load_extension_dialog_.get())
load_extension_dialog_->ListenerDestroyed();
}
void ExtensionLoaderHandler::FileHelper::ChooseFile() {
static const int kFileTypeIndex = 0; // No file type information to index.
static const ui::SelectFileDialog::Type kSelectType =
ui::SelectFileDialog::SELECT_FOLDER;
if (!load_extension_dialog_.get()) {
load_extension_dialog_ = ui::SelectFileDialog::Create(
this,
new ChromeSelectFilePolicy(
loader_handler_->web_ui()->GetWebContents()));
}
load_extension_dialog_->SelectFile(
kSelectType,
title_,
last_unpacked_directory_,
NULL,
kFileTypeIndex,
base::FilePath::StringType(),
loader_handler_->web_ui()->GetWebContents()->GetTopLevelNativeWindow(),
NULL);
content::RecordComputedAction("Options_LoadUnpackedExtension");
}
void ExtensionLoaderHandler::FileHelper::FileSelected(
const base::FilePath& path, int index, void* params) {
loader_handler_->LoadUnpackedExtensionImpl(path);
}
void ExtensionLoaderHandler::FileHelper::MultiFilesSelected(
const std::vector<base::FilePath>& files, void* params) {
NOTREACHED();
}
ExtensionLoaderHandler::ExtensionLoaderHandler(Profile* profile)
: profile_(profile),
file_helper_(new FileHelper(this)),
extension_error_reporter_observer_(this),
ui_ready_(false),
weak_ptr_factory_(this) {
DCHECK(profile_);
extension_error_reporter_observer_.Add(ExtensionErrorReporter::GetInstance());
}
ExtensionLoaderHandler::~ExtensionLoaderHandler() {
}
void ExtensionLoaderHandler::GetLocalizedValues(
content::WebUIDataSource* source) {
source->AddString(
"extensionLoadErrorHeading",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOAD_ERROR_HEADING));
source->AddString(
"extensionLoadErrorMessage",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOAD_ERROR_MESSAGE));
source->AddString(
"extensionLoadErrorRetry",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOAD_ERROR_RETRY));
source->AddString(
"extensionLoadErrorGiveUp",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOAD_ERROR_GIVE_UP));
source->AddString(
"extensionLoadCouldNotLoadManifest",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOAD_COULD_NOT_LOAD_MANIFEST));
source->AddString(
"extensionLoadAdditionalFailures",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOAD_ADDITIONAL_FAILURES));
}
void ExtensionLoaderHandler::RegisterMessages() {
// We observe WebContents in order to detect page refreshes, since notifying
// the frontend of load failures must be delayed until the page finishes
// loading. We never call Observe(NULL) because this object is constructed
// on page load and persists between refreshes.
content::WebContentsObserver::Observe(web_ui()->GetWebContents());
web_ui()->RegisterMessageCallback(
"extensionLoaderLoadUnpacked",
base::Bind(&ExtensionLoaderHandler::HandleLoadUnpacked,
weak_ptr_factory_.GetWeakPtr()));
web_ui()->RegisterMessageCallback(
"extensionLoaderRetry",
base::Bind(&ExtensionLoaderHandler::HandleRetry,
weak_ptr_factory_.GetWeakPtr()));
web_ui()->RegisterMessageCallback(
"extensionLoaderIgnoreFailure",
base::Bind(&ExtensionLoaderHandler::HandleIgnoreFailure,
weak_ptr_factory_.GetWeakPtr()));
web_ui()->RegisterMessageCallback(
"extensionLoaderDisplayFailures",
base::Bind(&ExtensionLoaderHandler::HandleDisplayFailures,
weak_ptr_factory_.GetWeakPtr()));
}
void ExtensionLoaderHandler::HandleLoadUnpacked(const base::ListValue* args) {
DCHECK(args->empty());
file_helper_->ChooseFile();
}
void ExtensionLoaderHandler::HandleRetry(const base::ListValue* args) {
DCHECK(args->empty());
const base::FilePath file_path = failed_paths_.back();
failed_paths_.pop_back();
LoadUnpackedExtensionImpl(file_path);
}
void ExtensionLoaderHandler::HandleIgnoreFailure(const base::ListValue* args) {
DCHECK(args->empty());
failed_paths_.pop_back();
}
void ExtensionLoaderHandler::HandleDisplayFailures(
const base::ListValue* args) {
DCHECK(args->empty());
ui_ready_ = true;
// Notify the frontend of any load failures that were triggered while the
// chrome://extensions page was loading.
if (!failures_.empty())
NotifyFrontendOfFailure();
}
void ExtensionLoaderHandler::LoadUnpackedExtensionImpl(
const base::FilePath& file_path) {
if (EndsWith(file_path.AsUTF16Unsafe(),
base::ASCIIToUTF16(".zip"),
false /* case insensitive */)) {
scoped_refptr<ZipFileInstaller> installer = ZipFileInstaller::Create(
ExtensionSystem::Get(profile_)->extension_service());
// We do our own error handling, so we don't want a load failure to trigger
// a dialog.
installer->set_be_noisy_on_failure(false);
installer->LoadFromZipFile(file_path);
} else {
scoped_refptr<UnpackedInstaller> installer = UnpackedInstaller::Create(
ExtensionSystem::Get(profile_)->extension_service());
// We do our own error handling, so we don't want a load failure to trigger
// a dialog.
installer->set_be_noisy_on_failure(false);
installer->Load(file_path);
}
}
void ExtensionLoaderHandler::OnLoadFailure(
content::BrowserContext* browser_context,
const base::FilePath& file_path,
const std::string& error) {
// Only show errors from our browser context.
if (web_ui()->GetWebContents()->GetBrowserContext() != browser_context)
return;
size_t line = 0u;
size_t column = 0u;
std::string regex =
base::StringPrintf("%s Line: (\\d+), column: (\\d+), .*",
manifest_errors::kManifestParseError);
// If this was a JSON parse error, we can highlight the exact line with the
// error. Otherwise, we should still display the manifest (for consistency,
// reference, and so that if we ever make this really fancy and add an editor,
// it's ready).
//
// This regex call can fail, but if it does, we just don't highlight anything.
re2::RE2::FullMatch(error, regex, &line, &column);
// This will read the manifest and call AddFailure with the read manifest
// contents.
base::PostTaskAndReplyWithResult(
content::BrowserThread::GetBlockingPool(),
FROM_HERE,
base::Bind(&ReadFileToString, file_path.Append(kManifestFilename)),
base::Bind(&ExtensionLoaderHandler::AddFailure,
weak_ptr_factory_.GetWeakPtr(),
file_path,
error,
line));
}
void ExtensionLoaderHandler::DidStartNavigationToPendingEntry(
const GURL& url,
content::NavigationController::ReloadType reload_type) {
// In the event of a page reload, we ensure that the frontend is not notified
// until the UI finishes loading, so we set |ui_ready_| to false. This is
// balanced in HandleDisplayFailures, which is called when the frontend is
// ready to receive failure notifications.
if (reload_type != content::NavigationController::NO_RELOAD)
ui_ready_ = false;
}
void ExtensionLoaderHandler::AddFailure(
const base::FilePath& file_path,
const std::string& error,
size_t line_number,
const std::string& manifest) {
failed_paths_.push_back(file_path);
base::FilePath prettified_path = path_util::PrettifyPath(file_path);
scoped_ptr<base::DictionaryValue> manifest_value(new base::DictionaryValue());
SourceHighlighter highlighter(manifest, line_number);
// If the line number is 0, this highlights no regions, but still adds the
// full manifest.
highlighter.SetHighlightedRegions(manifest_value.get());
scoped_ptr<base::DictionaryValue> failure(new base::DictionaryValue());
failure->Set("path",
new base::StringValue(prettified_path.LossyDisplayName()));
failure->Set("error", new base::StringValue(base::UTF8ToUTF16(error)));
failure->Set("manifest", manifest_value.release());
failures_.Append(failure.release());
// Only notify the frontend if the frontend UI is ready.
if (ui_ready_)
NotifyFrontendOfFailure();
}
void ExtensionLoaderHandler::NotifyFrontendOfFailure() {
web_ui()->CallJavascriptFunction(
"extensions.ExtensionLoader.notifyLoadFailed",
failures_);
failures_.Clear();
}
} // namespace extensions
<|endoftext|>
|
<commit_before>/*
* GridMapVisualization.cpp
*
* Created on: Nov 19, 2013
* Author: Péter Fankhauser
* Institute: ETH Zurich, Autonomous Systems Lab
*/
#include "grid_map_visualization/GridMapVisualization.hpp"
#include <grid_map_core/GridMap.hpp>
#include <grid_map/GridMapRosConverter.hpp>
using namespace std;
using namespace ros;
namespace grid_map_visualization {
GridMapVisualization::GridMapVisualization(ros::NodeHandle& nodeHandle, const std::string& parameterName)
: nodeHandle_(nodeHandle),
visualizationsParameter_(parameterName),
factory_(nodeHandle_)
{
ROS_INFO("Grid map visualization node started.");
readParameters();
mapSubscriber_ = nodeHandle_.subscribe(mapTopic_, 1, &GridMapVisualization::callback, this);
initialize();
}
GridMapVisualization::~GridMapVisualization()
{
}
bool GridMapVisualization::readParameters()
{
nodeHandle_.param("grid_map_topic", mapTopic_, string("/grid_map"));
// Configure the visualizations from a configuration stored on the parameter server.
XmlRpc::XmlRpcValue config;
if (!nodeHandle_.getParam(visualizationsParameter_, config)) {
ROS_WARN(
"Could not load the visualizations configuration from parameter %s, are you sure it was pushed to the parameter server? Assuming that you meant to leave it empty.",
visualizationsParameter_.c_str());
return false;
}
// Verify proper naming and structure,
if (config.getType() != XmlRpc::XmlRpcValue::TypeArray) {
ROS_ERROR("%s: The visualization specification must be a list, but it is of XmlRpcType %d",
visualizationsParameter_.c_str(), config.getType());
ROS_ERROR("The XML passed in is formatted as follows:\n %s", config.toXml().c_str());
return false;
}
// Iterate over all visualizations (may be just one),
for (unsigned int i = 0; i < config.size(); ++i) {
if (config[i].getType() != XmlRpc::XmlRpcValue::TypeStruct) {
ROS_ERROR("%s: Visualizations must be specified as maps, but they are XmlRpcType:%d",
visualizationsParameter_.c_str(), config[i].getType());
return false;
} else if (!config[i].hasMember("type")) {
ROS_ERROR("%s: Could not add a visualization because no type was given",
visualizationsParameter_.c_str());
return false;
} else if (!config[i].hasMember("name")) {
ROS_ERROR("%s: Could not add a visualization because no name was given",
visualizationsParameter_.c_str());
return false;
} else {
//Check for name collisions within the list itself.
for (int j = i + 1; j < config.size(); ++j) {
if (config[j].getType() != XmlRpc::XmlRpcValue::TypeStruct) {
ROS_ERROR("%s: Visualizations must be specified as maps, but they are XmlRpcType:%d",
visualizationsParameter_.c_str(), config[j].getType());
return false;
}
if (!config[j].hasMember("name")
|| config[i]["name"].getType() != XmlRpc::XmlRpcValue::TypeString
|| config[j]["name"].getType() != XmlRpc::XmlRpcValue::TypeString) {
ROS_ERROR("%s: Visualizations names must be strings, but they are XmlRpcTypes:%d and %d",
visualizationsParameter_.c_str(), config[i].getType(), config[j].getType());
return false;
}
std::string namei = config[i]["name"];
std::string namej = config[j]["name"];
if (namei == namej) {
ROS_ERROR("%s: A visualization with the name '%s' already exists.",
visualizationsParameter_.c_str(), namei.c_str());
return false;
}
}
}
// Make sure the filter chain has a valid type.
if (!factory_.isValidType(config[i]["type"])) {
ROS_ERROR("Could not find visualization of type '%s'.", std::string(config[i]["type"]).c_str());
return false;
}
}
for (int i = 0; i < config.size(); ++i) {
std::string type = config[i]["type"];
std::string name = config[i]["name"];
auto visualization = factory_.getInstance(type, name);
visualization->readParameters(config[i]);
visualizations_.push_back(visualization);
ROS_INFO("%s: Configured visualization of type '%s' with name '%s'.", visualizationsParameter_.c_str(), type.c_str(), name.c_str());
}
return true;
}
bool GridMapVisualization::initialize()
{
for (auto& visualization : visualizations_) {
visualization->initialize();
}
ROS_INFO("Grid map visualization initialized.");
return true;
}
void GridMapVisualization::callback(const grid_map_msgs::GridMap& message)
{
ROS_DEBUG("Grid map visualization received a map (timestamp %f) for visualization.", message.info.header.stamp.toSec());
grid_map::GridMap map;
grid_map::GridMapRosConverter::fromMessage(message, map);
for (auto& visualization : visualizations_) {
visualization->visualize(map);
}
}
} /* namespace */
<commit_msg>Quick fix for bandwith problems.<commit_after>/*
* GridMapVisualization.cpp
*
* Created on: Nov 19, 2013
* Author: Péter Fankhauser
* Institute: ETH Zurich, Autonomous Systems Lab
*/
#include "grid_map_visualization/GridMapVisualization.hpp"
#include <grid_map_core/GridMap.hpp>
#include <grid_map/GridMapRosConverter.hpp>
using namespace std;
using namespace ros;
namespace grid_map_visualization {
GridMapVisualization::GridMapVisualization(ros::NodeHandle& nodeHandle, const std::string& parameterName)
: nodeHandle_(nodeHandle),
visualizationsParameter_(parameterName),
factory_(nodeHandle_)
{
ROS_INFO("Grid map visualization node started.");
readParameters();
mapSubscriber_ = nodeHandle_.subscribe(mapTopic_, 1, &GridMapVisualization::callback, this);
mapSubscriber_.shutdown();
initialize();
}
GridMapVisualization::~GridMapVisualization()
{
}
bool GridMapVisualization::readParameters()
{
nodeHandle_.param("grid_map_topic", mapTopic_, string("/grid_map"));
// Configure the visualizations from a configuration stored on the parameter server.
XmlRpc::XmlRpcValue config;
if (!nodeHandle_.getParam(visualizationsParameter_, config)) {
ROS_WARN(
"Could not load the visualizations configuration from parameter %s, are you sure it was pushed to the parameter server? Assuming that you meant to leave it empty.",
visualizationsParameter_.c_str());
return false;
}
// Verify proper naming and structure,
if (config.getType() != XmlRpc::XmlRpcValue::TypeArray) {
ROS_ERROR("%s: The visualization specification must be a list, but it is of XmlRpcType %d",
visualizationsParameter_.c_str(), config.getType());
ROS_ERROR("The XML passed in is formatted as follows:\n %s", config.toXml().c_str());
return false;
}
// Iterate over all visualizations (may be just one),
for (unsigned int i = 0; i < config.size(); ++i) {
if (config[i].getType() != XmlRpc::XmlRpcValue::TypeStruct) {
ROS_ERROR("%s: Visualizations must be specified as maps, but they are XmlRpcType:%d",
visualizationsParameter_.c_str(), config[i].getType());
return false;
} else if (!config[i].hasMember("type")) {
ROS_ERROR("%s: Could not add a visualization because no type was given",
visualizationsParameter_.c_str());
return false;
} else if (!config[i].hasMember("name")) {
ROS_ERROR("%s: Could not add a visualization because no name was given",
visualizationsParameter_.c_str());
return false;
} else {
//Check for name collisions within the list itself.
for (int j = i + 1; j < config.size(); ++j) {
if (config[j].getType() != XmlRpc::XmlRpcValue::TypeStruct) {
ROS_ERROR("%s: Visualizations must be specified as maps, but they are XmlRpcType:%d",
visualizationsParameter_.c_str(), config[j].getType());
return false;
}
if (!config[j].hasMember("name")
|| config[i]["name"].getType() != XmlRpc::XmlRpcValue::TypeString
|| config[j]["name"].getType() != XmlRpc::XmlRpcValue::TypeString) {
ROS_ERROR("%s: Visualizations names must be strings, but they are XmlRpcTypes:%d and %d",
visualizationsParameter_.c_str(), config[i].getType(), config[j].getType());
return false;
}
std::string namei = config[i]["name"];
std::string namej = config[j]["name"];
if (namei == namej) {
ROS_ERROR("%s: A visualization with the name '%s' already exists.",
visualizationsParameter_.c_str(), namei.c_str());
return false;
}
}
}
// Make sure the filter chain has a valid type.
if (!factory_.isValidType(config[i]["type"])) {
ROS_ERROR("Could not find visualization of type '%s'.", std::string(config[i]["type"]).c_str());
return false;
}
}
for (int i = 0; i < config.size(); ++i) {
std::string type = config[i]["type"];
std::string name = config[i]["name"];
auto visualization = factory_.getInstance(type, name);
visualization->readParameters(config[i]);
visualizations_.push_back(visualization);
ROS_INFO("%s: Configured visualization of type '%s' with name '%s'.", visualizationsParameter_.c_str(), type.c_str(), name.c_str());
}
return true;
}
bool GridMapVisualization::initialize()
{
for (auto& visualization : visualizations_) {
visualization->initialize();
}
ROS_INFO("Grid map visualization initialized.");
return true;
}
void GridMapVisualization::callback(const grid_map_msgs::GridMap& message)
{
ROS_DEBUG("Grid map visualization received a map (timestamp %f) for visualization.", message.info.header.stamp.toSec());
grid_map::GridMap map;
grid_map::GridMapRosConverter::fromMessage(message, map);
for (auto& visualization : visualizations_) {
visualization->visualize(map);
}
}
} /* namespace */
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: mergekeys.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: obo $ $Date: 2007-03-14 08:27:13 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_stoc.hxx"
#include <vector>
#include <com/sun/star/registry/XRegistryKey.hpp>
#include <com/sun/star/registry/MergeConflictException.hpp>
#include "mergekeys.hxx"
#define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) )
using namespace ::rtl;
using namespace ::osl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star;
namespace stoc_impreg
{
struct Link
{
OUString m_name;
OUString m_target;
inline Link( OUString const & name, OUString const & target )
: m_name( name )
, m_target( target )
{}
};
typedef ::std::vector< Link > t_links;
//==================================================================================================
static void mergeKeys(
Reference< registry::XRegistryKey > const & xDest,
Reference< registry::XRegistryKey > const & xSource,
t_links & links )
// throw( registry::InvalidRegistryException, registry::MergeConflictException, RuntimeException )
{
if (!xSource.is() || !xSource->isValid()) {
throw registry::InvalidRegistryException(
OUSTR("source key is null or invalid!"),
Reference<XInterface>() );
}
if (!xDest.is() || !xDest->isValid()) {
throw registry::InvalidRegistryException(
OUSTR("destination key is null or invalid!"),
Reference<XInterface>() );
}
// write value
switch (xSource->getValueType())
{
case registry::RegistryValueType_NOT_DEFINED:
break;
case registry::RegistryValueType_LONG:
xDest->setLongValue( xSource->getLongValue() );
break;
case registry::RegistryValueType_ASCII:
xDest->setAsciiValue( xSource->getAsciiValue() );
break;
case registry::RegistryValueType_STRING:
xDest->setStringValue( xSource->getStringValue() );
break;
case registry::RegistryValueType_BINARY:
xDest->setBinaryValue( xSource->getBinaryValue() );
break;
case registry::RegistryValueType_LONGLIST:
xDest->setLongListValue( xSource->getLongListValue() );
break;
case registry::RegistryValueType_ASCIILIST:
xDest->setAsciiListValue( xSource->getAsciiListValue() );
break;
case registry::RegistryValueType_STRINGLIST:
xDest->setStringListValue( xSource->getStringListValue() );
break;
default:
OSL_ASSERT(false);
break;
}
// sub keys
Sequence< OUString > sourceKeys( xSource->getKeyNames() );
OUString const * pSourceKeys = sourceKeys.getConstArray();
for ( sal_Int32 nPos = sourceKeys.getLength(); nPos--; )
{
// key name
OUString name( pSourceKeys[ nPos ] );
sal_Int32 nSlash = name.lastIndexOf( '/' );
if (nSlash >= 0)
{
name = name.copy( nSlash +1 );
}
if (xSource->getKeyType( name ) == registry::RegistryKeyType_KEY)
{
// try to open exisiting dest key or create new one
Reference< registry::XRegistryKey > xDestKey( xDest->createKey( name ) );
Reference< registry::XRegistryKey > xSourceKey( xSource->openKey( name ) );
mergeKeys( xDestKey, xSourceKey, links );
xSourceKey->closeKey();
xDestKey->closeKey();
}
else // link
{
// remove existing key
Reference< registry::XRegistryKey > xDestKey( xDest->openKey( name ) );
if (xDestKey.is() && xDestKey->isValid()) // something to remove
{
xDestKey->closeKey();
if (xDest->getKeyType( name ) == registry::RegistryKeyType_LINK)
{
xDest->deleteLink( name );
}
else
{
xDest->deleteKey( name );
}
}
links.push_back( Link(
pSourceKeys[ nPos ], // abs path
xSource->getResolvedName( name ) // abs resolved name
) );
}
}
}
//==================================================================================================
void mergeKeys(
Reference< registry::XRegistryKey > const & xDest,
Reference< registry::XRegistryKey > const & xSource )
// throw( registry::InvalidRegistryException, registry::MergeConflictException, RuntimeException )
{
if (!xDest.is() || !xDest->isValid()) {
throw registry::InvalidRegistryException(
OUSTR("destination key is null or invalid!"),
Reference<XInterface>() );
}
if (xDest->isReadOnly())
{
throw registry::InvalidRegistryException(
OUString( RTL_CONSTASCII_USTRINGPARAM(
"destination registry is read-only! cannot merge!") ),
Reference< XInterface >() );
}
t_links links;
links.reserve( 16 );
mergeKeys( xDest, xSource, links );
for ( size_t nPos = links.size(); nPos--; )
{
Link const & r = links[ nPos ];
OSL_VERIFY( xDest->createLink( r.m_name, r.m_target ) );
}
}
}
<commit_msg>INTEGRATION: CWS changefileheader (1.7.26); FILE MERGED 2008/03/31 07:26:08 rt 1.7.26.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: mergekeys.cxx,v $
* $Revision: 1.8 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_stoc.hxx"
#include <vector>
#include <com/sun/star/registry/XRegistryKey.hpp>
#include <com/sun/star/registry/MergeConflictException.hpp>
#include "mergekeys.hxx"
#define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) )
using namespace ::rtl;
using namespace ::osl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star;
namespace stoc_impreg
{
struct Link
{
OUString m_name;
OUString m_target;
inline Link( OUString const & name, OUString const & target )
: m_name( name )
, m_target( target )
{}
};
typedef ::std::vector< Link > t_links;
//==================================================================================================
static void mergeKeys(
Reference< registry::XRegistryKey > const & xDest,
Reference< registry::XRegistryKey > const & xSource,
t_links & links )
// throw( registry::InvalidRegistryException, registry::MergeConflictException, RuntimeException )
{
if (!xSource.is() || !xSource->isValid()) {
throw registry::InvalidRegistryException(
OUSTR("source key is null or invalid!"),
Reference<XInterface>() );
}
if (!xDest.is() || !xDest->isValid()) {
throw registry::InvalidRegistryException(
OUSTR("destination key is null or invalid!"),
Reference<XInterface>() );
}
// write value
switch (xSource->getValueType())
{
case registry::RegistryValueType_NOT_DEFINED:
break;
case registry::RegistryValueType_LONG:
xDest->setLongValue( xSource->getLongValue() );
break;
case registry::RegistryValueType_ASCII:
xDest->setAsciiValue( xSource->getAsciiValue() );
break;
case registry::RegistryValueType_STRING:
xDest->setStringValue( xSource->getStringValue() );
break;
case registry::RegistryValueType_BINARY:
xDest->setBinaryValue( xSource->getBinaryValue() );
break;
case registry::RegistryValueType_LONGLIST:
xDest->setLongListValue( xSource->getLongListValue() );
break;
case registry::RegistryValueType_ASCIILIST:
xDest->setAsciiListValue( xSource->getAsciiListValue() );
break;
case registry::RegistryValueType_STRINGLIST:
xDest->setStringListValue( xSource->getStringListValue() );
break;
default:
OSL_ASSERT(false);
break;
}
// sub keys
Sequence< OUString > sourceKeys( xSource->getKeyNames() );
OUString const * pSourceKeys = sourceKeys.getConstArray();
for ( sal_Int32 nPos = sourceKeys.getLength(); nPos--; )
{
// key name
OUString name( pSourceKeys[ nPos ] );
sal_Int32 nSlash = name.lastIndexOf( '/' );
if (nSlash >= 0)
{
name = name.copy( nSlash +1 );
}
if (xSource->getKeyType( name ) == registry::RegistryKeyType_KEY)
{
// try to open exisiting dest key or create new one
Reference< registry::XRegistryKey > xDestKey( xDest->createKey( name ) );
Reference< registry::XRegistryKey > xSourceKey( xSource->openKey( name ) );
mergeKeys( xDestKey, xSourceKey, links );
xSourceKey->closeKey();
xDestKey->closeKey();
}
else // link
{
// remove existing key
Reference< registry::XRegistryKey > xDestKey( xDest->openKey( name ) );
if (xDestKey.is() && xDestKey->isValid()) // something to remove
{
xDestKey->closeKey();
if (xDest->getKeyType( name ) == registry::RegistryKeyType_LINK)
{
xDest->deleteLink( name );
}
else
{
xDest->deleteKey( name );
}
}
links.push_back( Link(
pSourceKeys[ nPos ], // abs path
xSource->getResolvedName( name ) // abs resolved name
) );
}
}
}
//==================================================================================================
void mergeKeys(
Reference< registry::XRegistryKey > const & xDest,
Reference< registry::XRegistryKey > const & xSource )
// throw( registry::InvalidRegistryException, registry::MergeConflictException, RuntimeException )
{
if (!xDest.is() || !xDest->isValid()) {
throw registry::InvalidRegistryException(
OUSTR("destination key is null or invalid!"),
Reference<XInterface>() );
}
if (xDest->isReadOnly())
{
throw registry::InvalidRegistryException(
OUString( RTL_CONSTASCII_USTRINGPARAM(
"destination registry is read-only! cannot merge!") ),
Reference< XInterface >() );
}
t_links links;
links.reserve( 16 );
mergeKeys( xDest, xSource, links );
for ( size_t nPos = links.size(); nPos--; )
{
Link const & r = links[ nPos ];
OSL_VERIFY( xDest->createLink( r.m_name, r.m_target ) );
}
}
}
<|endoftext|>
|
<commit_before>#include "Counter.h"
#include <iostream>
void Stack::push(int value) // adds elements to the stack
{
Stack *addEl = new Stack;
next = addEl->head;
addEl->value = value;
if (head != NULL)
{
tail->next = addEl;
tail = addEl;
}
else
{
head = tail = addEl;
}
}
void Stack::pop() // deletes the top elements from the array
{
int count = 0;
Stack *temp = head;
while (temp != tail)
{
temp = temp->next;
count++;
}
delete temp;
temp = head;
for (int i = 1; i < count;i++)
{
temp = temp->next;
}
tail = temp;
}
<commit_msg>Delete Counter.cpp<commit_after><|endoftext|>
|
<commit_before>/*
* MIT License
*
* Copyright (c) 2016-2019 xiongziliang <771730766@qq.com>
*
* This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit).
*
* 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 "Factory.h"
#include "H264Rtmp.h"
#include "AACRtmp.h"
#include "H264Rtp.h"
#include "AACRtp.h"
#include "H265Rtp.h"
namespace mediakit{
Track::Ptr Factory::getTrackBySdp(const SdpTrack::Ptr &track) {
if (strcasecmp(track->_codec.data(), "mpeg4-generic") == 0) {
string aac_cfg_str = FindField(track->_fmtp.data(), "config=", nullptr);
if (aac_cfg_str.empty()) {
aac_cfg_str = FindField(track->_fmtp.data(), "config=", ";");
}
if (aac_cfg_str.empty()) {
//延后获取adts头
return std::make_shared<AACTrack>();
}
string aac_cfg;
unsigned int cfg1;
sscanf(aac_cfg_str.substr(0, 2).data(), "%02X", &cfg1);
cfg1 &= 0x00FF;
aac_cfg.push_back(cfg1);
unsigned int cfg2;
sscanf(aac_cfg_str.substr(2, 2).data(), "%02X", &cfg2);
cfg2 &= 0x00FF;
aac_cfg.push_back(cfg2);
return std::make_shared<AACTrack>(aac_cfg);
}
if (strcasecmp(track->_codec.data(), "h264") == 0) {
string sps_pps = FindField(track->_fmtp.data(), "sprop-parameter-sets=", nullptr);
if(sps_pps.empty()){
return std::make_shared<H264Track>();
}
string base64_SPS = FindField(sps_pps.data(), NULL, ",");
string base64_PPS = FindField(sps_pps.data(), ",", NULL);
if(base64_PPS.back() == ';'){
base64_PPS.pop_back();
}
auto sps = decodeBase64(base64_SPS);
auto pps = decodeBase64(base64_PPS);
return std::make_shared<H264Track>(sps,pps,0,0);
}
if (strcasecmp(track->_codec.data(), "h265") == 0) {
//a=fmtp:96 sprop-sps=QgEBAWAAAAMAsAAAAwAAAwBdoAKAgC0WNrkky/AIAAADAAgAAAMBlQg=; sprop-pps=RAHA8vA8kAA=
int pt, id;
char sprop_vps[128] = {0},sprop_sps[128] = {0},sprop_pps[128] = {0};
if (5 == sscanf(track->_fmtp.data(), "%d profile-id=%d; sprop-sps=%127[^;]; sprop-pps=%127[^;]; sprop-vps=%127[^;]", &pt, &id, sprop_sps,sprop_pps, sprop_vps)) {
auto vps = decodeBase64(sprop_vps);
auto sps = decodeBase64(sprop_sps);
auto pps = decodeBase64(sprop_pps);
return std::make_shared<H265Track>(vps,sps,pps,0,0,0);
}
if (4 == sscanf(track->_fmtp.data(), "%d sprop-vps=%127[^;]; sprop-sps=%127[^;]; sprop-pps=%127[^;]", &pt, sprop_vps,sprop_sps, sprop_pps)) {
auto vps = decodeBase64(sprop_vps);
auto sps = decodeBase64(sprop_sps);
auto pps = decodeBase64(sprop_pps);
return std::make_shared<H265Track>(vps,sps,pps,0,0,0);
}
if (3 == sscanf(track->_fmtp.data(), "%d sprop-sps=%127[^;]; sprop-pps=%127[^;]", &pt,sprop_sps, sprop_pps)) {
auto sps = decodeBase64(sprop_sps);
auto pps = decodeBase64(sprop_pps);
return std::make_shared<H265Track>("",sps,pps,0,0,0);
}
return std::make_shared<H265Track>();
}
WarnL << "暂不支持该sdp:" << track->_codec << " " << track->_fmtp;
return nullptr;
}
Track::Ptr Factory::getTrackByCodecId(CodecId codecId) {
switch (codecId){
case CodecH264:{
return std::make_shared<H264Track>();
}
case CodecH265:{
return std::make_shared<H265Track>();
}
case CodecAAC:{
return std::make_shared<AACTrack>();
}
default:
WarnL << "暂不支持该CodecId:" << codecId;
return nullptr;
}
}
RtpCodec::Ptr Factory::getRtpEncoderBySdp(const Sdp::Ptr &sdp) {
GET_CONFIG(uint32_t,audio_mtu,Rtp::kAudioMtuSize);
GET_CONFIG(uint32_t,video_mtu,Rtp::kVideoMtuSize);
// ssrc不冲突即可,可以为任意的32位整形
static atomic<uint32_t> s_ssrc(0);
uint32_t ssrc = s_ssrc++;
if(!ssrc){
//ssrc不能为0
ssrc = 1;
}
if(sdp->getTrackType() == TrackVideo){
//视频的ssrc是偶数,方便调试
ssrc = 2 * ssrc;
}else{
//音频ssrc是奇数
ssrc = 2 * ssrc + 1;
}
auto mtu = (sdp->getTrackType() == TrackVideo ? video_mtu : audio_mtu);
auto sample_rate = sdp->getSampleRate();
auto pt = sdp->getPlayloadType();
auto interleaved = sdp->getTrackType() * 2;
auto codec_id = sdp->getCodecId();
switch (codec_id){
case CodecH264:
return std::make_shared<H264RtpEncoder>(ssrc,mtu,sample_rate,pt,interleaved);
case CodecH265:
return std::make_shared<H265RtpEncoder>(ssrc,mtu,sample_rate,pt,interleaved);
case CodecAAC:
return std::make_shared<AACRtpEncoder>(ssrc,mtu,sample_rate,pt,interleaved);
default:
WarnL << "暂不支持该CodecId:" << codec_id;
return nullptr;
}
}
RtpCodec::Ptr Factory::getRtpDecoderByTrack(const Track::Ptr &track) {
switch (track->getCodecId()){
case CodecH264:
return std::make_shared<H264RtpDecoder>();
case CodecH265:
return std::make_shared<H265RtpDecoder>();
case CodecAAC:
return std::make_shared<AACRtpDecoder>(track->clone());
default:
WarnL << "暂不支持该CodecId:" << track->getCodecId();
return nullptr;
}
}
/////////////////////////////rtmp相关///////////////////////////////////////////
Track::Ptr Factory::getTrackByAmf(const AMFValue &amf) {
CodecId codecId = getCodecIdByAmf(amf);
if(codecId == CodecInvalid){
return nullptr;
}
return getTrackByCodecId(codecId);
}
CodecId Factory::getCodecIdByAmf(const AMFValue &val){
if (val.type() == AMF_STRING){
auto str = val.as_string();
if(str == "avc1"){
return CodecH264;
}
if(str == "mp4a"){
return CodecAAC;
}
WarnL << "暂不支持该Amf:" << str;
return CodecInvalid;
}
if (val.type() != AMF_NULL){
auto type_id = val.as_integer();
switch (type_id){
case 7:{
return CodecH264;
}
case 10:{
return CodecAAC;
}
default:
WarnL << "暂不支持该Amf:" << type_id;
return CodecInvalid;
}
}else{
WarnL << "Metedata不存在相应的Track";
}
return CodecInvalid;
}
RtmpCodec::Ptr Factory::getRtmpCodecByTrack(const Track::Ptr &track) {
switch (track->getCodecId()){
case CodecH264:
return std::make_shared<H264RtmpEncoder>(track);
case CodecAAC:
return std::make_shared<AACRtmpEncoder>(track);
default:
WarnL << "暂不支持该CodecId:" << track->getCodecId();
return nullptr;
}
}
AMFValue Factory::getAmfByCodecId(CodecId codecId) {
switch (codecId){
case CodecAAC:{
return AMFValue("mp4a");
}
case CodecH264:{
return AMFValue("avc1");
}
default:
return AMFValue(AMF_NULL);
}
}
}//namespace mediakit
<commit_msg>完善对H265的sdp兼容性<commit_after>/*
* MIT License
*
* Copyright (c) 2016-2019 xiongziliang <771730766@qq.com>
*
* This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit).
*
* 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 "Factory.h"
#include "H264Rtmp.h"
#include "AACRtmp.h"
#include "H264Rtp.h"
#include "AACRtp.h"
#include "H265Rtp.h"
#include "Common/Parser.h"
namespace mediakit{
Track::Ptr Factory::getTrackBySdp(const SdpTrack::Ptr &track) {
if (strcasecmp(track->_codec.data(), "mpeg4-generic") == 0) {
string aac_cfg_str = FindField(track->_fmtp.data(), "config=", nullptr);
if (aac_cfg_str.empty()) {
aac_cfg_str = FindField(track->_fmtp.data(), "config=", ";");
}
if (aac_cfg_str.empty()) {
//延后获取adts头
return std::make_shared<AACTrack>();
}
string aac_cfg;
unsigned int cfg1;
sscanf(aac_cfg_str.substr(0, 2).data(), "%02X", &cfg1);
cfg1 &= 0x00FF;
aac_cfg.push_back(cfg1);
unsigned int cfg2;
sscanf(aac_cfg_str.substr(2, 2).data(), "%02X", &cfg2);
cfg2 &= 0x00FF;
aac_cfg.push_back(cfg2);
return std::make_shared<AACTrack>(aac_cfg);
}
if (strcasecmp(track->_codec.data(), "h264") == 0) {
string sps_pps = FindField(track->_fmtp.data(), "sprop-parameter-sets=", nullptr);
if(sps_pps.empty()){
return std::make_shared<H264Track>();
}
string base64_SPS = FindField(sps_pps.data(), NULL, ",");
string base64_PPS = FindField(sps_pps.data(), ",", NULL);
if(base64_PPS.back() == ';'){
base64_PPS.pop_back();
}
auto sps = decodeBase64(base64_SPS);
auto pps = decodeBase64(base64_PPS);
return std::make_shared<H264Track>(sps,pps,0,0);
}
if (strcasecmp(track->_codec.data(), "h265") == 0) {
//a=fmtp:96 sprop-sps=QgEBAWAAAAMAsAAAAwAAAwBdoAKAgC0WNrkky/AIAAADAAgAAAMBlQg=; sprop-pps=RAHA8vA8kAA=
auto map = Parser::parseArgs(track->_fmtp," ","=");
for(auto &pr : map){
trim(pr.second," ;");
}
auto vps = decodeBase64(map["sprop-vps"]);
auto sps = decodeBase64(map["sprop-sps"]);
auto pps = decodeBase64(map["sprop-pps"]);
return std::make_shared<H265Track>(vps,sps,pps,0,0,0);
}
WarnL << "暂不支持该sdp:" << track->_codec << " " << track->_fmtp;
return nullptr;
}
Track::Ptr Factory::getTrackByCodecId(CodecId codecId) {
switch (codecId){
case CodecH264:{
return std::make_shared<H264Track>();
}
case CodecH265:{
return std::make_shared<H265Track>();
}
case CodecAAC:{
return std::make_shared<AACTrack>();
}
default:
WarnL << "暂不支持该CodecId:" << codecId;
return nullptr;
}
}
RtpCodec::Ptr Factory::getRtpEncoderBySdp(const Sdp::Ptr &sdp) {
GET_CONFIG(uint32_t,audio_mtu,Rtp::kAudioMtuSize);
GET_CONFIG(uint32_t,video_mtu,Rtp::kVideoMtuSize);
// ssrc不冲突即可,可以为任意的32位整形
static atomic<uint32_t> s_ssrc(0);
uint32_t ssrc = s_ssrc++;
if(!ssrc){
//ssrc不能为0
ssrc = 1;
}
if(sdp->getTrackType() == TrackVideo){
//视频的ssrc是偶数,方便调试
ssrc = 2 * ssrc;
}else{
//音频ssrc是奇数
ssrc = 2 * ssrc + 1;
}
auto mtu = (sdp->getTrackType() == TrackVideo ? video_mtu : audio_mtu);
auto sample_rate = sdp->getSampleRate();
auto pt = sdp->getPlayloadType();
auto interleaved = sdp->getTrackType() * 2;
auto codec_id = sdp->getCodecId();
switch (codec_id){
case CodecH264:
return std::make_shared<H264RtpEncoder>(ssrc,mtu,sample_rate,pt,interleaved);
case CodecH265:
return std::make_shared<H265RtpEncoder>(ssrc,mtu,sample_rate,pt,interleaved);
case CodecAAC:
return std::make_shared<AACRtpEncoder>(ssrc,mtu,sample_rate,pt,interleaved);
default:
WarnL << "暂不支持该CodecId:" << codec_id;
return nullptr;
}
}
RtpCodec::Ptr Factory::getRtpDecoderByTrack(const Track::Ptr &track) {
switch (track->getCodecId()){
case CodecH264:
return std::make_shared<H264RtpDecoder>();
case CodecH265:
return std::make_shared<H265RtpDecoder>();
case CodecAAC:
return std::make_shared<AACRtpDecoder>(track->clone());
default:
WarnL << "暂不支持该CodecId:" << track->getCodecId();
return nullptr;
}
}
/////////////////////////////rtmp相关///////////////////////////////////////////
Track::Ptr Factory::getTrackByAmf(const AMFValue &amf) {
CodecId codecId = getCodecIdByAmf(amf);
if(codecId == CodecInvalid){
return nullptr;
}
return getTrackByCodecId(codecId);
}
CodecId Factory::getCodecIdByAmf(const AMFValue &val){
if (val.type() == AMF_STRING){
auto str = val.as_string();
if(str == "avc1"){
return CodecH264;
}
if(str == "mp4a"){
return CodecAAC;
}
WarnL << "暂不支持该Amf:" << str;
return CodecInvalid;
}
if (val.type() != AMF_NULL){
auto type_id = val.as_integer();
switch (type_id){
case 7:{
return CodecH264;
}
case 10:{
return CodecAAC;
}
default:
WarnL << "暂不支持该Amf:" << type_id;
return CodecInvalid;
}
}else{
WarnL << "Metedata不存在相应的Track";
}
return CodecInvalid;
}
RtmpCodec::Ptr Factory::getRtmpCodecByTrack(const Track::Ptr &track) {
switch (track->getCodecId()){
case CodecH264:
return std::make_shared<H264RtmpEncoder>(track);
case CodecAAC:
return std::make_shared<AACRtmpEncoder>(track);
default:
WarnL << "暂不支持该CodecId:" << track->getCodecId();
return nullptr;
}
}
AMFValue Factory::getAmfByCodecId(CodecId codecId) {
switch (codecId){
case CodecAAC:{
return AMFValue("mp4a");
}
case CodecH264:{
return AMFValue("avc1");
}
default:
return AMFValue(AMF_NULL);
}
}
}//namespace mediakit
<|endoftext|>
|
<commit_before>//=================================================================================================
// Copyright 2014-2015 Dirk Lemstra <https://graphicsmagick.codeplex.com/>
//
// Licensed under the ImageMagick License (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.imagemagick.org/script/license.php
//
// 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 "Stdafx.h"
using namespace System::Runtime::InteropServices;
namespace GraphicsMagick
{
//==============================================================================================
template <typename TStorageType>
TStorageType* Marshaller::MarshalStorageType(array<Byte>^ bytes)
{
int length = bytes->Length / sizeof(TStorageType);
TStorageType* unmanagedValue = new TStorageType[length];
Marshal::Copy(bytes, 0, IntPtr(unmanagedValue), bytes->Length);
return unmanagedValue;
}
//==============================================================================================
unsigned char* Marshaller::Marshal(array<Byte>^ bytes)
{
if (bytes == nullptr || bytes->Length == 0)
return NULL;
unsigned char* unmanagedValue = new unsigned char[bytes->Length];
Marshal::Copy(bytes, 0, IntPtr(unmanagedValue), bytes->Length);
return unmanagedValue;
}
//==============================================================================================
void Marshaller::Marshal(array<Byte>^ bytes, Magick::Blob* value)
{
if (bytes == nullptr || bytes->Length == 0)
return;
char* unmanagedValue = new char[bytes->Length];
Marshal::Copy(bytes, 0, IntPtr(unmanagedValue), bytes->Length);
value->update(unmanagedValue, bytes->Length);
delete[] unmanagedValue;
}
//==============================================================================================
void* Marshaller::Marshal(array<Byte>^ values, StorageType storageType)
{
Throw::IfNullOrEmpty("values", values);
switch(storageType)
{
case StorageType::Char:
return Marshal(values);
case StorageType::Double:
return MarshalStorageType<double>(values);
case StorageType::Float:
return MarshalStorageType<float>(values);
case StorageType::Integer:
return MarshalStorageType<int>(values);
case StorageType::Long:
return MarshalStorageType<long>(values);
case StorageType::Short:
return MarshalStorageType<short>(values);
default:
throw gcnew NotImplementedException();
}
}
//==============================================================================================
double* Marshaller::Marshal(array<double>^ values)
{
if (values == nullptr || values->Length == 0)
return NULL;
double* unmanagedValue = new double[values->Length];
Marshal::Copy(values, 0, IntPtr(unmanagedValue), values->Length);
return unmanagedValue;
}
//==============================================================================================
array<Byte>^ Marshaller::Marshal(Magick::Blob* value)
{
if (value == NULL || value->length() == 0)
return nullptr;
int length = Convert::ToInt32(value->length());
array<Byte>^ data = gcnew array<Byte>(length);
IntPtr ptr = IntPtr((void*)value->data());
Marshal::Copy(ptr, data, 0, length);
return data;
}
//==============================================================================================
array<double>^ Marshaller::Marshal(const double* values)
{
if (values == NULL)
return nullptr;
int length = 0;
const double* v = values;
while(*v != 0.0)
{
length++;
v++;
}
array<double>^ managedValue = gcnew array<double>(length);
int index = 0;
v = values;
while(*v != 0.0)
{
managedValue[index++] = *v++;
}
return managedValue;
}
//==============================================================================================
String^ Marshaller::Marshal(const std::string& value)
{
if (value.empty())
return nullptr;
else
return gcnew String(value.c_str(), 0, (int)value.length(), System::Text::Encoding::UTF8);
}
//==============================================================================================
std::string& Marshaller::Marshal(String^ value, std::string &unmanagedValue)
{
if (value == nullptr)
return unmanagedValue;
if (value->Length == 0)
{
unmanagedValue = "";
return unmanagedValue;
}
array<Byte>^ bytes = System::Text::Encoding::UTF8->GetBytes(value);
pin_ptr<unsigned char> bytesPtr = &bytes[0];
unmanagedValue = std::string(reinterpret_cast<char *>(bytesPtr), bytes->Length);
return unmanagedValue;
}
//==============================================================================================
double* Marshaller::MarshalAndTerminate(array<double>^ values)
{
if (values == nullptr || values->Length == 0)
return NULL;
int zeroIndex = Array::IndexOf(values, 0.0);
int length = zeroIndex == -1 ? values->Length + 1 : zeroIndex + 1;
double* unmanagedValue = new double[length];
Marshal::Copy(values, 0, IntPtr(unmanagedValue), length - 1);
unmanagedValue[length - 1] = 0.0;
return unmanagedValue;
}
//==============================================================================================
}<commit_msg>Avoid extra copy when creating blob. <commit_after>//=================================================================================================
// Copyright 2014-2015 Dirk Lemstra <https://graphicsmagick.codeplex.com/>
//
// Licensed under the ImageMagick License (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.imagemagick.org/script/license.php
//
// 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 "Stdafx.h"
using namespace System::Runtime::InteropServices;
namespace GraphicsMagick
{
//==============================================================================================
template <typename TStorageType>
TStorageType* Marshaller::MarshalStorageType(array<Byte>^ bytes)
{
int length = bytes->Length / sizeof(TStorageType);
TStorageType* unmanagedValue = new TStorageType[length];
Marshal::Copy(bytes, 0, IntPtr(unmanagedValue), bytes->Length);
return unmanagedValue;
}
//==============================================================================================
unsigned char* Marshaller::Marshal(array<Byte>^ bytes)
{
if (bytes == nullptr || bytes->Length == 0)
return NULL;
unsigned char* unmanagedValue = new unsigned char[bytes->Length];
Marshal::Copy(bytes, 0, IntPtr(unmanagedValue), bytes->Length);
return unmanagedValue;
}
//==============================================================================================
void Marshaller::Marshal(array<Byte>^ bytes, Magick::Blob* value)
{
if (bytes == nullptr || bytes->Length == 0)
return;
char* unmanagedValue = new char[bytes->Length];
Marshal::Copy(bytes, 0, IntPtr(unmanagedValue), bytes->Length);
value->updateNoCopy(unmanagedValue, bytes->Length);
}
//==============================================================================================
void* Marshaller::Marshal(array<Byte>^ values, StorageType storageType)
{
Throw::IfNullOrEmpty("values", values);
switch(storageType)
{
case StorageType::Char:
return Marshal(values);
case StorageType::Double:
return MarshalStorageType<double>(values);
case StorageType::Float:
return MarshalStorageType<float>(values);
case StorageType::Integer:
return MarshalStorageType<int>(values);
case StorageType::Long:
return MarshalStorageType<long>(values);
case StorageType::Short:
return MarshalStorageType<short>(values);
default:
throw gcnew NotImplementedException();
}
}
//==============================================================================================
double* Marshaller::Marshal(array<double>^ values)
{
if (values == nullptr || values->Length == 0)
return NULL;
double* unmanagedValue = new double[values->Length];
Marshal::Copy(values, 0, IntPtr(unmanagedValue), values->Length);
return unmanagedValue;
}
//==============================================================================================
array<Byte>^ Marshaller::Marshal(Magick::Blob* value)
{
if (value == NULL || value->length() == 0)
return nullptr;
int length = Convert::ToInt32(value->length());
array<Byte>^ data = gcnew array<Byte>(length);
IntPtr ptr = IntPtr((void*)value->data());
Marshal::Copy(ptr, data, 0, length);
return data;
}
//==============================================================================================
array<double>^ Marshaller::Marshal(const double* values)
{
if (values == NULL)
return nullptr;
int length = 0;
const double* v = values;
while(*v != 0.0)
{
length++;
v++;
}
array<double>^ managedValue = gcnew array<double>(length);
int index = 0;
v = values;
while(*v != 0.0)
{
managedValue[index++] = *v++;
}
return managedValue;
}
//==============================================================================================
String^ Marshaller::Marshal(const std::string& value)
{
if (value.empty())
return nullptr;
else
return gcnew String(value.c_str(), 0, (int)value.length(), System::Text::Encoding::UTF8);
}
//==============================================================================================
std::string& Marshaller::Marshal(String^ value, std::string &unmanagedValue)
{
if (value == nullptr)
return unmanagedValue;
if (value->Length == 0)
{
unmanagedValue = "";
return unmanagedValue;
}
array<Byte>^ bytes = System::Text::Encoding::UTF8->GetBytes(value);
pin_ptr<unsigned char> bytesPtr = &bytes[0];
unmanagedValue = std::string(reinterpret_cast<char *>(bytesPtr), bytes->Length);
return unmanagedValue;
}
//==============================================================================================
double* Marshaller::MarshalAndTerminate(array<double>^ values)
{
if (values == nullptr || values->Length == 0)
return NULL;
int zeroIndex = Array::IndexOf(values, 0.0);
int length = zeroIndex == -1 ? values->Length + 1 : zeroIndex + 1;
double* unmanagedValue = new double[length];
Marshal::Copy(values, 0, IntPtr(unmanagedValue), length - 1);
unmanagedValue[length - 1] = 0.0;
return unmanagedValue;
}
//==============================================================================================
}<|endoftext|>
|
<commit_before>#include "StdAfx.h"
#include "ThreadComponent.h"
thread_component::thread_component()
{
}
DWORD thread_component::GetExitCode()
{
return m_ExitCode;
}
bool thread_component::IsExecuting()
{
if (m_pThread == NULL)
return false;
return (WAIT_TIMEOUT == WaitForSingleObject(m_pThread->m_hThread, 0));
}
UINT thread_component::ExecuteThread(LPVOID pParam)
{
thread_component * pComponent = (thread_component *) pParam;
try
{
pComponent->m_ExitCode = pComponent->ExecOnThread();
}
catch(std::exception& ex)
{
pComponent->m_Error = ex.what();
pComponent->m_ExitCode = -1;
}
catch(...)
{
pComponent->m_Error = TEXT("Failed to execute threaded Component");
pComponent->m_ExitCode = -1;
}
return pComponent->m_ExitCode;
}
void thread_component::Init(CDialog * pDialog)
{
m_ExitCode = 0;
Component::Init(pDialog);
m_pThread = AfxBeginThread(ExecuteThread, this, 0, 0, CREATE_SUSPENDED);
m_pThread->ResumeThread();
}
bool thread_component::Exec()
{
if (m_pThread != NULL)
{
if (WAIT_FAILED == WaitForSingleObject(m_pThread->m_hThread, INFINITE))
{
throw std::exception("WaitForSingleObject failed");
}
if (m_Error.GetLength())
{
throw std::exception(DVLib::Tstring2string((LPCWSTR) m_Error).c_str());
}
}
return m_ExitCode == 0 ? true : false;
}
<commit_msg>Changed thread auto-delete semantics. Copied from https://dotnetinstaller.svn.sourceforge.net/svnroot/dotnetinstaller/trunk/, rev. 134 by dblockdotorg @ 2/19/2009 11:35 PM<commit_after>#include "StdAfx.h"
#include "ThreadComponent.h"
thread_component::thread_component()
{
}
DWORD thread_component::GetExitCode()
{
return m_ExitCode;
}
bool thread_component::IsExecuting()
{
if (m_pThread == NULL)
return false;
return (WAIT_TIMEOUT == WaitForSingleObject(m_pThread->m_hThread, 0));
}
UINT thread_component::ExecuteThread(LPVOID pParam)
{
thread_component * pComponent = (thread_component *) pParam;
try
{
pComponent->m_ExitCode = pComponent->ExecOnThread();
}
catch(std::exception& ex)
{
pComponent->m_Error = ex.what();
pComponent->m_ExitCode = -1;
}
catch(...)
{
pComponent->m_Error = TEXT("Failed to execute threaded Component");
pComponent->m_ExitCode = -1;
}
return pComponent->m_ExitCode;
}
void thread_component::Init(CDialog * pDialog)
{
m_ExitCode = 0;
Component::Init(pDialog);
m_pThread = AfxBeginThread(ExecuteThread, this, 0, 0, CREATE_SUSPENDED);
m_pThread->m_bAutoDelete = false;
m_pThread->ResumeThread();
}
bool thread_component::Exec()
{
if (m_pThread != NULL)
{
if (WAIT_FAILED == WaitForSingleObject(m_pThread->m_hThread, INFINITE))
{
throw std::exception("WaitForSingleObject failed");
}
delete m_pThread;
if (m_Error.GetLength())
{
throw std::exception(DVLib::Tstring2string((LPCWSTR) m_Error).c_str());
}
}
return m_ExitCode == 0 ? true : false;
}
<|endoftext|>
|
<commit_before>// **************************************************************************
// This file is property of and copyright by the ALICE HLT Project *
// ALICE Experiment at CERN, All rights reserved. *
// *
// Primary Authors: Sergey Gorbunov <sergey.gorbunov@kip.uni-heidelberg.de> *
// for The ALICE HLT Project. *
// *
// Permission to use, copy, modify and distribute this software and its *
// documentation strictly for non-commercial purposes is hereby granted *
// without fee, provided that the above copyright notice appears in all *
// copies and that both the copyright notice and this permission notice *
// appear in the supporting documentation. The authors make no claims *
// about the suitability of this software for any purpose. It is *
// provided "as is" without express or implied warranty. *
// *
//***************************************************************************
/// @file AliHLTTPCFastdEdxComponent.cxx
/// @author David Rohr <drohr@cern.ch>
/// @date May 2017
/// @brief dEdx calculation component for the HLT TPC
#include "AliHLTTPCFastdEdxComponent.h"
#include "AliCDBEntry.h"
#include "AliCDBManager.h"
#include "AliHLTDataTypes.h"
#include "AliHLTExternalTrackParam.h"
#include "AliHLTGlobalBarrelTrack.h"
#include "AliHLTTPCGeometry.h"
#include "AliHLTTPCRawCluster.h"
#include "AliHLTTPCDefinitions.h"
#include "AliTPCcalibDB.h"
#include "AliTPCRecoParam.h"
#include "AliHLTTPCdEdxData.h"
#include "AliHLTTPCRawCluster.h"
#include <algorithm>
ClassImp( AliHLTTPCFastdEdxComponent )
AliHLTTPCFastdEdxComponent::AliHLTTPCFastdEdxComponent() : AliHLTProcessor(), fBz(0.), fBufMax(NULL), fBufTot(NULL), fMaxClusterCount(1000)
{
for (int i = 0;i < 36 * 6;i++)
{
fNPatchClusters[0][i] = 0;
fPatchClusters[0][i] = NULL;
}
}
AliHLTTPCFastdEdxComponent::AliHLTTPCFastdEdxComponent( const AliHLTTPCFastdEdxComponent& ) : AliHLTProcessor(), fBz(0.), fBufMax(NULL), fBufTot(NULL), fMaxClusterCount(1000)
{
for (int i = 0;i < 36 * 6;i++)
{
fPatchClusters[0][i] = 0;
fPatchClusters[0][i] = NULL;
}
}
AliHLTTPCFastdEdxComponent& AliHLTTPCFastdEdxComponent::operator=( const AliHLTTPCFastdEdxComponent& )
{
fBz = 0;
fBufMax = NULL;
fBufTot = NULL;
fMaxClusterCount = 1000;
for (int i = 0; i < 36*6;i++)
{
fPatchClusters[0][i] = 0;
fPatchClusters[0][i] = NULL;
}
return *this;
}
AliHLTTPCFastdEdxComponent::~AliHLTTPCFastdEdxComponent()
{
DoDeinit();
}
const char* AliHLTTPCFastdEdxComponent::GetComponentID()
{
return "FastTPCdEdx";
}
void AliHLTTPCFastdEdxComponent::GetInputDataTypes( vector<AliHLTComponentDataType>& list )
{
list.clear();
list.push_back( kAliHLTDataTypeTrack|kAliHLTDataOriginTPC );
list.push_back( AliHLTTPCDefinitions::RawClustersDataType() );
}
AliHLTComponentDataType AliHLTTPCFastdEdxComponent::GetOutputDataType()
{
return AliHLTTPCDefinitions::TPCdEdxNew();
}
void AliHLTTPCFastdEdxComponent::GetOutputDataSize( unsigned long& constBase, double& inputMultiplier )
{
constBase = 200;
inputMultiplier = 0.1;
}
AliHLTComponent* AliHLTTPCFastdEdxComponent::Spawn()
{
return new AliHLTTPCFastdEdxComponent;
}
void AliHLTTPCFastdEdxComponent::SetDefaultConfiguration()
{
}
int AliHLTTPCFastdEdxComponent::ReadConfigurationString( const char* arguments )
{
int iResult = 0;
if ( !arguments ) return iResult;
TString allArgs = arguments;
TString argument;
int bMissingParam = 0;
TObjArray* pTokens = allArgs.Tokenize( " " );
int nArgs = pTokens ? pTokens->GetEntries() : 0;
for ( int i = 0; i < nArgs; i++ ) {
argument = ( ( TObjString* )pTokens->At( i ) )->GetString();
if ( argument.IsNull() ) continue;
HLTError( "Unknown option \"%s\"", argument.Data() );
iResult = -EINVAL;
}
delete pTokens;
if ( bMissingParam ) {
HLTError( "Specifier missed for parameter \"%s\"", argument.Data() );
iResult = -EINVAL;
}
return iResult;
}
int AliHLTTPCFastdEdxComponent::Configure( const char* cdbEntry, const char* chainId, const char *commandLine )
{
SetDefaultConfiguration();
int iResult = 0;
if ( commandLine && commandLine[0] != 0 )
{
HLTInfo( "received configuration string from HLT framework: \"%s\"", commandLine );
iResult = ReadConfigurationString( commandLine );
}
return iResult;
}
int AliHLTTPCFastdEdxComponent::DoInit( int argc, const char** argv )
{
// Configure the component
TString arguments = "";
for ( int i = 0; i < argc; i++ ) {
if ( !arguments.IsNull() ) arguments += " ";
arguments += argv[i];
}
int ret = Configure( NULL, NULL, arguments.Data() );
fBz = GetBz();
fBufMax = new float[fMaxClusterCount];
fBufTot = new float[fMaxClusterCount];
if (fBufMax == NULL || fBufTot == NULL)
{
HLTError("Memory allocation failed");
return(-ENOSPC);
}
return ret;
}
int AliHLTTPCFastdEdxComponent::DoDeinit()
{
return 0;
delete[] fBufMax;
delete[] fBufTot;
fBufMax = fBufTot = NULL;
}
int AliHLTTPCFastdEdxComponent::Reconfigure( const char* cdbEntry, const char* chainId )
{
return Configure( cdbEntry, chainId, NULL );
}
int AliHLTTPCFastdEdxComponent::DoEvent(const AliHLTComponentEventData& evtData, const AliHLTComponentBlockData* blocks, AliHLTComponentTriggerData& /*trigData*/, AliHLTUInt8_t* outputPtr, AliHLTUInt32_t& size, vector<AliHLTComponentBlockData>& outputBlocks)
{
AliHLTUInt32_t maxBufferSize = size;
size = 0; // output size
if (!IsDataEvent()) return 0;
for(int i = 0;i < 36 * 6;i++)
{
fNPatchClusters[0][i] = 0;
}
int nBlocks = (int) evtData.fBlockCnt;
int nInputClusters = 0;
int nInputTracks = 0;
// first read all raw clusters
for (int ndx = 0;ndx < nBlocks;ndx++)
{
const AliHLTComponentBlockData* iter = blocks+ndx;
if (iter->fDataType != AliHLTTPCDefinitions::RawClustersDataType()) continue;
Int_t slice=AliHLTTPCDefinitions::GetMinSliceNr(iter->fSpecification);
Int_t patch=AliHLTTPCDefinitions::GetMinPatchNr(iter->fSpecification);
fPatchClusters[slice][patch] = (AliHLTTPCRawClusterData*) iter->fPtr;
nInputClusters += fPatchClusters[slice][patch]->fCount;
fNPatchClusters[slice][patch] = fPatchClusters[slice][patch]->fCount;
}
// loop over the input tracks: calculate dEdx and write output
for (const AliHLTComponentBlockData* pBlock = GetFirstInputBlock(kAliHLTDataTypeTrack|kAliHLTDataOriginTPC);pBlock != NULL;pBlock=GetNextInputBlock())
{
AliHLTTracksData* dataPtr = (AliHLTTracksData*) pBlock->fPtr;
int nTracks = dataPtr->fCount;
const int outSize = sizeof(AliHLTTPCdEdxData) + nTracks * 10 * sizeof(float);
AliHLTTPCdEdxData* outPtr = (AliHLTTPCdEdxData*) (outputPtr + size);
if (size + outSize > maxBufferSize) //Check output size for current fValuesPerTrack = 10 (see below)
{
HLTWarning("Output buffer size exceeded");
return(-ENOSPC);
}
outPtr->fVersion = 1;
outPtr->fValuesPerTrack = 10;
outPtr->fCount = nTracks;
float* outFill = outPtr->fdEdxInfo;
AliHLTComponentBlockData outBlock;
FillBlockData(outBlock);
outBlock.fOffset = size;
outBlock.fSize = outSize;
outBlock.fDataType = AliHLTTPCDefinitions::TPCdEdxNew();
outBlock.fSpecification = pBlock->fSpecification;
AliHLTExternalTrackParam* currTrack = dataPtr->fTracklets;
nInputTracks+=nTracks;
for(int itr = 0;itr < nTracks && ((AliHLTUInt8_t*) currTrack < ((AliHLTUInt8_t*) pBlock->fPtr) + pBlock->fSize);itr++)
{
// create an off-line track
AliHLTGlobalBarrelTrack gb(*currTrack);
AliExternalTrackParam& track = gb;
int count = 0;
int countIROC = 0;
int countOROC1 = 0;
int lastPatch = AliHLTTPCGeometry::CluID2Partition(currTrack->fPointIDs[currTrack->fNPoints - 1]);
for(int ic = currTrack->fNPoints;--ic;)
{
UInt_t id = currTrack->fPointIDs[ic];
int iSlice = AliHLTTPCGeometry::CluID2Slice(id);
int iPatch = AliHLTTPCGeometry::CluID2Partition(id);
int iCluster = AliHLTTPCGeometry::CluID2Index(id);
AliHLTTPCRawCluster& cluster = fPatchClusters[iSlice][iPatch]->fClusters[iCluster];
if (cluster.GetFlagSplitAnyOrEdge()) continue;
float chargeTot = cluster.GetCharge();
float chargeMax = cluster.GetQMax();
int padRow = cluster.GetPadRow() + AliHLTTPCGeometry::GetFirstRow(iPatch);
float padPitchWidth = AliHLTTPCGeometry::GetPadPitchWidth(iPatch);
float padLength = AliHLTTPCGeometry::GetPadLength(padRow);
if (lastPatch != iPatch)
{
int sec = iSlice;
if (sec > 18) sec -= 18;
float alpha = 0.174533 + 0.349066 * sec;
track.RotateParamOnly(alpha);
lastPatch = iPatch;
}
int ret = track.PropagateParamOnlyTo(AliHLTTPCGeometry::Row2X(padRow), fBz);
if (ret == kFALSE) break;
float factor = sqrt((1 - track.GetSnp() * track.GetSnp()) / (1 + track.GetTgl() * track.GetTgl()));
factor /= padLength;
chargeTot *= factor;
chargeMax *= factor / padPitchWidth;
fBufTot[count] = chargeTot;
fBufMax[count++] = chargeMax;
if (padRow < AliHLTTPCGeometry::GetNRowLow()) countIROC++;
else if (padRow < AliHLTTPCGeometry::GetNRowLow() + AliHLTTPCGeometry::GetNRowUp1()) countOROC1++;
if (count >= fMaxClusterCount) break;
}
int countOROC2 = count - countIROC - countOROC1;
int countOROC = countOROC1 + countOROC2;
int truncLow = 5;
int truncHigh = 40;
outFill[0] = GetSortTruncMean(fBufTot , countIROC , countIROC * 100 / truncLow, countIROC * 100 / truncHigh);
outFill[1] = GetSortTruncMean(fBufTot + countIROC , countOROC1, countOROC1 * 100 / truncLow, countOROC1 * 100 / truncHigh);
outFill[2] = GetSortTruncMean(fBufTot + countIROC + countOROC1, countOROC2, countOROC2 * 100 / truncLow, countOROC2 * 100 / truncHigh);
outFill[3] = GetSortTruncMean(fBufTot + countIROC , countOROC , countOROC * 100 / truncLow, countOROC * 100 / truncHigh);
outFill[4] = GetSortTruncMean(fBufTot , count , count * 100 / truncLow, count * 100 / truncHigh);
outFill[5] = GetSortTruncMean(fBufMax , countIROC , countIROC * 100 / truncLow, countIROC * 100 / truncHigh);
outFill[6] = GetSortTruncMean(fBufMax + countIROC , countOROC1, countOROC1 * 100 / truncLow, countOROC1 * 100 / truncHigh);
outFill[7] = GetSortTruncMean(fBufMax + countIROC + countOROC1, countOROC2, countOROC2 * 100 / truncLow, countOROC2 * 100 / truncHigh);
outFill[8] = GetSortTruncMean(fBufMax + countIROC , countOROC , countOROC * 100 / truncLow, countOROC * 100 / truncHigh);
outFill[9] = GetSortTruncMean(fBufMax , count , count * 100 / truncLow, count * 100 / truncHigh);
unsigned int step = sizeof(AliHLTExternalTrackParam) + currTrack->fNPoints * sizeof(unsigned int);
currTrack = (AliHLTExternalTrackParam*) (((Byte_t*) currTrack) + step);
}
outputBlocks.push_back( outBlock );
size += outSize;
}
return 0;
}
float AliHLTTPCFastdEdxComponent::GetSortTruncMean(float* array, int count, int trunclow, int trunchigh)
{
if (count - trunclow - trunchigh <= 0) return(0.);
std::sort(array, array + count);
float mean = 0;
for (int i = trunclow;i < count - trunchigh;i++) mean += array[i];
return(mean / (count - trunclow - trunchigh));
}
<commit_msg>fix compiler warnings of gcc 4.8<commit_after>// **************************************************************************
// This file is property of and copyright by the ALICE HLT Project *
// ALICE Experiment at CERN, All rights reserved. *
// *
// Primary Authors: Sergey Gorbunov <sergey.gorbunov@kip.uni-heidelberg.de> *
// for The ALICE HLT Project. *
// *
// Permission to use, copy, modify and distribute this software and its *
// documentation strictly for non-commercial purposes is hereby granted *
// without fee, provided that the above copyright notice appears in all *
// copies and that both the copyright notice and this permission notice *
// appear in the supporting documentation. The authors make no claims *
// about the suitability of this software for any purpose. It is *
// provided "as is" without express or implied warranty. *
// *
//***************************************************************************
/// @file AliHLTTPCFastdEdxComponent.cxx
/// @author David Rohr <drohr@cern.ch>
/// @date May 2017
/// @brief dEdx calculation component for the HLT TPC
#include "AliHLTTPCFastdEdxComponent.h"
#include "AliCDBEntry.h"
#include "AliCDBManager.h"
#include "AliHLTDataTypes.h"
#include "AliHLTExternalTrackParam.h"
#include "AliHLTGlobalBarrelTrack.h"
#include "AliHLTTPCGeometry.h"
#include "AliHLTTPCRawCluster.h"
#include "AliHLTTPCDefinitions.h"
#include "AliTPCcalibDB.h"
#include "AliTPCRecoParam.h"
#include "AliHLTTPCdEdxData.h"
#include "AliHLTTPCRawCluster.h"
#include <algorithm>
ClassImp( AliHLTTPCFastdEdxComponent )
AliHLTTPCFastdEdxComponent::AliHLTTPCFastdEdxComponent() : AliHLTProcessor(), fBz(0.), fBufMax(NULL), fBufTot(NULL), fMaxClusterCount(1000)
{
for (int i = 0;i < 36;i++) for (int j = 0;j < 6;j++)
{
fNPatchClusters[i][j] = 0;
fPatchClusters[i][j] = NULL;
}
}
AliHLTTPCFastdEdxComponent::AliHLTTPCFastdEdxComponent( const AliHLTTPCFastdEdxComponent& ) : AliHLTProcessor(), fBz(0.), fBufMax(NULL), fBufTot(NULL), fMaxClusterCount(1000)
{
for (int i = 0;i < 36;i++) for (int j = 0;j < 6;j++)
{
fPatchClusters[i][j] = 0;
fPatchClusters[i][j] = NULL;
}
}
AliHLTTPCFastdEdxComponent& AliHLTTPCFastdEdxComponent::operator=( const AliHLTTPCFastdEdxComponent& )
{
fBz = 0;
fBufMax = NULL;
fBufTot = NULL;
fMaxClusterCount = 1000;
for (int i = 0; i < 36;i++) for (int j = 0;j < 6;j++)
{
fPatchClusters[i][j] = 0;
fPatchClusters[i][j] = NULL;
}
return *this;
}
AliHLTTPCFastdEdxComponent::~AliHLTTPCFastdEdxComponent()
{
DoDeinit();
}
const char* AliHLTTPCFastdEdxComponent::GetComponentID()
{
return "FastTPCdEdx";
}
void AliHLTTPCFastdEdxComponent::GetInputDataTypes( vector<AliHLTComponentDataType>& list )
{
list.clear();
list.push_back( kAliHLTDataTypeTrack|kAliHLTDataOriginTPC );
list.push_back( AliHLTTPCDefinitions::RawClustersDataType() );
}
AliHLTComponentDataType AliHLTTPCFastdEdxComponent::GetOutputDataType()
{
return AliHLTTPCDefinitions::TPCdEdxNew();
}
void AliHLTTPCFastdEdxComponent::GetOutputDataSize( unsigned long& constBase, double& inputMultiplier )
{
constBase = 200;
inputMultiplier = 0.1;
}
AliHLTComponent* AliHLTTPCFastdEdxComponent::Spawn()
{
return new AliHLTTPCFastdEdxComponent;
}
void AliHLTTPCFastdEdxComponent::SetDefaultConfiguration()
{
}
int AliHLTTPCFastdEdxComponent::ReadConfigurationString( const char* arguments )
{
int iResult = 0;
if ( !arguments ) return iResult;
TString allArgs = arguments;
TString argument;
int bMissingParam = 0;
TObjArray* pTokens = allArgs.Tokenize( " " );
int nArgs = pTokens ? pTokens->GetEntries() : 0;
for ( int i = 0; i < nArgs; i++ ) {
argument = ( ( TObjString* )pTokens->At( i ) )->GetString();
if ( argument.IsNull() ) continue;
HLTError( "Unknown option \"%s\"", argument.Data() );
iResult = -EINVAL;
}
delete pTokens;
if ( bMissingParam ) {
HLTError( "Specifier missed for parameter \"%s\"", argument.Data() );
iResult = -EINVAL;
}
return iResult;
}
int AliHLTTPCFastdEdxComponent::Configure( const char* cdbEntry, const char* chainId, const char *commandLine )
{
SetDefaultConfiguration();
int iResult = 0;
if ( commandLine && commandLine[0] != 0 )
{
HLTInfo( "received configuration string from HLT framework: \"%s\"", commandLine );
iResult = ReadConfigurationString( commandLine );
}
return iResult;
}
int AliHLTTPCFastdEdxComponent::DoInit( int argc, const char** argv )
{
// Configure the component
TString arguments = "";
for ( int i = 0; i < argc; i++ ) {
if ( !arguments.IsNull() ) arguments += " ";
arguments += argv[i];
}
int ret = Configure( NULL, NULL, arguments.Data() );
fBz = GetBz();
fBufMax = new float[fMaxClusterCount];
fBufTot = new float[fMaxClusterCount];
if (fBufMax == NULL || fBufTot == NULL)
{
HLTError("Memory allocation failed");
return(-ENOSPC);
}
return ret;
}
int AliHLTTPCFastdEdxComponent::DoDeinit()
{
return 0;
delete[] fBufMax;
delete[] fBufTot;
fBufMax = fBufTot = NULL;
}
int AliHLTTPCFastdEdxComponent::Reconfigure( const char* cdbEntry, const char* chainId )
{
return Configure( cdbEntry, chainId, NULL );
}
int AliHLTTPCFastdEdxComponent::DoEvent(const AliHLTComponentEventData& evtData, const AliHLTComponentBlockData* blocks, AliHLTComponentTriggerData& /*trigData*/, AliHLTUInt8_t* outputPtr, AliHLTUInt32_t& size, vector<AliHLTComponentBlockData>& outputBlocks)
{
AliHLTUInt32_t maxBufferSize = size;
size = 0; // output size
if (!IsDataEvent()) return 0;
for(int i = 0;i < 36;i++) for (int j = 0;j < 6;j++)
{
fNPatchClusters[i][j] = 0;
}
int nBlocks = (int) evtData.fBlockCnt;
int nInputClusters = 0;
int nInputTracks = 0;
// first read all raw clusters
for (int ndx = 0;ndx < nBlocks;ndx++)
{
const AliHLTComponentBlockData* iter = blocks+ndx;
if (iter->fDataType != AliHLTTPCDefinitions::RawClustersDataType()) continue;
Int_t slice=AliHLTTPCDefinitions::GetMinSliceNr(iter->fSpecification);
Int_t patch=AliHLTTPCDefinitions::GetMinPatchNr(iter->fSpecification);
fPatchClusters[slice][patch] = (AliHLTTPCRawClusterData*) iter->fPtr;
nInputClusters += fPatchClusters[slice][patch]->fCount;
fNPatchClusters[slice][patch] = fPatchClusters[slice][patch]->fCount;
}
// loop over the input tracks: calculate dEdx and write output
for (const AliHLTComponentBlockData* pBlock = GetFirstInputBlock(kAliHLTDataTypeTrack|kAliHLTDataOriginTPC);pBlock != NULL;pBlock=GetNextInputBlock())
{
AliHLTTracksData* dataPtr = (AliHLTTracksData*) pBlock->fPtr;
int nTracks = dataPtr->fCount;
const int outSize = sizeof(AliHLTTPCdEdxData) + nTracks * 10 * sizeof(float);
AliHLTTPCdEdxData* outPtr = (AliHLTTPCdEdxData*) (outputPtr + size);
if (size + outSize > maxBufferSize) //Check output size for current fValuesPerTrack = 10 (see below)
{
HLTWarning("Output buffer size exceeded");
return(-ENOSPC);
}
outPtr->fVersion = 1;
outPtr->fValuesPerTrack = 10;
outPtr->fCount = nTracks;
float* outFill = outPtr->fdEdxInfo;
AliHLTComponentBlockData outBlock;
FillBlockData(outBlock);
outBlock.fOffset = size;
outBlock.fSize = outSize;
outBlock.fDataType = AliHLTTPCDefinitions::TPCdEdxNew();
outBlock.fSpecification = pBlock->fSpecification;
AliHLTExternalTrackParam* currTrack = dataPtr->fTracklets;
nInputTracks+=nTracks;
for(int itr = 0;itr < nTracks && ((AliHLTUInt8_t*) currTrack < ((AliHLTUInt8_t*) pBlock->fPtr) + pBlock->fSize);itr++)
{
// create an off-line track
AliHLTGlobalBarrelTrack gb(*currTrack);
AliExternalTrackParam& track = gb;
int count = 0;
int countIROC = 0;
int countOROC1 = 0;
int lastPatch = AliHLTTPCGeometry::CluID2Partition(currTrack->fPointIDs[currTrack->fNPoints - 1]);
for(int ic = currTrack->fNPoints;--ic;)
{
UInt_t id = currTrack->fPointIDs[ic];
int iSlice = AliHLTTPCGeometry::CluID2Slice(id);
int iPatch = AliHLTTPCGeometry::CluID2Partition(id);
int iCluster = AliHLTTPCGeometry::CluID2Index(id);
AliHLTTPCRawCluster& cluster = fPatchClusters[iSlice][iPatch]->fClusters[iCluster];
if (cluster.GetFlagSplitAnyOrEdge()) continue;
float chargeTot = cluster.GetCharge();
float chargeMax = cluster.GetQMax();
int padRow = cluster.GetPadRow() + AliHLTTPCGeometry::GetFirstRow(iPatch);
float padPitchWidth = AliHLTTPCGeometry::GetPadPitchWidth(iPatch);
float padLength = AliHLTTPCGeometry::GetPadLength(padRow);
if (lastPatch != iPatch)
{
int sec = iSlice;
if (sec > 18) sec -= 18;
float alpha = 0.174533 + 0.349066 * sec;
track.RotateParamOnly(alpha);
lastPatch = iPatch;
}
int ret = track.PropagateParamOnlyTo(AliHLTTPCGeometry::Row2X(padRow), fBz);
if (ret == kFALSE) break;
float factor = sqrt((1 - track.GetSnp() * track.GetSnp()) / (1 + track.GetTgl() * track.GetTgl()));
factor /= padLength;
chargeTot *= factor;
chargeMax *= factor / padPitchWidth;
fBufTot[count] = chargeTot;
fBufMax[count++] = chargeMax;
if (padRow < AliHLTTPCGeometry::GetNRowLow()) countIROC++;
else if (padRow < AliHLTTPCGeometry::GetNRowLow() + AliHLTTPCGeometry::GetNRowUp1()) countOROC1++;
if (count >= fMaxClusterCount) break;
}
int countOROC2 = count - countIROC - countOROC1;
int countOROC = countOROC1 + countOROC2;
int truncLow = 5;
int truncHigh = 40;
outFill[0] = GetSortTruncMean(fBufTot , countIROC , countIROC * 100 / truncLow, countIROC * 100 / truncHigh);
outFill[1] = GetSortTruncMean(fBufTot + countIROC , countOROC1, countOROC1 * 100 / truncLow, countOROC1 * 100 / truncHigh);
outFill[2] = GetSortTruncMean(fBufTot + countIROC + countOROC1, countOROC2, countOROC2 * 100 / truncLow, countOROC2 * 100 / truncHigh);
outFill[3] = GetSortTruncMean(fBufTot + countIROC , countOROC , countOROC * 100 / truncLow, countOROC * 100 / truncHigh);
outFill[4] = GetSortTruncMean(fBufTot , count , count * 100 / truncLow, count * 100 / truncHigh);
outFill[5] = GetSortTruncMean(fBufMax , countIROC , countIROC * 100 / truncLow, countIROC * 100 / truncHigh);
outFill[6] = GetSortTruncMean(fBufMax + countIROC , countOROC1, countOROC1 * 100 / truncLow, countOROC1 * 100 / truncHigh);
outFill[7] = GetSortTruncMean(fBufMax + countIROC + countOROC1, countOROC2, countOROC2 * 100 / truncLow, countOROC2 * 100 / truncHigh);
outFill[8] = GetSortTruncMean(fBufMax + countIROC , countOROC , countOROC * 100 / truncLow, countOROC * 100 / truncHigh);
outFill[9] = GetSortTruncMean(fBufMax , count , count * 100 / truncLow, count * 100 / truncHigh);
unsigned int step = sizeof(AliHLTExternalTrackParam) + currTrack->fNPoints * sizeof(unsigned int);
currTrack = (AliHLTExternalTrackParam*) (((Byte_t*) currTrack) + step);
}
outputBlocks.push_back( outBlock );
size += outSize;
}
return 0;
}
float AliHLTTPCFastdEdxComponent::GetSortTruncMean(float* array, int count, int trunclow, int trunchigh)
{
if (count - trunclow - trunchigh <= 0) return(0.);
std::sort(array, array + count);
float mean = 0;
for (int i = trunclow;i < count - trunchigh;i++) mean += array[i];
return(mean / (count - trunclow - trunchigh));
}
<|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 "ast/FunctionsAnnotator.hpp"
#include "ast/SourceFile.hpp"
#include "ast/TypeTransformer.hpp"
#include "ast/ASTVisitor.hpp"
#include "ast/GetTypeVisitor.hpp"
#include "SymbolTable.hpp"
#include "SemanticalException.hpp"
#include "VisitorUtils.hpp"
#include "mangling.hpp"
#include "Options.hpp"
#include "Type.hpp"
using namespace eddic;
class FunctionInserterVisitor : public boost::static_visitor<> {
public:
AUTO_RECURSE_PROGRAM()
void operator()(ast::FunctionDeclaration& declaration){
auto return_type = visit(ast::TypeTransformer(), declaration.Content->returnType);
auto signature = std::make_shared<Function>(return_type, declaration.Content->functionName);
if(return_type->is_array()){
throw SemanticalException("Cannot return array from function", declaration.Content->position);
}
if(return_type->is_custom_type()){
throw SemanticalException("Cannot return struct from function", declaration.Content->position);
}
for(auto& param : declaration.Content->parameters){
auto paramType = visit(ast::TypeTransformer(), param.parameterType);
signature->parameters.push_back(ParameterType(param.parameterName, paramType));
}
declaration.Content->mangledName = signature->mangledName = mangle(declaration.Content->functionName, signature->parameters);
if(symbols.exists(signature->mangledName)){
throw SemanticalException("The function " + signature->name + " has already been defined", declaration.Content->position);
}
symbols.addFunction(signature);
symbols.getFunction(signature->mangledName)->context = declaration.Content->context;
}
AUTO_IGNORE_OTHERS()
};
class FunctionCheckerVisitor : public boost::static_visitor<> {
private:
std::shared_ptr<Function> currentFunction;
public:
AUTO_RECURSE_PROGRAM()
AUTO_RECURSE_GLOBAL_DECLARATION()
AUTO_RECURSE_SIMPLE_LOOPS()
AUTO_RECURSE_FOREACH()
AUTO_RECURSE_BRANCHES()
AUTO_RECURSE_BINARY_CONDITION()
AUTO_RECURSE_BUILTIN_OPERATORS()
AUTO_RECURSE_COMPOSED_VALUES()
AUTO_RECURSE_MINUS_PLUS_VALUES()
AUTO_RECURSE_VARIABLE_OPERATIONS()
void operator()(ast::FunctionDeclaration& declaration){
currentFunction = symbols.getFunction(declaration.Content->mangledName);
visit_each(*this, declaration.Content->instructions);
}
void permute(std::vector<std::vector<std::shared_ptr<const Type>>>& perms, std::vector<std::shared_ptr<const Type>>& types, int start){
for(std::size_t i = start; i < types.size(); ++i){
if(!types[i]->is_pointer() && !types[i]->is_array()){
std::vector<std::shared_ptr<const Type>> copy = types;
copy[i] = new_pointer_type(types[i]);
perms.push_back(copy);
permute(perms, copy, i + 1);
}
}
}
std::vector<std::vector<std::shared_ptr<const Type>>> permutations(std::vector<std::shared_ptr<const Type>>& types){
std::vector<std::vector<std::shared_ptr<const Type>>> perms;
permute(perms, types, 0);
return perms;
}
void operator()(ast::FunctionCall& functionCall){
visit_each(*this, functionCall.Content->values);
std::string name = functionCall.Content->functionName;
if(name == "println" || name == "print" || name == "duration"){
return;
}
std::vector<std::shared_ptr<const Type>> types;
ast::GetTypeVisitor visitor;
for(auto& value : functionCall.Content->values){
types.push_back(visit(visitor, value));
}
std::string mangled = mangle(name, types);
//If the function does not exists, try implicit conversions to pointers
if(!symbols.exists(mangled)){
auto perms = permutations(types);
for(auto& perm : perms){
mangled = mangle(name, perm);
if(symbols.exists(mangled)){
break;
}
}
}
if(symbols.exists(mangled)){
symbols.addReference(mangled);
functionCall.Content->mangled_name = mangled;
functionCall.Content->function = symbols.getFunction(mangled);
} else {
throw SemanticalException("The function \"" + unmangle(mangled) + "\" does not exists", functionCall.Content->position);
}
}
void operator()(ast::Return& return_){
return_.Content->function = currentFunction;
visit(*this, return_.Content->value);
}
AUTO_IGNORE_OTHERS()
};
void ast::defineFunctions(ast::SourceFile& program){
//First phase : Collect functions
FunctionInserterVisitor inserterVisitor;
inserterVisitor(program);
//Second phase : Verify calls
FunctionCheckerVisitor checkerVisitor;
checkerVisitor(program);
}
<commit_msg>Add reference to the used standard functions<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 "ast/FunctionsAnnotator.hpp"
#include "ast/SourceFile.hpp"
#include "ast/TypeTransformer.hpp"
#include "ast/ASTVisitor.hpp"
#include "ast/GetTypeVisitor.hpp"
#include "SymbolTable.hpp"
#include "SemanticalException.hpp"
#include "VisitorUtils.hpp"
#include "mangling.hpp"
#include "Options.hpp"
#include "Type.hpp"
using namespace eddic;
class FunctionInserterVisitor : public boost::static_visitor<> {
public:
AUTO_RECURSE_PROGRAM()
void operator()(ast::FunctionDeclaration& declaration){
auto return_type = visit(ast::TypeTransformer(), declaration.Content->returnType);
auto signature = std::make_shared<Function>(return_type, declaration.Content->functionName);
if(return_type->is_array()){
throw SemanticalException("Cannot return array from function", declaration.Content->position);
}
if(return_type->is_custom_type()){
throw SemanticalException("Cannot return struct from function", declaration.Content->position);
}
for(auto& param : declaration.Content->parameters){
auto paramType = visit(ast::TypeTransformer(), param.parameterType);
signature->parameters.push_back(ParameterType(param.parameterName, paramType));
}
declaration.Content->mangledName = signature->mangledName = mangle(declaration.Content->functionName, signature->parameters);
if(symbols.exists(signature->mangledName)){
throw SemanticalException("The function " + signature->name + " has already been defined", declaration.Content->position);
}
symbols.addFunction(signature);
symbols.getFunction(signature->mangledName)->context = declaration.Content->context;
}
AUTO_IGNORE_OTHERS()
};
class FunctionCheckerVisitor : public boost::static_visitor<> {
private:
std::shared_ptr<Function> currentFunction;
public:
AUTO_RECURSE_PROGRAM()
AUTO_RECURSE_GLOBAL_DECLARATION()
AUTO_RECURSE_SIMPLE_LOOPS()
AUTO_RECURSE_FOREACH()
AUTO_RECURSE_BRANCHES()
AUTO_RECURSE_BINARY_CONDITION()
AUTO_RECURSE_BUILTIN_OPERATORS()
AUTO_RECURSE_COMPOSED_VALUES()
AUTO_RECURSE_MINUS_PLUS_VALUES()
AUTO_RECURSE_VARIABLE_OPERATIONS()
void operator()(ast::FunctionDeclaration& declaration){
currentFunction = symbols.getFunction(declaration.Content->mangledName);
visit_each(*this, declaration.Content->instructions);
}
void permute(std::vector<std::vector<std::shared_ptr<const Type>>>& perms, std::vector<std::shared_ptr<const Type>>& types, int start){
for(std::size_t i = start; i < types.size(); ++i){
if(!types[i]->is_pointer() && !types[i]->is_array()){
std::vector<std::shared_ptr<const Type>> copy = types;
copy[i] = new_pointer_type(types[i]);
perms.push_back(copy);
permute(perms, copy, i + 1);
}
}
}
std::vector<std::vector<std::shared_ptr<const Type>>> permutations(std::vector<std::shared_ptr<const Type>>& types){
std::vector<std::vector<std::shared_ptr<const Type>>> perms;
permute(perms, types, 0);
return perms;
}
void operator()(ast::FunctionCall& functionCall){
visit_each(*this, functionCall.Content->values);
std::string name = functionCall.Content->functionName;
std::vector<std::shared_ptr<const Type>> types;
ast::GetTypeVisitor visitor;
for(auto& value : functionCall.Content->values){
types.push_back(visit(visitor, value));
}
std::string mangled = mangle(name, types);
if(name == "println" || name == "print" || name == "duration"){
symbols.addReference(mangled);
return;
}
//If the function does not exists, try implicit conversions to pointers
if(!symbols.exists(mangled)){
auto perms = permutations(types);
for(auto& perm : perms){
mangled = mangle(name, perm);
if(symbols.exists(mangled)){
break;
}
}
}
if(symbols.exists(mangled)){
symbols.addReference(mangled);
functionCall.Content->mangled_name = mangled;
functionCall.Content->function = symbols.getFunction(mangled);
} else {
throw SemanticalException("The function \"" + unmangle(mangled) + "\" does not exists", functionCall.Content->position);
}
}
void operator()(ast::Return& return_){
return_.Content->function = currentFunction;
visit(*this, return_.Content->value);
}
AUTO_IGNORE_OTHERS()
};
void ast::defineFunctions(ast::SourceFile& program){
//First phase : Collect functions
FunctionInserterVisitor inserterVisitor;
inserterVisitor(program);
//Second phase : Verify calls
FunctionCheckerVisitor checkerVisitor;
checkerVisitor(program);
}
<|endoftext|>
|
<commit_before>// SciTE - Scintilla based Text Editor
/** @file MatchMarker.cxx
** Mark all the matches of a string.
**/
// Copyright 1998-2011 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <string>
#include <vector>
#include "Scintilla.h"
#include "GUI.h"
#include "MatchMarker.h"
std::vector<LineRange> LinesBreak(GUI::ScintillaWindow *pSci) {
std::vector<LineRange> lineRanges;
if (pSci) {
const int lineEnd = pSci->Call(SCI_GETLINECOUNT);
const int lineStartVisible = pSci->Call(SCI_GETFIRSTVISIBLELINE);
const int linesOnScreen = pSci->Call(SCI_LINESONSCREEN);
const int surround = 40;
LineRange rangePriority(lineStartVisible - surround, lineStartVisible + linesOnScreen + surround);
if (rangePriority.lineStart < 0)
rangePriority.lineStart = 0;
if (rangePriority.lineEnd > lineEnd)
rangePriority.lineEnd = lineEnd;
lineRanges.push_back(rangePriority);
if (rangePriority.lineEnd < lineEnd)
lineRanges.push_back(LineRange(rangePriority.lineEnd, lineEnd));
if (rangePriority.lineStart > 0)
lineRanges.push_back(LineRange(0, rangePriority.lineStart));
}
return lineRanges;
}
MatchMarker::MatchMarker() :
pSci(0), styleMatch(-1), flagsMatch(0), indicator(0), bookMark(-1) {
}
MatchMarker::~MatchMarker() {
}
void MatchMarker::StartMatch(GUI::ScintillaWindow *pSci_,
std::string textMatch_, int flagsMatch_, int styleMatch_,
int indicator_, int bookMark_) {
lineRanges.clear();
pSci = pSci_;
textMatch = textMatch_;
flagsMatch = flagsMatch_;
styleMatch = styleMatch_;
indicator = indicator_;
bookMark = bookMark_;
lineRanges = LinesBreak(pSci);
// Perform the initial marking immediately to avoid flashing
Continue();
}
bool MatchMarker::Complete() const {
return lineRanges.empty();
}
void MatchMarker::Continue() {
const int segment = 200;
// Remove old indicators if any exist.
pSci->Call(SCI_SETINDICATORCURRENT, indicator);
LineRange rangeSearch = lineRanges[0];
int lineEndSegment = rangeSearch.lineStart + segment;
if (lineEndSegment > rangeSearch.lineEnd)
lineEndSegment = rangeSearch.lineEnd;
// Case sensitive & whole word only.
pSci->Call(SCI_SETSEARCHFLAGS, flagsMatch);
const int positionStart = pSci->Call(SCI_POSITIONFROMLINE, rangeSearch.lineStart);
const int positionEnd = pSci->Call(SCI_POSITIONFROMLINE, lineEndSegment);
pSci->Call(SCI_SETTARGETSTART, positionStart);
pSci->Call(SCI_SETTARGETEND, positionEnd);
pSci->Call(SCI_INDICATORCLEARRANGE, positionStart, positionEnd - positionStart);
//Monitor the amount of time took by the search.
GUI::ElapsedTime searchElapsedTime;
// Find the first occurrence of word.
int posFound = pSci->CallString(
SCI_SEARCHINTARGET, textMatch.length(), textMatch.c_str());
while (posFound != INVALID_POSITION) {
// Limit the search duration to 250 ms. Avoid to freeze editor for huge lines.
if (searchElapsedTime.Duration() > 100.25) {
// Clear all indicators because timer has expired.
pSci->Call(SCI_INDICATORCLEARRANGE, 0, pSci->Call(SCI_GETLENGTH));
lineRanges.clear();
break;
}
int posEndFound = pSci->Call(SCI_GETTARGETEND);
if ((styleMatch < 0) || (styleMatch == pSci->Call(SCI_GETSTYLEAT, posFound))) {
pSci->Call(SCI_INDICATORFILLRANGE, posFound, posEndFound - posFound);
if (bookMark >= 0) {
pSci->Call(SCI_MARKERADD,
pSci->Call(SCI_LINEFROMPOSITION, posFound), bookMark);
}
}
if (posEndFound == posFound) {
// Empty matches are possible for regex
posEndFound = pSci->Call(SCI_POSITIONAFTER, posEndFound);
}
// Try to find next occurrence of word.
pSci->Call(SCI_SETTARGETSTART, posEndFound);
pSci->Call(SCI_SETTARGETEND, positionEnd);
posFound = pSci->CallString(
SCI_SEARCHINTARGET, textMatch.length(), textMatch.c_str());
}
// Retire searched lines
if (lineEndSegment >= rangeSearch.lineEnd) {
lineRanges.erase(lineRanges.begin());
} else {
lineRanges[0].lineStart = lineEndSegment;
}
}
void MatchMarker::Stop() {
pSci = NULL;
lineRanges.clear();
}
<commit_msg>Remove incorrect comment.<commit_after>// SciTE - Scintilla based Text Editor
/** @file MatchMarker.cxx
** Mark all the matches of a string.
**/
// Copyright 1998-2011 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <string>
#include <vector>
#include "Scintilla.h"
#include "GUI.h"
#include "MatchMarker.h"
std::vector<LineRange> LinesBreak(GUI::ScintillaWindow *pSci) {
std::vector<LineRange> lineRanges;
if (pSci) {
const int lineEnd = pSci->Call(SCI_GETLINECOUNT);
const int lineStartVisible = pSci->Call(SCI_GETFIRSTVISIBLELINE);
const int linesOnScreen = pSci->Call(SCI_LINESONSCREEN);
const int surround = 40;
LineRange rangePriority(lineStartVisible - surround, lineStartVisible + linesOnScreen + surround);
if (rangePriority.lineStart < 0)
rangePriority.lineStart = 0;
if (rangePriority.lineEnd > lineEnd)
rangePriority.lineEnd = lineEnd;
lineRanges.push_back(rangePriority);
if (rangePriority.lineEnd < lineEnd)
lineRanges.push_back(LineRange(rangePriority.lineEnd, lineEnd));
if (rangePriority.lineStart > 0)
lineRanges.push_back(LineRange(0, rangePriority.lineStart));
}
return lineRanges;
}
MatchMarker::MatchMarker() :
pSci(0), styleMatch(-1), flagsMatch(0), indicator(0), bookMark(-1) {
}
MatchMarker::~MatchMarker() {
}
void MatchMarker::StartMatch(GUI::ScintillaWindow *pSci_,
std::string textMatch_, int flagsMatch_, int styleMatch_,
int indicator_, int bookMark_) {
lineRanges.clear();
pSci = pSci_;
textMatch = textMatch_;
flagsMatch = flagsMatch_;
styleMatch = styleMatch_;
indicator = indicator_;
bookMark = bookMark_;
lineRanges = LinesBreak(pSci);
// Perform the initial marking immediately to avoid flashing
Continue();
}
bool MatchMarker::Complete() const {
return lineRanges.empty();
}
void MatchMarker::Continue() {
const int segment = 200;
// Remove old indicators if any exist.
pSci->Call(SCI_SETINDICATORCURRENT, indicator);
LineRange rangeSearch = lineRanges[0];
int lineEndSegment = rangeSearch.lineStart + segment;
if (lineEndSegment > rangeSearch.lineEnd)
lineEndSegment = rangeSearch.lineEnd;
pSci->Call(SCI_SETSEARCHFLAGS, flagsMatch);
const int positionStart = pSci->Call(SCI_POSITIONFROMLINE, rangeSearch.lineStart);
const int positionEnd = pSci->Call(SCI_POSITIONFROMLINE, lineEndSegment);
pSci->Call(SCI_SETTARGETSTART, positionStart);
pSci->Call(SCI_SETTARGETEND, positionEnd);
pSci->Call(SCI_INDICATORCLEARRANGE, positionStart, positionEnd - positionStart);
//Monitor the amount of time took by the search.
GUI::ElapsedTime searchElapsedTime;
// Find the first occurrence of word.
int posFound = pSci->CallString(
SCI_SEARCHINTARGET, textMatch.length(), textMatch.c_str());
while (posFound != INVALID_POSITION) {
// Limit the search duration to 250 ms. Avoid to freeze editor for huge lines.
if (searchElapsedTime.Duration() > 100.25) {
// Clear all indicators because timer has expired.
pSci->Call(SCI_INDICATORCLEARRANGE, 0, pSci->Call(SCI_GETLENGTH));
lineRanges.clear();
break;
}
int posEndFound = pSci->Call(SCI_GETTARGETEND);
if ((styleMatch < 0) || (styleMatch == pSci->Call(SCI_GETSTYLEAT, posFound))) {
pSci->Call(SCI_INDICATORFILLRANGE, posFound, posEndFound - posFound);
if (bookMark >= 0) {
pSci->Call(SCI_MARKERADD,
pSci->Call(SCI_LINEFROMPOSITION, posFound), bookMark);
}
}
if (posEndFound == posFound) {
// Empty matches are possible for regex
posEndFound = pSci->Call(SCI_POSITIONAFTER, posEndFound);
}
// Try to find next occurrence of word.
pSci->Call(SCI_SETTARGETSTART, posEndFound);
pSci->Call(SCI_SETTARGETEND, positionEnd);
posFound = pSci->CallString(
SCI_SEARCHINTARGET, textMatch.length(), textMatch.c_str());
}
// Retire searched lines
if (lineEndSegment >= rangeSearch.lineEnd) {
lineRanges.erase(lineRanges.begin());
} else {
lineRanges[0].lineStart = lineEndSegment;
}
}
void MatchMarker::Stop() {
pSci = NULL;
lineRanges.clear();
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// CLASS HEADER
#include <dali/internal/system/tizen-wayland/widget-controller-tizen.h>
// EXTERNAL INCLUDES
#include <bundle.h>
#include <widget_base.h>
// INTERNAL INCLUDES
#include <dali/devel-api/adaptor-framework/accessibility-bridge.h>
namespace Dali
{
namespace Internal
{
namespace Adaptor
{
WidgetImplTizen::WidgetImplTizen(widget_base_instance_h instanceHandle)
: Widget::Impl(),
mInstanceHandle(instanceHandle),
mWindow(),
mWidgetId(),
mUsingKeyEvent(false)
{
}
WidgetImplTizen::~WidgetImplTizen()
{
}
void WidgetImplTizen::SetContentInfo(const std::string& contentInfo)
{
bundle* contentBundle;
bundle_raw* contentBundleRaw = reinterpret_cast<bundle_raw*>(const_cast<char*>(contentInfo.c_str()));
int len = contentInfo.length();
contentBundle = bundle_decode(contentBundleRaw, len);
widget_base_context_set_content_info(mInstanceHandle, contentBundle);
bundle_free(contentBundle);
}
bool WidgetImplTizen::IsKeyEventUsing() const
{
return mUsingKeyEvent;
}
void WidgetImplTizen::SetUsingKeyEvent(bool flag)
{
mUsingKeyEvent = flag;
}
void WidgetImplTizen::SetInformation(Dali::Window window, const std::string& widgetId)
{
using Dali::Accessibility::Bridge;
mWindow = window;
mWidgetId = widgetId;
auto preferredBusName = Bridge::MakeBusNameForWidget(widgetId);
Bridge::GetCurrentBridge()->SetPreferredBusName(preferredBusName);
}
Dali::Window WidgetImplTizen::GetWindow() const
{
return mWindow;
}
std::string WidgetImplTizen::GetWidgetId() const
{
return mWidgetId;
}
} // namespace Adaptor
} // namespace Internal
} // namespace Dali
<commit_msg>[AT-SPI] Suppress some events in Widget windows<commit_after>/*
* Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// CLASS HEADER
#include <dali/internal/system/tizen-wayland/widget-controller-tizen.h>
// EXTERNAL INCLUDES
#include <dali/public-api/actors/layer.h>
#include <bundle.h>
#include <widget_base.h>
// INTERNAL INCLUDES
#include <dali/devel-api/adaptor-framework/accessibility-bridge.h>
#include <dali/devel-api/atspi-interfaces/accessible.h>
namespace Dali
{
namespace Internal
{
namespace Adaptor
{
WidgetImplTizen::WidgetImplTizen(widget_base_instance_h instanceHandle)
: Widget::Impl(),
mInstanceHandle(instanceHandle),
mWindow(),
mWidgetId(),
mUsingKeyEvent(false)
{
}
WidgetImplTizen::~WidgetImplTizen()
{
}
void WidgetImplTizen::SetContentInfo(const std::string& contentInfo)
{
bundle* contentBundle;
bundle_raw* contentBundleRaw = reinterpret_cast<bundle_raw*>(const_cast<char*>(contentInfo.c_str()));
int len = contentInfo.length();
contentBundle = bundle_decode(contentBundleRaw, len);
widget_base_context_set_content_info(mInstanceHandle, contentBundle);
bundle_free(contentBundle);
}
bool WidgetImplTizen::IsKeyEventUsing() const
{
return mUsingKeyEvent;
}
void WidgetImplTizen::SetUsingKeyEvent(bool flag)
{
mUsingKeyEvent = flag;
}
void WidgetImplTizen::SetInformation(Dali::Window window, const std::string& widgetId)
{
using Dali::Accessibility::Bridge;
mWindow = window;
mWidgetId = widgetId;
auto preferredBusName = Bridge::MakeBusNameForWidget(widgetId);
Bridge::GetCurrentBridge()->SetPreferredBusName(preferredBusName);
// Widget should not send window events (which could narrow down the navigation context)
auto& suppressedEvents = Accessibility::Accessible::Get(window.GetRootLayer())->GetSuppressedEvents();
suppressedEvents[Accessibility::AtspiEvent::STATE_CHANGED] = true;
suppressedEvents[Accessibility::AtspiEvent::WINDOW_CHANGED] = true;
}
Dali::Window WidgetImplTizen::GetWindow() const
{
return mWindow;
}
std::string WidgetImplTizen::GetWidgetId() const
{
return mWidgetId;
}
} // namespace Adaptor
} // namespace Internal
} // namespace Dali
<|endoftext|>
|
<commit_before>/*
* PWM_Generator.cpp
*
* Created on: 11. 12. 2016
* Author: michp
*/
#include "PWM_Generator.h"
namespace flyhero
{
PWM_Generator &PWM_Generator::Instance()
{
static PWM_Generator instance;
return instance;
}
PWM_Generator::PWM_Generator()
{
gpio_config_t conf;
conf.intr_type = GPIO_INTR_DISABLE;
conf.mode = GPIO_MODE_OUTPUT;
conf.pull_down_en = GPIO_PULLDOWN_DISABLE;
conf.pull_up_en = GPIO_PULLUP_DISABLE;
conf.pin_bit_mask = GPIO_SEL_14 | GPIO_SEL_25 | GPIO_SEL_26 | GPIO_SEL_27;
gpio_config(&conf);
gpio_set_level(GPIO_NUM_25, 0);
gpio_set_level(GPIO_NUM_26, 0);
gpio_set_level(GPIO_NUM_27, 0);
gpio_set_level(GPIO_NUM_14, 0);
}
void PWM_Generator::Init()
{
ESP_ERROR_CHECK(mcpwm_gpio_init(MCPWM_UNIT_0, MCPWM0A, GPIO_NUM_25));
ESP_ERROR_CHECK(mcpwm_gpio_init(MCPWM_UNIT_0, MCPWM0B, GPIO_NUM_26));
ESP_ERROR_CHECK(mcpwm_gpio_init(MCPWM_UNIT_0, MCPWM1A, GPIO_NUM_27));
ESP_ERROR_CHECK(mcpwm_gpio_init(MCPWM_UNIT_0, MCPWM1B, GPIO_NUM_14));
mcpwm_config_t pwm_config;
pwm_config.cmpr_a = 0;
pwm_config.cmpr_b = 0;
pwm_config.counter_mode = MCPWM_UP_COUNTER;
pwm_config.duty_mode = MCPWM_DUTY_MODE_0;
pwm_config.frequency = 1000;
ESP_ERROR_CHECK(mcpwm_init(MCPWM_UNIT_0, MCPWM_TIMER_0, &pwm_config));
ESP_ERROR_CHECK(mcpwm_init(MCPWM_UNIT_0, MCPWM_TIMER_1, &pwm_config));
ESP_ERROR_CHECK(mcpwm_start(MCPWM_UNIT_0, MCPWM_TIMER_0));
ESP_ERROR_CHECK(mcpwm_start(MCPWM_UNIT_0, MCPWM_TIMER_1));
}
void PWM_Generator::Set_Pulse(Motor_Type motor, uint16_t us)
{
if (us > 1000)
return;
if (motor & MOTOR_FL)
ESP_ERROR_CHECK(mcpwm_set_duty_in_us(MCPWM_UNIT_0, MCPWM_TIMER_0, MCPWM_OPR_A, us));
if (motor & MOTOR_BL)
ESP_ERROR_CHECK(mcpwm_set_duty_in_us(MCPWM_UNIT_0, MCPWM_TIMER_0, MCPWM_OPR_B, us));
if (motor & MOTOR_FR)
ESP_ERROR_CHECK(mcpwm_set_duty_in_us(MCPWM_UNIT_0, MCPWM_TIMER_1, MCPWM_OPR_A, us));
if (motor & MOTOR_BR)
ESP_ERROR_CHECK(mcpwm_set_duty_in_us(MCPWM_UNIT_0, MCPWM_TIMER_1, MCPWM_OPR_B, us));
}
void PWM_Generator::Arm()
{
// we set maximum pulse here
this->Set_Pulse(MOTORS_ALL, 1000);
vTaskDelay(1000 / portTICK_RATE_MS);
// we set minimum pulse here
this->Set_Pulse(MOTORS_ALL, 0);
}
}
<commit_msg>(PWM generator): temporary add 1000 to duty time (https://github.com/michprev/flyhero-esp32-idf/commit/ea15fdcafc60ce614478a4b897cc6d5834979990)<commit_after>/*
* PWM_Generator.cpp
*
* Created on: 11. 12. 2016
* Author: michp
*/
#include "PWM_Generator.h"
namespace flyhero
{
PWM_Generator &PWM_Generator::Instance()
{
static PWM_Generator instance;
return instance;
}
PWM_Generator::PWM_Generator()
{
gpio_config_t conf;
conf.intr_type = GPIO_INTR_DISABLE;
conf.mode = GPIO_MODE_OUTPUT;
conf.pull_down_en = GPIO_PULLDOWN_DISABLE;
conf.pull_up_en = GPIO_PULLUP_DISABLE;
conf.pin_bit_mask = GPIO_SEL_14 | GPIO_SEL_25 | GPIO_SEL_26 | GPIO_SEL_27;
gpio_config(&conf);
gpio_set_level(GPIO_NUM_25, 0);
gpio_set_level(GPIO_NUM_26, 0);
gpio_set_level(GPIO_NUM_27, 0);
gpio_set_level(GPIO_NUM_14, 0);
}
void PWM_Generator::Init()
{
ESP_ERROR_CHECK(mcpwm_gpio_init(MCPWM_UNIT_0, MCPWM0A, GPIO_NUM_25));
ESP_ERROR_CHECK(mcpwm_gpio_init(MCPWM_UNIT_0, MCPWM0B, GPIO_NUM_26));
ESP_ERROR_CHECK(mcpwm_gpio_init(MCPWM_UNIT_0, MCPWM1A, GPIO_NUM_27));
ESP_ERROR_CHECK(mcpwm_gpio_init(MCPWM_UNIT_0, MCPWM1B, GPIO_NUM_14));
mcpwm_config_t pwm_config;
pwm_config.cmpr_a = 0;
pwm_config.cmpr_b = 0;
pwm_config.counter_mode = MCPWM_UP_COUNTER;
pwm_config.duty_mode = MCPWM_DUTY_MODE_0;
pwm_config.frequency = 1000;
ESP_ERROR_CHECK(mcpwm_init(MCPWM_UNIT_0, MCPWM_TIMER_0, &pwm_config));
ESP_ERROR_CHECK(mcpwm_init(MCPWM_UNIT_0, MCPWM_TIMER_1, &pwm_config));
ESP_ERROR_CHECK(mcpwm_start(MCPWM_UNIT_0, MCPWM_TIMER_0));
ESP_ERROR_CHECK(mcpwm_start(MCPWM_UNIT_0, MCPWM_TIMER_1));
}
void PWM_Generator::Set_Pulse(Motor_Type motor, uint16_t us)
{
if (us > 1000)
return;
us += 1000;
if (motor & MOTOR_FL)
ESP_ERROR_CHECK(mcpwm_set_duty_in_us(MCPWM_UNIT_0, MCPWM_TIMER_0, MCPWM_OPR_A, us));
if (motor & MOTOR_BL)
ESP_ERROR_CHECK(mcpwm_set_duty_in_us(MCPWM_UNIT_0, MCPWM_TIMER_0, MCPWM_OPR_B, us));
if (motor & MOTOR_FR)
ESP_ERROR_CHECK(mcpwm_set_duty_in_us(MCPWM_UNIT_0, MCPWM_TIMER_1, MCPWM_OPR_A, us));
if (motor & MOTOR_BR)
ESP_ERROR_CHECK(mcpwm_set_duty_in_us(MCPWM_UNIT_0, MCPWM_TIMER_1, MCPWM_OPR_B, us));
}
void PWM_Generator::Arm()
{
// we set maximum pulse here
this->Set_Pulse(MOTORS_ALL, 1000);
vTaskDelay(1000 / portTICK_RATE_MS);
// we set minimum pulse here
this->Set_Pulse(MOTORS_ALL, 0);
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: shape.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2008-01-17 08:05:45 $
*
* 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 OOX_DRAWINGML_SHAPE_HXX
#define OOX_DRAWINGML_SHAPE_HXX
#include "oox/helper/propertymap.hxx"
#include "oox/drawingml/theme.hxx"
#include "oox/drawingml/lineproperties.hxx"
#include "oox/drawingml/fillproperties.hxx"
#include "oox/drawingml/customshapeproperties.hxx"
#include "oox/drawingml/textbody.hxx"
#include "oox/drawingml/textliststyle.hxx"
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/drawing/XDrawPage.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <vector>
#include <map>
namespace oox { namespace drawingml {
class Shape;
typedef boost::shared_ptr< Shape > ShapePtr;
enum ShapeStyle
{
SHAPESTYLE_ln,
SHAPESTYLE_fill,
SHAPESTYLE_effect,
SHAPESTYLE_font
};
typedef std::map< ShapeStyle, oox::drawingml::ColorPtr > ShapeStylesColorMap;
typedef std::map< ShapeStyle, rtl::OUString > ShapeStylesIndexMap;
class Shape
: public boost::enable_shared_from_this< Shape >
{
public:
Shape( const sal_Char* pServiceType = NULL );
virtual ~Shape();
rtl::OUString& getServiceName(){ return msServiceName; };
void setServiceName( const sal_Char* pServiceName );
PropertyMap& getShapeProperties(){ return maShapeProperties; };
LinePropertiesPtr getLineProperties(){ return mpLinePropertiesPtr; };
FillPropertiesPtr getFillProperties(){ return mpFillPropertiesPtr; };
FillPropertiesPtr getGraphicProperties() { return mpGraphicPropertiesPtr; };
CustomShapePropertiesPtr getCustomShapeProperties(){ return mpCustomShapePropertiesPtr; };
void setPosition( com::sun::star::awt::Point nPosition ){ maPosition = nPosition; };
void setSize( com::sun::star::awt::Size aSize ){ maSize = aSize; };
void setRotation( sal_Int32 nRotation ) { mnRotation = nRotation; };
void setFlip( sal_Bool bFlipH, sal_Bool bFlipV ) { mbFlipH = bFlipH; mbFlipV = bFlipV; };
void addChild( const ShapePtr pChildPtr ) { maChilds.push_back( pChildPtr ); };
std::vector< ShapePtr >& getChilds() { return maChilds; };
void setName( const rtl::OUString& rName ) { msName = rName; };
::rtl::OUString getName( ) { return msName; }
void setId( const rtl::OUString& rId ) { msId = rId; };
void setSubType( sal_uInt32 nSubType ) { mnSubType = nSubType; };
sal_Int32 getSubType() const { return mnSubType; };
void setIndex( sal_uInt32 nIndex ) { mnIndex = nIndex; };
// setDefaults has to be called if styles are imported (OfficeXML is not storing properties having the default value)
void setDefaults();
void setTextBody(const TextBodyPtr & pTextBody);
TextBodyPtr getTextBody();
void setMasterTextListStyle( const TextListStylePtr& pMasterTextListStyle );
TextListStylePtr getMasterTextListStyle() const { return mpMasterTextListStyle; };
ShapeStylesColorMap& getShapeStylesColor(){ return maShapeStylesColorMap; };
ShapeStylesIndexMap& getShapeStylesIndex(){ return maShapeStylesIndexMap; };
// addShape is creating and inserting the corresponding XShape.
void addShape( const oox::core::XmlFilterBase& rFilterBase, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > &rxModel,
const oox::drawingml::ThemePtr, std::map< ::rtl::OUString, ShapePtr > &,
const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >& rxShapes,
const ::com::sun::star::awt::Rectangle* pShapeRect );
const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > & getXShape() const { return mxShape; }
virtual void applyShapeReference( const oox::drawingml::Shape& rReferencedShape );
protected:
::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >
createAndInsert( const oox::core::XmlFilterBase& rFilterBase, const rtl::OUString& rServiceName, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > &rxModel,
const oox::drawingml::ThemePtr pThemePtr, const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >& rxShapes,
const ::com::sun::star::awt::Rectangle* pShapeRect );
void addChilds( const oox::core::XmlFilterBase& rFilterBase, Shape& rMaster, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > &rxModel,
const oox::drawingml::ThemePtr, std::map< ::rtl::OUString, ShapePtr > &,
const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >& rxShapes,
const ::com::sun::star::awt::Rectangle& rClientRect );
std::vector< ShapePtr > maChilds; // only used for group shapes
TextBodyPtr mpTextBody;
LinePropertiesPtr mpLinePropertiesPtr;
FillPropertiesPtr mpFillPropertiesPtr;
FillPropertiesPtr mpGraphicPropertiesPtr;
CustomShapePropertiesPtr mpCustomShapePropertiesPtr;
PropertyMap maShapeProperties;
TextListStylePtr mpMasterTextListStyle;
::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > mxShape;
rtl::OUString msServiceName;
rtl::OUString msName;
rtl::OUString msId;
sal_uInt32 mnSubType; // if this type is not zero, then the shape is a placeholder
sal_uInt32 mnIndex;
ShapeStylesColorMap maShapeStylesColorMap;
ShapeStylesIndexMap maShapeStylesIndexMap;
com::sun::star::awt::Size maSize;
com::sun::star::awt::Point maPosition;
private:
void setShapeStyles( const oox::drawingml::ThemePtr pThemePtr, const oox::core::XmlFilterBase& rFilterBase );
sal_Int32 mnRotation;
sal_Bool mbFlipH;
sal_Bool mbFlipV;
};
} }
#endif // OOX_DRAWINGML_SHAPE_HXX
<commit_msg>INTEGRATION: CWS xmlfilter03_DEV300 (1.2.4); FILE MERGED 2008/02/07 15:18:19 sj 1.2.4.4: fixed some fill/line property problems 2008/02/04 13:31:34 dr 1.2.4.3: rework of fragment handler/context handler base classes 2008/02/01 09:54:06 dr 1.2.4.2: addShape() code cleanup, started xlsx drawing import 2008/01/22 16:42:13 hbrinkm 1.2.4.1: GetShapeType<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: shape.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: kz $ $Date: 2008-03-05 17:42:03 $
*
* 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 OOX_DRAWINGML_SHAPE_HXX
#define OOX_DRAWINGML_SHAPE_HXX
#include "oox/helper/propertymap.hxx"
#include "oox/drawingml/theme.hxx"
#include "oox/drawingml/lineproperties.hxx"
#include "oox/drawingml/fillproperties.hxx"
#include "oox/drawingml/customshapeproperties.hxx"
#include "oox/drawingml/textbody.hxx"
#include "oox/drawingml/textliststyle.hxx"
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/drawing/XDrawPage.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <vector>
#include <map>
namespace oox { namespace drawingml {
class Shape;
typedef boost::shared_ptr< Shape > ShapePtr;
typedef ::std::map< ::rtl::OUString, ShapePtr > ShapeIdMap;
enum ShapeStyle
{
SHAPESTYLE_ln,
SHAPESTYLE_fill,
SHAPESTYLE_effect,
SHAPESTYLE_font
};
typedef std::map< ShapeStyle, ColorPtr > ShapeStylesColorMap;
typedef std::map< ShapeStyle, rtl::OUString > ShapeStylesIndexMap;
class Shape
: public boost::enable_shared_from_this< Shape >
{
public:
Shape( const sal_Char* pServiceType = NULL );
virtual ~Shape();
rtl::OUString& getServiceName(){ return msServiceName; };
void setServiceName( const sal_Char* pServiceName );
PropertyMap& getShapeProperties(){ return maShapeProperties; };
LinePropertiesPtr getLineProperties(){ return mpLinePropertiesPtr; };
FillPropertiesPtr getFillProperties(){ return mpFillPropertiesPtr; };
FillPropertiesPtr getGraphicProperties() { return mpGraphicPropertiesPtr; };
CustomShapePropertiesPtr getCustomShapeProperties(){ return mpCustomShapePropertiesPtr; };
void setPosition( com::sun::star::awt::Point nPosition ){ maPosition = nPosition; };
void setSize( com::sun::star::awt::Size aSize ){ maSize = aSize; };
void setRotation( sal_Int32 nRotation ) { mnRotation = nRotation; };
void setFlip( sal_Bool bFlipH, sal_Bool bFlipV ) { mbFlipH = bFlipH; mbFlipV = bFlipV; };
void addChild( const ShapePtr pChildPtr ) { maChilds.push_back( pChildPtr ); };
std::vector< ShapePtr >& getChilds() { return maChilds; };
void setName( const rtl::OUString& rName ) { msName = rName; };
::rtl::OUString getName( ) { return msName; }
void setId( const rtl::OUString& rId ) { msId = rId; };
void setSubType( sal_uInt32 nSubType ) { mnSubType = nSubType; };
sal_Int32 getSubType() const { return mnSubType; };
void setIndex( sal_uInt32 nIndex ) { mnIndex = nIndex; };
// setDefaults has to be called if styles are imported (OfficeXML is not storing properties having the default value)
void setDefaults();
void setTextBody(const TextBodyPtr & pTextBody);
TextBodyPtr getTextBody();
void setMasterTextListStyle( const TextListStylePtr& pMasterTextListStyle );
TextListStylePtr getMasterTextListStyle() const { return mpMasterTextListStyle; };
ShapeStylesColorMap& getShapeStylesColor(){ return maShapeStylesColorMap; };
ShapeStylesIndexMap& getShapeStylesIndex(){ return maShapeStylesIndexMap; };
// addShape is creating and inserting the corresponding XShape.
void addShape(
const oox::core::XmlFilterBase& rFilterBase,
const ThemePtr& rxTheme,
const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >& rxShapes,
const ::com::sun::star::awt::Rectangle* pShapeRect = 0,
ShapeIdMap* pShapeMap = 0 );
const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > &
getXShape() const { return mxShape; }
virtual void applyShapeReference( const oox::drawingml::Shape& rReferencedShape );
protected:
::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >
createAndInsert(
const ::oox::core::XmlFilterBase& rFilterBase,
const ::rtl::OUString& rServiceName,
const ThemePtr& rxTheme,
const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >& rxShapes,
const ::com::sun::star::awt::Rectangle* pShapeRect );
void addChilds(
const ::oox::core::XmlFilterBase& rFilterBase,
Shape& rMaster,
const ThemePtr& rxTheme,
const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >& rxShapes,
const ::com::sun::star::awt::Rectangle& rClientRect,
ShapeIdMap* pShapeMap );
std::vector< ShapePtr > maChilds; // only used for group shapes
TextBodyPtr mpTextBody;
LinePropertiesPtr mpLinePropertiesPtr;
FillPropertiesPtr mpFillPropertiesPtr;
FillPropertiesPtr mpGraphicPropertiesPtr;
CustomShapePropertiesPtr mpCustomShapePropertiesPtr;
PropertyMap maShapeProperties;
TextListStylePtr mpMasterTextListStyle;
::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > mxShape;
rtl::OUString msServiceName;
rtl::OUString msName;
rtl::OUString msId;
sal_uInt32 mnSubType; // if this type is not zero, then the shape is a placeholder
sal_uInt32 mnIndex;
ShapeStylesColorMap maShapeStylesColorMap;
ShapeStylesIndexMap maShapeStylesIndexMap;
com::sun::star::awt::Size maSize;
com::sun::star::awt::Point maPosition;
private:
void setShapeStyles( const ThemePtr& rxTheme, LineProperties& rLineProperties, FillProperties& rFillProperties );
void setShapeStyleColors( const ::oox::core::XmlFilterBase& rFilterBase,
LineProperties& rLineProperties, FillProperties& rFillProperties, PropertyMap& rShapeProperties );
sal_Int32 mnRotation;
sal_Bool mbFlipH;
sal_Bool mbFlipV;
};
::rtl::OUString GetShapeType( sal_Int32 nType );
} }
#endif // OOX_DRAWINGML_SHAPE_HXX
<|endoftext|>
|
<commit_before>/**
* lengthPrefixStrings.cpp
*
* Author: Patrick Rummage (patrickbrummage@gmail.com)
*
* Objective:
* Implement a string type that stores its length at location[0].
* Define functions to append, concatenate, create substrings, and
* retrieve characters from strings of this type.
*/
#include <iostream>
using std::cin;
using std::cout;
typedef char *lengthString;
char characterAt(lengthString s, int position)
{
return s[position + 1];
}
void append(lengthString &s, char c)
{
int oldLength = s[0];
s[oldLength + 1] = c;
s[0] = oldLength + 1;
}
void concatenate(lengthString &s1, lengthString s2)
{
int s1_length = s1[0];
int s2_length = s2[0];
int newLength = s1_length + s2_length;
lengthString newS = new char[newLength + 1];
newS[0] = newLength;
for (int i = 1; i <= s1_length; i++)
{
newS[i] = s1[i];
}
for (int i = 1; i <= s2_length; i++)
{
newS[s1_length + i] = s2[i];
}
delete[] s1;
s1 = newS;
}
bool stringEqual(lengthString s1, lengthString s2)
{
int s_length = s1[0];
for (int i = 1; i <= s_length; i++)
{
if (s1[i] != s2[i])
{
return false;
}
}
return true;
}
lengthString substring(lengthString s, int position, int length)
{
lengthString sub = new char[length + 1];
sub[0] = length;
for (int i = 0; i < length; i++)
{
sub[1 + i] = s[position + i];
}
return sub;
}
//BROKEN!!
void replaceString(lengthString &s, lengthString target, lengthString replaceText)
{
int s_length = s[0];
int targetLength = target[0];
int replaceLength = replaceText[0];
int newLength = s_length + (replaceLength - targetLength);
lengthString newS = new char[newLength]; //FIX: DO WITHIN LOOP
bool match = false;
for (int i = 1; i <= s_length; i++)
{
if (s[i] == target[1])
{
if (stringEqual(substring(s, i, targetLength), target))
{
concatenate(newS, substring(s, 1, i - 1));
concatenate(newS, replaceText);
concatenate(newS, substring(s, i + targetLength, s_length - (i + 1)));
}
}
}
if (!match)
concatenate(newS, s);
delete[] s;
s = newS;
}
void input(lengthString &s)
{
char inputChar = cin.get();
while (inputChar != 10)
{
append(s, inputChar);
inputChar = cin.get();
}
}
void output(lengthString s)
{
int length = s[0];
for(int i = 1; i <= length; i++)
{
cout << s[i];
}
cout << "\n";
}
int main(int argc, char *argv[])
{
//Test append()
cout << "TESTING append\n";
lengthString string1 = new char[0];
cout << "Enter a string: ";
input(string1);
output(string1);
//Test concatenate()
cout << "**TESTING concatenate**\n";
lengthString string2 = new char[0];
cout << "Enter another string: ";
input(string2);
output(string2);
concatenate(string1, string2);
output(string1);
//Test substring()
cout << "**TESTING subString**\n";
lengthString subString = substring(string1, 3, 4);
output(subString);
//Test replaceString()
cout << "**TESTING replaceString**\n";
lengthString find = new char[0];
lengthString replace = new char[0];
cout << "Enter a string to find: ";
input(find);
cout << "Replace with: ";
input(replace);
replaceString(string1, find, replace);
output(string1);
return 0;
}
<commit_msg>K&R brackets, replaceString partially working<commit_after>/**
* lengthPrefixStrings.cpp
*
* Author: Patrick Rummage (patrickbrummage@gmail.com)
*
* Objective:
* Implement a string type that stores its length at location[0].
* Define functions to append, concatenate, create substrings, and
* retrieve characters from strings of this type.
*/
#include <iostream>
using std::cin;
using std::cout;
typedef char *lengthString;
char characterAt(lengthString s, int position)
{
return s[position + 1];
}
void append(lengthString &s, char c)
{
int oldLength = s[0];
s[oldLength + 1] = c;
s[0] = oldLength + 1;
}
void concatenate(lengthString &s1, lengthString s2)
{
int s1_length = s1[0];
int s2_length = s2[0];
int newLength = s1_length + s2_length;
lengthString newS = new char[newLength + 1];
newS[0] = newLength;
for (int i = 1; i <= s1_length; i++) {
newS[i] = s1[i];
}
for (int i = 1; i <= s2_length; i++) {
newS[s1_length + i] = s2[i];
}
delete[] s1;
s1 = newS;
}
bool stringEqual(lengthString s1, lengthString s2)
{
int s_length = s1[0];
for (int i = 1; i <= s_length; i++) {
if (s1[i] != s2[i]) {
return false;
}
}
return true;
}
lengthString substring(lengthString s, int position, int length)
{
lengthString sub = new char[length + 1];
sub[0] = length;
for (int i = 0; i < length; i++) {
sub[1 + i] = s[position + i];
}
return sub;
}
/*working for single, same-size replacements*/
void replaceString(lengthString &s, lengthString target, lengthString replaceText)
{
int s_length = s[0];
int targetLength = target[0];
int replaceLength = replaceText[0];
for (int i = 1; i <= s_length; i++) {
if (s[i] == target[1] &&
stringEqual(substring(s, i, targetLength), target)) {
int currentLength = s[0]; //In case length has changed
int newLength = currentLength + (replaceLength - targetLength);
/*Allocate and create new string*/
lengthString newS = new char[newLength];
lengthString begin = substring(s, 1, i - 1);
lengthString end = substring(s, i + targetLength, s_length - (i + 1));
concatenate(newS, begin); //Original beginning
concatenate(newS, replaceText); //Replace stuff
concatenate(newS, end); //Original end
delete[] s;
s = newS;
}
}
}
void input(lengthString &s)
{
char inputChar = cin.get();
while (inputChar != 10) {
append(s, inputChar);
inputChar = cin.get();
}
}
void output(lengthString s)
{
int length = s[0];
for(int i = 1; i <= length; i++) {
cout << s[i];
}
cout << "\n";
}
int main(int argc, char *argv[])
{
//Test append()
cout << "TESTING append\n";
lengthString string1 = new char[0];
cout << "Enter a string: ";
input(string1);
output(string1);
//Test concatenate()
cout << "**TESTING concatenate**\n";
lengthString string2 = new char[0];
cout << "Enter another string: ";
input(string2);
output(string2);
concatenate(string1, string2);
output(string1);
//Test substring()
cout << "**TESTING subString**\n";
lengthString subString = substring(string1, 3, 4);
output(subString);
//Test replaceString()
cout << "**TESTING replaceString**\n";
lengthString find = new char[0];
lengthString replace = new char[0];
cout << "Enter a string to find: ";
input(find);
cout << "Replace with: ";
input(replace);
replaceString(string1, find, replace);
output(string1);
return 0;
}
<|endoftext|>
|
<commit_before>#ifndef OPENGM_NEW_VISITOR_HXX
#define OPENGM_NEW_VISITOR_HXX
#include <iostream>
#include <map>
#include <opengm/opengm.hxx>
#include <opengm/utilities/timer.hxx>
namespace opengm{
namespace visitors{
struct VisitorReturnFlag{
const static size_t ContinueInf = 0;
const static size_t StopInfBoundReached = 1;
const static size_t StopInfTimeout = 2;
};
template<class INFERENCE>
class EmptyVisitor{
public:
EmptyVisitor(){
}
void begin(INFERENCE & inf){}
size_t operator()(INFERENCE & inf){
return VisitorReturnFlag::ContinueInf;
}
void end(INFERENCE & inf){
}
};
template<class INFERENCE>
class ExplicitEmptyVisitor{
public:
ExplicitEmptyVisitor(){
}
void begin(INFERENCE & inf, const typename INFERENCE::ValueType value, const typename INFERENCE::ValueType bound){}
size_t operator()(INFERENCE & inf, const typename INFERENCE::ValueType value, const typename INFERENCE::ValueType bound){
return VisitorReturnFlag::ContinueInf;
}
void end(INFERENCE & inf, const typename INFERENCE::ValueType value, const typename INFERENCE::ValueType bound){
}
};
template<class INFERENCE>
class VerboseVisitor{
public:
VerboseVisitor(const size_t visithNth=1,const bool multiline=false)
: iteration_(0),
visithNth_(visithNth),
multiline_(multiline){
}
void begin(INFERENCE & inf){
std::cout<<"begin: value "<<inf.value()<<" bound "<<inf.bound()<<"\n";
++iteration_;
}
size_t operator()(INFERENCE & inf){
if((iteration_)%visithNth_==0){
std::cout<<"step: "<<iteration_<<" value "<<inf.value()<<" bound "<<inf.bound()<<"\n";
}
++iteration_;
return VisitorReturnFlag::ContinueInf;
}
void end(INFERENCE & inf){
std::cout<<"value "<<inf.value()<<" bound "<<inf.bound()<<"\n";
}
private:
size_t iteration_;
size_t visithNth_;
bool multiline_;
};
template<class INFERENCE>
class ExplicitVerboseVisitor{
public:
ExplicitVerboseVisitor(const size_t visithNth=1,const bool multiline=false)
: iteration_(0),
visithNth_(visithNth),
multiline_(multiline){
}
void begin(INFERENCE & inf, const typename INFERENCE::ValueType value, const typename INFERENCE::ValueType bound){
std::cout<<"begin: value "<< value <<" bound "<< bound <<"\n";
++iteration_;
}
size_t operator()(INFERENCE & inf, const typename INFERENCE::ValueType value, const typename INFERENCE::ValueType bound){
if((iteration_)%visithNth_==0){
std::cout<<"step: "<<iteration_<<" value "<< value <<" bound "<< bound <<"\n";
}
++iteration_;
return VisitorReturnFlag::ContinueInf;
}
void end(INFERENCE & inf, const typename INFERENCE::ValueType value, const typename INFERENCE::ValueType bound){
std::cout<<"value "<< value <<" bound "<< bound <<"\n";
}
private:
size_t iteration_;
size_t visithNth_;
bool multiline_;
};
template<class INFERENCE>
class TimingVisitor{
public:
typedef typename INFERENCE::ValueType ValueType;
TimingVisitor(
const size_t visithNth=1,
const size_t reserve=0,
const bool verbose=true,
const bool multiline=true,
const double timeLimit=std::numeric_limits<double>::infinity(),
const double gapLimit=0.0
)
:
protocolMap_(),
times_(),
values_(),
bounds_(),
iterations_(),
timer_(),
iteration_(0),
visithNth_(visithNth),
verbose_(verbose),
multiline_(multiline),
timeLimit_(timeLimit),
gapLimit_(gapLimit),
totalTime_(0.0)
{
// allocate all protocolated items
ctime_ = & protocolMap_["ctime"] ;
times_ = & protocolMap_["times"] ;
values_ = & protocolMap_["values"] ;
bounds_ = & protocolMap_["bounds"] ;
iterations_ = & protocolMap_["iteration"];
// reservations
if(reserve>0){
times_->reserve(reserve);
values_->reserve(reserve);
bounds_->reserve(reserve);
iterations_->reserve(reserve);
}
// start timer to measure time from
// constructor call to "begin" call
timer_.tic();
}
void begin(INFERENCE & inf){
// stop timer which measured time from
// constructor call to this "begin" call
timer_.toc();
// store values bound time and iteration number
const ValueType val=inf.value();
const ValueType bound=inf.bound();
ctime_->push_back(timer_.elapsedTime());
times_->push_back(0);
values_->push_back(val);
bounds_->push_back(bound);
iterations_->push_back(double(iteration_));
// print step
if(verbose_)
std::cout<<"value "<<val<<" bound "<<bound<<"\n";
// increment iteration
++iteration_;
// restart timer
timer_.reset();
timer_.tic();
}
size_t operator()(INFERENCE & inf){
if(iteration_%visithNth_==0){
// stop timer
timer_.toc();
// store values bound time and iteration number
const ValueType val =inf.value();
const ValueType bound =inf.bound();
const double t = timer_.elapsedTime();
times_->push_back(t);
values_->push_back(val);
bounds_->push_back(bound);
iterations_->push_back(double(iteration_));
// increment total time
totalTime_+=t;
if(verbose_){
std::cout<<"step: "<<iteration_<<" value "<<val<<" bound "<<bound<<" [ "<<totalTime_ << "]" <<"\n";
}
// check if gap limit reached
if(std::fabs(bound - val) <= gapLimit_){
if(verbose_)
std::cout<<"gap limit reached\n";
// restart timer
timer_.reset();
timer_.tic();
return VisitorReturnFlag::StopInfBoundReached;
}
// check if time limit reached
if(totalTime_ > timeLimit_) {
if(verbose_)
std::cout<<"timeout reached\n";
// restart timer
timer_.reset();
timer_.tic();
return VisitorReturnFlag::StopInfTimeout;
}
// restart timer
timer_.reset();
timer_.tic();
}
++iteration_;
return VisitorReturnFlag::ContinueInf;
}
void end(INFERENCE & inf){
// stop timer
timer_.toc();
// store values bound time and iteration number
const ValueType val=inf.value();
const ValueType bound=inf.bound();
times_->push_back(timer_.elapsedTime());
values_->push_back(val);
bounds_->push_back(bound);
iterations_->push_back(double(iteration_));
if(verbose_){
std::cout<<"value "<<val<<" bound "<<bound<<"\n";
}
}
// timing visitor specific interface
const std::map< std::string, std::vector<double > > & protocolMap()const{
return protocolMap_;
}
const std::vector<double> & getConstructionTime()const{
return *ctime_;
}
const std::vector<double> & getTimes ()const{
return *times_;
}
const std::vector<double> & getValues ()const{
return *values_;
}
const std::vector<double> & getBounds ()const{
return *bounds_;
}
const std::vector<double> & getIterations ()const{
return *iterations_;
}
private:
std::map< std::string, std::vector<double > > protocolMap_;
std::vector<double > * ctime_;
std::vector<double > * times_;
std::vector<double > * values_;
std::vector<double > * bounds_;
std::vector<double > * iterations_;
opengm::Timer timer_;
opengm::Timer totalTimer_;
size_t iteration_;
size_t visithNth_;
bool verbose_;
bool multiline_;
double timeLimit_;
double gapLimit_;
double totalTime_;
};
template<class INFERENCE>
class ExplicitTimingVisitor{
public:
typedef typename INFERENCE::ValueType ValueType;
ExplicitTimingVisitor(
const size_t visithNth=1,
const size_t reserve=0,
const bool verbose=true,
const bool multiline=true,
const double timeLimit=std::numeric_limits<double>::infinity(),
const double gapLimit=0.0
)
:
protocolMap_(),
times_(),
values_(),
bounds_(),
iterations_(),
timer_(),
iteration_(0),
visithNth_(visithNth),
verbose_(verbose),
multiline_(multiline),
timeLimit_(timeLimit),
gapLimit_(gapLimit),
totalTime_(0.0)
{
// allocate all protocolated items
ctime_ = & protocolMap_["ctime"] ;
times_ = & protocolMap_["times"] ;
values_ = & protocolMap_["values"] ;
bounds_ = & protocolMap_["bounds"] ;
iterations_ = & protocolMap_["iteration"];
// reservations
if(reserve>0){
times_->reserve(reserve);
values_->reserve(reserve);
bounds_->reserve(reserve);
iterations_->reserve(reserve);
}
// start timer to measure time from
// constructor call to "begin" call
timer_.tic();
}
void begin(INFERENCE & inf, const typename INFERENCE::ValueType value, const typename INFERENCE::ValueType bound){
// stop timer which measured time from
// constructor call to this "begin" call
timer_.toc();
// store values bound time and iteration number
ctime_->push_back(timer_.elapsedTime());
times_->push_back(0);
values_->push_back(value);
bounds_->push_back(bound);
iterations_->push_back(double(iteration_));
// print step
if(verbose_)
std::cout<<"value "<<value<<" bound "<<bound<<"\n";
// increment iteration
++iteration_;
// restart timer
timer_.reset();
timer_.tic();
}
size_t operator()(INFERENCE & inf, const typename INFERENCE::ValueType value, const typename INFERENCE::ValueType bound){
if(iteration_%visithNth_==0){
// stop timer
timer_.toc();
// store values bound time and iteration number
const double t = timer_.elapsedTime();
times_->push_back(t);
values_->push_back(value);
bounds_->push_back(bound);
iterations_->push_back(double(iteration_));
// increment total time
totalTime_+=t;
if(verbose_){
std::cout<<"step: "<<iteration_<<" value "<<value<<" bound "<<bound<<" [ "<<totalTime_ << "]" <<"\n";
}
// check if gap limit reached
if(std::fabs(bound - value) <= gapLimit_){
if(verbose_)
std::cout<<"gap limit reached\n";
// restart timer
timer_.reset();
timer_.tic();
return VisitorReturnFlag::StopInfBoundReached;
}
// check if time limit reached
if(totalTime_ > timeLimit_) {
if(verbose_)
std::cout<<"timeout reached\n";
// restart timer
timer_.reset();
timer_.tic();
return VisitorReturnFlag::StopInfTimeout;
}
// restart timer
timer_.reset();
timer_.tic();
}
++iteration_;
return VisitorReturnFlag::ContinueInf;
}
void end(INFERENCE & inf, const typename INFERENCE::ValueType value, const typename INFERENCE::ValueType bound){
// stop timer
timer_.toc();
// store values bound time and iteration number
times_->push_back(timer_.elapsedTime());
values_->push_back(value);
bounds_->push_back(bound);
iterations_->push_back(double(iteration_));
if(verbose_){
std::cout<<"value "<<value<<" bound "<<bound<<"\n";
}
}
// timing visitor specific interface
const std::map< std::string, std::vector<double > > & protocolMap()const{
return protocolMap_;
}
const std::vector<double> & getConstructionTime()const{
return *ctime_;
}
const std::vector<double> & getTimes ()const{
return *times_;
}
const std::vector<double> & getValues ()const{
return *values_;
}
const std::vector<double> & getBounds ()const{
return *bounds_;
}
const std::vector<double> & getIterations ()const{
return *iterations_;
}
private:
std::map< std::string, std::vector<double > > protocolMap_;
std::vector<double > * ctime_;
std::vector<double > * times_;
std::vector<double > * values_;
std::vector<double > * bounds_;
std::vector<double > * iterations_;
opengm::Timer timer_;
opengm::Timer totalTimer_;
size_t iteration_;
size_t visithNth_;
bool verbose_;
bool multiline_;
double timeLimit_;
double gapLimit_;
double totalTime_;
};
}
}
#endif //OPENGM_NEW_VISITOR_HXX
<commit_msg>implmented addLog and log<commit_after>#ifndef OPENGM_NEW_VISITOR_HXX
#define OPENGM_NEW_VISITOR_HXX
#include <iostream>
#include <map>
#include <opengm/opengm.hxx>
#include <opengm/utilities/timer.hxx>
namespace opengm{
namespace visitors{
struct VisitorReturnFlag{
const static size_t ContinueInf = 0;
const static size_t StopInfBoundReached = 1;
const static size_t StopInfTimeout = 2;
};
template<class INFERENCE>
class EmptyVisitor{
public:
EmptyVisitor(){
}
void begin(INFERENCE & inf){}
size_t operator()(INFERENCE & inf){
return VisitorReturnFlag::ContinueInf;
}
void end(INFERENCE & inf){
}
void addLog(const std::string & logName){}
void log(const std::string & logName,const double logValue){}
};
template<class INFERENCE>
class ExplicitEmptyVisitor{
public:
ExplicitEmptyVisitor(){
}
void begin(INFERENCE & inf, const typename INFERENCE::ValueType value, const typename INFERENCE::ValueType bound){}
size_t operator()(INFERENCE & inf, const typename INFERENCE::ValueType value, const typename INFERENCE::ValueType bound){
return VisitorReturnFlag::ContinueInf;
}
void end(INFERENCE & inf, const typename INFERENCE::ValueType value, const typename INFERENCE::ValueType bound){
}
};
template<class INFERENCE>
class VerboseVisitor{
public:
VerboseVisitor(const size_t visithNth=1,const bool multiline=false)
: iteration_(0),
visithNth_(visithNth),
multiline_(multiline){
}
void begin(INFERENCE & inf){
std::cout<<"begin: value "<<inf.value()<<" bound "<<inf.bound()<<"\n";
++iteration_;
}
size_t operator()(INFERENCE & inf){
if((iteration_)%visithNth_==0){
std::cout<<"step: "<<iteration_<<" value "<<inf.value()<<" bound "<<inf.bound()<<"\n";
}
++iteration_;
return VisitorReturnFlag::ContinueInf;
}
void end(INFERENCE & inf){
std::cout<<"value "<<inf.value()<<" bound "<<inf.bound()<<"\n";
}
void addLog(const std::string & logName){}
void log(const std::string & logName,const double logValue){
if((iteration_)%visithNth_==0){
std::cout<<logName<<" "<<logValue<<"\n";
}
}
private:
size_t iteration_;
size_t visithNth_;
bool multiline_;
};
template<class INFERENCE>
class ExplicitVerboseVisitor{
public:
ExplicitVerboseVisitor(const size_t visithNth=1,const bool multiline=false)
: iteration_(0),
visithNth_(visithNth),
multiline_(multiline){
}
void begin(INFERENCE & inf, const typename INFERENCE::ValueType value, const typename INFERENCE::ValueType bound){
std::cout<<"begin: value "<< value <<" bound "<< bound <<"\n";
++iteration_;
}
size_t operator()(INFERENCE & inf, const typename INFERENCE::ValueType value, const typename INFERENCE::ValueType bound){
if((iteration_)%visithNth_==0){
std::cout<<"step: "<<iteration_<<" value "<< value <<" bound "<< bound <<"\n";
}
++iteration_;
return VisitorReturnFlag::ContinueInf;
}
void end(INFERENCE & inf, const typename INFERENCE::ValueType value, const typename INFERENCE::ValueType bound){
std::cout<<"value "<< value <<" bound "<< bound <<"\n";
}
private:
size_t iteration_;
size_t visithNth_;
bool multiline_;
};
template<class INFERENCE>
class TimingVisitor{
public:
typedef typename INFERENCE::ValueType ValueType;
TimingVisitor(
const size_t visithNth=1,
const size_t reserve=0,
const bool verbose=true,
const bool multiline=true,
const double timeLimit=std::numeric_limits<double>::infinity(),
const double gapLimit=0.0
)
:
protocolMap_(),
times_(),
values_(),
bounds_(),
iterations_(),
timer_(),
iteration_(0),
visithNth_(visithNth),
verbose_(verbose),
multiline_(multiline),
timeLimit_(timeLimit),
gapLimit_(gapLimit),
totalTime_(0.0)
{
// allocate all protocolated items
ctime_ = & protocolMap_["ctime"] ;
times_ = & protocolMap_["times"] ;
values_ = & protocolMap_["values"] ;
bounds_ = & protocolMap_["bounds"] ;
iterations_ = & protocolMap_["iteration"];
// reservations
if(reserve>0){
times_->reserve(reserve);
values_->reserve(reserve);
bounds_->reserve(reserve);
iterations_->reserve(reserve);
}
// start timer to measure time from
// constructor call to "begin" call
timer_.tic();
}
void begin(INFERENCE & inf){
// stop timer which measured time from
// constructor call to this "begin" call
timer_.toc();
// store values bound time and iteration number
const ValueType val=inf.value();
const ValueType bound=inf.bound();
ctime_->push_back(timer_.elapsedTime());
times_->push_back(0);
values_->push_back(val);
bounds_->push_back(bound);
iterations_->push_back(double(iteration_));
// print step
if(verbose_)
std::cout<<"value "<<val<<" bound "<<bound<<"\n";
// increment iteration
++iteration_;
// restart timer
timer_.reset();
timer_.tic();
}
size_t operator()(INFERENCE & inf){
if(iteration_%visithNth_==0){
// stop timer
timer_.toc();
// store values bound time and iteration number
const ValueType val =inf.value();
const ValueType bound =inf.bound();
const double t = timer_.elapsedTime();
times_->push_back(t);
values_->push_back(val);
bounds_->push_back(bound);
iterations_->push_back(double(iteration_));
for(size_t el=0;el<extraLogs_.size();++el){
protocolMap_[extraLogs_[el]].push_back( std::numeric_limits<double>::quiet_NaN() );
}
// increment total time
totalTime_+=t;
if(verbose_){
std::cout<<"step: "<<iteration_<<" value "<<val<<" bound "<<bound<<" [ "<<totalTime_ << "]" <<"\n";
}
// check if gap limit reached
if(std::fabs(bound - val) <= gapLimit_){
if(verbose_)
std::cout<<"gap limit reached\n";
// restart timer
timer_.reset();
timer_.tic();
return VisitorReturnFlag::StopInfBoundReached;
}
// check if time limit reached
if(totalTime_ > timeLimit_) {
if(verbose_)
std::cout<<"timeout reached\n";
// restart timer
timer_.reset();
timer_.tic();
return VisitorReturnFlag::StopInfTimeout;
}
// restart timer
timer_.reset();
timer_.tic();
}
++iteration_;
return VisitorReturnFlag::ContinueInf;
}
void end(INFERENCE & inf){
// stop timer
timer_.toc();
// store values bound time and iteration number
const ValueType val=inf.value();
const ValueType bound=inf.bound();
times_->push_back(timer_.elapsedTime());
values_->push_back(val);
bounds_->push_back(bound);
iterations_->push_back(double(iteration_));
if(verbose_){
std::cout<<"value "<<val<<" bound "<<bound<<"\n";
}
}
void addLog(const std::string & logName){
protocolMap_[logName]=std::vector<double>();
extraLogs_.push_back(logName);
}
void log(const std::string & logName,const double logValue){
if((iteration_)%visithNth_==0){
timer_.toc();
if(verbose_){
std::cout<<logName<<" "<<logValue<<"\n";
}
protocolMap_[logName].back()=logValue;
// start timer
timer_.tic();
}
}
// timing visitor specific interface
const std::map< std::string, std::vector<double > > & protocolMap()const{
return protocolMap_;
}
const std::vector<double> & getConstructionTime()const{
return *ctime_;
}
const std::vector<double> & getTimes ()const{
return *times_;
}
const std::vector<double> & getValues ()const{
return *values_;
}
const std::vector<double> & getBounds ()const{
return *bounds_;
}
const std::vector<double> & getIterations ()const{
return *iterations_;
}
private:
std::map< std::string, std::vector<double > > protocolMap_;
std::vector<std::string> extraLogs_;
std::vector<double > * ctime_;
std::vector<double > * times_;
std::vector<double > * values_;
std::vector<double > * bounds_;
std::vector<double > * iterations_;
opengm::Timer timer_;
opengm::Timer totalTimer_;
size_t iteration_;
size_t visithNth_;
bool verbose_;
bool multiline_;
double timeLimit_;
double gapLimit_;
double totalTime_;
};
template<class INFERENCE>
class ExplicitTimingVisitor{
public:
typedef typename INFERENCE::ValueType ValueType;
ExplicitTimingVisitor(
const size_t visithNth=1,
const size_t reserve=0,
const bool verbose=true,
const bool multiline=true,
const double timeLimit=std::numeric_limits<double>::infinity(),
const double gapLimit=0.0
)
:
protocolMap_(),
times_(),
values_(),
bounds_(),
iterations_(),
timer_(),
iteration_(0),
visithNth_(visithNth),
verbose_(verbose),
multiline_(multiline),
timeLimit_(timeLimit),
gapLimit_(gapLimit),
totalTime_(0.0)
{
// allocate all protocolated items
ctime_ = & protocolMap_["ctime"] ;
times_ = & protocolMap_["times"] ;
values_ = & protocolMap_["values"] ;
bounds_ = & protocolMap_["bounds"] ;
iterations_ = & protocolMap_["iteration"];
// reservations
if(reserve>0){
times_->reserve(reserve);
values_->reserve(reserve);
bounds_->reserve(reserve);
iterations_->reserve(reserve);
}
// start timer to measure time from
// constructor call to "begin" call
timer_.tic();
}
void begin(INFERENCE & inf, const typename INFERENCE::ValueType value, const typename INFERENCE::ValueType bound){
// stop timer which measured time from
// constructor call to this "begin" call
timer_.toc();
// store values bound time and iteration number
ctime_->push_back(timer_.elapsedTime());
times_->push_back(0);
values_->push_back(value);
bounds_->push_back(bound);
iterations_->push_back(double(iteration_));
// print step
if(verbose_)
std::cout<<"value "<<value<<" bound "<<bound<<"\n";
// increment iteration
++iteration_;
// restart timer
timer_.reset();
timer_.tic();
}
size_t operator()(INFERENCE & inf, const typename INFERENCE::ValueType value, const typename INFERENCE::ValueType bound){
if(iteration_%visithNth_==0){
// stop timer
timer_.toc();
// store values bound time and iteration number
const double t = timer_.elapsedTime();
times_->push_back(t);
values_->push_back(value);
bounds_->push_back(bound);
iterations_->push_back(double(iteration_));
// increment total time
totalTime_+=t;
if(verbose_){
std::cout<<"step: "<<iteration_<<" value "<<value<<" bound "<<bound<<" [ "<<totalTime_ << "]" <<"\n";
}
// check if gap limit reached
if(std::fabs(bound - value) <= gapLimit_){
if(verbose_)
std::cout<<"gap limit reached\n";
// restart timer
timer_.reset();
timer_.tic();
return VisitorReturnFlag::StopInfBoundReached;
}
// check if time limit reached
if(totalTime_ > timeLimit_) {
if(verbose_)
std::cout<<"timeout reached\n";
// restart timer
timer_.reset();
timer_.tic();
return VisitorReturnFlag::StopInfTimeout;
}
// restart timer
timer_.reset();
timer_.tic();
}
++iteration_;
return VisitorReturnFlag::ContinueInf;
}
void end(INFERENCE & inf, const typename INFERENCE::ValueType value, const typename INFERENCE::ValueType bound){
// stop timer
timer_.toc();
// store values bound time and iteration number
times_->push_back(timer_.elapsedTime());
values_->push_back(value);
bounds_->push_back(bound);
iterations_->push_back(double(iteration_));
if(verbose_){
std::cout<<"value "<<value<<" bound "<<bound<<"\n";
}
}
// timing visitor specific interface
const std::map< std::string, std::vector<double > > & protocolMap()const{
return protocolMap_;
}
const std::vector<double> & getConstructionTime()const{
return *ctime_;
}
const std::vector<double> & getTimes ()const{
return *times_;
}
const std::vector<double> & getValues ()const{
return *values_;
}
const std::vector<double> & getBounds ()const{
return *bounds_;
}
const std::vector<double> & getIterations ()const{
return *iterations_;
}
private:
std::map< std::string, std::vector<double > > protocolMap_;
std::vector<double > * ctime_;
std::vector<double > * times_;
std::vector<double > * values_;
std::vector<double > * bounds_;
std::vector<double > * iterations_;
opengm::Timer timer_;
opengm::Timer totalTimer_;
size_t iteration_;
size_t visithNth_;
bool verbose_;
bool multiline_;
double timeLimit_;
double gapLimit_;
double totalTime_;
};
}
}
#endif //OPENGM_NEW_VISITOR_HXX
<|endoftext|>
|
<commit_before>#include "Label.hpp"
namespace cstr
{
Label::Label(const sf::Vector2f& pos, const std::string& str, const sf::Font& font)
{
text.setFont(font);
text.setString(str);
text.setOrigin(text.getGlobalBounds().left + text.getGlobalBounds().width / 2, text.getGlobalBounds().top + text.getGlobalBounds().height / 2);
position = pos;
text.setPosition(position);
}
Label::~Label()
{
}
void Label::setFont(const sf::Font& font)
{
text.setFont(font);
text.setOrigin(text.getGlobalBounds().left + text.getGlobalBounds().width / 2, text.getGlobalBounds().top + text.getGlobalBounds().height / 2);
text.setPosition(position);
}
void Label::setText(const std::string& str)
{
text.setString(str);
text.setOrigin(text.getGlobalBounds().left + text.getGlobalBounds().width / 2, text.getGlobalBounds().top + text.getGlobalBounds().height / 2);
text.setPosition(position);
}
void Label::setTextColor(const sf::Color& tc)
{
text.setColor(tc);
}
bool Label::contains(sf::Vector2i /*point*/)
{
return false;
}
void Label::mousePressed()
{
}
void Label::mouseReleased()
{
}
void Label::mouseMovedOn()
{
}
void Label::mouseMovedOff()
{
}
void Label::textEntered(char /*c*/)
{
}
void Label::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
target.draw(text, states);
}
}
<commit_msg>Changed Label origin to top left<commit_after>#include "Label.hpp"
namespace cstr
{
Label::Label(const sf::Vector2f& pos, const std::string& str, const sf::Font& font)
{
text.setFont(font);
text.setString(str);
position = pos;
text.setPosition(position);
}
Label::~Label()
{
}
void Label::setFont(const sf::Font& font)
{
text.setFont(font);
text.setPosition(position);
}
void Label::setText(const std::string& str)
{
text.setString(str);
text.setPosition(position);
}
void Label::setTextColor(const sf::Color& tc)
{
text.setColor(tc);
}
bool Label::contains(sf::Vector2i /*point*/)
{
return false;
}
void Label::mousePressed()
{
}
void Label::mouseReleased()
{
}
void Label::mouseMovedOn()
{
}
void Label::mouseMovedOff()
{
}
void Label::textEntered(char /*c*/)
{
}
void Label::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
target.draw(text, states);
}
}
<|endoftext|>
|
<commit_before>#include "utils.h"
#if defined(Q_OS_WIN)
#include <windows.h>
#include <winsock2.h>
#include <winnt.h>
#include <shellapi.h>
#elif defined(Q_OS_LINUX)
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define SOCKET_ERROR (-1)
#elif defined(Q_OS_DARWIN)
#include <CoreFoundation/CoreFoundation.h>
#include <CoreServices/CoreServices.h>
#include "darwin/AppHandler.h"
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define SOCKET_ERROR (-1)
#endif
#include "modelserializer.h"
#include "modeldeserializer.h"
#include <algorithm>
#include <iterator>
#include <QObject>
#include <QStringList>
#include <QDir>
#include <QFont>
#include <QByteArray>
#include <QUrl>
#include <QMetaProperty>
#include <QDebug>
#include <QCoreApplication>
#include <QApplication>
#include <QMainWindow>
#include <set>
#include <map>
#include "version.hxx"
namespace {
int getEscape(const QChar* uc, int* pos, int len, int maxNumber = 999)
{
int i = *pos;
++i;
if (i < len && uc[i] == QLatin1Char('L'))
{
++i;
}
if (i < len)
{
int escape = uc[i].unicode() - '0';
if (uint(escape) >= 10U)
{
return -1;
}
++i;
while (i < len)
{
int digit = uc[i].unicode() - '0';
if (uint(digit) >= 10U)
{
break;
}
escape = (escape * 10) + digit;
++i;
}
if (escape <= maxNumber)
{
*pos = i;
return escape;
}
}
return -1;
}
bool isPortAvalible(unsigned short int dwPort, int type)
{
struct sockaddr_in client;
client.sin_family = AF_INET;
client.sin_port = htons(dwPort);
client.sin_addr.s_addr = inet_addr("127.0.0.1");
auto sock = socket(AF_INET, type, 0);
int result = bind(sock, (struct sockaddr*) &client, sizeof(client));
#ifdef Q_OS_WIN
closesocket(sock);
#else
close(sock);
#endif
return result != SOCKET_ERROR;
}
} // namespace
namespace utilities
{
const char* const kURLPrefixes[] = { "http://", "https://", "vidxden://1", "ftp://", "file://", "magnet:?" };
const auto kNumberOfPrefixes = sizeof(kURLPrefixes) / sizeof(kURLPrefixes[0]);
const int kOffsetPastSeparator[kNumberOfPrefixes] = { 3, 3, 4, 3, 3, 2 };
QStringList ParseUrls(const QString& data)
{
const QStringList list = data.split(QRegExp("[\\s\\\"\\n]+"), QString::SkipEmptyParts);
QStringList res;
for (const auto& v : list)
{
QString t = v.trimmed();
if (t.isEmpty())
{
continue;
}
QUrl url;
int offset = t.indexOf(':');
if (offset != -1)
{
// fix for urls that have few starting symbols lost
for (size_t i = 0; i < kNumberOfPrefixes; ++i)
{
int start = offset + kOffsetPastSeparator[i];
QString protocol_prefix = t.left(start);
QString prefix(kURLPrefixes[i]);
if (prefix.endsWith(protocol_prefix, Qt::CaseInsensitive))
{
url.setUrl(prefix + t.mid(start).remove('"'));
break;
}
}
}
if (url.isValid())
{
res << url.toString();
}
else if (QRegExp("^[a-z]:[\\\\/]|^/|^~/", Qt::CaseInsensitive).indexIn(t) != -1)
{
res << t;
}
}
return res;
}
void InitializeProjectDescription()
{
QCoreApplication::setApplicationVersion(PROJECT_VERSION);
QCoreApplication::setApplicationName(PROJECT_NAME);
QCoreApplication::setOrganizationName(PROJECT_NAME);
QCoreApplication::setOrganizationDomain(PROJECT_DOMAIN);
}
QFont GetAdaptedFont(int size, int additional_amount)
{
Q_UNUSED(additional_amount)
#ifdef Q_OS_DARWIN
QFont f("Lucida Grande");
f.setPixelSize(size + additional_amount);
return f;
#else
const float koef = 4 / 3.f;
QFont f("Segoe UI");
f.setPixelSize(size * koef);
return f;
#endif
}
///////////////////////////////////////////////////////////////////////////////
bool DeserializeObject(QXmlStreamReader* stream, QObject* object, const QString& name)
{
Q_ASSERT(stream);
ModelDeserializer deserializer(*stream);
return deserializer.deserialize(object, name);
}
void SerializeObject(QXmlStreamWriter* stream, QObject* object, const QString& name)
{
Q_ASSERT(stream);
ModelSerializer serializer(*stream);
serializer.serialize(object, name);
}
///////////////////////////////////////////////////////////////////////////////
QString SizeToString(quint64 size, int precision, int fieldWidth)
{
const unsigned int Kbytes_limit = 1 << 10; //1 Kb
const unsigned int Mbytes_limit = 1 << 20; //1 Mb
const unsigned int Gbytes_limit = 1 << 30; //1 Gb
if (size < Kbytes_limit)
{
return QStringLiteral("%1 B").arg(size);
}
else if (size < Mbytes_limit)
{
const double sizef = size / static_cast<double>(Kbytes_limit);
return QStringLiteral("%1 kB").arg(sizef, fieldWidth, 'f', precision);
}
else if (size < Gbytes_limit)
{
const double sizef = size / static_cast<double>(Mbytes_limit);
return QStringLiteral("%1 MB").arg(sizef, fieldWidth, 'f', precision);
}
const double sizef = size / static_cast<double>(Gbytes_limit);
return QStringLiteral("%1 GB").arg(sizef, fieldWidth, 'f', precision);
}
QString ProgressString(double progress)
{
// We don't want to display 100% unless the torrent is really complete
if (progress > 99.9 && progress < 100.)
{
progress = 99.9;
}
return
(progress <= 0) ? "0%" : ((progress >= 100) ? "100%" : QString("%1%").arg(progress, 0, 'f', 1));
}
// shamelessly stolen from qstring.cpp
QString multiArg(const QString& str, int numArgs, const QString* args)
{
QString result;
QMap<int, int> numbersUsed;
const QChar* uc = str.constData();
const int len = str.size();
const int end = len - 1;
int lastNumber = -1;
int i = 0;
// populate the numbersUsed map with the %n's that actually occur in the string
while (i < end)
{
if (uc[i] == QLatin1Char('%'))
{
int number = getEscape(uc, &i, len);
if (number != -1)
{
numbersUsed.insert(number, -1);
continue;
}
}
++i;
}
// assign an argument number to each of the %n's
QMap<int, int>::iterator j = numbersUsed.begin();
QMap<int, int>::iterator jend = numbersUsed.end();
int arg = 0;
while (j != jend && arg < numArgs)
{
*j = arg++;
lastNumber = j.key();
++j;
}
// sanity
if (numArgs > arg)
{
qWarning("QString::arg: %d argument(s) missing in %s", numArgs - arg, str.toLocal8Bit().data());
numArgs = arg;
}
i = 0;
while (i < len)
{
if (uc[i] == QLatin1Char('%') && i != end)
{
int number = getEscape(uc, &i, len, lastNumber);
int arg = numbersUsed[number];
if (number != -1 && arg != -1)
{
result += args[arg];
continue;
}
}
result += uc[i++];
}
return result;
}
bool CheckPortAvailable(int targetPort, const char** reason)
{
if (targetPort < 1 || targetPort > 0xffff)
{
if (reason)
{
*reason = "Port is out bounds.";
}
return false;
}
if (!isPortAvalible(targetPort, SOCK_STREAM))
{
if (reason)
{
*reason = "This TCP port is already in use.";
}
return false;
}
if (!isPortAvalible(targetPort, SOCK_DGRAM))
{
if (reason)
{
*reason = "This UDP port is already in use.";
}
return false;
}
return true;
}
#ifdef Q_OS_WIN
bool isAdminRights()
{
BOOL isAdmin = FALSE;
SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
PSID AdministratorsGroup;
if (AllocateAndInitializeSid(
&NtAuthority,
2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0,
&AdministratorsGroup) != FALSE)
{
if (!CheckTokenMembership(NULL, AdministratorsGroup, &isAdmin))
{
isAdmin = FALSE;
}
FreeSid(AdministratorsGroup);
}
return isAdmin != FALSE;
}
void runWithPrivileges(const wchar_t* arg, WId parent)
{
const auto applicationFilePath = qApp->applicationFilePath();
const auto applicationDirPath = qApp->applicationDirPath();
SHELLEXECUTEINFOW shex =
{
sizeof(SHELLEXECUTEINFOW),
0, // fMask
((parent) ? (HWND)parent : GetDesktopWindow()),
L"runas",
qUtf16Printable(applicationFilePath),
arg,
qUtf16Printable(applicationDirPath),
SW_NORMAL
};
BOOL res = ShellExecuteExW(&shex);
qDebug() << Q_FUNC_INFO << (res ? " succeeded" : " failed");
}
#endif
QMainWindow* getMainWindow()
{
for (QWidget* widget : QApplication::topLevelWidgets())
if (QMainWindow *mainWindow = qobject_cast<QMainWindow*>(widget))
return mainWindow;
return nullptr;
}
} // namespace utilities
<commit_msg>removing compiler warnings on Windows<commit_after>#include "utils.h"
#if defined(Q_OS_WIN)
#include <windows.h>
#include <winsock2.h>
#include <winnt.h>
#include <shellapi.h>
#elif defined(Q_OS_LINUX)
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define SOCKET_ERROR (-1)
#elif defined(Q_OS_DARWIN)
#include <CoreFoundation/CoreFoundation.h>
#include <CoreServices/CoreServices.h>
#include "darwin/AppHandler.h"
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define SOCKET_ERROR (-1)
#endif
#include "modelserializer.h"
#include "modeldeserializer.h"
#include <algorithm>
#include <iterator>
#include <QObject>
#include <QStringList>
#include <QDir>
#include <QFont>
#include <QByteArray>
#include <QUrl>
#include <QMetaProperty>
#include <QDebug>
#include <QCoreApplication>
#include <QApplication>
#include <QMainWindow>
#include <set>
#include <map>
#include "version.hxx"
namespace {
int getEscape(const QChar* uc, int* pos, int len, int maxNumber = 999)
{
int i = *pos;
++i;
if (i < len && uc[i] == QLatin1Char('L'))
{
++i;
}
if (i < len)
{
int escape = uc[i].unicode() - '0';
if (uint(escape) >= 10U)
{
return -1;
}
++i;
while (i < len)
{
int digit = uc[i].unicode() - '0';
if (uint(digit) >= 10U)
{
break;
}
escape = (escape * 10) + digit;
++i;
}
if (escape <= maxNumber)
{
*pos = i;
return escape;
}
}
return -1;
}
bool isPortAvalible(unsigned short int dwPort, int type)
{
sockaddr_in client {};
client.sin_family = AF_INET;
client.sin_port = htons(dwPort);
client.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
auto sock = socket(AF_INET, type, 0);
int result = bind(sock, (sockaddr*) &client, sizeof(client));
#ifdef Q_OS_WIN
closesocket(sock);
#else
close(sock);
#endif
return result != SOCKET_ERROR;
}
} // namespace
namespace utilities
{
const char* const kURLPrefixes[] = { "http://", "https://", "vidxden://1", "ftp://", "file://", "magnet:?" };
const auto kNumberOfPrefixes = sizeof(kURLPrefixes) / sizeof(kURLPrefixes[0]);
const int kOffsetPastSeparator[kNumberOfPrefixes] = { 3, 3, 4, 3, 3, 2 };
QStringList ParseUrls(const QString& data)
{
const QStringList list = data.split(QRegExp("[\\s\\\"\\n]+"), QString::SkipEmptyParts);
QStringList res;
for (const auto& v : list)
{
QString t = v.trimmed();
if (t.isEmpty())
{
continue;
}
QUrl url;
int offset = t.indexOf(':');
if (offset != -1)
{
// fix for urls that have few starting symbols lost
for (size_t i = 0; i < kNumberOfPrefixes; ++i)
{
int start = offset + kOffsetPastSeparator[i];
QString protocol_prefix = t.left(start);
QString prefix(kURLPrefixes[i]);
if (prefix.endsWith(protocol_prefix, Qt::CaseInsensitive))
{
url.setUrl(prefix + t.mid(start).remove('"'));
break;
}
}
}
if (url.isValid())
{
res << url.toString();
}
else if (QRegExp("^[a-z]:[\\\\/]|^/|^~/", Qt::CaseInsensitive).indexIn(t) != -1)
{
res << t;
}
}
return res;
}
void InitializeProjectDescription()
{
QCoreApplication::setApplicationVersion(PROJECT_VERSION);
QCoreApplication::setApplicationName(PROJECT_NAME);
QCoreApplication::setOrganizationName(PROJECT_NAME);
QCoreApplication::setOrganizationDomain(PROJECT_DOMAIN);
}
QFont GetAdaptedFont(int size, int additional_amount)
{
Q_UNUSED(additional_amount)
#ifdef Q_OS_DARWIN
QFont f("Lucida Grande");
f.setPixelSize(size + additional_amount);
return f;
#else
const float koef = 4 / 3.f;
QFont f("Segoe UI");
f.setPixelSize(size * koef);
return f;
#endif
}
///////////////////////////////////////////////////////////////////////////////
bool DeserializeObject(QXmlStreamReader* stream, QObject* object, const QString& name)
{
Q_ASSERT(stream);
ModelDeserializer deserializer(*stream);
return deserializer.deserialize(object, name);
}
void SerializeObject(QXmlStreamWriter* stream, QObject* object, const QString& name)
{
Q_ASSERT(stream);
ModelSerializer serializer(*stream);
serializer.serialize(object, name);
}
///////////////////////////////////////////////////////////////////////////////
QString SizeToString(quint64 size, int precision, int fieldWidth)
{
const unsigned int Kbytes_limit = 1 << 10; //1 Kb
const unsigned int Mbytes_limit = 1 << 20; //1 Mb
const unsigned int Gbytes_limit = 1 << 30; //1 Gb
if (size < Kbytes_limit)
{
return QStringLiteral("%1 B").arg(size);
}
else if (size < Mbytes_limit)
{
const double sizef = size / static_cast<double>(Kbytes_limit);
return QStringLiteral("%1 kB").arg(sizef, fieldWidth, 'f', precision);
}
else if (size < Gbytes_limit)
{
const double sizef = size / static_cast<double>(Mbytes_limit);
return QStringLiteral("%1 MB").arg(sizef, fieldWidth, 'f', precision);
}
const double sizef = size / static_cast<double>(Gbytes_limit);
return QStringLiteral("%1 GB").arg(sizef, fieldWidth, 'f', precision);
}
QString ProgressString(double progress)
{
// We don't want to display 100% unless the torrent is really complete
if (progress > 99.9 && progress < 100.)
{
progress = 99.9;
}
return
(progress <= 0) ? "0%" : ((progress >= 100) ? "100%" : QString("%1%").arg(progress, 0, 'f', 1));
}
// shamelessly stolen from qstring.cpp
QString multiArg(const QString& str, int numArgs, const QString* args)
{
QString result;
QMap<int, int> numbersUsed;
const QChar* uc = str.constData();
const int len = str.size();
const int end = len - 1;
int lastNumber = -1;
int i = 0;
// populate the numbersUsed map with the %n's that actually occur in the string
while (i < end)
{
if (uc[i] == QLatin1Char('%'))
{
int number = getEscape(uc, &i, len);
if (number != -1)
{
numbersUsed.insert(number, -1);
continue;
}
}
++i;
}
// assign an argument number to each of the %n's
QMap<int, int>::iterator j = numbersUsed.begin();
QMap<int, int>::iterator jend = numbersUsed.end();
int arg = 0;
while (j != jend && arg < numArgs)
{
*j = arg++;
lastNumber = j.key();
++j;
}
// sanity
if (numArgs > arg)
{
qWarning("QString::arg: %d argument(s) missing in %s", numArgs - arg, str.toLocal8Bit().data());
numArgs = arg;
}
i = 0;
while (i < len)
{
if (uc[i] == QLatin1Char('%') && i != end)
{
int number = getEscape(uc, &i, len, lastNumber);
int arg = numbersUsed[number];
if (number != -1 && arg != -1)
{
result += args[arg];
continue;
}
}
result += uc[i++];
}
return result;
}
bool CheckPortAvailable(int targetPort, const char** reason)
{
if (targetPort < 1 || targetPort > 0xffff)
{
if (reason)
{
*reason = "Port is out bounds.";
}
return false;
}
if (!isPortAvalible(targetPort, SOCK_STREAM))
{
if (reason)
{
*reason = "This TCP port is already in use.";
}
return false;
}
if (!isPortAvalible(targetPort, SOCK_DGRAM))
{
if (reason)
{
*reason = "This UDP port is already in use.";
}
return false;
}
return true;
}
#ifdef Q_OS_WIN
bool isAdminRights()
{
BOOL isAdmin = FALSE;
SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
PSID AdministratorsGroup;
if (AllocateAndInitializeSid(
&NtAuthority,
2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0,
&AdministratorsGroup) != FALSE)
{
if (!CheckTokenMembership(NULL, AdministratorsGroup, &isAdmin))
{
isAdmin = FALSE;
}
FreeSid(AdministratorsGroup);
}
return isAdmin != FALSE;
}
void runWithPrivileges(const wchar_t* arg, WId parent)
{
const auto applicationFilePath = qApp->applicationFilePath();
const auto applicationDirPath = qApp->applicationDirPath();
SHELLEXECUTEINFOW shex =
{
sizeof(SHELLEXECUTEINFOW),
0, // fMask
((parent) ? (HWND)parent : GetDesktopWindow()),
L"runas",
qUtf16Printable(applicationFilePath),
arg,
qUtf16Printable(applicationDirPath),
SW_NORMAL
};
BOOL res = ShellExecuteExW(&shex);
qDebug() << Q_FUNC_INFO << (res ? " succeeded" : " failed");
}
#endif
QMainWindow* getMainWindow()
{
for (QWidget* widget : QApplication::topLevelWidgets())
if (QMainWindow *mainWindow = qobject_cast<QMainWindow*>(widget))
return mainWindow;
return nullptr;
}
} // namespace utilities
<|endoftext|>
|
<commit_before>// 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 "chrome/browser/automation/ui_controls.h"
#include <X11/keysym.h>
#include <X11/Xlib.h>
#include "base/callback.h"
#include "base/logging.h"
#include "base/message_pump_x.h"
#include "chrome/browser/automation/ui_controls_internal.h"
#include "ui/aura/desktop.h"
#include "ui/base/keycodes/keyboard_code_conversion_x.h"
#include "ui/views/view.h"
namespace {
// Event waiter executes the specified closure|when a matching event
// is found.
// TODO(oshima): Move this to base.
class EventWaiter : public MessageLoopForUI::Observer {
public:
typedef bool (*EventWaiterMatcher)(const base::NativeEvent& event);
EventWaiter(const base::Closure& closure, EventWaiterMatcher matcher)
: closure_(closure),
matcher_(matcher) {
MessageLoopForUI::current()->AddObserver(this);
}
virtual ~EventWaiter() {
MessageLoopForUI::current()->RemoveObserver(this);
}
// MessageLoop::Observer implementation:
virtual base::EventStatus WillProcessEvent(
const base::NativeEvent& event) OVERRIDE {
if ((*matcher_)(event)) {
MessageLoop::current()->PostTask(FROM_HERE, closure_);
delete this;
}
return base::EVENT_CONTINUE;
}
virtual void DidProcessEvent(const base::NativeEvent& event) OVERRIDE {
}
private:
base::Closure closure_;
EventWaiterMatcher matcher_;
DISALLOW_COPY_AND_ASSIGN(EventWaiter);
};
// Latest mouse pointer location set by SendMouseMoveNotifyWhenDone.
int g_current_x = -1000;
int g_current_y = -1000;
// Returns atom that indidates that the XEvent is marker event.
Atom MarkerEventAtom() {
return XInternAtom(base::MessagePumpX::GetDefaultXDisplay(),
"marker_event",
False);
}
// Returns true when the event is a marker event.
bool Matcher(const base::NativeEvent& event) {
return event->xany.type == ClientMessage &&
event->xclient.message_type == MarkerEventAtom();
}
void RunClosureAfterEvents(const base::Closure closure) {
if (closure.is_null())
return;
static XEvent* marker_event = NULL;
if (!marker_event) {
marker_event = new XEvent();
marker_event->xclient.type = ClientMessage;
marker_event->xclient.display = NULL;
marker_event->xclient.window = None;
marker_event->xclient.format = 8;
}
marker_event->xclient.message_type = MarkerEventAtom();
aura::Desktop::GetInstance()->PostNativeEvent(marker_event);
new EventWaiter(closure, &Matcher);
}
} // namespace
namespace ui_controls {
bool SendKeyPress(gfx::NativeWindow window,
ui::KeyboardCode key,
bool control,
bool shift,
bool alt,
bool command) {
DCHECK(!command); // No command key on Aura
return SendKeyPressNotifyWhenDone(
window, key, control, shift, alt, command, base::Closure());
}
void SetMaskAndKeycodeThenSend(XEvent* xevent,
unsigned int mask,
unsigned int keycode) {
xevent->xkey.state |= mask;
xevent->xkey.keycode = keycode;
aura::Desktop::GetInstance()->PostNativeEvent(xevent);
}
void SetKeycodeAndSendThenUnmask(XEvent* xevent,
unsigned int mask,
unsigned int keycode) {
xevent->xkey.keycode = keycode;
aura::Desktop::GetInstance()->PostNativeEvent(xevent);
xevent->xkey.state ^= mask;
}
bool SendKeyPressNotifyWhenDone(gfx::NativeWindow window,
ui::KeyboardCode key,
bool control,
bool shift,
bool alt,
bool command,
const base::Closure& closure) {
DCHECK(!command); // No command key on Aura
XEvent xevent = {0};
xevent.xkey.type = KeyPress;
if (control)
SetMaskAndKeycodeThenSend(&xevent, ControlMask, XK_Control_L);
if (shift)
SetMaskAndKeycodeThenSend(&xevent, ShiftMask, XK_Shift_L);
if (alt)
SetMaskAndKeycodeThenSend(&xevent, Mod1Mask, XK_Alt_L);
xevent.xkey.keycode = ui::XKeysymForWindowsKeyCode(key, shift);
aura::Desktop::GetInstance()->PostNativeEvent(&xevent);
// Send key release events.
xevent.xkey.type = KeyRelease;
aura::Desktop::GetInstance()->PostNativeEvent(&xevent);
if (alt)
SetKeycodeAndSendThenUnmask(&xevent, Mod1Mask, XK_Alt_L);
if (shift)
SetKeycodeAndSendThenUnmask(&xevent, ShiftMask, XK_Shift_L);
if (control)
SetKeycodeAndSendThenUnmask(&xevent, ControlMask, XK_Control_L);
DCHECK(!xevent.xkey.state);
RunClosureAfterEvents(closure);
return true;
}
bool SendMouseMove(long x, long y) {
return SendMouseMoveNotifyWhenDone(x, y, base::Closure());
}
bool SendMouseMoveNotifyWhenDone(long x, long y, const base::Closure& closure) {
XEvent xevent = {0};
XMotionEvent* xmotion = &xevent.xmotion;
xmotion->type = MotionNotify;
g_current_x = xmotion->x = x;
g_current_y = xmotion->y = y;
xmotion->same_screen = True;
// Desktop will take care of other necessary fields.
aura::Desktop::GetInstance()->PostNativeEvent(&xevent);
RunClosureAfterEvents(closure);
return false;
}
bool SendMouseEvents(MouseButton type, int state) {
return SendMouseEventsNotifyWhenDone(type, state, base::Closure());
}
bool SendMouseEventsNotifyWhenDone(MouseButton type,
int state,
const base::Closure& closure) {
XEvent xevent = {0};
XButtonEvent* xbutton = &xevent.xbutton;
DCHECK_NE(g_current_x, -1000);
DCHECK_NE(g_current_y, -1000);
xbutton->x = g_current_x;
xbutton->y = g_current_y;
xbutton->same_screen = True;
switch (type) {
case LEFT:
xbutton->button = Button1;
xbutton->state = Button1Mask;
break;
case MIDDLE:
xbutton->button = Button2;
xbutton->state = Button2Mask;
break;
case RIGHT:
xbutton->button = Button3;
xbutton->state = Button3Mask;
break;
}
// Desktop will take care of other necessary fields.
aura::Desktop* desktop = aura::Desktop::GetInstance();
if (state & DOWN) {
xevent.xbutton.type = ButtonPress;
desktop->PostNativeEvent(&xevent);
}
if (state & UP) {
xevent.xbutton.type = ButtonRelease;
desktop->PostNativeEvent(&xevent);
}
RunClosureAfterEvents(closure);
return false;
}
bool SendMouseClick(MouseButton type) {
return SendMouseEvents(type, UP | DOWN);
}
void MoveMouseToCenterAndPress(views::View* view, MouseButton button,
int state, const base::Closure& closure) {
DCHECK(view);
DCHECK(view->GetWidget());
gfx::Point view_center(view->width() / 2, view->height() / 2);
views::View::ConvertPointToScreen(view, &view_center);
SendMouseMove(view_center.x(), view_center.y());
SendMouseEventsNotifyWhenDone(button, state, closure);
}
} // namespace ui_controls
<commit_msg>Aura: Convert keysym to kyeycode when posting XKeyEvent<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 "chrome/browser/automation/ui_controls.h"
#include <X11/keysym.h>
#include <X11/Xlib.h>
#include "base/callback.h"
#include "base/logging.h"
#include "base/message_pump_x.h"
#include "chrome/browser/automation/ui_controls_internal.h"
#include "ui/aura/desktop.h"
#include "ui/base/keycodes/keyboard_code_conversion_x.h"
#include "ui/views/view.h"
namespace {
// Event waiter executes the specified closure|when a matching event
// is found.
// TODO(oshima): Move this to base.
class EventWaiter : public MessageLoopForUI::Observer {
public:
typedef bool (*EventWaiterMatcher)(const base::NativeEvent& event);
EventWaiter(const base::Closure& closure, EventWaiterMatcher matcher)
: closure_(closure),
matcher_(matcher) {
MessageLoopForUI::current()->AddObserver(this);
}
virtual ~EventWaiter() {
MessageLoopForUI::current()->RemoveObserver(this);
}
// MessageLoop::Observer implementation:
virtual base::EventStatus WillProcessEvent(
const base::NativeEvent& event) OVERRIDE {
if ((*matcher_)(event)) {
MessageLoop::current()->PostTask(FROM_HERE, closure_);
delete this;
}
return base::EVENT_CONTINUE;
}
virtual void DidProcessEvent(const base::NativeEvent& event) OVERRIDE {
}
private:
base::Closure closure_;
EventWaiterMatcher matcher_;
DISALLOW_COPY_AND_ASSIGN(EventWaiter);
};
// Latest mouse pointer location set by SendMouseMoveNotifyWhenDone.
int g_current_x = -1000;
int g_current_y = -1000;
// Returns atom that indidates that the XEvent is marker event.
Atom MarkerEventAtom() {
return XInternAtom(base::MessagePumpX::GetDefaultXDisplay(),
"marker_event",
False);
}
// Returns true when the event is a marker event.
bool Matcher(const base::NativeEvent& event) {
return event->xany.type == ClientMessage &&
event->xclient.message_type == MarkerEventAtom();
}
void RunClosureAfterEvents(const base::Closure closure) {
if (closure.is_null())
return;
static XEvent* marker_event = NULL;
if (!marker_event) {
marker_event = new XEvent();
marker_event->xclient.type = ClientMessage;
marker_event->xclient.display = NULL;
marker_event->xclient.window = None;
marker_event->xclient.format = 8;
}
marker_event->xclient.message_type = MarkerEventAtom();
aura::Desktop::GetInstance()->PostNativeEvent(marker_event);
new EventWaiter(closure, &Matcher);
}
} // namespace
namespace ui_controls {
bool SendKeyPress(gfx::NativeWindow window,
ui::KeyboardCode key,
bool control,
bool shift,
bool alt,
bool command) {
DCHECK(!command); // No command key on Aura
return SendKeyPressNotifyWhenDone(
window, key, control, shift, alt, command, base::Closure());
}
void SetMaskAndKeycodeThenSend(XEvent* xevent,
unsigned int mask,
unsigned int keycode) {
xevent->xkey.state |= mask;
xevent->xkey.keycode = keycode;
aura::Desktop::GetInstance()->PostNativeEvent(xevent);
}
void SetKeycodeAndSendThenUnmask(XEvent* xevent,
unsigned int mask,
unsigned int keycode) {
xevent->xkey.keycode = keycode;
aura::Desktop::GetInstance()->PostNativeEvent(xevent);
xevent->xkey.state ^= mask;
}
bool SendKeyPressNotifyWhenDone(gfx::NativeWindow window,
ui::KeyboardCode key,
bool control,
bool shift,
bool alt,
bool command,
const base::Closure& closure) {
DCHECK(!command); // No command key on Aura
XEvent xevent = {0};
xevent.xkey.type = KeyPress;
if (control)
SetMaskAndKeycodeThenSend(&xevent, ControlMask, XK_Control_L);
if (shift)
SetMaskAndKeycodeThenSend(&xevent, ShiftMask, XK_Shift_L);
if (alt)
SetMaskAndKeycodeThenSend(&xevent, Mod1Mask, XK_Alt_L);
xevent.xkey.keycode =
XKeysymToKeycode(base::MessagePumpX::GetDefaultXDisplay(),
ui::XKeysymForWindowsKeyCode(key, shift));
aura::Desktop::GetInstance()->PostNativeEvent(&xevent);
// Send key release events.
xevent.xkey.type = KeyRelease;
aura::Desktop::GetInstance()->PostNativeEvent(&xevent);
if (alt)
SetKeycodeAndSendThenUnmask(&xevent, Mod1Mask, XK_Alt_L);
if (shift)
SetKeycodeAndSendThenUnmask(&xevent, ShiftMask, XK_Shift_L);
if (control)
SetKeycodeAndSendThenUnmask(&xevent, ControlMask, XK_Control_L);
DCHECK(!xevent.xkey.state);
RunClosureAfterEvents(closure);
return true;
}
bool SendMouseMove(long x, long y) {
return SendMouseMoveNotifyWhenDone(x, y, base::Closure());
}
bool SendMouseMoveNotifyWhenDone(long x, long y, const base::Closure& closure) {
XEvent xevent = {0};
XMotionEvent* xmotion = &xevent.xmotion;
xmotion->type = MotionNotify;
g_current_x = xmotion->x = x;
g_current_y = xmotion->y = y;
xmotion->same_screen = True;
// Desktop will take care of other necessary fields.
aura::Desktop::GetInstance()->PostNativeEvent(&xevent);
RunClosureAfterEvents(closure);
return false;
}
bool SendMouseEvents(MouseButton type, int state) {
return SendMouseEventsNotifyWhenDone(type, state, base::Closure());
}
bool SendMouseEventsNotifyWhenDone(MouseButton type,
int state,
const base::Closure& closure) {
XEvent xevent = {0};
XButtonEvent* xbutton = &xevent.xbutton;
DCHECK_NE(g_current_x, -1000);
DCHECK_NE(g_current_y, -1000);
xbutton->x = g_current_x;
xbutton->y = g_current_y;
xbutton->same_screen = True;
switch (type) {
case LEFT:
xbutton->button = Button1;
xbutton->state = Button1Mask;
break;
case MIDDLE:
xbutton->button = Button2;
xbutton->state = Button2Mask;
break;
case RIGHT:
xbutton->button = Button3;
xbutton->state = Button3Mask;
break;
}
// Desktop will take care of other necessary fields.
aura::Desktop* desktop = aura::Desktop::GetInstance();
if (state & DOWN) {
xevent.xbutton.type = ButtonPress;
desktop->PostNativeEvent(&xevent);
}
if (state & UP) {
xevent.xbutton.type = ButtonRelease;
desktop->PostNativeEvent(&xevent);
}
RunClosureAfterEvents(closure);
return false;
}
bool SendMouseClick(MouseButton type) {
return SendMouseEvents(type, UP | DOWN);
}
void MoveMouseToCenterAndPress(views::View* view, MouseButton button,
int state, const base::Closure& closure) {
DCHECK(view);
DCHECK(view->GetWidget());
gfx::Point view_center(view->width() / 2, view->height() / 2);
views::View::ConvertPointToScreen(view, &view_center);
SendMouseMove(view_center.x(), view_center.y());
SendMouseEventsNotifyWhenDone(button, state, closure);
}
} // namespace ui_controls
<|endoftext|>
|
<commit_before>// This file is part of the AliceVision project.
// Copyright (c) 2017 AliceVision contributors.
// 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 https://mozilla.org/MPL/2.0/.
#include <aliceVision/sfmData/SfMData.hpp>
#include <aliceVision/sfmDataIO/sfmDataIO.hpp>
#include <aliceVision/image/all.hpp>
#include <aliceVision/system/Logger.hpp>
#include <aliceVision/system/cmdline.hpp>
#include <aliceVision/config.hpp>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <boost/progress.hpp>
#include <stdlib.h>
#include <stdio.h>
#include <cmath>
#include <vector>
#include <set>
#include <iterator>
#include <iomanip>
// These constants define the current software version.
// They must be updated when the command line is changed.
#define ALICEVISION_SOFTWARE_VERSION_MAJOR 1
#define ALICEVISION_SOFTWARE_VERSION_MINOR 0
using namespace aliceVision;
using namespace aliceVision::camera;
using namespace aliceVision::geometry;
using namespace aliceVision::image;
using namespace aliceVision::sfmData;
namespace po = boost::program_options;
namespace fs = boost::filesystem;
class point2d
{
public:
point2d()
: x(0), y(0)
{}
union {
struct
{
double x, y;
};
double m[2];
};
};
class point3d
{
public:
point3d()
: x(0), y(0), z(0)
{}
union {
struct
{
double x, y, z;
};
double m[3];
};
};
struct orientedPoint
{
point3d p; // 3 * float : 3 * 4 = 12 Bytes : (one float is 4 Bytes : 3.4E +/- 38 (7 digits) )
point3d n; // 2 * float : 2 * 4 = 8 Bytes
float sim = 0; // 4-Bytes : 3.4E +/- 38 (7 digits)
// TOTAL: 12 + 8 + 4 = 24 Bytes
};
struct seed_io_block
{
orientedPoint op; // 28 bytes
point3d xax; // 12 bytes
point3d yax; // 12 bytes
float pixSize; // 4 bytes
uint64_t area; // 8 bytes
uint64_t segId; // 8 bytes
unsigned short ncams; // 2 bytes
unsigned short padding[3];
};
struct Seed
{
seed_io_block s;
unsigned short camId = 0;
point2d shift0;
point2d shift1;
};
typedef std::vector<Seed> SeedVector;
typedef stl::flat_map< size_t, SeedVector> SeedsPerView;
void retrieveSeedsPerView(
const SfMData& sfmData,
const std::set<IndexT>& viewIds,
SeedsPerView& outSeedsPerView)
{
static const double minAngle = 3.0;
for(const auto& s: sfmData.structure)
{
const IndexT landmarkId = s.first;
const Landmark& landmark = s.second;
// For each observation of a 3D landmark, we will export
// all other observations with an angle > minAngle.
for(const auto& obsA: landmark.observations)
{
const auto& obsACamId_it = viewIds.find(obsA.first);
if(obsACamId_it == viewIds.end())
continue; // this view cannot be exported to mvs, so we skip the observation
const View& viewA = *sfmData.getViews().at(obsA.first).get();
const geometry::Pose3 poseA = sfmData.getPose(viewA).getTransform();
const Pinhole * intrinsicsA = dynamic_cast<const Pinhole*>(sfmData.getIntrinsics().at(viewA.getIntrinsicId()).get());
for(const auto& obsB: landmark.observations)
{
// don't export itself
if(obsA.first == obsB.first)
continue;
const auto& obsBCamId_it = viewIds.find(obsB.first);
if(obsBCamId_it == viewIds.end())
continue; // this view cannot be exported to mvs, so we skip the observation
const unsigned short indexB = std::distance(viewIds.begin(), obsBCamId_it);
const View& viewB = *sfmData.getViews().at(obsB.first).get();
const geometry::Pose3 poseB = sfmData.getPose(viewB).getTransform();
const Pinhole * intrinsicsB = dynamic_cast<const Pinhole*>(sfmData.getIntrinsics().at(viewB.getIntrinsicId()).get());
const double angle = AngleBetweenRays(
poseA, intrinsicsA, poseB, intrinsicsB, obsA.second.x, obsB.second.x);
if(angle < minAngle)
continue;
Seed seed;
seed.camId = indexB;
seed.s.ncams = 1;
seed.s.segId = landmarkId;
seed.s.op.p.x = landmark.X(0);
seed.s.op.p.y = landmark.X(1);
seed.s.op.p.z = landmark.X(2);
outSeedsPerView[obsA.first].push_back(seed);
}
}
}
}
bool prepareDenseScene(const SfMData& sfmData, int beginIndex, int endIndex, const std::string& outFolder)
{
// defined view Ids
std::set<IndexT> viewIds;
sfmData::Views::const_iterator itViewBegin = sfmData.getViews().begin();
sfmData::Views::const_iterator itViewEnd = sfmData.getViews().end();
if(endIndex > 0)
{
itViewEnd = itViewBegin;
std::advance(itViewEnd, endIndex);
}
std::advance(itViewBegin, (beginIndex < 0) ? 0 : beginIndex);
// Export valid views as Projective Cameras
for(auto it = itViewBegin; it != itViewEnd; ++it)
{
const View* view = it->second.get();
if (!sfmData.isPoseAndIntrinsicDefined(view))
continue;
viewIds.insert(view->getViewId());
}
SeedsPerView seedsPerView;
retrieveSeedsPerView(sfmData, viewIds, seedsPerView);
// Export data
boost::progress_display progressBar(viewIds.size(), std::cout, "Exporting Scene Data\n");
// Export views:
// - viewId_P.txt (Pose of the reconstructed camera)
// - viewId.exr (undistorted colored image)
// - viewId_seeds.bin (3d points visible in this image)
#pragma omp parallel for num_threads(3)
for(int i = 0; i < viewIds.size(); ++i)
{
auto itView = viewIds.begin();
std::advance(itView, i);
const IndexT viewId = *itView;
const View* view = sfmData.getViews().at(viewId).get();
assert(view->getViewId() == viewId);
Intrinsics::const_iterator iterIntrinsic = sfmData.getIntrinsics().find(view->getIntrinsicId());
// We have a valid view with a corresponding camera & pose
const std::string baseFilename = std::to_string(viewId);
oiio::ParamValueList metadata;
// Export camera
{
// Export camera pose
const Pose3 pose = sfmData.getPose(*view).getTransform();
Mat34 P = iterIntrinsic->second.get()->get_projective_equivalent(pose);
std::ofstream fileP((fs::path(outFolder) / (baseFilename + "_P.txt")).string());
fileP << std::setprecision(10)
<< P(0, 0) << " " << P(0, 1) << " " << P(0, 2) << " " << P(0, 3) << "\n"
<< P(1, 0) << " " << P(1, 1) << " " << P(1, 2) << " " << P(1, 3) << "\n"
<< P(2, 0) << " " << P(2, 1) << " " << P(2, 2) << " " << P(2, 3) << "\n";
fileP.close();
Mat4 projectionMatrix;
projectionMatrix << P(0, 0), P(0, 1), P(0, 2), P(0, 3),
P(1, 0), P(1, 1), P(1, 2), P(1, 3),
P(2, 0), P(2, 1), P(2, 2), P(2, 3),
0, 0, 0, 1;
// Export camera intrinsics
const Mat3 K = dynamic_cast<const Pinhole*>(sfmData.getIntrinsicPtr(view->getIntrinsicId()))->K();
const Mat3& R = pose.rotation();
const Vec3& t = pose.translation();
std::ofstream fileKRt((fs::path(outFolder) / (baseFilename + "_KRt.txt")).string());
fileKRt << std::setprecision(10)
<< K(0, 0) << " " << K(0, 1) << " " << K(0, 2) << "\n"
<< K(1, 0) << " " << K(1, 1) << " " << K(1, 2) << "\n"
<< K(2, 0) << " " << K(2, 1) << " " << K(2, 2) << "\n"
<< "\n"
<< R(0, 0) << " " << R(0, 1) << " " << R(0, 2) << "\n"
<< R(1, 0) << " " << R(1, 1) << " " << R(1, 2) << "\n"
<< R(2, 0) << " " << R(2, 1) << " " << R(2, 2) << "\n"
<< "\n"
<< t(0) << " " << t(1) << " " << t(2) << "\n";
fileKRt.close();
// convert matrices to rowMajor
std::vector<double> vP(projectionMatrix.size());
std::vector<double> vK(K.size());
std::vector<double> vR(R.size());
typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> RowMatrixXd;
Eigen::Map<RowMatrixXd>(vP.data(), projectionMatrix.rows(), projectionMatrix.cols()) = projectionMatrix;
Eigen::Map<RowMatrixXd>(vK.data(), K.rows(), K.cols()) = K;
Eigen::Map<RowMatrixXd>(vR.data(), R.rows(), R.cols()) = R;
// add metadata
metadata.push_back(oiio::ParamValue("AliceVision:downscale", 1));
metadata.push_back(oiio::ParamValue("AliceVision:P", oiio::TypeDesc(oiio::TypeDesc::DOUBLE, oiio::TypeDesc::MATRIX44), 1, vP.data()));
metadata.push_back(oiio::ParamValue("AliceVision:K", oiio::TypeDesc(oiio::TypeDesc::DOUBLE, oiio::TypeDesc::MATRIX33), 1, vK.data()));
metadata.push_back(oiio::ParamValue("AliceVision:R", oiio::TypeDesc(oiio::TypeDesc::DOUBLE, oiio::TypeDesc::MATRIX33), 1, vR.data()));
metadata.push_back(oiio::ParamValue("AliceVision:t", oiio::TypeDesc(oiio::TypeDesc::DOUBLE, oiio::TypeDesc::VEC3), 1, t.data()));
}
// Export undistort image
{
const std::string srcImage = view->getImagePath();
std::string dstColorImage = (fs::path(outFolder) / (baseFilename + ".exr")).string();
const IntrinsicBase* cam = iterIntrinsic->second.get();
Image<RGBfColor> image, image_ud;
readImage(srcImage, image);
// Undistort
if(cam->isValid() && cam->have_disto())
{
// undistort the image and save it
UndistortImage(image, cam, image_ud, FBLACK);
writeImage(dstColorImage, image_ud, metadata);
}
else
{
writeImage(dstColorImage, image, metadata);
}
}
// Export Seeds
{
const std::string seedsFilepath = (fs::path(outFolder) / (baseFilename + "_seeds.bin")).string();
std::ofstream seedsFile(seedsFilepath, std::ios::binary);
const int nbSeeds = seedsPerView[viewId].size();
seedsFile.write((char*)&nbSeeds, sizeof(int));
for(const Seed& seed: seedsPerView.at(viewId))
{
seedsFile.write((char*)&seed, sizeof(seed_io_block) + sizeof(unsigned short) + 2 * sizeof(point2d)); //sizeof(Seed));
}
seedsFile.close();
}
#pragma omp critical
++progressBar;
}
return true;
}
int main(int argc, char *argv[])
{
// command-line parameters
std::string verboseLevel = system::EVerboseLevel_enumToString(system::Logger::getDefaultVerboseLevel());
std::string sfmDataFilename;
std::string outFolder;
int rangeStart = -1;
int rangeSize = 1;
po::options_description allParams("AliceVision prepareDenseScene");
po::options_description requiredParams("Required parameters");
requiredParams.add_options()
("input,i", po::value<std::string>(&sfmDataFilename)->required(),
"SfMData file.")
("output,o", po::value<std::string>(&outFolder)->required(),
"Output folder.");
po::options_description optionalParams("Optional parameters");
optionalParams.add_options()
("rangeStart", po::value<int>(&rangeStart)->default_value(rangeStart),
"Range image index start.")
("rangeSize", po::value<int>(&rangeSize)->default_value(rangeSize),
"Range size.");
po::options_description logParams("Log parameters");
logParams.add_options()
("verboseLevel,v", po::value<std::string>(&verboseLevel)->default_value(verboseLevel),
"verbosity level (fatal, error, warning, info, debug, trace).");
allParams.add(requiredParams).add(optionalParams).add(logParams);
po::variables_map vm;
try
{
po::store(po::parse_command_line(argc, argv, allParams), vm);
if(vm.count("help") || (argc == 1))
{
ALICEVISION_COUT(allParams);
return EXIT_SUCCESS;
}
po::notify(vm);
}
catch(boost::program_options::required_option& e)
{
ALICEVISION_CERR("ERROR: " << e.what());
ALICEVISION_COUT("Usage:\n\n" << allParams);
return EXIT_FAILURE;
}
catch(boost::program_options::error& e)
{
ALICEVISION_CERR("ERROR: " << e.what());
ALICEVISION_COUT("Usage:\n\n" << allParams);
return EXIT_FAILURE;
}
ALICEVISION_COUT("Program called with the following parameters:");
ALICEVISION_COUT(vm);
// set verbose level
system::Logger::get()->setLogLevel(verboseLevel);
// Create output dir
if(!fs::exists(outFolder))
fs::create_directory(outFolder);
// Read the input SfM scene
SfMData sfmData;
if(!sfmDataIO::Load(sfmData, sfmDataFilename, sfmDataIO::ESfMData::ALL))
{
ALICEVISION_LOG_ERROR("The input SfMData file '" << sfmDataFilename << "' cannot be read.");
return EXIT_FAILURE;
}
int rangeEnd = sfmData.getViews().size();
// set range
if(rangeStart != -1)
{
if(rangeStart < 0 || rangeSize < 0 ||
rangeStart > sfmData.getViews().size())
{
ALICEVISION_LOG_ERROR("Range is incorrect");
return EXIT_FAILURE;
}
if(rangeStart + rangeSize > sfmData.views.size())
rangeSize = sfmData.views.size() - rangeStart;
rangeEnd = rangeStart + rangeSize;
}
else
{
rangeStart = 0;
}
// export
if(prepareDenseScene(sfmData, rangeStart, rangeEnd, outFolder))
return EXIT_SUCCESS;
return EXIT_FAILURE;
}
<commit_msg>[software] `prepareDenseScene` Add options / Remove seeds export<commit_after>// This file is part of the AliceVision project.
// Copyright (c) 2017 AliceVision contributors.
// 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 https://mozilla.org/MPL/2.0/.
#include <aliceVision/sfmData/SfMData.hpp>
#include <aliceVision/sfmDataIO/sfmDataIO.hpp>
#include <aliceVision/image/all.hpp>
#include <aliceVision/system/Logger.hpp>
#include <aliceVision/system/cmdline.hpp>
#include <aliceVision/config.hpp>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <boost/progress.hpp>
#include <stdlib.h>
#include <stdio.h>
#include <cmath>
#include <vector>
#include <set>
#include <iterator>
#include <iomanip>
// These constants define the current software version.
// They must be updated when the command line is changed.
#define ALICEVISION_SOFTWARE_VERSION_MAJOR 2
#define ALICEVISION_SOFTWARE_VERSION_MINOR 0
using namespace aliceVision;
using namespace aliceVision::camera;
using namespace aliceVision::geometry;
using namespace aliceVision::image;
using namespace aliceVision::sfmData;
namespace po = boost::program_options;
namespace fs = boost::filesystem;
bool prepareDenseScene(const SfMData& sfmData,
int beginIndex,
int endIndex,
const std::string& outFolder,
image::EImageFileType outputFileType,
bool saveMetadata,
bool saveMatricesFiles)
{
// defined view Ids
std::set<IndexT> viewIds;
sfmData::Views::const_iterator itViewBegin = sfmData.getViews().begin();
sfmData::Views::const_iterator itViewEnd = sfmData.getViews().end();
if(endIndex > 0)
{
itViewEnd = itViewBegin;
std::advance(itViewEnd, endIndex);
}
std::advance(itViewBegin, (beginIndex < 0) ? 0 : beginIndex);
// export valid views as projective cameras
for(auto it = itViewBegin; it != itViewEnd; ++it)
{
const View* view = it->second.get();
if (!sfmData.isPoseAndIntrinsicDefined(view))
continue;
viewIds.insert(view->getViewId());
}
if((outputFileType != image::EImageFileType::EXR) && saveMetadata)
ALICEVISION_LOG_WARNING("Cannot save informations in images metadata.\n"
"Choose '.exr' file type if you want AliceVision custom metadata");
// export data
boost::progress_display progressBar(viewIds.size(), std::cout, "Exporting Scene Undistorted Images\n");
#pragma omp parallel for num_threads(3)
for(int i = 0; i < viewIds.size(); ++i)
{
auto itView = viewIds.begin();
std::advance(itView, i);
const IndexT viewId = *itView;
const View* view = sfmData.getViews().at(viewId).get();
Intrinsics::const_iterator iterIntrinsic = sfmData.getIntrinsics().find(view->getIntrinsicId());
//we have a valid view with a corresponding camera & pose
const std::string baseFilename = std::to_string(viewId);
oiio::ParamValueList metadata;
// export camera
if(saveMetadata || saveMatricesFiles)
{
// get camera pose / projection
const Pose3 pose = sfmData.getPose(*view).getTransform();
Mat34 P = iterIntrinsic->second.get()->get_projective_equivalent(pose);
// get camera intrinsics matrices
const Mat3 K = dynamic_cast<const Pinhole*>(sfmData.getIntrinsicPtr(view->getIntrinsicId()))->K();
const Mat3& R = pose.rotation();
const Vec3& t = pose.translation();
if(saveMatricesFiles)
{
std::ofstream fileP((fs::path(outFolder) / (baseFilename + "_P.txt")).string());
fileP << std::setprecision(10)
<< P(0, 0) << " " << P(0, 1) << " " << P(0, 2) << " " << P(0, 3) << "\n"
<< P(1, 0) << " " << P(1, 1) << " " << P(1, 2) << " " << P(1, 3) << "\n"
<< P(2, 0) << " " << P(2, 1) << " " << P(2, 2) << " " << P(2, 3) << "\n";
fileP.close();
std::ofstream fileKRt((fs::path(outFolder) / (baseFilename + "_KRt.txt")).string());
fileKRt << std::setprecision(10)
<< K(0, 0) << " " << K(0, 1) << " " << K(0, 2) << "\n"
<< K(1, 0) << " " << K(1, 1) << " " << K(1, 2) << "\n"
<< K(2, 0) << " " << K(2, 1) << " " << K(2, 2) << "\n"
<< "\n"
<< R(0, 0) << " " << R(0, 1) << " " << R(0, 2) << "\n"
<< R(1, 0) << " " << R(1, 1) << " " << R(1, 2) << "\n"
<< R(2, 0) << " " << R(2, 1) << " " << R(2, 2) << "\n"
<< "\n"
<< t(0) << " " << t(1) << " " << t(2) << "\n";
fileKRt.close();
}
if(saveMetadata)
{
// convert to 44 matix
Mat4 projectionMatrix;
projectionMatrix << P(0, 0), P(0, 1), P(0, 2), P(0, 3),
P(1, 0), P(1, 1), P(1, 2), P(1, 3),
P(2, 0), P(2, 1), P(2, 2), P(2, 3),
0, 0, 0, 1;
// convert matrices to rowMajor
std::vector<double> vP(projectionMatrix.size());
std::vector<double> vK(K.size());
std::vector<double> vR(R.size());
typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> RowMatrixXd;
Eigen::Map<RowMatrixXd>(vP.data(), projectionMatrix.rows(), projectionMatrix.cols()) = projectionMatrix;
Eigen::Map<RowMatrixXd>(vK.data(), K.rows(), K.cols()) = K;
Eigen::Map<RowMatrixXd>(vR.data(), R.rows(), R.cols()) = R;
// add metadata
metadata.push_back(oiio::ParamValue("AliceVision:downscale", 1));
metadata.push_back(oiio::ParamValue("AliceVision:P", oiio::TypeDesc(oiio::TypeDesc::DOUBLE, oiio::TypeDesc::MATRIX44), 1, vP.data()));
metadata.push_back(oiio::ParamValue("AliceVision:K", oiio::TypeDesc(oiio::TypeDesc::DOUBLE, oiio::TypeDesc::MATRIX33), 1, vK.data()));
metadata.push_back(oiio::ParamValue("AliceVision:R", oiio::TypeDesc(oiio::TypeDesc::DOUBLE, oiio::TypeDesc::MATRIX33), 1, vR.data()));
metadata.push_back(oiio::ParamValue("AliceVision:t", oiio::TypeDesc(oiio::TypeDesc::DOUBLE, oiio::TypeDesc::VEC3), 1, t.data()));
}
}
// export undistort image
{
const std::string srcImage = view->getImagePath();
std::string dstColorImage = (fs::path(outFolder) / (baseFilename + "." + image::EImageFileType_enumToString(outputFileType))).string();
const IntrinsicBase* cam = iterIntrinsic->second.get();
Image<RGBfColor> image, image_ud;
readImage(srcImage, image);
// undistort
if(cam->isValid() && cam->have_disto())
{
// undistort the image and save it
UndistortImage(image, cam, image_ud, FBLACK);
writeImage(dstColorImage, image_ud, metadata);
}
else
{
writeImage(dstColorImage, image, metadata);
}
}
#pragma omp critical
++progressBar;
}
return true;
}
int main(int argc, char *argv[])
{
// command-line parameters
std::string verboseLevel = system::EVerboseLevel_enumToString(system::Logger::getDefaultVerboseLevel());
std::string sfmDataFilename;
std::string outFolder;
std::string outImageFileTypeName = image::EImageFileType_enumToString(image::EImageFileType::EXR);
int rangeStart = -1;
int rangeSize = 1;
bool saveMetadata = true;
bool saveMatricesTxtFiles = false;
po::options_description allParams("AliceVision prepareDenseScene");
po::options_description requiredParams("Required parameters");
requiredParams.add_options()
("input,i", po::value<std::string>(&sfmDataFilename)->required(),
"SfMData file.")
("output,o", po::value<std::string>(&outFolder)->required(),
"Output folder.");
po::options_description optionalParams("Optional parameters");
optionalParams.add_options()
("outputFileType", po::value<std::string>(&outImageFileTypeName)->default_value(outImageFileTypeName),
image::EImageFileType_informations().c_str())
("saveMetadata", po::value<bool>(&saveMetadata)->default_value(saveMetadata),
"Save projections and intrinsics informations in images metadata.")
("saveMatricesTxtFiles", po::value<bool>(&saveMatricesTxtFiles)->default_value(saveMatricesTxtFiles),
"Save projections and intrinsics informations in text files.")
("rangeStart", po::value<int>(&rangeStart)->default_value(rangeStart),
"Range image index start.")
("rangeSize", po::value<int>(&rangeSize)->default_value(rangeSize),
"Range size.");
po::options_description logParams("Log parameters");
logParams.add_options()
("verboseLevel,v", po::value<std::string>(&verboseLevel)->default_value(verboseLevel),
"verbosity level (fatal, error, warning, info, debug, trace).");
allParams.add(requiredParams).add(optionalParams).add(logParams);
po::variables_map vm;
try
{
po::store(po::parse_command_line(argc, argv, allParams), vm);
if(vm.count("help") || (argc == 1))
{
ALICEVISION_COUT(allParams);
return EXIT_SUCCESS;
}
po::notify(vm);
}
catch(boost::program_options::required_option& e)
{
ALICEVISION_CERR("ERROR: " << e.what());
ALICEVISION_COUT("Usage:\n\n" << allParams);
return EXIT_FAILURE;
}
catch(boost::program_options::error& e)
{
ALICEVISION_CERR("ERROR: " << e.what());
ALICEVISION_COUT("Usage:\n\n" << allParams);
return EXIT_FAILURE;
}
ALICEVISION_COUT("Program called with the following parameters:");
ALICEVISION_COUT(vm);
// set verbose level
system::Logger::get()->setLogLevel(verboseLevel);
// set output file type
image::EImageFileType outputFileType = image::EImageFileType_stringToEnum(outImageFileTypeName);
// Create output dir
if(!fs::exists(outFolder))
fs::create_directory(outFolder);
// Read the input SfM scene
SfMData sfmData;
if(!sfmDataIO::Load(sfmData, sfmDataFilename, sfmDataIO::ESfMData::ALL))
{
ALICEVISION_LOG_ERROR("The input SfMData file '" << sfmDataFilename << "' cannot be read.");
return EXIT_FAILURE;
}
int rangeEnd = sfmData.getViews().size();
// set range
if(rangeStart != -1)
{
if(rangeStart < 0 || rangeSize < 0 ||
rangeStart > sfmData.getViews().size())
{
ALICEVISION_LOG_ERROR("Range is incorrect");
return EXIT_FAILURE;
}
if(rangeStart + rangeSize > sfmData.views.size())
rangeSize = sfmData.views.size() - rangeStart;
rangeEnd = rangeStart + rangeSize;
}
else
{
rangeStart = 0;
}
// export
if(prepareDenseScene(sfmData, rangeStart, rangeEnd, outFolder, outputFileType, saveMetadata, saveMatricesTxtFiles))
return EXIT_SUCCESS;
return EXIT_FAILURE;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2014 odan
* License: MIT License
*/
#include "Parameters5Gen.hpp"
namespace PokeRNG {
template<typename Constant>
Parameters5Gen<Constant>::Parameters5Gen() : nazo1(Constant::nazo1), nazo2(Constant::nazo2), nazo3(Constant::nazo3), nazo4(Constant::nazo4), nazo5(Constant::nazo5), vcount(Constant::vcount), gxstat(Constant::gxstat), frame(Constant::frame), timer0_min(Constant::timer0_min), timer0_max(Constant::timer0_max), timer0(timer0_min), key(0x2fff), mac_addr1(0), mac_addr2(0), mac_addr3(0), mac_addr4(0), mac_addr5(0), mac_addr6(0), year(0), month(0), day(0), hour(0), minute(0), second(0) { }
template<typename Constant>
void Parameters5Gen<Constant>::set_mac_addr(u32 m1, u32 m2, u32 m3, u32 m4, u32 m5, u32 m6) {
mac_addr1 = m1;
mac_addr2 = m2;
mac_addr3 = m3;
mac_addr4 = m4;
mac_addr5 = m5;
mac_addr6 = m6;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_year(u32 year_) {
year = year_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_month(u32 month_) {
month = month_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_day(u32 day_) {
day = day_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_hour(u32 hour_) {
hour = hour_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_minute(u32 minute_) {
minute = minute_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_second(u32 second_) {
second = second_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_date_time(const DateTime& date_time) {
year = date_time.get_year();
month = date_time.get_month();
day = date_time.get_day();
hour = date_time.get_hour();
minute = date_time.get_minute();
second = date_time.get_second();
}
template<typename Constant>
void Parameters5Gen<Constant>::set_key(u32 key_) {
key = key_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_timer0(u32 timer0_) {
timer0 = timer0_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_vcount(u32 vcount_) {
vcount = vcount_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_gxstat(u32 gxstat_) {
gxstat = gxstat_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_frame(u32 frame_) {
frame = frame_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_nazo1(u32 nazo1_) {
nazo1 = nazo1_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_nazo2(u32 nazo2_) {
nazo2 = nazo2_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_nazo3(u32 nazo3_) {
nazo3 = nazo3_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_nazo4(u32 nazo4_) {
nazo4 = nazo4_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_nazo5(u32 nazo5_) {
nazo5 = nazo5_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_timer0_min(u32 timer0_min_) {
timer0_min = timer0_min_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_timer0_max(u32 timer0_max_) {
timer0_max = timer0_max_;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_mac_addr1() const {
return mac_addr1;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_mac_addr2() const {
return mac_addr2;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_mac_addr3() const {
return mac_addr3;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_mac_addr4() const {
return mac_addr4;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_mac_addr5() const {
return mac_addr5;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_mac_addr6() const {
return mac_addr6;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_year() const {
return year;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_month() const {
return month;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_day() const {
return day;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_hour() const {
return hour;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_minute() const {
return minute;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_second() const {
return second;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_week() const {
return ((2000+year-(month<3)) + (2000+year-(month<3))/4 -
(2000+year-(month<3))/100 + (2000+year-(month<3))/400 +
(13*(month+(month<3)*12)+8)/5 + day) % 7;
}
template<typename Constant>
DateTime Parameters5Gen<Constant>::get_date_time() const {
DateTime date_time;
date_time.set_year(year);
date_time.set_month(year);
date_time.set_day(year);
date_time.set_hour(year);
date_time.set_minute(year);
date_time.set_second(year);
return date_time;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_nazo1() const {
return nazo1;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_nazo2() const {
return nazo2;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_nazo3() const {
return nazo3;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_nazo4() const {
return nazo4;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_nazo5() const {
return nazo5;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_vcount() const {
return vcount;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_timer0() const {
return timer0;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_gxstat() const {
return gxstat;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_frame() const {
return frame;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_key() const {
return key;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_timer0_min() const {
return timer0_min;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_timer0_max() const {
return timer0_max;
}
template class Parameters5Gen<ROMType::None>;
template class Parameters5Gen<ROMType::B1Ja>;
template class Parameters5Gen<ROMType::W1Ja>;
template class Parameters5Gen<ROMType::B2Ja>;
template class Parameters5Gen<ROMType::W2Ja>;
} // end PokeRNG
<commit_msg>get_date_timeを修正<commit_after>/*
* Copyright (c) 2014 odan
* License: MIT License
*/
#include "Parameters5Gen.hpp"
namespace PokeRNG {
template<typename Constant>
Parameters5Gen<Constant>::Parameters5Gen() : nazo1(Constant::nazo1), nazo2(Constant::nazo2), nazo3(Constant::nazo3), nazo4(Constant::nazo4), nazo5(Constant::nazo5), vcount(Constant::vcount), gxstat(Constant::gxstat), frame(Constant::frame), timer0_min(Constant::timer0_min), timer0_max(Constant::timer0_max), timer0(timer0_min), key(0x2fff), mac_addr1(0), mac_addr2(0), mac_addr3(0), mac_addr4(0), mac_addr5(0), mac_addr6(0), year(0), month(0), day(0), hour(0), minute(0), second(0) { }
template<typename Constant>
void Parameters5Gen<Constant>::set_mac_addr(u32 m1, u32 m2, u32 m3, u32 m4, u32 m5, u32 m6) {
mac_addr1 = m1;
mac_addr2 = m2;
mac_addr3 = m3;
mac_addr4 = m4;
mac_addr5 = m5;
mac_addr6 = m6;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_year(u32 year_) {
year = year_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_month(u32 month_) {
month = month_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_day(u32 day_) {
day = day_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_hour(u32 hour_) {
hour = hour_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_minute(u32 minute_) {
minute = minute_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_second(u32 second_) {
second = second_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_date_time(const DateTime& date_time) {
year = date_time.get_year();
month = date_time.get_month();
day = date_time.get_day();
hour = date_time.get_hour();
minute = date_time.get_minute();
second = date_time.get_second();
}
template<typename Constant>
void Parameters5Gen<Constant>::set_key(u32 key_) {
key = key_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_timer0(u32 timer0_) {
timer0 = timer0_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_vcount(u32 vcount_) {
vcount = vcount_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_gxstat(u32 gxstat_) {
gxstat = gxstat_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_frame(u32 frame_) {
frame = frame_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_nazo1(u32 nazo1_) {
nazo1 = nazo1_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_nazo2(u32 nazo2_) {
nazo2 = nazo2_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_nazo3(u32 nazo3_) {
nazo3 = nazo3_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_nazo4(u32 nazo4_) {
nazo4 = nazo4_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_nazo5(u32 nazo5_) {
nazo5 = nazo5_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_timer0_min(u32 timer0_min_) {
timer0_min = timer0_min_;
}
template<typename Constant>
void Parameters5Gen<Constant>::set_timer0_max(u32 timer0_max_) {
timer0_max = timer0_max_;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_mac_addr1() const {
return mac_addr1;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_mac_addr2() const {
return mac_addr2;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_mac_addr3() const {
return mac_addr3;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_mac_addr4() const {
return mac_addr4;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_mac_addr5() const {
return mac_addr5;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_mac_addr6() const {
return mac_addr6;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_year() const {
return year;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_month() const {
return month;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_day() const {
return day;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_hour() const {
return hour;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_minute() const {
return minute;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_second() const {
return second;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_week() const {
return ((2000+year-(month<3)) + (2000+year-(month<3))/4 -
(2000+year-(month<3))/100 + (2000+year-(month<3))/400 +
(13*(month+(month<3)*12)+8)/5 + day) % 7;
}
template<typename Constant>
DateTime Parameters5Gen<Constant>::get_date_time() const {
DateTime date_time;
date_time.set_year(year);
date_time.set_month(month);
date_time.set_day(day);
date_time.set_hour(hour);
date_time.set_minute(minute);
date_time.set_second(second);
return date_time;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_nazo1() const {
return nazo1;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_nazo2() const {
return nazo2;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_nazo3() const {
return nazo3;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_nazo4() const {
return nazo4;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_nazo5() const {
return nazo5;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_vcount() const {
return vcount;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_timer0() const {
return timer0;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_gxstat() const {
return gxstat;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_frame() const {
return frame;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_key() const {
return key;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_timer0_min() const {
return timer0_min;
}
template<typename Constant>
u32 Parameters5Gen<Constant>::get_timer0_max() const {
return timer0_max;
}
template class Parameters5Gen<ROMType::None>;
template class Parameters5Gen<ROMType::B1Ja>;
template class Parameters5Gen<ROMType::W1Ja>;
template class Parameters5Gen<ROMType::B2Ja>;
template class Parameters5Gen<ROMType::W2Ja>;
} // end PokeRNG
<|endoftext|>
|
<commit_before>
#include <Hord/Error.hpp>
#include <Hord/IO/Datastore.hpp>
#include <utility>
namespace Hord {
namespace IO {
// class Datastore implementation
#define HORD_SCOPE_CLASS_IDENT__ IO::Datastore
Datastore::Datastore(
String root_path
) noexcept
: m_root_path(std::move(root_path))
{}
Datastore::~Datastore() = default;
#define HORD_CLOSED_CHECK__ \
if (!is_open()) { \
HORD_THROW_ERROR_SCOPED_FQN( \
ErrorCode::datastore_closed, \
"cannot perform this operation while" \
" datastore is closed" \
); \
}
#define HORD_LOCKED_CHECK__ \
if (is_locked()) { \
HORD_THROW_ERROR_SCOPED_FQN( \
ErrorCode::datastore_locked, \
"cannot perform this operation while" \
" datastore is locked" \
); \
}
#define HORD_SCOPE_FUNC_IDENT__ set_root_path
void
Datastore::set_root_path(
String root_path
) {
if (is_open()) {
HORD_THROW_ERROR_SCOPED_FQN(
ErrorCode::datastore_property_immutable,
"cannot change root path while datastore is open"
);
}
m_root_path.assign(std::move(root_path));
}
#undef HORD_SCOPE_FUNC_IDENT__
#define HORD_SCOPE_FUNC_IDENT__ open
void
Datastore::open() {
if (is_open()) {
HORD_THROW_ERROR_SCOPED_FQN(
ErrorCode::datastore_open_already,
"datastore is already open"
);
}
open_impl();
}
#undef HORD_SCOPE_FUNC_IDENT__
#define HORD_SCOPE_FUNC_IDENT__ close
void
Datastore::close() {
HORD_LOCKED_CHECK__;
if (is_open()) {
close_impl();
}
}
#undef HORD_SCOPE_FUNC_IDENT__
// acquire
#define HORD_SCOPE_FUNC_IDENT__ acquire_input_stream
std::istream&
Datastore::acquire_input_stream(
IO::PropInfo const& prop_info
) {
HORD_CLOSED_CHECK__;
HORD_LOCKED_CHECK__;
return acquire_input_stream_impl(prop_info);
}
#undef HORD_SCOPE_FUNC_IDENT__
#define HORD_SCOPE_FUNC_IDENT__ acquire_output_stream
std::ostream&
Datastore::acquire_output_stream(
IO::PropInfo const& prop_info
) {
HORD_CLOSED_CHECK__;
HORD_LOCKED_CHECK__;
return acquire_output_stream_impl(prop_info);
}
#undef HORD_SCOPE_FUNC_IDENT__
// release
#define HORD_SCOPE_FUNC_IDENT__ release_input_stream
void
Datastore::release_input_stream(
IO::PropInfo const& prop_info
) {
HORD_CLOSED_CHECK__;
release_input_stream_impl(prop_info);
}
#undef HORD_SCOPE_FUNC_IDENT__
#define HORD_SCOPE_FUNC_IDENT__ release_output_stream
void
Datastore::release_output_stream(
IO::PropInfo const& prop_info
) {
HORD_CLOSED_CHECK__;
HORD_LOCKED_CHECK__;
release_output_stream_impl(prop_info);
}
#undef HORD_SCOPE_FUNC_IDENT__
#undef HORD_CLOSED_CHECK__
#undef HORD_LOCKED_CHECK__
#undef HORD_SCOPE_CLASS_IDENT__
} // namespace IO
} // namespace Hord
<commit_msg>IO::Datastore: removed erroneous lock check in release_output_stream().<commit_after>
#include <Hord/Error.hpp>
#include <Hord/IO/Datastore.hpp>
#include <utility>
namespace Hord {
namespace IO {
// class Datastore implementation
#define HORD_SCOPE_CLASS_IDENT__ IO::Datastore
Datastore::Datastore(
String root_path
) noexcept
: m_root_path(std::move(root_path))
{}
Datastore::~Datastore() = default;
#define HORD_CLOSED_CHECK__ \
if (!is_open()) { \
HORD_THROW_ERROR_SCOPED_FQN( \
ErrorCode::datastore_closed, \
"cannot perform this operation while" \
" datastore is closed" \
); \
}
#define HORD_LOCKED_CHECK__ \
if (is_locked()) { \
HORD_THROW_ERROR_SCOPED_FQN( \
ErrorCode::datastore_locked, \
"cannot perform this operation while" \
" datastore is locked" \
); \
}
#define HORD_SCOPE_FUNC_IDENT__ set_root_path
void
Datastore::set_root_path(
String root_path
) {
if (is_open()) {
HORD_THROW_ERROR_SCOPED_FQN(
ErrorCode::datastore_property_immutable,
"cannot change root path while datastore is open"
);
}
m_root_path.assign(std::move(root_path));
}
#undef HORD_SCOPE_FUNC_IDENT__
#define HORD_SCOPE_FUNC_IDENT__ open
void
Datastore::open() {
if (is_open()) {
HORD_THROW_ERROR_SCOPED_FQN(
ErrorCode::datastore_open_already,
"datastore is already open"
);
}
open_impl();
}
#undef HORD_SCOPE_FUNC_IDENT__
#define HORD_SCOPE_FUNC_IDENT__ close
void
Datastore::close() {
HORD_LOCKED_CHECK__;
if (is_open()) {
close_impl();
}
}
#undef HORD_SCOPE_FUNC_IDENT__
// acquire
#define HORD_SCOPE_FUNC_IDENT__ acquire_input_stream
std::istream&
Datastore::acquire_input_stream(
IO::PropInfo const& prop_info
) {
HORD_CLOSED_CHECK__;
HORD_LOCKED_CHECK__;
return acquire_input_stream_impl(prop_info);
}
#undef HORD_SCOPE_FUNC_IDENT__
#define HORD_SCOPE_FUNC_IDENT__ acquire_output_stream
std::ostream&
Datastore::acquire_output_stream(
IO::PropInfo const& prop_info
) {
HORD_CLOSED_CHECK__;
HORD_LOCKED_CHECK__;
return acquire_output_stream_impl(prop_info);
}
#undef HORD_SCOPE_FUNC_IDENT__
// release
#define HORD_SCOPE_FUNC_IDENT__ release_input_stream
void
Datastore::release_input_stream(
IO::PropInfo const& prop_info
) {
HORD_CLOSED_CHECK__;
release_input_stream_impl(prop_info);
}
#undef HORD_SCOPE_FUNC_IDENT__
#define HORD_SCOPE_FUNC_IDENT__ release_output_stream
void
Datastore::release_output_stream(
IO::PropInfo const& prop_info
) {
HORD_CLOSED_CHECK__;
release_output_stream_impl(prop_info);
}
#undef HORD_SCOPE_FUNC_IDENT__
#undef HORD_CLOSED_CHECK__
#undef HORD_LOCKED_CHECK__
#undef HORD_SCOPE_CLASS_IDENT__
} // namespace IO
} // namespace Hord
<|endoftext|>
|
<commit_before>#ifndef MJOLNIR_FORCE_FIELD
#define MJOLNIR_FORCE_FIELD
#include <mjolnir/core/LocalForceField.hpp>
#include <mjolnir/core/GlobalForceField.hpp>
#include <mjolnir/core/ExternalForceField.hpp>
namespace mjolnir
{
template<typename traitsT>
class ForceField
{
public:
typedef traitsT traits_type;
typedef typename traits_type::real_type real_type;
typedef typename traits_type::coordinate_type coordinate_type;
typedef System<traits_type> system_type;
typedef LocalForceField<traits_type> local_forcefield_type;
typedef GlobalForceField<traits_type> global_forcefield_type;
typedef ExternalForceField<traits_type> external_forcefield_type;
public:
ForceField(local_forcefield_type&& local, global_forcefield_type&& global)
: local_(std::move(local)), global_(std::move(global))
{}
ForceField(local_forcefield_type&& local,
global_forcefield_type&& global,
external_forcefield_type&& external)
: local_(std::move(local)), global_(std::move(global)),
external_(std::move(external))
{}
ForceField() = default;
~ForceField() = default;
ForceField(const ForceField&) = delete;
ForceField(ForceField&&) = default;
ForceField& operator=(const ForceField&) = delete;
ForceField& operator=(ForceField&&) = default;
// this modify system::topology by using local interaction info.
void initialize(system_type& sys)
{
// first, fetch current topology
local_.write_topology(sys.topology());
sys.topology().construct_molecules();
// based on the topology, make exclusion list
local_.initialize(sys);
global_.initialize(sys);
external_.initialize(sys);
}
// update parameters like temperature, ionic concentration, etc...
void update(const system_type& sys)
{
local_.update(sys);
global_.update(sys);
external_.update(sys);
}
void calc_force(system_type& sys)
{
local_.calc_force(sys);
global_.calc_force(sys);
external_.calc_force(sys);
}
real_type calc_energy(const system_type& sys) const
{
return local_.calc_energy(sys) + global_.calc_energy(sys) +
external_.calc_energy(sys);
}
std::string list_energy_name() const
{
return local_.list_energy() + global_.list_energy() +
external_.list_energy();
}
std::string dump_energy(const system_type& sys) const
{
return local_.dump_energy(sys) + global_.dump_energy(sys) +
external_.dump_energy(sys);
}
private:
local_forcefield_type local_;
global_forcefield_type global_;
external_forcefield_type external_;
};
} // mjolnir
#endif /* MJOLNIR_FORCE_FIELD */
<commit_msg>add an accessor to ForceField<commit_after>#ifndef MJOLNIR_FORCE_FIELD
#define MJOLNIR_FORCE_FIELD
#include <mjolnir/core/LocalForceField.hpp>
#include <mjolnir/core/GlobalForceField.hpp>
#include <mjolnir/core/ExternalForceField.hpp>
namespace mjolnir
{
template<typename traitsT>
class ForceField
{
public:
typedef traitsT traits_type;
typedef typename traits_type::real_type real_type;
typedef typename traits_type::coordinate_type coordinate_type;
typedef System<traits_type> system_type;
typedef LocalForceField<traits_type> local_forcefield_type;
typedef GlobalForceField<traits_type> global_forcefield_type;
typedef ExternalForceField<traits_type> external_forcefield_type;
public:
ForceField(local_forcefield_type&& local, global_forcefield_type&& global)
: local_(std::move(local)), global_(std::move(global))
{}
ForceField(local_forcefield_type&& local,
global_forcefield_type&& global,
external_forcefield_type&& external)
: local_(std::move(local)), global_(std::move(global)),
external_(std::move(external))
{}
ForceField() = default;
~ForceField() = default;
ForceField(const ForceField&) = delete;
ForceField(ForceField&&) = default;
ForceField& operator=(const ForceField&) = delete;
ForceField& operator=(ForceField&&) = default;
// this modify system::topology by using local interaction info.
void initialize(system_type& sys)
{
// first, fetch current topology
local_.write_topology(sys.topology());
sys.topology().construct_molecules();
// based on the topology, make exclusion list
local_.initialize(sys);
global_.initialize(sys);
external_.initialize(sys);
}
// update parameters like temperature, ionic concentration, etc...
void update(const system_type& sys)
{
local_.update(sys);
global_.update(sys);
external_.update(sys);
}
void calc_force(system_type& sys)
{
local_.calc_force(sys);
global_.calc_force(sys);
external_.calc_force(sys);
}
real_type calc_energy(const system_type& sys) const
{
return local_.calc_energy(sys) + global_.calc_energy(sys) +
external_.calc_energy(sys);
}
std::string list_energy_name() const
{
return local_.list_energy() + global_.list_energy() +
external_.list_energy();
}
std::string dump_energy(const system_type& sys) const
{
return local_.dump_energy(sys) + global_.dump_energy(sys) +
external_.dump_energy(sys);
}
local_forcefield_type const& local() const noexcept {return local_;}
global_forcefield_type const& global() const noexcept {return global_;}
external_forcefield_type const& external() const noexcept {return external_;}
private:
local_forcefield_type local_;
global_forcefield_type global_;
external_forcefield_type external_;
};
} // mjolnir
#endif /* MJOLNIR_FORCE_FIELD */
<|endoftext|>
|
<commit_before>// $Id$
// vim:tabstop=2
/***********************************************************************
***********************************************************************/
/**
* k-best Batch Mira, as described in:
*
* Colin Cherry and George Foster
* Batch Tuning Strategies for Statistical Machine Translation
* NAACL 2012
*
* Implemented by colin.cherry@nrc-cnrc.gc.ca
*
* To license implementations of any of the other tuners in that paper,
* please get in touch with any member of NRC Canada's Portage project
*
* Input is a set of n-best lists, encoded as feature and score files.
*
* Output is a weight file that results from running MIRA on these
* n-btest lists for J iterations. Will return the set that maximizes
* training BLEU.
**/
#include <cmath>
#include <cstddef>
#include <cstdlib>
#include <ctime>
#include <cassert>
#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <algorithm>
#include <boost/program_options.hpp>
#include <boost/scoped_ptr.hpp>
#include "BleuScorer.h"
#include "HypPackEnumerator.h"
#include "MiraFeatureVector.h"
#include "MiraWeightVector.h"
using namespace std;
using namespace MosesTuning;
namespace po = boost::program_options;
ValType evaluate(HypPackEnumerator* train, const AvgWeightVector& wv) {
vector<ValType> stats(kBleuNgramOrder*2+1,0);
for(train->reset(); !train->finished(); train->next()) {
// Find max model
size_t max_index=0;
ValType max_score=0;
for(size_t i=0;i<train->cur_size();i++) {
MiraFeatureVector vec(train->featuresAt(i));
ValType score = wv.score(vec);
if(i==0 || score > max_score) {
max_index = i;
max_score = score;
}
}
// Update stats
const vector<float>& sent = train->scoresAt(max_index);
for(size_t i=0;i<sent.size();i++) {
stats[i]+=sent[i];
}
}
return unsmoothedBleu(stats);
}
int main(int argc, char** argv)
{
bool help;
string denseInitFile;
string sparseInitFile;
vector<string> scoreFiles;
vector<string> featureFiles;
int seed;
string outputFile;
float c = 0.01; // Step-size cap C
float decay = 0.999; // Pseudo-corpus decay \gamma
int n_iters = 60; // Max epochs J
bool streaming = false; // Stream all k-best lists?
bool no_shuffle = false; // Don't shuffle, even for in memory version
bool model_bg = false; // Use model for background corpus
bool verbose = false; // Verbose updates
// Command-line processing follows pro.cpp
po::options_description desc("Allowed options");
desc.add_options()
("help,h", po::value(&help)->zero_tokens()->default_value(false), "Print this help message and exit")
("scfile,S", po::value<vector<string> >(&scoreFiles), "Scorer data files")
("ffile,F", po::value<vector<string> > (&featureFiles), "Feature data files")
("random-seed,r", po::value<int>(&seed), "Seed for random number generation")
("output-file,o", po::value<string>(&outputFile), "Output file")
("cparam,C", po::value<float>(&c), "MIRA C-parameter, lower for more regularization (default 0.01)")
("decay,D", po::value<float>(&decay), "BLEU background corpus decay rate (default 0.999)")
("iters,J", po::value<int>(&n_iters), "Number of MIRA iterations to run (default 60)")
("dense-init,d", po::value<string>(&denseInitFile), "Weight file for dense features")
("sparse-init,s", po::value<string>(&sparseInitFile), "Weight file for sparse features")
("streaming", po::value(&streaming)->zero_tokens()->default_value(false), "Stream n-best lists to save memory, implies --no-shuffle")
("no-shuffle", po::value(&no_shuffle)->zero_tokens()->default_value(false), "Don't shuffle hypotheses before each epoch")
("model-bg", po::value(&model_bg)->zero_tokens()->default_value(false), "Use model instead of hope for BLEU background")
("verbose", po::value(&verbose)->zero_tokens()->default_value(false), "Verbose updates")
;
po::options_description cmdline_options;
cmdline_options.add(desc);
po::variables_map vm;
po::store(po::command_line_parser(argc,argv).
options(cmdline_options).run(), vm);
po::notify(vm);
if (help) {
cout << "Usage: " + string(argv[0]) + " [options]" << endl;
cout << desc << endl;
exit(0);
}
cerr << "kbmira with c=" << c << " decay=" << decay << " no_shuffle=" << no_shuffle << endl;
if (vm.count("random-seed")) {
cerr << "Initialising random seed to " << seed << endl;
srand(seed);
} else {
cerr << "Initialising random seed from system clock" << endl;
srand(time(NULL));
}
// Initialize weights
///
// Dense
vector<parameter_t> initParams;
if(!denseInitFile.empty()) {
ifstream opt(denseInitFile.c_str());
string buffer;
if (opt.fail()) {
cerr << "could not open dense initfile: " << denseInitFile << endl;
exit(3);
}
parameter_t val;
getline(opt,buffer);
istringstream strstrm(buffer);
while(strstrm >> val) {
initParams.push_back(val);
}
opt.close();
}
size_t initDenseSize = initParams.size();
// Sparse
if(!sparseInitFile.empty()) {
if(initDenseSize==0) {
cerr << "sparse initialization requires dense initialization" << endl;
exit(3);
}
ifstream opt(sparseInitFile.c_str());
if(opt.fail()) {
cerr << "could not open sparse initfile: " << sparseInitFile << endl;
exit(3);
}
int sparseCount=0;
parameter_t val; std::string name;
while(opt >> name >> val) {
size_t id = SparseVector::encode(name) + initDenseSize;
while(initParams.size()<=id) initParams.push_back(0.0);
initParams[id] = val;
sparseCount++;
}
cerr << "Found " << sparseCount << " initial sparse features" << endl;
opt.close();
}
MiraWeightVector wv(initParams);
// Initialize background corpus
vector<ValType> bg;
for(int j=0;j<kBleuNgramOrder;j++){
bg.push_back(kBleuNgramOrder-j);
bg.push_back(kBleuNgramOrder-j);
}
bg.push_back(kBleuNgramOrder);
// Training loop
boost::scoped_ptr<HypPackEnumerator> train;
if(streaming)
train.reset(new StreamingHypPackEnumerator(featureFiles, scoreFiles));
else
train.reset(new RandomAccessHypPackEnumerator(featureFiles, scoreFiles, no_shuffle));
cerr << "Initial BLEU = " << evaluate(train.get(), wv.avg()) << endl;
ValType bestBleu = 0;
for(int j=0;j<n_iters;j++)
{
// MIRA train for one epoch
int iNumHyps = 0;
int iNumExamples = 0;
int iNumUpdates = 0;
ValType totalLoss = 0.0;
for(train->reset(); !train->finished(); train->next()) {
// Hope / fear decode
size_t hope_index=0, fear_index=0, model_index=0;
ValType hope_score=0, fear_score=0, model_score=0;
for(size_t i=0; i< train->cur_size(); i++) {
const MiraFeatureVector& vec=train->featuresAt(i);
ValType score = wv.score(vec);
ValType bleu = sentenceLevelBackgroundBleu(train->scoresAt(i),bg);
// Hope
if(i==0 || (score + bleu) > hope_score) {
hope_score = score + bleu;
hope_index = i;
}
// Fear
if(i==0 || (score - bleu) > fear_score) {
fear_score = score - bleu;
fear_index = i;
}
// Model
if(i==0 || score > model_score) {
model_score = score;
model_index = i;
}
iNumHyps++;
}
// Update weights
if(hope_index!=fear_index) {
// Vector difference
const MiraFeatureVector& hope=train->featuresAt(hope_index);
const MiraFeatureVector& fear=train->featuresAt(fear_index);
MiraFeatureVector diff = hope - fear;
// Bleu difference
const vector<float>& hope_stats = train->scoresAt(hope_index);
ValType hopeBleu = sentenceLevelBackgroundBleu(hope_stats, bg);
const vector<float>& fear_stats = train->scoresAt(fear_index);
ValType fearBleu = sentenceLevelBackgroundBleu(fear_stats, bg);
assert(hopeBleu + 1e-8 >= fearBleu);
ValType delta = hopeBleu - fearBleu;
// Loss and update
ValType diff_score = wv.score(diff);
ValType loss = delta - diff_score;
if(verbose) {
cerr << "Updating sent " << train->cur_id() << endl;
cerr << "Wght: " << wv << endl;
cerr << "Hope: " << hope << " => " << hopeBleu << " <> " << wv.score(hope) << endl;
cerr << "Fear: " << fear << " => " << fearBleu << " <> " << wv.score(fear) << endl;
cerr << "Diff: " << diff << " => " << delta << " <> " << diff_score << endl;
cerr << endl;
}
if(loss > 0) {
ValType eta = min(c, loss / diff.sqrNorm());
wv.update(diff,eta);
totalLoss+=loss;
iNumUpdates++;
}
// Update BLEU statistics
const vector<float>& model_stats = train->scoresAt(model_index);
for(size_t k=0;k<bg.size();k++) {
bg[k]*=decay;
if(model_bg)
bg[k]+=model_stats[k];
else
bg[k]+=hope_stats[k];
}
}
iNumExamples++;
}
// Training Epoch summary
cerr << iNumUpdates << "/" << iNumExamples << " updates"
<< ", avg loss = " << (totalLoss / iNumExamples);
// Evaluate current average weights
AvgWeightVector avg = wv.avg();
ValType bleu = evaluate(train.get(), avg);
cerr << ", BLEU = " << bleu << endl;
if(bleu > bestBleu) {
size_t num_dense = train->num_dense();
if(initDenseSize>0 && initDenseSize!=num_dense) {
cerr << "Error: Initial dense feature count and dense feature count from n-best do not match: "
<< initDenseSize << "!=" << num_dense << endl;
exit(1);
}
// Write to a file
ostream* out;
ofstream outFile;
if (!outputFile.empty() ) {
outFile.open(outputFile.c_str());
if (!(outFile)) {
cerr << "Error: Failed to open " << outputFile << endl;
exit(1);
}
out = &outFile;
} else {
out = &cout;
}
for(size_t i=0;i<avg.size();i++) {
if(i<num_dense)
*out << "F" << i << " " << avg.weight(i) << endl;
else {
if(abs(avg.weight(i))>1e-8)
*out << SparseVector::decode(i-num_dense) << " " << avg.weight(i) << endl;
}
}
outFile.close();
bestBleu = bleu;
}
}
cerr << "Best BLEU = " << bestBleu << endl;
}
// --Emacs trickery--
// Local Variables:
// mode:c++
// c-basic-offset:2
// End:
<commit_msg>As requested by my bosses: added NRC copyright to kbmira.<commit_after>// $Id$
// vim:tabstop=2
/***********************************************************************
K-best Batch MIRA for Moses
Copyright (C) 2012, National Research Council Canada / Conseil national
de recherches du Canada
***********************************************************************/
/**
* k-best Batch Mira, as described in:
*
* Colin Cherry and George Foster
* Batch Tuning Strategies for Statistical Machine Translation
* NAACL 2012
*
* Implemented by colin.cherry@nrc-cnrc.gc.ca
*
* To license implementations of any of the other tuners in that paper,
* please get in touch with any member of NRC Canada's Portage project
*
* Input is a set of n-best lists, encoded as feature and score files.
*
* Output is a weight file that results from running MIRA on these
* n-btest lists for J iterations. Will return the set that maximizes
* training BLEU.
**/
#include <cmath>
#include <cstddef>
#include <cstdlib>
#include <ctime>
#include <cassert>
#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <algorithm>
#include <boost/program_options.hpp>
#include <boost/scoped_ptr.hpp>
#include "BleuScorer.h"
#include "HypPackEnumerator.h"
#include "MiraFeatureVector.h"
#include "MiraWeightVector.h"
using namespace std;
using namespace MosesTuning;
namespace po = boost::program_options;
ValType evaluate(HypPackEnumerator* train, const AvgWeightVector& wv) {
vector<ValType> stats(kBleuNgramOrder*2+1,0);
for(train->reset(); !train->finished(); train->next()) {
// Find max model
size_t max_index=0;
ValType max_score=0;
for(size_t i=0;i<train->cur_size();i++) {
MiraFeatureVector vec(train->featuresAt(i));
ValType score = wv.score(vec);
if(i==0 || score > max_score) {
max_index = i;
max_score = score;
}
}
// Update stats
const vector<float>& sent = train->scoresAt(max_index);
for(size_t i=0;i<sent.size();i++) {
stats[i]+=sent[i];
}
}
return unsmoothedBleu(stats);
}
int main(int argc, char** argv)
{
bool help;
string denseInitFile;
string sparseInitFile;
vector<string> scoreFiles;
vector<string> featureFiles;
int seed;
string outputFile;
float c = 0.01; // Step-size cap C
float decay = 0.999; // Pseudo-corpus decay \gamma
int n_iters = 60; // Max epochs J
bool streaming = false; // Stream all k-best lists?
bool no_shuffle = false; // Don't shuffle, even for in memory version
bool model_bg = false; // Use model for background corpus
bool verbose = false; // Verbose updates
// Command-line processing follows pro.cpp
po::options_description desc("Allowed options");
desc.add_options()
("help,h", po::value(&help)->zero_tokens()->default_value(false), "Print this help message and exit")
("scfile,S", po::value<vector<string> >(&scoreFiles), "Scorer data files")
("ffile,F", po::value<vector<string> > (&featureFiles), "Feature data files")
("random-seed,r", po::value<int>(&seed), "Seed for random number generation")
("output-file,o", po::value<string>(&outputFile), "Output file")
("cparam,C", po::value<float>(&c), "MIRA C-parameter, lower for more regularization (default 0.01)")
("decay,D", po::value<float>(&decay), "BLEU background corpus decay rate (default 0.999)")
("iters,J", po::value<int>(&n_iters), "Number of MIRA iterations to run (default 60)")
("dense-init,d", po::value<string>(&denseInitFile), "Weight file for dense features")
("sparse-init,s", po::value<string>(&sparseInitFile), "Weight file for sparse features")
("streaming", po::value(&streaming)->zero_tokens()->default_value(false), "Stream n-best lists to save memory, implies --no-shuffle")
("no-shuffle", po::value(&no_shuffle)->zero_tokens()->default_value(false), "Don't shuffle hypotheses before each epoch")
("model-bg", po::value(&model_bg)->zero_tokens()->default_value(false), "Use model instead of hope for BLEU background")
("verbose", po::value(&verbose)->zero_tokens()->default_value(false), "Verbose updates")
;
po::options_description cmdline_options;
cmdline_options.add(desc);
po::variables_map vm;
po::store(po::command_line_parser(argc,argv).
options(cmdline_options).run(), vm);
po::notify(vm);
if (help) {
cout << "Usage: " + string(argv[0]) + " [options]" << endl;
cout << desc << endl;
exit(0);
}
cerr << "kbmira with c=" << c << " decay=" << decay << " no_shuffle=" << no_shuffle << endl;
if (vm.count("random-seed")) {
cerr << "Initialising random seed to " << seed << endl;
srand(seed);
} else {
cerr << "Initialising random seed from system clock" << endl;
srand(time(NULL));
}
// Initialize weights
///
// Dense
vector<parameter_t> initParams;
if(!denseInitFile.empty()) {
ifstream opt(denseInitFile.c_str());
string buffer;
if (opt.fail()) {
cerr << "could not open dense initfile: " << denseInitFile << endl;
exit(3);
}
parameter_t val;
getline(opt,buffer);
istringstream strstrm(buffer);
while(strstrm >> val) {
initParams.push_back(val);
}
opt.close();
}
size_t initDenseSize = initParams.size();
// Sparse
if(!sparseInitFile.empty()) {
if(initDenseSize==0) {
cerr << "sparse initialization requires dense initialization" << endl;
exit(3);
}
ifstream opt(sparseInitFile.c_str());
if(opt.fail()) {
cerr << "could not open sparse initfile: " << sparseInitFile << endl;
exit(3);
}
int sparseCount=0;
parameter_t val; std::string name;
while(opt >> name >> val) {
size_t id = SparseVector::encode(name) + initDenseSize;
while(initParams.size()<=id) initParams.push_back(0.0);
initParams[id] = val;
sparseCount++;
}
cerr << "Found " << sparseCount << " initial sparse features" << endl;
opt.close();
}
MiraWeightVector wv(initParams);
// Initialize background corpus
vector<ValType> bg;
for(int j=0;j<kBleuNgramOrder;j++){
bg.push_back(kBleuNgramOrder-j);
bg.push_back(kBleuNgramOrder-j);
}
bg.push_back(kBleuNgramOrder);
// Training loop
boost::scoped_ptr<HypPackEnumerator> train;
if(streaming)
train.reset(new StreamingHypPackEnumerator(featureFiles, scoreFiles));
else
train.reset(new RandomAccessHypPackEnumerator(featureFiles, scoreFiles, no_shuffle));
cerr << "Initial BLEU = " << evaluate(train.get(), wv.avg()) << endl;
ValType bestBleu = 0;
for(int j=0;j<n_iters;j++)
{
// MIRA train for one epoch
int iNumHyps = 0;
int iNumExamples = 0;
int iNumUpdates = 0;
ValType totalLoss = 0.0;
for(train->reset(); !train->finished(); train->next()) {
// Hope / fear decode
size_t hope_index=0, fear_index=0, model_index=0;
ValType hope_score=0, fear_score=0, model_score=0;
for(size_t i=0; i< train->cur_size(); i++) {
const MiraFeatureVector& vec=train->featuresAt(i);
ValType score = wv.score(vec);
ValType bleu = sentenceLevelBackgroundBleu(train->scoresAt(i),bg);
// Hope
if(i==0 || (score + bleu) > hope_score) {
hope_score = score + bleu;
hope_index = i;
}
// Fear
if(i==0 || (score - bleu) > fear_score) {
fear_score = score - bleu;
fear_index = i;
}
// Model
if(i==0 || score > model_score) {
model_score = score;
model_index = i;
}
iNumHyps++;
}
// Update weights
if(hope_index!=fear_index) {
// Vector difference
const MiraFeatureVector& hope=train->featuresAt(hope_index);
const MiraFeatureVector& fear=train->featuresAt(fear_index);
MiraFeatureVector diff = hope - fear;
// Bleu difference
const vector<float>& hope_stats = train->scoresAt(hope_index);
ValType hopeBleu = sentenceLevelBackgroundBleu(hope_stats, bg);
const vector<float>& fear_stats = train->scoresAt(fear_index);
ValType fearBleu = sentenceLevelBackgroundBleu(fear_stats, bg);
assert(hopeBleu + 1e-8 >= fearBleu);
ValType delta = hopeBleu - fearBleu;
// Loss and update
ValType diff_score = wv.score(diff);
ValType loss = delta - diff_score;
if(verbose) {
cerr << "Updating sent " << train->cur_id() << endl;
cerr << "Wght: " << wv << endl;
cerr << "Hope: " << hope << " => " << hopeBleu << " <> " << wv.score(hope) << endl;
cerr << "Fear: " << fear << " => " << fearBleu << " <> " << wv.score(fear) << endl;
cerr << "Diff: " << diff << " => " << delta << " <> " << diff_score << endl;
cerr << endl;
}
if(loss > 0) {
ValType eta = min(c, loss / diff.sqrNorm());
wv.update(diff,eta);
totalLoss+=loss;
iNumUpdates++;
}
// Update BLEU statistics
const vector<float>& model_stats = train->scoresAt(model_index);
for(size_t k=0;k<bg.size();k++) {
bg[k]*=decay;
if(model_bg)
bg[k]+=model_stats[k];
else
bg[k]+=hope_stats[k];
}
}
iNumExamples++;
}
// Training Epoch summary
cerr << iNumUpdates << "/" << iNumExamples << " updates"
<< ", avg loss = " << (totalLoss / iNumExamples);
// Evaluate current average weights
AvgWeightVector avg = wv.avg();
ValType bleu = evaluate(train.get(), avg);
cerr << ", BLEU = " << bleu << endl;
if(bleu > bestBleu) {
size_t num_dense = train->num_dense();
if(initDenseSize>0 && initDenseSize!=num_dense) {
cerr << "Error: Initial dense feature count and dense feature count from n-best do not match: "
<< initDenseSize << "!=" << num_dense << endl;
exit(1);
}
// Write to a file
ostream* out;
ofstream outFile;
if (!outputFile.empty() ) {
outFile.open(outputFile.c_str());
if (!(outFile)) {
cerr << "Error: Failed to open " << outputFile << endl;
exit(1);
}
out = &outFile;
} else {
out = &cout;
}
for(size_t i=0;i<avg.size();i++) {
if(i<num_dense)
*out << "F" << i << " " << avg.weight(i) << endl;
else {
if(abs(avg.weight(i))>1e-8)
*out << SparseVector::decode(i-num_dense) << " " << avg.weight(i) << endl;
}
}
outFile.close();
bestBleu = bleu;
}
}
cerr << "Best BLEU = " << bestBleu << endl;
}
// --Emacs trickery--
// Local Variables:
// mode:c++
// c-basic-offset:2
// End:
<|endoftext|>
|
<commit_before>//===- TopDownClosure.cpp - Compute the top-down interprocedure closure ---===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the TDDataStructures class, which represents the
// Top-down Interprocedural closure of the data structure graph over the
// program. This is useful (but not strictly necessary?) for applications
// like pointer analysis.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/DataStructure.h"
#include "llvm/Module.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Analysis/DSGraph.h"
#include "Support/Debug.h"
#include "Support/Statistic.h"
using namespace llvm;
namespace {
RegisterAnalysis<TDDataStructures> // Register the pass
Y("tddatastructure", "Top-down Data Structure Analysis");
Statistic<> NumTDInlines("tddatastructures", "Number of graphs inlined");
}
void TDDataStructures::markReachableFunctionsExternallyAccessible(DSNode *N,
hash_set<DSNode*> &Visited) {
if (!N || Visited.count(N)) return;
Visited.insert(N);
for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i) {
DSNodeHandle &NH = N->getLink(i*N->getPointerSize());
if (DSNode *NN = NH.getNode()) {
const std::vector<GlobalValue*> &Globals = NN->getGlobals();
for (unsigned G = 0, e = Globals.size(); G != e; ++G)
if (Function *F = dyn_cast<Function>(Globals[G]))
ArgsRemainIncomplete.insert(F);
markReachableFunctionsExternallyAccessible(NN, Visited);
}
}
}
// run - Calculate the top down data structure graphs for each function in the
// program.
//
bool TDDataStructures::run(Module &M) {
BUDataStructures &BU = getAnalysis<BUDataStructures>();
GlobalsGraph = new DSGraph(BU.getGlobalsGraph());
GlobalsGraph->setPrintAuxCalls();
// Figure out which functions must not mark their arguments complete because
// they are accessible outside this compilation unit. Currently, these
// arguments are functions which are reachable by global variables in the
// globals graph.
const DSGraph::ScalarMapTy &GGSM = GlobalsGraph->getScalarMap();
hash_set<DSNode*> Visited;
for (DSScalarMap::global_iterator I = GGSM.global_begin(), E = GGSM.global_end();
I != E; ++I)
markReachableFunctionsExternallyAccessible(GGSM.find(*I)->second.getNode(), Visited);
// Loop over unresolved call nodes. Any functions passed into (but not
// returned!) from unresolvable call nodes may be invoked outside of the
// current module.
const std::vector<DSCallSite> &Calls = GlobalsGraph->getAuxFunctionCalls();
for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
const DSCallSite &CS = Calls[i];
for (unsigned arg = 0, e = CS.getNumPtrArgs(); arg != e; ++arg)
markReachableFunctionsExternallyAccessible(CS.getPtrArg(arg).getNode(),
Visited);
}
Visited.clear();
// Functions without internal linkage also have unknown incoming arguments!
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
if (!I->isExternal() && !I->hasInternalLinkage())
ArgsRemainIncomplete.insert(I);
// We want to traverse the call graph in reverse post-order. To do this, we
// calculate a post-order traversal, then reverse it.
hash_set<DSGraph*> VisitedGraph;
std::vector<DSGraph*> PostOrder;
const BUDataStructures::ActualCalleesTy &ActualCallees =
getAnalysis<BUDataStructures>().getActualCallees();
// Calculate top-down from main...
if (Function *F = M.getMainFunction())
ComputePostOrder(*F, VisitedGraph, PostOrder, ActualCallees);
// Next calculate the graphs for each unreachable function...
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
ComputePostOrder(*I, VisitedGraph, PostOrder, ActualCallees);
VisitedGraph.clear(); // Release memory!
// Visit each of the graphs in reverse post-order now!
while (!PostOrder.empty()) {
inlineGraphIntoCallees(*PostOrder.back());
PostOrder.pop_back();
}
ArgsRemainIncomplete.clear();
return false;
}
DSGraph &TDDataStructures::getOrCreateDSGraph(Function &F) {
DSGraph *&G = DSInfo[&F];
if (G == 0) { // Not created yet? Clone BU graph...
G = new DSGraph(getAnalysis<BUDataStructures>().getDSGraph(F));
G->getAuxFunctionCalls().clear();
G->setPrintAuxCalls();
G->setGlobalsGraph(GlobalsGraph);
}
return *G;
}
void TDDataStructures::ComputePostOrder(Function &F,hash_set<DSGraph*> &Visited,
std::vector<DSGraph*> &PostOrder,
const BUDataStructures::ActualCalleesTy &ActualCallees) {
if (F.isExternal()) return;
DSGraph &G = getOrCreateDSGraph(F);
if (Visited.count(&G)) return;
Visited.insert(&G);
// Recursively traverse all of the callee graphs.
const std::vector<DSCallSite> &FunctionCalls = G.getFunctionCalls();
for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
Instruction *CallI = FunctionCalls[i].getCallSite().getInstruction();
std::pair<BUDataStructures::ActualCalleesTy::const_iterator,
BUDataStructures::ActualCalleesTy::const_iterator>
IP = ActualCallees.equal_range(CallI);
for (BUDataStructures::ActualCalleesTy::const_iterator I = IP.first;
I != IP.second; ++I)
ComputePostOrder(*I->second, Visited, PostOrder, ActualCallees);
}
PostOrder.push_back(&G);
}
// releaseMemory - If the pass pipeline is done with this pass, we can release
// our memory... here...
//
// FIXME: This should be releaseMemory and will work fine, except that LoadVN
// has no way to extend the lifetime of the pass, which screws up ds-aa.
//
void TDDataStructures::releaseMyMemory() {
for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
E = DSInfo.end(); I != E; ++I) {
I->second->getReturnNodes().erase(I->first);
if (I->second->getReturnNodes().empty())
delete I->second;
}
// Empty map so next time memory is released, data structures are not
// re-deleted.
DSInfo.clear();
delete GlobalsGraph;
GlobalsGraph = 0;
}
void TDDataStructures::inlineGraphIntoCallees(DSGraph &Graph) {
// Recompute the Incomplete markers and eliminate unreachable nodes.
Graph.removeTriviallyDeadNodes();
Graph.maskIncompleteMarkers();
// If any of the functions has incomplete incoming arguments, don't mark any
// of them as complete.
bool HasIncompleteArgs = false;
const DSGraph::ReturnNodesTy &GraphReturnNodes = Graph.getReturnNodes();
for (DSGraph::ReturnNodesTy::const_iterator I = GraphReturnNodes.begin(),
E = GraphReturnNodes.end(); I != E; ++I)
if (ArgsRemainIncomplete.count(I->first)) {
HasIncompleteArgs = true;
break;
}
// Now fold in the necessary globals from the GlobalsGraph. A global G
// must be folded in if it exists in the current graph (i.e., is not dead)
// and it was not inlined from any of my callers. If it was inlined from
// a caller, it would have been fully consistent with the GlobalsGraph
// in the caller so folding in is not necessary. Otherwise, this node came
// solely from this function's BU graph and so has to be made consistent.
//
Graph.updateFromGlobalGraph();
// Recompute the Incomplete markers. Depends on whether args are complete
unsigned Flags
= HasIncompleteArgs ? DSGraph::MarkFormalArgs : DSGraph::IgnoreFormalArgs;
Graph.markIncompleteNodes(Flags | DSGraph::IgnoreGlobals);
// Delete dead nodes. Treat globals that are unreachable as dead also.
Graph.removeDeadNodes(DSGraph::RemoveUnreachableGlobals);
// We are done with computing the current TD Graph! Now move on to
// inlining the current graph into the graphs for its callees, if any.
//
const std::vector<DSCallSite> &FunctionCalls = Graph.getFunctionCalls();
if (FunctionCalls.empty()) {
DEBUG(std::cerr << " [TD] No callees for: " << Graph.getFunctionNames()
<< "\n");
return;
}
// Now that we have information about all of the callees, propagate the
// current graph into the callees. Clone only the reachable subgraph at
// each call-site, not the entire graph (even though the entire graph
// would be cloned only once, this should still be better on average).
//
DEBUG(std::cerr << " [TD] Inlining '" << Graph.getFunctionNames() <<"' into "
<< FunctionCalls.size() << " call nodes.\n");
const BUDataStructures::ActualCalleesTy &ActualCallees =
getAnalysis<BUDataStructures>().getActualCallees();
// Loop over all the call sites and all the callees at each call site. Build
// a mapping from called DSGraph's to the call sites in this function that
// invoke them. This is useful because we can be more efficient if there are
// multiple call sites to the callees in the graph from this caller.
std::multimap<DSGraph*, std::pair<Function*, const DSCallSite*> > CallSites;
for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
Instruction *CallI = FunctionCalls[i].getCallSite().getInstruction();
// For each function in the invoked function list at this call site...
std::pair<BUDataStructures::ActualCalleesTy::const_iterator,
BUDataStructures::ActualCalleesTy::const_iterator>
IP = ActualCallees.equal_range(CallI);
// Loop over each actual callee at this call site
for (BUDataStructures::ActualCalleesTy::const_iterator I = IP.first;
I != IP.second; ++I) {
DSGraph& CalleeGraph = getDSGraph(*I->second);
assert(&CalleeGraph != &Graph && "TD need not inline graph into self!");
CallSites.insert(std::make_pair(&CalleeGraph,
std::make_pair(I->second, &FunctionCalls[i])));
}
}
// Now that we built the mapping, actually perform the inlining a callee graph
// at a time.
std::multimap<DSGraph*,std::pair<Function*,const DSCallSite*> >::iterator CSI;
for (CSI = CallSites.begin(); CSI != CallSites.end(); ) {
DSGraph &CalleeGraph = *CSI->first;
// Iterate through all of the call sites of this graph, cloning and merging
// any nodes required by the call.
ReachabilityCloner RC(CalleeGraph, Graph, DSGraph::StripModRefBits);
// Clone over any global nodes that appear in both graphs.
for (DSGraph::ScalarMapTy::const_iterator
SI = CalleeGraph.getScalarMap().begin(),
SE = CalleeGraph.getScalarMap().end(); SI != SE; ++SI)
if (GlobalValue *GV = dyn_cast<GlobalValue>(SI->first)) {
DSGraph::ScalarMapTy::const_iterator GI = Graph.getScalarMap().find(GV);
if (GI != Graph.getScalarMap().end())
RC.merge(SI->second, GI->second);
}
// Loop over all of the distinct call sites in the caller of the callee.
for (; CSI != CallSites.end() && CSI->first == &CalleeGraph; ++CSI) {
Function &CF = *CSI->second.first;
const DSCallSite &CS = *CSI->second.second;
DEBUG(std::cerr << " [TD] Resolving arguments for callee graph '"
<< CalleeGraph.getFunctionNames()
<< "': " << CF.getFunctionType()->getNumParams()
<< " args\n at call site (DSCallSite*) 0x" << &CS << "\n");
// Get the formal argument and return nodes for the called function and
// merge them with the cloned subgraph.
RC.mergeCallSite(CalleeGraph.getCallSiteForArguments(CF), CS);
++NumTDInlines;
}
}
DEBUG(std::cerr << " [TD] Done inlining into callees for: "
<< Graph.getFunctionNames() << " [" << Graph.getGraphSize() << "+"
<< Graph.getFunctionCalls().size() << "]\n");
}
<commit_msg>In the TD pass, iterate over globals directly instead of through the whole scalar map. This saves 5s in the TD pass, from 22->17s on perlbmk<commit_after>//===- TopDownClosure.cpp - Compute the top-down interprocedure closure ---===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the TDDataStructures class, which represents the
// Top-down Interprocedural closure of the data structure graph over the
// program. This is useful (but not strictly necessary?) for applications
// like pointer analysis.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/DataStructure.h"
#include "llvm/Module.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Analysis/DSGraph.h"
#include "Support/Debug.h"
#include "Support/Statistic.h"
using namespace llvm;
namespace {
RegisterAnalysis<TDDataStructures> // Register the pass
Y("tddatastructure", "Top-down Data Structure Analysis");
Statistic<> NumTDInlines("tddatastructures", "Number of graphs inlined");
}
void TDDataStructures::markReachableFunctionsExternallyAccessible(DSNode *N,
hash_set<DSNode*> &Visited) {
if (!N || Visited.count(N)) return;
Visited.insert(N);
for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i) {
DSNodeHandle &NH = N->getLink(i*N->getPointerSize());
if (DSNode *NN = NH.getNode()) {
const std::vector<GlobalValue*> &Globals = NN->getGlobals();
for (unsigned G = 0, e = Globals.size(); G != e; ++G)
if (Function *F = dyn_cast<Function>(Globals[G]))
ArgsRemainIncomplete.insert(F);
markReachableFunctionsExternallyAccessible(NN, Visited);
}
}
}
// run - Calculate the top down data structure graphs for each function in the
// program.
//
bool TDDataStructures::run(Module &M) {
BUDataStructures &BU = getAnalysis<BUDataStructures>();
GlobalsGraph = new DSGraph(BU.getGlobalsGraph());
GlobalsGraph->setPrintAuxCalls();
// Figure out which functions must not mark their arguments complete because
// they are accessible outside this compilation unit. Currently, these
// arguments are functions which are reachable by global variables in the
// globals graph.
const DSScalarMap &GGSM = GlobalsGraph->getScalarMap();
hash_set<DSNode*> Visited;
for (DSScalarMap::global_iterator I = GGSM.global_begin(), E = GGSM.global_end();
I != E; ++I)
markReachableFunctionsExternallyAccessible(GGSM.find(*I)->second.getNode(), Visited);
// Loop over unresolved call nodes. Any functions passed into (but not
// returned!) from unresolvable call nodes may be invoked outside of the
// current module.
const std::vector<DSCallSite> &Calls = GlobalsGraph->getAuxFunctionCalls();
for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
const DSCallSite &CS = Calls[i];
for (unsigned arg = 0, e = CS.getNumPtrArgs(); arg != e; ++arg)
markReachableFunctionsExternallyAccessible(CS.getPtrArg(arg).getNode(),
Visited);
}
Visited.clear();
// Functions without internal linkage also have unknown incoming arguments!
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
if (!I->isExternal() && !I->hasInternalLinkage())
ArgsRemainIncomplete.insert(I);
// We want to traverse the call graph in reverse post-order. To do this, we
// calculate a post-order traversal, then reverse it.
hash_set<DSGraph*> VisitedGraph;
std::vector<DSGraph*> PostOrder;
const BUDataStructures::ActualCalleesTy &ActualCallees =
getAnalysis<BUDataStructures>().getActualCallees();
// Calculate top-down from main...
if (Function *F = M.getMainFunction())
ComputePostOrder(*F, VisitedGraph, PostOrder, ActualCallees);
// Next calculate the graphs for each unreachable function...
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
ComputePostOrder(*I, VisitedGraph, PostOrder, ActualCallees);
VisitedGraph.clear(); // Release memory!
// Visit each of the graphs in reverse post-order now!
while (!PostOrder.empty()) {
inlineGraphIntoCallees(*PostOrder.back());
PostOrder.pop_back();
}
ArgsRemainIncomplete.clear();
return false;
}
DSGraph &TDDataStructures::getOrCreateDSGraph(Function &F) {
DSGraph *&G = DSInfo[&F];
if (G == 0) { // Not created yet? Clone BU graph...
G = new DSGraph(getAnalysis<BUDataStructures>().getDSGraph(F));
G->getAuxFunctionCalls().clear();
G->setPrintAuxCalls();
G->setGlobalsGraph(GlobalsGraph);
}
return *G;
}
void TDDataStructures::ComputePostOrder(Function &F,hash_set<DSGraph*> &Visited,
std::vector<DSGraph*> &PostOrder,
const BUDataStructures::ActualCalleesTy &ActualCallees) {
if (F.isExternal()) return;
DSGraph &G = getOrCreateDSGraph(F);
if (Visited.count(&G)) return;
Visited.insert(&G);
// Recursively traverse all of the callee graphs.
const std::vector<DSCallSite> &FunctionCalls = G.getFunctionCalls();
for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
Instruction *CallI = FunctionCalls[i].getCallSite().getInstruction();
std::pair<BUDataStructures::ActualCalleesTy::const_iterator,
BUDataStructures::ActualCalleesTy::const_iterator>
IP = ActualCallees.equal_range(CallI);
for (BUDataStructures::ActualCalleesTy::const_iterator I = IP.first;
I != IP.second; ++I)
ComputePostOrder(*I->second, Visited, PostOrder, ActualCallees);
}
PostOrder.push_back(&G);
}
// releaseMemory - If the pass pipeline is done with this pass, we can release
// our memory... here...
//
// FIXME: This should be releaseMemory and will work fine, except that LoadVN
// has no way to extend the lifetime of the pass, which screws up ds-aa.
//
void TDDataStructures::releaseMyMemory() {
for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
E = DSInfo.end(); I != E; ++I) {
I->second->getReturnNodes().erase(I->first);
if (I->second->getReturnNodes().empty())
delete I->second;
}
// Empty map so next time memory is released, data structures are not
// re-deleted.
DSInfo.clear();
delete GlobalsGraph;
GlobalsGraph = 0;
}
void TDDataStructures::inlineGraphIntoCallees(DSGraph &Graph) {
// Recompute the Incomplete markers and eliminate unreachable nodes.
Graph.removeTriviallyDeadNodes();
Graph.maskIncompleteMarkers();
// If any of the functions has incomplete incoming arguments, don't mark any
// of them as complete.
bool HasIncompleteArgs = false;
const DSGraph::ReturnNodesTy &GraphReturnNodes = Graph.getReturnNodes();
for (DSGraph::ReturnNodesTy::const_iterator I = GraphReturnNodes.begin(),
E = GraphReturnNodes.end(); I != E; ++I)
if (ArgsRemainIncomplete.count(I->first)) {
HasIncompleteArgs = true;
break;
}
// Now fold in the necessary globals from the GlobalsGraph. A global G
// must be folded in if it exists in the current graph (i.e., is not dead)
// and it was not inlined from any of my callers. If it was inlined from
// a caller, it would have been fully consistent with the GlobalsGraph
// in the caller so folding in is not necessary. Otherwise, this node came
// solely from this function's BU graph and so has to be made consistent.
//
Graph.updateFromGlobalGraph();
// Recompute the Incomplete markers. Depends on whether args are complete
unsigned Flags
= HasIncompleteArgs ? DSGraph::MarkFormalArgs : DSGraph::IgnoreFormalArgs;
Graph.markIncompleteNodes(Flags | DSGraph::IgnoreGlobals);
// Delete dead nodes. Treat globals that are unreachable as dead also.
Graph.removeDeadNodes(DSGraph::RemoveUnreachableGlobals);
// We are done with computing the current TD Graph! Now move on to
// inlining the current graph into the graphs for its callees, if any.
//
const std::vector<DSCallSite> &FunctionCalls = Graph.getFunctionCalls();
if (FunctionCalls.empty()) {
DEBUG(std::cerr << " [TD] No callees for: " << Graph.getFunctionNames()
<< "\n");
return;
}
// Now that we have information about all of the callees, propagate the
// current graph into the callees. Clone only the reachable subgraph at
// each call-site, not the entire graph (even though the entire graph
// would be cloned only once, this should still be better on average).
//
DEBUG(std::cerr << " [TD] Inlining '" << Graph.getFunctionNames() <<"' into "
<< FunctionCalls.size() << " call nodes.\n");
const BUDataStructures::ActualCalleesTy &ActualCallees =
getAnalysis<BUDataStructures>().getActualCallees();
// Loop over all the call sites and all the callees at each call site. Build
// a mapping from called DSGraph's to the call sites in this function that
// invoke them. This is useful because we can be more efficient if there are
// multiple call sites to the callees in the graph from this caller.
std::multimap<DSGraph*, std::pair<Function*, const DSCallSite*> > CallSites;
for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
Instruction *CallI = FunctionCalls[i].getCallSite().getInstruction();
// For each function in the invoked function list at this call site...
std::pair<BUDataStructures::ActualCalleesTy::const_iterator,
BUDataStructures::ActualCalleesTy::const_iterator>
IP = ActualCallees.equal_range(CallI);
// Loop over each actual callee at this call site
for (BUDataStructures::ActualCalleesTy::const_iterator I = IP.first;
I != IP.second; ++I) {
DSGraph& CalleeGraph = getDSGraph(*I->second);
assert(&CalleeGraph != &Graph && "TD need not inline graph into self!");
CallSites.insert(std::make_pair(&CalleeGraph,
std::make_pair(I->second, &FunctionCalls[i])));
}
}
// Now that we built the mapping, actually perform the inlining a callee graph
// at a time.
std::multimap<DSGraph*,std::pair<Function*,const DSCallSite*> >::iterator CSI;
for (CSI = CallSites.begin(); CSI != CallSites.end(); ) {
DSGraph &CalleeGraph = *CSI->first;
// Iterate through all of the call sites of this graph, cloning and merging
// any nodes required by the call.
ReachabilityCloner RC(CalleeGraph, Graph, DSGraph::StripModRefBits);
// Clone over any global nodes that appear in both graphs.
for (DSScalarMap::global_iterator
SI = CalleeGraph.getScalarMap().global_begin(),
SE = CalleeGraph.getScalarMap().global_end(); SI != SE; ++SI) {
DSScalarMap::const_iterator GI = Graph.getScalarMap().find(*SI);
if (GI != Graph.getScalarMap().end())
RC.merge(CalleeGraph.getNodeForValue(*SI), GI->second);
}
// Loop over all of the distinct call sites in the caller of the callee.
for (; CSI != CallSites.end() && CSI->first == &CalleeGraph; ++CSI) {
Function &CF = *CSI->second.first;
const DSCallSite &CS = *CSI->second.second;
DEBUG(std::cerr << " [TD] Resolving arguments for callee graph '"
<< CalleeGraph.getFunctionNames()
<< "': " << CF.getFunctionType()->getNumParams()
<< " args\n at call site (DSCallSite*) 0x" << &CS << "\n");
// Get the formal argument and return nodes for the called function and
// merge them with the cloned subgraph.
RC.mergeCallSite(CalleeGraph.getCallSiteForArguments(CF), CS);
++NumTDInlines;
}
}
DEBUG(std::cerr << " [TD] Done inlining into callees for: "
<< Graph.getFunctionNames() << " [" << Graph.getGraphSize() << "+"
<< Graph.getFunctionCalls().size() << "]\n");
}
<|endoftext|>
|
<commit_before>//===========================================
// Lumina-DE source code
// Copyright (c) 2016, Ken Moore
// Available under the 3-clause BSD license
// See the LICENSE file for full details
//===========================================
#include "session.h"
#include <QObject>
#include <QProcess>
#include <QProcessEnvironment>
#include <QDebug>
#include <LuminaUtils.h>
#include <LuminaOS.h>
void LSession::stopall(){
stopping = true;
for(int i=0; i<PROCS.length(); i++){
if(PROCS[i]->state()!=QProcess::NotRunning){ PROCS[i]->kill(); }
}
QCoreApplication::processEvents();
for(int i=0; i<PROCS.length(); i++){
if(PROCS[i]->state()!=QProcess::NotRunning){ PROCS[i]->terminate(); }
}
//QCoreApplication::exit(0);
}
void LSession::procFinished(){
//Go through and check the status on all the procs to determine which one finished
int stopped = 0;
for(int i=0; i<PROCS.length(); i++){
if(PROCS[i]->state()==QProcess::NotRunning){
stopped++;
if(!stopping){
//See if this process is the main desktop binary
if(PROCS[i]->program().section("/",-1) == "lumina-desktop"){ stopall(); } //start closing down everything
//else{ PROCS[i]->start(QIODevice::ReadOnly); } //restart the process
break;
}
}
}
if(stopping && stopped==PROCS.length()){
QCoreApplication::exit(0);
}
}
void LSession::startProcess(QString ID, QString command, QStringList watchfiles){
QString dir = QString(getenv("XDG_CONFIG_HOME"))+"/lumina-desktop/logs";
if(!QFile::exists(dir)){ QDir tmp(dir); tmp.mkpath(dir); }
QString logfile = dir+"/"+ID+".log";
if(QFile::exists(logfile+".old")){ QFile::remove(logfile+".old"); }
if(QFile::exists(logfile)){ QFile::rename(logfile,logfile+".old"); }
LProcess *proc = new LProcess(ID, watchfiles);
proc->setProcessChannelMode(QProcess::MergedChannels);
proc->setProcessEnvironment( QProcessEnvironment::systemEnvironment() );
proc->setStandardOutputFile(logfile);
proc->start(command, QIODevice::ReadOnly);
connect(proc, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(procFinished()) );
PROCS << proc;
}
void LSession::start(){
//First check for a valid installation
if( !LUtils::isValidBinary("fluxbox") || !LUtils::isValidBinary("lumina-desktop") ){
exit(1);
}
//Window Manager First
// FLUXBOX BUG BYPASS: if the ~/.fluxbox dir does not exist, it will ignore the given config file
if( !LUtils::isValidBinary("fluxbox") ){
qDebug() << "[INCOMPLETE LUMINA INSTALLATION] fluxbox binary is missing - cannot continue";
}else{
QString confDir = QString( getenv("XDG_CONFIG_HOME"))+"/lumina-desktop";
if(!QFile::exists(confDir)){ QDir dir(confDir); dir.mkpath(confDir); }
if(!QFile::exists(confDir+"/fluxbox-init")){
QFile::copy(LOS::LuminaShare()+"/fluxbox-init-rc",confDir+"/fluxbox-init");
QFile::setPermissions(confDir+"/fluxbox-init", QFile::ReadOwner | QFile::WriteOwner | QFile::ReadUser | QFile::ReadOther | QFile::ReadGroup);
}
if(!QFile::exists(confDir+"/fluxbox-keys")){
QStringList keys = LUtils::readFile(LOS::LuminaShare()+"/fluxbox-keys");
keys = keys.replaceInStrings("${XDG_CONFIG_HOME}", QString( getenv("XDG_CONFIG_HOME")));
LUtils::writeFile(confDir+"/fluxbox-keys", keys, true);
QFile::setPermissions(confDir+"/fluxbox-keys", QFile::ReadOwner | QFile::WriteOwner | QFile::ReadUser | QFile::ReadOther | QFile::ReadGroup);
}
// FLUXBOX BUG BYPASS: if the ~/.fluxbox dir does not exist, it will ignore the given config file
if(!QFile::exists(QDir::homePath()+"/.fluxbox")){
QDir dir; dir.mkpath(QDir::homePath()+"/.fluxbox");
}
QString cmd = "fluxbox -rc "+confDir+"/fluxbox-init -no-slit -no-toolbar";
startProcess("wm", cmd, QStringList() << confDir+"/fluxbox-init" << confDir+"/fluxbox-keys");
}
//Compositing manager
if(LUtils::isValidBinary("compton")){
QString set = QString(getenv("XDG_CONFIG_HOME"))+"/lumina-desktop/compton.conf";
if(!QFile::exists(set)){
QStringList dirs = QString(getenv("XDG_CONFIG_DIRS")).split(":");
for(int i=0; i<dirs.length(); i++){
if(QFile::exists(dirs[i]+"/compton.conf")){ QFile::copy(dirs[i]+"/compton.conf", set); break; }
else if(QFile::exists(dirs[i]+"/compton.conf.sample")){ QFile::copy(dirs[i]+"/compton.conf.sample", set); break; }
}
}
if(!QFile::exists(set)){
qDebug() << "Using default compton settings";
startProcess("compositing","compton");
}else{
startProcess("compositing","compton --config \""+set+"\"", QStringList() << set);
}
}else if(LUtils::isValidBinary("xcompmgr")){ startProcess("compositing","xcompmgr"); }
//Desktop Next
startProcess("runtime","lumina-desktop");
//ScreenSaver
if(LUtils::isValidBinary("xscreensaver")){ startProcess("screensaver","xscreensaver -no-splash"); }
}
<commit_msg>Also ensure that the XDG_CONFIG_HOME replacement happens on the fluxbox-init file as well.<commit_after>//===========================================
// Lumina-DE source code
// Copyright (c) 2016, Ken Moore
// Available under the 3-clause BSD license
// See the LICENSE file for full details
//===========================================
#include "session.h"
#include <QObject>
#include <QProcess>
#include <QProcessEnvironment>
#include <QDebug>
#include <LuminaUtils.h>
#include <LuminaOS.h>
void LSession::stopall(){
stopping = true;
for(int i=0; i<PROCS.length(); i++){
if(PROCS[i]->state()!=QProcess::NotRunning){ PROCS[i]->kill(); }
}
QCoreApplication::processEvents();
for(int i=0; i<PROCS.length(); i++){
if(PROCS[i]->state()!=QProcess::NotRunning){ PROCS[i]->terminate(); }
}
//QCoreApplication::exit(0);
}
void LSession::procFinished(){
//Go through and check the status on all the procs to determine which one finished
int stopped = 0;
for(int i=0; i<PROCS.length(); i++){
if(PROCS[i]->state()==QProcess::NotRunning){
stopped++;
if(!stopping){
//See if this process is the main desktop binary
if(PROCS[i]->program().section("/",-1) == "lumina-desktop"){ stopall(); } //start closing down everything
//else{ PROCS[i]->start(QIODevice::ReadOnly); } //restart the process
break;
}
}
}
if(stopping && stopped==PROCS.length()){
QCoreApplication::exit(0);
}
}
void LSession::startProcess(QString ID, QString command, QStringList watchfiles){
QString dir = QString(getenv("XDG_CONFIG_HOME"))+"/lumina-desktop/logs";
if(!QFile::exists(dir)){ QDir tmp(dir); tmp.mkpath(dir); }
QString logfile = dir+"/"+ID+".log";
if(QFile::exists(logfile+".old")){ QFile::remove(logfile+".old"); }
if(QFile::exists(logfile)){ QFile::rename(logfile,logfile+".old"); }
LProcess *proc = new LProcess(ID, watchfiles);
proc->setProcessChannelMode(QProcess::MergedChannels);
proc->setProcessEnvironment( QProcessEnvironment::systemEnvironment() );
proc->setStandardOutputFile(logfile);
proc->start(command, QIODevice::ReadOnly);
connect(proc, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(procFinished()) );
PROCS << proc;
}
void LSession::start(){
//First check for a valid installation
if( !LUtils::isValidBinary("fluxbox") || !LUtils::isValidBinary("lumina-desktop") ){
exit(1);
}
//Window Manager First
// FLUXBOX BUG BYPASS: if the ~/.fluxbox dir does not exist, it will ignore the given config file
if( !LUtils::isValidBinary("fluxbox") ){
qDebug() << "[INCOMPLETE LUMINA INSTALLATION] fluxbox binary is missing - cannot continue";
}else{
QString confDir = QString( getenv("XDG_CONFIG_HOME"))+"/lumina-desktop";
if(!QFile::exists(confDir)){ QDir dir(confDir); dir.mkpath(confDir); }
if(!QFile::exists(confDir+"/fluxbox-init")){
QStringList keys = LUtils::readFile(LOS::LuminaShare()+"/fluxbox-init-rc");
keys = keys.replaceInStrings("${XDG_CONFIG_HOME}", QString( getenv("XDG_CONFIG_HOME")));
LUtils::writeFile(confDir+"/fluxbox-init", keys, true);
QFile::setPermissions(confDir+"/fluxbox-init", QFile::ReadOwner | QFile::WriteOwner | QFile::ReadUser | QFile::ReadOther | QFile::ReadGroup);
}
if(!QFile::exists(confDir+"/fluxbox-keys")){
QStringList keys = LUtils::readFile(LOS::LuminaShare()+"/fluxbox-keys");
keys = keys.replaceInStrings("${XDG_CONFIG_HOME}", QString( getenv("XDG_CONFIG_HOME")));
LUtils::writeFile(confDir+"/fluxbox-keys", keys, true);
QFile::setPermissions(confDir+"/fluxbox-keys", QFile::ReadOwner | QFile::WriteOwner | QFile::ReadUser | QFile::ReadOther | QFile::ReadGroup);
}
// FLUXBOX BUG BYPASS: if the ~/.fluxbox dir does not exist, it will ignore the given config file
if(!QFile::exists(QDir::homePath()+"/.fluxbox")){
QDir dir; dir.mkpath(QDir::homePath()+"/.fluxbox");
}
QString cmd = "fluxbox -rc "+confDir+"/fluxbox-init -no-slit -no-toolbar";
startProcess("wm", cmd, QStringList() << confDir+"/fluxbox-init" << confDir+"/fluxbox-keys");
}
//Compositing manager
if(LUtils::isValidBinary("compton")){
QString set = QString(getenv("XDG_CONFIG_HOME"))+"/lumina-desktop/compton.conf";
if(!QFile::exists(set)){
QStringList dirs = QString(getenv("XDG_CONFIG_DIRS")).split(":");
for(int i=0; i<dirs.length(); i++){
if(QFile::exists(dirs[i]+"/compton.conf")){ QFile::copy(dirs[i]+"/compton.conf", set); break; }
else if(QFile::exists(dirs[i]+"/compton.conf.sample")){ QFile::copy(dirs[i]+"/compton.conf.sample", set); break; }
}
}
if(!QFile::exists(set)){
qDebug() << "Using default compton settings";
startProcess("compositing","compton");
}else{
startProcess("compositing","compton --config \""+set+"\"", QStringList() << set);
}
}else if(LUtils::isValidBinary("xcompmgr")){ startProcess("compositing","xcompmgr"); }
//Desktop Next
startProcess("runtime","lumina-desktop");
//ScreenSaver
if(LUtils::isValidBinary("xscreensaver")){ startProcess("screensaver","xscreensaver -no-splash"); }
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Tests the MetricsService stat recording to make sure that the numbers are
// what we expect.
#include <string>
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/platform_thread.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/prefs/pref_value_store.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/json_pref_store.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
class MetricsServiceTest : public UITest {
public:
MetricsServiceTest() : UITest() {
// We need to show the window so web content type tabs load.
show_window_ = true;
}
// Open a few tabs of random content
void OpenTabs() {
scoped_refptr<BrowserProxy> window = automation()->GetBrowserWindow(0);
ASSERT_TRUE(window.get());
FilePath page1_path;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &page1_path));
page1_path = page1_path.AppendASCII("title2.html");
ASSERT_TRUE(window->AppendTab(net::FilePathToFileURL(page1_path)));
FilePath page2_path;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &page2_path));
page2_path = page2_path.AppendASCII("iframe.html");
ASSERT_TRUE(window->AppendTab(net::FilePathToFileURL(page2_path)));
}
// Get a PrefService whose contents correspond to the Local State file
// that was saved by the app as it closed. The caller takes ownership of the
// returned PrefService object.
PrefService* GetLocalState() {
FilePath local_state_path = user_data_dir()
.Append(chrome::kLocalStateFilename);
return PrefService::CreateUserPrefService(local_state_path);
}
};
TEST_F(MetricsServiceTest, CloseRenderersNormally) {
OpenTabs();
QuitBrowser();
scoped_ptr<PrefService> local_state(GetLocalState());
local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
EXPECT_TRUE(local_state->GetBoolean(prefs::kStabilityExitedCleanly));
EXPECT_EQ(1, local_state->GetInteger(prefs::kStabilityLaunchCount));
EXPECT_EQ(3, local_state->GetInteger(prefs::kStabilityPageLoadCount));
EXPECT_EQ(0, local_state->GetInteger(prefs::kStabilityRendererCrashCount));
}
#if defined(OS_WIN)
// http://crbug.com/32048
#define CrashRenderers FLAKY_CrashRenders
#endif
TEST_F(MetricsServiceTest, CrashRenderers) {
// This doesn't make sense to test in single process mode.
if (in_process_renderer_)
return;
OpenTabs();
{
// Limit the lifetime of various automation proxies used here. We must
// destroy them before calling QuitBrowser.
scoped_refptr<BrowserProxy> window = automation()->GetBrowserWindow(0);
ASSERT_TRUE(window.get());
// Kill the process for one of the tabs.
scoped_refptr<TabProxy> tab(window->GetTab(1));
ASSERT_TRUE(tab.get());
// We should get a crash dump on Windows.
// Also on Linux with Breakpad enabled.
#if defined(OS_WIN) || defined(USE_LINUX_BREAKPAD)
expected_crashes_ = 1;
#endif
ASSERT_TRUE(tab->NavigateToURLAsync(GURL(chrome::kAboutCrashURL)));
}
// Give the browser a chance to notice the crashed tab.
PlatformThread::Sleep(sleep_timeout_ms());
QuitBrowser();
scoped_ptr<PrefService> local_state(GetLocalState());
local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
EXPECT_TRUE(local_state->GetBoolean(prefs::kStabilityExitedCleanly));
EXPECT_EQ(1, local_state->GetInteger(prefs::kStabilityLaunchCount));
EXPECT_EQ(4, local_state->GetInteger(prefs::kStabilityPageLoadCount));
EXPECT_EQ(1, local_state->GetInteger(prefs::kStabilityRendererCrashCount));
}
<commit_msg>Fix the expected number of crashes in a metrics test.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Tests the MetricsService stat recording to make sure that the numbers are
// what we expect.
#include <string>
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/platform_thread.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/prefs/pref_value_store.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/json_pref_store.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
class MetricsServiceTest : public UITest {
public:
MetricsServiceTest() : UITest() {
// We need to show the window so web content type tabs load.
show_window_ = true;
}
// Open a few tabs of random content
void OpenTabs() {
scoped_refptr<BrowserProxy> window = automation()->GetBrowserWindow(0);
ASSERT_TRUE(window.get());
FilePath page1_path;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &page1_path));
page1_path = page1_path.AppendASCII("title2.html");
ASSERT_TRUE(window->AppendTab(net::FilePathToFileURL(page1_path)));
FilePath page2_path;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &page2_path));
page2_path = page2_path.AppendASCII("iframe.html");
ASSERT_TRUE(window->AppendTab(net::FilePathToFileURL(page2_path)));
}
// Get a PrefService whose contents correspond to the Local State file
// that was saved by the app as it closed. The caller takes ownership of the
// returned PrefService object.
PrefService* GetLocalState() {
FilePath local_state_path = user_data_dir()
.Append(chrome::kLocalStateFilename);
return PrefService::CreateUserPrefService(local_state_path);
}
};
TEST_F(MetricsServiceTest, CloseRenderersNormally) {
OpenTabs();
QuitBrowser();
scoped_ptr<PrefService> local_state(GetLocalState());
local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
EXPECT_TRUE(local_state->GetBoolean(prefs::kStabilityExitedCleanly));
EXPECT_EQ(1, local_state->GetInteger(prefs::kStabilityLaunchCount));
EXPECT_EQ(3, local_state->GetInteger(prefs::kStabilityPageLoadCount));
EXPECT_EQ(0, local_state->GetInteger(prefs::kStabilityRendererCrashCount));
}
#if defined(OS_WIN)
// http://crbug.com/32048
#define CrashRenderers FLAKY_CrashRenders
#endif
TEST_F(MetricsServiceTest, CrashRenderers) {
// This doesn't make sense to test in single process mode.
if (in_process_renderer_)
return;
OpenTabs();
{
// Limit the lifetime of various automation proxies used here. We must
// destroy them before calling QuitBrowser.
scoped_refptr<BrowserProxy> window = automation()->GetBrowserWindow(0);
ASSERT_TRUE(window.get());
// Kill the process for one of the tabs.
scoped_refptr<TabProxy> tab(window->GetTab(1));
ASSERT_TRUE(tab.get());
// We can get crash dumps on Windows always, Linux when breakpad is
// enabled, and all platforms for official Google Chrome builds.
#if defined(OS_WIN) || defined(USE_LINUX_BREAKPAD) || \
defined(GOOGLE_CHROME_BUILD)
expected_crashes_ = 1;
#endif
ASSERT_TRUE(tab->NavigateToURLAsync(GURL(chrome::kAboutCrashURL)));
}
// Give the browser a chance to notice the crashed tab.
PlatformThread::Sleep(sleep_timeout_ms());
QuitBrowser();
scoped_ptr<PrefService> local_state(GetLocalState());
local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
EXPECT_TRUE(local_state->GetBoolean(prefs::kStabilityExitedCleanly));
EXPECT_EQ(1, local_state->GetInteger(prefs::kStabilityLaunchCount));
EXPECT_EQ(4, local_state->GetInteger(prefs::kStabilityPageLoadCount));
EXPECT_EQ(1, local_state->GetInteger(prefs::kStabilityRendererCrashCount));
}
<|endoftext|>
|
<commit_before><commit_msg>properly handle failure of loading a module<commit_after><|endoftext|>
|
<commit_before>#include "globalfunction.h"
#include <stdlib.h>
#include <univ/log.h>
#include <univ/univ.h>
using namespace Sloong;
using namespace Sloong::Universal;
#include <boost/foreach.hpp>
#include "dbproc.h"
#include "utility.h"
#include "jpeg.h"
#define ARRAYSIZE(a) (sizeof(a)/sizeof(a[0]))
CGlobalFunction* CGlobalFunction::g_pThis = NULL;
LuaFunctionRegistr g_LuaFunc[] =
{
{ "showLog", CGlobalFunction::Lua_showLog },
{ "querySql", CGlobalFunction::Lua_querySql },
{ "modifySql", CGlobalFunction::Lua_modifySql },
{ "getSqlError", CGlobalFunction::Lua_getSqlError },
{ "getThumbImage", CGlobalFunction::Lua_getThumbImage },
};
CGlobalFunction::CGlobalFunction()
{
m_pUtility = new CUtility();
m_pDBProc = new CDBProc();
g_pThis = this;
}
CGlobalFunction::~CGlobalFunction()
{
}
void Sloong::CGlobalFunction::Initialize( CLog* plog,CLua* pLua)
{
m_pLog = plog;
m_pLua = pLua;
m_pLua->SetErrorHandle(CGlobalFunction::HandleError);
vector<LuaFunctionRegistr> funcList(g_LuaFunc, g_LuaFunc + ARRAYSIZE(g_LuaFunc));
m_pLua->AddFunctions(&funcList);
// connect to db
m_pDBProc->Connect("localhost","root","sloong","sloong",0);
}
int Sloong::CGlobalFunction::Lua_querySql(lua_State* l)
{
auto lua = g_pThis->m_pLua;
vector<string> res;
g_pThis->m_pDBProc->Query(lua->GetStringArgument(1), res);
string allLine;
BOOST_FOREACH(string item, res)
{
string add = item;
CUniversal::Replace(add,"&","\&");
if ( allLine.empty())
{
allLine = add;
}
else
allLine = allLine + "&" + add;
}
lua->PushString(allLine);
return 1;
}
int Sloong::CGlobalFunction::Lua_modifySql(lua_State* l)
{
auto lua = g_pThis->m_pLua;
int nRes = g_pThis->m_pDBProc->Modify(lua->GetStringArgument(1));
lua->PushString(CUniversal::ntos(nRes));
return 1;
}
int Sloong::CGlobalFunction::Lua_getSqlError(lua_State *l)
{
g_pThis->m_pLua->PushString(g_pThis->m_pDBProc->GetError());
return 1;
}
<<<<<<< HEAD
<<<<<<< HEAD
=======
=======
>>>>>>> 0e9ce2205ca1529b4cd1887b3080e06308c23d4b
int Sloong::CGlobalFunction::Lua_getThumbImage(lua_State* l)
{
auto lua = g_pThis->m_pLua;
auto path = lua->GetStringArgument(1);
auto width = lua->GetNumberArgument(2);
auto height = lua->GetNumberArgument(3);
auto quality = lua->GetNumberArgument(4);
if ( access(path.c_str(),ACC_E) != -1 )
{
<<<<<<< HEAD
string thumbpath = CUniversal::Format("%s_%d_%d_%d.%s", path.substr(0, path.length() - 4), width, height, quality, path.substr(path.length() - 3));
=======
string thumbpath = CUniversal::Format("%s_%d_%d_%d.%s", path.substr(0, path.length() - 4), width, height, path.substr(path.length() - 3), 3 );
>>>>>>> 0e9ce2205ca1529b4cd1887b3080e06308c23d4b
if (access(thumbpath.c_str(), ACC_E) != 0)
{
CJPEG jpg;
jpg.Load(path);
<<<<<<< HEAD
jpg.Save(quality, width, height, thumbpath);
=======
jpg.Save(70, 0, 0, thumbpath);
>>>>>>> 0e9ce2205ca1529b4cd1887b3080e06308c23d4b
}
lua->PushString(thumbpath);
}
return 1;
}
<<<<<<< HEAD
>>>>>>> a5283e8... modify: when send a message fialed, the message is add to epoll list, then function is returnd. but now the message is not send done, in this time, send a other message, the message should be add to epoll list. no should send with direct.
=======
>>>>>>> 0e9ce2205ca1529b4cd1887b3080e06308c23d4b
void CGlobalFunction::HandleError(string err)
{
g_pThis->m_pLog->Log(err, ERR, -2);
}
int CGlobalFunction::Lua_showLog(lua_State* l)
{
g_pThis->m_pLog->Log(g_pThis->m_pLua->GetStringArgument(1));
}
<commit_msg>remove the merge text.<commit_after>#include "globalfunction.h"
#include <stdlib.h>
#include <univ/log.h>
#include <univ/univ.h>
using namespace Sloong;
using namespace Sloong::Universal;
#include <boost/foreach.hpp>
#include "dbproc.h"
#include "utility.h"
#include "jpeg.h"
#define ARRAYSIZE(a) (sizeof(a)/sizeof(a[0]))
CGlobalFunction* CGlobalFunction::g_pThis = NULL;
LuaFunctionRegistr g_LuaFunc[] =
{
{ "showLog", CGlobalFunction::Lua_showLog },
{ "querySql", CGlobalFunction::Lua_querySql },
{ "modifySql", CGlobalFunction::Lua_modifySql },
{ "getSqlError", CGlobalFunction::Lua_getSqlError },
{ "getThumbImage", CGlobalFunction::Lua_getThumbImage },
};
CGlobalFunction::CGlobalFunction()
{
m_pUtility = new CUtility();
m_pDBProc = new CDBProc();
g_pThis = this;
}
CGlobalFunction::~CGlobalFunction()
{
}
void Sloong::CGlobalFunction::Initialize( CLog* plog,CLua* pLua)
{
m_pLog = plog;
m_pLua = pLua;
m_pLua->SetErrorHandle(CGlobalFunction::HandleError);
vector<LuaFunctionRegistr> funcList(g_LuaFunc, g_LuaFunc + ARRAYSIZE(g_LuaFunc));
m_pLua->AddFunctions(&funcList);
// connect to db
m_pDBProc->Connect("localhost","root","sloong","sloong",0);
}
int Sloong::CGlobalFunction::Lua_querySql(lua_State* l)
{
auto lua = g_pThis->m_pLua;
vector<string> res;
g_pThis->m_pDBProc->Query(lua->GetStringArgument(1), res);
string allLine;
BOOST_FOREACH(string item, res)
{
string add = item;
CUniversal::Replace(add,"&","\&");
if ( allLine.empty())
{
allLine = add;
}
else
allLine = allLine + "&" + add;
}
lua->PushString(allLine);
return 1;
}
int Sloong::CGlobalFunction::Lua_modifySql(lua_State* l)
{
auto lua = g_pThis->m_pLua;
int nRes = g_pThis->m_pDBProc->Modify(lua->GetStringArgument(1));
lua->PushString(CUniversal::ntos(nRes));
return 1;
}
int Sloong::CGlobalFunction::Lua_getSqlError(lua_State *l)
{
g_pThis->m_pLua->PushString(g_pThis->m_pDBProc->GetError());
return 1;
}
int Sloong::CGlobalFunction::Lua_getThumbImage(lua_State* l)
{
auto lua = g_pThis->m_pLua;
auto path = lua->GetStringArgument(1);
auto width = lua->GetNumberArgument(2);
auto height = lua->GetNumberArgument(3);
auto quality = lua->GetNumberArgument(4);
if ( access(path.c_str(),ACC_E) != -1 )
{
string thumbpath = CUniversal::Format("%s_%d_%d_%d.%s", path.substr(0, path.length() - 4), width, height, quality, path.substr(path.length() - 3));
if (access(thumbpath.c_str(), ACC_E) != 0)
{
CJPEG jpg;
jpg.Load(path);
jpg.Save(quality, width, height, thumbpath);
}
lua->PushString(thumbpath);
}
return 1;
}
void CGlobalFunction::HandleError(string err)
{
g_pThis->m_pLog->Log(err, ERR, -2);
}
int CGlobalFunction::Lua_showLog(lua_State* l)
{
g_pThis->m_pLog->Log(g_pThis->m_pLua->GetStringArgument(1));
}
<|endoftext|>
|
<commit_before>// 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.
// Tests the MetricsService stat recording to make sure that the numbers are
// what we expect.
#include <string>
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/test/test_timeouts.h"
#include "base/threading/platform_thread.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/prefs/pref_service_mock_builder.h"
#include "chrome/browser/prefs/pref_value_store.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/json_pref_store.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
class MetricsServiceTest : public UITest {
public:
MetricsServiceTest() : UITest() {
// We need to show the window so web content type tabs load.
show_window_ = true;
}
// Open a few tabs of random content
void OpenTabs() {
scoped_refptr<BrowserProxy> window = automation()->GetBrowserWindow(0);
ASSERT_TRUE(window.get());
FilePath page1_path;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &page1_path));
page1_path = page1_path.AppendASCII("title2.html");
ASSERT_TRUE(window->AppendTab(net::FilePathToFileURL(page1_path)));
FilePath page2_path;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &page2_path));
page2_path = page2_path.AppendASCII("iframe.html");
ASSERT_TRUE(window->AppendTab(net::FilePathToFileURL(page2_path)));
}
// Get a PrefService whose contents correspond to the Local State file
// that was saved by the app as it closed. The caller takes ownership of the
// returned PrefService object.
PrefService* GetLocalState() {
FilePath path = user_data_dir().Append(chrome::kLocalStateFilename);
return PrefServiceMockBuilder().WithUserFilePrefs(path).Create();
}
};
TEST_F(MetricsServiceTest, CloseRenderersNormally) {
OpenTabs();
QuitBrowser();
scoped_ptr<PrefService> local_state(GetLocalState());
local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
EXPECT_TRUE(local_state->GetBoolean(prefs::kStabilityExitedCleanly));
EXPECT_EQ(1, local_state->GetInteger(prefs::kStabilityLaunchCount));
EXPECT_EQ(3, local_state->GetInteger(prefs::kStabilityPageLoadCount));
EXPECT_EQ(0, local_state->GetInteger(prefs::kStabilityRendererCrashCount));
}
TEST_F(MetricsServiceTest, CrashRenderers) {
// This doesn't make sense to test in single process mode.
if (ProxyLauncher::in_process_renderer())
return;
OpenTabs();
{
// Limit the lifetime of various automation proxies used here. We must
// destroy them before calling QuitBrowser.
scoped_refptr<BrowserProxy> window = automation()->GetBrowserWindow(0);
ASSERT_TRUE(window.get());
// Kill the process for one of the tabs.
scoped_refptr<TabProxy> tab(window->GetTab(1));
ASSERT_TRUE(tab.get());
// We can get crash dumps on Windows always, Linux when breakpad is
// enabled, and all platforms for official Google Chrome builds.
#if defined(OS_WIN) || defined(USE_LINUX_BREAKPAD) || \
defined(GOOGLE_CHROME_BUILD)
expected_crashes_ = 1;
#endif
ASSERT_TRUE(tab->NavigateToURLAsync(GURL(chrome::kAboutCrashURL)));
}
// Give the browser a chance to notice the crashed tab.
base::PlatformThread::Sleep(TestTimeouts::action_timeout_ms());
QuitBrowser();
scoped_ptr<PrefService> local_state(GetLocalState());
local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
EXPECT_TRUE(local_state->GetBoolean(prefs::kStabilityExitedCleanly));
EXPECT_EQ(1, local_state->GetInteger(prefs::kStabilityLaunchCount));
EXPECT_EQ(4, local_state->GetInteger(prefs::kStabilityPageLoadCount));
EXPECT_EQ(1, local_state->GetInteger(prefs::kStabilityRendererCrashCount));
}
<commit_msg>Disabling Crash Renderers test, it fails always on offical trunk builders Review URL: http://codereview.chromium.org/6578031<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.
// Tests the MetricsService stat recording to make sure that the numbers are
// what we expect.
#include <string>
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/test/test_timeouts.h"
#include "base/threading/platform_thread.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/prefs/pref_service_mock_builder.h"
#include "chrome/browser/prefs/pref_value_store.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/json_pref_store.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
class MetricsServiceTest : public UITest {
public:
MetricsServiceTest() : UITest() {
// We need to show the window so web content type tabs load.
show_window_ = true;
}
// Open a few tabs of random content
void OpenTabs() {
scoped_refptr<BrowserProxy> window = automation()->GetBrowserWindow(0);
ASSERT_TRUE(window.get());
FilePath page1_path;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &page1_path));
page1_path = page1_path.AppendASCII("title2.html");
ASSERT_TRUE(window->AppendTab(net::FilePathToFileURL(page1_path)));
FilePath page2_path;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &page2_path));
page2_path = page2_path.AppendASCII("iframe.html");
ASSERT_TRUE(window->AppendTab(net::FilePathToFileURL(page2_path)));
}
// Get a PrefService whose contents correspond to the Local State file
// that was saved by the app as it closed. The caller takes ownership of the
// returned PrefService object.
PrefService* GetLocalState() {
FilePath path = user_data_dir().Append(chrome::kLocalStateFilename);
return PrefServiceMockBuilder().WithUserFilePrefs(path).Create();
}
};
TEST_F(MetricsServiceTest, CloseRenderersNormally) {
OpenTabs();
QuitBrowser();
scoped_ptr<PrefService> local_state(GetLocalState());
local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
EXPECT_TRUE(local_state->GetBoolean(prefs::kStabilityExitedCleanly));
EXPECT_EQ(1, local_state->GetInteger(prefs::kStabilityLaunchCount));
EXPECT_EQ(3, local_state->GetInteger(prefs::kStabilityPageLoadCount));
EXPECT_EQ(0, local_state->GetInteger(prefs::kStabilityRendererCrashCount));
}
TEST_F(MetricsServiceTest, DISABLED_CrashRenderers) {
// This doesn't make sense to test in single process mode.
if (ProxyLauncher::in_process_renderer())
return;
OpenTabs();
{
// Limit the lifetime of various automation proxies used here. We must
// destroy them before calling QuitBrowser.
scoped_refptr<BrowserProxy> window = automation()->GetBrowserWindow(0);
ASSERT_TRUE(window.get());
// Kill the process for one of the tabs.
scoped_refptr<TabProxy> tab(window->GetTab(1));
ASSERT_TRUE(tab.get());
// We can get crash dumps on Windows always, Linux when breakpad is
// enabled, and all platforms for official Google Chrome builds.
#if defined(OS_WIN) || defined(USE_LINUX_BREAKPAD) || \
defined(GOOGLE_CHROME_BUILD)
expected_crashes_ = 1;
#endif
ASSERT_TRUE(tab->NavigateToURLAsync(GURL(chrome::kAboutCrashURL)));
}
// Give the browser a chance to notice the crashed tab.
base::PlatformThread::Sleep(TestTimeouts::action_timeout_ms());
QuitBrowser();
scoped_ptr<PrefService> local_state(GetLocalState());
local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
EXPECT_TRUE(local_state->GetBoolean(prefs::kStabilityExitedCleanly));
EXPECT_EQ(1, local_state->GetInteger(prefs::kStabilityLaunchCount));
EXPECT_EQ(4, local_state->GetInteger(prefs::kStabilityPageLoadCount));
EXPECT_EQ(1, local_state->GetInteger(prefs::kStabilityRendererCrashCount));
}
<|endoftext|>
|
<commit_before>#include <gtest/gtest.h>
#include <stan/optimization/lbfgs_update.hpp>
TEST(OptimizationLbfgsUpdate, lbfgs_update_secant) {
typedef stan::optimization::LBFGSUpdate<> QNUpdateT;
typedef QNUpdateT::VectorT VectorT;
const unsigned int nDim = 10;
const unsigned int maxRank = 3;
VectorT yk(nDim), sk(nDim), sdir(nDim);
// Construct a set of BFGS update vectors and check that
// the secant equation H*yk = sk is always satisfied.
for (unsigned int rank = 1; rank <= maxRank; rank++) {
QNUpdateT bfgsUp(rank);
for (unsigned int i = 0; i < nDim; i++) {
sk.setZero(nDim);
yk.setZero(nDim);
sk[i] = 1;
yk[i] = 1;
bfgsUp.update(yk,sk,i==0);
// Because the constructed update vectors are all orthogonal the secant
// equation should be exactlty satisfied for all nDim updates.
for (unsigned int j = 0; j <= std::min(rank,i); j++) {
sk.setZero(nDim);
yk.setZero(nDim);
sk[i - j] = 1;
yk[i - j] = 1;
bfgsUp.search_direction(sdir,yk);
EXPECT_NEAR((sdir + sk).norm(),0.0,1e-10);
}
}
}
}
TEST(OptimizationLbfgsUpdate, constructor) {
typedef stan::optimization::LBFGSUpdate<> QNUpdateT;
typedef QNUpdateT::VectorT VectorT;
const unsigned int maxRank = 3;
for (unsigned int rank = 1; rank <= maxRank; rank++) {
QNUpdateT bfgsUp(rank);
}
}
namespace stan {
namespace optimization {
class mock_lbfgs_update : public LBFGSUpdate<> {
public:
mock_lbfgs_update(size_t L) : LBFGSUpdate(L) {};
size_t get_history_size() { return this->_buf.capacity(); }
};
}
}
TEST(OptimizationLbfgsUpdate, set_history_size) {
typedef stan::optimization::mock_lbfgs_update QNUpdateT;
typedef QNUpdateT::VectorT VectorT;
const unsigned int nDim = 10;
const unsigned int maxRank = 3;
VectorT yk(nDim), sk(nDim), sdir(nDim);
for (unsigned int rank = 1; rank <= maxRank; rank++) {
QNUpdateT bfgsUp(rank);
EXPECT_FLOAT_EQ(bfgsUp.get_history_size(), rank);
bfgsUp.set_history_size(rank+1);
EXPECT_FLOAT_EQ(bfgsUp.get_history_size(), rank+1);
}
}
TEST(OptimizationLbfgsUpdate, update) {
typedef stan::optimization::LBFGSUpdate<> QNUpdateT;
typedef QNUpdateT::VectorT VectorT;
const unsigned int nDim = 10;
const unsigned int maxRank = 3;
VectorT yk(nDim), sk(nDim), sdir(nDim);
for (unsigned int rank = 1; rank <= maxRank; rank++) {
QNUpdateT bfgsUp(rank);
for (unsigned int i = 0; i < nDim; i++) {
sk.setZero(nDim);
yk.setZero(nDim);
sk[i] = 1;
yk[i] = 1;
bfgsUp.update(yk,sk,i==0);
}
}
}
TEST(OptimizationLbfgsUpdate, search_direction) {
typedef stan::optimization::LBFGSUpdate<> QNUpdateT;
typedef QNUpdateT::VectorT VectorT;
const unsigned int nDim = 10;
const unsigned int maxRank = 3;
VectorT yk(nDim), sk(nDim), sdir(nDim);
for (unsigned int rank = 1; rank <= maxRank; rank++) {
QNUpdateT bfgsUp(rank);
for (unsigned int i = 0; i < nDim; i++) {
for (unsigned int j = 0; j <= std::min(rank,i); j++) {
sk.setZero(nDim);
yk.setZero(nDim);
sk[i - j] = 1;
yk[i - j] = 1;
bfgsUp.search_direction(sdir,yk);
}
}
}
}
<commit_msg>1514: fixed template issue<commit_after>#include <gtest/gtest.h>
#include <stan/optimization/lbfgs_update.hpp>
TEST(OptimizationLbfgsUpdate, lbfgs_update_secant) {
typedef stan::optimization::LBFGSUpdate<> QNUpdateT;
typedef QNUpdateT::VectorT VectorT;
const unsigned int nDim = 10;
const unsigned int maxRank = 3;
VectorT yk(nDim), sk(nDim), sdir(nDim);
// Construct a set of BFGS update vectors and check that
// the secant equation H*yk = sk is always satisfied.
for (unsigned int rank = 1; rank <= maxRank; rank++) {
QNUpdateT bfgsUp(rank);
for (unsigned int i = 0; i < nDim; i++) {
sk.setZero(nDim);
yk.setZero(nDim);
sk[i] = 1;
yk[i] = 1;
bfgsUp.update(yk,sk,i==0);
// Because the constructed update vectors are all orthogonal the secant
// equation should be exactlty satisfied for all nDim updates.
for (unsigned int j = 0; j <= std::min(rank,i); j++) {
sk.setZero(nDim);
yk.setZero(nDim);
sk[i - j] = 1;
yk[i - j] = 1;
bfgsUp.search_direction(sdir,yk);
EXPECT_NEAR((sdir + sk).norm(),0.0,1e-10);
}
}
}
}
TEST(OptimizationLbfgsUpdate, constructor) {
typedef stan::optimization::LBFGSUpdate<> QNUpdateT;
typedef QNUpdateT::VectorT VectorT;
const unsigned int maxRank = 3;
for (unsigned int rank = 1; rank <= maxRank; rank++) {
QNUpdateT bfgsUp(rank);
}
}
namespace stan {
namespace optimization {
class mock_lbfgs_update : public LBFGSUpdate<> {
public:
mock_lbfgs_update(size_t L) : LBFGSUpdate<>(L) {};
size_t get_history_size() { return this->_buf.capacity(); }
};
}
}
TEST(OptimizationLbfgsUpdate, set_history_size) {
typedef stan::optimization::mock_lbfgs_update QNUpdateT;
typedef QNUpdateT::VectorT VectorT;
const unsigned int nDim = 10;
const unsigned int maxRank = 3;
VectorT yk(nDim), sk(nDim), sdir(nDim);
for (unsigned int rank = 1; rank <= maxRank; rank++) {
QNUpdateT bfgsUp(rank);
EXPECT_FLOAT_EQ(bfgsUp.get_history_size(), rank);
bfgsUp.set_history_size(rank+1);
EXPECT_FLOAT_EQ(bfgsUp.get_history_size(), rank+1);
}
}
TEST(OptimizationLbfgsUpdate, update) {
typedef stan::optimization::LBFGSUpdate<> QNUpdateT;
typedef QNUpdateT::VectorT VectorT;
const unsigned int nDim = 10;
const unsigned int maxRank = 3;
VectorT yk(nDim), sk(nDim), sdir(nDim);
for (unsigned int rank = 1; rank <= maxRank; rank++) {
QNUpdateT bfgsUp(rank);
for (unsigned int i = 0; i < nDim; i++) {
sk.setZero(nDim);
yk.setZero(nDim);
sk[i] = 1;
yk[i] = 1;
bfgsUp.update(yk,sk,i==0);
}
}
}
TEST(OptimizationLbfgsUpdate, search_direction) {
typedef stan::optimization::LBFGSUpdate<> QNUpdateT;
typedef QNUpdateT::VectorT VectorT;
const unsigned int nDim = 10;
const unsigned int maxRank = 3;
VectorT yk(nDim), sk(nDim), sdir(nDim);
for (unsigned int rank = 1; rank <= maxRank; rank++) {
QNUpdateT bfgsUp(rank);
for (unsigned int i = 0; i < nDim; i++) {
for (unsigned int j = 0; j <= std::min(rank,i); j++) {
sk.setZero(nDim);
yk.setZero(nDim);
sk[i - j] = 1;
yk[i - j] = 1;
bfgsUp.search_direction(sdir,yk);
}
}
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 - Mozy, Inc.
#include <boost/bind.hpp>
#include "mordor/xml/dom_parser.h"
#include "mordor/test/test.h"
#include "mordor/string.h"
using namespace Mordor;
static void callback(std::string &value, int &called,
const std::string &string)
{
value.append(string);
++called;
}
static void reference(std::string &value, int &called,
const std::string &string)
{
// When processing inner text a special callback is invoked for xml
// references
if (string == "&")
value.append("&");
else if (string == ">")
value.append(">");
else if (string == "<")
value.append("<");
else if (string == """)
value.append("\"");
else if (string == "'")
value.append("\'");
else
// Real code should also look for character references like &
MORDOR_NOTREACHED();
++called;
}
static void handlereferencecallback(std::string &value, int &called,
const std::string &string)
{
// A full Attribute value is passed, which may contain xml references
std::string rawstring(string);
replace(rawstring, "&", "&");
replace(rawstring, ">", ">" );
replace(rawstring, "<", "<" );
replace(rawstring, """, "\"");
replace(rawstring, "'", "\'");
// Should also look for character references like &
value.append(rawstring);
++called;
}
static void emptyTag(int &called)
{
++called;
}
MORDOR_UNITTEST(XMLParser, basic)
{
std::string start, end;
int calledStart = 0, calledEnd = 0;
CallbackXMLParserEventHandler handler(
boost::bind(&callback, boost::ref(start), boost::ref(calledStart), _1),
boost::bind(&callback, boost::ref(end), boost::ref(calledEnd), _1));
XMLParser parser(handler);
parser.run("<body></body>");
MORDOR_ASSERT(parser.final());
MORDOR_ASSERT(!parser.error());
MORDOR_TEST_ASSERT_EQUAL(calledStart, 1);
MORDOR_TEST_ASSERT_EQUAL(start, "body");
MORDOR_TEST_ASSERT_EQUAL(calledEnd, 1);
MORDOR_TEST_ASSERT_EQUAL(end, "body");
}
MORDOR_UNITTEST(XMLParser, emptyTag)
{
std::string tag;
int calledStart = 0, calledEmpty = 0;
CallbackXMLParserEventHandler handler(
boost::bind(&callback, boost::ref(tag), boost::ref(calledStart), _1),
NULL,
boost::bind(&emptyTag, boost::ref(calledEmpty)));
XMLParser parser(handler);
parser.run("<empty />");
MORDOR_ASSERT(parser.final());
MORDOR_ASSERT(!parser.error());
MORDOR_TEST_ASSERT_EQUAL(calledStart, 1);
MORDOR_TEST_ASSERT_EQUAL(tag, "empty");
MORDOR_TEST_ASSERT_EQUAL(calledEmpty, 1);
}
MORDOR_UNITTEST(XMLParser, references)
{
std::string text;
int called = 0;
CallbackXMLParserEventHandler handler(NULL,
NULL,
NULL,
NULL,
NULL,
boost::bind(&callback, boost::ref(text), boost::ref(called), _1),
boost::bind(&reference, boost::ref(text), boost::ref(called), _1));
XMLParser parser(handler);
parser.run("<root>sometext&somemoretext</root>");
MORDOR_ASSERT(parser.final());
MORDOR_ASSERT(!parser.error());
MORDOR_TEST_ASSERT_EQUAL(called, 3);
MORDOR_TEST_ASSERT_EQUAL(text, "sometext&somemoretext");
text.clear();
called = 0;
parser.run("<path>/Users/test1/Public/<C:\\abc\\n'&.txt1</path>");
MORDOR_ASSERT(parser.final());
MORDOR_ASSERT(!parser.error());
MORDOR_TEST_ASSERT_EQUAL(called, 6);
MORDOR_TEST_ASSERT_EQUAL(text, "/Users/test1/Public/<C:\\abc\\n'&.txt1");
text.clear();
called = 0;
parser.run("<p>"&</p>");
MORDOR_ASSERT(parser.final());
MORDOR_ASSERT(!parser.error());
MORDOR_TEST_ASSERT_EQUAL(called, 2);
MORDOR_TEST_ASSERT_EQUAL(text, "\"&");
}
MORDOR_UNITTEST(XMLParser, attribute)
{
std::string key, value;
int calledKey = 0, calledVal = 0;
CallbackXMLParserEventHandler handler(
NULL,
NULL,
NULL,
boost::bind(&callback, boost::ref(key), boost::ref(calledKey), _1),
boost::bind(&handlereferencecallback, boost::ref(value), boost::ref(calledVal), _1));
XMLParser parser(handler);
parser.run("<mykey query=\"mymail\"/>");
MORDOR_ASSERT(parser.final());
MORDOR_ASSERT(!parser.error());
MORDOR_TEST_ASSERT_EQUAL(calledKey, 1);
MORDOR_TEST_ASSERT_EQUAL(key, "query");
MORDOR_TEST_ASSERT_EQUAL(calledVal, 1);
MORDOR_TEST_ASSERT_EQUAL(value, "mymail");
key.clear(); value.clear();
calledKey = 0; calledVal = 0;
parser.run("<mykey qry=\""mymail'\"/>");
MORDOR_ASSERT(parser.final());
MORDOR_ASSERT(!parser.error());
MORDOR_TEST_ASSERT_EQUAL(calledKey, 1);
MORDOR_TEST_ASSERT_EQUAL(key, "qry");
MORDOR_TEST_ASSERT_EQUAL(calledVal, 1);
MORDOR_TEST_ASSERT_EQUAL(value, "\"mymail\'");
key.clear(); value.clear();
calledKey = 0; calledVal = 0;
parser.run("<mykey a=\'"\"\' b=\"foo's\"/>");
MORDOR_ASSERT(parser.final());
MORDOR_ASSERT(!parser.error());
MORDOR_TEST_ASSERT_EQUAL(calledKey, 2);
MORDOR_TEST_ASSERT_EQUAL(key, "ab"); // The test callback concatenates them together
MORDOR_TEST_ASSERT_EQUAL(calledVal, 2);
MORDOR_TEST_ASSERT_EQUAL(value, "\"\"foo's");
// A more complex real life XML
key.clear(); value.clear();
parser.run("<folder id=\"3\" i4ms=\"692002\" ms=\"456229\" name=\"Trash\" n=\"38\" l=\"1\"><search id=\"384010\" sortBy=\"dateDesc\" query=\"(to:(foo) tag:"mymail"\" name=\"inbox my mail\" l=\"3\" /></folder>");
MORDOR_ASSERT(parser.final());
MORDOR_ASSERT(!parser.error());
MORDOR_ASSERT(!key.empty());
MORDOR_ASSERT(!value.empty());
}
const char * xml_typical =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\t"
"<NamedObject type='file' deleted='false'>\n"
" <id>/sync/1/path/x.y.txt</id>"
" <versionId>1310496040</versionId>"
"\t<Version deleted='false'>"
"\t\t<versionId>1310496040</versionId>"
"<size>8</size>"
"<stime>Tue, 12 Jul 2011 18:40:40 GMT</stime>\r\n"
"<fileAttributes archive='true' not_content_indexed='true' />"
"</Version>"
"</NamedObject>";
MORDOR_UNITTEST(XMLParser, parsedocument)
{
// Confirm that a full xml with random white space and
// typical elements can be parsed.
XMLParserEventHandler defaulthandler;
XMLParser parser(defaulthandler);
parser.run(xml_typical);
MORDOR_ASSERT(parser.final());
MORDOR_ASSERT(!parser.error());
}
MORDOR_UNITTEST(XMLParser, domParser)
{
DOM::XMLParser parser;
DOM::Document::ptr doc = parser.loadDocument(
"<?xml version='1.0' encoding='UTF-8'?>\n"
"<root><children>\n"
"<child> this is child1\n</child>\n"
"<child>this is child2</child>\n"
"<empty id=\"1\" attr1=\"one\" attr2='two' />\n"
"<tag>tag text<subtag> "some & some" </subtag></tag>\n"
"</children></root>");
DOM::Element *root = (DOM::Element *)doc->getElementsByTagName("root")[0];
MORDOR_TEST_ASSERT_EQUAL("root", root->nodeName());
DOM::NodeList l = root->getElementsByTagName("child");
MORDOR_TEST_ASSERT_EQUAL(2u, l.size());
MORDOR_TEST_ASSERT_EQUAL("this is child1", l[0]->text());
MORDOR_TEST_ASSERT_EQUAL("this is child1", l[0]->firstChild()->nodeValue());
MORDOR_TEST_ASSERT_EQUAL("this is child2", l[1]->text());
DOM::Node *children = root->firstChild();
MORDOR_TEST_ASSERT_EQUAL(DOM::ELEMENT, children->nodeType());
MORDOR_TEST_ASSERT_EQUAL("children", children->nodeName());
MORDOR_TEST_ASSERT_EQUAL(4u, children->childNodes().size());
DOM::Element *empty = (DOM::Element *)children->childNodes()[2];
MORDOR_TEST_ASSERT_EQUAL("empty", empty->nodeName());
MORDOR_TEST_ASSERT_EQUAL(DOM::ELEMENT, empty->nodeType());
MORDOR_TEST_ASSERT_EQUAL("", empty->text());
MORDOR_TEST_ASSERT_EQUAL("1", empty->id);
MORDOR_TEST_ASSERT_EQUAL("one", empty->attribute("attr1"));
MORDOR_TEST_ASSERT_EQUAL("two", empty->attribute("attr2"));
MORDOR_TEST_ASSERT_EQUAL(true, empty->hasAttribute("attr2"));
MORDOR_TEST_ASSERT_EQUAL(false, empty->hasAttribute("attr3"));
DOM::Element *node = doc->getElementById("1");
MORDOR_TEST_ASSERT_EQUAL(empty, node);
MORDOR_TEST_ASSERT_EQUAL((DOM::Element *)NULL, doc->getElementById("haha"));
DOM::Node *tag = children->childNodes()[3];
MORDOR_TEST_ASSERT_EQUAL(DOM::ELEMENT, tag->nodeType());
MORDOR_TEST_ASSERT_EQUAL("tag", tag->nodeName());
MORDOR_TEST_ASSERT_EQUAL("tag text", tag->text());
MORDOR_TEST_ASSERT_EQUAL("tag text", tag->firstChild()->nodeValue());
DOM::NodeList subtags = ((DOM::Element *)tag)->getElementsByTagName("subtag");
MORDOR_TEST_ASSERT_EQUAL(1u, subtags.size());
MORDOR_TEST_ASSERT_EQUAL("\"some & some\"", subtags[0]->text());
}
MORDOR_UNITTEST(XMLParser, domParserInvalid)
{
DOM::XMLParser parser;
MORDOR_TEST_ASSERT_EXCEPTION(parser.loadDocument(
"<?xml version='1.0' encoding='UTF-8'?>\n"
"<root<children>\"somesome\n"),
std::invalid_argument);
}
#if 0
// Disabled until comment support fixed
MORDOR_UNITTEST(XMLParser, parsecomment)
{
XMLParserEventHandler defaulthandler;
XMLParser parser(defaulthandler);
parser.run("<!-- a comment -->");
MORDOR_ASSERT(parser.final());
MORDOR_ASSERT(!parser.error());
parser.run("foo <!-- bar --> baz <!-- qox --> blurb");
MORDOR_ASSERT(parser.final());
MORDOR_ASSERT(!parser.error());
parser.run("<![CDATA[ <!-- OMGWTFBBQ ]]>Shoulda used a <!-- real parser -->");
MORDOR_ASSERT(parser.final());
MORDOR_ASSERT(!parser.error());
}
#endif
<commit_msg>use double quote in ascii in comments<commit_after>// Copyright (c) 2010 - Mozy, Inc.
#include <boost/bind.hpp>
#include "mordor/xml/dom_parser.h"
#include "mordor/test/test.h"
#include "mordor/string.h"
using namespace Mordor;
static void callback(std::string &value, int &called,
const std::string &string)
{
value.append(string);
++called;
}
static void reference(std::string &value, int &called,
const std::string &string)
{
// When processing inner text a special callback is invoked for xml
// references
if (string == "&")
value.append("&");
else if (string == ">")
value.append(">");
else if (string == "<")
value.append("<");
else if (string == """)
value.append("\"");
else if (string == "'")
value.append("\'");
else
// Real code should also look for character references like "&"
MORDOR_NOTREACHED();
++called;
}
static void handlereferencecallback(std::string &value, int &called,
const std::string &string)
{
// A full Attribute value is passed, which may contain xml references
std::string rawstring(string);
replace(rawstring, "&", "&");
replace(rawstring, ">", ">" );
replace(rawstring, "<", "<" );
replace(rawstring, """, "\"");
replace(rawstring, "'", "\'");
// Should also look for character references like "&"
value.append(rawstring);
++called;
}
static void emptyTag(int &called)
{
++called;
}
MORDOR_UNITTEST(XMLParser, basic)
{
std::string start, end;
int calledStart = 0, calledEnd = 0;
CallbackXMLParserEventHandler handler(
boost::bind(&callback, boost::ref(start), boost::ref(calledStart), _1),
boost::bind(&callback, boost::ref(end), boost::ref(calledEnd), _1));
XMLParser parser(handler);
parser.run("<body></body>");
MORDOR_ASSERT(parser.final());
MORDOR_ASSERT(!parser.error());
MORDOR_TEST_ASSERT_EQUAL(calledStart, 1);
MORDOR_TEST_ASSERT_EQUAL(start, "body");
MORDOR_TEST_ASSERT_EQUAL(calledEnd, 1);
MORDOR_TEST_ASSERT_EQUAL(end, "body");
}
MORDOR_UNITTEST(XMLParser, emptyTag)
{
std::string tag;
int calledStart = 0, calledEmpty = 0;
CallbackXMLParserEventHandler handler(
boost::bind(&callback, boost::ref(tag), boost::ref(calledStart), _1),
NULL,
boost::bind(&emptyTag, boost::ref(calledEmpty)));
XMLParser parser(handler);
parser.run("<empty />");
MORDOR_ASSERT(parser.final());
MORDOR_ASSERT(!parser.error());
MORDOR_TEST_ASSERT_EQUAL(calledStart, 1);
MORDOR_TEST_ASSERT_EQUAL(tag, "empty");
MORDOR_TEST_ASSERT_EQUAL(calledEmpty, 1);
}
MORDOR_UNITTEST(XMLParser, references)
{
std::string text;
int called = 0;
CallbackXMLParserEventHandler handler(NULL,
NULL,
NULL,
NULL,
NULL,
boost::bind(&callback, boost::ref(text), boost::ref(called), _1),
boost::bind(&reference, boost::ref(text), boost::ref(called), _1));
XMLParser parser(handler);
parser.run("<root>sometext&somemoretext</root>");
MORDOR_ASSERT(parser.final());
MORDOR_ASSERT(!parser.error());
MORDOR_TEST_ASSERT_EQUAL(called, 3);
MORDOR_TEST_ASSERT_EQUAL(text, "sometext&somemoretext");
text.clear();
called = 0;
parser.run("<path>/Users/test1/Public/<C:\\abc\\n'&.txt1</path>");
MORDOR_ASSERT(parser.final());
MORDOR_ASSERT(!parser.error());
MORDOR_TEST_ASSERT_EQUAL(called, 6);
MORDOR_TEST_ASSERT_EQUAL(text, "/Users/test1/Public/<C:\\abc\\n'&.txt1");
text.clear();
called = 0;
parser.run("<p>"&</p>");
MORDOR_ASSERT(parser.final());
MORDOR_ASSERT(!parser.error());
MORDOR_TEST_ASSERT_EQUAL(called, 2);
MORDOR_TEST_ASSERT_EQUAL(text, "\"&");
}
MORDOR_UNITTEST(XMLParser, attribute)
{
std::string key, value;
int calledKey = 0, calledVal = 0;
CallbackXMLParserEventHandler handler(
NULL,
NULL,
NULL,
boost::bind(&callback, boost::ref(key), boost::ref(calledKey), _1),
boost::bind(&handlereferencecallback, boost::ref(value), boost::ref(calledVal), _1));
XMLParser parser(handler);
parser.run("<mykey query=\"mymail\"/>");
MORDOR_ASSERT(parser.final());
MORDOR_ASSERT(!parser.error());
MORDOR_TEST_ASSERT_EQUAL(calledKey, 1);
MORDOR_TEST_ASSERT_EQUAL(key, "query");
MORDOR_TEST_ASSERT_EQUAL(calledVal, 1);
MORDOR_TEST_ASSERT_EQUAL(value, "mymail");
key.clear(); value.clear();
calledKey = 0; calledVal = 0;
parser.run("<mykey qry=\""mymail'\"/>");
MORDOR_ASSERT(parser.final());
MORDOR_ASSERT(!parser.error());
MORDOR_TEST_ASSERT_EQUAL(calledKey, 1);
MORDOR_TEST_ASSERT_EQUAL(key, "qry");
MORDOR_TEST_ASSERT_EQUAL(calledVal, 1);
MORDOR_TEST_ASSERT_EQUAL(value, "\"mymail\'");
key.clear(); value.clear();
calledKey = 0; calledVal = 0;
parser.run("<mykey a=\'"\"\' b=\"foo's\"/>");
MORDOR_ASSERT(parser.final());
MORDOR_ASSERT(!parser.error());
MORDOR_TEST_ASSERT_EQUAL(calledKey, 2);
MORDOR_TEST_ASSERT_EQUAL(key, "ab"); // The test callback concatenates them together
MORDOR_TEST_ASSERT_EQUAL(calledVal, 2);
MORDOR_TEST_ASSERT_EQUAL(value, "\"\"foo's");
// A more complex real life XML
key.clear(); value.clear();
parser.run("<folder id=\"3\" i4ms=\"692002\" ms=\"456229\" name=\"Trash\" n=\"38\" l=\"1\"><search id=\"384010\" sortBy=\"dateDesc\" query=\"(to:(foo) tag:"mymail"\" name=\"inbox my mail\" l=\"3\" /></folder>");
MORDOR_ASSERT(parser.final());
MORDOR_ASSERT(!parser.error());
MORDOR_ASSERT(!key.empty());
MORDOR_ASSERT(!value.empty());
}
const char * xml_typical =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\t"
"<NamedObject type='file' deleted='false'>\n"
" <id>/sync/1/path/x.y.txt</id>"
" <versionId>1310496040</versionId>"
"\t<Version deleted='false'>"
"\t\t<versionId>1310496040</versionId>"
"<size>8</size>"
"<stime>Tue, 12 Jul 2011 18:40:40 GMT</stime>\r\n"
"<fileAttributes archive='true' not_content_indexed='true' />"
"</Version>"
"</NamedObject>";
MORDOR_UNITTEST(XMLParser, parsedocument)
{
// Confirm that a full xml with random white space and
// typical elements can be parsed.
XMLParserEventHandler defaulthandler;
XMLParser parser(defaulthandler);
parser.run(xml_typical);
MORDOR_ASSERT(parser.final());
MORDOR_ASSERT(!parser.error());
}
MORDOR_UNITTEST(XMLParser, domParser)
{
DOM::XMLParser parser;
DOM::Document::ptr doc = parser.loadDocument(
"<?xml version='1.0' encoding='UTF-8'?>\n"
"<root><children>\n"
"<child> this is child1\n</child>\n"
"<child>this is child2</child>\n"
"<empty id=\"1\" attr1=\"one\" attr2='two' />\n"
"<tag>tag text<subtag> "some & some" </subtag></tag>\n"
"</children></root>");
DOM::Element *root = (DOM::Element *)doc->getElementsByTagName("root")[0];
MORDOR_TEST_ASSERT_EQUAL("root", root->nodeName());
DOM::NodeList l = root->getElementsByTagName("child");
MORDOR_TEST_ASSERT_EQUAL(2u, l.size());
MORDOR_TEST_ASSERT_EQUAL("this is child1", l[0]->text());
MORDOR_TEST_ASSERT_EQUAL("this is child1", l[0]->firstChild()->nodeValue());
MORDOR_TEST_ASSERT_EQUAL("this is child2", l[1]->text());
DOM::Node *children = root->firstChild();
MORDOR_TEST_ASSERT_EQUAL(DOM::ELEMENT, children->nodeType());
MORDOR_TEST_ASSERT_EQUAL("children", children->nodeName());
MORDOR_TEST_ASSERT_EQUAL(4u, children->childNodes().size());
DOM::Element *empty = (DOM::Element *)children->childNodes()[2];
MORDOR_TEST_ASSERT_EQUAL("empty", empty->nodeName());
MORDOR_TEST_ASSERT_EQUAL(DOM::ELEMENT, empty->nodeType());
MORDOR_TEST_ASSERT_EQUAL("", empty->text());
MORDOR_TEST_ASSERT_EQUAL("1", empty->id);
MORDOR_TEST_ASSERT_EQUAL("one", empty->attribute("attr1"));
MORDOR_TEST_ASSERT_EQUAL("two", empty->attribute("attr2"));
MORDOR_TEST_ASSERT_EQUAL(true, empty->hasAttribute("attr2"));
MORDOR_TEST_ASSERT_EQUAL(false, empty->hasAttribute("attr3"));
DOM::Element *node = doc->getElementById("1");
MORDOR_TEST_ASSERT_EQUAL(empty, node);
MORDOR_TEST_ASSERT_EQUAL((DOM::Element *)NULL, doc->getElementById("haha"));
DOM::Node *tag = children->childNodes()[3];
MORDOR_TEST_ASSERT_EQUAL(DOM::ELEMENT, tag->nodeType());
MORDOR_TEST_ASSERT_EQUAL("tag", tag->nodeName());
MORDOR_TEST_ASSERT_EQUAL("tag text", tag->text());
MORDOR_TEST_ASSERT_EQUAL("tag text", tag->firstChild()->nodeValue());
DOM::NodeList subtags = ((DOM::Element *)tag)->getElementsByTagName("subtag");
MORDOR_TEST_ASSERT_EQUAL(1u, subtags.size());
MORDOR_TEST_ASSERT_EQUAL("\"some & some\"", subtags[0]->text());
}
MORDOR_UNITTEST(XMLParser, domParserInvalid)
{
DOM::XMLParser parser;
MORDOR_TEST_ASSERT_EXCEPTION(parser.loadDocument(
"<?xml version='1.0' encoding='UTF-8'?>\n"
"<root<children>\"somesome\n"),
std::invalid_argument);
}
#if 0
// Disabled until comment support fixed
MORDOR_UNITTEST(XMLParser, parsecomment)
{
XMLParserEventHandler defaulthandler;
XMLParser parser(defaulthandler);
parser.run("<!-- a comment -->");
MORDOR_ASSERT(parser.final());
MORDOR_ASSERT(!parser.error());
parser.run("foo <!-- bar --> baz <!-- qox --> blurb");
MORDOR_ASSERT(parser.final());
MORDOR_ASSERT(!parser.error());
parser.run("<![CDATA[ <!-- OMGWTFBBQ ]]>Shoulda used a <!-- real parser -->");
MORDOR_ASSERT(parser.final());
MORDOR_ASSERT(!parser.error());
}
#endif
<|endoftext|>
|
<commit_before>// $Id$
// vim:tabstop=2
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
***********************************************************************/
#include <cassert>
#include <algorithm>
#include <sstream>
#include <string>
#include "memory.h"
#include "FactorCollection.h"
#include "Phrase.h"
#include "StaticData.h" // GetMaxNumFactors
using namespace std;
namespace Moses
{
Phrase::Phrase(const Phrase ©)
:m_direction(copy.m_direction)
,m_words(copy.m_words)
{
}
Phrase& Phrase::operator=(const Phrase& x)
{
if(this!=&x) {
m_direction=x.m_direction;
m_words = x.m_words;
}
return *this;
}
Phrase::Phrase(FactorDirection direction, size_t reserveSize)
: m_direction(direction)
{
m_words.reserve(reserveSize);
}
Phrase::Phrase(FactorDirection direction, const vector< const Word* > &mergeWords)
:m_direction(direction)
{
m_words.reserve(mergeWords.size());
for (size_t currPos = 0 ; currPos < mergeWords.size() ; currPos++) {
AddWord(*mergeWords[currPos]);
}
}
Phrase::~Phrase()
{
}
void Phrase::MergeFactors(const Phrase ©)
{
assert(GetSize() == copy.GetSize());
size_t size = GetSize();
const size_t maxNumFactors = StaticData::Instance().GetMaxNumFactors(this->GetDirection());
for (size_t currPos = 0 ; currPos < size ; currPos++) {
for (unsigned int currFactor = 0 ; currFactor < maxNumFactors ; currFactor++) {
FactorType factorType = static_cast<FactorType>(currFactor);
const Factor *factor = copy.GetFactor(currPos, factorType);
if (factor != NULL)
SetFactor(currPos, factorType, factor);
}
}
}
void Phrase::MergeFactors(const Phrase ©, FactorType factorType)
{
assert(GetSize() == copy.GetSize());
for (size_t currPos = 0 ; currPos < GetSize() ; currPos++)
SetFactor(currPos, factorType, copy.GetFactor(currPos, factorType));
}
void Phrase::MergeFactors(const Phrase ©, const std::vector<FactorType>& factorVec)
{
assert(GetSize() == copy.GetSize());
for (size_t currPos = 0 ; currPos < GetSize() ; currPos++)
for (std::vector<FactorType>::const_iterator i = factorVec.begin();
i != factorVec.end(); ++i) {
SetFactor(currPos, *i, copy.GetFactor(currPos, *i));
}
}
Phrase Phrase::GetSubString(const WordsRange &wordsRange) const
{
Phrase retPhrase(m_direction, wordsRange.GetNumWordsCovered());
for (size_t currPos = wordsRange.GetStartPos() ; currPos <= wordsRange.GetEndPos() ; currPos++) {
Word &word = retPhrase.AddWord();
word = GetWord(currPos);
}
return retPhrase;
}
std::string Phrase::GetStringRep(const vector<FactorType> factorsToPrint) const
{
stringstream strme;
for (size_t pos = 0 ; pos < GetSize() ; pos++) {
strme << GetWord(pos).GetString(factorsToPrint, (pos != GetSize()-1));
}
return strme.str();
}
Word &Phrase::AddWord()
{
m_words.push_back(Word());
return m_words.back();
}
void Phrase::Append(const Phrase &endPhrase)
{
for (size_t i = 0; i < endPhrase.GetSize(); i++) {
AddWord(endPhrase.GetWord(i));
}
}
void Phrase::PrependWord(const Word &newWord)
{
AddWord();
// shift
for (size_t pos = GetSize() - 1; pos >= 1; --pos) {
const Word &word = m_words[pos - 1];
m_words[pos] = word;
}
m_words[0] = newWord;
}
vector< vector<string> > Phrase::Parse(const std::string &phraseString, const std::vector<FactorType> &factorOrder, const std::string& factorDelimiter)
{
bool isMultiCharDelimiter = factorDelimiter.size() > 1;
// parse
vector< vector<string> > phraseVector;
vector<string> annotatedWordVector = Tokenize(phraseString);
// KOMMA|none ART|Def.Z NN|Neut.NotGen.Sg VVFIN|none
// to
// "KOMMA|none" "ART|Def.Z" "NN|Neut.NotGen.Sg" "VVFIN|none"
for (size_t phrasePos = 0 ; phrasePos < annotatedWordVector.size() ; phrasePos++) {
string &annotatedWord = annotatedWordVector[phrasePos];
vector<string> factorStrVector;
if (isMultiCharDelimiter) {
factorStrVector = TokenizeMultiCharSeparator(annotatedWord, factorDelimiter);
} else {
factorStrVector = Tokenize(annotatedWord, factorDelimiter);
}
// KOMMA|none
// to
// "KOMMA" "none"
if (factorStrVector.size() != factorOrder.size()) {
TRACE_ERR( "[ERROR] Malformed input at " << /*StaticData::Instance().GetCurrentInputPosition() <<*/ std::endl
<< " Expected input to have words composed of " << factorOrder.size() << " factor(s) (form FAC1|FAC2|...)" << std::endl
<< " but instead received input with " << factorStrVector.size() << " factor(s).\n");
abort();
}
phraseVector.push_back(factorStrVector);
}
return phraseVector;
}
void Phrase::CreateFromString(const std::vector<FactorType> &factorOrder
, const vector< vector<string> > &phraseVector)
{
FactorCollection &factorCollection = FactorCollection::Instance();
m_words.reserve(phraseVector.size());
for (size_t phrasePos = 0 ; phrasePos < phraseVector.size() ; phrasePos++) {
// add word this phrase
Word &word = AddWord();
for (size_t currFactorIndex= 0 ; currFactorIndex < factorOrder.size() ; currFactorIndex++) {
FactorType factorType = factorOrder[currFactorIndex];
const string &factorStr = phraseVector[phrasePos][currFactorIndex];
const Factor *factor = factorCollection.AddFactor(m_direction, factorType, factorStr);
word[factorType] = factor;
}
}
}
void Phrase::CreateFromString(const std::vector<FactorType> &factorOrder
, const string &phraseString
, const string &factorDelimiter)
{
vector< vector<string> > phraseVector = Parse(phraseString, factorOrder, factorDelimiter);
CreateFromString(factorOrder, phraseVector);
}
void Phrase::CreateFromStringNewFormat(FactorDirection direction
, const std::vector<FactorType> &factorOrder
, const std::string &phraseString
, const std::string & /*factorDelimiter */
, Word &lhs)
{
// parse
vector<string> annotatedWordVector;
Tokenize(annotatedWordVector, phraseString);
// KOMMA|none ART|Def.Z NN|Neut.NotGen.Sg VVFIN|none
// to
// "KOMMA|none" "ART|Def.Z" "NN|Neut.NotGen.Sg" "VVFIN|none"
m_words.reserve(annotatedWordVector.size()-1);
for (size_t phrasePos = 0 ; phrasePos < annotatedWordVector.size() - 1 ; phrasePos++) {
string &annotatedWord = annotatedWordVector[phrasePos];
bool isNonTerminal;
if (annotatedWord.substr(0, 1) == "[" && annotatedWord.substr(annotatedWord.size()-1, 1) == "]") {
// non-term
isNonTerminal = true;
size_t nextPos = annotatedWord.find("[", 1);
assert(nextPos != string::npos);
if (direction == Input)
annotatedWord = annotatedWord.substr(1, nextPos - 2);
else
annotatedWord = annotatedWord.substr(nextPos + 1, annotatedWord.size() - nextPos - 2);
} else {
isNonTerminal = false;
}
Word &word = AddWord();
word.CreateFromString(direction, factorOrder, annotatedWord, isNonTerminal);
}
// lhs
string &annotatedWord = annotatedWordVector.back();
assert(annotatedWord.substr(0, 1) == "[" && annotatedWord.substr(annotatedWord.size()-1, 1) == "]");
annotatedWord = annotatedWord.substr(1, annotatedWord.size() - 2);
lhs.CreateFromString(direction, factorOrder, annotatedWord, true);
assert(lhs.IsNonTerminal());
}
int Phrase::Compare(const Phrase &other) const
{
#ifdef min
#undef min
#endif
size_t thisSize = GetSize()
,compareSize = other.GetSize();
if (thisSize != compareSize) {
return (thisSize < compareSize) ? -1 : 1;
}
for (size_t pos = 0 ; pos < thisSize ; pos++) {
const Word &thisWord = GetWord(pos)
,&otherWord = other.GetWord(pos);
int ret = Word::Compare(thisWord, otherWord);
if (ret != 0)
return ret;
}
return 0;
}
bool Phrase::Contains(const vector< vector<string> > &subPhraseVector
, const vector<FactorType> &inputFactor) const
{
const size_t subSize = subPhraseVector.size()
,thisSize= GetSize();
if (subSize > thisSize)
return false;
// try to match word-for-word
for (size_t currStartPos = 0 ; currStartPos < (thisSize - subSize + 1) ; currStartPos++) {
bool match = true;
for (size_t currFactorIndex = 0 ; currFactorIndex < inputFactor.size() ; currFactorIndex++) {
FactorType factorType = inputFactor[currFactorIndex];
for (size_t currSubPos = 0 ; currSubPos < subSize ; currSubPos++) {
size_t currThisPos = currSubPos + currStartPos;
const string &subStr = subPhraseVector[currSubPos][currFactorIndex]
,&thisStr = GetFactor(currThisPos, factorType)->GetString();
if (subStr != thisStr) {
match = false;
break;
}
}
if (!match)
break;
}
if (match)
return true;
}
return false;
}
bool Phrase::IsCompatible(const Phrase &inputPhrase) const
{
if (inputPhrase.GetSize() != GetSize()) {
return false;
}
const size_t size = GetSize();
const size_t maxNumFactors = StaticData::Instance().GetMaxNumFactors(this->GetDirection());
for (size_t currPos = 0 ; currPos < size ; currPos++) {
for (unsigned int currFactor = 0 ; currFactor < maxNumFactors ; currFactor++) {
FactorType factorType = static_cast<FactorType>(currFactor);
const Factor *thisFactor = GetFactor(currPos, factorType)
,*inputFactor = inputPhrase.GetFactor(currPos, factorType);
if (thisFactor != NULL && inputFactor != NULL && thisFactor != inputFactor)
return false;
}
}
return true;
}
bool Phrase::IsCompatible(const Phrase &inputPhrase, FactorType factorType) const
{
if (inputPhrase.GetSize() != GetSize()) {
return false;
}
for (size_t currPos = 0 ; currPos < GetSize() ; currPos++) {
if (GetFactor(currPos, factorType) != inputPhrase.GetFactor(currPos, factorType))
return false;
}
return true;
}
bool Phrase::IsCompatible(const Phrase &inputPhrase, const std::vector<FactorType>& factorVec) const
{
if (inputPhrase.GetSize() != GetSize()) {
return false;
}
for (size_t currPos = 0 ; currPos < GetSize() ; currPos++) {
for (std::vector<FactorType>::const_iterator i = factorVec.begin();
i != factorVec.end(); ++i) {
if (GetFactor(currPos, *i) != inputPhrase.GetFactor(currPos, *i))
return false;
}
}
return true;
}
size_t Phrase::GetNumTerminals() const
{
size_t ret = 0;
for (size_t pos = 0; pos < GetSize(); ++pos) {
if (!GetWord(pos).IsNonTerminal())
ret++;
}
return ret;
}
void Phrase::InitializeMemPool()
{
}
void Phrase::FinalizeMemPool()
{
}
TO_STRING_BODY(Phrase);
// friend
ostream& operator<<(ostream& out, const Phrase& phrase)
{
// out << "(size " << phrase.GetSize() << ") ";
for (size_t pos = 0 ; pos < phrase.GetSize() ; pos++) {
const Word &word = phrase.GetWord(pos);
out << word;
}
return out;
}
}
<commit_msg>Improve debug<commit_after>// $Id$
// vim:tabstop=2
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
***********************************************************************/
#include <cassert>
#include <algorithm>
#include <sstream>
#include <string>
#include "memory.h"
#include "FactorCollection.h"
#include "Phrase.h"
#include "StaticData.h" // GetMaxNumFactors
using namespace std;
namespace Moses
{
Phrase::Phrase(const Phrase ©)
:m_direction(copy.m_direction)
,m_words(copy.m_words)
{
}
Phrase& Phrase::operator=(const Phrase& x)
{
if(this!=&x) {
m_direction=x.m_direction;
m_words = x.m_words;
}
return *this;
}
Phrase::Phrase(FactorDirection direction, size_t reserveSize)
: m_direction(direction)
{
m_words.reserve(reserveSize);
}
Phrase::Phrase(FactorDirection direction, const vector< const Word* > &mergeWords)
:m_direction(direction)
{
m_words.reserve(mergeWords.size());
for (size_t currPos = 0 ; currPos < mergeWords.size() ; currPos++) {
AddWord(*mergeWords[currPos]);
}
}
Phrase::~Phrase()
{
}
void Phrase::MergeFactors(const Phrase ©)
{
assert(GetSize() == copy.GetSize());
size_t size = GetSize();
const size_t maxNumFactors = StaticData::Instance().GetMaxNumFactors(this->GetDirection());
for (size_t currPos = 0 ; currPos < size ; currPos++) {
for (unsigned int currFactor = 0 ; currFactor < maxNumFactors ; currFactor++) {
FactorType factorType = static_cast<FactorType>(currFactor);
const Factor *factor = copy.GetFactor(currPos, factorType);
if (factor != NULL)
SetFactor(currPos, factorType, factor);
}
}
}
void Phrase::MergeFactors(const Phrase ©, FactorType factorType)
{
assert(GetSize() == copy.GetSize());
for (size_t currPos = 0 ; currPos < GetSize() ; currPos++)
SetFactor(currPos, factorType, copy.GetFactor(currPos, factorType));
}
void Phrase::MergeFactors(const Phrase ©, const std::vector<FactorType>& factorVec)
{
assert(GetSize() == copy.GetSize());
for (size_t currPos = 0 ; currPos < GetSize() ; currPos++)
for (std::vector<FactorType>::const_iterator i = factorVec.begin();
i != factorVec.end(); ++i) {
SetFactor(currPos, *i, copy.GetFactor(currPos, *i));
}
}
Phrase Phrase::GetSubString(const WordsRange &wordsRange) const
{
Phrase retPhrase(m_direction, wordsRange.GetNumWordsCovered());
for (size_t currPos = wordsRange.GetStartPos() ; currPos <= wordsRange.GetEndPos() ; currPos++) {
Word &word = retPhrase.AddWord();
word = GetWord(currPos);
}
return retPhrase;
}
std::string Phrase::GetStringRep(const vector<FactorType> factorsToPrint) const
{
stringstream strme;
for (size_t pos = 0 ; pos < GetSize() ; pos++) {
strme << GetWord(pos).GetString(factorsToPrint, (pos != GetSize()-1));
}
return strme.str();
}
Word &Phrase::AddWord()
{
m_words.push_back(Word());
return m_words.back();
}
void Phrase::Append(const Phrase &endPhrase)
{
for (size_t i = 0; i < endPhrase.GetSize(); i++) {
AddWord(endPhrase.GetWord(i));
}
}
void Phrase::PrependWord(const Word &newWord)
{
AddWord();
// shift
for (size_t pos = GetSize() - 1; pos >= 1; --pos) {
const Word &word = m_words[pos - 1];
m_words[pos] = word;
}
m_words[0] = newWord;
}
vector< vector<string> > Phrase::Parse(const std::string &phraseString, const std::vector<FactorType> &factorOrder, const std::string& factorDelimiter)
{
bool isMultiCharDelimiter = factorDelimiter.size() > 1;
// parse
vector< vector<string> > phraseVector;
vector<string> annotatedWordVector = Tokenize(phraseString);
// KOMMA|none ART|Def.Z NN|Neut.NotGen.Sg VVFIN|none
// to
// "KOMMA|none" "ART|Def.Z" "NN|Neut.NotGen.Sg" "VVFIN|none"
for (size_t phrasePos = 0 ; phrasePos < annotatedWordVector.size() ; phrasePos++) {
string &annotatedWord = annotatedWordVector[phrasePos];
vector<string> factorStrVector;
if (isMultiCharDelimiter) {
factorStrVector = TokenizeMultiCharSeparator(annotatedWord, factorDelimiter);
} else {
factorStrVector = Tokenize(annotatedWord, factorDelimiter);
}
// KOMMA|none
// to
// "KOMMA" "none"
if (factorStrVector.size() != factorOrder.size()) {
TRACE_ERR( "[ERROR] Malformed input: '" << annotatedWord << "'" << std::endl
<< "In '" << phraseString << "'" << endl
<< " Expected input to have words composed of " << factorOrder.size() << " factor(s) (form FAC1|FAC2|...)" << std::endl
<< " but instead received input with " << factorStrVector.size() << " factor(s).\n");
abort();
}
phraseVector.push_back(factorStrVector);
}
return phraseVector;
}
void Phrase::CreateFromString(const std::vector<FactorType> &factorOrder
, const vector< vector<string> > &phraseVector)
{
FactorCollection &factorCollection = FactorCollection::Instance();
m_words.reserve(phraseVector.size());
for (size_t phrasePos = 0 ; phrasePos < phraseVector.size() ; phrasePos++) {
// add word this phrase
Word &word = AddWord();
for (size_t currFactorIndex= 0 ; currFactorIndex < factorOrder.size() ; currFactorIndex++) {
FactorType factorType = factorOrder[currFactorIndex];
const string &factorStr = phraseVector[phrasePos][currFactorIndex];
const Factor *factor = factorCollection.AddFactor(m_direction, factorType, factorStr);
word[factorType] = factor;
}
}
}
void Phrase::CreateFromString(const std::vector<FactorType> &factorOrder
, const string &phraseString
, const string &factorDelimiter)
{
vector< vector<string> > phraseVector = Parse(phraseString, factorOrder, factorDelimiter);
CreateFromString(factorOrder, phraseVector);
}
void Phrase::CreateFromStringNewFormat(FactorDirection direction
, const std::vector<FactorType> &factorOrder
, const std::string &phraseString
, const std::string & /*factorDelimiter */
, Word &lhs)
{
// parse
vector<string> annotatedWordVector;
Tokenize(annotatedWordVector, phraseString);
// KOMMA|none ART|Def.Z NN|Neut.NotGen.Sg VVFIN|none
// to
// "KOMMA|none" "ART|Def.Z" "NN|Neut.NotGen.Sg" "VVFIN|none"
m_words.reserve(annotatedWordVector.size()-1);
for (size_t phrasePos = 0 ; phrasePos < annotatedWordVector.size() - 1 ; phrasePos++) {
string &annotatedWord = annotatedWordVector[phrasePos];
bool isNonTerminal;
if (annotatedWord.substr(0, 1) == "[" && annotatedWord.substr(annotatedWord.size()-1, 1) == "]") {
// non-term
isNonTerminal = true;
size_t nextPos = annotatedWord.find("[", 1);
assert(nextPos != string::npos);
if (direction == Input)
annotatedWord = annotatedWord.substr(1, nextPos - 2);
else
annotatedWord = annotatedWord.substr(nextPos + 1, annotatedWord.size() - nextPos - 2);
} else {
isNonTerminal = false;
}
Word &word = AddWord();
word.CreateFromString(direction, factorOrder, annotatedWord, isNonTerminal);
}
// lhs
string &annotatedWord = annotatedWordVector.back();
assert(annotatedWord.substr(0, 1) == "[" && annotatedWord.substr(annotatedWord.size()-1, 1) == "]");
annotatedWord = annotatedWord.substr(1, annotatedWord.size() - 2);
lhs.CreateFromString(direction, factorOrder, annotatedWord, true);
assert(lhs.IsNonTerminal());
}
int Phrase::Compare(const Phrase &other) const
{
#ifdef min
#undef min
#endif
size_t thisSize = GetSize()
,compareSize = other.GetSize();
if (thisSize != compareSize) {
return (thisSize < compareSize) ? -1 : 1;
}
for (size_t pos = 0 ; pos < thisSize ; pos++) {
const Word &thisWord = GetWord(pos)
,&otherWord = other.GetWord(pos);
int ret = Word::Compare(thisWord, otherWord);
if (ret != 0)
return ret;
}
return 0;
}
bool Phrase::Contains(const vector< vector<string> > &subPhraseVector
, const vector<FactorType> &inputFactor) const
{
const size_t subSize = subPhraseVector.size()
,thisSize= GetSize();
if (subSize > thisSize)
return false;
// try to match word-for-word
for (size_t currStartPos = 0 ; currStartPos < (thisSize - subSize + 1) ; currStartPos++) {
bool match = true;
for (size_t currFactorIndex = 0 ; currFactorIndex < inputFactor.size() ; currFactorIndex++) {
FactorType factorType = inputFactor[currFactorIndex];
for (size_t currSubPos = 0 ; currSubPos < subSize ; currSubPos++) {
size_t currThisPos = currSubPos + currStartPos;
const string &subStr = subPhraseVector[currSubPos][currFactorIndex]
,&thisStr = GetFactor(currThisPos, factorType)->GetString();
if (subStr != thisStr) {
match = false;
break;
}
}
if (!match)
break;
}
if (match)
return true;
}
return false;
}
bool Phrase::IsCompatible(const Phrase &inputPhrase) const
{
if (inputPhrase.GetSize() != GetSize()) {
return false;
}
const size_t size = GetSize();
const size_t maxNumFactors = StaticData::Instance().GetMaxNumFactors(this->GetDirection());
for (size_t currPos = 0 ; currPos < size ; currPos++) {
for (unsigned int currFactor = 0 ; currFactor < maxNumFactors ; currFactor++) {
FactorType factorType = static_cast<FactorType>(currFactor);
const Factor *thisFactor = GetFactor(currPos, factorType)
,*inputFactor = inputPhrase.GetFactor(currPos, factorType);
if (thisFactor != NULL && inputFactor != NULL && thisFactor != inputFactor)
return false;
}
}
return true;
}
bool Phrase::IsCompatible(const Phrase &inputPhrase, FactorType factorType) const
{
if (inputPhrase.GetSize() != GetSize()) {
return false;
}
for (size_t currPos = 0 ; currPos < GetSize() ; currPos++) {
if (GetFactor(currPos, factorType) != inputPhrase.GetFactor(currPos, factorType))
return false;
}
return true;
}
bool Phrase::IsCompatible(const Phrase &inputPhrase, const std::vector<FactorType>& factorVec) const
{
if (inputPhrase.GetSize() != GetSize()) {
return false;
}
for (size_t currPos = 0 ; currPos < GetSize() ; currPos++) {
for (std::vector<FactorType>::const_iterator i = factorVec.begin();
i != factorVec.end(); ++i) {
if (GetFactor(currPos, *i) != inputPhrase.GetFactor(currPos, *i))
return false;
}
}
return true;
}
size_t Phrase::GetNumTerminals() const
{
size_t ret = 0;
for (size_t pos = 0; pos < GetSize(); ++pos) {
if (!GetWord(pos).IsNonTerminal())
ret++;
}
return ret;
}
void Phrase::InitializeMemPool()
{
}
void Phrase::FinalizeMemPool()
{
}
TO_STRING_BODY(Phrase);
// friend
ostream& operator<<(ostream& out, const Phrase& phrase)
{
// out << "(size " << phrase.GetSize() << ") ";
for (size_t pos = 0 ; pos < phrase.GetSize() ; pos++) {
const Word &word = phrase.GetWord(pos);
out << word;
}
return out;
}
}
<|endoftext|>
|
<commit_before><commit_msg>asio.cpp: review thread set name<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 2013-2018 Anton Kozhevnikov, Thomas Schulthess
// 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/** \file initialize_subspace.hpp
*
* \brief Initialize subspace for iterative diagonalization.
*/
inline void Band::initialize_subspace(K_point_set& kset__, Hamiltonian& H__) const
{
PROFILE("sirius::Band::initialize_subspace");
int N{0};
if (ctx_.iterative_solver_input().init_subspace_ == "lcao") {
/* get the total number of atomic-centered orbitals */
for (int iat = 0; iat < unit_cell_.num_atom_types(); iat++) {
auto& atom_type = unit_cell_.atom_type(iat);
int n{0};
for (int i = 0; i < atom_type.num_ps_atomic_wf(); i++) {
n += (2 * std::abs(atom_type.ps_atomic_wf(i).first) + 1);
}
N += atom_type.num_atoms() * n;
}
if (ctx_.comm().rank() == 0 && ctx_.control().verbosity_ >= 2) {
printf("number of atomic orbitals: %i\n", N);
}
}
H__.prepare();
for (int ikloc = 0; ikloc < kset__.spl_num_kpoints().local_size(); ikloc++) {
int ik = kset__.spl_num_kpoints(ikloc);
auto kp = kset__[ik];
if (ctx_.gamma_point() && (ctx_.so_correction() == false)) {
initialize_subspace<double>(kp, H__, N);
} else {
initialize_subspace<double_complex>(kp, H__, N);
}
}
H__.dismiss();
/* reset the energies for the iterative solver to do at least two steps */
for (int ik = 0; ik < kset__.num_kpoints(); ik++) {
for (int ispn = 0; ispn < ctx_.num_spin_dims(); ispn++) {
for (int i = 0; i < ctx_.num_bands(); i++) {
kset__[ik]->band_energy(i, ispn, 0);
kset__[ik]->band_occupancy(i, ispn, ctx_.max_occupancy());
}
}
}
}
template <typename T>
inline void Band::initialize_subspace(K_point* kp__, Hamiltonian& H__, int num_ao__) const
{
PROFILE("sirius::Band::initialize_subspace|kp");
/* number of non-zero spin components */
const int num_sc = (ctx_.num_mag_dims() == 3) ? 2 : 1;
/* short notation for number of target wave-functions */
int num_bands = ctx_.num_bands();
/* number of basis functions */
int num_phi = std::max(num_ao__, num_bands / num_sc);
int num_phi_tot = num_phi * num_sc;
auto& mp = ctx_.mem_pool(ctx_.host_memory_t());
ctx_.print_memory_usage(__FILE__, __LINE__);
/* initial basis functions */
Wave_functions phi(mp, kp__->gkvec_partition(), num_phi_tot, ctx_.preferred_memory_t(), num_sc);
for (int ispn = 0; ispn < num_sc; ispn++) {
phi.pw_coeffs(ispn).prime().zero();
}
utils::timer t1("sirius::Band::initialize_subspace|kp|wf");
/* get proper lmax */
int lmax{0};
for (int iat = 0; iat < unit_cell_.num_atom_types(); iat++) {
auto& atom_type = unit_cell_.atom_type(iat);
lmax = std::max(lmax, atom_type.lmax_ps_atomic_wf());
}
lmax = std::max(lmax, unit_cell_.lmax());
if (num_ao__ > 0) {
kp__->generate_atomic_wave_functions(num_ao__, phi);
}
/* fill remaining wave-functions with pseudo-random guess */
assert(kp__->num_gkvec() > num_phi + 10);
#pragma omp parallel for schedule(static)
for (int i = 0; i < num_phi - num_ao__; i++) {
for (int igk_loc = 0; igk_loc < kp__->num_gkvec_loc(); igk_loc++) {
/* global index of G+k vector */
int igk = kp__->idxgk(igk_loc);
if (igk == i + 1) {
phi.pw_coeffs(0).prime(igk_loc, num_ao__ + i) = 1.0;
}
if (igk == i + 2) {
phi.pw_coeffs(0).prime(igk_loc, num_ao__ + i) = 0.5;
}
if (igk == i + 3) {
phi.pw_coeffs(0).prime(igk_loc, num_ao__ + i) = 0.25;
}
}
}
std::vector<double> tmp(4096);
for (int i = 0; i < 4096; i++) {
tmp[i] = utils::random<double>();
}
#pragma omp parallel for schedule(static)
for (int i = 0; i < num_phi; i++) {
for (int igk_loc = kp__->gkvec().skip_g0(); igk_loc < kp__->num_gkvec_loc(); igk_loc++) {
/* global index of G+k vector */
int igk = kp__->idxgk(igk_loc);
phi.pw_coeffs(0).prime(igk_loc, i) += tmp[igk & 0xFFF] * 1e-5;
}
}
if (ctx_.num_mag_dims() == 3) {
/* make pure spinor up- and dn- wave functions */
phi.copy_from(device_t::CPU, num_phi, phi, 0, 0, 1, num_phi);
}
t1.stop();
ctx_.fft_coarse().prepare(kp__->gkvec_partition());
H__.local_op().prepare(kp__->gkvec_partition());
/* allocate wave-functions */
Wave_functions hphi(mp, kp__->gkvec_partition(), num_phi_tot, ctx_.preferred_memory_t(), num_sc);
Wave_functions ophi(mp, kp__->gkvec_partition(), num_phi_tot, ctx_.preferred_memory_t(), num_sc);
/* temporary wave-functions required as a storage during orthogonalization */
Wave_functions wf_tmp(mp, kp__->gkvec_partition(), num_phi_tot, ctx_.preferred_memory_t(), num_sc);
int bs = ctx_.cyclic_block_size();
auto& gen_solver = ctx_.gen_evp_solver();
dmatrix<T> hmlt(mp, num_phi_tot, num_phi_tot, ctx_.blacs_grid(), bs, bs);
dmatrix<T> ovlp(mp, num_phi_tot, num_phi_tot, ctx_.blacs_grid(), bs, bs);
dmatrix<T> evec(mp, num_phi_tot, num_phi_tot, ctx_.blacs_grid(), bs, bs);
std::vector<double> eval(num_bands);
ctx_.print_memory_usage(__FILE__, __LINE__);
kp__->beta_projectors().prepare();
if (is_device_memory(ctx_.preferred_memory_t())) {
auto& mpd = ctx_.mem_pool(memory_t::device);
for (int ispn = 0; ispn < num_sc; ispn++) {
phi.pw_coeffs(ispn).allocate(mpd);
phi.pw_coeffs(ispn).copy_to(memory_t::device, 0, num_phi_tot);
}
for (int ispn = 0; ispn < ctx_.num_spins(); ispn++) {
kp__->spinor_wave_functions().pw_coeffs(ispn).allocate(mpd);
}
for (int ispn = 0; ispn < num_sc; ispn++) {
hphi.pw_coeffs(ispn).allocate(mpd);
ophi.pw_coeffs(ispn).allocate(mpd);
wf_tmp.pw_coeffs(ispn).allocate(mpd);
}
evec.allocate(mpd);
hmlt.allocate(mpd);
ovlp.allocate(mpd);
}
ctx_.print_memory_usage(__FILE__, __LINE__);
if (ctx_.control().print_checksum_) {
for (int ispn = 0; ispn < num_sc; ispn++) {
auto cs = phi.checksum_pw(get_device_t(ctx_.preferred_memory_t()), ispn, 0, num_phi_tot);
if (kp__->comm().rank() == 0) {
std::stringstream s;
s << "initial_phi" << ispn;
utils::print_checksum(s.str(), cs);
}
}
}
for (int ispn_step = 0; ispn_step < ctx_.num_spin_dims(); ispn_step++) {
/* apply Hamiltonian and overlap operators to the new basis functions */
H__.apply_h_s<T>(kp__, (ctx_.num_mag_dims() == 3) ? 2 : ispn_step, 0, num_phi_tot, phi, &hphi, &ophi);
/* do some checks */
if (ctx_.control().verification_ >= 1) {
set_subspace_mtrx<T>(0, num_phi_tot, phi, ophi, ovlp);
if (ctx_.control().verification_ >= 2) {
ovlp.serialize("overlap", num_phi_tot);
}
double max_diff = check_hermitian(ovlp, num_phi_tot);
if (max_diff > 1e-12) {
std::stringstream s;
s << "overlap matrix is not hermitian, max_err = " << max_diff;
TERMINATE(s);
}
std::vector<double> eo(num_phi_tot);
auto& std_solver = ctx_.std_evp_solver();
if (std_solver.solve(num_phi_tot, num_phi_tot, ovlp, eo.data(), evec)) {
std::stringstream s;
s << "error in diagonalization";
TERMINATE(s);
}
if (kp__->comm().rank() == 0) {
printf("[verification] minimum eigen-value of the overlap matrix: %18.12f\n", eo[0]);
}
if (eo[0] < 0) {
TERMINATE("overlap matrix is not positively defined");
}
}
/* setup eigen-value problem */
set_subspace_mtrx<T>(0, num_phi_tot, phi, hphi, hmlt);
set_subspace_mtrx<T>(0, num_phi_tot, phi, ophi, ovlp);
if (ctx_.control().verification_ >= 2) {
hmlt.serialize("hmlt", num_phi_tot);
ovlp.serialize("ovlp", num_phi_tot);
}
/* solve generalized eigen-value problem with the size N and get lowest num_bands eigen-vectors */
if (gen_solver.solve(num_phi_tot, num_bands, hmlt, ovlp, eval.data(), evec)) {
std::stringstream s;
s << "error in diagonalziation";
TERMINATE(s);
}
if (ctx_.control().print_checksum_) {
auto cs = evec.checksum();
evec.blacs_grid().comm().allreduce(&cs, 1);
double cs1{0};
for (int i = 0; i < num_bands; i++) {
cs1 += eval[i];
}
if (kp__->comm().rank() == 0) {
utils::print_checksum("evec", cs);
utils::print_checksum("eval", cs1);
}
}
if (ctx_.control().verbosity_ >= 3 && kp__->comm().rank() == 0) {
for (int i = 0; i < num_bands; i++) {
printf("eval[%i]=%20.16f\n", i, eval[i]);
}
}
/* compute wave-functions */
/* \Psi_{i} = \sum_{mu} \phi_{mu} * Z_{mu, i} */
transform<T>(ctx_.preferred_memory_t(), ctx_.blas_linalg_t(), (ctx_.num_mag_dims() == 3) ? 2 : ispn_step,
{&phi}, 0, num_phi_tot, evec, 0, 0, {&kp__->spinor_wave_functions()}, 0, num_bands);
for (int j = 0; j < num_bands; j++) {
kp__->band_energy(j, ispn_step, eval[j]);
}
}
if (ctx_.control().print_checksum_) {
for (int ispn = 0; ispn < ctx_.num_spins(); ispn++) {
auto cs = kp__->spinor_wave_functions().checksum_pw(get_device_t(ctx_.preferred_memory_t()), ispn, 0, num_bands);
std::stringstream s;
s << "initial_spinor_wave_functions_" << ispn;
if (kp__->comm().rank() == 0) {
utils::print_checksum(s.str(), cs);
}
}
}
if (is_device_memory(ctx_.preferred_memory_t())) {
for (int ispn = 0; ispn < ctx_.num_spins(); ispn++) {
kp__->spinor_wave_functions().pw_coeffs(ispn).copy_to(memory_t::host, 0, num_bands);
kp__->spinor_wave_functions().pw_coeffs(ispn).deallocate(memory_t::device);
}
}
if (ctx_.control().print_checksum_) {
for (int ispn = 0; ispn < ctx_.num_spins(); ispn++) {
auto cs = kp__->spinor_wave_functions().checksum_pw(device_t::CPU, ispn, 0, num_bands);
std::stringstream s;
s << "initial_spinor_wave_functions_" << ispn;
if (kp__->comm().rank() == 0) {
utils::print_checksum(s.str(), cs);
}
}
}
/* check residuals */
if (ctx_.control().verification_ >= 1) {
check_residuals<T>(*kp__, H__);
check_wave_functions<T>(*kp__, H__);
}
kp__->beta_projectors().dismiss();
ctx_.fft_coarse().dismiss();
ctx_.print_memory_usage(__FILE__, __LINE__);
}
<commit_msg>small fix<commit_after>// Copyright (c) 2013-2018 Anton Kozhevnikov, Thomas Schulthess
// 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/** \file initialize_subspace.hpp
*
* \brief Initialize subspace for iterative diagonalization.
*/
inline void Band::initialize_subspace(K_point_set& kset__, Hamiltonian& H__) const
{
PROFILE("sirius::Band::initialize_subspace");
int N{0};
if (ctx_.iterative_solver_input().init_subspace_ == "lcao") {
/* get the total number of atomic-centered orbitals */
for (int iat = 0; iat < unit_cell_.num_atom_types(); iat++) {
auto& atom_type = unit_cell_.atom_type(iat);
int n{0};
for (int i = 0; i < atom_type.num_ps_atomic_wf(); i++) {
n += (2 * std::abs(atom_type.ps_atomic_wf(i).first) + 1);
}
N += atom_type.num_atoms() * n;
}
if (ctx_.comm().rank() == 0 && ctx_.control().verbosity_ >= 2) {
printf("number of atomic orbitals: %i\n", N);
}
}
H__.prepare();
for (int ikloc = 0; ikloc < kset__.spl_num_kpoints().local_size(); ikloc++) {
int ik = kset__.spl_num_kpoints(ikloc);
auto kp = kset__[ik];
if (ctx_.gamma_point() && (ctx_.so_correction() == false)) {
initialize_subspace<double>(kp, H__, N);
} else {
initialize_subspace<double_complex>(kp, H__, N);
}
}
H__.dismiss();
/* reset the energies for the iterative solver to do at least two steps */
for (int ik = 0; ik < kset__.num_kpoints(); ik++) {
for (int ispn = 0; ispn < ctx_.num_spin_dims(); ispn++) {
for (int i = 0; i < ctx_.num_bands(); i++) {
kset__[ik]->band_energy(i, ispn, 0);
kset__[ik]->band_occupancy(i, ispn, ctx_.max_occupancy());
}
}
}
}
template <typename T>
inline void Band::initialize_subspace(K_point* kp__, Hamiltonian& H__, int num_ao__) const
{
PROFILE("sirius::Band::initialize_subspace|kp");
/* number of non-zero spin components */
const int num_sc = (ctx_.num_mag_dims() == 3) ? 2 : 1;
/* short notation for number of target wave-functions */
int num_bands = ctx_.num_bands();
/* number of basis functions */
int num_phi = std::max(num_ao__, num_bands / num_sc);
int num_phi_tot = num_phi * num_sc;
auto& mp = ctx_.mem_pool(ctx_.host_memory_t());
ctx_.print_memory_usage(__FILE__, __LINE__);
/* initial basis functions */
Wave_functions phi(mp, kp__->gkvec_partition(), num_phi_tot, ctx_.preferred_memory_t(), num_sc);
for (int ispn = 0; ispn < num_sc; ispn++) {
phi.pw_coeffs(ispn).prime().zero();
}
utils::timer t1("sirius::Band::initialize_subspace|kp|wf");
/* get proper lmax */
int lmax{0};
for (int iat = 0; iat < unit_cell_.num_atom_types(); iat++) {
auto& atom_type = unit_cell_.atom_type(iat);
lmax = std::max(lmax, atom_type.lmax_ps_atomic_wf());
}
lmax = std::max(lmax, unit_cell_.lmax());
if (num_ao__ > 0) {
kp__->generate_atomic_wave_functions(num_ao__, phi);
}
/* fill remaining wave-functions with pseudo-random guess */
assert(kp__->num_gkvec() > num_phi + 10);
#pragma omp parallel for schedule(static)
for (int i = 0; i < num_phi - num_ao__; i++) {
for (int igk_loc = 0; igk_loc < kp__->num_gkvec_loc(); igk_loc++) {
/* global index of G+k vector */
int igk = kp__->idxgk(igk_loc);
if (igk == i + 1) {
phi.pw_coeffs(0).prime(igk_loc, num_ao__ + i) = 1.0;
}
if (igk == i + 2) {
phi.pw_coeffs(0).prime(igk_loc, num_ao__ + i) = 0.5;
}
if (igk == i + 3) {
phi.pw_coeffs(0).prime(igk_loc, num_ao__ + i) = 0.25;
}
}
}
std::vector<double> tmp(4096);
for (int i = 0; i < 4096; i++) {
tmp[i] = utils::random<double>();
}
#pragma omp parallel for schedule(static)
for (int i = 0; i < num_phi; i++) {
for (int igk_loc = kp__->gkvec().skip_g0(); igk_loc < kp__->num_gkvec_loc(); igk_loc++) {
/* global index of G+k vector */
int igk = kp__->idxgk(igk_loc);
phi.pw_coeffs(0).prime(igk_loc, i) += tmp[igk & 0xFFF] * 1e-5;
}
}
if (ctx_.num_mag_dims() == 3) {
/* make pure spinor up- and dn- wave functions */
phi.copy_from(device_t::CPU, num_phi, phi, 0, 0, 1, num_phi);
}
t1.stop();
ctx_.fft_coarse().prepare(kp__->gkvec_partition());
H__.local_op().prepare(kp__->gkvec_partition());
/* allocate wave-functions */
Wave_functions hphi(mp, kp__->gkvec_partition(), num_phi_tot, ctx_.preferred_memory_t(), num_sc);
Wave_functions ophi(mp, kp__->gkvec_partition(), num_phi_tot, ctx_.preferred_memory_t(), num_sc);
/* temporary wave-functions required as a storage during orthogonalization */
Wave_functions wf_tmp(mp, kp__->gkvec_partition(), num_phi_tot, ctx_.preferred_memory_t(), num_sc);
int bs = ctx_.cyclic_block_size();
auto& gen_solver = ctx_.gen_evp_solver();
dmatrix<T> hmlt(mp, num_phi_tot, num_phi_tot, ctx_.blacs_grid(), bs, bs);
dmatrix<T> ovlp(mp, num_phi_tot, num_phi_tot, ctx_.blacs_grid(), bs, bs);
dmatrix<T> evec(mp, num_phi_tot, num_phi_tot, ctx_.blacs_grid(), bs, bs);
std::vector<double> eval(num_bands);
ctx_.print_memory_usage(__FILE__, __LINE__);
kp__->beta_projectors().prepare();
if (is_device_memory(ctx_.preferred_memory_t())) {
auto& mpd = ctx_.mem_pool(memory_t::device);
for (int ispn = 0; ispn < num_sc; ispn++) {
phi.pw_coeffs(ispn).allocate(mpd);
phi.pw_coeffs(ispn).copy_to(memory_t::device, 0, num_phi_tot);
}
for (int ispn = 0; ispn < ctx_.num_spins(); ispn++) {
kp__->spinor_wave_functions().pw_coeffs(ispn).allocate(mpd);
}
for (int ispn = 0; ispn < num_sc; ispn++) {
hphi.pw_coeffs(ispn).allocate(mpd);
ophi.pw_coeffs(ispn).allocate(mpd);
wf_tmp.pw_coeffs(ispn).allocate(mpd);
}
evec.allocate(mpd);
hmlt.allocate(mpd);
ovlp.allocate(mpd);
}
ctx_.print_memory_usage(__FILE__, __LINE__);
if (ctx_.control().print_checksum_) {
for (int ispn = 0; ispn < num_sc; ispn++) {
auto cs = phi.checksum_pw(get_device_t(ctx_.preferred_memory_t()), ispn, 0, num_phi_tot);
if (kp__->comm().rank() == 0) {
std::stringstream s;
s << "initial_phi" << ispn;
utils::print_checksum(s.str(), cs);
}
}
}
for (int ispn_step = 0; ispn_step < ctx_.num_spin_dims(); ispn_step++) {
/* apply Hamiltonian and overlap operators to the new basis functions */
H__.apply_h_s<T>(kp__, (ctx_.num_mag_dims() == 3) ? 2 : ispn_step, 0, num_phi_tot, phi, &hphi, &ophi);
/* do some checks */
if (ctx_.control().verification_ >= 1) {
set_subspace_mtrx<T>(0, num_phi_tot, phi, ophi, ovlp);
if (ctx_.control().verification_ >= 2) {
ovlp.serialize("overlap", num_phi_tot);
}
double max_diff = check_hermitian(ovlp, num_phi_tot);
if (max_diff > 1e-12) {
std::stringstream s;
s << "overlap matrix is not hermitian, max_err = " << max_diff;
TERMINATE(s);
}
std::vector<double> eo(num_phi_tot);
auto& std_solver = ctx_.std_evp_solver();
if (std_solver.solve(num_phi_tot, num_phi_tot, ovlp, eo.data(), evec)) {
std::stringstream s;
s << "error in diagonalization";
TERMINATE(s);
}
if (kp__->comm().rank() == 0) {
printf("[verification] minimum eigen-value of the overlap matrix: %18.12f\n", eo[0]);
}
if (eo[0] < 0) {
TERMINATE("overlap matrix is not positively defined");
}
}
/* setup eigen-value problem */
set_subspace_mtrx<T>(0, num_phi_tot, phi, hphi, hmlt);
set_subspace_mtrx<T>(0, num_phi_tot, phi, ophi, ovlp);
if (ctx_.control().verification_ >= 2) {
hmlt.serialize("hmlt", num_phi_tot);
ovlp.serialize("ovlp", num_phi_tot);
}
/* solve generalized eigen-value problem with the size N and get lowest num_bands eigen-vectors */
if (gen_solver.solve(num_phi_tot, num_bands, hmlt, ovlp, eval.data(), evec)) {
std::stringstream s;
s << "error in diagonalziation";
TERMINATE(s);
}
if (ctx_.control().print_checksum_) {
auto cs = evec.checksum();
evec.blacs_grid().comm().allreduce(&cs, 1);
double cs1{0};
for (int i = 0; i < num_bands; i++) {
cs1 += eval[i];
}
if (kp__->comm().rank() == 0) {
utils::print_checksum("evec", cs);
utils::print_checksum("eval", cs1);
}
}
if (ctx_.control().verbosity_ >= 3 && kp__->comm().rank() == 0) {
for (int i = 0; i < num_bands; i++) {
printf("eval[%i]=%20.16f\n", i, eval[i]);
}
}
/* compute wave-functions */
/* \Psi_{i} = \sum_{mu} \phi_{mu} * Z_{mu, i} */
transform<T>(ctx_.preferred_memory_t(), ctx_.blas_linalg_t(), (ctx_.num_mag_dims() == 3) ? 2 : ispn_step,
{&phi}, 0, num_phi_tot, evec, 0, 0, {&kp__->spinor_wave_functions()}, 0, num_bands);
for (int j = 0; j < num_bands; j++) {
kp__->band_energy(j, ispn_step, eval[j]);
}
}
if (ctx_.control().print_checksum_) {
for (int ispn = 0; ispn < ctx_.num_spins(); ispn++) {
auto cs = kp__->spinor_wave_functions().checksum_pw(get_device_t(ctx_.preferred_memory_t()), ispn, 0, num_bands);
std::stringstream s;
s << "initial_spinor_wave_functions_" << ispn;
if (kp__->comm().rank() == 0) {
utils::print_checksum(s.str(), cs);
}
}
}
if (is_device_memory(ctx_.preferred_memory_t())) {
for (int ispn = 0; ispn < ctx_.num_spins(); ispn++) {
kp__->spinor_wave_functions().pw_coeffs(ispn).copy_to(memory_t::host, 0, num_bands);
kp__->spinor_wave_functions().pw_coeffs(ispn).deallocate(memory_t::device);
}
}
if (ctx_.control().print_checksum_) {
for (int ispn = 0; ispn < ctx_.num_spins(); ispn++) {
auto cs = kp__->spinor_wave_functions().checksum_pw(device_t::CPU, ispn, 0, num_bands);
std::stringstream s;
s << "initial_spinor_wave_functions_" << ispn;
if (kp__->comm().rank() == 0) {
utils::print_checksum(s.str(), cs);
}
}
}
/* check residuals */
if (ctx_.control().verification_ >= 2) {
check_residuals<T>(*kp__, H__);
check_wave_functions<T>(*kp__, H__);
}
kp__->beta_projectors().dismiss();
ctx_.fft_coarse().dismiss();
ctx_.print_memory_usage(__FILE__, __LINE__);
}
<|endoftext|>
|
<commit_before>/*
* opencog/server/ConsoleSocket.cc
*
* Copyright (C) 2002-2007 Novamente LLC
* All Rights Reserved
*
* Written by Andre Senna <senna@vettalabs.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* 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 Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <string>
#include <opencog/server/CogServer.h>
#include <opencog/server/ConsoleSocket.h>
#include <opencog/server/Request.h>
#include <opencog/util/Config.h>
#include <opencog/util/Logger.h>
#include <opencog/util/misc.h>
using namespace opencog;
ConsoleSocket::ConsoleSocket(boost::asio::io_service& _io_service) :
ServerSocket(_io_service),
RequestResult("text/plain")
{
SetLineProtocol(true);
_shell = NULL;
}
ConsoleSocket::~ConsoleSocket()
{
logger().debug("[ConsoleSocket] destructor");
// If there's a shell, let them know that we are going away.
// This wouldn't be needed if we had garbage collection.
if (_shell) _shell->socketClosed();
}
void ConsoleSocket::OnConnection()
{
logger().debug("[ConsoleSocket] OnConnection");
if (!isClosed()) sendPrompt();
}
void ConsoleSocket::sendPrompt()
{
if (config().get_bool("ANSI_ENABLED"))
Send(config()["ANSI_PROMPT"]);
else
Send(config()["PROMPT"]);
}
tcp::socket& ConsoleSocket::getSocket()
{
return ServerSocket::getSocket();
}
void ConsoleSocket::OnLine(const std::string& line)
{
// If a shell processor has been designated, then defer all
// processing to the shell. In particular, avoid as much overhead
// as possible, since the shell needs to be able to handle a
// high-speed data feed with as little getting in the way as
// possible.
if (_shell) {
_shell->eval(line, this);
return;
}
logger().debug("[ConsoleSocket] OnLine [%s]", line.c_str());
// parse command line
std::list<std::string> params;
tokenize(line, std::back_inserter(params), " \t\v\f");
logger().debug("params.size(): %d", params.size());
if (params.empty()) {
// return on empty/blank line
OnRequestComplete();
return;
}
std::string cmdName = params.front();
params.pop_front();
CogServer& cogserver = static_cast<CogServer&>(server());
_request = cogserver.createRequest(cmdName);
if (_request == NULL) {
char msg[256];
snprintf(msg, 256, "command \"%s\" not found\n", cmdName.c_str());
logger().error(msg);
Send(msg);
// try to send "help" command response
_request = cogserver.createRequest("help");
if (_request == NULL) {
// no help request; just terminate the request
OnRequestComplete();
return;
}
}
_request->setRequestResult(this);
_request->setParameters(params);
if (LineProtocol()) {
// We only add the command to the processing queue
// if it hasn't disabled the line protocol
cogserver.pushRequest(_request);
if (_request->isShell()) {
// Force a drain of this request, because we *must* enter shell mode
// before handling any additional input from the socket (since the
// next input is almost surely intended for the new shell, not for
// the cogserver one).
// NOTE: Calling this method for other kinds of requests may cause
// cogserver to crash due to concurrency issues, since this runs in
// a separate thread (for socket handler) instead of the main thread
// (where the server loop runs).
cogserver.processRequests();
}
} else {
// reset input buffer
_buffer.clear();
}
}
/**
* Buffer up incoming raw data until an end-of-transmission (EOT)
* is received. After the EOT, dispatch the buffered data as a single
* request.
*
* Note that there is just one ConsoleSocket per client, so the buffer
* is not shared.
*
* XXX the data buffer is currently just a string buffer, so any
* null char in the data stream will terminate the string. So
* this method isn't really for "raw" data containing null chars.
* This should be fixed someday, as needed.
*/
void ConsoleSocket::OnRawData(const char *buf, size_t len)
{
#ifndef __APPLE__
char* _tmp = strndup(buf, len);
logger().debug("[ConsoleSocket] OnRawData local buffer [%s]", _tmp);
free(_tmp);
#endif
_buffer.append(buf, len);
logger().debug("[ConsoleSocket] OnRawData: global buffer:\n%s\n", _buffer.c_str());
size_t buffer_len = _buffer.length();
bool rawDataEnd = false;
if (buffer_len > 1 && (_buffer.at(buffer_len-1) == 0xa)) {
if (_buffer.at(buffer_len-2) == 0x4) {
rawDataEnd = true;
} else if (buffer_len > 2 &&
(_buffer.at(buffer_len-2) == 0xd) &&
(_buffer.at(buffer_len-3) == 0x4)) {
rawDataEnd = true;
}
}
if (rawDataEnd) {
logger().debug("[ConsoleSocket] found EOT; dispatching");
// found the EOT pattern. dispatch the request and reset
// the socket's line protocol flag
_request->addParameter(_buffer);
CogServer& cogserver = static_cast<CogServer&>(server());
cogserver.pushRequest(_request);
SetLineProtocol(true);
}
}
void ConsoleSocket::OnRequestComplete()
{
logger().debug("[ConsoleSocket] OnRequestComplete");
sendPrompt();
}
void ConsoleSocket::SetDataRequest()
{
logger().debug("[ConsoleSocket] SetDataRequest");
SetLineProtocol(false);
}
void ConsoleSocket::Exit()
{
logger().debug("[ConsoleSocket] ExecuteExitRequest");
SetCloseAndDelete();
}
void ConsoleSocket::SendResult(const std::string& res)
{
Send(res);
}
void ConsoleSocket::SetShell(GenericShell *g)
{
_shell = g;
}
<commit_msg>don't dump stack trace on user error.<commit_after>/*
* opencog/server/ConsoleSocket.cc
*
* Copyright (C) 2002-2007 Novamente LLC
* All Rights Reserved
*
* Written by Andre Senna <senna@vettalabs.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* 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 Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <string>
#include <opencog/server/CogServer.h>
#include <opencog/server/ConsoleSocket.h>
#include <opencog/server/Request.h>
#include <opencog/util/Config.h>
#include <opencog/util/Logger.h>
#include <opencog/util/misc.h>
using namespace opencog;
ConsoleSocket::ConsoleSocket(boost::asio::io_service& _io_service) :
ServerSocket(_io_service),
RequestResult("text/plain")
{
SetLineProtocol(true);
_shell = NULL;
}
ConsoleSocket::~ConsoleSocket()
{
logger().debug("[ConsoleSocket] destructor");
// If there's a shell, let them know that we are going away.
// This wouldn't be needed if we had garbage collection.
if (_shell) _shell->socketClosed();
}
void ConsoleSocket::OnConnection()
{
logger().debug("[ConsoleSocket] OnConnection");
if (!isClosed()) sendPrompt();
}
void ConsoleSocket::sendPrompt()
{
if (config().get_bool("ANSI_ENABLED"))
Send(config()["ANSI_PROMPT"]);
else
Send(config()["PROMPT"]);
}
tcp::socket& ConsoleSocket::getSocket()
{
return ServerSocket::getSocket();
}
void ConsoleSocket::OnLine(const std::string& line)
{
// If a shell processor has been designated, then defer all
// processing to the shell. In particular, avoid as much overhead
// as possible, since the shell needs to be able to handle a
// high-speed data feed with as little getting in the way as
// possible.
if (_shell) {
_shell->eval(line, this);
return;
}
logger().debug("[ConsoleSocket] OnLine [%s]", line.c_str());
// parse command line
std::list<std::string> params;
tokenize(line, std::back_inserter(params), " \t\v\f");
logger().debug("params.size(): %d", params.size());
if (params.empty()) {
// return on empty/blank line
OnRequestComplete();
return;
}
std::string cmdName = params.front();
params.pop_front();
CogServer& cogserver = static_cast<CogServer&>(server());
_request = cogserver.createRequest(cmdName);
if (_request == NULL) {
char msg[256];
snprintf(msg, 256, "command \"%s\" not found\n", cmdName.c_str());
logger().warn(msg);
Send(msg);
// try to send "help" command response
_request = cogserver.createRequest("help");
if (_request == NULL) {
// no help request; just terminate the request
OnRequestComplete();
return;
}
}
_request->setRequestResult(this);
_request->setParameters(params);
if (LineProtocol()) {
// We only add the command to the processing queue
// if it hasn't disabled the line protocol
cogserver.pushRequest(_request);
if (_request->isShell()) {
// Force a drain of this request, because we *must* enter shell mode
// before handling any additional input from the socket (since the
// next input is almost surely intended for the new shell, not for
// the cogserver one).
// NOTE: Calling this method for other kinds of requests may cause
// cogserver to crash due to concurrency issues, since this runs in
// a separate thread (for socket handler) instead of the main thread
// (where the server loop runs).
cogserver.processRequests();
}
} else {
// reset input buffer
_buffer.clear();
}
}
/**
* Buffer up incoming raw data until an end-of-transmission (EOT)
* is received. After the EOT, dispatch the buffered data as a single
* request.
*
* Note that there is just one ConsoleSocket per client, so the buffer
* is not shared.
*
* XXX the data buffer is currently just a string buffer, so any
* null char in the data stream will terminate the string. So
* this method isn't really for "raw" data containing null chars.
* This should be fixed someday, as needed.
*/
void ConsoleSocket::OnRawData(const char *buf, size_t len)
{
#ifndef __APPLE__
char* _tmp = strndup(buf, len);
logger().debug("[ConsoleSocket] OnRawData local buffer [%s]", _tmp);
free(_tmp);
#endif
_buffer.append(buf, len);
logger().debug("[ConsoleSocket] OnRawData: global buffer:\n%s\n", _buffer.c_str());
size_t buffer_len = _buffer.length();
bool rawDataEnd = false;
if (buffer_len > 1 && (_buffer.at(buffer_len-1) == 0xa)) {
if (_buffer.at(buffer_len-2) == 0x4) {
rawDataEnd = true;
} else if (buffer_len > 2 &&
(_buffer.at(buffer_len-2) == 0xd) &&
(_buffer.at(buffer_len-3) == 0x4)) {
rawDataEnd = true;
}
}
if (rawDataEnd) {
logger().debug("[ConsoleSocket] found EOT; dispatching");
// found the EOT pattern. dispatch the request and reset
// the socket's line protocol flag
_request->addParameter(_buffer);
CogServer& cogserver = static_cast<CogServer&>(server());
cogserver.pushRequest(_request);
SetLineProtocol(true);
}
}
void ConsoleSocket::OnRequestComplete()
{
logger().debug("[ConsoleSocket] OnRequestComplete");
sendPrompt();
}
void ConsoleSocket::SetDataRequest()
{
logger().debug("[ConsoleSocket] SetDataRequest");
SetLineProtocol(false);
}
void ConsoleSocket::Exit()
{
logger().debug("[ConsoleSocket] ExecuteExitRequest");
SetCloseAndDelete();
}
void ConsoleSocket::SendResult(const std::string& res)
{
Send(res);
}
void ConsoleSocket::SetShell(GenericShell *g)
{
_shell = g;
}
<|endoftext|>
|
<commit_before>#include "ProfilingManager.hpp"
#include <imgui.h>
#include <GLFW/glfw3.h>
ProfilingManager::ProfilingManager() {
}
ProfilingManager::~ProfilingManager() {
}
void ProfilingManager::BeginFrame() {
// Clear previous results.
first.children.clear();
first.name = "";
first.duration = 0.0;
current = nullptr;
frameStart = glfwGetTime();
}
void ProfilingManager::ShowResults() {
// Calculate the time of this frame.
frameTimes[frame++] = static_cast<float>((glfwGetTime() - frameStart) * 1000.0);
if (frame >= frames)
frame = 0;
// Show the results.
ImGui::Begin("Profiling");
ImGui::Checkbox("Sync GPU and CPU", &syncGPU);
if (ImGui::CollapsingHeader("Frametimes"))
ShowFrametimes();
if (ImGui::CollapsingHeader("Breakdown"))
ShowResult(first);
ImGui::End();
}
ProfilingManager::Result* ProfilingManager::StartResult(const std::string& name) {
if (current == nullptr) {
first.name = name;
first.parent = nullptr;
current = &first;
} else {
current->children.push_back(ProfilingManager::Result(name, current));
Result* result = ¤t->children.back();
current = result;
}
return current;
}
void ProfilingManager::FinishResult(Result* result, double start) {
// Sync GPU and CPU.
if (syncGPU) {
ProfilingManager::Result gpuFinish("GPU Finish", current);
double gpuFinishStart = glfwGetTime();
glFinish();
gpuFinish.duration = glfwGetTime() - gpuFinishStart;
result->children.push_back(gpuFinish);
}
result->duration = glfwGetTime() - start;
current = result->parent;
}
void ProfilingManager::ShowFrametimes() {
ImGui::PlotLines("Frametimes", frameTimes, frames, 0, nullptr, 0.f, FLT_MAX, ImVec2(0.f, 300.f));
}
void ProfilingManager::ShowResult(Result& result) {
std::string resultString = result.name + " " + std::to_string(result.duration * 1000.0) + " ms###" + result.name;
if (ImGui::TreeNode(resultString.c_str())) {
if (result.parent != nullptr)
ImGui::ProgressBar(result.duration / result.parent->duration, ImVec2(0.0f,0.0f));
double otherTime = result.duration;
for (Result& child : result.children) {
ShowResult(child);
otherTime -= child.duration;
}
if (!result.children.empty()) {
Result other("Other", &result);
other.duration = otherTime;
ShowResult(other);
}
ImGui::TreePop();
}
}
ProfilingManager::Result::Result(const std::string& name, Result* parent) {
this->name = name;
this->parent = parent;
}
<commit_msg>Columns in profiling<commit_after>#include "ProfilingManager.hpp"
#include <imgui.h>
#include <GLFW/glfw3.h>
ProfilingManager::ProfilingManager() {
}
ProfilingManager::~ProfilingManager() {
}
void ProfilingManager::BeginFrame() {
// Clear previous results.
first.children.clear();
first.name = "";
first.duration = 0.0;
current = nullptr;
frameStart = glfwGetTime();
}
void ProfilingManager::ShowResults() {
// Calculate the time of this frame.
frameTimes[frame++] = static_cast<float>((glfwGetTime() - frameStart) * 1000.0);
if (frame >= frames)
frame = 0;
// Show the results.
ImGui::Begin("Profiling");
ImGui::Checkbox("Sync GPU and CPU", &syncGPU);
if (ImGui::CollapsingHeader("Frametimes"))
ShowFrametimes();
if (ImGui::CollapsingHeader("Breakdown")) {
ImGui::Columns(2);
ShowResult(first);
ImGui::Columns(1);
}
ImGui::End();
}
ProfilingManager::Result* ProfilingManager::StartResult(const std::string& name) {
if (current == nullptr) {
first.name = name;
first.parent = nullptr;
current = &first;
} else {
current->children.push_back(ProfilingManager::Result(name, current));
Result* result = ¤t->children.back();
current = result;
}
return current;
}
void ProfilingManager::FinishResult(Result* result, double start) {
// Sync GPU and CPU.
if (syncGPU) {
ProfilingManager::Result gpuFinish("GPU Finish", current);
double gpuFinishStart = glfwGetTime();
glFinish();
gpuFinish.duration = glfwGetTime() - gpuFinishStart;
result->children.push_back(gpuFinish);
}
result->duration = glfwGetTime() - start;
current = result->parent;
}
void ProfilingManager::ShowFrametimes() {
ImGui::PlotLines("Frametimes", frameTimes, frames, 0, nullptr, 0.f, FLT_MAX, ImVec2(0.f, 300.f));
}
void ProfilingManager::ShowResult(Result& result) {
std::string resultString = result.name + " " + std::to_string(result.duration * 1000.0) + " ms###" + result.name;
ImGui::AlignFirstTextHeightToWidgets();
bool expanded = ImGui::TreeNode(resultString.c_str());
ImGui::NextColumn();
if (result.parent != nullptr)
ImGui::ProgressBar(result.duration / result.parent->duration, ImVec2(0.0f,0.0f));
ImGui::NextColumn();
if (expanded) {
double otherTime = result.duration;
for (Result& child : result.children) {
ShowResult(child);
otherTime -= child.duration;
}
if (!result.children.empty()) {
Result other("Other", &result);
other.duration = otherTime;
ShowResult(other);
}
ImGui::TreePop();
}
}
ProfilingManager::Result::Result(const std::string& name, Result* parent) {
this->name = name;
this->parent = parent;
}
<|endoftext|>
|
<commit_before>#include "core.h"
#include "character.h"
#include "marge.h"
#include "margeIdleState.h"
#include "margeJumpAttackState.h"
MargeJumpAttackState::MargeJumpAttackState()
{
}
MargeJumpAttackState::~MargeJumpAttackState()
{
}
void MargeJumpAttackState::Update(Character& player)
{
if (player.position.y >= 0) {
player.position.y = 0;
player.ChangeState(new MargeIdleState, "idle");
}
else {
if (player.flipped)
player.position.x -= 5;
else
player.position.x += 5;
player.position.y += 4;
}
}
<commit_msg>Improve jumpAttack speed<commit_after>#include "core.h"
#include "character.h"
#include "marge.h"
#include "margeIdleState.h"
#include "margeJumpAttackState.h"
MargeJumpAttackState::MargeJumpAttackState()
{
}
MargeJumpAttackState::~MargeJumpAttackState()
{
}
void MargeJumpAttackState::Update(Character& player)
{
if (player.position.y >= 0) {
player.position.y = 0;
player.ChangeState(new MargeIdleState, "idle");
}
else {
if (player.flipped)
player.position.x -= 5;
else
player.position.x += 5;
player.position.y += 5;
}
}
<|endoftext|>
|
<commit_before>/*
* This file is part of SpeakEasy.
* Copyright (C) 2011-2013 Lambert Clara <lambert.clara@yahoo.fr>
*
* 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/>.
*/
/**
* @file SE_CGUIGLFW.cpp
* @brief Wrapper for GLFW library
*
* @author Lambert Clara <lambert.clara@yahoo.fr>
* @date Created : 2011-08-23
*/
#include "SE_CGUIGLFW.h"
#include <GLFW/glfw3.h>
#include "config.h"
#include "SE_CGUIManager.h"
#include "SE_CLogManager.h"
I32 const WINDOW_WIDTH = 640;
I32 const WINDOW_HEIGHT = 480;
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
SE_CGUIGLFW::SE_CGUIGLFW() :
m_pGLFWWindow(nullptr)
{
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
SE_CGUIGLFW::~SE_CGUIGLFW()
{
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
bool SE_CGUIGLFW::init()
{
bool initSuccess = false;
seLogDebug("Initializing GLFW", glfwGetVersionString());
glfwSetErrorCallback(SE_CGUIGLFW::logGLFWerror);
I32 const initStatus = glfwInit();
if(initStatus == GL_TRUE)
{
initSuccess = true;
}
else
{
seLogError("glfwInit failed");
}
return initSuccess;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
bool SE_CGUIGLFW::openWindow()
{
bool windowOpened = false;
glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
#ifdef SE_DEBUG
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
#endif // SE_DEBUG
// only enable NON-deprecated features
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_CONTEXT_ROBUSTNESS, GLFW_NO_ROBUSTNESS);
glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
glfwWindowHint(GLFW_VISIBLE, GL_TRUE);
m_pGLFWWindow = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT,
"SpeakEasy" " - " GIT_INFORMATIONS " - built on " __DATE__ " " __TIME__,
nullptr, // windowed
nullptr // do not share resources
);
if(m_pGLFWWindow != nullptr)
{
windowOpened = true;
// Make the context of the newly created window current
glfwMakeContextCurrent(m_pGLFWWindow);
// Ensure that we can capture the escape key being pressed below
glfwSetInputMode(m_pGLFWWindow, GLFW_STICKY_KEYS, GL_TRUE);
// Enable vertical sync (on cards that supports it)
//glfwSwapInterval(1);
// Disable vertical sync
glfwSwapInterval(0);
seLogDebug("OpenGL context version :", glGetString(GL_VERSION));
}
else
{
glfwTerminate();
seLogError("glfwCreateWindow failed");
}
return windowOpened;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void SE_CGUIGLFW::swapBuffers()
{
glfwSwapBuffers(m_pGLFWWindow);
glfwPollEvents();
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
bool SE_CGUIGLFW::windowClosed() const
{
bool const windowCloseRequested = glfwWindowShouldClose(m_pGLFWWindow) == GL_TRUE;
if(windowCloseRequested)
{
seLogInfo("GLFW window has been closed");
}
return windowCloseRequested;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
bool SE_CGUIGLFW::close()
{
if(m_pGLFWWindow)
{
glfwDestroyWindow(m_pGLFWWindow);
m_pGLFWWindow = nullptr;
}
glfwTerminate();
return true;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
bool SE_CGUIGLFW::quitPressed() const
{
// TODO only quit once escape is released ??
bool shouldQuit = false;
I32 const escapeKeyStatus = glfwGetKey(m_pGLFWWindow, GLFW_KEY_ESCAPE);
if(escapeKeyStatus == GLFW_PRESS)
{
shouldQuit = true;
seLogInfo("GLFW window received escape key");
}
return shouldQuit;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void SE_CGUIGLFW::logGLFWerror(I32 const inErrorCode,
char const * const inpDescriptionText)
{
(void)inErrorCode;
seLogError("GLFW error :", inpDescriptionText);
}
<commit_msg>Handle window resizing<commit_after>/*
* This file is part of SpeakEasy.
* Copyright (C) 2011-2013 Lambert Clara <lambert.clara@yahoo.fr>
*
* 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/>.
*/
/**
* @file SE_CGUIGLFW.cpp
* @brief Wrapper for GLFW library
*
* @author Lambert Clara <lambert.clara@yahoo.fr>
* @date Created : 2011-08-23
*/
#include "SE_CGUIGLFW.h"
#include <GLFW/glfw3.h>
#include "config.h"
#include "SE_CGUIManager.h"
#include "SE_CLogManager.h"
I32 const WINDOW_WIDTH = 640;
I32 const WINDOW_HEIGHT = 480;
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
SE_CGUIGLFW::SE_CGUIGLFW() :
m_pGLFWWindow(nullptr)
{
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
SE_CGUIGLFW::~SE_CGUIGLFW()
{
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
bool SE_CGUIGLFW::init()
{
bool initSuccess = false;
seLogDebug("Initializing GLFW", glfwGetVersionString());
glfwSetErrorCallback(SE_CGUIGLFW::logGLFWerror);
I32 const initStatus = glfwInit();
if(initStatus == GL_TRUE)
{
initSuccess = true;
}
else
{
seLogError("glfwInit failed");
}
return initSuccess;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
bool SE_CGUIGLFW::openWindow()
{
bool windowOpened = false;
glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
#ifdef SE_DEBUG
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
#endif // SE_DEBUG
// only enable NON-deprecated features
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_CONTEXT_ROBUSTNESS, GLFW_NO_ROBUSTNESS);
glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
glfwWindowHint(GLFW_VISIBLE, GL_TRUE);
m_pGLFWWindow = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT,
"SpeakEasy" " - " GIT_INFORMATIONS " - built on " __DATE__ " " __TIME__,
nullptr, // windowed
nullptr // do not share resources
);
if(m_pGLFWWindow != nullptr)
{
windowOpened = true;
// Make the context of the newly created window current
glfwMakeContextCurrent(m_pGLFWWindow);
// Ensure that we can capture the escape key being pressed below
glfwSetInputMode(m_pGLFWWindow, GLFW_STICKY_KEYS, GL_TRUE);
// Enable vertical sync (on cards that supports it)
//glfwSwapInterval(1);
// Disable vertical sync
glfwSwapInterval(0);
seLogDebug("OpenGL context version :", glGetString(GL_VERSION));
glfwSetWindowSizeCallback(m_pGLFWWindow,
[](GLFWwindow*, I32 inNewWidth, I32 inNewHeight)
{
glViewport(0, 0, inNewWidth, inNewHeight);
}
);
}
else
{
glfwTerminate();
seLogError("glfwCreateWindow failed");
}
return windowOpened;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void SE_CGUIGLFW::swapBuffers()
{
glfwSwapBuffers(m_pGLFWWindow);
glfwPollEvents();
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
bool SE_CGUIGLFW::windowClosed() const
{
bool const windowCloseRequested = glfwWindowShouldClose(m_pGLFWWindow) == GL_TRUE;
if(windowCloseRequested)
{
seLogInfo("GLFW window has been closed");
}
return windowCloseRequested;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
bool SE_CGUIGLFW::close()
{
if(m_pGLFWWindow)
{
glfwDestroyWindow(m_pGLFWWindow);
m_pGLFWWindow = nullptr;
}
glfwTerminate();
return true;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
bool SE_CGUIGLFW::quitPressed() const
{
// TODO only quit once escape is released ??
bool shouldQuit = false;
I32 const escapeKeyStatus = glfwGetKey(m_pGLFWWindow, GLFW_KEY_ESCAPE);
if(escapeKeyStatus == GLFW_PRESS)
{
shouldQuit = true;
seLogInfo("GLFW window received escape key");
}
return shouldQuit;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void SE_CGUIGLFW::logGLFWerror(I32 const inErrorCode,
char const * const inpDescriptionText)
{
(void)inErrorCode;
seLogError("GLFW error :", inpDescriptionText);
}
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. 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. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.2 2002/09/30 22:20:40 peiyongz
* Build with ICU MsgLoader
*
* Revision 1.1.1.1 2002/02/01 22:22:19 peiyongz
* sane_include
*
* Revision 1.7 2002/01/21 14:52:25 tng
* [Bug 5847] ICUMsgLoader can't be compiled with gcc 3.0.3 and ICU2. And also fix the memory leak introduced by Bug 2730 fix.
*
* Revision 1.6 2001/11/01 23:39:18 jasons
* 2001-11-01 Jason E. Stewart <jason@openinformatics.com>
*
* * src/util/MsgLoaders/ICU/ICUMsgLoader.hpp (Repository):
* * src/util/MsgLoaders/ICU/ICUMsgLoader.cpp (Repository):
* Updated to compile with ICU-1.8.1
*
* Revision 1.5 2000/03/02 19:55:14 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.4 2000/02/06 07:48:21 rahulj
* Year 2K copyright swat.
*
* Revision 1.3 2000/01/19 00:58:38 roddey
* Update to support new ICU 1.4 release.
*
* Revision 1.2 1999/11/19 21:24:03 aruna1
* incorporated ICU 1.3.1 related changes int he file
*
* Revision 1.1.1.1 1999/11/09 01:07:23 twl
* Initial checkin
*
* Revision 1.4 1999/11/08 20:45:26 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLMsgLoader.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
#include "ICUMsgLoader.hpp"
#include "string.h"
#include <stdio.h>
#include <stdlib.h>
// ---------------------------------------------------------------------------
// Local static methods
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Public Constructors and Destructor
// ---------------------------------------------------------------------------
ICUMsgLoader::ICUMsgLoader(const XMLCh* const msgDomain)
:fRootBundle(0)
,fDomainBundle(0)
{
// validation on msgDomain
if (XMLString::compareString(msgDomain, XMLUni::fgXMLErrDomain)
&& XMLString::compareString(msgDomain, XMLUni::fgExceptDomain)
&& XMLString::compareString(msgDomain, XMLUni::fgValidityDomain))
{
XMLPlatformUtils::panic(XMLPlatformUtils::Panic_UnknownMsgDomain);
}
//
// we hardcode the path for "root.res" for now
// assuming that Makefile would copy root.res from $ICUROOT/bin to $XERCESCROOT/bin
//
char tempBuf[1024];
strcpy(tempBuf, getenv("XERCESCROOT"));
strcat(tempBuf, "/bin/root.res");
UErrorCode err = U_ZERO_ERROR;
fRootBundle = ures_open(tempBuf, 0, &err);
if (!U_SUCCESS(err) || fRootBundle == NULL)
{
XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain);
}
//strip off path information, if any
int index = XMLString::lastIndexOf(msgDomain, chForwardSlash);
char *domainName = XMLString::transcode(&(msgDomain[index + 1]));
// get the resource bundle for the domain
fDomainBundle = ures_getByKey(fRootBundle, domainName, NULL, &err);
delete [] domainName;
if (!U_SUCCESS(err) || fDomainBundle == NULL)
{
XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain);
}
}
ICUMsgLoader::~ICUMsgLoader()
{
ures_close(fDomainBundle);
ures_close(fRootBundle);
}
// ---------------------------------------------------------------------------
// Implementation of the virtual message loader API
// ---------------------------------------------------------------------------
bool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars)
{
UErrorCode err = U_ZERO_ERROR;
int32_t strLen = 0;
// Assuming array format
const UChar *name = ures_getStringByIndex(fDomainBundle, (int32_t)msgToLoad-1, &strLen, &err);
if (!U_SUCCESS(err) || (name == NULL))
{
return false;
}
int retStrLen = strLen > maxChars ? maxChars : strLen;
if (sizeof(UChar)==sizeof(XMLCh))
{
XMLString::moveChars(toFill, (XMLCh*)name, retStrLen);
toFill[retStrLen] = (XMLCh) 0;
}
else
{
XMLCh* retStr = toFill;
const UChar *srcPtr = name;
while (retStrLen--)
*retStr++ = *srcPtr++;
*retStr = 0;
}
return true;
}
bool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars
, const XMLCh* const repText1
, const XMLCh* const repText2
, const XMLCh* const repText3
, const XMLCh* const repText4)
{
// Call the other version to load up the message
if (!loadMsg(msgToLoad, toFill, maxChars))
return false;
// And do the token replacement
XMLString::replaceTokens(toFill, maxChars, repText1, repText2, repText3, repText4);
return true;
}
bool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars
, const char* const repText1
, const char* const repText2
, const char* const repText3
, const char* const repText4)
{
//
// Transcode the provided parameters and call the other version,
// which will do the replacement work.
//
XMLCh* tmp1 = 0;
XMLCh* tmp2 = 0;
XMLCh* tmp3 = 0;
XMLCh* tmp4 = 0;
bool bRet = false;
if (repText1)
tmp1 = XMLString::transcode(repText1);
if (repText2)
tmp2 = XMLString::transcode(repText2);
if (repText3)
tmp3 = XMLString::transcode(repText3);
if (repText4)
tmp4 = XMLString::transcode(repText4);
bRet = loadMsg(msgToLoad, toFill, maxChars, tmp1, tmp2, tmp3, tmp4);
if (tmp1)
delete [] tmp1;
if (tmp2)
delete [] tmp2;
if (tmp3)
delete [] tmp3;
if (tmp4)
delete [] tmp4;
return bRet;
}
<commit_msg>XMLString::equals() to replace XMLString::compareString()<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. 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. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.3 2002/10/02 17:08:50 peiyongz
* XMLString::equals() to replace XMLString::compareString()
*
* Revision 1.2 2002/09/30 22:20:40 peiyongz
* Build with ICU MsgLoader
*
* Revision 1.1.1.1 2002/02/01 22:22:19 peiyongz
* sane_include
*
* Revision 1.7 2002/01/21 14:52:25 tng
* [Bug 5847] ICUMsgLoader can't be compiled with gcc 3.0.3 and ICU2. And also fix the memory leak introduced by Bug 2730 fix.
*
* Revision 1.6 2001/11/01 23:39:18 jasons
* 2001-11-01 Jason E. Stewart <jason@openinformatics.com>
*
* * src/util/MsgLoaders/ICU/ICUMsgLoader.hpp (Repository):
* * src/util/MsgLoaders/ICU/ICUMsgLoader.cpp (Repository):
* Updated to compile with ICU-1.8.1
*
* Revision 1.5 2000/03/02 19:55:14 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.4 2000/02/06 07:48:21 rahulj
* Year 2K copyright swat.
*
* Revision 1.3 2000/01/19 00:58:38 roddey
* Update to support new ICU 1.4 release.
*
* Revision 1.2 1999/11/19 21:24:03 aruna1
* incorporated ICU 1.3.1 related changes int he file
*
* Revision 1.1.1.1 1999/11/09 01:07:23 twl
* Initial checkin
*
* Revision 1.4 1999/11/08 20:45:26 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLMsgLoader.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
#include "ICUMsgLoader.hpp"
#include "string.h"
#include <stdio.h>
#include <stdlib.h>
// ---------------------------------------------------------------------------
// Local static methods
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Public Constructors and Destructor
// ---------------------------------------------------------------------------
ICUMsgLoader::ICUMsgLoader(const XMLCh* const msgDomain)
:fRootBundle(0)
,fDomainBundle(0)
{
// validation on msgDomain
if (!XMLString::equals(msgDomain, XMLUni::fgXMLErrDomain) &&
!XMLString::equals(msgDomain, XMLUni::fgExceptDomain) &&
!XMLString::equals(msgDomain, XMLUni::fgValidityDomain) )
{
XMLPlatformUtils::panic(XMLPlatformUtils::Panic_UnknownMsgDomain);
}
//
// we hardcode the path for "root.res" for now
// assuming that Makefile would copy root.res from $ICUROOT/bin to $XERCESCROOT/bin
//
char tempBuf[1024];
strcpy(tempBuf, getenv("XERCESCROOT"));
strcat(tempBuf, "/bin/root.res");
UErrorCode err = U_ZERO_ERROR;
fRootBundle = ures_open(tempBuf, 0, &err);
if (!U_SUCCESS(err) || fRootBundle == NULL)
{
XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain);
}
//strip off path information, if any
int index = XMLString::lastIndexOf(msgDomain, chForwardSlash);
char *domainName = XMLString::transcode(&(msgDomain[index + 1]));
// get the resource bundle for the domain
fDomainBundle = ures_getByKey(fRootBundle, domainName, NULL, &err);
delete [] domainName;
if (!U_SUCCESS(err) || fDomainBundle == NULL)
{
XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain);
}
}
ICUMsgLoader::~ICUMsgLoader()
{
ures_close(fDomainBundle);
ures_close(fRootBundle);
}
// ---------------------------------------------------------------------------
// Implementation of the virtual message loader API
// ---------------------------------------------------------------------------
bool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars)
{
UErrorCode err = U_ZERO_ERROR;
int32_t strLen = 0;
// Assuming array format
const UChar *name = ures_getStringByIndex(fDomainBundle, (int32_t)msgToLoad-1, &strLen, &err);
if (!U_SUCCESS(err) || (name == NULL))
{
return false;
}
int retStrLen = strLen > maxChars ? maxChars : strLen;
if (sizeof(UChar)==sizeof(XMLCh))
{
XMLString::moveChars(toFill, (XMLCh*)name, retStrLen);
toFill[retStrLen] = (XMLCh) 0;
}
else
{
XMLCh* retStr = toFill;
const UChar *srcPtr = name;
while (retStrLen--)
*retStr++ = *srcPtr++;
*retStr = 0;
}
return true;
}
bool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars
, const XMLCh* const repText1
, const XMLCh* const repText2
, const XMLCh* const repText3
, const XMLCh* const repText4)
{
// Call the other version to load up the message
if (!loadMsg(msgToLoad, toFill, maxChars))
return false;
// And do the token replacement
XMLString::replaceTokens(toFill, maxChars, repText1, repText2, repText3, repText4);
return true;
}
bool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars
, const char* const repText1
, const char* const repText2
, const char* const repText3
, const char* const repText4)
{
//
// Transcode the provided parameters and call the other version,
// which will do the replacement work.
//
XMLCh* tmp1 = 0;
XMLCh* tmp2 = 0;
XMLCh* tmp3 = 0;
XMLCh* tmp4 = 0;
bool bRet = false;
if (repText1)
tmp1 = XMLString::transcode(repText1);
if (repText2)
tmp2 = XMLString::transcode(repText2);
if (repText3)
tmp3 = XMLString::transcode(repText3);
if (repText4)
tmp4 = XMLString::transcode(repText4);
bRet = loadMsg(msgToLoad, toFill, maxChars, tmp1, tmp2, tmp3, tmp4);
if (tmp1)
delete [] tmp1;
if (tmp2)
delete [] tmp2;
if (tmp3)
delete [] tmp3;
if (tmp4)
delete [] tmp4;
return bRet;
}
<|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.
*/
/*
* $Id$
*/
#if !defined(XERCESC_INCLUDE_GUARD_XERCES_AUTOCONFIG_CONFIG_HPP)
#define XERCESC_INCLUDE_GUARD_XERCES_AUTOCONFIG_CONFIG_HPP
//
// There are two primary xerces configuration header files:
//
// Xerces_autoconf_config.hpp
//
// For configuration of items that must be accessable
// through public headers. This file has limited information
// and carefully works to avoid collision of macro names, etc.
//
// This file is included by XercesDefs.h.
// This version of the file is specific for Microsoft Visual C++
// family of compilers
//
// config.h
//
// This file is not used with Microsoft Visual C++; the macros
// it would specify are instead hardcoded in the makefiles
//
#include <basetsd.h>
// silence the warning "while compiling class-template member function xxxx : identifier was truncated to '255'
// characters in the browser information"
#pragma warning( disable: 4786 )
// ---------------------------------------------------------------------------
// These defines have been hardcoded for the Microsoft Visual C++ compilers
// ---------------------------------------------------------------------------
#undef XERCES_AUTOCONF
#undef XERCES_HAVE_SYS_TYPES_H
#undef XERCES_HAVE_INTTYPES_H
#define XERCES_S16BIT_INT signed short
#define XERCES_U16BIT_INT unsigned short
#define XERCES_S32BIT_INT INT32
#define XERCES_U32BIT_INT UINT32
// While VC6 has 64-bit int, there is no support in the libraries
// (e.g., iostream). So we are going to stick to 32-bit ints.
//
#if (_MSC_VER >= 1300)
# define XERCES_S64BIT_INT INT64
# define XERCES_U64BIT_INT UINT64
#else
# define XERCES_S64BIT_INT INT32
# define XERCES_U64BIT_INT UINT32
#endif
#ifdef _NATIVE_WCHAR_T_DEFINED
#define XERCES_XMLCH_T wchar_t
#else
#define XERCES_XMLCH_T unsigned short
#endif
#define XERCES_SIZE_T SIZE_T
#define XERCES_SSIZE_T SSIZE_T
#define XERCES_HAS_CPP_NAMESPACE 1
#define XERCES_STD_NAMESPACE 1
#define XERCES_NEW_IOSTREAMS 1
#undef XERCES_NO_NATIVE_BOOL
#define XERCES_LSTRSUPPORT 1
#ifdef XERCES_STATIC_LIBRARY
#define XERCES_PLATFORM_EXPORT
#define XERCES_PLATFORM_IMPORT
#else
#define XERCES_PLATFORM_EXPORT __declspec(dllexport)
#define XERCES_PLATFORM_IMPORT __declspec(dllimport)
#define DLL_EXPORT
#endif
#define XERCES_MFC_SUPPORT
#define XERCES_HAVE_INTRIN_H 1
#define XERCES_HAVE_EMMINTRIN_H 1
#define XERCES_HAVE_CPUID_INTRINSIC
#define XERCES_HAVE_SSE2_INTRINSIC
// ---------------------------------------------------------------------------
// XMLSize_t is the unsigned integral type.
// ---------------------------------------------------------------------------
typedef XERCES_SIZE_T XMLSize_t;
typedef XERCES_SSIZE_T XMLSSize_t;
// ---------------------------------------------------------------------------
// Define our version of the XML character
// ---------------------------------------------------------------------------
typedef XERCES_XMLCH_T XMLCh;
// ---------------------------------------------------------------------------
// Define unsigned 16, 32, and 64 bit integers
// ---------------------------------------------------------------------------
typedef XERCES_U16BIT_INT XMLUInt16;
typedef XERCES_U32BIT_INT XMLUInt32;
typedef XERCES_U64BIT_INT XMLUInt64;
// ---------------------------------------------------------------------------
// Define signed 16, 32, and 64 bit integers
// ---------------------------------------------------------------------------
typedef XERCES_S16BIT_INT XMLInt16;
typedef XERCES_S32BIT_INT XMLInt32;
typedef XERCES_S64BIT_INT XMLInt64;
// ---------------------------------------------------------------------------
// XMLFilePos is the type used to represent a file position.
// ---------------------------------------------------------------------------
typedef XMLUInt64 XMLFilePos;
// ---------------------------------------------------------------------------
// XMLFileLoc is the type used to represent a file location (line/column).
// ---------------------------------------------------------------------------
typedef XMLUInt64 XMLFileLoc;
// ---------------------------------------------------------------------------
// Force on the Xerces debug token if it is on in the build environment
// ---------------------------------------------------------------------------
#if defined(_DEBUG)
#define XERCES_DEBUG
#endif
#endif
<commit_msg>Intrinsics are not available in VS.NET 2003<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.
*/
/*
* $Id$
*/
#if !defined(XERCESC_INCLUDE_GUARD_XERCES_AUTOCONFIG_CONFIG_HPP)
#define XERCESC_INCLUDE_GUARD_XERCES_AUTOCONFIG_CONFIG_HPP
//
// There are two primary xerces configuration header files:
//
// Xerces_autoconf_config.hpp
//
// For configuration of items that must be accessable
// through public headers. This file has limited information
// and carefully works to avoid collision of macro names, etc.
//
// This file is included by XercesDefs.h.
// This version of the file is specific for Microsoft Visual C++
// family of compilers
//
// config.h
//
// This file is not used with Microsoft Visual C++; the macros
// it would specify are instead hardcoded in the makefiles
//
#include <basetsd.h>
// silence the warning "while compiling class-template member function xxxx : identifier was truncated to '255'
// characters in the browser information"
#pragma warning( disable: 4786 )
// ---------------------------------------------------------------------------
// These defines have been hardcoded for the Microsoft Visual C++ compilers
// ---------------------------------------------------------------------------
#undef XERCES_AUTOCONF
#undef XERCES_HAVE_SYS_TYPES_H
#undef XERCES_HAVE_INTTYPES_H
#define XERCES_S16BIT_INT signed short
#define XERCES_U16BIT_INT unsigned short
#define XERCES_S32BIT_INT INT32
#define XERCES_U32BIT_INT UINT32
// While VC6 has 64-bit int, there is no support in the libraries
// (e.g., iostream). So we are going to stick to 32-bit ints.
//
#if (_MSC_VER >= 1300)
# define XERCES_S64BIT_INT INT64
# define XERCES_U64BIT_INT UINT64
#else
# define XERCES_S64BIT_INT INT32
# define XERCES_U64BIT_INT UINT32
#endif
#ifdef _NATIVE_WCHAR_T_DEFINED
# define XERCES_XMLCH_T wchar_t
#else
# define XERCES_XMLCH_T unsigned short
#endif
#define XERCES_SIZE_T SIZE_T
#define XERCES_SSIZE_T SSIZE_T
#define XERCES_HAS_CPP_NAMESPACE 1
#define XERCES_STD_NAMESPACE 1
#define XERCES_NEW_IOSTREAMS 1
#undef XERCES_NO_NATIVE_BOOL
#define XERCES_LSTRSUPPORT 1
#ifdef XERCES_STATIC_LIBRARY
# define XERCES_PLATFORM_EXPORT
# define XERCES_PLATFORM_IMPORT
#else
# define XERCES_PLATFORM_EXPORT __declspec(dllexport)
# define XERCES_PLATFORM_IMPORT __declspec(dllimport)
# define DLL_EXPORT
#endif
#define XERCES_MFC_SUPPORT
#if (_MSC_VER >= 1400)
# define XERCES_HAVE_INTRIN_H 1
# define XERCES_HAVE_EMMINTRIN_H 1
# define XERCES_HAVE_CPUID_INTRINSIC
# define XERCES_HAVE_SSE2_INTRINSIC
#endif
// ---------------------------------------------------------------------------
// XMLSize_t is the unsigned integral type.
// ---------------------------------------------------------------------------
typedef XERCES_SIZE_T XMLSize_t;
typedef XERCES_SSIZE_T XMLSSize_t;
// ---------------------------------------------------------------------------
// Define our version of the XML character
// ---------------------------------------------------------------------------
typedef XERCES_XMLCH_T XMLCh;
// ---------------------------------------------------------------------------
// Define unsigned 16, 32, and 64 bit integers
// ---------------------------------------------------------------------------
typedef XERCES_U16BIT_INT XMLUInt16;
typedef XERCES_U32BIT_INT XMLUInt32;
typedef XERCES_U64BIT_INT XMLUInt64;
// ---------------------------------------------------------------------------
// Define signed 16, 32, and 64 bit integers
// ---------------------------------------------------------------------------
typedef XERCES_S16BIT_INT XMLInt16;
typedef XERCES_S32BIT_INT XMLInt32;
typedef XERCES_S64BIT_INT XMLInt64;
// ---------------------------------------------------------------------------
// XMLFilePos is the type used to represent a file position.
// ---------------------------------------------------------------------------
typedef XMLUInt64 XMLFilePos;
// ---------------------------------------------------------------------------
// XMLFileLoc is the type used to represent a file location (line/column).
// ---------------------------------------------------------------------------
typedef XMLUInt64 XMLFileLoc;
// ---------------------------------------------------------------------------
// Force on the Xerces debug token if it is on in the build environment
// ---------------------------------------------------------------------------
#if defined(_DEBUG)
# define XERCES_DEBUG
#endif
#endif
<|endoftext|>
|
<commit_before>#include <GL/glut.h>
#include <cmath>
#include <iostream>
#define PI 3.14159265359
using namespace std;
double a = -17;
double v = 0;
double y = 0.0;
double x = 0.0;
double y00 = 0;
double t = 0;
void radioactive();
void time_pass();
void init();
void Mouse( int button, int state, int x, int y);
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(0,0);
glutCreateWindow("Bounce");
glutIdleFunc(time_pass);
glutDisplayFunc(radioactive);
init();
glutMouseFunc(Mouse);
glutMainLoop();
}
void init()
{
glClearColor(1.0 ,1.0 ,0.0 ,0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
}
void radioactive()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0, 0.0, 0.0);
//gluLookAt(0.0,5.0,0.0, 0.0,0.0,0.0, 1.0,1.0,0.0);
glOrtho(-4.0, 4.0, 0.0, 8.0, -4.0, 4.0);
glTranslatef(x, y, 0.0);
glutWireSphere(0.4, 15, 15);
glLoadIdentity();
glutSwapBuffers();
}
void time_pass()
{
y = a * t * t + v * t + y00;
t += 0.01;
if (y < 0.50)
{
y00 = 0.50;
v = -a * t * 0.80;
t = 0;
}
glutPostRedisplay();
}
void Mouse( int button, int state, int xp, int yp ) {
if ( button==GLUT_LEFT_BUTTON && state==GLUT_DOWN ) {
x = (xp / 250.0d)*4.0 - 4.0d;
y00 = -((yp / 250.0d) - 1.0d)*4.0 + 4.0;
t = 0;
v = 18;
cout << x << '\t' << y00 << endl;
}
}
<commit_msg>VS compatibility<commit_after>#include <GL/glut.h>
#include <cmath>
#include <iostream>
#define PI 3.14159265359
using namespace std;
double a = -17;
double v = 0;
double y = 0.0;
double x = 0.0;
double yzero = 0;
double t = 0;
void radioactive();
void time_pass();
void init();
void Mouse( int button, int state, int x, int y);
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(0,0);
glutCreateWindow("Bounce");
glutIdleFunc(time_pass);
glutDisplayFunc(radioactive);
init();
glutMouseFunc(Mouse);
glutMainLoop();
}
void init()
{
glClearColor(1.0 ,1.0 ,0.0 ,0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
}
void radioactive()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0, 0.0, 0.0);
//gluLookAt(0.0,5.0,0.0, 0.0,0.0,0.0, 1.0,1.0,0.0);
glOrtho(-4.0, 4.0, 0.0, 8.0, -4.0, 4.0);
glTranslatef(x, y, 0.0);
glutWireSphere(0.4, 15, 15);
glLoadIdentity();
glutSwapBuffers();
}
void time_pass()
{
y = a * t * t + v * t + yzero;
t += 0.01;
if (y < 0.50)
{
yzero = 0.50;
v = -a * t * 0.80;
t = 0;
}
glutPostRedisplay();
}
void Mouse( int button, int state, int xp, int yp ) {
if ( button==GLUT_LEFT_BUTTON && state==GLUT_DOWN ) {
x = (xp / 250.0) * 4.0 - 4.0;
yzero = -((yp / 250.0) - 1.0) * 4.0 + 4.0;
t = 0;
v = 18;
cout << x << '\t' << yzero << endl;
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: X11_clipboard.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: hr $ $Date: 2004-09-08 15:52:13 $
*
* 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): _______________________________________
*
*
************************************************************************/
#include <X11/Xatom.h>
#include <X11_clipboard.hxx>
#include <X11_transferable.hxx>
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_RENDERINGCAPABILITIES_HPP_
#include <com/sun/star/datatransfer/clipboard/RenderingCapabilities.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_
#include <com/sun/star/registry/XRegistryKey.hpp>
#endif
#ifndef _UNO_DISPATCHER_H_
#include <uno/dispatcher.h> // declaration of generic uno interface
#endif
#ifndef _UNO_MAPPING_HXX_
#include <uno/mapping.hxx> // mapping stuff
#endif
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif
#ifndef _RTL_TENCINFO_H
#include <rtl/tencinfo.h>
#endif
#if OSL_DEBUG_LEVEL > 1
#include <stdio.h>
#endif
using namespace com::sun::star::datatransfer;
using namespace com::sun::star::datatransfer::clipboard;
using namespace com::sun::star::lang;
using namespace com::sun::star::uno;
using namespace com::sun::star::awt;
using namespace cppu;
using namespace osl;
using namespace rtl;
using namespace x11;
X11Clipboard::X11Clipboard( SelectionManager& rManager, Atom aSelection ) :
::cppu::WeakComponentImplHelper4<
::com::sun::star::datatransfer::clipboard::XClipboardEx,
::com::sun::star::datatransfer::clipboard::XClipboardNotifier,
::com::sun::star::lang::XServiceInfo,
::com::sun::star::lang::XInitialization
>( m_aMutex ),
m_rSelectionManager( rManager ),
m_xSelectionManager( & rManager ),
m_aSelection( aSelection )
{
#if OSL_DEBUG_LEVEL > 1
fprintf( stderr, "creating instance of X11Clipboard (this=%p)\n", this );
#endif
if( m_aSelection != None )
{
m_rSelectionManager.registerHandler( m_aSelection, *this );
}
else
{
m_rSelectionManager.registerHandler( XA_PRIMARY, *this );
m_rSelectionManager.registerHandler( m_rSelectionManager.getAtom( OUString::createFromAscii( "CLIPBOARD" ) ), *this );
}
}
// ------------------------------------------------------------------------
X11Clipboard::~X11Clipboard()
{
MutexGuard aGuard( *Mutex::getGlobalMutex() );
#if OSL_DEBUG_LEVEL > 1
fprintf( stderr, "shutting down instance of X11Clipboard (this=%p, Selecttion=\"%s\")\n", this, OUStringToOString( m_rSelectionManager.getString( m_aSelection ), RTL_TEXTENCODING_ISO_8859_1 ).getStr() );
#endif
if( m_aSelection != None )
m_rSelectionManager.deregisterHandler( m_aSelection );
else
{
m_rSelectionManager.deregisterHandler( XA_PRIMARY );
m_rSelectionManager.deregisterHandler( m_rSelectionManager.getAtom( OUString::createFromAscii( "CLIPBOARD" ) ) );
}
}
// ------------------------------------------------------------------------
void X11Clipboard::fireChangedContentsEvent()
{
ClearableMutexGuard aGuard( m_aMutex );
#if OSL_DEBUG_LEVEL > 1
fprintf( stderr, "X11Clipboard::fireChangedContentsEvent for %s (%d listeners)\n",
OUStringToOString( m_rSelectionManager.getString( m_aSelection ), RTL_TEXTENCODING_ISO_8859_1 ).getStr(), m_aListeners.size() );
#endif
::std::list< Reference< XClipboardListener > > listeners( m_aListeners );
aGuard.clear();
ClipboardEvent aEvent( static_cast<OWeakObject*>(this), m_aContents);
while( listeners.begin() != listeners.end() )
{
if( listeners.front().is() )
listeners.front()->changedContents(aEvent);
listeners.pop_front();
}
}
// ------------------------------------------------------------------------
void X11Clipboard::clearContents()
{
ClearableMutexGuard aGuard(m_aMutex);
// protect against deletion during outside call
Reference< XClipboard > xThis( static_cast<XClipboard*>(this));
// copy member references on stack so they can be called
// without having the mutex
Reference< XClipboardOwner > xOwner( m_aOwner );
Reference< XTransferable > xTrans( m_aContents );
// clear members
m_aOwner.clear();
m_aContents.clear();
// release the mutex
aGuard.clear();
// inform previous owner of lost ownership
if ( xOwner.is() )
xOwner->lostOwnership(xThis, m_aContents);
}
// ------------------------------------------------------------------------
Reference< XTransferable > SAL_CALL X11Clipboard::getContents()
throw(RuntimeException)
{
MutexGuard aGuard(m_aMutex);
if( ! m_aContents.is() )
m_aContents = new X11Transferable( SelectionManager::get(), static_cast< OWeakObject* >(this), m_aSelection );
return m_aContents;
}
// ------------------------------------------------------------------------
void SAL_CALL X11Clipboard::setContents(
const Reference< XTransferable >& xTrans,
const Reference< XClipboardOwner >& xClipboardOwner )
throw(RuntimeException)
{
// remember old values for callbacks before setting the new ones.
ClearableMutexGuard aGuard(m_aMutex);
Reference< XClipboardOwner > oldOwner( m_aOwner );
m_aOwner = xClipboardOwner;
Reference< XTransferable > oldContents( m_aContents );
m_aContents = xTrans;
aGuard.clear();
// for now request ownership for both selections
if( m_aSelection != None )
m_rSelectionManager.requestOwnership( m_aSelection );
else
{
m_rSelectionManager.requestOwnership( XA_PRIMARY );
m_rSelectionManager.requestOwnership( m_rSelectionManager.getAtom( OUString::createFromAscii( "CLIPBOARD" ) ) );
}
// notify old owner on loss of ownership
if( oldOwner.is() )
oldOwner->lostOwnership(static_cast < XClipboard * > (this), oldContents);
// notify all listeners on content changes
fireChangedContentsEvent();
}
// ------------------------------------------------------------------------
OUString SAL_CALL X11Clipboard::getName()
throw(RuntimeException)
{
return m_rSelectionManager.getString( m_aSelection );
}
// ------------------------------------------------------------------------
sal_Int8 SAL_CALL X11Clipboard::getRenderingCapabilities()
throw(RuntimeException)
{
return RenderingCapabilities::Delayed;
}
// ------------------------------------------------------------------------
void SAL_CALL X11Clipboard::addClipboardListener( const Reference< XClipboardListener >& listener )
throw(RuntimeException)
{
MutexGuard aGuard( m_aMutex );
m_aListeners.push_back( listener );
}
// ------------------------------------------------------------------------
void SAL_CALL X11Clipboard::removeClipboardListener( const Reference< XClipboardListener >& listener )
throw(RuntimeException)
{
MutexGuard aGuard( m_aMutex );
m_aListeners.remove( listener );
}
// ------------------------------------------------------------------------
Reference< XTransferable > X11Clipboard::getTransferable()
{
return getContents();
}
// ------------------------------------------------------------------------
void X11Clipboard::clearTransferable()
{
clearContents();
}
// ------------------------------------------------------------------------
void X11Clipboard::fireContentsChanged()
{
fireChangedContentsEvent();
}
// ------------------------------------------------------------------------
Reference< XInterface > X11Clipboard::getReference() throw()
{
return Reference< XInterface >( static_cast< OWeakObject* >(this) );
}
// ------------------------------------------------------------------------
OUString SAL_CALL X11Clipboard::getImplementationName( )
throw(RuntimeException)
{
return OUString::createFromAscii(X11_CLIPBOARD_IMPLEMENTATION_NAME);
}
// ------------------------------------------------------------------------
sal_Bool SAL_CALL X11Clipboard::supportsService( const OUString& ServiceName )
throw(RuntimeException)
{
Sequence < OUString > SupportedServicesNames = X11Clipboard_getSupportedServiceNames();
for ( sal_Int32 n = SupportedServicesNames.getLength(); n--; )
if (SupportedServicesNames[n].compareTo(ServiceName) == 0)
return sal_True;
return sal_False;
}
// ------------------------------------------------------------------------
void SAL_CALL X11Clipboard::initialize( const Sequence< Any >& rArgs ) throw( ::com::sun::star::uno::Exception )
{
}
// ------------------------------------------------------------------------
Sequence< OUString > SAL_CALL X11Clipboard::getSupportedServiceNames( )
throw(RuntimeException)
{
return X11Clipboard_getSupportedServiceNames();
}
<commit_msg>INTEGRATION: CWS vcl41 (1.12.12); FILE MERGED 2005/06/16 16:55:28 pl 1.12.12.1: #123063# fix a synchronization issue<commit_after>/*************************************************************************
*
* $RCSfile: X11_clipboard.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: obo $ $Date: 2005-07-06 09:16:29 $
*
* 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): _______________________________________
*
*
************************************************************************/
#include <X11/Xatom.h>
#include <X11_clipboard.hxx>
#include <X11_transferable.hxx>
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_RENDERINGCAPABILITIES_HPP_
#include <com/sun/star/datatransfer/clipboard/RenderingCapabilities.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_
#include <com/sun/star/registry/XRegistryKey.hpp>
#endif
#ifndef _UNO_DISPATCHER_H_
#include <uno/dispatcher.h> // declaration of generic uno interface
#endif
#ifndef _UNO_MAPPING_HXX_
#include <uno/mapping.hxx> // mapping stuff
#endif
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif
#ifndef _RTL_TENCINFO_H
#include <rtl/tencinfo.h>
#endif
#if OSL_DEBUG_LEVEL > 1
#include <stdio.h>
#endif
using namespace com::sun::star::datatransfer;
using namespace com::sun::star::datatransfer::clipboard;
using namespace com::sun::star::lang;
using namespace com::sun::star::uno;
using namespace com::sun::star::awt;
using namespace cppu;
using namespace osl;
using namespace rtl;
using namespace x11;
X11Clipboard::X11Clipboard( SelectionManager& rManager, Atom aSelection ) :
::cppu::WeakComponentImplHelper4<
::com::sun::star::datatransfer::clipboard::XClipboardEx,
::com::sun::star::datatransfer::clipboard::XClipboardNotifier,
::com::sun::star::lang::XServiceInfo,
::com::sun::star::lang::XInitialization
>( rManager.getMutex() ),
m_rSelectionManager( rManager ),
m_xSelectionManager( & rManager ),
m_aSelection( aSelection )
{
#if OSL_DEBUG_LEVEL > 1
fprintf( stderr, "creating instance of X11Clipboard (this=%p)\n", this );
#endif
if( m_aSelection != None )
{
m_rSelectionManager.registerHandler( m_aSelection, *this );
}
else
{
m_rSelectionManager.registerHandler( XA_PRIMARY, *this );
m_rSelectionManager.registerHandler( m_rSelectionManager.getAtom( OUString::createFromAscii( "CLIPBOARD" ) ), *this );
}
}
// ------------------------------------------------------------------------
X11Clipboard::~X11Clipboard()
{
MutexGuard aGuard( *Mutex::getGlobalMutex() );
#if OSL_DEBUG_LEVEL > 1
fprintf( stderr, "shutting down instance of X11Clipboard (this=%p, Selecttion=\"%s\")\n", this, OUStringToOString( m_rSelectionManager.getString( m_aSelection ), RTL_TEXTENCODING_ISO_8859_1 ).getStr() );
#endif
if( m_aSelection != None )
m_rSelectionManager.deregisterHandler( m_aSelection );
else
{
m_rSelectionManager.deregisterHandler( XA_PRIMARY );
m_rSelectionManager.deregisterHandler( m_rSelectionManager.getAtom( OUString::createFromAscii( "CLIPBOARD" ) ) );
}
}
// ------------------------------------------------------------------------
void X11Clipboard::fireChangedContentsEvent()
{
ClearableMutexGuard aGuard( m_rSelectionManager.getMutex() );
#if OSL_DEBUG_LEVEL > 1
fprintf( stderr, "X11Clipboard::fireChangedContentsEvent for %s (%d listeners)\n",
OUStringToOString( m_rSelectionManager.getString( m_aSelection ), RTL_TEXTENCODING_ISO_8859_1 ).getStr(), m_aListeners.size() );
#endif
::std::list< Reference< XClipboardListener > > listeners( m_aListeners );
aGuard.clear();
ClipboardEvent aEvent( static_cast<OWeakObject*>(this), m_aContents);
while( listeners.begin() != listeners.end() )
{
if( listeners.front().is() )
listeners.front()->changedContents(aEvent);
listeners.pop_front();
}
}
// ------------------------------------------------------------------------
void X11Clipboard::clearContents()
{
ClearableMutexGuard aGuard(m_rSelectionManager.getMutex());
// protect against deletion during outside call
Reference< XClipboard > xThis( static_cast<XClipboard*>(this));
// copy member references on stack so they can be called
// without having the mutex
Reference< XClipboardOwner > xOwner( m_aOwner );
Reference< XTransferable > xTrans( m_aContents );
// clear members
m_aOwner.clear();
m_aContents.clear();
// release the mutex
aGuard.clear();
// inform previous owner of lost ownership
if ( xOwner.is() )
xOwner->lostOwnership(xThis, m_aContents);
}
// ------------------------------------------------------------------------
Reference< XTransferable > SAL_CALL X11Clipboard::getContents()
throw(RuntimeException)
{
MutexGuard aGuard(m_rSelectionManager.getMutex());
if( ! m_aContents.is() )
m_aContents = new X11Transferable( SelectionManager::get(), static_cast< OWeakObject* >(this), m_aSelection );
return m_aContents;
}
// ------------------------------------------------------------------------
void SAL_CALL X11Clipboard::setContents(
const Reference< XTransferable >& xTrans,
const Reference< XClipboardOwner >& xClipboardOwner )
throw(RuntimeException)
{
// remember old values for callbacks before setting the new ones.
ClearableMutexGuard aGuard(m_rSelectionManager.getMutex());
Reference< XClipboardOwner > oldOwner( m_aOwner );
m_aOwner = xClipboardOwner;
Reference< XTransferable > oldContents( m_aContents );
m_aContents = xTrans;
aGuard.clear();
// for now request ownership for both selections
if( m_aSelection != None )
m_rSelectionManager.requestOwnership( m_aSelection );
else
{
m_rSelectionManager.requestOwnership( XA_PRIMARY );
m_rSelectionManager.requestOwnership( m_rSelectionManager.getAtom( OUString::createFromAscii( "CLIPBOARD" ) ) );
}
// notify old owner on loss of ownership
if( oldOwner.is() )
oldOwner->lostOwnership(static_cast < XClipboard * > (this), oldContents);
// notify all listeners on content changes
fireChangedContentsEvent();
}
// ------------------------------------------------------------------------
OUString SAL_CALL X11Clipboard::getName()
throw(RuntimeException)
{
return m_rSelectionManager.getString( m_aSelection );
}
// ------------------------------------------------------------------------
sal_Int8 SAL_CALL X11Clipboard::getRenderingCapabilities()
throw(RuntimeException)
{
return RenderingCapabilities::Delayed;
}
// ------------------------------------------------------------------------
void SAL_CALL X11Clipboard::addClipboardListener( const Reference< XClipboardListener >& listener )
throw(RuntimeException)
{
MutexGuard aGuard( m_rSelectionManager.getMutex() );
m_aListeners.push_back( listener );
}
// ------------------------------------------------------------------------
void SAL_CALL X11Clipboard::removeClipboardListener( const Reference< XClipboardListener >& listener )
throw(RuntimeException)
{
MutexGuard aGuard( m_rSelectionManager.getMutex() );
m_aListeners.remove( listener );
}
// ------------------------------------------------------------------------
Reference< XTransferable > X11Clipboard::getTransferable()
{
return getContents();
}
// ------------------------------------------------------------------------
void X11Clipboard::clearTransferable()
{
clearContents();
}
// ------------------------------------------------------------------------
void X11Clipboard::fireContentsChanged()
{
fireChangedContentsEvent();
}
// ------------------------------------------------------------------------
Reference< XInterface > X11Clipboard::getReference() throw()
{
return Reference< XInterface >( static_cast< OWeakObject* >(this) );
}
// ------------------------------------------------------------------------
OUString SAL_CALL X11Clipboard::getImplementationName( )
throw(RuntimeException)
{
return OUString::createFromAscii(X11_CLIPBOARD_IMPLEMENTATION_NAME);
}
// ------------------------------------------------------------------------
sal_Bool SAL_CALL X11Clipboard::supportsService( const OUString& ServiceName )
throw(RuntimeException)
{
Sequence < OUString > SupportedServicesNames = X11Clipboard_getSupportedServiceNames();
for ( sal_Int32 n = SupportedServicesNames.getLength(); n--; )
if (SupportedServicesNames[n].compareTo(ServiceName) == 0)
return sal_True;
return sal_False;
}
// ------------------------------------------------------------------------
void SAL_CALL X11Clipboard::initialize( const Sequence< Any >& rArgs ) throw( ::com::sun::star::uno::Exception )
{
}
// ------------------------------------------------------------------------
Sequence< OUString > SAL_CALL X11Clipboard::getSupportedServiceNames( )
throw(RuntimeException)
{
return X11Clipboard_getSupportedServiceNames();
}
<|endoftext|>
|
<commit_before>#include "Behavior.hpp"
#include <boost/foreach.hpp>
Gameplay::Behavior::Behavior(GameplayModule *gameplay, size_t minRobots)
: _gameplay(gameplay), _minRobots(minRobots)
{
}
Gameplay::Behavior::~Behavior()
{
}
bool Gameplay::Behavior::run()
{
return false;
}
bool Gameplay::Behavior::allVisible() const
{
if (_robots.empty())
{
return false;
}
BOOST_FOREACH(Robot *r, _robots)
{
if (r && !r->visible())
{
return false;
}
}
return true;
}
bool Gameplay::Behavior::assign(std::set<Robot *> &available)
{
takeBest(available);
return _robots.size() >= _minRobots;
}
bool Gameplay::Behavior::takeAll(std::set<Robot *> &available)
{
_robots = available;
available.clear();
return _robots.size() >= _minRobots;
}
Gameplay::Robot *Gameplay::Behavior::takeBest(std::set<Robot *> &available)
{
if (available.empty())
{
return 0;
}
float bestScore = 0;
Robot *best = 0;
BOOST_FOREACH(Robot *r, available)
{
if (!best)
{
best = r;
} else {
float s = score(r);
if (s < bestScore)
{
bestScore = s;
best = r;
}
}
}
// best is guaranteed not to be null because we already ensured that available is not empty.
available.erase(best);
_robots.insert(best);
return best;
}
float Gameplay::Behavior::score(Robot *r)
{
return 0;
}
void Gameplay::Behavior::drawText(const std::string& text,
const Geometry2d::Point& pt,
int r, int g, int b) {
Packet::LogFrame::DebugText t;
t.text = text;
t.pos = pt;
t.color[0] = r;
t.color[1] = g;
t.color[2] = b;
gameplay()->state()->debugText.push_back(t);
}
void Gameplay::Behavior::drawText(const std::string& text,
const Geometry2d::Point& pt,
const QColor& color) {
drawText(text, pt, color.red(), color.green(), color.blue());
}
void Gameplay::Behavior::drawLine(const Geometry2d::Segment& line,
int r, int g, int b) {
Packet::LogFrame::DebugLine ln;
ln.pt[0] = line.pt[0];
ln.pt[1] = line.pt[1];
ln.color[0] = r;
ln.color[1] = g;
ln.color[2] = b;
gameplay()->state()->debugLines.push_back(ln);
}
void Gameplay::Behavior::drawLine(const Geometry2d::Segment& line,
const QColor& color) {
drawLine(line, color.red(), color.green(), color.blue());
}
void Gameplay::Behavior::drawCircle(const Geometry2d::Point& center,
float radius, int r, int g, int b) {
Packet::LogFrame::DebugCircle c;
c.radius(radius);
c.center = center;
c.color[0] = r;
c.color[1] = g;
c.color[2] = b;
gameplay()->state()->debugCircles.push_back(c);
}
void Gameplay::Behavior::drawCircle(const Geometry2d::Point& center,
float radius,
const QColor& color) {
drawCircle(center, radius, color.red(), color.green(), color.blue());
}
<commit_msg>takeBest was using a score of zero for the first robot<commit_after>#include "Behavior.hpp"
#include <boost/foreach.hpp>
Gameplay::Behavior::Behavior(GameplayModule *gameplay, size_t minRobots)
: _gameplay(gameplay), _minRobots(minRobots)
{
}
Gameplay::Behavior::~Behavior()
{
}
bool Gameplay::Behavior::run()
{
return false;
}
bool Gameplay::Behavior::allVisible() const
{
if (_robots.empty())
{
return false;
}
BOOST_FOREACH(Robot *r, _robots)
{
if (r && !r->visible())
{
return false;
}
}
return true;
}
bool Gameplay::Behavior::assign(std::set<Robot *> &available)
{
takeBest(available);
return _robots.size() >= _minRobots;
}
bool Gameplay::Behavior::takeAll(std::set<Robot *> &available)
{
_robots = available;
available.clear();
return _robots.size() >= _minRobots;
}
Gameplay::Robot *Gameplay::Behavior::takeBest(std::set<Robot *> &available)
{
if (available.empty())
{
return 0;
}
float bestScore = 0;
Robot *best = 0;
BOOST_FOREACH(Robot *r, available)
{
float s = score(r);
if (!best)
{
bestScore = s;
best = r;
} else {
if (s < bestScore)
{
bestScore = s;
best = r;
}
}
}
// best is guaranteed not to be null because we already ensured that available is not empty.
available.erase(best);
_robots.insert(best);
return best;
}
float Gameplay::Behavior::score(Robot *r)
{
return 0;
}
void Gameplay::Behavior::drawText(const std::string& text,
const Geometry2d::Point& pt,
int r, int g, int b) {
Packet::LogFrame::DebugText t;
t.text = text;
t.pos = pt;
t.color[0] = r;
t.color[1] = g;
t.color[2] = b;
gameplay()->state()->debugText.push_back(t);
}
void Gameplay::Behavior::drawText(const std::string& text,
const Geometry2d::Point& pt,
const QColor& color) {
drawText(text, pt, color.red(), color.green(), color.blue());
}
void Gameplay::Behavior::drawLine(const Geometry2d::Segment& line,
int r, int g, int b) {
Packet::LogFrame::DebugLine ln;
ln.pt[0] = line.pt[0];
ln.pt[1] = line.pt[1];
ln.color[0] = r;
ln.color[1] = g;
ln.color[2] = b;
gameplay()->state()->debugLines.push_back(ln);
}
void Gameplay::Behavior::drawLine(const Geometry2d::Segment& line,
const QColor& color) {
drawLine(line, color.red(), color.green(), color.blue());
}
void Gameplay::Behavior::drawCircle(const Geometry2d::Point& center,
float radius, int r, int g, int b) {
Packet::LogFrame::DebugCircle c;
c.radius(radius);
c.center = center;
c.color[0] = r;
c.color[1] = g;
c.color[2] = b;
gameplay()->state()->debugCircles.push_back(c);
}
void Gameplay::Behavior::drawCircle(const Geometry2d::Point& center,
float radius,
const QColor& color) {
drawCircle(center, radius, color.red(), color.green(), color.blue());
}
<|endoftext|>
|
<commit_before>/*
openDCM, dimensional constraint manager
Copyright (C) 2012 Stefan Troeger <stefantroeger@gmx.net>
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef DCM_CORE_H
#define DCM_CORE_H
#ifdef _WIN32
//warning about to long decoraded names, won't affect the code correctness
#pragma warning( disable : 4503 )
//warning about changed pod initalising behaviour (boost blank in variant)
#pragma warning( disable : 4345 )
//disable boost concept checks, as some of them have alignment problems which bring msvc to an error
//(for example DFSvisitor check in boost::graph::depht_first_search)
//this has no runtime effect as these are only compile time checks
#include <boost/concept/assert.hpp>
#undef BOOST_CONCEPT_ASSERT
#define BOOST_CONCEPT_ASSERT(Model)
#include <boost/concept_check.hpp>
#endif
#include "core/defines.hpp"
#include "core/geometry.hpp"
#include "core/kernel.hpp"
#include "core/system.hpp"
#endif //DCM_CORE_H
<commit_msg>supress multiple assignment operator warning on msvc<commit_after>/*
openDCM, dimensional constraint manager
Copyright (C) 2012 Stefan Troeger <stefantroeger@gmx.net>
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef DCM_CORE_H
#define DCM_CORE_H
#ifdef _WIN32
//warning about to long decoraded names, won't affect the code correctness
#pragma warning( disable : 4503 )
//warning about changed pod initalising behaviour (boost blank in variant)
#pragma warning( disable : 4345 )
//warning about multiple assignemnt operators in Equation
#pragma warning( disable : 4522 )
//disable boost concept checks, as some of them have alignment problems which bring msvc to an error
//(for example DFSvisitor check in boost::graph::depht_first_search)
//this has no runtime effect as these are only compile time checks
#include <boost/concept/assert.hpp>
#undef BOOST_CONCEPT_ASSERT
#define BOOST_CONCEPT_ASSERT(Model)
#include <boost/concept_check.hpp>
#endif
#include "core/defines.hpp"
#include "core/geometry.hpp"
#include "core/kernel.hpp"
#include "core/system.hpp"
#endif //DCM_CORE_H
<|endoftext|>
|
<commit_before>// Copyright (C) 2005 John Gibson. See ``LICENSE'' for the license to this
// software and for a DISCLAIMER OF ALL WARRANTIES.
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <ugens.h> // for octpch and ampdb
#include <Ougens.h> // for Ooscil
#include "grainstream.h"
#include "grainvoice.h"
#include <assert.h>
#define DEBUG 0
//#define NDEBUG // disable asserts
#define ALL_VOICES_IN_USE -1
#define COUNT_VOICES
inline int _clamp(const int min, const int val, const int max)
{
if (val < min)
return min;
if (val > max)
return max;
return val;
}
// NOTE: We don't own the table memory.
GrainStream::GrainStream(const float srate, double *inputTable, int tableLen,
const int numInChans, const int numOutChans, const bool preserveGrainDur,
const int seed, const bool use3rdOrderInterp)
: _srate(srate), _inputtab(inputTable), _inputframes(tableLen / numInChans),
_outchans(numOutChans), _inchan(0), _winstart(-1), _winend(_inputframes),
_wrap(true), _inhop(0), _outhop(0), _maxinjitter(0.0), _maxoutjitter(0.0),
_transp(0.0), _maxtranspjitter(0.0), _transptab(NULL), _transplen(0),
_outframecount(0), _nextinstart(0), _nextoutstart(0), _travrate(1.0),
_lasttravrate(1.0), _lastinskip(DBL_MAX), _lastL(0.0f), _lastR(0.0f)
{
for (int i = 0; i < MAX_NUM_VOICES; i++)
_voices[i] = new GrainVoice(_srate, _inputtab, _inputframes, numInChans,
numOutChans, preserveGrainDur, use3rdOrderInterp);
_inrand = new LinearRandom(0.0, 1.0, seed);
_outrand = new LinearRandom(0.0, 1.0, seed * 2);
_durrand = new LinearRandom(0.0, 1.0, seed * 3);
_amprand = new LinearRandom(0.0, 1.0, seed * 4);
_transprand = new LinearRandom(0.0, 1.0, seed * 5);
_panrand = new LinearRandom(0.0, 1.0, seed * 6);
#ifdef COUNT_VOICES
_maxvoice = -1;
#endif
}
GrainStream::~GrainStream()
{
for (int i = 0; i < MAX_NUM_VOICES; i++)
delete _voices[i];
delete [] _transptab;
delete _inrand;
delete _outrand;
delete _durrand;
delete _amprand;
delete _transprand;
delete _panrand;
#ifdef COUNT_VOICES
advise("GRANULATE", "Used %d voices", _maxvoice + 1);
#endif
}
// NOTE: We don't own the table memory.
// Call this before ever calling prepare or processBlock.
void GrainStream::setGrainEnvelopeTable(double *table, int length)
{
for (int i = 0; i < MAX_NUM_VOICES; i++)
_voices[i]->setGrainEnvelopeTable(table, length);
}
// Set inskip, overriding current position, which results from the traversal
// rate. It's so important not to do this if the requested inskip hasn't
// changed that we do that checking here, rather than asking the caller to.
// Call setInskip just after calling setWindow.
void GrainStream::setInskip(const double inskip)
{
if (inskip != _lastinskip) {
_nextinstart = int((inskip * _srate) + 0.5);
_nextinstart = _clamp(_winstart, _nextinstart, _winend);
_lastinskip = inskip;
}
}
// Set input start and end point in frames. If this is the first time we're
// called, force next call to prepare or processBlock to start playing at
// start point. Otherwise, we'll come back to new start point at wraparound.
void GrainStream::setWindow(const double start, const double end)
{
const bool firsttime = (_winstart == -1);
_winstart = int((start * _srate) + 0.5);
_winend = int((end * _srate) + 0.5);
if (_winend < _winstart) {
int tmp = _winstart;
_winstart = _winend;
_winend = tmp;
}
if (_winstart < 0)
_winstart = 0;
if (firsttime)
_nextinstart = _winstart;
// NOTE: _winend is the last frame we use (not one past the last frame)
if (_winend >= _inputframes)
_winend = _inputframes - 1;
}
// Set both the input traversal rate and the output grain hop. Here are some
// possible values for <rate>, along with their interpretation.
//
// 0 no movement
// 1 move forward at normal rate (i.e., as fast as we hop through output)
// 2.5 move forward at a rate that is 2.5 times normal
// -1 move backward at normal rate
//
// <hop> is the number of seconds to skip on the output before starting a
// new grain. We add jitter to this amount in maybeStartGrain().
void GrainStream::setTraversalRateAndGrainHop(const double rate,
const double hop)
{
const double hopframes = hop * _srate;
_outhop = int(hopframes + 0.5);
if (rate < 0.0)
_inhop = int((hopframes * rate) - 0.5);
else
_inhop = int((hopframes * rate) + 0.5);
_travrate = rate;
#if DEBUG > 3
printf("inhop=%d, outhop=%d\n", _inhop, _outhop);
#endif
}
void GrainStream::setGrainTranspositionCollection(double *table, int length)
{
delete [] _transptab;
if (table) {
_transptab = new double [length];
for (int i = 0; i < length; i++)
_transptab[i] = octpch(table[i]);
_transplen = length;
_transprand->setmin(0.0);
}
else {
_transptab = NULL;
_transplen = 0;
}
}
// Given _transp and (possibly) _transptab, both in linear octaves, return
// grain transposition value in linear octaves.
const double GrainStream::getTransposition()
{
double transp = _transp;
const double transpjitter = (_maxtranspjitter == 0.0) ? 0.0
: _transprand->value();
if (_transptab) {
// Constrain <transpjitter> to nearest member of transposition collection.
double min = DBL_MAX;
int closest = 0;
for (int i = 0; i < _transplen; i++) {
const double proximity = fabs(_transptab[i] - transpjitter);
if (proximity < min) {
min = proximity;
closest = i;
}
#if DEBUG > 2
printf("transtab[%d]=%f, jitter=%f, proximity=%f, min=%f\n",
i, _transptab[i], transpjitter, proximity, min);
#endif
}
transp += _transptab[closest];
#if DEBUG > 1
printf("transpcoll chosen: %f (linoct) at index %d\n",
_transptab[closest], closest);
#endif
}
else {
transp += transpjitter;
#if DEBUG > 1
printf("transp (linoct): %f\n", transp);
#endif
}
return transp;
}
// Return index of first freq grain voice, or -1 if none are free.
const int GrainStream::firstFreeVoice()
{
for (int i = 0; i < MAX_NUM_VOICES; i++) {
if (_voices[i]->inUse() == false)
return i;
}
return ALL_VOICES_IN_USE;
}
// Decide whether to (re)initialize a grain.
// <bufoutstart> is the offset into the output buffer for the grain to start.
// This is relevant only when using block I/O.
bool GrainStream::maybeStartGrain(const int bufoutstart)
{
bool keepgoing = true;
if (_outframecount >= _nextoutstart) { // time to start another grain
bool forwards = (_travrate >= 0.0);
// When grain traversal changes sign, we need to adjust _nextinstart,
// because this is interpreted differently for the two directions.
// When moving forward, it's the lowest index we read for the grain;
// when moving backward, it's the highest.
int inoffset = 0;
if (_travrate != _lasttravrate) {
if (_travrate < 0.0 && _lasttravrate >= 0.0)
inoffset = 1; // add grain duration to _nextinstart below
else if (_lasttravrate <= 0.0 && _travrate > 0.0)
inoffset = -1; // subtract grain duration from _nextinstart below
_lasttravrate = _travrate;
}
const int voice = firstFreeVoice();
if (voice != ALL_VOICES_IN_USE) {
#ifdef COUNT_VOICES
if (voice > _maxvoice)
_maxvoice = voice;
#endif
const double outdur = _durrand->value();
// Try to prevent glitch when traversal rate crosses zero.
if (inoffset != 0) {
inoffset *= int((outdur * _srate) + 0.5);
_nextinstart += inoffset;
_nextinstart = _clamp(0, _nextinstart, _inputframes - 1);
}
const double amp = _amprand->value();
const double pan = _outchans > 1 ? _panrand->value() : 1.0;
const double transp = getTransposition();
if (outdur >= 0.0)
_voices[voice]->startGrain(bufoutstart, _nextinstart, outdur,
_inchan, amp, transp, pan, forwards);
}
const int injitter = (_maxinjitter == 0.0) ? 0
: int(_inrand->value() * _srate);
_nextinstart += _inhop + injitter;
// NB: injitter and _inhop can be negative.
if (forwards) {
if (_nextinstart < _winstart)
_nextinstart = _winstart;
const int overshoot = _nextinstart - _winend;
if (overshoot >= 0) {
if (_wrap)
_nextinstart = _winstart + overshoot;
else
keepgoing = false;
#if DEBUG > 0
printf("wrap to beginning... nextinstart=%d, overshoot=%d\n",
_nextinstart, overshoot);
#endif
}
}
else {
if (_nextinstart > _winend)
_nextinstart = _winend;
const int overshoot = _winstart - _nextinstart;
if (overshoot >= 0) {
if (_wrap)
_nextinstart = _winend - overshoot;
else
keepgoing = false;
#if DEBUG > 0
printf("wrap to ending... nextinstart=%d, overshoot=%d\n",
_nextinstart, overshoot);
#endif
}
}
const int outjitter = (_maxoutjitter == 0.0) ? 0
: int(_outrand->value() * _srate);
// NB: outjitter can be negative, so we must ensure that _nextoutstart
// will not be less than the next _outframecount.
_nextoutstart = _outframecount + _outhop + outjitter;
if (_nextoutstart <= _outframecount)
_nextoutstart = _outframecount + 1;
}
return keepgoing;
}
// Called for single-frame I/O.
void GrainStream::playGrains()
{
_lastL = 0.0f;
_lastR = 0.0f;
for (int i = 0; i < MAX_NUM_VOICES; i++) {
if (_voices[i]->inUse()) {
float sigL, sigR;
_voices[i]->next(sigL, sigR);
_lastL += sigL;
_lastR += sigR;
}
}
}
// Called for block I/O.
void GrainStream::playGrains(float buffer[], const int numFrames,
const float amp)
{
const int count = numFrames * _outchans;
for (int i = 0; i < count; i++)
buffer[i] = 0.0f;
for (int i = 0; i < MAX_NUM_VOICES; i++)
if (_voices[i]->inUse())
_voices[i]->next(buffer, numFrames, amp);
}
// Compute one frame of samples across all active grains. Activate a
// new grain if it's time. Return false if caller should terminate
// prematurely, due to running out of input when not using wraparound mode;
// otherwise return true.
bool GrainStream::prepare()
{
bool keepgoing = maybeStartGrain();
playGrains();
_outframecount++;
return keepgoing;
}
// Compute a block of samples and write them into <buffer>, which is
// assumed to hold <numFrames> frames of <_outchans> chans.
bool GrainStream::processBlock(float *buffer, const int numFrames,
const float amp)
{
bool keepgoing = true;
for (int i = 0; i < numFrames; i++) {
keepgoing = maybeStartGrain(i);
_outframecount++;
if (!keepgoing)
break;
}
playGrains(buffer, numFrames, amp);
return keepgoing;
}
<commit_msg>Additional range checking.<commit_after>// Copyright (C) 2005 John Gibson. See ``LICENSE'' for the license to this
// software and for a DISCLAIMER OF ALL WARRANTIES.
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <ugens.h> // for octpch and ampdb
#include <Ougens.h> // for Ooscil
#include "grainstream.h"
#include "grainvoice.h"
#include <assert.h>
#define DEBUG 0
//#define NDEBUG // disable asserts
#define ALL_VOICES_IN_USE -1
#define COUNT_VOICES
inline int _clamp(const int min, const int val, const int max)
{
if (val < min)
return min;
if (val > max)
return max;
return val;
}
// NOTE: We don't own the table memory.
GrainStream::GrainStream(const float srate, double *inputTable, int tableLen,
const int numInChans, const int numOutChans, const bool preserveGrainDur,
const int seed, const bool use3rdOrderInterp)
: _srate(srate), _inputtab(inputTable), _inputframes(tableLen / numInChans),
_outchans(numOutChans), _inchan(0), _winstart(-1), _winend(_inputframes),
_wrap(true), _inhop(0), _outhop(0), _maxinjitter(0.0), _maxoutjitter(0.0),
_transp(0.0), _maxtranspjitter(0.0), _transptab(NULL), _transplen(0),
_outframecount(0), _nextinstart(0), _nextoutstart(0), _travrate(1.0),
_lasttravrate(1.0), _lastinskip(DBL_MAX), _lastL(0.0f), _lastR(0.0f)
{
for (int i = 0; i < MAX_NUM_VOICES; i++)
_voices[i] = new GrainVoice(_srate, _inputtab, _inputframes, numInChans,
numOutChans, preserveGrainDur, use3rdOrderInterp);
_inrand = new LinearRandom(0.0, 1.0, seed);
_outrand = new LinearRandom(0.0, 1.0, seed * 2);
_durrand = new LinearRandom(0.0, 1.0, seed * 3);
_amprand = new LinearRandom(0.0, 1.0, seed * 4);
_transprand = new LinearRandom(0.0, 1.0, seed * 5);
_panrand = new LinearRandom(0.0, 1.0, seed * 6);
#ifdef COUNT_VOICES
_maxvoice = -1;
#endif
}
GrainStream::~GrainStream()
{
for (int i = 0; i < MAX_NUM_VOICES; i++)
delete _voices[i];
delete [] _transptab;
delete _inrand;
delete _outrand;
delete _durrand;
delete _amprand;
delete _transprand;
delete _panrand;
#ifdef COUNT_VOICES
advise("GRANULATE", "Used %d voices", _maxvoice + 1);
#endif
}
// NOTE: We don't own the table memory.
// Call this before ever calling prepare or processBlock.
void GrainStream::setGrainEnvelopeTable(double *table, int length)
{
for (int i = 0; i < MAX_NUM_VOICES; i++)
_voices[i]->setGrainEnvelopeTable(table, length);
}
// Set inskip, overriding current position, which results from the traversal
// rate. It's so important not to do this if the requested inskip hasn't
// changed that we do that checking here, rather than asking the caller to.
// Call setInskip just after calling setWindow.
void GrainStream::setInskip(const double inskip)
{
if (inskip != _lastinskip) {
_nextinstart = int((inskip * _srate) + 0.5);
_nextinstart = _clamp(_winstart, _nextinstart, _winend);
_lastinskip = inskip;
}
}
// Set input start and end point in frames. If this is the first time we're
// called, force next call to prepare or processBlock to start playing at
// start point. Otherwise, we'll come back to new start point at wraparound.
void GrainStream::setWindow(const double start, const double end)
{
const bool firsttime = (_winstart == -1);
_winstart = int((start * _srate) + 0.5);
_winend = int((end * _srate) + 0.5);
if (_winend < _winstart) {
int tmp = _winstart;
_winstart = _winend;
_winend = tmp;
}
if (_winstart < 0)
_winstart = 0;
if (firsttime)
_nextinstart = _winstart;
// NOTE: _winend is the last frame we use (not one past the last frame)
if (_winend >= _inputframes)
_winend = _inputframes - 1;
}
// Set both the input traversal rate and the output grain hop. Here are some
// possible values for <rate>, along with their interpretation.
//
// 0 no movement
// 1 move forward at normal rate (i.e., as fast as we hop through output)
// 2.5 move forward at a rate that is 2.5 times normal
// -1 move backward at normal rate
//
// <hop> is the number of seconds to skip on the output before starting a
// new grain. We add jitter to this amount in maybeStartGrain().
void GrainStream::setTraversalRateAndGrainHop(const double rate,
const double hop)
{
const double hopframes = hop * _srate;
_outhop = int(hopframes + 0.5);
if (rate < 0.0)
_inhop = int((hopframes * rate) - 0.5);
else
_inhop = int((hopframes * rate) + 0.5);
_travrate = rate;
#if DEBUG > 3
printf("inhop=%d, outhop=%d\n", _inhop, _outhop);
#endif
}
void GrainStream::setGrainTranspositionCollection(double *table, int length)
{
delete [] _transptab;
if (table) {
_transptab = new double [length];
for (int i = 0; i < length; i++)
_transptab[i] = octpch(table[i]);
_transplen = length;
_transprand->setmin(0.0);
}
else {
_transptab = NULL;
_transplen = 0;
}
}
// Given _transp and (possibly) _transptab, both in linear octaves, return
// grain transposition value in linear octaves.
const double GrainStream::getTransposition()
{
double transp = _transp;
const double transpjitter = (_maxtranspjitter == 0.0) ? 0.0
: _transprand->value();
if (_transptab) {
// Constrain <transpjitter> to nearest member of transposition collection.
double min = DBL_MAX;
int closest = 0;
for (int i = 0; i < _transplen; i++) {
const double proximity = fabs(_transptab[i] - transpjitter);
if (proximity < min) {
min = proximity;
closest = i;
}
#if DEBUG > 2
printf("transtab[%d]=%f, jitter=%f, proximity=%f, min=%f\n",
i, _transptab[i], transpjitter, proximity, min);
#endif
}
transp += _transptab[closest];
#if DEBUG > 1
printf("transpcoll chosen: %f (linoct) at index %d\n",
_transptab[closest], closest);
#endif
}
else {
transp += transpjitter;
#if DEBUG > 1
printf("transp (linoct): %f\n", transp);
#endif
}
return transp;
}
// Return index of first freq grain voice, or -1 if none are free.
const int GrainStream::firstFreeVoice()
{
for (int i = 0; i < MAX_NUM_VOICES; i++) {
if (_voices[i]->inUse() == false)
return i;
}
return ALL_VOICES_IN_USE;
}
// Decide whether to (re)initialize a grain.
// <bufoutstart> is the offset into the output buffer for the grain to start.
// This is relevant only when using block I/O.
bool GrainStream::maybeStartGrain(const int bufoutstart)
{
bool keepgoing = true;
if (_outframecount >= _nextoutstart) { // time to start another grain
bool forwards = (_travrate >= 0.0);
// When grain traversal changes sign, we need to adjust _nextinstart,
// because this is interpreted differently for the two directions.
// When moving forward, it's the lowest index we read for the grain;
// when moving backward, it's the highest.
int inoffset = 0;
if (_travrate != _lasttravrate) {
if (_travrate < 0.0 && _lasttravrate >= 0.0)
inoffset = 1; // add grain duration to _nextinstart below
else if (_lasttravrate <= 0.0 && _travrate > 0.0)
inoffset = -1; // subtract grain duration from _nextinstart below
_lasttravrate = _travrate;
}
const int voice = firstFreeVoice();
if (voice != ALL_VOICES_IN_USE) {
#ifdef COUNT_VOICES
if (voice > _maxvoice)
_maxvoice = voice;
#endif
const double outdur = _durrand->value();
// Try to prevent glitch when traversal rate crosses zero.
if (inoffset != 0) {
inoffset *= int((outdur * _srate) + 0.5);
_nextinstart += inoffset;
_nextinstart = _clamp(0, _nextinstart, _inputframes - 1);
}
const double amp = _amprand->value();
const double pan = _outchans > 1 ? _panrand->value() : 1.0;
const double transp = getTransposition();
if (outdur >= 0.0)
_voices[voice]->startGrain(bufoutstart, _nextinstart, outdur,
_inchan, amp, transp, pan, forwards);
}
const int injitter = (_maxinjitter == 0.0) ? 0
: int(_inrand->value() * _srate);
_nextinstart += _inhop + injitter;
// NB: injitter and _inhop can be negative.
if (forwards) {
if (_nextinstart < _winstart)
_nextinstart = _winstart;
const int overshoot = _nextinstart - _winend;
if (overshoot >= 0) {
if (_wrap) {
_nextinstart = _winstart + overshoot;
if (_nextinstart > _winend)
_nextinstart = _winend;
}
else
keepgoing = false;
#if DEBUG > 0
printf("wrap to beginning... nextinstart=%d, overshoot=%d\n",
_nextinstart, overshoot);
#endif
}
}
else {
if (_nextinstart > _winend)
_nextinstart = _winend;
const int overshoot = _winstart - _nextinstart;
if (overshoot >= 0) {
if (_wrap) {
_nextinstart = _winend - overshoot;
if (_nextinstart < _winstart)
_nextinstart = _winstart;
}
else
keepgoing = false;
#if DEBUG > 0
printf("wrap to ending... nextinstart=%d, overshoot=%d\n",
_nextinstart, overshoot);
#endif
}
}
const int outjitter = (_maxoutjitter == 0.0) ? 0
: int(_outrand->value() * _srate);
// NB: outjitter can be negative, so we must ensure that _nextoutstart
// will not be less than the next _outframecount.
_nextoutstart = _outframecount + _outhop + outjitter;
if (_nextoutstart <= _outframecount)
_nextoutstart = _outframecount + 1;
}
return keepgoing;
}
// Called for single-frame I/O.
void GrainStream::playGrains()
{
_lastL = 0.0f;
_lastR = 0.0f;
for (int i = 0; i < MAX_NUM_VOICES; i++) {
if (_voices[i]->inUse()) {
float sigL, sigR;
_voices[i]->next(sigL, sigR);
_lastL += sigL;
_lastR += sigR;
}
}
}
// Called for block I/O.
void GrainStream::playGrains(float buffer[], const int numFrames,
const float amp)
{
const int count = numFrames * _outchans;
for (int i = 0; i < count; i++)
buffer[i] = 0.0f;
for (int i = 0; i < MAX_NUM_VOICES; i++)
if (_voices[i]->inUse())
_voices[i]->next(buffer, numFrames, amp);
}
// Compute one frame of samples across all active grains. Activate a
// new grain if it's time. Return false if caller should terminate
// prematurely, due to running out of input when not using wraparound mode;
// otherwise return true.
bool GrainStream::prepare()
{
bool keepgoing = maybeStartGrain();
playGrains();
_outframecount++;
return keepgoing;
}
// Compute a block of samples and write them into <buffer>, which is
// assumed to hold <numFrames> frames of <_outchans> chans.
bool GrainStream::processBlock(float *buffer, const int numFrames,
const float amp)
{
bool keepgoing = true;
for (int i = 0; i < numFrames; i++) {
keepgoing = maybeStartGrain(i);
_outframecount++;
if (!keepgoing)
break;
}
playGrains(buffer, numFrames, amp);
return keepgoing;
}
<|endoftext|>
|
<commit_before>#include <algorithm>
#include <core_pins.h>
#include "StepControl.h"
#include "TeensyDelay/TeensyDelay.h"
//#include "HardwareSerial.h"
//
//void StepControl::move(Stepper& stepper1, Stepper& stepper2)
//{
// moveAsync(stepper1, stepper2);
// while (isRunning()) {
// delay(10);
// }
//}
//
//void StepControl::move(Stepper& stepper1, Stepper& stepper2, Stepper& stepper3)
//{
// moveAsync(stepper1, stepper2, stepper3);
// while (isRunning()) {
// delay(10);
// }
//}
<commit_msg>Update StepControl.cpp<commit_after>
<|endoftext|>
|
<commit_before>inline void Density::generate_valence(K_point_set& ks__)
{
PROFILE("sirius::Density::generate_valence");
double wt{0};
double occ_val{0};
for (int ik = 0; ik < ks__.num_kpoints(); ik++) {
wt += ks__[ik]->weight();
for (int j = 0; j < ctx_.num_bands(); j++) {
occ_val += ks__[ik]->weight() * ks__[ik]->band_occupancy(j);
}
}
if (std::abs(wt - 1.0) > 1e-12) {
std::stringstream s;
s << "K_point weights don't sum to one" << std::endl
<< " obtained sum: " << wt;
TERMINATE(s);
}
if (std::abs(occ_val - unit_cell_.num_valence_electrons()) > 1e-8) {
std::stringstream s;
s << "wrong band occupancies" << std::endl
<< " computed : " << occ_val << std::endl
<< " required : " << unit_cell_.num_valence_electrons() << std::endl
<< " difference : " << std::abs(occ_val - unit_cell_.num_valence_electrons());
WARNING(s);
}
density_matrix_.zero();
/* zero density and magnetization */
zero();
for (int i = 0; i < ctx_.num_mag_dims() + 1; i++) {
rho_mag_coarse_[i]->zero();
}
/* start the main loop over k-points */
for (int ikloc = 0; ikloc < ks__.spl_num_kpoints().local_size(); ikloc++) {
int ik = ks__.spl_num_kpoints(ikloc);
auto kp = ks__[ik];
for (int ispn = 0; ispn < ctx_.num_spins(); ispn++) {
int nbnd = kp->num_occupied_bands(ispn);
#ifdef __GPU
if (ctx_.processing_unit() == GPU && !keep_wf_on_gpu) {
/* allocate GPU memory */
kp->spinor_wave_functions(ispn).pw_coeffs().prime().allocate(memory_t::device);
kp->spinor_wave_functions(ispn).pw_coeffs().copy_to_device(0, nbnd);
}
#endif
/* swap wave functions */
//kp->spinor_wave_functions(ispn).pw_coeffs().remap_forward(ctx_.processing_unit(), kp->gkvec().partition().gvec_fft_slab(), nbnd);
kp->spinor_wave_functions(ispn).pw_coeffs().remap_forward(CPU, kp->gkvec().partition().gvec_fft_slab(), nbnd);
}
if (ctx_.esm_type() == electronic_structure_method_t::full_potential_lapwlo) {
add_k_point_contribution_dm<double_complex>(kp, density_matrix_);
}
if (ctx_.esm_type() == electronic_structure_method_t::pseudopotential) {
if (ctx_.gamma_point() && (ctx_.so_correction() == false)) {
add_k_point_contribution_dm<double>(kp, density_matrix_);
} else {
add_k_point_contribution_dm<double_complex>(kp, density_matrix_);
}
}
/* add contribution from regular space grid */
add_k_point_contribution_rg(kp);
#ifdef __GPU
if (ctx_.processing_unit() == GPU && !keep_wf_on_gpu) {
for (int ispn = 0; ispn < ctx_.num_spins(); ispn++) {
/* deallocate GPU memory */
kp->spinor_wave_functions(ispn).pw_coeffs().deallocate_on_device();
}
}
#endif
}
if (density_matrix_.size()) {
ctx_.comm().allreduce(density_matrix_.at<CPU>(), static_cast<int>(density_matrix_.size()));
}
ctx_.fft_coarse().prepare(ctx_.gvec_coarse().partition());
auto& comm = ctx_.gvec_coarse().comm_ortho_fft();
for (int j = 0; j < ctx_.num_mag_dims() + 1; j++) {
/* reduce arrays; assume that each rank did its own fraction of the density */
comm.allreduce(&rho_mag_coarse_[j]->f_rg(0), ctx_.fft_coarse().local_size());
if (ctx_.control().print_checksum_) {
auto cs = mdarray<double, 1>(&rho_mag_coarse_[j]->f_rg(0), ctx_.fft_coarse().local_size()).checksum();
ctx_.fft_coarse().comm().allreduce(&cs, 1);
if (ctx_.comm().rank() == 0) {
DUMP("checksum(rho_mag_coarse_rg) : %18.10f", cs);
}
}
/* transform to PW domain */
rho_mag_coarse_[j]->fft_transform(-1);
/* get the whole vector of PW coefficients */
auto fpw = rho_mag_coarse_[j]->gather_f_pw(); // TODO: reuse FFT G-vec arrays
if (ctx_.control().print_checksum_ && ctx_.comm().rank() == 0) {
auto z1 = mdarray<double_complex, 1>(&fpw[0], ctx_.gvec_coarse().num_gvec()).checksum();
DUMP("checksum(rho_mag_coarse_pw) : %18.10f %18.10f", z1.real(), z1.imag());
}
/* map to fine G-vector grid */
for (int i = 0; i < static_cast<int>(lf_gvec_.size()); i++) {
int igloc = lf_gvec_[i];
int ig = ctx_.gvec_coarse().index_by_gvec(ctx_.gvec().gvec(ctx_.gvec().offset() + igloc));
rho_vec_[j]->f_pw_local(igloc) = fpw[ig];
}
}
ctx_.fft_coarse().dismiss();
if (!ctx_.full_potential()) {
augment(ks__);
double nel = rho_->f_0().real() * unit_cell_.omega();
/* check the number of electrons */
if (std::abs(nel - unit_cell_.num_electrons()) > 1e-8) {
std::stringstream s;
s << "wrong unsymmetrized density" << std::endl
<< " obtained value : " << nel << std::endl
<< " target value : " << unit_cell_.num_electrons() << std::endl
<< " difference : " << std::abs(nel - unit_cell_.num_electrons()) << std::endl;
WARNING(s);
}
}
if (ctx_.esm_type() == electronic_structure_method_t::pseudopotential && ctx_.use_symmetry()) {
symmetrize_density_matrix();
}
/* for muffin-tin part */
if (ctx_.full_potential()) {
generate_valence_mt(ks__);
}
}
<commit_msg>print hash and checksum<commit_after>inline void Density::generate_valence(K_point_set& ks__)
{
PROFILE("sirius::Density::generate_valence");
double wt{0};
double occ_val{0};
for (int ik = 0; ik < ks__.num_kpoints(); ik++) {
wt += ks__[ik]->weight();
for (int j = 0; j < ctx_.num_bands(); j++) {
occ_val += ks__[ik]->weight() * ks__[ik]->band_occupancy(j);
}
}
if (std::abs(wt - 1.0) > 1e-12) {
std::stringstream s;
s << "K_point weights don't sum to one" << std::endl
<< " obtained sum: " << wt;
TERMINATE(s);
}
if (std::abs(occ_val - unit_cell_.num_valence_electrons()) > 1e-8) {
std::stringstream s;
s << "wrong band occupancies" << std::endl
<< " computed : " << occ_val << std::endl
<< " required : " << unit_cell_.num_valence_electrons() << std::endl
<< " difference : " << std::abs(occ_val - unit_cell_.num_valence_electrons());
WARNING(s);
}
density_matrix_.zero();
/* zero density and magnetization */
zero();
for (int i = 0; i < ctx_.num_mag_dims() + 1; i++) {
rho_mag_coarse_[i]->zero();
}
/* start the main loop over k-points */
for (int ikloc = 0; ikloc < ks__.spl_num_kpoints().local_size(); ikloc++) {
int ik = ks__.spl_num_kpoints(ikloc);
auto kp = ks__[ik];
for (int ispn = 0; ispn < ctx_.num_spins(); ispn++) {
int nbnd = kp->num_occupied_bands(ispn);
#ifdef __GPU
if (ctx_.processing_unit() == GPU && !keep_wf_on_gpu) {
/* allocate GPU memory */
kp->spinor_wave_functions(ispn).pw_coeffs().prime().allocate(memory_t::device);
kp->spinor_wave_functions(ispn).pw_coeffs().copy_to_device(0, nbnd);
}
#endif
/* swap wave functions */
//kp->spinor_wave_functions(ispn).pw_coeffs().remap_forward(ctx_.processing_unit(), kp->gkvec().partition().gvec_fft_slab(), nbnd);
kp->spinor_wave_functions(ispn).pw_coeffs().remap_forward(CPU, kp->gkvec().partition().gvec_fft_slab(), nbnd);
}
if (ctx_.esm_type() == electronic_structure_method_t::full_potential_lapwlo) {
add_k_point_contribution_dm<double_complex>(kp, density_matrix_);
}
if (ctx_.esm_type() == electronic_structure_method_t::pseudopotential) {
if (ctx_.gamma_point() && (ctx_.so_correction() == false)) {
add_k_point_contribution_dm<double>(kp, density_matrix_);
} else {
add_k_point_contribution_dm<double_complex>(kp, density_matrix_);
}
}
/* add contribution from regular space grid */
add_k_point_contribution_rg(kp);
#ifdef __GPU
if (ctx_.processing_unit() == GPU && !keep_wf_on_gpu) {
for (int ispn = 0; ispn < ctx_.num_spins(); ispn++) {
/* deallocate GPU memory */
kp->spinor_wave_functions(ispn).pw_coeffs().deallocate_on_device();
}
}
#endif
}
if (density_matrix_.size()) {
ctx_.comm().allreduce(density_matrix_.at<CPU>(), static_cast<int>(density_matrix_.size()));
}
ctx_.fft_coarse().prepare(ctx_.gvec_coarse().partition());
auto& comm = ctx_.gvec_coarse().comm_ortho_fft();
for (int j = 0; j < ctx_.num_mag_dims() + 1; j++) {
/* reduce arrays; assume that each rank did its own fraction of the density */
comm.allreduce(&rho_mag_coarse_[j]->f_rg(0), ctx_.fft_coarse().local_size());
if (ctx_.control().print_checksum_) {
auto cs = mdarray<double, 1>(&rho_mag_coarse_[j]->f_rg(0), ctx_.fft_coarse().local_size()).checksum();
ctx_.fft_coarse().comm().allreduce(&cs, 1);
if (ctx_.comm().rank() == 0) {
print_checksum("rho_mag_coarse_rg", cs);
}
}
/* transform to PW domain */
rho_mag_coarse_[j]->fft_transform(-1);
/* get the whole vector of PW coefficients */
auto fpw = rho_mag_coarse_[j]->gather_f_pw(); // TODO: reuse FFT G-vec arrays
/* print checksum */
if (ctx_.control().print_checksum_ && ctx_.comm().rank() == 0) {
auto z1 = mdarray<double_complex, 1>(&fpw[0], ctx_.gvec_coarse().num_gvec()).checksum();
print_checksum("rho_mag_coarse_pw", z1);
}
/* print hash */
if (ctx_.control().print_hash_ && ctx_.comm().rank() == 0) {
auto h = mdarray<double_complex, 1>(&fpw[0], ctx_.gvec_coarse().num_gvec()).hash();
print_hash("rho_mag_coarse_pw", h);
}
/* map to fine G-vector grid */
for (int i = 0; i < static_cast<int>(lf_gvec_.size()); i++) {
int igloc = lf_gvec_[i];
int ig = ctx_.gvec_coarse().index_by_gvec(ctx_.gvec().gvec(ctx_.gvec().offset() + igloc));
rho_vec_[j]->f_pw_local(igloc) = fpw[ig];
}
}
ctx_.fft_coarse().dismiss();
if (!ctx_.full_potential()) {
augment(ks__);
if (ctx_.control().print_hash_ && ctx_.comm().rank() == 0) {
auto h = mdarray<double_complex, 1>(&rho_->f_pw_local(0), ctx_.gvec().count()).hash();
print_hash("rho", h);
}
double nel = rho_->f_0().real() * unit_cell_.omega();
/* check the number of electrons */
if (std::abs(nel - unit_cell_.num_electrons()) > 1e-8) {
std::stringstream s;
s << "wrong unsymmetrized density" << std::endl
<< " obtained value : " << nel << std::endl
<< " target value : " << unit_cell_.num_electrons() << std::endl
<< " difference : " << std::abs(nel - unit_cell_.num_electrons()) << std::endl;
WARNING(s);
}
}
if (ctx_.esm_type() == electronic_structure_method_t::pseudopotential && ctx_.use_symmetry()) {
symmetrize_density_matrix();
}
/* for muffin-tin part */
if (ctx_.full_potential()) {
generate_valence_mt(ks__);
}
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
///
/// \file single_threaded.hpp
/// -------------------------
///
/// (c) Copyright Domagoj Saric 2019.
///
/// Use, modification and distribution are subject to the
/// Boost Software License, Version 1.0. (See accompanying file
/// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
///
/// See http://www.boost.org for most recent version.
///
////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------
#pragma once
#include "../hardware_concurrency.hpp"
#include <boost/core/no_exceptions_support.hpp>
#include <cstdint>
#include <future>
#include <thread>
#include <utility>
//------------------------------------------------------------------------------
namespace boost
{
//------------------------------------------------------------------------------
namespace sweater
{
//------------------------------------------------------------------------------
namespace single_threaded
{
//------------------------------------------------------------------------------
class shop
{
public:
using iterations_t = std::uint32_t;
constexpr shop() noexcept {}
static constexpr hardware_concurrency_t number_of_workers() noexcept { return 1; }
template <typename F>
void spread_the_sweat( iterations_t const iterations, F && __restrict work ) noexcept( noexcept( std::declval< F >()( 0, 42 ) ) )
{
work( 0, iterations );
}
template <typename F>
static void fire_and_forget( F && work )
{
# if defined( __EMSCRIPTEN__ ) && !defined( __EMSCRIPTEN_PTHREADS__ )
work();
# else
std::thread( std::forward<F>( work ) ).detach();
# endif
}
template <typename F>
static auto dispatch( F && work )
{
# if defined( __EMSCRIPTEN__ ) && !defined( __EMSCRIPTEN_PTHREADS__ )
using result_t = typename std::result_of<F()>::type;
std::promise< result_t > promise;
std::future < result_t > future( promise.get_future() );
fire_and_forget
(
[promise = std::move( promise ), work = std::forward<F>( work )]
() mutable noexcept
{
BOOST_TRY
{
if constexpr ( std::is_same_v<result_t, void> )
{
work();
promise.set_value();
}
else
{
promise.set_value( work() );
}
}
BOOST_CATCH( ... )
{
promise.set_exception( std::current_exception() );
}
BOOST_CATCH_END
}
);
return future;
# else
return std::async( std::launch::async | std::launch::deferred, std::forward<F>( work ) );
# endif
}
}; // class shop
//------------------------------------------------------------------------------
} // namespace single_threaded
//------------------------------------------------------------------------------
} // namespace sweater
//------------------------------------------------------------------------------
} // namespace boost
//------------------------------------------------------------------------------
<commit_msg>fix implicit cast error on some compilers<commit_after>////////////////////////////////////////////////////////////////////////////////
///
/// \file single_threaded.hpp
/// -------------------------
///
/// (c) Copyright Domagoj Saric 2019.
///
/// Use, modification and distribution are subject to the
/// Boost Software License, Version 1.0. (See accompanying file
/// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
///
/// See http://www.boost.org for most recent version.
///
////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------
#pragma once
#include "../hardware_concurrency.hpp"
#include <boost/core/no_exceptions_support.hpp>
#include <cstdint>
#include <future>
#include <thread>
#include <utility>
//------------------------------------------------------------------------------
namespace boost
{
//------------------------------------------------------------------------------
namespace sweater
{
//------------------------------------------------------------------------------
namespace single_threaded
{
//------------------------------------------------------------------------------
class shop
{
public:
using iterations_t = std::uint32_t;
constexpr shop() noexcept {}
static constexpr hardware_concurrency_t number_of_workers() noexcept { return 1; }
template <typename F>
void spread_the_sweat( iterations_t const iterations, F && __restrict work ) noexcept( noexcept( std::declval< F >()( 0, 42 ) ) )
{
work( static_cast< iterations_t >( 0 ), iterations );
}
template <typename F>
static void fire_and_forget( F && work )
{
# if defined( __EMSCRIPTEN__ ) && !defined( __EMSCRIPTEN_PTHREADS__ )
work();
# else
std::thread( std::forward<F>( work ) ).detach();
# endif
}
template <typename F>
static auto dispatch( F && work )
{
# if defined( __EMSCRIPTEN__ ) && !defined( __EMSCRIPTEN_PTHREADS__ )
using result_t = typename std::result_of<F()>::type;
std::promise< result_t > promise;
std::future < result_t > future( promise.get_future() );
fire_and_forget
(
[promise = std::move( promise ), work = std::forward<F>( work )]
() mutable noexcept
{
BOOST_TRY
{
if constexpr ( std::is_same_v<result_t, void> )
{
work();
promise.set_value();
}
else
{
promise.set_value( work() );
}
}
BOOST_CATCH( ... )
{
promise.set_exception( std::current_exception() );
}
BOOST_CATCH_END
}
);
return future;
# else
return std::async( std::launch::async | std::launch::deferred, std::forward<F>( work ) );
# endif
}
}; // class shop
//------------------------------------------------------------------------------
} // namespace single_threaded
//------------------------------------------------------------------------------
} // namespace sweater
//------------------------------------------------------------------------------
} // namespace boost
//------------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>#ifndef DUNE_STUFF_COMMON_PARAMETER_TREE_HH
#define DUNE_STUFF_COMMON_PARAMETER_TREE_HH
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#else
#include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG
#include <cstring>
#include <sstream>
#include <vector>
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>
#include <dune/common/exceptions.hh>
#include <dune/common/parametertreeparser.hh>
#include <dune/stuff/common/string.hh>
namespace Dune {
namespace Stuff {
namespace Common {
//! ParameterTree extension for nicer output
//! \todo TODO The report method should go into dune-common
class ParameterTreeX
: public Dune::ParameterTree {
public:
typedef Dune::ParameterTree BaseType;
ParameterTreeX()
{}
ParameterTreeX(int argc, char** argv, std::string filename)
: BaseType(init(argc, argv, filename))
{}
ParameterTreeX(const Dune::ParameterTree& other)
: BaseType(other)
{}
ParameterTreeX& operator=(const Dune::ParameterTree& other)
{
if (this != &other) {
BaseType::operator=(other);
}
return *this;
} // ParameterTreeX& operator=(const Dune::ParameterTree& other)
ParameterTreeX sub(const std::string& _sub) const
{
if (!hasSub(_sub))
DUNE_THROW(Dune::RangeError,
"\nERROR: sub '" << _sub << "' missing in the following Dune::ParameterTree:\n" << reportString(" "));
return ParameterTreeX(BaseType::sub(_sub));
}
void report(std::ostream& stream = std::cout, const std::string& prefix = "") const
{
reportAsSub(stream, prefix, "");
} // void report(std::ostream& stream = std::cout, const std::string& prefix = "") const
std::string reportString(const std::string& prefix = "") const
{
std::stringstream stream;
report(stream, prefix);
return stream.str();
} // std::stringstream reportString(const std::string& prefix = "") const
std::string get(const std::string& _key, const std::string& defaultValue) const
{
if (!BaseType::hasKey(_key))
std::cout << "WARNING: missing key '" << _key << "' is replaced by given default value '" << defaultValue << "'!" << std::endl;
return BaseType::get< std::string >(_key, defaultValue);
}
std::string get(const std::string& _key, const char* defaultValue) const
{
if (!BaseType::hasKey(_key))
std::cout << "WARNING: missing key '" << _key << "' is replaced by given default value '" << defaultValue << "'!" << std::endl;
return BaseType::get< std::string >(_key, defaultValue);
}
int get(const std::string& _key, int defaultValue) const
{
if (!BaseType::hasKey(_key))
std::cout << "WARNING: missing key '" << _key << "' is replaced by given default value '" << defaultValue << "'!" << std::endl;
return BaseType::get< int >(_key, defaultValue);
}
double get(const std::string& _key, double defaultValue) const
{
if (!BaseType::hasKey(_key))
std::cout << "WARNING: missing key '" << _key << "' is replaced by given default value '" << defaultValue << "'!" << std::endl;
return BaseType::get< double >(_key, defaultValue);
}
template< typename T >
T get(const std::string& _key, const T& defaultValue) const
{
if (!BaseType::hasKey(_key))
std::cout << "WARNING: missing key '" << _key << "' is replaced by given default value!" << std::endl;
return BaseType::get< T >(_key, defaultValue);
}
template< class T >
T get(const std::string& _key) const
{
if (!BaseType::hasKey(_key))
DUNE_THROW(Dune::RangeError,
"\nERROR: key '" << _key << "' missing in the following Dune::ParameterTree:\n" << reportString(" "));
return BaseType::get< T >(_key);
}
bool hasVector(const std::string& _key) const
{
if (hasKey(_key)) {
const std::string str = BaseType::get< std::string >(_key, "meaningless_default_value");
if (Dune::Stuff::Common::String::equal(str.substr(0, 1), "[")
&& Dune::Stuff::Common::String::equal(str.substr(str.size() - 1, 1), "]"))
return true;
}
return false;
} // bool hasVector(const std::string& vector) const
template< class T >
std::vector< T > getVector(const std::string& _key, const T& def, const unsigned int minSize) const
{
if (!hasKey(_key)) {
std::cout << "WARNING: missing key '" << _key << "' is replaced by given default value!" << std::endl;
return std::vector< T >(minSize, def);
} else {
const std::string str = BaseType::get(_key, "meaningless_default_value");
if (Dune::Stuff::Common::String::equal(str, "")) {
if (minSize > 0)
std::cout << "WARNING: vector '" << _key << "' was too small (0) and has been enlarged to size " << minSize << "!" << std::endl;
return std::vector< T >(minSize, def);
} else if (str.size() < 3) {
std::vector< T > ret;
ret.push_back(Dune::Stuff::Common::fromString< T >(str));
if (ret.size() < minSize) {
std::cout << "WARNING: vector '" << _key << "' was too small (" << ret.size() << ") and has been enlarged to size " << minSize << "!" << std::endl;
for (unsigned int i = ret.size(); i < minSize; ++i)
ret.push_back(def);
}
return ret;
} else {
// the dune parametertree strips any leading and trailing whitespace
// so we can be sure that the first and last have to be the brackets [] if this is a vector
std::vector< T > ret;
if (Dune::Stuff::Common::String::equal(str.substr(0, 1), "[")
&& Dune::Stuff::Common::String::equal(str.substr(str.size() - 1, 1), "]")) {
std::vector< std::string > tokens;
if (str.size() > 2)
tokens = Dune::Stuff::Common::tokenize< std::string >(str.substr(1, str.size() - 2), ";");
for (unsigned int i = 0; i < tokens.size(); ++i)
ret.push_back(Dune::Stuff::Common::fromString< T >(boost::algorithm::trim_copy(tokens[i])));
for (unsigned int i = ret.size(); i < minSize; ++i)
ret.push_back(def);
} else if (Dune::Stuff::Common::String::equal(str.substr(0, 1), "[")
|| Dune::Stuff::Common::String::equal(str.substr(str.size() - 1, 1), "]")) {
DUNE_THROW(Dune::RangeError, "Vectors have to be of the form '[entry_0; entry_1; ... ]'!");
} else {
ret = std::vector< T >(minSize, Dune::Stuff::Common::fromString< T >(boost::algorithm::trim_copy(str)));
}
return ret;
}
}
} // std::vector< T > getVector(const std::string& key, const T def) const
template< class T >
std::vector< T > getVector(const std::string& _key, const unsigned int minSize) const
{
if (!hasKey(_key)) {
DUNE_THROW(Dune::RangeError,
"\nERROR: key '" << _key << "' missing in the following Dune::ParameterTree:\n" << reportString(" "));
} else {
std::vector< T > ret;
const std::string str = get(_key, "meaningless_default_value");
// the dune parametertree strips any leading and trailing whitespace
// so we can be sure that the first and last have to be the brackets [] if this is a vector
if (Dune::Stuff::Common::String::equal(str.substr(0, 1), "[")
&& Dune::Stuff::Common::String::equal(str.substr(str.size() - 1, 1), "]")) {
const std::vector< std::string > tokens = Dune::Stuff::Common::tokenize< std::string >(str.substr(1, str.size() - 2), ";");
for (unsigned int i = 0; i < tokens.size(); ++i)
ret.push_back(Dune::Stuff::Common::fromString< T >(boost::algorithm::trim_copy(tokens[i])));
} else
DUNE_THROW(Dune::RangeError, "Vectors have to be of the form '[entry_0; entry_1; ... ]'!");
if (ret.size() < minSize)
DUNE_THROW(Dune::RangeError,
"\nERROR: vector '" << _key
<< "' too short (is " << ret.size() << ", should be at least " << minSize
<< ") in the following Dune::ParameterTree :\n" << reportString(" "));
return ret;
}
} // std::vector< T > getVector(const std::string& key, const T def) const
void assertKey(const std::string& _key) const
{
if (!BaseType::hasKey(_key))
DUNE_THROW(Dune::RangeError,
"\nERROR: key '" << _key << "' missing in the following Dune::ParameterTree:\n" << reportString(" "));
}
void assertSub(const std::string& _sub) const
{
if (!BaseType::hasSub(_sub))
DUNE_THROW(Dune::RangeError,
"\nERROR: sub '" << _sub << "' missing in the following Dune::ParameterTree:\n" << reportString(" "));
}
/**
\brief Fills a Dune::ParameterTree given a parameter file or command line arguments.
\param[in] argc
From \c main()
\param[in] argv
From \c main()
\param[out] paramTree
The Dune::ParameterTree that is to be filled.
**/
static ParameterTree init(int argc, char** argv, std::string filename)
{
Dune::ParameterTree paramTree;
if (argc == 1) {
Dune::ParameterTreeParser::readINITree(filename, paramTree);
} else if (argc == 2) {
Dune::ParameterTreeParser::readINITree(argv[1], paramTree);
} else {
Dune::ParameterTreeParser::readOptions(argc, argv, paramTree);
}
if (paramTree.hasKey("paramfile")) {
Dune::ParameterTreeParser::readINITree(paramTree.get< std::string >("paramfile"), paramTree, false);
}
return paramTree;
} // static ParameterTreeX init(...)
private:
void reportAsSub(std::ostream& stream, const std::string& prefix, const std::string& subPath) const
{
for (auto pair : values)
stream << prefix << pair.first << " = " << pair.second << std::endl;
// stream << prefix << pair.first << " = \"" << pair.second << "\"" << std::endl;
for (auto pair : subs) {
ParameterTreeX subTree(pair.second);
if (subTree.getValueKeys().size())
stream << prefix << "[ " << subPath << pair.first << " ]" << std::endl;
subTree.reportAsSub(stream, prefix, subPath + pair.first + ".");
}
} // void report(std::ostream& stream = std::cout, const std::string& prefix = "") const
}; // class ParameterTreeX
//! \todo TODO Remove this!
typedef ParameterTreeX ExtendedParameterTree;
} // namespace Common
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_COMMON_PARAMETER_TREE_HH
<commit_msg>Revert "[common.parameter.tree] renamed ExtendedParameterTree -> ParameterTreeX"<commit_after>#ifndef DUNE_STUFF_COMMON_PARAMETER_TREE_HH
#define DUNE_STUFF_COMMON_PARAMETER_TREE_HH
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#else
#include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG
#include <cstring>
#include <sstream>
#include <vector>
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>
#include <dune/common/exceptions.hh>
#include <dune/common/parametertreeparser.hh>
#include <dune/stuff/common/string.hh>
namespace Dune {
namespace Stuff {
namespace Common {
//! ParameterTree extension for nicer output
//! \todo TODO The report method should go into dune-common
class ExtendedParameterTree
: public Dune::ParameterTree {
public:
typedef Dune::ParameterTree BaseType;
ExtendedParameterTree()
{}
ExtendedParameterTree(int argc, char** argv, std::string filename)
: BaseType(init(argc, argv, filename))
{}
ExtendedParameterTree(const Dune::ParameterTree& other)
: BaseType(other)
{}
ExtendedParameterTree& operator=(const Dune::ParameterTree& other)
{
if (this != &other) {
BaseType::operator=(other);
}
return *this;
} // ExtendedParameterTree& operator=(const Dune::ParameterTree& other)
ExtendedParameterTree sub(const std::string& _sub) const
{
if (!hasSub(_sub))
DUNE_THROW(Dune::RangeError,
"\nError: sub '" << _sub << "' missing in the following Dune::ParameterTree:\n" << reportString(" "));
return ExtendedParameterTree(BaseType::sub(_sub));
}
void report(std::ostream& stream = std::cout, const std::string& prefix = "") const
{
reportAsSub(stream, prefix, "");
} // void report(std::ostream& stream = std::cout, const std::string& prefix = "") const
std::string reportString(const std::string& prefix = "") const
{
std::stringstream stream;
report(stream, prefix);
return stream.str();
} // std::stringstream reportString(const std::string& prefix = "") const
std::string get(const std::string& _key, const std::string& defaultValue) const
{
if (!BaseType::hasKey(_key))
std::cout << "Warning: missing key '" << _key << "' is replaced by given default value '" << defaultValue << "'!";
return BaseType::get< std::string >(_key, defaultValue);
}
std::string get(const std::string& _key, const char* defaultValue) const
{
if (!BaseType::hasKey(_key))
std::cout << "Warning: missing key '" << _key << "' is replaced by given default value '" << defaultValue << "'!";
return BaseType::get< std::string >(_key, defaultValue);
}
int get(const std::string& _key, int defaultValue) const
{
if (!BaseType::hasKey(_key))
std::cout << "Warning: missing key '" << _key << "' is replaced by given default value '" << defaultValue << "'!";
return BaseType::get< int >(_key, defaultValue);
}
double get(const std::string& _key, double defaultValue) const
{
if (!BaseType::hasKey(_key))
std::cout << "Warning: missing key '" << _key << "' is replaced by given default value '" << defaultValue << "'!";
return BaseType::get< double >(_key, defaultValue);
}
template< typename T >
T get(const std::string& _key, const T& defaultValue) const
{
if (!BaseType::hasKey(_key))
std::cout << "Warning: missing key '" << _key << "' is replaced by given default value!";
return BaseType::get< T >(_key, defaultValue);
}
template< class T >
T get(const std::string& _key) const
{
if (!BaseType::hasKey(_key))
DUNE_THROW(Dune::RangeError,
"\nError: key '" << _key << "' missing in the following Dune::ParameterTree:\n" << reportString(" "));
return BaseType::get< T >(_key);
}
bool hasVector(const std::string& _key) const
{
if (hasKey(_key)) {
const std::string str = BaseType::get< std::string >(_key, "meaningless_default_value");
if (Dune::Stuff::Common::String::equal(str.substr(0, 1), "[")
&& Dune::Stuff::Common::String::equal(str.substr(str.size() - 1, 1), "]"))
return true;
}
return false;
} // bool hasVector(const std::string& vector) const
template< class T >
std::vector< T > getVector(const std::string& _key, const T& def, const unsigned int minSize = 1) const
{
if (!hasKey(_key)) {
std::cout << "Warning: missing key '" << _key << "' is replaced by given default value!";
return std::vector< T >(minSize, def);
} else {
std::vector< T > ret;
const std::string str = get(_key, "meaningless_default_value");
// the dune parametertree strips any leading and trailing whitespace
// so we can be sure that the first and last have to be the brackets [] if this is a vector
if (Dune::Stuff::Common::String::equal(str.substr(0, 1), "[")
&& Dune::Stuff::Common::String::equal(str.substr(str.size() - 1, 1), "]")) {
const std::vector< std::string > tokens = Dune::Stuff::Common::tokenize< std::string >(str.substr(1, str.size() - 2), ";");
for (unsigned int i = 0; i < tokens.size(); ++i)
ret.push_back(Dune::Stuff::Common::fromString< T >(boost::algorithm::trim_copy(tokens[i])));
for (unsigned int i = ret.size(); i < minSize; ++i)
ret.push_back(def);
} else if (Dune::Stuff::Common::String::equal(str.substr(0, 1), "[")
|| Dune::Stuff::Common::String::equal(str.substr(str.size() - 1, 1), "]")) {
DUNE_THROW(Dune::RangeError, "Vectors have to be of the form '[entry_0; entry_1; ... ]'!");
} else {
ret = std::vector< T >(minSize, Dune::Stuff::Common::fromString< T >(boost::algorithm::trim_copy(str)));
}
return ret;
}
} // std::vector< T > getVector(const std::string& key, const T def) const
template< class T >
std::vector< T > getVector(const std::string& _key, const unsigned int desiredSize) const
{
if (!hasKey(_key)) {
DUNE_THROW(Dune::RangeError,
"\nError: key '" << _key << "' missing in the following Dune::ParameterTree:\n" << reportString(" "));
} else {
std::vector< T > ret;
const std::string str = get(_key, "meaningless_default_value");
// the dune parametertree strips any leading and trailing whitespace
// so we can be sure that the first and last have to be the brackets [] if this is a vector
if (Dune::Stuff::Common::String::equal(str.substr(0, 1), "[")
&& Dune::Stuff::Common::String::equal(str.substr(str.size() - 1, 1), "]")) {
const std::vector< std::string > tokens = Dune::Stuff::Common::tokenize< std::string >(str.substr(1, str.size() - 2), ";");
for (unsigned int i = 0; i < tokens.size(); ++i)
ret.push_back(Dune::Stuff::Common::fromString< T >(boost::algorithm::trim_copy(tokens[i])));
} else
DUNE_THROW(Dune::RangeError, "Vectors have to be of the form '[entry_0; entry_1; ... ]'!");
if (ret.size() != desiredSize)
DUNE_THROW(Dune::RangeError,
"\nError: vector '" << _key
<< "' does not have the desired size (is " << ret.size() << ", should be " << desiredSize
<< ") in the following Dune::ParameterTree :\n" << reportString(" "));
return ret;
}
} // std::vector< T > getVector(const std::string& key, const T def) const
void assertKey(const std::string& _key) const
{
if (!BaseType::hasKey(_key))
DUNE_THROW(Dune::RangeError,
"\nError: key '" << _key << "' missing in the following Dune::ParameterTree:\n" << reportString(" "));
}
void assertSub(const std::string& _sub) const
{
if (!BaseType::hasSub(_sub))
DUNE_THROW(Dune::RangeError,
"\nError: sub '" << _sub << "' missing in the following Dune::ParameterTree:\n" << reportString(" "));
}
/**
\brief Fills a Dune::ParameterTree given a parameter file or command line arguments.
\param[in] argc
From \c main()
\param[in] argv
From \c main()
\param[out] paramTree
The Dune::ParameterTree that is to be filled.
**/
static ParameterTree init(int argc, char** argv, std::string filename)
{
Dune::ParameterTree paramTree;
if (argc == 1) {
Dune::ParameterTreeParser::readINITree(filename, paramTree);
} else if (argc == 2) {
Dune::ParameterTreeParser::readINITree(argv[1], paramTree);
} else {
Dune::ParameterTreeParser::readOptions(argc, argv, paramTree);
}
if (paramTree.hasKey("paramfile")) {
Dune::ParameterTreeParser::readINITree(paramTree.get< std::string >("paramfile"), paramTree, false);
}
return paramTree;
} // static ExtendedParameterTree init(...)
private:
void reportAsSub(std::ostream& stream, const std::string& prefix, const std::string& subPath) const
{
for (auto pair : values)
stream << prefix << pair.first << " = " << pair.second << std::endl;
// stream << prefix << pair.first << " = \"" << pair.second << "\"" << std::endl;
for (auto pair : subs) {
ExtendedParameterTree subTree(pair.second);
if (subTree.getValueKeys().size())
stream << prefix << "[ " << subPath << pair.first << " ]" << std::endl;
subTree.reportAsSub(stream, prefix, subPath + pair.first + ".");
}
} // void report(std::ostream& stream = std::cout, const std::string& prefix = "") const
}; // class ExtendedParameterTree
} // namespace Common
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_COMMON_PARAMETER_TREE_HH
<|endoftext|>
|
<commit_before>#ifndef AL_OMNIAPP_H
#define AL_OMNIAPP_H
#include "allocore/al_Allocore.hpp"
#include "allocore/io/al_Window.hpp"
#include "allocore/protocol/al_OSC.hpp"
#include "alloutil/al_FPS.hpp"
#include "alloutil/al_OmniStereo.hpp"
#define PORT_TO_DEVICE_SERVER (12000)
#define PORT_FROM_DEVICE_SERVER (PORT_TO_DEVICE_SERVER + 1)
// deprecated, do not use:
#define DEVICE_SERVER_SEND_PORT (PORT_FROM_DEVICE_SERVER)
#define DEVICE_SERVER_RECEIVE_PORT (PORT_TO_DEVICE_SERVER)
#define DEVICE_SERVER_IP_ADDRESS "BOSSANOVA"
namespace al {
class OmniApp : public Window,
public osc::PacketHandler,
public FPS,
public OmniStereo::Drawable {
public:
OmniApp(std::string name = "omniapp", bool slave = false);
virtual ~OmniApp();
void start();
virtual void onDraw(Graphics& gl) {}
virtual void onAnimate(al_sec dt) {}
virtual void onSound(AudioIOData& io) {}
virtual void onMessage(osc::Message& m);
const AudioIO& audioIO() const { return mAudioIO; }
AudioIO& audioIO() { return mAudioIO; }
const Lens& lens() const { return mLens; }
Lens& lens() { return mLens; }
const Graphics& graphics() const { return mGraphics; }
Graphics& graphics() { return mGraphics; }
const Nav& nav() const { return mNav; }
Nav& nav() { return mNav; }
ShaderProgram& shader() { return mShader; }
const std::string& name() const { return mName; }
OmniApp& name(const std::string& v) {
mName = v;
return *this;
}
osc::Recv& oscRecv() { return mOSCRecv; }
osc::Send& oscSend() { return mOSCSend; }
OmniStereo& omni() { return mOmni; }
const std::string& hostName() const { return mHostName; }
bool omniEnable() const { return bOmniEnable; }
void omniEnable(bool b) { bOmniEnable = b; }
void initWindow(const Window::Dim& dims = Window::Dim(800, 400),
const std::string title = "OmniApp", double fps = 60,
Window::DisplayMode mode = Window::DEFAULT_BUF);
void initAudio(double audioRate = 44100, int audioBlockSize = 256);
void initAudio(std::string devicename, double audioRate, int audioBlockSize,
int audioInputs, int audioOutputs);
void initOmni(std::string path = "");
void sendHandshake();
void sendDisconnect();
virtual bool onCreate();
virtual bool onFrame();
virtual void onDrawOmni(OmniStereo& omni);
virtual std::string vertexCode();
virtual std::string fragmentCode();
// From 0 to 1, a shader uniform parameter. You can set this in the
// constructor of your App subclass and it will take effect in
// onCreate() when the shader is created.
float lightingAmount;
protected:
AudioIO mAudioIO;
OmniStereo mOmni;
Lens mLens;
Graphics mGraphics;
ShaderProgram mShader;
// control
Nav mNav;
Pose pose;
NavInputControl mNavControl;
StandardWindowKeyControls mStdControls;
osc::Recv mOSCRecv;
osc::Send mOSCSend;
std::string mName;
std::string mHostName;
double mNavSpeed, mNavTurnSpeed;
bool bOmniEnable, bSlave;
static void AppAudioCB(AudioIOData& io);
};
// INLINE IMPLEMENTATION //
inline OmniApp::OmniApp(std::string name, bool slave)
: mNavControl(mNav),
mOSCRecv(PORT_FROM_DEVICE_SERVER),
mOSCSend(PORT_TO_DEVICE_SERVER, DEVICE_SERVER_IP_ADDRESS),
bSlave(slave) {
bOmniEnable = true;
mHostName = Socket::hostName();
mName = name;
mNavSpeed = 1;
mNavTurnSpeed = 0.02;
lens().near(0.01).far(40).eyeSep(0.03);
nav().smooth(0.8);
lightingAmount = 1.0; // default
Window::append(mStdControls);
initWindow();
initOmni();
if (!bSlave) {
Window::append(mNavControl);
//initAudio(); //Ryan McGee: hack for broadcast app
oscRecv().bufferSize(32000);
oscRecv().handler(*this);
sendHandshake();
}
}
inline OmniApp::~OmniApp() {
if (!bSlave) sendDisconnect();
}
inline void OmniApp::initOmni(std::string path) {
mOmni.configure(path, mHostName);
if (mOmni.activeStereo()) {
mOmni.mode(OmniStereo::ACTIVE).stereo(true);
}
}
inline void OmniApp::initWindow(const Window::Dim& dims,
const std::string title, double fps,
Window::DisplayMode mode) {
Window::dimensions(dims);
Window::title(title);
Window::fps(fps);
Window::displayMode(mode);
}
inline void OmniApp::initAudio(double audioRate, int audioBlockSize) {
mAudioIO.callback = AppAudioCB;
mAudioIO.user(this);
mAudioIO.framesPerSecond(audioRate);
mAudioIO.framesPerBuffer(audioBlockSize);
}
inline void OmniApp::initAudio(std::string devicename, double audioRate,
int audioBlockSize, int audioInputs,
int audioOutputs) {
AudioDevice indev(devicename, AudioDevice::INPUT);
AudioDevice outdev(devicename, AudioDevice::OUTPUT);
indev.print();
outdev.print();
mAudioIO.deviceIn(indev);
mAudioIO.deviceOut(outdev);
mAudioIO.channelsOut(audioOutputs);
mAudioIO.channelsIn(audioInputs);
initAudio(audioRate, audioBlockSize);
}
inline void OmniApp::sendHandshake() {
oscSend().send("/handshake", name(), oscRecv().port());
}
inline void OmniApp::sendDisconnect() {
oscSend().send("/disconnectApplication", name());
}
inline void OmniApp::start() {
if (mOmni.activeStereo()) {
Window::displayMode(Window::displayMode() | Window::STEREO_BUF);
}
create();
if (mOmni.fullScreen()) {
fullScreen(true);
cursorHide(true);
}
if (!bSlave) {
if (oscSend().opened()) sendHandshake();
mAudioIO.start();
}
Main::get().start();
}
inline bool OmniApp::onCreate() {
mOmni.onCreate();
Shader vert, frag;
vert.source(OmniStereo::glsl() + vertexCode(), Shader::VERTEX).compile();
vert.printLog();
frag.source(fragmentCode(), Shader::FRAGMENT).compile();
frag.printLog();
mShader.attach(vert).attach(frag).link();
mShader.printLog();
mShader.begin();
mShader.uniform("lighting", lightingAmount);
mShader.uniform("texture", 0.0);
mShader.end();
return true;
}
inline bool OmniApp::onFrame() {
FPS::onFrame();
while (oscRecv().recv()) {
}
nav().step();
onAnimate(dt);
Viewport vp(width(), height());
if (bOmniEnable) {
mOmni.onFrame(*this, lens(), pose, vp);
} else {
mOmni.onFrameFront(*this, lens(), pose, vp);
}
return true;
}
inline void OmniApp::onDrawOmni(OmniStereo& omni) {
graphics().error("start onDraw");
mShader.begin();
mOmni.uniforms(mShader);
onDraw(graphics());
mShader.end();
}
inline void OmniApp::onMessage(osc::Message& m) {
float x;
if (m.addressPattern() == "/mx") {
m >> x;
nav().moveR(-x * mNavSpeed);
} else if (m.addressPattern() == "/my") {
m >> x;
nav().moveU(x * mNavSpeed);
} else if (m.addressPattern() == "/mz") {
m >> x;
nav().moveF(x * mNavSpeed);
} else if (m.addressPattern() == "/tx") {
m >> x;
nav().spinR(x * -mNavTurnSpeed);
} else if (m.addressPattern() == "/ty") {
m >> x;
nav().spinU(x * mNavTurnSpeed);
} else if (m.addressPattern() == "/tz") {
m >> x;
nav().spinF(x * -mNavTurnSpeed);
} else if (m.addressPattern() == "/home") {
nav().home();
} else if (m.addressPattern() == "/halt") {
nav().halt();
}
}
inline std::string OmniApp::vertexCode() {
return AL_STRINGIFY(varying vec4 color; varying vec3 normal, lightDir, eyeVec;
void main() {
color = gl_Color;
vec4 vertex = gl_ModelViewMatrix * gl_Vertex;
normal = gl_NormalMatrix * gl_Normal;
vec3 V = vertex.xyz;
eyeVec = normalize(-V);
lightDir = normalize(vec3(gl_LightSource[0].position.xyz - V));
gl_TexCoord[0] = gl_MultiTexCoord0;
gl_Position = omni_render(vertex);
});
}
inline std::string OmniApp::fragmentCode() {
return AL_STRINGIFY(uniform float lighting; uniform float texture;
uniform sampler2D texture0; varying vec4 color;
varying vec3 normal, lightDir, eyeVec; void main() {
vec4 colorMixed;
if (texture > 0.0) {
vec4 textureColor = texture2D(texture0, gl_TexCoord[0].st);
colorMixed = mix(color, textureColor, texture);
} else {
colorMixed = color;
}
vec4 final_color = colorMixed * gl_LightSource[0].ambient;
vec3 N = normalize(normal);
vec3 L = lightDir;
float lambertTerm = max(dot(N, L), 0.0);
final_color += gl_LightSource[0].diffuse * colorMixed * lambertTerm;
vec3 E = eyeVec;
vec3 R = reflect(-L, N);
float spec = pow(max(dot(R, E), 0.0), 0.9 + 1e-20);
final_color += gl_LightSource[0].specular * spec;
gl_FragColor = mix(colorMixed, final_color, lighting);
});
}
inline void OmniApp::AppAudioCB(AudioIOData& io) {
OmniApp& app = io.user<OmniApp>();
io.frame(0);
app.onSound(io);
}
}
#endif
<commit_msg>added eventhandler to omniApp to enable/disable omni<commit_after>#ifndef AL_OMNIAPP_H
#define AL_OMNIAPP_H
#include "allocore/al_Allocore.hpp"
#include "allocore/io/al_Window.hpp"
#include "allocore/protocol/al_OSC.hpp"
#include "alloutil/al_FPS.hpp"
#include "alloutil/al_OmniStereo.hpp"
#define PORT_TO_DEVICE_SERVER (12000)
#define PORT_FROM_DEVICE_SERVER (PORT_TO_DEVICE_SERVER + 1)
// deprecated, do not use:
#define DEVICE_SERVER_SEND_PORT (PORT_FROM_DEVICE_SERVER)
#define DEVICE_SERVER_RECEIVE_PORT (PORT_TO_DEVICE_SERVER)
#define DEVICE_SERVER_IP_ADDRESS "BOSSANOVA"
namespace al {
class OmniApp;
struct OmniControls : InputEventHandler {
OmniApp* oa;
bool onKeyDown(const Keyboard& k);
};
class OmniApp : public Window,
public osc::PacketHandler,
public FPS,
public OmniStereo::Drawable {
public:
OmniApp(std::string name = "omniapp", bool slave = false);
virtual ~OmniApp();
void start();
virtual void onDraw(Graphics& gl) {}
virtual void onAnimate(al_sec dt) {}
virtual void onSound(AudioIOData& io) {}
virtual void onMessage(osc::Message& m);
const AudioIO& audioIO() const { return mAudioIO; }
AudioIO& audioIO() { return mAudioIO; }
const Lens& lens() const { return mLens; }
Lens& lens() { return mLens; }
const Graphics& graphics() const { return mGraphics; }
Graphics& graphics() { return mGraphics; }
const Nav& nav() const { return mNav; }
Nav& nav() { return mNav; }
ShaderProgram& shader() { return mShader; }
const std::string& name() const { return mName; }
OmniApp& name(const std::string& v) {
mName = v;
return *this;
}
osc::Recv& oscRecv() { return mOSCRecv; }
osc::Send& oscSend() { return mOSCSend; }
OmniStereo& omni() { return mOmni; }
const std::string& hostName() const { return mHostName; }
bool omniEnable() const { return bOmniEnable; }
void omniEnable(bool b) { bOmniEnable = b; }
void initWindow(const Window::Dim& dims = Window::Dim(800, 400),
const std::string title = "OmniApp", double fps = 60,
Window::DisplayMode mode = Window::DEFAULT_BUF);
void initAudio(double audioRate = 44100, int audioBlockSize = 256);
void initAudio(std::string devicename, double audioRate, int audioBlockSize,
int audioInputs, int audioOutputs);
void initOmni(std::string path = "");
void sendHandshake();
void sendDisconnect();
virtual bool onCreate();
virtual bool onFrame();
virtual void onDrawOmni(OmniStereo& omni);
virtual std::string vertexCode();
virtual std::string fragmentCode();
// From 0 to 1, a shader uniform parameter. You can set this in the
// constructor of your App subclass and it will take effect in
// onCreate() when the shader is created.
float lightingAmount;
protected:
AudioIO mAudioIO;
OmniStereo mOmni;
Lens mLens;
Graphics mGraphics;
ShaderProgram mShader;
// control
Nav mNav;
Pose pose;
NavInputControl mNavControl;
StandardWindowKeyControls mStdControls;
OmniControls mOmniControls;
osc::Recv mOSCRecv;
osc::Send mOSCSend;
std::string mName;
std::string mHostName;
double mNavSpeed, mNavTurnSpeed;
bool bOmniEnable, bSlave;
static void AppAudioCB(AudioIOData& io);
};
// INLINE IMPLEMENTATION //
inline OmniApp::OmniApp(std::string name, bool slave)
: mNavControl(mNav),
mOSCRecv(PORT_FROM_DEVICE_SERVER),
mOSCSend(PORT_TO_DEVICE_SERVER, DEVICE_SERVER_IP_ADDRESS),
bSlave(slave) {
bOmniEnable = true;
mHostName = Socket::hostName();
mName = name;
mNavSpeed = 1;
mNavTurnSpeed = 0.02;
lens().near(0.01).far(40).eyeSep(0.03);
nav().smooth(0.8);
lightingAmount = 1.0; // default
Window::append(mStdControls);
initWindow();
initOmni();
if (!bSlave) {
Window::append(mNavControl);
//initAudio(); //Ryan McGee: hack for broadcast app
oscRecv().bufferSize(32000);
oscRecv().handler(*this);
sendHandshake();
}
mOmniControls.oa = this;
Window::append(mOmniControls);
}
inline OmniApp::~OmniApp() {
if (!bSlave) sendDisconnect();
}
inline void OmniApp::initOmni(std::string path) {
mOmni.configure(path, mHostName);
if (mOmni.activeStereo()) {
mOmni.mode(OmniStereo::ACTIVE).stereo(true);
}
}
inline void OmniApp::initWindow(const Window::Dim& dims,
const std::string title, double fps,
Window::DisplayMode mode) {
Window::dimensions(dims);
Window::title(title);
Window::fps(fps);
Window::displayMode(mode);
}
inline void OmniApp::initAudio(double audioRate, int audioBlockSize) {
mAudioIO.callback = AppAudioCB;
mAudioIO.user(this);
mAudioIO.framesPerSecond(audioRate);
mAudioIO.framesPerBuffer(audioBlockSize);
}
inline void OmniApp::initAudio(std::string devicename, double audioRate,
int audioBlockSize, int audioInputs,
int audioOutputs) {
AudioDevice indev(devicename, AudioDevice::INPUT);
AudioDevice outdev(devicename, AudioDevice::OUTPUT);
indev.print();
outdev.print();
mAudioIO.deviceIn(indev);
mAudioIO.deviceOut(outdev);
mAudioIO.channelsOut(audioOutputs);
mAudioIO.channelsIn(audioInputs);
initAudio(audioRate, audioBlockSize);
}
inline void OmniApp::sendHandshake() {
oscSend().send("/handshake", name(), oscRecv().port());
}
inline void OmniApp::sendDisconnect() {
oscSend().send("/disconnectApplication", name());
}
inline void OmniApp::start() {
if (mOmni.activeStereo()) {
Window::displayMode(Window::displayMode() | Window::STEREO_BUF);
}
create();
if (mOmni.fullScreen()) {
fullScreen(true);
cursorHide(true);
}
if (!bSlave) {
if (oscSend().opened()) sendHandshake();
mAudioIO.start();
}
Main::get().start();
}
inline bool OmniApp::onCreate() {
mOmni.onCreate();
Shader vert, frag;
vert.source(OmniStereo::glsl() + vertexCode(), Shader::VERTEX).compile();
vert.printLog();
frag.source(fragmentCode(), Shader::FRAGMENT).compile();
frag.printLog();
mShader.attach(vert).attach(frag).link();
mShader.printLog();
mShader.begin();
mShader.uniform("lighting", lightingAmount);
mShader.uniform("texture", 0.0);
mShader.end();
return true;
}
inline bool OmniApp::onFrame() {
FPS::onFrame();
while (oscRecv().recv()) {
}
nav().step();
onAnimate(dt);
Viewport vp(width(), height());
if (bOmniEnable) {
mOmni.onFrame(*this, lens(), pose, vp);
} else {
mOmni.onFrameFront(*this, lens(), pose, vp);
}
return true;
}
inline void OmniApp::onDrawOmni(OmniStereo& omni) {
graphics().error("start onDraw");
mShader.begin();
mOmni.uniforms(mShader);
onDraw(graphics());
mShader.end();
}
inline void OmniApp::onMessage(osc::Message& m) {
float x;
if (m.addressPattern() == "/mx") {
m >> x;
nav().moveR(-x * mNavSpeed);
} else if (m.addressPattern() == "/my") {
m >> x;
nav().moveU(x * mNavSpeed);
} else if (m.addressPattern() == "/mz") {
m >> x;
nav().moveF(x * mNavSpeed);
} else if (m.addressPattern() == "/tx") {
m >> x;
nav().spinR(x * -mNavTurnSpeed);
} else if (m.addressPattern() == "/ty") {
m >> x;
nav().spinU(x * mNavTurnSpeed);
} else if (m.addressPattern() == "/tz") {
m >> x;
nav().spinF(x * -mNavTurnSpeed);
} else if (m.addressPattern() == "/home") {
nav().home();
} else if (m.addressPattern() == "/halt") {
nav().halt();
}
}
inline std::string OmniApp::vertexCode() {
return AL_STRINGIFY(varying vec4 color; varying vec3 normal, lightDir, eyeVec;
void main() {
color = gl_Color;
vec4 vertex = gl_ModelViewMatrix * gl_Vertex;
normal = gl_NormalMatrix * gl_Normal;
vec3 V = vertex.xyz;
eyeVec = normalize(-V);
lightDir = normalize(vec3(gl_LightSource[0].position.xyz - V));
gl_TexCoord[0] = gl_MultiTexCoord0;
gl_Position = omni_render(vertex);
});
}
inline std::string OmniApp::fragmentCode() {
return AL_STRINGIFY(uniform float lighting; uniform float texture;
uniform sampler2D texture0; varying vec4 color;
varying vec3 normal, lightDir, eyeVec; void main() {
vec4 colorMixed;
if (texture > 0.0) {
vec4 textureColor = texture2D(texture0, gl_TexCoord[0].st);
colorMixed = mix(color, textureColor, texture);
} else {
colorMixed = color;
}
vec4 final_color = colorMixed * gl_LightSource[0].ambient;
vec3 N = normalize(normal);
vec3 L = lightDir;
float lambertTerm = max(dot(N, L), 0.0);
final_color += gl_LightSource[0].diffuse * colorMixed * lambertTerm;
vec3 E = eyeVec;
vec3 R = reflect(-L, N);
float spec = pow(max(dot(R, E), 0.0), 0.9 + 1e-20);
final_color += gl_LightSource[0].specular * spec;
gl_FragColor = mix(colorMixed, final_color, lighting);
});
}
inline void OmniApp::AppAudioCB(AudioIOData& io) {
OmniApp& app = io.user<OmniApp>();
io.frame(0);
app.onSound(io);
}
inline bool OmniControls::onKeyDown(const Keyboard& k){
if(k.key() == 'o'){
oa->omniEnable(!(oa->omniEnable()));
}
return true;
}
}
#endif
<|endoftext|>
|
<commit_before>#include <iostream>
#include <cmath>
using std::cin;
using std::cout;
using std::endl;
using std::string;
int menu();
int PowerDigitSum(int, int);
int AmicableNumbers(int);
void triangulo_pascal(int, int**);
void imprimir_matriz(int**,int);
void teorema_binomio(int**,int);
int main(int argc, char*argv[]){
int opcion = menu();
if (opcion == 1){
int base, expo;
cout << endl;
cout << "Ingrese una base: ";
cin >> base;
cout << "Ingrese una potencia: ";
cin >> expo;
cout << endl;
int resultado = PowerDigitSum(base, expo);
cout << "El resultado del exponencial es: " << pow(base, expo) << endl;
cout << "La suma de los digitos es: " << resultado << endl;
}else if (opcion == 2){
int limit = 10000, CheckLimit = 10000, resp1, resp2;
int DivisorsSum = AmicableNumbers(limit);
cout << "La suma de los divisores de 10000 es: " << DivisorsSum << endl;
resp1 = DivisorsSum;
limit = DivisorsSum;
DivisorsSum = AmicableNumbers(limit);
cout << "La suma de los divisores de " << limit << " es: " << DivisorsSum << endl;
resp2 = DivisorsSum;
if (CheckLimit == resp2){
cout << resp1 << " y " << resp2 << " son numeros amigables" << endl;
}else{
cout << resp1 << " y " << resp2 << " no son numeros amigables" << endl;
}
}else if (opcion == 3){
cout << "AQUI VA EL EJERCICIO 357";
}else if(opcion == 4){
int filas;
cout<< "Ingrese la cantidad de lineas del triangulo: ";
cin>> filas;
int** matriz = new int*[filas];
for(int i=0; i<filas; i++){
matriz[i]= new int[filas];
}
for(int i=0; i<filas;i++){
for(int j=0; j<filas;j++){
matriz[i][j]=0;
}
}
triangulo_pascal(filas,matriz);
imprimir_matriz(matriz,filas);
for (int i = 0; i < filas; i++){
delete[] matriz[i];
}
delete[] matriz;
}else if(opcion == 5){
int potencia;
cout<< "Ingrese la potencia del binomio: ";
cin>> potencia;
potencia++;
int** matriz = new int*[potencia];
for(int i=0; i<potencia; i++){
matriz[i]= new int[potencia];
}
for(int i=0; i<potencia;i++){
for(int j=0; j<potencia;j++){
matriz[i][j]=0;
}
}
triangulo_pascal(potencia,matriz);
teorema_binomio(matriz,potencia);
for (int i = 0; i < potencia; i++){
delete[] matriz[i];
}
delete[] matriz;
}
return 0;
}
void teorema_binomio(int** matriz,int potencia){
int potencia_x=potencia-2,potencia_y=1;
for(int i=0; i<potencia; i++){
if(i==0)
cout<< "X^"<<potencia-1<<" + ";
else if(matriz[potencia-1][i]==1)
cout<< "Y^"<<potencia_y<<endl;
else {
cout<<"("<<matriz[potencia-1][i]<<"X^"<<potencia_x<<")"<<"("<<"Y^"<<potencia_y<<")"<< " + ";
potencia_x--;
potencia_y++;
}
}
}
void imprimir_matriz(int** matriz,int filas){
for(int i=0; i<filas; i++){
for(int j=filas-1; j>=0; j--){
if(matriz[i][j])
cout<<matriz[i][j]<<" ";
else
cout<< " ";
}
cout<< endl;
}
}
void triangulo_pascal(int filas, int** matriz){
matriz[0][0]=1;
matriz[1][0]=1;
matriz[1][1]=1;
int cont;
for(int i=2; i<filas; i++){
cont =0;
for(int j=0; j<filas;j++){
if(j==0){
matriz[i][j]=1;
}else{
if(cont < i){
matriz[i][j]= matriz[i-1][j-1]+ matriz[i-1][j];
cont++;
}
}
}
}
}
int menu(){
int opcion;
cout << "1-Programa #1 (16)" << endl
<< "2-Porgrama #2 (21)" << endl
<< "3-Programa #3 (357)" << endl
<< "4-Triangulo de Pascal"<<endl
<< "5-Binomio elevado a la n"<<endl
<< "Ingrese una opcion: ";
cin >> opcion;
return opcion;
}
int PowerDigitSum(int base, int expo){//no esta terminado
int exponencial = pow(base, expo);
int aumentar = 1;
int resultado = 0;
int temp = 0;
for (int i = 0; i < aumentar; i++){
if (exponencial/10 != 0){
aumentar++;
resultado += exponencial%10;
exponencial = exponencial/10;
}else if (exponencial/10 == 0){
resultado += exponencial;
}
}
return resultado;
}
int AmicableNumbers(int limit){
int DivisorsSum = 0;
for (int i = 1; i < limit/2+1; i++){
if (limit % i == 0){
DivisorsSum += i;
}else{
}
}
return DivisorsSum;
}
<commit_msg>Terminado ejercicio 357 y tarea completa<commit_after>#include <iostream>
#include <cmath>
using std::cin;
using std::cout;
using std::endl;
using std::string;
int menu();
int PowerDigitSum(int, int);
int AmicableNumbers(int);
void triangulo_pascal(int, int**);
void imprimir_matriz(int**,int);
void teorema_binomio(int**,int);
void Primegeneratingintegers(int);
int main(int argc, char*argv[]){
int opcion = menu();
if (opcion == 1){
int base, expo;
cout << endl;
cout << "Ingrese una base: ";
cin >> base;
cout << "Ingrese una potencia: ";
cin >> expo;
cout << endl;
int resultado = PowerDigitSum(base, expo);
cout << "El resultado del exponencial es: " << pow(base, expo) << endl;
cout << "La suma de los digitos es: " << resultado << endl;
}else if (opcion == 2){
int limit = 10000, CheckLimit = 10000, resp1, resp2;
int DivisorsSum = AmicableNumbers(limit);
cout << "La suma de los divisores de 10000 es: " << DivisorsSum << endl;
resp1 = DivisorsSum;
limit = DivisorsSum;
DivisorsSum = AmicableNumbers(limit);
cout << "La suma de los divisores de " << limit << " es: " << DivisorsSum << endl;
resp2 = DivisorsSum;
if (CheckLimit == resp2){
cout << resp1 << " y " << resp2 << " son numeros amigables" << endl;
}else{
cout << resp1 << " y " << resp2 << " no son numeros amigables" << endl;
}
}else if (opcion == 3){
int num;
cout << "Ingresa el numero a evaluar: ";
cin >> num;
cout << endl;
cout << "Los primeros generados por los divisores de " << num << " son: " << endl;
Primegeneratingintegers(num);
}else if(opcion == 4){
int filas;
cout<< "Ingrese la cantidad de lineas del triangulo: ";
cin>> filas;
int** matriz = new int*[filas];
for(int i=0; i<filas; i++){
matriz[i]= new int[filas];
}
for(int i=0; i<filas;i++){
for(int j=0; j<filas;j++){
matriz[i][j]=0;
}
}
triangulo_pascal(filas,matriz);
imprimir_matriz(matriz,filas);
for (int i = 0; i < filas; i++){
delete[] matriz[i];
}
delete[] matriz;
}else if(opcion == 5){
int potencia;
cout<< "Ingrese la potencia del binomio: ";
cin>> potencia;
potencia++;
int** matriz = new int*[potencia];
for(int i=0; i<potencia; i++){
matriz[i]= new int[potencia];
}
for(int i=0; i<potencia;i++){
for(int j=0; j<potencia;j++){
matriz[i][j]=0;
}
}
triangulo_pascal(potencia,matriz);
teorema_binomio(matriz,potencia);
for (int i = 0; i < potencia; i++){
delete[] matriz[i];
}
delete[] matriz;
}
return 0;
}
void teorema_binomio(int** matriz,int potencia){
int potencia_x=potencia-2,potencia_y=1;
for(int i=0; i<potencia; i++){
if(i==0)
cout<< "X^"<<potencia-1<<" + ";
else if(matriz[potencia-1][i]==1)
cout<< "Y^"<<potencia_y<<endl;
else {
cout<<"("<<matriz[potencia-1][i]<<"X^"<<potencia_x<<")"<<"("<<"Y^"<<potencia_y<<")"<< " + ";
potencia_x--;
potencia_y++;
}
}
}
void imprimir_matriz(int** matriz,int filas){
for(int i=0; i<filas; i++){
for(int j=filas-1; j>=0; j--){
if(matriz[i][j])
cout<<matriz[i][j]<<" ";
else
cout<< " ";
}
cout<< endl;
}
}
void triangulo_pascal(int filas, int** matriz){
matriz[0][0]=1;
matriz[1][0]=1;
matriz[1][1]=1;
int cont;
for(int i=2; i<filas; i++){
cont =0;
for(int j=0; j<filas;j++){
if(j==0){
matriz[i][j]=1;
}else{
if(cont < i){
matriz[i][j]= matriz[i-1][j-1]+ matriz[i-1][j];
cont++;
}
}
}
}
}
int menu(){
int opcion;
cout << "1-Programa #1 (16)" << endl
<< "2-Porgrama #2 (21)" << endl
<< "3-Programa #3 (357)" << endl
<< "4-Triangulo de Pascal"<<endl
<< "5-Binomio elevado a la n"<<endl
<< "Ingrese una opcion: ";
cin >> opcion;
return opcion;
}
int PowerDigitSum(int base, int expo){//no esta terminado
int exponencial = pow(base, expo);
int aumentar = 1;
int resultado = 0;
int temp = 0;
for (int i = 0; i < aumentar; i++){
if (exponencial/10 != 0){
aumentar++;
resultado += exponencial%10;
exponencial = exponencial/10;
}else if (exponencial/10 == 0){
resultado += exponencial;
}
}
return resultado;
}
int AmicableNumbers(int limit){
int DivisorsSum = 0;
for (int i = 1; i < limit/2+1; i++){
if (limit % i == 0){
DivisorsSum += i;
}else{
}
}
return DivisorsSum;
}
void Primegeneratingintegers(int num){
for (int i = 1; i < num; ++i){
if (num % i == 0){
cout << (i + (num/i)) << " ";
}
}
cout << endl;
}
<|endoftext|>
|
<commit_before>#include"common/utils.h"
#include"common/mqtt_wrapper.h"
#include<chrono>
#include<getopt.h>
#include<iostream>
#include<fstream>
#include<string>
#include<exception>
#include<stdexcept>
#include<mosquittopp.h>
#include<ctime>
#include<stdio.h>
#include<unistd.h>
using namespace std;
class TLoggerConfig{// class for parsing config
public:
inline void SetPath(string s) { Path_to_log = s; }
inline string GetPath() { return Path_to_log; }
inline void SetSize(string s) { SetIntFromString(Size, s); };
inline int GetSize() { return Size; }
inline void SetDumpSupport(bool b) { DumpSupport = b; }
inline bool GetDumpSupport() { return DumpSupport; }
inline void SetTimeout(string s) { SetIntFromString(Timeout, s); }
inline int GetTimeout() { return Timeout; }
inline bool GetFullDump() { return FullDump; }
inline void SetFullDump(bool b) { FullDump = b; }
static void SetIntFromString(int& i, string s);
inline int GetNumber() { return Number; }
inline void SetNumber(string s) { SetIntFromString(Number, s); }
private:
string Path_to_log;
int Size;
bool DumpSupport;
int Timeout;
bool FullDump;
int Number;
};
void TLoggerConfig::SetIntFromString(int& i, string s ){
try {
if (s != "")
i = stoi(s.c_str());
}catch (const std::invalid_argument& argument) {
cerr << "invalid number " << s << endl;
exit(-1);
}catch (const std::out_of_range& argument){
cerr << "out of range " << s << endl;
exit(-1);
}
}
class MQTTLogger: public TMQTTWrapper
{
public:
MQTTLogger (const MQTTLogger::TConfig& mqtt_config, TLoggerConfig log_config);
~MQTTLogger();
void OnConnect(int rc) ;
void OnMessage(const struct mosquitto_message *message);
void OnSubscribe(int mid, int qos_count, const int *granted_qos);
//void SetLogFile(string path) { path_to_log = path; }
//void SetMaximum(int size);
//void SetTimeout(std::chrono::seconds timeout);
//void SetFullDump(bool fulldump);
private:
string Path_To_Log;// path to log file
int Max;// set maximum size of log file
unsigned int Timeout;// timeout after which we will do dump logs
bool FullDump;// if full_dump yes we doing full dump after timeout
ofstream Output;
int Number; // number of old log files;
};
MQTTLogger::MQTTLogger ( const MQTTLogger::TConfig& mqtt_config, TLoggerConfig log_config)
: TMQTTWrapper(mqtt_config)
{
Path_To_Log = log_config.GetPath();
Output.open(Path_To_Log, std::fstream::app);
if (!Output.is_open()){
cerr << "Cannot open log file for writting " << Path_To_Log << endl;
exit (-1);
}
Max = 1024 * log_config.GetSize();
Number = log_config.GetNumber();
Connect();
}
MQTTLogger::~MQTTLogger() {}
void MQTTLogger::OnConnect(int rc){
cout << "HELLO there\n";
Subscribe(NULL, "/#");
}
void MQTTLogger::OnSubscribe(int mid, int qos_count, const int *granted_qos){
cout << "subscription succeded\n";
}
void MQTTLogger::OnMessage(const struct mosquitto_message *message){
string topic = message->topic;
string payload = static_cast<const char*>(message->payload);
std::chrono::system_clock::time_point current_time = std::chrono::system_clock::now();
std::time_t tt = std::chrono::system_clock::to_time_t(current_time);
Output << topic + " " + payload << ctime( &tt) << endl;
if (Output.tellp() > Max){
Output.close();
int i;
for (i = Number-1; i > 0; i--){
if (access((Path_To_Log + "." + to_string(i)).c_str(), F_OK) != -1){// check if old log file exists
if (rename((Path_To_Log + "." + to_string(i)).c_str(), (Path_To_Log + "." + to_string(i+1)).c_str()) != 0){
cerr << "can't create old log file \n";
exit(-1);
}
}
}
if (rename(Path_To_Log.c_str(), (Path_To_Log + ".1").c_str()) != 0){
cerr << "can't create old log file \n";
exit(-1);
}
Output.open(Path_To_Log);
if (!Output.is_open()){
cerr << "Cannot open log file for writting " << Path_To_Log << endl;
exit (-1);
}
}
}
int main (int argc, char* argv[])
{
int rc;
TLoggerConfig log_config;
MQTTLogger::TConfig mqtt_config;
mqtt_config.Host = "localhost";
mqtt_config.Port = 1883;
int c;
log_config.SetPath("/var/log/mqtt.log");
log_config.SetSize("200");
log_config.SetDumpSupport (false);
log_config.SetTimeout("0");
log_config.SetFullDump(true);
log_config.SetNumber("2");
while ( (c = getopt(argc, argv, "h:p:H:t:d:s:f:n:") ) != -1 ){
switch(c){
case 'n':
printf ("option n with value '%s'\n", optarg);
log_config.SetNumber(string(optarg));
break;
case 'f':
printf ("option f with value '%s'\n", optarg);
log_config.SetPath(string(optarg));
break;
case 't':
printf ("option t with value '%s'\n", optarg);
log_config.SetDumpSupport(true);
log_config.SetTimeout(string(optarg));
break;
case 'p':
printf ( "option p with value '%s'\n",optarg);
TLoggerConfig::SetIntFromString(mqtt_config.Port, string(optarg));
break;
case 'H':
printf ("option h with value '%s'\n", optarg);
mqtt_config.Host = optarg;
break;
case 's':
printf ("option s with value '%s'\n",optarg);
log_config.SetSize(string(optarg));
break;
case 'd':
printf ("option d with value '%s'\n",optarg);
((string(optarg) == "y") || (string(optarg) == "yes")) ? log_config.SetFullDump(true): log_config.SetFullDump(false);
break;
case '?':
break;
case 'h':
printf ( "help menu\n");
default:
//printf ("?? Getopt returned character code 0%o ??\n",c);
printf("Usage:\n mqtt_logger [options]\n");
printf("Options:\n");
printf("\t-t TIMEOUT\t Timeoute (seconds) before rotation ( default: not set )\n");
printf("\t-p PORT\t set to what port mqtt_logger should connect (default: 1883)\n");
printf("\t-H IP\t set to what IP mqtt_logger should connect (default: localhost)\n");
printf("\t-d y|n\t choose yes|y = 'full dump' or only controls ( default yes)\n");
printf("\tp-s SIZE\t Max size (KB) before rotation ( default: 200KB)\n");
}
}
/* try {
if (config_fname_timeout != "")
log_config.timeout = stoi(config_fname_timeout.c_str());
}
catch (const std::invalid_argument& argument) {
cerr << "invalid number " << config_fname_timeout << endl;
return -1;
}catch (const std::out_of_range& argument){
cerr << "out of range " << config_fname_timeout << endl;
return -1;
}
try {
if (config_fname_size != "")
log_config.size = stoi(config_fname_size.c_str());
}catch (const std::invalid_argument& argument) {
cerr << "invalid number " << config_fname_size << endl;
return -1;
}catch (const std::out_of_range& argument){
cerr << "out of range " << config_fname_size << endl;
return -1 ;
}
try {
if (config_fname_port != "")
mqtt_config.Port = stoi(config_fname_port.c_str());
}
catch (const std::invalid_argument& argument) {
cerr << "invalid number" << config_fname_port << endl;
return -1;
}catch (const std::out_of_range& argument){
cerr << "out of range " << config_fname_port << endl;
}
*/
mosqpp::lib_init();
std::shared_ptr<MQTTLogger> mqtt_logger(new MQTTLogger(mqtt_config, log_config));
mqtt_logger->Init();
while (1){
rc = mqtt_logger->loop();
long int interval;
std::chrono::steady_clock::time_point previous_time = std::chrono::steady_clock::now();
if (rc != 0)
mqtt_logger->reconnect();
else{
interval = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now() - previous_time).count();
}
}
return 0;
}
<commit_msg>some correction<commit_after>#include"common/utils.h"
#include"common/mqtt_wrapper.h"
#include<chrono>
#include<getopt.h>
#include<iostream>
#include<fstream>
#include<string>
#include<exception>
#include<stdexcept>
#include<mosquittopp.h>
#include<ctime>
#include<stdio.h>
#include<unistd.h>
using namespace std;
class TLoggerConfig{// class for parsing config
public:
inline void SetPath(string s) { Path_to_log = s; }
inline string GetPath() { return Path_to_log; }
inline void SetSize(string s) { SetIntFromString(Size, s); };
inline int GetSize() { return Size; }
inline bool GetFullLog() { return FullLog; }
inline void SetFullLog(bool b) { FullLog = b; }
static void SetIntFromString(int& i, string s);
inline int GetNumber() { return Number; }
inline void SetNumber(string s) { SetIntFromString(Number, s); }
private:
string Path_to_log;
int Size;
bool FullLog;
int Number;
};
void TLoggerConfig::SetIntFromString(int& i, string s ){
try {
if (s != "")
i = stoi(s.c_str());
}catch (const std::invalid_argument& argument) {
cerr << "invalid number " << s << endl;
exit(-1);
}catch (const std::out_of_range& argument){
cerr << "out of range " << s << endl;
exit(-1);
}
}
class MQTTLogger: public TMQTTWrapper
{
public:
MQTTLogger (const MQTTLogger::TConfig& mqtt_config, TLoggerConfig log_config);
~MQTTLogger();
void OnConnect(int rc) ;
void OnMessage(const struct mosquitto_message *message);
void OnSubscribe(int mid, int qos_count, const int *granted_qos);
//void SetLogFile(string path) { path_to_log = path; }
//void SetMaximum(int size);
//void SetTimeout(std::chrono::seconds timeout);
//void SetFullDump(bool fulldump);
private:
string Path_To_Log;// path to log file
int Max;// set maximum size of log file
unsigned int Timeout;// timeout after which we will do dump logs
bool FullDump;// if full_dump yes we doing full dump after timeout
ofstream Output;
int Number; // number of old log files;
string Mask;
};
MQTTLogger::MQTTLogger ( const MQTTLogger::TConfig& mqtt_config, TLoggerConfig log_config)
: TMQTTWrapper(mqtt_config)
{
Path_To_Log = log_config.GetPath();
Output.open(Path_To_Log, std::fstream::app);
if (!Output.is_open()){
cerr << "Cannot open log file for writting " << Path_To_Log << endl;
exit (-1);
}
Max = 1024 * log_config.GetSize();
Number = log_config.GetNumber();
if (log_config.GetFullLog())
Mask = "/#";
else
Mask = "/devices/+/controls/#";
Connect();
}
MQTTLogger::~MQTTLogger() {}
void MQTTLogger::OnConnect(int rc){
cout << "HELLO there\n";
Subscribe(NULL, Mask);
}
void MQTTLogger::OnSubscribe(int mid, int qos_count, const int *granted_qos){
cout << "subscription succeded\n";
}
void MQTTLogger::OnMessage(const struct mosquitto_message *message){
string topic = message->topic;
string payload = static_cast<const char*>(message->payload);
std::chrono::system_clock::time_point current_time = std::chrono::system_clock::now();
std::time_t tt = std::chrono::system_clock::to_time_t(current_time);
Output << topic + " " + payload << ctime( &tt) << endl;
if (Output.tellp() > Max){
Output.close();
int i;
for (i = Number-1; i > 0; i--){
if (access((Path_To_Log + "." + to_string(i)).c_str(), F_OK) != -1){// check if old log file exists
if (rename((Path_To_Log + "." + to_string(i)).c_str(), (Path_To_Log + "." + to_string(i+1)).c_str()) != 0){
cerr << "can't create old log file \n";
exit(-1);
}
}
}
if (rename(Path_To_Log.c_str(), (Path_To_Log + ".1").c_str()) != 0){
cerr << "can't create old log file \n";
exit(-1);
}
Output.open(Path_To_Log);
if (!Output.is_open()){
cerr << "Cannot open log file for writting " << Path_To_Log << endl;
exit (-1);
}
mosquittopp::unsubscribe(NULL, Mask.c_str());
Subscribe(NULL, Mask);
}
}
int main (int argc, char* argv[])
{
int rc;
TLoggerConfig log_config;
MQTTLogger::TConfig mqtt_config;
mqtt_config.Host = "localhost";
mqtt_config.Port = 1883;
int c;
log_config.SetPath("/var/log/mqtt.log");
log_config.SetSize("200");
log_config.SetDumpSupport (false);
//log_config.SetTimeout("0");
log_config.SetFullLog(true);
log_config.SetNumber("2");
while ( (c = getopt(argc, argv, "hp:H:s:f:n:") ) != -1 ){
switch(c){
case 'n':
printf ("option n with value '%s'\n", optarg);
log_config.SetNumber(string(optarg));
break;
case 'f':
printf ("option f with value '%s'\n", optarg);
log_config.SetPath(string(optarg));
break;
case 'p':
printf ( "option p with value '%s'\n",optarg);
TLoggerConfig::SetIntFromString(mqtt_config.Port, string(optarg));
break;
case 'H':
printf ("option h with value '%s'\n", optarg);
mqtt_config.Host = optarg;
break;
case 's':
printf ("option s with value '%s'\n",optarg);
log_config.SetSize(string(optarg));
break;
case 'o':
printf ("option o with value '%s'\n",optarg);
((string(optarg) == "y") || (string(optarg) == "yes")) ? log_config.SetFullDump(true): log_config.SetFullDump(false);
break;
case '?':
break;
case 'h':
printf ( "help menu\n");
//printf ("?? Getopt returned character code 0%o ??\n",c);
printf("Usage:\n mqtt_logger [options]\n");
printf("Options:\n");
printf("\t-n NUMBER \t\t\t Number of old log files to remain(default 2) \n");
printf("\t-o \t\t\t Only controls to log\n");
//printf("\t-t TIMEOUT\t\t\t Timeoute (seconds) before rotation ( default: not set )\n");
printf("\t-p PORT \t\t\t set to what port mqtt_logger should connect (default: 1883)\n");
printf("\t-H IP \t\t\t set to what IP mqtt_logger should connect (default: localhost)\n");
//printf("\t-d y|n \t\t\t choose yes|y = 'full dump' or only controls ( default yes)\n");
printf("\t-s SIZE \t\t\t Max size (KB) before rotation ( default: 200KB)\n");
return 0;
}
}
/* try {
if (config_fname_timeout != "")
log_config.timeout = stoi(config_fname_timeout.c_str());
}
catch (const std::invalid_argument& argument) {
cerr << "invalid number " << config_fname_timeout << endl;
return -1;
}catch (const std::out_of_range& argument){
cerr << "out of range " << config_fname_timeout << endl;
return -1;
}
try {
if (config_fname_size != "")
log_config.size = stoi(config_fname_size.c_str());
}catch (const std::invalid_argument& argument) {
cerr << "invalid number " << config_fname_size << endl;
return -1;
}catch (const std::out_of_range& argument){
cerr << "out of range " << config_fname_size << endl;
return -1 ;
}
try {
if (config_fname_port != "")
mqtt_config.Port = stoi(config_fname_port.c_str());
}
catch (const std::invalid_argument& argument) {
cerr << "invalid number" << config_fname_port << endl;
return -1;
}catch (const std::out_of_range& argument){
cerr << "out of range " << config_fname_port << endl;
}
*/
mosqpp::lib_init();
std::shared_ptr<MQTTLogger> mqtt_logger(new MQTTLogger(mqtt_config, log_config));
mqtt_logger->Init();
while (1){
rc = mqtt_logger->loop();
long int interval;
std::chrono::steady_clock::time_point previous_time = std::chrono::steady_clock::now();
if (rc != 0)
mqtt_logger->reconnect();
else{
interval = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now() - previous_time).count();
}
}
return 0;
}
<|endoftext|>
|
<commit_before>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
*
* 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 "jstreamsconfig.h"
#include "bz2inputstream.h"
using namespace jstreams;
bool
BZ2InputStream::checkHeader(const char* data, int32_t datasize) {
static const char magic[] = {0x42, 0x5a, 0x68, 0x39, 0x31};
if (datasize < 5) return false;
return memcmp(data, magic, 5) == 0;
}
BZ2InputStream::BZ2InputStream(StreamBase<char>* input) {
// initialize values that signal state
this->input = input;
// TODO: check first bytes of stream before allocating buffer
// 0x42 0x5a 0x68 0x39 0x31
if (!checkMagic()) {
error = "Magic bytes are wrong.";
status = Error;
allocatedBz = false;
return;
}
bzstream = (bz_stream*)malloc(sizeof(bz_stream));
bzstream->bzalloc = NULL;
bzstream->bzfree = NULL;
bzstream->opaque = NULL;
bzstream->avail_in = 0;
bzstream->next_in = NULL;
int r;
r = BZ2_bzDecompressInit(bzstream, 1, 0);
if (r != BZ_OK) {
error = "Error initializing BZ2InputStream.";
fprintf(stderr, "Error initializing BZ2InputStream.\n");
dealloc();
status = Error;
return;
}
allocatedBz = true;
// signal that we need to read into the buffer
bzstream->avail_out = 1;
// set the minimum size for the output buffer
mark(262144);
}
BZ2InputStream::~BZ2InputStream() {
dealloc();
}
void
BZ2InputStream::dealloc() {
if (allocatedBz) {
BZ2_bzDecompressEnd(bzstream);
free(bzstream);
bzstream = 0;
}
}
bool
BZ2InputStream::checkMagic() {
const char* begin;
int32_t nread;
int64_t pos = input->getPosition();
nread = input->read(begin, 5, 5);
input->reset(pos);
if (nread != 5) {
return false;
}
return checkHeader(begin, 5);
}
void
BZ2InputStream::readFromStream() {
// read data from the input stream
const char* inStart;
int32_t nread;
nread = input->read(inStart, 1, 0);
if (status == Error) {
error = "Error reading bz2: ";
error += input->getError();
}
bzstream->next_in = (char*)inStart;
bzstream->avail_in = nread;
}
int32_t
BZ2InputStream::fillBuffer(char* start, int32_t space) {
if (bzstream == 0) return -1;
// make sure there is data to decompress
if (bzstream->avail_out != 0) {
readFromStream();
if (status != Ok) {
// no data was read
return -1;
}
}
// make sure we can write into the buffer
bzstream->avail_out = space;
bzstream->next_out = start;
// decompress
int r = BZ2_bzDecompress(bzstream);
// inform the buffer of the number of bytes that was read
int32_t nwritten = space - bzstream->avail_out;
switch (r) {
case BZ_PARAM_ERROR:
error = "BZ_PARAM_ERROR";
status = Error;
return -1;
case BZ_DATA_ERROR:
error = "BZ_DATA_ERROR";
status = Error;
return -1;
case BZ_DATA_ERROR_MAGIC:
error = "BZ_DATA_ERROR_MAGIC";
status = Error;
return -1;
case BZ_MEM_ERROR:
error = "BZ_MEM_ERROR";
status = Error;
return -1;
case BZ_STREAM_END:
// we are finished decompressing,
// (but this stream is not yet finished)
dealloc();
}
return nwritten;
}
<commit_msg>Fix reading of incomplete bzip2 streams.<commit_after>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
*
* 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 "jstreamsconfig.h"
#include "bz2inputstream.h"
using namespace jstreams;
bool
BZ2InputStream::checkHeader(const char* data, int32_t datasize) {
static const char magic[] = {0x42, 0x5a, 0x68, 0x39, 0x31};
if (datasize < 5) return false;
return memcmp(data, magic, 5) == 0;
}
BZ2InputStream::BZ2InputStream(StreamBase<char>* input) {
// initialize values that signal state
this->input = input;
// TODO: check first bytes of stream before allocating buffer
// 0x42 0x5a 0x68 0x39 0x31
if (!checkMagic()) {
error = "Magic bytes are wrong.";
status = Error;
allocatedBz = false;
return;
}
bzstream = (bz_stream*)malloc(sizeof(bz_stream));
bzstream->bzalloc = NULL;
bzstream->bzfree = NULL;
bzstream->opaque = NULL;
bzstream->avail_in = 0;
bzstream->next_in = NULL;
int r;
r = BZ2_bzDecompressInit(bzstream, 1, 0);
if (r != BZ_OK) {
error = "Error initializing BZ2InputStream.";
fprintf(stderr, "Error initializing BZ2InputStream.\n");
dealloc();
status = Error;
return;
}
allocatedBz = true;
// signal that we need to read into the buffer
bzstream->avail_out = 1;
// set the minimum size for the output buffer
mark(262144);
}
BZ2InputStream::~BZ2InputStream() {
dealloc();
}
void
BZ2InputStream::dealloc() {
if (allocatedBz) {
BZ2_bzDecompressEnd(bzstream);
free(bzstream);
bzstream = 0;
}
}
bool
BZ2InputStream::checkMagic() {
const char* begin;
int32_t nread;
int64_t pos = input->getPosition();
nread = input->read(begin, 5, 5);
input->reset(pos);
if (nread != 5) {
return false;
}
return checkHeader(begin, 5);
}
void
BZ2InputStream::readFromStream() {
// read data from the input stream
const char* inStart;
int32_t nread;
nread = input->read(inStart, 1, 0);
if (nread <= -1) {
status = Error;
error = input->getError();
} else if (nread < 1) {
status = Error;
error = "unexpected end of stream";
} else {
bzstream->next_in = (char*)inStart;
bzstream->avail_in = nread;
}
}
int32_t
BZ2InputStream::fillBuffer(char* start, int32_t space) {
if (bzstream == 0) return -1;
// make sure there is data to decompress
if (bzstream->avail_out != 0) {
readFromStream();
if (status != Ok) {
// no data was read
return -1;
}
}
// make sure we can write into the buffer
bzstream->avail_out = space;
bzstream->next_out = start;
// decompress
int r = BZ2_bzDecompress(bzstream);
// inform the buffer of the number of bytes that was read
int32_t nwritten = space - bzstream->avail_out;
switch (r) {
case BZ_PARAM_ERROR:
error = "BZ_PARAM_ERROR";
status = Error;
return -1;
case BZ_DATA_ERROR:
error = "BZ_DATA_ERROR";
status = Error;
return -1;
case BZ_DATA_ERROR_MAGIC:
error = "BZ_DATA_ERROR_MAGIC";
status = Error;
return -1;
case BZ_MEM_ERROR:
error = "BZ_MEM_ERROR";
status = Error;
return -1;
case BZ_STREAM_END:
// we are finished decompressing,
// (but this stream is not yet finished)
dealloc();
}
return nwritten;
}
<|endoftext|>
|
<commit_before>//
// created by : Timothée Feuillet
// date: 2022-2-18
//
//
// Copyright (c) 2022 Timothée Feuillet
//
// 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.
//
#pragma once
#include "chain.hpp"
namespace neam::async
{
/// \brief Simple chain variant that is simply "the previous operation has completed"
using continuation_chain = chain<>;
/// \brief return a chain that will be called when all the argument chains have completed.
/// Argument chains must be continuation_chain that have no callback
/// \note multi-chain needs dynamic allocation for the state
/// \todo put that in a pool, as the state is the same size for each multi-chain
template<typename Container>
continuation_chain multi_chain(Container&& c)
{
struct state_t
{
uint64_t count;
typename continuation_chain::state state;
};
if (!c.size())
return continuation_chain::create_and_complete();
continuation_chain ret;
state_t* state = new state_t {c.size(), ret.create_state() };
// create the lambda:
const auto lbd = [state]()
{
--state->count;
if (state->count == 0)
{
state->state.complete();
delete state;
}
};
// register in the chains:
for (auto& it : c)
{
it.then(lbd);
}
return ret;
};
/// \brief return a chain that will be called when all the argument chains have completed.
/// \note multi-chain needs dynamic allocation for the state
/// \todo put that in a pool, as the state is the same size for each multi-chain
template<typename CbState, typename Container, typename Fnc>
chain<CbState> multi_chain(CbState&& initial_state, Container&& c, Fnc&& fnc)
{
struct state_t
{
uint64_t count;
typename chain<CbState>::state state;
CbState data;
};
if (!c.size())
return chain<CbState>::create_and_complete(std::move(initial_state));
chain<CbState> ret;
state_t* state = new state_t {c.size(), ret.create_state(), std::move(initial_state) };
// create the lambda:
const auto lbd = [state, fnc = std::move(fnc)](CbState current)
{
fnc(state->data, current);
--state->count;
if (state->count == 0)
{
state->state.complete(std::move(state->data));
delete state;
}
};
// register in the chains:
for (auto& it : c)
{
it.then(lbd);
}
return ret;
};
}
<commit_msg>fix thread-safety problems<commit_after>//
// created by : Timothée Feuillet
// date: 2022-2-18
//
//
// Copyright (c) 2022 Timothée Feuillet
//
// 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.
//
#pragma once
#include "chain.hpp"
namespace neam::async
{
/// \brief Simple chain variant that is simply "the previous operation has completed"
using continuation_chain = chain<>;
/// \brief return a chain that will be called when all the argument chains have completed.
/// Argument chains must be continuation_chain that have no callback
/// \note multi-chain needs dynamic allocation for the state
/// \todo put that in a pool, as the state is the same size for each multi-chain
template<typename Container>
continuation_chain multi_chain(Container&& c)
{
struct state_t
{
std::atomic<uint64_t> count;
typename continuation_chain::state state;
};
if (!c.size())
return continuation_chain::create_and_complete();
continuation_chain ret;
state_t* state = new state_t {c.size(), ret.create_state() };
// create the lambda:
const auto lbd = [state]()
{
--state->count;
if (state->count == 0)
{
state->state.complete();
delete state;
}
};
// register in the chains:
for (auto& it : c)
{
it.then(lbd);
}
return ret;
}
/// \brief return a chain that will be called when all the argument chains have completed.
/// Argument chains must be continuation_chain that have no callback
/// \note multi-chain needs dynamic allocation for the state
/// \todo put that in a pool, as the state is the same size for each multi-chain
template<typename... Chains>
continuation_chain multi_chain_simple(Chains&&... chains)
{
struct state_t
{
std::atomic<uint64_t> count;
typename continuation_chain::state state;
};
if constexpr (sizeof...(Chains) == 0)
return continuation_chain::create_and_complete();
if constexpr (sizeof...(Chains) == 1)
return (chains,...);
continuation_chain ret;
state_t* state = new state_t { sizeof...(Chains), ret.create_state() };
// create the lambda:
const auto lbd = [state]()
{
--state->count;
if (state->count == 0)
{
state->state.complete();
delete state;
}
};
// register in the chains:
(chains.then(lbd), ...);
return ret;
}
/// \brief return a chain that will be called when all the argument chains have completed.
/// \note multi-chain needs dynamic allocation for the state
/// \todo put that in a pool, as the state is the same size for each multi-chain
template<typename CbState, typename Container, typename Fnc>
chain<CbState> multi_chain(CbState&& initial_state, Container&& c, Fnc&& fnc)
{
using cb_state_t = std::remove_reference_t<CbState>;
struct state_t
{
std::atomic<uint64_t> count;
typename chain<CbState>::state state;
cb_state_t data;
};
if (!c.size())
return chain<CbState>::create_and_complete(std::move(initial_state));
chain<CbState> ret;
state_t* state = new state_t {c.size(), ret.create_state(), std::move(initial_state) };
// create the lambda:
const auto lbd = [state, fnc = std::move(fnc)]<typename... Args>(Args&&... args)
{
fnc(state->data, std::forward<Args>(args)...);
--state->count;
if (state->count == 0)
{
state->state.complete(std::move(state->data));
delete state;
}
};
// register in the chains:
for (auto& it : c)
{
it.then(lbd);
}
return ret;
}
/// \brief return a chain that will be called when all the argument chains have completed.
/// \note multi-chain needs dynamic allocation for the state
/// \todo put that in a pool, as the state is the same size for each multi-chain
///
/// Accepts chains of different types.
/// If the chains are different, the provided function should be declared this way:
/// [/*...*/](CbState& state, auto&&... args) { /*...*/ };
template<typename CbState, typename Fnc, typename... Chains>
chain<CbState> multi_chain(CbState&& initial_state, Fnc&& fnc, Chains&&... chains)
{
using cb_state_t = std::remove_reference_t<CbState>;
struct state_t
{
std::atomic<uint64_t> count;
typename chain<CbState>::state state;
cb_state_t data;
};
if (!sizeof...(Chains))
return chain<CbState>::create_and_complete(std::move(initial_state));
chain<CbState> ret;
state_t* state = new state_t {sizeof...(Chains), ret.create_state(), std::move(initial_state) };
// create the lambda:
const auto lbd = [state, fnc = std::move(fnc)]<typename... Args>(Args&&... args)
{
fnc(state->data, std::forward<Args>(args)...);
--state->count;
if (state->count == 0)
{
state->state.complete(std::move(state->data));
delete state;
}
};
// register in the chains:
(chains.then(lbd), ...);
return ret;
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2019 The Open GEE 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
*
* 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 "StateUpdater.h"
#include "AssetVersionD.h"
#include "common/notify.h"
using namespace boost;
using namespace std;
// The depth_first_search function needs a way to map vertices to indexes. We
// store a unique index inside each vertex; the code below provides a way for
// boost to access them. These must be defined before including
// depth_first_search.hpp.
template <class Graph>
class InNodeVertexIndexMap {
public:
typedef readable_property_map_tag category;
typedef size_t value_type;
typedef value_type reference;
typedef typename Graph::vertex_descriptor key_type;
InNodeVertexIndexMap(const Graph & graph) : graph(graph) {};
const Graph & graph;
};
namespace boost {
template<>
struct property_map<StateUpdater::TreeType, vertex_index_t> {
typedef InNodeVertexIndexMap<StateUpdater::TreeType> const_type;
};
template<class Graph>
InNodeVertexIndexMap<Graph> get(vertex_index_t, const Graph & graph) {
return InNodeVertexIndexMap<Graph>(graph);
}
template<class Graph>
typename InNodeVertexIndexMap<Graph>::value_type get(
const InNodeVertexIndexMap<Graph> & map,
typename InNodeVertexIndexMap<Graph>::key_type vertex) {
return map.graph[vertex].index;
}
}
#include <boost/graph/depth_first_search.hpp>
StateUpdater::TreeType::vertex_descriptor
StateUpdater::BuildTree(const SharedString & ref) {
VertexMap vertices;
size_t index = 0;
list<TreeType::vertex_descriptor> toFillIn, toFillInNext;
// First create an empty vertex for the provided asset. Then fill it in,
// which includes adding its connections to other assets. Every time we fill
// in a node we will get new assets to add to the tree until all assets have
// been added. This basically builds the tree using a breadth first search,
// which allows us to keep memory usage (relatively) low by not forcing
// assets to stay in the cache and limiting the size of the toFillIn and
// toFillInNext lists.
auto myVertex = AddEmptyVertex(ref, vertices, index, toFillIn);
while (toFillIn.size() > 0) {
for (auto vertex : toFillIn) {
FillInVertex(vertex, vertices, index, toFillInNext);
}
toFillIn = std::move(toFillInNext);
toFillInNext.clear();
}
return myVertex;
}
// Creates an "empty" node for this asset if it has not already been added to
// the tree. The node has a default state and doesn't include links to
// inputs/children/etc. The vertex must be "filled in" by calling FillInVertex
// before it can be used.
StateUpdater::TreeType::vertex_descriptor
StateUpdater::AddEmptyVertex(
const SharedString & ref,
VertexMap & vertices,
size_t & index,
list<TreeType::vertex_descriptor> & toFillIn) {
auto myVertexIter = vertices.find(ref);
if (myVertexIter == vertices.end()) {
// I'm not in the graph yet, so make a new empty vertex and let the caller
// know we need to load it with the correct information
auto myVertex = add_vertex(tree);
tree[myVertex] = {ref, AssetDefs::New, index};
++index;
vertices[ref] = myVertex;
toFillIn.push_back(myVertex);
return myVertex;
}
else {
// I'm already in the graph, so just return my vertex descriptor.
return myVertexIter->second;
}
}
// "Fills in" an existing vertex with the state of an asset and its connections
// to other assets. Adds any new nodes that need to be filled in to toFillIn.
void StateUpdater::FillInVertex(
TreeType::vertex_descriptor myVertex,
VertexMap & vertices,
size_t & index,
list<TreeType::vertex_descriptor> & toFillIn) {
SharedString name = tree[myVertex].name;
notify(NFY_PROGRESS, "Loading '%s' for state update", name.toString().c_str());
AssetVersionD version(name);
if (!version) {
notify(NFY_WARN, "Could not load asset '%s' which is referenced by another asset.",
name.toString().c_str());
// Set it to a bad state, but use a state that can be fixed by another
// rebuild operation.
tree[myVertex].state = AssetDefs::Blocked;
return;
}
tree[myVertex].state = version->state;
vector<SharedString> dependents;
version->DependentChildren(dependents);
// Add the dependent children first. When we add the children next it will
// skip any that were already added
for (const auto & dep : dependents) {
auto depVertex = AddEmptyVertex(dep, vertices, index, toFillIn);
AddEdge(myVertex, depVertex, {DEPENDENT_CHILD});
}
for (const auto & child : version->children) {
auto childVertex = AddEmptyVertex(child, vertices, index, toFillIn);
AddEdge(myVertex, childVertex, {CHILD});
}
for (const auto & input : version->inputs) {
auto inputVertex = AddEmptyVertex(input, vertices, index, toFillIn);
AddEdge(myVertex, inputVertex, {INPUT});
}
for (const auto & parent : version->parents) {
auto parentVertex = AddEmptyVertex(parent, vertices, index, toFillIn);
AddEdge(parentVertex, myVertex, {CHILD});
}
for (const auto & listener : version->listeners) {
auto listenerVertex = AddEmptyVertex(listener, vertices, index, toFillIn);
AddEdge(listenerVertex, myVertex, {INPUT});
}
}
void StateUpdater::AddEdge(
TreeType::vertex_descriptor from,
TreeType::vertex_descriptor to,
AssetEdge data) {
auto edgeData = add_edge(from, to, tree);
// If this is a new edge, set the edge data. Also, if this is a dependent
// child it may have been added previously as a "normal" child.
if (edgeData.second || data.type == DEPENDENT_CHILD) {
tree[edgeData.first] = data;
}
}
void StateUpdater::SetStateForRefAndDependents(
const SharedString & ref,
AssetDefs::State newState,
std::function<bool(AssetDefs::State)> updateStatePredicate) {
auto refVertex = BuildTree(ref);
SetStateForVertexAndDependents(refVertex, newState, updateStatePredicate);
}
void StateUpdater::SetStateForVertexAndDependents(
TreeType::vertex_descriptor vertex,
AssetDefs::State newState,
std::function<bool(AssetDefs::State)> updateStatePredicate) {
if (updateStatePredicate(tree[vertex].state)) {
SharedString name = tree[vertex].name;
notify(NFY_PROGRESS, "Setting state of '%s' to '%s'",
name.toString().c_str(), ToString(newState).c_str());
{
// Limit the scope of the MutableAssetVersionD so that we release it
// as quickly as possible.
MutableAssetVersionD version(name);
if (version) {
// Set the state. The OnStateChange handler will take care
// of stopping any running tasks, etc
// false -> don't send notifications about the new state because we
// will change it soon.
version->SetMyStateOnly(newState, false);
}
else {
// This shoud never happen - we had to successfully load the asset
// previously to get it into the tree.
notify(NFY_WARN, "Could not load asset '%s' to set state.",
name.toString().c_str());
}
}
auto edgeIters = out_edges(vertex, tree);
auto edgeBegin = edgeIters.first;
auto edgeEnd = edgeIters.second;
for (auto i = edgeBegin; i != edgeEnd; ++i) {
if (tree[*i].type == DEPENDENT_CHILD) {
SetStateForVertexAndDependents(target(*i, tree), newState, updateStatePredicate);
}
}
}
}
class StateUpdater::UpdateStateVisitor : public default_dfs_visitor {
private:
class InputStates {
private:
uint numinputs = 0;
uint numgood = 0;
uint numblocking = 0;
uint numoffline = 0;
public:
void Add(AssetDefs::State inputState) {
++numinputs;
if (inputState == AssetDefs::Succeeded) {
++numgood;
} else if (inputState == AssetDefs::Offline) {
++numblocking;
++numoffline;
} else if (inputState & (AssetDefs::Blocked |
AssetDefs::Failed |
AssetDefs::Canceled |
AssetDefs::Bad)) {
++numblocking;
}
}
void GetOutputs(AssetDefs::State & stateByInputs, bool & blockersAreOffline, uint32 & numWaitingFor) {
if (numinputs == numgood) {
stateByInputs = AssetDefs::Queued;
} else if (numblocking) {
stateByInputs = AssetDefs::Blocked;
} else {
stateByInputs = AssetDefs::Waiting;
}
blockersAreOffline = (numblocking == numoffline);
if (stateByInputs == AssetDefs::Waiting) {
numWaitingFor = (numinputs - numgood);
} else {
numWaitingFor = 0;
}
}
};
class ChildStates {
private:
uint numkids = 0;
uint numgood = 0;
uint numblocking = 0;
uint numinprog = 0;
uint numfailed = 0;
public:
void Add(AssetDefs::State childState) {
++numkids;
if (childState == AssetDefs::Succeeded) {
++numgood;
} else if (childState == AssetDefs::Failed) {
++numfailed;
} else if (childState == AssetDefs::InProgress) {
++numinprog;
} else if (childState & (AssetDefs::Blocked |
AssetDefs::Canceled |
AssetDefs::Offline |
AssetDefs::Bad)) {
++numblocking;
}
}
void GetOutputs(AssetDefs::State & stateByChildren) {
if (numkids == numgood) {
stateByChildren = AssetDefs::Succeeded;
} else if (numblocking || numfailed) {
stateByChildren = AssetDefs::Blocked;
} else if (numgood || numinprog) {
stateByChildren = AssetDefs::InProgress;
} else {
stateByChildren = AssetDefs::Queued;
}
}
};
void CalculateStateParameters(
StateUpdater::TreeType::vertex_descriptor vertex,
const StateUpdater::TreeType & tree,
AssetDefs::State &stateByInputs,
AssetDefs::State &stateByChildren,
bool & blockersAreOffline,
uint32 & numWaitingFor) const {
InputStates inputStates;
ChildStates childStates;
auto edgeIters = out_edges(vertex, tree);
auto edgeBegin = edgeIters.first;
auto edgeEnd = edgeIters.second;
for (auto i = edgeBegin; i != edgeEnd; ++i) {
StateUpdater::DependencyType type = tree[*i].type;
StateUpdater::TreeType::vertex_descriptor dep = target(*i, tree);
AssetDefs::State depState = tree[dep].state;
switch(type) {
case StateUpdater::INPUT:
inputStates.Add(depState);
break;
case StateUpdater::CHILD:
case StateUpdater::DEPENDENT_CHILD:
childStates.Add(depState);
break;
}
}
inputStates.GetOutputs(stateByInputs, blockersAreOffline, numWaitingFor);
childStates.GetOutputs(stateByChildren);
}
public:
// Update the state of an asset after we've updated the state of its
// inputs and children.
virtual void finish_vertex(
StateUpdater::TreeType::vertex_descriptor vertex,
const StateUpdater::TreeType & tree) const {
SharedString name = tree[vertex].name;
notify(NFY_PROGRESS, "Calculating state for '%s'", name.toString().c_str());
AssetVersionD version(name);
if (!version) {
// This shoud never happen - we had to successfully load the asset
// previously to get it into the tree.
notify(NFY_WARN, "Could not load asset '%s' to recalculate state.",
name.toString().c_str());
return;
}
if (!version->NeedComputeState()) return;
AssetDefs::State stateByInputs;
AssetDefs::State stateByChildren;
bool blockersAreOffline;
uint32 numWaitingFor;
CalculateStateParameters(vertex, tree, stateByInputs, stateByChildren, blockersAreOffline, numWaitingFor);
AssetDefs::State newState =
version->CalcStateByInputsAndChildren(stateByInputs, stateByChildren, blockersAreOffline, numWaitingFor);
if (newState != tree[vertex].state) {
notify(NFY_PROGRESS, "Setting state of '%s' to '%s'",
name.toString().c_str(), ToString(newState).c_str());
MutableAssetVersionD mutableVersion(name);
if (!version) {
// This shoud never happen - we had to successfully load the asset
// previously to get it into the tree.
notify(NFY_WARN, "Could not load asset '%s' to set calculated state.",
name.toString().c_str());
return;
}
// Set the state and send notifications but don't propagate the change
// (we will take care of propagation during the graph traversal).
mutableVersion->SetMyStateOnly(newState);
// Update the state in the tree because other assets may need it to compute
// their own states. Use the state from the version because setting the
// state can sometimes trigger additional state changes.
// We const_cast here because the function signature forces us to pass
// the tree as a const.
const_cast<StateUpdater::TreeType&>(tree)[vertex].state = mutableVersion->state;
}
}
};
void StateUpdater::RecalculateAndSaveStates() {
// Traverse the state tree, recalculate states, and update states as needed.
// State is calculated for each vertex in the tree after state is calculated
// for all of its child and input vertices.
// Possible optimization: Many assets have significant overlap in their
// inputs. It might save time if we could calculate the overlapping state
// only once.
depth_first_search(tree, visitor(UpdateStateVisitor()));
}
<commit_msg>Enhance comments<commit_after>/*
* Copyright 2019 The Open GEE 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
*
* 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 "StateUpdater.h"
#include "AssetVersionD.h"
#include "common/notify.h"
using namespace boost;
using namespace std;
// The depth_first_search function needs a way to map vertices to indexes. We
// store a unique index inside each vertex; the code below provides a way for
// boost to access them. These must be defined before including
// depth_first_search.hpp.
template <class Graph>
class InNodeVertexIndexMap {
public:
typedef readable_property_map_tag category;
typedef size_t value_type;
typedef value_type reference;
typedef typename Graph::vertex_descriptor key_type;
InNodeVertexIndexMap(const Graph & graph) : graph(graph) {};
const Graph & graph;
};
namespace boost {
template<>
struct property_map<StateUpdater::TreeType, vertex_index_t> {
typedef InNodeVertexIndexMap<StateUpdater::TreeType> const_type;
};
template<class Graph>
InNodeVertexIndexMap<Graph> get(vertex_index_t, const Graph & graph) {
return InNodeVertexIndexMap<Graph>(graph);
}
template<class Graph>
typename InNodeVertexIndexMap<Graph>::value_type get(
const InNodeVertexIndexMap<Graph> & map,
typename InNodeVertexIndexMap<Graph>::key_type vertex) {
return map.graph[vertex].index;
}
}
#include <boost/graph/depth_first_search.hpp>
// Builds the asset version tree containing the specified asset version.
StateUpdater::TreeType::vertex_descriptor
StateUpdater::BuildTree(const SharedString & ref) {
VertexMap vertices;
size_t index = 0;
list<TreeType::vertex_descriptor> toFillIn, toFillInNext;
// First create an empty vertex for the provided asset. Then fill it in,
// which includes adding its connections to other assets. Every time we fill
// in a node we will get new assets to add to the tree until all assets have
// been added. This basically builds the tree using a breadth first search,
// which allows us to keep memory usage (relatively) low by not forcing
// assets to stay in the cache and limiting the size of the toFillIn and
// toFillInNext lists.
auto myVertex = AddEmptyVertex(ref, vertices, index, toFillIn);
while (toFillIn.size() > 0) {
for (auto vertex : toFillIn) {
FillInVertex(vertex, vertices, index, toFillInNext);
}
toFillIn = std::move(toFillInNext);
toFillInNext.clear();
}
return myVertex;
}
// Creates an "empty" node for this asset if it has not already been added to
// the tree. The node has a default state and doesn't include links to
// inputs/children/etc. The vertex must be "filled in" by calling FillInVertex
// before it can be used.
StateUpdater::TreeType::vertex_descriptor
StateUpdater::AddEmptyVertex(
const SharedString & ref,
VertexMap & vertices,
size_t & index,
list<TreeType::vertex_descriptor> & toFillIn) {
auto myVertexIter = vertices.find(ref);
if (myVertexIter == vertices.end()) {
// I'm not in the graph yet, so make a new empty vertex and let the caller
// know we need to load it with the correct information
auto myVertex = add_vertex(tree);
tree[myVertex] = {ref, AssetDefs::New, index};
++index;
vertices[ref] = myVertex;
toFillIn.push_back(myVertex);
return myVertex;
}
else {
// I'm already in the graph, so just return my vertex descriptor.
return myVertexIter->second;
}
}
// "Fills in" an existing vertex with the state of an asset and its connections
// to other assets. Adds any new nodes that need to be filled in to toFillIn.
void StateUpdater::FillInVertex(
TreeType::vertex_descriptor myVertex,
VertexMap & vertices,
size_t & index,
list<TreeType::vertex_descriptor> & toFillIn) {
SharedString name = tree[myVertex].name;
notify(NFY_PROGRESS, "Loading '%s' for state update", name.toString().c_str());
AssetVersionD version(name);
if (!version) {
notify(NFY_WARN, "Could not load asset '%s' which is referenced by another asset.",
name.toString().c_str());
// Set it to a bad state, but use a state that can be fixed by another
// rebuild operation.
tree[myVertex].state = AssetDefs::Blocked;
return;
}
tree[myVertex].state = version->state;
vector<SharedString> dependents;
version->DependentChildren(dependents);
// Add the dependent children first. When we add the children next it will
// skip any that were already added
for (const auto & dep : dependents) {
auto depVertex = AddEmptyVertex(dep, vertices, index, toFillIn);
AddEdge(myVertex, depVertex, {DEPENDENT_CHILD});
}
for (const auto & child : version->children) {
auto childVertex = AddEmptyVertex(child, vertices, index, toFillIn);
AddEdge(myVertex, childVertex, {CHILD});
}
for (const auto & input : version->inputs) {
auto inputVertex = AddEmptyVertex(input, vertices, index, toFillIn);
AddEdge(myVertex, inputVertex, {INPUT});
}
for (const auto & parent : version->parents) {
auto parentVertex = AddEmptyVertex(parent, vertices, index, toFillIn);
AddEdge(parentVertex, myVertex, {CHILD});
}
for (const auto & listener : version->listeners) {
auto listenerVertex = AddEmptyVertex(listener, vertices, index, toFillIn);
AddEdge(listenerVertex, myVertex, {INPUT});
}
}
void StateUpdater::AddEdge(
TreeType::vertex_descriptor from,
TreeType::vertex_descriptor to,
AssetEdge data) {
auto edgeData = add_edge(from, to, tree);
// If this is a new edge, set the edge data. Also, if this is a dependent
// child it may have been added previously as a "normal" child, so update
// the data in that case as well.
if (edgeData.second || data.type == DEPENDENT_CHILD) {
tree[edgeData.first] = data;
}
}
void StateUpdater::SetStateForRefAndDependents(
const SharedString & ref,
AssetDefs::State newState,
std::function<bool(AssetDefs::State)> updateStatePredicate) {
auto refVertex = BuildTree(ref);
SetStateForVertexAndDependents(refVertex, newState, updateStatePredicate);
}
// Sets the state for the specified ref and recursively sets the state for
// the ref's dependent children.
void StateUpdater::SetStateForVertexAndDependents(
TreeType::vertex_descriptor vertex,
AssetDefs::State newState,
std::function<bool(AssetDefs::State)> updateStatePredicate) {
if (updateStatePredicate(tree[vertex].state)) {
SharedString name = tree[vertex].name;
notify(NFY_PROGRESS, "Setting state of '%s' to '%s'",
name.toString().c_str(), ToString(newState).c_str());
{
// Limit the scope of the MutableAssetVersionD so that we release it
// as quickly as possible.
MutableAssetVersionD version(name);
if (version) {
// Set the state. The OnStateChange handler will take care
// of stopping any running tasks, etc
// false -> don't send notifications about the new state because we
// will change it soon.
version->SetMyStateOnly(newState, false);
}
else {
// This shoud never happen - we had to successfully load the asset
// previously to get it into the tree.
notify(NFY_WARN, "Could not load asset '%s' to set state.",
name.toString().c_str());
}
}
auto edgeIters = out_edges(vertex, tree);
auto edgeBegin = edgeIters.first;
auto edgeEnd = edgeIters.second;
for (auto i = edgeBegin; i != edgeEnd; ++i) {
if (tree[*i].type == DEPENDENT_CHILD) {
SetStateForVertexAndDependents(target(*i, tree), newState, updateStatePredicate);
}
}
}
}
// Helper class to calculate the state of asset versions based on the states
// of their inputs and children. It calculates states in depth-first order;
// we use the finish_vertex function to ensure that we calculate the state
// of an asset version after we've calculated the states of its inputs
// and children.
class StateUpdater::UpdateStateVisitor : public default_dfs_visitor {
private:
// Helper class for calculating state from inputs
class InputStates {
private:
uint numinputs = 0;
uint numgood = 0;
uint numblocking = 0;
uint numoffline = 0;
public:
void Add(AssetDefs::State inputState) {
++numinputs;
if (inputState == AssetDefs::Succeeded) {
++numgood;
} else if (inputState == AssetDefs::Offline) {
++numblocking;
++numoffline;
} else if (inputState & (AssetDefs::Blocked |
AssetDefs::Failed |
AssetDefs::Canceled |
AssetDefs::Bad)) {
++numblocking;
}
}
void GetOutputs(AssetDefs::State & stateByInputs, bool & blockersAreOffline, uint32 & numWaitingFor) {
if (numinputs == numgood) {
stateByInputs = AssetDefs::Queued;
} else if (numblocking) {
stateByInputs = AssetDefs::Blocked;
} else {
stateByInputs = AssetDefs::Waiting;
}
blockersAreOffline = (numblocking == numoffline);
if (stateByInputs == AssetDefs::Waiting) {
numWaitingFor = (numinputs - numgood);
} else {
numWaitingFor = 0;
}
}
};
// Helper class for calculating state from children
class ChildStates {
private:
uint numkids = 0;
uint numgood = 0;
uint numblocking = 0;
uint numinprog = 0;
uint numfailed = 0;
public:
void Add(AssetDefs::State childState) {
++numkids;
if (childState == AssetDefs::Succeeded) {
++numgood;
} else if (childState == AssetDefs::Failed) {
++numfailed;
} else if (childState == AssetDefs::InProgress) {
++numinprog;
} else if (childState & (AssetDefs::Blocked |
AssetDefs::Canceled |
AssetDefs::Offline |
AssetDefs::Bad)) {
++numblocking;
}
}
void GetOutputs(AssetDefs::State & stateByChildren) {
if (numkids == numgood) {
stateByChildren = AssetDefs::Succeeded;
} else if (numblocking || numfailed) {
stateByChildren = AssetDefs::Blocked;
} else if (numgood || numinprog) {
stateByChildren = AssetDefs::InProgress;
} else {
stateByChildren = AssetDefs::Queued;
}
}
};
// Loops through the inputs and children of an asset and calculates
// everything the asset verion needs to know to figure out its state. This
// data will be passed to the asset version so it can calculate its own
// state.
void CalculateStateParameters(
StateUpdater::TreeType::vertex_descriptor vertex,
const StateUpdater::TreeType & tree,
AssetDefs::State &stateByInputs,
AssetDefs::State &stateByChildren,
bool & blockersAreOffline,
uint32 & numWaitingFor) const {
InputStates inputStates;
ChildStates childStates;
auto edgeIters = out_edges(vertex, tree);
auto edgeBegin = edgeIters.first;
auto edgeEnd = edgeIters.second;
for (auto i = edgeBegin; i != edgeEnd; ++i) {
StateUpdater::DependencyType type = tree[*i].type;
StateUpdater::TreeType::vertex_descriptor dep = target(*i, tree);
AssetDefs::State depState = tree[dep].state;
switch(type) {
case StateUpdater::INPUT:
inputStates.Add(depState);
break;
case StateUpdater::CHILD:
case StateUpdater::DEPENDENT_CHILD:
childStates.Add(depState);
break;
}
}
inputStates.GetOutputs(stateByInputs, blockersAreOffline, numWaitingFor);
childStates.GetOutputs(stateByChildren);
}
public:
// Update the state of an asset after we've updated the state of its
// inputs and children.
virtual void finish_vertex(
StateUpdater::TreeType::vertex_descriptor vertex,
const StateUpdater::TreeType & tree) const {
SharedString name = tree[vertex].name;
notify(NFY_PROGRESS, "Calculating state for '%s'", name.toString().c_str());
AssetVersionD version(name);
if (!version) {
// This shoud never happen - we had to successfully load the asset
// previously to get it into the tree.
notify(NFY_WARN, "Could not load asset '%s' to recalculate state.",
name.toString().c_str());
return;
}
if (!version->NeedComputeState()) return;
AssetDefs::State stateByInputs;
AssetDefs::State stateByChildren;
bool blockersAreOffline;
uint32 numWaitingFor;
CalculateStateParameters(vertex, tree, stateByInputs, stateByChildren, blockersAreOffline, numWaitingFor);
AssetDefs::State newState =
version->CalcStateByInputsAndChildren(stateByInputs, stateByChildren, blockersAreOffline, numWaitingFor);
if (newState != tree[vertex].state) {
notify(NFY_PROGRESS, "Setting state of '%s' to '%s'",
name.toString().c_str(), ToString(newState).c_str());
MutableAssetVersionD mutableVersion(name);
if (!version) {
// This shoud never happen - we had to successfully load the asset
// previously to get it into the tree.
notify(NFY_WARN, "Could not load asset '%s' to set calculated state.",
name.toString().c_str());
return;
}
// Set the state and send notifications but don't propagate the change
// (we will take care of propagation during the graph traversal).
mutableVersion->SetMyStateOnly(newState);
// Update the state in the tree because other assets may need it to compute
// their own states. Use the state from the version because setting the
// state can sometimes trigger additional state changes.
// We const_cast here because the function signature forces us to pass
// the tree as a const.
const_cast<StateUpdater::TreeType&>(tree)[vertex].state = mutableVersion->state;
}
}
};
void StateUpdater::RecalculateAndSaveStates() {
// Traverse the state tree, recalculate states, and update states as needed.
// State is calculated for each vertex in the tree after state is calculated
// for all of its child and input vertices.
// Possible optimization: Many assets have significant overlap in their
// inputs. It might save time if we could calculate the overlapping state
// only once.
depth_first_search(tree, visitor(UpdateStateVisitor()));
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: toolbarcontrollerfactory.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2006-06-19 11:07:49 $
*
* 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 __FRAMEWORK_UIFACTORY_TOOLBARCONTROLLERFACTORY_HXX_
#define __FRAMEWORK_UIFACTORY_TOOLBARCONTROLLERFACTORY_HXX_
/** Attention: stl headers must(!) be included at first. Otherwhise it can make trouble
with solaris headers ...
*/
#include <vector>
#include <list>
#include <hash_map>
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_
#include <macros/xserviceinfo.hxx>
#endif
#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTICOMPONENTFACTORY_HPP_
#include <com/sun/star/lang/XMultiComponentFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XUICONTROLLERREGISTRATION_HPP_
#include <com/sun/star/frame/XUIControllerRegistration.hpp>
#endif
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
namespace framework
{
class ConfigurationAccess_ToolbarControllerFactory;
class ToolbarControllerFactory : public com::sun::star::lang::XTypeProvider ,
public com::sun::star::lang::XServiceInfo ,
public com::sun::star::lang::XMultiComponentFactory ,
public ::com::sun::star::frame::XUIControllerRegistration ,
private ThreadHelpBase , // Struct for right initalization of mutex member! Must be first of baseclasses.
public ::cppu::OWeakObject
{
public:
ToolbarControllerFactory( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager );
virtual ~ToolbarControllerFactory();
// XInterface, XTypeProvider, XServiceInfo
FWK_DECLARE_XINTERFACE
FWK_DECLARE_XTYPEPROVIDER
DECLARE_XSERVICEINFO
// XMultiComponentFactory
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceWithContext( const ::rtl::OUString& aServiceSpecifier, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& Context ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceWithArgumentsAndContext( const ::rtl::OUString& ServiceSpecifier, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& Arguments, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& Context ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getAvailableServiceNames() throw (::com::sun::star::uno::RuntimeException);
// XUIControllerRegistration
virtual sal_Bool SAL_CALL hasController( const ::rtl::OUString& aCommandURL, const rtl::OUString& aModuleName ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL registerController( const ::rtl::OUString& aCommandURL, const rtl::OUString& aModuleName, const ::rtl::OUString& aControllerImplementationName ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL deregisterController( const ::rtl::OUString& aCommandURL, const rtl::OUString& aModuleName ) throw (::com::sun::star::uno::RuntimeException);
private:
sal_Bool m_bConfigRead;
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xServiceManager;
ConfigurationAccess_ToolbarControllerFactory* m_pConfigAccess;
};
} // namespace framework
#endif // __FRAMEWORK_SERVICES_TOOLBARCONTROLLERFACTORY_HXX_
<commit_msg>INTEGRATION: CWS hr33 (1.4.138); FILE MERGED 2006/11/02 18:46:57 hr 1.4.138.2: RESYNC: (1.4-1.5); FILE MERGED 2006/05/03 16:02:15 hr 1.4.138.1: #i55967#: remove not needed STL includes<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: toolbarcontrollerfactory.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: vg $ $Date: 2006-11-22 10:42:05 $
*
* 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 __FRAMEWORK_UIFACTORY_TOOLBARCONTROLLERFACTORY_HXX_
#define __FRAMEWORK_UIFACTORY_TOOLBARCONTROLLERFACTORY_HXX_
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_
#include <macros/xserviceinfo.hxx>
#endif
#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTICOMPONENTFACTORY_HPP_
#include <com/sun/star/lang/XMultiComponentFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XUICONTROLLERREGISTRATION_HPP_
#include <com/sun/star/frame/XUIControllerRegistration.hpp>
#endif
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
namespace framework
{
class ConfigurationAccess_ToolbarControllerFactory;
class ToolbarControllerFactory : public com::sun::star::lang::XTypeProvider ,
public com::sun::star::lang::XServiceInfo ,
public com::sun::star::lang::XMultiComponentFactory ,
public ::com::sun::star::frame::XUIControllerRegistration ,
private ThreadHelpBase , // Struct for right initalization of mutex member! Must be first of baseclasses.
public ::cppu::OWeakObject
{
public:
ToolbarControllerFactory( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager );
virtual ~ToolbarControllerFactory();
// XInterface, XTypeProvider, XServiceInfo
FWK_DECLARE_XINTERFACE
FWK_DECLARE_XTYPEPROVIDER
DECLARE_XSERVICEINFO
// XMultiComponentFactory
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceWithContext( const ::rtl::OUString& aServiceSpecifier, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& Context ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceWithArgumentsAndContext( const ::rtl::OUString& ServiceSpecifier, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& Arguments, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& Context ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getAvailableServiceNames() throw (::com::sun::star::uno::RuntimeException);
// XUIControllerRegistration
virtual sal_Bool SAL_CALL hasController( const ::rtl::OUString& aCommandURL, const rtl::OUString& aModuleName ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL registerController( const ::rtl::OUString& aCommandURL, const rtl::OUString& aModuleName, const ::rtl::OUString& aControllerImplementationName ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL deregisterController( const ::rtl::OUString& aCommandURL, const rtl::OUString& aModuleName ) throw (::com::sun::star::uno::RuntimeException);
private:
sal_Bool m_bConfigRead;
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xServiceManager;
ConfigurationAccess_ToolbarControllerFactory* m_pConfigAccess;
};
} // namespace framework
#endif // __FRAMEWORK_SERVICES_TOOLBARCONTROLLERFACTORY_HXX_
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.