text stringlengths 54 60.6k |
|---|
<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 "config.h"
#include <wtf/HashSet.h>
#include <wtf/RefPtr.h>
#include <wtf/Vector.h>
#include "Document.h"
#include "Frame.h"
#include "Page.h"
#include "V8Binding.h"
#include "V8DOMWindow.h"
#include "V8Index.h"
#include "V8Proxy.h"
#undef LOG
#include "grit/webkit_resources.h"
#include "third_party/WebKit/WebKit/chromium/src/WebViewImpl.h"
#include "webkit/glue/devtools/debugger_agent_impl.h"
#include "webkit/glue/devtools/debugger_agent_manager.h"
#include "webkit/glue/glue_util.h"
#include "webkit/glue/webdevtoolsagent_impl.h"
#include "webkit/glue/webkit_glue.h"
using WebCore::DOMWindow;
using WebCore::Document;
using WebCore::Frame;
using WebCore::Page;
using WebCore::String;
using WebCore::V8ClassIndex;
using WebCore::V8Custom;
using WebCore::V8DOMWindow;
using WebCore::V8DOMWrapper;
using WebCore::V8Proxy;
using WebKit::WebViewImpl;
DebuggerAgentImpl::DebuggerAgentImpl(
WebViewImpl* web_view_impl,
DebuggerAgentDelegate* delegate,
WebDevToolsAgentImpl* webdevtools_agent)
: web_view_impl_(web_view_impl),
delegate_(delegate),
webdevtools_agent_(webdevtools_agent),
auto_continue_on_exception_(false) {
DebuggerAgentManager::DebugAttach(this);
}
DebuggerAgentImpl::~DebuggerAgentImpl() {
DebuggerAgentManager::DebugDetach(this);
}
void DebuggerAgentImpl::GetContextId() {
delegate_->SetContextId(webdevtools_agent_->host_id());
}
void DebuggerAgentImpl::DebuggerOutput(const String& command) {
delegate_->DebuggerOutput(command);
webdevtools_agent_->ForceRepaint();
}
// static
void DebuggerAgentImpl::CreateUtilityContext(
Frame* frame,
v8::Persistent<v8::Context>* context) {
v8::HandleScope scope;
// TODO(pfeldman): Validate against Soeren.
// Set up the DOM window as the prototype of the new global object.
v8::Handle<v8::Context> window_context =
V8Proxy::context(frame);
v8::Handle<v8::Object> window_global = window_context->Global();
v8::Handle<v8::Object> window_wrapper =
V8DOMWrapper::lookupDOMWrapper(V8ClassIndex::DOMWINDOW, window_global);
ASSERT(V8DOMWrapper::convertDOMWrapperToNative<DOMWindow>(window_wrapper) ==
frame->domWindow());
v8::Handle<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New();
// TODO(yurys): provide a function in v8 bindings that would make the
// utility context more like main world context of the inspected frame,
// otherwise we need to manually make it satisfy various invariants
// that V8Proxy::getEntered and some other V8Proxy methods expect to find
// on v8 contexts on the contexts stack.
// See V8Proxy::createNewContext.
//
// Install a security handler with V8.
global_template->SetAccessCheckCallbacks(
V8Custom::v8DOMWindowNamedSecurityCheck,
V8Custom::v8DOMWindowIndexedSecurityCheck,
v8::Integer::New(V8ClassIndex::DOMWINDOW));
// We set number of internal fields to match that in V8DOMWindow wrapper.
// See http://crbug.com/28961
global_template->SetInternalFieldCount(
V8Custom::kDOMWindowInternalFieldCount);
*context = v8::Context::New(
NULL /* no extensions */,
global_template,
v8::Handle<v8::Object>());
v8::Context::Scope context_scope(*context);
v8::Handle<v8::Object> global = (*context)->Global();
v8::Handle<v8::String> implicit_proto_string = v8::String::New("__proto__");
global->Set(implicit_proto_string, window_wrapper);
// Give the code running in the new context a way to get access to the
// original context.
global->Set(v8::String::New("contentWindow"), window_global);
// Inject javascript into the context.
base::StringPiece basejs = webkit_glue::GetDataResource(IDR_DEVTOOLS_BASE_JS);
v8::Script::Compile(v8::String::New(basejs.as_string().c_str()))->Run();
base::StringPiece injectjs_webkit =
webkit_glue::GetDataResource(IDR_DEVTOOLS_INJECT_WEBKIT_JS);
v8::Script::Compile(
v8::String::New(injectjs_webkit.as_string().c_str()))->Run();
base::StringPiece inject_dispatchjs = webkit_glue::GetDataResource(
IDR_DEVTOOLS_INJECT_DISPATCH_JS);
v8::Script::Compile(v8::String::New(
inject_dispatchjs.as_string().c_str()))->Run();
}
String DebuggerAgentImpl::ExecuteUtilityFunction(
v8::Handle<v8::Context> context,
int call_id,
const char* object,
const String &function_name,
const String& json_args,
bool async,
String* exception) {
v8::HandleScope scope;
ASSERT(!context.IsEmpty());
if (context.IsEmpty()) {
*exception = "No window context.";
return "";
}
v8::Context::Scope context_scope(context);
DebuggerAgentManager::UtilityContextScope utility_scope;
v8::Handle<v8::Object> dispatch_object = v8::Handle<v8::Object>::Cast(
context->Global()->Get(v8::String::New(object)));
v8::Handle<v8::Value> dispatch_function =
dispatch_object->Get(v8::String::New("dispatch"));
ASSERT(dispatch_function->IsFunction());
v8::Handle<v8::Function> function = v8::Handle<v8::Function>::Cast(dispatch_function);
v8::Handle<v8::String> function_name_wrapper = v8::Handle<v8::String>(
v8::String::New(function_name.utf8().data()));
v8::Handle<v8::String> json_args_wrapper = v8::Handle<v8::String>(
v8::String::New(json_args.utf8().data()));
v8::Handle<v8::Number> call_id_wrapper = v8::Handle<v8::Number>(
v8::Number::New(async ? call_id : 0));
v8::Handle<v8::Value> args[] = {
function_name_wrapper,
json_args_wrapper,
call_id_wrapper
};
v8::TryCatch try_catch;
v8::Handle<v8::Value> res_obj = function->Call(context->Global(), 3, args);
if (try_catch.HasCaught()) {
*exception = WebCore::toWebCoreString(try_catch.Message()->Get());
return "";
} else {
return WebCore::toWebCoreStringWithNullCheck(res_obj);
}
}
void DebuggerAgentImpl::ExecuteVoidJavaScript(v8::Handle<v8::Context> context) {
v8::HandleScope scope;
ASSERT(!context.IsEmpty());
v8::Context::Scope context_scope(context);
DebuggerAgentManager::UtilityContextScope utility_scope;
v8::Handle<v8::Value> function =
context->Global()->Get(v8::String::New("devtools$$void"));
ASSERT(function->IsFunction());
v8::Handle<v8::Value> args[] = {
v8::Local<v8::Value>()
};
v8::Handle<v8::Function>::Cast(function)->Call(context->Global(), 0, args);
}
WebCore::Page* DebuggerAgentImpl::GetPage() {
return web_view_impl_->page();
}
<commit_msg>DevTools: don't load base.js into injected script.<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 "config.h"
#include <wtf/HashSet.h>
#include <wtf/RefPtr.h>
#include <wtf/Vector.h>
#include "Document.h"
#include "Frame.h"
#include "Page.h"
#include "V8Binding.h"
#include "V8DOMWindow.h"
#include "V8Index.h"
#include "V8Proxy.h"
#undef LOG
#include "grit/webkit_resources.h"
#include "third_party/WebKit/WebKit/chromium/src/WebViewImpl.h"
#include "webkit/glue/devtools/debugger_agent_impl.h"
#include "webkit/glue/devtools/debugger_agent_manager.h"
#include "webkit/glue/glue_util.h"
#include "webkit/glue/webdevtoolsagent_impl.h"
#include "webkit/glue/webkit_glue.h"
using WebCore::DOMWindow;
using WebCore::Document;
using WebCore::Frame;
using WebCore::Page;
using WebCore::String;
using WebCore::V8ClassIndex;
using WebCore::V8Custom;
using WebCore::V8DOMWindow;
using WebCore::V8DOMWrapper;
using WebCore::V8Proxy;
using WebKit::WebViewImpl;
DebuggerAgentImpl::DebuggerAgentImpl(
WebViewImpl* web_view_impl,
DebuggerAgentDelegate* delegate,
WebDevToolsAgentImpl* webdevtools_agent)
: web_view_impl_(web_view_impl),
delegate_(delegate),
webdevtools_agent_(webdevtools_agent),
auto_continue_on_exception_(false) {
DebuggerAgentManager::DebugAttach(this);
}
DebuggerAgentImpl::~DebuggerAgentImpl() {
DebuggerAgentManager::DebugDetach(this);
}
void DebuggerAgentImpl::GetContextId() {
delegate_->SetContextId(webdevtools_agent_->host_id());
}
void DebuggerAgentImpl::DebuggerOutput(const String& command) {
delegate_->DebuggerOutput(command);
webdevtools_agent_->ForceRepaint();
}
// static
void DebuggerAgentImpl::CreateUtilityContext(
Frame* frame,
v8::Persistent<v8::Context>* context) {
v8::HandleScope scope;
// TODO(pfeldman): Validate against Soeren.
// Set up the DOM window as the prototype of the new global object.
v8::Handle<v8::Context> window_context =
V8Proxy::context(frame);
v8::Handle<v8::Object> window_global = window_context->Global();
v8::Handle<v8::Object> window_wrapper =
V8DOMWrapper::lookupDOMWrapper(V8ClassIndex::DOMWINDOW, window_global);
ASSERT(V8DOMWrapper::convertDOMWrapperToNative<DOMWindow>(window_wrapper) ==
frame->domWindow());
v8::Handle<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New();
// TODO(yurys): provide a function in v8 bindings that would make the
// utility context more like main world context of the inspected frame,
// otherwise we need to manually make it satisfy various invariants
// that V8Proxy::getEntered and some other V8Proxy methods expect to find
// on v8 contexts on the contexts stack.
// See V8Proxy::createNewContext.
//
// Install a security handler with V8.
global_template->SetAccessCheckCallbacks(
V8Custom::v8DOMWindowNamedSecurityCheck,
V8Custom::v8DOMWindowIndexedSecurityCheck,
v8::Integer::New(V8ClassIndex::DOMWINDOW));
// We set number of internal fields to match that in V8DOMWindow wrapper.
// See http://crbug.com/28961
global_template->SetInternalFieldCount(
V8Custom::kDOMWindowInternalFieldCount);
*context = v8::Context::New(
NULL /* no extensions */,
global_template,
v8::Handle<v8::Object>());
v8::Context::Scope context_scope(*context);
v8::Handle<v8::Object> global = (*context)->Global();
v8::Handle<v8::String> implicit_proto_string = v8::String::New("__proto__");
global->Set(implicit_proto_string, window_wrapper);
// Give the code running in the new context a way to get access to the
// original context.
global->Set(v8::String::New("contentWindow"), window_global);
// Inject javascript into the context.
base::StringPiece injectjs_webkit =
webkit_glue::GetDataResource(IDR_DEVTOOLS_INJECT_WEBKIT_JS);
v8::Script::Compile(
v8::String::New(injectjs_webkit.as_string().c_str()))->Run();
base::StringPiece inject_dispatchjs = webkit_glue::GetDataResource(
IDR_DEVTOOLS_INJECT_DISPATCH_JS);
v8::Script::Compile(v8::String::New(
inject_dispatchjs.as_string().c_str()))->Run();
}
String DebuggerAgentImpl::ExecuteUtilityFunction(
v8::Handle<v8::Context> context,
int call_id,
const char* object,
const String &function_name,
const String& json_args,
bool async,
String* exception) {
v8::HandleScope scope;
ASSERT(!context.IsEmpty());
if (context.IsEmpty()) {
*exception = "No window context.";
return "";
}
v8::Context::Scope context_scope(context);
DebuggerAgentManager::UtilityContextScope utility_scope;
v8::Handle<v8::Object> dispatch_object = v8::Handle<v8::Object>::Cast(
context->Global()->Get(v8::String::New(object)));
v8::Handle<v8::Value> dispatch_function =
dispatch_object->Get(v8::String::New("dispatch"));
ASSERT(dispatch_function->IsFunction());
v8::Handle<v8::Function> function = v8::Handle<v8::Function>::Cast(dispatch_function);
v8::Handle<v8::String> function_name_wrapper = v8::Handle<v8::String>(
v8::String::New(function_name.utf8().data()));
v8::Handle<v8::String> json_args_wrapper = v8::Handle<v8::String>(
v8::String::New(json_args.utf8().data()));
v8::Handle<v8::Number> call_id_wrapper = v8::Handle<v8::Number>(
v8::Number::New(async ? call_id : 0));
v8::Handle<v8::Value> args[] = {
function_name_wrapper,
json_args_wrapper,
call_id_wrapper
};
v8::TryCatch try_catch;
v8::Handle<v8::Value> res_obj = function->Call(context->Global(), 3, args);
if (try_catch.HasCaught()) {
*exception = WebCore::toWebCoreString(try_catch.Message()->Get());
return "";
} else {
return WebCore::toWebCoreStringWithNullCheck(res_obj);
}
}
void DebuggerAgentImpl::ExecuteVoidJavaScript(v8::Handle<v8::Context> context) {
v8::HandleScope scope;
ASSERT(!context.IsEmpty());
v8::Context::Scope context_scope(context);
DebuggerAgentManager::UtilityContextScope utility_scope;
v8::Handle<v8::Value> function =
context->Global()->Get(v8::String::New("devtools$$void"));
ASSERT(function->IsFunction());
v8::Handle<v8::Value> args[] = {
v8::Local<v8::Value>()
};
v8::Handle<v8::Function>::Cast(function)->Call(context->Global(), 0, args);
}
WebCore::Page* DebuggerAgentImpl::GetPage() {
return web_view_impl_->page();
}
<|endoftext|> |
<commit_before>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkTypes.h"
#if defined(SK_BUILD_FOR_WIN)
#include <GL/gl.h>
#include <d3d9.h>
#include <WindowsX.h>
#include "SkWindow.h"
#include "SkCanvas.h"
#include "SkOSMenu.h"
#include "SkTime.h"
#include "SkUtils.h"
#include "SkGraphics.h"
#define INVALIDATE_DELAY_MS 200
static SkOSWindow* gCurrOSWin;
static HWND gEventTarget;
#define WM_EVENT_CALLBACK (WM_USER+0)
void post_skwinevent()
{
PostMessage(gEventTarget, WM_EVENT_CALLBACK, 0, 0);
}
SkOSWindow::SkOSWindow(void* hWnd) : fHWND(hWnd),
fHGLRC(NULL),
fGLAttached(false),
fD3D9Device(NULL),
fD3D9Attached(FALSE) {
gEventTarget = (HWND)hWnd;
}
SkOSWindow::~SkOSWindow() {
if (NULL != fD3D9Device) {
((IDirect3DDevice9*)fD3D9Device)->Release();
}
if (NULL != fHGLRC) {
wglDeleteContext((HGLRC)fHGLRC);
}
}
static SkKey winToskKey(WPARAM vk) {
static const struct {
WPARAM fVK;
SkKey fKey;
} gPair[] = {
{ VK_BACK, kBack_SkKey },
{ VK_CLEAR, kBack_SkKey },
{ VK_RETURN, kOK_SkKey },
{ VK_UP, kUp_SkKey },
{ VK_DOWN, kDown_SkKey },
{ VK_LEFT, kLeft_SkKey },
{ VK_RIGHT, kRight_SkKey }
};
for (size_t i = 0; i < SK_ARRAY_COUNT(gPair); i++) {
if (gPair[i].fVK == vk) {
return gPair[i].fKey;
}
}
return kNONE_SkKey;
}
bool SkOSWindow::wndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
switch (message) {
case WM_KEYDOWN: {
SkKey key = winToskKey(wParam);
if (kNONE_SkKey != key) {
this->handleKey(key);
return true;
}
} break;
case WM_KEYUP: {
SkKey key = winToskKey(wParam);
if (kNONE_SkKey != key) {
this->handleKeyUp(key);
return true;
}
} break;
case WM_UNICHAR:
this->handleChar(wParam);
return true;
case WM_CHAR: {
this->handleChar(SkUTF8_ToUnichar((char*)&wParam));
return true;
} break;
case WM_SIZE:
this->resize(lParam & 0xFFFF, lParam >> 16);
break;
case WM_PAINT: {
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
this->doPaint(hdc);
EndPaint(hWnd, &ps);
return true;
} break;
case WM_TIMER: {
RECT* rect = (RECT*)wParam;
InvalidateRect(hWnd, rect, FALSE);
KillTimer(hWnd, (UINT_PTR)rect);
delete rect;
return true;
} break;
case WM_LBUTTONDOWN:
this->handleClick(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), Click::kDown_State);
return true;
case WM_MOUSEMOVE:
this->handleClick(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), Click::kMoved_State);
return true;
case WM_LBUTTONUP:
this->handleClick(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), Click::kUp_State);
return true;
case WM_EVENT_CALLBACK:
if (SkEvent::ProcessEvent()) {
post_skwinevent();
}
return true;
}
return false;
}
void SkOSWindow::doPaint(void* ctx) {
this->update(NULL);
if (!fGLAttached && !fD3D9Attached)
{
HDC hdc = (HDC)ctx;
const SkBitmap& bitmap = this->getBitmap();
BITMAPINFO bmi;
memset(&bmi, 0, sizeof(bmi));
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth = bitmap.width();
bmi.bmiHeader.biHeight = -bitmap.height(); // top-down image
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biCompression = BI_RGB;
bmi.bmiHeader.biSizeImage = 0;
//
// Do the SetDIBitsToDevice.
//
// TODO(wjmaclean):
// Fix this call to handle SkBitmaps that have rowBytes != width,
// i.e. may have padding at the end of lines. The SkASSERT below
// may be ignored by builds, and the only obviously safe option
// seems to be to copy the bitmap to a temporary (contiguous)
// buffer before passing to SetDIBitsToDevice().
SkASSERT(bitmap.width() * bitmap.bytesPerPixel() == bitmap.rowBytes());
bitmap.lockPixels();
int iRet = SetDIBitsToDevice(hdc,
0, 0,
bitmap.width(), bitmap.height(),
0, 0,
0, bitmap.height(),
bitmap.getPixels(),
&bmi,
DIB_RGB_COLORS);
bitmap.unlockPixels();
}
}
#if 0
void SkOSWindow::updateSize()
{
RECT r;
GetWindowRect((HWND)this->getHWND(), &r);
this->resize(r.right - r.left, r.bottom - r.top);
}
#endif
void SkOSWindow::onHandleInval(const SkIRect& r) {
RECT* rect = new RECT;
rect->left = r.fLeft;
rect->top = r.fTop;
rect->right = r.fRight;
rect->bottom = r.fBottom;
SetTimer((HWND)fHWND, (UINT_PTR)rect, INVALIDATE_DELAY_MS, NULL);
}
void SkOSWindow::onAddMenu(const SkOSMenu* sk_menu)
{
}
void SkOSWindow::onSetTitle(const char title[]){
SetWindowTextA((HWND)fHWND, title);
}
enum {
SK_MacReturnKey = 36,
SK_MacDeleteKey = 51,
SK_MacEndKey = 119,
SK_MacLeftKey = 123,
SK_MacRightKey = 124,
SK_MacDownKey = 125,
SK_MacUpKey = 126,
SK_Mac0Key = 0x52,
SK_Mac1Key = 0x53,
SK_Mac2Key = 0x54,
SK_Mac3Key = 0x55,
SK_Mac4Key = 0x56,
SK_Mac5Key = 0x57,
SK_Mac6Key = 0x58,
SK_Mac7Key = 0x59,
SK_Mac8Key = 0x5b,
SK_Mac9Key = 0x5c
};
static SkKey raw2key(uint32_t raw)
{
static const struct {
uint32_t fRaw;
SkKey fKey;
} gKeys[] = {
{ SK_MacUpKey, kUp_SkKey },
{ SK_MacDownKey, kDown_SkKey },
{ SK_MacLeftKey, kLeft_SkKey },
{ SK_MacRightKey, kRight_SkKey },
{ SK_MacReturnKey, kOK_SkKey },
{ SK_MacDeleteKey, kBack_SkKey },
{ SK_MacEndKey, kEnd_SkKey },
{ SK_Mac0Key, k0_SkKey },
{ SK_Mac1Key, k1_SkKey },
{ SK_Mac2Key, k2_SkKey },
{ SK_Mac3Key, k3_SkKey },
{ SK_Mac4Key, k4_SkKey },
{ SK_Mac5Key, k5_SkKey },
{ SK_Mac6Key, k6_SkKey },
{ SK_Mac7Key, k7_SkKey },
{ SK_Mac8Key, k8_SkKey },
{ SK_Mac9Key, k9_SkKey }
};
for (unsigned i = 0; i < SK_ARRAY_COUNT(gKeys); i++)
if (gKeys[i].fRaw == raw)
return gKeys[i].fKey;
return kNONE_SkKey;
}
///////////////////////////////////////////////////////////////////////////////////////
void SkEvent::SignalNonEmptyQueue()
{
post_skwinevent();
//SkDebugf("signal nonempty\n");
}
static UINT_PTR gTimer;
VOID CALLBACK sk_timer_proc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime)
{
SkEvent::ServiceQueueTimer();
//SkDebugf("timer task fired\n");
}
void SkEvent::SignalQueueTimer(SkMSec delay)
{
if (gTimer)
{
KillTimer(NULL, gTimer);
gTimer = NULL;
}
if (delay)
{
gTimer = SetTimer(NULL, 0, delay, sk_timer_proc);
//SkDebugf("SetTimer of %d returned %d\n", delay, gTimer);
}
}
#if defined(UNICODE)
#define STR_LIT(X) L## #X
#else
#define STR_LIT(X) #X
#endif
static HWND create_dummy()
{
HMODULE module = GetModuleHandle(NULL);
HWND dummy;
RECT windowRect;
windowRect.left = 0;
windowRect.right = 8;
windowRect.top = 0;
windowRect.bottom = 8;
WNDCLASS wc;
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wc.lpfnWndProc = (WNDPROC) DefWindowProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = module;
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = NULL;
wc.lpszMenuName = NULL;
wc.lpszClassName = STR_LIT("DummyClass");
if(!RegisterClass(&wc))
{
return 0;
}
DWORD style, exStyle;
exStyle = WS_EX_CLIENTEDGE;
style = WS_SYSMENU;
AdjustWindowRectEx(&windowRect, style, false, exStyle);
if(!(dummy = CreateWindowEx(exStyle,
STR_LIT("DummyClass"),
STR_LIT("DummyWindow"),
WS_CLIPSIBLINGS | WS_CLIPCHILDREN | style,
0, 0,
windowRect.right-windowRect.left,
windowRect.bottom-windowRect.top,
NULL, NULL,
module,
NULL)))
{
UnregisterClass(STR_LIT("DummyClass"), module);
return NULL;
}
ShowWindow(dummy, SW_HIDE);
return dummy;
}
void kill_dummy(HWND dummy) {
DestroyWindow(dummy);
HMODULE module = GetModuleHandle(NULL);
UnregisterClass(STR_LIT("DummyClass"), module);
}
// WGL_ARB_pixel_format
#define WGL_DRAW_TO_WINDOW_ARB 0x2001
#define WGL_ACCELERATION_ARB 0x2003
#define WGL_SUPPORT_OPENGL_ARB 0x2010
#define WGL_DOUBLE_BUFFER_ARB 0x2011
#define WGL_COLOR_BITS_ARB 0x2014
#define WGL_ALPHA_BITS_ARB 0x201B
#define WGL_STENCIL_BITS_ARB 0x2023
#define WGL_FULL_ACCELERATION_ARB 0x2027
// WGL_ARB_multisample
#define WGL_SAMPLE_BUFFERS_ARB 0x2041
#define WGL_SAMPLES_ARB 0x2042
#define USE_MSAA 0
HGLRC create_gl(HWND hwnd) {
HDC hdc;
HDC prevHDC;
HGLRC prevGLRC, glrc;
PIXELFORMATDESCRIPTOR pfd;
prevGLRC = wglGetCurrentContext();
prevHDC = wglGetCurrentDC();
int format = 0;
typedef BOOL (WINAPI *WGLChoosePixelFormatFunc)(HDC hdc,
const int *,
const FLOAT *,
UINT nMaxFormats,
int *,
UINT *);
static WGLChoosePixelFormatFunc wglChoosePixelFormatARB;
// This is horrible but true: wglGetProcAddress cannot be called before a
// context is created. SetPixelFormat also needs to be called before the
// context is created. But SetPixelFormat is only allowed to succeed once per
// window. So we need to create a dummy window in order to call
// wglGetProcAddress to get wglChoosePixelFormatARB.
if (NULL == wglChoosePixelFormatARB) {
ZeroMemory(&pfd, sizeof(pfd));
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 32;
pfd.cDepthBits = 0;
pfd.cStencilBits = 8;
pfd.iLayerType = PFD_MAIN_PLANE;
HWND dummy = create_dummy();
SkASSERT(NULL != dummy);
hdc = GetDC(dummy);
format = ChoosePixelFormat(hdc, &pfd);
SetPixelFormat(hdc, format, &pfd);
glrc = wglCreateContext(hdc);
SkASSERT(glrc);
wglMakeCurrent(hdc, glrc);
wglChoosePixelFormatARB = (WGLChoosePixelFormatFunc) wglGetProcAddress("wglChoosePixelFormatARB");
wglMakeCurrent(hdc, NULL);
wglDeleteContext(glrc);
glrc = 0;
kill_dummy(dummy);
if (NULL == wglChoosePixelFormatARB) {
return 0;
}
}
hdc = GetDC(hwnd);
format = 0;
GLint iattrs[] = {
WGL_DRAW_TO_WINDOW_ARB, TRUE,
WGL_DOUBLE_BUFFER_ARB, TRUE,
WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB,
WGL_SUPPORT_OPENGL_ARB, TRUE,
WGL_COLOR_BITS_ARB, 24,
WGL_ALPHA_BITS_ARB, 8,
WGL_STENCIL_BITS_ARB, 8,
#if USE_MSAA
WGL_SAMPLE_BUFFERS_ARB, TRUE,
WGL_SAMPLES_ARB, 0,
#else
0, 0, 0, 0,
#endif
0,0
};
for (int samples = 16; samples > 1; --samples) {
iattrs[15] = samples;
GLfloat fattrs[] = {0,0};
GLuint num;
int formats[64];
wglChoosePixelFormatARB(hdc, iattrs, fattrs, 64, formats, &num);
num = min(num,64);
for (GLuint i = 0; i < num; ++i) {
DescribePixelFormat(hdc, formats[i], sizeof(pfd), &pfd);
if (SetPixelFormat(hdc, formats[i], &pfd)) {
format = formats[i];
break;
}
}
}
if (0 == format) {
iattrs[12] = iattrs[13] = 0;
GLfloat fattrs[] = {0,0};
GLuint num;
wglChoosePixelFormatARB(hdc, iattrs, fattrs, 1, &format, &num);
DescribePixelFormat(hdc, format, sizeof(pfd), &pfd);
BOOL set = SetPixelFormat(hdc, format, &pfd);
SkASSERT(TRUE == set);
}
glrc = wglCreateContext(hdc);
SkASSERT(glrc);
wglMakeCurrent(prevHDC, prevGLRC);
return glrc;
}
bool SkOSWindow::attachGL() {
if (NULL == fHGLRC) {
fHGLRC = create_gl((HWND)fHWND);
if (NULL == fHGLRC) {
return false;
}
glClearStencil(0);
glClearColor(0, 0, 0, 0);
glStencilMask(0xffffffff);
glClear(GL_STENCIL_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
}
if (wglMakeCurrent(GetDC((HWND)fHWND), (HGLRC)fHGLRC)) {
glViewport(0, 0, SkScalarRound(this->width()),
SkScalarRound(this->height()));
fGLAttached = true;
return true;
}
return false;
}
void SkOSWindow::detachGL() {
wglMakeCurrent(GetDC((HWND)fHWND), 0);
fGLAttached = false;
}
void SkOSWindow::presentGL() {
glFlush();
SwapBuffers(GetDC((HWND)fHWND));
}
IDirect3DDevice9* create_d3d9_device(HWND hwnd) {
HRESULT hr;
IDirect3D9* d3d9;
d3d9 = Direct3DCreate9(D3D_SDK_VERSION);
if (NULL == d3d9) {
return NULL;
}
D3DDEVTYPE devType = D3DDEVTYPE_HAL;
//D3DDEVTYPE devType = D3DDEVTYPE_REF;
DWORD qLevels;
DWORD qLevelsDepth;
D3DMULTISAMPLE_TYPE type;
for (type = D3DMULTISAMPLE_16_SAMPLES;
type >= D3DMULTISAMPLE_NONMASKABLE; --(*(DWORD*)&type)) {
hr = d3d9->CheckDeviceMultiSampleType(D3DADAPTER_DEFAULT,
devType, D3DFMT_D24S8, TRUE,
type, &qLevels);
qLevels = (hr == D3D_OK) ? qLevels : 0;
hr = d3d9->CheckDeviceMultiSampleType(D3DADAPTER_DEFAULT,
devType, D3DFMT_A8R8G8B8, TRUE,
type, &qLevelsDepth);
qLevelsDepth = (hr == D3D_OK) ? qLevelsDepth : 0;
qLevels = min(qLevels,qLevelsDepth);
if (qLevels > 0) {
break;
}
}
qLevels = 0;
IDirect3DDevice9* d3d9Device;
D3DPRESENT_PARAMETERS pres;
memset(&pres, 0, sizeof(pres));
pres.EnableAutoDepthStencil = TRUE;
pres.AutoDepthStencilFormat = D3DFMT_D24S8;
pres.BackBufferCount = 2;
pres.BackBufferFormat = D3DFMT_A8R8G8B8;
pres.BackBufferHeight = 0;
pres.BackBufferWidth = 0;
if (qLevels > 0) {
pres.MultiSampleType = type;
pres.MultiSampleQuality = qLevels-1;
} else {
pres.MultiSampleType = D3DMULTISAMPLE_NONE;
pres.MultiSampleQuality = 0;
}
pres.SwapEffect = D3DSWAPEFFECT_DISCARD;
pres.Windowed = TRUE;
pres.hDeviceWindow = hwnd;
pres.PresentationInterval = 1;
pres.Flags = 0;
hr = d3d9->CreateDevice(D3DADAPTER_DEFAULT,
devType,
hwnd,
D3DCREATE_HARDWARE_VERTEXPROCESSING,
&pres,
&d3d9Device);
D3DERR_INVALIDCALL;
if (SUCCEEDED(hr)) {
d3d9Device->Clear(0, NULL, D3DCLEAR_TARGET, 0xFFFFFFFF, 0, 0);
return d3d9Device;
}
return NULL;
}
// This needs some improvement. D3D doesn't have the same notion of attach/detach
// as GL. However, just allowing GDI to write to the window after creating the
// D3D device seems to work.
// We need to handle resizing. On XP and earlier Reset() will trash all our textures
// so we would need to inform the SkGpu/caches or just recreate them. On Vista+ we
// could use an IDirect3DDevice9Ex and call ResetEx() to resize without trashing
// everything. Currently we do nothing and the D3D9 image gets stretched/compressed
// when resized.
bool SkOSWindow::attachD3D9() {
if (NULL == fD3D9Device) {
fD3D9Device = (void*) create_d3d9_device((HWND)fHWND);
}
if (NULL != fD3D9Device) {
((IDirect3DDevice9*)fD3D9Device)->BeginScene();
fD3D9Attached = true;
}
return fD3D9Attached;
}
void SkOSWindow::detachD3D9() {
if (NULL != fD3D9Device) {
((IDirect3DDevice9*)fD3D9Device)->EndScene();
}
fD3D9Attached = false;
}
void SkOSWindow::presentD3D9() {
if (NULL != fD3D9Device) {
HRESULT hr;
hr = ((IDirect3DDevice9*)fD3D9Device)->EndScene();
SkASSERT(SUCCEEDED(hr));
hr = ((IDirect3DDevice9*)d3d9Device())->Present(NULL, NULL, NULL, NULL);
SkASSERT(SUCCEEDED(hr));
hr = ((IDirect3DDevice9*)fD3D9Device)->Clear(0,NULL,D3DCLEAR_TARGET |
D3DCLEAR_STENCIL, 0x0, 0,
0);
SkASSERT(SUCCEEDED(hr));
hr = ((IDirect3DDevice9*)fD3D9Device)->BeginScene();
SkASSERT(SUCCEEDED(hr));
}
}
#endif
<commit_msg>remove SkOSWindow_Win.cpp (has been replaced by SkOSWindow_win.cpp [lowercase w])<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: LTables.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 05:48:22 $
*
* 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 _CONNECTIVITY_EVOAB_LTABLES_HXX_
#define _CONNECTIVITY_EVOAB_LTABLES_HXX_
#ifndef _CONNECTIVITY_FILE_TABLES_HXX_
#include "file/FTables.hxx"
#endif
namespace connectivity
{
namespace evoab
{
// namespace ::com::sun::star::sdbcx = ::com::sun::star::sdbcx;
typedef file::OTables OEvoabTables_BASE;
class OEvoabTables : public OEvoabTables_BASE
{
protected:
virtual sdbcx::ObjectType createObject(const ::rtl::OUString& _rName);
public:
OEvoabTables(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData >& _rMetaData,::cppu::OWeakObject& _rParent, ::osl::Mutex& _rMutex,
const TStringVector &_rVector) : OEvoabTables_BASE(_rMetaData,_rParent,_rMutex,_rVector)
{}
};
}
}
#endif // _CONNECTIVITY_EVOAB_LTABLES_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.4.372); FILE MERGED 2008/04/01 10:52:56 thb 1.4.372.2: #i85898# Stripping all external header guards 2008/03/28 15:23:31 rt 1.4.372.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: LTables.hxx,v $
* $Revision: 1.5 $
*
* 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 _CONNECTIVITY_EVOAB_LTABLES_HXX_
#define _CONNECTIVITY_EVOAB_LTABLES_HXX_
#include "file/FTables.hxx"
namespace connectivity
{
namespace evoab
{
// namespace ::com::sun::star::sdbcx = ::com::sun::star::sdbcx;
typedef file::OTables OEvoabTables_BASE;
class OEvoabTables : public OEvoabTables_BASE
{
protected:
virtual sdbcx::ObjectType createObject(const ::rtl::OUString& _rName);
public:
OEvoabTables(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData >& _rMetaData,::cppu::OWeakObject& _rParent, ::osl::Mutex& _rMutex,
const TStringVector &_rVector) : OEvoabTables_BASE(_rMetaData,_rParent,_rMutex,_rVector)
{}
};
}
}
#endif // _CONNECTIVITY_EVOAB_LTABLES_HXX_
<|endoftext|> |
<commit_before>#include "TextField.h"
const int TextField::ALIGN_LEFT = PANGO_ALIGN_LEFT;
const int TextField::ALIGN_RIGHT = PANGO_ALIGN_RIGHT;
const int TextField::ALIGN_CENTER = PANGO_ALIGN_CENTER;
TextField::TextField() {
pango = new ofxPango();
context = NULL;
layout = NULL;
fd = NULL;
changed = false;
umlautoffsetfactor=0.2;
umlautoffset=0;
setLetterSpacing(0);
setFontSize(15);
setFontName("Graphik");
setSize(20, 10);
setLineSpacing(1);
setTextAlign(ALIGN_LEFT);
setIndent(0.0);
setAntialiasType(CAIRO_ANTIALIAS_DEFAULT);
}
void TextField::setup() {
if (layout != NULL) delete layout;
layout = pango->createLayout(width, height);
layout->setWidth(width);
layout->fill(0, 0, 0, 0);
}
void TextField::update() {
if(changed){
renderText();
}
}
void TextField::_draw() {
// TODO: find a solution here... sometimes text-alpha is not properly blended
//ofSetColor(255, 255, 255, getCombinedAlpha());
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); // To avoid ugly dark eges in alpha blending
//glBlendFunc(GL_SOURCE1_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // To avoid ugly dark eges in alpha blending
textImage.draw(0, -umlautoffset);
}
void TextField::updateFontDescription() {
setFontDescription(fontName+" "+ofToString(fontSize));
if(layout!=NULL){
layout->context->setIdentityMatrix();
layout->context->translate(0, umlautoffset);
}
}
void TextField::setFontDescription(string _fontDescription) {
if(fd!=NULL){
delete fd;
}
fontDescription=_fontDescription;
fd = new ofxPCPangoFontDescription();
fd->createFromString(fontDescription);
changed=true;
}
void TextField::setText(string _text) {
if(_text == textContent) return;
textContent = _text;
changed=true;
}
void TextField::setFontName(string _fontName) {
if(_fontName == fontName) return;
fontName = _fontName;
updateFontDescription();
}
void TextField::setFontSize(float _fontSize) {
if(_fontSize == fontSize) return;
fontSize = _fontSize;
umlautoffset=fontSize*umlautoffsetfactor;
updateFontDescription();
}
void TextField::setSize(float _width, float _height) {
BasicScreenObject::setSize(_width, _height);
if (layout != NULL) delete layout;
layout = pango->createLayout(width, height+umlautoffset);
layout->context->setIdentityMatrix();
layout->context->translate(0, umlautoffset);
changed=true;
}
void TextField::setTextAlign(int _textAlign) {
if(_textAlign == textAlign) return;
textAlign = _textAlign;
changed = true;
}
void TextField::setLineSpacing(int _lineSpacing) {
if(_lineSpacing == lineSpacing) return;
lineSpacing = _lineSpacing;
changed = true;
}
void TextField::setLetterSpacing(int _letterSpacing){
if(_letterSpacing == letterSpacing) return;
letterSpacing=_letterSpacing;
changed = true;
}
void TextField::setIndent(float _indent) {
if(_indent == indent) return;
indent = _indent;
changed = true;
}
void TextField::setTabs(vector<int> _tabs) {
tabs = _tabs;
changed = true;
}
void TextField::setColor(float _r, float _g, float _b) {
BasicScreenObject::setColor(_r,_g,_b);
changed = true;
}
void TextField::setColor(ofColor _c) {
BasicScreenObject::setColor(_c.r,_c.g,_c.b);
changed = true;
}
void TextField::setAntialiasType(cairo_antialias_t _type) {
if(_type == antialiasType) return;
antialiasType = _type;
changed = true;
}
int TextField::getLineCount() {
return layout->getLineCount();
}
ofPoint TextField::getTextBounds() {
if (changed) {
renderText();
}
return bounds;
}
ofxPCPangoLayout* TextField::getLayout() {
return layout;
}
string TextField::getText() {
return textContent;
}
void TextField::renderText() {
string pre="";
string post="";
if(letterSpacing!=0){
pre="<span letter_spacing=\""+ofToString(letterSpacing)+"\" >";
post="</span>";
}
layout->context->clear();
layout->setFontDescription(*fd, antialiasType);
layout->setTextColor(color.r/255.0f, color.g/255.0f, color.b/255.0f, 1);
layout->setSpacing(lineSpacing);
layout->setIndent(indent);
layout->setMarkup(pre+textContent+post);
layout->setTabs(tabs);
layout->setPangoAlign(textAlign);
layout->show();
bounds=layout->getPixelSize();
changed=false;
if(bounds.y!=height){
setSize(width, bounds.y);
}
textImage.setFromPixels(layout->context->getSurface()->getPixels(), width, height+umlautoffset, OF_IMAGE_COLOR_ALPHA, true);
if (!changed) ofNotifyEvent(textRenderedEvent, myEventArgs, this);
}<commit_msg>fixed rare-case null-pointer bug<commit_after>#include "TextField.h"
const int TextField::ALIGN_LEFT = PANGO_ALIGN_LEFT;
const int TextField::ALIGN_RIGHT = PANGO_ALIGN_RIGHT;
const int TextField::ALIGN_CENTER = PANGO_ALIGN_CENTER;
TextField::TextField() {
pango = new ofxPango();
context = NULL;
layout = NULL;
fd = NULL;
changed = false;
umlautoffsetfactor=0.2;
umlautoffset=0;
textContent = "";
setLetterSpacing(0);
setFontSize(15);
setFontName("Graphik");
setSize(20, 10);
setLineSpacing(1);
setTextAlign(ALIGN_LEFT);
setIndent(0.0);
setAntialiasType(CAIRO_ANTIALIAS_DEFAULT);
}
void TextField::setup() {
if (layout != NULL) delete layout;
layout = pango->createLayout(width, height);
layout->setWidth(width);
layout->fill(0, 0, 0, 0);
}
void TextField::update() {
if(changed){
renderText();
}
}
void TextField::_draw() {
// TODO: find a solution here... sometimes text-alpha is not properly blended
//ofSetColor(255, 255, 255, getCombinedAlpha());
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); // To avoid ugly dark eges in alpha blending
//glBlendFunc(GL_SOURCE1_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // To avoid ugly dark eges in alpha blending
textImage.draw(0, -umlautoffset);
}
void TextField::updateFontDescription() {
setFontDescription(fontName+" "+ofToString(fontSize));
if(layout!=NULL){
layout->context->setIdentityMatrix();
layout->context->translate(0, umlautoffset);
}
}
void TextField::setFontDescription(string _fontDescription) {
if(fd!=NULL){
delete fd;
}
fontDescription=_fontDescription;
fd = new ofxPCPangoFontDescription();
fd->createFromString(fontDescription);
changed=true;
}
void TextField::setText(string _text) {
if(_text == textContent) return;
textContent = _text;
changed=true;
}
void TextField::setFontName(string _fontName) {
if(_fontName == fontName) return;
fontName = _fontName;
updateFontDescription();
}
void TextField::setFontSize(float _fontSize) {
if(_fontSize == fontSize) return;
fontSize = _fontSize;
umlautoffset=fontSize*umlautoffsetfactor;
updateFontDescription();
}
void TextField::setSize(float _width, float _height) {
BasicScreenObject::setSize(_width, _height);
if (layout != NULL) delete layout;
layout = pango->createLayout(width, height+umlautoffset);
layout->context->setIdentityMatrix();
layout->context->translate(0, umlautoffset);
changed=true;
}
void TextField::setTextAlign(int _textAlign) {
if(_textAlign == textAlign) return;
textAlign = _textAlign;
changed = true;
}
void TextField::setLineSpacing(int _lineSpacing) {
if(_lineSpacing == lineSpacing) return;
lineSpacing = _lineSpacing;
changed = true;
}
void TextField::setLetterSpacing(int _letterSpacing){
if(_letterSpacing == letterSpacing) return;
letterSpacing=_letterSpacing;
changed = true;
}
void TextField::setIndent(float _indent) {
if(_indent == indent) return;
indent = _indent;
changed = true;
}
void TextField::setTabs(vector<int> _tabs) {
tabs = _tabs;
changed = true;
}
void TextField::setColor(float _r, float _g, float _b) {
BasicScreenObject::setColor(_r,_g,_b);
changed = true;
}
void TextField::setColor(ofColor _c) {
BasicScreenObject::setColor(_c.r,_c.g,_c.b);
changed = true;
}
void TextField::setAntialiasType(cairo_antialias_t _type) {
if(_type == antialiasType) return;
antialiasType = _type;
changed = true;
}
int TextField::getLineCount() {
return layout->getLineCount();
}
ofPoint TextField::getTextBounds() {
if (changed) {
renderText();
}
return bounds;
}
ofxPCPangoLayout* TextField::getLayout() {
return layout;
}
string TextField::getText() {
return textContent;
}
void TextField::renderText() {
string pre="";
string post="";
if(letterSpacing!=0){
pre="<span letter_spacing=\""+ofToString(letterSpacing)+"\" >";
post="</span>";
}
layout->context->clear();
layout->setFontDescription(*fd, antialiasType);
layout->setTextColor(color.r/255.0f, color.g/255.0f, color.b/255.0f, 1);
layout->setSpacing(lineSpacing);
layout->setIndent(indent);
layout->setMarkup(pre+textContent+post);
layout->setTabs(tabs);
layout->setPangoAlign(textAlign);
layout->show();
bounds=layout->getPixelSize();
changed=false;
if(bounds.y!=height){
setSize(width, bounds.y);
}
textImage.setFromPixels(layout->context->getSurface()->getPixels(), width, height+umlautoffset, OF_IMAGE_COLOR_ALPHA, true);
if (!changed) ofNotifyEvent(textRenderedEvent, myEventArgs, this);
}<|endoftext|> |
<commit_before>#include "backuplistwidget.h"
#include "backuplistitem.h"
#include "debug.h"
#include "utils.h"
#include <QDropEvent>
#include <QFileInfo>
#include <QMessageBox>
#include <QMimeData>
#include <QSettings>
BackupListWidget::BackupListWidget(QWidget *parent) : QListWidget(parent)
{
QSettings settings;
QStringList urls = settings.value("app/backup_list").toStringList();
if(!urls.isEmpty())
{
QList<QUrl> urllist;
foreach(QString url, urls)
urllist << QUrl::fromUserInput(url);
if(!urllist.isEmpty())
QMetaObject::invokeMethod(this, "addItemsWithUrls", QUEUED,
Q_ARG(QList<QUrl>, urllist));
}
connect(this, &QListWidget::itemActivated, [&](QListWidgetItem *item) {
static_cast<BackupListItem *>(item)->browseUrl();
});
}
BackupListWidget::~BackupListWidget()
{
QSettings settings;
QStringList urls;
for(int i = 0; i < count(); ++i)
{
BackupListItem *backupItem = static_cast<BackupListItem *>(item(i));
urls << backupItem->url().toString(QUrl::FullyEncoded);
}
settings.setValue("app/backup_list", urls);
settings.sync();
clear();
}
void BackupListWidget::addItemWithUrl(QUrl url)
{
if(url.isEmpty())
return;
QString fileUrl = url.toLocalFile();
if(fileUrl.isEmpty())
return;
QFileInfo file(fileUrl);
if(!file.exists())
return;
QList<QUrl> urls = itemUrls();
bool matches = false;
foreach(QUrl existingUrl, urls)
{
if(url == existingUrl)
{
matches = true;
break;
}
QFileInfo existingFile(existingUrl.toLocalFile());
if(existingFile.isDir() &&
fileUrl.startsWith(existingFile.absoluteFilePath()))
{
matches = true;
break;
}
}
if(matches)
{
auto confirm =
QMessageBox::question(this, tr("Confirm action"),
tr("This file or directory was already"
" in the backup list; adding it again"
" will have no effect:\n%1\n"
"Add anyway?").arg(url.toLocalFile()));
if(confirm == QMessageBox::No)
return;
}
BackupListItem *item = new BackupListItem(url);
connect(item, &BackupListItem::requestDelete, this,
&BackupListWidget::removeItems);
connect(item, &BackupListItem::requestUpdate, this,
&BackupListWidget::recomputeListTotals);
insertItem(count(), item);
setItemWidget(item, item->widget());
emit itemWithUrlAdded(url);
}
void BackupListWidget::addItemsWithUrls(QList<QUrl> urls)
{
foreach(QUrl url, urls)
addItemWithUrl(url);
recomputeListTotals();
}
void BackupListWidget::setItemsWithUrls(QList<QUrl> urls)
{
clear();
addItemsWithUrls(urls);
}
QList<QUrl> BackupListWidget::itemUrls()
{
QList<QUrl> urls;
for(int i = 0; i < count(); ++i)
{
BackupListItem *backupItem = static_cast<BackupListItem *>(item(i));
urls << backupItem->url().toString(QUrl::FullyEncoded);
}
return urls;
}
void BackupListWidget::removeItems()
{
if(selectedItems().count() == 0)
{
// attempt to remove the sender
BackupListItem *backupItem = qobject_cast<BackupListItem *>(sender());
if(backupItem)
delete backupItem;
}
else
{
foreach(QListWidgetItem *item, selectedItems())
{
if(item && item->isSelected())
delete item;
}
}
recomputeListTotals();
}
void BackupListWidget::recomputeListTotals()
{
quint64 items = 0;
quint64 size = 0;
for(int i = 0; i < count(); ++i)
{
BackupListItem *backupItem = static_cast<BackupListItem *>(item(i));
if(backupItem && (backupItem->count() != 0))
{
items += backupItem->count();
size += backupItem->size();
}
}
emit itemTotals(items, size);
}
void BackupListWidget::dragMoveEvent(QDragMoveEvent *event)
{
if(!event->mimeData()->hasUrls())
{
event->ignore();
return;
}
event->accept();
}
void BackupListWidget::dragEnterEvent(QDragEnterEvent *event)
{
if(event->mimeData()->hasUrls())
event->acceptProposedAction();
}
void BackupListWidget::dropEvent(QDropEvent *event)
{
QList<QUrl> urls = event->mimeData()->urls();
if(!urls.isEmpty())
addItemsWithUrls(urls);
event->acceptProposedAction();
}
void BackupListWidget::keyReleaseEvent(QKeyEvent *event)
{
switch(event->key())
{
case Qt::Key_Delete:
case Qt::Key_Backspace:
removeItems();
break;
case Qt::Key_Escape:
if(!selectedItems().isEmpty())
clearSelection();
else
QListWidget::keyReleaseEvent(event);
break;
default:
QListWidget::keyReleaseEvent(event);
}
}
<commit_msg>Edit text in warning box for adding a url twice<commit_after>#include "backuplistwidget.h"
#include "backuplistitem.h"
#include "debug.h"
#include "utils.h"
#include <QDropEvent>
#include <QFileInfo>
#include <QMessageBox>
#include <QMimeData>
#include <QSettings>
BackupListWidget::BackupListWidget(QWidget *parent) : QListWidget(parent)
{
QSettings settings;
QStringList urls = settings.value("app/backup_list").toStringList();
if(!urls.isEmpty())
{
QList<QUrl> urllist;
foreach(QString url, urls)
urllist << QUrl::fromUserInput(url);
if(!urllist.isEmpty())
QMetaObject::invokeMethod(this, "addItemsWithUrls", QUEUED,
Q_ARG(QList<QUrl>, urllist));
}
connect(this, &QListWidget::itemActivated, [&](QListWidgetItem *item) {
static_cast<BackupListItem *>(item)->browseUrl();
});
}
BackupListWidget::~BackupListWidget()
{
QSettings settings;
QStringList urls;
for(int i = 0; i < count(); ++i)
{
BackupListItem *backupItem = static_cast<BackupListItem *>(item(i));
urls << backupItem->url().toString(QUrl::FullyEncoded);
}
settings.setValue("app/backup_list", urls);
settings.sync();
clear();
}
void BackupListWidget::addItemWithUrl(QUrl url)
{
if(url.isEmpty())
return;
QString fileUrl = url.toLocalFile();
if(fileUrl.isEmpty())
return;
QFileInfo file(fileUrl);
if(!file.exists())
return;
QList<QUrl> urls = itemUrls();
bool matches = false;
foreach(QUrl existingUrl, urls)
{
if(url == existingUrl)
{
matches = true;
break;
}
QFileInfo existingFile(existingUrl.toLocalFile());
if(existingFile.isDir() &&
fileUrl.startsWith(existingFile.absoluteFilePath()))
{
matches = true;
break;
}
}
if(matches)
{
auto confirm =
QMessageBox::question(this, tr("Confirm action"),
tr("The file or directory:\n %1\n"
"was already in the backup list;"
" adding it again will have no effect.\n"
"Add anyway?").arg(url.toLocalFile()));
if(confirm == QMessageBox::No)
return;
}
BackupListItem *item = new BackupListItem(url);
connect(item, &BackupListItem::requestDelete, this,
&BackupListWidget::removeItems);
connect(item, &BackupListItem::requestUpdate, this,
&BackupListWidget::recomputeListTotals);
insertItem(count(), item);
setItemWidget(item, item->widget());
emit itemWithUrlAdded(url);
}
void BackupListWidget::addItemsWithUrls(QList<QUrl> urls)
{
foreach(QUrl url, urls)
addItemWithUrl(url);
recomputeListTotals();
}
void BackupListWidget::setItemsWithUrls(QList<QUrl> urls)
{
clear();
addItemsWithUrls(urls);
}
QList<QUrl> BackupListWidget::itemUrls()
{
QList<QUrl> urls;
for(int i = 0; i < count(); ++i)
{
BackupListItem *backupItem = static_cast<BackupListItem *>(item(i));
urls << backupItem->url().toString(QUrl::FullyEncoded);
}
return urls;
}
void BackupListWidget::removeItems()
{
if(selectedItems().count() == 0)
{
// attempt to remove the sender
BackupListItem *backupItem = qobject_cast<BackupListItem *>(sender());
if(backupItem)
delete backupItem;
}
else
{
foreach(QListWidgetItem *item, selectedItems())
{
if(item && item->isSelected())
delete item;
}
}
recomputeListTotals();
}
void BackupListWidget::recomputeListTotals()
{
quint64 items = 0;
quint64 size = 0;
for(int i = 0; i < count(); ++i)
{
BackupListItem *backupItem = static_cast<BackupListItem *>(item(i));
if(backupItem && (backupItem->count() != 0))
{
items += backupItem->count();
size += backupItem->size();
}
}
emit itemTotals(items, size);
}
void BackupListWidget::dragMoveEvent(QDragMoveEvent *event)
{
if(!event->mimeData()->hasUrls())
{
event->ignore();
return;
}
event->accept();
}
void BackupListWidget::dragEnterEvent(QDragEnterEvent *event)
{
if(event->mimeData()->hasUrls())
event->acceptProposedAction();
}
void BackupListWidget::dropEvent(QDropEvent *event)
{
QList<QUrl> urls = event->mimeData()->urls();
if(!urls.isEmpty())
addItemsWithUrls(urls);
event->acceptProposedAction();
}
void BackupListWidget::keyReleaseEvent(QKeyEvent *event)
{
switch(event->key())
{
case Qt::Key_Delete:
case Qt::Key_Backspace:
removeItems();
break;
case Qt::Key_Escape:
if(!selectedItems().isEmpty())
clearSelection();
else
QListWidget::keyReleaseEvent(event);
break;
default:
QListWidget::keyReleaseEvent(event);
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <cstdio>
#include <string>
#include "google_breakpad/processor/basic_source_line_resolver.h"
#include "google_breakpad/processor/code_module.h"
#include "google_breakpad/processor/stack_frame.h"
#include "processor/linked_ptr.h"
#include "processor/logging.h"
#include "processor/scoped_ptr.h"
#include "processor/stack_frame_info.h"
#define ASSERT_TRUE(cond) \
if (!(cond)) { \
fprintf(stderr, "FAILED: %s at %s:%d\n", #cond, __FILE__, __LINE__); \
return false; \
}
#define ASSERT_FALSE(cond) ASSERT_TRUE(!(cond))
#define ASSERT_EQ(e1, e2) ASSERT_TRUE((e1) == (e2))
namespace {
using std::string;
using google_breakpad::BasicSourceLineResolver;
using google_breakpad::CodeModule;
using google_breakpad::linked_ptr;
using google_breakpad::scoped_ptr;
using google_breakpad::StackFrame;
using google_breakpad::StackFrameInfo;
class TestCodeModule : public CodeModule {
public:
TestCodeModule(string code_file) : code_file_(code_file) {}
virtual ~TestCodeModule() {}
virtual u_int64_t base_address() const { return 0; }
virtual u_int64_t size() const { return 0x4000; }
virtual string code_file() const { return code_file_; }
virtual string code_identifier() const { return ""; }
virtual string debug_file() const { return ""; }
virtual string debug_identifier() const { return ""; }
virtual string version() const { return ""; }
virtual const CodeModule* Copy() const {
return new TestCodeModule(code_file_);
}
private:
string code_file_;
};
static bool VerifyEmpty(const StackFrame &frame) {
ASSERT_TRUE(frame.function_name.empty());
ASSERT_TRUE(frame.source_file_name.empty());
ASSERT_EQ(frame.source_line, 0);
return true;
}
static void ClearSourceLineInfo(StackFrame *frame) {
frame->function_name.clear();
frame->module = NULL;
frame->source_file_name.clear();
frame->source_line = 0;
}
static bool RunTests() {
string testdata_dir = string(getenv("srcdir") ? getenv("srcdir") : ".") +
"/src/processor/testdata";
BasicSourceLineResolver resolver;
ASSERT_TRUE(resolver.LoadModule("module1", testdata_dir + "/module1.out"));
ASSERT_TRUE(resolver.HasModule("module1"));
ASSERT_TRUE(resolver.LoadModule("module2", testdata_dir + "/module2.out"));
ASSERT_TRUE(resolver.HasModule("module2"));
TestCodeModule module1("module1");
StackFrame frame;
frame.instruction = 0x1000;
frame.module = NULL;
scoped_ptr<StackFrameInfo> frame_info(resolver.FillSourceLineInfo(&frame));
ASSERT_FALSE(frame.module);
ASSERT_TRUE(frame.function_name.empty());
ASSERT_EQ(frame.function_base, 0);
ASSERT_TRUE(frame.source_file_name.empty());
ASSERT_EQ(frame.source_line, 0);
ASSERT_EQ(frame.source_line_base, 0);
frame.module = &module1;
frame_info.reset(resolver.FillSourceLineInfo(&frame));
ASSERT_EQ(frame.function_name, "Function1_1");
ASSERT_TRUE(frame.module);
ASSERT_EQ(frame.module->code_file(), "module1");
ASSERT_EQ(frame.function_base, 0x1000);
ASSERT_EQ(frame.source_file_name, "file1_1.cc");
ASSERT_EQ(frame.source_line, 44);
ASSERT_EQ(frame.source_line_base, 0x1000);
ASSERT_TRUE(frame_info.get());
ASSERT_FALSE(frame_info->allocates_base_pointer);
ASSERT_EQ(frame_info->program_string,
"$eip 4 + ^ = $esp $ebp 8 + = $ebp $ebp ^ =");
ClearSourceLineInfo(&frame);
frame.instruction = 0x800;
frame.module = &module1;
frame_info.reset(resolver.FillSourceLineInfo(&frame));
ASSERT_TRUE(VerifyEmpty(frame));
ASSERT_FALSE(frame_info.get());
frame.instruction = 0x1280;
frame_info.reset(resolver.FillSourceLineInfo(&frame));
ASSERT_EQ(frame.function_name, "Function1_3");
ASSERT_TRUE(frame.source_file_name.empty());
ASSERT_EQ(frame.source_line, 0);
ASSERT_TRUE(frame_info.get());
ASSERT_FALSE(frame_info->allocates_base_pointer);
ASSERT_TRUE(frame_info->program_string.empty());
frame.instruction = 0x1380;
frame_info.reset(resolver.FillSourceLineInfo(&frame));
ASSERT_EQ(frame.function_name, "Function1_4");
ASSERT_TRUE(frame.source_file_name.empty());
ASSERT_EQ(frame.source_line, 0);
ASSERT_TRUE(frame_info.get());
ASSERT_FALSE(frame_info->allocates_base_pointer);
ASSERT_FALSE(frame_info->program_string.empty());
frame.instruction = 0x2000;
frame_info.reset(resolver.FillSourceLineInfo(&frame));
ASSERT_FALSE(frame_info.get());
TestCodeModule module2("module2");
frame.instruction = 0x2181;
frame.module = &module2;
frame_info.reset(resolver.FillSourceLineInfo(&frame));
ASSERT_EQ(frame.function_name, "Function2_2");
ASSERT_EQ(frame.function_base, 0x2170);
ASSERT_TRUE(frame.module);
ASSERT_EQ(frame.module->code_file(), "module2");
ASSERT_EQ(frame.source_file_name, "file2_2.cc");
ASSERT_EQ(frame.source_line, 21);
ASSERT_EQ(frame.source_line_base, 0x2180);
ASSERT_TRUE(frame_info.get());
ASSERT_EQ(frame_info->prolog_size, 1);
frame.instruction = 0x216f;
resolver.FillSourceLineInfo(&frame);
ASSERT_EQ(frame.function_name, "Public2_1");
ClearSourceLineInfo(&frame);
frame.instruction = 0x219f;
frame.module = &module2;
resolver.FillSourceLineInfo(&frame);
ASSERT_TRUE(frame.function_name.empty());
frame.instruction = 0x21a0;
frame.module = &module2;
resolver.FillSourceLineInfo(&frame);
ASSERT_EQ(frame.function_name, "Public2_2");
ASSERT_FALSE(resolver.LoadModule("module3",
testdata_dir + "/module3_bad.out"));
ASSERT_FALSE(resolver.HasModule("module3"));
ASSERT_FALSE(resolver.LoadModule("module4",
testdata_dir + "/module4_bad.out"));
ASSERT_FALSE(resolver.HasModule("module4"));
ASSERT_FALSE(resolver.LoadModule("module5",
testdata_dir + "/invalid-filename"));
ASSERT_FALSE(resolver.HasModule("module5"));
ASSERT_FALSE(resolver.HasModule("invalid-module"));
return true;
}
} // namespace
int main(int argc, char **argv) {
BPLOG_INIT(&argc, &argv);
if (!RunTests()) {
return 1;
}
return 0;
}
<commit_msg>Fix memory leak in test case when calling into basic source line resolver.<commit_after>// Copyright (c) 2006, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <cstdio>
#include <string>
#include "google_breakpad/processor/basic_source_line_resolver.h"
#include "google_breakpad/processor/code_module.h"
#include "google_breakpad/processor/stack_frame.h"
#include "processor/linked_ptr.h"
#include "processor/logging.h"
#include "processor/scoped_ptr.h"
#include "processor/stack_frame_info.h"
#define ASSERT_TRUE(cond) \
if (!(cond)) { \
fprintf(stderr, "FAILED: %s at %s:%d\n", #cond, __FILE__, __LINE__); \
return false; \
}
#define ASSERT_FALSE(cond) ASSERT_TRUE(!(cond))
#define ASSERT_EQ(e1, e2) ASSERT_TRUE((e1) == (e2))
namespace {
using std::string;
using google_breakpad::BasicSourceLineResolver;
using google_breakpad::CodeModule;
using google_breakpad::linked_ptr;
using google_breakpad::scoped_ptr;
using google_breakpad::StackFrame;
using google_breakpad::StackFrameInfo;
class TestCodeModule : public CodeModule {
public:
TestCodeModule(string code_file) : code_file_(code_file) {}
virtual ~TestCodeModule() {}
virtual u_int64_t base_address() const { return 0; }
virtual u_int64_t size() const { return 0x4000; }
virtual string code_file() const { return code_file_; }
virtual string code_identifier() const { return ""; }
virtual string debug_file() const { return ""; }
virtual string debug_identifier() const { return ""; }
virtual string version() const { return ""; }
virtual const CodeModule* Copy() const {
return new TestCodeModule(code_file_);
}
private:
string code_file_;
};
static bool VerifyEmpty(const StackFrame &frame) {
ASSERT_TRUE(frame.function_name.empty());
ASSERT_TRUE(frame.source_file_name.empty());
ASSERT_EQ(frame.source_line, 0);
return true;
}
static void ClearSourceLineInfo(StackFrame *frame) {
frame->function_name.clear();
frame->module = NULL;
frame->source_file_name.clear();
frame->source_line = 0;
}
static bool RunTests() {
string testdata_dir = string(getenv("srcdir") ? getenv("srcdir") : ".") +
"/src/processor/testdata";
BasicSourceLineResolver resolver;
ASSERT_TRUE(resolver.LoadModule("module1", testdata_dir + "/module1.out"));
ASSERT_TRUE(resolver.HasModule("module1"));
ASSERT_TRUE(resolver.LoadModule("module2", testdata_dir + "/module2.out"));
ASSERT_TRUE(resolver.HasModule("module2"));
TestCodeModule module1("module1");
StackFrame frame;
frame.instruction = 0x1000;
frame.module = NULL;
scoped_ptr<StackFrameInfo> frame_info(resolver.FillSourceLineInfo(&frame));
ASSERT_FALSE(frame.module);
ASSERT_TRUE(frame.function_name.empty());
ASSERT_EQ(frame.function_base, 0);
ASSERT_TRUE(frame.source_file_name.empty());
ASSERT_EQ(frame.source_line, 0);
ASSERT_EQ(frame.source_line_base, 0);
frame.module = &module1;
frame_info.reset(resolver.FillSourceLineInfo(&frame));
ASSERT_EQ(frame.function_name, "Function1_1");
ASSERT_TRUE(frame.module);
ASSERT_EQ(frame.module->code_file(), "module1");
ASSERT_EQ(frame.function_base, 0x1000);
ASSERT_EQ(frame.source_file_name, "file1_1.cc");
ASSERT_EQ(frame.source_line, 44);
ASSERT_EQ(frame.source_line_base, 0x1000);
ASSERT_TRUE(frame_info.get());
ASSERT_FALSE(frame_info->allocates_base_pointer);
ASSERT_EQ(frame_info->program_string,
"$eip 4 + ^ = $esp $ebp 8 + = $ebp $ebp ^ =");
ClearSourceLineInfo(&frame);
frame.instruction = 0x800;
frame.module = &module1;
frame_info.reset(resolver.FillSourceLineInfo(&frame));
ASSERT_TRUE(VerifyEmpty(frame));
ASSERT_FALSE(frame_info.get());
frame.instruction = 0x1280;
frame_info.reset(resolver.FillSourceLineInfo(&frame));
ASSERT_EQ(frame.function_name, "Function1_3");
ASSERT_TRUE(frame.source_file_name.empty());
ASSERT_EQ(frame.source_line, 0);
ASSERT_TRUE(frame_info.get());
ASSERT_FALSE(frame_info->allocates_base_pointer);
ASSERT_TRUE(frame_info->program_string.empty());
frame.instruction = 0x1380;
frame_info.reset(resolver.FillSourceLineInfo(&frame));
ASSERT_EQ(frame.function_name, "Function1_4");
ASSERT_TRUE(frame.source_file_name.empty());
ASSERT_EQ(frame.source_line, 0);
ASSERT_TRUE(frame_info.get());
ASSERT_FALSE(frame_info->allocates_base_pointer);
ASSERT_FALSE(frame_info->program_string.empty());
frame.instruction = 0x2000;
frame_info.reset(resolver.FillSourceLineInfo(&frame));
ASSERT_FALSE(frame_info.get());
TestCodeModule module2("module2");
frame.instruction = 0x2181;
frame.module = &module2;
frame_info.reset(resolver.FillSourceLineInfo(&frame));
ASSERT_EQ(frame.function_name, "Function2_2");
ASSERT_EQ(frame.function_base, 0x2170);
ASSERT_TRUE(frame.module);
ASSERT_EQ(frame.module->code_file(), "module2");
ASSERT_EQ(frame.source_file_name, "file2_2.cc");
ASSERT_EQ(frame.source_line, 21);
ASSERT_EQ(frame.source_line_base, 0x2180);
ASSERT_TRUE(frame_info.get());
ASSERT_EQ(frame_info->prolog_size, 1);
frame.instruction = 0x216f;
StackFrameInfo *s;
s = resolver.FillSourceLineInfo(&frame);
ASSERT_EQ(frame.function_name, "Public2_1");
delete s;
ClearSourceLineInfo(&frame);
frame.instruction = 0x219f;
frame.module = &module2;
resolver.FillSourceLineInfo(&frame);
ASSERT_TRUE(frame.function_name.empty());
frame.instruction = 0x21a0;
frame.module = &module2;
s = resolver.FillSourceLineInfo(&frame);
ASSERT_EQ(frame.function_name, "Public2_2");
delete s;
ASSERT_FALSE(resolver.LoadModule("module3",
testdata_dir + "/module3_bad.out"));
ASSERT_FALSE(resolver.HasModule("module3"));
ASSERT_FALSE(resolver.LoadModule("module4",
testdata_dir + "/module4_bad.out"));
ASSERT_FALSE(resolver.HasModule("module4"));
ASSERT_FALSE(resolver.LoadModule("module5",
testdata_dir + "/invalid-filename"));
ASSERT_FALSE(resolver.HasModule("module5"));
ASSERT_FALSE(resolver.HasModule("invalid-module"));
return true;
}
} // namespace
int main(int argc, char **argv) {
BPLOG_INIT(&argc, &argv);
if (!RunTests()) {
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before>#include "recent_file_cache.h"
#include <chrono>
#include <iomanip>
#include <iostream>
#include <memory>
#include <queue>
#include <sstream>
#include <string>
#include <unordered_map>
#include <utility>
#include <uv.h>
#include <vector>
#include "../helper/common.h"
#include "../helper/libuv.h"
#include "../log.h"
using std::chrono::minutes;
using std::chrono::steady_clock;
using std::chrono::time_point;
using std::endl;
using std::move;
using std::ostream;
using std::ostringstream;
using std::pair;
using std::queue;
using std::shared_ptr;
using std::static_pointer_cast;
using std::string;
using std::vector;
shared_ptr<StatResult> StatResult::at(string &&path, bool file_hint, bool directory_hint)
{
FSReq lstat_req;
int lstat_err = uv_fs_lstat(nullptr, &lstat_req.req, path.c_str(), nullptr);
// Ignore lstat() errors on entries that:
// (a) we aren't allowed to see
// (b) are at paths with too many symlinks or looping symlinks
// (c) have names that are too long
// (d) have a path component that is (no longer) a directory
// Log any other errno that we see.
if (lstat_err != 0 && lstat_err != UV_ENOENT && lstat_err != UV_EACCES && lstat_err != UV_ELOOP
&& lstat_err != UV_ENAMETOOLONG && lstat_err != ENOTDIR) {
LOGGER << "lstat(" << path << ") failed: " << uv_strerror(lstat_err) << "." << endl;
}
EntryKind guessed_kind = kind_from_stat(lstat_req.req.statbuf);
if (guessed_kind == KIND_UNKNOWN) {
if (file_hint && !directory_hint) guessed_kind = KIND_FILE;
if (!file_hint && directory_hint) guessed_kind = KIND_DIRECTORY;
}
return shared_ptr<StatResult>(new AbsentEntry(move(path), guessed_kind));
}
bool StatResult::has_changed_from(const StatResult &other) const
{
return entry_kind != other.entry_kind || path != other.path;
}
bool StatResult::could_be_rename_of(const StatResult &other) const
{
return !kinds_are_different(entry_kind, other.entry_kind);
}
bool StatResult::update_for_rename(const std::string &from_dir_path, const std::string &to_dir_path)
{
if (path.size() > from_dir_path.size() && path.rfind(from_dir_path, 0) == 0) {
path = to_dir_path + path.substr(from_dir_path.size());
return true;
}
return false;
}
const string &StatResult::get_path() const
{
return path;
}
EntryKind StatResult::get_entry_kind() const
{
return entry_kind;
}
ostream &operator<<(ostream &out, const StatResult &result)
{
out << result.to_string(true);
return out;
}
PresentEntry::PresentEntry(std::string &&path, EntryKind entry_kind, uint64_t inode, uint64_t size) :
StatResult(move(path), entry_kind),
inode{inode},
size{size},
last_seen{steady_clock::now()}
{
//
}
bool PresentEntry::is_present() const
{
return true;
}
bool PresentEntry::has_changed_from(const StatResult &other) const
{
if (StatResult::has_changed_from(other)) return true;
if (other.is_absent()) return true;
const auto &casted = static_cast<const PresentEntry &>(other); // NOLINT
return inode != casted.get_inode() || get_path() != casted.get_path();
}
bool PresentEntry::could_be_rename_of(const StatResult &other) const
{
if (!StatResult::could_be_rename_of(other)) return false;
if (other.is_absent()) return false;
const auto &casted = static_cast<const PresentEntry &>(other); // NOLINT
return inode == casted.get_inode() && !kinds_are_different(get_entry_kind(), casted.get_entry_kind());
}
uint64_t PresentEntry::get_inode() const
{
return inode;
}
uint64_t PresentEntry::get_size() const
{
return size;
}
const time_point<steady_clock> &PresentEntry::get_last_seen() const
{
return last_seen;
}
string PresentEntry::to_string(bool verbose) const
{
ostringstream result;
result << "[present " << get_entry_kind();
if (verbose) result << " (" << get_path() << ")";
result << " inode=" << inode << " size=" << size << "]";
return result.str();
}
bool AbsentEntry::is_present() const
{
return false;
}
bool AbsentEntry::has_changed_from(const StatResult &other) const
{
if (StatResult::has_changed_from(other)) return true;
if (other.is_present()) return true;
return false;
}
bool AbsentEntry::could_be_rename_of(const StatResult & /*other*/) const
{
return false;
}
string AbsentEntry::to_string(bool verbose) const
{
ostringstream result;
result << "[absent " << get_entry_kind();
if (verbose) result << " (" << get_path() << ")";
result << "]";
return result.str();
}
RecentFileCache::RecentFileCache(size_t maximum_size) : maximum_size{maximum_size}
{
//
}
shared_ptr<StatResult> RecentFileCache::current_at_path(const string &path, bool file_hint, bool directory_hint)
{
auto maybe_pending = pending.find(path);
if (maybe_pending != pending.end()) {
return maybe_pending->second;
}
shared_ptr<StatResult> stat_result = StatResult::at(string(path), file_hint, directory_hint);
if (stat_result->is_present()) {
pending.emplace(path, static_pointer_cast<PresentEntry>(stat_result));
}
return stat_result;
}
shared_ptr<StatResult> RecentFileCache::former_at_path(const string &path, bool file_hint, bool directory_hint)
{
auto maybe = by_path.find(path);
if (maybe == by_path.end()) {
EntryKind kind = KIND_UNKNOWN;
if (file_hint && !directory_hint) kind = KIND_FILE;
if (!file_hint && directory_hint) kind = KIND_DIRECTORY;
return shared_ptr<StatResult>(new AbsentEntry(string(path), kind));
}
return maybe->second;
}
void RecentFileCache::evict(const string &path)
{
auto maybe = by_path.find(path);
if (maybe != by_path.end()) {
shared_ptr<PresentEntry> existing = maybe->second;
auto range = by_timestamp.equal_range(existing->get_last_seen());
auto to_erase = by_timestamp.end();
for (auto it = range.first; it != range.second; ++it) {
if (it->second == existing) {
to_erase = it;
}
}
if (to_erase != by_timestamp.end()) {
by_timestamp.erase(to_erase);
}
by_path.erase(maybe);
}
}
void RecentFileCache::evict(const shared_ptr<PresentEntry> &entry)
{
auto maybe = by_path.find(entry->get_path());
if (maybe != by_path.end() && maybe->second == entry) {
evict(entry->get_path());
}
}
void RecentFileCache::update_for_rename(const string &from_dir_path, const string &to_dir_path)
{
vector<pair<string, string>> renames;
for (auto &each : by_path) {
if (each.second->update_for_rename(from_dir_path, to_dir_path)) {
renames.emplace_back(each.first, each.second->get_path());
}
}
for (auto &rename : renames) {
shared_ptr<PresentEntry> p = by_path[rename.first];
by_path.erase(rename.first);
by_path.emplace(rename.second, p);
}
}
void RecentFileCache::apply()
{
for (auto &pair : pending) {
shared_ptr<PresentEntry> &present = pair.second;
// Clear an existing entry at the same path if one exists
evict(present->get_path());
// Add the new PresentEntry
by_path.emplace(present->get_path(), present);
by_timestamp.emplace(present->get_last_seen(), present);
}
pending.clear();
}
void RecentFileCache::prune()
{
if (by_path.size() <= maximum_size) {
return;
}
size_t to_remove = by_path.size() - maximum_size;
LOGGER << "Cache currently contains " << plural(by_path.size(), "entry", "entries") << ". Pruning triggered." << endl;
auto last = by_timestamp.begin();
for (size_t i = 0; i < to_remove && last != by_timestamp.end(); i++) {
++last;
}
for (auto it = by_timestamp.begin(); it != last; ++it) {
shared_ptr<PresentEntry> entry = it->second;
by_path.erase(entry->get_path());
}
by_timestamp.erase(by_timestamp.begin(), last);
LOGGER << "Pruned " << plural(to_remove, "entry", "entries") << ". " << plural(by_path.size(), "entry", "entries")
<< " remain." << endl;
}
void RecentFileCache::prepopulate(const string &root, size_t max)
{
size_t bounded_max = max > maximum_size ? maximum_size : max;
size_t entries = prepopulate_helper(root, bounded_max);
apply();
LOGGER << "Pre-populated cache with " << entries << " entries." << endl;
}
size_t RecentFileCache::prepopulate_helper(const string &root, size_t max)
{
size_t count = 0;
size_t entries = 0;
queue<string> next_roots;
next_roots.push(root);
while (count < max && !next_roots.empty()) {
string current_root(next_roots.front());
next_roots.pop();
FSReq scan_req;
int scan_err = uv_fs_scandir(nullptr, &scan_req.req, current_root.c_str(), 0, nullptr);
if (scan_err < 0) {
LOGGER << "Unable to open directory " << current_root << ": " << uv_strerror(scan_err) << "." << endl;
continue;
}
uv_dirent_t dirent{};
int next_err = uv_fs_scandir_next(&scan_req.req, &dirent);
while (next_err == 0) {
string entry_name(dirent.name);
string entry_path(path_join(current_root, entry_name));
bool file_hint = dirent.type == UV_DIRENT_FILE;
bool dir_hint = dirent.type == UV_DIRENT_DIR;
shared_ptr<StatResult> r = current_at_path(entry_path, file_hint, dir_hint);
if (r->is_present()) {
entries++;
if (r->get_entry_kind() == KIND_DIRECTORY) next_roots.push(entry_path);
}
count++;
if (count >= max) {
return entries;
}
next_err = uv_fs_scandir_next(&scan_req.req, &dirent);
}
if (next_err != UV_EOF) {
LOGGER << "Unable to list entries in directory " << current_root << ": " << uv_strerror(next_err) << "." << endl;
}
}
return entries;
}
void RecentFileCache::resize(size_t maximum_size)
{
this->maximum_size = maximum_size;
prune();
}
<commit_msg>Actually return PresentEntries from StatResult::at<commit_after>#include "recent_file_cache.h"
#include <chrono>
#include <iomanip>
#include <iostream>
#include <memory>
#include <queue>
#include <sstream>
#include <string>
#include <unordered_map>
#include <utility>
#include <uv.h>
#include <vector>
#include "../helper/common.h"
#include "../helper/libuv.h"
#include "../log.h"
using std::chrono::minutes;
using std::chrono::steady_clock;
using std::chrono::time_point;
using std::endl;
using std::move;
using std::ostream;
using std::ostringstream;
using std::pair;
using std::queue;
using std::shared_ptr;
using std::static_pointer_cast;
using std::string;
using std::vector;
shared_ptr<StatResult> StatResult::at(string &&path, bool file_hint, bool directory_hint)
{
FSReq lstat_req;
int lstat_err = uv_fs_lstat(nullptr, &lstat_req.req, path.c_str(), nullptr);
if (lstat_err != 0) {
// Ignore lstat() errors on entries that:
// (a) we aren't allowed to see
// (b) are at paths with too many symlinks or looping symlinks
// (c) have names that are too long
// (d) have a path component that is (no longer) a directory
// Log any other errno that we see.
if (lstat_err != UV_ENOENT && lstat_err != UV_EACCES && lstat_err != UV_ELOOP && lstat_err != UV_ENAMETOOLONG
&& lstat_err != UV_ENOTDIR) {
LOGGER << "lstat(" << path << ") failed: " << uv_strerror(lstat_err) << "." << endl;
}
EntryKind guessed_kind = KIND_UNKNOWN;
if (file_hint && !directory_hint) guessed_kind = KIND_FILE;
if (!file_hint && directory_hint) guessed_kind = KIND_DIRECTORY;
return shared_ptr<StatResult>(new AbsentEntry(move(path), guessed_kind));
}
uv_stat_t &stat = lstat_req.req.statbuf;
EntryKind kind = kind_from_stat(stat);
return shared_ptr<StatResult>(new PresentEntry(move(path), kind, stat.st_ino, stat.st_size));
}
bool StatResult::has_changed_from(const StatResult &other) const
{
return entry_kind != other.entry_kind || path != other.path;
}
bool StatResult::could_be_rename_of(const StatResult &other) const
{
return !kinds_are_different(entry_kind, other.entry_kind);
}
bool StatResult::update_for_rename(const std::string &from_dir_path, const std::string &to_dir_path)
{
if (path.size() > from_dir_path.size() && path.rfind(from_dir_path, 0) == 0) {
path = to_dir_path + path.substr(from_dir_path.size());
return true;
}
return false;
}
const string &StatResult::get_path() const
{
return path;
}
EntryKind StatResult::get_entry_kind() const
{
return entry_kind;
}
ostream &operator<<(ostream &out, const StatResult &result)
{
out << result.to_string(true);
return out;
}
PresentEntry::PresentEntry(std::string &&path, EntryKind entry_kind, uint64_t inode, uint64_t size) :
StatResult(move(path), entry_kind),
inode{inode},
size{size},
last_seen{steady_clock::now()}
{
//
}
bool PresentEntry::is_present() const
{
return true;
}
bool PresentEntry::has_changed_from(const StatResult &other) const
{
if (StatResult::has_changed_from(other)) return true;
if (other.is_absent()) return true;
const auto &casted = static_cast<const PresentEntry &>(other); // NOLINT
return inode != casted.get_inode() || get_path() != casted.get_path();
}
bool PresentEntry::could_be_rename_of(const StatResult &other) const
{
if (!StatResult::could_be_rename_of(other)) return false;
if (other.is_absent()) return false;
const auto &casted = static_cast<const PresentEntry &>(other); // NOLINT
return inode == casted.get_inode() && !kinds_are_different(get_entry_kind(), casted.get_entry_kind());
}
uint64_t PresentEntry::get_inode() const
{
return inode;
}
uint64_t PresentEntry::get_size() const
{
return size;
}
const time_point<steady_clock> &PresentEntry::get_last_seen() const
{
return last_seen;
}
string PresentEntry::to_string(bool verbose) const
{
ostringstream result;
result << "[present " << get_entry_kind();
if (verbose) result << " (" << get_path() << ")";
result << " inode=" << inode << " size=" << size << "]";
return result.str();
}
bool AbsentEntry::is_present() const
{
return false;
}
bool AbsentEntry::has_changed_from(const StatResult &other) const
{
if (StatResult::has_changed_from(other)) return true;
if (other.is_present()) return true;
return false;
}
bool AbsentEntry::could_be_rename_of(const StatResult & /*other*/) const
{
return false;
}
string AbsentEntry::to_string(bool verbose) const
{
ostringstream result;
result << "[absent " << get_entry_kind();
if (verbose) result << " (" << get_path() << ")";
result << "]";
return result.str();
}
RecentFileCache::RecentFileCache(size_t maximum_size) : maximum_size{maximum_size}
{
//
}
shared_ptr<StatResult> RecentFileCache::current_at_path(const string &path, bool file_hint, bool directory_hint)
{
auto maybe_pending = pending.find(path);
if (maybe_pending != pending.end()) {
return maybe_pending->second;
}
shared_ptr<StatResult> stat_result = StatResult::at(string(path), file_hint, directory_hint);
if (stat_result->is_present()) {
pending.emplace(path, static_pointer_cast<PresentEntry>(stat_result));
}
return stat_result;
}
shared_ptr<StatResult> RecentFileCache::former_at_path(const string &path, bool file_hint, bool directory_hint)
{
auto maybe = by_path.find(path);
if (maybe == by_path.end()) {
EntryKind kind = KIND_UNKNOWN;
if (file_hint && !directory_hint) kind = KIND_FILE;
if (!file_hint && directory_hint) kind = KIND_DIRECTORY;
return shared_ptr<StatResult>(new AbsentEntry(string(path), kind));
}
return maybe->second;
}
void RecentFileCache::evict(const string &path)
{
auto maybe = by_path.find(path);
if (maybe != by_path.end()) {
shared_ptr<PresentEntry> existing = maybe->second;
auto range = by_timestamp.equal_range(existing->get_last_seen());
auto to_erase = by_timestamp.end();
for (auto it = range.first; it != range.second; ++it) {
if (it->second == existing) {
to_erase = it;
}
}
if (to_erase != by_timestamp.end()) {
by_timestamp.erase(to_erase);
}
by_path.erase(maybe);
}
}
void RecentFileCache::evict(const shared_ptr<PresentEntry> &entry)
{
auto maybe = by_path.find(entry->get_path());
if (maybe != by_path.end() && maybe->second == entry) {
evict(entry->get_path());
}
}
void RecentFileCache::update_for_rename(const string &from_dir_path, const string &to_dir_path)
{
vector<pair<string, string>> renames;
for (auto &each : by_path) {
if (each.second->update_for_rename(from_dir_path, to_dir_path)) {
renames.emplace_back(each.first, each.second->get_path());
}
}
for (auto &rename : renames) {
shared_ptr<PresentEntry> p = by_path[rename.first];
by_path.erase(rename.first);
by_path.emplace(rename.second, p);
}
}
void RecentFileCache::apply()
{
for (auto &pair : pending) {
shared_ptr<PresentEntry> &present = pair.second;
// Clear an existing entry at the same path if one exists
evict(present->get_path());
// Add the new PresentEntry
by_path.emplace(present->get_path(), present);
by_timestamp.emplace(present->get_last_seen(), present);
}
pending.clear();
}
void RecentFileCache::prune()
{
if (by_path.size() <= maximum_size) {
return;
}
size_t to_remove = by_path.size() - maximum_size;
LOGGER << "Cache currently contains " << plural(by_path.size(), "entry", "entries") << ". Pruning triggered." << endl;
auto last = by_timestamp.begin();
for (size_t i = 0; i < to_remove && last != by_timestamp.end(); i++) {
++last;
}
for (auto it = by_timestamp.begin(); it != last; ++it) {
shared_ptr<PresentEntry> entry = it->second;
by_path.erase(entry->get_path());
}
by_timestamp.erase(by_timestamp.begin(), last);
LOGGER << "Pruned " << plural(to_remove, "entry", "entries") << ". " << plural(by_path.size(), "entry", "entries")
<< " remain." << endl;
}
void RecentFileCache::prepopulate(const string &root, size_t max)
{
size_t bounded_max = max > maximum_size ? maximum_size : max;
size_t entries = prepopulate_helper(root, bounded_max);
apply();
LOGGER << "Pre-populated cache with " << entries << " entries." << endl;
}
size_t RecentFileCache::prepopulate_helper(const string &root, size_t max)
{
size_t count = 0;
size_t entries = 0;
queue<string> next_roots;
next_roots.push(root);
while (count < max && !next_roots.empty()) {
string current_root(next_roots.front());
next_roots.pop();
FSReq scan_req;
int scan_err = uv_fs_scandir(nullptr, &scan_req.req, current_root.c_str(), 0, nullptr);
if (scan_err < 0) {
LOGGER << "Unable to open directory " << current_root << ": " << uv_strerror(scan_err) << "." << endl;
continue;
}
uv_dirent_t dirent{};
int next_err = uv_fs_scandir_next(&scan_req.req, &dirent);
while (next_err == 0) {
string entry_name(dirent.name);
string entry_path(path_join(current_root, entry_name));
bool file_hint = dirent.type == UV_DIRENT_FILE;
bool dir_hint = dirent.type == UV_DIRENT_DIR;
shared_ptr<StatResult> r = current_at_path(entry_path, file_hint, dir_hint);
if (r->is_present()) {
entries++;
if (r->get_entry_kind() == KIND_DIRECTORY) next_roots.push(entry_path);
}
count++;
if (count >= max) {
return entries;
}
next_err = uv_fs_scandir_next(&scan_req.req, &dirent);
}
if (next_err != UV_EOF) {
LOGGER << "Unable to list entries in directory " << current_root << ": " << uv_strerror(next_err) << "." << endl;
}
}
return entries;
}
void RecentFileCache::resize(size_t maximum_size)
{
this->maximum_size = maximum_size;
prune();
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* icon_view.cpp : Icon view for the Playlist
****************************************************************************
* Copyright © 2010 the VideoLAN team
* $Id$
*
* Authors: Jean-Baptiste Kempf <jb@videolan.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#include "components/playlist/icon_view.hpp"
#include "components/playlist/playlist_model.hpp"
#include "components/playlist/sorting.h"
#include "input_manager.hpp"
#include <QApplication>
#include <QPainter>
#include <QRect>
#include <QStyleOptionViewItem>
#include <QFontMetrics>
#include <QPixmapCache>
#include <QDrag>
#include <QDragMoveEvent>
#include "assert.h"
#define ART_SIZE_W 110
#define ART_SIZE_H 80
#define ART_RADIUS 5
#define SPACER 5
QString AbstractPlViewItemDelegate::getMeta( const QModelIndex & index, int meta ) const
{
return index.model()->index( index.row(),
PLModel::columnFromMeta( meta ),
index.parent() )
.data().toString();
}
void AbstractPlViewItemDelegate::paintBackground(
QPainter *painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
/* FIXME: This does not indicate item selection in all QStyles, so for the time being we
have to draw it ourselves, to ensure visible effect of selection on all platforms */
/* QApplication::style()->drawPrimitive( QStyle::PE_PanelItemViewItem, &option,
painter ); */
painter->save();
QRect r = option.rect.adjusted( 0, 0, -1, -1 );
if( option.state & QStyle::State_Selected )
{
painter->setBrush( option.palette.color( QPalette::Highlight ) );
painter->setPen( option.palette.color( QPalette::Highlight ).darker( 150 ) );
painter->drawRect( r );
}
else if( index.data( PLModel::IsCurrentRole ).toBool() )
{
painter->setBrush( QBrush( Qt::lightGray ) );
painter->setPen( QColor( Qt::darkGray ) );
painter->drawRect( r );
}
if( option.state & QStyle::State_MouseOver )
{
painter->setOpacity( 0.5 );
painter->setPen( Qt::NoPen );
painter->setBrush( option.palette.color( QPalette::Highlight ).lighter( 150 ) );
painter->drawRect( option.rect );
}
painter->restore();
}
QPixmap AbstractPlViewItemDelegate::getArtPixmap( const QModelIndex & index, const QSize & size ) const
{
PLItem *item = static_cast<PLItem*>( index.internalPointer() );
assert( item );
QString artUrl = InputManager::decodeArtURL( item->inputItem() );
if( artUrl.isEmpty() )
{
for( int i = 0; i < item->childCount(); i++ )
{
artUrl = InputManager::decodeArtURL( item->child( i )->inputItem() );
if( !artUrl.isEmpty() )
break;
}
}
QPixmap artPix;
QString key = artUrl + QString("%1%2").arg(size.width()).arg(size.height());
if( !QPixmapCache::find( key, artPix ))
{
if( artUrl.isEmpty() || !artPix.load( artUrl ) )
{
key = QString("noart%1%2").arg(size.width()).arg(size.height());
if( !QPixmapCache::find( key, artPix ) )
{
artPix = QPixmap( ":/noart" ).scaled( size,
Qt::KeepAspectRatio,
Qt::SmoothTransformation );
QPixmapCache::insert( key, artPix );
}
}
else
{
artPix = artPix.scaled( size, Qt::KeepAspectRatio, Qt::SmoothTransformation );
QPixmapCache::insert( key, artPix );
}
}
return artPix;
}
void PlIconViewItemDelegate::paint( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
QString title = getMeta( index, COLUMN_TITLE );
QString artist = getMeta( index, COLUMN_ARTIST );
QPixmap artPix = getArtPixmap( index, QSize( ART_SIZE_W, ART_SIZE_H ) );
paintBackground( painter, option, index );
painter->save();
QRect artRect( option.rect.x() + 5 + ( ART_SIZE_W - artPix.width() ) / 2,
option.rect.y() + 5 + ( ART_SIZE_H - artPix.height() ) / 2,
artPix.width(), artPix.height() );
// Draw the drop shadow
painter->save();
painter->setOpacity( 0.7 );
painter->setBrush( QBrush( Qt::darkGray ) );
painter->setPen( Qt::NoPen );
painter->drawRoundedRect( artRect.adjusted( 0, 0, 2, 2 ), ART_RADIUS, ART_RADIUS );
painter->restore();
// Draw the art pixmap
QPainterPath artRectPath;
artRectPath.addRoundedRect( artRect, ART_RADIUS, ART_RADIUS );
painter->setClipPath( artRectPath );
painter->drawPixmap( artRect, artPix );
painter->setClipping( false );
if( option.state & QStyle::State_Selected )
painter->setPen( option.palette.color( QPalette::HighlightedText ) );
QFont font( index.data( Qt::FontRole ).value<QFont>() );
font.setPointSize( 7 );
//Draw children indicator
if( !index.data( PLModel::IsLeafNodeRole ).toBool() )
{
painter->setOpacity( 0.75 );
QRect r( option.rect );
r.setSize( QSize( 25, 25 ) );
r.translate( 5, 5 );
painter->fillRect( r, option.palette.color( QPalette::Mid ) );
painter->setOpacity( 1.0 );
QPixmap dirPix( ":/type/node" );
QRect r2( dirPix.rect() );
r2.moveCenter( r.center() );
painter->drawPixmap( r2, dirPix );
}
// Draw title
font.setItalic( true );
painter->setFont( font );
QFontMetrics fm = painter->fontMetrics();
QRect textRect = option.rect.adjusted( 1, ART_SIZE_H + 10, 0, -1 );
textRect.setHeight( fm.height() );
painter->drawText( textRect,
fm.elidedText( title, Qt::ElideRight, textRect.width() ),
QTextOption( Qt::AlignCenter ) );
// Draw artist
painter->setPen( painter->pen().color().lighter( 150 ) );
font.setItalic( false );
painter->setFont( font );
fm = painter->fontMetrics();
textRect.moveTop( textRect.bottom() + 1 );
painter->drawText( textRect,
fm.elidedText( artist, Qt::ElideRight, textRect.width() ),
QTextOption( Qt::AlignCenter ) );
painter->restore();
}
QSize PlIconViewItemDelegate::sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
QFont f;
f.setPointSize( 7 );
f.setBold( true );
QFontMetrics fm( f );
int textHeight = fm.height();
QSize sz ( ART_SIZE_W + 2 * SPACER,
ART_SIZE_H + 3 * SPACER + 2 * textHeight + 1 );
return sz;
}
#define LISTVIEW_ART_SIZE 45
void PlListViewItemDelegate::paint( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
QModelIndex parent = index.parent();
QModelIndex i;
QString title = getMeta( index, COLUMN_TITLE );
QString duration = getMeta( index, COLUMN_DURATION );
if( !duration.isEmpty() ) title += QString(" [%1]").arg( duration );
QString artist = getMeta( index, COLUMN_ARTIST );
QString album = getMeta( index, COLUMN_ALBUM );
QString trackNum = getMeta( index, COLUMN_TRACK_NUMBER );
QString artistAlbum = artist
+ ( artist.isEmpty() ? QString() : QString( ": " ) )
+ album
+ ( album.isEmpty() || trackNum.isEmpty() ?
QString() : QString( " [#%1]" ).arg( trackNum ) );
QPixmap artPix = getArtPixmap( index, QSize( LISTVIEW_ART_SIZE, LISTVIEW_ART_SIZE ) );
//Draw selection rectangle and current playing item indication
paintBackground( painter, option, index );
QRect artRect( artPix.rect() );
artRect.moveCenter( QPoint( artRect.center().x() + 3,
option.rect.center().y() ) );
//Draw album art
painter->drawPixmap( artRect, artPix );
//Start drawing text
painter->save();
if( option.state & QStyle::State_Selected )
painter->setPen( option.palette.color( QPalette::HighlightedText ) );
QTextOption textOpt( Qt::AlignVCenter | Qt::AlignLeft );
textOpt.setWrapMode( QTextOption::NoWrap );
QFont f( index.data( Qt::FontRole ).value<QFont>() );
//Draw title info
f.setItalic( true );
painter->setFont( f );
QFontMetrics fm( painter->fontMetrics() );
QRect textRect = option.rect.adjusted( LISTVIEW_ART_SIZE + 10, 0, -10, 0 );
if( !artistAlbum.isEmpty() )
{
textRect.setHeight( fm.height() );
textRect.moveBottom( option.rect.center().y() - 2 );
}
//Draw children indicator
if( !index.data( PLModel::IsLeafNodeRole ).toBool() )
{
QPixmap dirPix = QPixmap( ":/type/node" );
painter->drawPixmap( QPoint( textRect.x(), textRect.center().y() - dirPix.height() / 2 ),
dirPix );
textRect.setLeft( textRect.x() + dirPix.width() + 5 );
}
painter->drawText( textRect,
fm.elidedText( title, Qt::ElideRight, textRect.width() ),
textOpt );
// Draw artist and album info
if( !artistAlbum.isEmpty() )
{
f.setItalic( false );
painter->setFont( f );
fm = painter->fontMetrics();
textRect.moveTop( textRect.bottom() + 4 );
textRect.setLeft( textRect.x() + 20 );
painter->drawText( textRect,
fm.elidedText( artistAlbum, Qt::ElideRight, textRect.width() ),
textOpt );
}
painter->restore();
}
QSize PlListViewItemDelegate::sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
QFont f;
f.setBold( true );
QFontMetrics fm( f );
int height = qMax( LISTVIEW_ART_SIZE, 2 * fm.height() + 4 ) + 6;
return QSize( 0, height );
}
static void plViewStartDrag( QAbstractItemView *view, const Qt::DropActions & supportedActions )
{
QDrag *drag = new QDrag( view );
drag->setPixmap( QPixmap( ":/noart64" ) );
drag->setMimeData( view->model()->mimeData(
view->selectionModel()->selectedIndexes() ) );
drag->exec( supportedActions );
}
static void plViewDragMoveEvent( QAbstractItemView *view, QDragMoveEvent * event )
{
if( event->keyboardModifiers() & Qt::ControlModifier &&
event->possibleActions() & Qt::CopyAction )
event->setDropAction( Qt::CopyAction );
else event->acceptProposedAction();
}
PlIconView::PlIconView( PLModel *model, QWidget *parent ) : QListView( parent )
{
PlIconViewItemDelegate *delegate = new PlIconViewItemDelegate( this );
setModel( model );
setViewMode( QListView::IconMode );
setMovement( QListView::Static );
setResizeMode( QListView::Adjust );
setGridSize( delegate->sizeHint() );
setWrapping( true );
setUniformItemSizes( true );
setSelectionMode( QAbstractItemView::ExtendedSelection );
setDragEnabled(true);
/* dropping in QListView::IconMode does not seem to work */
//setAcceptDrops( true );
//setDropIndicatorShown(true);
setItemDelegate( delegate );
}
void PlIconView::startDrag ( Qt::DropActions supportedActions )
{
plViewStartDrag( this, supportedActions );
}
void PlIconView::dragMoveEvent ( QDragMoveEvent * event )
{
plViewDragMoveEvent( this, event );
QAbstractItemView::dragMoveEvent( event );
}
PlListView::PlListView( PLModel *model, QWidget *parent ) : QListView( parent )
{
setModel( model );
setViewMode( QListView::ListMode );
setUniformItemSizes( true );
setSelectionMode( QAbstractItemView::ExtendedSelection );
setAlternatingRowColors( true );
setDragEnabled(true);
setAcceptDrops( true );
setDropIndicatorShown(true);
PlListViewItemDelegate *delegate = new PlListViewItemDelegate( this );
setItemDelegate( delegate );
}
void PlListView::startDrag ( Qt::DropActions supportedActions )
{
plViewStartDrag( this, supportedActions );
}
void PlListView::dragMoveEvent ( QDragMoveEvent * event )
{
plViewDragMoveEvent( this, event );
QAbstractItemView::dragMoveEvent( event );
}
void PlTreeView::startDrag ( Qt::DropActions supportedActions )
{
plViewStartDrag( this, supportedActions );
}
void PlTreeView::dragMoveEvent ( QDragMoveEvent * event )
{
plViewDragMoveEvent( this, event );
QAbstractItemView::dragMoveEvent( event );
}
<commit_msg>Qt: listView, fix and optimize artist and album display<commit_after>/*****************************************************************************
* icon_view.cpp : Icon view for the Playlist
****************************************************************************
* Copyright © 2010 the VideoLAN team
* $Id$
*
* Authors: Jean-Baptiste Kempf <jb@videolan.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#include "components/playlist/icon_view.hpp"
#include "components/playlist/playlist_model.hpp"
#include "components/playlist/sorting.h"
#include "input_manager.hpp"
#include <QApplication>
#include <QPainter>
#include <QRect>
#include <QStyleOptionViewItem>
#include <QFontMetrics>
#include <QPixmapCache>
#include <QDrag>
#include <QDragMoveEvent>
#include "assert.h"
#define ART_SIZE_W 110
#define ART_SIZE_H 80
#define ART_RADIUS 5
#define SPACER 5
QString AbstractPlViewItemDelegate::getMeta( const QModelIndex & index, int meta ) const
{
return index.model()->index( index.row(),
PLModel::columnFromMeta( meta ),
index.parent() )
.data().toString();
}
void AbstractPlViewItemDelegate::paintBackground(
QPainter *painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
/* FIXME: This does not indicate item selection in all QStyles, so for the time being we
have to draw it ourselves, to ensure visible effect of selection on all platforms */
/* QApplication::style()->drawPrimitive( QStyle::PE_PanelItemViewItem, &option,
painter ); */
painter->save();
QRect r = option.rect.adjusted( 0, 0, -1, -1 );
if( option.state & QStyle::State_Selected )
{
painter->setBrush( option.palette.color( QPalette::Highlight ) );
painter->setPen( option.palette.color( QPalette::Highlight ).darker( 150 ) );
painter->drawRect( r );
}
else if( index.data( PLModel::IsCurrentRole ).toBool() )
{
painter->setBrush( QBrush( Qt::lightGray ) );
painter->setPen( QColor( Qt::darkGray ) );
painter->drawRect( r );
}
if( option.state & QStyle::State_MouseOver )
{
painter->setOpacity( 0.5 );
painter->setPen( Qt::NoPen );
painter->setBrush( option.palette.color( QPalette::Highlight ).lighter( 150 ) );
painter->drawRect( option.rect );
}
painter->restore();
}
QPixmap AbstractPlViewItemDelegate::getArtPixmap( const QModelIndex & index, const QSize & size ) const
{
PLItem *item = static_cast<PLItem*>( index.internalPointer() );
assert( item );
QString artUrl = InputManager::decodeArtURL( item->inputItem() );
if( artUrl.isEmpty() )
{
for( int i = 0; i < item->childCount(); i++ )
{
artUrl = InputManager::decodeArtURL( item->child( i )->inputItem() );
if( !artUrl.isEmpty() )
break;
}
}
QPixmap artPix;
QString key = artUrl + QString("%1%2").arg(size.width()).arg(size.height());
if( !QPixmapCache::find( key, artPix ))
{
if( artUrl.isEmpty() || !artPix.load( artUrl ) )
{
key = QString("noart%1%2").arg(size.width()).arg(size.height());
if( !QPixmapCache::find( key, artPix ) )
{
artPix = QPixmap( ":/noart" ).scaled( size,
Qt::KeepAspectRatio,
Qt::SmoothTransformation );
QPixmapCache::insert( key, artPix );
}
}
else
{
artPix = artPix.scaled( size, Qt::KeepAspectRatio, Qt::SmoothTransformation );
QPixmapCache::insert( key, artPix );
}
}
return artPix;
}
void PlIconViewItemDelegate::paint( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
QString title = getMeta( index, COLUMN_TITLE );
QString artist = getMeta( index, COLUMN_ARTIST );
QPixmap artPix = getArtPixmap( index, QSize( ART_SIZE_W, ART_SIZE_H ) );
paintBackground( painter, option, index );
painter->save();
QRect artRect( option.rect.x() + 5 + ( ART_SIZE_W - artPix.width() ) / 2,
option.rect.y() + 5 + ( ART_SIZE_H - artPix.height() ) / 2,
artPix.width(), artPix.height() );
// Draw the drop shadow
painter->save();
painter->setOpacity( 0.7 );
painter->setBrush( QBrush( Qt::darkGray ) );
painter->setPen( Qt::NoPen );
painter->drawRoundedRect( artRect.adjusted( 0, 0, 2, 2 ), ART_RADIUS, ART_RADIUS );
painter->restore();
// Draw the art pixmap
QPainterPath artRectPath;
artRectPath.addRoundedRect( artRect, ART_RADIUS, ART_RADIUS );
painter->setClipPath( artRectPath );
painter->drawPixmap( artRect, artPix );
painter->setClipping( false );
if( option.state & QStyle::State_Selected )
painter->setPen( option.palette.color( QPalette::HighlightedText ) );
QFont font( index.data( Qt::FontRole ).value<QFont>() );
font.setPointSize( 7 );
//Draw children indicator
if( !index.data( PLModel::IsLeafNodeRole ).toBool() )
{
painter->setOpacity( 0.75 );
QRect r( option.rect );
r.setSize( QSize( 25, 25 ) );
r.translate( 5, 5 );
painter->fillRect( r, option.palette.color( QPalette::Mid ) );
painter->setOpacity( 1.0 );
QPixmap dirPix( ":/type/node" );
QRect r2( dirPix.rect() );
r2.moveCenter( r.center() );
painter->drawPixmap( r2, dirPix );
}
// Draw title
font.setItalic( true );
painter->setFont( font );
QFontMetrics fm = painter->fontMetrics();
QRect textRect = option.rect.adjusted( 1, ART_SIZE_H + 10, 0, -1 );
textRect.setHeight( fm.height() );
painter->drawText( textRect,
fm.elidedText( title, Qt::ElideRight, textRect.width() ),
QTextOption( Qt::AlignCenter ) );
// Draw artist
painter->setPen( painter->pen().color().lighter( 150 ) );
font.setItalic( false );
painter->setFont( font );
fm = painter->fontMetrics();
textRect.moveTop( textRect.bottom() + 1 );
painter->drawText( textRect,
fm.elidedText( artist, Qt::ElideRight, textRect.width() ),
QTextOption( Qt::AlignCenter ) );
painter->restore();
}
QSize PlIconViewItemDelegate::sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
QFont f;
f.setPointSize( 7 );
f.setBold( true );
QFontMetrics fm( f );
int textHeight = fm.height();
QSize sz ( ART_SIZE_W + 2 * SPACER,
ART_SIZE_H + 3 * SPACER + 2 * textHeight + 1 );
return sz;
}
#define LISTVIEW_ART_SIZE 45
void PlListViewItemDelegate::paint( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
QModelIndex parent = index.parent();
QModelIndex i;
QString title = getMeta( index, COLUMN_TITLE );
QString duration = getMeta( index, COLUMN_DURATION );
if( !duration.isEmpty() ) title += QString(" [%1]").arg( duration );
QString artist = getMeta( index, COLUMN_ARTIST );
QString album = getMeta( index, COLUMN_ALBUM );
QString trackNum = getMeta( index, COLUMN_TRACK_NUMBER );
QString artistAlbum = artist;
if( !album.isEmpty() )
{
if( !artist.isEmpty() ) artistAlbum += ": ";
artistAlbum += album;
if( !trackNum.isEmpty() ) artistAlbum += QString( " [#%1]" ).arg( trackNum );
}
QPixmap artPix = getArtPixmap( index, QSize( LISTVIEW_ART_SIZE, LISTVIEW_ART_SIZE ) );
//Draw selection rectangle and current playing item indication
paintBackground( painter, option, index );
QRect artRect( artPix.rect() );
artRect.moveCenter( QPoint( artRect.center().x() + 3,
option.rect.center().y() ) );
//Draw album art
painter->drawPixmap( artRect, artPix );
//Start drawing text
painter->save();
if( option.state & QStyle::State_Selected )
painter->setPen( option.palette.color( QPalette::HighlightedText ) );
QTextOption textOpt( Qt::AlignVCenter | Qt::AlignLeft );
textOpt.setWrapMode( QTextOption::NoWrap );
QFont f( index.data( Qt::FontRole ).value<QFont>() );
//Draw title info
f.setItalic( true );
painter->setFont( f );
QFontMetrics fm( painter->fontMetrics() );
QRect textRect = option.rect.adjusted( LISTVIEW_ART_SIZE + 10, 0, -10, 0 );
if( !artistAlbum.isEmpty() )
{
textRect.setHeight( fm.height() );
textRect.moveBottom( option.rect.center().y() - 2 );
}
//Draw children indicator
if( !index.data( PLModel::IsLeafNodeRole ).toBool() )
{
QPixmap dirPix = QPixmap( ":/type/node" );
painter->drawPixmap( QPoint( textRect.x(), textRect.center().y() - dirPix.height() / 2 ),
dirPix );
textRect.setLeft( textRect.x() + dirPix.width() + 5 );
}
painter->drawText( textRect,
fm.elidedText( title, Qt::ElideRight, textRect.width() ),
textOpt );
// Draw artist and album info
if( !artistAlbum.isEmpty() )
{
f.setItalic( false );
painter->setFont( f );
fm = painter->fontMetrics();
textRect.moveTop( textRect.bottom() + 4 );
textRect.setLeft( textRect.x() + 20 );
painter->drawText( textRect,
fm.elidedText( artistAlbum, Qt::ElideRight, textRect.width() ),
textOpt );
}
painter->restore();
}
QSize PlListViewItemDelegate::sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
QFont f;
f.setBold( true );
QFontMetrics fm( f );
int height = qMax( LISTVIEW_ART_SIZE, 2 * fm.height() + 4 ) + 6;
return QSize( 0, height );
}
static void plViewStartDrag( QAbstractItemView *view, const Qt::DropActions & supportedActions )
{
QDrag *drag = new QDrag( view );
drag->setPixmap( QPixmap( ":/noart64" ) );
drag->setMimeData( view->model()->mimeData(
view->selectionModel()->selectedIndexes() ) );
drag->exec( supportedActions );
}
static void plViewDragMoveEvent( QAbstractItemView *view, QDragMoveEvent * event )
{
if( event->keyboardModifiers() & Qt::ControlModifier &&
event->possibleActions() & Qt::CopyAction )
event->setDropAction( Qt::CopyAction );
else event->acceptProposedAction();
}
PlIconView::PlIconView( PLModel *model, QWidget *parent ) : QListView( parent )
{
PlIconViewItemDelegate *delegate = new PlIconViewItemDelegate( this );
setModel( model );
setViewMode( QListView::IconMode );
setMovement( QListView::Static );
setResizeMode( QListView::Adjust );
setGridSize( delegate->sizeHint() );
setWrapping( true );
setUniformItemSizes( true );
setSelectionMode( QAbstractItemView::ExtendedSelection );
setDragEnabled(true);
/* dropping in QListView::IconMode does not seem to work */
//setAcceptDrops( true );
//setDropIndicatorShown(true);
setItemDelegate( delegate );
}
void PlIconView::startDrag ( Qt::DropActions supportedActions )
{
plViewStartDrag( this, supportedActions );
}
void PlIconView::dragMoveEvent ( QDragMoveEvent * event )
{
plViewDragMoveEvent( this, event );
QAbstractItemView::dragMoveEvent( event );
}
PlListView::PlListView( PLModel *model, QWidget *parent ) : QListView( parent )
{
setModel( model );
setViewMode( QListView::ListMode );
setUniformItemSizes( true );
setSelectionMode( QAbstractItemView::ExtendedSelection );
setAlternatingRowColors( true );
setDragEnabled(true);
setAcceptDrops( true );
setDropIndicatorShown(true);
PlListViewItemDelegate *delegate = new PlListViewItemDelegate( this );
setItemDelegate( delegate );
}
void PlListView::startDrag ( Qt::DropActions supportedActions )
{
plViewStartDrag( this, supportedActions );
}
void PlListView::dragMoveEvent ( QDragMoveEvent * event )
{
plViewDragMoveEvent( this, event );
QAbstractItemView::dragMoveEvent( event );
}
void PlTreeView::startDrag ( Qt::DropActions supportedActions )
{
plViewStartDrag( this, supportedActions );
}
void PlTreeView::dragMoveEvent ( QDragMoveEvent * event )
{
plViewDragMoveEvent( this, event );
QAbstractItemView::dragMoveEvent( event );
}
<|endoftext|> |
<commit_before>#include "include/calculator.h"
#include <assert.h>
Calculator::Calculator(MoveListener *lis) : Constructor(lis) {}
Calculator::~Calculator() {}
const Point *Calculator::get_point(constr_num n, bool on_y_axis)
{
Point *p;
if (on_y_axis)
p = new Point(0, n);
else
p = new Point(n);
if (addPoint(p))
return p;
return nullptr;
}
const Point *Calculator::add(constr_num a, constr_num b)
{
const Point *pa = get_point(a),
*pb = get_point(b);
if (pa == nullptr || pb == nullptr)
return nullptr;
auto *l = join_segment(*origin, *pb);
if (l == nullptr) // b = 0
return pa;
l = translate(*l, *pa);
assert(l != nullptr); // translate only returns null for arguments not contained
return &l->end;
}
const Point *Calculator::sub(constr_num a, constr_num b)
{
const Point *pa = get_point(a),
*pb = get_point(b);
if (pa == nullptr || pb == nullptr)
return nullptr;
auto *l = join_segment(*pb, *origin);
if (l == nullptr) // b = 0
return pa;
l = translate(*l, *pa);
assert(l != nullptr); // translate only returns null for arguments not contained
return &l->end;
}
const Point *Calculator::mul(constr_num a, constr_num b)
{
const Point *pa = get_point(a),
*pb = get_point(b, true);
if (pa == nullptr || pb == nullptr)
return nullptr;
auto *l = join_line(*pa, *unit_y);
assert(l != nullptr);
return meet(*parallel(*l, *pb), *x_axis); // both l and pb are contained
}
const Point *Calculator::div(constr_num a, constr_num b)
{
if (b == 0)
return nullptr;
const Point *pa = get_point(a),
*pb = get_point(b, true);
if (pa == nullptr || pb == nullptr)
return nullptr;
auto *l = join_line(*pa, *pb);
assert(l != nullptr); // true only if a = b = 0
return meet(*parallel(*l, *unit_y), *x_axis); // both l and unit_y are contained
}
const Point *Calculator::sqrt(constr_num a)
{
const Point *pa = get_point(a),
*neg_x = get_point(-1);
if (pa == nullptr || a < 0)
return nullptr;
if (a == 0)
return origin;
auto *center = midpoint(*neg_x, *pa);
assert(center != nullptr); // both neg_x and pa are contained
auto meets = meet(*y_axis, *join_circle(*center, *pa)); // circle will always exist, as center != pa
return meets.first->y < 0 ? meets.second : meets.first; // (0, √a)
}
const Point *Calculator::construct_number(constr_num n)
{
}
<commit_msg>Added construct_number<commit_after>#include "include/calculator.h"
#include <assert.h>
Calculator::Calculator(MoveListener *lis) : Constructor(lis) {}
Calculator::~Calculator() {}
const Point *Calculator::get_point(constr_num n, bool on_y_axis)
{
Point *p;
if (on_y_axis)
p = new Point(0, n);
else
p = new Point(n);
if (addPoint(p))
return p;
return nullptr;
}
const Point *Calculator::add(constr_num a, constr_num b)
{
const Point *pa = get_point(a),
*pb = get_point(b);
if (pa == nullptr || pb == nullptr)
return nullptr;
auto *l = join_segment(*origin, *pb);
if (l == nullptr) // b = 0
return pa;
l = translate(*l, *pa);
assert(l != nullptr); // translate only returns null for arguments not contained
return &l->end;
}
const Point *Calculator::sub(constr_num a, constr_num b)
{
const Point *pa = get_point(a),
*pb = get_point(b);
if (pa == nullptr || pb == nullptr)
return nullptr;
auto *l = join_segment(*pb, *origin);
if (l == nullptr) // b = 0
return pa;
l = translate(*l, *pa);
assert(l != nullptr); // translate only returns null for arguments not contained
return &l->end;
}
const Point *Calculator::mul(constr_num a, constr_num b)
{
const Point *pa = get_point(a),
*pb = get_point(b, true);
if (pa == nullptr || pb == nullptr)
return nullptr;
auto *l = join_line(*pa, *unit_y);
assert(l != nullptr);
return meet(*parallel(*l, *pb), *x_axis); // both l and pb are contained
}
const Point *Calculator::div(constr_num a, constr_num b)
{
if (b == 0)
return nullptr;
const Point *pa = get_point(a),
*pb = get_point(b, true);
if (pa == nullptr || pb == nullptr)
return nullptr;
auto *l = join_line(*pa, *pb);
assert(l != nullptr); // true only if a = b = 0
return meet(*parallel(*l, *unit_y), *x_axis); // both l and unit_y are contained
}
const Point *Calculator::sqrt(constr_num a)
{
const Point *pa = get_point(a),
*neg_x = get_point(-1);
if (pa == nullptr || a < 0)
return nullptr;
if (a == 0)
return origin;
auto *center = midpoint(*neg_x, *pa);
assert(center != nullptr); // both neg_x and pa are contained
auto meets = meet(*y_axis, *join_circle(*center, *pa)); // circle will always exist, as center != pa
return meets.first->y < 0 ? meets.second : meets.first; // (0, √a)
}
const Point *Calculator::construct_number(constr_num n)
{
const Point *p;
switch (n.expr->type) {
case 0:
p = new Point(n.expr->expr_union.constant);
addPoint(p);
return p;
case 1:
switch (n.expr->expr_union.unary.op) {
case 1:
return sub(0, n.expr->expr_union.unary.arg);
case 2:
return div(1, n.expr->expr_union.unary.arg);
default:
return sqrt(n.expr->expr_union.unary.arg);
}
default:
switch (n.expr->expr_union.binary.op) {
case 1:
return add(n.expr->expr_union.binary.arg1,
n.expr->expr_union.binary.arg2);
default:
return add(n.expr->expr_union.binary.arg1,
n.expr->expr_union.binary.arg2);
}
}
}
<|endoftext|> |
<commit_before>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "ImageFunction.h"
#include "MooseUtils.h"
// External includes
#include "pcrecpp.h"
#include "tinydir.h"
template<>
InputParameters validParams<ImageFunction>()
{
// Define the possible image formats
MooseEnum type("png, tif, tiff", "png");
// Define the general parameters
InputParameters params = validParams<Function>();
params.addParam<FileName>("file", "Image to open, utilize this option when a single file is given");
params.addParam<FileName>("file_base", "Image file base to open, use this option when a stack of images must be read (ignord if 'file' is given)");
params.addParam<MooseEnum>("file_type", type, "Image file type, use this to specify the type of file for an image stack (use with 'file_base'; ignored if 'file' is given)");
params.addParam<std::vector<unsigned int> >("file_range", "Range of images to analyze, used with 'file_base' (ignored if 'file' is given)");
params.addParam<Point>("origin", "Origin of the image (defualts to mesh origin)");
params.addParam<Point>("dimensions", "x,y,z dimensions of the image (defaults to mesh dimensions)");
params.addParam<unsigned int>("component", "The image component to return, leaving this blank will result in a greyscale value for the image to be created. The component number is zero based, i.e. 0 returns the first component of the image");
// Shift and Scale (application of these occurs prior to threshold)
params.addParam<double>("shift", 0, "Value to add to all pixels; occurs prior to scaling");
params.addParam<double>("scale", 1, "Multiplier to apply to all pixel values; occurs after shifting");
params.addParamNamesToGroup("shift scale", "Rescale");
// Threshold parameters
params.addParam<double>("threshold", "The threshold value");
params.addParam<double>("upper_value", "The value to set for data greater than the threshold value");
params.addParam<double>("lower_value", "The value to set for data less than the threshold value");
params.addParamNamesToGroup("threshold upper_value lower_value", "Threshold");
// Flip image
params.addParam<bool>("flip_x", false, "Flip the image along the x-axis");
params.addParam<bool>("flip_y", false, "Flip the image along the y-axis");
params.addParam<bool>("flip_z", false, "Flip the image along the z-axis");
params.addParamNamesToGroup("flip_x flip_y flip_z", "Flip");
return params;
}
ImageFunction::ImageFunction(const std::string & name, InputParameters parameters) :
Function(name, parameters),
#ifdef LIBMESH_HAVE_VTK
_data(NULL),
#endif
_file_base(getParam<FileName>("file_base")),
_file_type(getParam<MooseEnum>("file_type"))
{
#ifndef LIBMESH_HAVE_VTK
// This should be impossible to reach, the registration of ImageFunction is also guarded with LIBMESH_HAVE_VTK
mooseError("libMesh must be configured with VTK enabled to utilize ImageFunction");
#endif
}
void
ImageFunction::initialSetup()
{
#ifdef LIBMESH_HAVE_VTK
// Initialize the image data (i.e, set origin, ...)
initImageData();
// Create a list of files to extract data from
getFiles();
// Read the image stack
if (_file_type == "png")
readImages<vtkPNGReader>();
else if (_file_type == "tiff" || _file_type == "tif")
readImages<vtkTIFFReader>();
else
mooseError("Un-supported file type '" << _file_type << "'");
// Set the component parameter
/* If the parameter is not set then vtkMagnitude() will applied */
if (isParamValid("component"))
{
unsigned int n = _data->GetNumberOfScalarComponents();
_component = getParam<unsigned int>("component");
if (_component >= n)
mooseError("'component' parameter must be empty or have a value of 0 to " << n-1);
}
else
_component = 0;
// Apply filters, the toggling on and off of each filter is handled internally
vtkMagnitude();
vtkShiftAndScale();
vtkThreshold();
vtkFlip();
#endif
}
ImageFunction::~ImageFunction()
{
}
Real
ImageFunction::value(Real /*t*/, const Point & p)
{
#ifdef LIBMESH_HAVE_VTK
// Do nothing if the point is outside of the image domain
if (!_bounding_box.contains_point(p))
return 0.0;
// Deterimine pixel coordinates
std::vector<int> x(3,0);
for (int i = 0; i < LIBMESH_DIM; ++i)
{
// Compute position, only if voxel size is greater than zero
if (_voxel[i] == 0)
x[i] = 0;
else
{
x[i] = std::floor((p(i) - _origin(i))/_voxel[i]);
// If the point falls on the mesh extents the index needs to be decreased by one
if (x[i] == _dims[i])
x[i]--;
}
}
// Return the image data at the given point
return _data->GetScalarComponentAsDouble(x[0], x[1], x[2], _component);
#else
libmesh_ignore(p); // avoid un-used parameter warnings
return 0.0;
#endif
}
void
ImageFunction::initImageData()
{
#ifdef LIBMESH_HAVE_VTK
// Get access to the Mesh object
FEProblem * fe_problem = getParam<FEProblem *>("_fe_problem");
MooseMesh & mesh = fe_problem->mesh();
// Set the dimensions from the Mesh if not set by the User
if (isParamValid("dimensions"))
_physical_dims = getParam<Point>("dimensions");
else
{
_physical_dims(0) = mesh.getParam<Real>("xmax") - mesh.getParam<Real>("xmin");
#if LIBMESH_DIM > 1
_physical_dims(1) = mesh.getParam<Real>("ymax") - mesh.getParam<Real>("ymin");
#endif
#if LIBMESH_DIM > 2
_physical_dims(2) = mesh.getParam<Real>("zmax") - mesh.getParam<Real>("zmin");
#endif
}
// Set the origin from the Mesh if not set in the input file
if (isParamValid("origin"))
_origin = getParam<Point>("origin");
else
{
_origin(0) = mesh.getParam<Real>("xmin");
#if LIBMESH_DIM > 1
_origin(1) = mesh.getParam<Real>("ymin");
#endif
#if LIBMESH_DIM > 2
_origin(2) = mesh.getParam<Real>("zmin");
#endif
}
// Check the file range and do some error checking
if (isParamValid("file_range"))
{
_file_range = getParam<std::vector<unsigned int> >("file_range");
if (_file_range.size() == 1)
_file_range.push_back(_file_range[0]);
if (_file_range.size() != 2)
mooseError("Image range must specify one or two interger values");
if (_file_range[1] < _file_range[0])
mooseError("Image range must specify exactly two interger values, with the second larger than the first");
}
else
{
_file_range.push_back(0);
_file_range.push_back(std::numeric_limits<unsigned int>::max());
}
#endif
}
void
ImageFunction::getFiles()
{
#ifdef LIBMESH_HAVE_VTK
// Storage for the file names
_files = vtkSmartPointer<vtkStringArray>::New();
// Use specified file name
if (isParamValid("file"))
{
std::string filename = getParam<FileName>("file");
_files->InsertNextValue(filename);
_file_type = filename.substr(filename.find_last_of(".") + 1);
}
// File stack
else
{
// Separate the file base from the path
std::pair<std::string, std::string> split_file = MooseUtils::splitFileName(_file_base);
// Create directory object
tinydir_dir dir;
tinydir_open_sorted(&dir, split_file.first.c_str());
// Regex for extracting numbers from file
std::ostringstream oss;
oss << "(" << split_file.second << ".*?(\\d+))\\..*";
pcrecpp::RE re_base_and_file_num(oss.str()); // Will pull out the full base and the file number simultaneously
// Loop through the files in the directory
for (unsigned int i = 0; i < dir.n_files; i++)
{
// Upate the current file
tinydir_file file;
tinydir_readfile_n(&dir, &file, i);
// Store the file if it has proper extension as in numeric range
if (!file.is_dir && MooseUtils::hasExtension(file.name, _file_type))
{
std::string the_base;
int file_num = 0;
re_base_and_file_num.FullMatch(file.name, &the_base, &file_num);
if (!the_base.empty() && file_num >= _file_range[0] && file_num <= _file_range[1])
_files->InsertNextValue(split_file.first + "/" + file.name);
}
}
tinydir_close(&dir);
}
// Error if no files where located
if (_files->GetNumberOfValues() == 0)
mooseError("No image file(s) located");
#endif
}
void
ImageFunction::vtkMagnitude()
{
#ifdef LIBMESH_HAVE_VTK
// Do nothing if 'component' is set
if (isParamValid("component"))
return;
// Apply the greyscale filtering
_magnitude_filter = vtkSmartPointer<vtkImageMagnitude>::New();
#if VTK_MAJOR_VERSION <= 5
_magnitude_filter->SetInput(_data);
#else
_magnitude_filter->SetInputData(_data);
#endif
_magnitude_filter->Update();
_data = _magnitude_filter->GetOutput();
#endif
}
void
ImageFunction::vtkShiftAndScale()
{
#ifdef LIBMESH_HAVE_VTK
// Capture the parameters
double shift = getParam<double>("shift");
double scale = getParam<double>("scale");
// Do nothing if shift and scale are not set
if (shift == 0 || scale == 1)
return;
// Perform the scaling and offset actions
_shift_scale_filter = vtkSmartPointer<vtkImageShiftScale>::New();
_shift_scale_filter->SetOutputScalarTypeToDouble();
#if VTK_MAJOR_VERSION <= 5
_shift_scale_filter->SetInput(_data);
#else
_shift_scale_filter->SetInputData(_data);
#endif
_shift_scale_filter->SetShift(shift);
_shift_scale_filter->SetScale(scale);
_shift_scale_filter->Update();
_data = _shift_scale_filter->GetOutput();
#endif
}
void
ImageFunction::vtkThreshold()
{
#ifdef LIBMESH_HAVE_VTK
// Do nothing if threshold not set
if (!isParamValid("threshold"))
return;
// Error if both upper and lower are not set
if (!isParamValid("upper_value") || !isParamValid("lower_value"))
mooseError("When thresholding is applied, both the upper_value and lower_value parameters must be set");
// Create the thresholding object
_image_threshold = vtkSmartPointer<vtkImageThreshold>::New();
// Set the data source
#if VTK_MAJOR_VERSION < 6
_image_threshold->SetInput(_data);
#else
_image_threshold->SetInputData(_data);
#endif
// Setup the thresholding options
_image_threshold->ThresholdByUpper(getParam<Real>("threshold"));
_image_threshold->ReplaceInOn();
_image_threshold->SetInValue(getParam<Real>("upper_value"));
_image_threshold->ReplaceOutOn();
_image_threshold->SetOutValue(getParam<Real>("lower_value"));
_image_threshold->SetOutputScalarTypeToDouble();
// Perform the thresholding
_image_threshold->Update();
_data = _image_threshold->GetOutput();
#endif
}
void
ImageFunction::vtkFlip()
{
#ifdef LIBMESH_HAVE_VTK
// x-axis
if (getParam<bool>("flip_x"))
{
_flip_filter_x = imageFlip(0);
_data = _flip_filter_x->GetOutput();
}
// y-axis
if (getParam<bool>("flip_y"))
{
_flip_filter_y = imageFlip(1);
_data = _flip_filter_y->GetOutput();
}
// z-axis
if (getParam<bool>("flip_z"))
{
_flip_filter_z = imageFlip(2);
_data = _flip_filter_z->GetOutput();
}
#endif
}
#ifdef LIBMESH_HAVE_VTK
vtkSmartPointer<vtkImageFlip>
ImageFunction::imageFlip(const int & axis)
{
vtkSmartPointer<vtkImageFlip> flip_image = vtkSmartPointer<vtkImageFlip>::New();
// Set the data source
#if VTK_MAJOR_VERSION < 6
flip_image->SetInput(_data);
#else
flip_image->SetInputData(_data);
#endif
// Perform the flip
flip_image->SetFilteredAxis(axis);
flip_image->Update();
// Return the flip filter pointer
return flip_image;
}
#endif
<commit_msg>Fixing a few signed/unsigned comparison warnings.<commit_after>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "ImageFunction.h"
#include "MooseUtils.h"
// External includes
#include "pcrecpp.h"
#include "tinydir.h"
template<>
InputParameters validParams<ImageFunction>()
{
// Define the possible image formats
MooseEnum type("png, tif, tiff", "png");
// Define the general parameters
InputParameters params = validParams<Function>();
params.addParam<FileName>("file", "Image to open, utilize this option when a single file is given");
params.addParam<FileName>("file_base", "Image file base to open, use this option when a stack of images must be read (ignord if 'file' is given)");
params.addParam<MooseEnum>("file_type", type, "Image file type, use this to specify the type of file for an image stack (use with 'file_base'; ignored if 'file' is given)");
params.addParam<std::vector<unsigned int> >("file_range", "Range of images to analyze, used with 'file_base' (ignored if 'file' is given)");
params.addParam<Point>("origin", "Origin of the image (defualts to mesh origin)");
params.addParam<Point>("dimensions", "x,y,z dimensions of the image (defaults to mesh dimensions)");
params.addParam<unsigned int>("component", "The image component to return, leaving this blank will result in a greyscale value for the image to be created. The component number is zero based, i.e. 0 returns the first component of the image");
// Shift and Scale (application of these occurs prior to threshold)
params.addParam<double>("shift", 0, "Value to add to all pixels; occurs prior to scaling");
params.addParam<double>("scale", 1, "Multiplier to apply to all pixel values; occurs after shifting");
params.addParamNamesToGroup("shift scale", "Rescale");
// Threshold parameters
params.addParam<double>("threshold", "The threshold value");
params.addParam<double>("upper_value", "The value to set for data greater than the threshold value");
params.addParam<double>("lower_value", "The value to set for data less than the threshold value");
params.addParamNamesToGroup("threshold upper_value lower_value", "Threshold");
// Flip image
params.addParam<bool>("flip_x", false, "Flip the image along the x-axis");
params.addParam<bool>("flip_y", false, "Flip the image along the y-axis");
params.addParam<bool>("flip_z", false, "Flip the image along the z-axis");
params.addParamNamesToGroup("flip_x flip_y flip_z", "Flip");
return params;
}
ImageFunction::ImageFunction(const std::string & name, InputParameters parameters) :
Function(name, parameters),
#ifdef LIBMESH_HAVE_VTK
_data(NULL),
#endif
_file_base(getParam<FileName>("file_base")),
_file_type(getParam<MooseEnum>("file_type"))
{
#ifndef LIBMESH_HAVE_VTK
// This should be impossible to reach, the registration of ImageFunction is also guarded with LIBMESH_HAVE_VTK
mooseError("libMesh must be configured with VTK enabled to utilize ImageFunction");
#endif
}
void
ImageFunction::initialSetup()
{
#ifdef LIBMESH_HAVE_VTK
// Initialize the image data (i.e, set origin, ...)
initImageData();
// Create a list of files to extract data from
getFiles();
// Read the image stack
if (_file_type == "png")
readImages<vtkPNGReader>();
else if (_file_type == "tiff" || _file_type == "tif")
readImages<vtkTIFFReader>();
else
mooseError("Un-supported file type '" << _file_type << "'");
// Set the component parameter
/* If the parameter is not set then vtkMagnitude() will applied */
if (isParamValid("component"))
{
unsigned int n = _data->GetNumberOfScalarComponents();
_component = getParam<unsigned int>("component");
if (_component >= n)
mooseError("'component' parameter must be empty or have a value of 0 to " << n-1);
}
else
_component = 0;
// Apply filters, the toggling on and off of each filter is handled internally
vtkMagnitude();
vtkShiftAndScale();
vtkThreshold();
vtkFlip();
#endif
}
ImageFunction::~ImageFunction()
{
}
Real
ImageFunction::value(Real /*t*/, const Point & p)
{
#ifdef LIBMESH_HAVE_VTK
// Do nothing if the point is outside of the image domain
if (!_bounding_box.contains_point(p))
return 0.0;
// Deterimine pixel coordinates
std::vector<int> x(3,0);
for (int i = 0; i < LIBMESH_DIM; ++i)
{
// Compute position, only if voxel size is greater than zero
if (_voxel[i] == 0)
x[i] = 0;
else
{
x[i] = std::floor((p(i) - _origin(i))/_voxel[i]);
// If the point falls on the mesh extents the index needs to be decreased by one
if (x[i] == _dims[i])
x[i]--;
}
}
// Return the image data at the given point
return _data->GetScalarComponentAsDouble(x[0], x[1], x[2], _component);
#else
libmesh_ignore(p); // avoid un-used parameter warnings
return 0.0;
#endif
}
void
ImageFunction::initImageData()
{
#ifdef LIBMESH_HAVE_VTK
// Get access to the Mesh object
FEProblem * fe_problem = getParam<FEProblem *>("_fe_problem");
MooseMesh & mesh = fe_problem->mesh();
// Set the dimensions from the Mesh if not set by the User
if (isParamValid("dimensions"))
_physical_dims = getParam<Point>("dimensions");
else
{
_physical_dims(0) = mesh.getParam<Real>("xmax") - mesh.getParam<Real>("xmin");
#if LIBMESH_DIM > 1
_physical_dims(1) = mesh.getParam<Real>("ymax") - mesh.getParam<Real>("ymin");
#endif
#if LIBMESH_DIM > 2
_physical_dims(2) = mesh.getParam<Real>("zmax") - mesh.getParam<Real>("zmin");
#endif
}
// Set the origin from the Mesh if not set in the input file
if (isParamValid("origin"))
_origin = getParam<Point>("origin");
else
{
_origin(0) = mesh.getParam<Real>("xmin");
#if LIBMESH_DIM > 1
_origin(1) = mesh.getParam<Real>("ymin");
#endif
#if LIBMESH_DIM > 2
_origin(2) = mesh.getParam<Real>("zmin");
#endif
}
// Check the file range and do some error checking
if (isParamValid("file_range"))
{
_file_range = getParam<std::vector<unsigned int> >("file_range");
if (_file_range.size() == 1)
_file_range.push_back(_file_range[0]);
if (_file_range.size() != 2)
mooseError("Image range must specify one or two interger values");
if (_file_range[1] < _file_range[0])
mooseError("Image range must specify exactly two interger values, with the second larger than the first");
}
else
{
_file_range.push_back(0);
_file_range.push_back(std::numeric_limits<unsigned int>::max());
}
#endif
}
void
ImageFunction::getFiles()
{
#ifdef LIBMESH_HAVE_VTK
// Storage for the file names
_files = vtkSmartPointer<vtkStringArray>::New();
// Use specified file name
if (isParamValid("file"))
{
std::string filename = getParam<FileName>("file");
_files->InsertNextValue(filename);
_file_type = filename.substr(filename.find_last_of(".") + 1);
}
// File stack
else
{
// Separate the file base from the path
std::pair<std::string, std::string> split_file = MooseUtils::splitFileName(_file_base);
// Create directory object
tinydir_dir dir;
tinydir_open_sorted(&dir, split_file.first.c_str());
// Regex for extracting numbers from file
std::ostringstream oss;
oss << "(" << split_file.second << ".*?(\\d+))\\..*";
pcrecpp::RE re_base_and_file_num(oss.str()); // Will pull out the full base and the file number simultaneously
// Loop through the files in the directory
for (int i = 0; i < dir.n_files; i++)
{
// Upate the current file
tinydir_file file;
tinydir_readfile_n(&dir, &file, i);
// Store the file if it has proper extension as in numeric range
if (!file.is_dir && MooseUtils::hasExtension(file.name, _file_type))
{
std::string the_base;
unsigned file_num = 0;
re_base_and_file_num.FullMatch(file.name, &the_base, &file_num);
if (!the_base.empty() && file_num >= _file_range[0] && file_num <= _file_range[1])
_files->InsertNextValue(split_file.first + "/" + file.name);
}
}
tinydir_close(&dir);
}
// Error if no files where located
if (_files->GetNumberOfValues() == 0)
mooseError("No image file(s) located");
#endif
}
void
ImageFunction::vtkMagnitude()
{
#ifdef LIBMESH_HAVE_VTK
// Do nothing if 'component' is set
if (isParamValid("component"))
return;
// Apply the greyscale filtering
_magnitude_filter = vtkSmartPointer<vtkImageMagnitude>::New();
#if VTK_MAJOR_VERSION <= 5
_magnitude_filter->SetInput(_data);
#else
_magnitude_filter->SetInputData(_data);
#endif
_magnitude_filter->Update();
_data = _magnitude_filter->GetOutput();
#endif
}
void
ImageFunction::vtkShiftAndScale()
{
#ifdef LIBMESH_HAVE_VTK
// Capture the parameters
double shift = getParam<double>("shift");
double scale = getParam<double>("scale");
// Do nothing if shift and scale are not set
if (shift == 0 || scale == 1)
return;
// Perform the scaling and offset actions
_shift_scale_filter = vtkSmartPointer<vtkImageShiftScale>::New();
_shift_scale_filter->SetOutputScalarTypeToDouble();
#if VTK_MAJOR_VERSION <= 5
_shift_scale_filter->SetInput(_data);
#else
_shift_scale_filter->SetInputData(_data);
#endif
_shift_scale_filter->SetShift(shift);
_shift_scale_filter->SetScale(scale);
_shift_scale_filter->Update();
_data = _shift_scale_filter->GetOutput();
#endif
}
void
ImageFunction::vtkThreshold()
{
#ifdef LIBMESH_HAVE_VTK
// Do nothing if threshold not set
if (!isParamValid("threshold"))
return;
// Error if both upper and lower are not set
if (!isParamValid("upper_value") || !isParamValid("lower_value"))
mooseError("When thresholding is applied, both the upper_value and lower_value parameters must be set");
// Create the thresholding object
_image_threshold = vtkSmartPointer<vtkImageThreshold>::New();
// Set the data source
#if VTK_MAJOR_VERSION < 6
_image_threshold->SetInput(_data);
#else
_image_threshold->SetInputData(_data);
#endif
// Setup the thresholding options
_image_threshold->ThresholdByUpper(getParam<Real>("threshold"));
_image_threshold->ReplaceInOn();
_image_threshold->SetInValue(getParam<Real>("upper_value"));
_image_threshold->ReplaceOutOn();
_image_threshold->SetOutValue(getParam<Real>("lower_value"));
_image_threshold->SetOutputScalarTypeToDouble();
// Perform the thresholding
_image_threshold->Update();
_data = _image_threshold->GetOutput();
#endif
}
void
ImageFunction::vtkFlip()
{
#ifdef LIBMESH_HAVE_VTK
// x-axis
if (getParam<bool>("flip_x"))
{
_flip_filter_x = imageFlip(0);
_data = _flip_filter_x->GetOutput();
}
// y-axis
if (getParam<bool>("flip_y"))
{
_flip_filter_y = imageFlip(1);
_data = _flip_filter_y->GetOutput();
}
// z-axis
if (getParam<bool>("flip_z"))
{
_flip_filter_z = imageFlip(2);
_data = _flip_filter_z->GetOutput();
}
#endif
}
#ifdef LIBMESH_HAVE_VTK
vtkSmartPointer<vtkImageFlip>
ImageFunction::imageFlip(const int & axis)
{
vtkSmartPointer<vtkImageFlip> flip_image = vtkSmartPointer<vtkImageFlip>::New();
// Set the data source
#if VTK_MAJOR_VERSION < 6
flip_image->SetInput(_data);
#else
flip_image->SetInputData(_data);
#endif
// Perform the flip
flip_image->SetFilteredAxis(axis);
flip_image->Update();
// Return the flip filter pointer
return flip_image;
}
#endif
<|endoftext|> |
<commit_before>//--------------------------------------------------------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 1998, 1999, 2000, 2001, 2002 by the deal authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//--------------------------------------------------------------------------
#include <base/point.h>
#include <base/auto_derivative_function.h>
#include <lac/vector.h>
#include <cmath>
// if necessary try to work around a bug in the IBM xlC compiler
#ifdef XLC_WORK_AROUND_STD_BUG
using namespace std;
#endif
template <int dim>
AutoDerivativeFunction<dim>::AutoDerivativeFunction (const double hh,
const unsigned int n_components,
const double initial_time):
Function<dim>(n_components, initial_time),
h(1),
ht(dim),
formula(Euler)
{
set_h(hh);
set_formula();
}
template <int dim>
AutoDerivativeFunction<dim>::~AutoDerivativeFunction ()
{}
template <int dim>
void
AutoDerivativeFunction<dim>::set_formula (const DifferenceFormula form)
{
formula = form;
}
template <int dim>
void
AutoDerivativeFunction<dim>::set_h (const double hh)
{
h=hh;
for (unsigned int i=0; i<dim; ++i)
ht[i][i]=h;
}
template <int dim>
Tensor<1,dim>
AutoDerivativeFunction<dim>::gradient (const Point<dim> &p,
const unsigned int comp) const
{
Tensor<1,dim> grad;
switch (formula)
{
case UpwindEuler:
{
Tensor<1,dim> q1;
for (unsigned int i=0; i<dim; ++i)
{
q1=p-ht[i];
grad[i]=(value(p, comp)-value(q1, comp))/h;
}
break;
}
case Euler:
{
Tensor<1,dim> q1, q2;
for (unsigned int i=0; i<dim; ++i)
{
q1=p+ht[i];
q2=p-ht[i];
grad[i]=(value(q1, comp)-value(q2, comp))/(2*h);
}
break;
}
case FourthOrder:
{
Tensor<1,dim> q1, q2, q3, q4;
for (unsigned int i=0; i<dim; ++i)
{
q2=p+ht[i];
q1=q2+ht[i];
q3=p-ht[i];
q4=q3-ht[i];
grad[i]=(- value(q1, comp)
+8*value(q2, comp)
-8*value(q3, comp)
+ value(q4, comp))/(12*h);
}
break;
}
default:
Assert(false, ExcInvalidFormula());
}
return grad;
}
template <int dim>
void AutoDerivativeFunction<dim>::vector_gradient (const Point<dim> &p,
typename std::vector<Tensor<1,dim> > &gradients) const
{
Assert (gradients.size() == n_components, ExcDimensionMismatch(gradients.size(), n_components));
switch (formula)
{
case UpwindEuler:
{
Tensor<1,dim> q1;
Vector<double> v(n_components), v1(n_components);
const double h_inv=1./h;
for (unsigned int i=0; i<dim; ++i)
{
q1=p-ht[i];
vector_value(p, v);
vector_value(q1, v1);
for (unsigned int comp=0; comp<n_components; ++comp)
gradients[comp][i]=(v(comp)-v1(comp))*h_inv;
}
break;
}
case Euler:
{
Tensor<1,dim> q1, q2;
Vector<double> v1(n_components), v2(n_components);
const double h_inv_2=1./(2*h);
for (unsigned int i=0; i<dim; ++i)
{
q1=p+ht[i];
q2=p-ht[i];
vector_value(q1, v1);
vector_value(q2, v2);
for (unsigned int comp=0; comp<n_components; ++comp)
gradients[comp][i]=(v1(comp)-v2(comp))*h_inv_2;
}
break;
}
case FourthOrder:
{
Tensor<1,dim> q1, q2, q3, q4;
Vector<double> v1(n_components), v2(n_components), v3(n_components), v4(n_components);
const double h_inv_12=1./(12*h);
for (unsigned int i=0; i<dim; ++i)
{
q2=p+ht[i];
q1=q2+ht[i];
q3=p-ht[i];
q4=q3-ht[i];
vector_value(q1, v1);
vector_value(q2, v2);
vector_value(q3, v3);
vector_value(q4, v4);
for (unsigned int comp=0; comp<n_components; ++comp)
gradients[comp][i]=(-v1(comp)+8*v2(comp)-8*v3(comp)+v4(comp))*h_inv_12;
}
break;
}
default:
Assert(false, ExcInvalidFormula());
}
}
template <int dim>
void AutoDerivativeFunction<dim>::gradient_list (const typename std::vector<Point<dim> > &points,
typename std::vector<Tensor<1,dim> > &gradients,
const unsigned int comp) const
{
Assert (gradients.size() == points.size(),
ExcDimensionMismatch(gradients.size(), points.size()));
switch (formula)
{
case UpwindEuler:
{
Tensor<1,dim> q1;
for (unsigned p=0; p<points.size(); ++p)
for (unsigned int i=0; i<dim; ++i)
{
q1=points[p]-ht[i];
gradients[p][i]=(value(points[p], comp)-value(q1, comp))/h;
}
break;
}
case Euler:
{
Tensor<1,dim> q1, q2;
for (unsigned p=0; p<points.size(); ++p)
for (unsigned int i=0; i<dim; ++i)
{
q1=points[p]+ht[i];
q2=points[p]-ht[i];
gradients[p][i]=(value(q1, comp)-value(q2, comp))/(2*h);
}
break;
}
case FourthOrder:
{
Tensor<1,dim> q1, q2, q3, q4;
for (unsigned p=0; p<points.size(); ++p)
for (unsigned int i=0; i<dim; ++i)
{
q2=points[p]+ht[i];
q1=q2+ht[i];
q3=points[p]-ht[i];
q4=q3-ht[i];
gradients[p][i]=(- value(q1, comp)
+8*value(q2, comp)
-8*value(q3, comp)
+ value(q4, comp))/(12*h);
}
break;
}
default:
Assert(false, ExcInvalidFormula());
}
}
template <int dim>
void
AutoDerivativeFunction<dim>::
vector_gradient_list (const typename std::vector<Point<dim> > &points,
typename std::vector<typename std::vector<Tensor<1,dim> > > &gradients) const
{
Assert (gradients.size() == points.size(),
ExcDimensionMismatch(gradients.size(), points.size()));
for (unsigned p=0; p<points.size(); ++p)
Assert (gradients[p].size() == n_components,
ExcDimensionMismatch(gradients.size(), n_components));
switch (formula)
{
case UpwindEuler:
{
Tensor<1,dim> q1;
for (unsigned p=0; p<points.size(); ++p)
for (unsigned int i=0; i<dim; ++i)
{
q1=points[p]-ht[i];
for (unsigned int comp=0; comp<n_components; ++comp)
gradients[p][comp][i]=(value(points[p], comp)-value(q1, comp))/h;
}
break;
}
case Euler:
{
Tensor<1,dim> q1, q2;
for (unsigned p=0; p<points.size(); ++p)
for (unsigned int i=0; i<dim; ++i)
{
q1=points[p]+ht[i];
q2=points[p]-ht[i];
for (unsigned int comp=0; comp<n_components; ++comp)
gradients[p][comp][i]=(value(q1, comp)-value(q2, comp))/(2*h);
}
break;
}
case FourthOrder:
{
Tensor<1,dim> q1, q2, q3, q4;
for (unsigned p=0; p<points.size(); ++p)
for (unsigned int i=0; i<dim; ++i)
{
q2=points[p]+ht[i];
q1=q2+ht[i];
q3=points[p]-ht[i];
q4=q3-ht[i];
for (unsigned int comp=0; comp<n_components; ++comp)
gradients[p][comp][i]=(- value(q1, comp)
+8*value(q2, comp)
-8*value(q3, comp)
+ value(q4, comp))/(12*h);
}
break;
}
default:
Assert(false, ExcInvalidFormula());
}
}
template <int dim>
typename AutoDerivativeFunction<dim>::DifferenceFormula
AutoDerivativeFunction<dim>::get_formula_of_order(const unsigned int ord)
{
switch (ord)
{
case 0:
case 1: return UpwindEuler;
case 2: return Euler;
case 3:
case 4: return FourthOrder;
default:
Assert(false, ExcNotImplemented());
}
return Euler;
}
template class AutoDerivativeFunction<1>;
template class AutoDerivativeFunction<2>;
template class AutoDerivativeFunction<3>;
<commit_msg>Tensors which are actually Points are Points now<commit_after>//--------------------------------------------------------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 1998, 1999, 2000, 2001, 2002 by the deal authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//--------------------------------------------------------------------------
#include <base/point.h>
#include <base/auto_derivative_function.h>
#include <lac/vector.h>
#include <cmath>
// if necessary try to work around a bug in the IBM xlC compiler
#ifdef XLC_WORK_AROUND_STD_BUG
using namespace std;
#endif
template <int dim>
AutoDerivativeFunction<dim>::AutoDerivativeFunction (const double hh,
const unsigned int n_components,
const double initial_time):
Function<dim>(n_components, initial_time),
h(1),
ht(dim),
formula(Euler)
{
set_h(hh);
set_formula();
}
template <int dim>
AutoDerivativeFunction<dim>::~AutoDerivativeFunction ()
{}
template <int dim>
void
AutoDerivativeFunction<dim>::set_formula (const DifferenceFormula form)
{
formula = form;
}
template <int dim>
void
AutoDerivativeFunction<dim>::set_h (const double hh)
{
h=hh;
for (unsigned int i=0; i<dim; ++i)
ht[i][i]=h;
}
template <int dim>
Tensor<1,dim>
AutoDerivativeFunction<dim>::gradient (const Point<dim> &p,
const unsigned int comp) const
{
Tensor<1,dim> grad;
switch (formula)
{
case UpwindEuler:
{
Point<dim> q1;
for (unsigned int i=0; i<dim; ++i)
{
q1=p-ht[i];
grad[i]=(value(p, comp)-value(q1, comp))/h;
}
break;
}
case Euler:
{
Point<dim> q1, q2;
for (unsigned int i=0; i<dim; ++i)
{
q1=p+ht[i];
q2=p-ht[i];
grad[i]=(value(q1, comp)-value(q2, comp))/(2*h);
}
break;
}
case FourthOrder:
{
Point<dim> q1, q2, q3, q4;
for (unsigned int i=0; i<dim; ++i)
{
q2=p+ht[i];
q1=q2+ht[i];
q3=p-ht[i];
q4=q3-ht[i];
grad[i]=(- value(q1, comp)
+8*value(q2, comp)
-8*value(q3, comp)
+ value(q4, comp))/(12*h);
}
break;
}
default:
Assert(false, ExcInvalidFormula());
}
return grad;
}
template <int dim>
void AutoDerivativeFunction<dim>::vector_gradient (const Point<dim> &p,
typename std::vector<Tensor<1,dim> > &gradients) const
{
Assert (gradients.size() == n_components, ExcDimensionMismatch(gradients.size(), n_components));
switch (formula)
{
case UpwindEuler:
{
Point<dim> q1;
Vector<double> v(n_components), v1(n_components);
const double h_inv=1./h;
for (unsigned int i=0; i<dim; ++i)
{
q1=p-ht[i];
vector_value(p, v);
vector_value(q1, v1);
for (unsigned int comp=0; comp<n_components; ++comp)
gradients[comp][i]=(v(comp)-v1(comp))*h_inv;
}
break;
}
case Euler:
{
Point<dim> q1, q2;
Vector<double> v1(n_components), v2(n_components);
const double h_inv_2=1./(2*h);
for (unsigned int i=0; i<dim; ++i)
{
q1=p+ht[i];
q2=p-ht[i];
vector_value(q1, v1);
vector_value(q2, v2);
for (unsigned int comp=0; comp<n_components; ++comp)
gradients[comp][i]=(v1(comp)-v2(comp))*h_inv_2;
}
break;
}
case FourthOrder:
{
Point<dim> q1, q2, q3, q4;
Vector<double> v1(n_components), v2(n_components), v3(n_components), v4(n_components);
const double h_inv_12=1./(12*h);
for (unsigned int i=0; i<dim; ++i)
{
q2=p+ht[i];
q1=q2+ht[i];
q3=p-ht[i];
q4=q3-ht[i];
vector_value(q1, v1);
vector_value(q2, v2);
vector_value(q3, v3);
vector_value(q4, v4);
for (unsigned int comp=0; comp<n_components; ++comp)
gradients[comp][i]=(-v1(comp)+8*v2(comp)-8*v3(comp)+v4(comp))*h_inv_12;
}
break;
}
default:
Assert(false, ExcInvalidFormula());
}
}
template <int dim>
void AutoDerivativeFunction<dim>::gradient_list (const typename std::vector<Point<dim> > &points,
typename std::vector<Tensor<1,dim> > &gradients,
const unsigned int comp) const
{
Assert (gradients.size() == points.size(),
ExcDimensionMismatch(gradients.size(), points.size()));
switch (formula)
{
case UpwindEuler:
{
Point<dim> q1;
for (unsigned p=0; p<points.size(); ++p)
for (unsigned int i=0; i<dim; ++i)
{
q1=points[p]-ht[i];
gradients[p][i]=(value(points[p], comp)-value(q1, comp))/h;
}
break;
}
case Euler:
{
Point<dim> q1, q2;
for (unsigned p=0; p<points.size(); ++p)
for (unsigned int i=0; i<dim; ++i)
{
q1=points[p]+ht[i];
q2=points[p]-ht[i];
gradients[p][i]=(value(q1, comp)-value(q2, comp))/(2*h);
}
break;
}
case FourthOrder:
{
Point<dim> q1, q2, q3, q4;
for (unsigned p=0; p<points.size(); ++p)
for (unsigned int i=0; i<dim; ++i)
{
q2=points[p]+ht[i];
q1=q2+ht[i];
q3=points[p]-ht[i];
q4=q3-ht[i];
gradients[p][i]=(- value(q1, comp)
+8*value(q2, comp)
-8*value(q3, comp)
+ value(q4, comp))/(12*h);
}
break;
}
default:
Assert(false, ExcInvalidFormula());
}
}
template <int dim>
void
AutoDerivativeFunction<dim>::
vector_gradient_list (const typename std::vector<Point<dim> > &points,
typename std::vector<typename std::vector<Tensor<1,dim> > > &gradients) const
{
Assert (gradients.size() == points.size(),
ExcDimensionMismatch(gradients.size(), points.size()));
for (unsigned p=0; p<points.size(); ++p)
Assert (gradients[p].size() == n_components,
ExcDimensionMismatch(gradients.size(), n_components));
switch (formula)
{
case UpwindEuler:
{
Point<dim> q1;
for (unsigned p=0; p<points.size(); ++p)
for (unsigned int i=0; i<dim; ++i)
{
q1=points[p]-ht[i];
for (unsigned int comp=0; comp<n_components; ++comp)
gradients[p][comp][i]=(value(points[p], comp)-value(q1, comp))/h;
}
break;
}
case Euler:
{
Point<dim> q1, q2;
for (unsigned p=0; p<points.size(); ++p)
for (unsigned int i=0; i<dim; ++i)
{
q1=points[p]+ht[i];
q2=points[p]-ht[i];
for (unsigned int comp=0; comp<n_components; ++comp)
gradients[p][comp][i]=(value(q1, comp)-value(q2, comp))/(2*h);
}
break;
}
case FourthOrder:
{
Point<dim> q1, q2, q3, q4;
for (unsigned p=0; p<points.size(); ++p)
for (unsigned int i=0; i<dim; ++i)
{
q2=points[p]+ht[i];
q1=q2+ht[i];
q3=points[p]-ht[i];
q4=q3-ht[i];
for (unsigned int comp=0; comp<n_components; ++comp)
gradients[p][comp][i]=(- value(q1, comp)
+8*value(q2, comp)
-8*value(q3, comp)
+ value(q4, comp))/(12*h);
}
break;
}
default:
Assert(false, ExcInvalidFormula());
}
}
template <int dim>
typename AutoDerivativeFunction<dim>::DifferenceFormula
AutoDerivativeFunction<dim>::get_formula_of_order(const unsigned int ord)
{
switch (ord)
{
case 0:
case 1: return UpwindEuler;
case 2: return Euler;
case 3:
case 4: return FourthOrder;
default:
Assert(false, ExcNotImplemented());
}
return Euler;
}
template class AutoDerivativeFunction<1>;
template class AutoDerivativeFunction<2>;
template class AutoDerivativeFunction<3>;
<|endoftext|> |
<commit_before><commit_msg>Prediction: use obstacle id to group obstacles, instead<commit_after><|endoftext|> |
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2019 ScyllaDB Ltd.
*/
#pragma once
#include "syscall_work_queue.hh"
namespace seastar {
class reactor;
class thread_pool {
reactor* _reactor;
uint64_t _aio_threaded_fallbacks = 0;
#ifndef HAVE_OSV
syscall_work_queue inter_thread_wq;
posix_thread _worker_thread;
std::atomic<bool> _stopped = { false };
std::atomic<bool> _main_thread_idle = { false };
public:
explicit thread_pool(reactor* r, sstring thread_name);
~thread_pool();
template <typename T, typename Func>
future<T> submit(Func func) {
++_aio_threaded_fallbacks;
return inter_thread_wq.submit<T>(std::move(func));
}
uint64_t operation_count() const { return _aio_threaded_fallbacks; }
unsigned complete() { return inter_thread_wq.complete(); }
// Before we enter interrupt mode, we must make sure that the syscall thread will properly
// generate signals to wake us up. This means we need to make sure that all modifications to
// the pending and completed fields in the inter_thread_wq are visible to all threads.
//
// Simple release-acquire won't do because we also need to serialize all writes that happens
// before the syscall thread loads this value, so we'll need full seq_cst.
void enter_interrupt_mode() { _main_thread_idle.store(true, std::memory_order_seq_cst); }
// When we exit interrupt mode, however, we can safely used relaxed order. If any reordering
// takes place, we'll get an extra signal and complete will be called one extra time, which is
// harmless.
void exit_interrupt_mode() { _main_thread_idle.store(false, std::memory_order_relaxed); }
#else
public:
template <typename T, typename Func>
future<T> submit(Func func) { std::cerr << "thread_pool not yet implemented on osv\n"; abort(); }
#endif
private:
void work(sstring thread_name);
};
}
<commit_msg>reactor: thread_pool: submit: specify as noexcept<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2019 ScyllaDB Ltd.
*/
#pragma once
#include "syscall_work_queue.hh"
namespace seastar {
class reactor;
class thread_pool {
reactor* _reactor;
uint64_t _aio_threaded_fallbacks = 0;
#ifndef HAVE_OSV
syscall_work_queue inter_thread_wq;
posix_thread _worker_thread;
std::atomic<bool> _stopped = { false };
std::atomic<bool> _main_thread_idle = { false };
public:
explicit thread_pool(reactor* r, sstring thread_name);
~thread_pool();
template <typename T, typename Func>
future<T> submit(Func func) noexcept {
++_aio_threaded_fallbacks;
return inter_thread_wq.submit<T>(std::move(func));
}
uint64_t operation_count() const { return _aio_threaded_fallbacks; }
unsigned complete() { return inter_thread_wq.complete(); }
// Before we enter interrupt mode, we must make sure that the syscall thread will properly
// generate signals to wake us up. This means we need to make sure that all modifications to
// the pending and completed fields in the inter_thread_wq are visible to all threads.
//
// Simple release-acquire won't do because we also need to serialize all writes that happens
// before the syscall thread loads this value, so we'll need full seq_cst.
void enter_interrupt_mode() { _main_thread_idle.store(true, std::memory_order_seq_cst); }
// When we exit interrupt mode, however, we can safely used relaxed order. If any reordering
// takes place, we'll get an extra signal and complete will be called one extra time, which is
// harmless.
void exit_interrupt_mode() { _main_thread_idle.store(false, std::memory_order_relaxed); }
#else
public:
template <typename T, typename Func>
future<T> submit(Func func) { std::cerr << "thread_pool not yet implemented on osv\n"; abort(); }
#endif
private:
void work(sstring thread_name);
};
}
<|endoftext|> |
<commit_before>/*
* fMBT, free Model Based Testing tool
* Copyright (c) 2012 Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU Lesser General Public License,
* version 2.1, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
* more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include "coverage_include.hh"
#include "helper.hh"
Coverage_Include_base::Coverage_Include_base(Log& l,
const std::string& param,
bool _exclude): Coverage(l), child(NULL), exclude(_exclude)
{
commalist(param,subs);
if (subs.size()>1) {
child=new_coverage(l,subs.back());
}
status&=(child!=NULL);
}
void Coverage_Include_base::set_model(Model* _model)
{
Coverage::set_model(_model);
std::vector<std::string>& n=model->getActionNames();
for(unsigned i=0;i<subs.size()-1;i++) {
int p=find(n,subs[i]);
if (p) {
log.debug("Action %s %i\n",subs[i].c_str(),p);
filteractions.insert(p);
} else {
// regexp?
std::vector<int> r;
if (subs[i][0]=='\'' || subs[i][0]=='\"') {
// Let's remove first and the last charaster
subs[i]=subs[i].substr(1,subs[i].length()-2);
regexpmatch(subs[i],n,r,false);
for(unsigned j=0;j<r.size();j++) {
log.debug("regexp %s %i\n",subs[i].c_str(),r[j]);
filteractions.insert(r[j]);
}
} else {
log.debug("No such action %s\n",subs[i].c_str());
}
}
}
ActionNames.push_back(""); // TAU
for(unsigned i=1;i<n.size();i++) {
if ((filteractions.find(i)==filteractions.end())==exclude) {
log.debug("N: %s\n",n[i].c_str());
ActionNames.push_back(n[i]);
}
}
alpha=new Alphabet_impl(ActionNames,SPNames);
submodel=new Model_yes(log,"");
submodel->set_model(alpha);
child->set_model(submodel);
}
class Coverage_Include: public Coverage_Include_base {
public:
Coverage_Include(Log&l, const std::string& param):
Coverage_Include_base(l,param,false) {
}
virtual ~Coverage_Include() { }
};
class Coverage_Exclude: public Coverage_Include_base {
public:
Coverage_Exclude(Log&l, const std::string& param):
Coverage_Include_base(l,param,true) {
}
virtual ~Coverage_Exclude() { }
};
FACTORY_DEFAULT_CREATOR(Coverage, Coverage_Include, "include")
FACTORY_DEFAULT_CREATOR(Coverage, Coverage_Exclude, "exclude")
<commit_msg>heuristic_include semantic is better. Let's use same in the coverage_include<commit_after>/*
* fMBT, free Model Based Testing tool
* Copyright (c) 2012 Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU Lesser General Public License,
* version 2.1, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
* more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include "coverage_include.hh"
#include "helper.hh"
Coverage_Include_base::Coverage_Include_base(Log& l,
const std::string& param,
bool _exclude): Coverage(l), child(NULL), exclude(_exclude)
{
commalist(param,subs);
if (subs.size()>1) {
child=new_coverage(l,subs.back());
}
status&=(child!=NULL);
}
void Coverage_Include_base::set_model(Model* _model)
{
Coverage::set_model(_model);
std::vector<std::string>& n=model->getActionNames();
for(unsigned i=0;i<subs.size()-1;i++) {
int p=find(n,subs[i]);
if (p) {
log.debug("Action %s %i\n",subs[i].c_str(),p);
filteractions.insert(p);
} else {
// regexp?
std::vector<int> r;
if (subs[i][0]=='\'' || subs[i][0]=='\"') {
// Let's remove first and the last charaster
subs[i]=subs[i].substr(1,subs[i].length()-2);
}
regexpmatch(subs[i],n,r,false);
for(unsigned j=0;j<r.size();j++) {
log.debug("regexp %s %i\n",subs[i].c_str(),r[j]);
filteractions.insert(r[j]);
}
}
}
ActionNames.push_back(""); // TAU
for(unsigned i=1;i<n.size();i++) {
if ((filteractions.find(i)==filteractions.end())==exclude) {
log.debug("N: %s\n",n[i].c_str());
ActionNames.push_back(n[i]);
}
}
alpha=new Alphabet_impl(ActionNames,SPNames);
submodel=new Model_yes(log,"");
submodel->set_model(alpha);
child->set_model(submodel);
}
class Coverage_Include: public Coverage_Include_base {
public:
Coverage_Include(Log&l, const std::string& param):
Coverage_Include_base(l,param,false) {
}
virtual ~Coverage_Include() { }
};
class Coverage_Exclude: public Coverage_Include_base {
public:
Coverage_Exclude(Log&l, const std::string& param):
Coverage_Include_base(l,param,true) {
}
virtual ~Coverage_Exclude() { }
};
FACTORY_DEFAULT_CREATOR(Coverage, Coverage_Include, "include")
FACTORY_DEFAULT_CREATOR(Coverage, Coverage_Exclude, "exclude")
<|endoftext|> |
<commit_before>
// Copyright (c) 2008-2009, Regents of the University of Colorado.
// This work was supported by NASA contracts NNJ05HE10G, NNC06CB40C, and
// NNC07CB47C.
#include <QGridLayout>
#include <QPushButton>
#include <QLineEdit>
#include <QString>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <iostream>
#include "resourceview.h"
using namespace std;
ResourceView :: ResourceView (QWidget* parent) : QGridLayout(parent) {
popupError = new QErrorMessage();
habTypeTitle = new QLabel("HAB Type");
habIdTitle = new QLabel("HAB ID");
nodeIdTitle = new QLabel("Node ID");
resourceIdTitle = new QLabel("Resource");
flavorTitle = new QLabel("Flavor");
dataTypeTitle = new QLabel("Data Type");
timestampTitle = new QLabel("Timestamp");
valueTitle = new QLabel("Value");
submitResourceValue = new QPushButton(tr("&Update Value"));
plotButton = new QPushButton(tr("&Plot"));
valueEditor = new QLineEdit();
habType = new QLabel();
habId = new QLabel();
nodeId = new QLabel();
resourceId = new QLabel();
flavor = new QLabel();
dataType = new QLabel();
timestamp = new QLabel();
value = new QLabel();
addWidget(habTypeTitle, 0, 0, Qt::AlignCenter);
addWidget(habIdTitle, 1, 0, Qt::AlignCenter);
addWidget(nodeIdTitle, 2, 0, Qt::AlignCenter);
addWidget(resourceIdTitle, 3, 0, Qt::AlignCenter);
addWidget(flavorTitle, 4, 0, Qt::AlignCenter);
addWidget(dataTypeTitle, 5, 0, Qt::AlignCenter);
addWidget(timestampTitle, 6, 0, Qt::AlignCenter);
addWidget(valueTitle, 7, 0, Qt::AlignCenter);
addWidget(habType, 0, 1, Qt::AlignCenter);
addWidget(habId, 1, 1, Qt::AlignCenter);
addWidget(nodeId, 2, 1, Qt::AlignCenter);
addWidget(resourceId, 3, 1, Qt::AlignCenter);
addWidget(flavor, 4, 1, Qt::AlignCenter);
addWidget(dataType, 5, 1, Qt::AlignCenter);
addWidget(timestamp, 6, 1, Qt::AlignCenter);
addWidget(value, 7, 1, Qt::AlignCenter);
addWidget(plotButton, 8, 0, 1, 2, Qt::AlignCenter); // for plotting
plotButton->setDisabled(true);
setColumnMinimumWidth(0, 50);
setColumnStretch(0, 0);
setColumnMinimumWidth(1, 50);
setColumnStretch(1, 0);
connect(valueEditor, SIGNAL(returnPressed()), this, SLOT(textEntered()));
connect(submitResourceValue, SIGNAL(pressed()), this, SLOT(textEntered()));
connect(plotButton, SIGNAL(clicked()), this, SLOT(plotClicked()));
}
void ResourceView::updatePanel(bionet_resource_t* resource) {
bionet_datapoint_t *datapoint = bionet_resource_get_datapoint_by_index(resource, 0);
if (datapoint != NULL) {
QString exactValue(bionet_value_to_str(bionet_datapoint_get_value(datapoint)));
// For all of the really large resources
if (exactValue.toFloat() > 1e16)
value->setText(QString().setNum(exactValue.toFloat(), 'e', 16));
else
value->setText(exactValue);
timestamp->setText(bionet_datapoint_timestamp_to_string(datapoint));
} else {
timestamp->setText("N/A");
value->setText("(no known value)");
}
if ((bionet_resource_get_flavor(resource) == BIONET_RESOURCE_FLAVOR_PARAMETER) ||
(bionet_resource_get_flavor(resource) == BIONET_RESOURCE_FLAVOR_ACTUATOR)) {
removeWidget(plotButton);
addWidget(submitResourceValue, 8, 0);
addWidget(valueEditor, 8, 1);
submitResourceValue->show();
valueEditor->show();
addWidget(plotButton, 9, 0, 1, 2, Qt::AlignCenter);
plotButton->setFocusPolicy(Qt::NoFocus);
submitResourceValue->setFocusPolicy(Qt::ClickFocus);
valueEditor->setFocusPolicy(Qt::StrongFocus);
submitResourceValue->setEnabled(true);
valueEditor->setEnabled(true);
} else if (rowCount() == 10) {
removeSubmitableRows();
plotButton->setFocusPolicy(Qt::StrongFocus);
}
if (bionet_resource_get_data_type(resource) == BIONET_RESOURCE_DATA_TYPE_STRING)
plotButton->setEnabled(false);
else
plotButton->setEnabled(true);
return;
}
void ResourceView::clearView() {
if (rowCount() == 10) {
// if there was send update button there would be 10 rows
removeSubmitableRows();
}
habType->setText(QString());
habId->setText(QString());
nodeId->setText(QString());
resourceId->setText(QString());
flavor->setText(QString());
dataType->setText(QString());
timestamp->setText(QString());
value->setText(QString());
plotButton->setDisabled(true);
}
void ResourceView::lostHab(bionet_hab_t* hab) {
if (habInPanel(bionet_hab_get_type(hab), bionet_hab_get_id(hab)))
clearView();
}
void ResourceView::lostNode(bionet_node_t* node) {
bionet_hab_t* hab = bionet_node_get_hab(node);
if (nodeInPanel(bionet_hab_get_type(hab), bionet_hab_get_id(hab), bionet_node_get_id(node)))
clearView();
}
void ResourceView::newResourceSelected(bionet_resource_t* resource) {
bionet_hab_t *hab;
bionet_node_t *node;
node = bionet_resource_get_node(resource);
hab = bionet_resource_get_hab(resource);
resourceIdTitle->setText("Resource");
flavorTitle->setText("Flavor");
dataTypeTitle->setText("Data Type");
timestampTitle->setText("Timestamp");
valueTitle->setText("Value");
habType->setText(bionet_hab_get_type(hab));
habId->setText(bionet_hab_get_id(hab));
nodeId->setText(bionet_node_get_id(node));
resourceId->setText(bionet_resource_get_id(resource));
flavor->setText(bionet_resource_flavor_to_string(bionet_resource_get_flavor(resource)));
dataType->setText(bionet_resource_data_type_to_string(bionet_resource_get_data_type(resource)));
plotButton->setDisabled(false);
updatePanel(resource);
return;
}
void ResourceView::newStreamSelected(bionet_stream_t* stream) {
bionet_hab_t *hab;
bionet_node_t *node;
node = bionet_stream_get_node(stream);
hab = bionet_node_get_hab(node);
if (rowCount() == 10) {
removeSubmitableRows();
plotButton->setDisabled(true);
}
resourceIdTitle->setText("Stream");
flavorTitle->setText("Direction");
dataTypeTitle->setText("Type");
timestampTitle->setText("");
valueTitle->setText("");
habType->setText(bionet_hab_get_type(hab));
habId->setText(bionet_hab_get_id(hab));
nodeId->setText(bionet_node_get_id(node));
resourceId->setText(bionet_stream_get_id(stream));
flavor->setText(bionet_stream_direction_to_string(bionet_stream_get_direction(stream)));
dataType->setText(bionet_stream_get_type(stream));
timestamp->setText("");
value->setText("");
}
void ResourceView::resourceValueChanged(bionet_datapoint_t* datapoint) {
bionet_resource_t *resource;
if (datapoint == NULL)
return;
resource = bionet_datapoint_get_resource(datapoint);
if (resourceInPanel(resource))
updatePanel(resource);
}
void ResourceView::textEntered() {
int r = 0;
QString name;
if (valueEditor->text() == NULL) {
return;
}
name = QString("%1.%2.%3:%4").arg(habType->text()).arg(habId->text()).arg(nodeId->text()).arg(resourceId->text());
qDebug("set resource name %s", qPrintable(name));
r = bionet_set_resource_by_name(qPrintable(name), qPrintable(valueEditor->text()));
if (r < 0) {
popupError->showMessage("Unable to set resource value");
}
valueEditor->clear();
}
bool ResourceView::habInPanel(const char* habTypeComparison, const char* habIdComparison) {
if ((habIdComparison == habId->text()) &&
(habTypeComparison == habType->text()))
return TRUE;
return FALSE;
}
bool ResourceView::nodeInPanel(const char* habTypeComparison, const char* habIdComparison, const char* nodeIdComparison) {
if ((habInPanel(habTypeComparison, habIdComparison)) &&
(nodeIdComparison == nodeId->text()))
return TRUE;
return FALSE;
}
bool ResourceView::resourceInPanel(bionet_resource_t* resource) {
bionet_hab_t* hab;
bionet_node_t* node;
node = bionet_resource_get_node(resource);
hab = bionet_resource_get_hab(resource);
if (nodeInPanel(bionet_hab_get_type(hab), bionet_hab_get_id(hab), bionet_node_get_id(node)) &&
(bionet_resource_get_id(resource) == resourceId->text()))
return TRUE;
return FALSE;
}
void ResourceView::removeSubmitableRows() {
//removeWidget(plotButton);
removeWidget(submitResourceValue);
submitResourceValue->hide();
removeWidget(valueEditor);
valueEditor->hide();
addWidget(plotButton, 8, 0, 1, 2, Qt::AlignCenter);
}
void ResourceView::plotClicked() {
if ((habType->text() == NULL) ||
(habId->text() == NULL) ||
(nodeId->text() == NULL) ||
(resourceId->text() == NULL))
return;
bionet_resource_t* res = resourceInView();
if (res == NULL)
return;
if (bionet_resource_get_data_type(res) == BIONET_RESOURCE_DATA_TYPE_STRING)
return;
QString id = QString("%1.%2.%3:%4").arg(habType->text()).arg(habId->text()).arg(nodeId->text()).arg(resourceId->text());
//cout << "Sending " << qPrintable(id) << endl;
emit(plotResource(id));
}
bionet_resource_t* ResourceView::resourceInView() {
bionet_resource_t * resource;
resource = bionet_cache_lookup_resource(
qPrintable(habType->text()),
qPrintable(habId->text()),
qPrintable(nodeId->text()),
qPrintable(resourceId->text()));
return resource;
}
<commit_msg>removing a qDebug<commit_after>
// Copyright (c) 2008-2009, Regents of the University of Colorado.
// This work was supported by NASA contracts NNJ05HE10G, NNC06CB40C, and
// NNC07CB47C.
#include <QGridLayout>
#include <QPushButton>
#include <QLineEdit>
#include <QString>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <iostream>
#include "resourceview.h"
using namespace std;
ResourceView :: ResourceView (QWidget* parent) : QGridLayout(parent) {
popupError = new QErrorMessage();
habTypeTitle = new QLabel("HAB Type");
habIdTitle = new QLabel("HAB ID");
nodeIdTitle = new QLabel("Node ID");
resourceIdTitle = new QLabel("Resource");
flavorTitle = new QLabel("Flavor");
dataTypeTitle = new QLabel("Data Type");
timestampTitle = new QLabel("Timestamp");
valueTitle = new QLabel("Value");
submitResourceValue = new QPushButton(tr("&Update Value"));
plotButton = new QPushButton(tr("&Plot"));
valueEditor = new QLineEdit();
habType = new QLabel();
habId = new QLabel();
nodeId = new QLabel();
resourceId = new QLabel();
flavor = new QLabel();
dataType = new QLabel();
timestamp = new QLabel();
value = new QLabel();
addWidget(habTypeTitle, 0, 0, Qt::AlignCenter);
addWidget(habIdTitle, 1, 0, Qt::AlignCenter);
addWidget(nodeIdTitle, 2, 0, Qt::AlignCenter);
addWidget(resourceIdTitle, 3, 0, Qt::AlignCenter);
addWidget(flavorTitle, 4, 0, Qt::AlignCenter);
addWidget(dataTypeTitle, 5, 0, Qt::AlignCenter);
addWidget(timestampTitle, 6, 0, Qt::AlignCenter);
addWidget(valueTitle, 7, 0, Qt::AlignCenter);
addWidget(habType, 0, 1, Qt::AlignCenter);
addWidget(habId, 1, 1, Qt::AlignCenter);
addWidget(nodeId, 2, 1, Qt::AlignCenter);
addWidget(resourceId, 3, 1, Qt::AlignCenter);
addWidget(flavor, 4, 1, Qt::AlignCenter);
addWidget(dataType, 5, 1, Qt::AlignCenter);
addWidget(timestamp, 6, 1, Qt::AlignCenter);
addWidget(value, 7, 1, Qt::AlignCenter);
addWidget(plotButton, 8, 0, 1, 2, Qt::AlignCenter); // for plotting
plotButton->setDisabled(true);
setColumnMinimumWidth(0, 50);
setColumnStretch(0, 0);
setColumnMinimumWidth(1, 50);
setColumnStretch(1, 0);
connect(valueEditor, SIGNAL(returnPressed()), this, SLOT(textEntered()));
connect(submitResourceValue, SIGNAL(pressed()), this, SLOT(textEntered()));
connect(plotButton, SIGNAL(clicked()), this, SLOT(plotClicked()));
}
void ResourceView::updatePanel(bionet_resource_t* resource) {
bionet_datapoint_t *datapoint = bionet_resource_get_datapoint_by_index(resource, 0);
if (datapoint != NULL) {
QString exactValue(bionet_value_to_str(bionet_datapoint_get_value(datapoint)));
// For all of the really large resources
if (exactValue.toFloat() > 1e16)
value->setText(QString().setNum(exactValue.toFloat(), 'e', 16));
else
value->setText(exactValue);
timestamp->setText(bionet_datapoint_timestamp_to_string(datapoint));
} else {
timestamp->setText("N/A");
value->setText("(no known value)");
}
if ((bionet_resource_get_flavor(resource) == BIONET_RESOURCE_FLAVOR_PARAMETER) ||
(bionet_resource_get_flavor(resource) == BIONET_RESOURCE_FLAVOR_ACTUATOR)) {
removeWidget(plotButton);
addWidget(submitResourceValue, 8, 0);
addWidget(valueEditor, 8, 1);
submitResourceValue->show();
valueEditor->show();
addWidget(plotButton, 9, 0, 1, 2, Qt::AlignCenter);
plotButton->setFocusPolicy(Qt::NoFocus);
submitResourceValue->setFocusPolicy(Qt::ClickFocus);
valueEditor->setFocusPolicy(Qt::StrongFocus);
submitResourceValue->setEnabled(true);
valueEditor->setEnabled(true);
} else if (rowCount() == 10) {
removeSubmitableRows();
plotButton->setFocusPolicy(Qt::StrongFocus);
}
if (bionet_resource_get_data_type(resource) == BIONET_RESOURCE_DATA_TYPE_STRING)
plotButton->setEnabled(false);
else
plotButton->setEnabled(true);
return;
}
void ResourceView::clearView() {
if (rowCount() == 10) {
// if there was send update button there would be 10 rows
removeSubmitableRows();
}
habType->setText(QString());
habId->setText(QString());
nodeId->setText(QString());
resourceId->setText(QString());
flavor->setText(QString());
dataType->setText(QString());
timestamp->setText(QString());
value->setText(QString());
plotButton->setDisabled(true);
}
void ResourceView::lostHab(bionet_hab_t* hab) {
if (habInPanel(bionet_hab_get_type(hab), bionet_hab_get_id(hab)))
clearView();
}
void ResourceView::lostNode(bionet_node_t* node) {
bionet_hab_t* hab = bionet_node_get_hab(node);
if (nodeInPanel(bionet_hab_get_type(hab), bionet_hab_get_id(hab), bionet_node_get_id(node)))
clearView();
}
void ResourceView::newResourceSelected(bionet_resource_t* resource) {
bionet_hab_t *hab;
bionet_node_t *node;
node = bionet_resource_get_node(resource);
hab = bionet_resource_get_hab(resource);
resourceIdTitle->setText("Resource");
flavorTitle->setText("Flavor");
dataTypeTitle->setText("Data Type");
timestampTitle->setText("Timestamp");
valueTitle->setText("Value");
habType->setText(bionet_hab_get_type(hab));
habId->setText(bionet_hab_get_id(hab));
nodeId->setText(bionet_node_get_id(node));
resourceId->setText(bionet_resource_get_id(resource));
flavor->setText(bionet_resource_flavor_to_string(bionet_resource_get_flavor(resource)));
dataType->setText(bionet_resource_data_type_to_string(bionet_resource_get_data_type(resource)));
plotButton->setDisabled(false);
updatePanel(resource);
return;
}
void ResourceView::newStreamSelected(bionet_stream_t* stream) {
bionet_hab_t *hab;
bionet_node_t *node;
node = bionet_stream_get_node(stream);
hab = bionet_node_get_hab(node);
if (rowCount() == 10) {
removeSubmitableRows();
plotButton->setDisabled(true);
}
resourceIdTitle->setText("Stream");
flavorTitle->setText("Direction");
dataTypeTitle->setText("Type");
timestampTitle->setText("");
valueTitle->setText("");
habType->setText(bionet_hab_get_type(hab));
habId->setText(bionet_hab_get_id(hab));
nodeId->setText(bionet_node_get_id(node));
resourceId->setText(bionet_stream_get_id(stream));
flavor->setText(bionet_stream_direction_to_string(bionet_stream_get_direction(stream)));
dataType->setText(bionet_stream_get_type(stream));
timestamp->setText("");
value->setText("");
}
void ResourceView::resourceValueChanged(bionet_datapoint_t* datapoint) {
bionet_resource_t *resource;
if (datapoint == NULL)
return;
resource = bionet_datapoint_get_resource(datapoint);
if (resourceInPanel(resource))
updatePanel(resource);
}
void ResourceView::textEntered() {
int r = 0;
QString name;
if (valueEditor->text() == NULL) {
return;
}
name = QString("%1.%2.%3:%4").arg(habType->text()).arg(habId->text()).arg(nodeId->text()).arg(resourceId->text());
r = bionet_set_resource_by_name(qPrintable(name), qPrintable(valueEditor->text()));
if (r < 0) {
popupError->showMessage("Unable to set resource value");
}
valueEditor->clear();
}
bool ResourceView::habInPanel(const char* habTypeComparison, const char* habIdComparison) {
if ((habIdComparison == habId->text()) &&
(habTypeComparison == habType->text()))
return TRUE;
return FALSE;
}
bool ResourceView::nodeInPanel(const char* habTypeComparison, const char* habIdComparison, const char* nodeIdComparison) {
if ((habInPanel(habTypeComparison, habIdComparison)) &&
(nodeIdComparison == nodeId->text()))
return TRUE;
return FALSE;
}
bool ResourceView::resourceInPanel(bionet_resource_t* resource) {
bionet_hab_t* hab;
bionet_node_t* node;
node = bionet_resource_get_node(resource);
hab = bionet_resource_get_hab(resource);
if (nodeInPanel(bionet_hab_get_type(hab), bionet_hab_get_id(hab), bionet_node_get_id(node)) &&
(bionet_resource_get_id(resource) == resourceId->text()))
return TRUE;
return FALSE;
}
void ResourceView::removeSubmitableRows() {
//removeWidget(plotButton);
removeWidget(submitResourceValue);
submitResourceValue->hide();
removeWidget(valueEditor);
valueEditor->hide();
addWidget(plotButton, 8, 0, 1, 2, Qt::AlignCenter);
}
void ResourceView::plotClicked() {
if ((habType->text() == NULL) ||
(habId->text() == NULL) ||
(nodeId->text() == NULL) ||
(resourceId->text() == NULL))
return;
bionet_resource_t* res = resourceInView();
if (res == NULL)
return;
if (bionet_resource_get_data_type(res) == BIONET_RESOURCE_DATA_TYPE_STRING)
return;
QString id = QString("%1.%2.%3:%4").arg(habType->text()).arg(habId->text()).arg(nodeId->text()).arg(resourceId->text());
//cout << "Sending " << qPrintable(id) << endl;
emit(plotResource(id));
}
bionet_resource_t* ResourceView::resourceInView() {
bionet_resource_t * resource;
resource = bionet_cache_lookup_resource(
qPrintable(habType->text()),
qPrintable(habId->text()),
qPrintable(nodeId->text()),
qPrintable(resourceId->text()));
return resource;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2016 Jack Grigg
// Copyright (c) 2016 The Zcash developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <algorithm>
#include <cassert>
// Checks if the intersection of a.indices and b.indices is empty
template<size_t WIDTH>
bool DistinctIndices(const FullStepRow<WIDTH>& a, const FullStepRow<WIDTH>& b, size_t len, size_t lenIndices)
{
std::vector<eh_index> aSrt = a.GetIndices(len, lenIndices);
std::vector<eh_index> bSrt = b.GetIndices(len, lenIndices);
std::sort(aSrt.begin(), aSrt.end());
std::sort(bSrt.begin(), bSrt.end());
unsigned int i = 0;
for (unsigned int j = 0; j < bSrt.size(); j++) {
while (aSrt[i] < bSrt[j]) {
i++;
if (i == aSrt.size()) { return true; }
}
assert(aSrt[i] >= bSrt[j]);
if (aSrt[i] == bSrt[j]) { return false; }
}
return true;
}
template<size_t WIDTH>
bool IsValidBranch(const FullStepRow<WIDTH>& a, const size_t len, const unsigned int ilen, const eh_trunc t)
{
return TruncateIndex(ArrayToEhIndex(a.hash+len), ilen) == t;
}
<commit_msg>Auto merge of #1005 - bitcartel:zc.v0.11.2.z4_issue_857_optimize, r=ebfull<commit_after>// Copyright (c) 2016 Jack Grigg
// Copyright (c) 2016 The Zcash developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <algorithm>
#include <cassert>
// Checks if the intersection of a.indices and b.indices is empty
template<size_t WIDTH>
bool DistinctIndices(const FullStepRow<WIDTH>& a, const FullStepRow<WIDTH>& b, size_t len, size_t lenIndices)
{
std::vector<eh_index> vIndicesA = a.GetIndices(len, lenIndices);
std::vector<eh_index> vIndicesB = b.GetIndices(len, lenIndices);
for(auto const& value1: vIndicesA) {
for(auto const& value2: vIndicesB) {
if (value1==value2) {
return false;
}
}
}
return true;
}
template<size_t WIDTH>
bool IsValidBranch(const FullStepRow<WIDTH>& a, const size_t len, const unsigned int ilen, const eh_trunc t)
{
return TruncateIndex(ArrayToEhIndex(a.hash+len), ilen) == t;
}
<|endoftext|> |
<commit_before>#include <supermarx/serialization/msgpack_deserializer.hpp>
#include <cstring>
namespace supermarx
{
msgpack_deserializer::msgpack_deserializer()
: pac()
, pac_result()
, stack()
{}
msgpack_deserializer::~msgpack_deserializer()
{}
msgpack_deserializer::stack_e::stack_e(const msgpack::object* _obj_ptr, type_t _t, size_t _n, size_t _i)
: obj_ptr(_obj_ptr)
, t(_t)
, n(_n)
, i(_i)
{}
void msgpack_deserializer::feed(const std::string& str)
{
pac.reserve_buffer(str.size());
memcpy(pac.buffer(), str.data(), str.size());
pac.buffer_consumed(str.size());
}
std::string convert_msgpack_type(const msgpack::type::object_type t)
{
switch(t)
{
case msgpack::type::ARRAY:
return "ARRAY";
case msgpack::type::BOOLEAN:
return "BOOLEAN";
case msgpack::type::FLOAT:
return "FLOAT";
case msgpack::type::MAP:
return "MAP";
case msgpack::type::NEGATIVE_INTEGER:
return "NEGATIVE_INTEGER";
case msgpack::type::NIL:
return "NIL";
case msgpack::type::POSITIVE_INTEGER:
return "POSITIVE_INTEGER";
case msgpack::type::STR:
return "STR";
case msgpack::type::BIN:
return "BIN";
case msgpack::type::EXT:
return "EXT";
default:
return "UNKNOWN";
}
}
const msgpack::object& msgpack_deserializer::read(const msgpack::type::object_type t_expected)
{
if(stack.empty())
{
if(!pac.next(&pac_result))
throw type_error("anything", "nothing (stream empty)");
stack.emplace(&pac_result.get(), type_t::non_container, 1, 0);
}
stack_e& e = stack.top();
const msgpack::object* result_ptr;
switch(e.t)
{
case type_t::array:
result_ptr = &e.obj_ptr->via.array.ptr[e.i];
break;
case type_t::map:
{
msgpack::object_kv& kv = e.obj_ptr->via.map.ptr[e.i/2];
result_ptr = (e.i % 2 == 0) ? &kv.key : &kv.val;
}
break;
case type_t::non_container:
result_ptr = e.obj_ptr;
break;
}
if(t_expected != result_ptr->type)
throw type_error(convert_msgpack_type(t_expected), convert_msgpack_type(result_ptr->type));
e.i++;
if(e.i >= e.n)
stack.pop();
return *result_ptr;
}
void msgpack_deserializer::read_key(const std::string& key)
{
if(stack.empty() || stack.top().t != type_t::map)
return; //Do not check if we're not in a map
const msgpack::object& obj = read(msgpack::type::STR);
const std::string received(obj.via.str.ptr, obj.via.str.size);
if(key != received)
throw key_error(key, received);
}
template<typename R = void, typename S, typename F>
inline R autorollbackonfailure(S& stack, F f)
{
// Protection against changes in top node; and removal (pop) of top node
auto const e = stack.top();
size_t depth = stack.size();
auto rollback_f([&]()
{
if(depth == stack.size())
stack.top() = e;
else if(depth == stack.size() - 1)
stack.emplace(e);
else
throw std::logic_error("Rollback failure");
});
try
{
return f();
} catch(msgpack_deserializer::type_error e)
{
rollback_f();
throw e;
} catch(msgpack_deserializer::key_error e)
{
rollback_f();
throw e;
} catch(std::runtime_error e)
{
rollback_f();
throw e;
}
}
size_t msgpack_deserializer::read_array(const std::string& name)
{
return autorollbackonfailure<size_t>(stack, [&]() {
read_key(name);
const msgpack::object& obj = read(msgpack::type::ARRAY);
if(obj.via.array.size > 0)
stack.emplace(&obj, type_t::array, obj.via.array.size, 0);
return obj.via.array.size;
});
}
size_t msgpack_deserializer::read_object(const std::string& name)
{
read_key(name);
const msgpack::object& obj = read(msgpack::type::MAP);
if(obj.via.map.size > 0)
stack.emplace(&obj, type_t::map, obj.via.map.size*2, 0);
return obj.via.map.size;
}
void msgpack_deserializer::read_null(const std::string& name)
{
autorollbackonfailure(stack, [&]() {
read_key(name);
read(msgpack::type::NIL);
});
}
void msgpack_deserializer::read(const std::string& key, uint64_t& x)
{
autorollbackonfailure(stack, [&]() {
read_key(key);
const msgpack::object& obj = read(msgpack::type::POSITIVE_INTEGER);
x = obj.via.u64;
});
}
void msgpack_deserializer::read(const std::string& key, raw& x)
{
autorollbackonfailure(stack, [&]() {
read_key(key);
const msgpack::object& obj = read(msgpack::type::BIN);
raw tmp(obj.via.bin.ptr, obj.via.bin.size);
x.swap(tmp);
});
}
void msgpack_deserializer::read(const std::string &key, token &x)
{
autorollbackonfailure(stack, [&]() {
read_key(key);
const msgpack::object& obj = read(msgpack::type::BIN);
if(obj.via.bin.size != x.size())
throw std::runtime_error("Incorrect size of token from msgpack_deserializer buffer");
std::memcpy(x.data(), obj.via.bin.ptr, obj.via.bin.size);
});
}
void msgpack_deserializer::read(const std::string& key, std::string& x)
{
autorollbackonfailure(stack, [&]() {
read_key(key);
const msgpack::object& obj = read(msgpack::type::STR);
x = std::string(obj.via.str.ptr, obj.via.str.size);
});
}
}
<commit_msg>Do not attempt to rollback when original state is empty<commit_after>#include <supermarx/serialization/msgpack_deserializer.hpp>
#include <cstring>
#include <utility>
namespace supermarx
{
msgpack_deserializer::msgpack_deserializer()
: pac()
, pac_result()
, stack()
{}
msgpack_deserializer::~msgpack_deserializer()
{}
msgpack_deserializer::stack_e::stack_e(const msgpack::object* _obj_ptr, type_t _t, size_t _n, size_t _i)
: obj_ptr(_obj_ptr)
, t(_t)
, n(_n)
, i(_i)
{}
void msgpack_deserializer::feed(const std::string& str)
{
pac.reserve_buffer(str.size());
memcpy(pac.buffer(), str.data(), str.size());
pac.buffer_consumed(str.size());
}
std::string convert_msgpack_type(const msgpack::type::object_type t)
{
switch(t)
{
case msgpack::type::ARRAY:
return "ARRAY";
case msgpack::type::BOOLEAN:
return "BOOLEAN";
case msgpack::type::FLOAT:
return "FLOAT";
case msgpack::type::MAP:
return "MAP";
case msgpack::type::NEGATIVE_INTEGER:
return "NEGATIVE_INTEGER";
case msgpack::type::NIL:
return "NIL";
case msgpack::type::POSITIVE_INTEGER:
return "POSITIVE_INTEGER";
case msgpack::type::STR:
return "STR";
case msgpack::type::BIN:
return "BIN";
case msgpack::type::EXT:
return "EXT";
default:
return "UNKNOWN";
}
}
const msgpack::object& msgpack_deserializer::read(const msgpack::type::object_type t_expected)
{
if(stack.empty())
{
if(!pac.next(&pac_result))
throw type_error("anything", "nothing (stream empty)");
stack.emplace(&pac_result.get(), type_t::non_container, 1, 0);
}
stack_e& e = stack.top();
const msgpack::object* result_ptr;
switch(e.t)
{
case type_t::array:
result_ptr = &e.obj_ptr->via.array.ptr[e.i];
break;
case type_t::map:
{
msgpack::object_kv& kv = e.obj_ptr->via.map.ptr[e.i/2];
result_ptr = (e.i % 2 == 0) ? &kv.key : &kv.val;
}
break;
case type_t::non_container:
result_ptr = e.obj_ptr;
break;
}
if(t_expected != result_ptr->type)
throw type_error(convert_msgpack_type(t_expected), convert_msgpack_type(result_ptr->type));
e.i++;
if(e.i >= e.n)
stack.pop();
return *result_ptr;
}
void msgpack_deserializer::read_key(const std::string& key)
{
if(stack.empty() || stack.top().t != type_t::map)
return; //Do not check if we're not in a map
const msgpack::object& obj = read(msgpack::type::STR);
const std::string received(obj.via.str.ptr, obj.via.str.size);
if(key != received)
throw key_error(key, received);
}
template<typename R = void, typename S, typename F>
inline R autorollbackonfailure(S& stack, F f)
{
// Protection against changes in top node; and removal (pop) of top node
if(stack.empty())
return f(); // Nothing to rollback in any case
auto const e = stack.top();
size_t depth = stack.size();
auto rollback_f([&]()
{
if(depth == stack.size())
stack.top().i = e.i;
else if(depth == stack.size() - 1)
stack.emplace(e);
else
throw std::logic_error("Rollback failure");
});
try
{
return f();
} catch(msgpack_deserializer::type_error e)
{
rollback_f();
throw e;
} catch(msgpack_deserializer::key_error e)
{
rollback_f();
throw e;
} catch(std::runtime_error e)
{
rollback_f();
throw e;
}
}
size_t msgpack_deserializer::read_array(const std::string& name)
{
return autorollbackonfailure<size_t>(stack, [&]() {
read_key(name);
const msgpack::object& obj = read(msgpack::type::ARRAY);
if(obj.via.array.size > 0)
stack.emplace(&obj, type_t::array, obj.via.array.size, 0);
return obj.via.array.size;
});
}
size_t msgpack_deserializer::read_object(const std::string& name)
{
read_key(name);
const msgpack::object& obj = read(msgpack::type::MAP);
if(obj.via.map.size > 0)
stack.emplace(&obj, type_t::map, obj.via.map.size*2, 0);
return obj.via.map.size;
}
void msgpack_deserializer::read_null(const std::string& name)
{
autorollbackonfailure(stack, [&]() {
read_key(name);
read(msgpack::type::NIL);
});
}
void msgpack_deserializer::read(const std::string& key, uint64_t& x)
{
autorollbackonfailure(stack, [&]() {
read_key(key);
const msgpack::object& obj = read(msgpack::type::POSITIVE_INTEGER);
x = obj.via.u64;
});
}
void msgpack_deserializer::read(const std::string& key, raw& x)
{
autorollbackonfailure(stack, [&]() {
read_key(key);
const msgpack::object& obj = read(msgpack::type::BIN);
raw tmp(obj.via.bin.ptr, obj.via.bin.size);
x.swap(tmp);
});
}
void msgpack_deserializer::read(const std::string &key, token &x)
{
autorollbackonfailure(stack, [&]() {
read_key(key);
const msgpack::object& obj = read(msgpack::type::BIN);
if(obj.via.bin.size != x.size())
throw std::runtime_error("Incorrect size of token from msgpack_deserializer buffer");
std::memcpy(x.data(), obj.via.bin.ptr, obj.via.bin.size);
});
}
void msgpack_deserializer::read(const std::string& key, std::string& x)
{
autorollbackonfailure(stack, [&]() {
read_key(key);
const msgpack::object& obj = read(msgpack::type::STR);
x = std::string(obj.via.str.ptr, obj.via.str.size);
});
}
}
<|endoftext|> |
<commit_before>/*
* Copyright © 2014 Mozilla Foundation
*
* This program is made available under an ISC-style license. See the
* accompanying file LICENSE for details.
*/
#include <cmath>
#include <cassert>
#include <cstring>
#include <cstddef>
#include <cstdio>
#if defined(HAVE_CONFIG_H)
#include "config.h"
#endif
#include "cubeb_resampler.h"
#include "cubeb-speex-resampler.h"
#include "cubeb_resampler_internal.h"
#include "cubeb_utils.h"
int
to_speex_quality(cubeb_resampler_quality q)
{
switch(q) {
case CUBEB_RESAMPLER_QUALITY_VOIP:
return SPEEX_RESAMPLER_QUALITY_VOIP;
case CUBEB_RESAMPLER_QUALITY_DEFAULT:
return SPEEX_RESAMPLER_QUALITY_DEFAULT;
case CUBEB_RESAMPLER_QUALITY_DESKTOP:
return SPEEX_RESAMPLER_QUALITY_DESKTOP;
default:
assert(false);
return 0XFFFFFFFF;
}
}
template<typename T>
cubeb_resampler_speex_one_way<T>::cubeb_resampler_speex_one_way(uint32_t channels,
uint32_t source_rate,
uint32_t target_rate,
int quality)
: processor(channels)
, resampling_ratio(static_cast<float>(source_rate) / target_rate)
, additional_latency(0)
{
int r;
speex_resampler = speex_resampler_init(channels, source_rate,
target_rate, quality, &r);
assert(r == RESAMPLER_ERR_SUCCESS && "resampler allocation failure");
}
template<typename T>
cubeb_resampler_speex_one_way<T>::~cubeb_resampler_speex_one_way()
{
speex_resampler_destroy(speex_resampler);
}
long noop_resampler::fill(void * input_buffer, long * input_frames_count,
void * output_buffer, long output_frames)
{
assert(input_buffer && output_buffer &&
*input_frames_count >= output_frames ||
!input_buffer && input_frames_count == 0 ||
!output_buffer && output_frames== 0);
if (*input_frames_count != output_frames) {
assert(*input_frames_count > output_frames);
*input_frames_count = output_frames;
}
return data_callback(stream, user_ptr,
input_buffer, output_buffer, output_frames);
}
template<typename T, typename InputProcessor, typename OutputProcessor>
cubeb_resampler_speex<T, InputProcessor, OutputProcessor>
::cubeb_resampler_speex(InputProcessor * input_processor,
OutputProcessor * output_processor,
cubeb_stream * s,
cubeb_data_callback cb,
void * ptr)
: input_processor(input_processor)
, output_processor(output_processor)
, stream(s)
, data_callback(cb)
, user_ptr(ptr)
{
if (input_processor && output_processor) {
// Add some delay on the processor that has the lowest delay so that the
// streams are synchronized.
uint32_t in_latency = input_processor->latency();
uint32_t out_latency = output_processor->latency();
if (in_latency > out_latency) {
uint32_t latency_diff = in_latency - out_latency;
output_processor->add_latency(latency_diff);
} else if (in_latency < out_latency) {
uint32_t latency_diff = out_latency - in_latency;
input_processor->add_latency(latency_diff);
}
fill_internal = &cubeb_resampler_speex::fill_internal_duplex;
} else if (input_processor) {
fill_internal = &cubeb_resampler_speex::fill_internal_input;
} else if (output_processor) {
fill_internal = &cubeb_resampler_speex::fill_internal_output;
}
}
template<typename T, typename InputProcessor, typename OutputProcessor>
cubeb_resampler_speex<T, InputProcessor, OutputProcessor>
::~cubeb_resampler_speex()
{ }
template<typename T, typename InputProcessor, typename OutputProcessor>
long
cubeb_resampler_speex<T, InputProcessor, OutputProcessor>
::fill(void * input_buffer, long * input_frames_count,
void * output_buffer, long output_frames_needed)
{
/* Input and output buffers, typed */
T * in_buffer = reinterpret_cast<T*>(input_buffer);
T * out_buffer = reinterpret_cast<T*>(output_buffer);
return (this->*fill_internal)(in_buffer, input_frames_count,
out_buffer, output_frames_needed);
}
template<typename T, typename InputProcessor, typename OutputProcessor>
long
cubeb_resampler_speex<T, InputProcessor, OutputProcessor>
::fill_internal_output(T * input_buffer, long * input_frames_count,
T * output_buffer, long output_frames_needed)
{
assert(!input_buffer && !input_frames_count &&
output_buffer && output_frames_needed);
long got = 0;
T * out_unprocessed = nullptr;
uint32_t output_frames_before_processing =
output_processor->input_needed_for_output(output_frames_needed);
/* fill directly the input buffer of the output processor to save a copy */
out_unprocessed =
output_processor->input_buffer(output_frames_before_processing);
got = data_callback(stream, user_ptr,
nullptr, nullptr,
output_frames_before_processing);
/* Process the output. If not enough frames have been returned from the
* callback, drain the processors. */
if (got != output_frames_before_processing) {
got = output_processor->drain(output_buffer, output_frames_needed);
}
else {
output_processor->output(output_buffer, output_frames_needed);
got = output_frames_needed;
}
return got;
}
template<typename T, typename InputProcessor, typename OutputProcessor>
long
cubeb_resampler_speex<T, InputProcessor, OutputProcessor>
::fill_internal_input(T * input_buffer, long * input_frames_count,
T * output_buffer, long output_frames_needed)
{
assert(input_buffer && input_frames_count && *input_frames_count &&
!output_buffer);
/* The input data, after eventual resampling. This is passed to the callback. */
T * resampled_input = nullptr;
/* The number of frames returned from the callback. */
long got = 0;
uint32_t resampled_frame_count = input_processor->output_for_input(*input_frames_count);
/* process the input, and present exactly `output_frames_needed` in the
* callback. */
input_processor->input(input_buffer, *input_frames_count);
resampled_input = input_processor->output(resampled_frame_count);
got = data_callback(stream, user_ptr,
resampled_input, nullptr, resampled_frame_count);
return *input_frames_count;
}
template<typename T, typename InputProcessor, typename OutputProcessor>
long
cubeb_resampler_speex<T, InputProcessor, OutputProcessor>
::fill_internal_duplex(T * in_buffer, long * input_frames_count,
T * out_buffer, long output_frames_needed)
{
/* The input data, after eventual resampling. This is passed to the callback. */
T * resampled_input = nullptr;
/* The output buffer passed down in the callback, that might be resampled. */
T * out_unprocessed = nullptr;
size_t output_frames_before_processing;
/* The number of frames returned from the callback. */
long got = 0;
/* We need to determine how much frames to present to the consumer.
* - If we have a two way stream, but we're only resampling input, we resample
* the input to the number of output frames.
* - If we have a two way stream, but we're only resampling the output, we
* resize the input buffer of the output resampler to the number of input
* frames, and we resample it afterwards.
* - If we resample both ways, we resample the input to the number of frames
* we would need to pass down to the consumer (before resampling the output),
* get the output data, and resample it to the number of frames needed by the
* caller. */
output_frames_before_processing =
output_processor->input_needed_for_output(output_frames_needed);
/* fill directly the input buffer of the output processor to save a copy */
out_unprocessed =
output_processor->input_buffer(output_frames_before_processing);
if (in_buffer) {
/* process the input, and present exactly `output_frames_needed` in the
* callback. */
input_processor->input(in_buffer, *input_frames_count);
resampled_input =
input_processor->output(output_frames_before_processing);
} else {
resampled_input = nullptr;
}
got = data_callback(stream, user_ptr,
resampled_input, out_unprocessed,
output_frames_before_processing);
/* Process the output. If not enough frames have been returned from the
* callback, drain the processors. */
if (got != output_frames_before_processing) {
got = output_processor->drain(out_buffer, output_frames_needed);
} else {
output_processor->output(out_buffer, output_frames_needed);
got = output_frames_needed;
}
return got;
}
/* Resampler C API */
cubeb_resampler *
cubeb_resampler_create(cubeb_stream * stream,
cubeb_stream_params * input_params,
cubeb_stream_params * output_params,
unsigned int target_rate,
cubeb_data_callback callback,
void * user_ptr,
cubeb_resampler_quality quality)
{
cubeb_sample_format format;
assert(input_params || output_params);
if (input_params) {
format = input_params->format;
} else {
format = output_params->format;
}
switch(format) {
case CUBEB_SAMPLE_S16NE:
return cubeb_resampler_create_internal<short>(stream,
input_params,
output_params,
target_rate,
callback,
user_ptr,
quality);
case CUBEB_SAMPLE_FLOAT32NE:
return cubeb_resampler_create_internal<float>(stream,
input_params,
output_params,
target_rate,
callback,
user_ptr,
quality);
default:
assert(false);
}
}
long
cubeb_resampler_fill(cubeb_resampler * resampler,
void * input_buffer,
long * input_frames_count,
void * output_buffer,
long output_frames_needed)
{
return resampler->fill(input_buffer, input_frames_count,
output_buffer, output_frames_needed);
}
void
cubeb_resampler_destroy(cubeb_resampler * resampler)
{
delete resampler;
}
long
cubeb_resampler_latency(cubeb_resampler * resampler)
{
return resampler->latency();
}
<commit_msg>Make the noop_resampler work in output-only mode, by null-checking the pointers.<commit_after>/*
* Copyright © 2014 Mozilla Foundation
*
* This program is made available under an ISC-style license. See the
* accompanying file LICENSE for details.
*/
#include <cmath>
#include <cassert>
#include <cstring>
#include <cstddef>
#include <cstdio>
#if defined(HAVE_CONFIG_H)
#include "config.h"
#endif
#include "cubeb_resampler.h"
#include "cubeb-speex-resampler.h"
#include "cubeb_resampler_internal.h"
#include "cubeb_utils.h"
int
to_speex_quality(cubeb_resampler_quality q)
{
switch(q) {
case CUBEB_RESAMPLER_QUALITY_VOIP:
return SPEEX_RESAMPLER_QUALITY_VOIP;
case CUBEB_RESAMPLER_QUALITY_DEFAULT:
return SPEEX_RESAMPLER_QUALITY_DEFAULT;
case CUBEB_RESAMPLER_QUALITY_DESKTOP:
return SPEEX_RESAMPLER_QUALITY_DESKTOP;
default:
assert(false);
return 0XFFFFFFFF;
}
}
template<typename T>
cubeb_resampler_speex_one_way<T>::cubeb_resampler_speex_one_way(uint32_t channels,
uint32_t source_rate,
uint32_t target_rate,
int quality)
: processor(channels)
, resampling_ratio(static_cast<float>(source_rate) / target_rate)
, additional_latency(0)
{
int r;
speex_resampler = speex_resampler_init(channels, source_rate,
target_rate, quality, &r);
assert(r == RESAMPLER_ERR_SUCCESS && "resampler allocation failure");
}
template<typename T>
cubeb_resampler_speex_one_way<T>::~cubeb_resampler_speex_one_way()
{
speex_resampler_destroy(speex_resampler);
}
long noop_resampler::fill(void * input_buffer, long * input_frames_count,
void * output_buffer, long output_frames)
{
assert(input_buffer && output_buffer &&
*input_frames_count >= output_frames ||
!input_buffer && !input_frames_count ||
!output_buffer && output_frames == 0);
if (output_buffer == nullptr) {
output_frames = *input_frames_count;
}
if (input_buffer && *input_frames_count != output_frames) {
assert(*input_frames_count > output_frames);
*input_frames_count = output_frames;
}
return data_callback(stream, user_ptr,
input_buffer, output_buffer, output_frames);
}
template<typename T, typename InputProcessor, typename OutputProcessor>
cubeb_resampler_speex<T, InputProcessor, OutputProcessor>
::cubeb_resampler_speex(InputProcessor * input_processor,
OutputProcessor * output_processor,
cubeb_stream * s,
cubeb_data_callback cb,
void * ptr)
: input_processor(input_processor)
, output_processor(output_processor)
, stream(s)
, data_callback(cb)
, user_ptr(ptr)
{
if (input_processor && output_processor) {
// Add some delay on the processor that has the lowest delay so that the
// streams are synchronized.
uint32_t in_latency = input_processor->latency();
uint32_t out_latency = output_processor->latency();
if (in_latency > out_latency) {
uint32_t latency_diff = in_latency - out_latency;
output_processor->add_latency(latency_diff);
} else if (in_latency < out_latency) {
uint32_t latency_diff = out_latency - in_latency;
input_processor->add_latency(latency_diff);
}
fill_internal = &cubeb_resampler_speex::fill_internal_duplex;
} else if (input_processor) {
fill_internal = &cubeb_resampler_speex::fill_internal_input;
} else if (output_processor) {
fill_internal = &cubeb_resampler_speex::fill_internal_output;
}
}
template<typename T, typename InputProcessor, typename OutputProcessor>
cubeb_resampler_speex<T, InputProcessor, OutputProcessor>
::~cubeb_resampler_speex()
{ }
template<typename T, typename InputProcessor, typename OutputProcessor>
long
cubeb_resampler_speex<T, InputProcessor, OutputProcessor>
::fill(void * input_buffer, long * input_frames_count,
void * output_buffer, long output_frames_needed)
{
/* Input and output buffers, typed */
T * in_buffer = reinterpret_cast<T*>(input_buffer);
T * out_buffer = reinterpret_cast<T*>(output_buffer);
return (this->*fill_internal)(in_buffer, input_frames_count,
out_buffer, output_frames_needed);
}
template<typename T, typename InputProcessor, typename OutputProcessor>
long
cubeb_resampler_speex<T, InputProcessor, OutputProcessor>
::fill_internal_output(T * input_buffer, long * input_frames_count,
T * output_buffer, long output_frames_needed)
{
assert(!input_buffer && !input_frames_count &&
output_buffer && output_frames_needed);
long got = 0;
T * out_unprocessed = nullptr;
uint32_t output_frames_before_processing =
output_processor->input_needed_for_output(output_frames_needed);
/* fill directly the input buffer of the output processor to save a copy */
out_unprocessed =
output_processor->input_buffer(output_frames_before_processing);
got = data_callback(stream, user_ptr,
nullptr, nullptr,
output_frames_before_processing);
/* Process the output. If not enough frames have been returned from the
* callback, drain the processors. */
if (got != output_frames_before_processing) {
got = output_processor->drain(output_buffer, output_frames_needed);
}
else {
output_processor->output(output_buffer, output_frames_needed);
got = output_frames_needed;
}
return got;
}
template<typename T, typename InputProcessor, typename OutputProcessor>
long
cubeb_resampler_speex<T, InputProcessor, OutputProcessor>
::fill_internal_input(T * input_buffer, long * input_frames_count,
T * output_buffer, long output_frames_needed)
{
assert(input_buffer && input_frames_count && *input_frames_count &&
!output_buffer);
/* The input data, after eventual resampling. This is passed to the callback. */
T * resampled_input = nullptr;
/* The number of frames returned from the callback. */
long got = 0;
uint32_t resampled_frame_count = input_processor->output_for_input(*input_frames_count);
/* process the input, and present exactly `output_frames_needed` in the
* callback. */
input_processor->input(input_buffer, *input_frames_count);
resampled_input = input_processor->output(resampled_frame_count);
got = data_callback(stream, user_ptr,
resampled_input, nullptr, resampled_frame_count);
return *input_frames_count;
}
template<typename T, typename InputProcessor, typename OutputProcessor>
long
cubeb_resampler_speex<T, InputProcessor, OutputProcessor>
::fill_internal_duplex(T * in_buffer, long * input_frames_count,
T * out_buffer, long output_frames_needed)
{
/* The input data, after eventual resampling. This is passed to the callback. */
T * resampled_input = nullptr;
/* The output buffer passed down in the callback, that might be resampled. */
T * out_unprocessed = nullptr;
size_t output_frames_before_processing;
/* The number of frames returned from the callback. */
long got = 0;
/* We need to determine how much frames to present to the consumer.
* - If we have a two way stream, but we're only resampling input, we resample
* the input to the number of output frames.
* - If we have a two way stream, but we're only resampling the output, we
* resize the input buffer of the output resampler to the number of input
* frames, and we resample it afterwards.
* - If we resample both ways, we resample the input to the number of frames
* we would need to pass down to the consumer (before resampling the output),
* get the output data, and resample it to the number of frames needed by the
* caller. */
output_frames_before_processing =
output_processor->input_needed_for_output(output_frames_needed);
/* fill directly the input buffer of the output processor to save a copy */
out_unprocessed =
output_processor->input_buffer(output_frames_before_processing);
if (in_buffer) {
/* process the input, and present exactly `output_frames_needed` in the
* callback. */
input_processor->input(in_buffer, *input_frames_count);
resampled_input =
input_processor->output(output_frames_before_processing);
} else {
resampled_input = nullptr;
}
got = data_callback(stream, user_ptr,
resampled_input, out_unprocessed,
output_frames_before_processing);
/* Process the output. If not enough frames have been returned from the
* callback, drain the processors. */
if (got != output_frames_before_processing) {
got = output_processor->drain(out_buffer, output_frames_needed);
} else {
output_processor->output(out_buffer, output_frames_needed);
got = output_frames_needed;
}
return got;
}
/* Resampler C API */
cubeb_resampler *
cubeb_resampler_create(cubeb_stream * stream,
cubeb_stream_params * input_params,
cubeb_stream_params * output_params,
unsigned int target_rate,
cubeb_data_callback callback,
void * user_ptr,
cubeb_resampler_quality quality)
{
cubeb_sample_format format;
assert(input_params || output_params);
if (input_params) {
format = input_params->format;
} else {
format = output_params->format;
}
switch(format) {
case CUBEB_SAMPLE_S16NE:
return cubeb_resampler_create_internal<short>(stream,
input_params,
output_params,
target_rate,
callback,
user_ptr,
quality);
case CUBEB_SAMPLE_FLOAT32NE:
return cubeb_resampler_create_internal<float>(stream,
input_params,
output_params,
target_rate,
callback,
user_ptr,
quality);
default:
assert(false);
}
}
long
cubeb_resampler_fill(cubeb_resampler * resampler,
void * input_buffer,
long * input_frames_count,
void * output_buffer,
long output_frames_needed)
{
return resampler->fill(input_buffer, input_frames_count,
output_buffer, output_frames_needed);
}
void
cubeb_resampler_destroy(cubeb_resampler * resampler)
{
delete resampler;
}
long
cubeb_resampler_latency(cubeb_resampler * resampler)
{
return resampler->latency();
}
<|endoftext|> |
<commit_before>#pragma once
#ifndef CUDA_STREAM_H_
#define CUDA_STREAM_H_
#include "cuda/api/types.h"
#include "cuda/api/error.hpp"
#include "cuda/api/kernel_launch.cuh"
#include "cuda/api/current_device.hpp"
#include "cuda/api/device_count.hpp"
#include <cuda_runtime_api.h>
#include <string>
#include <functional>
namespace cuda {
namespace stream {
/**
* Creates a new stream on the current device.
*
* @return the created stream's id
*/
inline id_t create(
priority_t priority = default_priority,
bool synchronizes_with_default_stream = true)
{
unsigned int flags = synchronizes_with_default_stream ?
cudaStreamDefault : cudaStreamNonBlocking;
stream::id_t new_stream_id;
auto result = cudaStreamCreateWithPriority(&new_stream_id, flags, priority);
throw_if_error(result,
std::string("Failed creating a new stream on CUDA device ")
+ std::to_string(device::current::get_id()));
return new_stream_id;
}
/**
* Creates a new stream on an artibrary device
* (which may or may not be the current one)
*
* @return the created stream's id
*/
inline id_t create(
device::id_t device_id,
priority_t priority = default_priority,
bool synchronizes_with_default_stream = true)
{
device::current::ScopedDeviceOverride<> set_device_for_this_scope(device_id);
return create(priority, synchronizes_with_default_stream);
}
} // namespace stream
template <bool AssumesDeviceIsCurrent = detail::do_not_assume_device_is_current>
class stream_t {
public: // type definitions
using callback_t = std::function<void(stream::id_t, status_t)>;
using priority_t = stream::priority_t;
enum : bool {
doesnt_synchronizes_with_default_stream = false,
does_synchronize_with_default_stream = true,
};
protected: // type definitions
using DeviceSetter = ::cuda::device::current::ScopedDeviceOverride<AssumesDeviceIsCurrent>;
public: // statics
/**
* Check whethers a certain stream is associated with a specific device.
*
* @note the stream_t class includes information regarding a stream's
* device association, so this function only makes sense for CUDA stream
* identifiers
*
* @param stream_id the CUDA runtime API identifier for the stream whose
* association is to be checked
* @param device_id a CUDA device identifier
* @return true if the specified stream is associated with the specified
* device, false if they are unassociated
* @throws if the association check returns anything weird
*/
static bool associated_with(stream::id_t stream_id, device::id_t device_id)
{
DeviceSetter set_device_for_this_scope(device_id);
auto result = cudaStreamQuery(stream_id);
switch(result) {
case cudaSuccess:
case cudaErrorNotReady:
return true;
case cudaErrorInvalidResourceHandle:
return false;
default:
throw(std::logic_error("unexpected status returned from cudaStreamQuery()"));
}
}
public: // const getters
stream::id_t id() const { return id_; }
device::id_t device_id() const { return device_id_; }
public: // other non-mutators
/**
* Strangely enough, CUDA won't tell you which device a stream is associated with,
* while it can - supposedly - tell this itself when querying stream status. So,
* let's use that. This is ugly and possibly buggy, but it _might_ just work.
*
* @param stream_id a stream identifier
* @return the identifier of the device for which the stream was created.
*/
device::id_t get_associated_device(stream::id_t stream_id) const
{
if (stream_id == cuda::stream::default_stream_id) {
throw std::invalid_argument("Cannot determine device association The default/null stream");
}
for(device::id_t d = 0; d < device::count(); d++) {
if (associated_with(stream_id, d)) { return d; }
}
throw std::runtime_error("Could not find any device associated with a specified stream");
}
/**
* When true, work running in the created stream may run concurrently with
* work in stream 0 (the NULL stream), and there is no implicit
* synchronization performed between it and stream 0.
*/
bool synchronizes_with_default_stream() const
{
unsigned int flags;
auto result = cudaStreamGetFlags(id_, &flags);
throw_if_error(result,
std::string("Failed obtaining flags for a stream")
+ " on CUDA device " + std::to_string(device_id_));
return flags & cudaStreamNonBlocking;
}
priority_t priority() const
{
int the_priority;
auto result = cudaStreamGetPriority(id_, &the_priority);
throw_if_error(result,
std::string("Failure obtaining priority for a stream")
+ " on CUDA device " + std::to_string(device_id_));
return the_priority;
}
/**
* Check whether the queue has any incomplete operations
*
* @todo What if there are incomplete operations, but they're all waiting on
* something on another queue? Should the queue count as "busy" then?
*
* @return true if all enqueued operations have been completed; false if there
* are any incomplete enqueued operations
*/
bool busy() const
{
DeviceSetter set_device_for_this_scope(device_id_);
auto result = cudaStreamQuery(id_);
switch(result) {
case cudaSuccess:
return true;
case cudaErrorNotReady:
return false;
default:
throw(std::logic_error("unexpected status returned from cudaStreamQuery()"));
}
}
protected: // static methods
/**
* Untested!
*/
static void callback_adapter(stream::id_t stream_id, status_t status, void *type_erased_callback)
{
auto retyped_callback = reinterpret_cast<callback_t*>(type_erased_callback);
(*retyped_callback)(stream_id, status);
}
public: // mutators
template<typename KernelFunction, typename... KernelParameters>
void launch(
const KernelFunction& kernel_function,
launch_configuration_t launch_configuration,
KernelParameters... parameters)
{
return ::cuda::launch(kernel_function, launch_configuration, id_, parameters...);
}
// TODO: Duplicate the above better?
template<typename KernelFunction, typename... KernelParameters>
void enqueue(
const KernelFunction& kernel_function,
launch_configuration_t launch_configuration,
KernelParameters... parameters)
{
return launch(kernel_function, launch_configuration, id_, parameters...);
}
__host__ void synchronize()
{
DeviceSetter set_device_for_this_scope(id_);
// TODO: some kind of string representation for the stream
auto result = cudaStreamSynchronize(id_);
throw_if_error(result,
std::string("Failed synchronizing a stream")
+ " on CUDA device " + std::to_string(device_id_));
}
__host__ void add_callback (callback_t& callback)
{
DeviceSetter set_device_for_this_scope(id_);
// The nVIDIA runtime API (upto v.8) requires flags to be 0, see
// http://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__STREAM.html#group__CUDART__STREAM
enum : unsigned int { fixed_flags = 0 };
// This always registers the static function callback_adapter as the callback -
// but what that one will do is call the actual callback we were passed; note
// that since you can one can have a lambda capture data and wrap that in an
// std::function, there's not much need (it would seem) for an extra inner
// user_data parameter to callback_t.
auto result = cudaStreamAddCallback(id_, &callback_adapter, &callback, fixed_flags);
throw_if_error(result,
std::string("Failed adding a callback to stream ")
+ " on CUDA device " + std::to_string(device_id_));
}
// TODO: wrap this with a nicer interface taking a lambda...
/**
* Attaches a region of managed memory (i.e. in an address space visible
* on all CUDA devices and the host) to this specific stream on its specific device.
* This is actually a commitment vis-a-vis the CUDA driver and the GPU itself that
* it doesn't need to worry about accesses to this memory from elsewhere, and can
* optimize accordingly. Also, the host will be allowed to read from this memory
* region whenever no kernels are pending on this stream
*
* @note This happens asynchronously, as an operation on this stream, i.e.
* the attachment goes into effect (some time after) after previous stream
* operations have concluded.
*
* @param managed_region_start a pointer to the beginning of the managed memory region.
* This cannot be a pointer to anywhere in the middle of an allocated region - you must
* pass whatever cudaMallocManaged (@ref memory::managed:allocate
*/
void enqueue_memory_attachment(const void* managed_region_start)
{
DeviceSetter set_device_for_this_scope(id_);
// This fixed value is required by the CUDA Runtime API,
// to indicate that the entire memory region, rather than a part of it, will be
// attached to this stream
constexpr const size_t length = 0;
auto result = cudaStreamAttachMemAsync(id_, managed_region_start, length, cudaMemAttachSingle);
throw_if_error(result,
std::string("Failed attaching a managed memory region to a stream")
+ " on CUDA device " + std::to_string(device_id_));
}
void wait(event::id_t event_id)
{
// Required by the CUDA runtime API
constexpr const unsigned int flags = 0;
auto result = cudaStreamWaitEvent(id_, event_id, flags);
throw_if_error(result,
std::string("Failed waiting for an event")
+ " on CUDA device " + std::to_string(device_id_));
}
// TODO: wait() with an event_t - possible?
public: // constructors and destructor
stream_t(cuda::device::id_t device_id, stream::id_t stream_id) : device_id_(device_id), id_(stream_id)
{
// TODO: Should we check that the stream is actually associated with the device?
}
~stream_t() { if (is_owning) cudaStreamDestroy(id_); }
public: // named constructor idioms
stream_t<detail::do_not_assume_device_is_current> create(
device::id_t device_id,
priority_t priority = stream::default_priority,
bool synchronizes_with_default_stream = true)
{
return stream_t<detail::do_not_assume_device_is_current>(
AssumesDeviceIsCurrent ?
stream::create(priority, synchronizes_with_default_stream) :
stream::create(device_id, priority, synchronizes_with_default_stream)
);
}
protected: // constructors
// The ctors here are called by named constructor idioms, see below; we don't
// want to "just" create streams willy-nilly just by writing "stream_t my_stream;"...
/**
*
*
* @param device_id
* @param priority a value in the device's allowed priority range
* (@ref cudaDeviceGetStreamPriorityRange
* @param synchronizes_with_default_stream
*/
stream_t(
cuda::device::id_t device_id,
priority_t priority = stream::default_priority,
bool synchronizes_with_default_stream = true) : device_id_(device_id), is_owning(true)
{
stream::create(device_id, priority, synchronizes_with_default_stream);
}
stream_t() : stream_t(cuda::device::current::get_id()) { };
protected: // data members
cuda::device::id_t device_id_;
stream::id_t id_;
bool is_owning { false };
};
template <bool AssumesDeviceIsCurrent = false>
using queue_t = stream_t<AssumesDeviceIsCurrent>;
using queue_id_t = stream::id_t;
} // namespace cuda
#endif /* CUDA_STREAM_H_ */
<commit_msg>Removed the methods regarding stream<->device association out of `stream_t` - as it can only be constructed with a known device association; they are now the freestanding functions `cuda::stream::associated_device` and `cuda::stream::is_associated_with`.<commit_after>#pragma once
#ifndef CUDA_STREAM_H_
#define CUDA_STREAM_H_
#include "cuda/api/types.h"
#include "cuda/api/error.hpp"
#include "cuda/api/kernel_launch.cuh"
#include "cuda/api/current_device.hpp"
#include "cuda/api/device_count.hpp"
#include <cuda_runtime_api.h>
#include <string>
#include <functional>
namespace cuda {
namespace stream {
/**
* Creates a new stream on the current device.
*
* @note stream_t construction _never_ creates a stream!
*
* @return the created stream's id
*/
inline id_t create(
priority_t priority = default_priority,
bool synchronizes_with_default_stream = true)
{
unsigned int flags = synchronizes_with_default_stream ?
cudaStreamDefault : cudaStreamNonBlocking;
stream::id_t new_stream_id;
auto result = cudaStreamCreateWithPriority(&new_stream_id, flags, priority);
throw_if_error(result,
std::string("Failed creating a new stream on CUDA device ")
+ std::to_string(device::current::get_id()));
return new_stream_id;
}
/**
* Creates a new stream on an artibrary device
* (which may or may not be the current one)
*
* @note stream_t construction _never_ creates a stream!
*
* @return the created stream's id
*/
inline id_t create(
device::id_t device_id,
priority_t priority = default_priority,
bool synchronizes_with_default_stream = true)
{
device::current::ScopedDeviceOverride<> set_device_for_this_scope(device_id);
return create(priority, synchronizes_with_default_stream);
}
/**
* Check whether a certain stream is associated with a specific device.
*
* @note the stream_t class includes information regarding a stream's
* device association, so this function only makes sense for CUDA stream
* identifiers
*
* @param stream_id the CUDA runtime API identifier for the stream whose
* association is to be checked
* @param device_id a CUDA device identifier
* @return true if the specified stream is associated with the specified
* device, false if they are unassociated
* @throws if the association check returns anything weird
*/
inline bool is_associated_with(stream::id_t stream_id, device::id_t device_id)
{
device::current::ScopedDeviceOverride<detail::do_not_assume_device_is_current>
set_device_for_this_scope(device_id);
auto result = cudaStreamQuery(stream_id);
switch(result) {
case cudaSuccess:
case cudaErrorNotReady:
return true;
case cudaErrorInvalidResourceHandle:
return false;
default:
throw(std::logic_error("unexpected status returned from cudaStreamQuery()"));
}
}
/**
* Strangely enough, CUDA won't tell you which device a stream is associated with,
* while it can - supposedly - tell this itself when querying stream status. So,
* let's use that. This is ugly and possibly buggy, but it _might_ just work.
*
* @param stream_id a stream identifier
* @return the identifier of the device for which the stream was created.
*/
inline device::id_t associated_device(stream::id_t stream_id)
{
if (stream_id == cuda::stream::default_stream_id) {
throw std::invalid_argument("Cannot determine device association for the default/null stream");
}
for(device::id_t device_index = 0; device_index < device::count(); device_index++) {
if (is_associated_with(stream_id, device_index)) { return device_index; }
}
throw std::runtime_error(
"Could not find any device associated with stream " + detail::as_hex((size_t) stream_id));
}
} // namespace stream
template <bool AssumesDeviceIsCurrent = detail::do_not_assume_device_is_current>
class stream_t {
public: // type definitions
using callback_t = std::function<void(stream::id_t, status_t)>;
using priority_t = stream::priority_t;
enum : bool {
doesnt_synchronizes_with_default_stream = false,
does_synchronize_with_default_stream = true,
};
protected: // type definitions
using DeviceSetter = ::cuda::device::current::ScopedDeviceOverride<AssumesDeviceIsCurrent>;
public: // const getters
stream::id_t id() const { return id_; }
device::id_t device_id() const { return device_id_; }
public: // other non-mutators
/**
* When true, work running in the created stream may run concurrently with
* work in stream 0 (the NULL stream), and there is no implicit
* synchronization performed between it and stream 0.
*/
bool synchronizes_with_default_stream() const
{
unsigned int flags;
auto result = cudaStreamGetFlags(id_, &flags);
throw_if_error(result,
std::string("Failed obtaining flags for a stream")
+ " on CUDA device " + std::to_string(device_id_));
return flags & cudaStreamNonBlocking;
}
priority_t priority() const
{
int the_priority;
auto result = cudaStreamGetPriority(id_, &the_priority);
throw_if_error(result,
std::string("Failure obtaining priority for a stream")
+ " on CUDA device " + std::to_string(device_id_));
return the_priority;
}
/**
* Check whether the queue has any incomplete operations
*
* @todo What if there are incomplete operations, but they're all waiting on
* something on another queue? Should the queue count as "busy" then?
*
* @return true if all enqueued operations have been completed; false if there
* are any incomplete enqueued operations
*/
bool busy() const
{
DeviceSetter set_device_for_this_scope(device_id_);
auto result = cudaStreamQuery(id_);
switch(result) {
case cudaSuccess:
return true;
case cudaErrorNotReady:
return false;
default:
throw(std::logic_error("unexpected status returned from cudaStreamQuery()"));
}
}
protected: // static methods
/**
* Untested!
*/
static void callback_adapter(stream::id_t stream_id, status_t status, void *type_erased_callback)
{
auto retyped_callback = reinterpret_cast<callback_t*>(type_erased_callback);
(*retyped_callback)(stream_id, status);
}
public: // mutators
template<typename KernelFunction, typename... KernelParameters>
void launch(
const KernelFunction& kernel_function,
launch_configuration_t launch_configuration,
KernelParameters... parameters)
{
return ::cuda::launch(kernel_function, launch_configuration, id_, parameters...);
}
// TODO: Duplicate the above better?
template<typename KernelFunction, typename... KernelParameters>
void enqueue(
const KernelFunction& kernel_function,
launch_configuration_t launch_configuration,
KernelParameters... parameters)
{
return launch(kernel_function, launch_configuration, id_, parameters...);
}
__host__ void synchronize()
{
DeviceSetter set_device_for_this_scope(id_);
// TODO: some kind of string representation for the stream
auto result = cudaStreamSynchronize(id_);
throw_if_error(result,
std::string("Failed synchronizing a stream")
+ " on CUDA device " + std::to_string(device_id_));
}
__host__ void add_callback (callback_t& callback)
{
DeviceSetter set_device_for_this_scope(id_);
// The nVIDIA runtime API (upto v.8) requires flags to be 0, see
// http://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__STREAM.html#group__CUDART__STREAM
enum : unsigned int { fixed_flags = 0 };
// This always registers the static function callback_adapter as the callback -
// but what that one will do is call the actual callback we were passed; note
// that since you can one can have a lambda capture data and wrap that in an
// std::function, there's not much need (it would seem) for an extra inner
// user_data parameter to callback_t.
auto result = cudaStreamAddCallback(id_, &callback_adapter, &callback, fixed_flags);
throw_if_error(result,
std::string("Failed adding a callback to stream ")
+ " on CUDA device " + std::to_string(device_id_));
}
// TODO: wrap this with a nicer interface taking a lambda...
/**
* Attaches a region of managed memory (i.e. in an address space visible
* on all CUDA devices and the host) to this specific stream on its specific device.
* This is actually a commitment vis-a-vis the CUDA driver and the GPU itself that
* it doesn't need to worry about accesses to this memory from elsewhere, and can
* optimize accordingly. Also, the host will be allowed to read from this memory
* region whenever no kernels are pending on this stream
*
* @note This happens asynchronously, as an operation on this stream, i.e.
* the attachment goes into effect (some time after) after previous stream
* operations have concluded.
*
* @param managed_region_start a pointer to the beginning of the managed memory region.
* This cannot be a pointer to anywhere in the middle of an allocated region - you must
* pass whatever cudaMallocManaged (@ref memory::managed:allocate
*/
void enqueue_memory_attachment(const void* managed_region_start)
{
DeviceSetter set_device_for_this_scope(id_);
// This fixed value is required by the CUDA Runtime API,
// to indicate that the entire memory region, rather than a part of it, will be
// attached to this stream
constexpr const size_t length = 0;
auto result = cudaStreamAttachMemAsync(id_, managed_region_start, length, cudaMemAttachSingle);
throw_if_error(result,
std::string("Failed attaching a managed memory region to a stream")
+ " on CUDA device " + std::to_string(device_id_));
}
void wait(event::id_t event_id)
{
// Required by the CUDA runtime API
constexpr const unsigned int flags = 0;
auto result = cudaStreamWaitEvent(id_, event_id, flags);
throw_if_error(result,
std::string("Failed waiting for an event")
+ " on CUDA device " + std::to_string(device_id_));
}
// TODO: wait() with an event_t - possible?
public: // constructors and destructor
stream_t(cuda::device::id_t device_id, stream::id_t stream_id) : device_id_(device_id), id_(stream_id)
{
// TODO: Should we check that the stream is actually associated with the device?
}
~stream_t() { if (is_owning) cudaStreamDestroy(id_); }
public: // named constructor idioms
stream_t<detail::do_not_assume_device_is_current> create(
device::id_t device_id,
priority_t priority = stream::default_priority,
bool synchronizes_with_default_stream = true)
{
return stream_t<detail::do_not_assume_device_is_current>(
AssumesDeviceIsCurrent ?
stream::create(priority, synchronizes_with_default_stream) :
stream::create(device_id, priority, synchronizes_with_default_stream)
);
}
protected: // constructors
// The ctors here are called by named constructor idioms, see below; we don't
// want to "just" create streams willy-nilly just by writing "stream_t my_stream;"...
/**
*
*
* @param device_id
* @param priority a value in the device's allowed priority range
* (@ref cudaDeviceGetStreamPriorityRange
* @param synchronizes_with_default_stream
*/
stream_t(
cuda::device::id_t device_id,
priority_t priority = stream::default_priority,
bool synchronizes_with_default_stream = true) : device_id_(device_id), is_owning(true)
{
stream::create(device_id, priority, synchronizes_with_default_stream);
}
stream_t() : stream_t(cuda::device::current::get_id()) { };
protected: // data members
cuda::device::id_t device_id_;
stream::id_t id_;
bool is_owning { false };
};
template <bool AssumesDeviceIsCurrent = false>
using queue_t = stream_t<AssumesDeviceIsCurrent>;
using queue_id_t = stream::id_t;
} // namespace cuda
#endif /* CUDA_STREAM_H_ */
<|endoftext|> |
<commit_before>/*
* consumer_qglsl.cpp
* Copyright (C) 2012-2014 Dan Dennedy <dan@dennedy.org>
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <framework/mlt.h>
#include <QApplication>
#include <QLocale>
#include <QGLWidget>
#include <QMutex>
#include <QWaitCondition>
#include <QtGlobal>
#if defined(Q_OS_UNIX) && !defined(Q_OS_MAC)
#include <X11/Xlib.h>
#endif
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
class GLWidget : public QGLWidget
{
private:
QGLWidget *renderContext;
bool isInitialized;
QMutex mutex;
QWaitCondition condition;
public:
GLWidget()
#ifdef Q_OS_MAC
: QGLWidget()
#else
: QGLWidget(0, 0, Qt::SplashScreen)
#endif
, renderContext(0)
, isInitialized(false)
{
resize(0, 0);
show();
}
~GLWidget()
{
delete renderContext;
}
bool createRenderContext()
{
if (!isInitialized) {
mutex.lock();
condition.wait(&mutex);
mutex.unlock();
}
if (!renderContext) {
renderContext = new QGLWidget(0, this, Qt::SplashScreen);
renderContext->resize(0, 0);
renderContext->makeCurrent();
}
return renderContext->isValid();
}
protected:
void initializeGL()
{
condition.wakeAll();
isInitialized = true;
}
};
#else // Qt 5
#include <QThread>
#include <QOpenGLContext>
#include <QOffscreenSurface>
typedef void* ( *thread_function_t )( void* );
class RenderThread : public QThread
{
public:
RenderThread(thread_function_t function, void *data)
: QThread(0)
, m_function(function)
, m_data(data)
{
m_context = new QOpenGLContext;
m_context->create();
m_context->moveToThread(this);
m_surface = new QOffscreenSurface();
m_surface->create();
}
~RenderThread()
{
#ifndef Q_OS_WIN
m_surface->destroy();
delete m_surface;
#endif
}
protected:
void run()
{
Q_ASSERT(m_context->isValid());
m_context->makeCurrent(m_surface);
m_function(m_data);
m_context->doneCurrent();
delete m_context;
}
private:
thread_function_t m_function;
void* m_data;
QOpenGLContext* m_context;
QOffscreenSurface* m_surface;
};
static void onThreadCreate(mlt_properties owner, mlt_consumer self,
RenderThread** thread, int* priority, thread_function_t function, void* data )
{
Q_UNUSED(owner)
Q_UNUSED(priority)
(*thread) = new RenderThread(function, data);
(*thread)->start();
}
static void onThreadJoin(mlt_properties owner, mlt_consumer self, RenderThread* thread)
{
Q_UNUSED(owner)
Q_UNUSED(self)
if (thread) {
thread->wait();
qApp->processEvents();
delete thread;
}
}
#endif // Qt 5
static void onThreadStarted(mlt_properties owner, mlt_consumer consumer)
{
mlt_service service = MLT_CONSUMER_SERVICE(consumer);
mlt_properties properties = MLT_CONSUMER_PROPERTIES(consumer);
mlt_filter filter = (mlt_filter) mlt_properties_get_data(properties, "glslManager", NULL);
mlt_properties filter_properties = MLT_FILTER_PROPERTIES(filter);
mlt_log_debug(service, "%s\n", __FUNCTION__);
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
GLWidget *widget = (GLWidget*) mlt_properties_get_data(properties, "GLWidget", NULL);
if (widget->createRenderContext()) {
#else
{
#endif
mlt_events_fire(filter_properties, "init glsl", NULL);
if (!mlt_properties_get_int(filter_properties, "glsl_supported")) {
mlt_log_fatal(service,
"OpenGL Shading Language rendering is not supported on this machine.\n" );
mlt_events_fire(properties, "consumer-fatal-error", NULL);
}
}
}
static void onThreadStopped(mlt_properties owner, mlt_consumer consumer)
{
mlt_properties properties = MLT_CONSUMER_PROPERTIES(consumer);
mlt_filter filter = (mlt_filter) mlt_properties_get_data(properties, "glslManager", NULL);
mlt_events_fire(MLT_FILTER_PROPERTIES(filter), "close glsl", NULL);
}
static void onCleanup(mlt_properties owner, mlt_consumer consumer)
{
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
GLWidget* widget = (GLWidget*) mlt_properties_get_data( MLT_CONSUMER_PROPERTIES(consumer), "GLWidget", NULL);
delete widget;
mlt_properties_set_data(MLT_CONSUMER_PROPERTIES(consumer), "GLWidget", NULL, 0, NULL, NULL);
qApp->processEvents();
#endif
}
extern "C" {
mlt_consumer consumer_qglsl_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
{
mlt_consumer consumer = mlt_factory_consumer(profile, "multi", arg);
if (consumer) {
mlt_filter filter = mlt_factory_filter(profile, "glsl.manager", 0);
if (filter) {
mlt_properties properties = MLT_CONSUMER_PROPERTIES(consumer);
mlt_properties_set_data(properties, "glslManager", filter, 0, (mlt_destructor) mlt_filter_close, NULL);
mlt_events_register( properties, "consumer-cleanup", NULL );
mlt_events_listen(properties, consumer, "consumer-thread-started", (mlt_listener) onThreadStarted);
mlt_events_listen(properties, consumer, "consumer-thread-stopped", (mlt_listener) onThreadStopped);
mlt_events_listen(properties, consumer, "consumer-cleanup", (mlt_listener) onCleanup);
#if defined(Q_OS_UNIX) && !defined(Q_OS_MAC)
XInitThreads();
if ( getenv("DISPLAY") == 0 ) {
mlt_log_error(MLT_CONSUMER_SERVICE(consumer), "The qglsl consumer requires a X11 environment.\nPlease either run melt from an X session or use a fake X server like xvfb:\nxvfb-run -a melt (...)\n" );
} else
#endif
if (!qApp) {
int argc = 1;
char* argv[1];
argv[0] = (char*) "MLT qglsl consumer";
new QApplication(argc, argv);
const char *localename = mlt_properties_get_lcnumeric(properties);
QLocale::setDefault(QLocale(localename));
}
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
mlt_properties_set_data(properties, "GLWidget", new GLWidget, 0, NULL, NULL);
#else
mlt_events_listen(properties, consumer, "consumer-thread-create", (mlt_listener) onThreadCreate);
mlt_events_listen(properties, consumer, "consumer-thread-join", (mlt_listener) onThreadJoin);
#endif
qApp->processEvents();
return consumer;
}
mlt_consumer_close(consumer);
}
return NULL;
}
}
<commit_msg>Fix closing the render thread.<commit_after>/*
* consumer_qglsl.cpp
* Copyright (C) 2012-2014 Dan Dennedy <dan@dennedy.org>
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <framework/mlt.h>
#include <QApplication>
#include <QLocale>
#include <QGLWidget>
#include <QMutex>
#include <QWaitCondition>
#include <QtGlobal>
#if defined(Q_OS_UNIX) && !defined(Q_OS_MAC)
#include <X11/Xlib.h>
#endif
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
class GLWidget : public QGLWidget
{
private:
QGLWidget *renderContext;
bool isInitialized;
QMutex mutex;
QWaitCondition condition;
public:
GLWidget()
#ifdef Q_OS_MAC
: QGLWidget()
#else
: QGLWidget(0, 0, Qt::SplashScreen)
#endif
, renderContext(0)
, isInitialized(false)
{
resize(0, 0);
show();
}
~GLWidget()
{
delete renderContext;
}
bool createRenderContext()
{
if (!isInitialized) {
mutex.lock();
condition.wait(&mutex);
mutex.unlock();
}
if (!renderContext) {
renderContext = new QGLWidget(0, this, Qt::SplashScreen);
renderContext->resize(0, 0);
renderContext->makeCurrent();
}
return renderContext->isValid();
}
protected:
void initializeGL()
{
condition.wakeAll();
isInitialized = true;
}
};
#else // Qt 5
#include <QThread>
#include <QOpenGLContext>
#include <QOffscreenSurface>
typedef void* ( *thread_function_t )( void* );
class RenderThread : public QThread
{
public:
RenderThread(thread_function_t function, void *data)
: QThread(0)
, m_function(function)
, m_data(data)
{
m_context = new QOpenGLContext;
m_context->create();
m_context->moveToThread(this);
m_surface = new QOffscreenSurface();
m_surface->create();
}
~RenderThread()
{
m_surface->destroy();
delete m_surface;
}
protected:
void run()
{
Q_ASSERT(m_context->isValid());
m_context->makeCurrent(m_surface);
m_function(m_data);
m_context->doneCurrent();
delete m_context;
}
private:
thread_function_t m_function;
void* m_data;
QOpenGLContext* m_context;
QOffscreenSurface* m_surface;
};
static void onThreadCreate(mlt_properties owner, mlt_consumer self,
RenderThread** thread, int* priority, thread_function_t function, void* data )
{
Q_UNUSED(owner)
Q_UNUSED(priority)
(*thread) = new RenderThread(function, data);
(*thread)->start();
}
static void onThreadJoin(mlt_properties owner, mlt_consumer self, RenderThread* thread)
{
Q_UNUSED(owner)
Q_UNUSED(self)
if (thread) {
thread->quit();
thread->wait();
qApp->processEvents();
delete thread;
}
}
#endif // Qt 5
static void onThreadStarted(mlt_properties owner, mlt_consumer consumer)
{
mlt_service service = MLT_CONSUMER_SERVICE(consumer);
mlt_properties properties = MLT_CONSUMER_PROPERTIES(consumer);
mlt_filter filter = (mlt_filter) mlt_properties_get_data(properties, "glslManager", NULL);
mlt_properties filter_properties = MLT_FILTER_PROPERTIES(filter);
mlt_log_debug(service, "%s\n", __FUNCTION__);
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
GLWidget *widget = (GLWidget*) mlt_properties_get_data(properties, "GLWidget", NULL);
if (widget->createRenderContext()) {
#else
{
#endif
mlt_events_fire(filter_properties, "init glsl", NULL);
if (!mlt_properties_get_int(filter_properties, "glsl_supported")) {
mlt_log_fatal(service,
"OpenGL Shading Language rendering is not supported on this machine.\n" );
mlt_events_fire(properties, "consumer-fatal-error", NULL);
}
}
}
static void onThreadStopped(mlt_properties owner, mlt_consumer consumer)
{
mlt_properties properties = MLT_CONSUMER_PROPERTIES(consumer);
mlt_filter filter = (mlt_filter) mlt_properties_get_data(properties, "glslManager", NULL);
mlt_events_fire(MLT_FILTER_PROPERTIES(filter), "close glsl", NULL);
}
static void onCleanup(mlt_properties owner, mlt_consumer consumer)
{
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
GLWidget* widget = (GLWidget*) mlt_properties_get_data( MLT_CONSUMER_PROPERTIES(consumer), "GLWidget", NULL);
delete widget;
mlt_properties_set_data(MLT_CONSUMER_PROPERTIES(consumer), "GLWidget", NULL, 0, NULL, NULL);
qApp->processEvents();
#endif
}
extern "C" {
mlt_consumer consumer_qglsl_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
{
mlt_consumer consumer = mlt_factory_consumer(profile, "multi", arg);
if (consumer) {
mlt_filter filter = mlt_factory_filter(profile, "glsl.manager", 0);
if (filter) {
mlt_properties properties = MLT_CONSUMER_PROPERTIES(consumer);
mlt_properties_set_data(properties, "glslManager", filter, 0, (mlt_destructor) mlt_filter_close, NULL);
mlt_events_register( properties, "consumer-cleanup", NULL );
mlt_events_listen(properties, consumer, "consumer-thread-started", (mlt_listener) onThreadStarted);
mlt_events_listen(properties, consumer, "consumer-thread-stopped", (mlt_listener) onThreadStopped);
mlt_events_listen(properties, consumer, "consumer-cleanup", (mlt_listener) onCleanup);
#if defined(Q_OS_UNIX) && !defined(Q_OS_MAC)
XInitThreads();
if ( getenv("DISPLAY") == 0 ) {
mlt_log_error(MLT_CONSUMER_SERVICE(consumer), "The qglsl consumer requires a X11 environment.\nPlease either run melt from an X session or use a fake X server like xvfb:\nxvfb-run -a melt (...)\n" );
} else
#endif
if (!qApp) {
int argc = 1;
char* argv[1];
argv[0] = (char*) "MLT qglsl consumer";
new QApplication(argc, argv);
const char *localename = mlt_properties_get_lcnumeric(properties);
QLocale::setDefault(QLocale(localename));
}
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
mlt_properties_set_data(properties, "GLWidget", new GLWidget, 0, NULL, NULL);
#else
mlt_events_listen(properties, consumer, "consumer-thread-create", (mlt_listener) onThreadCreate);
mlt_events_listen(properties, consumer, "consumer-thread-join", (mlt_listener) onThreadJoin);
#endif
qApp->processEvents();
return consumer;
}
mlt_consumer_close(consumer);
}
return NULL;
}
}
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. 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 PCL_KDTREE_KDTREE_IMPL_FLANN_H_
#define PCL_KDTREE_KDTREE_IMPL_FLANN_H_
#include "pcl/kdtree/kdtree_flann.h"
#include <pcl/console/print.h>
#include <flann/flann.hpp>
namespace pcl
{
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
void KdTreeFLANN<PointT>::setInputCloud (const PointCloudConstPtr &cloud, const IndicesConstPtr &indices)
{
cleanup (); // Perform an automatic cleanup of structures
if (!initParameters())
return;
input_ = cloud;
indices_ = indices;
if (input_ == NULL)
return;
m_lock_.lock ();
// Allocate enough data
if (!input_)
{
PCL_ERROR ("[pcl::KdTreeANN::setInputCloud] Invalid input!\n");
return;
}
if (indices != NULL)
convertCloudToArray (*input_, *indices_);
else
convertCloudToArray (*input_);
initData ();
m_lock_.unlock ();
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> int
KdTreeFLANN<PointT>::nearestKSearch (const PointT &point, int k,
std::vector<int> &k_indices,
std::vector<float> &k_distances)
{
if (!point_representation_->isValid (point))
{
//PCL_ERROR_STREAM ("[pcl::KdTreeFLANN::nearestKSearch] Invalid query point given!" << point);
return (0);
}
if (k_indices.size() < (size_t)k) {
k_indices.resize(k);
}
if (k_distances.size() < (size_t)k) {
k_distances.resize(k);
}
std::vector<float> tmp (dim_);
point_representation_->vectorize ((PointT)point, tmp);
flann::Matrix<int> k_indices_mat (&k_indices[0], 1, k);
flann::Matrix<float> k_distances_mat (&k_distances[0], 1, k);
flann_index_->knnSearch (flann::Matrix<float>(&tmp[0], 1, dim_), k_indices_mat, k_distances_mat, k, flann::SearchParams (-1 ,epsilon_));
// Do mapping to original point cloud
if (!identity_mapping_) {
for (size_t i = 0; i < k_indices.size (); ++i)
{
int& neighbor_index = k_indices[i];
neighbor_index = index_mapping_[neighbor_index];
}
}
return (k);
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
int KdTreeFLANN<PointT>::radiusSearch (const PointT &point, double radius, std::vector<int> &k_indices,
std::vector<float> &k_squared_distances, int max_nn) const
{
static flann::Matrix<int> indices_empty;
static flann::Matrix<float> dists_empty;
if (!point_representation_->isValid (point))
{
//PCL_ERROR_STREAM ("[pcl::KdTreeFLANN::radiusSearch] Invalid query point given!" << point);
return 0;
}
std::vector<float> tmp(dim_);
point_representation_->vectorize ((PointT)point, tmp);
radius *= radius; // flann uses squared radius
size_t size;
if (indices_ == NULL) // no indices set, use full size of point cloud:
size = input_->points.size ();
else
size = indices_->size ();
int neighbors_in_radius = 0;
if (k_indices.size () == size && k_squared_distances.size () == size) // preallocated vectors
{
// if using preallocated vectors we ignore max_nn as we are sure to have enought space
// to store all neighbors found in radius
flann::Matrix<int> k_indices_mat (&k_indices[0], 1, k_indices.size());
flann::Matrix<float> k_distances_mat (&k_squared_distances[0], 1, k_squared_distances.size());
neighbors_in_radius = flann_index_->radiusSearch (flann::Matrix<float>(&tmp[0], 1, dim_),
k_indices_mat, k_distances_mat, radius, flann::SearchParams (-1, epsilon_, sorted_));
}
else // need to do search twice, first to find how many neighbors and allocate the vectors
{
neighbors_in_radius = flann_index_->radiusSearch (flann::Matrix<float>(&tmp[0], 1, dim_),
indices_empty, dists_empty, radius, flann::SearchParams (-1, epsilon_, sorted_));
if (max_nn > 0)
{
neighbors_in_radius = std::min(neighbors_in_radius, max_nn);
}
k_indices.resize (neighbors_in_radius);
k_squared_distances.resize (neighbors_in_radius);
if (neighbors_in_radius == 0)
{
return (0);
}
flann::Matrix<int> k_indices_mat (&k_indices[0], 1, k_indices.size());
flann::Matrix<float> k_distances_mat (&k_squared_distances[0], 1, k_squared_distances.size());
flann_index_->radiusSearch (flann::Matrix<float>(&tmp[0], 1, dim_),
k_indices_mat, k_distances_mat, radius, flann::SearchParams (-1, epsilon_, sorted_));
}
// Do mapping to original point cloud
if (!identity_mapping_) {
for (int i = 0; i < neighbors_in_radius; ++i)
{
int& neighbor_index = k_indices[i];
neighbor_index = index_mapping_[neighbor_index];
}
}
return (neighbors_in_radius);
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
void KdTreeFLANN<PointT>::cleanup ()
{
delete flann_index_;
m_lock_.lock ();
// Data array cleanup
free (cloud_);
cloud_ = NULL;
index_mapping_.clear();
if (indices_)
indices_.reset ();
m_lock_.unlock ();
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
bool KdTreeFLANN<PointT>::initParameters ()
{
epsilon_ = 0.0; // default error bound value
dim_ = point_representation_->getNumberOfDimensions (); // Number of dimensions - default is 3 = xyz
// Create the kd_tree representation
return (true);
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
void KdTreeFLANN<PointT>::initData ()
{
flann_index_ = new FLANNIndex(flann::Matrix<float>(cloud_, index_mapping_.size(), dim_),
flann::KDTreeSingleIndexParams(15)); // max 15 points/leaf
flann_index_->buildIndex();
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
void KdTreeFLANN<PointT>::convertCloudToArray (const PointCloud &ros_cloud)
{
// No point in doing anything if the array is empty
if (ros_cloud.points.empty ())
{
cloud_ = NULL;
return;
}
int original_no_of_points = ros_cloud.points.size();
cloud_ = (float*)malloc (original_no_of_points * dim_ * sizeof(float));
float* cloud_ptr = cloud_;
index_mapping_.reserve(original_no_of_points);
identity_mapping_ = true;
for (int cloud_index = 0; cloud_index < original_no_of_points; ++cloud_index)
{
const PointT point = ros_cloud.points[cloud_index];
// Check if the point is invalid
if (!point_representation_->isValid(point)) {
identity_mapping_ = false;
continue;
}
index_mapping_.push_back(cloud_index);
point_representation_->vectorize(point, cloud_ptr);
cloud_ptr += dim_;
}
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
void KdTreeFLANN<PointT>::convertCloudToArray (const PointCloud &ros_cloud, const std::vector<int> &indices)
{
// No point in doing anything if the array is empty
if (ros_cloud.points.empty ())
{
cloud_ = NULL;
return;
}
int original_no_of_points = indices.size();
cloud_ = (float*)malloc (original_no_of_points * dim_ * sizeof (float));
float* cloud_ptr = cloud_;
index_mapping_.reserve(original_no_of_points);
identity_mapping_ = true;
for (int indices_index = 0; indices_index < original_no_of_points; ++indices_index)
{
int cloud_index = indices[indices_index];
const PointT point = ros_cloud.points[cloud_index];
// Check if the point is invalid
if (!point_representation_->isValid(point)) {
identity_mapping_ = false;
continue;
}
index_mapping_.push_back(indices_index); // If the returned index should be for the indices vector
//index_mapping_.push_back(cloud_index); // If the returned index should be for the ros cloud
point_representation_->vectorize(point, cloud_ptr);
cloud_ptr += dim_;
}
}
} // end namespace
#define PCL_INSTANTIATE_KdTreeFLANN(T) template class PCL_EXPORTS pcl::KdTreeFLANN<T>;
#endif //#ifndef _PCL_KDTREE_KDTREE_IMPL_FLANN_H_
<commit_msg>Fixing brackets according to PCL code guidelines<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. 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 PCL_KDTREE_KDTREE_IMPL_FLANN_H_
#define PCL_KDTREE_KDTREE_IMPL_FLANN_H_
#include "pcl/kdtree/kdtree_flann.h"
#include <pcl/console/print.h>
#include <flann/flann.hpp>
namespace pcl
{
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
void KdTreeFLANN<PointT>::setInputCloud (const PointCloudConstPtr &cloud, const IndicesConstPtr &indices)
{
cleanup (); // Perform an automatic cleanup of structures
if (!initParameters())
return;
input_ = cloud;
indices_ = indices;
if (input_ == NULL)
return;
m_lock_.lock ();
// Allocate enough data
if (!input_)
{
PCL_ERROR ("[pcl::KdTreeANN::setInputCloud] Invalid input!\n");
return;
}
if (indices != NULL)
convertCloudToArray (*input_, *indices_);
else
convertCloudToArray (*input_);
initData ();
m_lock_.unlock ();
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> int
KdTreeFLANN<PointT>::nearestKSearch (const PointT &point, int k,
std::vector<int> &k_indices,
std::vector<float> &k_distances)
{
if (!point_representation_->isValid (point))
{
//PCL_ERROR_STREAM ("[pcl::KdTreeFLANN::nearestKSearch] Invalid query point given!" << point);
return (0);
}
if (k_indices.size() < (size_t)k)
{
k_indices.resize(k);
}
if (k_distances.size() < (size_t)k)
{
k_distances.resize(k);
}
std::vector<float> tmp (dim_);
point_representation_->vectorize ((PointT)point, tmp);
flann::Matrix<int> k_indices_mat (&k_indices[0], 1, k);
flann::Matrix<float> k_distances_mat (&k_distances[0], 1, k);
flann_index_->knnSearch (flann::Matrix<float>(&tmp[0], 1, dim_), k_indices_mat, k_distances_mat, k, flann::SearchParams (-1 ,epsilon_));
// Do mapping to original point cloud
if (!identity_mapping_) {
for (size_t i = 0; i < k_indices.size (); ++i)
{
int& neighbor_index = k_indices[i];
neighbor_index = index_mapping_[neighbor_index];
}
}
return (k);
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
int KdTreeFLANN<PointT>::radiusSearch (const PointT &point, double radius, std::vector<int> &k_indices,
std::vector<float> &k_squared_distances, int max_nn) const
{
static flann::Matrix<int> indices_empty;
static flann::Matrix<float> dists_empty;
if (!point_representation_->isValid (point))
{
//PCL_ERROR_STREAM ("[pcl::KdTreeFLANN::radiusSearch] Invalid query point given!" << point);
return 0;
}
std::vector<float> tmp(dim_);
point_representation_->vectorize ((PointT)point, tmp);
radius *= radius; // flann uses squared radius
size_t size;
if (indices_ == NULL) // no indices set, use full size of point cloud:
size = input_->points.size ();
else
size = indices_->size ();
int neighbors_in_radius = 0;
if (k_indices.size () == size && k_squared_distances.size () == size) // preallocated vectors
{
// if using preallocated vectors we ignore max_nn as we are sure to have enought space
// to store all neighbors found in radius
flann::Matrix<int> k_indices_mat (&k_indices[0], 1, k_indices.size());
flann::Matrix<float> k_distances_mat (&k_squared_distances[0], 1, k_squared_distances.size());
neighbors_in_radius = flann_index_->radiusSearch (flann::Matrix<float>(&tmp[0], 1, dim_),
k_indices_mat, k_distances_mat, radius, flann::SearchParams (-1, epsilon_, sorted_));
}
else // need to do search twice, first to find how many neighbors and allocate the vectors
{
neighbors_in_radius = flann_index_->radiusSearch (flann::Matrix<float>(&tmp[0], 1, dim_),
indices_empty, dists_empty, radius, flann::SearchParams (-1, epsilon_, sorted_));
if (max_nn > 0)
{
neighbors_in_radius = std::min(neighbors_in_radius, max_nn);
}
k_indices.resize (neighbors_in_radius);
k_squared_distances.resize (neighbors_in_radius);
if (neighbors_in_radius == 0)
{
return (0);
}
flann::Matrix<int> k_indices_mat (&k_indices[0], 1, k_indices.size());
flann::Matrix<float> k_distances_mat (&k_squared_distances[0], 1, k_squared_distances.size());
flann_index_->radiusSearch (flann::Matrix<float>(&tmp[0], 1, dim_),
k_indices_mat, k_distances_mat, radius, flann::SearchParams (-1, epsilon_, sorted_));
}
// Do mapping to original point cloud
if (!identity_mapping_) {
for (int i = 0; i < neighbors_in_radius; ++i)
{
int& neighbor_index = k_indices[i];
neighbor_index = index_mapping_[neighbor_index];
}
}
return (neighbors_in_radius);
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
void KdTreeFLANN<PointT>::cleanup ()
{
delete flann_index_;
m_lock_.lock ();
// Data array cleanup
free (cloud_);
cloud_ = NULL;
index_mapping_.clear();
if (indices_)
indices_.reset ();
m_lock_.unlock ();
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
bool KdTreeFLANN<PointT>::initParameters ()
{
epsilon_ = 0.0; // default error bound value
dim_ = point_representation_->getNumberOfDimensions (); // Number of dimensions - default is 3 = xyz
// Create the kd_tree representation
return (true);
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
void KdTreeFLANN<PointT>::initData ()
{
flann_index_ = new FLANNIndex(flann::Matrix<float>(cloud_, index_mapping_.size(), dim_),
flann::KDTreeSingleIndexParams(15)); // max 15 points/leaf
flann_index_->buildIndex();
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
void KdTreeFLANN<PointT>::convertCloudToArray (const PointCloud &ros_cloud)
{
// No point in doing anything if the array is empty
if (ros_cloud.points.empty ())
{
cloud_ = NULL;
return;
}
int original_no_of_points = ros_cloud.points.size();
cloud_ = (float*)malloc (original_no_of_points * dim_ * sizeof(float));
float* cloud_ptr = cloud_;
index_mapping_.reserve(original_no_of_points);
identity_mapping_ = true;
for (int cloud_index = 0; cloud_index < original_no_of_points; ++cloud_index)
{
const PointT point = ros_cloud.points[cloud_index];
// Check if the point is invalid
if (!point_representation_->isValid(point)) {
identity_mapping_ = false;
continue;
}
index_mapping_.push_back(cloud_index);
point_representation_->vectorize(point, cloud_ptr);
cloud_ptr += dim_;
}
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
void KdTreeFLANN<PointT>::convertCloudToArray (const PointCloud &ros_cloud, const std::vector<int> &indices)
{
// No point in doing anything if the array is empty
if (ros_cloud.points.empty ())
{
cloud_ = NULL;
return;
}
int original_no_of_points = indices.size();
cloud_ = (float*)malloc (original_no_of_points * dim_ * sizeof (float));
float* cloud_ptr = cloud_;
index_mapping_.reserve(original_no_of_points);
identity_mapping_ = true;
for (int indices_index = 0; indices_index < original_no_of_points; ++indices_index)
{
int cloud_index = indices[indices_index];
const PointT point = ros_cloud.points[cloud_index];
// Check if the point is invalid
if (!point_representation_->isValid(point)) {
identity_mapping_ = false;
continue;
}
index_mapping_.push_back(indices_index); // If the returned index should be for the indices vector
//index_mapping_.push_back(cloud_index); // If the returned index should be for the ros cloud
point_representation_->vectorize(point, cloud_ptr);
cloud_ptr += dim_;
}
}
} // end namespace
#define PCL_INSTANTIATE_KdTreeFLANN(T) template class PCL_EXPORTS pcl::KdTreeFLANN<T>;
#endif //#ifndef _PCL_KDTREE_KDTREE_IMPL_FLANN_H_
<|endoftext|> |
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH *
* *
* 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. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#ifndef SOFA_CORE_COLLISION_GENERICCONTACTCORRECTION_INL
#define SOFA_CORE_COLLISION_GENERICCONTACTCORRECTION_INL
#include "GenericConstraintCorrection.h"
#include <sofa/defaulttype/RigidTypes.h>
#include <sofa/simulation/Node.h>
#include <sofa/simulation/MechanicalVisitor.h>
#include <sofa/core/visual/VisualParams.h>
#include <SofaBaseLinearSolver/GraphScatteredTypes.h>
#include <sstream>
#include <list>
namespace sofa {
namespace component {
namespace constraintset {
GenericConstraintCorrection::GenericConstraintCorrection()
: solverName( initData(&solverName, "solverName", "name of the constraint solver") )
{
odesolver = NULL;
}
GenericConstraintCorrection::~GenericConstraintCorrection() {}
void GenericConstraintCorrection::bwdInit() {
sofa::core::objectmodel::BaseContext* c = this->getContext();
c->get(odesolver, core::objectmodel::BaseContext::SearchRoot);
linearsolvers.clear();
const helper::vector<std::string>& solverNames = solverName.getValue();
for (unsigned int i=0; i<solverNames.size(); ++i) {
sofa::core::behavior::LinearSolver* s = NULL;
c->get(s, solverNames[i]);
if (s) {
if (s->getTemplateName() == "GraphScattered") {
serr << "ERROR GenericConstraintCorrection cannot use the solver " << solverNames[i] << " because it is templated on GraphScatteredType" << sendl;
} else {
linearsolvers.push_back(s);
}
} else serr << "Solver \"" << solverNames[i] << "\" not found." << sendl;
}
if (odesolver == NULL) {
serr << "GenericConstraintCorrection: ERROR no OdeSolver found."<<sendl;
return;
}
if (linearsolvers.size()==0) {
serr << "GenericConstraintCorrection: ERROR no LinearSolver found."<<sendl;
return;
}
sout << "Found " << linearsolvers.size() << "linearsolvers" << sendl;
for (unsigned i = 0; i < linearsolvers.size(); i++) {
sout << linearsolvers[i]->getName() << sendl;
}
}
void GenericConstraintCorrection::cleanup()
{
while(!constraintsolvers.empty())
{
constraintsolvers.back()->removeConstraintCorrection(this);
constraintsolvers.pop_back();
}
sofa::core::behavior::BaseConstraintCorrection::cleanup();
}
void GenericConstraintCorrection::addConstraintSolver(core::behavior::ConstraintSolver *s)
{
constraintsolvers.push_back(s);
}
void GenericConstraintCorrection::removeConstraintSolver(core::behavior::ConstraintSolver *s)
{
constraintsolvers.remove(s);
}
void GenericConstraintCorrection::rebuildSystem(double massFactor, double forceFactor) {
for (unsigned i = 0; i < linearsolvers.size(); i++) {
linearsolvers[i]->rebuildSystem(massFactor, forceFactor);
}
}
void GenericConstraintCorrection::addComplianceInConstraintSpace(const sofa::core::ConstraintParams *cparams, sofa::defaulttype::BaseMatrix* W) {
if (!odesolver) return;
// use the OdeSolver to get the position integration factor
double factor = 1.0;
switch (cparams->constOrder())
{
case core::ConstraintParams::POS_AND_VEL :
case core::ConstraintParams::POS :
factor = odesolver->getPositionIntegrationFactor();
break;
case core::ConstraintParams::ACC :
case core::ConstraintParams::VEL :
factor = odesolver->getVelocityIntegrationFactor();
break;
default :
break;
}
// use the Linear solver to compute J*inv(M)*Jt, where M is the mechanical linear system matrix
for (unsigned i = 0; i < linearsolvers.size(); i++) {
linearsolvers[i]->buildComplianceMatrix(W, factor);
}
}
void GenericConstraintCorrection::computeAndApplyMotionCorrection(const core::ConstraintParams * /*cparams*/, core::MultiVecCoordId /*xId*/, core::MultiVecDerivId /*vId*/, core::MultiVecDerivId /*fId*/, const defaulttype::BaseVector *lambda) {
if (!odesolver) return;
const double positionFactor = odesolver->getPositionIntegrationFactor();
const double velocityFactor = odesolver->getVelocityIntegrationFactor();
for (unsigned i = 0; i < linearsolvers.size(); i++) {
linearsolvers[i]->applyContactForce(lambda,positionFactor,velocityFactor);
}
}
void GenericConstraintCorrection::computeResidual(const sofa::core::ExecParams* params, sofa::defaulttype::BaseVector *lambda) {
for (unsigned i = 0; i < linearsolvers.size(); i++) {
linearsolvers[i]->computeResidual(params,lambda);
}
}
void GenericConstraintCorrection::computeAndApplyPositionCorrection(const sofa::core::ConstraintParams * /*cparams*/, sofa::core::MultiVecCoordId /*xId*/, sofa::core::MultiVecDerivId /*fId*/, const sofa::defaulttype::BaseVector *lambda) {
if (!odesolver) return;
const double positionFactor = odesolver->getPositionIntegrationFactor();
for (unsigned i = 0; i < linearsolvers.size(); i++) {
linearsolvers[i]->applyContactForce(lambda,positionFactor,0.0);
}
}
void GenericConstraintCorrection::computeAndApplyVelocityCorrection(const sofa::core::ConstraintParams * /*cparams*/, sofa::core::MultiVecDerivId /*vId*/, sofa::core::MultiVecDerivId /*fId*/, const sofa::defaulttype::BaseVector *lambda) {
if (!odesolver) return;
const double velocityFactor = odesolver->getVelocityIntegrationFactor();
for (unsigned i = 0; i < linearsolvers.size(); i++) {
linearsolvers[i]->applyContactForce(lambda,0.0,velocityFactor);
}
}
void GenericConstraintCorrection::applyContactForce(const defaulttype::BaseVector *f) {
if (!odesolver) return;
const double positionFactor = odesolver->getPositionIntegrationFactor();
const double velocityFactor = odesolver->getVelocityIntegrationFactor();
for (unsigned i = 0; i < linearsolvers.size(); i++) {
linearsolvers[i]->applyContactForce(f,positionFactor,velocityFactor);
}
}
void GenericConstraintCorrection::getComplianceMatrix(defaulttype::BaseMatrix* Minv) const {
if (!odesolver) return;
// use the OdeSolver to get the position integration factor
double factor = odesolver->getPositionIntegrationFactor();
// use the Linear solver to compute J*inv(M)*Jt, where M is the mechanical linear system matrix
for (unsigned i = 0; i < linearsolvers.size(); i++) {
linearsolvers[i]->buildComplianceMatrix(Minv, factor);
}
}
void GenericConstraintCorrection::applyPredictiveConstraintForce(const core::ConstraintParams * /*cparams*/, core::MultiVecDerivId /*f*/, const defaulttype::BaseVector * /*lambda*/) {
// printf("GenericConstraintCorrection::applyPredictiveConstraintForce not implemented\n");
// if (mstate)
// {
// Data< VecDeriv > *f_d = f[mstate].write();
// if (f_d)
// {
// applyPredictiveConstraintForce(cparams, *f_d, lambda);
// }
// }
}
void GenericConstraintCorrection::resetContactForce() {
// printf("GenericConstraintCorrection::resetContactForce not implemented\n");
// Data<VecDeriv>& forceData = *this->mstate->write(core::VecDerivId::force());
// VecDeriv& force = *forceData.beginEdit();
// for( unsigned i=0; i<force.size(); ++i )
// force[i] = Deriv();
// forceData.endEdit();
}
} // namespace constraintset
} // namespace component
} // namespace sofa
#endif
<commit_msg>FIX : GenericConstraintCorrection's ODESolver is searched locally<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH *
* *
* 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. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#ifndef SOFA_CORE_COLLISION_GENERICCONTACTCORRECTION_INL
#define SOFA_CORE_COLLISION_GENERICCONTACTCORRECTION_INL
#include "GenericConstraintCorrection.h"
#include <sofa/defaulttype/RigidTypes.h>
#include <sofa/simulation/Node.h>
#include <sofa/simulation/MechanicalVisitor.h>
#include <sofa/core/visual/VisualParams.h>
#include <SofaBaseLinearSolver/GraphScatteredTypes.h>
#include <sstream>
#include <list>
namespace sofa {
namespace component {
namespace constraintset {
GenericConstraintCorrection::GenericConstraintCorrection()
: solverName( initData(&solverName, "solverName", "name of the constraint solver") )
{
odesolver = NULL;
}
GenericConstraintCorrection::~GenericConstraintCorrection() {}
void GenericConstraintCorrection::bwdInit() {
sofa::core::objectmodel::BaseContext* c = this->getContext();
c->get(odesolver, core::objectmodel::BaseContext::Local);
linearsolvers.clear();
const helper::vector<std::string>& solverNames = solverName.getValue();
for (unsigned int i=0; i<solverNames.size(); ++i) {
sofa::core::behavior::LinearSolver* s = NULL;
c->get(s, solverNames[i]);
if (s) {
if (s->getTemplateName() == "GraphScattered") {
serr << "ERROR GenericConstraintCorrection cannot use the solver " << solverNames[i] << " because it is templated on GraphScatteredType" << sendl;
} else {
linearsolvers.push_back(s);
}
} else serr << "Solver \"" << solverNames[i] << "\" not found." << sendl;
}
if (odesolver == NULL) {
serr << "GenericConstraintCorrection: ERROR no OdeSolver found."<<sendl;
return;
}
if (linearsolvers.size()==0) {
serr << "GenericConstraintCorrection: ERROR no LinearSolver found."<<sendl;
return;
}
sout << "Found " << linearsolvers.size() << "linearsolvers" << sendl;
for (unsigned i = 0; i < linearsolvers.size(); i++) {
sout << linearsolvers[i]->getName() << sendl;
}
}
void GenericConstraintCorrection::cleanup()
{
while(!constraintsolvers.empty())
{
constraintsolvers.back()->removeConstraintCorrection(this);
constraintsolvers.pop_back();
}
sofa::core::behavior::BaseConstraintCorrection::cleanup();
}
void GenericConstraintCorrection::addConstraintSolver(core::behavior::ConstraintSolver *s)
{
constraintsolvers.push_back(s);
}
void GenericConstraintCorrection::removeConstraintSolver(core::behavior::ConstraintSolver *s)
{
constraintsolvers.remove(s);
}
void GenericConstraintCorrection::rebuildSystem(double massFactor, double forceFactor) {
for (unsigned i = 0; i < linearsolvers.size(); i++) {
linearsolvers[i]->rebuildSystem(massFactor, forceFactor);
}
}
void GenericConstraintCorrection::addComplianceInConstraintSpace(const sofa::core::ConstraintParams *cparams, sofa::defaulttype::BaseMatrix* W) {
if (!odesolver) return;
// use the OdeSolver to get the position integration factor
double factor = 1.0;
switch (cparams->constOrder())
{
case core::ConstraintParams::POS_AND_VEL :
case core::ConstraintParams::POS :
factor = odesolver->getPositionIntegrationFactor();
break;
case core::ConstraintParams::ACC :
case core::ConstraintParams::VEL :
factor = odesolver->getVelocityIntegrationFactor();
break;
default :
break;
}
// use the Linear solver to compute J*inv(M)*Jt, where M is the mechanical linear system matrix
for (unsigned i = 0; i < linearsolvers.size(); i++) {
linearsolvers[i]->buildComplianceMatrix(W, factor);
}
}
void GenericConstraintCorrection::computeAndApplyMotionCorrection(const core::ConstraintParams * /*cparams*/, core::MultiVecCoordId /*xId*/, core::MultiVecDerivId /*vId*/, core::MultiVecDerivId /*fId*/, const defaulttype::BaseVector *lambda) {
if (!odesolver) return;
const double positionFactor = odesolver->getPositionIntegrationFactor();
const double velocityFactor = odesolver->getVelocityIntegrationFactor();
for (unsigned i = 0; i < linearsolvers.size(); i++) {
linearsolvers[i]->applyContactForce(lambda,positionFactor,velocityFactor);
}
}
void GenericConstraintCorrection::computeResidual(const sofa::core::ExecParams* params, sofa::defaulttype::BaseVector *lambda) {
for (unsigned i = 0; i < linearsolvers.size(); i++) {
linearsolvers[i]->computeResidual(params,lambda);
}
}
void GenericConstraintCorrection::computeAndApplyPositionCorrection(const sofa::core::ConstraintParams * /*cparams*/, sofa::core::MultiVecCoordId /*xId*/, sofa::core::MultiVecDerivId /*fId*/, const sofa::defaulttype::BaseVector *lambda) {
if (!odesolver) return;
const double positionFactor = odesolver->getPositionIntegrationFactor();
for (unsigned i = 0; i < linearsolvers.size(); i++) {
linearsolvers[i]->applyContactForce(lambda,positionFactor,0.0);
}
}
void GenericConstraintCorrection::computeAndApplyVelocityCorrection(const sofa::core::ConstraintParams * /*cparams*/, sofa::core::MultiVecDerivId /*vId*/, sofa::core::MultiVecDerivId /*fId*/, const sofa::defaulttype::BaseVector *lambda) {
if (!odesolver) return;
const double velocityFactor = odesolver->getVelocityIntegrationFactor();
for (unsigned i = 0; i < linearsolvers.size(); i++) {
linearsolvers[i]->applyContactForce(lambda,0.0,velocityFactor);
}
}
void GenericConstraintCorrection::applyContactForce(const defaulttype::BaseVector *f) {
if (!odesolver) return;
const double positionFactor = odesolver->getPositionIntegrationFactor();
const double velocityFactor = odesolver->getVelocityIntegrationFactor();
for (unsigned i = 0; i < linearsolvers.size(); i++) {
linearsolvers[i]->applyContactForce(f,positionFactor,velocityFactor);
}
}
void GenericConstraintCorrection::getComplianceMatrix(defaulttype::BaseMatrix* Minv) const {
if (!odesolver) return;
// use the OdeSolver to get the position integration factor
double factor = odesolver->getPositionIntegrationFactor();
// use the Linear solver to compute J*inv(M)*Jt, where M is the mechanical linear system matrix
for (unsigned i = 0; i < linearsolvers.size(); i++) {
linearsolvers[i]->buildComplianceMatrix(Minv, factor);
}
}
void GenericConstraintCorrection::applyPredictiveConstraintForce(const core::ConstraintParams * /*cparams*/, core::MultiVecDerivId /*f*/, const defaulttype::BaseVector * /*lambda*/) {
// printf("GenericConstraintCorrection::applyPredictiveConstraintForce not implemented\n");
// if (mstate)
// {
// Data< VecDeriv > *f_d = f[mstate].write();
// if (f_d)
// {
// applyPredictiveConstraintForce(cparams, *f_d, lambda);
// }
// }
}
void GenericConstraintCorrection::resetContactForce() {
// printf("GenericConstraintCorrection::resetContactForce not implemented\n");
// Data<VecDeriv>& forceData = *this->mstate->write(core::VecDerivId::force());
// VecDeriv& force = *forceData.beginEdit();
// for( unsigned i=0; i<force.size(); ++i )
// force[i] = Deriv();
// forceData.endEdit();
}
} // namespace constraintset
} // namespace component
} // namespace sofa
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2012
* Alessio Sclocco <a.sclocco@vu.nl>
*
* 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/>.
*
*/
#define __CL_ENABLE_EXCEPTIONS
#include <CL/cl.hpp>
#include <string>
#include <vector>
#include <cmath>
#include <cstring>
using std::string;
using std::vector;
using std::make_pair;
using std::pow;
using std::ceil;
#include <Exceptions.hpp>
#include <CLData.hpp>
#include <utils.hpp>
#include <Kernel.hpp>
#include <Observation.hpp>
using isa::Exceptions::OpenCLError;
using isa::OpenCL::CLData;
using isa::utils::giga;
using isa::utils::toStringValue;
using isa::utils::toString;
using isa::utils::replace;
using isa::OpenCL::Kernel;
using AstroData::Observation;
#ifndef FOLDING_HPP
#define FOLDING_HPP
namespace PulsarSearch {
// OpenCL folding algorithm
template< typename T > class Folding : public Kernel< T > {
public:
Folding(string name, string dataType);
void generateCode() throw (OpenCLError);
void operator()(CLData< T > * input, CLData< T > * output, CLData< unsigned int > * counters) throw (OpenCLError);
inline void setNrDMsPerBlock(unsigned int DMs);
inline void setNrPeriodsPerBlock(unsigned int periods);
inline void setNrBinsPerBlock(unsigned int bins);
inline void setNrDMsPerThread(unsigned int DMs);
inline void setNrPeriodsPerThread(unsigned int periods);
inline void setNrBinsPerThread(unsigned int bins);
inline void setObservation(Observation< T > * obs);
private:
unsigned int nrDMsPerBlock;
unsigned int nrPeriodsPerBlock;
unsigned int nrBinsPerBlock;
unsigned int nrDMsPerThread;
unsigned int nrPeriodsPerThread;
unsigned int nrBinsPerThread;
cl::NDRange globalSize;
cl::NDRange localSize;
Observation< T > * observation;
};
// Implementation
template< typename T > Folding< T >::Folding(string name, string dataType) : Kernel< T >(name, dataType), nrDMsPerBlock(0), nrPeriodsPerBlock(0), nrBinsPerBlock(0), nrDMsPerThread(0), nrPeriodsPerThread(0), nrBinsPerThread(0), globalSize(cl::NDRange(1, 1, 1)), localSize(cl::NDRange(1, 1, 1)), observation(0) {}
template< typename T > void Folding< T >::generateCode() throw (OpenCLError) {
// Begin kernel's template
string nrSamplesPerSecond_s = toStringValue< unsigned int >(observation->getNrSamplesPerSecond());
string nrPaddedDMs_s = toStringValue< unsigned int >(observation->getNrPaddedDMs());
string nrPeriods_s = toStringValue< unsigned int >(observation->getNrPeriods());
string nrBins_s = toStringValue< unsigned int >(observation->getNrBins());
string nrDMsPerBlock_s = toStringValue< unsigned int >(nrDMsPerBlock);
string nrDMsPerThread_s = toStringValue< unsigned int >(nrDMsPerThread);
string nrPeriodsPerBlock_s = toStringValue< unsigned int >(nrPeriodsPerBlock);
string nrPeriodsPerThread_s = toStringValue< unsigned int >(nrPeriodsPerThread);
string nrBinsPerBlock_s = toStringValue< unsigned int >(nrBinsPerBlock);
string nrBinsPerThread_s = toStringValue< unsigned int >(nrBinsPerThread);
delete this->code;
this->code = new string();
*(this->code) = "__kernel void " + this->name + "(__global const " + this->dataType + " * const restrict samples, __global " + this->dataType + " * const restrict bins, __global unsigned int * const restrict counters) {\n"
"<%DEFS%>"
"<%LOADS%>"
"\n"
"<%COMPUTE%>"
"\n"
"<%STORE%>"
"}\n";
string defsDMTemplate = "const unsigned int DM<%DM_NUM%> = (get_group_id(0) * " + nrDMsPerBlock_s + " * " + nrDMsPerThread_s + ") + get_local_id(0) + (<%DM_NUM%> * " + nrDMsPerBlock_s + ");\n";
string defsPeriodTemplate = "const unsigned int period<%PERIOD_NUM%> = (get_group_id(1) * " + nrPeriodsPerBlock_s + " * " + nrDMsPerThread_s + ") + get_local_id(1) + (<%PERIOD_NUM%> * " + nrPeriodsPerBlock_s + ");\n"
"const unsigned int period<%PERIOD_NUM%>Value = (period<%PERIOD_NUM%> + 1) * " + nrBins_s + ";\n";
string defsTemplate = "const unsigned int bin<%BIN_NUM%> = (get_group_id(2) * " + nrBinsPerBlock_s + " * " + nrBinsPerThread_s + ") + get_local_id(2) + (<%BIN_NUM%> * " + nrBinsPerBlock_s + ");\n"
"unsigned int foldedCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> = 0;\n"
+ this->dataType + " foldedSampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> = 0;\n"
"const unsigned int pCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> = 0;\n";
string loadsTemplate = "pCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> = counters[(bin<%BIN_NUM%> * " + nrPeriods_s + " * " + nrPaddedDMs_s + ") + (period<%PERIOD_NUM%> * " + nrPaddedDMs_s + ") + DM<%DM_NUM%>];\n";
string computeTemplate = "unsigned int sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> = (bin<%BIN_NUM%> * period<%PERIOD_NUM%>) + bin<%BIN_NUM%> + ((pCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> / (period<%PERIOD_NUM%> + 1)) * period<%PERIOD_NUM%>Value) + (pCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> % (period<%PERIOD_NUM%> + 1));\n"
"if ( (sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> % "+ nrSamplesPerSecond_s + ") == 0 ) {\n"
"sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> = 0;\n"
"} else {\n"
"sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> = (sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> % "+ nrSamplesPerSecond_s + ") - (sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> / "+ nrSamplesPerSecond_s + ");\n"
"}\n"
"while ( sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> < " + nrSamplesPerSecond_s + " ) {\n"
"foldedSampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> += samples[(sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> * " + nrPaddedDMs_s + ") + DM<%DM_NUM%>];\n"
"foldedCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%>++;\n"
"if ( ((foldedCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> + pCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%>) % (period<%PERIOD_NUM%> + 1)) == 0 ) {\n"
"sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> += period<%PERIOD_NUM%>Value;\n"
"} else {\n"
"sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%>++;\n"
"}\n"
"}\n";
string storeTemplate = "if ( foldedCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> > 0 ) {\n"
"const unsigned int outputItem = (bin<%BIN_NUM%> * " + nrPeriods_s + " * " + nrPaddedDMs_s + ") + (period<%PERIOD_NUM%> * " + nrPaddedDMs_s + ") + DM<%DM_NUM%>;\n"
"const "+ this->dataType + " pValue = bins[outputItem];\n"
+ this->dataType + " addedFraction = 0;"
"addedFraction = convert_float(foldedCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%>) / (foldedCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> + pCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%>);\n"
"foldedSampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> /= foldedCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%>;\n"
"counters[outputItem] = pCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> + foldedCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%>;\n"
"bins[outputItem] = (addedFraction * foldedSampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%>) + ((1.0f - addedFraction) * pValue);\n"
"}\n";
// End kernel's template
string * defs = new string();
string * loads = new string();
string * computes = new string();
string * stores = new string();
for ( unsigned int DM = 0; DM < nrDMsPerThread; DM++ ) {
string * DM_s = toString< unsigned int >(DM);
string * temp = 0;
temp = replace(&defsDMTemplate, "<%DM_NUM%>", *DM_s);
defs->append(*temp);
delete temp;
for ( unsigned int period = 0; period < nrPeriodsPerThread; period++ ) {
string * period_s = toString< unsigned int >(period);
string * temp = 0;
temp = replace(&defsPeriodTemplate, "<%PERIOD_NUM%>", *period_s);
defs->append(*temp);
delete temp;
for ( unsigned int bin = 0; bin < nrBinsPerThread; bin++ ) {
string * bin_s = toString< unsigned int >(bin);
string * temp = 0;
temp = replace(&defsTemplate, "<%BIN_NUM%>", *bin_s);
temp = replace(temp, "<%PERIOD_NUM%>", *period_s, true);
temp = replace(temp, "<%DM_NUM%>", *DM_s, true);
defs->append(*temp);
delete temp;
temp = replace(&loadsTemplate, "<%BIN_NUM%>", *bin_s);
temp = replace(temp, "<%PERIOD_NUM%>", *period_s, true);
temp = replace(temp, "<%DM_NUM%>", *DM_s, true);
loads->append(*temp);
delete temp;
temp = replace(&computeTemplate, "<%BIN_NUM%>", *bin_s);
temp = replace(temp, "<%PERIOD_NUM%>", *period_s, true);
temp = replace(temp, "<%DM_NUM%>", *DM_s, true);
computes->append(*temp);
delete temp;
temp = replace(&storeTemplate, "<%BIN_NUM%>", *bin_s);
temp = replace(temp, "<%PERIOD_NUM%>", *period_s, true);
temp = replace(temp, "<%DM_NUM%>", *DM_s, true);
stores->append(*temp);
delete temp;
delete bin_s;
}
delete period_s;
}
delete DM_s;
}
this->code = replace(this->code, "<%DEFS%>", *defs, true);
this->code = replace(this->code, "<%LOADS%>", *loads, true);
this->code = replace(this->code, "<%COMPUTE%>", *computes, true);
this->code = replace(this->code, "<%STORE%>", *stores, true);
delete defs;
delete computes;
delete stores;
globalSize = cl::NDRange(observation->getNrDMs() / nrDMsPerThread, observation->getNrPeriods() / nrPeriodsPerThread, observation->getNrBins() / nrBinsPerThread);
localSize = cl::NDRange(nrDMsPerBlock, nrPeriodsPerBlock, nrBinsPerBlock);
this->gflop = giga(static_cast< long long unsigned int >(observation->getNrDMs()) * observation->getNrPeriods() * observation->getNrSamplesPerSecond());
this->compile();
}
template< typename T > void Folding< T >::operator()(CLData< T > * input, CLData< T > * output, CLData< unsigned int > * counters) throw (OpenCLError) {
this->setArgument(0, *(input->getDeviceData()));
this->setArgument(1, *(output->getDeviceData()));
this->setArgument(2, *(counters->getDeviceData()));
this->run(globalSize, localSize);
}
template< typename T > inline void Folding< T >::setNrDMsPerBlock(unsigned int DMs) {
nrDMsPerBlock = DMs;
}
template< typename T > inline void Folding< T >::setNrPeriodsPerBlock(unsigned int periods) {
nrPeriodsPerBlock = periods;
}
template< typename T > inline void Folding< T >::setNrBinsPerBlock(unsigned int bins) {
nrBinsPerBlock = bins;
}
template< typename T > inline void Folding< T >::setNrDMsPerThread(unsigned int DMs) {
nrDMsPerThread = DMs;
}
template< typename T > inline void Folding< T >::setNrPeriodsPerThread(unsigned int periods) {
nrPeriodsPerThread = periods;
}
template< typename T > inline void Folding< T >::setNrBinsPerThread(unsigned int bins) {
nrBinsPerThread = bins;
}
template< typename T > inline void Folding< T >::setObservation(Observation< T > * obs) {
observation = obs;
}
} // PulsarSearch
#endif // FOLDING_HPP
<commit_msg>Forgot to delete a const statement.<commit_after>/*
* Copyright (C) 2012
* Alessio Sclocco <a.sclocco@vu.nl>
*
* 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/>.
*
*/
#define __CL_ENABLE_EXCEPTIONS
#include <CL/cl.hpp>
#include <string>
#include <vector>
#include <cmath>
#include <cstring>
using std::string;
using std::vector;
using std::make_pair;
using std::pow;
using std::ceil;
#include <Exceptions.hpp>
#include <CLData.hpp>
#include <utils.hpp>
#include <Kernel.hpp>
#include <Observation.hpp>
using isa::Exceptions::OpenCLError;
using isa::OpenCL::CLData;
using isa::utils::giga;
using isa::utils::toStringValue;
using isa::utils::toString;
using isa::utils::replace;
using isa::OpenCL::Kernel;
using AstroData::Observation;
#ifndef FOLDING_HPP
#define FOLDING_HPP
namespace PulsarSearch {
// OpenCL folding algorithm
template< typename T > class Folding : public Kernel< T > {
public:
Folding(string name, string dataType);
void generateCode() throw (OpenCLError);
void operator()(CLData< T > * input, CLData< T > * output, CLData< unsigned int > * counters) throw (OpenCLError);
inline void setNrDMsPerBlock(unsigned int DMs);
inline void setNrPeriodsPerBlock(unsigned int periods);
inline void setNrBinsPerBlock(unsigned int bins);
inline void setNrDMsPerThread(unsigned int DMs);
inline void setNrPeriodsPerThread(unsigned int periods);
inline void setNrBinsPerThread(unsigned int bins);
inline void setObservation(Observation< T > * obs);
private:
unsigned int nrDMsPerBlock;
unsigned int nrPeriodsPerBlock;
unsigned int nrBinsPerBlock;
unsigned int nrDMsPerThread;
unsigned int nrPeriodsPerThread;
unsigned int nrBinsPerThread;
cl::NDRange globalSize;
cl::NDRange localSize;
Observation< T > * observation;
};
// Implementation
template< typename T > Folding< T >::Folding(string name, string dataType) : Kernel< T >(name, dataType), nrDMsPerBlock(0), nrPeriodsPerBlock(0), nrBinsPerBlock(0), nrDMsPerThread(0), nrPeriodsPerThread(0), nrBinsPerThread(0), globalSize(cl::NDRange(1, 1, 1)), localSize(cl::NDRange(1, 1, 1)), observation(0) {}
template< typename T > void Folding< T >::generateCode() throw (OpenCLError) {
// Begin kernel's template
string nrSamplesPerSecond_s = toStringValue< unsigned int >(observation->getNrSamplesPerSecond());
string nrPaddedDMs_s = toStringValue< unsigned int >(observation->getNrPaddedDMs());
string nrPeriods_s = toStringValue< unsigned int >(observation->getNrPeriods());
string nrBins_s = toStringValue< unsigned int >(observation->getNrBins());
string nrDMsPerBlock_s = toStringValue< unsigned int >(nrDMsPerBlock);
string nrDMsPerThread_s = toStringValue< unsigned int >(nrDMsPerThread);
string nrPeriodsPerBlock_s = toStringValue< unsigned int >(nrPeriodsPerBlock);
string nrPeriodsPerThread_s = toStringValue< unsigned int >(nrPeriodsPerThread);
string nrBinsPerBlock_s = toStringValue< unsigned int >(nrBinsPerBlock);
string nrBinsPerThread_s = toStringValue< unsigned int >(nrBinsPerThread);
delete this->code;
this->code = new string();
*(this->code) = "__kernel void " + this->name + "(__global const " + this->dataType + " * const restrict samples, __global " + this->dataType + " * const restrict bins, __global unsigned int * const restrict counters) {\n"
"<%DEFS%>"
"<%LOADS%>"
"\n"
"<%COMPUTE%>"
"\n"
"<%STORE%>"
"}\n";
string defsDMTemplate = "const unsigned int DM<%DM_NUM%> = (get_group_id(0) * " + nrDMsPerBlock_s + " * " + nrDMsPerThread_s + ") + get_local_id(0) + (<%DM_NUM%> * " + nrDMsPerBlock_s + ");\n";
string defsPeriodTemplate = "const unsigned int period<%PERIOD_NUM%> = (get_group_id(1) * " + nrPeriodsPerBlock_s + " * " + nrDMsPerThread_s + ") + get_local_id(1) + (<%PERIOD_NUM%> * " + nrPeriodsPerBlock_s + ");\n"
"const unsigned int period<%PERIOD_NUM%>Value = (period<%PERIOD_NUM%> + 1) * " + nrBins_s + ";\n";
string defsTemplate = "const unsigned int bin<%BIN_NUM%> = (get_group_id(2) * " + nrBinsPerBlock_s + " * " + nrBinsPerThread_s + ") + get_local_id(2) + (<%BIN_NUM%> * " + nrBinsPerBlock_s + ");\n"
"unsigned int foldedCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> = 0;\n"
+ this->dataType + " foldedSampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> = 0;\n"
"unsigned int pCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> = 0;\n";
string loadsTemplate = "pCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> = counters[(bin<%BIN_NUM%> * " + nrPeriods_s + " * " + nrPaddedDMs_s + ") + (period<%PERIOD_NUM%> * " + nrPaddedDMs_s + ") + DM<%DM_NUM%>];\n";
string computeTemplate = "unsigned int sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> = (bin<%BIN_NUM%> * period<%PERIOD_NUM%>) + bin<%BIN_NUM%> + ((pCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> / (period<%PERIOD_NUM%> + 1)) * period<%PERIOD_NUM%>Value) + (pCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> % (period<%PERIOD_NUM%> + 1));\n"
"if ( (sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> % "+ nrSamplesPerSecond_s + ") == 0 ) {\n"
"sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> = 0;\n"
"} else {\n"
"sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> = (sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> % "+ nrSamplesPerSecond_s + ") - (sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> / "+ nrSamplesPerSecond_s + ");\n"
"}\n"
"while ( sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> < " + nrSamplesPerSecond_s + " ) {\n"
"foldedSampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> += samples[(sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> * " + nrPaddedDMs_s + ") + DM<%DM_NUM%>];\n"
"foldedCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%>++;\n"
"if ( ((foldedCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> + pCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%>) % (period<%PERIOD_NUM%> + 1)) == 0 ) {\n"
"sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> += period<%PERIOD_NUM%>Value;\n"
"} else {\n"
"sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%>++;\n"
"}\n"
"}\n";
string storeTemplate = "if ( foldedCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> > 0 ) {\n"
"const unsigned int outputItem = (bin<%BIN_NUM%> * " + nrPeriods_s + " * " + nrPaddedDMs_s + ") + (period<%PERIOD_NUM%> * " + nrPaddedDMs_s + ") + DM<%DM_NUM%>;\n"
"const "+ this->dataType + " pValue = bins[outputItem];\n"
+ this->dataType + " addedFraction = 0;"
"addedFraction = convert_float(foldedCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%>) / (foldedCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> + pCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%>);\n"
"foldedSampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> /= foldedCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%>;\n"
"counters[outputItem] = pCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> + foldedCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%>;\n"
"bins[outputItem] = (addedFraction * foldedSampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%>) + ((1.0f - addedFraction) * pValue);\n"
"}\n";
// End kernel's template
string * defs = new string();
string * loads = new string();
string * computes = new string();
string * stores = new string();
for ( unsigned int DM = 0; DM < nrDMsPerThread; DM++ ) {
string * DM_s = toString< unsigned int >(DM);
string * temp = 0;
temp = replace(&defsDMTemplate, "<%DM_NUM%>", *DM_s);
defs->append(*temp);
delete temp;
for ( unsigned int period = 0; period < nrPeriodsPerThread; period++ ) {
string * period_s = toString< unsigned int >(period);
string * temp = 0;
temp = replace(&defsPeriodTemplate, "<%PERIOD_NUM%>", *period_s);
defs->append(*temp);
delete temp;
for ( unsigned int bin = 0; bin < nrBinsPerThread; bin++ ) {
string * bin_s = toString< unsigned int >(bin);
string * temp = 0;
temp = replace(&defsTemplate, "<%BIN_NUM%>", *bin_s);
temp = replace(temp, "<%PERIOD_NUM%>", *period_s, true);
temp = replace(temp, "<%DM_NUM%>", *DM_s, true);
defs->append(*temp);
delete temp;
temp = replace(&loadsTemplate, "<%BIN_NUM%>", *bin_s);
temp = replace(temp, "<%PERIOD_NUM%>", *period_s, true);
temp = replace(temp, "<%DM_NUM%>", *DM_s, true);
loads->append(*temp);
delete temp;
temp = replace(&computeTemplate, "<%BIN_NUM%>", *bin_s);
temp = replace(temp, "<%PERIOD_NUM%>", *period_s, true);
temp = replace(temp, "<%DM_NUM%>", *DM_s, true);
computes->append(*temp);
delete temp;
temp = replace(&storeTemplate, "<%BIN_NUM%>", *bin_s);
temp = replace(temp, "<%PERIOD_NUM%>", *period_s, true);
temp = replace(temp, "<%DM_NUM%>", *DM_s, true);
stores->append(*temp);
delete temp;
delete bin_s;
}
delete period_s;
}
delete DM_s;
}
this->code = replace(this->code, "<%DEFS%>", *defs, true);
this->code = replace(this->code, "<%LOADS%>", *loads, true);
this->code = replace(this->code, "<%COMPUTE%>", *computes, true);
this->code = replace(this->code, "<%STORE%>", *stores, true);
delete defs;
delete computes;
delete stores;
globalSize = cl::NDRange(observation->getNrDMs() / nrDMsPerThread, observation->getNrPeriods() / nrPeriodsPerThread, observation->getNrBins() / nrBinsPerThread);
localSize = cl::NDRange(nrDMsPerBlock, nrPeriodsPerBlock, nrBinsPerBlock);
this->gflop = giga(static_cast< long long unsigned int >(observation->getNrDMs()) * observation->getNrPeriods() * observation->getNrSamplesPerSecond());
this->compile();
}
template< typename T > void Folding< T >::operator()(CLData< T > * input, CLData< T > * output, CLData< unsigned int > * counters) throw (OpenCLError) {
this->setArgument(0, *(input->getDeviceData()));
this->setArgument(1, *(output->getDeviceData()));
this->setArgument(2, *(counters->getDeviceData()));
this->run(globalSize, localSize);
}
template< typename T > inline void Folding< T >::setNrDMsPerBlock(unsigned int DMs) {
nrDMsPerBlock = DMs;
}
template< typename T > inline void Folding< T >::setNrPeriodsPerBlock(unsigned int periods) {
nrPeriodsPerBlock = periods;
}
template< typename T > inline void Folding< T >::setNrBinsPerBlock(unsigned int bins) {
nrBinsPerBlock = bins;
}
template< typename T > inline void Folding< T >::setNrDMsPerThread(unsigned int DMs) {
nrDMsPerThread = DMs;
}
template< typename T > inline void Folding< T >::setNrPeriodsPerThread(unsigned int periods) {
nrPeriodsPerThread = periods;
}
template< typename T > inline void Folding< T >::setNrBinsPerThread(unsigned int bins) {
nrBinsPerThread = bins;
}
template< typename T > inline void Folding< T >::setObservation(Observation< T > * obs) {
observation = obs;
}
} // PulsarSearch
#endif // FOLDING_HPP
<|endoftext|> |
<commit_before>#include "depthviewwindow.h"
#include "ui_depthviewwindow.h"
#include "exportdialog.h"
#include "settingswindow.h"
#include "version.h"
#include "renderers.h"
#include <QKeyEvent>
#include <QFileDialog>
#include <QDebug>
#include <QMessageBox>
#include <QTime>
#include <QMimeData>
#include <QUrl>
DepthViewWindow::DepthViewWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::DepthViewWindow)
#ifdef DEPTHVIEW_PORTABLE
, settings(QApplication::applicationDirPath() + "/DepthView.conf", QSettings::IniFormat)
#endif
{
ui->setupUi(this);
ui->imageWidget->addActions(ui->menubar->actions());
ui->imageWidget->setContextMenuPolicy(Qt::ActionsContextMenu);
connect(ui->imageWidget, SIGNAL(doubleClicked()), ui->actionFullscreen, SLOT(toggle()));
connect(ui->actionZoomIn, SIGNAL(triggered()), ui->imageWidget, SLOT(zoomIn()));
connect(ui->actionZoomOut, SIGNAL(triggered()), ui->imageWidget, SLOT(zoomOut()));
connect(ui->actionShowMenuBar, SIGNAL(toggled(bool)), ui->menubar, SLOT(setVisible(bool)));
connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(showLoadImageDialog()));
connect(ui->actionExit, SIGNAL(triggered()), this, SLOT(close()));
this->loadSettings();
}
DepthViewWindow::~DepthViewWindow(){
settings.setValue("lastrun", QDate::currentDate().toString());
delete ui;
}
bool DepthViewWindow::loadImage(const QString &filename){
QFileInfo info(filename);
if(info.exists() && (info.suffix().toLower() == "jps" || info.suffix().toLower() == "pns")){
QDir::setCurrent(info.path());
currentFile = info.fileName();
if(ui->imageWidget->loadStereoImage(currentFile)){
this->setWindowTitle(currentFile);
ui->imageWidget->repaint();
return true;
}else{
currentFile.clear();
this->setWindowTitle("DepthView");
}
}
return false;
}
bool DepthViewWindow::showLoadImageDialog(){
QString filename = QFileDialog::getOpenFileName(this, tr("Open Image"), "", tr("Stereo Image Files (*.jps *.pns)"));
return loadImage(filename);
}
void DepthViewWindow::on_actionAnglaphFullColor_triggered(){
ui->imageWidget->setRenderMode(ImageWidget::AnglaphFull);
}
void DepthViewWindow::on_actionAnglaphHalfColor_triggered(){
ui->imageWidget->setRenderMode(ImageWidget::AnglaphHalf);
}
void DepthViewWindow::on_actionAnglaphGreyscale_triggered(){
ui->imageWidget->setRenderMode(ImageWidget::AnglaphGreyscale);
}
void DepthViewWindow::on_actionSideBySideNoMirror_triggered(){
ui->imageWidget->setRenderMode(ImageWidget::SidebySide);
}
void DepthViewWindow::on_actionSideBySideMirrorLeft_triggered(){
ui->imageWidget->setRenderMode(ImageWidget::SidebySideMLeft);
}
void DepthViewWindow::on_actionSideBySideMirrorRight_triggered(){
ui->imageWidget->setRenderMode(ImageWidget::SidebySideMRight);
}
void DepthViewWindow::on_actionSideBySideMirrorBoth_triggered(){
ui->imageWidget->setRenderMode(ImageWidget::SidebySideMBoth);
}
void DepthViewWindow::on_actionTopBottomNoMirror_triggered(){
ui->imageWidget->setRenderMode(ImageWidget::TopBottom);
}
void DepthViewWindow::on_actionTopBottomMirrorTop_triggered(){
ui->imageWidget->setRenderMode(ImageWidget::TopBottomMTop);
}
void DepthViewWindow::on_actionTopBottomMirrorBottom_triggered(){
ui->imageWidget->setRenderMode(ImageWidget::TopBottomMBottom);
}
void DepthViewWindow::on_actionTopBottomMirrorBoth_triggered(){
ui->imageWidget->setRenderMode(ImageWidget::TopBottomMBoth);
}
void DepthViewWindow::on_actionInterlacedHorizontal_triggered(){
ui->imageWidget->setRenderMode(ImageWidget::InterlacedHorizontal);
}
void DepthViewWindow::on_actionInterlacedVertical_triggered(){
ui->imageWidget->setRenderMode(ImageWidget::InterlacedVertical);
}
void DepthViewWindow::on_actionCheckerboard_triggered(){
ui->imageWidget->setRenderMode(ImageWidget::Checkerboard);
}
void DepthViewWindow::on_actionSingleLeft_triggered(){
ui->imageWidget->setRenderMode(ImageWidget::MonoLeft);
}
void DepthViewWindow::on_actionSingleRight_triggered(){
ui->imageWidget->setRenderMode(ImageWidget::MonoRight);
}
void DepthViewWindow::on_actionFullscreen_toggled(bool val){
if(val){
setWindowState(windowState() | Qt::WindowFullScreen);
ui->actionShowMenuBar->setChecked(false);
}else{
setWindowState(windowState() & ~Qt::WindowFullScreen);
if(settings.contains(SettingsWindow::showmenubar)){
ui->actionShowMenuBar->setChecked(settings.value(SettingsWindow::showmenubar).toBool());
}else{
ui->actionShowMenuBar->setChecked(true);
}
}
}
void DepthViewWindow::on_actionNext_triggered(){
QStringList entryList = QDir::current().entryList(fileFilters);
if(!entryList.empty()){
int index = entryList.indexOf(currentFile) + 1;
if(index < 0){
index = entryList.count() - 1;
}else if(index >= entryList.count()){
index = 0;
}
loadImage(entryList[index]);
}
}
void DepthViewWindow::on_actionPrevious_triggered(){
QStringList entryList = QDir::current().entryList(fileFilters);
if(!entryList.empty()){
int index = entryList.indexOf(currentFile) - 1;
if(index < 0){
index = entryList.count() - 1;
}else if(index >= entryList.count()){
index = 0;
}
loadImage(entryList[index]);
}
}
void DepthViewWindow::on_actionFirst_triggered(){
QStringList entryList = QDir::current().entryList(fileFilters);
if(!entryList.isEmpty()){
loadImage(entryList[0]);
}
}
void DepthViewWindow::on_actionLast_triggered(){
QStringList entryList = QDir::current().entryList(fileFilters);
if(!entryList.isEmpty()){
loadImage(entryList[entryList.count() - 1]);
}
}
void DepthViewWindow::mousePressEvent(QMouseEvent *e){
if(e->buttons() == Qt::XButton2){
this->on_actionNext_triggered();
}
if(e->buttons() == Qt::XButton1){
this->on_actionPrevious_triggered();
}
}
void DepthViewWindow::mouseDoubleClickEvent(QMouseEvent *e){
if(e->button() == Qt::LeftButton){
ui->actionFullscreen->toggle();
}
}
void DepthViewWindow::on_actionSaveAs_triggered(){
QString filename = QFileDialog::getSaveFileName(this, tr("Save Image"), "",
tr("Stereo Image Files (*.jps *.pns);;Image Files (*.bmp *.jpg *.jpeg *.png *.ppm *.tiff *.xbm *.xpm)"));
if(filename.contains(".jps", Qt::CaseInsensitive) || filename.contains(".pns", Qt::CaseInsensitive)){
QImage out = drawSideBySide(ui->imageWidget->imgL,ui->imageWidget->imgR, 0, 0);
if(!out.isNull()){
if(filename.contains(".jps", Qt::CaseInsensitive)){
out.save(filename, "JPG");
}
if(filename.contains(".pns", Qt::CaseInsensitive)){
out.save(filename, "PNG");
}
}
}
else if(!filename.isNull()){
ExportDialog dialog(this);
if(dialog.exec() == QDialog::Accepted){
if(dialog.anglaph){
QImage out = drawAnglaph(ui->imageWidget->imgL, ui->imageWidget->imgR, 0, 0, QSize(), 1.0f, dialog.colormult);
if(!out.isNull()){
out.save(filename, NULL, dialog.quality);
}
}else if(dialog.sidebyside){
QImage out = drawSideBySide(ui->imageWidget->imgL, ui->imageWidget->imgR, 0, 0, QSize(), 1.0f, dialog.mirrorL, dialog.mirrorR);
if(!out.isNull()){
out.save(filename, NULL, dialog.quality);
}
}else{
if(dialog.saveL && dialog.saveR){
if(!ui->imageWidget->imgL.isNull()){
QString filenameL = filename;
ui->imageWidget->imgL.save(filenameL.insert(filenameL.lastIndexOf('.'), 'L'), NULL, dialog.quality);
}
if(!ui->imageWidget->imgR.isNull()){
QString filenameR = filename;
ui->imageWidget->imgR.save(filenameR.insert(filenameR.lastIndexOf('.'), 'R'), NULL, dialog.quality);
}
}else if(dialog.saveL){
if(!ui->imageWidget->imgL.isNull()){
ui->imageWidget->imgL.save(filename, NULL, dialog.quality);
}
}else if(dialog.saveR){
if(!ui->imageWidget->imgR.isNull()){
ui->imageWidget->imgR.save(filename, NULL, dialog.quality);
}
}
}
}
}
}
void DepthViewWindow::on_actionFit_triggered(){
ui->imageWidget->setZoom(0.0f);
}
void DepthViewWindow::on_actionzoom100_triggered(){
ui->imageWidget->setZoom(1.0f);
}
void DepthViewWindow::on_actionzoom50_triggered(){
ui->imageWidget->setZoom(0.5f);
}
void DepthViewWindow::on_actionzoom200_triggered(){
ui->imageWidget->setZoom(2.0f);
}
void DepthViewWindow::on_actionOptions_triggered(){
SettingsWindow settingsdialog(settings, this);
if(settingsdialog.exec() == QDialog::Accepted){
this->loadSettings();
}
}
void DepthViewWindow::on_actionSwap_Left_Right_toggled(bool val){
ui->imageWidget->swapLR = val;
ui->imageWidget->repaint();
}
void DepthViewWindow::on_actionShow_Scrollbars_toggled(bool val){
ui->imageWidget->showScrollbars = val;
ui->imageWidget->recalculatescroolmax();
}
void DepthViewWindow::on_actionAbout_triggered(){
QMessageBox::about(this, tr("About DepthView"),
tr("<html><head/><body>"
"<h1>DepthView %1 (%2)</h1>"
"<p>DepthView is a basic application for viewing stereo 3D image files.</p>"
"<p>DepthView website: <a href=\"https://github.com/chipgw/depthview\">github.com/chipgw/depthview</a></p>"
"<p>Please report any bugs at: <a href=\"https://github.com/chipgw/depthview/issues\">github.com/chipgw/depthview/issues</a></p>"
"</body></html>").arg(version::getVersionString()).arg(version::git_revision.left(7)));
}
void DepthViewWindow::on_actionAboutQt_triggered(){
QMessageBox::aboutQt(this);
}
bool DepthViewWindow::setRenderModeFromString(const QString &renderer){
if(ImageWidget::drawModeNames.contains(renderer)){
ui->imageWidget->setRenderMode(ImageWidget::drawModeNames.value(renderer));
return true;
}
return false;
}
void DepthViewWindow::loadSettings(){
if(settings.contains(SettingsWindow::defaultrender)){
setRenderModeFromString(settings.value(SettingsWindow::defaultrender).toString());
}
if(settings.contains(SettingsWindow::startfullscreen)){
ui->actionFullscreen->setChecked(settings.value(SettingsWindow::startfullscreen).toBool());
}else{
ui->actionFullscreen->setChecked(false);
}
if(settings.contains(SettingsWindow::swapLR)){
ui->actionSwap_Left_Right->setChecked(settings.value(SettingsWindow::swapLR).toBool());
}else{
ui->actionSwap_Left_Right->setChecked(false);
}
if(settings.contains(SettingsWindow::showmenubar)){
ui->actionShowMenuBar->setChecked(settings.value(SettingsWindow::showmenubar).toBool());
}else{
ui->actionShowMenuBar->setChecked(true);
}
if(settings.contains(SettingsWindow::disabledragdrop)){
setAcceptDrops(!settings.value(SettingsWindow::disabledragdrop).toBool());
}else{
setAcceptDrops(true);
}
if(settings.contains(SettingsWindow::continuouspan)){
ui->imageWidget->enableContinuousPan = settings.value(SettingsWindow::continuouspan).toBool();
}else{
ui->imageWidget->enableContinuousPan = true;
}
if(settings.contains(SettingsWindow::showscrollbars)){
ui->actionShow_Scrollbars->setChecked(settings.value(SettingsWindow::showscrollbars).toBool());
}else{
ui->actionShow_Scrollbars->setChecked(true);
}
if(settings.contains(SettingsWindow::startupdirectory) && currentFile.isEmpty() && !settings.value(SettingsWindow::startupdirectory).toString().isEmpty()){
QDir::setCurrent(settings.value(SettingsWindow::startupdirectory).toString());
}
}
void DepthViewWindow::parseCommandLine(const QStringList &args){
bool loaded = !this->currentFile.isEmpty();
QString warning;
for(QStringListIterator i(args); i.hasNext();){
const QString &arg = i.next();
if(arg == "--fullscreen"){
ui->actionFullscreen->setChecked(true);
}else if(arg == "--startdir"){
if(i.hasNext()){
const QString &dir = i.next();
if(!QDir::setCurrent(dir)){
warning.append(tr("<p>Invalid directory \"\%1\" passed to \"--startdir\" argument!</p>").arg(dir));
}
}else{
warning.append(tr("<p>Argument \"--startdir\" passed with no argument after it!</p>"));
}
}else if(arg == "--renderer"){
if(i.hasNext()){
const QString &renderer = i.next();
if(!setRenderModeFromString(renderer)){
warning.append(tr("<p>Invalid renderer \"%1\" passed to \"--renderer\" argument!</p>").arg(renderer));
}
}else{
warning.append(tr("<p>Argument \"--renderer\" passed with no argument after it!</p>"));
}
}else if(!loaded){
loaded = loadImage(arg);
}
}
if(!warning.isEmpty()){
QMessageBox::warning(this, tr("Warning: Invalid Command Line!"), warning);
}
if(!loaded && (!settings.contains(SettingsWindow::filedialogstartup) || settings.value(SettingsWindow::filedialogstartup).toBool())){
showLoadImageDialog();
}
}
void DepthViewWindow::dragEnterEvent(QDragEnterEvent *event){
if(event->mimeData()->hasUrls()){
foreach(QUrl url, event->mimeData()->urls()){
QFileInfo info(url.toLocalFile());
if(info.exists() && (info.suffix().toLower() == "jps" || info.suffix().toLower() == "pns")){
return event->acceptProposedAction();
}
}
}
}
void DepthViewWindow::dropEvent(QDropEvent *event){
if(event->mimeData()->hasUrls()){
foreach(QUrl url, event->mimeData()->urls()){
if(loadImage(url.toLocalFile())){
event->acceptProposedAction();
break;
}
}
}
}
const QStringList DepthViewWindow::fileFilters = QStringList() << "*.jps" << "*.pns";
<commit_msg>add "Portable" to about box in portable builds.<commit_after>#include "depthviewwindow.h"
#include "ui_depthviewwindow.h"
#include "exportdialog.h"
#include "settingswindow.h"
#include "version.h"
#include "renderers.h"
#include <QKeyEvent>
#include <QFileDialog>
#include <QDebug>
#include <QMessageBox>
#include <QTime>
#include <QMimeData>
#include <QUrl>
DepthViewWindow::DepthViewWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::DepthViewWindow)
#ifdef DEPTHVIEW_PORTABLE
, settings(QApplication::applicationDirPath() + "/DepthView.conf", QSettings::IniFormat)
#endif
{
ui->setupUi(this);
ui->imageWidget->addActions(ui->menubar->actions());
ui->imageWidget->setContextMenuPolicy(Qt::ActionsContextMenu);
connect(ui->imageWidget, SIGNAL(doubleClicked()), ui->actionFullscreen, SLOT(toggle()));
connect(ui->actionZoomIn, SIGNAL(triggered()), ui->imageWidget, SLOT(zoomIn()));
connect(ui->actionZoomOut, SIGNAL(triggered()), ui->imageWidget, SLOT(zoomOut()));
connect(ui->actionShowMenuBar, SIGNAL(toggled(bool)), ui->menubar, SLOT(setVisible(bool)));
connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(showLoadImageDialog()));
connect(ui->actionExit, SIGNAL(triggered()), this, SLOT(close()));
this->loadSettings();
}
DepthViewWindow::~DepthViewWindow(){
settings.setValue("lastrun", QDate::currentDate().toString());
delete ui;
}
bool DepthViewWindow::loadImage(const QString &filename){
QFileInfo info(filename);
if(info.exists() && (info.suffix().toLower() == "jps" || info.suffix().toLower() == "pns")){
QDir::setCurrent(info.path());
currentFile = info.fileName();
if(ui->imageWidget->loadStereoImage(currentFile)){
this->setWindowTitle(currentFile);
ui->imageWidget->repaint();
return true;
}else{
currentFile.clear();
this->setWindowTitle("DepthView");
}
}
return false;
}
bool DepthViewWindow::showLoadImageDialog(){
QString filename = QFileDialog::getOpenFileName(this, tr("Open Image"), "", tr("Stereo Image Files (*.jps *.pns)"));
return loadImage(filename);
}
void DepthViewWindow::on_actionAnglaphFullColor_triggered(){
ui->imageWidget->setRenderMode(ImageWidget::AnglaphFull);
}
void DepthViewWindow::on_actionAnglaphHalfColor_triggered(){
ui->imageWidget->setRenderMode(ImageWidget::AnglaphHalf);
}
void DepthViewWindow::on_actionAnglaphGreyscale_triggered(){
ui->imageWidget->setRenderMode(ImageWidget::AnglaphGreyscale);
}
void DepthViewWindow::on_actionSideBySideNoMirror_triggered(){
ui->imageWidget->setRenderMode(ImageWidget::SidebySide);
}
void DepthViewWindow::on_actionSideBySideMirrorLeft_triggered(){
ui->imageWidget->setRenderMode(ImageWidget::SidebySideMLeft);
}
void DepthViewWindow::on_actionSideBySideMirrorRight_triggered(){
ui->imageWidget->setRenderMode(ImageWidget::SidebySideMRight);
}
void DepthViewWindow::on_actionSideBySideMirrorBoth_triggered(){
ui->imageWidget->setRenderMode(ImageWidget::SidebySideMBoth);
}
void DepthViewWindow::on_actionTopBottomNoMirror_triggered(){
ui->imageWidget->setRenderMode(ImageWidget::TopBottom);
}
void DepthViewWindow::on_actionTopBottomMirrorTop_triggered(){
ui->imageWidget->setRenderMode(ImageWidget::TopBottomMTop);
}
void DepthViewWindow::on_actionTopBottomMirrorBottom_triggered(){
ui->imageWidget->setRenderMode(ImageWidget::TopBottomMBottom);
}
void DepthViewWindow::on_actionTopBottomMirrorBoth_triggered(){
ui->imageWidget->setRenderMode(ImageWidget::TopBottomMBoth);
}
void DepthViewWindow::on_actionInterlacedHorizontal_triggered(){
ui->imageWidget->setRenderMode(ImageWidget::InterlacedHorizontal);
}
void DepthViewWindow::on_actionInterlacedVertical_triggered(){
ui->imageWidget->setRenderMode(ImageWidget::InterlacedVertical);
}
void DepthViewWindow::on_actionCheckerboard_triggered(){
ui->imageWidget->setRenderMode(ImageWidget::Checkerboard);
}
void DepthViewWindow::on_actionSingleLeft_triggered(){
ui->imageWidget->setRenderMode(ImageWidget::MonoLeft);
}
void DepthViewWindow::on_actionSingleRight_triggered(){
ui->imageWidget->setRenderMode(ImageWidget::MonoRight);
}
void DepthViewWindow::on_actionFullscreen_toggled(bool val){
if(val){
setWindowState(windowState() | Qt::WindowFullScreen);
ui->actionShowMenuBar->setChecked(false);
}else{
setWindowState(windowState() & ~Qt::WindowFullScreen);
if(settings.contains(SettingsWindow::showmenubar)){
ui->actionShowMenuBar->setChecked(settings.value(SettingsWindow::showmenubar).toBool());
}else{
ui->actionShowMenuBar->setChecked(true);
}
}
}
void DepthViewWindow::on_actionNext_triggered(){
QStringList entryList = QDir::current().entryList(fileFilters);
if(!entryList.empty()){
int index = entryList.indexOf(currentFile) + 1;
if(index < 0){
index = entryList.count() - 1;
}else if(index >= entryList.count()){
index = 0;
}
loadImage(entryList[index]);
}
}
void DepthViewWindow::on_actionPrevious_triggered(){
QStringList entryList = QDir::current().entryList(fileFilters);
if(!entryList.empty()){
int index = entryList.indexOf(currentFile) - 1;
if(index < 0){
index = entryList.count() - 1;
}else if(index >= entryList.count()){
index = 0;
}
loadImage(entryList[index]);
}
}
void DepthViewWindow::on_actionFirst_triggered(){
QStringList entryList = QDir::current().entryList(fileFilters);
if(!entryList.isEmpty()){
loadImage(entryList[0]);
}
}
void DepthViewWindow::on_actionLast_triggered(){
QStringList entryList = QDir::current().entryList(fileFilters);
if(!entryList.isEmpty()){
loadImage(entryList[entryList.count() - 1]);
}
}
void DepthViewWindow::mousePressEvent(QMouseEvent *e){
if(e->buttons() == Qt::XButton2){
this->on_actionNext_triggered();
}
if(e->buttons() == Qt::XButton1){
this->on_actionPrevious_triggered();
}
}
void DepthViewWindow::mouseDoubleClickEvent(QMouseEvent *e){
if(e->button() == Qt::LeftButton){
ui->actionFullscreen->toggle();
}
}
void DepthViewWindow::on_actionSaveAs_triggered(){
QString filename = QFileDialog::getSaveFileName(this, tr("Save Image"), "",
tr("Stereo Image Files (*.jps *.pns);;Image Files (*.bmp *.jpg *.jpeg *.png *.ppm *.tiff *.xbm *.xpm)"));
if(filename.contains(".jps", Qt::CaseInsensitive) || filename.contains(".pns", Qt::CaseInsensitive)){
QImage out = drawSideBySide(ui->imageWidget->imgL,ui->imageWidget->imgR, 0, 0);
if(!out.isNull()){
if(filename.contains(".jps", Qt::CaseInsensitive)){
out.save(filename, "JPG");
}
if(filename.contains(".pns", Qt::CaseInsensitive)){
out.save(filename, "PNG");
}
}
}
else if(!filename.isNull()){
ExportDialog dialog(this);
if(dialog.exec() == QDialog::Accepted){
if(dialog.anglaph){
QImage out = drawAnglaph(ui->imageWidget->imgL, ui->imageWidget->imgR, 0, 0, QSize(), 1.0f, dialog.colormult);
if(!out.isNull()){
out.save(filename, NULL, dialog.quality);
}
}else if(dialog.sidebyside){
QImage out = drawSideBySide(ui->imageWidget->imgL, ui->imageWidget->imgR, 0, 0, QSize(), 1.0f, dialog.mirrorL, dialog.mirrorR);
if(!out.isNull()){
out.save(filename, NULL, dialog.quality);
}
}else{
if(dialog.saveL && dialog.saveR){
if(!ui->imageWidget->imgL.isNull()){
QString filenameL = filename;
ui->imageWidget->imgL.save(filenameL.insert(filenameL.lastIndexOf('.'), 'L'), NULL, dialog.quality);
}
if(!ui->imageWidget->imgR.isNull()){
QString filenameR = filename;
ui->imageWidget->imgR.save(filenameR.insert(filenameR.lastIndexOf('.'), 'R'), NULL, dialog.quality);
}
}else if(dialog.saveL){
if(!ui->imageWidget->imgL.isNull()){
ui->imageWidget->imgL.save(filename, NULL, dialog.quality);
}
}else if(dialog.saveR){
if(!ui->imageWidget->imgR.isNull()){
ui->imageWidget->imgR.save(filename, NULL, dialog.quality);
}
}
}
}
}
}
void DepthViewWindow::on_actionFit_triggered(){
ui->imageWidget->setZoom(0.0f);
}
void DepthViewWindow::on_actionzoom100_triggered(){
ui->imageWidget->setZoom(1.0f);
}
void DepthViewWindow::on_actionzoom50_triggered(){
ui->imageWidget->setZoom(0.5f);
}
void DepthViewWindow::on_actionzoom200_triggered(){
ui->imageWidget->setZoom(2.0f);
}
void DepthViewWindow::on_actionOptions_triggered(){
SettingsWindow settingsdialog(settings, this);
if(settingsdialog.exec() == QDialog::Accepted){
this->loadSettings();
}
}
void DepthViewWindow::on_actionSwap_Left_Right_toggled(bool val){
ui->imageWidget->swapLR = val;
ui->imageWidget->repaint();
}
void DepthViewWindow::on_actionShow_Scrollbars_toggled(bool val){
ui->imageWidget->showScrollbars = val;
ui->imageWidget->recalculatescroolmax();
}
void DepthViewWindow::on_actionAbout_triggered(){
QMessageBox::about(this, tr("About DepthView"),
tr("<html><head/><body>"
"<h1>DepthView %1"
#ifdef DEPTHVIEW_PORTABLE
" Portable"
#endif
" (%2)</h1>"
"<p>DepthView is a basic application for viewing stereo 3D image files.</p>"
"<p>DepthView website: <a href=\"https://github.com/chipgw/depthview\">github.com/chipgw/depthview</a></p>"
"<p>Please report any bugs at: <a href=\"https://github.com/chipgw/depthview/issues\">github.com/chipgw/depthview/issues</a></p>"
"</body></html>").arg(version::getVersionString()).arg(version::git_revision.left(7)));
}
void DepthViewWindow::on_actionAboutQt_triggered(){
QMessageBox::aboutQt(this);
}
bool DepthViewWindow::setRenderModeFromString(const QString &renderer){
if(ImageWidget::drawModeNames.contains(renderer)){
ui->imageWidget->setRenderMode(ImageWidget::drawModeNames.value(renderer));
return true;
}
return false;
}
void DepthViewWindow::loadSettings(){
if(settings.contains(SettingsWindow::defaultrender)){
setRenderModeFromString(settings.value(SettingsWindow::defaultrender).toString());
}
if(settings.contains(SettingsWindow::startfullscreen)){
ui->actionFullscreen->setChecked(settings.value(SettingsWindow::startfullscreen).toBool());
}else{
ui->actionFullscreen->setChecked(false);
}
if(settings.contains(SettingsWindow::swapLR)){
ui->actionSwap_Left_Right->setChecked(settings.value(SettingsWindow::swapLR).toBool());
}else{
ui->actionSwap_Left_Right->setChecked(false);
}
if(settings.contains(SettingsWindow::showmenubar)){
ui->actionShowMenuBar->setChecked(settings.value(SettingsWindow::showmenubar).toBool());
}else{
ui->actionShowMenuBar->setChecked(true);
}
if(settings.contains(SettingsWindow::disabledragdrop)){
setAcceptDrops(!settings.value(SettingsWindow::disabledragdrop).toBool());
}else{
setAcceptDrops(true);
}
if(settings.contains(SettingsWindow::continuouspan)){
ui->imageWidget->enableContinuousPan = settings.value(SettingsWindow::continuouspan).toBool();
}else{
ui->imageWidget->enableContinuousPan = true;
}
if(settings.contains(SettingsWindow::showscrollbars)){
ui->actionShow_Scrollbars->setChecked(settings.value(SettingsWindow::showscrollbars).toBool());
}else{
ui->actionShow_Scrollbars->setChecked(true);
}
if(settings.contains(SettingsWindow::startupdirectory) && currentFile.isEmpty() && !settings.value(SettingsWindow::startupdirectory).toString().isEmpty()){
QDir::setCurrent(settings.value(SettingsWindow::startupdirectory).toString());
}
}
void DepthViewWindow::parseCommandLine(const QStringList &args){
bool loaded = !this->currentFile.isEmpty();
QString warning;
for(QStringListIterator i(args); i.hasNext();){
const QString &arg = i.next();
if(arg == "--fullscreen"){
ui->actionFullscreen->setChecked(true);
}else if(arg == "--startdir"){
if(i.hasNext()){
const QString &dir = i.next();
if(!QDir::setCurrent(dir)){
warning.append(tr("<p>Invalid directory \"\%1\" passed to \"--startdir\" argument!</p>").arg(dir));
}
}else{
warning.append(tr("<p>Argument \"--startdir\" passed with no argument after it!</p>"));
}
}else if(arg == "--renderer"){
if(i.hasNext()){
const QString &renderer = i.next();
if(!setRenderModeFromString(renderer)){
warning.append(tr("<p>Invalid renderer \"%1\" passed to \"--renderer\" argument!</p>").arg(renderer));
}
}else{
warning.append(tr("<p>Argument \"--renderer\" passed with no argument after it!</p>"));
}
}else if(!loaded){
loaded = loadImage(arg);
}
}
if(!warning.isEmpty()){
QMessageBox::warning(this, tr("Warning: Invalid Command Line!"), warning);
}
if(!loaded && (!settings.contains(SettingsWindow::filedialogstartup) || settings.value(SettingsWindow::filedialogstartup).toBool())){
showLoadImageDialog();
}
}
void DepthViewWindow::dragEnterEvent(QDragEnterEvent *event){
if(event->mimeData()->hasUrls()){
foreach(QUrl url, event->mimeData()->urls()){
QFileInfo info(url.toLocalFile());
if(info.exists() && (info.suffix().toLower() == "jps" || info.suffix().toLower() == "pns")){
return event->acceptProposedAction();
}
}
}
}
void DepthViewWindow::dropEvent(QDropEvent *event){
if(event->mimeData()->hasUrls()){
foreach(QUrl url, event->mimeData()->urls()){
if(loadImage(url.toLocalFile())){
event->acceptProposedAction();
break;
}
}
}
}
const QStringList DepthViewWindow::fileFilters = QStringList() << "*.jps" << "*.pns";
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////
//
// ChCModelGPU.cpp
//
// ------------------------------------------------
// Copyright:Alessandro Tasora / DeltaKnowledge
// www.deltaknowledge.com
// ------------------------------------------------
///////////////////////////////////////////////////
#include "ChCCollisionModelGPU.h"
#include "physics/ChBody.h"
#include "physics/ChSystem.h"
namespace chrono {
namespace collision {
ChCollisionModelGPU::ChCollisionModelGPU() {
nObjects = 0;
colFam = -1;
noCollWith = -2;
inertia = R3(0);
}
ChCollisionModelGPU::~ChCollisionModelGPU() {
mData.clear();
}
int ChCollisionModelGPU::ClearModel() {
if (GetPhysicsItem()->GetSystem() && GetPhysicsItem()->GetCollide()) {
GetPhysicsItem()->GetSystem()->GetCollisionSystem()->Remove(this);
}
mData.clear();
nObjects = 0;
colFam = -1;
noCollWith = -2;
return 1;
}
int ChCollisionModelGPU::BuildModel() {
this->GetBody()->SetInertiaXX(ChVector<>(inertia.x, inertia.y, inertia.z));
if (GetPhysicsItem()->GetSystem() && GetPhysicsItem()->GetCollide()) {
GetPhysicsItem()->GetSystem()->GetCollisionSystem()->Add(this);
}
return 1;
}
bool ChCollisionModelGPU::AddSphere(double radius, ChVector<> *posv) {
ChVector<> *pos;
if (posv != 0) {
pos = posv;
} else {
pos = new ChVector<>(0, 0, 0);
}
double mass = this->GetBody()->GetMass();
inertia += pos->Length2() * mass + R3(2 / 5.0 * mass * radius * radius, 2 / 5.0 * mass * radius * radius, 2 / 5.0 * mass * radius * radius);
model_type = SPHERE;
nObjects++;
bData tData;
tData.A = R3(pos->x, pos->y, pos->z);
tData.B = R3(radius, 0, 0);
tData.C = R3(0, 0, 0);
tData.R = R4(1, 0, 0, 0);
tData.type = SPHERE;
mData.push_back(tData);
return true;
}
bool ChCollisionModelGPU::AddEllipsoid(double rx, double ry, double rz, ChVector<> *posv, ChMatrix33<> *rotv) {
ChVector<> *pos;
if (posv != 0) {
pos = posv;
} else {
pos = new ChVector<>(0, 0, 0);
}
ChMatrix33<> *rot;
if (rotv != 0) {
rot = rotv;
} else {
rot = new ChMatrix33<>();
}
double mass = this->GetBody()->GetMass();
inertia += pos->Length2() * mass
+ R3(1 / 5.0 * mass * (ry * ry + rz * rz), 1 / 5.0 * mass * (rx * rx + rz * rz), 1 / 5.0 * mass * (rx * rx + ry * ry));
model_type = ELLIPSOID;
nObjects++;
bData tData;
tData.A = R3(pos->x, pos->y, pos->z);
tData.B = R3(rx, ry, rz);
tData.C = R3(0, 0, 0);
tData.R = R4(rot->Get_A_quaternion().e0, rot->Get_A_quaternion().e1, rot->Get_A_quaternion().e2, rot->Get_A_quaternion().e3);
tData.type = ELLIPSOID;
mData.push_back(tData);
return true;
}
bool ChCollisionModelGPU::AddBox(double rx, double ry, double rz, ChVector<> *posv, ChMatrix33<> *rotv) {
ChVector<> *pos;
if (posv != 0) {
pos = posv;
} else {
pos = new ChVector<>(0, 0, 0);
}
ChMatrix33<> *rot;
if (rotv != 0) {
rot = rotv;
} else {
rot = new ChMatrix33<>();
}
double mass = this->GetBody()->GetMass();
inertia += pos->Length2() * mass
+ R3(1 / 12.0 * mass * (ry * ry + rz * rz), 1 / 12.0 * mass * (rx * rx + rz * rz), 1 / 12.0 * mass * (rx * rx + ry * ry));
model_type = BOX;
nObjects++;
bData tData;
tData.A = R3(pos->x, pos->y, pos->z);
tData.B = R3(rx, ry, rz);
tData.C = R3(0, 0, 0);
tData.R = R4(rot->Get_A_quaternion().e0, rot->Get_A_quaternion().e1, rot->Get_A_quaternion().e2, rot->Get_A_quaternion().e3);
tData.type = BOX;
mData.push_back(tData);
return true;
}
bool ChCollisionModelGPU::AddTriangle(ChVector<> A, ChVector<> B, ChVector<> C, ChVector<> *posv, ChMatrix33<> *rotv) {
ChVector<> *pos;
if (posv != 0) {
pos = posv;
} else {
pos = new ChVector<>(0, 0, 0);
}
ChMatrix33<> *rot;
if (rotv != 0) {
rot = rotv;
} else {
rot = new ChMatrix33<>();
}
double mass = this->GetBody()->GetMass();
model_type = TRIANGLEMESH;
nObjects++;
bData tData;
tData.A = R3(A.x + pos->x, A.y + pos->y, A.z + pos->z);
tData.B = R3(B.x + pos->x, B.y + pos->y, B.z + pos->z);
tData.C = R3(C.x + pos->x, C.y + pos->y, C.z + pos->z);
tData.R = R4(rot->Get_A_quaternion().e0, rot->Get_A_quaternion().e1, rot->Get_A_quaternion().e2, rot->Get_A_quaternion().e3);
tData.type = TRIANGLEMESH;
mData.push_back(tData);
return true;
}
bool ChCollisionModelGPU::AddCylinder(double rx, double ry, double rz, ChVector<> *posv, ChMatrix33<> *rotv) {
ChVector<> *pos;
if (posv != 0) {
pos = posv;
} else {
pos = new ChVector<>(0, 0, 0);
}
ChMatrix33<> *rot;
if (rotv != 0) {
rot = rotv;
} else {
rot = new ChMatrix33<>();
}
double mass = this->GetBody()->GetMass();
inertia += pos->Length2() * mass
+ R3(1 / 12.0 * mass * (3 * rx * rx + ry * ry), 1 / 2.0 * mass * (rx * rx), 1 / 12.0 * mass * (3 * rx * rx + ry * ry));
model_type = CYLINDER;
nObjects++;
bData tData;
tData.A = R3(pos->x, pos->y, pos->z);
tData.B = R3(rx, ry, rz);
tData.C = R3(0, 0, 0);
tData.R = R4(rot->Get_A_quaternion().e0, rot->Get_A_quaternion().e1, rot->Get_A_quaternion().e2, rot->Get_A_quaternion().e3);
tData.type = CYLINDER;
mData.push_back(tData);
return true;
}
bool ChCollisionModelGPU::AddCone(double rx, double ry, double rz, ChVector<> *posv, ChMatrix33<> *rotv) {
ChVector<> *pos;
if (posv != 0) {
pos = posv;
} else {
pos = new ChVector<>(0, 0, 0);
}
ChMatrix33<> *rot;
if (rotv != 0) {
rot = rotv;
} else {
rot = new ChMatrix33<>();
}
double mass = this->GetBody()->GetMass();
real radius = rx;
real height = ry;
inertia += pos->Length2() * mass + R3(
(3.0f / 80.0f) * mass * (radius * radius + 4 * height * height),
(3.0f / 10.0f) * mass * radius * radius,
(3.0f / 80.0f) * mass * (radius * radius + 4 * height * height));
model_type = CONE;
nObjects++;
bData tData;
tData.A = R3(pos->x, pos->y, pos->z);
tData.B = R3(radius, height, radius);
tData.C = R3(0, 0, 0);
tData.R = R4(rot->Get_A_quaternion().e0, rot->Get_A_quaternion().e1, rot->Get_A_quaternion().e2, rot->Get_A_quaternion().e3);
tData.type = CONE;
mData.push_back(tData);
return true;
}
bool ChCollisionModelGPU::AddConvexHull(std::vector<ChVector<double> > &pointlist, ChVector<> *pos, ChMatrix33<> *rot) {
//NOT SUPPORTED
return false;
}
bool ChCollisionModelGPU::AddBarrel(double Y_low, double Y_high, double R_vert, double R_hor, double R_offset, ChVector<> *pos, ChMatrix33<> *rot) {
//NOT SUPPORTED
return false;
}
bool ChCollisionModelGPU::AddRectangle(double rx, double ry) {
return false;
}
bool ChCollisionModelGPU::AddDisc(double rad) {
return false;
}
bool ChCollisionModelGPU::AddEllipse(double rx, double ry) {
return false;
}
bool ChCollisionModelGPU::AddCapsule(double len, double rad) {
return false;
}
bool ChCollisionModelGPU::AddCone(double rad, double h) {
return false;
}
/// Add a triangle mesh to this model
bool ChCollisionModelGPU::AddTriangleMesh(
const geometry::ChTriangleMesh &trimesh,
bool is_static,
bool is_convex,
ChVector<> *posv,
ChMatrix33<> *rotv) {
ChVector<> *pos;
// if (posv != 0) {
// pos = posv;
// } else {
pos = new ChVector<>(0, 0, 0);
// }
ChMatrix33<> *rot;
if (rotv != 0) {
rot = rotv;
} else {
rot = new ChMatrix33<>();
}
model_type = TRIANGLEMESH;
nObjects += trimesh.getNumTriangles();
bData tData;
for (int i = 0; i < trimesh.getNumTriangles(); i++) {
ChTriangle temptri = trimesh.getTriangle(i);
tData.A = R3(temptri.p1.x + pos->x, temptri.p1.y + pos->y, temptri.p1.z + pos->z);
tData.B = R3(temptri.p2.x + pos->x, temptri.p2.y + pos->y, temptri.p2.z + pos->z);
tData.C = R3(temptri.p3.x + pos->x, temptri.p3.y + pos->y, temptri.p3.z + pos->z);
tData.R = R4(rot->Get_A_quaternion().e0, rot->Get_A_quaternion().e1, rot->Get_A_quaternion().e2, rot->Get_A_quaternion().e3);
tData.type = TRIANGLEMESH;
mData.push_back(tData);
}
return true;
}
bool ChCollisionModelGPU::AddCopyOfAnotherModel(ChCollisionModel *another) {
//NOT SUPPORTED
return false;
}
void ChCollisionModelGPU::GetAABB(ChVector<> &bbmin, ChVector<> &bbmax) const {
}
void ChCollisionModelGPU::SetFamily(int mfamily) {
colFam = mfamily;
}
int ChCollisionModelGPU::GetFamily() {
return colFam;
}
void ChCollisionModelGPU::SetFamilyMaskNoCollisionWithFamily(int mfamily) {
noCollWith = mfamily;
}
void ChCollisionModelGPU::SetFamilyMaskDoCollisionWithFamily(int mfamily) {
if (noCollWith == mfamily) {
noCollWith = -1;
}
}
bool ChCollisionModelGPU::GetFamilyMaskDoesCollisionWithFamily(int mfamily) {
return (noCollWith != mfamily);
}
int ChCollisionModelGPU::GetNoCollFamily() {
return noCollWith;
}
void ChCollisionModelGPU::SyncPosition() {
ChBody *bpointer = GetBody();
assert(bpointer);
//assert(bpointer->GetSystem());
}
ChPhysicsItem *ChCollisionModelGPU::GetPhysicsItem() {
return (ChPhysicsItem *) GetBody();
}
} // END_OF_NAMESPACE____
} // END_OF_NAMESPACE____
<commit_msg>COrrected compound moment of inertia tensors. Only translations on a single axis will behave correctly for now.<commit_after>//////////////////////////////////////////////////
//
// ChCModelGPU.cpp
//
// ------------------------------------------------
// Copyright:Alessandro Tasora / DeltaKnowledge
// www.deltaknowledge.com
// ------------------------------------------------
///////////////////////////////////////////////////
#include "ChCCollisionModelGPU.h"
#include "physics/ChBody.h"
#include "physics/ChSystem.h"
namespace chrono {
namespace collision {
ChCollisionModelGPU::ChCollisionModelGPU() {
nObjects = 0;
colFam = -1;
noCollWith = -2;
inertia = R3(0);
}
ChCollisionModelGPU::~ChCollisionModelGPU() {
mData.clear();
}
int ChCollisionModelGPU::ClearModel() {
if (GetPhysicsItem()->GetSystem() && GetPhysicsItem()->GetCollide()) {
GetPhysicsItem()->GetSystem()->GetCollisionSystem()->Remove(this);
}
mData.clear();
nObjects = 0;
colFam = -1;
noCollWith = -2;
return 1;
}
int ChCollisionModelGPU::BuildModel() {
this->GetBody()->SetInertiaXX(ChVector<>(inertia.x, inertia.y, inertia.z));
if (GetPhysicsItem()->GetSystem() && GetPhysicsItem()->GetCollide()) {
GetPhysicsItem()->GetSystem()->GetCollisionSystem()->Add(this);
}
return 1;
}
bool ChCollisionModelGPU::AddSphere(double radius, ChVector<> *posv) {
ChVector<> *pos;
if (posv != 0) {
pos = posv;
} else {
pos = new ChVector<>(0, 0, 0);
}
double mass = this->GetBody()->GetMass();
real3 local_inertia = R3(2 / 5.0 * mass * radius * radius, 2 / 5.0 * mass * radius * radius, 2 / 5.0 * mass * radius * radius);
inertia.x += local_inertia.x+mass*(pos->Length2()-pos->x*pos->x);
inertia.y += local_inertia.y+mass*(pos->Length2()-pos->y*pos->y);
inertia.z += local_inertia.z+mass*(pos->Length2()-pos->z*pos->z);
model_type = SPHERE;
nObjects++;
bData tData;
tData.A = R3(pos->x, pos->y, pos->z);
tData.B = R3(radius, 0, 0);
tData.C = R3(0, 0, 0);
tData.R = R4(1, 0, 0, 0);
tData.type = SPHERE;
mData.push_back(tData);
return true;
}
bool ChCollisionModelGPU::AddEllipsoid(double rx, double ry, double rz, ChVector<> *posv, ChMatrix33<> *rotv) {
ChVector<> *pos;
if (posv != 0) {
pos = posv;
} else {
pos = new ChVector<>(0, 0, 0);
}
ChMatrix33<> *rot;
if (rotv != 0) {
rot = rotv;
} else {
rot = new ChMatrix33<>();
}
double mass = this->GetBody()->GetMass();
real3 local_inertia =R3(1 / 5.0 * mass * (ry * ry + rz * rz), 1 / 5.0 * mass * (rx * rx + rz * rz), 1 / 5.0 * mass * (rx * rx + ry * ry));
inertia.x += local_inertia.x+mass*(pos->Length2()-pos->x*pos->x);
inertia.y += local_inertia.y+mass*(pos->Length2()-pos->y*pos->y);
inertia.z += local_inertia.z+mass*(pos->Length2()-pos->z*pos->z);
model_type = ELLIPSOID;
nObjects++;
bData tData;
tData.A = R3(pos->x, pos->y, pos->z);
tData.B = R3(rx, ry, rz);
tData.C = R3(0, 0, 0);
tData.R = R4(rot->Get_A_quaternion().e0, rot->Get_A_quaternion().e1, rot->Get_A_quaternion().e2, rot->Get_A_quaternion().e3);
tData.type = ELLIPSOID;
mData.push_back(tData);
return true;
}
bool ChCollisionModelGPU::AddBox(double rx, double ry, double rz, ChVector<> *posv, ChMatrix33<> *rotv) {
ChVector<> *pos;
if (posv != 0) {
pos = posv;
} else {
pos = new ChVector<>(0, 0, 0);
}
ChMatrix33<> *rot;
if (rotv != 0) {
rot = rotv;
} else {
rot = new ChMatrix33<>();
}
double mass = this->GetBody()->GetMass();
real3 local_inertia =R3(1 / 12.0 * mass * (ry * ry + rz * rz), 1 / 12.0 * mass * (rx * rx + rz * rz), 1 / 12.0 * mass * (rx * rx + ry * ry));
inertia.x += local_inertia.x+mass*(pos->Length2()-pos->x*pos->x);
inertia.y += local_inertia.y+mass*(pos->Length2()-pos->y*pos->y);
inertia.z += local_inertia.z+mass*(pos->Length2()-pos->z*pos->z);
model_type = BOX;
nObjects++;
bData tData;
tData.A = R3(pos->x, pos->y, pos->z);
tData.B = R3(rx, ry, rz);
tData.C = R3(0, 0, 0);
tData.R = R4(rot->Get_A_quaternion().e0, rot->Get_A_quaternion().e1, rot->Get_A_quaternion().e2, rot->Get_A_quaternion().e3);
tData.type = BOX;
mData.push_back(tData);
return true;
}
bool ChCollisionModelGPU::AddTriangle(ChVector<> A, ChVector<> B, ChVector<> C, ChVector<> *posv, ChMatrix33<> *rotv) {
ChVector<> *pos;
if (posv != 0) {
pos = posv;
} else {
pos = new ChVector<>(0, 0, 0);
}
ChMatrix33<> *rot;
if (rotv != 0) {
rot = rotv;
} else {
rot = new ChMatrix33<>();
}
double mass = this->GetBody()->GetMass();
model_type = TRIANGLEMESH;
nObjects++;
bData tData;
tData.A = R3(A.x + pos->x, A.y + pos->y, A.z + pos->z);
tData.B = R3(B.x + pos->x, B.y + pos->y, B.z + pos->z);
tData.C = R3(C.x + pos->x, C.y + pos->y, C.z + pos->z);
tData.R = R4(rot->Get_A_quaternion().e0, rot->Get_A_quaternion().e1, rot->Get_A_quaternion().e2, rot->Get_A_quaternion().e3);
tData.type = TRIANGLEMESH;
mData.push_back(tData);
return true;
}
bool ChCollisionModelGPU::AddCylinder(double rx, double ry, double rz, ChVector<> *posv, ChMatrix33<> *rotv) {
ChVector<> *pos;
if (posv != 0) {
pos = posv;
} else {
pos = new ChVector<>(0, 0, 0);
}
ChMatrix33<> *rot;
if (rotv != 0) {
rot = rotv;
} else {
rot = new ChMatrix33<>();
}
double mass = this->GetBody()->GetMass();
real3 local_inertia =R3(1 / 12.0 * mass * (3 * rx * rx + ry * ry), 1 / 2.0 * mass * (rx * rx), 1 / 12.0 * mass * (3 * rx * rx + ry * ry));
inertia.x += local_inertia.x+mass*(pos->Length2()-pos->x*pos->x);
inertia.y += local_inertia.y+mass*(pos->Length2()-pos->y*pos->y);
inertia.z += local_inertia.z+mass*(pos->Length2()-pos->z*pos->z);
model_type = CYLINDER;
nObjects++;
bData tData;
tData.A = R3(pos->x, pos->y, pos->z);
tData.B = R3(rx, ry, rz);
tData.C = R3(0, 0, 0);
tData.R = R4(rot->Get_A_quaternion().e0, rot->Get_A_quaternion().e1, rot->Get_A_quaternion().e2, rot->Get_A_quaternion().e3);
tData.type = CYLINDER;
mData.push_back(tData);
return true;
}
bool ChCollisionModelGPU::AddCone(double rx, double ry, double rz, ChVector<> *posv, ChMatrix33<> *rotv) {
ChVector<> *pos;
if (posv != 0) {
pos = posv;
} else {
pos = new ChVector<>(0, 0, 0);
}
ChMatrix33<> *rot;
if (rotv != 0) {
rot = rotv;
} else {
rot = new ChMatrix33<>();
}
double mass = this->GetBody()->GetMass();
real radius = rx;
real height = ry;
real3 local_inertia =R3(
(3.0f / 80.0f) * mass * (radius * radius + 4 * height * height),
(3.0f / 10.0f) * mass * radius * radius,
(3.0f / 80.0f) * mass * (radius * radius + 4 * height * height));
inertia.x += local_inertia.x+mass*(pos->Length2()-pos->x*pos->x);
inertia.y += local_inertia.y+mass*(pos->Length2()-pos->y*pos->y);
inertia.z += local_inertia.z+mass*(pos->Length2()-pos->z*pos->z);
model_type = CONE;
nObjects++;
bData tData;
tData.A = R3(pos->x, pos->y, pos->z);
tData.B = R3(radius, height, radius);
tData.C = R3(0, 0, 0);
tData.R = R4(rot->Get_A_quaternion().e0, rot->Get_A_quaternion().e1, rot->Get_A_quaternion().e2, rot->Get_A_quaternion().e3);
tData.type = CONE;
mData.push_back(tData);
return true;
}
bool ChCollisionModelGPU::AddConvexHull(std::vector<ChVector<double> > &pointlist, ChVector<> *pos, ChMatrix33<> *rot) {
//NOT SUPPORTED
return false;
}
bool ChCollisionModelGPU::AddBarrel(double Y_low, double Y_high, double R_vert, double R_hor, double R_offset, ChVector<> *pos, ChMatrix33<> *rot) {
//NOT SUPPORTED
return false;
}
bool ChCollisionModelGPU::AddRectangle(double rx, double ry) {
return false;
}
bool ChCollisionModelGPU::AddDisc(double rad) {
return false;
}
bool ChCollisionModelGPU::AddEllipse(double rx, double ry) {
return false;
}
bool ChCollisionModelGPU::AddCapsule(double len, double rad) {
return false;
}
bool ChCollisionModelGPU::AddCone(double rad, double h) {
return false;
}
/// Add a triangle mesh to this model
bool ChCollisionModelGPU::AddTriangleMesh(
const geometry::ChTriangleMesh &trimesh,
bool is_static,
bool is_convex,
ChVector<> *posv,
ChMatrix33<> *rotv) {
ChVector<> *pos;
// if (posv != 0) {
// pos = posv;
// } else {
pos = new ChVector<>(0, 0, 0);
// }
ChMatrix33<> *rot;
if (rotv != 0) {
rot = rotv;
} else {
rot = new ChMatrix33<>();
}
model_type = TRIANGLEMESH;
nObjects += trimesh.getNumTriangles();
bData tData;
for (int i = 0; i < trimesh.getNumTriangles(); i++) {
ChTriangle temptri = trimesh.getTriangle(i);
tData.A = R3(temptri.p1.x + pos->x, temptri.p1.y + pos->y, temptri.p1.z + pos->z);
tData.B = R3(temptri.p2.x + pos->x, temptri.p2.y + pos->y, temptri.p2.z + pos->z);
tData.C = R3(temptri.p3.x + pos->x, temptri.p3.y + pos->y, temptri.p3.z + pos->z);
tData.R = R4(rot->Get_A_quaternion().e0, rot->Get_A_quaternion().e1, rot->Get_A_quaternion().e2, rot->Get_A_quaternion().e3);
tData.type = TRIANGLEMESH;
mData.push_back(tData);
}
return true;
}
bool ChCollisionModelGPU::AddCopyOfAnotherModel(ChCollisionModel *another) {
//NOT SUPPORTED
return false;
}
void ChCollisionModelGPU::GetAABB(ChVector<> &bbmin, ChVector<> &bbmax) const {
}
void ChCollisionModelGPU::SetFamily(int mfamily) {
colFam = mfamily;
}
int ChCollisionModelGPU::GetFamily() {
return colFam;
}
void ChCollisionModelGPU::SetFamilyMaskNoCollisionWithFamily(int mfamily) {
noCollWith = mfamily;
}
void ChCollisionModelGPU::SetFamilyMaskDoCollisionWithFamily(int mfamily) {
if (noCollWith == mfamily) {
noCollWith = -1;
}
}
bool ChCollisionModelGPU::GetFamilyMaskDoesCollisionWithFamily(int mfamily) {
return (noCollWith != mfamily);
}
int ChCollisionModelGPU::GetNoCollFamily() {
return noCollWith;
}
void ChCollisionModelGPU::SyncPosition() {
ChBody *bpointer = GetBody();
assert(bpointer);
//assert(bpointer->GetSystem());
}
ChPhysicsItem *ChCollisionModelGPU::GetPhysicsItem() {
return (ChPhysicsItem *) GetBody();
}
} // END_OF_NAMESPACE____
} // END_OF_NAMESPACE____
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Library
Module: Interact.hh
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
// .NAME vlRenderWindowInteractor - provide event driven interface to rendering window
// .SECTION Description
// vlRenderWindowInteractor is a convenience object that provides event
// bindings to common graphics functions. For example, camera
// zoom-in/zoom-out, azimuth, and roll.
// .SECTION Event Bindings
// Mouse bindings:
// Button 1 - rotate
// Button 2 - pan
// Button 3 - zoom
// (Distance from center of renderer viewport controls amount of
// rotate, pan, zoom).
// Keystrokes:
// w - turn all actors wireframe
// s - turn all actors surface
#ifndef __vlRenderWindowInteractor_h
#define __vlRenderWindowInteractor_h
#include "RenderW.hh"
#include "Camera.hh"
#include "Light.hh"
class vlRenderWindowInteractor : public vlObject
{
public:
vlRenderWindowInteractor();
~vlRenderWindowInteractor();
char *GetClassName() {return "vlRenderWindowInteractor";};
void PrintSelf(ostream& os, vlIndent indent);
virtual void Initialize() = 0;
virtual void Start() = 0;
// Description:
// Get the rendering window being controlled by this object.
vlSetObjectMacro(RenderWindow,vlRenderWindow);
vlGetObjectMacro(RenderWindow,vlRenderWindow);
// Description:
// Turn on/off the automatic repositioning of lights as the camera moves.
vlSetMacro(LightFollowCamera,int);
vlGetMacro(LightFollowCamera,int);
vlBooleanMacro(LightFollowCamera,int);
// Description:
// See whether interactor has been initialized yet.
vlGetMacro(Initialized,int);
void FindPokedCamera(int,int);
void FindPokedRenderer(int,int);
protected:
vlRenderWindow *RenderWindow;
vlCamera *CurrentCamera;
vlLight *CurrentLight;
vlRenderer *CurrentRenderer;
int LightFollowCamera;
float Center[2];
float DeltaAzimuth;
float DeltaElevation;
int Size[2];
int State;
float FocalDepth;
int Initialized;
};
#endif
<commit_msg>ENH:: Added reset method.<commit_after>/*=========================================================================
Program: Visualization Library
Module: Interact.hh
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
// .NAME vlRenderWindowInteractor - provide event driven interface to rendering window
// .SECTION Description
// vlRenderWindowInteractor is a convenience object that provides event
// bindings to common graphics functions. For example, camera
// zoom-in/zoom-out, azimuth, and roll.
// .SECTION Event Bindings
// Mouse bindings:
// Button 1 - rotate
// Button 2 - pan
// Button 3 - zoom
// (Distance from center of renderer viewport controls amount of
// rotate, pan, zoom).
// Keystrokes:
// r - reset camera view
// w - turn all actors wireframe
// s - turn all actors surface
#ifndef __vlRenderWindowInteractor_h
#define __vlRenderWindowInteractor_h
#include "RenderW.hh"
#include "Camera.hh"
#include "Light.hh"
class vlRenderWindowInteractor : public vlObject
{
public:
vlRenderWindowInteractor();
~vlRenderWindowInteractor();
char *GetClassName() {return "vlRenderWindowInteractor";};
void PrintSelf(ostream& os, vlIndent indent);
virtual void Initialize() = 0;
virtual void Start() = 0;
// Description:
// Get the rendering window being controlled by this object.
vlSetObjectMacro(RenderWindow,vlRenderWindow);
vlGetObjectMacro(RenderWindow,vlRenderWindow);
// Description:
// Turn on/off the automatic repositioning of lights as the camera moves.
vlSetMacro(LightFollowCamera,int);
vlGetMacro(LightFollowCamera,int);
vlBooleanMacro(LightFollowCamera,int);
// Description:
// See whether interactor has been initialized yet.
vlGetMacro(Initialized,int);
void FindPokedCamera(int,int);
void FindPokedRenderer(int,int);
protected:
vlRenderWindow *RenderWindow;
vlCamera *CurrentCamera;
vlLight *CurrentLight;
vlRenderer *CurrentRenderer;
int LightFollowCamera;
float Center[2];
float DeltaAzimuth;
float DeltaElevation;
int Size[2];
int State;
float FocalDepth;
int Initialized;
};
#endif
<|endoftext|> |
<commit_before>#include "../NULLC/nullc.h"
#if defined(_MSC_VER)
#pragma warning(disable: 4996)
#endif
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char* translationDependencies[128];
unsigned translationDependencyCount = 0;
void AddDependency(const char *fileName)
{
if(translationDependencyCount < 128)
translationDependencies[translationDependencyCount++] = fileName;
}
int main(int argc, char** argv)
{
nullcInit();
nullcAddImportPath("Modules/");
if(argc == 1)
{
printf("usage: nullcl [-o output.ncm] file.nc [-m module.name] [file2.nc [-m module.name] ...]\n");
printf("usage: nullcl -c output.cpp file.nc\n");
printf("usage: nullcl -x output.exe file.nc\n");
return 1;
}
int argIndex = 1;
FILE *mergeFile = NULL;
if(strcmp("-o", argv[argIndex]) == 0)
{
argIndex++;
if(argIndex == argc)
{
printf("Output file name not found after -o\n");
nullcTerminate();
return 1;
}
mergeFile = fopen(argv[argIndex], "wb");
if(!mergeFile)
{
printf("Cannot create output file %s\n", argv[argIndex]);
nullcTerminate();
return 1;
}
argIndex++;
}else if(strcmp("-c", argv[argIndex]) == 0 || strcmp("-x", argv[argIndex]) == 0){
bool link = strcmp("-x", argv[argIndex]) == 0;
argIndex++;
if(argIndex == argc)
{
printf("Output file name not found after -o\n");
nullcTerminate();
return 1;
}
const char *outputName = argv[argIndex++];
if(argIndex == argc)
{
printf("Input file name not found\n");
nullcTerminate();
return 1;
}
const char *fileName = argv[argIndex++];
FILE *ncFile = fopen(fileName, "rb");
if(!ncFile)
{
printf("Cannot open file %s\n", fileName);
nullcTerminate();
return 1;
}
fseek(ncFile, 0, SEEK_END);
unsigned int textSize = ftell(ncFile);
fseek(ncFile, 0, SEEK_SET);
char *fileContent = new char[textSize+1];
fread(fileContent, 1, textSize, ncFile);
fileContent[textSize] = 0;
fclose(ncFile);
if(!nullcCompile(fileContent))
{
printf("Compilation of %s failed with error:\n%s\n", fileName, nullcGetLastError());
delete[] fileContent;
return 1;
}
if(!nullcTranslateToC(link ? "__temp.cpp" : outputName, "main", AddDependency))
{
printf("Compilation of %s failed with error:\n%s\n", fileName, nullcGetLastError());
delete[] fileContent;
return 1;
}
if(link)
{
// $$$ move this to a dependency file?
char cmdLine[4096];
char *pos = cmdLine;
strcpy(pos, "gcc -g -o ");
pos += strlen(pos);
strcpy(pos, outputName);
pos += strlen(pos);
strcpy(pos, " __temp.cpp");
pos += strlen(pos);
strcpy(pos, " -lstdc++");
pos += strlen(pos);
char tmp[256];
sprintf(tmp, "runtime.cpp");
if(FILE *file = fopen(tmp, "r"))
{
*(pos++) = ' ';
strcpy(pos, tmp);
pos += strlen(pos);
fclose(file);
}
else
{
sprintf(tmp, "translation/runtime.cpp");
if(FILE *file = fopen(tmp, "r"))
{
*(pos++) = ' ';
strcpy(pos, tmp);
pos += strlen(pos);
fclose(file);
}
}
for(unsigned i = 0; i < translationDependencyCount; i++)
{
const char *dependency = translationDependencies[i];
*(pos++) = ' ';
strcpy(pos, dependency);
pos += strlen(pos);
if(strstr(dependency, "import_"))
{
sprintf(tmp, "%s", dependency + strlen("import_"));
if(char *pos = strstr(tmp, "_nc.cpp"))
strcpy(pos, "_bind.cpp");
if(FILE *file = fopen(tmp, "r"))
{
*(pos++) = ' ';
strcpy(pos, tmp);
pos += strlen(pos);
fclose(file);
}
else
{
sprintf(tmp, "translation/%s", dependency + strlen("import_"));
if(char *pos = strstr(tmp, "_nc.cpp"))
strcpy(pos, "_bind.cpp");
if(FILE *file = fopen(tmp, "r"))
{
*(pos++) = ' ';
strcpy(pos, tmp);
pos += strlen(pos);
fclose(file);
}
}
}
}
printf("Command line: %s\n", cmdLine);
system(cmdLine);
}
delete[] fileContent;
nullcTerminate();
return 0;
}
int currIndex = argIndex;
while(argIndex < argc)
{
const char *fileName = argv[argIndex++];
FILE *ncFile = fopen(fileName, "rb");
if(!ncFile)
{
printf("Cannot open file %s\n", fileName);
break;
}
fseek(ncFile, 0, SEEK_END);
unsigned int textSize = ftell(ncFile);
fseek(ncFile, 0, SEEK_SET);
char *fileContent = new char[textSize+1];
fread(fileContent, 1, textSize, ncFile);
fileContent[textSize] = 0;
fclose(ncFile);
if(!nullcCompile(fileContent))
{
printf("Compilation of %s failed with error:\n%s\n", fileName, nullcGetLastError());
delete[] fileContent;
return 1;
}
unsigned int *bytecode = NULL;
nullcGetBytecode((char**)&bytecode);
delete[] fileContent;
// Create module name
char moduleName[1024];
if(argIndex < argc && strcmp("-m", argv[argIndex]) == 0)
{
argIndex++;
if(argIndex == argc)
{
printf("Module name not found after -m\n");
break;
}
strcpy(moduleName, argv[argIndex++]);
}else{
strcpy(moduleName, fileName);
if(char *extensionPos = strchr(moduleName, '.'))
*extensionPos = '\0';
char *pos = moduleName;
while(*pos)
{
if(*pos++ == '\\' || *pos++ == '/')
pos[-1] = '.';
}
}
nullcLoadModuleByBinary(moduleName, (const char*)bytecode);
if(!mergeFile)
{
char newName[1024];
strcpy(newName, fileName);
strcat(newName, "m");
FILE *nmcFile = fopen(newName, "wb");
if(!nmcFile)
{
printf("Cannot create output file %s\n", newName);
break;
}
fwrite(moduleName, 1, strlen(moduleName) + 1, nmcFile);
fwrite(bytecode, 1, *bytecode, nmcFile);
fclose(nmcFile);
}else{
fwrite(moduleName, 1, strlen(moduleName) + 1, mergeFile);
fwrite(bytecode, 1, *bytecode, mergeFile);
}
}
if(currIndex == argIndex)
printf("None of the input files were found\n");
if(mergeFile)
fclose(mergeFile);
nullcTerminate();
return argIndex != argc;
}
<commit_msg>Check for long file names<commit_after>#include "../NULLC/nullc.h"
#if defined(_MSC_VER)
#pragma warning(disable: 4996)
#endif
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char* translationDependencies[128];
unsigned translationDependencyCount = 0;
void AddDependency(const char *fileName)
{
if(translationDependencyCount < 128)
translationDependencies[translationDependencyCount++] = fileName;
}
int main(int argc, char** argv)
{
nullcInit();
nullcAddImportPath("Modules/");
if(argc == 1)
{
printf("usage: nullcl [-o output.ncm] file.nc [-m module.name] [file2.nc [-m module.name] ...]\n");
printf("usage: nullcl -c output.cpp file.nc\n");
printf("usage: nullcl -x output.exe file.nc\n");
return 1;
}
int argIndex = 1;
FILE *mergeFile = NULL;
if(strcmp("-o", argv[argIndex]) == 0)
{
argIndex++;
if(argIndex == argc)
{
printf("Output file name not found after -o\n");
nullcTerminate();
return 1;
}
mergeFile = fopen(argv[argIndex], "wb");
if(!mergeFile)
{
printf("Cannot create output file %s\n", argv[argIndex]);
nullcTerminate();
return 1;
}
argIndex++;
}else if(strcmp("-c", argv[argIndex]) == 0 || strcmp("-x", argv[argIndex]) == 0){
bool link = strcmp("-x", argv[argIndex]) == 0;
argIndex++;
if(argIndex == argc)
{
printf("Output file name not found after -o\n");
nullcTerminate();
return 1;
}
const char *outputName = argv[argIndex++];
if(argIndex == argc)
{
printf("Input file name not found\n");
nullcTerminate();
return 1;
}
const char *fileName = argv[argIndex++];
FILE *ncFile = fopen(fileName, "rb");
if(!ncFile)
{
printf("Cannot open file %s\n", fileName);
nullcTerminate();
return 1;
}
fseek(ncFile, 0, SEEK_END);
unsigned int textSize = ftell(ncFile);
fseek(ncFile, 0, SEEK_SET);
char *fileContent = new char[textSize+1];
fread(fileContent, 1, textSize, ncFile);
fileContent[textSize] = 0;
fclose(ncFile);
if(!nullcCompile(fileContent))
{
printf("Compilation of %s failed with error:\n%s\n", fileName, nullcGetLastError());
delete[] fileContent;
return 1;
}
if(!nullcTranslateToC(link ? "__temp.cpp" : outputName, "main", AddDependency))
{
printf("Compilation of %s failed with error:\n%s\n", fileName, nullcGetLastError());
delete[] fileContent;
return 1;
}
if(link)
{
// $$$ move this to a dependency file?
char cmdLine[4096];
char *pos = cmdLine;
strcpy(pos, "gcc -g -o ");
pos += strlen(pos);
strcpy(pos, outputName);
pos += strlen(pos);
strcpy(pos, " __temp.cpp");
pos += strlen(pos);
strcpy(pos, " -lstdc++");
pos += strlen(pos);
char tmp[256];
sprintf(tmp, "runtime.cpp");
if(FILE *file = fopen(tmp, "r"))
{
*(pos++) = ' ';
strcpy(pos, tmp);
pos += strlen(pos);
fclose(file);
}
else
{
sprintf(tmp, "translation/runtime.cpp");
if(FILE *file = fopen(tmp, "r"))
{
*(pos++) = ' ';
strcpy(pos, tmp);
pos += strlen(pos);
fclose(file);
}
}
for(unsigned i = 0; i < translationDependencyCount; i++)
{
const char *dependency = translationDependencies[i];
*(pos++) = ' ';
strcpy(pos, dependency);
pos += strlen(pos);
if(strstr(dependency, "import_"))
{
sprintf(tmp, "%s", dependency + strlen("import_"));
if(char *pos = strstr(tmp, "_nc.cpp"))
strcpy(pos, "_bind.cpp");
if(FILE *file = fopen(tmp, "r"))
{
*(pos++) = ' ';
strcpy(pos, tmp);
pos += strlen(pos);
fclose(file);
}
else
{
sprintf(tmp, "translation/%s", dependency + strlen("import_"));
if(char *pos = strstr(tmp, "_nc.cpp"))
strcpy(pos, "_bind.cpp");
if(FILE *file = fopen(tmp, "r"))
{
*(pos++) = ' ';
strcpy(pos, tmp);
pos += strlen(pos);
fclose(file);
}
}
}
}
printf("Command line: %s\n", cmdLine);
system(cmdLine);
}
delete[] fileContent;
nullcTerminate();
return 0;
}
int currIndex = argIndex;
while(argIndex < argc)
{
const char *fileName = argv[argIndex++];
FILE *ncFile = fopen(fileName, "rb");
if(!ncFile)
{
printf("Cannot open file %s\n", fileName);
break;
}
fseek(ncFile, 0, SEEK_END);
unsigned int textSize = ftell(ncFile);
fseek(ncFile, 0, SEEK_SET);
char *fileContent = new char[textSize+1];
fread(fileContent, 1, textSize, ncFile);
fileContent[textSize] = 0;
fclose(ncFile);
if(!nullcCompile(fileContent))
{
printf("Compilation of %s failed with error:\n%s\n", fileName, nullcGetLastError());
delete[] fileContent;
return 1;
}
unsigned int *bytecode = NULL;
nullcGetBytecode((char**)&bytecode);
delete[] fileContent;
// Create module name
char moduleName[1024];
if(argIndex < argc && strcmp("-m", argv[argIndex]) == 0)
{
argIndex++;
if(argIndex == argc)
{
printf("Module name not found after -m\n");
break;
}
if(strlen(argv[argIndex]) + 1 >= 1024)
{
printf("Module name is too long\n");
break;
}
strcpy(moduleName, argv[argIndex]);
argIndex++;
}
else
{
if(strlen(fileName) + 1 >= 1024)
{
printf("File name is too long\n");
break;
}
strcpy(moduleName, fileName);
if(char *extensionPos = strchr(moduleName, '.'))
*extensionPos = '\0';
char *pos = moduleName;
while(*pos)
{
if(*pos++ == '\\' || *pos++ == '/')
pos[-1] = '.';
}
}
nullcLoadModuleByBinary(moduleName, (const char*)bytecode);
if(!mergeFile)
{
char newName[1024];
// Ont extra character for 'm' appended at the end
if(strlen(fileName) + 1 >= 1024 - 1)
{
printf("File name is too long\n");
break;
}
strcpy(newName, fileName);
strcat(newName, "m");
FILE *nmcFile = fopen(newName, "wb");
if(!nmcFile)
{
printf("Cannot create output file %s\n", newName);
break;
}
fwrite(moduleName, 1, strlen(moduleName) + 1, nmcFile);
fwrite(bytecode, 1, *bytecode, nmcFile);
fclose(nmcFile);
}else{
fwrite(moduleName, 1, strlen(moduleName) + 1, mergeFile);
fwrite(bytecode, 1, *bytecode, mergeFile);
}
}
if(currIndex == argIndex)
printf("None of the input files were found\n");
if(mergeFile)
fclose(mergeFile);
nullcTerminate();
return argIndex != argc;
}
<|endoftext|> |
<commit_before>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gl/GrGLInterface.h"
#include "../GrGLUtil.h"
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <GL/GL.h>
/*
* Windows makes the GL funcs all be __stdcall instead of __cdecl :(
* This implementation will only work if GR_GL_FUNCTION_TYPE is __stdcall.
* Otherwise, a springboard would be needed that hides the calling convention.
*/
#define GR_GL_GET_PROC(F) interface->f ## F = (GrGL ## F ## Proc) wglGetProcAddress("gl" #F);
#define GR_GL_GET_PROC_SUFFIX(F, S) interface->f ## F = (GrGL ## F ## Proc) wglGetProcAddress("gl" #F #S);
const GrGLInterface* GrGLCreateNativeInterface() {
// wglGetProcAddress requires a context.
// GL Function pointers retrieved in one context may not be valid in another
// context. For that reason we create a new GrGLInterface each time we're
// called.
if (NULL != wglGetCurrentContext()) {
const char* versionString = (const char*) glGetString(GL_VERSION);
const char* extString = (const char*) glGetString(GL_EXTENSIONS);
GrGLVersion glVer = GrGLGetVersionFromString(versionString);
if (glVer < GR_GL_VER(1,5)) {
// We must have array and element_array buffer objects.
return NULL;
}
GrGLInterface* interface = new GrGLInterface();
// Functions that are part of GL 1.1 will return NULL in
// wglGetProcAddress
interface->fBindTexture = glBindTexture;
interface->fBlendFunc = glBlendFunc;
if (glVer >= GR_GL_VER(1,4) ||
GrGLHasExtensionFromString("GL_ARB_imaging", extString) ||
GrGLHasExtensionFromString("GL_EXT_blend_color", extString)) {
GR_GL_GET_PROC(BlendColor);
}
interface->fClear = glClear;
interface->fClearColor = glClearColor;
interface->fClearStencil = glClearStencil;
interface->fColorMask = glColorMask;
interface->fCullFace = glCullFace;
interface->fDeleteTextures = glDeleteTextures;
interface->fDepthMask = glDepthMask;
interface->fDisable = glDisable;
interface->fDrawArrays = glDrawArrays;
interface->fDrawElements = glDrawElements;
interface->fDrawBuffer = glDrawBuffer;
interface->fEnable = glEnable;
interface->fFrontFace = glFrontFace;
interface->fFinish = glFinish;
interface->fFlush = glFlush;
interface->fGenTextures = glGenTextures;
interface->fGetError = glGetError;
interface->fGetIntegerv = glGetIntegerv;
interface->fGetString = glGetString;
interface->fGetTexLevelParameteriv = glGetTexLevelParameteriv;
interface->fLineWidth = glLineWidth;
interface->fLoadIdentity = glLoadIdentity;
interface->fLoadMatrixf = glLoadMatrixf;
interface->fMatrixMode = glMatrixMode;
interface->fPixelStorei = glPixelStorei;
interface->fReadBuffer = glReadBuffer;
interface->fReadPixels = glReadPixels;
interface->fScissor = glScissor;
interface->fStencilFunc = glStencilFunc;
interface->fStencilMask = glStencilMask;
interface->fStencilOp = glStencilOp;
interface->fTexImage2D = glTexImage2D;
interface->fTexParameteri = glTexParameteri;
interface->fTexParameteriv = glTexParameteriv;
if (glVer >= GR_GL_VER(4,2) ||
GrGLHasExtensionFromString("GL_ARB_texture_storage", extString)) {
GR_GL_GET_PROC(TexStorage2D);
} else if (GrGLHasExtensionFromString("GL_EXT_texture_storage", extString)) {
GR_GL_GET_PROC_SUFFIX(TexStorage2D, EXT);
}
interface->fTexSubImage2D = glTexSubImage2D;
interface->fViewport = glViewport;
GR_GL_GET_PROC(ActiveTexture);
GR_GL_GET_PROC(AttachShader);
GR_GL_GET_PROC(BeginQuery);
GR_GL_GET_PROC(BindAttribLocation);
GR_GL_GET_PROC(BindBuffer);
GR_GL_GET_PROC(BindFragDataLocation);
GR_GL_GET_PROC(BufferData);
GR_GL_GET_PROC(BufferSubData);
GR_GL_GET_PROC(CompileShader);
GR_GL_GET_PROC(CompressedTexImage2D);
GR_GL_GET_PROC(CreateProgram);
GR_GL_GET_PROC(CreateShader);
GR_GL_GET_PROC(DeleteBuffers);
GR_GL_GET_PROC(DeleteQueries);
GR_GL_GET_PROC(DeleteProgram);
GR_GL_GET_PROC(DeleteShader);
GR_GL_GET_PROC(DisableVertexAttribArray);
GR_GL_GET_PROC(DrawBuffers);
GR_GL_GET_PROC(EnableVertexAttribArray);
GR_GL_GET_PROC(EndQuery);
GR_GL_GET_PROC(GenBuffers);
GR_GL_GET_PROC(GenQueries);
GR_GL_GET_PROC(GetBufferParameteriv);
GR_GL_GET_PROC(GetQueryiv);
GR_GL_GET_PROC(GetQueryObjectiv);
GR_GL_GET_PROC(GetQueryObjectuiv);
if (glVer > GR_GL_VER(3,3) ||
GrGLHasExtensionFromString("GL_ARB_timer_query", extString)) {
GR_GL_GET_PROC(GetQueryObjecti64v);
GR_GL_GET_PROC(GetQueryObjectui64v);
GR_GL_GET_PROC(QueryCounter);
} else if (GrGLHasExtensionFromString("GL_EXT_timer_query", extString)) {
GR_GL_GET_PROC_SUFFIX(GetQueryObjecti64v, EXT);
GR_GL_GET_PROC_SUFFIX(GetQueryObjectui64v, EXT);
}
GR_GL_GET_PROC(GetProgramInfoLog);
GR_GL_GET_PROC(GetProgramiv);
GR_GL_GET_PROC(GetShaderInfoLog);
GR_GL_GET_PROC(GetShaderiv);
GR_GL_GET_PROC(GetUniformLocation);
GR_GL_GET_PROC(LinkProgram);
if (GrGLHasExtensionFromString("GL_NV_framebuffer_multisample_coverage", extString)) {
GR_GL_GET_PROC_SUFFIX(RenderbufferStorageMultisampleCoverage, NV);
}
GR_GL_GET_PROC(ShaderSource);
GR_GL_GET_PROC(StencilFuncSeparate);
GR_GL_GET_PROC(StencilMaskSeparate);
GR_GL_GET_PROC(StencilOpSeparate);
GR_GL_GET_PROC(Uniform1f);
GR_GL_GET_PROC(Uniform1i);
GR_GL_GET_PROC(Uniform1fv);
GR_GL_GET_PROC(Uniform1iv);
GR_GL_GET_PROC(Uniform2f);
GR_GL_GET_PROC(Uniform2i);
GR_GL_GET_PROC(Uniform2fv);
GR_GL_GET_PROC(Uniform2iv);
GR_GL_GET_PROC(Uniform3f);
GR_GL_GET_PROC(Uniform3i);
GR_GL_GET_PROC(Uniform3fv);
GR_GL_GET_PROC(Uniform3iv);
GR_GL_GET_PROC(Uniform4f);
GR_GL_GET_PROC(Uniform4i);
GR_GL_GET_PROC(Uniform4fv);
GR_GL_GET_PROC(Uniform4iv);
GR_GL_GET_PROC(UniformMatrix2fv);
GR_GL_GET_PROC(UniformMatrix3fv);
GR_GL_GET_PROC(UniformMatrix4fv);
GR_GL_GET_PROC(UseProgram);
GR_GL_GET_PROC(VertexAttrib4fv);
GR_GL_GET_PROC(VertexAttribPointer);
GR_GL_GET_PROC(BindFragDataLocationIndexed);
// First look for GL3.0 FBO or GL_ARB_framebuffer_object (same since
// GL_ARB_framebuffer_object doesn't use ARB suffix.)
if (glVer > GR_GL_VER(3,0) ||
GrGLHasExtensionFromString("GL_ARB_framebuffer_object", extString)) {
GR_GL_GET_PROC(GenFramebuffers);
GR_GL_GET_PROC(GetFramebufferAttachmentParameteriv);
GR_GL_GET_PROC(GetRenderbufferParameteriv);
GR_GL_GET_PROC(BindFramebuffer);
GR_GL_GET_PROC(FramebufferTexture2D);
GR_GL_GET_PROC(CheckFramebufferStatus);
GR_GL_GET_PROC(DeleteFramebuffers);
GR_GL_GET_PROC(RenderbufferStorage);
GR_GL_GET_PROC(GenRenderbuffers);
GR_GL_GET_PROC(DeleteRenderbuffers);
GR_GL_GET_PROC(FramebufferRenderbuffer);
GR_GL_GET_PROC(BindRenderbuffer);
GR_GL_GET_PROC(RenderbufferStorageMultisample);
GR_GL_GET_PROC(BlitFramebuffer);
} else if (GrGLHasExtensionFromString("GL_EXT_framebuffer_object",
extString)) {
GR_GL_GET_PROC_SUFFIX(GenFramebuffers, EXT);
GR_GL_GET_PROC_SUFFIX(GetFramebufferAttachmentParameteriv, EXT);
GR_GL_GET_PROC_SUFFIX(GetRenderbufferParameteriv, EXT);
GR_GL_GET_PROC_SUFFIX(BindFramebuffer, EXT);
GR_GL_GET_PROC_SUFFIX(FramebufferTexture2D, EXT);
GR_GL_GET_PROC_SUFFIX(CheckFramebufferStatus, EXT);
GR_GL_GET_PROC_SUFFIX(DeleteFramebuffers, EXT);
GR_GL_GET_PROC_SUFFIX(RenderbufferStorage, EXT);
GR_GL_GET_PROC_SUFFIX(GenRenderbuffers, EXT);
GR_GL_GET_PROC_SUFFIX(DeleteRenderbuffers, EXT);
GR_GL_GET_PROC_SUFFIX(FramebufferRenderbuffer, EXT);
GR_GL_GET_PROC_SUFFIX(BindRenderbuffer, EXT);
if (GrGLHasExtensionFromString("GL_EXT_framebuffer_multisample", extString)) {
GR_GL_GET_PROC_SUFFIX(RenderbufferStorageMultisample, EXT);
}
if (GrGLHasExtensionFromString("GL_EXT_framebuffer_blit", extString)) {
GR_GL_GET_PROC_SUFFIX(BlitFramebuffer, EXT);
}
} else {
// we must have FBOs
delete interface;
return NULL;
}
GR_GL_GET_PROC(MapBuffer);
GR_GL_GET_PROC(UnmapBuffer);
if (GrGLHasExtensionFromString("GL_NV_path_rendering", extString)) {
GR_GL_GET_PROC_SUFFIX(PathCommands, NV);
GR_GL_GET_PROC_SUFFIX(PathCoords, NV);
GR_GL_GET_PROC_SUFFIX(PathSubCommands, NV);
GR_GL_GET_PROC_SUFFIX(PathSubCoords, NV);
GR_GL_GET_PROC_SUFFIX(PathString, NV);
GR_GL_GET_PROC_SUFFIX(PathGlyphs, NV);
GR_GL_GET_PROC_SUFFIX(PathGlyphRange, NV);
GR_GL_GET_PROC_SUFFIX(WeightPaths, NV);
GR_GL_GET_PROC_SUFFIX(CopyPath, NV);
GR_GL_GET_PROC_SUFFIX(InterpolatePaths, NV);
GR_GL_GET_PROC_SUFFIX(TransformPath, NV);
GR_GL_GET_PROC_SUFFIX(PathParameteriv, NV);
GR_GL_GET_PROC_SUFFIX(PathParameteri, NV);
GR_GL_GET_PROC_SUFFIX(PathParameterfv, NV);
GR_GL_GET_PROC_SUFFIX(PathParameterf, NV);
GR_GL_GET_PROC_SUFFIX(PathDashArray, NV);
GR_GL_GET_PROC_SUFFIX(GenPaths, NV);
GR_GL_GET_PROC_SUFFIX(DeletePaths, NV);
GR_GL_GET_PROC_SUFFIX(IsPath, NV);
GR_GL_GET_PROC_SUFFIX(PathStencilFunc, NV);
GR_GL_GET_PROC_SUFFIX(PathStencilDepthOffset, NV);
GR_GL_GET_PROC_SUFFIX(StencilFillPath, NV);
GR_GL_GET_PROC_SUFFIX(StencilStrokePath, NV);
GR_GL_GET_PROC_SUFFIX(StencilFillPathInstanced, NV);
GR_GL_GET_PROC_SUFFIX(StencilStrokePathInstanced, NV);
GR_GL_GET_PROC_SUFFIX(PathCoverDepthFunc, NV);
GR_GL_GET_PROC_SUFFIX(PathColorGen, NV);
GR_GL_GET_PROC_SUFFIX(PathTexGen, NV);
GR_GL_GET_PROC_SUFFIX(PathFogGen, NV);
GR_GL_GET_PROC_SUFFIX(CoverFillPath, NV);
GR_GL_GET_PROC_SUFFIX(CoverStrokePath, NV);
GR_GL_GET_PROC_SUFFIX(CoverFillPathInstanced, NV);
GR_GL_GET_PROC_SUFFIX(CoverStrokePathInstanced, NV);
GR_GL_GET_PROC_SUFFIX(GetPathParameteriv, NV);
GR_GL_GET_PROC_SUFFIX(GetPathParameterfv, NV);
GR_GL_GET_PROC_SUFFIX(GetPathCommands, NV);
GR_GL_GET_PROC_SUFFIX(GetPathCoords, NV);
GR_GL_GET_PROC_SUFFIX(GetPathDashArray, NV);
GR_GL_GET_PROC_SUFFIX(GetPathMetrics, NV);
GR_GL_GET_PROC_SUFFIX(GetPathMetricRange, NV);
GR_GL_GET_PROC_SUFFIX(GetPathSpacing, NV);
GR_GL_GET_PROC_SUFFIX(GetPathColorGeniv, NV);
GR_GL_GET_PROC_SUFFIX(GetPathColorGenfv, NV);
GR_GL_GET_PROC_SUFFIX(GetPathTexGeniv, NV);
GR_GL_GET_PROC_SUFFIX(GetPathTexGenfv, NV);
GR_GL_GET_PROC_SUFFIX(IsPointInFillPath, NV);
GR_GL_GET_PROC_SUFFIX(IsPointInStrokePath, NV);
GR_GL_GET_PROC_SUFFIX(GetPathLength, NV);
GR_GL_GET_PROC_SUFFIX(PointAlongPath, NV);
}
interface->fBindingsExported = kDesktop_GrGLBinding;
return interface;
} else {
return NULL;
}
}
<commit_msg>Make windows GrGLCreateNatriveInterface not us GL.h and not use linker to resolve gl functions. Instead load the GL library and use GetProcAddress.<commit_after>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gl/GrGLInterface.h"
#include "../GrGLUtil.h"
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
/*
* Windows makes the GL funcs all be __stdcall instead of __cdecl :(
* This implementation will only work if GR_GL_FUNCTION_TYPE is __stdcall.
* Otherwise, a springboard would be needed that hides the calling convention.
*/
#define SET_PROC(F) interface->f ## F = (GrGL ## F ## Proc) GetProcAddress(alu.get(), "gl" #F);
#define WGL_SET_PROC(F) interface->f ## F = (GrGL ## F ## Proc) wglGetProcAddress("gl" #F);
#define WGL_SET_PROC_SUFFIX(F, S) interface->f ## F = \
(GrGL ## F ## Proc) wglGetProcAddress("gl" #F #S);
class AutoLibraryUnload {
public:
AutoLibraryUnload(const char* moduleName) {
fModule = LoadLibrary(moduleName);
}
~AutoLibraryUnload() {
if (NULL != fModule) {
FreeLibrary(fModule);
}
}
HMODULE get() const { return fModule; }
private:
HMODULE fModule;
};
const GrGLInterface* GrGLCreateNativeInterface() {
// wglGetProcAddress requires a context.
// GL Function pointers retrieved in one context may not be valid in another
// context. For that reason we create a new GrGLInterface each time we're
// called.
AutoLibraryUnload alu("opengl32.dll");
if (NULL == alu.get()) {
return NULL;
}
GrGLGetStringProc glGetString =
(GrGLGetStringProc) GetProcAddress(alu.get(), "glGetString");
if (NULL != wglGetCurrentContext()) {
const char* versionString = (const char*) glGetString(GR_GL_VERSION);
const char* extString = (const char*) glGetString(GR_GL_EXTENSIONS);
GrGLVersion glVer = GrGLGetVersionFromString(versionString);
if (glVer < GR_GL_VER(1,5)) {
// We must have array and element_array buffer objects.
return NULL;
}
GrGLInterface* interface = new GrGLInterface();
// Functions that are part of GL 1.1 will return NULL in
// wglGetProcAddress
SET_PROC(BindTexture)
SET_PROC(BlendFunc)
if (glVer >= GR_GL_VER(1,4) ||
GrGLHasExtensionFromString("GL_ARB_imaging", extString) ||
GrGLHasExtensionFromString("GL_EXT_blend_color", extString)) {
WGL_SET_PROC(BlendColor);
}
SET_PROC(Clear)
SET_PROC(ClearColor)
SET_PROC(ClearStencil)
SET_PROC(ColorMask)
SET_PROC(CullFace)
SET_PROC(DeleteTextures)
SET_PROC(DepthMask)
SET_PROC(Disable)
SET_PROC(DrawArrays)
SET_PROC(DrawElements)
SET_PROC(DrawBuffer)
SET_PROC(Enable)
SET_PROC(FrontFace)
SET_PROC(Finish)
SET_PROC(Flush)
SET_PROC(GenTextures)
SET_PROC(GetError)
SET_PROC(GetIntegerv)
SET_PROC(GetString)
SET_PROC(GetTexLevelParameteriv)
SET_PROC(LineWidth)
SET_PROC(LoadIdentity)
SET_PROC(LoadMatrixf)
SET_PROC(MatrixMode)
SET_PROC(PixelStorei)
SET_PROC(ReadBuffer)
SET_PROC(ReadPixels)
SET_PROC(Scissor)
SET_PROC(StencilFunc)
SET_PROC(StencilMask)
SET_PROC(StencilOp)
SET_PROC(TexImage2D)
SET_PROC(TexParameteri)
SET_PROC(TexParameteriv)
if (glVer >= GR_GL_VER(4,2) ||
GrGLHasExtensionFromString("GL_ARB_texture_storage", extString)) {
WGL_SET_PROC(TexStorage2D);
} else if (GrGLHasExtensionFromString("GL_EXT_texture_storage", extString)) {
WGL_SET_PROC_SUFFIX(TexStorage2D, EXT);
}
SET_PROC(TexSubImage2D)
SET_PROC(Viewport)
WGL_SET_PROC(ActiveTexture);
WGL_SET_PROC(AttachShader);
WGL_SET_PROC(BeginQuery);
WGL_SET_PROC(BindAttribLocation);
WGL_SET_PROC(BindBuffer);
WGL_SET_PROC(BindFragDataLocation);
WGL_SET_PROC(BufferData);
WGL_SET_PROC(BufferSubData);
WGL_SET_PROC(CompileShader);
WGL_SET_PROC(CompressedTexImage2D);
WGL_SET_PROC(CreateProgram);
WGL_SET_PROC(CreateShader);
WGL_SET_PROC(DeleteBuffers);
WGL_SET_PROC(DeleteQueries);
WGL_SET_PROC(DeleteProgram);
WGL_SET_PROC(DeleteShader);
WGL_SET_PROC(DisableVertexAttribArray);
WGL_SET_PROC(DrawBuffers);
WGL_SET_PROC(EnableVertexAttribArray);
WGL_SET_PROC(EndQuery);
WGL_SET_PROC(GenBuffers);
WGL_SET_PROC(GenQueries);
WGL_SET_PROC(GetBufferParameteriv);
WGL_SET_PROC(GetQueryiv);
WGL_SET_PROC(GetQueryObjectiv);
WGL_SET_PROC(GetQueryObjectuiv);
if (glVer > GR_GL_VER(3,3) ||
GrGLHasExtensionFromString("GL_ARB_timer_query", extString)) {
WGL_SET_PROC(GetQueryObjecti64v);
WGL_SET_PROC(GetQueryObjectui64v);
WGL_SET_PROC(QueryCounter);
} else if (GrGLHasExtensionFromString("GL_EXT_timer_query", extString)) {
WGL_SET_PROC_SUFFIX(GetQueryObjecti64v, EXT);
WGL_SET_PROC_SUFFIX(GetQueryObjectui64v, EXT);
}
WGL_SET_PROC(GetProgramInfoLog);
WGL_SET_PROC(GetProgramiv);
WGL_SET_PROC(GetShaderInfoLog);
WGL_SET_PROC(GetShaderiv);
WGL_SET_PROC(GetUniformLocation);
WGL_SET_PROC(LinkProgram);
if (GrGLHasExtensionFromString("GL_NV_framebuffer_multisample_coverage", extString)) {
WGL_SET_PROC_SUFFIX(RenderbufferStorageMultisampleCoverage, NV);
}
WGL_SET_PROC(ShaderSource);
WGL_SET_PROC(StencilFuncSeparate);
WGL_SET_PROC(StencilMaskSeparate);
WGL_SET_PROC(StencilOpSeparate);
WGL_SET_PROC(Uniform1f);
WGL_SET_PROC(Uniform1i);
WGL_SET_PROC(Uniform1fv);
WGL_SET_PROC(Uniform1iv);
WGL_SET_PROC(Uniform2f);
WGL_SET_PROC(Uniform2i);
WGL_SET_PROC(Uniform2fv);
WGL_SET_PROC(Uniform2iv);
WGL_SET_PROC(Uniform3f);
WGL_SET_PROC(Uniform3i);
WGL_SET_PROC(Uniform3fv);
WGL_SET_PROC(Uniform3iv);
WGL_SET_PROC(Uniform4f);
WGL_SET_PROC(Uniform4i);
WGL_SET_PROC(Uniform4fv);
WGL_SET_PROC(Uniform4iv);
WGL_SET_PROC(UniformMatrix2fv);
WGL_SET_PROC(UniformMatrix3fv);
WGL_SET_PROC(UniformMatrix4fv);
WGL_SET_PROC(UseProgram);
WGL_SET_PROC(VertexAttrib4fv);
WGL_SET_PROC(VertexAttribPointer);
WGL_SET_PROC(BindFragDataLocationIndexed);
// First look for GL3.0 FBO or GL_ARB_framebuffer_object (same since
// GL_ARB_framebuffer_object doesn't use ARB suffix.)
if (glVer > GR_GL_VER(3,0) ||
GrGLHasExtensionFromString("GL_ARB_framebuffer_object", extString)) {
WGL_SET_PROC(GenFramebuffers);
WGL_SET_PROC(GetFramebufferAttachmentParameteriv);
WGL_SET_PROC(GetRenderbufferParameteriv);
WGL_SET_PROC(BindFramebuffer);
WGL_SET_PROC(FramebufferTexture2D);
WGL_SET_PROC(CheckFramebufferStatus);
WGL_SET_PROC(DeleteFramebuffers);
WGL_SET_PROC(RenderbufferStorage);
WGL_SET_PROC(GenRenderbuffers);
WGL_SET_PROC(DeleteRenderbuffers);
WGL_SET_PROC(FramebufferRenderbuffer);
WGL_SET_PROC(BindRenderbuffer);
WGL_SET_PROC(RenderbufferStorageMultisample);
WGL_SET_PROC(BlitFramebuffer);
} else if (GrGLHasExtensionFromString("GL_EXT_framebuffer_object",
extString)) {
WGL_SET_PROC_SUFFIX(GenFramebuffers, EXT);
WGL_SET_PROC_SUFFIX(GetFramebufferAttachmentParameteriv, EXT);
WGL_SET_PROC_SUFFIX(GetRenderbufferParameteriv, EXT);
WGL_SET_PROC_SUFFIX(BindFramebuffer, EXT);
WGL_SET_PROC_SUFFIX(FramebufferTexture2D, EXT);
WGL_SET_PROC_SUFFIX(CheckFramebufferStatus, EXT);
WGL_SET_PROC_SUFFIX(DeleteFramebuffers, EXT);
WGL_SET_PROC_SUFFIX(RenderbufferStorage, EXT);
WGL_SET_PROC_SUFFIX(GenRenderbuffers, EXT);
WGL_SET_PROC_SUFFIX(DeleteRenderbuffers, EXT);
WGL_SET_PROC_SUFFIX(FramebufferRenderbuffer, EXT);
WGL_SET_PROC_SUFFIX(BindRenderbuffer, EXT);
if (GrGLHasExtensionFromString("GL_EXT_framebuffer_multisample", extString)) {
WGL_SET_PROC_SUFFIX(RenderbufferStorageMultisample, EXT);
}
if (GrGLHasExtensionFromString("GL_EXT_framebuffer_blit", extString)) {
WGL_SET_PROC_SUFFIX(BlitFramebuffer, EXT);
}
} else {
// we must have FBOs
delete interface;
return NULL;
}
WGL_SET_PROC(MapBuffer);
WGL_SET_PROC(UnmapBuffer);
if (GrGLHasExtensionFromString("GL_NV_path_rendering", extString)) {
WGL_SET_PROC_SUFFIX(PathCommands, NV);
WGL_SET_PROC_SUFFIX(PathCoords, NV);
WGL_SET_PROC_SUFFIX(PathSubCommands, NV);
WGL_SET_PROC_SUFFIX(PathSubCoords, NV);
WGL_SET_PROC_SUFFIX(PathString, NV);
WGL_SET_PROC_SUFFIX(PathGlyphs, NV);
WGL_SET_PROC_SUFFIX(PathGlyphRange, NV);
WGL_SET_PROC_SUFFIX(WeightPaths, NV);
WGL_SET_PROC_SUFFIX(CopyPath, NV);
WGL_SET_PROC_SUFFIX(InterpolatePaths, NV);
WGL_SET_PROC_SUFFIX(TransformPath, NV);
WGL_SET_PROC_SUFFIX(PathParameteriv, NV);
WGL_SET_PROC_SUFFIX(PathParameteri, NV);
WGL_SET_PROC_SUFFIX(PathParameterfv, NV);
WGL_SET_PROC_SUFFIX(PathParameterf, NV);
WGL_SET_PROC_SUFFIX(PathDashArray, NV);
WGL_SET_PROC_SUFFIX(GenPaths, NV);
WGL_SET_PROC_SUFFIX(DeletePaths, NV);
WGL_SET_PROC_SUFFIX(IsPath, NV);
WGL_SET_PROC_SUFFIX(PathStencilFunc, NV);
WGL_SET_PROC_SUFFIX(PathStencilDepthOffset, NV);
WGL_SET_PROC_SUFFIX(StencilFillPath, NV);
WGL_SET_PROC_SUFFIX(StencilStrokePath, NV);
WGL_SET_PROC_SUFFIX(StencilFillPathInstanced, NV);
WGL_SET_PROC_SUFFIX(StencilStrokePathInstanced, NV);
WGL_SET_PROC_SUFFIX(PathCoverDepthFunc, NV);
WGL_SET_PROC_SUFFIX(PathColorGen, NV);
WGL_SET_PROC_SUFFIX(PathTexGen, NV);
WGL_SET_PROC_SUFFIX(PathFogGen, NV);
WGL_SET_PROC_SUFFIX(CoverFillPath, NV);
WGL_SET_PROC_SUFFIX(CoverStrokePath, NV);
WGL_SET_PROC_SUFFIX(CoverFillPathInstanced, NV);
WGL_SET_PROC_SUFFIX(CoverStrokePathInstanced, NV);
WGL_SET_PROC_SUFFIX(GetPathParameteriv, NV);
WGL_SET_PROC_SUFFIX(GetPathParameterfv, NV);
WGL_SET_PROC_SUFFIX(GetPathCommands, NV);
WGL_SET_PROC_SUFFIX(GetPathCoords, NV);
WGL_SET_PROC_SUFFIX(GetPathDashArray, NV);
WGL_SET_PROC_SUFFIX(GetPathMetrics, NV);
WGL_SET_PROC_SUFFIX(GetPathMetricRange, NV);
WGL_SET_PROC_SUFFIX(GetPathSpacing, NV);
WGL_SET_PROC_SUFFIX(GetPathColorGeniv, NV);
WGL_SET_PROC_SUFFIX(GetPathColorGenfv, NV);
WGL_SET_PROC_SUFFIX(GetPathTexGeniv, NV);
WGL_SET_PROC_SUFFIX(GetPathTexGenfv, NV);
WGL_SET_PROC_SUFFIX(IsPointInFillPath, NV);
WGL_SET_PROC_SUFFIX(IsPointInStrokePath, NV);
WGL_SET_PROC_SUFFIX(GetPathLength, NV);
WGL_SET_PROC_SUFFIX(PointAlongPath, NV);
}
interface->fBindingsExported = kDesktop_GrGLBinding;
return interface;
} else {
return NULL;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2016 - 2021 gary@drinkingtea.net
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <ox/claw/read.hpp>
#include "pack.hpp"
namespace nostalgia {
namespace {
/**
* Convert path references to inodes to save space
* @param buff buffer holding file
* @return error
* stub for now
*/
static ox::Error pathToInode(ox::Vector<uint8_t>*) noexcept {
return OxError(0);
}
// just strip header for now...
static ox::Error toMetalClaw(ox::Vector<uint8_t> *buff) noexcept {
auto [mc, err] = ox::stripClawHeader(ox::bit_cast<char*>(buff->data()), buff->size());
oxReturnError(err);
buff->resize(mc.size());
ox_memcpy(buff->data(), mc.data(), mc.size());
return OxError(0);
}
// claw file transformations are broken out because path to inode
// transformations need to be done after the copy to the new FS is complete
static ox::Error transformClaw(ox::FileSystem *dest, ox::String path) noexcept {
// copy
oxTrace("pack::transformClaw") << "path:" << path.c_str();
oxRequire(fileList, dest->ls(path.c_str()));
for (auto i = 0u; i < fileList.size(); ++i) {
auto &name = fileList[i];
auto filePath = path + name;
auto [stat, err] = dest->stat(filePath.c_str());
oxReturnError(err);
if (stat.fileType == ox::FileType_Directory) {
const auto dir = path + name + '/';
oxReturnError(transformClaw(dest, dir));
} else {
// do transforms
if (name.endsWith(".ng") || name.endsWith(".npal")) {
// load file
ox::Vector<uint8_t> buff(stat.size);
oxReturnError(dest->read(filePath.c_str(), buff.data(), buff.size()));
// do transformations
oxReturnError(pathToInode(&buff));
oxReturnError(toMetalClaw(&buff));
// write file to dest
oxReturnError(dest->write(filePath.c_str(), buff.data(), buff.size()));
}
}
}
return OxError(0);
}
static ox::Error verifyFile(ox::FileSystem *fs, const ox::String &path, const ox::Vector<uint8_t> &expected) noexcept {
ox::Vector<uint8_t> buff(expected.size());
oxReturnError(fs->read(path.c_str(), buff.data(), buff.size()));
return OxError(buff == expected ? 0 : 1);
}
struct VerificationPair {
ox::String path;
ox::Vector<uint8_t> buff;
};
static ox::Error copy(ox::FileSystem *src, ox::FileSystem *dest, ox::String path) noexcept {
oxOutf("copying directory: {}\n", path);
ox::Vector<VerificationPair> verificationPairs;
// copy
oxRequire(fileList, src->ls(path.c_str()));
for (auto i = 0u; i < fileList.size(); ++i) {
auto &name = fileList[i];
auto currentFile = path + name;
if (currentFile == "/.nostalgia") {
continue;
}
oxOutf("reading {}\n", name);
auto [stat, err] = src->stat((currentFile).c_str());
oxReturnError(err);
if (stat.fileType == ox::FileType_Directory) {
oxReturnError(dest->mkdir(currentFile.c_str(), true));
oxReturnError(copy(src, dest, currentFile + '/'));
} else {
ox::Vector<uint8_t> buff;
// load file
buff.resize(stat.size);
oxReturnError(src->read(currentFile.c_str(), buff.data(), buff.size()));
// write file to dest
oxOutf("writing {}\n", currentFile);
oxReturnError(dest->write(currentFile.c_str(), buff.data(), buff.size()));
oxReturnError(verifyFile(dest, currentFile, buff));
verificationPairs.push_back({currentFile, buff});
}
}
// verify all at once in addition to right after the files are written
for (auto i = 0u; i < verificationPairs.size(); ++i) {
const auto &v = verificationPairs[i];
oxReturnError(verifyFile(dest, v.path, v.buff));
}
return OxError(0);
}
}
ox::Error pack(ox::FileSystem *src, ox::FileSystem *dest) noexcept {
oxReturnError(copy(src, dest, "/"));
oxReturnError(transformClaw(dest, "/"));
return OxError(0);
}
}
<commit_msg>[nostalgia/tools/pack] Remove unnecessary copies and conversions<commit_after>/*
* Copyright 2016 - 2021 gary@drinkingtea.net
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <ox/claw/read.hpp>
#include "pack.hpp"
namespace nostalgia {
namespace {
/**
* Convert path references to inodes to save space
* @param buff buffer holding file
* @return error
* stub for now
*/
static ox::Error pathToInode(ox::Vector<uint8_t>*) noexcept {
return OxError(0);
}
// just strip header for now...
static ox::Error toMetalClaw(ox::Vector<uint8_t> *buff) noexcept {
auto [mc, err] = ox::stripClawHeader(ox::bit_cast<char*>(buff->data()), buff->size());
oxReturnError(err);
buff->resize(mc.size());
ox_memcpy(buff->data(), mc.data(), mc.size());
return OxError(0);
}
// claw file transformations are broken out because path to inode
// transformations need to be done after the copy to the new FS is complete
static ox::Error transformClaw(ox::FileSystem *dest, const ox::String &path) noexcept {
// copy
oxTracef("pack::transformClaw", "path: {}", path);
oxRequire(fileList, dest->ls(path));
for (auto i = 0u; i < fileList.size(); ++i) {
auto &name = fileList[i];
auto filePath = path + name;
auto [stat, err] = dest->stat(filePath.c_str());
oxReturnError(err);
if (stat.fileType == ox::FileType_Directory) {
const auto dir = path + name + '/';
oxReturnError(transformClaw(dest, dir));
} else {
// do transforms
if (name.endsWith(".ng") || name.endsWith(".npal")) {
// load file
ox::Vector<uint8_t> buff(stat.size);
oxReturnError(dest->read(filePath.c_str(), buff.data(), buff.size()));
// do transformations
oxReturnError(pathToInode(&buff));
oxReturnError(toMetalClaw(&buff));
// write file to dest
oxReturnError(dest->write(filePath.c_str(), buff.data(), buff.size()));
}
}
}
return OxError(0);
}
static ox::Error verifyFile(ox::FileSystem *fs, const ox::String &path, const ox::Vector<uint8_t> &expected) noexcept {
ox::Vector<uint8_t> buff(expected.size());
oxReturnError(fs->read(path.c_str(), buff.data(), buff.size()));
return OxError(buff == expected ? 0 : 1);
}
struct VerificationPair {
ox::String path;
ox::Vector<uint8_t> buff;
};
static ox::Error copy(ox::FileSystem *src, ox::FileSystem *dest, const ox::String &path) noexcept {
oxOutf("copying directory: {}\n", path);
ox::Vector<VerificationPair> verificationPairs;
// copy
oxRequire(fileList, src->ls(path));
for (auto i = 0u; i < fileList.size(); ++i) {
auto &name = fileList[i];
auto currentFile = path + name;
if (currentFile == "/.nostalgia") {
continue;
}
oxOutf("reading {}\n", name);
auto [stat, err] = src->stat((currentFile).c_str());
oxReturnError(err);
if (stat.fileType == ox::FileType_Directory) {
oxReturnError(dest->mkdir(currentFile.c_str(), true));
oxReturnError(copy(src, dest, currentFile + '/'));
} else {
ox::Vector<uint8_t> buff;
// load file
buff.resize(stat.size);
oxReturnError(src->read(currentFile.c_str(), buff.data(), buff.size()));
// write file to dest
oxOutf("writing {}\n", currentFile);
oxReturnError(dest->write(currentFile.c_str(), buff.data(), buff.size()));
oxReturnError(verifyFile(dest, currentFile, buff));
verificationPairs.push_back({currentFile, buff});
}
}
// verify all at once in addition to right after the files are written
for (auto i = 0u; i < verificationPairs.size(); ++i) {
const auto &v = verificationPairs[i];
oxReturnError(verifyFile(dest, v.path, v.buff));
}
return OxError(0);
}
}
ox::Error pack(ox::FileSystem *src, ox::FileSystem *dest) noexcept {
oxReturnError(copy(src, dest, "/"));
oxReturnError(transformClaw(dest, "/"));
return OxError(0);
}
}
<|endoftext|> |
<commit_before>#include <map>
#include <vector>
#include <string>
#include <time.h>
#include "NFComm/NFPluginModule/NFIPluginManager.h"
#include "NFComm/NFCore/NFQueue.h"
#include "NFComm/RapidXML/rapidxml.hpp"
#include "NFComm/RapidXML/rapidxml_iterators.hpp"
#include "NFComm/RapidXML/rapidxml_print.hpp"
#include "NFComm/RapidXML/rapidxml_utils.hpp"
#include "NFComm/NFPluginModule/NFPlatform.h"
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <errno.h>
#if NF_PLATFORM == NF_PLATFORM_WIN
#include <io.h>
#include <windows.h>
#include <conio.h>
#else
#include <iconv.h>
#include <unistd.h>
#include <cstdio>
#include <dirent.h>
#include <sys/stat.h>
#endif
bool GetPluginNameList(std::string& strPlugin, std::vector<std::string>& pluginList, std::string& configPath)
{
rapidxml::file<> fdoc(strPlugin.c_str());
rapidxml::xml_document<> doc;
doc.parse<0>(fdoc.data());
rapidxml::xml_node<>* pRoot = doc.first_node();
for (rapidxml::xml_node<>* pPluginNode = pRoot->first_node("Plugin"); pPluginNode; pPluginNode = pPluginNode->next_sibling("Plugin"))
{
const char* strPluginName = pPluginNode->first_attribute("Name")->value();
const char* strMain = pPluginNode->first_attribute("Main")->value();
pluginList.push_back(std::string(strPluginName));
}
rapidxml::xml_node<>* pPluginAppNode = pRoot->first_node("APPID");
if (!pPluginAppNode)
{
//NFASSERT(0, "There are no App ID", __FILE__, __FUNCTION__);
return false;
}
const char* strAppID = pPluginAppNode->first_attribute("Name")->value();
if (!strAppID)
{
//NFASSERT(0, "There are no App ID", __FILE__, __FUNCTION__);
return false;
}
rapidxml::xml_node<>* pPluginConfigPathNode = pRoot->first_node("ConfigPath");
if (!pPluginConfigPathNode)
{
//NFASSERT(0, "There are no ConfigPath", __FILE__, __FUNCTION__);
return false;
}
if (NULL == pPluginConfigPathNode->first_attribute("Name"))
{
//NFASSERT(0, "There are no ConfigPath.Name", __FILE__, __FUNCTION__);
return false;
}
configPath = pPluginConfigPathNode->first_attribute("Name")->value();
return true;
}
int CopyFile(std::string& SourceFile, std::string& NewFile)
{
ifstream in;
ofstream out;
in.open(SourceFile.c_str(), ios::binary);//Դļ
if (in.fail())//Դļʧ
{
cout << "Error 1: Fail to open the source file." << endl;
in.close();
out.close();
return 0;
}
out.open(NewFile.c_str(), ios::binary);//Ŀļ
if (out.fail())//ļʧ
{
cout << "Error 2: Fail to create the new file." << endl;
out.close();
in.close();
return 0;
}
else//ļ
{
out << in.rdbuf();
out.close();
in.close();
return 1;
}
}
std::vector<std::string> GetFileListInFolder(std::string folderPath, int depth)
{
std::vector<std::string> result;
#if NF_PLATFORM == NF_PLATFORM_WIN
_finddata_t FileInfo;
std::string strfind = folderPath + "\\*";
long long Handle = _findfirst(strfind.c_str(), &FileInfo);
if (Handle == -1L)
{
std::cerr << "can not match the folder path" << std::endl;
exit(-1);
}
do {
//жǷĿ¼
if (FileInfo.attrib & _A_SUBDIR)
{
//Ҫ
if ((strcmp(FileInfo.name, ".") != 0) && (strcmp(FileInfo.name, "..") != 0))
{
std::string newPath = folderPath + "\\" + FileInfo.name;
//dfsFolder(newPath, depth);
auto newResult = GetFileListInFolder(newPath, depth);
result.insert(result.begin(), newResult.begin(), newResult.end());
}
}
else
{
std::string filename = (folderPath + "\\" + FileInfo.name);
result.push_back(filename);
}
} while (_findnext(Handle, &FileInfo) == 0);
_findclose(Handle);
#else
DIR *dp;
struct dirent *entry;
struct stat statbuf;
char absolutepath[512];
if ((dp = opendir(folderPath.c_str())) == NULL) {
fprintf(stderr, "Can`t open directory %s\n", folderPath.c_str());
return result;
}
while ((entry = readdir(dp)) != NULL) {
std::string strEntry = folderPath + entry->d_name;
lstat(strEntry.c_str(), &statbuf);
if (S_ISDIR(statbuf.st_mode)) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
{
continue;
}
std::string childpath = folderPath + "/" + entry->d_name;
auto newResult = GetFileListInFolder(childpath, depth);
result.insert(result.begin(), newResult.begin(), newResult.end());
}
else
{
sprintf(absolutepath, "%s/%s", folderPath.c_str(), entry->d_name);
result.push_back(absolutepath);
}
}
closedir(dp);
sort(result.begin(), result.end());//
#endif
return result;
}
void StringReplace(std::string &strBig, const std::string &strsrc, const std::string &strdst)
{
std::string::size_type pos = 0;
std::string::size_type srclen = strsrc.size();
std::string::size_type dstlen = strdst.size();
while ((pos = strBig.find(strsrc, pos)) != std::string::npos)
{
strBig.replace(pos, srclen, strdst);
pos += dstlen;
}
}
void printResult(int result, std::string& strName)
{
if (result == 1)
{
printf("Copy file: %s success!\n", strName.c_str());
}
else
{
printf("Copy file: %s failed!\n", strName.c_str());
}
}
int main()
{
std::vector<std::string> fileList;
std::vector<std::string> errorFileList;
#if NF_PLATFORM == NF_PLATFORM_WIN
printf("NFAutoCopyDll is Running in Windows...\n");
#else
printf("NFAutoCopyDll is Running in Linux...\n");
#endif
#ifdef NF_DEBUG_MODE
fileList = GetFileListInFolder("../../Debug/", 10);
printf("Debug Mode, And fileList size == %d\n", fileList.size());
#else
fileList = GetFileListInFolder("../../Release/", 10);
printf("Release Mode, And fileList size == %d\n", fileList.size());
#endif
for (auto fileName : fileList)
{
if (fileName.find("Plugin.xml") != std::string::npos)
{
StringReplace(fileName, "\\", "/");
StringReplace(fileName, "//", "/");
printf("Reading xml file: %s\n", fileName.c_str());
std::vector<std::string> pluginList;
std::string configPath = "";
GetPluginNameList(fileName, pluginList, configPath);
if (pluginList.size() > 0 && configPath != "")
{
#if NF_PLATFORM == NF_PLATFORM_WIN
pluginList.push_back("libprotobuf");
pluginList.push_back("NFMessageDefine");
#else
pluginList.push_back("NFMessageDefine");
#endif
pluginList.push_back("NFPluginLoader");
configPath = "../" + configPath;
configPath = fileName.substr(0, fileName.find_last_of("/")) + "/" + configPath;
for (std::string name : pluginList)
{
int result = 0;
if (name == "NFPluginLoader")
{
int result = 0;
#if NF_PLATFORM == NF_PLATFORM_WIN
#ifdef NF_DEBUG_MODE
std::string src = configPath + "Comm/Debug/" + name;
std::string des = fileName.substr(0, fileName.find_last_of("/")) + "/" + name;
auto strSrc = src + "_d.exe";
auto strDes = des + "_d.exe";
auto strSrcPDB = src + "_d.pdb";
auto strDesPDB = des + "_d.pdb";
result = CopyFile(strSrc, strDes);
if (result != 1)
{
errorFileList.push_back(strSrc);
}
printResult(result, strSrc);
result = CopyFile(strSrcPDB, strDesPDB);
if (result != 1)
{
errorFileList.push_back(strSrcPDB);
}
printResult(result, strSrcPDB);
#else
std::string src = configPath + "Comm/Release/" + name;
std::string des = fileName.substr(0, fileName.find_last_of("/")) + "/" + name;
auto strSrc = src + ".exe";
auto strDes = des + ".exe";
int result = 0;
result = CopyFile(strSrc, strDes);
if (result != 1)
{
errorFileList.push_back(strSrc);
}
printResult(result, strSrc);
#endif
#else
std::string src = configPath + "Comm/" + name;
std::string des = fileName.substr(0, fileName.find_last_of("/")) + "/" + name;
auto strSrc = src + "_d";
auto strDes = des + "_d";
result = CopyFile(strSrc, strDes);
if (result != 1)
{
errorFileList.push_back(strSrc);
}
printResult(result, strSrc);
#endif
}
else
{
#if NF_PLATFORM == NF_PLATFORM_WIN
#ifdef NF_DEBUG_MODE
std::string src = configPath + "Comm/Debug/" + name;
std::string des = fileName.substr(0, fileName.find_last_of("/")) + "/" + name;
auto strSrc = src + "_d.dll";
auto strDes = des + "_d.dll";
auto strSrcPDB = src + "_d.pdb";
auto strDesPDB = des + "_d.pdb";
result = CopyFile(strSrc, strDes);
if (result != 1)
{
errorFileList.push_back(strSrc);
}
printResult(result, strSrc);
result = CopyFile(strSrcPDB, strDesPDB);
if (result != 1)
{
errorFileList.push_back(strSrcPDB);
}
printResult(result, strSrcPDB);
#else
std::string src = configPath + "Comm/Release/" + name;
std::string des = fileName.substr(0, fileName.find_last_of("/")) + "/" + name;
auto strSrc = src + ".dll";
auto strDes = des + ".dll";
result = CopyFile(strSrc, strDes);
if (result != 1)
{
errorFileList.push_back(strSrc);
}
printResult(result, strSrc);
#endif
#else
std::string src = configPath + "Comm/lib" + name;
std::string des = fileName.substr(0, fileName.find_last_of("/")) + "/" + name;
auto strSrc = src + "_d.so";
auto strDes = des + "_d.so";
result = CopyFile(strSrc, strDes);
if (result != 1)
{
errorFileList.push_back(strSrc);
}
printResult(result, strSrc);
#endif
}
}
}
}
}
if (errorFileList.size() <= 0)
{
printf("File Copy Done with NO ERROR!\n");
}
else
{
printf("File Copy Done with %d errors as follow:\n", (int)errorFileList.size());
for (auto errFile : errorFileList)
{
printf("\t%s\n", errFile.c_str());
}
}
#if NF_PLATFORM == NF_PLATFORM_WIN
printf("Press any Key to Exit!");
getch();
#else
#endif
return 0;
}<commit_msg>fixed for compile NFAutoCopyDll<commit_after>#include <map>
#include <vector>
#include <string>
#include <time.h>
#include "NFComm/NFPluginModule/NFIPluginManager.h"
#include "NFComm/NFCore/NFQueue.h"
#include "Dependencies/RapidXML/rapidxml.hpp"
#include "Dependencies/RapidXML/rapidxml_iterators.hpp"
#include "Dependencies/RapidXML/rapidxml_print.hpp"
#include "Dependencies/RapidXML/rapidxml_utils.hpp"
#include "NFComm/NFPluginModule/NFPlatform.h"
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <errno.h>
#if NF_PLATFORM == NF_PLATFORM_WIN
#include <io.h>
#include <windows.h>
#include <conio.h>
#else
#include <iconv.h>
#include <unistd.h>
#include <cstdio>
#include <dirent.h>
#include <sys/stat.h>
#endif
bool GetPluginNameList(std::string& strPlugin, std::vector<std::string>& pluginList, std::string& configPath)
{
rapidxml::file<> fdoc(strPlugin.c_str());
rapidxml::xml_document<> doc;
doc.parse<0>(fdoc.data());
rapidxml::xml_node<>* pRoot = doc.first_node();
for (rapidxml::xml_node<>* pPluginNode = pRoot->first_node("Plugin"); pPluginNode; pPluginNode = pPluginNode->next_sibling("Plugin"))
{
const char* strPluginName = pPluginNode->first_attribute("Name")->value();
const char* strMain = pPluginNode->first_attribute("Main")->value();
pluginList.push_back(std::string(strPluginName));
}
rapidxml::xml_node<>* pPluginAppNode = pRoot->first_node("APPID");
if (!pPluginAppNode)
{
//NFASSERT(0, "There are no App ID", __FILE__, __FUNCTION__);
return false;
}
const char* strAppID = pPluginAppNode->first_attribute("Name")->value();
if (!strAppID)
{
//NFASSERT(0, "There are no App ID", __FILE__, __FUNCTION__);
return false;
}
rapidxml::xml_node<>* pPluginConfigPathNode = pRoot->first_node("ConfigPath");
if (!pPluginConfigPathNode)
{
//NFASSERT(0, "There are no ConfigPath", __FILE__, __FUNCTION__);
return false;
}
if (NULL == pPluginConfigPathNode->first_attribute("Name"))
{
//NFASSERT(0, "There are no ConfigPath.Name", __FILE__, __FUNCTION__);
return false;
}
configPath = pPluginConfigPathNode->first_attribute("Name")->value();
return true;
}
int CopyFile(std::string& SourceFile, std::string& NewFile)
{
ifstream in;
ofstream out;
in.open(SourceFile.c_str(), ios::binary);//Դļ
if (in.fail())//Դļʧ
{
cout << "Error 1: Fail to open the source file." << endl;
in.close();
out.close();
return 0;
}
out.open(NewFile.c_str(), ios::binary);//Ŀļ
if (out.fail())//ļʧ
{
cout << "Error 2: Fail to create the new file." << endl;
out.close();
in.close();
return 0;
}
else//ļ
{
out << in.rdbuf();
out.close();
in.close();
return 1;
}
}
std::vector<std::string> GetFileListInFolder(std::string folderPath, int depth)
{
std::vector<std::string> result;
#if NF_PLATFORM == NF_PLATFORM_WIN
_finddata_t FileInfo;
std::string strfind = folderPath + "\\*";
long long Handle = _findfirst(strfind.c_str(), &FileInfo);
if (Handle == -1L)
{
std::cerr << "can not match the folder path" << std::endl;
exit(-1);
}
do {
//жǷĿ¼
if (FileInfo.attrib & _A_SUBDIR)
{
//Ҫ
if ((strcmp(FileInfo.name, ".") != 0) && (strcmp(FileInfo.name, "..") != 0))
{
std::string newPath = folderPath + "\\" + FileInfo.name;
//dfsFolder(newPath, depth);
auto newResult = GetFileListInFolder(newPath, depth);
result.insert(result.begin(), newResult.begin(), newResult.end());
}
}
else
{
std::string filename = (folderPath + "\\" + FileInfo.name);
result.push_back(filename);
}
} while (_findnext(Handle, &FileInfo) == 0);
_findclose(Handle);
#else
DIR *dp;
struct dirent *entry;
struct stat statbuf;
char absolutepath[512];
if ((dp = opendir(folderPath.c_str())) == NULL) {
fprintf(stderr, "Can`t open directory %s\n", folderPath.c_str());
return result;
}
while ((entry = readdir(dp)) != NULL) {
std::string strEntry = folderPath + entry->d_name;
lstat(strEntry.c_str(), &statbuf);
if (S_ISDIR(statbuf.st_mode)) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
{
continue;
}
std::string childpath = folderPath + "/" + entry->d_name;
auto newResult = GetFileListInFolder(childpath, depth);
result.insert(result.begin(), newResult.begin(), newResult.end());
}
else
{
sprintf(absolutepath, "%s/%s", folderPath.c_str(), entry->d_name);
result.push_back(absolutepath);
}
}
closedir(dp);
sort(result.begin(), result.end());//
#endif
return result;
}
void StringReplace(std::string &strBig, const std::string &strsrc, const std::string &strdst)
{
std::string::size_type pos = 0;
std::string::size_type srclen = strsrc.size();
std::string::size_type dstlen = strdst.size();
while ((pos = strBig.find(strsrc, pos)) != std::string::npos)
{
strBig.replace(pos, srclen, strdst);
pos += dstlen;
}
}
void printResult(int result, std::string& strName)
{
if (result == 1)
{
printf("Copy file: %s success!\n", strName.c_str());
}
else
{
printf("Copy file: %s failed!\n", strName.c_str());
}
}
int main()
{
std::vector<std::string> fileList;
std::vector<std::string> errorFileList;
#if NF_PLATFORM == NF_PLATFORM_WIN
printf("NFAutoCopyDll is Running in Windows...\n");
#else
printf("NFAutoCopyDll is Running in Linux...\n");
#endif
#ifdef NF_DEBUG_MODE
fileList = GetFileListInFolder("../../Debug/", 10);
printf("Debug Mode, And fileList size == %d\n", fileList.size());
#else
fileList = GetFileListInFolder("../../Release/", 10);
printf("Release Mode, And fileList size == %d\n", fileList.size());
#endif
for (auto fileName : fileList)
{
if (fileName.find("Plugin.xml") != std::string::npos)
{
StringReplace(fileName, "\\", "/");
StringReplace(fileName, "//", "/");
printf("Reading xml file: %s\n", fileName.c_str());
std::vector<std::string> pluginList;
std::string configPath = "";
GetPluginNameList(fileName, pluginList, configPath);
if (pluginList.size() > 0 && configPath != "")
{
#if NF_PLATFORM == NF_PLATFORM_WIN
pluginList.push_back("libprotobuf");
pluginList.push_back("NFMessageDefine");
#else
pluginList.push_back("NFMessageDefine");
#endif
pluginList.push_back("NFPluginLoader");
configPath = "../" + configPath;
configPath = fileName.substr(0, fileName.find_last_of("/")) + "/" + configPath;
for (std::string name : pluginList)
{
int result = 0;
if (name == "NFPluginLoader")
{
int result = 0;
#if NF_PLATFORM == NF_PLATFORM_WIN
#ifdef NF_DEBUG_MODE
std::string src = configPath + "Comm/Debug/" + name;
std::string des = fileName.substr(0, fileName.find_last_of("/")) + "/" + name;
auto strSrc = src + "_d.exe";
auto strDes = des + "_d.exe";
auto strSrcPDB = src + "_d.pdb";
auto strDesPDB = des + "_d.pdb";
result = CopyFile(strSrc, strDes);
if (result != 1)
{
errorFileList.push_back(strSrc);
}
printResult(result, strSrc);
result = CopyFile(strSrcPDB, strDesPDB);
if (result != 1)
{
errorFileList.push_back(strSrcPDB);
}
printResult(result, strSrcPDB);
#else
std::string src = configPath + "Comm/Release/" + name;
std::string des = fileName.substr(0, fileName.find_last_of("/")) + "/" + name;
auto strSrc = src + ".exe";
auto strDes = des + ".exe";
int result = 0;
result = CopyFile(strSrc, strDes);
if (result != 1)
{
errorFileList.push_back(strSrc);
}
printResult(result, strSrc);
#endif
#else
std::string src = configPath + "Comm/" + name;
std::string des = fileName.substr(0, fileName.find_last_of("/")) + "/" + name;
auto strSrc = src + "_d";
auto strDes = des + "_d";
result = CopyFile(strSrc, strDes);
if (result != 1)
{
errorFileList.push_back(strSrc);
}
printResult(result, strSrc);
#endif
}
else
{
#if NF_PLATFORM == NF_PLATFORM_WIN
#ifdef NF_DEBUG_MODE
std::string src = configPath + "Comm/Debug/" + name;
std::string des = fileName.substr(0, fileName.find_last_of("/")) + "/" + name;
auto strSrc = src + "_d.dll";
auto strDes = des + "_d.dll";
auto strSrcPDB = src + "_d.pdb";
auto strDesPDB = des + "_d.pdb";
result = CopyFile(strSrc, strDes);
if (result != 1)
{
errorFileList.push_back(strSrc);
}
printResult(result, strSrc);
result = CopyFile(strSrcPDB, strDesPDB);
if (result != 1)
{
errorFileList.push_back(strSrcPDB);
}
printResult(result, strSrcPDB);
#else
std::string src = configPath + "Comm/Release/" + name;
std::string des = fileName.substr(0, fileName.find_last_of("/")) + "/" + name;
auto strSrc = src + ".dll";
auto strDes = des + ".dll";
result = CopyFile(strSrc, strDes);
if (result != 1)
{
errorFileList.push_back(strSrc);
}
printResult(result, strSrc);
#endif
#else
std::string src = configPath + "Comm/lib" + name;
std::string des = fileName.substr(0, fileName.find_last_of("/")) + "/" + name;
auto strSrc = src + "_d.so";
auto strDes = des + "_d.so";
result = CopyFile(strSrc, strDes);
if (result != 1)
{
errorFileList.push_back(strSrc);
}
printResult(result, strSrc);
#endif
}
}
}
}
}
if (errorFileList.size() <= 0)
{
printf("File Copy Done with NO ERROR!\n");
}
else
{
printf("File Copy Done with %d errors as follow:\n", (int)errorFileList.size());
for (auto errFile : errorFileList)
{
printf("\t%s\n", errFile.c_str());
}
}
#if NF_PLATFORM == NF_PLATFORM_WIN
printf("Press any Key to Exit!");
getch();
#else
#endif
return 0;
}<|endoftext|> |
<commit_before>#include <sstream>
#include <iostream>
#include <QDir>
#include <QDebug>
#include <QFileInfo>
#include <QEventLoop>
#include <QMutexLocker>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QCoreApplication>
#include "Util.h"
#include "Downloader.h"
#include "DownloadTask.h"
BEGIN_NAMESPACE
Downloader::Downloader(const QUrl &url)
: url{url}, conns{1}, chunks{-1}, chunkSize{-1}, downloadCount{0},
rangeCount{0}, contentLen{0}, offset{0}, confirm{false}, resume{false},
verbose{false}, dryRun{false}, showHeaders{false}, single{true},
resumable{false}, reply{nullptr}
{
connect(&commitThread, &CommitThread::finished,
this, &Downloader::onCommitThreadFinished);
connect(this, &Downloader::chunkToThread,
&commitThread, &CommitThread::enqueueChunk,
Qt::QueuedConnection);
}
void Downloader::setHttpCredentials(const QString &user,
const QString &pass) {
httpUser = user;
httpPass = pass;
}
void Downloader::start() {
// Fetch HEAD to find out the size but also if it exists.
reply = getHead(url);
if (!reply) {
QCoreApplication::exit(-1);
return;
}
url = reply->url();
// Find "Content-Length".
bool ok;
contentLen =
QString::fromUtf8(reply->rawHeader("Content-Length")).toLongLong(&ok);
if (!ok || contentLen == 0) {
qCritical() << "ERROR Invalid content length:" << contentLen;
QCoreApplication::exit(-1);
return;
}
// Check if the total is different than the Content-Length and, if
// so, then change to that number.
if (reply->hasRawHeader("Content-Range")) {
single = false;
QString range = QString::fromUtf8(reply->rawHeader("Content-Range"));
QStringList elms = range.split("/", QString::SkipEmptyParts);
if (elms.size() == 2) {
qint64 tot = elms[1].toLongLong(&ok);
if (ok && tot > 0 && tot != contentLen) {
contentLen = tot;
}
}
}
QString type;
if (reply->hasRawHeader("Content-Type")) {
type = QString::fromUtf8(reply->rawHeader("Content-Type"));
int pos;
if ((pos = type.indexOf(";")) != -1) {
type = type.mid(0, pos);
}
}
// Check if filename is defined.
if (reply->hasRawHeader("Content-Disposition")) {
QString hdr = QString::fromUtf8(reply->rawHeader("Content-Disposition"));
int pos = hdr.indexOf("; filename=");
if (pos != -1) {
hdr = hdr.mid(pos + 11).trimmed();
if (hdr.startsWith("\"")) {
hdr = hdr.mid(1);
}
if (hdr.endsWith("\"")) {
hdr.chop(1);
}
if (!hdr.isEmpty()) {
fileOverride = hdr;
}
}
}
qDebug() << "File size" << qPrintable(Util::formatSize(contentLen, 1))
<< qPrintable(!type.isEmpty() ? "[" + type + "]" : "");
// Check for header "Accept-Ranges" and whether it has "bytes"
// supported.
resumable = false;
if (reply->hasRawHeader("Accept-Ranges")) {
const QString ranges = QString::fromUtf8(reply->rawHeader("Accept-Ranges"));
resumable = ranges.toLower().contains("bytes");
}
if (verbose) {
qDebug() << qPrintable(QString("%1RESUMABLE").
arg(resumable ? "" : "NOT "));
}
if (!resumable && resume) {
qCritical() << "ERROR Cannot resume because server doesn't support it!";
QCoreApplication::exit(-1);
return;
}
// Clean reply.
reply->close();
reply = nullptr;
// If performing a dry run then stop now.
if (dryRun) {
emit finished();
return;
}
if (!setupFile()) {
QCoreApplication::exit(-1);
return;
}
createRanges();
setupThreadPool();
emit information(outputPath, contentLen, rangeCount, conns, offset);
// Start actual download.
download();
}
void Downloader::stop() {
pool.stop();
if (commitThread.isRunning()) {
commitThread.requestInterruption();
commitThread.wait();
}
}
void Downloader::onDownloadTaskFinished(int num, Range range, QByteArray *data) {
QMutexLocker locker{&finishedMutex};
chunksMap[range.first] = data;
downloadCount++;
saveChunk();
emit chunkFinished(num, range);
}
void Downloader::onDownloadTaskFailed(int num, Range range, int httpCode,
QNetworkReply::NetworkError error) {
emit chunkFailed(num, range, httpCode, error);
}
void Downloader::onCommitThreadFinished() {
emit finished();
}
QNetworkReply *Downloader::getHead(const QUrl &url) {
if (verbose) {
qDebug() << "HEAD" << qPrintable(url.toString(QUrl::FullyEncoded));
}
// Emulating a HEAD by doing a GET which only retrieves range
// 0-0. This is necessary because some sites return different
// headers for HEAD/GET even though they should be the same!
QNetworkRequest req{url};
req.setRawHeader("Range", QString("bytes=0-0").toUtf8());
req.setRawHeader("Accept-Encoding", "identity");
if (!httpUser.isEmpty() && !httpPass.isEmpty()) {
req.setRawHeader("Authorization",
Util::createHttpAuthHeader(httpUser, httpPass));
}
//auto *rep = netmgr.head(req);
auto *rep = netmgr.get(req);
QEventLoop loop;
connect(rep, &QNetworkReply::finished, &loop, &QEventLoop::quit);
loop.exec();
if (rep->error() != QNetworkReply::NoError) {
rep->abort();
qCritical() << "ERROR" << qPrintable(Util::getErrorString(rep->error()));
return nullptr;
}
int code = rep->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
if (verbose) {
qDebug() << "CODE" << code;
if (showHeaders) {
qDebug() << "HEADERS"
<< qPrintable(Util::formatHeaders(rep->rawHeaderPairs()));
}
}
static bool didRedir = false;
if (code >= 200 && code < 300) {
if (url != this->url) {
qDebug() << "Resolved to"
<< qPrintable(url.toString(QUrl::FullyEncoded));
}
if (confirm && didRedir) {
if (!Util::askProceed(tr("Do you want to continue?") + " [y/N] ")) {
rep->abort();
qCritical() << "Aborting..";
return nullptr;
}
}
}
// Handle redirect.
else if (code >= 300 && code < 400) {
if (!rep->hasRawHeader("Location")) {
rep->abort();
qCritical() << "ERROR Could not resolve URL!";
return nullptr;
}
QString locHdr = QString::fromUtf8(rep->rawHeader("Location"));
QUrl loc{locHdr};
if (!loc.isValid()) {
rep->abort();
qCritical() << "ERROR Invalid redirection header:"
<< qPrintable(loc.toString(QUrl::FullyEncoded));
return nullptr;
}
// If relative then try resolving with the previous URL.
if (loc.isRelative()) {
loc = url.resolved(loc);
}
if (verbose) {
qDebug() << "REDIRECT" << qPrintable(loc.toString(QUrl::FullyEncoded));
}
didRedir = true;
rep->abort();
rep = getHead(loc);
}
// Client errors.
else if (code >= 400 && code < 500) {
rep->abort();
qDebug() << "CLIENT ERROR";
return nullptr;
}
// Server errors.
else if (code >= 500 && code < 600) {
rep->abort();
qDebug() << "SERVER ERROR";
return nullptr;
}
return rep;
}
bool Downloader::setupFile() {
QFileInfo fi{url.path()};
QDir dir = (outputDir.isEmpty() ? QDir::current() : outputDir);
QString name = (fileOverride.isEmpty() ? fi.fileName() : fileOverride);
outputPath = dir.absoluteFilePath(name);
qDebug() << "Saving to" << qPrintable(outputPath);
auto *file = new QFile{outputPath};
if (file->exists() && !resume) {
if (!QFile::remove(outputPath)) {
qCritical() << "ERROR Could not truncate output file!";
delete file;
return false;
}
}
if (resume) {
qint64 fileSize{file->size()};
if (fileSize >= contentLen) {
qCritical() << "Cannot resume download because the size is larger than or"
<< "equal:" << qPrintable(Util::formatSize(fileSize, 1))
<< "vs." << qPrintable(Util::formatSize(contentLen, 1));
if (confirm &&
!Util::askProceed("Do you want to truncate file and continue? [y/N] ")) {
qCritical() << "Aborting..";
delete file;
return false;
}
if (!confirm) {
qDebug() << "Truncating file";
}
resume = false;
}
else if (fileSize > 0) {
offset = fileSize;
float perc = (long double)offset / (long double)contentLen * 100.0;
qDebug() << "Resuming at offset"
<< qPrintable(Util::formatSize(offset, 1))
<< qPrintable(QString("(%1%)").arg(perc, 0, 'f', 1));
}
}
QIODevice::OpenMode openMode{QIODevice::WriteOnly};
if (resume) {
openMode |= QIODevice::Append;
}
else {
openMode |= QIODevice::Truncate;
}
if (!file->open(openMode)) {
qCritical() << "ERROR Could not open file for writing!";
delete file;
return false;
}
commitThread.setFile(file);
return true;
}
void Downloader::createRanges() {
ranges.clear();
chunksMap.clear();
qint64 size = 1048576;
if (chunkSize != -1) {
size = chunkSize;
}
else if (chunks != -1) {
size = (contentLen - offset) / chunks;
}
else if (conns >= 8) {
size = (contentLen - offset) / conns;
constexpr qint64 MB{10485760}; // 10 MB
if (size > MB) size = MB;
}
// If more than one chunk/connection requested but ranges are not
// supported then fallback to one connection.
if (size < contentLen && single) {
qWarning() << "WARN Ranges not supported!";
qWarning() << "WARN Falling back to single connection!";
conns = 1;
size = contentLen;
}
if (verbose) {
qDebug() << "CHUNK SIZE" << qPrintable(Util::formatSize(size, 1));
}
for (qint64 start = offset; start < contentLen; start += size) {
qint64 end = start + size;
if (end >= contentLen) {
end = contentLen;
}
ranges.enqueue(Range{start, end - 1});
chunksMap[start] = nullptr;
}
rangeCount = ranges.size();
if (verbose) {
qDebug() << "CHUNKS" << rangeCount;
}
}
void Downloader::setupThreadPool() {
// Cap connections to the amount of chunks to download.
if (conns > ranges.size()) {
int old{conns};
conns = ranges.size();
qDebug() << "Connections capped to chunks:" << old << "->" << conns;
}
pool.setMaxThreadCount(conns);
}
void Downloader::download() {
// Fill queue with tasks and start immediately.
int num{1};
while (!ranges.empty()) {
auto range = ranges.dequeue();
auto *task = new DownloadTask{url, range, num++, httpUser, httpPass};
connect(task, SIGNAL(started(int)), SIGNAL(chunkStarted(int)));
connect(task, SIGNAL(progress(int, qint64, qint64)),
SIGNAL(chunkProgress(int, qint64, qint64)));
connect(task, &DownloadTask::finished,
this, &Downloader::onDownloadTaskFinished);
connect(task, &DownloadTask::failed,
this, &Downloader::onDownloadTaskFailed);
pool.start(task);
}
}
void Downloader::saveChunk() {
// Lock on chunks map is required to be acquired going into this
// method!
if (chunksMap.isEmpty()) {
// Wait for commit thread to be done.
return;
}
auto key = chunksMap.firstKey();
const auto *value = chunksMap[key];
if (value != nullptr) {
emit chunkToThread(value, chunksMap.size() == 1);
if (!commitThread.isRunning()) {
commitThread.start();
}
chunksMap.remove(key);
}
// If everything has been downloaded then call method again.
if (rangeCount == downloadCount) {
saveChunk();
}
}
END_NAMESPACE
<commit_msg>#5: Also fallback if -c arg >1 and ranges not supported.<commit_after>#include <sstream>
#include <iostream>
#include <QDir>
#include <QDebug>
#include <QFileInfo>
#include <QEventLoop>
#include <QMutexLocker>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QCoreApplication>
#include "Util.h"
#include "Downloader.h"
#include "DownloadTask.h"
BEGIN_NAMESPACE
Downloader::Downloader(const QUrl &url)
: url{url}, conns{1}, chunks{-1}, chunkSize{-1}, downloadCount{0},
rangeCount{0}, contentLen{0}, offset{0}, confirm{false}, resume{false},
verbose{false}, dryRun{false}, showHeaders{false}, single{true},
resumable{false}, reply{nullptr}
{
connect(&commitThread, &CommitThread::finished,
this, &Downloader::onCommitThreadFinished);
connect(this, &Downloader::chunkToThread,
&commitThread, &CommitThread::enqueueChunk,
Qt::QueuedConnection);
}
void Downloader::setHttpCredentials(const QString &user,
const QString &pass) {
httpUser = user;
httpPass = pass;
}
void Downloader::start() {
// Fetch HEAD to find out the size but also if it exists.
reply = getHead(url);
if (!reply) {
QCoreApplication::exit(-1);
return;
}
url = reply->url();
// Find "Content-Length".
bool ok;
contentLen =
QString::fromUtf8(reply->rawHeader("Content-Length")).toLongLong(&ok);
if (!ok || contentLen == 0) {
qCritical() << "ERROR Invalid content length:" << contentLen;
QCoreApplication::exit(-1);
return;
}
// Check if the total is different than the Content-Length and, if
// so, then change to that number.
if (reply->hasRawHeader("Content-Range")) {
single = false;
QString range = QString::fromUtf8(reply->rawHeader("Content-Range"));
QStringList elms = range.split("/", QString::SkipEmptyParts);
if (elms.size() == 2) {
qint64 tot = elms[1].toLongLong(&ok);
if (ok && tot > 0 && tot != contentLen) {
contentLen = tot;
}
}
}
QString type;
if (reply->hasRawHeader("Content-Type")) {
type = QString::fromUtf8(reply->rawHeader("Content-Type"));
int pos;
if ((pos = type.indexOf(";")) != -1) {
type = type.mid(0, pos);
}
}
// Check if filename is defined.
if (reply->hasRawHeader("Content-Disposition")) {
QString hdr = QString::fromUtf8(reply->rawHeader("Content-Disposition"));
int pos = hdr.indexOf("; filename=");
if (pos != -1) {
hdr = hdr.mid(pos + 11).trimmed();
if (hdr.startsWith("\"")) {
hdr = hdr.mid(1);
}
if (hdr.endsWith("\"")) {
hdr.chop(1);
}
if (!hdr.isEmpty()) {
fileOverride = hdr;
}
}
}
qDebug() << "File size" << qPrintable(Util::formatSize(contentLen, 1))
<< qPrintable(!type.isEmpty() ? "[" + type + "]" : "");
// Check for header "Accept-Ranges" and whether it has "bytes"
// supported.
resumable = false;
if (reply->hasRawHeader("Accept-Ranges")) {
const QString ranges = QString::fromUtf8(reply->rawHeader("Accept-Ranges"));
resumable = ranges.toLower().contains("bytes");
}
if (verbose) {
qDebug() << qPrintable(QString("%1RESUMABLE").
arg(resumable ? "" : "NOT "));
}
if (!resumable && resume) {
qCritical() << "ERROR Cannot resume because server doesn't support it!";
QCoreApplication::exit(-1);
return;
}
// Clean reply.
reply->close();
reply = nullptr;
// If performing a dry run then stop now.
if (dryRun) {
emit finished();
return;
}
if (!setupFile()) {
QCoreApplication::exit(-1);
return;
}
createRanges();
setupThreadPool();
emit information(outputPath, contentLen, rangeCount, conns, offset);
// Start actual download.
download();
}
void Downloader::stop() {
pool.stop();
if (commitThread.isRunning()) {
commitThread.requestInterruption();
commitThread.wait();
}
}
void Downloader::onDownloadTaskFinished(int num, Range range, QByteArray *data) {
QMutexLocker locker{&finishedMutex};
chunksMap[range.first] = data;
downloadCount++;
saveChunk();
emit chunkFinished(num, range);
}
void Downloader::onDownloadTaskFailed(int num, Range range, int httpCode,
QNetworkReply::NetworkError error) {
emit chunkFailed(num, range, httpCode, error);
}
void Downloader::onCommitThreadFinished() {
emit finished();
}
QNetworkReply *Downloader::getHead(const QUrl &url) {
if (verbose) {
qDebug() << "HEAD" << qPrintable(url.toString(QUrl::FullyEncoded));
}
// Emulating a HEAD by doing a GET which only retrieves range
// 0-0. This is necessary because some sites return different
// headers for HEAD/GET even though they should be the same!
QNetworkRequest req{url};
req.setRawHeader("Range", QString("bytes=0-0").toUtf8());
req.setRawHeader("Accept-Encoding", "identity");
if (!httpUser.isEmpty() && !httpPass.isEmpty()) {
req.setRawHeader("Authorization",
Util::createHttpAuthHeader(httpUser, httpPass));
}
//auto *rep = netmgr.head(req);
auto *rep = netmgr.get(req);
QEventLoop loop;
connect(rep, &QNetworkReply::finished, &loop, &QEventLoop::quit);
loop.exec();
if (rep->error() != QNetworkReply::NoError) {
rep->abort();
qCritical() << "ERROR" << qPrintable(Util::getErrorString(rep->error()));
return nullptr;
}
int code = rep->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
if (verbose) {
qDebug() << "CODE" << code;
if (showHeaders) {
qDebug() << "HEADERS"
<< qPrintable(Util::formatHeaders(rep->rawHeaderPairs()));
}
}
static bool didRedir = false;
if (code >= 200 && code < 300) {
if (url != this->url) {
qDebug() << "Resolved to"
<< qPrintable(url.toString(QUrl::FullyEncoded));
}
if (confirm && didRedir) {
if (!Util::askProceed(tr("Do you want to continue?") + " [y/N] ")) {
rep->abort();
qCritical() << "Aborting..";
return nullptr;
}
}
}
// Handle redirect.
else if (code >= 300 && code < 400) {
if (!rep->hasRawHeader("Location")) {
rep->abort();
qCritical() << "ERROR Could not resolve URL!";
return nullptr;
}
QString locHdr = QString::fromUtf8(rep->rawHeader("Location"));
QUrl loc{locHdr};
if (!loc.isValid()) {
rep->abort();
qCritical() << "ERROR Invalid redirection header:"
<< qPrintable(loc.toString(QUrl::FullyEncoded));
return nullptr;
}
// If relative then try resolving with the previous URL.
if (loc.isRelative()) {
loc = url.resolved(loc);
}
if (verbose) {
qDebug() << "REDIRECT" << qPrintable(loc.toString(QUrl::FullyEncoded));
}
didRedir = true;
rep->abort();
rep = getHead(loc);
}
// Client errors.
else if (code >= 400 && code < 500) {
rep->abort();
qDebug() << "CLIENT ERROR";
return nullptr;
}
// Server errors.
else if (code >= 500 && code < 600) {
rep->abort();
qDebug() << "SERVER ERROR";
return nullptr;
}
return rep;
}
bool Downloader::setupFile() {
QFileInfo fi{url.path()};
QDir dir = (outputDir.isEmpty() ? QDir::current() : outputDir);
QString name = (fileOverride.isEmpty() ? fi.fileName() : fileOverride);
outputPath = dir.absoluteFilePath(name);
qDebug() << "Saving to" << qPrintable(outputPath);
auto *file = new QFile{outputPath};
if (file->exists() && !resume) {
if (!QFile::remove(outputPath)) {
qCritical() << "ERROR Could not truncate output file!";
delete file;
return false;
}
}
if (resume) {
qint64 fileSize{file->size()};
if (fileSize >= contentLen) {
qCritical() << "Cannot resume download because the size is larger than or"
<< "equal:" << qPrintable(Util::formatSize(fileSize, 1))
<< "vs." << qPrintable(Util::formatSize(contentLen, 1));
if (confirm &&
!Util::askProceed("Do you want to truncate file and continue? [y/N] ")) {
qCritical() << "Aborting..";
delete file;
return false;
}
if (!confirm) {
qDebug() << "Truncating file";
}
resume = false;
}
else if (fileSize > 0) {
offset = fileSize;
float perc = (long double)offset / (long double)contentLen * 100.0;
qDebug() << "Resuming at offset"
<< qPrintable(Util::formatSize(offset, 1))
<< qPrintable(QString("(%1%)").arg(perc, 0, 'f', 1));
}
}
QIODevice::OpenMode openMode{QIODevice::WriteOnly};
if (resume) {
openMode |= QIODevice::Append;
}
else {
openMode |= QIODevice::Truncate;
}
if (!file->open(openMode)) {
qCritical() << "ERROR Could not open file for writing!";
delete file;
return false;
}
commitThread.setFile(file);
return true;
}
void Downloader::createRanges() {
ranges.clear();
chunksMap.clear();
qint64 size = 1048576;
if (chunkSize != -1) {
size = chunkSize;
}
else if (chunks != -1) {
size = (contentLen - offset) / chunks;
}
else if (conns >= 8) {
size = (contentLen - offset) / conns;
constexpr qint64 MB{10485760}; // 10 MB
if (size > MB) size = MB;
}
// If more than one chunk/connection requested but ranges are not
// supported then fallback to one connection.
if (single && (conns > 1 || size < contentLen)) {
qWarning() << "WARN Ranges not supported!";
qWarning() << "WARN Falling back to single connection!";
conns = 1;
size = contentLen;
}
if (verbose) {
qDebug() << "CHUNK SIZE" << qPrintable(Util::formatSize(size, 1));
}
for (qint64 start = offset; start < contentLen; start += size) {
qint64 end = start + size;
if (end >= contentLen) {
end = contentLen;
}
ranges.enqueue(Range{start, end - 1});
chunksMap[start] = nullptr;
}
rangeCount = ranges.size();
if (verbose) {
qDebug() << "CHUNKS" << rangeCount;
}
}
void Downloader::setupThreadPool() {
// Cap connections to the amount of chunks to download.
if (conns > ranges.size()) {
int old{conns};
conns = ranges.size();
qDebug() << "Connections capped to chunks:" << old << "->" << conns;
}
pool.setMaxThreadCount(conns);
}
void Downloader::download() {
// Fill queue with tasks and start immediately.
int num{1};
while (!ranges.empty()) {
auto range = ranges.dequeue();
auto *task = new DownloadTask{url, range, num++, httpUser, httpPass};
connect(task, SIGNAL(started(int)), SIGNAL(chunkStarted(int)));
connect(task, SIGNAL(progress(int, qint64, qint64)),
SIGNAL(chunkProgress(int, qint64, qint64)));
connect(task, &DownloadTask::finished,
this, &Downloader::onDownloadTaskFinished);
connect(task, &DownloadTask::failed,
this, &Downloader::onDownloadTaskFailed);
pool.start(task);
}
}
void Downloader::saveChunk() {
// Lock on chunks map is required to be acquired going into this
// method!
if (chunksMap.isEmpty()) {
// Wait for commit thread to be done.
return;
}
auto key = chunksMap.firstKey();
const auto *value = chunksMap[key];
if (value != nullptr) {
emit chunkToThread(value, chunksMap.size() == 1);
if (!commitThread.isRunning()) {
commitThread.start();
}
chunksMap.remove(key);
}
// If everything has been downloaded then call method again.
if (rangeCount == downloadCount) {
saveChunk();
}
}
END_NAMESPACE
<|endoftext|> |
<commit_before>/**
* Appcelerator Kroll - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.
*/
#include "../utils.h"
namespace UTILS_NS
{
namespace Win32Utils
{
std::string QuickFormatMessage(DWORD errorCode, DWORD flags)
{
std::string result;
LPWSTR errorText = NULL;
FormatMessageW(
flags,
NULL, // unused with FORMAT_MESSAGE_FROM_SYSTEM
errorCode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPWSTR) &errorText,
0, // minimum size for output buffer
NULL);
if (errorText)
{
result = WideToUTF8(errorText);
LocalFree(errorText);
}
return result;
}
}
std::wstring MultiByteToWide(const std::string& in, UINT codePage)
{
return MultiByteToWide(in.c_str(), in.size(), codePage);
}
std::wstring MultiByteToWide(const char* in, size_t size, UINT codePage)
{
if (size == 0)
return L"";
wchar_t* buffer = new wchar_t[size + 1];
buffer[size] = '\0';
MultiByteToWideChar(codePage, 0, in, -1, buffer, (int) size);
std::wstring out(buffer);
delete [] buffer;
return out;
}
std::string WideToMultiByte(const std::wstring& in, UINT codePage)
{
return WideToMultiByte(in.c_str(), in.size(), codePage);
}
std::string WideToMultiByte(const wchar_t* in, size_t size, UINT codePage)
{
if (size == 0)
return "";
int bufferSize = (4 * size) + 1;
char* buffer = new char[4 * size + 1];
buffer[4 * size] = '\0';
WideCharToMultiByte(codePage, 0, in, -1, buffer, (int) (bufferSize - 1), NULL, NULL);
std::string out(buffer);
delete [] buffer;
return out;
}
std::string MultiByteToMultiByte(const std::string& in, UINT codePageIn, UINT codePageOut)
{
std::wstring wideString(MultiByteToWide(in, codePageIn));
return WideToMultiByte(wideString, codePageOut);
}
std::wstring UTF8ToWide(const std::string& in)
{
return MultiByteToWide(in.c_str(), CP_UTF8);
}
std::wstring UTF8ToWide(const char *in)
{
return MultiByteToWide(in, CP_UTF8);
}
std::string WideToUTF8(const std::wstring& in)
{
return WideToUTF8(in.c_str());
}
std::string WideToUTF8(const wchar_t* in)
{
return WideToMultiByte(in, CP_UTF8);
}
}
<commit_msg>Fix build warning for Win32.<commit_after>/**
* Appcelerator Kroll - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.
*/
#include "../utils.h"
namespace UTILS_NS
{
namespace Win32Utils
{
std::string QuickFormatMessage(DWORD errorCode, DWORD flags)
{
std::string result;
LPWSTR errorText = NULL;
FormatMessageW(
flags,
NULL, // unused with FORMAT_MESSAGE_FROM_SYSTEM
errorCode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPWSTR) &errorText,
0, // minimum size for output buffer
NULL);
if (errorText)
{
result = WideToUTF8(errorText);
LocalFree(errorText);
}
return result;
}
}
std::wstring MultiByteToWide(const std::string& in, UINT codePage)
{
return MultiByteToWide(in.c_str(), in.size(), codePage);
}
std::wstring MultiByteToWide(const char* in, size_t size, UINT codePage)
{
if (size == 0)
return L"";
wchar_t* buffer = new wchar_t[size + 1];
buffer[size] = '\0';
MultiByteToWideChar(codePage, 0, in, -1, buffer, (int) size);
std::wstring out(buffer);
delete [] buffer;
return out;
}
std::string WideToMultiByte(const std::wstring& in, UINT codePage)
{
return WideToMultiByte(in.c_str(), in.size(), codePage);
}
std::string WideToMultiByte(const wchar_t* in, size_t size, UINT codePage)
{
if (size == 0)
return "";
size_t bufferSize = (4 * size) + 1;
char* buffer = new char[4 * size + 1];
buffer[4 * size] = '\0';
WideCharToMultiByte(codePage, 0, in, -1, buffer, static_cast<int>(bufferSize - 1), NULL, NULL);
std::string out(buffer);
delete [] buffer;
return out;
}
std::string MultiByteToMultiByte(const std::string& in, UINT codePageIn, UINT codePageOut)
{
std::wstring wideString(MultiByteToWide(in, codePageIn));
return WideToMultiByte(wideString, codePageOut);
}
std::wstring UTF8ToWide(const std::string& in)
{
return MultiByteToWide(in.c_str(), CP_UTF8);
}
std::wstring UTF8ToWide(const char *in)
{
return MultiByteToWide(in, CP_UTF8);
}
std::string WideToUTF8(const std::wstring& in)
{
return WideToUTF8(in.c_str());
}
std::string WideToUTF8(const wchar_t* in)
{
return WideToMultiByte(in, CP_UTF8);
}
}
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
// STL
#include <complex>
#include <vector>
#include <array>
#include <algorithm> //For value_testable
#include <iosfwd> //For stream support
#include <type_traits> //For static assertions tests
#include <tuple> //For TMP stuff
#include <thread>
// cpp_utils
#include "cpp_utils/compat.hpp"
#include "cpp_utils/tmp.hpp"
#include "cpp_utils/likely.hpp"
#include "cpp_utils/assert.hpp"
#include "cpp_utils/parallel.hpp"
// Macro to handle noexcept and cpp_assert
namespace etl {
#ifdef NDEBUG
constexpr bool assert_nothrow = true;
#else
#ifdef CPP_UTILS_ASSERT_EXCEPTION
constexpr bool assert_nothrow = false;
#else
constexpr bool assert_nothrow = true;
#endif
#endif
/*!
* \brief Alignment flag to aligned expressions
*
* This can be used to make expressions more clear.
*/
constexpr bool aligned = false;
/*!
* \brief Alignment flag to unaligned expressions.
*
* This can be used to make expressions more clear.
*/
constexpr bool unaligned = false;
/*!
* \brief The current major version number of the library
*/
constexpr size_t version_major = 1;
/*!
* \brief The current minor version number of the library
*/
constexpr size_t version_minor = 1;
/*!
* \brief The current revision version number of the library
*/
constexpr size_t version_revision = 0;
} //end of namespace etl
/*!
* \brief String representation of the current version of the library.
*/
#define ETL_VERSION_STR "1.1"
/*!
* \brief The current major version number of the library
*/
#define ETL_VERSION_MAJOR 1
/*!
* \brief The current minor version number of the library
*/
#define ETL_VERSION_MINOR 1
/*!
* \brief The current revision version number of the library
*/
#define ETL_VERSION_REVISION 0
<commit_msg>Update version<commit_after>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
// STL
#include <complex>
#include <vector>
#include <array>
#include <algorithm> //For value_testable
#include <iosfwd> //For stream support
#include <type_traits> //For static assertions tests
#include <tuple> //For TMP stuff
#include <thread>
// cpp_utils
#include "cpp_utils/compat.hpp"
#include "cpp_utils/tmp.hpp"
#include "cpp_utils/likely.hpp"
#include "cpp_utils/assert.hpp"
#include "cpp_utils/parallel.hpp"
// Macro to handle noexcept and cpp_assert
namespace etl {
#ifdef NDEBUG
constexpr bool assert_nothrow = true;
#else
#ifdef CPP_UTILS_ASSERT_EXCEPTION
constexpr bool assert_nothrow = false;
#else
constexpr bool assert_nothrow = true;
#endif
#endif
/*!
* \brief Alignment flag to aligned expressions
*
* This can be used to make expressions more clear.
*/
constexpr bool aligned = false;
/*!
* \brief Alignment flag to unaligned expressions.
*
* This can be used to make expressions more clear.
*/
constexpr bool unaligned = false;
/*!
* \brief The current major version number of the library
*/
constexpr size_t version_major = 1;
/*!
* \brief The current minor version number of the library
*/
constexpr size_t version_minor = 2;
/*!
* \brief The current revision version number of the library
*/
constexpr size_t version_revision = 0;
} //end of namespace etl
/*!
* \brief String representation of the current version of the library.
*/
#define ETL_VERSION_STR "1.2"
/*!
* \brief The current major version number of the library
*/
#define ETL_VERSION_MAJOR 1
/*!
* \brief The current minor version number of the library
*/
#define ETL_VERSION_MINOR 2
/*!
* \brief The current revision version number of the library
*/
#define ETL_VERSION_REVISION 0
<|endoftext|> |
<commit_before>/* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2017, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero Public License for more details.
*
* You should have received a copy of the GNU Affero Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ---------------------------------------------------------------------
*/
#ifndef NUPIC_UTIL_SLIDING_WINDOW_HPP
#define NUPIC_UTIL_SLIDING_WINDOW_HPP
#include <vector>
#include <algorithm>
#include <iterator>
#include <cmath>
#include <string>
#include <nupic/types/Types.hpp>
#include <nupic/utils/Log.hpp>
#include <nupic/math/Math.hpp> //for macro ASSERT_INPUT_ITERATOR
namespace nupic {
namespace util {
template<class T>
class SlidingWindow {
public:
SlidingWindow(UInt maxCapacity, std::string id="SlidingWindow", int debug=0) :
maxCapacity(maxCapacity),
ID(id),
DEBUG(debug)
{
buffer_.reserve(maxCapacity);
idxNext_ = 0;
}
template<class IteratorT>
SlidingWindow(UInt maxCapacity, IteratorT initialData_begin,
IteratorT initialData_end, std::string id="SlidingWindow", int debug=0):
SlidingWindow(maxCapacity, id, debug) {
// Assert that It obeys the STL forward iterator concept
ASSERT_INPUT_ITERATOR(IteratorT);
for(IteratorT it = initialData_begin; it != initialData_end; ++it) {
append(*it);
}
}
size_t size() const {
NTA_ASSERT(buffer_.size() <= maxCapacity);
return buffer_.size();
}
/** append new value to the end of the buffer and handle the
"overflows"-may pop the oldest element if full.
*/
void append(T newValue) {
if(size() < maxCapacity) {
buffer_.push_back(newValue);
} else {
buffer_[idxNext_] = newValue;
}
idxNext_ = (idxNext_ +1 ) %maxCapacity;
}
/** like append, but return the dropped value if it was dropped.
:param T newValue - new value to append to the sliding window
:param T* - a return pass-by-value with the removed element,
if this function returns false, this value will remain unchanged.
:return bool if some value has been dropped (and updated as
droppedValue)
*/
bool append(T newValue, T* droppedValue) {
//only in this case we drop oldest; this happens always after
//first maxCap steps ; must be checked before append()
const bool isFull = (buffer_.size()==maxCapacity);
if(isFull) {
*droppedValue = buffer_[idxNext_];
}
append(newValue);
return isFull;
}
/**
:return unordered content (data ) of this sl. window;
call getLinearizedData() if you need them oredered from
oldest->newest
This direct access method is fast.
*/
const std::vector<T>& getData() const {
return buffer_;
}
/** linearize method for the internal buffer; this is slower than
the pure getData() but ensures that the data are ordered (oldest at
the beginning, newest at the end of the vector
This handles case of |5,6;1,2,3,4| => |1,2,3,4,5,6|
:return new linearized vector
*/
std::vector<T> getLinearizedData() const {
std::vector<T> lin;
lin.reserve(buffer_.size());
//insert the "older" part at the beginning
lin.insert(std::begin(lin), std::begin(buffer_) + idxNext_, std::end(buffer_));
//append the "newer" part to the end of the constructed vect
lin.insert(std::end(lin), std::begin(buffer_), std::begin(buffer_) + idxNext_);
return lin;
}
bool operator==(const SlidingWindow& r2) const {
const bool sameSizes = (this->size() == r2.size()) && (this->maxCapacity == r2.maxCapacity);
return sameSizes && std::equal(this->buffer_.cbegin(), this->buffer_.cend(), r2.getData().cbegin()); //also content must be same
}
bool operator!=(const SlidingWindow& r2) const {
return !operator==(r2);
}
/** operator[] provides fast access to the elements indexed relatively
to the oldest element. So slidingWindow[0] returns oldest element,
slidingWindow[size()] returns the newest.
:param UInt index - index/offset from the oldest element, values 0..size()
:return T - i-th oldest value in the buffer
:throws 0<=index<=size()
*/
T& operator[](UInt index) {
NTA_ASSERT(index <= size());
NTA_ASSERT(size() > 0);
//get last updated position, "current"+index(offset)
//avoid calling getLinearizeData() as it involves copy()
if (size() == maxCapacity) {
return &buffer_[(idxNext_ + index) % maxCapacity];
} else {
return &buffer_[index];
}
}
const T& operator[](UInt index) const {
return this->operator[](index); //call the overloaded operator[] above
}
std::ostream& operator<<(std::ostream& os) {
return os << ID << std::endl;
}
public:
const UInt maxCapacity;
const std::string ID; //name of this object
const int DEBUG;
private:
std::vector<T> buffer_;
UInt idxNext_;
};
}} //end ns
#endif //header
<commit_msg>SlidingWindow: rev: fix op==<commit_after>/* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2017, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero Public License for more details.
*
* You should have received a copy of the GNU Affero Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ---------------------------------------------------------------------
*/
#ifndef NUPIC_UTIL_SLIDING_WINDOW_HPP
#define NUPIC_UTIL_SLIDING_WINDOW_HPP
#include <vector>
#include <algorithm>
#include <iterator>
#include <cmath>
#include <string>
#include <nupic/types/Types.hpp>
#include <nupic/utils/Log.hpp>
#include <nupic/math/Math.hpp> //for macro ASSERT_INPUT_ITERATOR
namespace nupic {
namespace util {
template<class T>
class SlidingWindow {
public:
SlidingWindow(UInt maxCapacity, std::string id="SlidingWindow", int debug=0) :
maxCapacity(maxCapacity),
ID(id),
DEBUG(debug)
{
buffer_.reserve(maxCapacity);
idxNext_ = 0;
}
template<class IteratorT>
SlidingWindow(UInt maxCapacity, IteratorT initialData_begin,
IteratorT initialData_end, std::string id="SlidingWindow", int debug=0):
SlidingWindow(maxCapacity, id, debug) {
// Assert that It obeys the STL forward iterator concept
ASSERT_INPUT_ITERATOR(IteratorT);
for(IteratorT it = initialData_begin; it != initialData_end; ++it) {
append(*it);
}
}
size_t size() const {
NTA_ASSERT(buffer_.size() <= maxCapacity);
return buffer_.size();
}
/** append new value to the end of the buffer and handle the
"overflows"-may pop the oldest element if full.
*/
void append(T newValue) {
if(size() < maxCapacity) {
buffer_.push_back(newValue);
} else {
buffer_[idxNext_] = newValue;
}
idxNext_ = (idxNext_ +1 ) %maxCapacity;
}
/** like append, but return the dropped value if it was dropped.
:param T newValue - new value to append to the sliding window
:param T* - a return pass-by-value with the removed element,
if this function returns false, this value will remain unchanged.
:return bool if some value has been dropped (and updated as
droppedValue)
*/
bool append(T newValue, T* droppedValue) {
//only in this case we drop oldest; this happens always after
//first maxCap steps ; must be checked before append()
const bool isFull = (buffer_.size()==maxCapacity);
if(isFull) {
*droppedValue = buffer_[idxNext_];
}
append(newValue);
return isFull;
}
/**
:return unordered content (data ) of this sl. window;
call getLinearizedData() if you need them oredered from
oldest->newest
This direct access method is fast.
*/
const std::vector<T>& getData() const {
return buffer_;
}
/** linearize method for the internal buffer; this is slower than
the pure getData() but ensures that the data are ordered (oldest at
the beginning, newest at the end of the vector
This handles case of |5,6;1,2,3,4| => |1,2,3,4,5,6|
:return new linearized vector
*/
std::vector<T> getLinearizedData() const {
std::vector<T> lin;
lin.reserve(buffer_.size());
//insert the "older" part at the beginning
lin.insert(std::begin(lin), std::begin(buffer_) + idxNext_, std::end(buffer_));
//append the "newer" part to the end of the constructed vect
lin.insert(std::end(lin), std::begin(buffer_), std::begin(buffer_) + idxNext_);
return lin;
}
bool operator==(const SlidingWindow& r2) const {
const bool sameSizes = (this->size() == r2.size()) && (this->maxCapacity == r2.maxCapacity);
if(!sameSizes) return false;
const std::vector<T> v1 = this->getLinearizedData();
const std::vector<T> v2 = r2.getLinearizedData();
return sameSizes && std::equal(v1.cbegin(), v1.cend(), v2.cbegin()); //also content must be same
}
bool operator!=(const SlidingWindow& r2) const {
return !operator==(r2);
}
/** operator[] provides fast access to the elements indexed relatively
to the oldest element. So slidingWindow[0] returns oldest element,
slidingWindow[size()] returns the newest.
:param UInt index - index/offset from the oldest element, values 0..size()
:return T - i-th oldest value in the buffer
:throws 0<=index<=size()
*/
T& operator[](UInt index) {
NTA_ASSERT(index <= size());
NTA_ASSERT(size() > 0);
//get last updated position, "current"+index(offset)
//avoid calling getLinearizeData() as it involves copy()
if (size() == maxCapacity) {
return &buffer_[(idxNext_ + index) % maxCapacity];
} else {
return &buffer_[index];
}
}
const T& operator[](UInt index) const {
return this->operator[](index); //call the overloaded operator[] above
}
std::ostream& operator<<(std::ostream& os) {
return os << ID << std::endl;
}
public:
const UInt maxCapacity;
const std::string ID; //name of this object
const int DEBUG;
private:
std::vector<T> buffer_;
UInt idxNext_;
};
}} //end ns
#endif //header
<|endoftext|> |
<commit_before>/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkTileGrid.h"
SkTileGrid::SkTileGrid(int xTiles, int yTiles, const SkTileGridFactory::TileGridInfo& info)
: fXTiles(xTiles)
, fYTiles(yTiles)
, fInfo(info)
, fCount(0)
, fTiles(SkNEW_ARRAY(SkTDArray<Entry>, xTiles * yTiles)) {
// Margin is offset by 1 as a provision for AA and
// to cancel-out the outset applied by getClipDeviceBounds.
fInfo.fMargin.fHeight++;
fInfo.fMargin.fWidth++;
}
SkTileGrid::~SkTileGrid() {
SkDELETE_ARRAY(fTiles);
}
void SkTileGrid::insert(void* data, const SkRect& fbounds, bool) {
SkASSERT(!fbounds.isEmpty());
SkIRect dilatedBounds;
if (fbounds.isLargest()) {
// Dilating the largest SkIRect will overflow. Other nearly-largest rects may overflow too,
// but we don't make active use of them like we do the largest.
dilatedBounds.setLargest();
} else {
fbounds.roundOut(&dilatedBounds);
dilatedBounds.outset(fInfo.fMargin.width(), fInfo.fMargin.height());
dilatedBounds.offset(fInfo.fOffset);
}
const SkIRect gridBounds =
{ 0, 0, fInfo.fTileInterval.width() * fXTiles, fInfo.fTileInterval.height() * fYTiles };
if (!SkIRect::Intersects(dilatedBounds, gridBounds)) {
return;
}
// Note: SkIRects are non-inclusive of the right() column and bottom() row,
// hence the "-1"s in the computations of maxX and maxY.
int minX = SkMax32(0, SkMin32(dilatedBounds.left() / fInfo.fTileInterval.width(), fXTiles - 1));
int minY = SkMax32(0, SkMin32(dilatedBounds.top() / fInfo.fTileInterval.height(), fYTiles - 1));
int maxX = SkMax32(0, SkMin32((dilatedBounds.right() - 1) / fInfo.fTileInterval.width(),
fXTiles - 1));
int maxY = SkMax32(0, SkMin32((dilatedBounds.bottom() - 1) / fInfo.fTileInterval.height(),
fYTiles - 1));
Entry entry = { fCount++, data };
for (int x = minX; x <= maxX; x++) {
for (int y = minY; y <= maxY; y++) {
fTiles[y * fXTiles + x].push(entry);
}
}
}
static int divide_ceil(int x, int y) {
return (x + y - 1) / y;
}
// Number of tiles for which data is allocated on the stack in
// SkTileGrid::search. If malloc becomes a bottleneck, we may consider
// increasing this number. Typical large web page, say 2k x 16k, would
// require 512 tiles of size 256 x 256 pixels.
static const int kStackAllocationTileCount = 1024;
void SkTileGrid::search(const SkRect& query, SkTDArray<void*>* results) const {
SkIRect adjusted;
query.roundOut(&adjusted);
// The inset is to counteract the outset that was applied in 'insert'
// The outset/inset is to optimize for lookups of size
// 'tileInterval + 2 * margin' that are aligned with the tile grid.
adjusted.inset(fInfo.fMargin.width(), fInfo.fMargin.height());
adjusted.offset(fInfo.fOffset);
adjusted.sort(); // in case the inset inverted the rectangle
// Convert the query rectangle from device coordinates to tile coordinates
// by rounding outwards to the nearest tile boundary so that the resulting tile
// region includes the query rectangle.
int startX = adjusted.left() / fInfo.fTileInterval.width(),
startY = adjusted.top() / fInfo.fTileInterval.height();
int endX = divide_ceil(adjusted.right(), fInfo.fTileInterval.width()),
endY = divide_ceil(adjusted.bottom(), fInfo.fTileInterval.height());
// Logically, we could pin endX to [startX, fXTiles], but we force it
// up to (startX, fXTiles] to make sure we hit at least one tile.
// This snaps just-out-of-bounds queries to the neighboring border tile.
// I don't know if this is an important feature outside of unit tests.
startX = SkPin32(startX, 0, fXTiles - 1);
startY = SkPin32(startY, 0, fYTiles - 1);
endX = SkPin32(endX, startX + 1, fXTiles);
endY = SkPin32(endY, startY + 1, fYTiles);
const int tilesHit = (endX - startX) * (endY - startY);
SkASSERT(tilesHit > 0);
if (tilesHit == 1) {
// A performance shortcut. The merging code below would work fine here too.
const SkTDArray<Entry>& tile = fTiles[startY * fXTiles + startX];
results->setCount(tile.count());
for (int i = 0; i < tile.count(); i++) {
(*results)[i] = tile[i].data;
}
return;
}
// We've got to merge the data in many tiles into a single sorted and deduplicated stream.
// We do a simple k-way merge based on the order the data was inserted.
// Gather pointers to the starts and ends of the tiles to merge.
SkAutoSTArray<kStackAllocationTileCount, const Entry*> starts(tilesHit), ends(tilesHit);
int i = 0;
for (int x = startX; x < endX; x++) {
for (int y = startY; y < endY; y++) {
starts[i] = fTiles[y * fXTiles + x].begin();
ends[i] = fTiles[y * fXTiles + x].end();
i++;
}
}
// Merge tiles into results until they're fully consumed.
results->reset();
while (true) {
// The tiles themselves are already ordered, so the earliest is at the front of some tile.
// It may be at the front of several, even all, tiles.
const Entry* earliest = NULL;
for (int i = 0; i < starts.count(); i++) {
if (starts[i] < ends[i]) {
if (NULL == earliest || starts[i]->order < earliest->order) {
earliest = starts[i];
}
}
}
// If we didn't find an earliest entry, there isn't anything left to merge.
if (NULL == earliest) {
return;
}
// We did find an earliest entry. Output it, and step forward every tile that contains it.
results->push(earliest->data);
for (int i = 0; i < starts.count(); i++) {
if (starts[i] < ends[i] && starts[i]->order == earliest->order) {
starts[i]++;
}
}
}
}
void SkTileGrid::clear() {
for (int i = 0; i < fXTiles * fYTiles; i++) {
fTiles[i].reset();
}
}
void SkTileGrid::rewindInserts() {
SkASSERT(fClient);
for (int i = 0; i < fXTiles * fYTiles; i++) {
while (!fTiles[i].isEmpty() && fClient->shouldRewind(fTiles[i].top().data)) {
fTiles[i].pop();
}
}
}
<commit_msg>Swap iteration order in TileGrid::insert().<commit_after>/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkTileGrid.h"
SkTileGrid::SkTileGrid(int xTiles, int yTiles, const SkTileGridFactory::TileGridInfo& info)
: fXTiles(xTiles)
, fYTiles(yTiles)
, fInfo(info)
, fCount(0)
, fTiles(SkNEW_ARRAY(SkTDArray<Entry>, xTiles * yTiles)) {
// Margin is offset by 1 as a provision for AA and
// to cancel-out the outset applied by getClipDeviceBounds.
fInfo.fMargin.fHeight++;
fInfo.fMargin.fWidth++;
}
SkTileGrid::~SkTileGrid() {
SkDELETE_ARRAY(fTiles);
}
void SkTileGrid::insert(void* data, const SkRect& fbounds, bool) {
SkASSERT(!fbounds.isEmpty());
SkIRect dilatedBounds;
if (fbounds.isLargest()) {
// Dilating the largest SkIRect will overflow. Other nearly-largest rects may overflow too,
// but we don't make active use of them like we do the largest.
dilatedBounds.setLargest();
} else {
fbounds.roundOut(&dilatedBounds);
dilatedBounds.outset(fInfo.fMargin.width(), fInfo.fMargin.height());
dilatedBounds.offset(fInfo.fOffset);
}
const SkIRect gridBounds =
{ 0, 0, fInfo.fTileInterval.width() * fXTiles, fInfo.fTileInterval.height() * fYTiles };
if (!SkIRect::Intersects(dilatedBounds, gridBounds)) {
return;
}
// Note: SkIRects are non-inclusive of the right() column and bottom() row,
// hence the "-1"s in the computations of maxX and maxY.
int minX = SkMax32(0, SkMin32(dilatedBounds.left() / fInfo.fTileInterval.width(), fXTiles - 1));
int minY = SkMax32(0, SkMin32(dilatedBounds.top() / fInfo.fTileInterval.height(), fYTiles - 1));
int maxX = SkMax32(0, SkMin32((dilatedBounds.right() - 1) / fInfo.fTileInterval.width(),
fXTiles - 1));
int maxY = SkMax32(0, SkMin32((dilatedBounds.bottom() - 1) / fInfo.fTileInterval.height(),
fYTiles - 1));
Entry entry = { fCount++, data };
for (int y = minY; y <= maxY; y++) {
for (int x = minX; x <= maxX; x++) {
fTiles[y * fXTiles + x].push(entry);
}
}
}
static int divide_ceil(int x, int y) {
return (x + y - 1) / y;
}
// Number of tiles for which data is allocated on the stack in
// SkTileGrid::search. If malloc becomes a bottleneck, we may consider
// increasing this number. Typical large web page, say 2k x 16k, would
// require 512 tiles of size 256 x 256 pixels.
static const int kStackAllocationTileCount = 1024;
void SkTileGrid::search(const SkRect& query, SkTDArray<void*>* results) const {
SkIRect adjusted;
query.roundOut(&adjusted);
// The inset is to counteract the outset that was applied in 'insert'
// The outset/inset is to optimize for lookups of size
// 'tileInterval + 2 * margin' that are aligned with the tile grid.
adjusted.inset(fInfo.fMargin.width(), fInfo.fMargin.height());
adjusted.offset(fInfo.fOffset);
adjusted.sort(); // in case the inset inverted the rectangle
// Convert the query rectangle from device coordinates to tile coordinates
// by rounding outwards to the nearest tile boundary so that the resulting tile
// region includes the query rectangle.
int startX = adjusted.left() / fInfo.fTileInterval.width(),
startY = adjusted.top() / fInfo.fTileInterval.height();
int endX = divide_ceil(adjusted.right(), fInfo.fTileInterval.width()),
endY = divide_ceil(adjusted.bottom(), fInfo.fTileInterval.height());
// Logically, we could pin endX to [startX, fXTiles], but we force it
// up to (startX, fXTiles] to make sure we hit at least one tile.
// This snaps just-out-of-bounds queries to the neighboring border tile.
// I don't know if this is an important feature outside of unit tests.
startX = SkPin32(startX, 0, fXTiles - 1);
startY = SkPin32(startY, 0, fYTiles - 1);
endX = SkPin32(endX, startX + 1, fXTiles);
endY = SkPin32(endY, startY + 1, fYTiles);
const int tilesHit = (endX - startX) * (endY - startY);
SkASSERT(tilesHit > 0);
if (tilesHit == 1) {
// A performance shortcut. The merging code below would work fine here too.
const SkTDArray<Entry>& tile = fTiles[startY * fXTiles + startX];
results->setCount(tile.count());
for (int i = 0; i < tile.count(); i++) {
(*results)[i] = tile[i].data;
}
return;
}
// We've got to merge the data in many tiles into a single sorted and deduplicated stream.
// We do a simple k-way merge based on the order the data was inserted.
// Gather pointers to the starts and ends of the tiles to merge.
SkAutoSTArray<kStackAllocationTileCount, const Entry*> starts(tilesHit), ends(tilesHit);
int i = 0;
for (int x = startX; x < endX; x++) {
for (int y = startY; y < endY; y++) {
starts[i] = fTiles[y * fXTiles + x].begin();
ends[i] = fTiles[y * fXTiles + x].end();
i++;
}
}
// Merge tiles into results until they're fully consumed.
results->reset();
while (true) {
// The tiles themselves are already ordered, so the earliest is at the front of some tile.
// It may be at the front of several, even all, tiles.
const Entry* earliest = NULL;
for (int i = 0; i < starts.count(); i++) {
if (starts[i] < ends[i]) {
if (NULL == earliest || starts[i]->order < earliest->order) {
earliest = starts[i];
}
}
}
// If we didn't find an earliest entry, there isn't anything left to merge.
if (NULL == earliest) {
return;
}
// We did find an earliest entry. Output it, and step forward every tile that contains it.
results->push(earliest->data);
for (int i = 0; i < starts.count(); i++) {
if (starts[i] < ends[i] && starts[i]->order == earliest->order) {
starts[i]++;
}
}
}
}
void SkTileGrid::clear() {
for (int i = 0; i < fXTiles * fYTiles; i++) {
fTiles[i].reset();
}
}
void SkTileGrid::rewindInserts() {
SkASSERT(fClient);
for (int i = 0; i < fXTiles * fYTiles; i++) {
while (!fTiles[i].isEmpty() && fClient->shouldRewind(fTiles[i].top().data)) {
fTiles[i].pop();
}
}
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "addqtoperation.h"
#include "addkeysoperation.h"
#include "findkeyoperation.h"
#include "findvalueoperation.h"
#include "getoperation.h"
#include "rmkeysoperation.h"
#include "settings.h"
#include <iostream>
// Qt version file stuff:
static char PREFIX[] = "QtVersion.";
static char VERSION[] = "Version";
// BaseQtVersion:
static char ID[] = "Id";
static char DISPLAYNAME[] = "Name";
static char AUTODETECTED[] = "isAutodetected";
static char AUTODETECTION_SOURCE[] = "autodetectionSource";
static char QMAKE[] = "QMakePath";
static char TYPE[] = "QtVersion.Type";
QString AddQtOperation::name() const
{
return QLatin1String("addQt");
}
QString AddQtOperation::helpText() const
{
return QLatin1String("add a Qt version to Qt Creator");
}
QString AddQtOperation::argumentsHelpText() const
{
return QLatin1String(" --id <ID> id of the new Qt version. (required)\n"
" --name <NAME> display name of the new Qt version. (required)\n"
" --qmake <PATH> path to qmake. (required)\n"
" --type <TYPE> type of Qt version to add. (required)\n"
" <KEY> <TYPE:VALUE> extra key value pairs\n");
}
bool AddQtOperation::setArguments(const QStringList &args)
{
for (int i = 0; i < args.count(); ++i) {
const QString current = args.at(i);
const QString next = ((i + 1) < args.count()) ? args.at(i + 1) : QString();
if (current == QLatin1String("--id")) {
if (next.isNull()) {
std::cerr << "Error parsing after --id." << std::endl << std::endl;
return false;
}
++i; // skip next;
m_id = next;
continue;
}
if (current == QLatin1String("--name")) {
if (next.isNull()) {
std::cerr << "Error parsing after --name." << std::endl << std::endl;
return false;
}
++i; // skip next;
m_displayName = next;
continue;
}
if (current == QLatin1String("--qmake")) {
if (next.isNull()) {
std::cerr << "Error parsing after --qmake." << std::endl << std::endl;
return false;
}
++i; // skip next;
m_qmake = next;
continue;
}
if (current == QLatin1String("--type")) {
if (next.isNull()) {
std::cerr << "Error parsing after --type." << std::endl << std::endl;
return false;
}
++i; // skip next;
m_type = next;
continue;
}
if (next.isNull()) {
std::cerr << "Unknown parameter: " << qPrintable(current) << std::endl << std::endl;
return false;
}
++i; // skip next;
KeyValuePair pair(current, next);
if (!pair.value.isValid()) {
std::cerr << "Error parsing: " << qPrintable(current) << " " << qPrintable(next) << std::endl << std::endl;
return false;
}
m_extra << pair;
}
if (m_id.isEmpty()) {
std::cerr << "Error no id was passed." << std::endl << std::endl;
}
if (m_displayName.isEmpty()) {
std::cerr << "Error no display name was passed." << std::endl << std::endl;
}
if (m_qmake.isEmpty()) {
std::cerr << "Error no qmake was passed." << std::endl << std::endl;
}
if (m_type.isEmpty()) {
std::cerr << "Error no type was passed." << std::endl << std::endl;
}
return !m_id.isEmpty() && !m_displayName.isEmpty() && !m_qmake.isEmpty() && !m_type.isEmpty();
}
int AddQtOperation::execute() const
{
QVariantMap map = load(QLatin1String("qtversions"));
if (map.isEmpty())
map = initializeQtVersions();
map = addQt(map, m_id, m_displayName, m_type, m_qmake, m_extra);
if (map.isEmpty())
return -2;
return save(map, QLatin1String("qtversions")) ? 0 : -3;
}
#ifdef WITH_TESTS
bool AddQtOperation::test() const
{
QVariantMap map = initializeQtVersions();
if (!map.count() == 1
|| !map.contains(QLatin1String(VERSION))
|| map.value(QLatin1String(VERSION)).toInt() != 1)
return false;
map = addQt(map, QLatin1String("testId"), QLatin1String("Test Qt Version"), QLatin1String("testType"),
QLatin1String("/tmp/test/qmake"),
KeyValuePairList() << KeyValuePair(QLatin1String("extraData"), QVariant(QLatin1String("extraValue"))));
if (map.count() != 2
|| !map.contains(QLatin1String(VERSION))
|| map.value(QLatin1String(VERSION)).toInt() != 1
|| !map.contains(QLatin1String("QtVersion.0")))
return false;
QVariantMap version0 = map.value(QLatin1String("QtVersion.0")).toMap();
if (version0.count() != 7
|| !version0.contains(QLatin1String(ID))
|| version0.value(QLatin1String(ID)).toInt() != -1
|| !version0.contains(QLatin1String(DISPLAYNAME))
|| version0.value(QLatin1String(DISPLAYNAME)).toString() != QLatin1String("Test Qt Version")
|| !version0.contains(QLatin1String(AUTODETECTED))
|| version0.value(QLatin1String(AUTODETECTED)).toBool() != true
|| !version0.contains(QLatin1String(AUTODETECTION_SOURCE))
|| version0.value(QLatin1String(AUTODETECTION_SOURCE)).toString() != QLatin1String("testId")
|| !version0.contains(QLatin1String(TYPE))
|| version0.value(QLatin1String(TYPE)).toString() != QLatin1String("testType")
|| !version0.contains(QLatin1String(QMAKE))
|| version0.value(QLatin1String(QMAKE)).toString() != QLatin1String("/tmp/test/qmake")
|| !version0.contains(QLatin1String("extraData"))
|| version0.value(QLatin1String("extraData")).toString() != QLatin1String("extraValue"))
return false;
// Ignore existing ids:
QVariantMap result = addQt(map, QLatin1String("testId"), QLatin1String("Test Qt Version2"), QLatin1String("testType2"),
QLatin1String("/tmp/test/qmake2"),
KeyValuePairList() << KeyValuePair(QLatin1String("extraData"), QVariant(QLatin1String("extraValue"))));
if (!result.isEmpty())
return false;
// Make sure name is unique:
map = addQt(map, QLatin1String("testId2"), QLatin1String("Test Qt Version"), QLatin1String("testType3"),
QLatin1String("/tmp/test/qmake2"),
KeyValuePairList() << KeyValuePair(QLatin1String("extraData"), QVariant(QLatin1String("extraValue"))));
if (map.count() != 3
|| !map.contains(QLatin1String(VERSION))
|| map.value(QLatin1String(VERSION)).toInt() != 1
|| !map.contains(QLatin1String("QtVersion.0"))
|| !map.contains(QLatin1String("QtVersion.1")))
return false;
if (map.value(QLatin1String("QtVersion.0")) != version0)
return false;
QVariantMap version1 = map.value(QLatin1String("QtVersion.1")).toMap();
if (version1.count() != 7
|| !version1.contains(QLatin1String(ID))
|| version1.value(QLatin1String(ID)).toInt() != -1
|| !version1.contains(QLatin1String(DISPLAYNAME))
|| version1.value(QLatin1String(DISPLAYNAME)).toString() != QLatin1String("Test Qt Version2")
|| !version1.contains(QLatin1String(AUTODETECTED))
|| version1.value(QLatin1String(AUTODETECTED)).toBool() != true
|| !version1.contains(QLatin1String(AUTODETECTION_SOURCE))
|| version1.value(QLatin1String(AUTODETECTION_SOURCE)).toString() != QLatin1String("testId2")
|| !version1.contains(QLatin1String(TYPE))
|| version1.value(QLatin1String(TYPE)).toString() != QLatin1String("testType3")
|| !version1.contains(QLatin1String(QMAKE))
|| version1.value(QLatin1String(QMAKE)).toString() != QLatin1String("/tmp/test/qmake2")
|| !version1.contains(QLatin1String("extraData"))
|| version1.value(QLatin1String("extraData")).toString() != QLatin1String("extraValue"))
return false;
return true;
}
#endif
QVariantMap AddQtOperation::addQt(const QVariantMap &map,
const QString &id, const QString &displayName, const QString &type,
const QString &qmake, const KeyValuePairList &extra)
{
// Sanity check: Make sure autodetection source is not in use already:
QStringList valueKeys = FindValueOperation::findValues(map, id);
bool hasId = false;
foreach (const QString &k, valueKeys) {
if (k.endsWith(QString(QLatin1Char('/')) + QLatin1String(AUTODETECTION_SOURCE))) {
hasId = true;
break;
}
}
if (hasId) {
std::cerr << "Error: Id " << qPrintable(id) << " already defined as Qt versions." << std::endl;
return QVariantMap();
}
// Find position to insert:
int versionCount = 0;
for (QVariantMap::const_iterator i = map.begin(); i != map.end(); ++i) {
if (!i.key().startsWith(QLatin1String(PREFIX)))
continue;
QString number = i.key().mid(QString::fromLatin1(PREFIX).count());
bool ok;
int count = number.toInt(&ok);
if (ok && count >= versionCount)
versionCount = count + 1;
}
const QString qt = QString::fromLatin1(PREFIX) + QString::number(versionCount);
// Sanity check: Make sure displayName is unique.
QStringList nameKeys = FindKeyOperation::findKey(map, QLatin1String(DISPLAYNAME));
QStringList nameList;
foreach (const QString nameKey, nameKeys)
nameList << GetOperation::get(map, nameKey).toString();
const QString uniqueName = makeUnique(displayName, nameList);
// insert data:
KeyValuePairList data;
data << KeyValuePair(QStringList() << qt << QLatin1String(ID), QVariant(-1));
data << KeyValuePair(QStringList() << qt << QLatin1String(DISPLAYNAME), QVariant(uniqueName));
data << KeyValuePair(QStringList() << qt << QLatin1String(AUTODETECTED), QVariant(true));
data << KeyValuePair(QStringList() << qt << QLatin1String(AUTODETECTION_SOURCE), QVariant(id));
data << KeyValuePair(QStringList() << qt << QLatin1String(QMAKE), QVariant(qmake));
data << KeyValuePair(QStringList() << qt << QLatin1String(TYPE), QVariant(type));
KeyValuePairList qtExtraList;
foreach (const KeyValuePair &pair, extra)
qtExtraList << KeyValuePair(QStringList() << qt << pair.key, pair.value);
data.append(qtExtraList);
return AddKeysOperation::addKeys(map, data);
}
QVariantMap AddQtOperation::initializeQtVersions()
{
QVariantMap map;
map.insert(QLatin1String(VERSION), 1);
return map;
}
<commit_msg>sdktool: Make sure to put a sane qmake path into qtversions.xml<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "addqtoperation.h"
#include "addkeysoperation.h"
#include "findkeyoperation.h"
#include "findvalueoperation.h"
#include "getoperation.h"
#include "rmkeysoperation.h"
#include "settings.h"
#include <QDir>
#include <iostream>
// Qt version file stuff:
static char PREFIX[] = "QtVersion.";
static char VERSION[] = "Version";
// BaseQtVersion:
static char ID[] = "Id";
static char DISPLAYNAME[] = "Name";
static char AUTODETECTED[] = "isAutodetected";
static char AUTODETECTION_SOURCE[] = "autodetectionSource";
static char QMAKE[] = "QMakePath";
static char TYPE[] = "QtVersion.Type";
QString AddQtOperation::name() const
{
return QLatin1String("addQt");
}
QString AddQtOperation::helpText() const
{
return QLatin1String("add a Qt version to Qt Creator");
}
QString AddQtOperation::argumentsHelpText() const
{
return QLatin1String(" --id <ID> id of the new Qt version. (required)\n"
" --name <NAME> display name of the new Qt version. (required)\n"
" --qmake <PATH> path to qmake. (required)\n"
" --type <TYPE> type of Qt version to add. (required)\n"
" <KEY> <TYPE:VALUE> extra key value pairs\n");
}
bool AddQtOperation::setArguments(const QStringList &args)
{
for (int i = 0; i < args.count(); ++i) {
const QString current = args.at(i);
const QString next = ((i + 1) < args.count()) ? args.at(i + 1) : QString();
if (current == QLatin1String("--id")) {
if (next.isNull()) {
std::cerr << "Error parsing after --id." << std::endl << std::endl;
return false;
}
++i; // skip next;
m_id = next;
continue;
}
if (current == QLatin1String("--name")) {
if (next.isNull()) {
std::cerr << "Error parsing after --name." << std::endl << std::endl;
return false;
}
++i; // skip next;
m_displayName = next;
continue;
}
if (current == QLatin1String("--qmake")) {
if (next.isNull()) {
std::cerr << "Error parsing after --qmake." << std::endl << std::endl;
return false;
}
++i; // skip next;
m_qmake = next;
continue;
}
if (current == QLatin1String("--type")) {
if (next.isNull()) {
std::cerr << "Error parsing after --type." << std::endl << std::endl;
return false;
}
++i; // skip next;
m_type = next;
continue;
}
if (next.isNull()) {
std::cerr << "Unknown parameter: " << qPrintable(current) << std::endl << std::endl;
return false;
}
++i; // skip next;
KeyValuePair pair(current, next);
if (!pair.value.isValid()) {
std::cerr << "Error parsing: " << qPrintable(current) << " " << qPrintable(next) << std::endl << std::endl;
return false;
}
m_extra << pair;
}
if (m_id.isEmpty()) {
std::cerr << "Error no id was passed." << std::endl << std::endl;
}
if (m_displayName.isEmpty()) {
std::cerr << "Error no display name was passed." << std::endl << std::endl;
}
if (m_qmake.isEmpty()) {
std::cerr << "Error no qmake was passed." << std::endl << std::endl;
}
if (m_type.isEmpty()) {
std::cerr << "Error no type was passed." << std::endl << std::endl;
}
return !m_id.isEmpty() && !m_displayName.isEmpty() && !m_qmake.isEmpty() && !m_type.isEmpty();
}
int AddQtOperation::execute() const
{
QVariantMap map = load(QLatin1String("qtversions"));
if (map.isEmpty())
map = initializeQtVersions();
map = addQt(map, m_id, m_displayName, m_type, m_qmake, m_extra);
if (map.isEmpty())
return -2;
return save(map, QLatin1String("qtversions")) ? 0 : -3;
}
#ifdef WITH_TESTS
bool AddQtOperation::test() const
{
QVariantMap map = initializeQtVersions();
if (!map.count() == 1
|| !map.contains(QLatin1String(VERSION))
|| map.value(QLatin1String(VERSION)).toInt() != 1)
return false;
#if defined Q_OS_WIN
map = addQt(map, QLatin1String("testId"), QLatin1String("Test Qt Version"), QLatin1String("testType"),
QLatin1String("/tmp//../tmp/test\\qmake"),
KeyValuePairList() << KeyValuePair(QLatin1String("extraData"), QVariant(QLatin1String("extraValue"))));
#else
map = addQt(map, QLatin1String("testId"), QLatin1String("Test Qt Version"), QLatin1String("testType"),
QLatin1String("/tmp//../tmp/test/qmake"),
KeyValuePairList() << KeyValuePair(QLatin1String("extraData"), QVariant(QLatin1String("extraValue"))));
#endif
if (map.count() != 2
|| !map.contains(QLatin1String(VERSION))
|| map.value(QLatin1String(VERSION)).toInt() != 1
|| !map.contains(QLatin1String("QtVersion.0")))
return false;
QVariantMap version0 = map.value(QLatin1String("QtVersion.0")).toMap();
if (version0.count() != 7
|| !version0.contains(QLatin1String(ID))
|| version0.value(QLatin1String(ID)).toInt() != -1
|| !version0.contains(QLatin1String(DISPLAYNAME))
|| version0.value(QLatin1String(DISPLAYNAME)).toString() != QLatin1String("Test Qt Version")
|| !version0.contains(QLatin1String(AUTODETECTED))
|| version0.value(QLatin1String(AUTODETECTED)).toBool() != true
|| !version0.contains(QLatin1String(AUTODETECTION_SOURCE))
|| version0.value(QLatin1String(AUTODETECTION_SOURCE)).toString() != QLatin1String("testId")
|| !version0.contains(QLatin1String(TYPE))
|| version0.value(QLatin1String(TYPE)).toString() != QLatin1String("testType")
|| !version0.contains(QLatin1String(QMAKE))
|| version0.value(QLatin1String(QMAKE)).toString() != QLatin1String("/tmp/test/qmake")
|| !version0.contains(QLatin1String("extraData"))
|| version0.value(QLatin1String("extraData")).toString() != QLatin1String("extraValue"))
return false;
// Ignore existing ids:
QVariantMap result = addQt(map, QLatin1String("testId"), QLatin1String("Test Qt Version2"), QLatin1String("testType2"),
QLatin1String("/tmp/test/qmake2"),
KeyValuePairList() << KeyValuePair(QLatin1String("extraData"), QVariant(QLatin1String("extraValue"))));
if (!result.isEmpty())
return false;
// Make sure name is unique:
map = addQt(map, QLatin1String("testId2"), QLatin1String("Test Qt Version"), QLatin1String("testType3"),
QLatin1String("/tmp/test/qmake2"),
KeyValuePairList() << KeyValuePair(QLatin1String("extraData"), QVariant(QLatin1String("extraValue"))));
if (map.count() != 3
|| !map.contains(QLatin1String(VERSION))
|| map.value(QLatin1String(VERSION)).toInt() != 1
|| !map.contains(QLatin1String("QtVersion.0"))
|| !map.contains(QLatin1String("QtVersion.1")))
return false;
if (map.value(QLatin1String("QtVersion.0")) != version0)
return false;
QVariantMap version1 = map.value(QLatin1String("QtVersion.1")).toMap();
if (version1.count() != 7
|| !version1.contains(QLatin1String(ID))
|| version1.value(QLatin1String(ID)).toInt() != -1
|| !version1.contains(QLatin1String(DISPLAYNAME))
|| version1.value(QLatin1String(DISPLAYNAME)).toString() != QLatin1String("Test Qt Version2")
|| !version1.contains(QLatin1String(AUTODETECTED))
|| version1.value(QLatin1String(AUTODETECTED)).toBool() != true
|| !version1.contains(QLatin1String(AUTODETECTION_SOURCE))
|| version1.value(QLatin1String(AUTODETECTION_SOURCE)).toString() != QLatin1String("testId2")
|| !version1.contains(QLatin1String(TYPE))
|| version1.value(QLatin1String(TYPE)).toString() != QLatin1String("testType3")
|| !version1.contains(QLatin1String(QMAKE))
|| version1.value(QLatin1String(QMAKE)).toString() != QLatin1String("/tmp/test/qmake2")
|| !version1.contains(QLatin1String("extraData"))
|| version1.value(QLatin1String("extraData")).toString() != QLatin1String("extraValue"))
return false;
return true;
}
#endif
QVariantMap AddQtOperation::addQt(const QVariantMap &map,
const QString &id, const QString &displayName, const QString &type,
const QString &qmake, const KeyValuePairList &extra)
{
// Sanity check: Make sure autodetection source is not in use already:
QStringList valueKeys = FindValueOperation::findValues(map, id);
bool hasId = false;
foreach (const QString &k, valueKeys) {
if (k.endsWith(QString(QLatin1Char('/')) + QLatin1String(AUTODETECTION_SOURCE))) {
hasId = true;
break;
}
}
if (hasId) {
std::cerr << "Error: Id " << qPrintable(id) << " already defined as Qt versions." << std::endl;
return QVariantMap();
}
// Find position to insert:
int versionCount = 0;
for (QVariantMap::const_iterator i = map.begin(); i != map.end(); ++i) {
if (!i.key().startsWith(QLatin1String(PREFIX)))
continue;
QString number = i.key().mid(QString::fromLatin1(PREFIX).count());
bool ok;
int count = number.toInt(&ok);
if (ok && count >= versionCount)
versionCount = count + 1;
}
const QString qt = QString::fromLatin1(PREFIX) + QString::number(versionCount);
// Sanity check: Make sure displayName is unique.
QStringList nameKeys = FindKeyOperation::findKey(map, QLatin1String(DISPLAYNAME));
QStringList nameList;
foreach (const QString nameKey, nameKeys)
nameList << GetOperation::get(map, nameKey).toString();
const QString uniqueName = makeUnique(displayName, nameList);
// Sanitize qmake path:
QString saneQmake = QDir::cleanPath(QDir::fromNativeSeparators(qmake));
// insert data:
KeyValuePairList data;
data << KeyValuePair(QStringList() << qt << QLatin1String(ID), QVariant(-1));
data << KeyValuePair(QStringList() << qt << QLatin1String(DISPLAYNAME), QVariant(uniqueName));
data << KeyValuePair(QStringList() << qt << QLatin1String(AUTODETECTED), QVariant(true));
data << KeyValuePair(QStringList() << qt << QLatin1String(AUTODETECTION_SOURCE), QVariant(id));
data << KeyValuePair(QStringList() << qt << QLatin1String(QMAKE), QVariant(saneQmake));
data << KeyValuePair(QStringList() << qt << QLatin1String(TYPE), QVariant(type));
KeyValuePairList qtExtraList;
foreach (const KeyValuePair &pair, extra)
qtExtraList << KeyValuePair(QStringList() << qt << pair.key, pair.value);
data.append(qtExtraList);
return AddKeysOperation::addKeys(map, data);
}
QVariantMap AddQtOperation::initializeQtVersions()
{
QVariantMap map;
map.insert(QLatin1String(VERSION), 1);
return map;
}
<|endoftext|> |
<commit_before>/*FPL_AUTO_NAMESPACE
*******************************************************************************
FPL Simple Audio Playback Demo
*******************************************************************************
This demo plays a contiguous sine or square wave in the expected S16 format.
- You fill out the audio settings you want or leave the default
- You fill out the audio client read callback and user data pointer
- You initialize the platform with InitFlags::Audio and pass your settings as second parameter
- You start playing the audio using PlayAudio()
- When you are done you stop it using StopAudio()
- You release the platform
- Done
*/
#define FPL_IMPLEMENTATION
#define FPL_NO_WINDOW
#include <final_platform_layer.hpp>
#include <math.h> // sinf
#include <stdio.h> // getchar
struct AudioTest {
uint32_t toneHz;
uint32_t toneVolume;
uint32_t runningSampleIndex;
uint32_t wavePeriod;
bool useSquareWave;
};
static const float PI32 = 3.14159265359f;
using namespace fpl;
static uint32_t FillAudioBuffer(const AudioDeviceFormat &nativeFormat, const uint32_t frameCount, void *outputSamples, void *userData) {
AudioTest *audioTest = (AudioTest *)userData;
FPL_ASSERT(audioTest != nullptr);
FPL_ASSERT(nativeFormat.type == AudioFormatType::S16);
uint32_t result = 0;
int16_t *outSamples = (int16_t *)outputSamples;
uint32_t halfWavePeriod = audioTest->wavePeriod / 2;
for (uint32_t frameIndex = 0; frameIndex < frameCount; ++frameIndex) {
int16_t sampleValue;
if (audioTest->useSquareWave) {
sampleValue = ((audioTest->runningSampleIndex++ / halfWavePeriod) % 2) ? (int16_t)audioTest->toneVolume : -(int16_t)audioTest->toneVolume;
} else {
float t = 2.0f * PI32 * (float)audioTest->runningSampleIndex++ / (float)audioTest->wavePeriod;
sampleValue = (int16_t)(sinf(t) * audioTest->toneVolume);
}
for (uint32_t channelIndex = 0; channelIndex < nativeFormat.channels; ++channelIndex) {
*outSamples++ = sampleValue;
++result;
}
}
return result;
}
int main(int argc, char **args) {
int result = -1;
// Initialize to default settings which is 48 KHz and 2 Channels
Settings settings = DefaultSettings();
// Optionally overwrite audio settings if needed
// Setup some state for the sine/square wave generation
AudioTest audioTest = {};
audioTest.toneHz = 256;
audioTest.toneVolume = 1000;
audioTest.wavePeriod = settings.audio.deviceFormat.sampleRate / audioTest.toneHz;
audioTest.useSquareWave = false;
// Provide client read callback and optionally user data
settings.audio.clientReadCallback = FillAudioBuffer;
settings.audio.userData = &audioTest;
settings.audio.deviceFormat.type = AudioFormatType::S16;
settings.audio.deviceFormat.channels = 2;
settings.audio.deviceFormat.sampleRate = 48000;
// Find audio device
if (InitPlatform(InitFlags::Audio, settings)) {
AudioDeviceID audioDevices[16] = {};
uint32_t deviceCount = audio::GetAudioDevices(audioDevices, FPL_ARRAYCOUNT(audioDevices));
if (deviceCount > 0) {
settings.audio.deviceID = audioDevices[0];
console::ConsoleFormatOut("Using audio device: %s\n", settings.audio.deviceID.name);
}
ReleasePlatform();
}
// Initialize the platform with audio enabled and the settings
if (InitPlatform(InitFlags::Audio, settings)) {
// You can overwrite the client read callback and user data if you want to
audio::SetAudioClientReadCallback(FillAudioBuffer, &audioTest);
// Start audio playback (This will start calling clientReadCallback regulary)
if (audio::PlayAudio() == audio::AudioResult::Success) {
// Print out the native audio format
AudioDeviceFormat nativeFormat = audio::GetAudioHardwareFormat();
console::ConsoleFormatOut("Audio with %lu KHz and %lu channels is playing, press any key to stop playback...\n", nativeFormat.sampleRate, nativeFormat.channels);
// Wait for any key presses
getchar();
// Stop audio playback
audio::StopAudio();
}
// Release the platform
ReleasePlatform();
result = 0;
}
return(result);
}<commit_msg>Use replacement for getchar in audio demo<commit_after>/*FPL_AUTO_NAMESPACE
*******************************************************************************
FPL Simple Audio Playback Demo
*******************************************************************************
This demo plays a contiguous sine or square wave in the expected S16 format.
- You fill out the audio settings you want or leave the default
- You fill out the audio client read callback and user data pointer
- You initialize the platform with InitFlags::Audio and pass your settings as second parameter
- You start playing the audio using PlayAudio()
- When you are done you stop it using StopAudio()
- You release the platform
- Done
*/
#define FPL_IMPLEMENTATION
#define FPL_NO_WINDOW
#include <final_platform_layer.hpp>
#include <math.h> // sinf
struct AudioTest {
uint32_t toneHz;
uint32_t toneVolume;
uint32_t runningSampleIndex;
uint32_t wavePeriod;
bool useSquareWave;
};
static const float PI32 = 3.14159265359f;
using namespace fpl;
using namespace fpl::console;
static uint32_t FillAudioBuffer(const AudioDeviceFormat &nativeFormat, const uint32_t frameCount, void *outputSamples, void *userData) {
AudioTest *audioTest = (AudioTest *)userData;
FPL_ASSERT(audioTest != nullptr);
FPL_ASSERT(nativeFormat.type == AudioFormatType::S16);
uint32_t result = 0;
int16_t *outSamples = (int16_t *)outputSamples;
uint32_t halfWavePeriod = audioTest->wavePeriod / 2;
for (uint32_t frameIndex = 0; frameIndex < frameCount; ++frameIndex) {
int16_t sampleValue;
if (audioTest->useSquareWave) {
sampleValue = ((audioTest->runningSampleIndex++ / halfWavePeriod) % 2) ? (int16_t)audioTest->toneVolume : -(int16_t)audioTest->toneVolume;
} else {
float t = 2.0f * PI32 * (float)audioTest->runningSampleIndex++ / (float)audioTest->wavePeriod;
sampleValue = (int16_t)(sinf(t) * audioTest->toneVolume);
}
for (uint32_t channelIndex = 0; channelIndex < nativeFormat.channels; ++channelIndex) {
*outSamples++ = sampleValue;
++result;
}
}
return result;
}
int main(int argc, char **args) {
int result = -1;
// Initialize to default settings which is 48 KHz and 2 Channels
Settings settings = DefaultSettings();
// Optionally overwrite audio settings if needed
// Setup some state for the sine/square wave generation
AudioTest audioTest = {};
audioTest.toneHz = 256;
audioTest.toneVolume = 1000;
audioTest.wavePeriod = settings.audio.deviceFormat.sampleRate / audioTest.toneHz;
audioTest.useSquareWave = false;
// Provide client read callback and optionally user data
settings.audio.clientReadCallback = FillAudioBuffer;
settings.audio.userData = &audioTest;
settings.audio.deviceFormat.type = AudioFormatType::S16;
settings.audio.deviceFormat.channels = 2;
settings.audio.deviceFormat.sampleRate = 48000;
// Find audio device
if (InitPlatform(InitFlags::Audio, settings)) {
AudioDeviceID audioDevices[16] = {};
uint32_t deviceCount = audio::GetAudioDevices(audioDevices, FPL_ARRAYCOUNT(audioDevices));
if (deviceCount > 0) {
settings.audio.deviceID = audioDevices[0];
ConsoleFormatOut("Using audio device: %s\n", settings.audio.deviceID.name);
}
ReleasePlatform();
}
// Initialize the platform with audio enabled and the settings
if (InitPlatform(InitFlags::Audio, settings)) {
// Print out the native audio format
AudioDeviceFormat nativeFormat = audio::GetAudioHardwareFormat();
// You can overwrite the client read callback and user data if you want to
audio::SetAudioClientReadCallback(FillAudioBuffer, &audioTest);
// Start audio playback (This will start calling clientReadCallback regulary)
if (audio::PlayAudio() == audio::AudioResult::Success) {
ConsoleFormatOut("Audio with %lu KHz and %lu channels is playing, press any key to stop playback...\n", nativeFormat.sampleRate, nativeFormat.channels);
// Wait for any key presses
ConsoleWaitForCharInput();
// Stop audio playback
audio::StopAudio();
}
// Release the platform
ReleasePlatform();
result = 0;
}
return(result);
}<|endoftext|> |
<commit_before>/*
* Copyright 2011 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkAdvancedTypefaceMetrics.h"
#include "SkFontDescriptor.h"
#include "SkFontHost.h"
#include "SkFontStream.h"
#include "SkStream.h"
#include "SkTypeface.h"
SK_DEFINE_INST_COUNT(SkTypeface)
//#define TRACE_LIFECYCLE
#ifdef TRACE_LIFECYCLE
static int32_t gTypefaceCounter;
#endif
SkTypeface::SkTypeface(Style style, SkFontID fontID, bool isFixedPitch)
: fUniqueID(fontID), fStyle(style), fIsFixedPitch(isFixedPitch) {
#ifdef TRACE_LIFECYCLE
SkDebugf("SkTypeface: create %p fontID %d total %d\n",
this, fontID, ++gTypefaceCounter);
#endif
}
SkTypeface::~SkTypeface() {
#ifdef TRACE_LIFECYCLE
SkDebugf("SkTypeface: destroy %p fontID %d total %d\n",
this, fUniqueID, --gTypefaceCounter);
#endif
}
///////////////////////////////////////////////////////////////////////////////
SkTypeface* SkTypeface::GetDefaultTypeface(Style style) {
// we keep a reference to this guy for all time, since if we return its
// fontID, the font cache may later on ask to resolve that back into a
// typeface object.
static const uint32_t FONT_STYLE_COUNT = 4;
static SkTypeface* gDefaultTypefaces[FONT_STYLE_COUNT];
SkASSERT((unsigned)style < FONT_STYLE_COUNT);
// mask off any other bits to avoid a crash in SK_RELEASE
style = (Style)(style & 0x03);
if (NULL == gDefaultTypefaces[style]) {
gDefaultTypefaces[style] =
SkFontHost::CreateTypeface(NULL, NULL, style);
}
return gDefaultTypefaces[style];
}
SkTypeface* SkTypeface::RefDefault(Style style) {
return SkRef(GetDefaultTypeface(style));
}
uint32_t SkTypeface::UniqueID(const SkTypeface* face) {
if (NULL == face) {
face = GetDefaultTypeface();
}
return face->uniqueID();
}
bool SkTypeface::Equal(const SkTypeface* facea, const SkTypeface* faceb) {
return SkTypeface::UniqueID(facea) == SkTypeface::UniqueID(faceb);
}
///////////////////////////////////////////////////////////////////////////////
SkTypeface* SkTypeface::CreateFromName(const char name[], Style style) {
if (NULL == name) {
return RefDefault(style);
}
return SkFontHost::CreateTypeface(NULL, name, style);
}
SkTypeface* SkTypeface::CreateFromTypeface(const SkTypeface* family, Style s) {
if (family && family->style() == s) {
family->ref();
return const_cast<SkTypeface*>(family);
}
return SkFontHost::CreateTypeface(family, NULL, s);
}
SkTypeface* SkTypeface::CreateFromStream(SkStream* stream) {
return SkFontHost::CreateTypefaceFromStream(stream);
}
SkTypeface* SkTypeface::CreateFromFile(const char path[]) {
return SkFontHost::CreateTypefaceFromFile(path);
}
///////////////////////////////////////////////////////////////////////////////
void SkTypeface::serialize(SkWStream* wstream) const {
bool isLocal = false;
SkFontDescriptor desc(this->style());
this->onGetFontDescriptor(&desc, &isLocal);
desc.serialize(wstream);
if (isLocal) {
int ttcIndex; // TODO: write this to the stream?
SkAutoTUnref<SkStream> rstream(this->openStream(&ttcIndex));
if (rstream.get()) {
size_t length = rstream->getLength();
wstream->writePackedUInt(length);
wstream->writeStream(rstream, length);
} else {
wstream->writePackedUInt(0);
}
} else {
wstream->writePackedUInt(0);
}
}
SkTypeface* SkTypeface::Deserialize(SkStream* stream) {
SkFontDescriptor desc(stream);
size_t length = stream->readPackedUInt();
if (length > 0) {
void* addr = sk_malloc_flags(length, 0);
if (addr) {
SkAutoTUnref<SkMemoryStream> localStream(SkNEW(SkMemoryStream));
localStream->setMemoryOwned(addr, length);
if (stream->read(addr, length) == length) {
return SkTypeface::CreateFromStream(localStream.get());
} else {
// Failed to read the full font data, so fall through and try to create from name.
// If this is because of EOF, all subsequent reads from the stream will be EOF.
// If this is because of a stream error, the stream is in an error state,
// do not attempt to skip any remaining bytes.
}
} else {
// failed to allocate, so just skip and create-from-name
stream->skip(length);
}
}
return SkTypeface::CreateFromName(desc.getFamilyName(), desc.getStyle());
}
///////////////////////////////////////////////////////////////////////////////
int SkTypeface::countTables() const {
return this->onGetTableTags(NULL);
}
int SkTypeface::getTableTags(SkFontTableTag tags[]) const {
return this->onGetTableTags(tags);
}
size_t SkTypeface::getTableSize(SkFontTableTag tag) const {
return this->onGetTableData(tag, 0, ~0U, NULL);
}
size_t SkTypeface::getTableData(SkFontTableTag tag, size_t offset, size_t length,
void* data) const {
return this->onGetTableData(tag, offset, length, data);
}
SkStream* SkTypeface::openStream(int* ttcIndex) const {
int ttcIndexStorage;
if (NULL == ttcIndex) {
// So our subclasses don't need to check for null param
ttcIndex = &ttcIndexStorage;
}
return this->onOpenStream(ttcIndex);
}
int SkTypeface::charsToGlyphs(const void* chars, Encoding encoding,
uint16_t glyphs[], int glyphCount) const {
if (glyphCount <= 0) {
return 0;
}
if (NULL == chars || (unsigned)encoding > kUTF32_Encoding) {
if (glyphs) {
sk_bzero(glyphs, glyphCount * sizeof(glyphs[0]));
}
return 0;
}
return this->onCharsToGlyphs(chars, encoding, glyphs, glyphCount);
}
int SkTypeface::countGlyphs() const {
return this->onCountGlyphs();
}
int SkTypeface::getUnitsPerEm() const {
// should we try to cache this in the base-class?
return this->onGetUPEM();
}
void SkTypeface::getFamilyName(SkString* name) const {
bool isLocal = false;
SkFontDescriptor desc(this->style());
this->onGetFontDescriptor(&desc, &isLocal);
name->set(desc.getFamilyName());
}
SkAdvancedTypefaceMetrics* SkTypeface::getAdvancedTypefaceMetrics(
SkAdvancedTypefaceMetrics::PerGlyphInfo info,
const uint32_t* glyphIDs,
uint32_t glyphIDsCount) const {
return this->onGetAdvancedTypefaceMetrics(info, glyphIDs, glyphIDsCount);
}
SkTypeface* SkTypeface::refMatchingStyle(Style style) const {
return this->onRefMatchingStyle(style);
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
int SkTypeface::onCharsToGlyphs(const void* chars, Encoding encoding,
uint16_t glyphs[], int glyphCount) const {
SkDebugf("onCharsToGlyphs unimplemented\n");
if (glyphs && glyphCount > 0) {
sk_bzero(glyphs, glyphCount * sizeof(glyphs[0]));
}
return 0;
}
int SkTypeface::onGetUPEM() const {
int upem = 0;
SkAdvancedTypefaceMetrics* metrics;
metrics = this->getAdvancedTypefaceMetrics(
SkAdvancedTypefaceMetrics::kNo_PerGlyphInfo,
NULL, 0);
if (metrics) {
upem = metrics->fEmSize;
metrics->unref();
}
return upem;
}
int SkTypeface::onGetTableTags(SkFontTableTag tags[]) const {
int ttcIndex;
SkAutoTUnref<SkStream> stream(this->openStream(&ttcIndex));
return stream.get() ? SkFontStream::GetTableTags(stream, ttcIndex, tags) : 0;
}
size_t SkTypeface::onGetTableData(SkFontTableTag tag, size_t offset,
size_t length, void* data) const {
int ttcIndex;
SkAutoTUnref<SkStream> stream(this->openStream(&ttcIndex));
return stream.get()
? SkFontStream::GetTableData(stream, ttcIndex, tag, offset, length, data)
: 0;
}
<commit_msg>Remove old default implementation of SkTypeface::onGetUPEM.<commit_after>/*
* Copyright 2011 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkAdvancedTypefaceMetrics.h"
#include "SkFontDescriptor.h"
#include "SkFontHost.h"
#include "SkFontStream.h"
#include "SkStream.h"
#include "SkTypeface.h"
SK_DEFINE_INST_COUNT(SkTypeface)
//#define TRACE_LIFECYCLE
#ifdef TRACE_LIFECYCLE
static int32_t gTypefaceCounter;
#endif
SkTypeface::SkTypeface(Style style, SkFontID fontID, bool isFixedPitch)
: fUniqueID(fontID), fStyle(style), fIsFixedPitch(isFixedPitch) {
#ifdef TRACE_LIFECYCLE
SkDebugf("SkTypeface: create %p fontID %d total %d\n",
this, fontID, ++gTypefaceCounter);
#endif
}
SkTypeface::~SkTypeface() {
#ifdef TRACE_LIFECYCLE
SkDebugf("SkTypeface: destroy %p fontID %d total %d\n",
this, fUniqueID, --gTypefaceCounter);
#endif
}
///////////////////////////////////////////////////////////////////////////////
SkTypeface* SkTypeface::GetDefaultTypeface(Style style) {
// we keep a reference to this guy for all time, since if we return its
// fontID, the font cache may later on ask to resolve that back into a
// typeface object.
static const uint32_t FONT_STYLE_COUNT = 4;
static SkTypeface* gDefaultTypefaces[FONT_STYLE_COUNT];
SkASSERT((unsigned)style < FONT_STYLE_COUNT);
// mask off any other bits to avoid a crash in SK_RELEASE
style = (Style)(style & 0x03);
if (NULL == gDefaultTypefaces[style]) {
gDefaultTypefaces[style] =
SkFontHost::CreateTypeface(NULL, NULL, style);
}
return gDefaultTypefaces[style];
}
SkTypeface* SkTypeface::RefDefault(Style style) {
return SkRef(GetDefaultTypeface(style));
}
uint32_t SkTypeface::UniqueID(const SkTypeface* face) {
if (NULL == face) {
face = GetDefaultTypeface();
}
return face->uniqueID();
}
bool SkTypeface::Equal(const SkTypeface* facea, const SkTypeface* faceb) {
return SkTypeface::UniqueID(facea) == SkTypeface::UniqueID(faceb);
}
///////////////////////////////////////////////////////////////////////////////
SkTypeface* SkTypeface::CreateFromName(const char name[], Style style) {
if (NULL == name) {
return RefDefault(style);
}
return SkFontHost::CreateTypeface(NULL, name, style);
}
SkTypeface* SkTypeface::CreateFromTypeface(const SkTypeface* family, Style s) {
if (family && family->style() == s) {
family->ref();
return const_cast<SkTypeface*>(family);
}
return SkFontHost::CreateTypeface(family, NULL, s);
}
SkTypeface* SkTypeface::CreateFromStream(SkStream* stream) {
return SkFontHost::CreateTypefaceFromStream(stream);
}
SkTypeface* SkTypeface::CreateFromFile(const char path[]) {
return SkFontHost::CreateTypefaceFromFile(path);
}
///////////////////////////////////////////////////////////////////////////////
void SkTypeface::serialize(SkWStream* wstream) const {
bool isLocal = false;
SkFontDescriptor desc(this->style());
this->onGetFontDescriptor(&desc, &isLocal);
desc.serialize(wstream);
if (isLocal) {
int ttcIndex; // TODO: write this to the stream?
SkAutoTUnref<SkStream> rstream(this->openStream(&ttcIndex));
if (rstream.get()) {
size_t length = rstream->getLength();
wstream->writePackedUInt(length);
wstream->writeStream(rstream, length);
} else {
wstream->writePackedUInt(0);
}
} else {
wstream->writePackedUInt(0);
}
}
SkTypeface* SkTypeface::Deserialize(SkStream* stream) {
SkFontDescriptor desc(stream);
size_t length = stream->readPackedUInt();
if (length > 0) {
void* addr = sk_malloc_flags(length, 0);
if (addr) {
SkAutoTUnref<SkMemoryStream> localStream(SkNEW(SkMemoryStream));
localStream->setMemoryOwned(addr, length);
if (stream->read(addr, length) == length) {
return SkTypeface::CreateFromStream(localStream.get());
} else {
// Failed to read the full font data, so fall through and try to create from name.
// If this is because of EOF, all subsequent reads from the stream will be EOF.
// If this is because of a stream error, the stream is in an error state,
// do not attempt to skip any remaining bytes.
}
} else {
// failed to allocate, so just skip and create-from-name
stream->skip(length);
}
}
return SkTypeface::CreateFromName(desc.getFamilyName(), desc.getStyle());
}
///////////////////////////////////////////////////////////////////////////////
int SkTypeface::countTables() const {
return this->onGetTableTags(NULL);
}
int SkTypeface::getTableTags(SkFontTableTag tags[]) const {
return this->onGetTableTags(tags);
}
size_t SkTypeface::getTableSize(SkFontTableTag tag) const {
return this->onGetTableData(tag, 0, ~0U, NULL);
}
size_t SkTypeface::getTableData(SkFontTableTag tag, size_t offset, size_t length,
void* data) const {
return this->onGetTableData(tag, offset, length, data);
}
SkStream* SkTypeface::openStream(int* ttcIndex) const {
int ttcIndexStorage;
if (NULL == ttcIndex) {
// So our subclasses don't need to check for null param
ttcIndex = &ttcIndexStorage;
}
return this->onOpenStream(ttcIndex);
}
int SkTypeface::charsToGlyphs(const void* chars, Encoding encoding,
uint16_t glyphs[], int glyphCount) const {
if (glyphCount <= 0) {
return 0;
}
if (NULL == chars || (unsigned)encoding > kUTF32_Encoding) {
if (glyphs) {
sk_bzero(glyphs, glyphCount * sizeof(glyphs[0]));
}
return 0;
}
return this->onCharsToGlyphs(chars, encoding, glyphs, glyphCount);
}
int SkTypeface::countGlyphs() const {
return this->onCountGlyphs();
}
int SkTypeface::getUnitsPerEm() const {
// should we try to cache this in the base-class?
return this->onGetUPEM();
}
void SkTypeface::getFamilyName(SkString* name) const {
bool isLocal = false;
SkFontDescriptor desc(this->style());
this->onGetFontDescriptor(&desc, &isLocal);
name->set(desc.getFamilyName());
}
SkAdvancedTypefaceMetrics* SkTypeface::getAdvancedTypefaceMetrics(
SkAdvancedTypefaceMetrics::PerGlyphInfo info,
const uint32_t* glyphIDs,
uint32_t glyphIDsCount) const {
return this->onGetAdvancedTypefaceMetrics(info, glyphIDs, glyphIDsCount);
}
SkTypeface* SkTypeface::refMatchingStyle(Style style) const {
return this->onRefMatchingStyle(style);
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
int SkTypeface::onCharsToGlyphs(const void* chars, Encoding encoding,
uint16_t glyphs[], int glyphCount) const {
SkDebugf("onCharsToGlyphs unimplemented\n");
if (glyphs && glyphCount > 0) {
sk_bzero(glyphs, glyphCount * sizeof(glyphs[0]));
}
return 0;
}
int SkTypeface::onGetTableTags(SkFontTableTag tags[]) const {
int ttcIndex;
SkAutoTUnref<SkStream> stream(this->openStream(&ttcIndex));
return stream.get() ? SkFontStream::GetTableTags(stream, ttcIndex, tags) : 0;
}
size_t SkTypeface::onGetTableData(SkFontTableTag tag, size_t offset,
size_t length, void* data) const {
int ttcIndex;
SkAutoTUnref<SkStream> stream(this->openStream(&ttcIndex));
return stream.get()
? SkFontStream::GetTableData(stream, ttcIndex, tag, offset, length, data)
: 0;
}
<|endoftext|> |
<commit_before>
<commit_msg>Delete 1.cpp<commit_after><|endoftext|> |
<commit_before>/**
* @file manager.hpp
* @brief COSSB component manager
* @author Byunghun Hwang<bhhwang@nsynapse.com>
* @date 2015. 6. 21
* @details
*/
#ifndef _COSSB_MANAGER_HPP_
#define _COSSB_MANAGER_HPP_
#include <map>
#include <vector>
#include <string>
#include "arch/singleton.hpp"
#include "base/configreader.hpp"
using namespace std;
namespace cossb {
namespace base { template<class T> class libadopter; }
namespace interface {
class ilog;
class iobject;
}
namespace manager {
/**
* @brief component manager derived from singleton pattern
*/
class component_manager : public arch::singleton<component_manager> {
public:
component_manager();
virtual ~component_manager();
component_manager(const component_manager&) = delete;
component_manager& operator = (const component_manager&) = delete;
/**
* @brief install specific component
*/
bool install(const char* component_name);
/**
* @brief uninstall specific component
*/
bool uninstall(const char* component_name);
bool uninstall();
/**
* @brief run specific component
*/
bool run(const char* component_name);
/**
* @brief run all components
*/
bool run();
/**
* @brief stop specific component
*/
bool stop(const char* component_name);
/**
* @brief stop all components
*/
bool stop();
/**
* @brief get count of the installed components
*/
int count();
};
#define cossb_component_manager cossb::manager::component_manager::instance()
/**
* @brief system manager derived from singleton pattern
*/
class system_manager : public arch::singleton<system_manager> {
public:
system_manager();
virtual ~system_manager();
system_manager(const system_manager&) = delete;
system_manager& operator = (const system_manager&) = delete;
/**
* @brief setup system configuration
*/
bool setup(base::configreader* config);
/**
* @brief check configured or not
*/
bool is_setup() const;
private:
bool initialized = false;
/**
* @brief dependent libraries adopter
*/
base::libadopter<interface::ilog>* _log_adopter = nullptr;
/**
* @brief service library container
*/
map<std::string, base::libadopter<interface::iobject>*> _lib_container;
};
#define cossb_system_manager cossb::manager::system_manager::instance()
} /* namespace manager */
} /* namespace cossb */
#endif
<commit_msg>enable accessing component driver via broker<commit_after>/**
* @file manager.hpp
* @brief COSSB component manager
* @author Byunghun Hwang<bhhwang@nsynapse.com>
* @date 2015. 6. 21
* @details
*/
#ifndef _COSSB_MANAGER_HPP_
#define _COSSB_MANAGER_HPP_
#include <map>
#include <vector>
#include <string>
#include "arch/singleton.hpp"
#include "base/configreader.hpp"
using namespace std;
namespace cossb {
namespace base { template<class T> class libadopter; }
namespace interface {
class ilog;
class iobject;
}
namespace driver { class component_driver; }
namespace manager {
/**
* @brief component manager derived from singleton pattern
*/
class component_manager : public arch::singleton<component_manager> {
public:
component_manager();
virtual ~component_manager();
component_manager(const component_manager&) = delete;
component_manager& operator = (const component_manager&) = delete;
/**
* @brief install specific component
*/
bool install(const char* component_name);
/**
* @brief uninstall specific component
*/
bool uninstall(const char* component_name);
bool uninstall();
/**
* @brief run specific component
*/
bool run(const char* component_name);
/**
* @brief run all components
*/
bool run();
/**
* @brief stop specific component
*/
bool stop(const char* component_name);
/**
* @brief stop all components
*/
bool stop();
/**
* @brief get count of the installed components
*/
int count();
/**
* @brief return specific component driver
*/
driver::component_driver* get_driver(const char* component_name);
};
#define cossb_component_manager cossb::manager::component_manager::instance()
/**
* @brief system manager derived from singleton pattern
*/
class system_manager : public arch::singleton<system_manager> {
public:
system_manager();
virtual ~system_manager();
system_manager(const system_manager&) = delete;
system_manager& operator = (const system_manager&) = delete;
/**
* @brief setup system configuration
*/
bool setup(base::configreader* config);
/**
* @brief check configured or not
*/
bool is_setup() const;
private:
bool initialized = false;
/**
* @brief dependent libraries adopter
*/
base::libadopter<interface::ilog>* _log_adopter = nullptr;
/**
* @brief service library container
*/
map<std::string, base::libadopter<interface::iobject>*> _lib_container;
};
#define cossb_system_manager cossb::manager::system_manager::instance()
} /* namespace manager */
} /* namespace cossb */
#endif
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2013 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file led.cpp
*
* LED driver.
*/
#include <nuttx/config.h>
#include <drivers/device/device.h>
#include <drivers/drv_led.h>
/*
* Ideally we'd be able to get these from up_internal.h,
* but since we want to be able to disable the NuttX use
* of leds for system indication at will and there is no
* separate switch, we need to build independent of the
* CONFIG_ARCH_LEDS configuration switch.
*/
__BEGIN_DECLS
extern void led_init();
extern void led_on(int led);
extern void led_off(int led);
extern void led_toggle(int led);
__END_DECLS
class LED : device::CDev
{
public:
LED();
virtual ~LED();
virtual int init();
virtual int ioctl(struct file *filp, int cmd, unsigned long arg);
};
LED::LED() :
CDev("led", LED_DEVICE_PATH)
{
// force immediate init/device registration
init();
}
LED::~LED()
{
}
int
LED::init()
{
CDev::init();
led_init();
return 0;
}
int
LED::ioctl(struct file *filp, int cmd, unsigned long arg)
{
int result = OK;
switch (cmd) {
case LED_ON:
led_on(arg);
break;
case LED_OFF:
led_off(arg);
break;
case LED_TOGGLE:
led_toggle(arg);
break;
default:
result = CDev::ioctl(filp, cmd, arg);
}
return result;
}
namespace
{
LED *gLED;
}
void
drv_led_start(void)
{
if (gLED == nullptr) {
gLED = new LED;
if (gLED != nullptr)
gLED->init();
}
}
<commit_msg>Led: move to 0 based index<commit_after>/****************************************************************************
*
* Copyright (c) 2013 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file led.cpp
*
* LED driver.
*/
#include <nuttx/config.h>
#include <drivers/device/device.h>
#include <drivers/drv_led.h>
/*
* Ideally we'd be able to get these from up_internal.h,
* but since we want to be able to disable the NuttX use
* of leds for system indication at will and there is no
* separate switch, we need to build independent of the
* CONFIG_ARCH_LEDS configuration switch.
*/
__BEGIN_DECLS
extern void led_init();
extern void led_on(int led);
extern void led_off(int led);
extern void led_toggle(int led);
__END_DECLS
class LED : device::CDev
{
public:
LED();
virtual ~LED();
virtual int init();
virtual int ioctl(struct file *filp, int cmd, unsigned long arg);
};
LED::LED() :
CDev("led", LED0_DEVICE_PATH)
{
// force immediate init/device registration
init();
}
LED::~LED()
{
}
int
LED::init()
{
CDev::init();
led_init();
return 0;
}
int
LED::ioctl(struct file *filp, int cmd, unsigned long arg)
{
int result = OK;
switch (cmd) {
case LED_ON:
led_on(arg);
break;
case LED_OFF:
led_off(arg);
break;
case LED_TOGGLE:
led_toggle(arg);
break;
default:
result = CDev::ioctl(filp, cmd, arg);
}
return result;
}
namespace
{
LED *gLED;
}
void
drv_led_start(void)
{
if (gLED == nullptr) {
gLED = new LED;
if (gLED != nullptr)
gLED->init();
}
}
<|endoftext|> |
<commit_before>#ifndef INCLUDED_TOBY_VARIANT_H
#define INCLUDED_TOBY_VARIANT_H
#include "overload_set.hpp"
#include <cstddef>
#include <stdexcept>
#include <spdlog/sinks/null_sink.h>
#include <spdlog/spdlog.h>
namespace toby {
namespace detail {
inline auto logger() {
auto l = spdlog::get("variant");
if (l) {
return l;
}
return spdlog::create("variant",
spdlog::sink_ptr(new spdlog::sinks::null_sink_st()));
}
template <typename I, I N, typename... Ts>
struct variant_construct;
template <typename I, I N>
struct variant_construct<I, N> {
static I construct();
};
template <typename I, I N, typename T, typename... Ts>
struct variant_construct<I, N, T, Ts...>
: private variant_construct<I, N + 1, Ts...> {
using super = variant_construct<I, N + 1, Ts...>;
static I construct(void* storage, const T& value) {
logger()->debug() << "copy construct<" << N << ">";
new (storage) T(value);
return N;
}
static I construct(void* storage, T&& value) {
logger()->debug() << "move construct<" << N << ">";
new (storage) T(std::forward<T>(value));
return N;
}
using super::construct;
};
template <typename I, I N, typename... Ts>
struct variant_visit;
template <typename I, I N>
struct variant_visit<I, N> {
template <typename R, typename F>
static R visit_helper_const(I tag, const void*, F&&) {
throw std::logic_error("variant tag invalid: " + std::to_string(tag));
}
template <typename R, typename F>
static R visit_helper_rvalue(I tag, void*, F&&) {
throw std::logic_error("variant tag invalid: " + std::to_string(tag));
}
};
template <typename I, I N, typename T, typename... Ts>
struct variant_visit<I, N, T, Ts...> : private variant_visit<I, N + 1, Ts...> {
using super = variant_visit<I, N + 1, Ts...>;
template <typename R, typename F>
static R visit_helper_const(I tag, const void* storage, F&& f) {
logger()->debug() << "visit_helper<" << N << "> const& (" << tag << ")";
if (tag == N) {
return f(*reinterpret_cast<const T*>(storage));
}
return super::template visit_helper_const<R>(tag, storage,
std::forward<F>(f));
}
template <typename R, typename F>
static R visit_helper_rvalue(I tag, void* storage, F&& f) {
logger()->debug() << "visit_helper<" << N << "> && (" << tag << ")";
if (tag == N) {
return f(std::move(*reinterpret_cast<T*>(storage)));
}
return super::template visit_helper_rvalue<R>(tag, storage,
std::forward<F>(f));
}
};
template <uintmax_t N, typename Enable = void>
struct smallest_unisnged_type;
template <uintmax_t N>
struct smallest_unisnged_type<
N, typename std::enable_if_t<N <= std::numeric_limits<uint8_t>::max()>> {
using type = uint8_t;
};
template <uintmax_t N>
using smallest_unisnged_type_t = typename smallest_unisnged_type<N>::type;
template <typename... Ts>
struct variant_helper {
using tag_type = smallest_unisnged_type_t<sizeof...(Ts)>;
using super_construct = variant_construct<tag_type, 0, Ts...>;
using super_visit = variant_visit<tag_type, 0, Ts...>;
};
}
template <typename... Ts>
class variant : private detail::variant_helper<Ts...>::super_construct,
private detail::variant_helper<Ts...>::super_visit {
using helper = detail::variant_helper<Ts...>;
using super_construct = typename helper::super_construct;
using super_visit = typename helper::super_visit;
public:
typename std::aligned_union_t<0, char, Ts...> storage;
typename helper::tag_type tag;
private:
using super_construct::construct;
void destruct() {
std::move(*this).template visit<void>([this](auto&& v) {
using T = std::decay_t<decltype(v)>;
v.~T();
});
}
public:
template <typename T, typename = decltype(construct(
&storage, std::forward<T>(std::declval<T>())))>
variant(T&& value) {
tag = construct(&storage, std::forward<T>(value));
}
variant(const variant& other) {
detail::logger()->debug("variant copy constructor");
other.visit<void>(
[this](auto&& value) { tag = this->construct(&storage, value); });
}
variant(variant&& other) {
detail::logger()->debug("variant move constructor");
std::move(other).template visit<void>([this](auto&& value) {
tag = this->construct(&storage, std::forward<decltype(value)>(value));
});
}
template <typename T, typename = decltype(construct(
&storage, std::forward<T>(std::declval<T>())))>
variant& operator=(T&& value) {
destruct();
tag = construct(&storage, std::forward<T>(value));
return *this;
}
variant& operator=(const variant& other) {
detail::logger()->debug("variant copy assignment");
destruct();
other.visit<void>(
[this](auto&& value) { tag = this->construct(&storage, value); });
return *this;
}
variant& operator=(variant&& other) {
detail::logger()->debug("variant move assignment");
destruct();
std::move(other).template visit<void>([this](auto&& value) {
tag = this->construct(&storage, std::forward<decltype(value)>(value));
});
return *this;
}
~variant() { destruct(); }
template <typename R, typename F>
auto visit(F&& f) const& {
detail::logger()->debug("visit const &");
return super_visit::template visit_helper_const<R>(tag, &storage,
std::forward<F>(f));
}
template <typename R, typename F>
auto visit(F&& f) && {
detail::logger()->debug("visit &&");
return std::move(*this).super_visit::template visit_helper_rvalue<R>(
tag, &storage, std::forward<F>(f));
}
template <typename R, typename... Fs>
auto visit(Fs&&... fs) const& {
return visit<R>(overload_set<Fs...>(std::forward<Fs>(fs)...));
}
template <typename R, typename... Fs>
auto visit(Fs&&... fs) && {
return std::move(*this).template visit<R>(
overload_set<Fs...>(std::forward<Fs>(fs)...));
}
};
template <typename... Ts>
std::ostream& operator<<(std::ostream& os, const variant<Ts...>& v) {
os << "variant[" << v.tag << "]: ";
v.template visit<void>([&os](const auto& x) { os << x; });
return os;
}
} // namespace toby
#endif
<commit_msg>variant: enforce unique types<commit_after>#ifndef INCLUDED_TOBY_VARIANT_H
#define INCLUDED_TOBY_VARIANT_H
#include "overload_set.hpp"
#include <cstddef>
#include <experimental/type_traits>
#include <stdexcept>
#include <spdlog/sinks/null_sink.h>
#include <spdlog/spdlog.h>
namespace toby {
namespace detail {
inline auto logger() {
auto l = spdlog::get("variant");
if (l) {
return l;
}
return spdlog::create("variant",
spdlog::sink_ptr(new spdlog::sinks::null_sink_st()));
}
template <typename I, I N, typename... Ts>
struct variant_construct;
template <typename I, I N>
struct variant_construct<I, N> {
static I construct();
};
template <typename I, I N, typename T, typename... Ts>
struct variant_construct<I, N, T, Ts...>
: private variant_construct<I, N + 1, Ts...> {
using super = variant_construct<I, N + 1, Ts...>;
static_assert(!std::experimental::disjunction<std::is_same<T, Ts>...>::value,
"types must be unique");
static I construct(void* storage, const T& value) {
logger()->debug() << "copy construct<" << N << ">";
new (storage) T(value);
return N;
}
static I construct(void* storage, T&& value) {
logger()->debug() << "move construct<" << N << ">";
new (storage) T(std::forward<T>(value));
return N;
}
using super::construct;
};
template <typename I, I N, typename... Ts>
struct variant_visit;
template <typename I, I N>
struct variant_visit<I, N> {
template <typename R, typename F>
static R visit_helper_const(I tag, const void*, F&&) {
throw std::logic_error("variant tag invalid: " + std::to_string(tag));
}
template <typename R, typename F>
static R visit_helper_rvalue(I tag, void*, F&&) {
throw std::logic_error("variant tag invalid: " + std::to_string(tag));
}
};
template <typename I, I N, typename T, typename... Ts>
struct variant_visit<I, N, T, Ts...> : private variant_visit<I, N + 1, Ts...> {
using super = variant_visit<I, N + 1, Ts...>;
template <typename R, typename F>
static R visit_helper_const(I tag, const void* storage, F&& f) {
logger()->debug() << "visit_helper<" << N << "> const& (" << tag << ")";
if (tag == N) {
return f(*reinterpret_cast<const T*>(storage));
}
return super::template visit_helper_const<R>(tag, storage,
std::forward<F>(f));
}
template <typename R, typename F>
static R visit_helper_rvalue(I tag, void* storage, F&& f) {
logger()->debug() << "visit_helper<" << N << "> && (" << tag << ")";
if (tag == N) {
return f(std::move(*reinterpret_cast<T*>(storage)));
}
return super::template visit_helper_rvalue<R>(tag, storage,
std::forward<F>(f));
}
};
template <uintmax_t N, typename Enable = void>
struct smallest_unisnged_type;
template <uintmax_t N>
struct smallest_unisnged_type<
N, typename std::enable_if_t<N <= std::numeric_limits<uint8_t>::max()>> {
using type = uint8_t;
};
template <uintmax_t N>
using smallest_unisnged_type_t = typename smallest_unisnged_type<N>::type;
template <typename... Ts>
struct variant_helper {
using tag_type = smallest_unisnged_type_t<sizeof...(Ts)>;
using super_construct = variant_construct<tag_type, 0, Ts...>;
using super_visit = variant_visit<tag_type, 0, Ts...>;
};
}
template <typename... Ts>
class variant : private detail::variant_helper<Ts...>::super_construct,
private detail::variant_helper<Ts...>::super_visit {
using helper = detail::variant_helper<Ts...>;
using super_construct = typename helper::super_construct;
using super_visit = typename helper::super_visit;
public:
typename std::aligned_union_t<0, char, Ts...> storage;
typename helper::tag_type tag;
private:
using super_construct::construct;
void destruct() {
std::move(*this).template visit<void>([this](auto&& v) {
using T = std::decay_t<decltype(v)>;
v.~T();
});
}
public:
template <typename T, typename = decltype(construct(
&storage, std::forward<T>(std::declval<T>())))>
variant(T&& value) {
tag = construct(&storage, std::forward<T>(value));
}
variant(const variant& other) {
detail::logger()->debug("variant copy constructor");
other.visit<void>(
[this](auto&& value) { tag = this->construct(&storage, value); });
}
variant(variant&& other) {
detail::logger()->debug("variant move constructor");
std::move(other).template visit<void>([this](auto&& value) {
tag = this->construct(&storage, std::forward<decltype(value)>(value));
});
}
template <typename T, typename = decltype(construct(
&storage, std::forward<T>(std::declval<T>())))>
variant& operator=(T&& value) {
destruct();
tag = construct(&storage, std::forward<T>(value));
return *this;
}
variant& operator=(const variant& other) {
detail::logger()->debug("variant copy assignment");
destruct();
other.visit<void>(
[this](auto&& value) { tag = this->construct(&storage, value); });
return *this;
}
variant& operator=(variant&& other) {
detail::logger()->debug("variant move assignment");
destruct();
std::move(other).template visit<void>([this](auto&& value) {
tag = this->construct(&storage, std::forward<decltype(value)>(value));
});
return *this;
}
~variant() { destruct(); }
template <typename R, typename F>
auto visit(F&& f) const& {
detail::logger()->debug("visit const &");
return super_visit::template visit_helper_const<R>(tag, &storage,
std::forward<F>(f));
}
template <typename R, typename F>
auto visit(F&& f) && {
detail::logger()->debug("visit &&");
return std::move(*this).super_visit::template visit_helper_rvalue<R>(
tag, &storage, std::forward<F>(f));
}
template <typename R, typename... Fs>
auto visit(Fs&&... fs) const& {
return visit<R>(overload_set<Fs...>(std::forward<Fs>(fs)...));
}
template <typename R, typename... Fs>
auto visit(Fs&&... fs) && {
return std::move(*this).template visit<R>(
overload_set<Fs...>(std::forward<Fs>(fs)...));
}
};
template <typename... Ts>
std::ostream& operator<<(std::ostream& os, const variant<Ts...>& v) {
os << "variant[" << v.tag << "]: ";
v.template visit<void>([&os](const auto& x) { os << x; });
return os;
}
} // namespace toby
#endif
<|endoftext|> |
<commit_before>/********************************************************************
* Description: inijoint.cc
* INI file initialization routines for joint/axis NML
*
* Derived from a work by Fred Proctor & Will Shackleford
*
* Author:
* License: GPL Version 2
* System: Linux
*
* Copyright (c) 2004-2009 All rights reserved.
********************************************************************/
#include <unistd.h>
#include <stdio.h> // NULL
#include <stdlib.h> // atol(), _itoa()
#include <string.h> // strcmp()
#include <ctype.h> // isdigit()
#include <sys/types.h>
#include <sys/stat.h>
#include "emc.hh"
#include "rcs_print.hh"
#include "emcIniFile.hh"
#include "inijoint.hh" // these decls
#include "emcglb.h" // EMC_DEBUG
#include "emccfg.h" // default values for globals
/*
loadJoint(int joint)
Loads ini file params for joint, joint = 0, ...
TYPE <LINEAR ANGULAR> type of joint
MAX_VELOCITY <float> max vel for joint
MAX_ACCELERATION <float> max accel for joint
BACKLASH <float> backlash
MIN_LIMIT <float> minimum soft position limit
MAX_LIMIT <float> maximum soft position limit
FERROR <float> maximum following error, scaled to max vel
MIN_FERROR <float> minimum following error
HOME <float> home position (where to go after home)
HOME_FINAL_VEL <float> speed to move from HOME_OFFSET to HOME location (at the end of homing)
HOME_OFFSET <float> home switch/index pulse location
HOME_SEARCH_VEL <float> homing speed, search phase
HOME_LATCH_VEL <float> homing speed, latch phase
HOME_USE_INDEX <bool> use index pulse when homing
HOME_IGNORE_LIMITS <bool> ignore limit switches when homing
COMP_FILE <filename> file of joint compensation points
calls:
emcJointSetType(int joint, unsigned char jointType);
emcJointSetUnits(int joint, double units);
emcJointSetBacklash(int joint, double backlash);
emcJointSetMinPositionLimit(int joint, double limit);
emcJointSetMaxPositionLimit(int joint, double limit);
emcJointSetFerror(int joint, double ferror);
emcJointSetMinFerror(int joint, double ferror);
emcJointSetHomingParams(int joint, double home, double offset, double home_vel,
double search_vel, double latch_vel, int use_index,
int ignore_limits, int is_shared, int sequence, int volatile_home));
emcJointActivate(int joint);
emcJointSetMaxVelocity(int joint, double vel);
emcJointSetMaxAcceleration(int joint, double acc);
emcJointLoadComp(int joint, const char * file, int comp_file_type);
*/
static int loadJoint(int joint, EmcIniFile *jointIniFile)
{
char jointString[16];
const char *inistring;
EmcJointType jointType;
double units;
double backlash;
double offset;
double limit;
double home;
double search_vel;
double latch_vel;
double home_vel; // moving from OFFSET to HOME
bool use_index;
bool ignore_limits;
bool is_shared;
int sequence;
int volatile_home;
int locking_indexer;
int comp_file_type; //type for the compensation file. type==0 means nom, forw, rev.
double maxVelocity;
double maxAcceleration;
double ferror;
// compose string to match, joint = 0 -> JOINT_0, etc.
sprintf(jointString, "JOINT_%d", joint);
jointIniFile->EnableExceptions(EmcIniFile::ERR_CONVERSION);
try {
// set joint type
jointType = EMC_LINEAR; // default
jointIniFile->Find(&jointType, "TYPE", jointString);
if (0 != emcJointSetType(joint, jointType)) {
return -1;
}
// set units
if(jointType == EMC_LINEAR){
units = emcTrajGetLinearUnits();
}else{
units = emcTrajGetAngularUnits();
}
if (0 != emcJointSetUnits(joint, units)) {
return -1;
}
// set backlash
backlash = 0; // default
jointIniFile->Find(&backlash, "BACKLASH", jointString);
if (0 != emcJointSetBacklash(joint, backlash)) {
return -1;
}
// set min position limit
limit = -1e99; // default
jointIniFile->Find(&limit, "MIN_LIMIT", jointString);
if (0 != emcJointSetMinPositionLimit(joint, limit)) {
return -1;
}
// set max position limit
limit = 1e99; // default
jointIniFile->Find(&limit, "MAX_LIMIT", jointString);
if (0 != emcJointSetMaxPositionLimit(joint, limit)) {
return -1;
}
// set following error limit (at max speed)
ferror = 1; // default
jointIniFile->Find(&ferror, "FERROR", jointString);
if (0 != emcJointSetFerror(joint, ferror)) {
return -1;
}
// do MIN_FERROR, if it's there. If not, use value of maxFerror above
jointIniFile->Find(&ferror, "MIN_FERROR", jointString);
if (0 != emcJointSetMinFerror(joint, ferror)) {
return -1;
}
// set homing paramsters (total of 6)
home = 0; // default
jointIniFile->Find(&home, "HOME", jointString);
offset = 0; // default
jointIniFile->Find(&offset, "HOME_OFFSET", jointString);
search_vel = 0; // default
jointIniFile->Find(&search_vel, "HOME_SEARCH_VEL", jointString);
latch_vel = 0; // default
jointIniFile->Find(&latch_vel, "HOME_LATCH_VEL", jointString);
home_vel = -1; // default (rapid)
jointIniFile->Find(&home_vel, "HOME_VEL", jointString);
is_shared = false; // default
jointIniFile->Find(&is_shared, "HOME_IS_SHARED", jointString);
use_index = false; // default
jointIniFile->Find(&use_index, "HOME_USE_INDEX", jointString);
ignore_limits = false; // default
jointIniFile->Find(&ignore_limits, "HOME_IGNORE_LIMITS", jointString);
sequence = -1; // default
jointIniFile->Find(&sequence, "HOME_SEQUENCE", jointString);
volatile_home = 0; // default
jointIniFile->Find(&volatile_home, "VOLATILE_HOME", jointString);
locking_indexer = false;
jointIniFile->Find(&locking_indexer, "LOCKING_INDEXER", jointString);
// issue NML message to set all params
if (0 != emcJointSetHomingParams(joint, home, offset, home_vel, search_vel,
latch_vel, (int)use_index, (int)ignore_limits,
(int)is_shared, sequence, volatile_home, locking_indexer)) {
return -1;
}
// set maximum velocity
maxVelocity = DEFAULT_JOINT_MAX_VELOCITY;
jointIniFile->Find(&maxVelocity, "MAX_VELOCITY", jointString);
if (0 != emcJointSetMaxVelocity(joint, maxVelocity)) {
return -1;
}
maxAcceleration = DEFAULT_JOINT_MAX_ACCELERATION;
jointIniFile->Find(&maxAcceleration, "MAX_ACCELERATION", jointString);
if (0 != emcJointSetMaxAcceleration(joint, maxAcceleration)) {
return -1;
}
comp_file_type = 0; // default
jointIniFile->Find(&comp_file_type, "COMP_FILE_TYPE", jointString);
if (NULL != (inistring = jointIniFile->Find("COMP_FILE", jointString))) {
if (0 != emcJointLoadComp(joint, inistring, comp_file_type)) {
return -1;
}
}
}
catch (EmcIniFile::Exception &e) {
e.Print();
return -1;
}
// lastly, activate joint. Do this last so that the motion controller
// won't flag errors midway during configuration
if (0 != emcJointActivate(joint)) {
return -1;
}
return 0;
}
/*
iniJoint(int joint, const char *filename)
Loads ini file parameters for specified joint, [0 .. AXES - 1]
Looks for AXES in TRAJ section for how many to do, up to
EMC_JOINT_MAX.
*/
int iniJoint(int joint, const char *filename)
{
EmcIniFile jointIniFile(EmcIniFile::ERR_TAG_NOT_FOUND |
EmcIniFile::ERR_SECTION_NOT_FOUND |
EmcIniFile::ERR_CONVERSION);
if (jointIniFile.Open(filename) == false) {
return -1;
}
// load its values
if (0 != loadJoint(joint, &jointIniFile)) {
return -1;
}
return 0;
}
<commit_msg>Rename HOME_VEL to HOME_FINAL_VEL ini file entry<commit_after>/********************************************************************
* Description: inijoint.cc
* INI file initialization routines for joint/axis NML
*
* Derived from a work by Fred Proctor & Will Shackleford
*
* Author:
* License: GPL Version 2
* System: Linux
*
* Copyright (c) 2004-2009 All rights reserved.
********************************************************************/
#include <unistd.h>
#include <stdio.h> // NULL
#include <stdlib.h> // atol(), _itoa()
#include <string.h> // strcmp()
#include <ctype.h> // isdigit()
#include <sys/types.h>
#include <sys/stat.h>
#include "emc.hh"
#include "rcs_print.hh"
#include "emcIniFile.hh"
#include "inijoint.hh" // these decls
#include "emcglb.h" // EMC_DEBUG
#include "emccfg.h" // default values for globals
/*
loadJoint(int joint)
Loads ini file params for joint, joint = 0, ...
TYPE <LINEAR ANGULAR> type of joint
MAX_VELOCITY <float> max vel for joint
MAX_ACCELERATION <float> max accel for joint
BACKLASH <float> backlash
MIN_LIMIT <float> minimum soft position limit
MAX_LIMIT <float> maximum soft position limit
FERROR <float> maximum following error, scaled to max vel
MIN_FERROR <float> minimum following error
HOME <float> home position (where to go after home)
HOME_FINAL_VEL <float> speed to move from HOME_OFFSET to HOME location (at the end of homing)
HOME_OFFSET <float> home switch/index pulse location
HOME_SEARCH_VEL <float> homing speed, search phase
HOME_LATCH_VEL <float> homing speed, latch phase
HOME_USE_INDEX <bool> use index pulse when homing
HOME_IGNORE_LIMITS <bool> ignore limit switches when homing
COMP_FILE <filename> file of joint compensation points
calls:
emcJointSetType(int joint, unsigned char jointType);
emcJointSetUnits(int joint, double units);
emcJointSetBacklash(int joint, double backlash);
emcJointSetMinPositionLimit(int joint, double limit);
emcJointSetMaxPositionLimit(int joint, double limit);
emcJointSetFerror(int joint, double ferror);
emcJointSetMinFerror(int joint, double ferror);
emcJointSetHomingParams(int joint, double home, double offset, double home_vel,
double search_vel, double latch_vel, int use_index,
int ignore_limits, int is_shared, int sequence, int volatile_home));
emcJointActivate(int joint);
emcJointSetMaxVelocity(int joint, double vel);
emcJointSetMaxAcceleration(int joint, double acc);
emcJointLoadComp(int joint, const char * file, int comp_file_type);
*/
static int loadJoint(int joint, EmcIniFile *jointIniFile)
{
char jointString[16];
const char *inistring;
EmcJointType jointType;
double units;
double backlash;
double offset;
double limit;
double home;
double search_vel;
double latch_vel;
double final_vel; // moving from OFFSET to HOME
bool use_index;
bool ignore_limits;
bool is_shared;
int sequence;
int volatile_home;
int locking_indexer;
int comp_file_type; //type for the compensation file. type==0 means nom, forw, rev.
double maxVelocity;
double maxAcceleration;
double ferror;
// compose string to match, joint = 0 -> JOINT_0, etc.
sprintf(jointString, "JOINT_%d", joint);
jointIniFile->EnableExceptions(EmcIniFile::ERR_CONVERSION);
try {
// set joint type
jointType = EMC_LINEAR; // default
jointIniFile->Find(&jointType, "TYPE", jointString);
if (0 != emcJointSetType(joint, jointType)) {
return -1;
}
// set units
if(jointType == EMC_LINEAR){
units = emcTrajGetLinearUnits();
}else{
units = emcTrajGetAngularUnits();
}
if (0 != emcJointSetUnits(joint, units)) {
return -1;
}
// set backlash
backlash = 0; // default
jointIniFile->Find(&backlash, "BACKLASH", jointString);
if (0 != emcJointSetBacklash(joint, backlash)) {
return -1;
}
// set min position limit
limit = -1e99; // default
jointIniFile->Find(&limit, "MIN_LIMIT", jointString);
if (0 != emcJointSetMinPositionLimit(joint, limit)) {
return -1;
}
// set max position limit
limit = 1e99; // default
jointIniFile->Find(&limit, "MAX_LIMIT", jointString);
if (0 != emcJointSetMaxPositionLimit(joint, limit)) {
return -1;
}
// set following error limit (at max speed)
ferror = 1; // default
jointIniFile->Find(&ferror, "FERROR", jointString);
if (0 != emcJointSetFerror(joint, ferror)) {
return -1;
}
// do MIN_FERROR, if it's there. If not, use value of maxFerror above
jointIniFile->Find(&ferror, "MIN_FERROR", jointString);
if (0 != emcJointSetMinFerror(joint, ferror)) {
return -1;
}
// set homing paramsters (total of 6)
home = 0; // default
jointIniFile->Find(&home, "HOME", jointString);
offset = 0; // default
jointIniFile->Find(&offset, "HOME_OFFSET", jointString);
search_vel = 0; // default
jointIniFile->Find(&search_vel, "HOME_SEARCH_VEL", jointString);
latch_vel = 0; // default
jointIniFile->Find(&latch_vel, "HOME_LATCH_VEL", jointString);
final_vel = -1; // default (rapid)
jointIniFile->Find(&final_vel, "HOME_FINAL_VEL", jointString);
is_shared = false; // default
jointIniFile->Find(&is_shared, "HOME_IS_SHARED", jointString);
use_index = false; // default
jointIniFile->Find(&use_index, "HOME_USE_INDEX", jointString);
ignore_limits = false; // default
jointIniFile->Find(&ignore_limits, "HOME_IGNORE_LIMITS", jointString);
sequence = -1; // default
jointIniFile->Find(&sequence, "HOME_SEQUENCE", jointString);
volatile_home = 0; // default
jointIniFile->Find(&volatile_home, "VOLATILE_HOME", jointString);
locking_indexer = false;
jointIniFile->Find(&locking_indexer, "LOCKING_INDEXER", jointString);
// issue NML message to set all params
if (0 != emcJointSetHomingParams(joint, home, offset, final_vel, search_vel,
latch_vel, (int)use_index, (int)ignore_limits,
(int)is_shared, sequence, volatile_home, locking_indexer)) {
return -1;
}
// set maximum velocity
maxVelocity = DEFAULT_JOINT_MAX_VELOCITY;
jointIniFile->Find(&maxVelocity, "MAX_VELOCITY", jointString);
if (0 != emcJointSetMaxVelocity(joint, maxVelocity)) {
return -1;
}
maxAcceleration = DEFAULT_JOINT_MAX_ACCELERATION;
jointIniFile->Find(&maxAcceleration, "MAX_ACCELERATION", jointString);
if (0 != emcJointSetMaxAcceleration(joint, maxAcceleration)) {
return -1;
}
comp_file_type = 0; // default
jointIniFile->Find(&comp_file_type, "COMP_FILE_TYPE", jointString);
if (NULL != (inistring = jointIniFile->Find("COMP_FILE", jointString))) {
if (0 != emcJointLoadComp(joint, inistring, comp_file_type)) {
return -1;
}
}
}
catch (EmcIniFile::Exception &e) {
e.Print();
return -1;
}
// lastly, activate joint. Do this last so that the motion controller
// won't flag errors midway during configuration
if (0 != emcJointActivate(joint)) {
return -1;
}
return 0;
}
/*
iniJoint(int joint, const char *filename)
Loads ini file parameters for specified joint, [0 .. AXES - 1]
Looks for AXES in TRAJ section for how many to do, up to
EMC_JOINT_MAX.
*/
int iniJoint(int joint, const char *filename)
{
EmcIniFile jointIniFile(EmcIniFile::ERR_TAG_NOT_FOUND |
EmcIniFile::ERR_SECTION_NOT_FOUND |
EmcIniFile::ERR_CONVERSION);
if (jointIniFile.Open(filename) == false) {
return -1;
}
// load its values
if (0 != loadJoint(joint, &jointIniFile)) {
return -1;
}
return 0;
}
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (c) 2015 Stefan Tröger <stefantroeger@gmx.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* 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., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <cfloat>
#include <BRepBuilderAPI_MakeFace.hxx>
#endif
#include "ShapeBinder.h"
#include <Mod/Part/App/TopoShape.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
using namespace PartDesign;
// ============================================================================
PROPERTY_SOURCE(PartDesign::ShapeBinder, Part::Feature)
ShapeBinder::ShapeBinder()
{
ADD_PROPERTY_TYPE(Support, (0,0), "",(App::PropertyType)(App::Prop_None),"Support of the geometry");
Placement.setStatus(App::Property::Hidden, true);
}
ShapeBinder::~ShapeBinder()
{
}
short int ShapeBinder::mustExecute(void) const {
if(Support.isTouched())
return 1;
return Part::Feature::mustExecute();
}
App::DocumentObjectExecReturn* ShapeBinder::execute(void) {
if(! this->isRestoring()){
Part::Feature* obj = nullptr;
std::vector<std::string> subs;
ShapeBinder::getFilteredReferences(&Support, obj, subs);
//if we have a link we rebuild the shape, but we change nothing if we are a simple copy
if(obj) {
Shape.setValue(ShapeBinder::buildShapeFromReferences(obj, subs).getShape());
Placement.setValue(obj->Placement.getValue());
}
}
return Part::Feature::execute();
}
void ShapeBinder::getFilteredReferences(App::PropertyLinkSubList* prop, Part::Feature*& obj, std::vector< std::string >& subobjects) {
obj = nullptr;
subobjects.clear();
auto objs = prop->getValues();
auto subs = prop->getSubValues();
if(objs.empty()) {
return;
}
//we only allow one part feature, so get the first one we find
size_t index = 0;
while(index < objs.size() && !objs[index]->isDerivedFrom(Part::Feature::getClassTypeId()))
index++;
//do we have any part feature?
if(index >= objs.size())
return;
obj = static_cast<Part::Feature*>(objs[index]);
//if we have no subshpape we use the whole shape
if(subs[index].empty()) {
return;
}
//collect all subshapes for the object
index = 0;
for(std::string sub : subs) {
//we only allow subshapes from a single Part::Feature
if(objs[index] != obj)
continue;
//in this mode the full shape is not allowed, as we already started the subshape
//processing
if(sub.empty())
continue;
subobjects.push_back(sub);
}
}
Part::TopoShape ShapeBinder::buildShapeFromReferences( Part::Feature* obj, std::vector< std::string > subs) {
if(!obj)
return TopoDS_Shape();
if(subs.empty())
return obj->Shape.getShape();
//if we use multiple subshapes we build a shape from them by fusing them together
Part::TopoShape base;
std::vector<TopoDS_Shape> operators;
for(std::string sub : subs) {
if(base.isNull())
base = obj->Shape.getShape().getSubShape(sub.c_str());
else
operators.push_back(obj->Shape.getShape().getSubShape(sub.c_str()));
}
try {
if(!operators.empty() && !base.isNull())
return base.fuse(operators);
}
catch(...) {
return base;
}
return base;
}
void ShapeBinder::handleChangedPropertyType(Base::XMLReader &reader, const char *TypeName, App::Property *prop)
{
// The type of Support was App::PropertyLinkSubList in the past
if (prop == &Support && strcmp(TypeName, "App::PropertyLinkSubList") == 0) {
Support.Restore(reader);
}
}
<commit_msg>fixes #0003161: Shape Binder not at expected place<commit_after>/***************************************************************************
* Copyright (c) 2015 Stefan Tröger <stefantroeger@gmx.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* 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., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <cfloat>
#include <BRepBuilderAPI_MakeFace.hxx>
#endif
#include "ShapeBinder.h"
#include <Mod/Part/App/TopoShape.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
using namespace PartDesign;
// ============================================================================
PROPERTY_SOURCE(PartDesign::ShapeBinder, Part::Feature)
ShapeBinder::ShapeBinder()
{
ADD_PROPERTY_TYPE(Support, (0,0), "",(App::PropertyType)(App::Prop_None),"Support of the geometry");
Placement.setStatus(App::Property::Hidden, true);
}
ShapeBinder::~ShapeBinder()
{
}
short int ShapeBinder::mustExecute(void) const {
if(Support.isTouched())
return 1;
return Part::Feature::mustExecute();
}
App::DocumentObjectExecReturn* ShapeBinder::execute(void) {
if(! this->isRestoring()){
Part::Feature* obj = nullptr;
std::vector<std::string> subs;
ShapeBinder::getFilteredReferences(&Support, obj, subs);
//if we have a link we rebuild the shape, but we change nothing if we are a simple copy
if(obj) {
Part::TopoShape shape = ShapeBinder::buildShapeFromReferences(obj, subs);
Base::Placement placement(shape.getTransform());
Shape.setValue(shape);
Placement.setValue(placement);
}
}
return Part::Feature::execute();
}
void ShapeBinder::getFilteredReferences(App::PropertyLinkSubList* prop, Part::Feature*& obj, std::vector< std::string >& subobjects) {
obj = nullptr;
subobjects.clear();
auto objs = prop->getValues();
auto subs = prop->getSubValues();
if(objs.empty()) {
return;
}
//we only allow one part feature, so get the first one we find
size_t index = 0;
while(index < objs.size() && !objs[index]->isDerivedFrom(Part::Feature::getClassTypeId()))
index++;
//do we have any part feature?
if(index >= objs.size())
return;
obj = static_cast<Part::Feature*>(objs[index]);
//if we have no subshpape we use the whole shape
if(subs[index].empty()) {
return;
}
//collect all subshapes for the object
index = 0;
for(std::string sub : subs) {
//we only allow subshapes from a single Part::Feature
if(objs[index] != obj)
continue;
//in this mode the full shape is not allowed, as we already started the subshape
//processing
if(sub.empty())
continue;
subobjects.push_back(sub);
}
}
Part::TopoShape ShapeBinder::buildShapeFromReferences( Part::Feature* obj, std::vector< std::string > subs) {
if(!obj)
return TopoDS_Shape();
if(subs.empty())
return obj->Shape.getShape();
//if we use multiple subshapes we build a shape from them by fusing them together
Part::TopoShape base;
std::vector<TopoDS_Shape> operators;
for(std::string sub : subs) {
if(base.isNull())
base = obj->Shape.getShape().getSubShape(sub.c_str());
else
operators.push_back(obj->Shape.getShape().getSubShape(sub.c_str()));
}
try {
if(!operators.empty() && !base.isNull())
return base.fuse(operators);
}
catch(...) {
return base;
}
return base;
}
void ShapeBinder::handleChangedPropertyType(Base::XMLReader &reader, const char *TypeName, App::Property *prop)
{
// The type of Support was App::PropertyLinkSubList in the past
if (prop == &Support && strcmp(TypeName, "App::PropertyLinkSubList") == 0) {
Support.Restore(reader);
}
}
<|endoftext|> |
<commit_before>// Copyright (C) 2012 Jérôme Leclercq
// This file is part of the "Nazara Engine - Renderer module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Renderer/OpenGL.hpp>
#include <Nazara/Renderer/HardwareBuffer.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Renderer/Context.hpp>
#include <cstring>
#include <stdexcept>
#include <Nazara/Renderer/Debug.hpp>
namespace
{
using LockRoutine = nzUInt8* (*)(nzBufferType type, nzBufferAccess access, unsigned int offset, unsigned int size);
nzUInt8* LockBuffer(nzBufferType type, nzBufferAccess access, unsigned int offset, unsigned int size)
{
NazaraUnused(size);
if (access == nzBufferAccess_DiscardAndWrite)
{
GLint bufSize;
glGetBufferParameteriv(NzOpenGL::BufferTargetBinding[type], GL_BUFFER_SIZE, &bufSize);
GLint bufUsage;
glGetBufferParameteriv(NzOpenGL::BufferTargetBinding[type], GL_BUFFER_USAGE, &bufUsage);
// On discard le buffer
glBufferData(NzOpenGL::BufferTargetBinding[type], bufSize, nullptr, bufUsage);
}
void* ptr = glMapBuffer(NzOpenGL::BufferTarget[type], NzOpenGL::BufferLock[access]);
if (ptr)
return reinterpret_cast<nzUInt8*>(ptr) + offset;
else
return nullptr;
}
nzUInt8* LockBufferRange(nzBufferType type, nzBufferAccess access, unsigned int offset, unsigned int size)
{
return reinterpret_cast<nzUInt8*>(glMapBufferRange(NzOpenGL::BufferTarget[type], offset, size, NzOpenGL::BufferLockRange[access]));
}
nzUInt8* LockBufferFirstRun(nzBufferType type, nzBufferAccess access, unsigned int offset, unsigned int size);
LockRoutine mapBuffer = LockBufferFirstRun;
nzUInt8* LockBufferFirstRun(nzBufferType type, nzBufferAccess access, unsigned int offset, unsigned int size)
{
if (glMapBufferRange)
mapBuffer = LockBufferRange;
else
mapBuffer = LockBuffer;
return mapBuffer(type, access, offset, size);
}
}
NzHardwareBuffer::NzHardwareBuffer(NzBuffer* parent, nzBufferType type) :
m_type(type),
m_parent(parent)
{
}
NzHardwareBuffer::~NzHardwareBuffer()
{
}
void NzHardwareBuffer::Bind()
{
#ifdef NAZARA_DEBUG
if (NzContext::GetCurrent() == nullptr)
{
NazaraError("No active context");
return;
}
#endif
glBindBuffer(NzOpenGL::BufferTarget[m_type], m_buffer);
}
bool NzHardwareBuffer::Create(unsigned int size, nzBufferUsage usage)
{
NzContext::EnsureContext();
m_buffer = 0;
glGenBuffers(1, &m_buffer);
GLint previous;
glGetIntegerv(NzOpenGL::BufferTargetBinding[m_type], &previous);
glBindBuffer(NzOpenGL::BufferTarget[m_type], m_buffer);
glBufferData(NzOpenGL::BufferTarget[m_type], size, nullptr, NzOpenGL::BufferUsage[usage]);
// Pour ne pas perturber le rendu, on n'interfère pas avec le binding déjà présent
if (previous != 0)
glBindBuffer(NzOpenGL::BufferTarget[m_type], previous);
return true;
}
void NzHardwareBuffer::Destroy()
{
NzContext::EnsureContext();
glDeleteBuffers(1, &m_buffer);
}
bool NzHardwareBuffer::Fill(const void* data, unsigned int offset, unsigned int size)
{
NzContext::EnsureContext();
GLuint previous;
glGetIntegerv(NzOpenGL::BufferTargetBinding[m_type], reinterpret_cast<GLint*>(&previous));
if (previous != m_buffer)
glBindBuffer(NzOpenGL::BufferTarget[m_type], m_buffer);
// Il semblerait que glBuffer(Sub)Data soit plus performant que glMapBuffer(Range) en dessous d'un certain seuil
// http://www.stevestreeting.com/2007/03/17/glmapbuffer-vs-glbuffersubdata-the-return/
if (size < 32*1024)
{
// http://www.opengl.org/wiki/Vertex_Specification_Best_Practices
if (size == m_parent->GetSize())
glBufferData(NzOpenGL::BufferTarget[m_type], m_parent->GetSize(), nullptr, NzOpenGL::BufferUsage[m_parent->GetUsage()]); // Discard
glBufferSubData(NzOpenGL::BufferTarget[m_type], offset, size, data);
}
else
{
nzUInt8* ptr = mapBuffer(m_type, (size == m_parent->GetSize()) ? nzBufferAccess_DiscardAndWrite : nzBufferAccess_WriteOnly, offset, size);
if (!ptr)
{
NazaraError("Failed to map buffer");
return false;
}
std::memcpy(ptr, data, size);
if (glUnmapBuffer(NzOpenGL::BufferTarget[m_type]) != GL_TRUE)
{
// Une erreur rare est survenue, nous devons réinitialiser le buffer
NazaraError("Failed to unmap buffer, reinitialising content... (OpenGL error : 0x" + NzString::Number(glGetError(), 16) + ')');
glBufferData(NzOpenGL::BufferTarget[m_type], m_parent->GetSize(), nullptr, NzOpenGL::BufferUsage[m_parent->GetStorage()]);
return false;
}
}
// Inutile de rebinder s'il n'y avait aucun buffer (Optimise les opérations chaînées)
if (previous != m_buffer && previous != 0)
glBindBuffer(NzOpenGL::BufferTarget[m_type], previous);
return true;
}
void* NzHardwareBuffer::GetPointer()
{
return nullptr;
}
bool NzHardwareBuffer::IsHardware() const
{
return true;
}
void* NzHardwareBuffer::Map(nzBufferAccess access, unsigned int offset, unsigned int size)
{
NzContext::EnsureContext();
// Pour ne pas perturber le rendu, on n'interfère pas avec le binding déjà présent
GLuint previous;
glGetIntegerv(NzOpenGL::BufferTargetBinding[m_type], reinterpret_cast<GLint*>(&previous));
if (previous != m_buffer)
glBindBuffer(NzOpenGL::BufferTarget[m_type], m_buffer);
void* ptr = mapBuffer(m_type, access, offset, size);
// Inutile de rebinder s'il n'y avait aucun buffer (Optimise les opérrations chaînées)
if (previous != m_buffer && previous != 0)
glBindBuffer(NzOpenGL::BufferTarget[m_type], previous);
return ptr;
}
bool NzHardwareBuffer::Unmap()
{
NzContext::EnsureContext();
GLuint previous;
glGetIntegerv(NzOpenGL::BufferTargetBinding[m_type], reinterpret_cast<GLint*>(&previous));
if (previous != m_buffer)
glBindBuffer(NzOpenGL::BufferTarget[m_type], m_buffer);
if (glUnmapBuffer(NzOpenGL::BufferTarget[m_type]) != GL_TRUE)
{
// Une erreur rare est survenue, nous devons réinitialiser le buffer
NazaraError("Failed to unmap buffer, reinitialising content... (OpenGL error : 0x" + NzString::Number(glGetError(), 16) + ')');
glBufferData(NzOpenGL::BufferTarget[m_type], m_parent->GetSize(), nullptr, NzOpenGL::BufferUsage[m_parent->GetStorage()]);
// Inutile de rebinder s'il n'y avait aucun buffer (Optimise les opérations chaînées)
if (previous != m_buffer && previous != 0)
glBindBuffer(NzOpenGL::BufferTarget[m_type], previous);
return false;
}
// Inutile de rebinder s'il n'y avait aucun buffer (Optimise les opérations chaînées)
if (previous != m_buffer && previous != 0)
glBindBuffer(NzOpenGL::BufferTarget[m_type], previous);
return true;
}
<commit_msg>Simplified code<commit_after>// Copyright (C) 2012 Jérôme Leclercq
// This file is part of the "Nazara Engine - Renderer module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Renderer/OpenGL.hpp>
#include <Nazara/Renderer/HardwareBuffer.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Renderer/Context.hpp>
#include <cstring>
#include <stdexcept>
#include <Nazara/Renderer/Debug.hpp>
namespace
{
using LockRoutine = nzUInt8* (*)(nzBufferType type, nzBufferAccess access, unsigned int offset, unsigned int size);
nzUInt8* LockBuffer(nzBufferType type, nzBufferAccess access, unsigned int offset, unsigned int size)
{
NazaraUnused(size);
if (access == nzBufferAccess_DiscardAndWrite)
{
GLint bufSize;
glGetBufferParameteriv(NzOpenGL::BufferTargetBinding[type], GL_BUFFER_SIZE, &bufSize);
GLint bufUsage;
glGetBufferParameteriv(NzOpenGL::BufferTargetBinding[type], GL_BUFFER_USAGE, &bufUsage);
// On discard le buffer
glBufferData(NzOpenGL::BufferTargetBinding[type], bufSize, nullptr, bufUsage);
}
void* ptr = glMapBuffer(NzOpenGL::BufferTarget[type], NzOpenGL::BufferLock[access]);
if (ptr)
return reinterpret_cast<nzUInt8*>(ptr) + offset;
else
return nullptr;
}
nzUInt8* LockBufferRange(nzBufferType type, nzBufferAccess access, unsigned int offset, unsigned int size)
{
return reinterpret_cast<nzUInt8*>(glMapBufferRange(NzOpenGL::BufferTarget[type], offset, size, NzOpenGL::BufferLockRange[access]));
}
nzUInt8* LockBufferFirstRun(nzBufferType type, nzBufferAccess access, unsigned int offset, unsigned int size);
LockRoutine mapBuffer = LockBufferFirstRun;
nzUInt8* LockBufferFirstRun(nzBufferType type, nzBufferAccess access, unsigned int offset, unsigned int size)
{
if (glMapBufferRange)
mapBuffer = LockBufferRange;
else
mapBuffer = LockBuffer;
return mapBuffer(type, access, offset, size);
}
}
NzHardwareBuffer::NzHardwareBuffer(NzBuffer* parent, nzBufferType type) :
m_type(type),
m_parent(parent)
{
}
NzHardwareBuffer::~NzHardwareBuffer() = default;
void NzHardwareBuffer::Bind()
{
#ifdef NAZARA_DEBUG
if (NzContext::GetCurrent() == nullptr)
{
NazaraError("No active context");
return;
}
#endif
glBindBuffer(NzOpenGL::BufferTarget[m_type], m_buffer);
}
bool NzHardwareBuffer::Create(unsigned int size, nzBufferUsage usage)
{
NzContext::EnsureContext();
m_buffer = 0;
glGenBuffers(1, &m_buffer);
GLint previous;
glGetIntegerv(NzOpenGL::BufferTargetBinding[m_type], &previous);
glBindBuffer(NzOpenGL::BufferTarget[m_type], m_buffer);
glBufferData(NzOpenGL::BufferTarget[m_type], size, nullptr, NzOpenGL::BufferUsage[usage]);
// Pour ne pas perturber le rendu, on n'interfère pas avec le binding déjà présent
if (previous != 0)
glBindBuffer(NzOpenGL::BufferTarget[m_type], previous);
return true;
}
void NzHardwareBuffer::Destroy()
{
NzContext::EnsureContext();
glDeleteBuffers(1, &m_buffer);
}
bool NzHardwareBuffer::Fill(const void* data, unsigned int offset, unsigned int size)
{
NzContext::EnsureContext();
GLuint previous;
glGetIntegerv(NzOpenGL::BufferTargetBinding[m_type], reinterpret_cast<GLint*>(&previous));
if (previous != m_buffer)
glBindBuffer(NzOpenGL::BufferTarget[m_type], m_buffer);
// Il semblerait que glBuffer(Sub)Data soit plus performant que glMapBuffer(Range) en dessous d'un certain seuil
// http://www.stevestreeting.com/2007/03/17/glmapbuffer-vs-glbuffersubdata-the-return/
if (size < 32*1024)
{
// http://www.opengl.org/wiki/Vertex_Specification_Best_Practices
if (size == m_parent->GetSize())
glBufferData(NzOpenGL::BufferTarget[m_type], m_parent->GetSize(), nullptr, NzOpenGL::BufferUsage[m_parent->GetUsage()]); // Discard
glBufferSubData(NzOpenGL::BufferTarget[m_type], offset, size, data);
}
else
{
nzUInt8* ptr = mapBuffer(m_type, (size == m_parent->GetSize()) ? nzBufferAccess_DiscardAndWrite : nzBufferAccess_WriteOnly, offset, size);
if (!ptr)
{
NazaraError("Failed to map buffer");
return false;
}
std::memcpy(ptr, data, size);
if (glUnmapBuffer(NzOpenGL::BufferTarget[m_type]) != GL_TRUE)
{
// Une erreur rare est survenue, nous devons réinitialiser le buffer
NazaraError("Failed to unmap buffer, reinitialising content... (OpenGL error : 0x" + NzString::Number(glGetError(), 16) + ')');
glBufferData(NzOpenGL::BufferTarget[m_type], m_parent->GetSize(), nullptr, NzOpenGL::BufferUsage[m_parent->GetStorage()]);
return false;
}
}
// Inutile de rebinder s'il n'y avait aucun buffer (Optimise les opérations chaînées)
if (previous != m_buffer && previous != 0)
glBindBuffer(NzOpenGL::BufferTarget[m_type], previous);
return true;
}
void* NzHardwareBuffer::GetPointer()
{
return nullptr;
}
bool NzHardwareBuffer::IsHardware() const
{
return true;
}
void* NzHardwareBuffer::Map(nzBufferAccess access, unsigned int offset, unsigned int size)
{
NzContext::EnsureContext();
// Pour ne pas perturber le rendu, on n'interfère pas avec le binding déjà présent
GLuint previous;
glGetIntegerv(NzOpenGL::BufferTargetBinding[m_type], reinterpret_cast<GLint*>(&previous));
if (previous != m_buffer)
glBindBuffer(NzOpenGL::BufferTarget[m_type], m_buffer);
void* ptr = mapBuffer(m_type, access, offset, size);
// Inutile de rebinder s'il n'y avait aucun buffer (Optimise les opérrations chaînées)
if (previous != m_buffer && previous != 0)
glBindBuffer(NzOpenGL::BufferTarget[m_type], previous);
return ptr;
}
bool NzHardwareBuffer::Unmap()
{
NzContext::EnsureContext();
GLuint previous;
glGetIntegerv(NzOpenGL::BufferTargetBinding[m_type], reinterpret_cast<GLint*>(&previous));
if (previous != m_buffer)
glBindBuffer(NzOpenGL::BufferTarget[m_type], m_buffer);
if (glUnmapBuffer(NzOpenGL::BufferTarget[m_type]) != GL_TRUE)
{
// Une erreur rare est survenue, nous devons réinitialiser le buffer
NazaraError("Failed to unmap buffer, reinitialising content... (OpenGL error : 0x" + NzString::Number(glGetError(), 16) + ')');
glBufferData(NzOpenGL::BufferTarget[m_type], m_parent->GetSize(), nullptr, NzOpenGL::BufferUsage[m_parent->GetStorage()]);
// Inutile de rebinder s'il n'y avait aucun buffer (Optimise les opérations chaînées)
if (previous != m_buffer && previous != 0)
glBindBuffer(NzOpenGL::BufferTarget[m_type], previous);
return false;
}
// Inutile de rebinder s'il n'y avait aucun buffer (Optimise les opérations chaînées)
if (previous != m_buffer && previous != 0)
glBindBuffer(NzOpenGL::BufferTarget[m_type], previous);
return true;
}
<|endoftext|> |
<commit_before>/* Copyright 2009 SPARTA, Inc., dba Cobham Analytic Solutions
*
* This file is part of WATCHER.
*
* WATCHER 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.
*
* WATCHER 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 Watcher. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file layerPreviewWindow.cpp
* @author Geoff Lawler <geoff.lawler@cobham.com>
* @date 2010-07-13
*/
#include "layerPreviewWindow.h"
#include "libwatcher/labelMessage.h"
namespace watcher
{
using namespace event;
INIT_LOGGER(LayerPreviewWindow, "LayerPreviewWindow");
// lives in manetGLView.cpp
extern float fast_arctan2( float y, float x );
LayerPreviewWindow::LayerPreviewWindow(QWidget *parent) :
QGLWidget(parent), node1(), node2(), layer(NULL)
{
}
LayerPreviewWindow::~LayerPreviewWindow()
{
}
void LayerPreviewWindow::setLayerData(WatcherLayerData *l)
{
// layer=l;
// layer->clear();
// node1.loadConfiguration(event::PHYSICAL_LAYER, NodeIdentifier::from_string("192.168.1.101"));
// node2.loadConfiguration(event::PHYSICAL_LAYER, NodeIdentifier::from_string("192.168.1.102"));
// // add test node label, and test floating label
// LabelMessagePtr mess=LabelMessagePtr(new LabelMessage("Floating Label"));
// mess->lat=1.0;
// mess->lng=1.0;
// mess->alt=1.0;
// mess->addLabel=true;
// layer->addRemoveFloatingLabel(mess, true);
// mess->lat=0.0;
// mess->lng=0.0;
// mess->alt=0.0;
// mess->label="Node Label";
// mess->fromNodeID=node1.nodeId;
// layer->addRemoveFloatingLabel(mess, true);
}
void LayerPreviewWindow::initializeGL()
{
// TRACE_ENTER();
// GLfloat matShine=0.6;
// GLfloat specReflection[] = { 0.05, 0.05, 0.05, 1.0f };
// GLfloat globalAmbientLight[] = { 0.0f, 0.0f, 0.0f, 1.0f };
// GLfloat posLight0[]={ 50.0f, 50.0f, 000.0f, 1.0f };
// GLfloat ambLight0[]={ 0.25, 0.25, 0.25, 1.0f };
// GLfloat specLight0[]={ 0.1f, 0.1f, 0.1f, 1.0f };
// GLfloat diffLight0[]={ 0.05, 0.05, 0.05, 1.0f };
// glEnable(GL_DEPTH_TEST);
// glDepthFunc(GL_LESS);
// glEnable(GL_BLEND);
// glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// // glBlendFunc(GL_SRC_ALPHA_SATURATE, GL_ONE);
// glEnable(GL_TEXTURE_2D);
// glLightModelfv(GL_LIGHT_MODEL_AMBIENT, globalAmbientLight);
// glShadeModel(GL_SMOOTH);
// // glShadeModel(GL_FLAT);
// // LIGHT0
// glLightfv(GL_LIGHT0, GL_POSITION, posLight0);
// glLightfv(GL_LIGHT0, GL_AMBIENT, ambLight0);
// glLightfv(GL_LIGHT0, GL_SPECULAR, specLight0);
// glLightfv(GL_LIGHT0, GL_DIFFUSE, diffLight0);
// glEnable(GL_LIGHTING);
// glEnable(GL_LIGHT0);
// glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
// glEnable(GL_COLOR_MATERIAL);
// glMaterialfv(GL_FRONT, GL_SPECULAR, specReflection);
// glMaterialf(GL_FRONT, GL_SHININESS, matShine);
// TRACE_EXIT();
}
void LayerPreviewWindow::resizeGL(int w, int h)
{
// glViewport(0, 0, w, h);
// glMatrixMode(GL_PROJECTION);
// glLoadIdentity();
// gluPerspective(40.0, GLfloat(w)/GLfloat(h), 1.0, 50.0);
}
void LayerPreviewWindow::paintGL()
{
}
void LayerPreviewWindow::drawGraph()
{
// drawNode(node1);
// drawNode(node2);
// if (!layer)
// return;
// drawEdge(layer->edgeDisplayInfo, node1, node2);
// {
// WatcherLayerData::ReadLock readLock(layer->floatingLabelsMutex);
// drawLabel(layer->floatingLabels.begin()->lat, layer->floatingLabels.begin()->lng, layer->floatingLabels.begin()->alt,
// *layer->floatingLabels.begin());
// }
// {
// WatcherLayerData::ReadLock readLock(layer->nodeLabelsMutexes[0]);
// drawLabel(node1.x, node1.y, node1.z, *layer->nodeLabels[0].begin());
// }
}
void LayerPreviewWindow::drawNode(const NodeDisplayInfo &node)
{
// GLdouble x=node.x;
// GLdouble y=node.y;
// GLdouble z=node.z;
// GLfloat nodeColor[]={
// node.color.r/255.0,
// node.color.g/255.0,
// node.color.b/255.0,
// node.color.a/255.0
// };
// glPushMatrix();
// glTranslated(x, y, z);
// glColor4fv(nodeColor);
// GLUquadricObj *quadric=gluNewQuadric();
// gluQuadricNormals(quadric, GLU_SMOOTH);
// gluSphere(quadric, 4, 15, 15);
// gluDeleteQuadric(quadric);
// renderText(0, 6, 3, QString(node.get_label().c_str()),
// QFont(node.labelFont.c_str(), static_cast<int>(node.labelPointSize)));
// glPopMatrix();
}
void LayerPreviewWindow::drawEdge(const EdgeDisplayInfo &edge, const NodeDisplayInfo &node1, const NodeDisplayInfo &node2)
{
// GLdouble x1=node1.x;
// GLdouble y1=node1.y;
// GLdouble z1=node1.z;
// GLdouble x2=node2.x;
// GLdouble y2=node2.y;
// GLdouble z2=node2.z;
// double width=edge.width;
// GLfloat edgeColor[]={
// edge.color.r/255.0,
// edge.color.g/255.0,
// edge.color.b/255.0,
// edge.color.a/255.0,
// };
// glColor4fv(edgeColor);
// GLUquadricObj *quadric=gluNewQuadric();
// gluQuadricNormals(quadric, GLU_SMOOTH);
// float vx = x2-x1;
// float vy = y2-y1;
// float vz = z2-z1;
// //handle the degenerate case of z1 == z2 with an approximation
// if(vz == 0)
// vz = .0001;
// float v = sqrt( vx*vx + vy*vy + vz*vz );
// float ax = 57.2957795*acos( vz/v );
// if ( vz < 0.0 )
// ax = -ax;
// float rx = -vy*vz;
// float ry = vx*vz;
// glPushMatrix();
// //draw the cylinder body
// glTranslatef( x1,y1,z1 );
// glRotatef(ax, rx, ry, 0.0);
// gluQuadricOrientation(quadric,GLU_OUTSIDE);
// gluCylinder(quadric, width, 0, v, 15, 15);
// glPopMatrix();
// gluDeleteQuadric(quadric);
// // draw the edge's label, if there is one.
// if (edge.label!="none") {
// const GLfloat clr[]={
// edge.labelColor.r/255.0,
// edge.labelColor.g/255.0,
// edge.labelColor.b/255.0,
// edge.labelColor.a/255.0
// };
// glColor4fv(clr);
// GLdouble lx=(x1+x2)/2.0;
// GLdouble ly=(y1+y2)/2.0;
// GLdouble lz=(z1+z2)/2.0;
// GLdouble a=fast_arctan2(x1-x2 , y1-y2);
// GLdouble th=10.0;
// renderText(lx+sin(a-M_PI_2),ly+cos(a-M_PI_2)*th, lz,
// QString(edge.label.c_str()),
// QFont(QString(edge.labelFont.c_str()), (int)(edge.labelPointSize)));
// }
}
void LayerPreviewWindow::drawLabel(const GLfloat &x, const GLfloat &y, const GLfloat &z, const LabelDisplayInfo &l)
{
// int fgColor[]={
// l.foregroundColor.r,
// l.foregroundColor.g,
// l.foregroundColor.b,
// l.foregroundColor.a
// };
// float offset=4.0;
// QFont f(l.fontName.c_str(), (int)(l.pointSize));
// qglColor(QColor(fgColor[0], fgColor[1], fgColor[2], fgColor[3]));
// renderText(x+offset, y+offset, z+2.0, l.labelText.c_str(), f);
}
} // namespace watcher
<commit_msg>stop 'unused parameter' warnings in unused code.<commit_after>/* Copyright 2009 SPARTA, Inc., dba Cobham Analytic Solutions
*
* This file is part of WATCHER.
*
* WATCHER 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.
*
* WATCHER 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 Watcher. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file layerPreviewWindow.cpp
* @author Geoff Lawler <geoff.lawler@cobham.com>
* @date 2010-07-13
*/
#include "layerPreviewWindow.h"
#include "libwatcher/labelMessage.h"
#define UNUSED(e) do { (void)(e); } while (0)
namespace watcher
{
using namespace event;
INIT_LOGGER(LayerPreviewWindow, "LayerPreviewWindow");
// lives in manetGLView.cpp
extern float fast_arctan2( float y, float x );
LayerPreviewWindow::LayerPreviewWindow(QWidget *parent) :
QGLWidget(parent), node1(), node2(), layer(NULL)
{
}
LayerPreviewWindow::~LayerPreviewWindow()
{
}
void LayerPreviewWindow::setLayerData(WatcherLayerData *l)
{
UNUSED(l);
// layer=l;
// layer->clear();
// node1.loadConfiguration(event::PHYSICAL_LAYER, NodeIdentifier::from_string("192.168.1.101"));
// node2.loadConfiguration(event::PHYSICAL_LAYER, NodeIdentifier::from_string("192.168.1.102"));
// // add test node label, and test floating label
// LabelMessagePtr mess=LabelMessagePtr(new LabelMessage("Floating Label"));
// mess->lat=1.0;
// mess->lng=1.0;
// mess->alt=1.0;
// mess->addLabel=true;
// layer->addRemoveFloatingLabel(mess, true);
// mess->lat=0.0;
// mess->lng=0.0;
// mess->alt=0.0;
// mess->label="Node Label";
// mess->fromNodeID=node1.nodeId;
// layer->addRemoveFloatingLabel(mess, true);
}
void LayerPreviewWindow::initializeGL()
{
// TRACE_ENTER();
// GLfloat matShine=0.6;
// GLfloat specReflection[] = { 0.05, 0.05, 0.05, 1.0f };
// GLfloat globalAmbientLight[] = { 0.0f, 0.0f, 0.0f, 1.0f };
// GLfloat posLight0[]={ 50.0f, 50.0f, 000.0f, 1.0f };
// GLfloat ambLight0[]={ 0.25, 0.25, 0.25, 1.0f };
// GLfloat specLight0[]={ 0.1f, 0.1f, 0.1f, 1.0f };
// GLfloat diffLight0[]={ 0.05, 0.05, 0.05, 1.0f };
// glEnable(GL_DEPTH_TEST);
// glDepthFunc(GL_LESS);
// glEnable(GL_BLEND);
// glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// // glBlendFunc(GL_SRC_ALPHA_SATURATE, GL_ONE);
// glEnable(GL_TEXTURE_2D);
// glLightModelfv(GL_LIGHT_MODEL_AMBIENT, globalAmbientLight);
// glShadeModel(GL_SMOOTH);
// // glShadeModel(GL_FLAT);
// // LIGHT0
// glLightfv(GL_LIGHT0, GL_POSITION, posLight0);
// glLightfv(GL_LIGHT0, GL_AMBIENT, ambLight0);
// glLightfv(GL_LIGHT0, GL_SPECULAR, specLight0);
// glLightfv(GL_LIGHT0, GL_DIFFUSE, diffLight0);
// glEnable(GL_LIGHTING);
// glEnable(GL_LIGHT0);
// glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
// glEnable(GL_COLOR_MATERIAL);
// glMaterialfv(GL_FRONT, GL_SPECULAR, specReflection);
// glMaterialf(GL_FRONT, GL_SHININESS, matShine);
// TRACE_EXIT();
}
void LayerPreviewWindow::resizeGL(int w, int h)
{
UNUSED(w);
UNUSED(h);
// glViewport(0, 0, w, h);
// glMatrixMode(GL_PROJECTION);
// glLoadIdentity();
// gluPerspective(40.0, GLfloat(w)/GLfloat(h), 1.0, 50.0);
}
void LayerPreviewWindow::paintGL()
{
}
void LayerPreviewWindow::drawGraph()
{
// drawNode(node1);
// drawNode(node2);
// if (!layer)
// return;
// drawEdge(layer->edgeDisplayInfo, node1, node2);
// {
// WatcherLayerData::ReadLock readLock(layer->floatingLabelsMutex);
// drawLabel(layer->floatingLabels.begin()->lat, layer->floatingLabels.begin()->lng, layer->floatingLabels.begin()->alt,
// *layer->floatingLabels.begin());
// }
// {
// WatcherLayerData::ReadLock readLock(layer->nodeLabelsMutexes[0]);
// drawLabel(node1.x, node1.y, node1.z, *layer->nodeLabels[0].begin());
// }
}
void LayerPreviewWindow::drawNode(const NodeDisplayInfo &node)
{
UNUSED(node);
// GLdouble x=node.x;
// GLdouble y=node.y;
// GLdouble z=node.z;
// GLfloat nodeColor[]={
// node.color.r/255.0,
// node.color.g/255.0,
// node.color.b/255.0,
// node.color.a/255.0
// };
// glPushMatrix();
// glTranslated(x, y, z);
// glColor4fv(nodeColor);
// GLUquadricObj *quadric=gluNewQuadric();
// gluQuadricNormals(quadric, GLU_SMOOTH);
// gluSphere(quadric, 4, 15, 15);
// gluDeleteQuadric(quadric);
// renderText(0, 6, 3, QString(node.get_label().c_str()),
// QFont(node.labelFont.c_str(), static_cast<int>(node.labelPointSize)));
// glPopMatrix();
}
void LayerPreviewWindow::drawEdge(const EdgeDisplayInfo &edge, const NodeDisplayInfo &node1, const NodeDisplayInfo &node2)
{
UNUSED(edge);
UNUSED(node1);
UNUSED(node2);
// GLdouble x1=node1.x;
// GLdouble y1=node1.y;
// GLdouble z1=node1.z;
// GLdouble x2=node2.x;
// GLdouble y2=node2.y;
// GLdouble z2=node2.z;
// double width=edge.width;
// GLfloat edgeColor[]={
// edge.color.r/255.0,
// edge.color.g/255.0,
// edge.color.b/255.0,
// edge.color.a/255.0,
// };
// glColor4fv(edgeColor);
// GLUquadricObj *quadric=gluNewQuadric();
// gluQuadricNormals(quadric, GLU_SMOOTH);
// float vx = x2-x1;
// float vy = y2-y1;
// float vz = z2-z1;
// //handle the degenerate case of z1 == z2 with an approximation
// if(vz == 0)
// vz = .0001;
// float v = sqrt( vx*vx + vy*vy + vz*vz );
// float ax = 57.2957795*acos( vz/v );
// if ( vz < 0.0 )
// ax = -ax;
// float rx = -vy*vz;
// float ry = vx*vz;
// glPushMatrix();
// //draw the cylinder body
// glTranslatef( x1,y1,z1 );
// glRotatef(ax, rx, ry, 0.0);
// gluQuadricOrientation(quadric,GLU_OUTSIDE);
// gluCylinder(quadric, width, 0, v, 15, 15);
// glPopMatrix();
// gluDeleteQuadric(quadric);
// // draw the edge's label, if there is one.
// if (edge.label!="none") {
// const GLfloat clr[]={
// edge.labelColor.r/255.0,
// edge.labelColor.g/255.0,
// edge.labelColor.b/255.0,
// edge.labelColor.a/255.0
// };
// glColor4fv(clr);
// GLdouble lx=(x1+x2)/2.0;
// GLdouble ly=(y1+y2)/2.0;
// GLdouble lz=(z1+z2)/2.0;
// GLdouble a=fast_arctan2(x1-x2 , y1-y2);
// GLdouble th=10.0;
// renderText(lx+sin(a-M_PI_2),ly+cos(a-M_PI_2)*th, lz,
// QString(edge.label.c_str()),
// QFont(QString(edge.labelFont.c_str()), (int)(edge.labelPointSize)));
// }
}
void LayerPreviewWindow::drawLabel(const GLfloat &x, const GLfloat &y, const GLfloat &z, const LabelDisplayInfo &l)
{
UNUSED(x);
UNUSED(y);
UNUSED(z);
UNUSED(l);
// int fgColor[]={
// l.foregroundColor.r,
// l.foregroundColor.g,
// l.foregroundColor.b,
// l.foregroundColor.a
// };
// float offset=4.0;
// QFont f(l.fontName.c_str(), (int)(l.pointSize));
// qglColor(QColor(fgColor[0], fgColor[1], fgColor[2], fgColor[3]));
// renderText(x+offset, y+offset, z+2.0, l.labelText.c_str(), f);
}
} // namespace watcher
<|endoftext|> |
<commit_before>#include "nanodbc.h"
#include "example_unicode_utils.h"
#include <algorithm>
#include <array>
#include <codecvt>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <stdexcept>
#include <string>
#ifdef _WIN32
#define NOMINMAX
#include <windows.h> // SQLLEN, SQLULEN, SQLHWND
#endif
#include <sql.h>
#include <sqlext.h>
#include "nanodbc.h"
using namespace std;
using namespace nanodbc;
#define NANODBC_COLUMN(p) \
std::cout << std::setw(25) << std::left << #p << ": " << std::right << any_to_string(cols.p()) << std::endl
#define ODBC_CHECK(r, handle, handle_type, msg) \
if (r!=SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO) \
throw nanodbc::database_error(handle, handle_type, msg)
void usage(std::ostream& out, std::string const& binary_name)
{
out << "usage: " << binary_name << " connection_string table_name" << std::endl;
}
int main(int argc, char* argv[])
{
if(argc < 3 || argc > 4)
{
char* app_name = strrchr(argv[0], '/');
app_name = app_name ? app_name + 1 : argv[0];
if(0 == strncmp(app_name, "lt-", 3))
app_name += 3; // remove libtool prefix
usage(cerr, app_name);
return EXIT_FAILURE;
}
try
{
// Example:
// "Driver={ODBC Driver 11 for SQL Server};Server=xxx.sqlserver.net;Database=mydb;UID=joe;PWD=secret;"
auto const connection_string(convert(argv[1]));
auto const table_name(convert(argv[2]));
nanodbc::string_type schema_name;
if (argc == 4)
schema_name = convert(argv[3]);
connection conn(connection_string);
catalog cat(conn);
auto cols = cat.find_columns(nanodbc::string_type(), table_name, schema_name);
while (cols.next())
{
if (cols.ordinal_position() == 1)
{
NANODBC_COLUMN(table_catalog);
NANODBC_COLUMN(table_schema);
NANODBC_COLUMN(table_name);
}
std::cout << "--------------------------------" << std::endl;
NANODBC_COLUMN(ordinal_position);
NANODBC_COLUMN(column_name);
NANODBC_COLUMN(type_name);
NANODBC_COLUMN(data_type);
NANODBC_COLUMN(sql_data_type);
NANODBC_COLUMN(sql_datetime_subtype);
NANODBC_COLUMN(column_size);
NANODBC_COLUMN(decimal_digits);
NANODBC_COLUMN(buffer_length);
NANODBC_COLUMN(char_octed_length);
NANODBC_COLUMN(numeric_precision_radix);
NANODBC_COLUMN(nullable);
NANODBC_COLUMN(is_nullable);
NANODBC_COLUMN(remarks);
NANODBC_COLUMN(column_default);
std::cout << std::endl;
}
}
catch (std::runtime_error const& e)
{
std::cerr << e.what() << std::endl;
}
}
<commit_msg>Add missing optional schema_name parameter to usage info.<commit_after>#include "nanodbc.h"
#include "example_unicode_utils.h"
#include <algorithm>
#include <array>
#include <codecvt>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <stdexcept>
#include <string>
#ifdef _WIN32
#define NOMINMAX
#include <windows.h> // SQLLEN, SQLULEN, SQLHWND
#endif
#include <sql.h>
#include <sqlext.h>
#include "nanodbc.h"
using namespace std;
using namespace nanodbc;
#define NANODBC_COLUMN(p) \
std::cout << std::setw(25) << std::left << #p << ": " << std::right << any_to_string(cols.p()) << std::endl
#define ODBC_CHECK(r, handle, handle_type, msg) \
if (r!=SQL_SUCCESS && r != SQL_SUCCESS_WITH_INFO) \
throw nanodbc::database_error(handle, handle_type, msg)
void usage(std::ostream& out, std::string const& binary_name)
{
out << "usage: " << binary_name << " connection_string table_name [schema_name]" << std::endl;
}
int main(int argc, char* argv[])
{
if(argc < 3 || argc > 4)
{
char* app_name = strrchr(argv[0], '/');
app_name = app_name ? app_name + 1 : argv[0];
if(0 == strncmp(app_name, "lt-", 3))
app_name += 3; // remove libtool prefix
usage(cerr, app_name);
return EXIT_FAILURE;
}
try
{
// Example:
// "Driver={ODBC Driver 11 for SQL Server};Server=xxx.sqlserver.net;Database=mydb;UID=joe;PWD=secret;"
auto const connection_string(convert(argv[1]));
auto const table_name(convert(argv[2]));
nanodbc::string_type schema_name;
if (argc == 4)
schema_name = convert(argv[3]);
connection conn(connection_string);
catalog cat(conn);
auto cols = cat.find_columns(nanodbc::string_type(), table_name, schema_name);
while (cols.next())
{
if (cols.ordinal_position() == 1)
{
NANODBC_COLUMN(table_catalog);
NANODBC_COLUMN(table_schema);
NANODBC_COLUMN(table_name);
}
std::cout << "--------------------------------" << std::endl;
NANODBC_COLUMN(ordinal_position);
NANODBC_COLUMN(column_name);
NANODBC_COLUMN(type_name);
NANODBC_COLUMN(data_type);
NANODBC_COLUMN(sql_data_type);
NANODBC_COLUMN(sql_datetime_subtype);
NANODBC_COLUMN(column_size);
NANODBC_COLUMN(decimal_digits);
NANODBC_COLUMN(buffer_length);
NANODBC_COLUMN(char_octed_length);
NANODBC_COLUMN(numeric_precision_radix);
NANODBC_COLUMN(nullable);
NANODBC_COLUMN(is_nullable);
NANODBC_COLUMN(remarks);
NANODBC_COLUMN(column_default);
std::cout << std::endl;
}
}
catch (std::runtime_error const& e)
{
std::cerr << e.what() << std::endl;
}
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "WPXSvStream.hxx"
#include <tools/stream.hxx>
#include <unotools/streamwrap.hxx>
#include <unotools/ucbstreamhelper.hxx>
#include <limits>
#include <vector>
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::io;
namespace
{
static void splitPath( std::vector<OUString> &rElems, const OUString &rPath )
{
for (sal_Int32 i = 0; i >= 0;)
rElems.push_back( rPath.getToken( 0, '/', i ) );
}
} // anonymous namespace
typedef struct
{
SotStorageRef ref;
} SotStorageRefWrapper;
typedef struct
{
SotStorageStreamRef ref;
} SotStorageStreamRefWrapper;
class WPXSvInputStreamImpl
{
public :
WPXSvInputStreamImpl( ::com::sun::star::uno::Reference<
::com::sun::star::io::XInputStream > xStream );
~WPXSvInputStreamImpl();
bool isOLEStream();
WPXInputStream * getDocumentOLEStream(const char *name);
const unsigned char *read(unsigned long numBytes, unsigned long &numBytesRead);
int seek(long offset);
long tell();
bool atEOS();
void invalidateReadBuffer();
private:
::std::vector< SotStorageRefWrapper > mxChildrenStorages;
::std::vector< SotStorageStreamRefWrapper > mxChildrenStreams;
::com::sun::star::uno::Reference<
::com::sun::star::io::XInputStream > mxStream;
::com::sun::star::uno::Reference<
::com::sun::star::io::XSeekable > mxSeekable;
::com::sun::star::uno::Sequence< sal_Int8 > maData;
public:
sal_Int64 mnLength;
unsigned char *mpReadBuffer;
unsigned long mnReadBufferLength;
unsigned long mnReadBufferPos;
};
WPXSvInputStreamImpl::WPXSvInputStreamImpl( Reference< XInputStream > xStream ) :
mxChildrenStorages(),
mxChildrenStreams(),
mxStream(xStream),
mxSeekable(xStream, UNO_QUERY),
maData(0),
mnLength(0),
mpReadBuffer(0),
mnReadBufferLength(0),
mnReadBufferPos(0)
{
if (!xStream.is() || !mxStream.is())
mnLength = 0;
else
{
if (!mxSeekable.is())
mnLength = 0;
else
{
try
{
mnLength = mxSeekable->getLength();
}
catch ( ... )
{
SAL_WARN("writerperfect", "mnLength = mxSeekable->getLength() threw exception");
mnLength = 0;
}
}
}
}
WPXSvInputStreamImpl::~WPXSvInputStreamImpl()
{
if (mpReadBuffer)
delete [] mpReadBuffer;
}
const unsigned char *WPXSvInputStreamImpl::read(unsigned long numBytes, unsigned long &numBytesRead)
{
numBytesRead = 0;
if (numBytes == 0 || atEOS())
return 0;
numBytesRead = mxStream->readSomeBytes (maData, numBytes);
if (numBytesRead == 0)
return 0;
return (const unsigned char *)maData.getConstArray();
}
long WPXSvInputStreamImpl::tell()
{
if ((mnLength == 0) || !mxStream.is() || !mxSeekable.is())
return -1L;
else
{
sal_Int64 tmpPosition = mxSeekable->getPosition();
if ((tmpPosition < 0) || (tmpPosition > (std::numeric_limits<long>::max)()))
return -1L;
return (long)tmpPosition;
}
}
int WPXSvInputStreamImpl::seek(long offset)
{
if ((mnLength == 0) || !mxStream.is() || !mxSeekable.is())
return -1;
sal_Int64 tmpPosition = mxSeekable->getPosition();
if ((tmpPosition < 0) || (tmpPosition > (std::numeric_limits<long>::max)()))
return -1;
try
{
mxSeekable->seek(offset);
return 0;
}
catch (...)
{
SAL_WARN("writerperfect", "mxSeekable->seek(offset) threw exception");
return -1;
}
}
bool WPXSvInputStreamImpl::atEOS()
{
if ((mnLength == 0) || !mxStream.is() || !mxSeekable.is())
return true;
return (mxSeekable->getPosition() >= mnLength);
}
bool WPXSvInputStreamImpl::isOLEStream()
{
if ((mnLength == 0) || !mxStream.is() || !mxSeekable.is())
return false;
sal_Int64 tmpPosition = mxSeekable->getPosition();
mxSeekable->seek(0);
SvStream *pStream = utl::UcbStreamHelper::CreateStream( mxStream );
bool bAns = pStream && SotStorage::IsOLEStorage( pStream );
if (pStream)
delete pStream;
mxSeekable->seek(tmpPosition);
return bAns;
}
WPXInputStream *WPXSvInputStreamImpl::getDocumentOLEStream(const char *name)
{
if (!name)
return 0;
OUString rPath(name,strlen(name),RTL_TEXTENCODING_UTF8);
std::vector<OUString> aElems;
splitPath( aElems, rPath );
if ((mnLength == 0) || !mxStream.is() || !mxSeekable.is())
return 0;
sal_Int64 tmpPosition = mxSeekable->getPosition();
mxSeekable->seek(0);
SvStream *pStream = utl::UcbStreamHelper::CreateStream( mxStream );
if (!pStream || !SotStorage::IsOLEStorage( pStream ))
{
mxSeekable->seek(tmpPosition);
return 0;
}
SotStorageRefWrapper storageRefWrapper;
storageRefWrapper.ref = new SotStorage( pStream, sal_True );
mxChildrenStorages.push_back( storageRefWrapper );
unsigned i = 0;
while (i < aElems.size())
{
if( mxChildrenStorages.back().ref->IsStream(aElems[i]))
break;
else if (mxChildrenStorages.back().ref->IsStorage(aElems[i]))
{
SotStorageRef tmpParent(mxChildrenStorages.back().ref);
storageRefWrapper.ref = tmpParent->OpenSotStorage(aElems[i++], STREAM_STD_READ);
mxChildrenStorages.push_back(storageRefWrapper);
}
else
// should not happen
return 0;
}
// For the while don't return stream in this situation.
// Later, given how libcdr's zip stream implementation behaves,
// return the first stream in the storage if there is one.
if (i >= aElems.size())
return 0;
SotStorageStreamRefWrapper storageStreamRefWrapper;
storageStreamRefWrapper.ref = mxChildrenStorages.back().ref->OpenSotStream( aElems[i], STREAM_STD_READ );
mxChildrenStreams.push_back( storageStreamRefWrapper );
mxSeekable->seek(tmpPosition);
if ( !mxChildrenStreams.back().ref.Is() || mxChildrenStreams.back().ref->GetError() )
{
mxSeekable->seek(tmpPosition);
return 0;
}
Reference < XInputStream > xContents(new utl::OSeekableInputStreamWrapper( mxChildrenStreams.back().ref ));
mxSeekable->seek(tmpPosition);
if (xContents.is())
return new WPXSvInputStream( xContents );
else
return 0;
}
void WPXSvInputStreamImpl::invalidateReadBuffer()
{
if (mpReadBuffer)
{
seek((long) tell() + (long)mnReadBufferPos - (long)mnReadBufferLength);
delete [] mpReadBuffer;
mpReadBuffer = 0;
mnReadBufferPos = 0;
mnReadBufferLength = 0;
}
}
WPXSvInputStream::WPXSvInputStream( Reference< XInputStream > xStream ) :
mpImpl(new WPXSvInputStreamImpl(xStream))
{
}
WPXSvInputStream::~WPXSvInputStream()
{
if (mpImpl)
delete mpImpl;
}
#define BUFFER_MAX 65536
const unsigned char *WPXSvInputStream::read(unsigned long numBytes, unsigned long &numBytesRead)
{
numBytesRead = 0;
if (numBytes == 0 || numBytes > (std::numeric_limits<unsigned long>::max)()/2)
return 0;
if (mpImpl->mpReadBuffer)
{
if ((mpImpl->mnReadBufferPos + numBytes > mpImpl->mnReadBufferPos) && (mpImpl->mnReadBufferPos + numBytes <= mpImpl->mnReadBufferLength))
{
const unsigned char *pTmp = mpImpl->mpReadBuffer + mpImpl->mnReadBufferPos;
mpImpl->mnReadBufferPos += numBytes;
numBytesRead = numBytes;
return pTmp;
}
mpImpl->invalidateReadBuffer();
}
unsigned long curpos = (unsigned long) mpImpl->tell();
if (curpos == (unsigned long)-1) // returned ERROR
return 0;
if ((curpos + numBytes < curpos) /*overflow*/ ||
(curpos + numBytes >= (sal_uInt64)mpImpl->mnLength)) /*reading more than available*/
{
numBytes = mpImpl->mnLength - curpos;
}
if (numBytes < BUFFER_MAX)
{
if (BUFFER_MAX < mpImpl->mnLength - curpos)
mpImpl->mnReadBufferLength = BUFFER_MAX;
else /* BUFFER_MAX >= mpImpl->mnLength - curpos */
mpImpl->mnReadBufferLength = mpImpl->mnLength - curpos;
}
else
mpImpl->mnReadBufferLength = numBytes;
mpImpl->seek((long) curpos);
mpImpl->mpReadBuffer = new unsigned char[mpImpl->mnReadBufferLength];
unsigned long tmpNumBytes(0);
const unsigned char *pTmp = mpImpl->read(mpImpl->mnReadBufferLength, tmpNumBytes);
if (tmpNumBytes != mpImpl->mnReadBufferLength)
mpImpl->mnReadBufferLength = tmpNumBytes;
mpImpl->mnReadBufferPos = 0;
if (!mpImpl->mnReadBufferLength)
return 0;
numBytesRead = numBytes;
mpImpl->mnReadBufferPos += numBytesRead;
memcpy(mpImpl->mpReadBuffer, pTmp, mpImpl->mnReadBufferLength);
return const_cast<const unsigned char *>(mpImpl->mpReadBuffer);
}
long WPXSvInputStream::tell()
{
long retVal = mpImpl->tell();
return retVal - (long)mpImpl->mnReadBufferLength + (long)mpImpl->mnReadBufferPos;
}
int WPXSvInputStream::seek(long offset, WPX_SEEK_TYPE seekType)
{
sal_Int64 tmpOffset = offset;
if (seekType == WPX_SEEK_CUR)
tmpOffset += tell();
if (seekType == WPX_SEEK_END)
tmpOffset += mpImpl->mnLength;
int retVal = 0;
if (tmpOffset < 0)
{
tmpOffset = 0;
retVal = -1;
}
if (tmpOffset > mpImpl->mnLength)
{
tmpOffset = mpImpl->mnLength;
retVal = -1;
}
if (tmpOffset < mpImpl->tell() && (unsigned long)tmpOffset >= (unsigned long)mpImpl->tell() - mpImpl->mnReadBufferLength)
{
mpImpl->mnReadBufferPos = (unsigned long)(tmpOffset + (long) mpImpl->mnReadBufferLength - (long) mpImpl->tell());
return 0;
}
mpImpl->invalidateReadBuffer();
if (mpImpl->seek(tmpOffset))
return -1;
return retVal;
}
bool WPXSvInputStream::atEOS()
{
return mpImpl->atEOS() && mpImpl->mnReadBufferPos == mpImpl->mnReadBufferLength;
}
bool WPXSvInputStream::isOLEStream()
{
mpImpl->invalidateReadBuffer();
return mpImpl->isOLEStream();
}
WPXInputStream *WPXSvInputStream::getDocumentOLEStream(const char *name)
{
mpImpl->invalidateReadBuffer();
return mpImpl->getDocumentOLEStream(name);
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Avoid some memcpy when not necessary<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "WPXSvStream.hxx"
#include <tools/stream.hxx>
#include <unotools/streamwrap.hxx>
#include <unotools/ucbstreamhelper.hxx>
#include <limits>
#include <vector>
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::io;
namespace
{
static void splitPath( std::vector<OUString> &rElems, const OUString &rPath )
{
for (sal_Int32 i = 0; i >= 0;)
rElems.push_back( rPath.getToken( 0, '/', i ) );
}
} // anonymous namespace
typedef struct
{
SotStorageRef ref;
} SotStorageRefWrapper;
typedef struct
{
SotStorageStreamRef ref;
} SotStorageStreamRefWrapper;
class WPXSvInputStreamImpl
{
public :
WPXSvInputStreamImpl( ::com::sun::star::uno::Reference<
::com::sun::star::io::XInputStream > xStream );
~WPXSvInputStreamImpl();
bool isOLEStream();
WPXInputStream * getDocumentOLEStream(const char *name);
const unsigned char *read(unsigned long numBytes, unsigned long &numBytesRead);
int seek(long offset);
long tell();
bool atEOS();
void invalidateReadBuffer();
private:
::std::vector< SotStorageRefWrapper > mxChildrenStorages;
::std::vector< SotStorageStreamRefWrapper > mxChildrenStreams;
::com::sun::star::uno::Reference<
::com::sun::star::io::XInputStream > mxStream;
::com::sun::star::uno::Reference<
::com::sun::star::io::XSeekable > mxSeekable;
::com::sun::star::uno::Sequence< sal_Int8 > maData;
public:
sal_Int64 mnLength;
unsigned char *mpReadBuffer;
unsigned long mnReadBufferLength;
unsigned long mnReadBufferPos;
};
WPXSvInputStreamImpl::WPXSvInputStreamImpl( Reference< XInputStream > xStream ) :
mxChildrenStorages(),
mxChildrenStreams(),
mxStream(xStream),
mxSeekable(xStream, UNO_QUERY),
maData(0),
mnLength(0),
mpReadBuffer(0),
mnReadBufferLength(0),
mnReadBufferPos(0)
{
if (!xStream.is() || !mxStream.is())
mnLength = 0;
else
{
if (!mxSeekable.is())
mnLength = 0;
else
{
try
{
mnLength = mxSeekable->getLength();
}
catch ( ... )
{
SAL_WARN("writerperfect", "mnLength = mxSeekable->getLength() threw exception");
mnLength = 0;
}
}
}
}
WPXSvInputStreamImpl::~WPXSvInputStreamImpl()
{
if (mpReadBuffer)
delete [] mpReadBuffer;
}
const unsigned char *WPXSvInputStreamImpl::read(unsigned long numBytes, unsigned long &numBytesRead)
{
numBytesRead = 0;
if (numBytes == 0 || atEOS())
return 0;
numBytesRead = mxStream->readSomeBytes (maData, numBytes);
if (numBytesRead == 0)
return 0;
return (const unsigned char *)maData.getConstArray();
}
long WPXSvInputStreamImpl::tell()
{
if ((mnLength == 0) || !mxStream.is() || !mxSeekable.is())
return -1L;
else
{
sal_Int64 tmpPosition = mxSeekable->getPosition();
if ((tmpPosition < 0) || (tmpPosition > (std::numeric_limits<long>::max)()))
return -1L;
return (long)tmpPosition;
}
}
int WPXSvInputStreamImpl::seek(long offset)
{
if ((mnLength == 0) || !mxStream.is() || !mxSeekable.is())
return -1;
sal_Int64 tmpPosition = mxSeekable->getPosition();
if ((tmpPosition < 0) || (tmpPosition > (std::numeric_limits<long>::max)()))
return -1;
try
{
mxSeekable->seek(offset);
return 0;
}
catch (...)
{
SAL_WARN("writerperfect", "mxSeekable->seek(offset) threw exception");
return -1;
}
}
bool WPXSvInputStreamImpl::atEOS()
{
if ((mnLength == 0) || !mxStream.is() || !mxSeekable.is())
return true;
return (mxSeekable->getPosition() >= mnLength);
}
bool WPXSvInputStreamImpl::isOLEStream()
{
if ((mnLength == 0) || !mxStream.is() || !mxSeekable.is())
return false;
sal_Int64 tmpPosition = mxSeekable->getPosition();
mxSeekable->seek(0);
SvStream *pStream = utl::UcbStreamHelper::CreateStream( mxStream );
bool bAns = pStream && SotStorage::IsOLEStorage( pStream );
if (pStream)
delete pStream;
mxSeekable->seek(tmpPosition);
return bAns;
}
WPXInputStream *WPXSvInputStreamImpl::getDocumentOLEStream(const char *name)
{
if (!name)
return 0;
OUString rPath(name,strlen(name),RTL_TEXTENCODING_UTF8);
std::vector<OUString> aElems;
splitPath( aElems, rPath );
if ((mnLength == 0) || !mxStream.is() || !mxSeekable.is())
return 0;
sal_Int64 tmpPosition = mxSeekable->getPosition();
mxSeekable->seek(0);
SvStream *pStream = utl::UcbStreamHelper::CreateStream( mxStream );
if (!pStream || !SotStorage::IsOLEStorage( pStream ))
{
mxSeekable->seek(tmpPosition);
return 0;
}
SotStorageRefWrapper storageRefWrapper;
storageRefWrapper.ref = new SotStorage( pStream, sal_True );
mxChildrenStorages.push_back( storageRefWrapper );
unsigned i = 0;
while (i < aElems.size())
{
if( mxChildrenStorages.back().ref->IsStream(aElems[i]))
break;
else if (mxChildrenStorages.back().ref->IsStorage(aElems[i]))
{
SotStorageRef tmpParent(mxChildrenStorages.back().ref);
storageRefWrapper.ref = tmpParent->OpenSotStorage(aElems[i++], STREAM_STD_READ);
mxChildrenStorages.push_back(storageRefWrapper);
}
else
// should not happen
return 0;
}
// For the while don't return stream in this situation.
// Later, given how libcdr's zip stream implementation behaves,
// return the first stream in the storage if there is one.
if (i >= aElems.size())
return 0;
SotStorageStreamRefWrapper storageStreamRefWrapper;
storageStreamRefWrapper.ref = mxChildrenStorages.back().ref->OpenSotStream( aElems[i], STREAM_STD_READ );
mxChildrenStreams.push_back( storageStreamRefWrapper );
mxSeekable->seek(tmpPosition);
if ( !mxChildrenStreams.back().ref.Is() || mxChildrenStreams.back().ref->GetError() )
{
mxSeekable->seek(tmpPosition);
return 0;
}
Reference < XInputStream > xContents(new utl::OSeekableInputStreamWrapper( mxChildrenStreams.back().ref ));
mxSeekable->seek(tmpPosition);
if (xContents.is())
return new WPXSvInputStream( xContents );
else
return 0;
}
void WPXSvInputStreamImpl::invalidateReadBuffer()
{
if (mpReadBuffer)
{
seek((long) tell() + (long)mnReadBufferPos - (long)mnReadBufferLength);
delete [] mpReadBuffer;
mpReadBuffer = 0;
mnReadBufferPos = 0;
mnReadBufferLength = 0;
}
}
WPXSvInputStream::WPXSvInputStream( Reference< XInputStream > xStream ) :
mpImpl(new WPXSvInputStreamImpl(xStream))
{
}
WPXSvInputStream::~WPXSvInputStream()
{
if (mpImpl)
delete mpImpl;
}
#define BUFFER_MAX 65536
const unsigned char *WPXSvInputStream::read(unsigned long numBytes, unsigned long &numBytesRead)
{
numBytesRead = 0;
if (numBytes == 0 || numBytes > (std::numeric_limits<unsigned long>::max)()/2)
return 0;
if (mpImpl->mpReadBuffer)
{
if ((mpImpl->mnReadBufferPos + numBytes > mpImpl->mnReadBufferPos) && (mpImpl->mnReadBufferPos + numBytes <= mpImpl->mnReadBufferLength))
{
const unsigned char *pTmp = mpImpl->mpReadBuffer + mpImpl->mnReadBufferPos;
mpImpl->mnReadBufferPos += numBytes;
numBytesRead = numBytes;
return pTmp;
}
mpImpl->invalidateReadBuffer();
}
unsigned long curpos = (unsigned long) mpImpl->tell();
if (curpos == (unsigned long)-1) // returned ERROR
return 0;
if ((curpos + numBytes < curpos) /*overflow*/ ||
(curpos + numBytes >= (sal_uInt64)mpImpl->mnLength)) /*reading more than available*/
{
numBytes = mpImpl->mnLength - curpos;
}
if (numBytes < BUFFER_MAX)
{
if (BUFFER_MAX < mpImpl->mnLength - curpos)
mpImpl->mnReadBufferLength = BUFFER_MAX;
else /* BUFFER_MAX >= mpImpl->mnLength - curpos */
mpImpl->mnReadBufferLength = mpImpl->mnLength - curpos;
}
else
return mpImpl->read(numBytes, numBytesRead);
mpImpl->mpReadBuffer = new unsigned char[mpImpl->mnReadBufferLength];
unsigned long tmpNumBytes(0);
const unsigned char *pTmp = mpImpl->read(mpImpl->mnReadBufferLength, tmpNumBytes);
if (tmpNumBytes != mpImpl->mnReadBufferLength)
mpImpl->mnReadBufferLength = tmpNumBytes;
mpImpl->mnReadBufferPos = 0;
if (!mpImpl->mnReadBufferLength)
return 0;
numBytesRead = numBytes;
mpImpl->mnReadBufferPos += numBytesRead;
memcpy(mpImpl->mpReadBuffer, pTmp, mpImpl->mnReadBufferLength);
return const_cast<const unsigned char *>(mpImpl->mpReadBuffer);
}
long WPXSvInputStream::tell()
{
long retVal = mpImpl->tell();
return retVal - (long)mpImpl->mnReadBufferLength + (long)mpImpl->mnReadBufferPos;
}
int WPXSvInputStream::seek(long offset, WPX_SEEK_TYPE seekType)
{
sal_Int64 tmpOffset = offset;
if (seekType == WPX_SEEK_CUR)
tmpOffset += tell();
if (seekType == WPX_SEEK_END)
tmpOffset += mpImpl->mnLength;
int retVal = 0;
if (tmpOffset < 0)
{
tmpOffset = 0;
retVal = -1;
}
if (tmpOffset > mpImpl->mnLength)
{
tmpOffset = mpImpl->mnLength;
retVal = -1;
}
if (tmpOffset < mpImpl->tell() && (unsigned long)tmpOffset >= (unsigned long)mpImpl->tell() - mpImpl->mnReadBufferLength)
{
mpImpl->mnReadBufferPos = (unsigned long)(tmpOffset + (long) mpImpl->mnReadBufferLength - (long) mpImpl->tell());
return retVal;
}
mpImpl->invalidateReadBuffer();
if (mpImpl->seek(tmpOffset))
return -1;
return retVal;
}
bool WPXSvInputStream::atEOS()
{
return mpImpl->atEOS() && mpImpl->mnReadBufferPos == mpImpl->mnReadBufferLength;
}
bool WPXSvInputStream::isOLEStream()
{
mpImpl->invalidateReadBuffer();
return mpImpl->isOLEStream();
}
WPXInputStream *WPXSvInputStream::getDocumentOLEStream(const char *name)
{
mpImpl->invalidateReadBuffer();
return mpImpl->getDocumentOLEStream(name);
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/***************************************************************************
* algo/test_parallel_sort.cpp
*
* Part of the STXXL. See http://stxxl.sourceforge.net
*
* Copyright (C) 2007 Johannes Singler <singler@ira.uka.de>
* Copyright (C) 2008 Andreas Beckmann <beckmann@cs.uni-frankfurt.de>
*
* 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)
**************************************************************************/
#define MCSTL_QUICKSORT_WORKAROUND 0
#if !defined(STXXL_NOT_CONSIDER_SORT_MEMORY_OVERHEAD)
#define STXXL_NOT_CONSIDER_SORT_MEMORY_OVERHEAD 0
#endif
#include <algorithm>
#include <functional>
#include <limits>
#include <stxxl/vector>
#include <stxxl/stream>
#include <stxxl/scan>
#include <stxxl/sort>
#ifdef __MCSTL__
#include <mcstl.h>
#endif
const unsigned long long megabyte = 1024 * 1024;
//const int block_size = STXXL_DEFAULT_BLOCK_SIZE(my_type);
const int block_size = 4 * megabyte;
#define RECORD_SIZE 16
#define MAGIC 123
stxxl::unsigned_type run_size;
stxxl::unsigned_type buffer_size;
struct my_type
{
typedef unsigned long long key_type;
key_type _key;
key_type _load;
char _data[RECORD_SIZE - 2 * sizeof(key_type)];
key_type key() const { return _key; }
my_type() { }
my_type(key_type __key) : _key(__key) { }
my_type(key_type __key, key_type __load) : _key(__key), _load(__load) { }
void operator = (const key_type & __key) { _key = __key; }
void operator = (const my_type & mt)
{
_key = mt._key;
_load = mt._load;
}
};
bool operator < (const my_type & a, const my_type & b);
inline bool operator < (const my_type & a, const my_type & b)
{
return a.key() < b.key();
}
inline bool operator == (const my_type & a, const my_type & b)
{
return a.key() == b.key();
}
inline std::ostream & operator << (std::ostream & o, const my_type & obj)
{
o << obj._key << "/" << obj._load;
return o;
}
struct cmp_less_key : public std::less<my_type>
{
my_type min_value() const { return my_type(std::numeric_limits<my_type::key_type>::min(), MAGIC); }
my_type max_value() const { return my_type(std::numeric_limits<my_type::key_type>::max(), MAGIC); }
};
typedef stxxl::vector<my_type, 4, stxxl::lru_pager<8>, block_size, STXXL_DEFAULT_ALLOC_STRATEGY> vector_type;
stxxl::unsigned_type checksum(vector_type & input)
{
stxxl::unsigned_type sum = 0;
for (vector_type::const_iterator i = input.begin(); i != input.end(); ++i)
sum += (*i)._key;
return sum;
}
void linear_sort_normal(vector_type & input)
{
stxxl::unsigned_type sum1 = checksum(input);
stxxl::stats_data stats_begin(*stxxl::stats::get_instance());
double start = stxxl::timestamp();
stxxl::sort(input.begin(), input.end(), cmp_less_key(), run_size);
double stop = stxxl::timestamp();
std::cout << stxxl::stats_data(*stxxl::stats::get_instance()) - stats_begin;
stxxl::unsigned_type sum2 = checksum(input);
std::cout << sum1 << " ?= " << sum2 << std::endl;
STXXL_MSG((stxxl::is_sorted<vector_type::const_iterator>(input.begin(), input.end()) ? "OK" : "NOT SORTED"));
std::cout << "Linear sorting normal took " << (stop - start) << " seconds." << std::endl;
}
void linear_sort_streamed(vector_type & input, vector_type & output)
{
stxxl::unsigned_type sum1 = checksum(input);
stxxl::stats_data stats_begin(*stxxl::stats::get_instance());
double start = stxxl::timestamp();
typedef __typeof__(stxxl::stream::streamify(input.begin(), input.end())) input_stream_type;
input_stream_type input_stream = stxxl::stream::streamify(input.begin(), input.end());
typedef cmp_less_key comparator_type;
comparator_type cl;
typedef stxxl::stream::sort<input_stream_type, comparator_type, block_size> sort_stream_type;
sort_stream_type sort_stream(input_stream, cl, run_size);
vector_type::iterator o = stxxl::stream::materialize(sort_stream, output.begin(), output.end());
double stop = stxxl::timestamp();
std::cout << stxxl::stats_data(*stxxl::stats::get_instance()) - stats_begin;
stxxl::unsigned_type sum2 = checksum(output);
std::cout << sum1 << " ?= " << sum2 << std::endl;
if (sum1 != sum2)
STXXL_MSG("WRONG DATA");
STXXL_MSG((stxxl::is_sorted<vector_type::const_iterator>(output.begin(), output.end(), comparator_type()) ? "OK" : "NOT SORTED"));
std::cout << "Linear sorting streamed took " << (stop - start) << " seconds." << std::endl;
}
int main(int argc, const char ** argv)
{
if (argc < 6) {
std::cout << "Usage: " << argv[0] << " [n in MiB] [p threads] [M in MiB] [sorting algorithm: m | q | qb | s] [merging algorithm: p | s | n]" << std::endl;
return -1;
}
stxxl::config::get_instance();
#if STXXL_PARALLEL_MULTIWAY_MERGE
STXXL_MSG("STXXL_PARALLEL_MULTIWAY_MERGE");
#endif
unsigned long megabytes_to_process = atoi(argv[1]);
int p = atoi(argv[2]);
stxxl::unsigned_type memory_to_use = (stxxl::unsigned_type)atoi(argv[3]) * megabyte;
run_size = memory_to_use;
buffer_size = memory_to_use / 16;
#ifdef _GLIBCXX_PARALLEL
omp_set_num_threads(p);
__gnu_parallel::_Settings parallel_settings(__gnu_parallel::_Settings::get());
parallel_settings.merge_splitting = __gnu_parallel::EXACT;
parallel_settings.merge_minimal_n = 10000;
parallel_settings.merge_oversampling = 10;
parallel_settings.multiway_merge_algorithm = __gnu_parallel::LOSER_TREE;
parallel_settings.multiway_merge_splitting = __gnu_parallel::EXACT;
parallel_settings.multiway_merge_oversampling = 10;
parallel_settings.multiway_merge_minimal_n = 10000;
parallel_settings.multiway_merge_minimal_k = 2;
if (!strcmp(argv[4], "q")) //quicksort
parallel_settings.sort_algorithm = __gnu_parallel::QS;
else if (!strcmp(argv[4], "qb")) //balanced quicksort
parallel_settings.sort_algorithm = __gnu_parallel::QS_BALANCED;
else if (!strcmp(argv[4], "m")) //merge sort
parallel_settings.sort_algorithm = __gnu_parallel::MWMS;
else /*if(!strcmp(argv[4], "s"))*/ //sequential (default)
{
parallel_settings.sort_algorithm = __gnu_parallel::QS;
parallel_settings.sort_minimal_n = memory_to_use;
}
if (!strcmp(argv[5], "p")) //parallel
{
stxxl::SETTINGS::native_merge = false;
//parallel_settings.multiway_merge_minimal_n = 1024; //leave as default
}
else if (!strcmp(argv[5], "s")) //sequential
{
stxxl::SETTINGS::native_merge = false;
parallel_settings.multiway_merge_minimal_n = memory_to_use; //too much to be called
}
else /*if(!strcmp(argv[5], "n"))*/ //native (default)
stxxl::SETTINGS::native_merge = true;
parallel_settings.multiway_merge_minimal_k = 2;
__gnu_parallel::_Settings::set(parallel_settings);
assert(&__gnu_parallel::_Settings::get() != ¶llel_settings);
if (0)
printf("%d %p: mwms %d, q %d, qb %d",
__gnu_parallel::_Settings::get().sort_algorithm,
&__gnu_parallel::_Settings::get().sort_algorithm,
__gnu_parallel::MWMS,
__gnu_parallel::QS,
__gnu_parallel::QS_BALANCED);
#endif
#ifdef __MCSTL__
mcstl::HEURISTIC::num_threads = p;
mcstl::HEURISTIC::force_sequential = false;
mcstl::HEURISTIC::merge_splitting = mcstl::HEURISTIC::EXACT;
mcstl::HEURISTIC::merge_minimal_n = 10000;
mcstl::HEURISTIC::merge_oversampling = 10;
mcstl::HEURISTIC::multiway_merge_algorithm = mcstl::HEURISTIC::LOSER_TREE;
mcstl::HEURISTIC::multiway_merge_splitting = mcstl::HEURISTIC::EXACT;
mcstl::HEURISTIC::multiway_merge_oversampling = 10;
mcstl::HEURISTIC::multiway_merge_minimal_n = 10000;
mcstl::HEURISTIC::multiway_merge_minimal_k = 2;
if (!strcmp(argv[4], "q")) //quicksort
mcstl::HEURISTIC::sort_algorithm = mcstl::HEURISTIC::QS;
else if (!strcmp(argv[4], "qb")) //balanced quicksort
mcstl::HEURISTIC::sort_algorithm = mcstl::HEURISTIC::QS_BALANCED;
else if (!strcmp(argv[4], "m")) //merge sort
mcstl::HEURISTIC::sort_algorithm = mcstl::HEURISTIC::MWMS;
else /*if(!strcmp(argv[4], "s"))*/ //sequential (default)
{
mcstl::HEURISTIC::sort_algorithm = mcstl::HEURISTIC::QS;
mcstl::HEURISTIC::sort_minimal_n = memory_to_use;
}
if (!strcmp(argv[5], "p")) //parallel
{
stxxl::SETTINGS::native_merge = false;
//mcstl::HEURISTIC::multiway_merge_minimal_n = 1024; //leave as default
}
else if (!strcmp(argv[5], "s")) //sequential
{
stxxl::SETTINGS::native_merge = false;
mcstl::HEURISTIC::multiway_merge_minimal_n = memory_to_use; //too much to be called
}
else /*if(!strcmp(argv[5], "n"))*/ //native (default)
stxxl::SETTINGS::native_merge = true;
mcstl::HEURISTIC::multiway_merge_minimal_k = 2;
#endif
std::cout << "Sorting " << megabytes_to_process << " MiB of data ("
<< (megabytes_to_process * megabyte / sizeof(my_type)) << " elements) using "
<< (memory_to_use / megabyte) << " MiB of internal memory and "
<< p << " thread(s), block size "
<< block_size << ", element size " << sizeof(my_type) << std::endl;
const stxxl::int64 n_records =
stxxl::int64(megabytes_to_process) * stxxl::int64(megabyte) / sizeof(my_type);
vector_type input(n_records);
stxxl::stats_data stats_begin(*stxxl::stats::get_instance());
double generate_start = stxxl::timestamp();
stxxl::generate(input.begin(), input.end(), stxxl::random_number64(), memory_to_use / STXXL_DEFAULT_BLOCK_SIZE(my_type));
double generate_stop = stxxl::timestamp();
std::cout << stxxl::stats_data(*stxxl::stats::get_instance()) - stats_begin;
std::cout << "Generating took " << (generate_stop - generate_start) << " seconds." << std::endl;
STXXL_MSG(((stxxl::is_sorted<vector_type::const_iterator>(input.begin(), input.end())) ? "OK" : "NOT SORTED"));
{
vector_type output(n_records);
linear_sort_streamed(input, output);
linear_sort_normal(input);
}
return 0;
}
// vim: et:ts=4:sw=4
<commit_msg>use the return value, g++-4.6 has a new warning unused-but-set-variable<commit_after>/***************************************************************************
* algo/test_parallel_sort.cpp
*
* Part of the STXXL. See http://stxxl.sourceforge.net
*
* Copyright (C) 2007 Johannes Singler <singler@ira.uka.de>
* Copyright (C) 2008 Andreas Beckmann <beckmann@cs.uni-frankfurt.de>
*
* 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)
**************************************************************************/
#define MCSTL_QUICKSORT_WORKAROUND 0
#if !defined(STXXL_NOT_CONSIDER_SORT_MEMORY_OVERHEAD)
#define STXXL_NOT_CONSIDER_SORT_MEMORY_OVERHEAD 0
#endif
#include <algorithm>
#include <functional>
#include <limits>
#include <stxxl/vector>
#include <stxxl/stream>
#include <stxxl/scan>
#include <stxxl/sort>
#ifdef __MCSTL__
#include <mcstl.h>
#endif
const unsigned long long megabyte = 1024 * 1024;
//const int block_size = STXXL_DEFAULT_BLOCK_SIZE(my_type);
const int block_size = 4 * megabyte;
#define RECORD_SIZE 16
#define MAGIC 123
stxxl::unsigned_type run_size;
stxxl::unsigned_type buffer_size;
struct my_type
{
typedef unsigned long long key_type;
key_type _key;
key_type _load;
char _data[RECORD_SIZE - 2 * sizeof(key_type)];
key_type key() const { return _key; }
my_type() { }
my_type(key_type __key) : _key(__key) { }
my_type(key_type __key, key_type __load) : _key(__key), _load(__load) { }
void operator = (const key_type & __key) { _key = __key; }
void operator = (const my_type & mt)
{
_key = mt._key;
_load = mt._load;
}
};
bool operator < (const my_type & a, const my_type & b);
inline bool operator < (const my_type & a, const my_type & b)
{
return a.key() < b.key();
}
inline bool operator == (const my_type & a, const my_type & b)
{
return a.key() == b.key();
}
inline std::ostream & operator << (std::ostream & o, const my_type & obj)
{
o << obj._key << "/" << obj._load;
return o;
}
struct cmp_less_key : public std::less<my_type>
{
my_type min_value() const { return my_type(std::numeric_limits<my_type::key_type>::min(), MAGIC); }
my_type max_value() const { return my_type(std::numeric_limits<my_type::key_type>::max(), MAGIC); }
};
typedef stxxl::vector<my_type, 4, stxxl::lru_pager<8>, block_size, STXXL_DEFAULT_ALLOC_STRATEGY> vector_type;
stxxl::unsigned_type checksum(vector_type & input)
{
stxxl::unsigned_type sum = 0;
for (vector_type::const_iterator i = input.begin(); i != input.end(); ++i)
sum += (*i)._key;
return sum;
}
void linear_sort_normal(vector_type & input)
{
stxxl::unsigned_type sum1 = checksum(input);
stxxl::stats_data stats_begin(*stxxl::stats::get_instance());
double start = stxxl::timestamp();
stxxl::sort(input.begin(), input.end(), cmp_less_key(), run_size);
double stop = stxxl::timestamp();
std::cout << stxxl::stats_data(*stxxl::stats::get_instance()) - stats_begin;
stxxl::unsigned_type sum2 = checksum(input);
std::cout << sum1 << " ?= " << sum2 << std::endl;
STXXL_MSG((stxxl::is_sorted<vector_type::const_iterator>(input.begin(), input.end()) ? "OK" : "NOT SORTED"));
std::cout << "Linear sorting normal took " << (stop - start) << " seconds." << std::endl;
}
void linear_sort_streamed(vector_type & input, vector_type & output)
{
stxxl::unsigned_type sum1 = checksum(input);
stxxl::stats_data stats_begin(*stxxl::stats::get_instance());
double start = stxxl::timestamp();
typedef __typeof__(stxxl::stream::streamify(input.begin(), input.end())) input_stream_type;
input_stream_type input_stream = stxxl::stream::streamify(input.begin(), input.end());
typedef cmp_less_key comparator_type;
comparator_type cl;
typedef stxxl::stream::sort<input_stream_type, comparator_type, block_size> sort_stream_type;
sort_stream_type sort_stream(input_stream, cl, run_size);
vector_type::iterator o = stxxl::stream::materialize(sort_stream, output.begin(), output.end());
assert(o == output.end());
double stop = stxxl::timestamp();
std::cout << stxxl::stats_data(*stxxl::stats::get_instance()) - stats_begin;
stxxl::unsigned_type sum2 = checksum(output);
std::cout << sum1 << " ?= " << sum2 << std::endl;
if (sum1 != sum2)
STXXL_MSG("WRONG DATA");
STXXL_MSG((stxxl::is_sorted<vector_type::const_iterator>(output.begin(), output.end(), comparator_type()) ? "OK" : "NOT SORTED"));
std::cout << "Linear sorting streamed took " << (stop - start) << " seconds." << std::endl;
}
int main(int argc, const char ** argv)
{
if (argc < 6) {
std::cout << "Usage: " << argv[0] << " [n in MiB] [p threads] [M in MiB] [sorting algorithm: m | q | qb | s] [merging algorithm: p | s | n]" << std::endl;
return -1;
}
stxxl::config::get_instance();
#if STXXL_PARALLEL_MULTIWAY_MERGE
STXXL_MSG("STXXL_PARALLEL_MULTIWAY_MERGE");
#endif
unsigned long megabytes_to_process = atoi(argv[1]);
int p = atoi(argv[2]);
stxxl::unsigned_type memory_to_use = (stxxl::unsigned_type)atoi(argv[3]) * megabyte;
run_size = memory_to_use;
buffer_size = memory_to_use / 16;
#ifdef _GLIBCXX_PARALLEL
omp_set_num_threads(p);
__gnu_parallel::_Settings parallel_settings(__gnu_parallel::_Settings::get());
parallel_settings.merge_splitting = __gnu_parallel::EXACT;
parallel_settings.merge_minimal_n = 10000;
parallel_settings.merge_oversampling = 10;
parallel_settings.multiway_merge_algorithm = __gnu_parallel::LOSER_TREE;
parallel_settings.multiway_merge_splitting = __gnu_parallel::EXACT;
parallel_settings.multiway_merge_oversampling = 10;
parallel_settings.multiway_merge_minimal_n = 10000;
parallel_settings.multiway_merge_minimal_k = 2;
if (!strcmp(argv[4], "q")) //quicksort
parallel_settings.sort_algorithm = __gnu_parallel::QS;
else if (!strcmp(argv[4], "qb")) //balanced quicksort
parallel_settings.sort_algorithm = __gnu_parallel::QS_BALANCED;
else if (!strcmp(argv[4], "m")) //merge sort
parallel_settings.sort_algorithm = __gnu_parallel::MWMS;
else /*if(!strcmp(argv[4], "s"))*/ //sequential (default)
{
parallel_settings.sort_algorithm = __gnu_parallel::QS;
parallel_settings.sort_minimal_n = memory_to_use;
}
if (!strcmp(argv[5], "p")) //parallel
{
stxxl::SETTINGS::native_merge = false;
//parallel_settings.multiway_merge_minimal_n = 1024; //leave as default
}
else if (!strcmp(argv[5], "s")) //sequential
{
stxxl::SETTINGS::native_merge = false;
parallel_settings.multiway_merge_minimal_n = memory_to_use; //too much to be called
}
else /*if(!strcmp(argv[5], "n"))*/ //native (default)
stxxl::SETTINGS::native_merge = true;
parallel_settings.multiway_merge_minimal_k = 2;
__gnu_parallel::_Settings::set(parallel_settings);
assert(&__gnu_parallel::_Settings::get() != ¶llel_settings);
if (0)
printf("%d %p: mwms %d, q %d, qb %d",
__gnu_parallel::_Settings::get().sort_algorithm,
&__gnu_parallel::_Settings::get().sort_algorithm,
__gnu_parallel::MWMS,
__gnu_parallel::QS,
__gnu_parallel::QS_BALANCED);
#endif
#ifdef __MCSTL__
mcstl::HEURISTIC::num_threads = p;
mcstl::HEURISTIC::force_sequential = false;
mcstl::HEURISTIC::merge_splitting = mcstl::HEURISTIC::EXACT;
mcstl::HEURISTIC::merge_minimal_n = 10000;
mcstl::HEURISTIC::merge_oversampling = 10;
mcstl::HEURISTIC::multiway_merge_algorithm = mcstl::HEURISTIC::LOSER_TREE;
mcstl::HEURISTIC::multiway_merge_splitting = mcstl::HEURISTIC::EXACT;
mcstl::HEURISTIC::multiway_merge_oversampling = 10;
mcstl::HEURISTIC::multiway_merge_minimal_n = 10000;
mcstl::HEURISTIC::multiway_merge_minimal_k = 2;
if (!strcmp(argv[4], "q")) //quicksort
mcstl::HEURISTIC::sort_algorithm = mcstl::HEURISTIC::QS;
else if (!strcmp(argv[4], "qb")) //balanced quicksort
mcstl::HEURISTIC::sort_algorithm = mcstl::HEURISTIC::QS_BALANCED;
else if (!strcmp(argv[4], "m")) //merge sort
mcstl::HEURISTIC::sort_algorithm = mcstl::HEURISTIC::MWMS;
else /*if(!strcmp(argv[4], "s"))*/ //sequential (default)
{
mcstl::HEURISTIC::sort_algorithm = mcstl::HEURISTIC::QS;
mcstl::HEURISTIC::sort_minimal_n = memory_to_use;
}
if (!strcmp(argv[5], "p")) //parallel
{
stxxl::SETTINGS::native_merge = false;
//mcstl::HEURISTIC::multiway_merge_minimal_n = 1024; //leave as default
}
else if (!strcmp(argv[5], "s")) //sequential
{
stxxl::SETTINGS::native_merge = false;
mcstl::HEURISTIC::multiway_merge_minimal_n = memory_to_use; //too much to be called
}
else /*if(!strcmp(argv[5], "n"))*/ //native (default)
stxxl::SETTINGS::native_merge = true;
mcstl::HEURISTIC::multiway_merge_minimal_k = 2;
#endif
std::cout << "Sorting " << megabytes_to_process << " MiB of data ("
<< (megabytes_to_process * megabyte / sizeof(my_type)) << " elements) using "
<< (memory_to_use / megabyte) << " MiB of internal memory and "
<< p << " thread(s), block size "
<< block_size << ", element size " << sizeof(my_type) << std::endl;
const stxxl::int64 n_records =
stxxl::int64(megabytes_to_process) * stxxl::int64(megabyte) / sizeof(my_type);
vector_type input(n_records);
stxxl::stats_data stats_begin(*stxxl::stats::get_instance());
double generate_start = stxxl::timestamp();
stxxl::generate(input.begin(), input.end(), stxxl::random_number64(), memory_to_use / STXXL_DEFAULT_BLOCK_SIZE(my_type));
double generate_stop = stxxl::timestamp();
std::cout << stxxl::stats_data(*stxxl::stats::get_instance()) - stats_begin;
std::cout << "Generating took " << (generate_stop - generate_start) << " seconds." << std::endl;
STXXL_MSG(((stxxl::is_sorted<vector_type::const_iterator>(input.begin(), input.end())) ? "OK" : "NOT SORTED"));
{
vector_type output(n_records);
linear_sort_streamed(input, output);
linear_sort_normal(input);
}
return 0;
}
// vim: et:ts=4:sw=4
<|endoftext|> |
<commit_before>//
// a21 — Arduino Toolkit.
// Copyright (C) 2016-2017, Aleh Dzenisiuk. http://github.com/aleh/a21
//
#include <Arduino.h>
#include <util/delay.h>
#include "pcd8544fonts.hpp"
namespace a21 {
/**
* Basic wrapper for a PCD8544 LCD display (such as the one that was used on Nokia 5110) with softwate SPI.
* Note that the 'slow' parameter should be true only if this happen to be ported on a faster MCU
* and we need to ensure clock speed is less than 4 MHz.
* (The clock frequency will be less than 2 MHz on 16MHz Arduinos even with 'slow' being false.)
*/
template<typename pinRST, typename pinCE, typename pinDC, typename pinDIN, typename pinCLK, bool slow = false>
class PCD8544 {
/** Delays execution for at least a half of the minimal clock period, which is 1/4 us in the datasheet. */
static inline void delay125() __attribute__((always_inline)) {
_delay_us((1.0 / 4000000) / 2);
}
static inline void writeBit(bool b) __attribute__((always_inline)) {
// Set the data bit, will have enough time to settle before the clock raising.
pinDIN::write(b);
// Clock the data bit out on the raising edge.
pinCLK::setLow();
// Let's delay a bit in the slow mode.
if (slow)
delay125();
// Clock it out!
pinCLK::setHigh();
// The preparation for the next bit slow enough, so no delays are actually needed here.
}
enum ValueType : uint8_t {
Command,
Data
};
static void write(ValueType valueType, uint8_t value) {
pinDC::write(valueType == Data);
writeBit(value & _BV(7));
writeBit(value & _BV(6));
writeBit(value & _BV(5));
writeBit(value & _BV(4));
writeBit(value & _BV(3));
writeBit(value & _BV(2));
writeBit(value & _BV(1));
writeBit(value & _BV(0));
}
static void beginWriting() {
pinCLK::setLow();
pinCE::setLow();
}
static void endWriting() {
pinCE::setHigh();
}
enum FunctionSetCommand : uint8_t {
FunctionSet = 0x20,
/** 0 - basic command set, 1 - extended command set. */
H = 1,
/** 0 - horizontal addressing mode, 1 - vertical addressing mode. */
V = 2,
/** 0 - chip active, 1 - chip in power down mode. */
PD = 4
};
enum DisplayControlCommand : uint8_t {
DisplayControl = 0x08,
D = 0x04,
E = 0x01,
DisplayBlank = (uint8_t)(~(D | E)),
NormalMode = (uint8_t)(D & ~E),
AllSegmentsOn = (uint8_t)(~D & E),
InverseVideoMode = (uint8_t)(D | E)
};
enum SetXAddressCommand : uint8_t {
SetXAddress = 0x80,
SetXAddressMask = 0x7F
};
enum SetYAddressCommand : uint8_t {
SetYAddress = 0x40,
SetYAddressMask = 0x07
};
enum TemperatureControlExtendedCommand : uint8_t {
TemperatureControl = 0x04,
TemperatureControlMask = 0x3
};
enum BiasSystemExtendedCommand : uint8_t {
BiasSystem = 0x10,
BiasSystemMask = 0x07
};
enum SetVopExtendedCommand : uint8_t {
SetVop = 0x80,
SetVopMask = 0x7F
};
static inline void extendedCommandSet(bool extended) {
write(Command, extended ? (FunctionSet | H) & ~(PD | V) : (FunctionSet | 0) & ~(PD | V | H));
}
static inline void setAddressInternal(uint8_t col, uint8_t row) {
extendedCommandSet(false);
write(Command, SetXAddress | col);
write(Command, SetYAddress | row);
}
static inline void config(uint8_t operatingVoltage, uint8_t biasSystem, uint8_t temperatureControl) {
beginWriting();
// TODO: perhaps make the display mode a parameter?
extendedCommandSet(false);
write(Command, DisplayControl | NormalMode);
extendedCommandSet(true);
write(Command, SetVop | (operatingVoltage & SetVopMask));
write(Command, BiasSystem | (biasSystem & BiasSystemMask));
write(Command, TemperatureControl | (temperatureControl & TemperatureControlMask));
endWriting();
}
public:
/** Number of addressable rows, with every row corresponding to 8 horizontal lines of actual pixels. */
static const int Rows = 6;
/** Number of addressable columns, though unlike rows every column corresponds to 1 vertical line of pixels. */
static const int Cols = 84;
/** Maximum value for the parameter of operatingVoltage function, though the actual usable values are usually much smaller. */
const uint8_t MaxVoltage = 0x7F;
/** Sets operational voltage affecting contrast of the display. */
static void operatingVoltage(uint8_t value) {
beginWriting();
extendedCommandSet(true);
write(Command, SetVop | value);
endWriting();
}
/** Clears the display. */
static void clear() {
beginWriting();
setAddressInternal(0, 0);
for (int i = 0; i < Rows * Cols; i++) {
write(Data, 0);
}
endWriting();
}
/** Initializes the device and transport pins. */
static void begin(uint8_t operatingVoltage = 52, uint8_t biasSystem = 4, uint8_t temperatureControl = 2) {
pinDIN::setOutput();
pinDIN::setLow();
pinCLK::setOutput();
pinCLK::setLow();
pinDC::setOutput();
pinDC::setLow();
pinCE::setOutput();
pinCE::setHigh();
pinRST::setOutput();
pinRST::setLow();
delay125();
pinRST::setHigh();
config(operatingVoltage, biasSystem, temperatureControl);
clear();
}
/**
* Transports a bunch of bytes for the given row. Each byte is responsible for a 8 pixel column within the row
* (MSB is in the bottom of the row, LSB is in the top).
*
* The row is filled from left to right (i.e. column address is automaticallt incremented).
* col col + 1
* line row * 8: # bit 0 # bit 0 ...
* line row * 8 + 1: # bit 1 # bit 1 ...
* ...
* line row * 8 + 7: # bit 7 # bit 7 ...
* ^ ^
* byte 0 byte 1
*
* Note that if more bytes are provided than is left in the row, then they'll be written to the next one
* (or the first one in case of the last row).
*/
static void writeRow(uint8_t col, uint8_t row, const uint8_t *data, uint8_t data_length) {
beginWriting();
setAddressInternal(col, row);
const uint8_t *src = data;
for (uint8_t c = data_length; c > 0; c--) {
write(Data, *src++);
}
endWriting();
}
static void fillRow(uint8_t col, uint8_t row, uint8_t length, uint8_t filler) {
beginWriting();
setAddressInternal(col, row);
for (uint8_t c = length; c > 0; c--) {
write(Data, filler);
}
endWriting();
}
//
// Fonts
//
/** Returns the width of the glyph corresponding to a character in the given font and, if a buffer is provided,
* copies glyph's bitmap into it. */
static uint8_t dataForCharacter(PCD8544Font font, char ch, uint8_t *buffer) {
const uint8_t *p = font;
uint8_t options = pgm_read_byte(p++);
if ((options & 1) && 'a' <= ch && ch <= 'z') {
ch = ch - 'a' + 'A';
}
while (true) {
// First character in the range (0 would mean no more ranges are defined).
uint8_t first = pgm_read_byte(p++);
if (first == 0)
break;
// Last character in the range.
uint8_t last = pgm_read_byte(p++);
// Number of bytes every character in the range occupies.
uint8_t bytes_per_character = pgm_read_byte(p++);
if (first <= ch && ch <= last) {
// Our character is in the range, let's copy the data for it.
p += (ch - first) * bytes_per_character;
// The first byte of the glyph data is the actual width of the glyph.
uint8_t width = pgm_read_byte(p++);
// Copy the bitmap if the caller expects it.
if (buffer) {
memcpy_PF(buffer, (uint_farptr_t)p, width);
}
return width;
}
// Well, let's skip to the next range of characters.
p += (last + 1 - first) * bytes_per_character;
}
// Let's return data for sort of a default character.
return dataForCharacter(font, '?', buffer);
}
static uint8_t textWidth(PCD8544Font font, const char *text) {
char ch;
const char *src = text;
uint8_t result = 0;
while ((ch = *src++)) {
uint8_t width = dataForCharacter(font, ch, NULL);
result += width + 1;
}
return result;
}
/** Returns how many characters will fit max_width without being truncacted. */
static uint8_t numberOfCharsFittingWidth(PCD8544Font font, const char *text, uint8_t max_width) {
uint8_t result = 0;
char ch;
const char *src = text;
uint8_t total_width = 0;
while ((ch = *src++)) {
uint8_t new_total_width = total_width + dataForCharacter(font, ch, NULL) + 1;
if (new_total_width > max_width)
break;
total_width = new_total_width;
result++;
}
return result;
}
static uint8_t drawText(
PCD8544Font font,
const uint8_t col,
const uint8_t row,
const uint8_t max_width,
const char *text,
const uint8_t xor_mask = 0
) {
beginWriting();
setAddressInternal(col, row);
char ch;
const char *src = text;
uint8_t width_left = max_width;
while ((ch = *src++)) {
uint8_t bitmap[8];
uint8_t width = dataForCharacter(font, ch, bitmap);
for (uint8_t i = 0; i < width; i++) {
write(Data, bitmap[i] ^ xor_mask);
if (--width_left == 0) {
endWriting();
return 0;
}
}
write(Data, xor_mask);
if (--width_left == 0)
break;
}
endWriting();
return max_width - width_left;
}
};
template<typename lcd, typename font>
class PCD8544Console {
private:
static const uint8_t MaxCols = lcd::Cols / 4;
char _buffer[lcd::Rows][MaxCols + 1];
uint8_t _row;
uint8_t _col;
uint8_t _rowWidth;
uint8_t _filledRows;
void newline() {
_col = 0;
_rowWidth = 0;
_row++;
if (_row >= lcd::Rows) {
_row = 0;
}
_filledRows++;
if (_filledRows >= lcd::Rows) {
_filledRows--;
}
_buffer[_row][_col] = 0;
}
void carriage_return() {
_col = 0;
_rowWidth = 0;
}
public:
PCD8544Console() : _row(0), _col(0), _rowWidth(0), _filledRows(0) {}
void clear() {
_row = _filledRows = 0;
_col = 0;
_rowWidth = 0;
for (uint8_t row = 0; row < lcd::Rows; row++) {
_buffer[row][0] = 0;
}
}
void draw() {
for (uint8_t i = 0; i <= _filledRows; i++) {
int8_t row_index = _row - _filledRows + i;
if (row_index < 0)
row_index += lcd::Rows;
// Print the row and erase the rest.
uint8_t width = lcd::drawText(font::font(), 0, i, lcd::Cols, _buffer[row_index]);
lcd::fillRow(width, i, lcd::Cols - width, 0);
}
}
void print(const char *text) {
char ch;
const char *src = text;
while ((ch = *src++)) {
if (ch >= ' ') {
uint8_t width = lcd::dataForCharacter(font::font(), ch, NULL);
if (_col >= MaxCols || _rowWidth + width >= lcd::Cols) {
newline();
}
_buffer[_row][_col] = ch;
_col++;
_buffer[_row][_col] = 0;
_rowWidth += width + 1;
} else if (ch == '\n') {
newline();
} else if (ch == '\r') {
carriage_return();
}
}
}
};
} // namespace
<commit_msg>Fix PCD8544 console output to redraw the screen all the times<commit_after>//
// a21 — Arduino Toolkit.
// Copyright (C) 2016-2017, Aleh Dzenisiuk. http://github.com/aleh/a21
//
#include <Arduino.h>
#include <util/delay.h>
#include "pcd8544fonts.hpp"
namespace a21 {
/**
* Basic wrapper for a PCD8544 LCD display (such as the one that was used on Nokia 5110) with softwate SPI.
* Note that the 'slow' parameter should be true only if this happen to be ported on a faster MCU
* and we need to ensure clock speed is less than 4 MHz.
* (The clock frequency will be less than 2 MHz on 16MHz Arduinos even with 'slow' being false.)
*/
template<typename pinRST, typename pinCE, typename pinDC, typename pinDIN, typename pinCLK, bool slow = false>
class PCD8544 {
/** Delays execution for at least a half of the minimal clock period, which is 1/4 us in the datasheet. */
static inline void delay125() __attribute__((always_inline)) {
_delay_us((1.0 / 4000000) / 2);
}
static inline void writeBit(bool b) __attribute__((always_inline)) {
// Set the data bit, will have enough time to settle before the clock raising.
pinDIN::write(b);
// Clock the data bit out on the raising edge.
pinCLK::setLow();
// Let's delay a bit in the slow mode.
if (slow)
delay125();
// Clock it out!
pinCLK::setHigh();
// The preparation for the next bit slow enough, so no delays are actually needed here.
}
enum ValueType : uint8_t {
Command,
Data
};
static void write(ValueType valueType, uint8_t value) {
pinDC::write(valueType == Data);
writeBit(value & _BV(7));
writeBit(value & _BV(6));
writeBit(value & _BV(5));
writeBit(value & _BV(4));
writeBit(value & _BV(3));
writeBit(value & _BV(2));
writeBit(value & _BV(1));
writeBit(value & _BV(0));
}
static void beginWriting() {
pinCLK::setLow();
pinCE::setLow();
}
static void endWriting() {
pinCE::setHigh();
}
enum FunctionSetCommand : uint8_t {
FunctionSet = 0x20,
/** 0 - basic command set, 1 - extended command set. */
H = 1,
/** 0 - horizontal addressing mode, 1 - vertical addressing mode. */
V = 2,
/** 0 - chip active, 1 - chip in power down mode. */
PD = 4
};
enum DisplayControlCommand : uint8_t {
DisplayControl = 0x08,
D = 0x04,
E = 0x01,
DisplayBlank = (uint8_t)(~(D | E)),
NormalMode = (uint8_t)(D & ~E),
AllSegmentsOn = (uint8_t)(~D & E),
InverseVideoMode = (uint8_t)(D | E)
};
enum SetXAddressCommand : uint8_t {
SetXAddress = 0x80,
SetXAddressMask = 0x7F
};
enum SetYAddressCommand : uint8_t {
SetYAddress = 0x40,
SetYAddressMask = 0x07
};
enum TemperatureControlExtendedCommand : uint8_t {
TemperatureControl = 0x04,
TemperatureControlMask = 0x3
};
enum BiasSystemExtendedCommand : uint8_t {
BiasSystem = 0x10,
BiasSystemMask = 0x07
};
enum SetVopExtendedCommand : uint8_t {
SetVop = 0x80,
SetVopMask = 0x7F
};
static inline void extendedCommandSet(bool extended) {
write(Command, extended ? (FunctionSet | H) & ~(PD | V) : (FunctionSet | 0) & ~(PD | V | H));
}
static inline void setAddressInternal(uint8_t col, uint8_t row) {
extendedCommandSet(false);
write(Command, SetXAddress | col);
write(Command, SetYAddress | row);
}
static inline void config(uint8_t operatingVoltage, uint8_t biasSystem, uint8_t temperatureControl) {
beginWriting();
// TODO: perhaps make the display mode a parameter?
extendedCommandSet(false);
write(Command, DisplayControl | NormalMode);
extendedCommandSet(true);
write(Command, SetVop | (operatingVoltage & SetVopMask));
write(Command, BiasSystem | (biasSystem & BiasSystemMask));
write(Command, TemperatureControl | (temperatureControl & TemperatureControlMask));
endWriting();
}
public:
/** Number of addressable rows, with every row corresponding to 8 horizontal lines of actual pixels. */
static const int Rows = 6;
/** Number of addressable columns, though unlike rows every column corresponds to 1 vertical line of pixels. */
static const int Cols = 84;
/** Maximum value for the parameter of operatingVoltage function, though the actual usable values are usually much smaller. */
const uint8_t MaxVoltage = 0x7F;
/** Sets operational voltage affecting contrast of the display. */
static void operatingVoltage(uint8_t value) {
beginWriting();
extendedCommandSet(true);
write(Command, SetVop | value);
endWriting();
}
/** Clears the display. */
static void clear() {
beginWriting();
setAddressInternal(0, 0);
for (int i = 0; i < Rows * Cols; i++) {
write(Data, 0);
}
endWriting();
}
/** Initializes the device and transport pins. */
static void begin(uint8_t operatingVoltage = 52, uint8_t biasSystem = 4, uint8_t temperatureControl = 2) {
pinDIN::setOutput();
pinDIN::setLow();
pinCLK::setOutput();
pinCLK::setLow();
pinDC::setOutput();
pinDC::setLow();
pinCE::setOutput();
pinCE::setHigh();
pinRST::setOutput();
pinRST::setLow();
delay125();
pinRST::setHigh();
config(operatingVoltage, biasSystem, temperatureControl);
clear();
}
/**
* Transports a bunch of bytes for the given row. Each byte is responsible for a 8 pixel column within the row
* (MSB is in the bottom of the row, LSB is in the top).
*
* The row is filled from left to right (i.e. column address is automaticallt incremented).
* col col + 1
* line row * 8: # bit 0 # bit 0 ...
* line row * 8 + 1: # bit 1 # bit 1 ...
* ...
* line row * 8 + 7: # bit 7 # bit 7 ...
* ^ ^
* byte 0 byte 1
*
* Note that if more bytes are provided than is left in the row, then they'll be written to the next one
* (or the first one in case of the last row).
*/
static void writeRow(uint8_t col, uint8_t row, const uint8_t *data, uint8_t data_length) {
beginWriting();
setAddressInternal(col, row);
const uint8_t *src = data;
for (uint8_t c = data_length; c > 0; c--) {
write(Data, *src++);
}
endWriting();
}
static void fillRow(uint8_t col, uint8_t row, uint8_t length, uint8_t filler) {
beginWriting();
setAddressInternal(col, row);
for (uint8_t c = length; c > 0; c--) {
write(Data, filler);
}
endWriting();
}
//
// Fonts
//
/** Returns the width of the glyph corresponding to a character in the given font and, if a buffer is provided,
* copies glyph's bitmap into it. */
static uint8_t dataForCharacter(PCD8544Font font, char ch, uint8_t *buffer) {
const uint8_t *p = font;
uint8_t options = pgm_read_byte(p++);
if ((options & 1) && 'a' <= ch && ch <= 'z') {
ch = ch - 'a' + 'A';
}
while (true) {
// First character in the range (0 would mean no more ranges are defined).
uint8_t first = pgm_read_byte(p++);
if (first == 0)
break;
// Last character in the range.
uint8_t last = pgm_read_byte(p++);
// Number of bytes every character in the range occupies.
uint8_t bytes_per_character = pgm_read_byte(p++);
if (first <= ch && ch <= last) {
// Our character is in the range, let's copy the data for it.
p += (ch - first) * bytes_per_character;
// The first byte of the glyph data is the actual width of the glyph.
uint8_t width = pgm_read_byte(p++);
// Copy the bitmap if the caller expects it.
if (buffer) {
memcpy_PF(buffer, (uint_farptr_t)p, width);
}
return width;
}
// Well, let's skip to the next range of characters.
p += (last + 1 - first) * bytes_per_character;
}
// Let's return data for sort of a default character.
return dataForCharacter(font, '?', buffer);
}
static uint8_t textWidth(PCD8544Font font, const char *text) {
char ch;
const char *src = text;
uint8_t result = 0;
while ((ch = *src++)) {
uint8_t width = dataForCharacter(font, ch, NULL);
result += width + 1;
}
return result;
}
/** Returns how many characters will fit max_width without being truncacted. */
static uint8_t numberOfCharsFittingWidth(PCD8544Font font, const char *text, uint8_t max_width) {
uint8_t result = 0;
char ch;
const char *src = text;
uint8_t total_width = 0;
while ((ch = *src++)) {
uint8_t new_total_width = total_width + dataForCharacter(font, ch, NULL) + 1;
if (new_total_width > max_width)
break;
total_width = new_total_width;
result++;
}
return result;
}
static uint8_t drawText(
PCD8544Font font,
const uint8_t col,
const uint8_t row,
const uint8_t max_width,
const char *text,
const uint8_t xor_mask = 0
) {
beginWriting();
setAddressInternal(col, row);
char ch;
const char *src = text;
uint8_t width_left = max_width;
while ((ch = *src++)) {
uint8_t bitmap[8];
uint8_t width = dataForCharacter(font, ch, bitmap);
for (uint8_t i = 0; i < width; i++) {
write(Data, bitmap[i] ^ xor_mask);
if (--width_left == 0) {
endWriting();
return 0;
}
}
write(Data, xor_mask);
if (--width_left == 0)
break;
}
endWriting();
return max_width - width_left;
}
};
template<typename lcd, typename font>
class PCD8544Console {
private:
static const uint8_t MaxCols = lcd::Cols / 4;
char _buffer[lcd::Rows][MaxCols + 1];
uint8_t _row;
uint8_t _col;
uint8_t _rowWidth;
uint8_t _filledRows;
void newline() {
_col = 0;
_rowWidth = 0;
_row++;
if (_row >= lcd::Rows) {
_row = 0;
}
_filledRows++;
if (_filledRows >= lcd::Rows) {
_filledRows--;
}
_buffer[_row][_col] = 0;
}
void carriage_return() {
_col = 0;
_rowWidth = 0;
}
public:
PCD8544Console() : _row(0), _col(0), _rowWidth(0), _filledRows(0) {}
void clear() {
_row = _filledRows = 0;
_col = 0;
_rowWidth = 0;
for (uint8_t row = 0; row < lcd::Rows; row++) {
_buffer[row][0] = 0;
}
}
void draw() {
for (uint8_t i = 0; i < lcd::Rows; i++) {
int8_t row_index = _row - _filledRows + i;
if (row_index < 0)
row_index += lcd::Rows;
// Print the row and erase the rest.
uint8_t width = lcd::drawText(font::font(), 0, i, lcd::Cols, _buffer[row_index]);
lcd::fillRow(width, i, lcd::Cols - width, 0);
}
}
void print(const char *text) {
char ch;
const char *src = text;
while ((ch = *src++)) {
if (ch >= ' ') {
uint8_t width = lcd::dataForCharacter(font::font(), ch, NULL);
if (_col >= MaxCols || _rowWidth + width >= lcd::Cols) {
newline();
}
_buffer[_row][_col] = ch;
_col++;
_buffer[_row][_col] = 0;
_rowWidth += width + 1;
} else if (ch == '\n') {
newline();
} else if (ch == '\r') {
carriage_return();
}
}
}
};
} // namespace
<|endoftext|> |
<commit_before>/*
(c) Copyright 2000 convergence integrated media GmbH.
All rights reserved.
Written by Denis Oliver Kropp <dok@convergence.de> and
Andreas Hundt <andi@convergence.de>.
The contents of this software are proprietary and confidential to
convergence integrated media GmbH. Use of this information is
to be in accordance with the terms of the license agreement you
entered into with convergence integrated media GmbH. Individuals
having access to this software are responsible for maintaining the
confidentiality of the content and for keeping the software secure
when not in use. Transfer to any party is strictly forbidden other
than as expressly permitted in writing by convergence integrated
media GmbH. Unauthorized transfer to or possession by any
unauthorized party may be a criminal offense.
convergence integrated media GmbH MAKES NO WARRANTIES EITHER
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
OR NON-INFRINGEMENT.
convergence integrated media GmbH SHALL NOT BE LIABLE FOR ANY
DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
convergence integrated media GmbH
Rosenthaler Str.51
D-10178 Berlin / Germany
*/
extern "C" {
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <malloc.h>
#include <directfb.h>
#include <misc/util.h>
#include <core/core.h>
#include <core/coredefs.h>
#include <core/layers.h>
#include <core/gfxcard.h>
#include <display/idirectfbsurface.h>
}
#include <aviplay.h>
/*
* private data struct of IDirectFBVideoProvider
*/
typedef struct {
int ref; /* reference counter */
IAviPlayer *player;
IDirectFBSurface *destination;
DFBRectangle dest_rect;
DVFrameCallback callback;
void *ctx;
CardState state;
CoreSurface source;
} IDirectFBVideoProvider_AviFile_data;
static void IDirectFBVideoProvider_AviFile_Destruct(
IDirectFBVideoProvider *thiz )
{
IDirectFBVideoProvider_AviFile_data *data;
data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;
if (data->player->IsPlaying())
data->player->Stop();
free( thiz->priv );
thiz->priv = NULL;
}
static DFBResult IDirectFBVideoProvider_AviFile_AddRef(
IDirectFBVideoProvider *thiz )
{
IDirectFBVideoProvider_AviFile_data *data;
if (!thiz)
return DFB_INVARG;
data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;
if (!data)
return DFB_DEAD;
data->ref++;
return DFB_OK;
}
static DFBResult IDirectFBVideoProvider_AviFile_Release(
IDirectFBVideoProvider *thiz )
{
IDirectFBVideoProvider_AviFile_data *data;
if (!thiz)
return DFB_INVARG;
data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;
if (!data)
return DFB_DEAD;
if (--data->ref == 0) {
IDirectFBVideoProvider_AviFile_Destruct( thiz );
}
return DFB_OK;
}
static DFBResult IDirectFBVideoProvider_AviFile_GetSurfaceDescription(
IDirectFBVideoProvider *thiz,
DFBSurfaceDescription *desc )
{
IDirectFBVideoProvider_AviFile_data *data;
if (!thiz || !desc)
return DFB_INVARG;
data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;
if (!data)
return DFB_DEAD;
memset( desc, 0, sizeof(DFBSurfaceDescription) );
desc->flags = (DFBSurfaceDescriptionFlags)
(DSDESC_WIDTH | DSDESC_HEIGHT | DSDESC_BPP);
desc->width = data->player->Width();
desc->height = data->player->Height();
desc->bpp = BYTES_PER_PIXEL(layers->surface->format)*8;
return DFB_OK;
}
static DFBResult IDirectFBVideoProvider_AviFile_PlayTo(
IDirectFBVideoProvider *thiz,
IDirectFBSurface *destination,
DFBRectangle *dstrect,
DVFrameCallback callback,
void *ctx )
{
DFBRectangle rect;
IDirectFBVideoProvider_AviFile_data *data;
IDirectFBSurface_data *dst_data;
if (!thiz || !destination)
return DFB_INVARG;
data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;
dst_data = (IDirectFBSurface_data*)destination->priv;
if (!data || !dst_data)
return DFB_DEAD;
thiz->Stop( thiz );
/* build the destination rectangle */
if (dstrect) {
if (dstrect->w < 0 || dstrect->h < 0)
return DFB_INVARG;
rect = *dstrect;
rect.x += dst_data->req_rect.x;
rect.y += dst_data->req_rect.y;
}
else
rect = dst_data->req_rect;
/* save for later blitting operation */
data->dest_rect = rect;
/* build the clip rectangle */
if (!rectangle_intersect( &rect, &dst_data->clip_rect ))
return DFB_INVARG;
/* put the destination clip into the state */
data->state.clip.x1 = rect.x;
data->state.clip.y1 = rect.y;
data->state.clip.x2 = rect.x + rect.w - 1;
data->state.clip.y2 = rect.y + rect.h - 1;
data->state.destination = dst_data->surface;
data->state.modified = (StateModificationFlags)
(data->state.modified | SMF_CLIP | SMF_DESTINATION);
destination->AddRef( destination );
data->destination = destination; /* FIXME: install listener */
data->callback = callback;
data->ctx = ctx;
data->player->Start();
return DFB_OK;
}
static DFBResult IDirectFBVideoProvider_AviFile_Stop(
IDirectFBVideoProvider *thiz )
{
IDirectFBVideoProvider_AviFile_data *data;
if (!thiz)
return DFB_INVARG;
data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;
if (!data)
return DFB_DEAD;
if (data->player->IsPlaying())
data->player->Stop();
if (data->destination) {
data->destination->Release( data->destination );
data->destination = NULL; /* FIXME: remove listener */
}
return DFB_OK;
}
static DFBResult IDirectFBVideoProvider_AviFile_SeekTo(
IDirectFBVideoProvider *thiz,
double seconds )
{
IDirectFBVideoProvider_AviFile_data *data;
if (!thiz)
return DFB_INVARG;
data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;
if (!data)
return DFB_DEAD;
data->player->Reseek( seconds );
return DFB_OK;
}
static void AviFile_DrawCallback( const CImage *image, void *p )
{
IDirectFBVideoProvider_AviFile_data *data =
(IDirectFBVideoProvider_AviFile_data*)p;
data->source.front_buffer->system.addr = (void*)(image->Data());
data->source.front_buffer->system.pitch = image->Bpl();
DFBRectangle rect = { 0, 0, image->Width(), image->Height() };
if (rect.w == data->dest_rect.w && rect.h == data->dest_rect.h) {
gfxcard_blit( &rect, data->dest_rect.x,
data->dest_rect.y, &data->state );
}
else {
DFBRectangle drect = data->dest_rect;
gfxcard_stretchblit( &rect, &drect, &data->state );
}
if (data->callback)
data->callback( data->ctx );
}
/* exported symbols */
extern "C" {
const char *get_type()
{
return "IDirectFBVideoProvider";
}
const char *get_implementation()
{
return "AviFile";
}
DFBResult Probe( const char *filename )
{
if (strstr( filename, ".avi" ) ||
strstr( filename, ".AVI" ))
return DFB_OK;
return DFB_UNSUPPORTED;
}
DFBResult Construct( IDirectFBVideoProvider *thiz, const char *filename )
{
IDirectFBVideoProvider_AviFile_data *data;
data = (IDirectFBVideoProvider_AviFile_data*)
malloc( sizeof(IDirectFBVideoProvider_AviFile_data) );
memset( data, 0, sizeof(IDirectFBVideoProvider_AviFile_data) );
thiz->priv = data;
data->ref = 1;
try {
data->player = CreateAviPlayer( filename, 16 /* FIXME */ );
data->player->SetDrawCallback2( AviFile_DrawCallback, data );
}
catch (FatalError e) {
ERRORMSG( "DirectFB/AviFile: CreateAviPlayer failed: %s\n",
e.GetDesc() );
free( data );
return DFB_FAILURE;
}
#warning If the two lines below fail to compile change them to "GetWidth, GetHeight"
data->source.width = data->player->Width();
data->source.height = data->player->Height();
data->source.format = DSPF_RGB16;
data->source.front_buffer = (SurfaceBuffer*)malloc( sizeof(SurfaceBuffer) );
memset( data->source.front_buffer, 0, sizeof(SurfaceBuffer) );
data->source.front_buffer->policy = CSP_SYSTEMONLY;
data->source.front_buffer->system.health = CSH_STORED;
data->source.back_buffer = data->source.front_buffer;
pthread_mutex_init( &data->source.front_lock, NULL );
pthread_mutex_init( &data->source.back_lock, NULL );
pthread_mutex_init( &data->source.listeners_mutex, NULL );
data->state.source = &data->source;
data->state.modified = SMF_ALL;
thiz->AddRef = IDirectFBVideoProvider_AviFile_AddRef;
thiz->Release = IDirectFBVideoProvider_AviFile_Release;
thiz->GetSurfaceDescription =
IDirectFBVideoProvider_AviFile_GetSurfaceDescription;
thiz->PlayTo = IDirectFBVideoProvider_AviFile_PlayTo;
thiz->Stop = IDirectFBVideoProvider_AviFile_Stop;
thiz->SeekTo = IDirectFBVideoProvider_AviFile_SeekTo;
return DFB_OK;
}
}
<commit_msg>compiles with newest avifile version now<commit_after>/*
(c) Copyright 2000 convergence integrated media GmbH.
All rights reserved.
Written by Denis Oliver Kropp <dok@convergence.de> and
Andreas Hundt <andi@convergence.de>.
The contents of this software are proprietary and confidential to
convergence integrated media GmbH. Use of this information is
to be in accordance with the terms of the license agreement you
entered into with convergence integrated media GmbH. Individuals
having access to this software are responsible for maintaining the
confidentiality of the content and for keeping the software secure
when not in use. Transfer to any party is strictly forbidden other
than as expressly permitted in writing by convergence integrated
media GmbH. Unauthorized transfer to or possession by any
unauthorized party may be a criminal offense.
convergence integrated media GmbH MAKES NO WARRANTIES EITHER
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
OR NON-INFRINGEMENT.
convergence integrated media GmbH SHALL NOT BE LIABLE FOR ANY
DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
convergence integrated media GmbH
Rosenthaler Str.51
D-10178 Berlin / Germany
*/
extern "C" {
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <malloc.h>
#include <directfb.h>
#include <misc/util.h>
#include <core/core.h>
#include <core/coredefs.h>
#include <core/layers.h>
#include <core/gfxcard.h>
#include <display/idirectfbsurface.h>
}
#include <aviplay.h>
/*
* private data struct of IDirectFBVideoProvider
*/
typedef struct {
int ref; /* reference counter */
IAviPlayer *player;
IDirectFBSurface *destination;
DFBRectangle dest_rect;
DVFrameCallback callback;
void *ctx;
CardState state;
CoreSurface source;
} IDirectFBVideoProvider_AviFile_data;
static void IDirectFBVideoProvider_AviFile_Destruct(
IDirectFBVideoProvider *thiz )
{
IDirectFBVideoProvider_AviFile_data *data;
data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;
if (data->player->IsPlaying())
data->player->Stop();
free( thiz->priv );
thiz->priv = NULL;
}
static DFBResult IDirectFBVideoProvider_AviFile_AddRef(
IDirectFBVideoProvider *thiz )
{
IDirectFBVideoProvider_AviFile_data *data;
if (!thiz)
return DFB_INVARG;
data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;
if (!data)
return DFB_DEAD;
data->ref++;
return DFB_OK;
}
static DFBResult IDirectFBVideoProvider_AviFile_Release(
IDirectFBVideoProvider *thiz )
{
IDirectFBVideoProvider_AviFile_data *data;
if (!thiz)
return DFB_INVARG;
data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;
if (!data)
return DFB_DEAD;
if (--data->ref == 0) {
IDirectFBVideoProvider_AviFile_Destruct( thiz );
}
return DFB_OK;
}
static DFBResult IDirectFBVideoProvider_AviFile_GetSurfaceDescription(
IDirectFBVideoProvider *thiz,
DFBSurfaceDescription *desc )
{
IDirectFBVideoProvider_AviFile_data *data;
if (!thiz || !desc)
return DFB_INVARG;
data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;
if (!data)
return DFB_DEAD;
memset( desc, 0, sizeof(DFBSurfaceDescription) );
desc->flags = (DFBSurfaceDescriptionFlags)
(DSDESC_WIDTH | DSDESC_HEIGHT | DSDESC_BPP);
desc->width = data->player->GetWidth();
desc->height = data->player->GetHeight();
desc->bpp = BYTES_PER_PIXEL(layers->surface->format)*8;
return DFB_OK;
}
static DFBResult IDirectFBVideoProvider_AviFile_PlayTo(
IDirectFBVideoProvider *thiz,
IDirectFBSurface *destination,
DFBRectangle *dstrect,
DVFrameCallback callback,
void *ctx )
{
DFBRectangle rect;
IDirectFBVideoProvider_AviFile_data *data;
IDirectFBSurface_data *dst_data;
if (!thiz || !destination)
return DFB_INVARG;
data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;
dst_data = (IDirectFBSurface_data*)destination->priv;
if (!data || !dst_data)
return DFB_DEAD;
thiz->Stop( thiz );
/* build the destination rectangle */
if (dstrect) {
if (dstrect->w < 0 || dstrect->h < 0)
return DFB_INVARG;
rect = *dstrect;
rect.x += dst_data->req_rect.x;
rect.y += dst_data->req_rect.y;
}
else
rect = dst_data->req_rect;
/* save for later blitting operation */
data->dest_rect = rect;
/* build the clip rectangle */
if (!rectangle_intersect( &rect, &dst_data->clip_rect ))
return DFB_INVARG;
/* put the destination clip into the state */
data->state.clip.x1 = rect.x;
data->state.clip.y1 = rect.y;
data->state.clip.x2 = rect.x + rect.w - 1;
data->state.clip.y2 = rect.y + rect.h - 1;
data->state.destination = dst_data->surface;
data->state.modified = (StateModificationFlags)
(data->state.modified | SMF_CLIP | SMF_DESTINATION);
destination->AddRef( destination );
data->destination = destination; /* FIXME: install listener */
data->callback = callback;
data->ctx = ctx;
data->player->Start();
return DFB_OK;
}
static DFBResult IDirectFBVideoProvider_AviFile_Stop(
IDirectFBVideoProvider *thiz )
{
IDirectFBVideoProvider_AviFile_data *data;
if (!thiz)
return DFB_INVARG;
data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;
if (!data)
return DFB_DEAD;
if (data->player->IsPlaying())
data->player->Stop();
if (data->destination) {
data->destination->Release( data->destination );
data->destination = NULL; /* FIXME: remove listener */
}
return DFB_OK;
}
static DFBResult IDirectFBVideoProvider_AviFile_SeekTo(
IDirectFBVideoProvider *thiz,
double seconds )
{
IDirectFBVideoProvider_AviFile_data *data;
if (!thiz)
return DFB_INVARG;
data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;
if (!data)
return DFB_DEAD;
data->player->Reseek( seconds );
return DFB_OK;
}
static void AviFile_DrawCallback( const CImage *image, void *p )
{
IDirectFBVideoProvider_AviFile_data *data =
(IDirectFBVideoProvider_AviFile_data*)p;
data->source.front_buffer->system.addr = (void*)(image->Data());
data->source.front_buffer->system.pitch = image->Bpl();
DFBRectangle rect = { 0, 0, image->Width(), image->Height() };
if (rect.w == data->dest_rect.w && rect.h == data->dest_rect.h) {
gfxcard_blit( &rect, data->dest_rect.x,
data->dest_rect.y, &data->state );
}
else {
DFBRectangle drect = data->dest_rect;
gfxcard_stretchblit( &rect, &drect, &data->state );
}
if (data->callback)
data->callback( data->ctx );
}
/* exported symbols */
extern "C" {
const char *get_type()
{
return "IDirectFBVideoProvider";
}
const char *get_implementation()
{
return "AviFile";
}
DFBResult Probe( const char *filename )
{
if (strstr( filename, ".avi" ) ||
strstr( filename, ".AVI" ))
return DFB_OK;
return DFB_UNSUPPORTED;
}
DFBResult Construct( IDirectFBVideoProvider *thiz, const char *filename )
{
IDirectFBVideoProvider_AviFile_data *data;
data = (IDirectFBVideoProvider_AviFile_data*)
malloc( sizeof(IDirectFBVideoProvider_AviFile_data) );
memset( data, 0, sizeof(IDirectFBVideoProvider_AviFile_data) );
thiz->priv = data;
data->ref = 1;
try {
data->player = CreateAviPlayer( filename, 16 /* FIXME */ );
data->player->SetDrawCallback2( AviFile_DrawCallback, data );
}
catch (FatalError e) {
ERRORMSG( "DirectFB/AviFile: CreateAviPlayer failed: %s\n",
e.GetDesc() );
free( data );
return DFB_FAILURE;
}
data->source.width = data->player->GetWidth();
data->source.height = data->player->GetHeight();
data->source.format = DSPF_RGB16;
data->source.front_buffer = (SurfaceBuffer*)malloc( sizeof(SurfaceBuffer) );
memset( data->source.front_buffer, 0, sizeof(SurfaceBuffer) );
data->source.front_buffer->policy = CSP_SYSTEMONLY;
data->source.front_buffer->system.health = CSH_STORED;
data->source.back_buffer = data->source.front_buffer;
pthread_mutex_init( &data->source.front_lock, NULL );
pthread_mutex_init( &data->source.back_lock, NULL );
pthread_mutex_init( &data->source.listeners_mutex, NULL );
data->state.source = &data->source;
data->state.modified = SMF_ALL;
thiz->AddRef = IDirectFBVideoProvider_AviFile_AddRef;
thiz->Release = IDirectFBVideoProvider_AviFile_Release;
thiz->GetSurfaceDescription =
IDirectFBVideoProvider_AviFile_GetSurfaceDescription;
thiz->PlayTo = IDirectFBVideoProvider_AviFile_PlayTo;
thiz->Stop = IDirectFBVideoProvider_AviFile_Stop;
thiz->SeekTo = IDirectFBVideoProvider_AviFile_SeekTo;
return DFB_OK;
}
}
<|endoftext|> |
<commit_before>#include<iostream>
#include<fstream>
#include<cstdlib>
#include<cstring>
#include<string>
#include<ctime>
using namespace std;
int main()
{
time_t timer;
tm *t;
int is_done = 0;
timer = time(NULL);
t = localtime(&timer);
if((t->tm_hour > 7) && ((t->tm_hour < 16)||((t->tm_hour==16) && (t->tm_min < 30)))){
goto python;
}
while(1){
while(1){ // 8 5п ڽ û
timer = time(NULL);
t = localtime(&timer);
if(t->tm_min == 6){
is_done = 0;
}
if(is_done == 0 && (t->tm_hour == 8 && t->tm_min == 1)){
is_done = 1;
goto python;
}
}
python:;
ifstream in("info.txt");
string id, pw;
int _1, _2, _3;
if(!in.is_open()){
cout << "No Input.txt!" << endl;
continue;
}
in >> id >> pw >> _1 >> _2 >> _3;
in.close();
char cmd[100];
sprintf(cmd, "python _FILE_ 2017%s %s %d %d %d", id.c_str(), pw.c_str(), _1, _2, _3);
is_done = 1;
system(cmd);
}
return 0;
}
<commit_msg>Delete loop.cpp<commit_after><|endoftext|> |
<commit_before>// (C) 2014 Arek Olek
#include <unordered_map>
#include <boost/graph/adjacency_matrix.hpp>
#include "debug.hpp"
namespace detail {
boost::adjacency_matrix<boost::undirectedS> typedef graph;
template <class Input, class Output>
void copy_edges(const Input& in, Output& out) {
auto es = edges(in);
for(auto e = es.first; e != es.second; ++e)
add_edge(source(*e, in), target(*e, in), out);
}
}
template <class Graph>
class leaf_info {
public:
leaf_info(Graph const & T_) : T(T_) {
update();
}
bool is_path() const {
return L.size() == 2;
}
std::vector<unsigned> const & leaves() const {
return L;
}
unsigned branching(unsigned x) const {
return B.at(x);
}
unsigned branching_neighbor(unsigned x) const {
return N.at(x);
}
void update() {
L.clear();
B.clear();
N.clear();
auto vs = vertices(T);
for(auto vit = vs.first; vit != vs.second; ++vit)
if(degree(*vit, T) == 1) {
unsigned l = *vit;
L.push_back(l);
unsigned p = l;
unsigned x = *adjacent_vertices(l, T).first;
while(degree(x, T) == 2)
std::tie(p, x) = next(p, x, T);
if(degree(x, T) > 2) {
B[l] = x;
N[l] = p;
}
}
}
std::pair<unsigned, unsigned> next(unsigned a, unsigned b, Graph const & T) {
auto it = adjacent_vertices(b, T).first;
return make_pair(b, a == *it ? *(++it) : *it);
}
private:
Graph const& T;
std::vector<unsigned> L;
std::unordered_map<unsigned, unsigned> B, N;
};
template <class Graph>
Graph prieto(Graph& G) {
//detail::graph M(num_vertices(G));
//detail::copy_edges(G, M);
auto T = dfs_tree(G);
leaf_info<Graph> info(T);
//int i = 0;
do {
//show("tree" + std::to_string(i++) + ".dot", M, T);
} while(!info.is_path() && rule2(G, T, info));
return T;
}
template <class Graph, class Tree, class LeafInfo>
bool rule2(Graph& G, Tree& T, LeafInfo& info) {
for(auto x : info.leaves())
for(auto y : info.leaves())
if(edge(x, y, G).second) {
add_edge(x, y, T);
remove_edge(info.branching(x), info.branching_neighbor(x), T);
info.update();
return true;
}
return false;
}
<commit_msg>refactor to prepare for next rules<commit_after>// (C) 2014 Arek Olek
#include <unordered_map>
#include <boost/functional/hash.hpp>
#include <boost/graph/adjacency_matrix.hpp>
#include "debug.hpp"
namespace detail {
boost::adjacency_matrix<boost::undirectedS> typedef graph;
template <class Input, class Output>
void copy_edges(const Input& in, Output& out) {
auto es = edges(in);
for(auto e = es.first; e != es.second; ++e)
add_edge(source(*e, in), target(*e, in), out);
}
}
namespace std {
template<typename S, typename T>
struct hash<pair<S, T>> {
inline size_t operator()(const pair<S, T> & v) const {
size_t seed = 0;
boost::hash_combine(seed, v.first);
boost::hash_combine(seed, v.second);
return seed;
}
};
}
template <class Graph>
class leaf_info {
public:
leaf_info(Graph const & T_) : T(T_) {
update();
}
bool is_path() const {
return L.size() == 2;
}
std::vector<unsigned> const & leaves() const {
return L;
}
unsigned branching(unsigned l) const {
return B.at(l);
}
unsigned parent(unsigned x, unsigned l) const {
return P.at(uintpair(l, x));
}
void update() {
L.clear();
B.clear();
P.clear();
auto vs = vertices(T);
for(auto vit = vs.first; vit != vs.second; ++vit)
if(degree(*vit, T) == 1) {
L.push_back(*vit);
traverse(*vit, T);
}
}
void traverse(unsigned l, Graph const & T) {
traverse(l, l, l, T);
}
void traverse(unsigned l, unsigned a, unsigned b, Graph const & T) {
do {
std::tie(a, b) = next(a, b, T);
P[uintpair(l, b)] = a;
} while(degree(b, T) == 2);
if(degree(b, T) > 2) {
B[l] = b;
}
}
std::pair<unsigned, unsigned> next(unsigned a, unsigned b, Graph const & T) {
auto it = adjacent_vertices(b, T).first;
return make_pair(b, a == *it ? *(++it) : *it);
}
private:
Graph const& T;
std::vector<unsigned> L;
std::pair<unsigned, unsigned> typedef uintpair;
std::unordered_map<unsigned, unsigned> B;
std::unordered_map<uintpair, unsigned> P;
};
template <class Graph>
Graph prieto(Graph& G) {
//detail::graph M(num_vertices(G));
//detail::copy_edges(G, M);
auto T = dfs_tree(G);
leaf_info<Graph> info(T);
//int i = 0;
do {
//show("tree" + std::to_string(i++) + ".dot", M, T);
} while(!info.is_path() && rule2(G, T, info));
return T;
}
template <class Graph, class Tree, class LeafInfo>
bool rule2(Graph& G, Tree& T, LeafInfo& info) {
for(auto l1 : info.leaves())
for(auto l2 : info.leaves())
if(edge(l1, l2, G).second) {
add_edge(l1, l2, T);
auto b = info.branching(l1);
remove_edge(b, info.parent(b, l1), T);
info.update();
return true;
}
return false;
}
<|endoftext|> |
<commit_before>// (C) 2014 Arek Olek
#include <functional>
#include <unordered_map>
#include <boost/functional/hash.hpp>
#include <boost/graph/adjacency_matrix.hpp>
#include "debug.hpp"
namespace detail {
boost::adjacency_matrix<boost::undirectedS> typedef graph;
template <class Input, class Output>
void copy_edges(const Input& in, Output& out) {
auto es = edges(in);
for(auto e = es.first; e != es.second; ++e)
add_edge(source(*e, in), target(*e, in), out);
}
}
namespace std {
template<typename S, typename T>
struct hash<pair<S, T>> {
inline size_t operator()(const pair<S, T> & v) const {
size_t seed = 0;
boost::hash_combine(seed, v.first);
boost::hash_combine(seed, v.second);
return seed;
}
};
}
template <class Graph>
class leaf_info {
public:
leaf_info(Graph const & T_) : T(T_) {
update();
}
bool is_path() const {
return L.size() == 2;
}
std::vector<unsigned> const & leaves() const {
return L;
}
unsigned branching(unsigned l) const {
return B.at(l);
}
unsigned parent(unsigned x, unsigned l) const {
return P.at(uintpair(l, x));
}
void update() {
L.clear();
B.clear();
P.clear();
auto vs = vertices(T);
for(auto vit = vs.first; vit != vs.second; ++vit)
if(degree(*vit, T) == 1) {
L.push_back(*vit);
traverse(*vit, T);
}
}
void traverse(unsigned l, Graph const & T) {
traverse(l, l, next(l, l, T).second, T);
}
void traverse(unsigned l, unsigned a, unsigned b, Graph const & T) {
P[uintpair(l, b)] = a;
while(degree(b, T) == 2) {
std::tie(a, b) = next(a, b, T);
P[uintpair(l, b)] = a;
}
if(degree(b, T) > 2) {
if(B.count(l) == 0)
B[l] = b;
auto vs = adjacent_vertices(b, T);
for(auto v = vs.first; v != vs.second; ++v)
if(*v != a)
traverse(l, b, *v, T);
}
}
std::pair<unsigned, unsigned> next(unsigned a, unsigned b, Graph const & T) {
auto it = adjacent_vertices(b, T).first;
return make_pair(b, a == *it ? *(++it) : *it);
}
private:
Graph const& T;
std::vector<unsigned> L;
std::pair<unsigned, unsigned> typedef uintpair;
std::unordered_map<unsigned, unsigned> B;
std::unordered_map<uintpair, unsigned> P;
};
template <class Graph>
Graph prieto(Graph& G) {
//detail::graph M(num_vertices(G));
//detail::copy_edges(G, M);
auto T = dfs_tree(G);
leaf_info<Graph> info(T);
//int i = 0;
do {
//show("tree" + std::to_string(i++) + ".dot", M, T);
} while(!info.is_path() && rule2(G, T, info));
return T;
}
template <class Graph, class Tree, class LeafInfo>
bool rule2(Graph& G, Tree& T, LeafInfo& info) {
for(auto l1 : info.leaves())
for(auto l2 : info.leaves())
if(edge(l1, l2, G).second) {
add_edge(l1, l2, T);
auto b = info.branching(l1);
remove_edge(b, info.parent(b, l1), T);
info.update();
return true;
}
return false;
}
template <class Graph>
Graph lost_light(Graph& G) {
auto T = dfs_tree(G);
leaf_info<Graph> info(T);
std::function<bool(Graph&,Graph&,leaf_info<Graph>&)> typedef rule;
std::vector<rule> rules {rule2<Graph,Graph,leaf_info<Graph>>};
bool applied = true;
while(applied && !info.is_path()) {
applied = false;
for(auto rule : rules) {
if(rule(G, T, info)) {
applied = true;
break;
}
}
}
return T;
}
<commit_msg>add rule no 3<commit_after>// (C) 2014 Arek Olek
#include <functional>
#include <unordered_map>
#include <boost/functional/hash.hpp>
#include <boost/graph/adjacency_matrix.hpp>
#include "debug.hpp"
namespace detail {
boost::adjacency_matrix<boost::undirectedS> typedef graph;
template <class Input, class Output>
void copy_edges(const Input& in, Output& out) {
auto es = edges(in);
for(auto e = es.first; e != es.second; ++e)
add_edge(source(*e, in), target(*e, in), out);
}
}
namespace std {
template<typename S, typename T>
struct hash<pair<S, T>> {
inline size_t operator()(const pair<S, T> & v) const {
size_t seed = 0;
boost::hash_combine(seed, v.first);
boost::hash_combine(seed, v.second);
return seed;
}
};
}
template <class Graph>
class leaf_info {
public:
leaf_info(Graph const & T_) : T(T_) {
update();
}
bool is_path() const {
return L.size() == 2;
}
std::vector<unsigned> const & leaves() const {
return L;
}
unsigned branching(unsigned l) const {
return B.at(l);
}
unsigned parent(unsigned x, unsigned l) const {
return P.at(uintpair(l, x));
}
void update() {
L.clear();
B.clear();
P.clear();
auto vs = vertices(T);
for(auto vit = vs.first; vit != vs.second; ++vit)
if(degree(*vit, T) == 1) {
L.push_back(*vit);
traverse(*vit, T);
}
}
void traverse(unsigned l, Graph const & T) {
traverse(l, l, next(l, l, T).second, T);
}
void traverse(unsigned l, unsigned a, unsigned b, Graph const & T) {
P[uintpair(l, b)] = a;
while(degree(b, T) == 2) {
std::tie(a, b) = next(a, b, T);
P[uintpair(l, b)] = a;
}
if(degree(b, T) > 2) {
if(B.count(l) == 0)
B[l] = b;
auto vs = adjacent_vertices(b, T);
for(auto v = vs.first; v != vs.second; ++v)
if(*v != a)
traverse(l, b, *v, T);
}
}
std::pair<unsigned, unsigned> next(unsigned a, unsigned b, Graph const & T) {
auto it = adjacent_vertices(b, T).first;
return make_pair(b, a == *it ? *(++it) : *it);
}
private:
Graph const& T;
std::vector<unsigned> L;
std::pair<unsigned, unsigned> typedef uintpair;
std::unordered_map<unsigned, unsigned> B;
std::unordered_map<uintpair, unsigned> P;
};
template <class Graph>
Graph prieto(Graph& G) {
//detail::graph M(num_vertices(G));
//detail::copy_edges(G, M);
auto T = dfs_tree(G);
leaf_info<Graph> info(T);
//int i = 0;
do {
//show("tree" + std::to_string(i++) + ".dot", M, T);
} while(!info.is_path() && rule2(G, T, info));
return T;
}
template <class Graph, class Tree, class LeafInfo>
bool rule2(Graph& G, Tree& T, LeafInfo& info) {
for(auto l1 : info.leaves())
for(auto l2 : info.leaves())
if(edge(l1, l2, G).second) {
add_edge(l1, l2, T);
auto b = info.branching(l1);
remove_edge(b, info.parent(b, l1), T);
info.update();
return true;
}
return false;
}
template <class Graph, class Tree, class LeafInfo>
bool rule3(Graph& G, Tree& T, LeafInfo& info) {
for(auto l : info.leaves()) {
auto treeNeighbor = *adjacent_vertices(l, T).first;
auto vs = adjacent_vertices(l, G);
for(auto x = vs.first; x != vs.second; ++x)
if(*x != treeNeighbor) {
auto xl = info.parent(*x, l);
if(degree(xl, T) > 2) {
add_edge(l, *x, T);
remove_edge(*x, xl, T);
info.update();
return true;
}
}
}
return false;
}
template <class Graph>
Graph lost_light(Graph& G) {
auto T = dfs_tree(G);
leaf_info<Graph> info(T);
std::function<bool(Graph&,Graph&,leaf_info<Graph>&)> typedef rule;
std::vector<rule> rules {
rule2<Graph,Graph,leaf_info<Graph>>,
rule3<Graph,Graph,leaf_info<Graph>>,
};
bool applied = true;
while(applied && !info.is_path()) {
applied = false;
for(auto rule : rules) {
if(rule(G, T, info)) {
applied = true;
break;
}
}
}
return T;
}
<|endoftext|> |
<commit_before>#include <node.h>
#include <v8.h>
#include <unistd.h>
#include <string.h>
#include <string>
#include <cstring>
using namespace v8;
char* ValueToChar(Handle<Value> val) {
String::Utf8Value s(val->ToString());
return (char*)std::string(*s, s.length()).data();
}
char** Params(const Arguments& args) {
char **results = new char*[args.Length()+1];
for (int i = 0; i < args.Length(); i++) {
char *arg = ValueToChar(args[i]);
results[i]=arg;
}
results[args.Length()] = NULL;
return results;
}
Handle<Value> sexec(const Arguments& args) {
HandleScope scope;
int stdoutPipeFD[2];
int stderrPipeFD[2];
if (pipe(stdoutPipeFD) == -1 || pipe(stderrPipeFD) == -1) {
return ThrowException(String::New("Pipe not created"));
}
if (fork() == 0) {
char **params = Params(args);
close(stdoutPipeFD[0]);
close(stderrPipeFD[0]);
dup2(stdoutPipeFD[1], 1);
dup2(stderrPipeFD[1], 2);
close(stdoutPipeFD[1]);
close(stderrPipeFD[1]);
execvp(params[0], params);
} else {
char buff[1024];
Local<String> stdout = String::Empty();
Local<String> stderr = String::Empty();
Local<Object> ret = Object::New();
int readed = 0;
ret->Set(
String::NewSymbol("target"),
args[0]
);
close(stdoutPipeFD[1]);
close(stderrPipeFD[1]);
while ((readed = read(stdoutPipeFD[0], buff, sizeof(buff))) != 0) {
stdout = String::Concat(stdout, String::New(buff, readed));
}
ret->Set(
String::NewSymbol("out"),
stdout
);
while ((readed = read(stderrPipeFD[0], buff, sizeof(buff))) != 0) {
stdout = String::Concat(stderr, String::New(buff, readed));
}
ret->Set(
String::NewSymbol("err"),
stderr
);
return scope.Close(ret);
}
return scope.Close(String::New("null"));
}
void init(Handle<Object> target) {
target->Set(String::New("exec"), FunctionTemplate::New(sexec)->GetFunction());
}
NODE_MODULE(pse, init);
<commit_msg>[fix] Linux support.<commit_after>#include <node.h>
#include <v8.h>
#include <unistd.h>
#include <string.h>
#include <string>
#include <cstring>
using namespace v8;
Handle<Value> sexec(const Arguments& args) {
HandleScope scope;
int stdoutPipeFD[2];
int stderrPipeFD[2];
char **arguments = new char*[args.Length()+1];
if (pipe(stdoutPipeFD) == -1 || pipe(stderrPipeFD) == -1) {
return ThrowException(String::New("Pipe not created"));
}
for (int i = 0; i < args.Length(); i++) {
String::Utf8Value* s = new String::Utf8Value(args[i]->ToString());
arguments[i] = new char[s->length()];
strcpy(arguments[i], **s);
delete s;
}
arguments[args.Length()] = NULL;
if (fork() == 0) {
close(stdoutPipeFD[0]);
close(stderrPipeFD[0]);
dup2(stdoutPipeFD[1], 1);
dup2(stderrPipeFD[1], 2);
close(stdoutPipeFD[1]);
close(stderrPipeFD[1]);
execvp(arguments[0], arguments);
} else {
char buff[1024];
Local<String> stdout = String::Empty();
Local<String> stderr = String::Empty();
Local<Object> ret = Object::New();
int readed = 0;
ret->Set(
String::NewSymbol("target"),
String::New(arguments[0])
);
close(stdoutPipeFD[1]);
close(stderrPipeFD[1]);
while ((readed = read(stdoutPipeFD[0], buff, sizeof(buff))) != 0) {
stdout = String::Concat(stdout, String::New(buff, readed));
}
ret->Set(
String::NewSymbol("out"),
stdout
);
while ((readed = read(stderrPipeFD[0], buff, sizeof(buff))) != 0) {
stdout = String::Concat(stderr, String::New(buff, readed));
}
ret->Set(
String::NewSymbol("err"),
stderr
);
return scope.Close(ret);
}
return scope.Close(String::New("null"));
}
void init(Handle<Object> target) {
target->Set(String::New("exec"), FunctionTemplate::New(sexec)->GetFunction());
}
NODE_MODULE(pse, init);
<|endoftext|> |
<commit_before>/*
Copyright 2013,2014 Marko Dimjašević, Simone Atzeni, Ivo Ugrina, Zvonimir Rakamarić
This file is part of maline.
maline 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.
maline 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 maline. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <sstream>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/lexical_cast.hpp>
using namespace boost::algorithm;
int main(int argc, char **argv)
{
int N, ratio;
int mSize, mTrainingSize, mTestingSize;
int gSize, gTrainingSize, gTestingSize;
std::string line;
if(argc < 2) {
printf("Usage: %s FILENAME RATIO\n", argv[0]);
exit(-1);
}
std::istringstream buffer(argv[2]);
buffer >> ratio;
std::string filename1(argv[1]);
std::stringstream s1;
s1 << ratio;
filename1.append(".training." + s1.str());
std::ofstream training_file(filename1.c_str());
if(!training_file.is_open()) {
std::cerr << "Couldn't open " << filename1 << std::endl;
exit(-1);
}
std::string filename2(argv[1]);
std::stringstream s2;
s2 << ratio;
filename2.append(".testing." + s2.str());
std::ofstream testing_file(filename2.c_str());
if(!testing_file.is_open()) {
std::cerr << "Couldn't open " << filename2 << std::endl;
exit(-1);
}
std::ifstream file(argv[1], std::ios_base::in);
boost::iostreams::filtering_istream in1;
in1.push(file);
mSize=0;
gSize=0;
for(; std::getline(in1, line); ) {
//std::cout << "Processed line " << line.size() << "\n";
if (boost::starts_with(line, "+1"))
gSize++;
else
mSize++;
}
gTrainingSize = (ratio * gSize) / 100;
gTestingSize = gSize - gTrainingSize;
mTrainingSize = (ratio * mSize) / 100;
mTestingSize = mSize - mTrainingSize;
printf("# Apps | goodware | malware | total\n);"
printf("Total | %d | %d | %d\n", gSize, mSize, gSize + mSize);
printf("Training | %d | %d | %d\n", gTrainingSize, mTrainingSize, gTrainingSize + mTrainingSize);
printf("Testing | %d | %d | %d\n", gTestingSize, mTrainingSize, gTestingSize + mTestingSize);
std::ifstream file2(argv[1], std::ios_base::in);
boost::iostreams::filtering_istream in2;
in2.push(file2);
int i = 0;
for(; std::getline(in2, line); ) {
if(i < gTrainingSize) {
training_file << line << "\n";
} else if(i < gSize) {
testing_file << line << "\n";
} else if(i < gSize + mTrainingSize) {
training_file << line << "\n";
} else {
testing_file << line << "\n";
}
i++;
}
training_file.close();
testing_file.close();
return 0;
}
<commit_msg>Parallelized script for SVM algorithm<commit_after>/*
Copyright 2013,2014 Marko Dimjašević, Simone Atzeni, Ivo Ugrina, Zvonimir Rakamarić
This file is part of maline.
maline 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.
maline 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 maline. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <sstream>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/lexical_cast.hpp>
using namespace boost::algorithm;
int main(int argc, char **argv)
{
int N, ratio;
int mSize, mTrainingSize, mTestingSize;
int gSize, gTrainingSize, gTestingSize;
std::string line;
if(argc < 2) {
printf("Usage: %s FILENAME RATIO\n", argv[0]);
exit(-1);
}
std::istringstream buffer(argv[2]);
buffer >> ratio;
std::string filename1(argv[1]);
std::stringstream s1;
s1 << ratio;
filename1.append(".training." + s1.str());
std::ofstream training_file(filename1.c_str());
if(!training_file.is_open()) {
std::cerr << "Couldn't open " << filename1 << std::endl;
exit(-1);
}
std::string filename2(argv[1]);
std::stringstream s2;
s2 << ratio;
filename2.append(".testing." + s2.str());
std::ofstream testing_file(filename2.c_str());
if(!testing_file.is_open()) {
std::cerr << "Couldn't open " << filename2 << std::endl;
exit(-1);
}
std::ifstream file(argv[1], std::ios_base::in);
boost::iostreams::filtering_istream in1;
in1.push(file);
mSize=0;
gSize=0;
for(; std::getline(in1, line); ) {
//std::cout << "Processed line " << line.size() << "\n";
if (boost::starts_with(line, "+1"))
gSize++;
else
mSize++;
}
gTrainingSize = (ratio * gSize) / 100;
gTestingSize = gSize - gTrainingSize;
mTrainingSize = (ratio * mSize) / 100;
mTestingSize = mSize - mTrainingSize;
printf("# Apps | goodware | malware | total\n");
printf("Total | %d | %d | %d\n", gSize, mSize, gSize + mSize);
printf("Training | %d | %d | %d\n", gTrainingSize, mTrainingSize, gTrainingSize + mTrainingSize);
printf("Testing | %d | %d | %d\n", gTestingSize, mTrainingSize, gTestingSize + mTestingSize);
std::ifstream file2(argv[1], std::ios_base::in);
boost::iostreams::filtering_istream in2;
in2.push(file2);
int i = 0;
for(; std::getline(in2, line); ) {
if(i < gTrainingSize) {
training_file << line << "\n";
} else if(i < gSize) {
testing_file << line << "\n";
} else if(i < gSize + mTrainingSize) {
training_file << line << "\n";
} else {
testing_file << line << "\n";
}
i++;
}
training_file.close();
testing_file.close();
return 0;
}
<|endoftext|> |
<commit_before>#include <cstdlib>
#include <iostream>
#include "mipp_scalar_op.h"
template <typename T> T mipp_scop::andb(const T val1, const T val2) { return val1 & val2; }
template < > float mipp_scop::andb(const float val1, const float val2) { return float(int(val1) & int(val2)); }
template < > double mipp_scop::andb(const double val1, const double val2) { return double(long long(val1) & long long(val2)); }
template <typename T> T mipp_scop::xorb(const T val1, const T val2) { return val1 ^ val2; }
template < > float mipp_scop::xorb(const float val1, const float val2) { return float(int(val1) ^ int(val2)); }
template < > double mipp_scop::xorb(const double val1, const double val2) { return double(long long(val1) ^ long long(val2)); }
template <typename T> T mipp_scop::div2(const T val) { return val * (T)0.5; }
template < > int mipp_scop::div2(const int val) { return val >> 1; }
template < > short mipp_scop::div2(const short val) { return val >> 1; }
template < > signed char mipp_scop::div2(const signed char val) { return val >> 1; }
template <typename T> T mipp_scop::div4(const T val) { return val * (T)0.25; }
template < > int mipp_scop::div4(const int val) { return val >> 2; }
template < > short mipp_scop::div4(const short val) { return val >> 2; }
template < > signed char mipp_scop::div4(const signed char val) { return val >> 2; }
template <typename T> T mipp_scop::lshift(const T val, const int n) { return val << n; }
template < > double mipp_scop::lshift(const double val, const int n) { return double(unsigned long long(val) << n); }
template < > float mipp_scop::lshift(const float val, const int n) { return float(unsigned(val) << n); }
template < > long long mipp_scop::lshift(const long long val, const int n) { return long long(unsigned long long(val) << n); }
template < > int mipp_scop::lshift(const int val, const int n) { return int(unsigned(val) << n); }
template < > short mipp_scop::lshift(const short val, const int n) { return short(unsigned short(val) << n); }
template < > signed char mipp_scop::lshift(const signed char val, const int n) { return signed char(unsigned char(val) << n); }
template <typename T> T mipp_scop::rshift(const T val, const int n) { return val >> n; }
template < > double mipp_scop::rshift(const double val, const int n) { return double(unsigned long long(val) >> n); }
template < > float mipp_scop::rshift(const float val, const int n) { return float(unsigned(val) >> n); }
template < > long long mipp_scop::rshift(const long long val, const int n) { return long long(unsigned long long(val) >> n); }
template < > int mipp_scop::rshift(const int val, const int n) { return int(unsigned(val) >> n); }
template < > short mipp_scop::rshift(const short val, const int n) { return short(unsigned short(val) >> n); }
template < > signed char mipp_scop::rshift(const signed char val, const int n) { return signed char(unsigned char(val) >> n); }
// ==================================================================================== explicit template instantiation
template double mipp_scop::andb(const double , const double );
template float mipp_scop::andb(const float , const float );
template long long mipp_scop::andb(const long long , const long long );
template int mipp_scop::andb(const int , const int );
template short mipp_scop::andb(const short , const short );
template signed char mipp_scop::andb(const signed char, const signed char);
template double mipp_scop::xorb(const double , const double );
template float mipp_scop::xorb(const float , const float );
template long long mipp_scop::xorb(const long long , const long long );
template int mipp_scop::xorb(const int , const int );
template short mipp_scop::xorb(const short , const short );
template signed char mipp_scop::xorb(const signed char, const signed char);
template double mipp_scop::div2(const double );
template float mipp_scop::div2(const float );
template long long mipp_scop::div2(const long long );
template int mipp_scop::div2(const int );
template short mipp_scop::div2(const short );
template signed char mipp_scop::div2(const signed char);
template double mipp_scop::div4(const double );
template float mipp_scop::div4(const float );
template long long mipp_scop::div4(const long long );
template int mipp_scop::div4(const int );
template short mipp_scop::div4(const short );
template signed char mipp_scop::div4(const signed char);
template double mipp_scop::lshift(const double , const int);
template float mipp_scop::lshift(const float , const int);
template long long mipp_scop::lshift(const long long , const int);
template int mipp_scop::lshift(const int , const int);
template short mipp_scop::lshift(const short , const int);
template signed char mipp_scop::lshift(const signed char, const int);
template double mipp_scop::rshift(const double , const int);
template float mipp_scop::rshift(const float , const int);
template long long mipp_scop::rshift(const long long , const int);
template int mipp_scop::rshift(const int , const int);
template short mipp_scop::rshift(const short , const int);
template signed char mipp_scop::rshift(const signed char, const int);
// ==================================================================================== explicit template instantiation<commit_msg>Fix compilation errors on gcc.<commit_after>#include <cstdlib>
#include <iostream>
#include "mipp_scalar_op.h"
namespace mipp_scop
{
template <typename T> T andb(const T val1, const T val2) { return val1 & val2; }
template < > float andb(const float val1, const float val2) { return static_cast<float >(static_cast<int >(val1) & static_cast<int >(val2)); }
template < > double andb(const double val1, const double val2) { return static_cast<double>(static_cast<long long>(val1) & static_cast<long long>(val2)); }
template <typename T> T xorb(const T val1, const T val2) { return val1 ^ val2; }
template < > float xorb(const float val1, const float val2) { return static_cast<float >(static_cast<int >(val1) ^ static_cast<int >(val2)); }
template < > double xorb(const double val1, const double val2) { return static_cast<double>(static_cast<long long>(val1) ^ static_cast<long long>(val2)); }
template <typename T> T div2(const T val) { return val * (T)0.5; }
template < > int div2(const int val) { return val >> 1; }
template < > short div2(const short val) { return val >> 1; }
template < > signed char div2(const signed char val) { return val >> 1; }
template <typename T> T div4(const T val) { return val * (T)0.25; }
template < > int div4(const int val) { return val >> 2; }
template < > short div4(const short val) { return val >> 2; }
template < > signed char div4(const signed char val) { return val >> 2; }
template <typename T> T lshift(const T val, const int n) { return val << n; }
template < > double lshift(const double val, const int n) { return static_cast<double >(static_cast<unsigned long long>(val) << n); }
template < > float lshift(const float val, const int n) { return static_cast<float >(static_cast<unsigned >(val) << n); }
template < > long long lshift(const long long val, const int n) { return static_cast<long long >(static_cast<unsigned long long>(val) << n); }
template < > int lshift(const int val, const int n) { return static_cast<int >(static_cast<unsigned >(val) << n); }
template < > short lshift(const short val, const int n) { return static_cast<short >(static_cast<unsigned short >(val) << n); }
template < > signed char lshift(const signed char val, const int n) { return static_cast<signed char>(static_cast<unsigned char >(val) << n); }
template <typename T> T rshift(const T val, const int n) { return val >> n; }
template < > double rshift(const double val, const int n) { return static_cast<double >(static_cast<unsigned long long>(val) >> n); }
template < > float rshift(const float val, const int n) { return static_cast<float >(static_cast<unsigned >(val) >> n); }
template < > long long rshift(const long long val, const int n) { return static_cast<long long >(static_cast<unsigned long long>(val) >> n); }
template < > int rshift(const int val, const int n) { return static_cast<int >(static_cast<unsigned >(val) >> n); }
template < > short rshift(const short val, const int n) { return static_cast<short >(static_cast<unsigned short >(val) >> n); }
template < > signed char rshift(const signed char val, const int n) { return static_cast<signed char>(static_cast<unsigned char >(val) >> n); }
}
// ==================================================================================== explicit template instantiation
template double mipp_scop::andb(const double , const double );
template float mipp_scop::andb(const float , const float );
template long long mipp_scop::andb(const long long , const long long );
template int mipp_scop::andb(const int , const int );
template short mipp_scop::andb(const short , const short );
template signed char mipp_scop::andb(const signed char, const signed char);
template double mipp_scop::xorb(const double , const double );
template float mipp_scop::xorb(const float , const float );
template long long mipp_scop::xorb(const long long , const long long );
template int mipp_scop::xorb(const int , const int );
template short mipp_scop::xorb(const short , const short );
template signed char mipp_scop::xorb(const signed char, const signed char);
template double mipp_scop::div2(const double );
template float mipp_scop::div2(const float );
template long long mipp_scop::div2(const long long );
template int mipp_scop::div2(const int );
template short mipp_scop::div2(const short );
template signed char mipp_scop::div2(const signed char);
template double mipp_scop::div4(const double );
template float mipp_scop::div4(const float );
template long long mipp_scop::div4(const long long );
template int mipp_scop::div4(const int );
template short mipp_scop::div4(const short );
template signed char mipp_scop::div4(const signed char);
template double mipp_scop::lshift(const double , const int);
template float mipp_scop::lshift(const float , const int);
template long long mipp_scop::lshift(const long long , const int);
template int mipp_scop::lshift(const int , const int);
template short mipp_scop::lshift(const short , const int);
template signed char mipp_scop::lshift(const signed char, const int);
template double mipp_scop::rshift(const double , const int);
template float mipp_scop::rshift(const float , const int);
template long long mipp_scop::rshift(const long long , const int);
template int mipp_scop::rshift(const int , const int);
template short mipp_scop::rshift(const short , const int);
template signed char mipp_scop::rshift(const signed char, const int);
// ==================================================================================== explicit template instantiation
<|endoftext|> |
<commit_before><commit_msg>SampleApp: fixed initialization of m_pEngineFactory in Metal mode<commit_after><|endoftext|> |
<commit_before>7e791939-2d15-11e5-af21-0401358ea401<commit_msg>7e79193a-2d15-11e5-af21-0401358ea401<commit_after>7e79193a-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>
#include <vector>
#include <fstream>
#include <ctime>
#include "Map.h"
#include "Zombie.h"
#include "Player.h"
#include "Plant.h"
using namespace std;
bool allZombiesDie(const Zombie * zombie, size_t num);
int main()
{
//game start
cout << " -----------------------------" << endl
<< "| Plants v.s Zombies |" << endl
<< " -----------------------------" << endl;
constexpr int LAND_DEFAULT=8;
constexpr int LAND_MAX=10;
constexpr int LAND_MIN=1;
constexpr int ZOMBIE_DEFAULT=3;
constexpr int ZOMBIE_MAX=10;
constexpr int ZOMBIE_MIN=1;
string input;
//initialize game setting
cout << "Number of lands on the map (" << LAND_MIN << "-" << LAND_MAX << ", default: " << LAND_DEFAULT <<")...>";
int value = LAND_DEFAULT;
getline(cin, input);
if(!input.empty())
{
istringstream stream( input );
stream >> value;
if(value > LAND_MAX) value = LAND_MAX;
if(value < LAND_MIN) value = LAND_MIN;
}
const int LANDS=value;
cout << "Number of zombies on the map (" << ZOMBIE_MIN << "-" << ZOMBIE_MAX << ", default: "<< ZOMBIE_DEFAULT <<")...>";
value=ZOMBIE_DEFAULT;
getline(cin, input);
if(!input.empty())
{
istringstream stream( input );
stream >> value;
if(value > ZOMBIE_MAX) value = ZOMBIE_MAX;
if(value < ZOMBIE_MIN) value = ZOMBIE_MIN;
}
const int ZOMBIES=value;
//game rules
cout << "=============================================================================" << endl
<< "Plants vs. Zombies Rule:" << endl
<< endl
<< "How to win:" << endl
<< " (1) All zombies are dead." << endl
<< " (2) At least one plant is live." << endl
<< " (3) The number of dead bomb plants cannot exceed the number of zombies." << endl
<< endl
<< "How to lose:" << endl
<< " All plants are dead." << endl
<< "=============================================================================" << endl;
system("pause");
system("cls");
//construct
srand(time(0)); // random number seed
Player *player = new Player;
Zombie *zombie = new Zombie[ZOMBIES];
Zombie::TotalNum = ZOMBIES;
Map *map = new Map(LANDS);
vector<Plant*> plant;
fstream fin("plants.txt", fstream::in);
string str;
if(fin)
{
while(fin >> str)
{
Plant *tmp = nullptr;
switch(str[0])
{
case 'C':
{
tmp = new CoinPlant(fin);
break;
}
case 'S':
{
tmp = new HornPlant(fin);
break;
}
case 'B':
{
tmp = new BombPlant(fin);
break;
}
case 'H':
{
tmp = new HealPlant(fin);
break;
}
default:
continue;
}
if(tmp)
{
plant.push_back(tmp);
}
}
}
player->Move(rand()%LANDS);
for (int i=0; i<ZOMBIES; ++i)
zombie[i].Move(rand()%LANDS);
while(true)
{
map->Display(*player, zombie);
cout << "------------------------------------------------" << endl;
cout << "Zombie information:" << endl;
for(int i=0; i<ZOMBIES; i++)
{
cout << '[' << i << "] " << zombie[i];
}
cout << endl << "================================================" << endl;
for(size_t i=0; i<plant.size(); ++i)
{
cout << "[" << i << "] " ;
plant[i]->Print();
cout << endl;
}
int choice = plant.size();
if (player->Money() > 0)
{
cout << endl << "Player $" << player->Money() ;
cout << ":\tEnter your choice (" << plant.size() << " to give up, default: " << choice << ")...>";
getline(cin, input);
if(!input.empty())
{
istringstream stream( input );
stream >> value;
if(value <= plant.size() && value >= 0) choice = value;
}
}
// end game condition
if (!map->IsNonPlant())
{
cout << "Oh no... You have no plant on the map ...." << endl;
break;
}
else if (BombPlant::deadNum >= ZOMBIES/2)
{
cout << "You lose the game since you cannot use that many bomb plants!" << endl;
break;
}
else
{
cout << "Congratulations! You have killed all zombies!" << endl;
break;
}
break;
}
/*
if(choice=plant.size()) break;
int cost=0;
string plantname;
switch(plant[choice].type())
{
case 'C':
CoinPlant *tmp = new CoinPlant(*dynamic_cast<CoinPlant *>(plant[choice]))
land->plant(tmp);
plantname="CoinPlant";
cost=tmp->price();
case 'S':
HornPlant *tmp = new HornPlant(*dynamic_cast<CoinPlant *>(plant[choice]))
land->plant(tmp);
plantname="HornPlant";
cost=tmp->price();
case 'B':
BombPlant *tmp = new BombPlant(*dynamic_cast<CoinPlant *>(plant[choice]));
land->plant(tmp);
plantname="BombPlant";
cost=tmp->price();
case 'H':
HealPlant *tmp = new HealPlant(*dynamic_cast<CoinPlant *>(plant[choice]));
land->plant(tmp);
plantname="HealPlant";
cost=tmp->price();
}
if(player->money() >= cost)
{
cout << "You have planted " << plantname << " at land 7 !";
break;
}
else
{
cout << "Not enough money! Please input again.";
}
}*/
// destruct
while(!plant.empty())
{
delete plant.back();
plant.pop_back();
}
delete player;
delete map;
delete [] zombie;
return 0;
}
bool allZombiesDie(Zombie * zombie, size_t num)
{
for(size_t i=0; i<num && !zombie[i].isAlive(); ++i)
return (i==num-1);
}
<commit_msg>modify player menu<commit_after>#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>
#include <vector>
#include <fstream>
#include <ctime>
#include "Map.h"
#include "Zombie.h"
#include "Player.h"
#include "Plant.h"
using namespace std;
bool allZombiesDie(const Zombie * zombie, size_t num);
int main()
{
//game start
cout << " -----------------------------" << endl
<< "| Plants v.s Zombies |" << endl
<< " -----------------------------" << endl;
constexpr int LAND_DEFAULT=8;
constexpr int LAND_MAX=10;
constexpr int LAND_MIN=1;
constexpr int ZOMBIE_DEFAULT=3;
constexpr int ZOMBIE_MAX=10;
constexpr int ZOMBIE_MIN=1;
string input;
//initialize game setting
cout << "Number of lands on the map (" << LAND_MIN << "-" << LAND_MAX << ", default: " << LAND_DEFAULT <<")...>";
int value = LAND_DEFAULT;
getline(cin, input);
if(!input.empty())
{
istringstream stream( input );
stream >> value;
if(value > LAND_MAX) value = LAND_MAX;
if(value < LAND_MIN) value = LAND_MIN;
}
const int LANDS=value;
cout << "Number of zombies on the map (" << ZOMBIE_MIN << "-" << ZOMBIE_MAX << ", default: "<< ZOMBIE_DEFAULT <<")...>";
value=ZOMBIE_DEFAULT;
getline(cin, input);
if(!input.empty())
{
istringstream stream( input );
stream >> value;
if(value > ZOMBIE_MAX) value = ZOMBIE_MAX;
if(value < ZOMBIE_MIN) value = ZOMBIE_MIN;
}
const int ZOMBIES=value;
//game rules
cout << "=============================================================================" << endl
<< "Plants vs. Zombies Rule:" << endl
<< endl
<< "How to win:" << endl
<< " (1) All zombies are dead." << endl
<< " (2) At least one plant is live." << endl
<< " (3) The number of dead bomb plants cannot exceed the number of zombies." << endl
<< endl
<< "How to lose:" << endl
<< " All plants are dead." << endl
<< "=============================================================================" << endl;
system("pause");
system("cls");
//construct
srand(time(0)); // random number seed
Player *player = new Player;
Zombie *zombie = new Zombie[ZOMBIES];
Zombie::TotalNum = ZOMBIES;
Map *map = new Map(LANDS);
vector<Plant*> plant;
fstream fin("plants.txt", fstream::in);
string str;
if(fin)
{
while(fin >> str)
{
Plant *tmp = nullptr;
switch(str[0])
{
case 'C':
{
tmp = new CoinPlant(fin);
break;
}
case 'S':
{
tmp = new HornPlant(fin);
break;
}
case 'B':
{
tmp = new BombPlant(fin);
break;
}
case 'H':
{
tmp = new HealPlant(fin);
break;
}
default:
continue;
}
if(tmp)
{
plant.push_back(tmp);
}
}
}
player->Move(rand()%LANDS);
for (int i=0; i<ZOMBIES; ++i)
zombie[i].Move(rand()%LANDS);
while(true)
{
map->Display(*player, zombie);
cout << "------------------------------------------------" << endl;
cout << "Zombie information:" << endl;
for(int i=0; i<ZOMBIES; i++)
{
cout << '[' << i << "] " << zombie[i];
}
cout << endl << "================================================" << endl;
for(size_t i=0; i<plant.size(); ++i)
{
cout << "[" << i << "] " ;
plant[i]->Print();
cout << endl;
}
int choice = plant.size();
do
{
if (player->Money() <= 0)
{
cout << "You don't have enough money" << endl;
}
else if (map->GetLand(player->Pos())->IsEmpty())
{
cout << endl << "Player $" << player->Money() ;
cout << ":\tEnter your choice (" << plant.size() << " to give up, default: " << choice << ")...>";
getline(cin, input);
if(!input.empty())
{
istringstream stream( input );
stream >> value;
if(value <= plant.size() && value >= 0) choice = value;
}
}
if(choice != plant.size() && plant[choice]->Price() >= player->Money())
cout << "Not enough money! Please input again!" << endl;
}
while(choice != plant.size() && plant[choice]->Price() >= player->Money());
// end game condition
if (!map->IsNonPlant())
{
cout << "Oh no... You have no plant on the map ...." << endl;
break;
}
else if (BombPlant::deadNum >= ZOMBIES/2)
{
cout << "You lose the game since you cannot use that many bomb plants!" << endl;
break;
}
else
{
cout << "Congratulations! You have killed all zombies!" << endl;
break;
}
break;
}
/*
if(choice=plant.size()) break;
int cost=0;
string plantname;
switch(plant[choice].type())
{
case 'C':
CoinPlant *tmp = new CoinPlant(*dynamic_cast<CoinPlant *>(plant[choice]))
land->plant(tmp);
plantname="CoinPlant";
cost=tmp->price();
case 'S':
HornPlant *tmp = new HornPlant(*dynamic_cast<CoinPlant *>(plant[choice]))
land->plant(tmp);
plantname="HornPlant";
cost=tmp->price();
case 'B':
BombPlant *tmp = new BombPlant(*dynamic_cast<CoinPlant *>(plant[choice]));
land->plant(tmp);
plantname="BombPlant";
cost=tmp->price();
case 'H':
HealPlant *tmp = new HealPlant(*dynamic_cast<CoinPlant *>(plant[choice]));
land->plant(tmp);
plantname="HealPlant";
cost=tmp->price();
}
if(player->money() >= cost)
{
cout << "You have planted " << plantname << " at land 7 !";
break;
}
else
{
cout << "Not enough money! Please input again.";
}
}*/
// destruct
while(!plant.empty())
{
delete plant.back();
plant.pop_back();
}
delete player;
delete map;
delete [] zombie;
return 0;
}
bool allZombiesDie(Zombie * zombie, size_t num)
{
for(size_t i=0; i<num && !zombie[i].isAlive(); ++i)
return (i==num-1);
}
<|endoftext|> |
<commit_before>c88d76ee-2747-11e6-949c-e0f84713e7b8<commit_msg>fixes, fixes for everyone<commit_after>c93a6f21-2747-11e6-8a87-e0f84713e7b8<|endoftext|> |
<commit_before>6d89f92e-5216-11e5-8612-6c40088e03e4<commit_msg>6d90b464-5216-11e5-b75c-6c40088e03e4<commit_after>6d90b464-5216-11e5-b75c-6c40088e03e4<|endoftext|> |
<commit_before>809e9294-2d15-11e5-af21-0401358ea401<commit_msg>809e9295-2d15-11e5-af21-0401358ea401<commit_after>809e9295-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>50c7aa23-2e4f-11e5-ba23-28cfe91dbc4b<commit_msg>50ce6bc0-2e4f-11e5-9bf6-28cfe91dbc4b<commit_after>50ce6bc0-2e4f-11e5-9bf6-28cfe91dbc4b<|endoftext|> |
<commit_before>6c7f3ac6-5216-11e5-91d1-6c40088e03e4<commit_msg>6c860da6-5216-11e5-8f47-6c40088e03e4<commit_after>6c860da6-5216-11e5-8f47-6c40088e03e4<|endoftext|> |
<commit_before>5cb64e87-2748-11e6-b1ce-e0f84713e7b8<commit_msg>Backup, rebase this later<commit_after>5ccb2de3-2748-11e6-8abd-e0f84713e7b8<|endoftext|> |
<commit_before>25e25451-ad5d-11e7-9f29-ac87a332f658<commit_msg>oh my, I hate roselyn<commit_after>264cdecf-ad5d-11e7-a76a-ac87a332f658<|endoftext|> |
<commit_before>683129f4-2fa5-11e5-b37c-00012e3d3f12<commit_msg>683373e4-2fa5-11e5-9eb1-00012e3d3f12<commit_after>683373e4-2fa5-11e5-9eb1-00012e3d3f12<|endoftext|> |
<commit_before>63ca22b8-5216-11e5-b442-6c40088e03e4<commit_msg>63d0962c-5216-11e5-a457-6c40088e03e4<commit_after>63d0962c-5216-11e5-a457-6c40088e03e4<|endoftext|> |
<commit_before>d40b83e6-ad5b-11e7-86fb-ac87a332f658<commit_msg>Finished?<commit_after>d4873fa3-ad5b-11e7-8f6c-ac87a332f658<|endoftext|> |
<commit_before>76599c3a-5216-11e5-8d75-6c40088e03e4<commit_msg>766046f4-5216-11e5-8c27-6c40088e03e4<commit_after>766046f4-5216-11e5-8c27-6c40088e03e4<|endoftext|> |
<commit_before>e9e461fe-585a-11e5-b987-6c40088e03e4<commit_msg>e9eb21cc-585a-11e5-888e-6c40088e03e4<commit_after>e9eb21cc-585a-11e5-888e-6c40088e03e4<|endoftext|> |
<commit_before>/*
* main.cpp
*
* Created on: Apr 9, 2014
* Author: Pimenta
*/
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <fstream>
#include <string>
using namespace std;
typedef int64_t word_t;
typedef uint64_t uword_t;
typedef uint32_t address_t;
#ifndef MEM_WORDS
#define MEM_WORDS 0x2000
#endif
const uword_t ADDRESS_WIDTH = uword_t(log2(double(MEM_WORDS)));
const uword_t ADDRESS_MASK = uword_t(MEM_WORDS - 1);
int main(int argc, char* argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage mode: subleq-sim <meminit_file>\n");
return 0;
}
uword_t* mem = new uword_t[MEM_WORDS];
// read data
ifstream f(argv[1]);
for (address_t words = 0; ; ++words) {
string tmp;
// skip address
f >> tmp;
if (tmp == "END;") {
break;
}
while (f.get() != ':');
f.get();
// read word
tmp = "";
for (char c = f.get(); c != ';'; c = f.get())
tmp += c;
sscanf(tmp.c_str(), "%llx", &mem[words]);
}
f.close();
// run
uword_t instruction;
address_t Aaddr, Baddr, Jaddr;
word_t sub;
for (address_t ip = 0; ; ip = sub <= 0 ? Jaddr : ip + 1) {
instruction = mem[ip];
if (0 > (word_t)instruction) {
break;
}
Aaddr = (instruction >> 2*ADDRESS_WIDTH) & ADDRESS_MASK;
Baddr = (instruction >> 1*ADDRESS_WIDTH) & ADDRESS_MASK;
Jaddr = (instruction >> 0*ADDRESS_WIDTH) & ADDRESS_MASK;
sub = mem[Baddr] - mem[Aaddr];
mem[Baddr] = sub;
printf("0x%08X: A=0x%08X(0x%016llX) B=0x%08X(0x%016llX) J=0x%08X sub=0x%016llX\n", ip, Aaddr, mem[Aaddr], Baddr, mem[Baddr], Jaddr, sub);
fflush(stdout);
}
delete[] mem;
return 0;
}
<commit_msg>Fixing bug<commit_after>/*
* main.cpp
*
* Created on: Apr 9, 2014
* Author: Pimenta
*/
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <fstream>
#include <string>
using namespace std;
typedef int64_t word_t;
typedef uint64_t uword_t;
typedef uint32_t address_t;
#ifndef MEM_WORDS
#define MEM_WORDS 0x2000
#endif
const uword_t ADDRESS_WIDTH = uword_t(log2(double(MEM_WORDS)));
const uword_t ADDRESS_MASK = uword_t(MEM_WORDS - 1);
int main(int argc, char* argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage mode: subleq-sim <meminit_file>\n");
return 0;
}
uword_t* mem = new uword_t[MEM_WORDS];
// read data
ifstream f(argv[1]);
for (address_t words = 0; ; ++words) {
string tmp;
// skip address
f >> tmp;
if (tmp == "END;") {
break;
}
while (f.get() != ':');
f.get();
// read word
tmp = "";
for (char c = f.get(); c != ';'; c = f.get())
tmp += c;
sscanf(tmp.c_str(), "%llx", &mem[words]);
}
f.close();
// run
uword_t instruction;
address_t Aaddr, Baddr, Jaddr;
word_t sub;
for (address_t ip = 0; ; ip = sub <= 0 ? Jaddr : ip + 1) {
instruction = mem[ip];
if (0 > (word_t)instruction) {
break;
}
Aaddr = (instruction >> 2*ADDRESS_WIDTH) & ADDRESS_MASK;
Baddr = (instruction >> 1*ADDRESS_WIDTH) & ADDRESS_MASK;
Jaddr = (instruction >> 0*ADDRESS_WIDTH) & ADDRESS_MASK;
sub = mem[Baddr] - mem[Aaddr];
printf("0x%08X: A=0x%08X(0x%016llX) B=0x%08X(0x%016llX) J=0x%08X sub=0x%016llX\n", ip, Aaddr, mem[Aaddr], Baddr, mem[Baddr], Jaddr, sub);
fflush(stdout);
mem[Baddr] = sub;
}
delete[] mem;
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <cmath>
using std::cin;
using std::cout;
using std::endl;
uint f(uint n)
{
switch(n)
{
case 0:
case 1:
case 2:
return 1;
case 3:
return 2;
default:
uint k = ceil(-0.5+sqrt(1+8*n)/2);
uint res = 0;
for (uint i = k; i <= n; ++i)
{
res += f(n-k);
}
return res;
}
return n;
}
int main()
{
uint n = 6;
//cin >> n;
cout << f(n) << endl;
return 0;
}
<commit_msg>fix implementation<commit_after>#include <iostream>
#include <cmath>
using std::cin;
using std::cout;
using std::endl;
uint f(uint n, uint base)
{
switch(n)
{
case 0:
case 1:
case 2:
return 1;
case 3:
return (base > 3) ? 2 : 1;
default:
uint k = ceil(-0.5+sqrt(1+8*n)/2);
uint res = 0;
for (uint i = k; i <= n; ++i)
res += f(n-i, i);
return res;
}
return n;
}
int main()
{
uint n = 7;
//cin >> n;
cout << f(n, n+1) << endl;
return 0;
}
<|endoftext|> |
<commit_before>f0958b33-327f-11e5-a323-9cf387a8033e<commit_msg>f09ba011-327f-11e5-ac88-9cf387a8033e<commit_after>f09ba011-327f-11e5-ac88-9cf387a8033e<|endoftext|> |
<commit_before>105011ac-2f67-11e5-a654-6c40088e03e4<commit_msg>105715ec-2f67-11e5-b329-6c40088e03e4<commit_after>105715ec-2f67-11e5-b329-6c40088e03e4<|endoftext|> |
<commit_before>#include <stdint.h>
#ifdef __cplusplus
#include <cstdlib>
#else
#include <stdlib.h>
#endif
#ifdef __APPLE__
#include <SDL/SDL.h>
#else
#include <SDL.h>
#endif
#define round(x) ((x)>=0?(int16_t)((x)+0.5):(int16_t)((x)-0.5))
#include "constants.h"
#include "RenderingContext.h"
#include "AmsFont.h"
#include "Oscillator.h"
#include "OscRamp.h"
#include "OscPulse.h"
#include "OscTri.h"
#include "FreqSeq.h"
int16_t mute = 1;
float amp = 0.1;
OscPulse osc1;
OscTri osc2;
OscTri osc3;
FreqSeq seq;
float map(float value, float iMin, float iMax, float oMin, float oMax) {
return oMin + (oMax - oMin) * (value - iMin) / (iMax - iMin);
}
void audioCallback(void* udata, uint8_t* stream0, int len) {
int16_t* stream = (int16_t*) stream0;
for (len >>= 1; len; len--) {
// update sequencer
float f = seq.tic();
osc1.freq = f;
osc2.freq = f / 3.01;
// update oscillators
float o1 = osc1.tic();
float o2 = osc2.tic();
float o3 = osc3.tic();
// o3 = (1 - o3) / 2;
o3 = map(o3, -1, 1, 0, 0.5);
osc1.width = o3;
osc2.width = o3;
// simple mix + amplification
float o = (o1 + o2);
o *= amp;
// trim overload
if (o < -1) o = -1;
if (o > 1) o = 1;
// convert to output format
o = 0x8000 * o * mute;
// write in buffer
*stream++ = round(o);
}
}
int main(int argc, char** argv) {
// initialize SDL video and audio
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) return 1;
// make sure SDL cleans up before exit
atexit(SDL_Quit);
// init audio
{
SDL_AudioSpec audioSpec;
audioSpec.freq = SAMPLE_RATE;
audioSpec.format = AUDIO_S16;
audioSpec.channels = 1;
audioSpec.samples = 512;
audioSpec.callback = audioCallback;
SDL_OpenAudio(&audioSpec, NULL);
}
osc3.freq = 0.03;
osc3.width = 0.9;
SDL_PauseAudio(0); // start audio
SDL_Surface* screen = SDL_SetVideoMode(SCREEN_W, SCREEN_H, 16, SDL_HWSURFACE | SDL_DOUBLEBUF);
SDL_WM_SetCaption("oodio", NULL);
RenderingContext ctx(screen);
ctx.backgroundColor(0, 0, 127);
// load images
AmsFont font("amstradFont.bmp");
font.paper(19);
font.pen(6);
font.locate(5, 8);
font.print(" -----OO/D/IO----- \n");
font.paper(1);
font.pen(24);
// program main loop
bool run = true;
while (run) {
//-------------------------
// message processing loop
SDL_Event event;
while (SDL_PollEvent(&event)) {
// check for messages
switch (event.type) {
case SDL_QUIT:
// exit if the window is closed
run = false;
break;
// check for keypresses
case SDL_KEYDOWN:
// exit if ESCAPE is pressed
if (event.key.keysym.sym == SDLK_ESCAPE) run = false;
// start / stop sound with F1 key
else if (event.key.keysym.sym == SDLK_F1) mute = mute == 0 ? 1 : 0;
else if (event.key.keysym.sym == SDLK_F2) osc1.freq = 110;
else if (event.key.keysym.sym == SDLK_F3) osc1.freq = 440;
// keyboard
else if (event.key.keysym.sym <= 256 && event.key.keysym.sym >= 0 ) {
font.print(event.key.keysym.sym);
}
break;
}
}
ctx.clear();
ctx.drawImage(font.getImage(), 0, 0);
ctx.update();
SDL_Delay(40); // 25 FPS
}
SDL_CloseAudio(); // close audio
return 0;
}
<commit_msg>basic mouse support<commit_after>#include <stdint.h>
#ifdef __cplusplus
#include <cstdlib>
#else
#include <stdlib.h>
#endif
#ifdef __APPLE__
#include <SDL/SDL.h>
#else
#include <SDL.h>
#endif
#define round(x) ((x)>=0?(int16_t)((x)+0.5):(int16_t)((x)-0.5))
#include "constants.h"
#include "RenderingContext.h"
#include "AmsFont.h"
#include "Oscillator.h"
#include "OscRamp.h"
#include "OscPulse.h"
#include "OscTri.h"
#include "FreqSeq.h"
int16_t mute = 1;
float amp = 0.1;
OscPulse osc1;
OscTri osc2;
OscTri osc3;
FreqSeq seq;
float map(float value, float iMin, float iMax, float oMin, float oMax) {
return oMin + (oMax - oMin) * (value - iMin) / (iMax - iMin);
}
void audioCallback(void* udata, uint8_t* stream0, int len) {
int16_t* stream = (int16_t*) stream0;
for (len >>= 1; len; len--) {
// update sequencer
float f = seq.tic();
osc1.freq = f;
osc2.freq = f / 3.01;
// update oscillators
float o1 = osc1.tic();
float o2 = osc2.tic();
float o3 = osc3.tic();
// o3 = (1 - o3) / 2;
o3 = map(o3, -1, 1, 0, 0.5);
osc1.width = o3;
osc2.width = o3;
// simple mix + amplification
float o = (o1 + o2);
o *= amp;
// trim overload
if (o < -1) o = -1;
if (o > 1) o = 1;
// convert to output format
o = 0x8000 * o * mute;
// write in buffer
*stream++ = round(o);
}
}
int main(int argc, char** argv) {
// initialize SDL video and audio
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) return 1;
// make sure SDL cleans up before exit
atexit(SDL_Quit);
// init audio
{
SDL_AudioSpec audioSpec;
audioSpec.freq = SAMPLE_RATE;
audioSpec.format = AUDIO_S16;
audioSpec.channels = 1;
audioSpec.samples = 512;
audioSpec.callback = audioCallback;
SDL_OpenAudio(&audioSpec, NULL);
}
osc3.freq = 0.03;
osc3.width = 0.9;
SDL_PauseAudio(0); // start audio
SDL_Surface* screen = SDL_SetVideoMode(SCREEN_W, SCREEN_H, 16, SDL_HWSURFACE | SDL_DOUBLEBUF);
SDL_WM_SetCaption("oodio", NULL);
RenderingContext ctx(screen);
ctx.backgroundColor(0, 0, 127);
// load images
AmsFont font("amstradFont.bmp");
font.paper(19);
font.pen(6);
font.locate(5, 8);
font.print(" -----OO/D/IO----- \n");
font.paper(1);
font.pen(24);
// program main loop
bool run = true;
while (run) {
//-------------------------
// message processing loop
SDL_Event event;
while (SDL_PollEvent(&event)) {
// check for messages
switch (event.type) {
case SDL_QUIT:
// exit if the window is closed
run = false;
break;
// check for keypresses
case SDL_KEYDOWN:
// exit if ESCAPE is pressed
if (event.key.keysym.sym == SDLK_ESCAPE) run = false;
// start / stop sound with F1 key
else if (event.key.keysym.sym == SDLK_F1) mute = mute == 0 ? 1 : 0;
else if (event.key.keysym.sym == SDLK_F2) osc1.freq = 110;
else if (event.key.keysym.sym == SDLK_F3) osc1.freq = 440;
// keyboard
else if (event.key.keysym.sym <= 256 && event.key.keysym.sym >= 0 ) {
font.print(event.key.keysym.sym);
}
break;
case SDL_MOUSEMOTION:
font.locate(event.motion.x / (8 * PIXEL), event.motion.y / (8 * PIXEL));
font.print('*');
break;
}
}
ctx.clear();
ctx.drawImage(font.getImage(), 0, 0);
ctx.update();
SDL_Delay(40); // 25 FPS
}
SDL_CloseAudio(); // close audio
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <math.h>
#include <vector>
#include <random>
#include <algorithm> // std::sort
#include <fstream>
//random generator
std::random_device rd;
std::mt19937 generator(rd());
std::uniform_real_distribution<double> uniform_distr(-1, 1);
#define population 100
#define elitism 0.2
#define randomBehaviour 0.2
#define mutationRate 0.1
#define mutationRange 0.2
double Sigmoid(double in)
{
return 1.0/(1.0 + exp(-in));
}
struct Neuron
{
std::vector<double> weights;
double value;
void Populate(int nInputs)
{
for(int i=0; i<nInputs; i++)
{
weights.push_back(uniform_distr(generator));
}
}
Neuron(){}
Neuron(int nInputs)
{
Populate(nInputs);
}
};
struct Layer
{
int index;
std::vector<Neuron> neurons;
void Populate(int nNeurons, int nInputs)
{
for(int i=0; i < nNeurons; i++)
{
Neuron newNeuron;
newNeuron.Populate(nInputs);
neurons.push_back(newNeuron);
}
}
Layer(){}
Layer(int nNeurons, int nInputs)
{
Populate(nNeurons,nInputs);
}
Layer(int ind, int nNeurons, int nInputs)
{
index = ind;
Populate(nNeurons,nInputs);
}
};
struct Network
{
std::vector<Layer> layers;
void perceptronGeneration(int nInputs, std::vector<int> nHiddens, int nOutputs)
{
int previousNeurons = 0;
int ind = 0;
Layer firstLayer(ind, nInputs, previousNeurons);
layers.push_back(firstLayer);
ind++;
previousNeurons = nInputs;
//for(int i=0; i<nHiddens.size(); i++)
for(auto nHidden : nHiddens)
{
Layer Hlayer(ind, nHidden, previousNeurons);
previousNeurons = nHidden;
layers.push_back(Hlayer);
ind++;
}
Layer lastLayer(ind, nOutputs, previousNeurons);
layers.push_back(lastLayer);
}
std::vector<double> FeedForward(std::vector<double> Inputs)
{
for(int i=0; i<Inputs.size(); i++)
layers[0].neurons[i].value = Inputs[i];
Layer previousLayer = layers[0];
for(int i=1; i<layers.size(); i++)
{
//for(auto currentNeuron : layers[i].neurons)
for(int j=0; j<layers[i].neurons.size(); j++)
{
double sum = 0;
//for(auto previousNeuron : previousLayer.neurons)
for(int k=0; k<previousLayer.neurons.size(); k++)
{
sum += previousLayer.neurons[k].value*layers[i].neurons[j].weights[k];
}
layers[i].neurons[j].value = Sigmoid(sum);
}
previousLayer = layers[i];
}
std::vector<double> output;
Layer lastLayer = layers.back();
for(auto neuron : lastLayer.neurons)
output.push_back(neuron.value);
return output;
}
void Randomize()
{
for(auto &l : layers)
{
//skip input layer that has no weights
if(l.index == 0) continue;
for(auto &n : l.neurons)
for(auto &w : n.weights)
w = uniform_distr(generator);
}
}
void print()
{
std::cout << "hello world, i am a neural network and my layers are = " << std::endl;
for(auto l : layers)
{
//skip input layer that has no weights
if(l.index == 0) continue;
std::cout << "hello world, i am layer number " << l.index << " and my neurons are = " << std::endl;
int j=0;
for(auto n : l.neurons)
{
std::cout << "hello world, i am neuron number " << j << " and my weights are = " << std::endl;
j++;
for(auto w : n.weights)
std::cout << w << std::endl;
}
}
}
Network(){}
Network(int nInputs, std::vector<int> nHiddens, int nOutputs)
{
perceptronGeneration(nInputs, nHiddens, nOutputs);
}
};
struct Genome
{
Network network;
double score;
void ReadfromFile(const char* filename)
{
//std::vector<double> weights;
std::ifstream in(filename);
double number;
//while (in >> number) {
// weights.push_back(number);
//}
//int i = 0;
for(auto &l : network.layers)
{
//skip input layer that has no weights
if(l.index == 0) continue;
for(auto &n : l.neurons)
{
for(auto &w : n.weights)
in >> w;// = weights[i++];
}
}
in.close();
}
void SavetoFile(const char* filename)
{
std::ofstream output;
output.open(filename);
for(auto l : network.layers)
{
//skip input layer that has no weights
if(l.index == 0) continue;
for(auto n : l.neurons)
{
for(auto w : n.weights)
output << w << std::endl;
}
}
output.close();
}
//to sort a vector of genomes
bool operator < (const Genome& g) const
{
return (score < g.score);
}
Genome(){}
Genome(Network n, double s) : network(n), score(s) {}
};
struct Generation
{
std::vector<Genome> genomes;
//void addGenome(){} //TODO add genome and sort score
Genome breed(Genome g1, Genome g2)
{
Genome child = g1;
for(int i=0; i<g2.network.layers.size(); i++)
for(int j=0; j<g2.network.layers[i].neurons.size(); j++)
for(int k=0; k<g2.network.layers[i].neurons[j].weights.size(); k++)
{
double r = uniform_distr(generator);
//std::cout << r << std::endl;
if(r < 0.5)
child.network.layers[i].neurons[j].weights[k] = g2.network.layers[i].neurons[j].weights[k];
r = uniform_distr(generator);
if(r < mutationRate)
child.network.layers[i].neurons[j].weights[k] = uniform_distr(generator)*mutationRange*2.0 - mutationRange;
}
return child;
}
void nextGeneration()
{
std::vector<Genome> nextG;
for (int i=0; i < floor(elitism*population); i++)
nextG.push_back(genomes[i]);
for (int i=0; i < floor(randomBehaviour*population); i++)
{
Genome g = genomes[0];
g.network.Randomize();
nextG.push_back(g);
}
int max = 0;
while(nextG.size() < genomes.size())
{
for(int i=0; i<max; i++)
nextG.push_back(breed(genomes[i],genomes[max]));
max++;
if(max >= genomes.size()) max = 0;
}
//reset scores
for(auto &genome : nextG)
{
genome.score = 0;
}
genomes = nextG;
}
void Sort()
{
std::sort(genomes.begin(), genomes.end());
std::reverse(genomes.begin(),genomes.end());
}
double avgScore()
{
double avg = 0;
for(auto &genome : genomes)
avg += genome.score;
return avg/population;
}
Generation(){}
Generation(int nInputs, std::vector<int> nHiddens, int nOutputs)
{
for (int i=0; i < population; i++)
{
Network n(nInputs,nHiddens,nOutputs);
Genome g(n,0);
genomes.push_back(g);
}
}
};
int main()
{
//XOR TEST
Generation X(2,{3},1);
std::vector<std::vector<double>> dataset = {{1,0},{1,1},{0,1},{0,0}};
std::vector<double> truth = {1,0,1,0};
int count = 0;
std::vector<double> avgscore;
while(1)
{
count++;
for(auto &genome : X.genomes)
{
std::vector<double> output;
for(auto input : dataset)
{
auto c = genome.network.FeedForward(input);
output.push_back(c[0]>0.5);
}
for(int i=0; i<4; i++)
if(output[i] == truth[i]) genome.score++;
}
X.Sort();
//if(!(count%100))
// avgscore.push_back(X.avgScore());
if(X.genomes[0].score == 4) break;
X.nextGeneration();
}
std::cout << "XOR solved!!" << std::endl;
std::cout << "number of generations = " << count << std::endl;
Genome champ = X.genomes[0];
//revaluate champ
std::vector<double> output;
for(auto input : dataset)
{
auto c = champ.network.FeedForward(input);
output.push_back(c[0]);
}
for(int i=0; i<output.size(); i++)
{
std::cout<< "the output of {" << dataset[i][0] << "," << dataset[i][1] << "} is " << output[i] << std::endl;
}
champ.SavetoFile("champ.nn");
champ.network.print();
Network t(2,{3},1);
Genome test(t,0);
test.ReadfromFile("champ.nn");
test.network.print();
/*
std::cout << std::endl;
for(auto &genome : X.genomes)
std::cout << genome.score;
std::cout << std::endl;
std::ofstream output;
output.open("scores.txt");
for(int i=0; i<avgscore.size(); i++)
{
output << i << "\t" << avgscore[i] << std::endl;
}
output.close();
*/
return 0;
}<commit_msg>save update<commit_after>#include <iostream>
#include <math.h>
#include <vector>
#include <random>
#include <algorithm> // std::sort
#include <fstream>
//random generator
std::random_device rd;
std::mt19937 generator(rd());
std::uniform_real_distribution<double> uniform_distr(-1, 1);
#define population 100
#define elitism 0.2
#define randomBehaviour 0.2
#define mutationRate 0.1
#define mutationRange 0.2
double Sigmoid(double in)
{
return 1.0/(1.0 + exp(-in));
}
struct Neuron
{
std::vector<double> weights;
double value;
void Populate(int nInputs)
{
for(int i=0; i<nInputs; i++)
{
weights.push_back(uniform_distr(generator));
}
}
Neuron(){}
Neuron(int nInputs)
{
Populate(nInputs);
}
};
struct Layer
{
int index;
std::vector<Neuron> neurons;
void Populate(int nNeurons, int nInputs)
{
for(int i=0; i < nNeurons; i++)
{
Neuron newNeuron;
newNeuron.Populate(nInputs);
neurons.push_back(newNeuron);
}
}
Layer(){}
Layer(int nNeurons, int nInputs)
{
Populate(nNeurons,nInputs);
}
Layer(int ind, int nNeurons, int nInputs)
{
index = ind;
Populate(nNeurons,nInputs);
}
};
struct Network
{
std::vector<Layer> layers;
void perceptronGeneration(int nInputs, std::vector<int> nHiddens, int nOutputs)
{
int previousNeurons = 0;
int ind = 0;
Layer firstLayer(ind, nInputs, previousNeurons);
layers.push_back(firstLayer);
ind++;
previousNeurons = nInputs;
//for(int i=0; i<nHiddens.size(); i++)
for(auto nHidden : nHiddens)
{
Layer Hlayer(ind, nHidden, previousNeurons);
previousNeurons = nHidden;
layers.push_back(Hlayer);
ind++;
}
Layer lastLayer(ind, nOutputs, previousNeurons);
layers.push_back(lastLayer);
}
std::vector<double> FeedForward(std::vector<double> Inputs)
{
for(int i=0; i<Inputs.size(); i++)
layers[0].neurons[i].value = Inputs[i];
Layer previousLayer = layers[0];
for(int i=1; i<layers.size(); i++)
{
//for(auto currentNeuron : layers[i].neurons)
for(int j=0; j<layers[i].neurons.size(); j++)
{
double sum = 0;
//for(auto previousNeuron : previousLayer.neurons)
for(int k=0; k<previousLayer.neurons.size(); k++)
{
sum += previousLayer.neurons[k].value*layers[i].neurons[j].weights[k];
}
layers[i].neurons[j].value = Sigmoid(sum);
}
previousLayer = layers[i];
}
std::vector<double> output;
Layer lastLayer = layers.back();
for(auto neuron : lastLayer.neurons)
output.push_back(neuron.value);
return output;
}
void Randomize()
{
for(auto &l : layers)
{
//skip input layer that has no weights
if(l.index == 0) continue;
for(auto &n : l.neurons)
for(auto &w : n.weights)
w = uniform_distr(generator);
}
}
void print()
{
std::cout << "hello world, i am a neural network and my layers are = " << std::endl;
for(auto l : layers)
{
//skip input layer that has no weights
if(l.index == 0) continue;
std::cout << "hello world, i am layer number " << l.index << " and my neurons are = " << std::endl;
int j=0;
for(auto n : l.neurons)
{
std::cout << "hello world, i am neuron number " << j << " and my weights are = " << std::endl;
j++;
for(auto w : n.weights)
std::cout << w << std::endl;
}
}
}
Network(){}
Network(int nInputs, std::vector<int> nHiddens, int nOutputs)
{
perceptronGeneration(nInputs, nHiddens, nOutputs);
}
};
struct Genome
{
Network network;
double score;
void ReadfromFile(const char* filename)
{
std::ifstream in(filename);
for(auto &l : network.layers)
{
//skip input layer that has no weights
if(l.index == 0) continue;
for(auto &n : l.neurons)
{
for(auto &w : n.weights)
in >> w;
}
}
in.close();
}
void SavetoFile(const char* filename)
{
std::ofstream output;
output.open(filename);
for(auto l : network.layers)
{
//skip input layer that has no weights
if(l.index == 0) continue;
for(auto n : l.neurons)
{
for(auto w : n.weights)
output << w << std::endl;
}
}
output.close();
}
//to sort a vector of genomes
bool operator < (const Genome& g) const
{
return (score < g.score);
}
Genome(){}
Genome(Network n, double s) : network(n), score(s) {}
};
struct Generation
{
std::vector<Genome> genomes;
//void addGenome(){} //TODO add genome and sort score
Genome breed(Genome g1, Genome g2)
{
Genome child = g1;
for(int i=0; i<g2.network.layers.size(); i++)
for(int j=0; j<g2.network.layers[i].neurons.size(); j++)
for(int k=0; k<g2.network.layers[i].neurons[j].weights.size(); k++)
{
double r = uniform_distr(generator);
//std::cout << r << std::endl;
if(r < 0.5)
child.network.layers[i].neurons[j].weights[k] = g2.network.layers[i].neurons[j].weights[k];
r = uniform_distr(generator);
if(r < mutationRate)
child.network.layers[i].neurons[j].weights[k] = uniform_distr(generator)*mutationRange*2.0 - mutationRange;
}
return child;
}
void nextGeneration()
{
std::vector<Genome> nextG;
for (int i=0; i < floor(elitism*population); i++)
nextG.push_back(genomes[i]);
for (int i=0; i < floor(randomBehaviour*population); i++)
{
Genome g = genomes[0];
g.network.Randomize();
nextG.push_back(g);
}
int max = 0;
while(nextG.size() < genomes.size())
{
for(int i=0; i<max; i++)
nextG.push_back(breed(genomes[i],genomes[max]));
max++;
if(max >= genomes.size()) max = 0;
}
//reset scores
for(auto &genome : nextG)
{
genome.score = 0;
}
genomes = nextG;
}
void Sort()
{
std::sort(genomes.begin(), genomes.end());
std::reverse(genomes.begin(),genomes.end());
}
double avgScore()
{
double avg = 0;
for(auto &genome : genomes)
avg += genome.score;
return avg/population;
}
Generation(){}
Generation(int nInputs, std::vector<int> nHiddens, int nOutputs)
{
for (int i=0; i < population; i++)
{
Network n(nInputs,nHiddens,nOutputs);
Genome g(n,0);
genomes.push_back(g);
}
}
};
int main()
{
//XOR TEST
Generation X(2,{3},1);
std::vector<std::vector<double>> dataset = {{1,0},{1,1},{0,1},{0,0}};
std::vector<double> truth = {1,0,1,0};
int count = 0;
std::vector<double> avgscore;
while(1)
{
count++;
for(auto &genome : X.genomes)
{
std::vector<double> output;
for(auto input : dataset)
{
auto c = genome.network.FeedForward(input);
output.push_back(c[0]>0.5);
}
for(int i=0; i<4; i++)
if(output[i] == truth[i]) genome.score++;
}
X.Sort();
//if(!(count%100))
// avgscore.push_back(X.avgScore());
if(X.genomes[0].score == 4) break;
X.nextGeneration();
}
std::cout << "XOR solved!!" << std::endl;
std::cout << "number of generations = " << count << std::endl;
Genome champ = X.genomes[0];
//revaluate champ
std::vector<double> output;
for(auto input : dataset)
{
auto c = champ.network.FeedForward(input);
output.push_back(c[0]);
}
for(int i=0; i<output.size(); i++)
{
std::cout<< "the output of {" << dataset[i][0] << "," << dataset[i][1] << "} is " << output[i] << std::endl;
}
champ.SavetoFile("champ.nn");
champ.network.print();
Network t(2,{3},1);
Genome test(t,0);
test.ReadfromFile("champ.nn");
test.network.print();
/*
std::cout << std::endl;
for(auto &genome : X.genomes)
std::cout << genome.score;
std::cout << std::endl;
std::ofstream output;
output.open("scores.txt");
for(int i=0; i<avgscore.size(); i++)
{
output << i << "\t" << avgscore[i] << std::endl;
}
output.close();
*/
return 0;
}<|endoftext|> |
<commit_before>912fb388-35ca-11e5-8b66-6c40088e03e4<commit_msg>91367c1e-35ca-11e5-98d9-6c40088e03e4<commit_after>91367c1e-35ca-11e5-98d9-6c40088e03e4<|endoftext|> |
<commit_before>7760ae44-2d53-11e5-baeb-247703a38240<commit_msg>77613166-2d53-11e5-baeb-247703a38240<commit_after>77613166-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>9101ad76-2d14-11e5-af21-0401358ea401<commit_msg>9101ad77-2d14-11e5-af21-0401358ea401<commit_after>9101ad77-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>b4b7a9f5-327f-11e5-85dc-9cf387a8033e<commit_msg>b4bde473-327f-11e5-9967-9cf387a8033e<commit_after>b4bde473-327f-11e5-9967-9cf387a8033e<|endoftext|> |
<commit_before>b6aa3bee-2747-11e6-baae-e0f84713e7b8<commit_msg>update testing<commit_after>b6be830f-2747-11e6-a371-e0f84713e7b8<|endoftext|> |
<commit_before>#include <iostream>
#include <tuple>
#include <functional>
template<size_t _I>
struct _Index
{
using _Next = _Index<_I+1>;
static const size_t value = _I;
};
template<typename _Cs, typename _I>
struct _Evaluate
{
template<typename _Values>
inline
static void _evaluate(const _Cs &cs, const _Values& values) {
if (!std::get<_I::value>(cs)(values)) {
_Evaluate<_Cs, typename _I::_Next>::_evaluate(cs, values);
}
};
};
template<typename _Cs>
struct _Evaluate<_Cs, _Index<std::tuple_size<_Cs>::value>>
{
template<typename _Values>
inline
static void _evaluate(const _Cs &cs, const _Values& values) {
};
};
template<typename _Cs, typename ... _T>
struct _Switch
{
_Cs mCases;
_Switch(_Cs && cases)
: mCases(cases)
{
}
void operator()(const _T& ... values)
{
_Evaluate<_Cs, _Index<0>>::_evaluate(mCases, std::make_tuple(std::cref(values)...));
}
};
template<typename ... _T>
struct _Switch<void, _T ...>
{
_Switch()
{
}
};
template<typename ... _T>
inline constexpr
_Switch<void, _T...> _switch()
{
return _Switch<void, _T...>();
}
template<typename _Fnc, typename ... _T>
struct _Case
{
_Fnc mFnc;
std::tuple<const _T& ...> mValues;
_Case(_Fnc&& fnc, std::tuple<const _T& ...>&& values)
: mFnc(fnc),
mValues(values)
{}
bool operator()(const std::tuple<const _T& ...>& values) const
{
if(values == mValues) {
mFnc(values);
return true;
}
return false;
}
};
template<typename ... _T>
struct _Case<void, _T...>
{
std::tuple<const _T& ...> mValues;
_Case(const _T & ... values)
: mValues(values ...)
{}
template<typename _Fnc>
_Case<_Fnc, _T ...> operator()(_Fnc&& fnc)
{
return _Case<_Fnc, _T ...>(std::forward<_Fnc>(fnc), std::move(mValues));
}
};
template<typename ... _T>
inline constexpr
_Case<void, _T...> _case(_T && ... values)
{
return _Case<void, _T...>(values ...);
}
template<typename _Cs, typename _Fnc, typename ... _T>
inline constexpr
auto operator <= (_Switch<_Cs, _T ...>&& s, _Case<_Fnc, _T ...>&& c) ->
_Switch<decltype(std::tuple_cat(std::move(s.mCases), std::tuple<_Case<_Fnc, _T ...>>(std::forward<_Case<_Fnc, _T ...>>(c)))), _T ...>
{
using _Result = _Switch<decltype(std::tuple_cat(std::move(s.mCases), std::tuple<_Case<_Fnc, _T ...>>(std::forward<_Case<_Fnc, _T ...>>(c)))), _T ...>;
return _Result(std::tuple_cat(std::move(s.mCases), std::tuple<_Case<_Fnc, _T ...>>(std::forward<_Case<_Fnc, _T ...>>(c))));
}
template<typename _Fnc, typename ... _T>
inline constexpr
_Switch<std::tuple<_Case<_Fnc, _T ...>>, _T ...> operator <= (_Switch<void, _T ...>&& s, _Case<_Fnc, _T ...>&& c)
{
return _Switch<std::tuple<_Case<_Fnc, _T ...>>, _T ...>(std::tuple<_Case<_Fnc, _T ...>>(std::forward<_Case<_Fnc, _T ...>>(c)));
}
int main()
{
int x = 1, y = 3;
auto a = _switch<int, int>()
<= _case(1,0)([](int, int){std::cout << "Hello, World 1-0!" << std::endl;})
<= _case(1,1)([](int, int){std::cout << "Hello, World 1-1" << std::endl;});
a(x,y);
return 0;
}<commit_msg>add call function<commit_after>#include <iostream>
#include <tuple>
#include <functional>
template<std::size_t ... _Indices>
struct Indices {};
template<std::size_t _N, std::size_t... _Is>
struct BuildIndices : BuildIndices<_N-1, _N-1, _Is ...>
{};
template<std::size_t... _Is>
struct BuildIndices<0, _Is ...> : Indices<_Is ...>
{};
template<typename _Fnc, typename _Args, std::size_t ... _Indices>
auto _call(_Fnc &&f, _Args &&args, const Indices<_Indices...> &) -> decltype(f(std::get<_Indices>(args)...))
{
return f(std::get<_Indices>(args)...);
}
template<typename _Fnc, typename _Args>
auto call(_Fnc &&f, const _Args &args) -> decltype(_call(f, args, BuildIndices< std::tuple_size<_Args>::value>()))
{
return _call(f, args, BuildIndices< std::tuple_size<_Args>::value>());
}
template<size_t _I>
struct _Index
{
using _Next = _Index<_I+1>;
static const size_t value = _I;
};
template<typename _Cs, typename _I>
struct _Evaluate
{
template<typename _Values>
inline
static void _evaluate(const _Cs &cs, const _Values& values) {
if (!call(std::get<_I::value>(cs), values)) {
_Evaluate<_Cs, typename _I::_Next>::_evaluate(cs, values);
}
};
};
template<typename _Cs>
struct _Evaluate<_Cs, _Index<std::tuple_size<_Cs>::value>>
{
template<typename _Values>
inline
static void _evaluate(const _Cs &cs, const _Values& values) {
};
};
template<typename _Cs, typename ... _T>
struct _Switch
{
_Cs mCases;
_Switch(_Cs && cases)
: mCases(cases)
{
}
void operator()(const _T& ... values)
{
_Evaluate<_Cs, _Index<0>>::_evaluate(mCases, std::make_tuple(std::cref(values)...));
}
};
template<typename ... _T>
struct _Switch<void, _T ...>
{
_Switch()
{
}
};
template<typename ... _T>
inline constexpr
_Switch<void, _T...> _switch()
{
return _Switch<void, _T...>();
}
template<typename _Fnc, typename ... _T>
struct _Case
{
_Fnc mFnc;
std::tuple<const _T& ...> mValues;
_Case(_Fnc&& fnc, std::tuple<const _T& ...>&& values)
: mFnc(fnc),
mValues(values)
{}
bool operator()(const std::tuple<const _T& ...>& values) const
{
if(values == mValues) {
mFnc(values);
return true;
}
return false;
}
};
template<typename ... _T>
struct _Case<void, _T...>
{
std::tuple<const _T& ...> mValues;
_Case(const _T & ... values)
: mValues(values ...)
{}
template<typename _Fnc>
_Case<_Fnc, _T ...> operator()(_Fnc&& fnc)
{
return _Case<_Fnc, _T ...>(std::forward<_Fnc>(fnc), std::move(mValues));
}
};
template<typename ... _T>
inline constexpr
_Case<void, _T...> _case(_T && ... values)
{
return _Case<void, _T...>(values ...);
}
template<typename _Cs, typename _Fnc, typename ... _T>
inline constexpr
auto operator <= (_Switch<_Cs, _T ...>&& s, _Case<_Fnc, _T ...>&& c) ->
_Switch<decltype(std::tuple_cat(std::move(s.mCases), std::tuple<_Case<_Fnc, _T ...>>(std::forward<_Case<_Fnc, _T ...>>(c)))), _T ...>
{
using _Result = _Switch<decltype(std::tuple_cat(std::move(s.mCases), std::tuple<_Case<_Fnc, _T ...>>(std::forward<_Case<_Fnc, _T ...>>(c)))), _T ...>;
return _Result(std::tuple_cat(std::move(s.mCases), std::tuple<_Case<_Fnc, _T ...>>(std::forward<_Case<_Fnc, _T ...>>(c))));
}
template<typename _Fnc, typename ... _T>
inline constexpr
_Switch<std::tuple<_Case<_Fnc, _T ...>>, _T ...> operator <= (_Switch<void, _T ...>&& s, _Case<_Fnc, _T ...>&& c)
{
return _Switch<std::tuple<_Case<_Fnc, _T ...>>, _T ...>(std::tuple<_Case<_Fnc, _T ...>>(std::forward<_Case<_Fnc, _T ...>>(c)));
}
int main()
{
int x = 1, y = 3;
auto a = _switch<int, int>()
<= _case(1,0)([](int, int){std::cout << "Hello, World 1-0!" << std::endl;})
<= _case(1,1)([](int, int){std::cout << "Hello, World 1-1" << std::endl;});
a(x,y);
return 0;
}
<|endoftext|> |
<commit_before>#include "overnet.h"
#include "event.h"
#include "event_scheduler.h"
#include "network.h"
#include "util.h"
#include <iostream>
#include <string>
#include <sstream>
#include <cmath>
//default setting
vector<UINT32> Stat::Ping_per_node;
vector<UINT32> Stat::Storage_per_node; //GNRS storage overhead
vector<UINT32> Stat::Workload_per_node; //GNRS answer query overhead
vector<Query_Latency> Stat::Query_latency_time;
vector<Query_Latency> Stat::Insertion_latency_time;
vector<Retry_Count> Stat::Retry_Cnt;
vector<Retry_Count> Stat::DHT_RetryCnt;
vector<UINT32> Stat::Migration_per_node;
UINT32 Stat::Premature_joins=0;
UINT32 Stat::Premature_leaves=0;
FLOAT64 Settings::EndTime = 5000;
FLOAT64 Settings::TestThreshold = 0.1;
UINT32 Settings::TotalVirtualGUID = 1000000000;
UINT32 Settings::TotalActiveGUID = 10000; //
UINT32 Settings::NeighborSize =0; //full range neighbor size if undefined in command line, use default 2*ceil(K/2)
UINT32 Settings::DHTHop = 5;//estimated hops for a DHT path
UINT32 Settings::GNRS_K =5;
FLOAT64 Settings::OnOffSession =10;//session length for churn
UINT32 Settings::OnOffRounds=0;//0: leave, 1: leave+join, 2: leave+join+leave...
UINT32 Settings::ChurnHours =0;//# of consecutive hours of churn generation
UINT32 Settings::QueryHours =0;//# of hours query generation
UINT32 Settings::UpdateHours =0;//# of hours update generation
FLOAT64 Settings::QueryPerNode = 10000;
FLOAT64 Settings::UpdatePerNode = 1000;
string Settings::outFileName;
FLOAT64 Settings::ChurnPerNode=0.01;
/*!
* @brief Computes floor(log2(n))
* Works by finding position of MSB set.
* @returns -1 if n == 0.
*/
static inline INT32 FloorLog2(UINT32 n)
{
INT32 p = 0;
if (n == 0) return -1;
if (n & 0xffff0000) { p += 16; n >>= 16; }
if (n & 0x0000ff00) { p += 8; n >>= 8; }
if (n & 0x000000f0) { p += 4; n >>= 4; }
if (n & 0x0000000c) { p += 2; n >>= 2; }
if (n & 0x00000002) { p += 1; }
return p;
}
/*!
* @brief Computes floor(log2(n))
* Works by finding position of MSB set.
* @returns -1 if n == 0.
*/
static inline INT32 CeilLog2(UINT32 n)
{
return FloorLog2(n - 1) + 1;
}
void ParseArg(const char * argv)
{
string arg(argv);
if (arg.find("gnrs_k=") != string::npos)
{
stringstream ss (stringstream::in | stringstream::out);
ss <<arg.substr(8);
ss >>Settings::GNRS_K;
}
else if (arg.find("endtime=") != string::npos)
{
stringstream ss (stringstream::in | stringstream::out);
ss <<arg.substr(8);
ss >>Settings::EndTime;
}
else if (arg.find("testthreshold=") != string::npos)
{
stringstream ss (stringstream::in | stringstream::out);
ss <<arg.substr(14);
ss >>Settings::TestThreshold;
}
else if (arg.find("onoffsession=") != string::npos)
{
stringstream ss (stringstream::in | stringstream::out);
ss <<arg.substr(13);
ss >>Settings::OnOffSession;
}
else if (arg.find("onoffrounds=") != string::npos)
{
stringstream ss (stringstream::in | stringstream::out);
ss <<arg.substr(12);
ss >>Settings::OnOffRounds;
}
else if (arg.find("churnhours=") != string::npos)
{
stringstream ss (stringstream::in | stringstream::out);
ss <<arg.substr(11);
ss >>Settings::ChurnHours;
}
else if (arg.find("queryhours=") != string::npos)
{
stringstream ss (stringstream::in | stringstream::out);
ss <<arg.substr(11);
ss >>Settings::QueryHours;
}
else if (arg.find("updatehours=") != string::npos)
{
stringstream ss (stringstream::in | stringstream::out);
ss <<arg.substr(12);
ss >>Settings::UpdateHours;
}
else if (arg.find("querypernode=") != string::npos)
{
stringstream ss (stringstream::in | stringstream::out);
ss <<arg.substr(13);
ss >>Settings::QueryPerNode;
}
else if (arg.find("updatepernode=") != string::npos)
{
stringstream ss (stringstream::in | stringstream::out);
ss <<arg.substr(14);
ss >>Settings::UpdatePerNode;
}
else if (arg.find("totalactiveguid=") != string::npos)
{
stringstream ss (stringstream::in | stringstream::out);
ss <<arg.substr(16);
ss >>Settings::TotalActiveGUID;
}
else if (arg.find("neighborsize=") != string::npos)
{
stringstream ss (stringstream::in | stringstream::out);
ss <<arg.substr(13);
ss >>Settings::NeighborSize;
}
else if (arg.find("outfilename=") != string::npos)
{
stringstream ss (stringstream::in | stringstream::out);
ss <<arg.substr(12);
ss >>Settings::outFileName;
}
else if (arg.find("churnpernode=") != string::npos)
{
stringstream ss (stringstream::in | stringstream::out);
ss <<arg.substr(13);
ss >>Settings::ChurnPerNode;
}
}
int main(int argc, const char* argv[])
{
EventScheduler::Inst()->AddEvent(new DummyEvent());
cout <<"Initializing the network ..." <<endl;
//Underlay::CreateInst("2220IXP_Prov4_IXP2_m_route.txt", "2220IXP_Prov4_IXP2_m_ASInfo.txt");
//Underlay::CreateInst("2220SQ_Prov4_m_route.txt", "2220SQ_Prov4_m_ASInfo.txt");
//argv[1]: routeFileName, argv[2]:asInfoFileName
Underlay::CreateInst(argv[1], argv[2]);
if(argc>3){
for (int i = 3; i < argc; i++) {
ParseArg(argv[i]);
}
}
/*for (int i = 0; i < Underlay::Inst()->as_v.size(); i++) {
cout<<"for as "<<i<<" tier = "<<Underlay::Inst()->as_v[i]._asIdx<<endl;
for (int j = 0; j < Underlay::Inst()->as_v.size(); j++) {
cout<<"latency "<<i<<" to "<<j<<" = "<<Underlay::Inst()->getLatency(i,j)<<endl;
}
}*/
Underlay::Inst()->InitializeWorkload();
cout<<"total # nodes "<<Underlay::Inst()->global_node_table.size()<<endl;
//Settings::DHTHop = log10((FLOAT64)Underlay::Inst()->global_node_table.size());
/*
if(Settings::QueryHours > Settings::UpdateHours)
Settings::EndTime = Settings::QueryHours;
else
Settings::EndTime = Settings::UpdateHours;
* */
cout<<"Settings::"<<endl;
cout<<"Settings::EndTime="<<Settings::EndTime<<endl;
cout<<"Settings::TestThreshold="<<Settings::TestThreshold<<endl;
cout<<"Settings::TotalVirtualGUID="<<Settings::TotalVirtualGUID<<endl;
cout<<"Settings::TotalActiveGUID="<<Settings::TotalActiveGUID<<endl; //
cout<<"Settings::NeighborSize="<<Settings::NeighborSize<<endl; //full range neighbor size if undefined in command line, use default 2*ceil(K/2)
cout<<"Settings::DHTHop="<<Settings::DHTHop<<endl;//estimated hops for a DHT path
cout<<"Settings::GNRS_K="<<Settings::GNRS_K<<endl;
cout<<"Settings::OnOffSession="<<Settings::OnOffSession<<endl;//session length for churn
cout<<"Settings::OnOffRounds="<<Settings::OnOffRounds<<endl;//0: leave, 1: leave+join, 2: leave+join+leave...
cout<<"Settings::ChurnHours="<<Settings::ChurnHours<<endl;//# of consecutive hours of churn generation
cout<<"Settings::QueryHours="<<Settings::QueryHours<<endl;//# of hours query generation
cout<<"Settings::UpdateHours="<<Settings::UpdateHours<<endl;//# of hours update generation
cout<<"Settings::QueryPerNode="<<Settings::QueryPerNode<<endl;
cout<<"Settings::UpdatePerNode="<<Settings::UpdatePerNode<<endl;
cout<<"Settings::ChurnPerNode="<<Settings::ChurnPerNode<<endl;
/*
for (int i = 0; i < Underlay::Inst()->global_node_table.size(); i++) {
cout<<"for node "<<i <<" "<<Underlay::Inst()->global_node_table[i].getASIdx()<<endl;
}*/
for (UINT32 i = 0; i < Underlay::Inst()->GetNumOfNode(); i++) {
Stat::Migration_per_node.push_back(0);
Stat::Ping_per_node.push_back(0);
Stat::Storage_per_node.push_back(0);
Stat::Workload_per_node.push_back(0);
}
UINT32 totalNodes = Underlay::Inst()->global_node_table.size();
if(Settings::ChurnHours)
Underlay::Inst()->generateLeaveChurn(Settings::ChurnHours, Settings::ChurnPerNode*totalNodes,
Settings::OnOffSession, Settings::OnOffRounds);
/*
if(Settings::QueryHours)
Underlay::Inst()->generateWorkload(Settings::QueryHours,Settings::QueryPerNode*totalNodes,'Q');
if(Settings::UpdateHours)
Underlay::Inst()->generateWorkload(Settings::UpdateHours,Settings::UpdatePerNode*totalNodes,'U');
* */
cout <<"total queued jobs: " <<EventScheduler::Inst()->GetSize() <<" info: ";
while ( EventScheduler::Inst()->GetCurrentTime() <= Settings::EndTime
&& EventScheduler::Inst()->GetSize()>1){
Event * pevent = EventScheduler::Inst()->CurrentEvent();
//cout <<"queued jobs: " <<EventScheduler::Inst()->GetSize() <<" info: ";
pevent->PrintInfo();
if (pevent->Callback()){
delete pevent;
}
EventScheduler::Inst()->NextEvent();
}
/*
for (int i = 0; i < Stat::Query_latency_time.size(); i++) {
cout<<Stat::Query_latency_time[i]._delay<<" "<<Stat::Query_latency_time[i]._time<<endl;
}
cout<<"Stat::Insertion_latency_time.size() "<<Stat::Insertion_latency_time.size()<<endl;
for (int i = 0; i < Stat::Insertion_latency_time.size(); i++) {
cout<<Stat::Insertion_latency_time[i]._delay<<" "<<Stat::Insertion_latency_time[i]._time<<endl;
}
cout<<"Stat::Retry_Cnt.size()"<<Stat::Retry_Cnt.size()<<endl;
for (int i = 0; i < Stat::Retry_Cnt.size();i++) {
cout<<Stat::Retry_Cnt[i]._retry<<" "<<Stat::Retry_Cnt[i]._operation<<" "<<Stat::Retry_Cnt[i]._time<<" "<<Stat::Retry_Cnt[i]._delay<<endl;
}
for (int i = 0; i < Stat::Stat::DHT_Retry_time.size(); i++) {
cout<<Stat::Stat::DHT_Retry_time[i]._retry<<" "<<Stat::Stat::DHT_Retry_time[i]._operation<<" "<<Stat::Stat::DHT_Retry_time[i]._time<<endl;
}
*/
cout<<"Stat::Retry_Cnt.size()"<<Stat::Retry_Cnt.size()<<endl;
for (int i = 0; i < Stat::Retry_Cnt.size();i++) {
cout<<Stat::Retry_Cnt[i]._time<<" "<<Stat::Retry_Cnt[i]._retryUpdate<<" "<<Stat::Retry_Cnt[i]._retryQuery<<endl;
}
for (int i = 0; i < Stat::DHT_RetryCnt.size(); i++) {
cout<<Stat::DHT_RetryCnt[i]._time<<" "<<Stat::DHT_RetryCnt[i]._retryUpdate<<" "<<Stat::DHT_RetryCnt[i]._retryQuery<<endl;
}
Underlay::Inst()->PrintRetryStat();
Underlay::Inst()->PrintLatencyStat();
/*for (int i = 0; i < 10; i++) {
for(int j=0; j<10; j++)
cout<<i+j+1<<" ";
}*/
}
<commit_msg>fix a bug in add query/insertion event periodically<commit_after>#include "overnet.h"
#include "event.h"
#include "event_scheduler.h"
#include "network.h"
#include "util.h"
#include <iostream>
#include <string>
#include <sstream>
#include <cmath>
//default setting
vector<UINT32> Stat::Ping_per_node;
vector<UINT32> Stat::Storage_per_node; //GNRS storage overhead
vector<UINT32> Stat::Workload_per_node; //GNRS answer query overhead
vector<Query_Latency> Stat::Query_latency_time;
vector<Query_Latency> Stat::Insertion_latency_time;
vector<Retry_Count> Stat::Retry_Cnt;
vector<Retry_Count> Stat::DHT_RetryCnt;
vector<UINT32> Stat::Migration_per_node;
UINT32 Stat::Premature_joins=0;
UINT32 Stat::Premature_leaves=0;
FLOAT64 Settings::EndTime = 5000;
FLOAT64 Settings::TestThreshold = 0.1;
UINT32 Settings::TotalVirtualGUID = 1000000000;
UINT32 Settings::TotalActiveGUID = 10000; //
UINT32 Settings::NeighborSize =0; //full range neighbor size if undefined in command line, use default 2*ceil(K/2)
UINT32 Settings::DHTHop = 5;//estimated hops for a DHT path
UINT32 Settings::GNRS_K =5;
FLOAT64 Settings::OnOffSession =10;//session length for churn
UINT32 Settings::OnOffRounds=0;//0: leave, 1: leave+join, 2: leave+join+leave...
UINT32 Settings::ChurnHours =0;//# of consecutive hours of churn generation
UINT32 Settings::QueryHours =0;//# of hours query generation
UINT32 Settings::UpdateHours =0;//# of hours update generation
FLOAT64 Settings::QueryPerNode = 10000;
FLOAT64 Settings::UpdatePerNode = 1000;
string Settings::outFileName;
FLOAT64 Settings::ChurnPerNode=0.01;
/*!
* @brief Computes floor(log2(n))
* Works by finding position of MSB set.
* @returns -1 if n == 0.
*/
static inline INT32 FloorLog2(UINT32 n)
{
INT32 p = 0;
if (n == 0) return -1;
if (n & 0xffff0000) { p += 16; n >>= 16; }
if (n & 0x0000ff00) { p += 8; n >>= 8; }
if (n & 0x000000f0) { p += 4; n >>= 4; }
if (n & 0x0000000c) { p += 2; n >>= 2; }
if (n & 0x00000002) { p += 1; }
return p;
}
/*!
* @brief Computes floor(log2(n))
* Works by finding position of MSB set.
* @returns -1 if n == 0.
*/
static inline INT32 CeilLog2(UINT32 n)
{
return FloorLog2(n - 1) + 1;
}
void ParseArg(const char * argv)
{
string arg(argv);
if (arg.find("gnrs_k=") != string::npos)
{
stringstream ss (stringstream::in | stringstream::out);
ss <<arg.substr(8);
ss >>Settings::GNRS_K;
}
else if (arg.find("endtime=") != string::npos)
{
stringstream ss (stringstream::in | stringstream::out);
ss <<arg.substr(8);
ss >>Settings::EndTime;
}
else if (arg.find("testthreshold=") != string::npos)
{
stringstream ss (stringstream::in | stringstream::out);
ss <<arg.substr(14);
ss >>Settings::TestThreshold;
}
else if (arg.find("onoffsession=") != string::npos)
{
stringstream ss (stringstream::in | stringstream::out);
ss <<arg.substr(13);
ss >>Settings::OnOffSession;
}
else if (arg.find("onoffrounds=") != string::npos)
{
stringstream ss (stringstream::in | stringstream::out);
ss <<arg.substr(12);
ss >>Settings::OnOffRounds;
}
else if (arg.find("churnhours=") != string::npos)
{
stringstream ss (stringstream::in | stringstream::out);
ss <<arg.substr(11);
ss >>Settings::ChurnHours;
}
else if (arg.find("queryhours=") != string::npos)
{
stringstream ss (stringstream::in | stringstream::out);
ss <<arg.substr(11);
ss >>Settings::QueryHours;
}
else if (arg.find("updatehours=") != string::npos)
{
stringstream ss (stringstream::in | stringstream::out);
ss <<arg.substr(12);
ss >>Settings::UpdateHours;
}
else if (arg.find("querypernode=") != string::npos)
{
stringstream ss (stringstream::in | stringstream::out);
ss <<arg.substr(13);
ss >>Settings::QueryPerNode;
}
else if (arg.find("updatepernode=") != string::npos)
{
stringstream ss (stringstream::in | stringstream::out);
ss <<arg.substr(14);
ss >>Settings::UpdatePerNode;
}
else if (arg.find("totalactiveguid=") != string::npos)
{
stringstream ss (stringstream::in | stringstream::out);
ss <<arg.substr(16);
ss >>Settings::TotalActiveGUID;
}
else if (arg.find("neighborsize=") != string::npos)
{
stringstream ss (stringstream::in | stringstream::out);
ss <<arg.substr(13);
ss >>Settings::NeighborSize;
}
else if (arg.find("outfilename=") != string::npos)
{
stringstream ss (stringstream::in | stringstream::out);
ss <<arg.substr(12);
ss >>Settings::outFileName;
}
else if (arg.find("churnpernode=") != string::npos)
{
stringstream ss (stringstream::in | stringstream::out);
ss <<arg.substr(13);
ss >>Settings::ChurnPerNode;
}
}
int main(int argc, const char* argv[])
{
EventScheduler::Inst()->AddEvent(new DummyEvent());
cout <<"Initializing the network ..." <<endl;
//Underlay::CreateInst("2220IXP_Prov4_IXP2_m_route.txt", "2220IXP_Prov4_IXP2_m_ASInfo.txt");
//Underlay::CreateInst("2220SQ_Prov4_m_route.txt", "2220SQ_Prov4_m_ASInfo.txt");
//argv[1]: routeFileName, argv[2]:asInfoFileName
Underlay::CreateInst(argv[1], argv[2]);
if(argc>3){
for (int i = 3; i < argc; i++) {
ParseArg(argv[i]);
}
}
/*for (int i = 0; i < Underlay::Inst()->as_v.size(); i++) {
cout<<"for as "<<i<<" tier = "<<Underlay::Inst()->as_v[i]._asIdx<<endl;
for (int j = 0; j < Underlay::Inst()->as_v.size(); j++) {
cout<<"latency "<<i<<" to "<<j<<" = "<<Underlay::Inst()->getLatency(i,j)<<endl;
}
}*/
Underlay::Inst()->InitializeWorkload();
cout<<"total # nodes "<<Underlay::Inst()->global_node_table.size()<<endl;
//Settings::DHTHop = log10((FLOAT64)Underlay::Inst()->global_node_table.size());
/*
if(Settings::QueryHours > Settings::UpdateHours)
Settings::EndTime = Settings::QueryHours;
else
Settings::EndTime = Settings::UpdateHours;
*/
cout<<"Settings::"<<endl;
cout<<"Settings::EndTime="<<Settings::EndTime<<endl;
cout<<"Settings::TestThreshold="<<Settings::TestThreshold<<endl;
cout<<"Settings::TotalVirtualGUID="<<Settings::TotalVirtualGUID<<endl;
cout<<"Settings::TotalActiveGUID="<<Settings::TotalActiveGUID<<endl; //
cout<<"Settings::NeighborSize="<<Settings::NeighborSize<<endl; //full range neighbor size if undefined in command line, use default 2*ceil(K/2)
cout<<"Settings::DHTHop="<<Settings::DHTHop<<endl;//estimated hops for a DHT path
cout<<"Settings::GNRS_K="<<Settings::GNRS_K<<endl;
cout<<"Settings::OnOffSession="<<Settings::OnOffSession<<endl;//session length for churn
cout<<"Settings::OnOffRounds="<<Settings::OnOffRounds<<endl;//0: leave, 1: leave+join, 2: leave+join+leave...
cout<<"Settings::ChurnHours="<<Settings::ChurnHours<<endl;//# of consecutive hours of churn generation
cout<<"Settings::QueryHours="<<Settings::QueryHours<<endl;//# of hours query generation
cout<<"Settings::UpdateHours="<<Settings::UpdateHours<<endl;//# of hours update generation
cout<<"Settings::QueryPerNode="<<Settings::QueryPerNode<<endl;
cout<<"Settings::UpdatePerNode="<<Settings::UpdatePerNode<<endl;
cout<<"Settings::ChurnPerNode="<<Settings::ChurnPerNode<<endl;
/*
for (int i = 0; i < Underlay::Inst()->global_node_table.size(); i++) {
cout<<"for node "<<i <<" "<<Underlay::Inst()->global_node_table[i].getASIdx()<<endl;
}*/
for (UINT32 i = 0; i < Underlay::Inst()->GetNumOfNode(); i++) {
Stat::Migration_per_node.push_back(0);
Stat::Ping_per_node.push_back(0);
Stat::Storage_per_node.push_back(0);
Stat::Workload_per_node.push_back(0);
}
UINT32 totalNodes = Underlay::Inst()->global_node_table.size();
if(Settings::ChurnHours)
Underlay::Inst()->generateLeaveChurn(Settings::ChurnHours, Settings::ChurnPerNode*totalNodes,
Settings::OnOffSession, Settings::OnOffRounds);
/*
if(Settings::QueryHours)
Underlay::Inst()->generateWorkload(Settings::QueryHours,Settings::QueryPerNode*totalNodes,'Q');
if(Settings::UpdateHours)
Underlay::Inst()->generateWorkload(Settings::UpdateHours,Settings::UpdatePerNode*totalNodes,'U');
* */
cout <<"total queued jobs: " <<EventScheduler::Inst()->GetSize() <<" info: ";
while ( EventScheduler::Inst()->GetCurrentTime() <= Settings::EndTime
&& EventScheduler::Inst()->GetSize()>1){
Event * pevent = EventScheduler::Inst()->CurrentEvent();
//cout <<"queued jobs: " <<EventScheduler::Inst()->GetSize() <<" info: ";
pevent->PrintInfo();
if (pevent->Callback()){
delete pevent;
}
EventScheduler::Inst()->NextEvent();
}
/*
for (int i = 0; i < Stat::Query_latency_time.size(); i++) {
cout<<Stat::Query_latency_time[i]._delay<<" "<<Stat::Query_latency_time[i]._time<<endl;
}
cout<<"Stat::Insertion_latency_time.size() "<<Stat::Insertion_latency_time.size()<<endl;
for (int i = 0; i < Stat::Insertion_latency_time.size(); i++) {
cout<<Stat::Insertion_latency_time[i]._delay<<" "<<Stat::Insertion_latency_time[i]._time<<endl;
}
cout<<"Stat::Retry_Cnt.size()"<<Stat::Retry_Cnt.size()<<endl;
for (int i = 0; i < Stat::Retry_Cnt.size();i++) {
cout<<Stat::Retry_Cnt[i]._retry<<" "<<Stat::Retry_Cnt[i]._operation<<" "<<Stat::Retry_Cnt[i]._time<<" "<<Stat::Retry_Cnt[i]._delay<<endl;
}
for (int i = 0; i < Stat::Stat::DHT_Retry_time.size(); i++) {
cout<<Stat::Stat::DHT_Retry_time[i]._retry<<" "<<Stat::Stat::DHT_Retry_time[i]._operation<<" "<<Stat::Stat::DHT_Retry_time[i]._time<<endl;
}
*/
cout<<"Stat::Retry_Cnt.size()"<<Stat::Retry_Cnt.size()<<endl;
for (int i = 0; i < Stat::Retry_Cnt.size();i++) {
cout<<Stat::Retry_Cnt[i]._time<<" "<<Stat::Retry_Cnt[i]._retryUpdate<<" "<<Stat::Retry_Cnt[i]._retryQuery<<endl;
}
for (int i = 0; i < Stat::DHT_RetryCnt.size(); i++) {
cout<<Stat::DHT_RetryCnt[i]._time<<" "<<Stat::DHT_RetryCnt[i]._retryUpdate<<" "<<Stat::DHT_RetryCnt[i]._retryQuery<<endl;
}
Underlay::Inst()->PrintRetryStat();
Underlay::Inst()->PrintLatencyStat();
/*for (int i = 0; i < 10; i++) {
for(int j=0; j<10; j++)
cout<<i+j+1<<" ";
}*/
}
<|endoftext|> |
<commit_before>5ae7ecc8-2d16-11e5-af21-0401358ea401<commit_msg>5ae7ecc9-2d16-11e5-af21-0401358ea401<commit_after>5ae7ecc9-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>
#include <cstring>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <array>
#include "config.h"
#include <mpr/mpr_cpp.h>
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
using namespace mpr;
int received = 0;
int verbose = 1;
int terminate = 0;
class out_stream : public std::ostream {
public:
out_stream() : std::ostream (&buf) {}
private:
class null_out_buf : public std::streambuf {
public:
virtual std::streamsize xsputn (const char * s, std::streamsize n) {
return n;
}
virtual int overflow (int c) {
return 1;
}
};
null_out_buf buf;
};
out_stream null_out;
void handler(mpr_sig sig, mpr_sig_evt event, mpr_id instance, int length,
mpr_type type, const void *value, mpr_time t)
{
++received;
if (!verbose)
return;
const char *name = mpr_obj_get_prop_as_str(sig, MPR_PROP_NAME, NULL);
printf("\t\t\t\t\t | --> signal update: %s:%2lu got", name,
(unsigned long)instance);
if (value) {
switch (type) {
case MPR_INT32: {
int *v = (int*)value;
for (int i = 0; i < length; i++) {
printf(" %2d", v[i]);
}
break;
}
case MPR_FLT: {
float *v = (float*)value;
for (int i = 0; i < length; i++) {
printf(" %2f", v[i]);
}
break;
}
case MPR_DBL: {
double *v = (double*)value;
for (int i = 0; i < length; i++) {
printf(" %2f", v[i]);
}
break;
}
default:
break;
}
}
else {
printf(" ––––––––");
mpr_sig_release_inst(sig, instance, MPR_NOW);
}
printf("\n");
}
int main(int argc, char ** argv)
{
unsigned int i = 0, j, result = 0;
// process flags for -v verbose, -t terminate, -h help
for (i = 1; i < argc; i++) {
if (argv[i] && argv[i][0] == '-') {
int len = strlen(argv[i]);
for (j = 1; j < len; j++) {
switch (argv[i][j]) {
case 'h':
printf("testcpp.cpp: possible arguments "
"-q quiet (suppress output), "
"-t terminate automatically, "
"-h help\n");
return 1;
break;
case 'q':
verbose = 0;
break;
case 't':
terminate = 1;
break;
default:
break;
}
}
}
}
std::ostream& out = verbose ? std::cout : null_out;
Device dev("mydevice");
// make a copy of the device to check reference counting
// Device devcopy(dev);
Signal sig = dev.add_sig(MPR_DIR_IN, "in1", 1, MPR_FLT, "meters", 0, 0, 0,
handler);
dev.remove_sig(sig);
dev.add_sig(MPR_DIR_IN, "in2", 2, MPR_INT32, 0, 0, 0, 0, handler);
dev.add_sig(MPR_DIR_IN, "in3", 2, MPR_INT32, 0, 0, 0, 0, handler);
dev.add_sig(MPR_DIR_IN, "in4", 2, MPR_INT32, 0, 0, 0, 0, handler);
sig = dev.add_sig(MPR_DIR_OUT, "out1", 1, MPR_FLT, "na");
dev.remove_sig(sig);
sig = dev.add_sig(MPR_DIR_OUT, "out2", 3, MPR_DBL, "meters");
out << "waiting" << std::endl;
while (!dev.ready()) {
dev.poll(100);
}
out << "ready" << std::endl;
out << "device " << dev[MPR_PROP_NAME] << " ready..." << std::endl;
out << " ordinal: " << dev["ordinal"] << std::endl;
out << " id: " << dev[MPR_PROP_ID] << std::endl;
out << " interface: " << dev.graph().iface() << std::endl;
out << " bus url: " << dev.graph().address() << std::endl;
out << " port: " << dev["port"] << std::endl;
out << " num_inputs: " << dev.signals(MPR_DIR_IN).size() << std::endl;
out << " num_outputs: " << dev.signals(MPR_DIR_OUT).size() << std::endl;
out << " num_incoming_maps: " << dev.signals().maps(MPR_DIR_IN).size()
<< std::endl;
out << " num_outgoing_maps: " << dev.signals().maps(MPR_DIR_OUT).size()
<< std::endl;
int value[] = {1,2,3,4,5,6};
dev.set_prop("foo", 6, value);
out << "foo: " << dev["foo"] << std::endl;
// test std::array<std::string>
out << "set and get std::array<std::string>: ";
std::array<std::string, 3> a1 = {{"one", "two", "three"}};
dev.set_prop("foo", a1);
const std::array<std::string, 8> a2 = dev["foo"];
for (i = 0; i < 8; i++)
out << a2[i] << " ";
out << std::endl;
// test std::array<const char*>
out << "set and get std::array<const char*>: ";
std::array<const char*, 3> a3 = {{"four", "five", "six"}};
dev.set_prop("foo", a3);
std::array<const char*, 3> a4 = dev["foo"];
for (i = 0; i < a4.size(); i++)
out << a4[i] << " ";
out << std::endl;
// test plain array of const char*
out << "set and get const char*[]: ";
const char* a5[3] = {"seven", "eight", "nine"};
dev.set_prop("foo", 3, a5);
const char **a6 = dev["foo"];
out << a6[0] << " " << a6[1] << " " << a6[2] << std::endl;
// test plain array of float
out << "set and get float[]: ";
float a7[3] = {7.7f, 8.8f, 9.9f};
dev.set_prop("foo", 3, a7);
const float *a8 = dev["foo"];
out << a8[0] << " " << a8[1] << " " << a8[2] << std::endl;
// test std::vector<const char*>
out << "set and get std::vector<const char*>: ";
const char *a9[3] = {"ten", "eleven", "twelve"};
std::vector<const char*> v1(a9, std::end(a9));
dev.set_prop("foo", v1);
std::vector<const char*> v2 = dev["foo"];
out << "foo: ";
for (std::vector<const char*>::iterator it = v2.begin(); it != v2.end(); ++it)
out << *it << " ";
out << std::endl;
// test std::vector<std::string>
out << "set and get std::vector<std::string>: ";
const char *a10[3] = {"thirteen", "14", "15"};
std::vector<std::string> v3(a10, std::end(a10));
dev.set_prop("foo", v3);
std::vector<std::string> v4 = dev["foo"];
out << "foo: ";
for (std::vector<std::string>::iterator it = v4.begin(); it != v4.end(); ++it)
out << *it << " ";
out << std::endl;
Property p("temp", "tempstring");
dev.set_prop(p);
out << p.key << ": " << p << std::endl;
dev.remove_prop("foo");
out << "foo: " << dev["foo"] << " (should be 0x0)" << std::endl;
out << "signal: " << sig << std::endl;
Signal::List qsig = dev.signals(MPR_DIR_IN);
qsig.begin();
for (; qsig != qsig.end(); ++qsig) {
out << " input: " << *qsig << std::endl;
}
Graph graph(MPR_OBJ);
Map map(dev.signals(MPR_DIR_OUT)[0], dev.signals(MPR_DIR_IN)[1]);
map.set_prop(MPR_PROP_EXPR, "y=x[0:1]+123");
map.push();
while (!map.ready()) {
dev.poll(100);
}
std::vector <double> v(3);
while (i++ < 100) {
dev.poll(10);
graph.poll();
v[i%3] = i;
sig.set_value(v);
}
// try retrieving linked devices
out << "devices linked to " << dev << ":" << std::endl;
Device::List foo = dev[MPR_PROP_LINKED];
for (; foo != foo.end(); foo++) {
out << " " << *foo << std::endl;
}
// try combining queries
out << "devices with name matching 'my*' AND >=0 inputs" << std::endl;
Device::List qdev = graph.devices();
qdev.filter(Property(MPR_PROP_NAME, "my*"), MPR_OP_EQ);
qdev.filter(Property(MPR_PROP_NUM_SIGS_IN, 0), MPR_OP_GTE);
for (; qdev != qdev.end(); qdev++) {
out << " " << *qdev << " (" << (*qdev)[MPR_PROP_NUM_SIGS_IN]
<< " inputs)" << std::endl;
}
// check graph records
out << "graph records:" << std::endl;
for (const Device d : graph.devices()) {
out << " device: " << d << std::endl;
for (Signal s : d.signals(MPR_DIR_IN)) {
out << " input: " << s << std::endl;
}
for (Signal s : d.signals(MPR_DIR_OUT)) {
out << " output: " << s << std::endl;
}
}
for (Map m : graph.maps()) {
out << " map: " << m << std::endl;
}
// test API for signal instances
out << "testing instances API" << std::endl;
int num_inst = 10;
mpr::Signal multisend = dev.add_sig(MPR_DIR_OUT, "multisend", 1, MPR_FLT,
0, 0, 0, &num_inst, 0, 0);
mpr::Signal multirecv = dev.add_sig(MPR_DIR_IN, "multirecv", 1, MPR_FLT,
0, 0, 0, &num_inst, handler, MPR_SIG_UPDATE);
multisend.set_prop(MPR_PROP_STEAL_MODE, (int)MPR_STEAL_OLDEST);
multirecv.set_prop(MPR_PROP_STEAL_MODE, (int)MPR_STEAL_OLDEST);
mpr::Map map2(multisend, multirecv);
map2.push();
while (!map2.ready()) {
dev.poll(100);
}
unsigned long id;
for (int i = 0; i < 200; i++) {
dev.poll(100);
id = (rand() % 10) + 5;
switch (rand() % 5) {
case 0:
// try to destroy an instance
if (verbose)
printf("\t\t Retiring instance %2lu --> |\n",
(unsigned long)id);
multisend.instance(id).release();
break;
default:
// try to update an instance
float v = (rand() % 10) * 1.0f;
multisend.instance(id).set_value(v);
if (verbose)
printf("Sender instance %2lu updated to %2f --> |\n",
(unsigned long)id, v);
break;
}
}
// test some time manipulation
Time t1(10, 200);
Time t2(10, 300);
if (t1 < t2)
out << "t1 is less than t2" << std::endl;
t1 += t2;
if (t1 >= t2)
out << "(t1 + t2) is greater then or equal to t2" << std::endl;
printf("\r..................................................Test %s\x1B[0m.\n",
result ? "\x1B[31mFAILED" : "\x1B[32mPASSED");
return result;
}
<commit_msg>Fix for testcpp non-verbose mode.<commit_after>
#include <cstring>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <array>
#include "config.h"
#include <mpr/mpr_cpp.h>
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
using namespace mpr;
int received = 0;
int verbose = 1;
int terminate = 0;
class out_stream : public std::ostream {
public:
out_stream() : std::ostream (&buf) {}
private:
class null_out_buf : public std::streambuf {
public:
virtual std::streamsize xsputn (const char * s, std::streamsize n) {
return n;
}
virtual int overflow (int c) {
return 1;
}
};
null_out_buf buf;
};
out_stream null_out;
void handler(mpr_sig sig, mpr_sig_evt event, mpr_id instance, int length,
mpr_type type, const void *value, mpr_time t)
{
++received;
if (verbose) {
const char *name = mpr_obj_get_prop_as_str(sig, MPR_PROP_NAME, NULL);
printf("\t\t\t\t\t | --> signal update: %s:%2lu got", name,
(unsigned long)instance);
}
if (!value) {
if (verbose)
printf(" ––––––––\n");
mpr_sig_release_inst(sig, instance, MPR_NOW);
return;
}
else if (!verbose)
return;
switch (type) {
case MPR_INT32: {
int *v = (int*)value;
for (int i = 0; i < length; i++) {
printf(" %2d", v[i]);
}
break;
}
case MPR_FLT: {
float *v = (float*)value;
for (int i = 0; i < length; i++) {
printf(" %2f", v[i]);
}
break;
}
case MPR_DBL: {
double *v = (double*)value;
for (int i = 0; i < length; i++) {
printf(" %2f", v[i]);
}
break;
}
default:
break;
}
printf("\n");
}
int main(int argc, char ** argv)
{
unsigned int i = 0, j, result = 0;
// process flags for -v verbose, -t terminate, -h help
for (i = 1; i < argc; i++) {
if (argv[i] && argv[i][0] == '-') {
int len = strlen(argv[i]);
for (j = 1; j < len; j++) {
switch (argv[i][j]) {
case 'h':
printf("testcpp.cpp: possible arguments "
"-q quiet (suppress output), "
"-t terminate automatically, "
"-h help\n");
return 1;
break;
case 'q':
verbose = 0;
break;
case 't':
terminate = 1;
break;
default:
break;
}
}
}
}
std::ostream& out = verbose ? std::cout : null_out;
Device dev("mydevice");
// make a copy of the device to check reference counting
Device devcopy(dev);
Signal sig = dev.add_sig(MPR_DIR_IN, "in1", 1, MPR_FLT, "meters", 0, 0, 0,
handler);
dev.remove_sig(sig);
dev.add_sig(MPR_DIR_IN, "in2", 2, MPR_INT32, 0, 0, 0, 0, handler);
dev.add_sig(MPR_DIR_IN, "in3", 2, MPR_INT32, 0, 0, 0, 0, handler);
dev.add_sig(MPR_DIR_IN, "in4", 2, MPR_INT32, 0, 0, 0, 0, handler);
sig = dev.add_sig(MPR_DIR_OUT, "out1", 1, MPR_FLT, "na");
dev.remove_sig(sig);
sig = dev.add_sig(MPR_DIR_OUT, "out2", 3, MPR_DBL, "meters");
out << "waiting" << std::endl;
while (!dev.ready()) {
dev.poll(100);
}
out << "ready" << std::endl;
out << "device " << dev[MPR_PROP_NAME] << " ready..." << std::endl;
out << " ordinal: " << dev["ordinal"] << std::endl;
out << " id: " << dev[MPR_PROP_ID] << std::endl;
out << " interface: " << dev.graph().iface() << std::endl;
out << " bus url: " << dev.graph().address() << std::endl;
out << " port: " << dev["port"] << std::endl;
out << " num_inputs: " << dev.signals(MPR_DIR_IN).size() << std::endl;
out << " num_outputs: " << dev.signals(MPR_DIR_OUT).size() << std::endl;
out << " num_incoming_maps: " << dev.signals().maps(MPR_DIR_IN).size()
<< std::endl;
out << " num_outgoing_maps: " << dev.signals().maps(MPR_DIR_OUT).size()
<< std::endl;
int value[] = {1,2,3,4,5,6};
dev.set_prop("foo", 6, value);
out << "foo: " << dev["foo"] << std::endl;
// test std::array<std::string>
out << "set and get std::array<std::string>: ";
std::array<std::string, 3> a1 = {{"one", "two", "three"}};
dev.set_prop("foo", a1);
const std::array<std::string, 8> a2 = dev["foo"];
for (i = 0; i < 8; i++)
out << a2[i] << " ";
out << std::endl;
// test std::array<const char*>
out << "set and get std::array<const char*>: ";
std::array<const char*, 3> a3 = {{"four", "five", "six"}};
dev.set_prop("foo", a3);
std::array<const char*, 3> a4 = dev["foo"];
for (i = 0; i < a4.size(); i++)
out << a4[i] << " ";
out << std::endl;
// test plain array of const char*
out << "set and get const char*[]: ";
const char* a5[3] = {"seven", "eight", "nine"};
dev.set_prop("foo", 3, a5);
const char **a6 = dev["foo"];
out << a6[0] << " " << a6[1] << " " << a6[2] << std::endl;
// test plain array of float
out << "set and get float[]: ";
float a7[3] = {7.7f, 8.8f, 9.9f};
dev.set_prop("foo", 3, a7);
const float *a8 = dev["foo"];
out << a8[0] << " " << a8[1] << " " << a8[2] << std::endl;
// test std::vector<const char*>
out << "set and get std::vector<const char*>: ";
const char *a9[3] = {"ten", "eleven", "twelve"};
std::vector<const char*> v1(a9, std::end(a9));
dev.set_prop("foo", v1);
std::vector<const char*> v2 = dev["foo"];
out << "foo: ";
for (std::vector<const char*>::iterator it = v2.begin(); it != v2.end(); ++it)
out << *it << " ";
out << std::endl;
// test std::vector<std::string>
out << "set and get std::vector<std::string>: ";
const char *a10[3] = {"thirteen", "14", "15"};
std::vector<std::string> v3(a10, std::end(a10));
dev.set_prop("foo", v3);
std::vector<std::string> v4 = dev["foo"];
out << "foo: ";
for (std::vector<std::string>::iterator it = v4.begin(); it != v4.end(); ++it)
out << *it << " ";
out << std::endl;
Property p("temp", "tempstring");
dev.set_prop(p);
out << p.key << ": " << p << std::endl;
dev.remove_prop("foo");
out << "foo: " << dev["foo"] << " (should be 0x0)" << std::endl;
out << "signal: " << sig << std::endl;
Signal::List qsig = dev.signals(MPR_DIR_IN);
qsig.begin();
for (; qsig != qsig.end(); ++qsig) {
out << " input: " << *qsig << std::endl;
}
Graph graph(MPR_OBJ);
Map map(dev.signals(MPR_DIR_OUT)[0], dev.signals(MPR_DIR_IN)[1]);
map.set_prop(MPR_PROP_EXPR, "y=x[0:1]+123");
map.push();
while (!map.ready()) {
dev.poll(100);
}
std::vector <double> v(3);
while (i++ < 100) {
dev.poll(10);
graph.poll();
v[i%3] = i;
sig.set_value(v);
}
// try retrieving linked devices
out << "devices linked to " << dev << ":" << std::endl;
Device::List foo = dev[MPR_PROP_LINKED];
for (; foo != foo.end(); foo++) {
out << " " << *foo << std::endl;
}
// try combining queries
out << "devices with name matching 'my*' AND >=0 inputs" << std::endl;
Device::List qdev = graph.devices();
qdev.filter(Property(MPR_PROP_NAME, "my*"), MPR_OP_EQ);
qdev.filter(Property(MPR_PROP_NUM_SIGS_IN, 0), MPR_OP_GTE);
for (; qdev != qdev.end(); qdev++) {
out << " " << *qdev << " (" << (*qdev)[MPR_PROP_NUM_SIGS_IN]
<< " inputs)" << std::endl;
}
// check graph records
out << "graph records:" << std::endl;
for (const Device d : graph.devices()) {
out << " device: " << d << std::endl;
for (Signal s : d.signals(MPR_DIR_IN)) {
out << " input: " << s << std::endl;
}
for (Signal s : d.signals(MPR_DIR_OUT)) {
out << " output: " << s << std::endl;
}
}
for (Map m : graph.maps()) {
out << " map: " << m << std::endl;
}
// test API for signal instances
out << "testing instances API" << std::endl;
int num_inst = 10;
mpr::Signal multisend = dev.add_sig(MPR_DIR_OUT, "multisend", 1, MPR_FLT,
0, 0, 0, &num_inst, 0, 0);
mpr::Signal multirecv = dev.add_sig(MPR_DIR_IN, "multirecv", 1, MPR_FLT,
0, 0, 0, &num_inst, handler, MPR_SIG_UPDATE);
multisend.set_prop(MPR_PROP_STEAL_MODE, (int)MPR_STEAL_OLDEST);
multirecv.set_prop(MPR_PROP_STEAL_MODE, (int)MPR_STEAL_OLDEST);
mpr::Map map2(multisend, multirecv);
map2.push();
while (!map2.ready()) {
dev.poll(100);
}
unsigned long id;
for (int i = 0; i < 200; i++) {
dev.poll(100);
id = (rand() % 10) + 5;
switch (rand() % 5) {
case 0:
// try to destroy an instance
if (verbose)
printf("\t\t Retiring instance %2lu --> |\n",
(unsigned long)id);
multisend.instance(id).release();
break;
default:
// try to update an instance
float v = (rand() % 10) * 1.0f;
multisend.instance(id).set_value(v);
if (verbose)
printf("Sender instance %2lu updated to %2f --> |\n",
(unsigned long)id, v);
break;
}
}
// test some time manipulation
Time t1(10, 200);
Time t2(10, 300);
if (t1 < t2)
out << "t1 is less than t2" << std::endl;
t1 += t2;
if (t1 >= t2)
out << "(t1 + t2) is greater then or equal to t2" << std::endl;
printf("\r..................................................Test %s\x1B[0m.\n",
result ? "\x1B[31mFAILED" : "\x1B[32mPASSED");
return result;
}
<|endoftext|> |
<commit_before>9a3cd254-35ca-11e5-85e2-6c40088e03e4<commit_msg>9a43c32e-35ca-11e5-adab-6c40088e03e4<commit_after>9a43c32e-35ca-11e5-adab-6c40088e03e4<|endoftext|> |
<commit_before>809e91e0-2d15-11e5-af21-0401358ea401<commit_msg>809e91e1-2d15-11e5-af21-0401358ea401<commit_after>809e91e1-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>e3e263c8-585a-11e5-898d-6c40088e03e4<commit_msg>e3e9f93a-585a-11e5-bb69-6c40088e03e4<commit_after>e3e9f93a-585a-11e5-bb69-6c40088e03e4<|endoftext|> |
<commit_before>4d0f072e-2748-11e6-9a4d-e0f84713e7b8<commit_msg>This'll fix that<commit_after>4d2a9207-2748-11e6-b5c0-e0f84713e7b8<|endoftext|> |
<commit_before>9101ada8-2d14-11e5-af21-0401358ea401<commit_msg>9101ada9-2d14-11e5-af21-0401358ea401<commit_after>9101ada9-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>2e24fd80-2f67-11e5-86b3-6c40088e03e4<commit_msg>2e2b8762-2f67-11e5-9387-6c40088e03e4<commit_after>2e2b8762-2f67-11e5-9387-6c40088e03e4<|endoftext|> |
<commit_before>#include <cstdio>
#include <list>
#include <vector>
#include <stack>
#define WHITE -1
typedef std::vector< std::list<int> > graph;
typedef std::list<int>::iterator iter;
int output1 = 0, output2 = 0, output3 = 0;
void DFS_visit(graph &g, int v, int color[], std::stack<int> &stack) {
color[v] = !WHITE;
for (iter vIter = g[v].begin(); vIter != g[v].end(); vIter++) {
int u = *vIter;
if (color[u] == WHITE) {
DFS_visit(g, u, color, stack);
}
}
stack.push(v);
}
int DFS_visit2(graph &g, int u, int color[], bool &out_edge) {
int size = 1;
color[u] = output1;
for (iter vIter = g[u].begin(); vIter != g[u].end(); vIter++) {
if (color[*vIter] == WHITE)
size += DFS_visit2(g, *vIter, color, out_edge);
else if (color[*vIter] != output1)
out_edge = true;
}
return size;
}
void create_transpose_graph(graph &g, graph &t) {
for (int i = 0; i < (int) g.size(); i++)
for (iter vIter = g[i].begin(); vIter != g[i].end(); vIter++)
t[*vIter].push_back(i);
}
void solve(graph &g) {
int V = g.size();
int color[V], i;
std::stack<int> stack;
graph t(V);
create_transpose_graph(g, t);
for (i = 0; i < V; i++) { color[i] = WHITE; }
for (i = 0; i < V; i++) {
if (color[i] == WHITE) {
DFS_visit(t, i, color, stack);
}
}
for (i = 0; i < V; i++) { color[i] = WHITE; }
while (stack.size() > 0) {
int u = stack.top();
stack.pop();
if (color[u] == WHITE) {
bool out_edge = false;
int size = DFS_visit2(g, u, color, out_edge);
if (!out_edge) output3++;
output2 = std::max(size, output2);
output1++;
}
}
}
int main() {
int V, E, v1, v2;
scanf("%d %d%*c", &V, &E);
graph g(V);
for (int i = 0; i < E; i++) {
scanf("%d %d%*c", &v1, &v2);
g[v1-1].push_back(v2-1);
}
solve(g);
printf("%d\n%d\n%d\n", output1, output2, output3);
return 0;
}
<commit_msg>reduced source size<commit_after>#include <cstdio>
#include <list>
#include <vector>
#include <stack>
#define WHITE -1
typedef std::vector< std::list<int> > graph;
typedef std::list<int>::iterator iter;
int output1 = 0, output2 = 0, output3 = 0;
void DFS_visit(graph &g, int v, int color[], std::stack<int> &stack) {
color[v] = !WHITE;
for (iter vIter = g[v].begin(); vIter != g[v].end(); vIter++)
if (color[*vIter] == WHITE)
DFS_visit(g, *vIter, color, stack);
stack.push(v);
}
int DFS_visit2(graph &g, int u, int color[], bool &out_edge) {
int size = 1;
color[u] = output1;
for (iter vIter = g[u].begin(); vIter != g[u].end(); vIter++)
if (color[*vIter] == WHITE)
size += DFS_visit2(g, *vIter, color, out_edge);
else if (color[*vIter] != output1)
out_edge = true;
return size;
}
void create_transpose_graph(graph &g, graph &t) {
for (int i = 0; i < (int) g.size(); i++)
for (iter vIter = g[i].begin(); vIter != g[i].end(); vIter++)
t[*vIter].push_back(i);
}
void solve(graph &g) {
int V = g.size();
int color[V], i;
std::stack<int> stack;
graph t(V);
create_transpose_graph(g, t);
for (i = 0; i < V; i++) color[i] = WHITE;
for (i = 0; i < V; i++)
if (color[i] == WHITE)
DFS_visit(t, i, color, stack);
for (i = 0; i < V; i++) color[i] = WHITE;
while (stack.size() > 0) {
int u = stack.top();
stack.pop();
if (color[u] == WHITE) {
bool out_edge = false;
int size = DFS_visit2(g, u, color, out_edge);
if (!out_edge) output3++;
output2 = std::max(size, output2);
output1++;
}
}
}
int main() {
int V, E, v1, v2;
scanf("%d %d%*c", &V, &E);
graph g(V);
for (int i = 0; i < E; i++) {
scanf("%d %d%*c", &v1, &v2);
g[v1-1].push_back(v2-1);
}
solve(g);
printf("%d\n%d\n%d\n", output1, output2, output3);
return 0;
}
<|endoftext|> |
<commit_before>c1bd23a8-35ca-11e5-b78c-6c40088e03e4<commit_msg>c1c3c582-35ca-11e5-a8c6-6c40088e03e4<commit_after>c1c3c582-35ca-11e5-a8c6-6c40088e03e4<|endoftext|> |
<commit_before>059b25f8-2f67-11e5-bd1e-6c40088e03e4<commit_msg>05a1c5de-2f67-11e5-b4e1-6c40088e03e4<commit_after>05a1c5de-2f67-11e5-b4e1-6c40088e03e4<|endoftext|> |
<commit_before>809e91d3-2d15-11e5-af21-0401358ea401<commit_msg>809e91d4-2d15-11e5-af21-0401358ea401<commit_after>809e91d4-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>a19cc2d4-327f-11e5-a7db-9cf387a8033e<commit_msg>a1a259c2-327f-11e5-ac56-9cf387a8033e<commit_after>a1a259c2-327f-11e5-ac56-9cf387a8033e<|endoftext|> |
<commit_before>250e0be6-2d3f-11e5-9396-c82a142b6f9b<commit_msg>25633e4a-2d3f-11e5-9901-c82a142b6f9b<commit_after>25633e4a-2d3f-11e5-9901-c82a142b6f9b<|endoftext|> |
<commit_before>7e7919f5-2d15-11e5-af21-0401358ea401<commit_msg>7e7919f6-2d15-11e5-af21-0401358ea401<commit_after>7e7919f6-2d15-11e5-af21-0401358ea401<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.