text
stringlengths 54
60.6k
|
---|
<commit_before>#include <cstdlib>
#include <vector>
#include <fstream>
#include <sstream>
#include <experimental/optional>
#include "windows.h"
#include "Objbase.h"
#include "Shlobj.h"
using namespace std;
using namespace std::experimental;
TCHAR select_directory_path[MAX_PATH];
// TODO: A lot of error detection and handling is missing.
class COM {
public:
COM() {
if (CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED) != S_OK)
throw runtime_error("Failed to initialize COM.");
}
~COM() {
CoUninitialize();
}
};
class file_search {
public:
WIN32_FIND_DATA find_data;
HANDLE handle;
file_search(string search_path) : find_data({}) {
handle = FindFirstFile(search_path.c_str(), &find_data);
}
~file_search() {
if (handle != nullptr) FindClose(handle);
}
bool find_next() {
return FindNextFile(handle, &find_data);
}
inline const char* found_filename() { return find_data.cFileName; };
};
optional<string> select_directory() {
BROWSEINFO browseinfo {};
browseinfo.pszDisplayName = select_directory_path;
browseinfo.lpszTitle = "Please select directory containing the bin files.";
browseinfo.ulFlags = BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE | BIF_NONEWFOLDERBUTTON;
PIDLIST_ABSOLUTE idlist = SHBrowseForFolder(&browseinfo);
if (idlist == nullptr) {
return {};
}
else {
if (!SHGetPathFromIDList(idlist, select_directory_path)) {
CoTaskMemFree(idlist);
throw runtime_error("SHGetPathFromIDList failed.");
};
CoTaskMemFree(idlist);
return string(select_directory_path);
}
}
vector<string> find_bin_files(string directory) {
vector<string> result;
file_search fs(directory + "\\*.bin");
if (GetLastError() != ERROR_FILE_NOT_FOUND) {
result.emplace_back(fs.found_filename());
while (fs.find_next()) {
result.emplace_back(fs.found_filename());
}
}
return result;
}
string generate_cuesheet(vector<string> files) {
stringstream ss;
if (files.size() > 0) {
ss << "FILE \"" << files.at(0) << "\" BINARY\n";
ss << " TRACK 01 MODE2/2352\n";
ss << " INDEX 01 00:00:00\n";
for(size_t track = 1; track < files.size(); ++track) {
ss << "FILE \"" << files.at(track) << "\" BINARY\n";
ss << " TRACK ";
if (track < 10) ss << '0';
ss << track << " AUDIO\n";
ss << " INDEX 00 00:00:00\n";
ss << " INDEX 01 00:02:00\n";
};
}
return ss.str();
}
string generate_cuesheet_filename(vector<string> files) {
return "Cuesheet.cue";
}
bool file_exists(string filename) {
file_search fs(filename);
auto error_code = GetLastError();
if (error_code == ERROR_FILE_NOT_FOUND) return false;
if (error_code == ERROR_NO_MORE_FILES) return true;
throw error_code;
}
int main(int argc, const char* argv[]) {
try {
COM com;
auto dir = select_directory();
if (dir) {
auto files = find_bin_files(*dir);
if (files.empty()) throw runtime_error("No bin files found in the selected directory.");
auto cuesheet = generate_cuesheet(files);
string filename = generate_cuesheet_filename(files);
string full_filename = *dir + '\\' + filename;
bool write_file = true;
if (file_exists(full_filename) &&
(MessageBox(nullptr, "A cuesheet file already exists. Do you want to overwrite it?", "File exists", MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON2) == IDNO)) {
write_file = false;
}
if (write_file) {
ofstream file(full_filename.c_str(), ios::out);
file << cuesheet.c_str();
}
}
}
catch (const exception& e) {
MessageBox(nullptr, e.what(), "Error", MB_OK | MB_ICONERROR);
return EXIT_FAILURE;
}
catch (DWORD error_code) {
LPSTR buffer = nullptr;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr,
error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<LPSTR>(&buffer), 0, nullptr);
MessageBox(nullptr, buffer, "Error", MB_OK | MB_ICONERROR);
LocalFree(buffer);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>Add save dialog to select cuesheet filename<commit_after>#include <cstdlib>
#include <vector>
#include <fstream>
#include <sstream>
#include <experimental/optional>
#include "windows.h"
#include "Objbase.h"
#include "Shlobj.h"
using namespace std;
using namespace std::experimental;
TCHAR select_directory_path[MAX_PATH];
// TODO: A lot of error detection and handling is missing.
class COM {
public:
COM() {
if (CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED) != S_OK)
throw runtime_error("Failed to initialize COM.");
}
~COM() {
CoUninitialize();
}
};
class file_search {
public:
WIN32_FIND_DATA find_data;
HANDLE handle;
file_search(string search_path) : find_data({}) {
handle = FindFirstFile(search_path.c_str(), &find_data);
}
~file_search() {
if (handle != nullptr) FindClose(handle);
}
bool find_next() {
return FindNextFile(handle, &find_data);
}
inline const char* found_filename() { return find_data.cFileName; };
};
optional<string> select_directory() {
BROWSEINFO browseinfo {};
browseinfo.pszDisplayName = select_directory_path;
browseinfo.lpszTitle = "Please select directory containing the bin files.";
browseinfo.ulFlags = BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE | BIF_NONEWFOLDERBUTTON;
PIDLIST_ABSOLUTE idlist = SHBrowseForFolder(&browseinfo);
if (idlist == nullptr) {
return {};
}
else {
if (!SHGetPathFromIDList(idlist, select_directory_path)) {
CoTaskMemFree(idlist);
throw runtime_error("SHGetPathFromIDList failed.");
};
CoTaskMemFree(idlist);
return string(select_directory_path);
}
}
vector<string> find_bin_files(string directory) {
vector<string> result;
file_search fs(directory + "\\*.bin");
if (GetLastError() != ERROR_FILE_NOT_FOUND) {
result.emplace_back(fs.found_filename());
while (fs.find_next()) {
result.emplace_back(fs.found_filename());
}
}
return result;
}
string generate_cuesheet(vector<string> files) {
stringstream ss;
if (files.size() > 0) {
ss << "FILE \"" << files.at(0) << "\" BINARY\n";
ss << " TRACK 01 MODE2/2352\n";
ss << " INDEX 01 00:00:00\n";
for(size_t track = 1; track < files.size(); ++track) {
ss << "FILE \"" << files.at(track) << "\" BINARY\n";
ss << " TRACK ";
if (track < 10) ss << '0';
ss << track << " AUDIO\n";
ss << " INDEX 00 00:00:00\n";
ss << " INDEX 01 00:02:00\n";
};
}
return ss.str();
}
optional<string> get_cuesheet_filename(string directory, vector<string> files) {
TCHAR filename[MAX_PATH];
filename[0] = 0;
OPENFILENAME save_dialog {};
save_dialog.lStructSize = sizeof(save_dialog);
save_dialog.lpstrFilter = "Cuesheet files (*.cue)\0*.cue\0All files\0*";
save_dialog.lpstrDefExt = "cue";
save_dialog.lpstrFile = filename;
save_dialog.lpstrInitialDir = directory.c_str();
save_dialog.nMaxFile = MAX_PATH;
save_dialog.Flags = OFN_DONTADDTORECENT | OFN_ENABLESIZING | OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST;
save_dialog.FlagsEx = OFN_EX_NOPLACESBAR;
if (GetSaveFileName(&save_dialog)) {
return string(filename);
}
else {
return {};
}
}
bool file_exists(string filename) {
file_search fs(filename);
auto error_code = GetLastError();
if (error_code == ERROR_FILE_NOT_FOUND) return false;
if (error_code == ERROR_NO_MORE_FILES) return true;
throw error_code;
}
int main(int argc, const char* argv[]) {
try {
COM com;
auto dir = select_directory();
if (dir) {
auto files = find_bin_files(*dir);
if (files.empty()) throw runtime_error("No bin files found in the selected directory.");
auto cuesheet = generate_cuesheet(files);
auto filename = get_cuesheet_filename(*dir, files);
if (filename) {
ofstream file(filename->c_str(), ios::out);
file << cuesheet.c_str();
}
}
}
catch (const exception& e) {
MessageBox(nullptr, e.what(), "Error", MB_OK | MB_ICONERROR);
return EXIT_FAILURE;
}
catch (DWORD error_code) {
LPSTR buffer = nullptr;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr,
error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<LPSTR>(&buffer), 0, nullptr);
MessageBox(nullptr, buffer, "Error", MB_OK | MB_ICONERROR);
LocalFree(buffer);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include "compiler.h"
#include "mswin.h"
#include "glinit.h"
#include "model.h"
#include "cmdline.h"
#include <windowsx.h>
// #include "tinyscheme-config.h"
// #include <scheme-private.h>
// #include <scheme.h>
#include <cstdint>
namespace usr {
// Program name.
static const TCHAR * const program_name = TEXT ("Polymorph");
static const TCHAR * const message =
TEXT ("And the ratios of their numbers, motions, and ")
TEXT ("other properties, everywhere God, as far as ")
TEXT ("necessity allowed or gave consent, has exactly ")
TEXT ("perfected, and harmonised in due proportion.");
// TEXT ("\n\nThis screensaver includes TinyScheme, developed by Dimitrios ")
// TEXT ("Souflis and licensed under the Modified BSD License. ")
// TEXT ("See \"tinyscheme/COPYING.txt\" for details.");
}
inline std::uint64_t qpc ()
{
LARGE_INTEGER t;
::QueryPerformanceCounter (& t);
return t.QuadPart;
}
struct window_struct_t
{
model_t model;
POINT initial_cursor_position;
run_mode_t mode;
};
LRESULT CALLBACK InitWndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
LRESULT CALLBACK MainWndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
HGLRC setup_opengl_context (HWND hwnd);
// Called by custom_entry_point (below).
int custom_main (HINSTANCE hInstance)
{
// Read command line arguments.
HWND parent = NULL;
run_mode_t mode = parse_command_line (::GetCommandLine (), & parent);
if (mode == configure) {
::MessageBox (NULL, usr::message, usr::program_name, MB_OK | MB_ICONASTERISK);
return 0;
}
// Placement and window style of the main window.
RECT rect;
DWORD style;
DWORD ex_style = 0;
if (mode == embedded) {
style = WS_CHILD | WS_VISIBLE;
::GetClientRect (parent, & rect); // 0, 0, width, height
}
else {
style = WS_POPUP | WS_VISIBLE;
if (mode == fullscreen) ex_style = WS_EX_TOPMOST;
rect.left = ::GetSystemMetrics (SM_XVIRTUALSCREEN);
rect.top = ::GetSystemMetrics (SM_YVIRTUALSCREEN);
rect.right = ::GetSystemMetrics (SM_CXVIRTUALSCREEN); // actually width, not right
rect.bottom = ::GetSystemMetrics (SM_CYVIRTUALSCREEN); // actually height, not bottom
}
window_struct_t ws ALIGNED16;
ws.mode = mode;
// Create a window with an OpenGL rendering context.
// To obtain a proper OpenGL pixel format, we need to call wglChoosePixelFormatARB, but
// first we must obtain the address of that function by calling using wglGetProcAddress,
// which requires that an OpenGL rendering context is current, which requires a device
// context that supports OpenGL, which requires a window with an OpenGL pixel format.
// Bootstrap the process with a legacy OpenGL pixel format. According to MSDN,
// "Once a window's pixel format is set, it cannot be changed", so the window
// and associated resources are of no further use and are destroyed here.
// Create the dummy window. See InitWndProc.
// Note this window does not survive creation.
WNDCLASS init_wc;
::ZeroMemory (& init_wc, sizeof init_wc);
init_wc.hInstance = hInstance;
init_wc.lpfnWndProc = & InitWndProc;
init_wc.lpszClassName = TEXT ("GLinit");
ATOM init_wc_atom = ::RegisterClass (& init_wc);
::CreateWindowEx (0, MAKEINTATOM (init_wc_atom), TEXT (""), 0,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL, NULL, hInstance, NULL);
::UnregisterClass (MAKEINTATOM (init_wc_atom), hInstance);
// Exit if we failed to get the function pointers.
if (! wglChoosePixelFormatARB) return -1;
// Create the main window. See MainWndProc.
WNDCLASS main_wc;
::ZeroMemory (& main_wc, sizeof main_wc);
main_wc.hInstance = hInstance;
main_wc.lpfnWndProc = & MainWndProc;
main_wc.hIcon = ::LoadIcon (hInstance, MAKEINTRESOURCE (257));
main_wc.lpszClassName = usr::program_name;
ATOM main_wc_atom = ::RegisterClass (& main_wc);
HWND hwnd = ::CreateWindowEx (ex_style, MAKEINTATOM (main_wc_atom), usr::program_name, style,
rect.left, rect.top, rect.right, rect.bottom,
parent, NULL, hInstance, & ws);
// Exit if we failed to create the window.
if (! hwnd) return 1;
// Enter the main loop.
MSG msg;
while (::GetMessage (& msg, NULL, 0, 0)) {
::TranslateMessage (& msg);
::DispatchMessage (& msg);
}
::UnregisterClass (MAKEINTATOM (main_wc_atom), hInstance);
return msg.wParam;
}
LRESULT CALLBACK InitWndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if (msg == WM_NCCREATE) {
// Set up legacy rendering context to get OpenGL function pointers.
PIXELFORMATDESCRIPTOR pfd;
::ZeroMemory (& pfd, sizeof pfd);
pfd.nSize = sizeof pfd;
pfd.dwFlags = PFD_SUPPORT_OPENGL;
if (HDC hdc = ::GetDC (hwnd)) {
int pf = ::ChoosePixelFormat (hdc, & pfd);
::SetPixelFormat (hdc, pf, & pfd);
if (HGLRC hglrc = ::wglCreateContext (hdc)) {
::wglMakeCurrent (hdc, hglrc);
// Get the function pointers.
get_glprocs ();
::wglMakeCurrent (NULL, NULL);
::wglDeleteContext (hglrc);
}
::ReleaseDC (hwnd, hdc);
}
return FALSE; // Abort window creation.
}
else {
return ::DefWindowProc (hwnd, msg, wParam, lParam);
}
}
LRESULT CALLBACK MainWndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
LRESULT result = 0;
bool call_def_window_proc = false, close_window = false;
// Retrieve the window-struct pointer from the window userdata.
window_struct_t * ws = reinterpret_cast <window_struct_t *> (::GetWindowLongPtr (hwnd, GWLP_USERDATA));
switch (msg) {
case WM_CREATE: {
result = -1; // Abort window creation.
// Stash the window-struct pointer in the window userdata.
CREATESTRUCT * cs = reinterpret_cast <CREATESTRUCT *> (lParam);
ws = reinterpret_cast <window_struct_t *> (cs->lpCreateParams);
::SetWindowLongPtr (hwnd, GWLP_USERDATA, reinterpret_cast <LONG_PTR> (ws));
// Remember initial mouse-pointer position to detect mouse movement.
::GetCursorPos (& ws->initial_cursor_position);
// Set up OpenGL rendering context.
HGLRC hglrc = setup_opengl_context (hwnd);
if (hglrc) {
ws->model.initialize (qpc (), cs->cx, cs->cy);
::PostMessage (hwnd, WM_APP, 0, 0); // Start the simulation.
result = 0; // Allow window creation to continue.
}
break;
}
case WM_APP: {
ws->model.draw_next ();
::InvalidateRect (hwnd, NULL, FALSE);
break;
}
case WM_PAINT: {
PAINTSTRUCT ps;
::BeginPaint (hwnd, & ps);
::SwapBuffers (ps.hdc);
::EndPaint (hwnd, & ps);
::PostMessage (hwnd, WM_APP, 0, 0);
break;
}
case WM_SETCURSOR:
::SetCursor (ws->mode == fullscreen ? NULL : (::LoadCursor (NULL, IDC_ARROW)));
break;
case WM_MOUSEMOVE:
if (ws->mode == fullscreen) {
// Compare the current mouse position with the one stored in the window struct.
POINT current = { GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam) };
::ClientToScreen (hwnd, & current);
SHORT dx = current.x - ws->initial_cursor_position.x;
SHORT dy = current.y - ws->initial_cursor_position.y;
close_window = dx > 10 || dy > 10 || dx * dx + dy * dy > 100;
}
break;
case WM_KEYDOWN: case WM_LBUTTONDOWN: case WM_MBUTTONDOWN: case WM_RBUTTONDOWN:
close_window = ws->mode == fullscreen || ws->mode == special;
break;
case WM_ACTIVATE: case WM_ACTIVATEAPP: case WM_NCACTIVATE:
close_window = ws->mode == fullscreen && LOWORD (wParam) == WA_INACTIVE;
call_def_window_proc = true;
break;
case WM_SYSCOMMAND:
call_def_window_proc = ! (ws->mode == fullscreen && wParam == SC_SCREENSAVE);
break;
case WM_DESTROY:
::wglMakeCurrent (NULL, NULL);
//::wglDeleteContext (ws->hglrc);
::PostQuitMessage (0);
break;
default:
call_def_window_proc = true;
break;
}
if (close_window) {
::PostMessage (hwnd, WM_CLOSE, 0, 0);
}
if (call_def_window_proc) {
result = ::DefWindowProc (hwnd, msg, wParam, lParam);
}
return result;
}
// Set up a proper pixel format and rendering context for the main window.
HGLRC setup_opengl_context (HWND hwnd)
{
const int pf_attribs [] = {
WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB,
WGL_SWAP_METHOD_ARB, WGL_SWAP_EXCHANGE_ARB,
WGL_COLOR_BITS_ARB, 32,
WGL_DEPTH_BITS_ARB, 4,
WGL_SAMPLE_BUFFERS_ARB, GL_FALSE,
//WGL_SAMPLES_ARB, 5,
0, 0,
};
const int context_attribs [] = {
WGL_CONTEXT_MAJOR_VERSION_ARB, 4,
WGL_CONTEXT_MINOR_VERSION_ARB, 2,
WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
0, 0,
};
HGLRC hglrc = NULL;
int pf;
UINT pfcount;
if (HDC hdc = ::GetDC (hwnd)) {
if (wglChoosePixelFormatARB (hdc, pf_attribs, NULL, 1, & pf, & pfcount)) {
if (::SetPixelFormat (hdc, pf, NULL)) {
hglrc = wglCreateContextAttribsARB (hdc, NULL, context_attribs);
if (hglrc) {
::wglMakeCurrent (hdc, hglrc);
}
}
}
::ReleaseDC (hwnd, hdc);
}
return hglrc;
}
// Tiny startup.
// No standard handles, window placement, environment variables,
// command-line transformation, global constructors and destructors,
// atexit functions, stack realignment, thread-local storage,
// runtime relocation fixups, 387 floating-point initialization,
// signal handlers or exceptions.
extern "C"
{
// This symbol is provided by all recent GCC or MSVC linkers.
extern IMAGE_DOS_HEADER __ImageBase;
// This must be specified in the link command line, "-Wl,-ecustom_startup".
extern void custom_startup ()
{
HINSTANCE hInstance = reinterpret_cast <HINSTANCE> (& __ImageBase);
int status = custom_main (hInstance);
::ExitProcess (static_cast <UINT> (status));
}
}
<commit_msg>main.cpp: comment fix<commit_after>#include "compiler.h"
#include "mswin.h"
#include "glinit.h"
#include "model.h"
#include "cmdline.h"
#include <windowsx.h>
// #include "tinyscheme-config.h"
// #include <scheme-private.h>
// #include <scheme.h>
#include <cstdint>
namespace usr {
// Program name.
static const TCHAR * const program_name = TEXT ("Polymorph");
static const TCHAR * const message =
TEXT ("And the ratios of their numbers, motions, and ")
TEXT ("other properties, everywhere God, as far as ")
TEXT ("necessity allowed or gave consent, has exactly ")
TEXT ("perfected, and harmonised in due proportion.");
// TEXT ("\n\nThis screensaver includes TinyScheme, developed by Dimitrios ")
// TEXT ("Souflis and licensed under the Modified BSD License. ")
// TEXT ("See \"tinyscheme/COPYING.txt\" for details.");
}
inline std::uint64_t qpc ()
{
LARGE_INTEGER t;
::QueryPerformanceCounter (& t);
return t.QuadPart;
}
struct window_struct_t
{
model_t model;
POINT initial_cursor_position;
run_mode_t mode;
};
LRESULT CALLBACK InitWndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
LRESULT CALLBACK MainWndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
HGLRC setup_opengl_context (HWND hwnd);
// Called by custom_entry_point (below).
int custom_main (HINSTANCE hInstance)
{
// Read command line arguments.
HWND parent = NULL;
run_mode_t mode = parse_command_line (::GetCommandLine (), & parent);
if (mode == configure) {
::MessageBox (NULL, usr::message, usr::program_name, MB_OK | MB_ICONASTERISK);
return 0;
}
// Placement and window style of the main window.
RECT rect;
DWORD style;
DWORD ex_style = 0;
if (mode == embedded) {
style = WS_CHILD | WS_VISIBLE;
::GetClientRect (parent, & rect); // 0, 0, width, height
}
else {
style = WS_POPUP | WS_VISIBLE;
if (mode == fullscreen) ex_style = WS_EX_TOPMOST;
rect.left = ::GetSystemMetrics (SM_XVIRTUALSCREEN);
rect.top = ::GetSystemMetrics (SM_YVIRTUALSCREEN);
rect.right = ::GetSystemMetrics (SM_CXVIRTUALSCREEN); // actually width, not right
rect.bottom = ::GetSystemMetrics (SM_CYVIRTUALSCREEN); // actually height, not bottom
}
window_struct_t ws ALIGNED16;
ws.mode = mode;
// Create a window with an OpenGL rendering context.
// To obtain a proper OpenGL pixel format, we need to call wglChoosePixelFormatARB, but
// first we must obtain the address of that function by calling using wglGetProcAddress,
// which requires that an OpenGL rendering context is current, which requires a device
// context that supports OpenGL, which requires a window with an OpenGL pixel format.
// Bootstrap the process with a legacy OpenGL pixel format. According to MSDN,
// "Once a window's pixel format is set, it cannot be changed", so the window
// and associated resources are of no further use and are destroyed here.
// Create the dummy window. See InitWndProc.
// Note this window does not survive creation.
WNDCLASS init_wc;
::ZeroMemory (& init_wc, sizeof init_wc);
init_wc.hInstance = hInstance;
init_wc.lpfnWndProc = & InitWndProc;
init_wc.lpszClassName = TEXT ("GLinit");
ATOM init_wc_atom = ::RegisterClass (& init_wc);
::CreateWindowEx (0, MAKEINTATOM (init_wc_atom), TEXT (""), 0,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL, NULL, hInstance, NULL);
::UnregisterClass (MAKEINTATOM (init_wc_atom), hInstance);
// Exit if we failed to get the function pointers.
if (! wglChoosePixelFormatARB) return -1;
// Create the main window. See MainWndProc.
WNDCLASS main_wc;
::ZeroMemory (& main_wc, sizeof main_wc);
main_wc.hInstance = hInstance;
main_wc.lpfnWndProc = & MainWndProc;
main_wc.hIcon = ::LoadIcon (hInstance, MAKEINTRESOURCE (257));
main_wc.lpszClassName = usr::program_name;
ATOM main_wc_atom = ::RegisterClass (& main_wc);
HWND hwnd = ::CreateWindowEx (ex_style, MAKEINTATOM (main_wc_atom), usr::program_name, style,
rect.left, rect.top, rect.right, rect.bottom,
parent, NULL, hInstance, & ws);
// Exit if we failed to create the window.
if (! hwnd) return 1;
// Enter the main loop.
MSG msg;
while (::GetMessage (& msg, NULL, 0, 0)) {
::TranslateMessage (& msg);
::DispatchMessage (& msg);
}
::UnregisterClass (MAKEINTATOM (main_wc_atom), hInstance);
return msg.wParam;
}
LRESULT CALLBACK InitWndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if (msg == WM_NCCREATE) {
// Set up legacy rendering context to get OpenGL function pointers.
PIXELFORMATDESCRIPTOR pfd;
::ZeroMemory (& pfd, sizeof pfd);
pfd.nSize = sizeof pfd;
pfd.dwFlags = PFD_SUPPORT_OPENGL;
if (HDC hdc = ::GetDC (hwnd)) {
int pf = ::ChoosePixelFormat (hdc, & pfd);
::SetPixelFormat (hdc, pf, & pfd);
if (HGLRC hglrc = ::wglCreateContext (hdc)) {
::wglMakeCurrent (hdc, hglrc);
// Get the function pointers.
get_glprocs ();
::wglMakeCurrent (NULL, NULL);
::wglDeleteContext (hglrc);
}
::ReleaseDC (hwnd, hdc);
}
return FALSE; // Abort window creation.
}
else {
return ::DefWindowProc (hwnd, msg, wParam, lParam);
}
}
LRESULT CALLBACK MainWndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
LRESULT result = 0;
bool call_def_window_proc = false, close_window = false;
// Retrieve the window-struct pointer from the window userdata.
window_struct_t * ws = reinterpret_cast <window_struct_t *> (::GetWindowLongPtr (hwnd, GWLP_USERDATA));
switch (msg) {
case WM_CREATE: {
result = -1; // Abort window creation.
// Stash the window-struct pointer in the window userdata.
CREATESTRUCT * cs = reinterpret_cast <CREATESTRUCT *> (lParam);
ws = reinterpret_cast <window_struct_t *> (cs->lpCreateParams);
::SetWindowLongPtr (hwnd, GWLP_USERDATA, reinterpret_cast <LONG_PTR> (ws));
// Remember initial mouse-pointer position to detect mouse movement.
::GetCursorPos (& ws->initial_cursor_position);
// Set up OpenGL rendering context.
HGLRC hglrc = setup_opengl_context (hwnd);
if (hglrc) {
ws->model.initialize (qpc (), cs->cx, cs->cy);
::PostMessage (hwnd, WM_APP, 0, 0); // Start the simulation.
result = 0; // Allow window creation to continue.
}
break;
}
case WM_APP: {
ws->model.draw_next ();
::InvalidateRect (hwnd, NULL, FALSE);
break;
}
case WM_PAINT: {
PAINTSTRUCT ps;
::BeginPaint (hwnd, & ps);
::SwapBuffers (ps.hdc);
::EndPaint (hwnd, & ps);
::PostMessage (hwnd, WM_APP, 0, 0);
break;
}
case WM_SETCURSOR:
::SetCursor (ws->mode == fullscreen ? NULL : (::LoadCursor (NULL, IDC_ARROW)));
break;
case WM_MOUSEMOVE:
if (ws->mode == fullscreen) {
// Compare the current mouse position with the one stored in the window struct.
POINT current = { GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam) };
::ClientToScreen (hwnd, & current);
SHORT dx = current.x - ws->initial_cursor_position.x;
SHORT dy = current.y - ws->initial_cursor_position.y;
close_window = dx > 10 || dy > 10 || dx * dx + dy * dy > 100;
}
break;
case WM_KEYDOWN: case WM_LBUTTONDOWN: case WM_MBUTTONDOWN: case WM_RBUTTONDOWN:
close_window = ws->mode == fullscreen || ws->mode == special;
break;
case WM_ACTIVATE: case WM_ACTIVATEAPP: case WM_NCACTIVATE:
close_window = ws->mode == fullscreen && LOWORD (wParam) == WA_INACTIVE;
call_def_window_proc = true;
break;
case WM_SYSCOMMAND:
call_def_window_proc = ! (ws->mode == fullscreen && wParam == SC_SCREENSAVE);
break;
case WM_DESTROY:
::wglMakeCurrent (NULL, NULL);
//::wglDeleteContext (ws->hglrc);
::PostQuitMessage (0);
break;
default:
call_def_window_proc = true;
break;
}
if (close_window) {
::PostMessage (hwnd, WM_CLOSE, 0, 0);
}
if (call_def_window_proc) {
result = ::DefWindowProc (hwnd, msg, wParam, lParam);
}
return result;
}
// Set up a proper pixel format and rendering context for the main window.
HGLRC setup_opengl_context (HWND hwnd)
{
const int pf_attribs [] = {
WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB,
WGL_SWAP_METHOD_ARB, WGL_SWAP_EXCHANGE_ARB,
WGL_COLOR_BITS_ARB, 32,
WGL_DEPTH_BITS_ARB, 4,
WGL_SAMPLE_BUFFERS_ARB, GL_FALSE,
//WGL_SAMPLES_ARB, 5,
0, 0,
};
const int context_attribs [] = {
WGL_CONTEXT_MAJOR_VERSION_ARB, 4,
WGL_CONTEXT_MINOR_VERSION_ARB, 2,
WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
0, 0,
};
HGLRC hglrc = NULL;
int pf;
UINT pfcount;
if (HDC hdc = ::GetDC (hwnd)) {
if (wglChoosePixelFormatARB (hdc, pf_attribs, NULL, 1, & pf, & pfcount)) {
if (::SetPixelFormat (hdc, pf, NULL)) {
hglrc = wglCreateContextAttribsARB (hdc, NULL, context_attribs);
if (hglrc) {
::wglMakeCurrent (hdc, hglrc);
}
}
}
::ReleaseDC (hwnd, hdc);
}
return hglrc;
}
// Tiny startup.
// No standard handles, window placement, environment variables,
// command-line transformation, global constructors and destructors,
// atexit functions, stack realignment, thread-local storage,
// runtime relocation fixups, 387 floating-point initialization,
// signal handlers or exceptions.
extern "C"
{
// This symbol is provided by all recent GCC and MSVC linkers.
extern IMAGE_DOS_HEADER __ImageBase;
// This entry point must be specified in the linker command line.
extern void custom_startup ()
{
HINSTANCE hInstance = reinterpret_cast <HINSTANCE> (& __ImageBase);
int status = custom_main (hInstance);
::ExitProcess (static_cast <UINT> (status));
}
}
<|endoftext|> |
<commit_before>#include "S3StreamDefaults.h"
#include <ossim/base/ossimPreferences.h>
#include <ossim/base/ossimEnvironmentUtility.h>
// defaults to a 1 megabyte block size
//
ossim_int64 ossim::S3StreamDefaults::m_readBlocksize = 32768;
ossim_int64 ossim::S3StreamDefaults::m_nReadCacheHeaders = 10000;
void ossim::S3StreamDefaults::loadDefaults()
{
ossimString s3ReadBlocksize = ossimEnvironmentUtility::instance()->getEnvironmentVariable("OSSIM_PLUGINS_AWS_S3_READBLOCKSIZE");
ossimString nReadCacheHeaders = ossimPreferences::instance()->findPreference("OSSIM_PLUGINS_AWS_S3_NREADCACHEHEADERS");
if(s3ReadBlocksize.empty())
{
s3ReadBlocksize = ossimPreferences::instance()->findPreference("ossim.plugins.aws.s3.readBlocksize");
}
if(!s3ReadBlocksize.empty())
{
ossim_int64 blockSize = s3ReadBlocksize.toInt64();
if(blockSize > 0)
{
ossimString byteType(s3ReadBlocksize.begin()+(s3ReadBlocksize.size()-1), s3ReadBlocksize.end());
byteType.upcase();
m_readBlocksize = blockSize;
if ( byteType == "K")
{
m_readBlocksize *=static_cast<ossim_int64>(1024);
}
else if ( byteType == "M")
{
m_readBlocksize *=static_cast<ossim_int64>(1048576);
}
else if ( byteType == "G")
{
m_readBlocksize *=static_cast<ossim_int64>(1073741824);
}
}
}
if(nReadCacheHeaders.empty())
{
nReadCacheHeaders = ossimPreferences::instance()->findPreference("ossim.plugins.aws.s3.nReadCacheHeaders");
}
if(!nReadCacheHeaders.empty())
{
m_nReadCacheHeaders = nReadCacheHeaders.toInt64();
if(m_nReadCacheHeaders < 0)
{
m_nReadCacheHeaders = 10000;
}
}
}
<commit_msg>Added debug to the defaults<commit_after>#include "S3StreamDefaults.h"
#include <ossim/base/ossimPreferences.h>
#include <ossim/base/ossimEnvironmentUtility.h>
#include <ossim/base/ossimTrace.h>
// defaults to a 1 megabyte block size
//
ossim_int64 ossim::S3StreamDefaults::m_readBlocksize = 32768;
ossim_int64 ossim::S3StreamDefaults::m_nReadCacheHeaders = 10000;
static ossimTrace traceDebug("ossimS3StreamDefaults:debug");
void ossim::S3StreamDefaults::loadDefaults()
{
if(traceDebug())
{
ossimNotify(ossimNotifyLevel_DEBUG)
<< "ossim::S3StreamDefaults::loadDefaults() DEBUG: entered.....\n";
}
ossimString s3ReadBlocksize = ossimEnvironmentUtility::instance()->getEnvironmentVariable("OSSIM_PLUGINS_AWS_S3_READBLOCKSIZE");
ossimString nReadCacheHeaders = ossimPreferences::instance()->findPreference("OSSIM_PLUGINS_AWS_S3_NREADCACHEHEADERS");
if(s3ReadBlocksize.empty())
{
s3ReadBlocksize = ossimPreferences::instance()->findPreference("ossim.plugins.aws.s3.readBlocksize");
}
if(!s3ReadBlocksize.empty())
{
ossim_int64 blockSize = s3ReadBlocksize.toInt64();
if(blockSize > 0)
{
ossimString byteType(s3ReadBlocksize.begin()+(s3ReadBlocksize.size()-1), s3ReadBlocksize.end());
byteType.upcase();
m_readBlocksize = blockSize;
if ( byteType == "K")
{
m_readBlocksize *=static_cast<ossim_int64>(1024);
}
else if ( byteType == "M")
{
m_readBlocksize *=static_cast<ossim_int64>(1048576);
}
else if ( byteType == "G")
{
m_readBlocksize *=static_cast<ossim_int64>(1073741824);
}
}
}
if(nReadCacheHeaders.empty())
{
nReadCacheHeaders = ossimPreferences::instance()->findPreference("ossim.plugins.aws.s3.nReadCacheHeaders");
}
if(!nReadCacheHeaders.empty())
{
m_nReadCacheHeaders = nReadCacheHeaders.toInt64();
if(m_nReadCacheHeaders < 0)
{
m_nReadCacheHeaders = 10000;
}
}
if(traceDebug())
{
ossimNotify(ossimNotifyLevel_DEBUG)
<< "m_readBlocksize: " << m_readBlocksize << "\n";
ossimNotify(ossimNotifyLevel_DEBUG)
<< "m_nReadCacheHeaders: " << m_nReadCacheHeaders << "\n";
ossimNotify(ossimNotifyLevel_DEBUG)
<< "ossim::S3StreamDefaults::loadDefaults() DEBUG: leaving.....\n";
}
}
<|endoftext|> |
<commit_before>#define DEBUG
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/epoll.h>
//for connection to server
bool ready4data = false;//set to true when streaming starts
bool inited = false;
bool stopparsing = false;
timeval lastrec;
int CONN_fd = 0;
#include "../util/ddv_socket.cpp" //DDVTech Socket wrapper
#include "../util/flv_sock.cpp" //FLV parsing with SocketW
#include "parsechunks.cpp" //chunkstream parsing
#include "handshake.cpp" //handshaking
int server_socket = 0;
void termination_handler (int signum){
if (server_socket == 0) return;
close(server_socket);
server_socket = 0;
}
int main(int argc, char ** argv){
//setup signal handler
struct sigaction new_action;
new_action.sa_handler = termination_handler;
sigemptyset (&new_action.sa_mask);
new_action.sa_flags = 0;
sigaction (SIGINT, &new_action, NULL);
sigaction (SIGHUP, &new_action, NULL);
sigaction (SIGTERM, &new_action, NULL);
server_socket = DDV_Listen(1935);
if ((argc < 2) || (argv[1] == "nd")){
if (server_socket > 0){daemon(1, 0);}else{return 1;}
}
int status;
while (server_socket > 0){
waitpid((pid_t)-1, &status, WNOHANG);
CONN_fd = DDV_Accept(server_socket);
if (CONN_fd > 0){
pid_t myid = fork();
if (myid == 0){
break;
}else{
printf("Spawned new process %i for handling socket %i\n", (int)myid, CONN_fd);
}
}
}
if (server_socket <= 0){
return 0;
}
unsigned int ts;
unsigned int fts = 0;
unsigned int ftst;
int ss;
FLV_Pack * tag;
//first timestamp set
firsttime = getNowMS();
#ifdef DEBUG
fprintf(stderr, "Doing handshake...\n");
#endif
if (doHandshake()){
#ifdef DEBUG
fprintf(stderr, "Handshake succcess!\n");
#endif
}else{
#ifdef DEBUG
fprintf(stderr, "Handshake fail!\n");
#endif
return 0;
}
#ifdef DEBUG
fprintf(stderr, "Starting processing...\n");
#endif
int retval;
int poller = epoll_create(1);
struct epoll_event ev;
ev.events = EPOLLIN;
ev.data.fd = CONN_fd;
epoll_ctl(poller, EPOLL_CTL_ADD, CONN_fd, &ev);
struct epoll_event events[1];
while (!socketError && !All_Hell_Broke_Loose){
//only parse input if available or not yet init'ed
//rightnow = getNowMS();
retval = epoll_wait(poller, events, 1, 0);
if (!ready4data || (snd_cnt - snd_window_at >= snd_window_size)){
if (DDV_ready(CONN_fd)){
parseChunk();
}
}
if (ready4data){
if (!inited){
//we are ready, connect the socket!
ss = DDV_OpenUnix(streamname.c_str());
if (ss <= 0){
#ifdef DEBUG
fprintf(stderr, "Could not connect to server!\n");
#endif
return 0;
}
#ifdef DEBUG
fprintf(stderr, "Everything connected, starting to send video data...\n");
#endif
inited = true;
}
//only send data if previous data has been ACK'ed...
if (snd_cnt - snd_window_at < snd_window_size){
if (FLV_GetPacket(tag, ss)){//able to read a full packet?
ts = tag->data[7] * 256*256*256;
ts += tag->data[4] * 256*256;
ts += tag->data[5] * 256;
ts += tag->data[6];
if (ts != 0){
if (fts == 0){fts = ts;ftst = getNowMS();}
ts -= fts;
tag->data[7] = ts / (256*256*256);
tag->data[4] = ts / (256*256);
tag->data[5] = ts / 256;
tag->data[6] = ts % 256;
ts += ftst;
}else{
ftst = getNowMS();
tag->data[7] = ftst / (256*256*256);
tag->data[4] = ftst / (256*256);
tag->data[5] = ftst / 256;
tag->data[6] = ftst % 256;
}
SendMedia((unsigned char)tag->data[0], (unsigned char *)tag->data+11, tag->len-15, ts);
#ifdef DEBUG
fprintf(stderr, "Sent a tag to %i\n", CONN_fd);
#endif
}
}
}
//send ACK if we received a whole window
if (rec_cnt - rec_window_at > rec_window_size){
rec_window_at = rec_cnt;
SendCTL(3, rec_cnt);//send ack (msg 3)
}
}
//#ifdef DEBUG
fprintf(stderr, "User %i disconnected.\n", CONN_fd);
//#endif
return 0;
}//main
<commit_msg>DDVSocket edits<commit_after>#define DEBUG
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/epoll.h>
//for connection to server
bool ready4data = false;//set to true when streaming starts
bool inited = false;
bool stopparsing = false;
timeval lastrec;
int CONN_fd = 0;
#include "../util/ddv_socket.cpp" //DDVTech Socket wrapper
#include "../util/flv_sock.cpp" //FLV parsing with SocketW
#include "parsechunks.cpp" //chunkstream parsing
#include "handshake.cpp" //handshaking
int server_socket = 0;
void termination_handler (int signum){
if (server_socket == 0) return;
close(server_socket);
server_socket = 0;
}
int main(int argc, char ** argv){
//setup signal handler
struct sigaction new_action;
new_action.sa_handler = termination_handler;
sigemptyset (&new_action.sa_mask);
new_action.sa_flags = 0;
sigaction (SIGINT, &new_action, NULL);
sigaction (SIGHUP, &new_action, NULL);
sigaction (SIGTERM, &new_action, NULL);
server_socket = DDV_Listen(1935);
if ((argc < 2) || (argv[1] == "nd")){
if (server_socket > 0){daemon(1, 0);}else{return 1;}
}
int status;
while (server_socket > 0){
waitpid((pid_t)-1, &status, WNOHANG);
CONN_fd = DDV_Accept(server_socket);
if (CONN_fd > 0){
pid_t myid = fork();
if (myid == 0){
break;
}else{
printf("Spawned new process %i for handling socket %i\n", (int)myid, CONN_fd);
}
}
}
if (server_socket <= 0){
return 0;
}
unsigned int ts;
unsigned int fts = 0;
unsigned int ftst;
int ss;
FLV_Pack * tag;
//first timestamp set
firsttime = getNowMS();
#ifdef DEBUG
fprintf(stderr, "Doing handshake...\n");
#endif
if (doHandshake()){
#ifdef DEBUG
fprintf(stderr, "Handshake succcess!\n");
#endif
}else{
#ifdef DEBUG
fprintf(stderr, "Handshake fail!\n");
#endif
return 0;
}
#ifdef DEBUG
fprintf(stderr, "Starting processing...\n");
#endif
int retval;
int poller = epoll_create(1);
struct epoll_event ev;
ev.events = EPOLLIN;
ev.data.fd = CONN_fd;
epoll_ctl(poller, EPOLL_CTL_ADD, CONN_fd, &ev);
struct epoll_event events[1];
while (!socketError && !All_Hell_Broke_Loose){
//only parse input if available or not yet init'ed
//rightnow = getNowMS();
retval = epoll_wait(poller, events, 1, 0);
if (!ready4data || (snd_cnt - snd_window_at >= snd_window_size)){
if (DDV_ready(CONN_fd)){
parseChunk();
}
}
if (ready4data){
if (!inited){
//we are ready, connect the socket!
ss = DDV_OpenUnix(streamname.c_str());
if (ss <= 0){
#ifdef DEBUG
fprintf(stderr, "Could not connect to server!\n");
#endif
return 0;
}
#ifdef DEBUG
fprintf(stderr, "Everything connected, starting to send video data...\n");
#endif
inited = true;
}
//only send data if previous data has been ACK'ed...
//if (snd_cnt - snd_window_at < snd_window_size){
if (FLV_GetPacket(tag, ss)){//able to read a full packet?
ts = tag->data[7] * 256*256*256;
ts += tag->data[4] * 256*256;
ts += tag->data[5] * 256;
ts += tag->data[6];
if (ts != 0){
if (fts == 0){fts = ts;ftst = getNowMS();}
ts -= fts;
tag->data[7] = ts / (256*256*256);
tag->data[4] = ts / (256*256);
tag->data[5] = ts / 256;
tag->data[6] = ts % 256;
ts += ftst;
}else{
ftst = getNowMS();
tag->data[7] = ftst / (256*256*256);
tag->data[4] = ftst / (256*256);
tag->data[5] = ftst / 256;
tag->data[6] = ftst % 256;
}
SendMedia((unsigned char)tag->data[0], (unsigned char *)tag->data+11, tag->len-15, ts);
#ifdef DEBUG
fprintf(stderr, "Sent a tag to %i\n", CONN_fd);
#endif
}
//}
}
//send ACK if we received a whole window
if (rec_cnt - rec_window_at > rec_window_size){
rec_window_at = rec_cnt;
SendCTL(3, rec_cnt);//send ack (msg 3)
}
}
//#ifdef DEBUG
fprintf(stderr, "User %i disconnected.\n", CONN_fd);
//#endif
return 0;
}//main
<|endoftext|> |
<commit_before>#include <algorithm>
#include <cassert>
#include <cstdlib>
#include <fcntl.h>
#include <fstream>
#include <iostream>
#include <string>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <vector>
#include <regex.h>
#include <sys/time.h>
#include <termios.h>
// http://stackoverflow.com/questions/1413445/read-a-password-from-stdcin
void setStdinEcho(bool enable = true) {
struct termios tty;
tcgetattr(STDIN_FILENO, &tty);
if( !enable )
tty.c_lflag &= ~ECHO;
else
tty.c_lflag |= ECHO;
(void) tcsetattr(STDIN_FILENO, TCSANOW, &tty);
}
void readQuestions(std::ifstream& questionFile, std::vector<std::string>& questions) {
int rv;
regex_t * exp = new regex_t;
rv = regcomp(exp, "^//.*", REG_EXTENDED);
if (rv != 0) {
std::cout << "regcomp failed with " << rv << std::endl;
}
while(questionFile) {
std::string line;
std::getline(questionFile, line);
if (line.length() > 1 && regexec(exp, line.c_str(), 0, NULL, 0) == REG_NOMATCH)
questions.push_back(line);
}
std::sort(questions.begin(), questions.end());
regfree(exp);
}
unsigned int getRnd(void) {
int urandom = open("/dev/urandom", O_RDONLY);
assert(urandom);
unsigned int rndNumber;
read(urandom, &rndNumber, sizeof(unsigned int));
close(urandom);
return rndNumber;
}
void usage(void) {
std::cout << "usage: ./question filename" << std::endl;
}
int main(int argc, char ** argv) {
if (argc != 2) {
usage();
return EXIT_FAILURE;
}
std::string filename(argv[1]);
std::vector<std::string> * questions = new std::vector<std::string>;
std::ifstream questionFile(filename.c_str());
if (questionFile.good()) {
readQuestions(questionFile, *questions);
}
else {
std::cerr << "Can't open given file " << filename << std::endl;
return EXIT_FAILURE;
}
questionFile.close();
std::vector<std::string> * todo = new std::vector<std::string>(*questions);
std::vector<std::string> * done = new std::vector<std::string>;
std::string question;
timeval * starttime = new timeval;
timeval * endtime = new timeval;
while(true) {
int id = getRnd() % todo->size();
question = (*todo)[id];
todo->erase(std::find(todo->begin(), todo->end(), question));
done->push_back(question);
std::cout << question << std::endl;
gettimeofday(starttime, NULL);
if (todo->empty())
std::swap(todo, done);
setStdinEcho(false);
std::cin.get();
setStdinEcho(true);
gettimeofday(endtime, NULL);
double elapsed_time = static_cast<double>(endtime->tv_sec) + static_cast<double>(endtime->tv_usec) * 1E-6;
elapsed_time -= static_cast<double>(starttime->tv_sec) + static_cast<double>(starttime->tv_usec) * 1E-6;
std::cout << elapsed_time << " seconds for answer!" << std::endl;
}
delete starttime;
delete endtime;
delete todo;
delete done;
return EXIT_SUCCESS;
}
<commit_msg>added completion notification<commit_after>#include <algorithm>
#include <cassert>
#include <cstdlib>
#include <fcntl.h>
#include <fstream>
#include <iostream>
#include <string>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <vector>
#include <regex.h>
#include <sys/time.h>
#include <termios.h>
// http://stackoverflow.com/questions/1413445/read-a-password-from-stdcin
void setStdinEcho(bool enable = true) {
struct termios tty;
tcgetattr(STDIN_FILENO, &tty);
if( !enable )
tty.c_lflag &= ~ECHO;
else
tty.c_lflag |= ECHO;
(void) tcsetattr(STDIN_FILENO, TCSANOW, &tty);
}
void readQuestions(std::ifstream& questionFile, std::vector<std::string>& questions) {
int rv;
regex_t * exp = new regex_t;
rv = regcomp(exp, "^//.*", REG_EXTENDED);
if (rv != 0) {
std::cout << "regcomp failed with " << rv << std::endl;
}
while(questionFile) {
std::string line;
std::getline(questionFile, line);
if (line.length() > 1 && regexec(exp, line.c_str(), 0, NULL, 0) == REG_NOMATCH)
questions.push_back(line);
}
std::sort(questions.begin(), questions.end());
regfree(exp);
}
unsigned int getRnd(void) {
int urandom = open("/dev/urandom", O_RDONLY);
assert(urandom);
unsigned int rndNumber;
read(urandom, &rndNumber, sizeof(unsigned int));
close(urandom);
return rndNumber;
}
void usage(void) {
std::cout << "usage: ./question filename" << std::endl;
}
int main(int argc, char ** argv) {
if (argc != 2) {
usage();
return EXIT_FAILURE;
}
std::string filename(argv[1]);
std::vector<std::string> * questions = new std::vector<std::string>;
std::ifstream questionFile(filename.c_str());
if (questionFile.good()) {
readQuestions(questionFile, *questions);
}
else {
std::cerr << "Can't open given file " << filename << std::endl;
return EXIT_FAILURE;
}
questionFile.close();
std::vector<std::string> * todo = new std::vector<std::string>(*questions);
std::vector<std::string> * done = new std::vector<std::string>;
std::string question;
timeval * starttime = new timeval;
timeval * endtime = new timeval;
while(true) {
int id = getRnd() % todo->size();
question = (*todo)[id];
todo->erase(std::find(todo->begin(), todo->end(), question));
done->push_back(question);
std::cout << question << std::endl;
gettimeofday(starttime, NULL);
setStdinEcho(false);
std::cin.get();
setStdinEcho(true);
gettimeofday(endtime, NULL);
double elapsed_time = static_cast<double>(endtime->tv_sec) + static_cast<double>(endtime->tv_usec) * 1E-6;
elapsed_time -= static_cast<double>(starttime->tv_sec) + static_cast<double>(starttime->tv_usec) * 1E-6;
std::cout << elapsed_time << " seconds for answer!" << std::endl;
if (todo->empty()) {
std::swap(todo, done);
std::cout << "### Complete, starting again. ###" << std::endl;
}
}
delete starttime;
delete endtime;
delete todo;
delete done;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_desktop.hxx"
#include "dp_misc.h"
#include "dp_platform.hxx"
#include "rtl/ustring.hxx"
#include "rtl/ustrbuf.hxx"
#include "rtl/instance.hxx"
#include "rtl/bootstrap.hxx"
#define PLATFORM_ALL "all"
#define PLATFORM_WIN_X86 "windows_x86"
#define PLATFORM_LINUX_X86 "linux_x86"
#define PLATFORM_LINUX_X86_64 "linux_x86_64"
#define PLATFORM_KFREEBSD_X86 "kfreebsd_x86"
#define PLATFORM_KFREEBSD_X86_64 "kfreebsd_x86_64"
#define PLATFORM_LINUX_SPARC "linux_sparc"
#define PLATFORM_LINUX_POWERPC "linux_powerpc"
#define PLATFORM_LINUX_POWERPC64 "linux_powerpc64"
#define PLATFORM_LINUX_ARM_EABI "linux_arm_eabi"
#define PLATFORM_LINUX_ARM_OABI "linux_arm_oabi"
#define PLATFORM_LINUX_MIPS_EL "linux_mips_el"
#define PLATFORM_LINUX_MIPS_EB "linux_mips_eb"
#define PLATFORM_LINUX_IA64 "linux_ia64"
#define PLATFORM_LINUX_M68K "linux_m68k"
#define PLATFORM_LINUX_S390 "linux_s390"
#define PLATFORM_LINUX_S390x "linux_s390x"
#define PLATFORM_LINUX_HPPA "linux_hppa"
#define PLATFORM_LINUX_ALPHA "linux_alpha"
#define PLATFORM_SOLARIS_SPARC "solaris_sparc"
#define PLATFORM_SOLARIS_SPARC64 "solaris_sparc64"
#define PLATFORM_SOLARIS_X86 "solaris_x86"
#define PLATFORM_FREEBSD_X86 "freebsd_x86"
#define PLATFORM_FREEBSD_X86_64 "freebsd_x86_64"
#define PLATFORM_NETBSD_X86 "netbsd_x86"
#define PLATFORM_NETBSD_X86_64 "netbsd_x86_64"
#define PLATFORM_MACOSX_X86 "macosx_x86"
#define PLATFORM_MACOSX_PPC "macosx_powerpc"
#define PLATFORM_OS2_X86 "os2_x86"
#define PLATFORM_OPENBSD_X86 "openbsd_x86"
#define PLATFORM_OPENBSD_X86_64 "openbsd_x86_64"
#define PLATFORM_DRAGONFLY_X86 "dragonfly_x86"
#define PLATFORM_DRAGONFLY_X86_64 "dragonfly_x86_64"
#define PLATFORM_AIX_POWERPC "aix_powerpc"
#define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) )
using ::rtl::OUString;
namespace css = ::com::sun::star;
namespace dp_misc
{
namespace
{
struct StrOperatingSystem :
public rtl::StaticWithInit<const OUString, StrOperatingSystem> {
const OUString operator () () {
OUString os( RTL_CONSTASCII_USTRINGPARAM("$_OS") );
::rtl::Bootstrap::expandMacros( os );
return os;
}
};
struct StrCPU :
public rtl::StaticWithInit<const OUString, StrCPU> {
const OUString operator () () {
OUString arch( RTL_CONSTASCII_USTRINGPARAM("$_ARCH") );
::rtl::Bootstrap::expandMacros( arch );
return arch;
}
};
struct StrPlatform : public rtl::StaticWithInit<
const OUString, StrPlatform> {
const OUString operator () () {
::rtl::OUStringBuffer buf;
buf.append( StrOperatingSystem::get() );
buf.append( static_cast<sal_Unicode>('_') );
buf.append( StrCPU::get() );
return buf.makeStringAndClear();
}
};
bool checkOSandCPU(OUString const & os, OUString const & cpu)
{
return os.equals(StrOperatingSystem::get())
&& cpu.equals(StrCPU::get());
}
bool isValidPlatform(OUString const & token )
{
bool ret = false;
if (token.equals(OUSTR(PLATFORM_ALL)))
ret = true;
else if (token.equals(OUSTR(PLATFORM_WIN_X86)))
ret = checkOSandCPU(OUSTR("Windows"), OUSTR("x86"));
else if (token.equals(OUSTR(PLATFORM_LINUX_X86)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("x86"));
else if (token.equals(OUSTR(PLATFORM_LINUX_X86_64)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("X86_64"));
else if (token.equals(OUSTR(PLATFORM_KFREEBSD_X86)))
ret = checkOSandCPU(OUSTR("kFreeBSD"), OUSTR("x86"));
else if (token.equals(OUSTR(PLATFORM_KFREEBSD_X86_64)))
ret = checkOSandCPU(OUSTR("kFreeBSD"), OUSTR("X86_64"));
else if (token.equals(OUSTR(PLATFORM_LINUX_SPARC)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("SPARC"));
else if (token.equals(OUSTR(PLATFORM_LINUX_POWERPC)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("PowerPC"));
else if (token.equals(OUSTR(PLATFORM_LINUX_POWERPC64)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("PowerPC_64"));
else if (token.equals(OUSTR(PLATFORM_LINUX_ARM_EABI)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("ARM_EABI"));
else if (token.equals(OUSTR(PLATFORM_LINUX_ARM_OABI)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("ARM_OABI"));
else if (token.equals(OUSTR(PLATFORM_LINUX_MIPS_EL)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("MIPS_EL"));
else if (token.equals(OUSTR(PLATFORM_LINUX_MIPS_EB)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("MIPS_EB"));
else if (token.equals(OUSTR(PLATFORM_LINUX_IA64)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("IA64"));
else if (token.equals(OUSTR(PLATFORM_LINUX_M68K)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("M68K"));
else if (token.equals(OUSTR(PLATFORM_LINUX_S390)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("S390"));
else if (token.equals(OUSTR(PLATFORM_LINUX_S390x)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("S390x"));
else if (token.equals(OUSTR(PLATFORM_LINUX_HPPA)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("HPPA"));
else if (token.equals(OUSTR(PLATFORM_LINUX_ALPHA)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("ALPHA"));
else if (token.equals(OUSTR(PLATFORM_SOLARIS_SPARC)))
ret = checkOSandCPU(OUSTR("Solaris"), OUSTR("SPARC"));
else if (token.equals(OUSTR(PLATFORM_SOLARIS_SPARC64)))
ret = checkOSandCPU(OUSTR("Solaris"), OUSTR("SPARC64"));
else if (token.equals(OUSTR(PLATFORM_SOLARIS_X86)))
ret = checkOSandCPU(OUSTR("Solaris"), OUSTR("x86"));
else if (token.equals(OUSTR(PLATFORM_FREEBSD_X86)))
ret = checkOSandCPU(OUSTR("FreeBSD"), OUSTR("x86"));
else if (token.equals(OUSTR(PLATFORM_FREEBSD_X86_64)))
ret = checkOSandCPU(OUSTR("FreeBSD"), OUSTR("X86_64"));
else if (token.equals(OUSTR(PLATFORM_NETBSD_X86)))
ret = checkOSandCPU(OUSTR("NetBSD"), OUSTR("x86"));
else if (token.equals(OUSTR(PLATFORM_NETBSD_X86_64)))
ret = checkOSandCPU(OUSTR("NetBSD"), OUSTR("X86_64"));
else if (token.equals(OUSTR(PLATFORM_MACOSX_X86)))
ret = checkOSandCPU(OUSTR("MacOSX"), OUSTR("x86"));
else if (token.equals(OUSTR(PLATFORM_MACOSX_PPC)))
ret = checkOSandCPU(OUSTR("MacOSX"), OUSTR("PowerPC"));
else if (token.equals(OUSTR(PLATFORM_OS2_X86)))
ret = checkOSandCPU(OUSTR("OS2"), OUSTR("x86"));
else if (token.equals(OUSTR(PLATFORM_AIX_POWERPC)))
ret = checkOSandCPU(OUSTR("AIX"), OUSTR("PowerPC"));
else if (token.equals(OUSTR(PLATFORM_OPENBSD_X86)))
ret = checkOSandCPU(OUSTR("OpenBSD"), OUSTR("x86"));
else if (token.equals(OUSTR(PLATFORM_OPENBSD_X86_64)))
ret = checkOSandCPU(OUSTR("OpenBSD"), OUSTR("X86_64"));
else if (token.equals(OUSTR(PLATFORM_DRAGONFLY_X86)))
ret = checkOSandCPU(OUSTR("DragonFly"), OUSTR("x86"));
else if (token.equals(OUSTR(PLATFORM_DRAGONFLY_X86_64)))
ret = checkOSandCPU(OUSTR("DragonFly"), OUSTR("X86_64"));
else
{
OSL_ENSURE(0, "Extension Manager: The extension supports an unknown platform. "
"Check the platform element in the description.xml");
ret = false;
}
return ret;
}
} // anon namespace
//=============================================================================
OUString const & getPlatformString()
{
return StrPlatform::get();
}
bool platform_fits( OUString const & platform_string )
{
sal_Int32 index = 0;
for (;;)
{
const OUString token(
platform_string.getToken( 0, ',', index ).trim() );
// check if this platform:
if (token.equalsIgnoreAsciiCase( StrPlatform::get() ) ||
(token.indexOf( '_' ) < 0 && /* check OS part only */
token.equalsIgnoreAsciiCase( StrOperatingSystem::get() )))
{
return true;
}
if (index < 0)
break;
}
return false;
}
bool hasValidPlatform( css::uno::Sequence<OUString> const & platformStrings)
{
bool ret = false;
for (sal_Int32 i = 0; i < platformStrings.getLength(); i++)
{
if (isValidPlatform(platformStrings[i]))
{
ret = true;
break;
}
}
return ret;
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Add x64 Windows here, too<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_desktop.hxx"
#include "dp_misc.h"
#include "dp_platform.hxx"
#include "rtl/ustring.hxx"
#include "rtl/ustrbuf.hxx"
#include "rtl/instance.hxx"
#include "rtl/bootstrap.hxx"
#define PLATFORM_ALL "all"
#define PLATFORM_WIN_X86 "windows_x86"
#define PLATFORM_WIN_X86_64 "windows_x86_64"
#define PLATFORM_LINUX_X86 "linux_x86"
#define PLATFORM_LINUX_X86_64 "linux_x86_64"
#define PLATFORM_KFREEBSD_X86 "kfreebsd_x86"
#define PLATFORM_KFREEBSD_X86_64 "kfreebsd_x86_64"
#define PLATFORM_LINUX_SPARC "linux_sparc"
#define PLATFORM_LINUX_POWERPC "linux_powerpc"
#define PLATFORM_LINUX_POWERPC64 "linux_powerpc64"
#define PLATFORM_LINUX_ARM_EABI "linux_arm_eabi"
#define PLATFORM_LINUX_ARM_OABI "linux_arm_oabi"
#define PLATFORM_LINUX_MIPS_EL "linux_mips_el"
#define PLATFORM_LINUX_MIPS_EB "linux_mips_eb"
#define PLATFORM_LINUX_IA64 "linux_ia64"
#define PLATFORM_LINUX_M68K "linux_m68k"
#define PLATFORM_LINUX_S390 "linux_s390"
#define PLATFORM_LINUX_S390x "linux_s390x"
#define PLATFORM_LINUX_HPPA "linux_hppa"
#define PLATFORM_LINUX_ALPHA "linux_alpha"
#define PLATFORM_SOLARIS_SPARC "solaris_sparc"
#define PLATFORM_SOLARIS_SPARC64 "solaris_sparc64"
#define PLATFORM_SOLARIS_X86 "solaris_x86"
#define PLATFORM_FREEBSD_X86 "freebsd_x86"
#define PLATFORM_FREEBSD_X86_64 "freebsd_x86_64"
#define PLATFORM_NETBSD_X86 "netbsd_x86"
#define PLATFORM_NETBSD_X86_64 "netbsd_x86_64"
#define PLATFORM_MACOSX_X86 "macosx_x86"
#define PLATFORM_MACOSX_PPC "macosx_powerpc"
#define PLATFORM_OS2_X86 "os2_x86"
#define PLATFORM_OPENBSD_X86 "openbsd_x86"
#define PLATFORM_OPENBSD_X86_64 "openbsd_x86_64"
#define PLATFORM_DRAGONFLY_X86 "dragonfly_x86"
#define PLATFORM_DRAGONFLY_X86_64 "dragonfly_x86_64"
#define PLATFORM_AIX_POWERPC "aix_powerpc"
#define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) )
using ::rtl::OUString;
namespace css = ::com::sun::star;
namespace dp_misc
{
namespace
{
struct StrOperatingSystem :
public rtl::StaticWithInit<const OUString, StrOperatingSystem> {
const OUString operator () () {
OUString os( RTL_CONSTASCII_USTRINGPARAM("$_OS") );
::rtl::Bootstrap::expandMacros( os );
return os;
}
};
struct StrCPU :
public rtl::StaticWithInit<const OUString, StrCPU> {
const OUString operator () () {
OUString arch( RTL_CONSTASCII_USTRINGPARAM("$_ARCH") );
::rtl::Bootstrap::expandMacros( arch );
return arch;
}
};
struct StrPlatform : public rtl::StaticWithInit<
const OUString, StrPlatform> {
const OUString operator () () {
::rtl::OUStringBuffer buf;
buf.append( StrOperatingSystem::get() );
buf.append( static_cast<sal_Unicode>('_') );
buf.append( StrCPU::get() );
return buf.makeStringAndClear();
}
};
bool checkOSandCPU(OUString const & os, OUString const & cpu)
{
return os.equals(StrOperatingSystem::get())
&& cpu.equals(StrCPU::get());
}
bool isValidPlatform(OUString const & token )
{
bool ret = false;
if (token.equals(OUSTR(PLATFORM_ALL)))
ret = true;
else if (token.equals(OUSTR(PLATFORM_WIN_X86)))
ret = checkOSandCPU(OUSTR("Windows"), OUSTR("x86"));
else if (token.equals(OUSTR(PLATFORM_WIN_X86_64)))
ret = checkOSandCPU(OUSTR("Windows"), OUSTR("x86_64"));
else if (token.equals(OUSTR(PLATFORM_LINUX_X86)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("x86"));
else if (token.equals(OUSTR(PLATFORM_LINUX_X86_64)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("X86_64"));
else if (token.equals(OUSTR(PLATFORM_KFREEBSD_X86)))
ret = checkOSandCPU(OUSTR("kFreeBSD"), OUSTR("x86"));
else if (token.equals(OUSTR(PLATFORM_KFREEBSD_X86_64)))
ret = checkOSandCPU(OUSTR("kFreeBSD"), OUSTR("X86_64"));
else if (token.equals(OUSTR(PLATFORM_LINUX_SPARC)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("SPARC"));
else if (token.equals(OUSTR(PLATFORM_LINUX_POWERPC)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("PowerPC"));
else if (token.equals(OUSTR(PLATFORM_LINUX_POWERPC64)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("PowerPC_64"));
else if (token.equals(OUSTR(PLATFORM_LINUX_ARM_EABI)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("ARM_EABI"));
else if (token.equals(OUSTR(PLATFORM_LINUX_ARM_OABI)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("ARM_OABI"));
else if (token.equals(OUSTR(PLATFORM_LINUX_MIPS_EL)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("MIPS_EL"));
else if (token.equals(OUSTR(PLATFORM_LINUX_MIPS_EB)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("MIPS_EB"));
else if (token.equals(OUSTR(PLATFORM_LINUX_IA64)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("IA64"));
else if (token.equals(OUSTR(PLATFORM_LINUX_M68K)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("M68K"));
else if (token.equals(OUSTR(PLATFORM_LINUX_S390)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("S390"));
else if (token.equals(OUSTR(PLATFORM_LINUX_S390x)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("S390x"));
else if (token.equals(OUSTR(PLATFORM_LINUX_HPPA)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("HPPA"));
else if (token.equals(OUSTR(PLATFORM_LINUX_ALPHA)))
ret = checkOSandCPU(OUSTR("Linux"), OUSTR("ALPHA"));
else if (token.equals(OUSTR(PLATFORM_SOLARIS_SPARC)))
ret = checkOSandCPU(OUSTR("Solaris"), OUSTR("SPARC"));
else if (token.equals(OUSTR(PLATFORM_SOLARIS_SPARC64)))
ret = checkOSandCPU(OUSTR("Solaris"), OUSTR("SPARC64"));
else if (token.equals(OUSTR(PLATFORM_SOLARIS_X86)))
ret = checkOSandCPU(OUSTR("Solaris"), OUSTR("x86"));
else if (token.equals(OUSTR(PLATFORM_FREEBSD_X86)))
ret = checkOSandCPU(OUSTR("FreeBSD"), OUSTR("x86"));
else if (token.equals(OUSTR(PLATFORM_FREEBSD_X86_64)))
ret = checkOSandCPU(OUSTR("FreeBSD"), OUSTR("X86_64"));
else if (token.equals(OUSTR(PLATFORM_NETBSD_X86)))
ret = checkOSandCPU(OUSTR("NetBSD"), OUSTR("x86"));
else if (token.equals(OUSTR(PLATFORM_NETBSD_X86_64)))
ret = checkOSandCPU(OUSTR("NetBSD"), OUSTR("X86_64"));
else if (token.equals(OUSTR(PLATFORM_MACOSX_X86)))
ret = checkOSandCPU(OUSTR("MacOSX"), OUSTR("x86"));
else if (token.equals(OUSTR(PLATFORM_MACOSX_PPC)))
ret = checkOSandCPU(OUSTR("MacOSX"), OUSTR("PowerPC"));
else if (token.equals(OUSTR(PLATFORM_OS2_X86)))
ret = checkOSandCPU(OUSTR("OS2"), OUSTR("x86"));
else if (token.equals(OUSTR(PLATFORM_AIX_POWERPC)))
ret = checkOSandCPU(OUSTR("AIX"), OUSTR("PowerPC"));
else if (token.equals(OUSTR(PLATFORM_OPENBSD_X86)))
ret = checkOSandCPU(OUSTR("OpenBSD"), OUSTR("x86"));
else if (token.equals(OUSTR(PLATFORM_OPENBSD_X86_64)))
ret = checkOSandCPU(OUSTR("OpenBSD"), OUSTR("X86_64"));
else if (token.equals(OUSTR(PLATFORM_DRAGONFLY_X86)))
ret = checkOSandCPU(OUSTR("DragonFly"), OUSTR("x86"));
else if (token.equals(OUSTR(PLATFORM_DRAGONFLY_X86_64)))
ret = checkOSandCPU(OUSTR("DragonFly"), OUSTR("X86_64"));
else
{
OSL_ENSURE(0, "Extension Manager: The extension supports an unknown platform. "
"Check the platform element in the description.xml");
ret = false;
}
return ret;
}
} // anon namespace
//=============================================================================
OUString const & getPlatformString()
{
return StrPlatform::get();
}
bool platform_fits( OUString const & platform_string )
{
sal_Int32 index = 0;
for (;;)
{
const OUString token(
platform_string.getToken( 0, ',', index ).trim() );
// check if this platform:
if (token.equalsIgnoreAsciiCase( StrPlatform::get() ) ||
(token.indexOf( '_' ) < 0 && /* check OS part only */
token.equalsIgnoreAsciiCase( StrOperatingSystem::get() )))
{
return true;
}
if (index < 0)
break;
}
return false;
}
bool hasValidPlatform( css::uno::Sequence<OUString> const & platformStrings)
{
bool ret = false;
for (sal_Int32 i = 0; i < platformStrings.getLength(); i++)
{
if (isValidPlatform(platformStrings[i]))
{
ret = true;
break;
}
}
return ret;
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>//===-- Hexagon.cpp -------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "InputFiles.h"
#include "Symbols.h"
#include "Target.h"
#include "lld/Common/ErrorHandler.h"
#include "llvm/BinaryFormat/ELF.h"
#include "llvm/Object/ELF.h"
#include "llvm/Support/Endian.h"
using namespace llvm;
using namespace llvm::object;
using namespace llvm::support::endian;
using namespace llvm::ELF;
using namespace lld;
using namespace lld::elf;
namespace {
class Hexagon final : public TargetInfo {
public:
uint32_t calcEFlags() const override;
RelExpr getRelExpr(RelType Type, const Symbol &S,
const uint8_t *Loc) const override;
void relocateOne(uint8_t *Loc, RelType Type, uint64_t Val) const override;
};
} // namespace
// Support V60 only at the moment.
uint32_t Hexagon::calcEFlags() const { return 0x60; }
static uint32_t applyMask(uint32_t Mask, uint32_t Data) {
uint32_t Result = 0;
size_t Off = 0;
for (size_t Bit = 0; Bit != 32; ++Bit) {
uint32_t ValBit = (Data >> Off) & 1;
uint32_t MaskBit = (Mask >> Bit) & 1;
if (MaskBit) {
Result |= (ValBit << Bit);
++Off;
}
}
return Result;
}
RelExpr Hexagon::getRelExpr(RelType Type, const Symbol &S,
const uint8_t *Loc) const {
switch (Type) {
case R_HEX_B15_PCREL:
case R_HEX_B15_PCREL_X:
case R_HEX_B22_PCREL:
case R_HEX_B22_PCREL_X:
case R_HEX_B32_PCREL_X:
case R_HEX_6_PCREL_X:
return R_PC;
default:
return R_ABS;
}
}
static uint32_t findMaskR6(uint32_t Insn) {
// There are (arguably too) many relocation masks for the DSP's
// R_HEX_6_X type. The table below is used to select the correct mask
// for the given instruction.
struct InstructionMask {
uint32_t CmpMask;
uint32_t RelocMask;
};
static const InstructionMask R6[] = {
{0x38000000, 0x0000201f}, {0x39000000, 0x0000201f},
{0x3e000000, 0x00001f80}, {0x3f000000, 0x00001f80},
{0x40000000, 0x000020f8}, {0x41000000, 0x000007e0},
{0x42000000, 0x000020f8}, {0x43000000, 0x000007e0},
{0x44000000, 0x000020f8}, {0x45000000, 0x000007e0},
{0x46000000, 0x000020f8}, {0x47000000, 0x000007e0},
{0x6a000000, 0x00001f80}, {0x7c000000, 0x001f2000},
{0x9a000000, 0x00000f60}, {0x9b000000, 0x00000f60},
{0x9c000000, 0x00000f60}, {0x9d000000, 0x00000f60},
{0x9f000000, 0x001f0100}, {0xab000000, 0x0000003f},
{0xad000000, 0x0000003f}, {0xaf000000, 0x00030078},
{0xd7000000, 0x006020e0}, {0xd8000000, 0x006020e0},
{0xdb000000, 0x006020e0}, {0xdf000000, 0x006020e0}};
// Duplex forms have a fixed mask and parse bits 15:14 are always
// zero. Non-duplex insns will always have at least one bit set in the
// parse field.
if ((0xC000 & Insn) == 0x0)
return 0x03f00000;
for (InstructionMask I : R6)
if ((0xff000000 & Insn) == I.CmpMask)
return I.RelocMask;
error("unrecognized instruction for R_HEX_6 relocation: 0x" +
utohexstr(Insn));
return 0;
}
static uint32_t findMaskR8(uint32_t Insn) {
if ((0xff000000 & Insn) == 0xde000000)
return 0x00e020e8;
if ((0xff000000 & Insn) == 0x3c000000)
return 0x0000207f;
return 0x00001fe0;
}
static void or32le(uint8_t *P, int32_t V) { write32le(P, read32le(P) | V); }
void Hexagon::relocateOne(uint8_t *Loc, RelType Type, uint64_t Val) const {
switch (Type) {
case R_HEX_NONE:
break;
case R_HEX_6_PCREL_X:
case R_HEX_6_X:
or32le(Loc, applyMask(findMaskR6(read32le(Loc)), Val));
break;
case R_HEX_8_X:
or32le(Loc, applyMask(findMaskR8(read32le(Loc)), Val));
break;
case R_HEX_12_X:
or32le(Loc, applyMask(0x000007e0, Val));
break;
case R_HEX_32:
or32le(Loc, applyMask(0xffffffff, Val));
break;
case R_HEX_32_6_X:
or32le(Loc, applyMask(0x0fff3fff, Val >> 6));
break;
case R_HEX_B15_PCREL:
or32le(Loc, applyMask(0x00df20fe, Val >> 2));
break;
case R_HEX_B15_PCREL_X:
or32le(Loc, applyMask(0x00df20fe, Val & 0x3f));
break;
case R_HEX_B22_PCREL:
or32le(Loc, applyMask(0x1ff3ffe, Val >> 2));
break;
case R_HEX_B22_PCREL_X:
or32le(Loc, applyMask(0x1ff3ffe, Val & 0x3f));
break;
case R_HEX_B32_PCREL_X:
or32le(Loc, applyMask(0x0fff3fff, Val >> 6));
break;
case R_HEX_HI16:
or32le(Loc, applyMask(0x00c03fff, Val >> 16));
break;
case R_HEX_LO16:
or32le(Loc, applyMask(0x00c03fff, Val));
break;
default:
error(getErrorLocation(Loc) + "unrecognized reloc " + toString(Type));
break;
}
}
TargetInfo *elf::getHexagonTargetInfo() {
static Hexagon Target;
return &Target;
}
<commit_msg>Remove unnecessary applyMask() application.<commit_after>//===-- Hexagon.cpp -------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "InputFiles.h"
#include "Symbols.h"
#include "Target.h"
#include "lld/Common/ErrorHandler.h"
#include "llvm/BinaryFormat/ELF.h"
#include "llvm/Object/ELF.h"
#include "llvm/Support/Endian.h"
using namespace llvm;
using namespace llvm::object;
using namespace llvm::support::endian;
using namespace llvm::ELF;
using namespace lld;
using namespace lld::elf;
namespace {
class Hexagon final : public TargetInfo {
public:
uint32_t calcEFlags() const override;
RelExpr getRelExpr(RelType Type, const Symbol &S,
const uint8_t *Loc) const override;
void relocateOne(uint8_t *Loc, RelType Type, uint64_t Val) const override;
};
} // namespace
// Support V60 only at the moment.
uint32_t Hexagon::calcEFlags() const { return 0x60; }
static uint32_t applyMask(uint32_t Mask, uint32_t Data) {
uint32_t Result = 0;
size_t Off = 0;
for (size_t Bit = 0; Bit != 32; ++Bit) {
uint32_t ValBit = (Data >> Off) & 1;
uint32_t MaskBit = (Mask >> Bit) & 1;
if (MaskBit) {
Result |= (ValBit << Bit);
++Off;
}
}
return Result;
}
RelExpr Hexagon::getRelExpr(RelType Type, const Symbol &S,
const uint8_t *Loc) const {
switch (Type) {
case R_HEX_B15_PCREL:
case R_HEX_B15_PCREL_X:
case R_HEX_B22_PCREL:
case R_HEX_B22_PCREL_X:
case R_HEX_B32_PCREL_X:
case R_HEX_6_PCREL_X:
return R_PC;
default:
return R_ABS;
}
}
static uint32_t findMaskR6(uint32_t Insn) {
// There are (arguably too) many relocation masks for the DSP's
// R_HEX_6_X type. The table below is used to select the correct mask
// for the given instruction.
struct InstructionMask {
uint32_t CmpMask;
uint32_t RelocMask;
};
static const InstructionMask R6[] = {
{0x38000000, 0x0000201f}, {0x39000000, 0x0000201f},
{0x3e000000, 0x00001f80}, {0x3f000000, 0x00001f80},
{0x40000000, 0x000020f8}, {0x41000000, 0x000007e0},
{0x42000000, 0x000020f8}, {0x43000000, 0x000007e0},
{0x44000000, 0x000020f8}, {0x45000000, 0x000007e0},
{0x46000000, 0x000020f8}, {0x47000000, 0x000007e0},
{0x6a000000, 0x00001f80}, {0x7c000000, 0x001f2000},
{0x9a000000, 0x00000f60}, {0x9b000000, 0x00000f60},
{0x9c000000, 0x00000f60}, {0x9d000000, 0x00000f60},
{0x9f000000, 0x001f0100}, {0xab000000, 0x0000003f},
{0xad000000, 0x0000003f}, {0xaf000000, 0x00030078},
{0xd7000000, 0x006020e0}, {0xd8000000, 0x006020e0},
{0xdb000000, 0x006020e0}, {0xdf000000, 0x006020e0}};
// Duplex forms have a fixed mask and parse bits 15:14 are always
// zero. Non-duplex insns will always have at least one bit set in the
// parse field.
if ((0xC000 & Insn) == 0x0)
return 0x03f00000;
for (InstructionMask I : R6)
if ((0xff000000 & Insn) == I.CmpMask)
return I.RelocMask;
error("unrecognized instruction for R_HEX_6 relocation: 0x" +
utohexstr(Insn));
return 0;
}
static uint32_t findMaskR8(uint32_t Insn) {
if ((0xff000000 & Insn) == 0xde000000)
return 0x00e020e8;
if ((0xff000000 & Insn) == 0x3c000000)
return 0x0000207f;
return 0x00001fe0;
}
static void or32le(uint8_t *P, int32_t V) { write32le(P, read32le(P) | V); }
void Hexagon::relocateOne(uint8_t *Loc, RelType Type, uint64_t Val) const {
switch (Type) {
case R_HEX_NONE:
break;
case R_HEX_6_PCREL_X:
case R_HEX_6_X:
or32le(Loc, applyMask(findMaskR6(read32le(Loc)), Val));
break;
case R_HEX_8_X:
or32le(Loc, applyMask(findMaskR8(read32le(Loc)), Val));
break;
case R_HEX_12_X:
or32le(Loc, applyMask(0x000007e0, Val));
break;
case R_HEX_32:
or32le(Loc, Val);
break;
case R_HEX_32_6_X:
or32le(Loc, applyMask(0x0fff3fff, Val >> 6));
break;
case R_HEX_B15_PCREL:
or32le(Loc, applyMask(0x00df20fe, Val >> 2));
break;
case R_HEX_B15_PCREL_X:
or32le(Loc, applyMask(0x00df20fe, Val & 0x3f));
break;
case R_HEX_B22_PCREL:
or32le(Loc, applyMask(0x1ff3ffe, Val >> 2));
break;
case R_HEX_B22_PCREL_X:
or32le(Loc, applyMask(0x1ff3ffe, Val & 0x3f));
break;
case R_HEX_B32_PCREL_X:
or32le(Loc, applyMask(0x0fff3fff, Val >> 6));
break;
case R_HEX_HI16:
or32le(Loc, applyMask(0x00c03fff, Val >> 16));
break;
case R_HEX_LO16:
or32le(Loc, applyMask(0x00c03fff, Val));
break;
default:
error(getErrorLocation(Loc) + "unrecognized reloc " + toString(Type));
break;
}
}
TargetInfo *elf::getHexagonTargetInfo() {
static Hexagon Target;
return &Target;
}
<|endoftext|> |
<commit_before>#include "ResourceManager.h"
#include <string>
#include <vector>
#ifdef __MACH__
#include <CoreFoundation/CoreFoundation.h>
#endif
namespace ResourceManager
{
namespace Internal
{
std::vector<std::string> searchPaths;
std::string userDirectoryPath;
bool FileExists ( const std::string& path )
{
return false;
}
}
using namespace Internal;
// utility function for reading from a RWops in full
void* ReadFull ( size_t* length, SDL_RWops* ops, int autoclose )
{
size_t len = SDL_RWseek(ops, 0, SEEK_END);
*length = len;
SDL_RWseek(ops, 0, SEEK_SET);
void* buffer = malloc(len);
SDL_RWread(ops, buffer, 1, len);
if (autoclose)
SDL_RWclose(ops);
return buffer;
}
SDL_RWops* OpenFile ( const std::string& name )
{
for (std::vector<std::string>::iterator iter = searchPaths.begin(); iter != searchPaths.end(); iter++)
{
std::string fullPath = (*iter) + '/' + name;
if (FileExists(fullPath))
{
return SDL_RWFromFile(fullPath.c_str(), "r");
}
}
return NULL;
}
void WriteFile ( const std::string& name, const void* data, size_t len )
{
std::string path = userDirectoryPath + '/' + name;
FILE* fp = fopen(path.c_str(), "rb");
assert(fp);
fwrite(data, 1, len, fp);
fclose(fp);
}
void Init ()
{
searchPaths.clear();
#ifdef __MACH__
char systemDirectory[1024];
char userDirectory[1024];
sprintf(userDirectory, "%s/Library/Application Support/Xsera", getenv("HOME"));
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef resourcePath = CFBundleCopyResourcesDirectoryURL(mainBundle);
CFURLGetFileSystemRepresentation(resourcePath, 1, (Uint8*)systemDirectory, sizeof(systemDirectory));
CFRelease(resourcePath);
searchPaths.push_back(systemDirectory);
searchPaths.push_back(userDirectory);
userDirectoryPath = userDirectory;
#endif
}
}
<commit_msg>Finished resource manager.<commit_after>#include "ResourceManager.h"
#include <string>
#include <vector>
#ifdef __MACH__
#include <CoreFoundation/CoreFoundation.h>
#endif
namespace ResourceManager
{
namespace Internal
{
std::vector<std::string> searchPaths;
std::string userDirectoryPath;
bool FileExists ( const std::string& path )
{
FILE* fp = fopen(path.c_str(), "rb");
if (fp)
fclose(fp);
return fp != NULL;
}
}
using namespace Internal;
// utility function for reading from a RWops in full
void* ReadFull ( size_t* length, SDL_RWops* ops, int autoclose )
{
size_t len = SDL_RWseek(ops, 0, SEEK_END);
*length = len;
SDL_RWseek(ops, 0, SEEK_SET);
void* buffer = malloc(len);
SDL_RWread(ops, buffer, 1, len);
if (autoclose)
SDL_RWclose(ops);
return buffer;
}
SDL_RWops* OpenFile ( const std::string& name )
{
for (std::vector<std::string>::iterator iter = searchPaths.begin(); iter != searchPaths.end(); iter++)
{
std::string fullPath = (*iter) + '/' + name;
if (FileExists(fullPath))
{
return SDL_RWFromFile(fullPath.c_str(), "r");
}
}
return NULL;
}
void WriteFile ( const std::string& name, const void* data, size_t len )
{
std::string path = userDirectoryPath + '/' + name;
FILE* fp = fopen(path.c_str(), "rb");
assert(fp);
fwrite(data, 1, len, fp);
fclose(fp);
}
void Init ()
{
searchPaths.clear();
#ifdef __MACH__
char systemDirectory[1024];
char userDirectory[1024];
sprintf(userDirectory, "%s/Library/Application Support/Xsera", getenv("HOME"));
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef resourcePath = CFBundleCopyResourcesDirectoryURL(mainBundle);
CFURLGetFileSystemRepresentation(resourcePath, 1, (Uint8*)systemDirectory, sizeof(systemDirectory));
CFRelease(resourcePath);
searchPaths.push_back(systemDirectory);
searchPaths.push_back(userDirectory);
userDirectoryPath = userDirectory;
#endif
}
}
<|endoftext|> |
<commit_before>#include "../tjh_draw.h"
const int WIDTH = 640;
const int HEIGHT = 480;
float clamp( float v, float min, float max )
{
float vmin = min < max ? min : max;
float vmax = max > min ? max : min;
if( v < vmin ) return vmin;
if( v > vmax ) return vmax;
return v;
}
int main()
{
draw::init( __FILE__, 640, 480 );
float x = 100;
float y = 100;
float xSpeed = 2;
float ySpeed = 2;
float size = 50;
bool done = false;
SDL_Event event;
while( !done )
{
while( SDL_PollEvent( &event ) )
{
if( event.type == SDL_QUIT ) done = true;
}
draw::clear(0.1, 0.1, 0.1);
draw::setColor( 0.5, 0.5, 0.5 );
draw::rectangle( x, y, size, size );
x += xSpeed;
float newx = clamp(x, 0, WIDTH - size);
if( newx != x )
{
x = newx;
xSpeed *= -1;
}
y += ySpeed;
float newy = clamp(y, 0, HEIGHT - size);
if( newy != y )
{
y = newy;
ySpeed *= -1;
}
draw::flush();
draw::present();
}
draw::shutdown();
return 0;
}
#define TJH_DRAW_IMPLEMENTATION
#include "../tjh_draw.h"<commit_msg>rename functions for new draw.h<commit_after>#include "../tjh_draw.h"
const int WIDTH = 640;
const int HEIGHT = 480;
float clamp( float v, float min, float max )
{
float vmin = min < max ? min : max;
float vmax = max > min ? max : min;
if( v < vmin ) return vmin;
if( v > vmax ) return vmax;
return v;
}
int main()
{
draw::init( __FILE__, 640, 480 );
float x = 100;
float y = 100;
float xSpeed = 2;
float ySpeed = 2;
float size = 50;
bool done = false;
SDL_Event event;
while( !done )
{
while( SDL_PollEvent( &event ) )
{
if( event.type == SDL_QUIT ) done = true;
}
draw::clear(0.1, 0.1, 0.1);
draw::setColor( 0.5, 0.5, 0.5 );
draw::rect( x, y, size, size );
x += xSpeed;
float newx = clamp(x, 0, WIDTH - size);
if( newx != x )
{
x = newx;
xSpeed *= -1;
}
y += ySpeed;
float newy = clamp(y, 0, HEIGHT - size);
if( newy != y )
{
y = newy;
ySpeed *= -1;
}
draw::flush();
draw::present();
}
draw::shutdown();
return 0;
}
#define TJH_DRAW_IMPLEMENTATION
#include "../tjh_draw.h"<|endoftext|> |
<commit_before>#include <fstream>
#include "get-cluster.h"
using namespace cv;
using namespace std;
int main(int argc, char* argv[]){
if (argc < 3){
cout << "Usage: " << endl
<< "IntrinsicImage.exe [-i input_image_path] [-o output_path]" << endl;
exit(-1);
}
string image_path;
string region_file_path;
string mask_file_path;
string output_path;
for (int i = 1; i < argc; i = i + 2){
if (strcmp(argv[i], "-i") == 0){
image_path = string(argv[i+1]);
cout << "image_path: " << image_path << endl;
}
else if (strcmp(argv[i], "-r") == 0){
region_file_path = string(argv[i + 1]);
cout << "region_file_path: " << region_file_path << endl;
}
else if (strcmp(argv[i], "-m") == 0){
mask_file_path = string(argv[i + 1]);
}
else if (strcmp(argv[i], "-o") == 0){
output_path = string(argv[i + 1]);
cout << "output_path: " << output_path << endl;
}
}
Mat_<Vec3b> image = imread(image_path);
int image_width = image.cols;
int image_height = image.rows;
Mat_<Vec3b> lab_image(image_height, image_width);
Mat_<int> region(image_height, image_width, 1); // not used now
int expected_cluster_num = 500;
Mat_<int> mask(image_height, image_width, 1); // not used now
// transform into lab color space
cvtColor(image, lab_image, CV_BGR2Lab);
if(region_file_path.empty() == false){
ifstream fin;
fin.open(region_file_path);
for (int i = 0; i < image_height; i++){
for (int j = 0; j < image_width; j++){
fin >> region(i, j);
}
}
expected_cluster_num = 3000;
}
if(mask_file_path.empty() == false){
Mat_<uchar> temp = imread(mask_file_path);
mask = temp > 200;
}
Mat_<Vec3d> project_image = Mat_<Vec3d>(lab_image);
double l_ratio = 0.3;
for (int i = 0; i < image_height; i++){
for (int j = 0; j < image_width; j++){
project_image(i, j)[0] *= 0.3;
}
}
double sigma = 0;
double c = 500; // 1.0
int min_size = 5;
int cluster_num = 0;
Mat_<Vec3b> output;
Mat_<int> label;
cout << "Segment the image..." << endl;
GetReflectanceCluster(project_image, sigma, c, min_size, &cluster_num,
output, label, expected_cluster_num, region);
cout << "Super-pixel num: " << cluster_num << endl;
ofstream fout;
fout.open(output_path);
fout << cv::format(label, cv::Formatter::FMT_CSV) << endl;
return 0;
}
<commit_msg>rm: main file<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (C) 2004, 2005, 2006, 2008 Nikolas Zimmermann <[email protected]>
* Copyright (C) 2004, 2005, 2006, 2007 Rob Buis <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "core/svg/SVGCursorElement.h"
#include "core/SVGNames.h"
#include "core/XLinkNames.h"
namespace blink {
inline SVGCursorElement::SVGCursorElement(Document& document)
: SVGElement(SVGNames::cursorTag, document)
, SVGTests(this)
, SVGURIReference(this)
, m_x(SVGAnimatedLength::create(this, SVGNames::xAttr, SVGLength::create(LengthModeWidth), AllowNegativeLengths))
, m_y(SVGAnimatedLength::create(this, SVGNames::yAttr, SVGLength::create(LengthModeHeight), AllowNegativeLengths))
{
addToPropertyMap(m_x);
addToPropertyMap(m_y);
}
DEFINE_NODE_FACTORY(SVGCursorElement)
SVGCursorElement::~SVGCursorElement()
{
// The below teardown is all handled by weak pointer processing in oilpan.
#if !ENABLE(OILPAN)
for (auto& client : m_clients)
client->cursorElementRemoved();
#endif
}
bool SVGCursorElement::isSupportedAttribute(const QualifiedName& attrName)
{
DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
if (supportedAttributes.isEmpty()) {
SVGTests::addSupportedAttributes(supportedAttributes);
SVGURIReference::addSupportedAttributes(supportedAttributes);
supportedAttributes.add(SVGNames::xAttr);
supportedAttributes.add(SVGNames::yAttr);
}
return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
}
void SVGCursorElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
parseAttributeNew(name, value);
}
void SVGCursorElement::addClient(SVGElement* element)
{
m_clients.add(element);
element->setCursorElement(this);
}
#if !ENABLE(OILPAN)
void SVGCursorElement::removeClient(SVGElement* element)
{
HashSet<RawPtr<SVGElement> >::iterator it = m_clients.find(element);
if (it != m_clients.end()) {
m_clients.remove(it);
element->cursorElementRemoved();
}
}
#endif
void SVGCursorElement::removeReferencedElement(SVGElement* element)
{
m_clients.remove(element);
}
void SVGCursorElement::svgAttributeChanged(const QualifiedName& attrName)
{
if (!isSupportedAttribute(attrName)) {
SVGElement::svgAttributeChanged(attrName);
return;
}
SVGElement::InvalidationGuard invalidationGuard(this);
// Any change of a cursor specific attribute triggers this recalc.
for (auto& client : m_clients)
client->setNeedsStyleRecalc(SubtreeStyleChange, StyleChangeReasonForTracing::create(StyleChangeReason::SVGCursor));
}
void SVGCursorElement::trace(Visitor* visitor)
{
#if ENABLE(OILPAN)
visitor->trace(m_clients);
#endif
SVGElement::trace(visitor);
}
} // namespace blink
<commit_msg>Oilpan: fix build after r183736.<commit_after>/*
* Copyright (C) 2004, 2005, 2006, 2008 Nikolas Zimmermann <[email protected]>
* Copyright (C) 2004, 2005, 2006, 2007 Rob Buis <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "core/svg/SVGCursorElement.h"
#include "core/SVGNames.h"
#include "core/XLinkNames.h"
namespace blink {
inline SVGCursorElement::SVGCursorElement(Document& document)
: SVGElement(SVGNames::cursorTag, document)
, SVGTests(this)
, SVGURIReference(this)
, m_x(SVGAnimatedLength::create(this, SVGNames::xAttr, SVGLength::create(LengthModeWidth), AllowNegativeLengths))
, m_y(SVGAnimatedLength::create(this, SVGNames::yAttr, SVGLength::create(LengthModeHeight), AllowNegativeLengths))
{
addToPropertyMap(m_x);
addToPropertyMap(m_y);
}
DEFINE_NODE_FACTORY(SVGCursorElement)
SVGCursorElement::~SVGCursorElement()
{
// The below teardown is all handled by weak pointer processing in oilpan.
#if !ENABLE(OILPAN)
for (const auto& client : m_clients)
client->cursorElementRemoved();
#endif
}
bool SVGCursorElement::isSupportedAttribute(const QualifiedName& attrName)
{
DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
if (supportedAttributes.isEmpty()) {
SVGTests::addSupportedAttributes(supportedAttributes);
SVGURIReference::addSupportedAttributes(supportedAttributes);
supportedAttributes.add(SVGNames::xAttr);
supportedAttributes.add(SVGNames::yAttr);
}
return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
}
void SVGCursorElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
parseAttributeNew(name, value);
}
void SVGCursorElement::addClient(SVGElement* element)
{
m_clients.add(element);
element->setCursorElement(this);
}
#if !ENABLE(OILPAN)
void SVGCursorElement::removeClient(SVGElement* element)
{
HashSet<RawPtr<SVGElement> >::iterator it = m_clients.find(element);
if (it != m_clients.end()) {
m_clients.remove(it);
element->cursorElementRemoved();
}
}
#endif
void SVGCursorElement::removeReferencedElement(SVGElement* element)
{
m_clients.remove(element);
}
void SVGCursorElement::svgAttributeChanged(const QualifiedName& attrName)
{
if (!isSupportedAttribute(attrName)) {
SVGElement::svgAttributeChanged(attrName);
return;
}
SVGElement::InvalidationGuard invalidationGuard(this);
// Any change of a cursor specific attribute triggers this recalc.
for (const auto& client : m_clients)
client->setNeedsStyleRecalc(SubtreeStyleChange, StyleChangeReasonForTracing::create(StyleChangeReason::SVGCursor));
}
void SVGCursorElement::trace(Visitor* visitor)
{
#if ENABLE(OILPAN)
visitor->trace(m_clients);
#endif
SVGElement::trace(visitor);
}
} // namespace blink
<|endoftext|> |
<commit_before>/*
* classes_io.cpp
*
* Created on: May 11, 2016
* Author: zmij
*/
#include <gtest/gtest.h>
#include <test/classes_for_io.hpp>
#include <wire/encoding/buffers.hpp>
namespace wire {
namespace encoding {
namespace test {
TEST(IO, Polymorphic)
{
::test::derived_ptr inst1 = ::std::make_shared< ::test::derived >();
inst1->fvalue = 3.14;
inst1->svalue = "inst1";
inst1->ivalue = 100500;
::test::derived_ptr inst2 = ::std::make_shared< ::test::derived >();
inst2->fvalue = 2.718;
inst2->svalue = "inst2";
inst2->bvalue = inst1;
inst2->ivalue = 42;
::test::derived_ptr inst3 = ::std::make_shared< ::test::derived >();
inst3->fvalue = 2.718 * 3.14;
inst3->svalue = "inst3";
inst3->bvalue = inst1;
inst3->ivalue = 13;
::test::base_ptr b1 = inst2;
::test::base_ptr b2 = inst3;
outgoing out{ core::connector_ptr{} };
{
write(::std::back_inserter(out), b1, b2);
out.close_all_encaps();
::std::cerr << "Out buffer size " << out.size() << "\n";
out.debug_print(::std::cerr);
}
incoming in{ message{}, ::std::move(out) };
{
b1.reset();
b2.reset();
auto encaps = in.current_encapsulation();
auto b = encaps.begin();
auto e = encaps.end();
read(b, e, b1, b2);
encaps.read_indirection_table(b);
EXPECT_TRUE(b1.get());
EXPECT_TRUE(b2.get());
}
}
} /* namespace test */
} /* namespace encoding */
} /* namespace wire */
<commit_msg>Tests for polymorphic I/O<commit_after>/*
* classes_io.cpp
*
* Created on: May 11, 2016
* Author: zmij
*/
#include <gtest/gtest.h>
#include <test/classes_for_io.hpp>
#include <wire/encoding/buffers.hpp>
namespace wire {
namespace encoding {
namespace test {
TEST(IO, Polymorphic)
{
outgoing out{ core::connector_ptr{} };
{
::test::derived_ptr inst1 = ::std::make_shared< ::test::derived >();
inst1->fvalue = 3.14;
inst1->svalue = "inst1";
inst1->ivalue = 100500;
::test::derived_ptr inst2 = ::std::make_shared< ::test::derived >();
inst2->fvalue = 2.718;
inst2->svalue = "inst2";
inst2->bvalue = inst1;
inst2->ivalue = 42;
::test::derived_ptr inst3 = ::std::make_shared< ::test::derived >();
inst3->fvalue = 2.718 * 3.14;
inst3->svalue = "inst3";
inst3->bvalue = inst1;
inst3->ivalue = 13;
::test::base_ptr b1 = inst2;
::test::base_ptr b2 = inst3;
write(::std::back_inserter(out), b1, b2);
out.close_all_encaps();
::std::cerr << "Out buffer size " << out.size() << "\n";
out.debug_print(::std::cerr);
}
incoming in{ message{}, ::std::move(out) };
{
::test::base_ptr b1;
::test::base_ptr b2;
auto encaps = in.current_encapsulation();
auto b = encaps.begin();
auto e = encaps.end();
read(b, e, b1, b2);
encaps.read_indirection_table(b);
ASSERT_TRUE(b1.get());
ASSERT_TRUE(b2.get());
auto d1 = ::std::dynamic_pointer_cast<::test::derived>(b1);
auto d2 = ::std::dynamic_pointer_cast<::test::derived>(b2);
ASSERT_TRUE(d1.get());
ASSERT_TRUE(d2.get());
EXPECT_TRUE(d1->bvalue.get());
EXPECT_EQ(d1->bvalue, d2->bvalue);
}
}
} /* namespace test */
} /* namespace encoding */
} /* namespace wire */
<|endoftext|> |
<commit_before>#include <thread>
#include <utility>
#include <istream>
#include "database.hpp"
#include "ui.hpp"
#include "searching.hpp"
using namespace magicSearchEngine;
using namespace std;
int
main(int argc, char *argv[]) {
JSONDatabase database;
search_engine oraculum(database);
// We expect enough space between running this program and writing the first
// command within its interface. So for fluency, we run a new thread doing
// expensive methods separately and after command processing we only check,
// that the user was not too fast. In case, we join the thread and simply wait.
thread data_loading([&]() {
database.load_database();
oraculum.create_index();
});
console cmd_ui(cin);
while (true) {
auto command = cmd_ui.get_cmd();
switch (command.first) {
case cmd::error:
case cmd::parse_error:
cmd_ui.bad_input();
case cmd::end_of_input:
case cmd::exit:
return 0;
case cmd::none:
this_thread::yield();
break;
case cmd::find:
{
if (!database.is_ready()) {
data_loading.join();
}
auto res = oraculum.search_for(command.second[1]);
if (res == nullptr) {
cout << "Demanded card was not found." << endl;
}
else {
cout << *(res) << endl;
}
break;
}
case cmd::similar:
{
if (!database.is_ready()) {
data_loading.join();
}
auto && res = oraculum.find_similar(command.second[1], 3);
if (res.size() == 0) {
cout << "Demanded card was not found." << endl;
}
for (auto && card : res) {
cout << *card << endl;
}
}
default:
this_thread::yield();
break;
}
}
}
<commit_msg>[src/main.cpp] Script mode added, docopt.cpp used.<commit_after>#include <thread>
#include <utility>
#include <istream>
#include <map>
#include "database.hpp"
#include "ui.hpp"
#include "searching.hpp"
#include "../docopt.cpp/docopt.h"
using namespace magicSearchEngine;
using namespace std;
static const char USAGE[] =
R"(Magic Search Engine.
Usage:
MagicSearchEngine find <name>
MagicSearchEngine similar <name> [<number>]
MagicSearchEngine (-h | --help)
MagicSearchEngine --interactive
MagicSearchEngine --version
Options:
<number> Number of cards returned [default: 3].
-h --help Show this screen.
--interactive Run interactive mode (type 'help' there).
--version Show version.
)";
static const char USAGE_INTERACTIVE[] =
R"(Magic Search Engine, interactive mode.
Usage:
find <name>
similar <name> [<number>]
MagicSearchEngine (h | help)
Options:
<number> Number of cards returned [default: 3].
-h --help Show this screen.
)";
inline void
find(const JSONDatabase & database,
search_engine & oraculum,
thread & data_loading,
const string & name) {
if (!database.is_ready()) {
data_loading.join();
}
auto res = oraculum.search_for(name);
if (res == nullptr) {
cout << "Demanded card was not found." << endl;
}
else {
cout << *(res) << endl;
}
}
inline void
similar(const JSONDatabase & database,
search_engine & oraculum,
thread & data_loading,
const string & name,
const string & count) {
// Parsing count.
int cnt = 1;
try {
cnt = stoi(count);
if (cnt < 1) {
cout << "Number must be a positive integer." << endl;
return;
}
}
catch (...) {
cout << USAGE << endl;
return;
}
// Is db loaded?
if (!database.is_ready()) {
data_loading.join();
}
// Searching.
vector<const Card *> res;
res = oraculum.find_similar(name, cnt); // Here cnt is >= 1.
if (res.size() == 0) {
cout << "Demanded card was not found." << endl;
}
else {
for (const Card * card : res) {
cout << (*card) << endl;
}
}
}
inline void
interactive_mode(const JSONDatabase & database,
search_engine & oraculum,
thread & data_loading) {
console cmd_ui(cin);
while (true) {
const auto & c = cmd_ui.get_cmd();
switch (c.first) {
case cmd::error:
case cmd::parse_error:
cout << "Error while parsing last input. Use command \"help\"." << endl;
case cmd::help:
cout << USAGE_INTERACTIVE << endl;
break;
case cmd::end_of_input:
case cmd::exit:
return;
case cmd::none:
this_thread::yield();
break;
case cmd::find:
{
find(database, oraculum, data_loading, c.second[1]);
break;
}
case cmd::similar:
{
if (c.second.size() == 2)
similar(database, oraculum, data_loading, c.second[1], "3");
else
similar(database, oraculum, data_loading, c.second[1], c.second[2]);
break;
}
default:
this_thread::yield();
break;
}
}
}
int
main(int argc, char * argv[]) {
JSONDatabase database;
search_engine oraculum(database);
// We expect enough space between running this program and writing the first
// command in interactive mode. So for fluency, we run a new thread doing
// expensive methods separately and after command processing we only check,
// that the user was not too fast. In case, we join the thread and simply wait.
thread data_loading([&]() {
database.load_database();
oraculum.create_index();
});
map<string, docopt::value> args = docopt::docopt(USAGE,{argv + 1, argv + argc},
true, // show help if requested
"Magic Search Engine 1.0"); // version string
if (args["find"].asBool()) {
find(database, oraculum, data_loading, args["<name>"].asString());
}
else if (args["similar"].asBool()) {
if (!args["<number>"]) {
similar(database, oraculum, data_loading, args["<name>"].asString(), "3");
}
else {
similar(database, oraculum, data_loading, args["<name>"].asString(), args["<number>"].asString());
}
}
else if (args["--interactive"].asBool()) {
interactive_mode(database, oraculum, data_loading);
}
// Avoiding destruction of detachable thread in case of script mode with
// wrong input parameters (i.g. negative number). In this way detached
// thread is killed with main() instead of terminating program with thread
// exception.
if (data_loading.joinable())
data_loading.detach();
return 0;
}
<|endoftext|> |
<commit_before>
/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2014 Max-Planck-Institute for Intelligent Systems,
* University of Southern California
* Jan Issac ([email protected])
* Manuel Wuthrich ([email protected])
*
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * 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.
*
*/
/**
* @date 2014
* @author Jan Issac ([email protected])
* Max-Planck-Institute for Intelligent Systems, University of Southern California
*/
#include <gtest/gtest.h>
#include <fl/exception/exception.hpp>
#include <fl/filter/gaussian/point_set.hpp>
#include <fl/filter/gaussian/gaussian_filter.hpp>
TEST(Exception, create)
{
struct FirstWeight
{
double w;
std::string name;
};
typedef fl::PointSet<Eigen::Matrix<double, 1, 1>, -1> SigmaPointGaussian;
SigmaPointGaussian sigmas(1);
try
{
sigmas.point(0, Eigen::Matrix<double, 1, 1>::Random(), {1.23, 1.24});
sigmas.point(1, Eigen::Matrix<double, 1, 1>::Random(), {1.23, 1.24});
sigmas.point(2, Eigen::Matrix<double, 1, 1>::Random(), {1.23, 1.24});
}
catch(fl::OutOfBoundsException& e) { }
catch(...)
{
ADD_FAILURE();
}
}
TEST(Exception, OutOfBoundsException_default_construction)
{
fl::OutOfBoundsException e;
// EXPECT_NE(
// std::string(e.what()).find("Index out of bounds"),
// std::string::npos);
try {
fl_throw(fl::OutOfBoundsException());
} catch (fl::Exception& e) {
std::cout << e.what() << std::endl;
}
}
TEST(Exception, OutOfBoundsException_index)
{
fl::OutOfBoundsException e(10);
// EXPECT_NE(
// std::string(e.what()).find("Index[10] out of bounds"),
// std::string::npos);
try {
fl_throw(e);
} catch (fl::Exception& e) {
std::cout << e.what() << std::endl;
}
}
TEST(Exception, OutOfBoundsException_index_size)
{
fl::OutOfBoundsException e(10, 8);
EXPECT_NE(
std::string(e.what()).find("Index[10] out of bounds [0, 8)"),
std::string::npos);
try {
fl_throw(e);
} catch (fl::Exception& e) {
std::cout << e.what() << std::endl;
}
}
<commit_msg>Updated exception tests<commit_after>
/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2014 Max-Planck-Institute for Intelligent Systems,
* University of Southern California
* Jan Issac ([email protected])
* Manuel Wuthrich ([email protected])
*
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * 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.
*
*/
/**
* @date 2014
* @author Jan Issac ([email protected])
* Max-Planck-Institute for Intelligent Systems, University of Southern California
*/
#include <gtest/gtest.h>
#include <fl/exception/exception.hpp>
#include <fl/filter/gaussian/point_set.hpp>
#include <fl/filter/gaussian/gaussian_filter.hpp>
TEST(Exception, create)
{
struct FirstWeight
{
double w;
std::string name;
};
typedef fl::PointSet<Eigen::Matrix<double, 1, 1>, -1> SigmaPointGaussian;
SigmaPointGaussian sigmas(1);
try
{
sigmas.point(0, Eigen::Matrix<double, 1, 1>::Random(), {1.23, 1.24});
sigmas.point(1, Eigen::Matrix<double, 1, 1>::Random(), {1.23, 1.24});
sigmas.point(2, Eigen::Matrix<double, 1, 1>::Random(), {1.23, 1.24});
}
catch(fl::OutOfBoundsException& e) { }
catch(...)
{
ADD_FAILURE();
}
}
TEST(Exception, OutOfBoundsException_default_construction)
{
fl::OutOfBoundsException e;
EXPECT_NE(
std::string(e.what()).find("Index out of bounds"),
std::string::npos);
// try {
// fl_throw(fl::OutOfBoundsException());
// } catch (fl::Exception& e) {
// std::cout << e.what() << std::endl;
// }
}
TEST(Exception, OutOfBoundsException_index)
{
fl::OutOfBoundsException e(10);
EXPECT_NE(
std::string(e.what()).find("Index[10] out of bounds"),
std::string::npos);
// try {
// fl_throw(e);
// } catch (fl::Exception& e) {
// std::cout << e.what() << std::endl;
// }
}
TEST(Exception, OutOfBoundsException_index_size)
{
fl::OutOfBoundsException e(10, 8);
EXPECT_NE(
std::string(e.what()).find("Index[10] out of bounds [0, 8)"),
std::string::npos);
// try {
// fl_throw(e);
// } catch (fl::Exception& e) {
// std::cout << e.what() << std::endl;
// }
}
<|endoftext|> |
<commit_before>//
// main.cpp
// thermaleraser
//
// Created by Mark Larus on 9/8/12.
// Copyright (c) 2012 Kenyon College. All rights reserved.
//
#include <omp.h>
#include <iostream>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_sf.h>
#include <time.h>
#include <semaphore.h>
#include <algorithm>
#include <math.h>
#include <sqlite3.h>
#include <assert.h>
#include <set>
#include <boost/program_options.hpp>
#include <boost/timer/timer.hpp>
#include "States.h"
#include "System.h"
#include "Utilities.h"
#define print(x) std::cout<<#x <<": " <<x<<std::endl;
namespace opt = boost::program_options;
enum OutputType {
CommaSeparated,
PrettyPrint,
Mathematica,
NoOutput
};
void simulate_and_print(Constants constants, int iterations, OutputType type);
int main(int argc, char * argv[]) {
/*! Initialize options list.
*/
bool verbose = false;
const int default_iterations = 1<<16;
opt::options_description desc("Allowed options");
desc.add_options()
("iterations,n",opt::value<int>(), "Number of iterations")
("help","Show help message")
("verbose,v", "Show extensive debugging info")
("output,o", opt::value<int>(), "Output style.");
;
opt::variables_map vmap;
opt::store(opt::parse_command_line(argc,argv,desc),vmap);
opt::notify(vmap);
if (vmap.count("help")) {
std::cout << desc << "\n";
return 1;
}
verbose = vmap.count("verbose");
int iterations = vmap.count("iterations") ? vmap["iterations"].as<int>() : default_iterations;
if (verbose) {
print(iterations);
#pragma omp parallel
#pragma omp single
print(omp_get_num_threads());
}
OutputType output_style = vmap.count("output") ? (OutputType)vmap["output"].as<int>() : CommaSeparated;
/*! This call sets up our state machine for the wheel. Each state (i.e. "A0", "C1") is
represented by an object with pointers to the next states and the bit-flip states. */
setupStates();
Constants constants;
/*! The delta used here is NOT, at this point, the delta used in the paper. This is the
ratio of ones to zeroes in the bit stream. Probably worth changing the name, but
calculating this at runtime is just an invitation for bugs. */
constants.delta = .5;
constants.epsilon = .7;
constants.tau = 1;
int dimension = 50;
for (int k=dimension*dimension; k>=0; k--) {
constants.epsilon = (k % dimension)/(double)(dimension);
constants.delta = .5 + .5*(k / dimension)/(double)(dimension);
simulate_and_print(constants, iterations, output_style);
}
}
void simulate_and_print(Constants constants, int iterations, OutputType type) {
boost::timer::auto_cpu_timer t;
/*! Use this to change the length of the tape. */
const int BIT_STREAM_LENGTH = 8;
int first_pass_iterations = iterations;
System *systems = new System[first_pass_iterations];
int *histogram = new int[1<<BIT_STREAM_LENGTH];
std::fill_n(histogram, 1<<BIT_STREAM_LENGTH, 0);
long double *p = new long double[1<<BIT_STREAM_LENGTH];
long double *p_prime = new long double[1<<BIT_STREAM_LENGTH];
long double sum = 0;
const long double beta = log((1+constants.epsilon)/(1-constants.epsilon));
long double max_surprise = 0;
long double min_surprise = LONG_MAX;
#pragma omp parallel
{
//TODO: Move this into a semaphore in the utility function
gsl_rng *localRNG = GSLRandomNumberGenerator();
#pragma omp for
for (int k=0; k<first_pass_iterations; ++k) {
System *currentSystem = systems+k;
currentSystem->constants = constants;
currentSystem->nbits = BIT_STREAM_LENGTH;
evolveSystem(currentSystem, localRNG);
histogram[systems[k].endingBitString]++;
}
#pragma omp single nowait
delete [] systems;
#pragma omp for nowait
for(int k=0; k<1<<BIT_STREAM_LENGTH; k++) {
int setBits = bitCount(k,BIT_STREAM_LENGTH);
p[k] = gsl_ran_binomial_pdf(setBits, constants.delta, BIT_STREAM_LENGTH)/gsl_sf_choose(BIT_STREAM_LENGTH,setBits);
p_prime[k]=static_cast<long double>(histogram[k])/(first_pass_iterations);
}
#pragma omp single nowait
delete [] histogram;
#pragma omp barrier
//Make sure we don't accidentally share a seed.
#pragma omp for reduction(+ : sum)
for(int k=0; k<iterations; k++) {
System *currentSystem = new System();
currentSystem->constants = constants;
currentSystem->nbits = BIT_STREAM_LENGTH;
evolveSystem(currentSystem, localRNG);
long double surprise = exp(beta*currentSystem->mass)*p_prime[currentSystem->endingBitString]/p[currentSystem->startingBitString];
max_surprise = surprise > max_surprise ? surprise : max_surprise;
min_surprise = surprise && surprise < min_surprise ? surprise : min_surprise;
sum = sum + surprise;
delete currentSystem;
}
#pragma omp single nowait
{
delete [] p_prime;
delete [] p;
if(type==CommaSeparated) {
static int once = 0;
if (!once) {
std::cout<<"delta,epsilon,avg,max_surprise\n";
once=1;
}
std::cout<< constants.delta << "," << constants.epsilon << "," << sum/iterations << "," << max_surprise << std::endl;
}
if(type==PrettyPrint) {
print(beta);
print(constants.delta);
print(constants.epsilon);
print(sum/iterations);
print(max_surprise);
print(sum);
std::cout<<std::endl;
}
if (type==Mathematica) {
assert(0);
}
}
gsl_rng_free(localRNG);
}
}
<commit_msg>Parallelize at higher granularity.<commit_after>//
// main.cpp
// thermaleraser
//
// Created by Mark Larus on 9/8/12.
// Copyright (c) 2012 Kenyon College. All rights reserved.
//
#include <omp.h>
#include <iostream>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_sf.h>
#include <time.h>
#include <semaphore.h>
#include <algorithm>
#include <math.h>
#include <sqlite3.h>
#include <assert.h>
#include <set>
#include <boost/program_options.hpp>
#include <boost/timer/timer.hpp>
#include "States.h"
#include "System.h"
#include "Utilities.h"
#define print(x) std::cout<<#x <<": " <<x<<std::endl;
namespace opt = boost::program_options;
enum OutputType {
CommaSeparated,
PrettyPrint,
Mathematica,
NoOutput
};
void simulate_and_print(Constants constants, int iterations, OutputType type);
int main(int argc, char * argv[]) {
/*! Initialize options list.
*/
bool verbose = false;
const int default_iterations = 1<<16;
opt::options_description desc("Allowed options");
desc.add_options()
("iterations,n",opt::value<int>(), "Number of iterations")
("help","Show help message")
("verbose,v", "Show extensive debugging info")
("output,o", opt::value<int>(), "Output style.");
;
opt::variables_map vmap;
opt::store(opt::parse_command_line(argc,argv,desc),vmap);
opt::notify(vmap);
if (vmap.count("help")) {
std::cout << desc << "\n";
return 1;
}
verbose = vmap.count("verbose");
int iterations = vmap.count("iterations") ? vmap["iterations"].as<int>() : default_iterations;
if (verbose) {
print(iterations);
#pragma omp parallel
#pragma omp single
print(omp_get_num_threads());
}
OutputType output_style = vmap.count("output") ? (OutputType)vmap["output"].as<int>() : CommaSeparated;
/*! This call sets up our state machine for the wheel. Each state (i.e. "A0", "C1") is
represented by an object with pointers to the next states and the bit-flip states. */
setupStates();
Constants constants;
/*! The delta used here is NOT, at this point, the delta used in the paper. This is the
ratio of ones to zeroes in the bit stream. Probably worth changing the name, but
calculating this at runtime is just an invitation for bugs. */
constants.delta = .5;
constants.epsilon = .7;
constants.tau = 1;
int dimension = 50;
#pragma omp parallel for private(constants)
for (int k=dimension*dimension; k>=0; k--) {
constants.epsilon = (k % dimension)/(double)(dimension);
constants.delta = .5 + .5*(k / dimension)/(double)(dimension);
simulate_and_print(constants, iterations, output_style);
}
}
void simulate_and_print(Constants constants, int iterations, OutputType type) {
/*! Use this to change the length of the tape. */
const int BIT_STREAM_LENGTH = 8;
int first_pass_iterations = iterations;
System *systems = new System[first_pass_iterations];
int *histogram = new int[1<<BIT_STREAM_LENGTH];
std::fill_n(histogram, 1<<BIT_STREAM_LENGTH, 0);
long double *p = new long double[1<<BIT_STREAM_LENGTH];
long double *p_prime = new long double[1<<BIT_STREAM_LENGTH];
long double sum = 0;
const long double beta = log((1+constants.epsilon)/(1-constants.epsilon));
long double max_surprise = 0;
long double min_surprise = LONG_MAX;
#pragma omp parallel
{
//TODO: Move this into a semaphore in the utility function
gsl_rng *localRNG = GSLRandomNumberGenerator();
#pragma omp for
for (int k=0; k<first_pass_iterations; ++k) {
System *currentSystem = systems+k;
currentSystem->constants = constants;
currentSystem->nbits = BIT_STREAM_LENGTH;
evolveSystem(currentSystem, localRNG);
histogram[systems[k].endingBitString]++;
}
#pragma omp single nowait
delete [] systems;
#pragma omp for nowait
for(int k=0; k<1<<BIT_STREAM_LENGTH; k++) {
int setBits = bitCount(k,BIT_STREAM_LENGTH);
p[k] = gsl_ran_binomial_pdf(setBits, constants.delta, BIT_STREAM_LENGTH)/gsl_sf_choose(BIT_STREAM_LENGTH,setBits);
p_prime[k]=static_cast<long double>(histogram[k])/(first_pass_iterations);
}
#pragma omp single nowait
delete [] histogram;
#pragma omp barrier
#pragma omp for reduction(+ : sum)
for(int k=0; k<iterations; k++) {
System *currentSystem = new System();
currentSystem->constants = constants;
currentSystem->nbits = BIT_STREAM_LENGTH;
evolveSystem(currentSystem, localRNG);
long double surprise = exp(beta*currentSystem->mass)*p_prime[currentSystem->endingBitString]/p[currentSystem->startingBitString];
max_surprise = surprise > max_surprise ? surprise : max_surprise;
min_surprise = surprise && surprise < min_surprise ? surprise : min_surprise;
sum = sum + surprise;
delete currentSystem;
}
#pragma omp single nowait
{
delete [] p_prime;
delete [] p;
}
#pragma omp critical
{
if(type==CommaSeparated) {
static int once = 0;
if (!once) {
std::cout<<"delta,epsilon,avg,max_surprise\n";
once=1;
}
std::cout<< constants.delta << "," << constants.epsilon << "," << sum/iterations << "," << max_surprise << std::endl;
}
if(type==PrettyPrint) {
print(beta);
print(constants.delta);
print(constants.epsilon);
print(sum/iterations);
print(max_surprise);
print(sum);
std::cout<<std::endl;
}
if (type==Mathematica) {
assert(0);
}
}
gsl_rng_free(localRNG);
}
}
<|endoftext|> |
<commit_before>/*
vc_crt_fix_ulink.cpp
Workaround for Visual C++ CRT incompatibility with old Windows versions (ulink version)
*/
/*
Copyright © 2010 Far Group
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "disable_warnings_in_std_begin.hpp"
#include <windows.h>
#include "disable_warnings_in_std_end.hpp"
#include <delayimp.h>
//----------------------------------------------------------------------------
static LPVOID WINAPI no_recode_pointer(LPVOID p)
{
return p;
}
//----------------------------------------------------------------------------
static FARPROC WINAPI delayFailureHook(/*dliNotification*/unsigned dliNotify,
PDelayLoadInfo pdli)
{
if( dliNotify == /*dliFailGetProcAddress*/dliFailGetProc
&& pdli && pdli->cb == sizeof(*pdli)
&& pdli->hmodCur == GetModuleHandleA("kernel32")
&& pdli->dlp.fImportByName && pdli->dlp.szProcName
&& ( !lstrcmpA(pdli->dlp.szProcName, "EncodePointer")
|| !lstrcmpA(pdli->dlp.szProcName, "DecodePointer")))
{
return (FARPROC)no_recode_pointer;
}
return nullptr;
}
//----------------------------------------------------------------------------
#if _MSC_FULL_VER >= 190024215 // VS2015sp3
const
#endif
PfnDliHook __pfnDliFailureHook2 = (PfnDliHook)delayFailureHook;
//----------------------------------------------------------------------------
// TODO: Add GetModuleHandleExW
<commit_msg>remove compiler warning (VS2017.6)<commit_after>/*
vc_crt_fix_ulink.cpp
Workaround for Visual C++ CRT incompatibility with old Windows versions (ulink version)
*/
/*
Copyright © 2010 Far Group
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "disable_warnings_in_std_begin.hpp"
#include <windows.h>
#include "disable_warnings_in_std_end.hpp"
#include <delayimp.h>
//----------------------------------------------------------------------------
static LPVOID WINAPI no_recode_pointer(LPVOID p)
{
return p;
}
//----------------------------------------------------------------------------
static FARPROC WINAPI delayFailureHook(/*dliNotification*/unsigned dliNotify,
PDelayLoadInfo pdli)
{
if( dliNotify == /*dliFailGetProcAddress*/dliFailGetProc
&& pdli && pdli->cb == sizeof(*pdli)
&& pdli->hmodCur == GetModuleHandleA("kernel32")
&& pdli->dlp.fImportByName && pdli->dlp.szProcName
&& ( !lstrcmpA(pdli->dlp.szProcName, "EncodePointer")
|| !lstrcmpA(pdli->dlp.szProcName, "DecodePointer")))
{
#pragma warning(disable: 4191) // unsafe conversion from...to
return (FARPROC)no_recode_pointer;
#pragma warning(default: 4191)
}
return nullptr;
}
//----------------------------------------------------------------------------
#if _MSC_FULL_VER >= 190024215 // VS2015sp3
const
#endif
PfnDliHook __pfnDliFailureHook2 = (PfnDliHook)delayFailureHook;
//----------------------------------------------------------------------------
// TODO: Add GetModuleHandleExW
<|endoftext|> |
<commit_before>#ifndef UNIT_TEST
#include <Arduino.h>
#include <avr/wdt.h>
#include <DHT.h>
#include <TimerOne.h>
#include "lib/SDCard.h"
#include "PinMap.h"
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP085_U.h>
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
// #include "test/bmp.test.h"
SoftwareSerial gpsSerial(9, 10);
DHT dht(DHTPIN, DHTTYPE);
SDCard sd(SD_PIN);
Adafruit_BMP085_Unified bmp = Adafruit_BMP085_Unified(10085);
TinyGPSPlus gps;
float lat = 0.00;
float lng = 0.00;
float hum = 0;
float tmp = 0;
float hid = 0;
int mq7 = 0;
int mq2 = 0;
int mq135 = 0;
int readMQ(int pin) {
int value = analogRead(pin);
if (isnan(value)) {
return -1;
} else {
return value;
}
}
void serialize(char* fmt) {
sprintf(fmt, "{mq7:%i,mq2:%i,mq135:%i,hum:%i,tmp:%i,hid:%i;}", mq7, mq2, mq135, (int)hum, (int)tmp, (int)(hid+0.5));
}
void callback() {
mq7 = readMQ(MQ7PIN);
char foo [64];
sprintf(foo, "%d", mq7);
// Serial.println(foo);
// mq2 = readMQ(MQ2PIN);
// mq135 = readMQ(MQ135PIN);
// hid = dht.computeHeatIndex(tmp, hum, false);
//
// char fmt [64];
// serialize(fmt);
// if (Serial.available()) {
// Serial.println(fmt);
// }
}
long rgbToVoltage(long value) {
return map(value, 0, 255, 0, 1023);
}
ISR(WDT_vect) {
}
void setup() {
pinMode(LED_BLUE, OUTPUT);
pinMode(LED_GREEN, OUTPUT);
pinMode(LED_RED, OUTPUT);
analogWrite(LED_RED, rgbToVoltage(242));
analogWrite(LED_GREEN, rgbToVoltage(14));
analogWrite(LED_BLUE, rgbToVoltage(48));
Serial.begin(9600);
gpsSerial.begin(9600);
while(!Serial) {;}
// while(!gpsSerial) {;}
// // dht.begin();
Timer1.initialize(1000000);
Timer1.attachInterrupt(callback);
if(!sd.begin()) {
Serial.println("sd could not begin!");
while(1);
}
// setup went ok, blue color means good to go
// red light is more intense than the others, so the voltage is cut down by three
analogWrite(LED_RED, rgbToVoltage(39)/3);
analogWrite(LED_GREEN, rgbToVoltage(18));
analogWrite(LED_BLUE, rgbToVoltage(229));
// enable watchdog with 2 seconds timer
wdt_enable(WDTO_2S);
// sd.writeToFile("gpslog.txt", "lat, lng, time");
}
void loop() {
// send data only when you receive data:
if (gpsSerial.available() > 0) {
gps.encode(gpsSerial.read());
if (gps.location.isValid()) {
analogWrite(LED_RED, rgbToVoltage(39)/3);
analogWrite(LED_GREEN, rgbToVoltage(18));
analogWrite(LED_BLUE, rgbToVoltage(229));
lat = gps.location.lat();
lng = gps.location.lng();
char gpsData [64];
sprintf(gpsData, "%0.2f,%0.2f,%lu", lat, lng, (long unsigned int) gps.time.value());
sd.writeToFile("gpslog.txt", gpsData);
} else {
analogWrite(LED_RED, rgbToVoltage(242));
analogWrite(LED_GREEN, rgbToVoltage(14));
analogWrite(LED_BLUE, rgbToVoltage(48));
}
}
// reset watchdog timer
wdt_reset();
}
#endif
<commit_msg>fix lat lng types to double<commit_after>#ifndef UNIT_TEST
#include <Arduino.h>
#include <avr/wdt.h>
#include <DHT.h>
#include <TimerOne.h>
#include "lib/SDCard.h"
#include "PinMap.h"
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP085_U.h>
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
// #include "test/bmp.test.h"
SoftwareSerial gpsSerial(9, 10);
DHT dht(DHTPIN, DHTTYPE);
SDCard sd(SD_PIN);
Adafruit_BMP085_Unified bmp = Adafruit_BMP085_Unified(10085);
TinyGPSPlus gps;
double lat = 0.00;
double lng = 0.00;
float hum = 0;
float tmp = 0;
float hid = 0;
int mq7 = 0;
int mq2 = 0;
int mq135 = 0;
int readMQ(int pin) {
int value = analogRead(pin);
if (isnan(value)) {
return -1;
} else {
return value;
}
}
void serialize(char* fmt) {
sprintf(fmt, "{mq7:%i,mq2:%i,mq135:%i,hum:%i,tmp:%i,hid:%i;}", mq7, mq2, mq135, (int)hum, (int)tmp, (int)(hid+0.5));
}
void callback() {
mq7 = readMQ(MQ7PIN);
char foo [64];
sprintf(foo, "%d", mq7);
// Serial.println(foo);
// mq2 = readMQ(MQ2PIN);
// mq135 = readMQ(MQ135PIN);
// hid = dht.computeHeatIndex(tmp, hum, false);
//
// char fmt [64];
// serialize(fmt);
// if (Serial.available()) {
// Serial.println(fmt);
// }
}
long rgbToVoltage(long value) {
return map(value, 0, 255, 0, 1023);
}
ISR(WDT_vect) {
}
void setup() {
pinMode(LED_BLUE, OUTPUT);
pinMode(LED_GREEN, OUTPUT);
pinMode(LED_RED, OUTPUT);
analogWrite(LED_RED, rgbToVoltage(242));
analogWrite(LED_GREEN, rgbToVoltage(14));
analogWrite(LED_BLUE, rgbToVoltage(48));
Serial.begin(9600);
gpsSerial.begin(9600);
while(!Serial) {;}
// while(!gpsSerial) {;}
// // dht.begin();
Timer1.initialize(1000000);
Timer1.attachInterrupt(callback);
if(!sd.begin()) {
Serial.println("sd could not begin!");
while(1);
}
// setup went ok, blue color means good to go
// red light is more intense than the others, so the voltage is cut down by three
analogWrite(LED_RED, rgbToVoltage(39)/3);
analogWrite(LED_GREEN, rgbToVoltage(18));
analogWrite(LED_BLUE, rgbToVoltage(229));
// enable watchdog with 2 seconds timer
wdt_enable(WDTO_2S);
// sd.writeToFile("gpslog.txt", "lat, lng, time");
}
void loop() {
// send data only when you receive data:
if (gpsSerial.available() > 0) {
gps.encode(gpsSerial.read());
if (gps.location.isValid()) {
analogWrite(LED_RED, rgbToVoltage(39)/3);
analogWrite(LED_GREEN, rgbToVoltage(18));
analogWrite(LED_BLUE, rgbToVoltage(229));
lat = gps.location.lat();
lng = gps.location.lng();
char gpsData [64];
sprintf(gpsData, "%0.2f,%0.2f,%lu", lat, lng, (long unsigned int) gps.time.value());
sd.writeToFile("gpslog.txt", gpsData);
} else {
analogWrite(LED_RED, rgbToVoltage(242));
analogWrite(LED_GREEN, rgbToVoltage(14));
analogWrite(LED_BLUE, rgbToVoltage(48));
}
}
// reset watchdog timer
wdt_reset();
}
#endif
<|endoftext|> |
<commit_before>#include <iostream>
#include <cassert>
#include <cmath>
#include <tclap/CmdLine.h>
#include <fitsio.h>
#define fits_check(x) (x); if (status) { fits_report_error(stderr, status); exit(status); }
#define fits_checkp(x) (x); if (*status) { fits_report_error(stderr, *status); exit(*status); }
using namespace std;
const double NULL_VALUE = NAN;
long get_nimages(const string &filename) {
fitsfile *fptr;
int status = 0;
fits_check(fits_open_file(&fptr, filename.c_str(), READONLY, &status));
int hdutype = 0;
fits_check(fits_movabs_hdu(fptr, 2, &hdutype, &status));
assert(BINARY_TBL == hdutype);
long nrows = 0;
fits_check(fits_get_num_rows(fptr, &nrows, &status));
fits_check(fits_close_file(fptr, &status));
return nrows;
}
void compute_image_dimensions(const vector<string> &files, long *nobjects, long *nimages) {
*nobjects = files.size();
vector<long> sizes;
transform(files.begin(), files.end(), back_inserter(sizes), get_nimages);
*nimages = *max_element(sizes.begin(), sizes.end());
cout << endl;
}
vector<double> get_column(const string &filename, const string &column, int datatype, int *status) {
fitsfile *fptr;
long nimages = get_nimages(filename);
vector<double> out(nimages);
fits_checkp(fits_open_file(&fptr, filename.c_str(), READONLY, status));
fits_checkp(fits_movabs_hdu(fptr, 2, NULL, status));
int colnum = 0;
fits_checkp(fits_get_colnum(fptr, CASEINSEN, const_cast<char*>(column.c_str()), &colnum, status));
assert(0 != colnum);
cout << column << " column number: " << colnum << endl;
fits_checkp(fits_read_col(fptr, datatype, colnum, 1, 1, nimages, NULL, &out[0], NULL, status));
fits_checkp(fits_close_file(fptr, status));
return out;
}
void create_image_hdu(const string &hdu_name, const string &column, fitsfile *fptr, int datatype, const vector<string> &files, long nobjects, long nimages, int *status) {
long naxes[] = {nimages, nobjects};
switch (datatype) {
case TDOUBLE:
fits_checkp(fits_create_img(fptr, DOUBLE_IMG, 2, naxes, status));
break;
case TINT:
fits_checkp(fits_create_img(fptr, LONG_IMG, 2, naxes, status));
break;
default:
cerr << "Unsupported data type: " << datatype << endl;
exit(-1);
break;
}
/* Check that we've changed hdu */
int hdunum = 0;
fits_checkp(fits_get_hdu_num(fptr, &hdunum));
char *extname = const_cast<char*>(hdu_name.c_str());
fits_checkp(fits_update_key(fptr, TSTRING, "EXTNAME", extname, NULL, status));
for (int i=0; i<nobjects; i++) {
auto filename = files[i];
auto data = get_column(filename, column, datatype, status);
for (int j=data.size(); j<nimages; j++) {
data.push_back(NULL_VALUE);
}
long fpixel[] = {1, i + 1};
long lpixel[] = {nimages, i + 1};
fits_checkp(fits_write_subset(fptr, datatype, fpixel, lpixel, &data[0], status));
}
}
fitsfile *create_and_clobber(const string &filename) {
int status = 0;
fitsfile *fptr = nullptr;
fits_create_file(&fptr, filename.c_str(), &status);
if (FILE_NOT_CREATED == status) {
cerr << "File " << filename << " exists, overwriting" << endl;
remove(filename.c_str());
status = 0;
return create_and_clobber(filename);
} else if (0 != status) {
fits_report_error(stderr, status);
exit(status);
}
return fptr;
}
void combine_files(const vector<string> &files, const string &output) {
long nobjects = 0, nimages = 0;
fitsfile *fptr;
int status = 0;
compute_image_dimensions(files, &nobjects, &nimages);
cout << "Image dimensions: " << nimages << " images, " << nobjects << " objects" << endl;
fptr = create_and_clobber(output);
assert(nullptr != fptr);
/* Create the primary hdu */
fits_check(fits_create_img(fptr, BYTE_IMG, 0, NULL, &status));
/* Write the HDUS */
fits_check(create_image_hdu("HJD", "TIME", fptr, TDOUBLE, files, nobjects, nimages, &status));
fits_check(create_image_hdu("FLUX", "DETFLUX", fptr, TDOUBLE, files, nobjects, nimages, &status));
fits_check(create_image_hdu("FLUXERR", "DETFLUX_ERR", fptr, TDOUBLE, files, nobjects, nimages, &status));
fits_check(create_image_hdu("CCDX", "CENT_COL", fptr, TDOUBLE, files, nobjects, nimages, &status));
fits_check(create_image_hdu("CCDY", "CENT_ROW", fptr, TDOUBLE, files, nobjects, nimages, &status));
fits_check(create_image_hdu("QUALITY", "QUALITY", fptr, TINT, files, nobjects, nimages, &status));
fits_check(fits_close_file(fptr, &status));
}
int main(int argc, const char *argv[]) {
try {
TCLAP::CmdLine cmd("extract", ' ', "0.0.1");
TCLAP::UnlabeledMultiArg<string> filesArg("files", "files to combine", true, "filename", cmd);
TCLAP::ValueArg<string> outputArg("o", "output", "output filename", true, "", "filename", cmd);
cmd.parse(argc, argv);
combine_files(filesArg.getValue(), outputArg.getValue());
} catch (TCLAP::ArgException &e) {
std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
return 1;
}
return 0;
}
<commit_msg>Add print statements<commit_after>#include <iostream>
#include <cassert>
#include <cmath>
#include <tclap/CmdLine.h>
#include <fitsio.h>
#define fits_check(x) (x); if (status) { fits_report_error(stderr, status); exit(status); }
#define fits_checkp(x) (x); if (*status) { fits_report_error(stderr, *status); exit(*status); }
using namespace std;
const double NULL_VALUE = NAN;
long get_nimages(const string &filename) {
fitsfile *fptr;
int status = 0;
fits_check(fits_open_file(&fptr, filename.c_str(), READONLY, &status));
int hdutype = 0;
fits_check(fits_movabs_hdu(fptr, 2, &hdutype, &status));
assert(BINARY_TBL == hdutype);
long nrows = 0;
fits_check(fits_get_num_rows(fptr, &nrows, &status));
fits_check(fits_close_file(fptr, &status));
return nrows;
}
void compute_image_dimensions(const vector<string> &files, long *nobjects, long *nimages) {
*nobjects = files.size();
vector<long> sizes;
transform(files.begin(), files.end(), back_inserter(sizes), get_nimages);
*nimages = *max_element(sizes.begin(), sizes.end());
cout << endl;
}
vector<double> get_column(const string &filename, const string &column, int datatype, int *status) {
fitsfile *fptr;
long nimages = get_nimages(filename);
vector<double> out(nimages);
fits_checkp(fits_open_file(&fptr, filename.c_str(), READONLY, status));
fits_checkp(fits_movabs_hdu(fptr, 2, NULL, status));
int colnum = 0;
fits_checkp(fits_get_colnum(fptr, CASEINSEN, const_cast<char*>(column.c_str()), &colnum, status));
assert(0 != colnum);
cout << column << " column number: " << colnum << endl;
fits_checkp(fits_read_col(fptr, datatype, colnum, 1, 1, nimages, NULL, &out[0], NULL, status));
fits_checkp(fits_close_file(fptr, status));
return out;
}
void create_image_hdu(const string &hdu_name, const string &column, fitsfile *fptr, int datatype, const vector<string> &files, long nobjects, long nimages, int *status) {
cout << "Creating " << hdu_name << " hdu, from column " << column << endl;
long naxes[] = {nimages, nobjects};
switch (datatype) {
case TDOUBLE:
fits_checkp(fits_create_img(fptr, DOUBLE_IMG, 2, naxes, status));
break;
case TINT:
fits_checkp(fits_create_img(fptr, LONG_IMG, 2, naxes, status));
break;
default:
cerr << "Unsupported data type: " << datatype << endl;
exit(-1);
break;
}
/* Check that we've changed hdu */
int hdunum = 0;
fits_checkp(fits_get_hdu_num(fptr, &hdunum));
cout << "Writing hdu name" << endl;
char *extname = const_cast<char*>(hdu_name.c_str());
fits_checkp(fits_update_key(fptr, TSTRING, "EXTNAME", extname, NULL, status));
for (int i=0; i<nobjects; i++) {
auto filename = files[i];
cout << "Updating from file " << filename << endl;
auto data = get_column(filename, column, datatype, status);
for (int j=data.size(); j<nimages; j++) {
data.push_back(NULL_VALUE);
}
long fpixel[] = {1, i + 1};
long lpixel[] = {nimages, i + 1};
fits_checkp(fits_write_subset(fptr, datatype, fpixel, lpixel, &data[0], status));
}
}
fitsfile *create_and_clobber(const string &filename) {
int status = 0;
fitsfile *fptr = nullptr;
fits_create_file(&fptr, filename.c_str(), &status);
if (FILE_NOT_CREATED == status) {
cerr << "File " << filename << " exists, overwriting" << endl;
remove(filename.c_str());
status = 0;
return create_and_clobber(filename);
} else if (0 != status) {
fits_report_error(stderr, status);
exit(status);
}
return fptr;
}
void combine_files(const vector<string> &files, const string &output) {
long nobjects = 0, nimages = 0;
fitsfile *fptr;
int status = 0;
compute_image_dimensions(files, &nobjects, &nimages);
cout << "Image dimensions: " << nimages << " images, " << nobjects << " objects" << endl;
fptr = create_and_clobber(output);
assert(nullptr != fptr);
/* Create the primary hdu */
cout << "Creating primary hdu" << endl;
fits_check(fits_create_img(fptr, BYTE_IMG, 0, NULL, &status));
/* Write the image HDUS */
fits_check(create_image_hdu("HJD", "TIME", fptr, TDOUBLE, files, nobjects, nimages, &status));
fits_check(create_image_hdu("FLUX", "DETFLUX", fptr, TDOUBLE, files, nobjects, nimages, &status));
fits_check(create_image_hdu("FLUXERR", "DETFLUX_ERR", fptr, TDOUBLE, files, nobjects, nimages, &status));
fits_check(create_image_hdu("CCDX", "CENT_COL", fptr, TDOUBLE, files, nobjects, nimages, &status));
fits_check(create_image_hdu("CCDY", "CENT_ROW", fptr, TDOUBLE, files, nobjects, nimages, &status));
fits_check(create_image_hdu("QUALITY", "QUALITY", fptr, TINT, files, nobjects, nimages, &status));
fits_check(fits_close_file(fptr, &status));
}
int main(int argc, const char *argv[]) {
try {
TCLAP::CmdLine cmd("extract", ' ', "0.0.1");
TCLAP::UnlabeledMultiArg<string> filesArg("files", "files to combine", true, "filename", cmd);
TCLAP::ValueArg<string> outputArg("o", "output", "output filename", true, "", "filename", cmd);
cmd.parse(argc, argv);
combine_files(filesArg.getValue(), outputArg.getValue());
} catch (TCLAP::ArgException &e) {
std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <cv.h>
#include <highgui.h>
#include <unistd.h>
using namespace std;
using namespace cv;
typedef Vec3b Color;
typedef vector<Mat> World;
typedef Color (*Rule)(Color, const vector<Color> &);
typedef struct {
unsigned int thread_id;
unsigned int thread_count;
World *src;
World *dst;
Rule r;
} thread_data;
void set_color(World &, int x, int y, int t, Color);
Color get_color(const World &, int x, int y, int t);
void *update_thread(void *);
void update(World *src, World *dst, Rule, unsigned int thread_count);
Color my_rule(Color, const vector<Color> &);
/*** Customize this rule ***/
Color my_rule(Color c, const vector<Color> &cs) {
float r = 0;
float g = 0;
float b = 0;
for (int i = 0; i < (int)cs.size(); i++) {
r += cs[i][2];
g += cs[i][1];
b += cs[i][0];
}
r /= cs.size()-1;
g /= cs.size()-1;
b /= cs.size()-1;
c[0] = b;
c[1] = g;
c[2] = r;
return c;
}
/***************************/
void set_color(World &w, int x, int y, int t, Color c) {
Mat m = w.at(t);
m.at<Vec3b>(y,x) = c;
}
Color get_color(const World &w, int x, int y, int t) {
Mat m = w.at(t);
return m.at<Vec3b>(y,x);
}
void *update_thread(void *data) {
thread_data *d = (thread_data*)data;
World *src = d->src;
World *dst = d->dst;
Rule r = d->r;
int x_min = 0;
int y_min = 0;
int t_min = 0;
int x_max = src->at(0).cols-1;
int y_max = src->at(0).rows-1;
int t_max = src->size()-1;
for (int t = d->thread_id; t < (int)src->size(); t+=d->thread_count) {
cout << ".";
for (int y = 0; y < src->at(t).rows; y++)
for (int x = 0; x < src->at(t).cols; x++) {
Color c = get_color(*src, x, y, t);
vector<Color> neighbors;
for (int dt = -1; dt <= 1; dt++) {
if (t+dt >= t_min && t+dt <= t_max) {
if (x-1 >= x_min) neighbors.push_back(get_color(*src,x-1,y,t+dt));
if (x+1 <= x_max) neighbors.push_back(get_color(*src,x+1,y,t+dt));
if (y-1 >= y_min) neighbors.push_back(get_color(*src,x,y-1,t+dt));
if (y+1 <= y_max) neighbors.push_back(get_color(*src,x,y+1,t+dt));
if (x-1 >= x_min && y-1 >= y_min) neighbors.push_back(get_color(*src,x-1,y-1,t+dt));
if (x+1 <= x_max && y-1 >= y_min) neighbors.push_back(get_color(*src,x+1,y-1,t+dt));
if (x-1 >= x_min && y+1 <= y_max) neighbors.push_back(get_color(*src,x-1,y+1,t+dt));
if (x+1 <= x_max && y+1 <= y_max) neighbors.push_back(get_color(*src,x+1,y+1,t+dt));
if (dt != 0) neighbors.push_back(get_color(*src,x,y,t+dt));
}
}
set_color(*dst, x, y, t, r(c, neighbors));
}
}
return NULL;
}
void update(World *src, World *dst, Rule r, unsigned int thread_count) {
pthread_t threads[thread_count];
int irets[thread_count];
thread_data data[thread_count];
for (unsigned int i = 0; i < thread_count; i++) {
data[i] = thread_data{i, thread_count, src, dst, my_rule};
irets[i] = pthread_create(&threads[i], NULL, update_thread, &data);
if (irets[i]) {
fprintf(stderr,"Error - pthread_create() return code: %d\n",irets[i]);
exit(EXIT_FAILURE);
}
}
for (unsigned int i = 0; i < thread_count; i++) {
pthread_join(threads[i], NULL);
}
}
int main(int argc, char **argv) {
setbuf(stdout, NULL);
int tvalue = 1;
char *ivalue = NULL;
int c;
opterr = 0;
while ((c = getopt(argc, argv, "t:i:")) != -1) {
switch (c) {
case 't':
tvalue = atoi(optarg);
break;
case 'i':
ivalue = optarg;
break;
case '?':
if (optopt == 'i')
fprintf(stderr, "Option -%c requires an argument.\n", optopt);
else if(isprint(optopt))
fprintf(stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf(stderr,
"Unknown option character `\\x%x'.\n",
optopt);
return 1;
default:
abort();
}
}
cout << argc - optind<< endl;
char usage[] = "usage: %s -i inputfile [-t threadcount] outputfile\n";
if (ivalue == NULL || argc - optind != 1) {
fprintf(stderr, usage, argv[0]);
return 1;
}
VideoCapture vc = VideoCapture(ivalue);
if (!vc.isOpened())
return 1;
vector<Mat> framesFront, framesBack;
Mat f;
for (int i = 0; i < vc.get(CV_CAP_PROP_FRAME_COUNT); i++) {
cout << "Frame " << i << "..." << endl;
vc >> f;
framesFront.push_back(f.clone());
framesBack.push_back(f.clone());
}
VideoWriter vw;
int ex = CV_FOURCC('I', 'Y', 'U', 'V');
vw.open("out.avi", ex, vc.get(CV_CAP_PROP_FPS), f.size());
vector<Mat> *src = &framesFront;
vector<Mat> *dst = &framesBack;
for (int i = 0; i < vc.get(CV_CAP_PROP_FRAME_COUNT); i++) {
cout << "Frame " << i;
update(src, dst, my_rule, tvalue);
cout << "writing...";
vw.write(dst->at(i));
swap(src, dst);
cout << "done." << endl;
}
return 0;
}
<commit_msg>removed some debugging stuff i forgot to remove on the last commit<commit_after>#include <iostream>
#include <cv.h>
#include <highgui.h>
#include <unistd.h>
using namespace std;
using namespace cv;
typedef Vec3b Color;
typedef vector<Mat> World;
typedef Color (*Rule)(Color, const vector<Color> &);
typedef struct {
unsigned int thread_id;
unsigned int thread_count;
World *src;
World *dst;
Rule r;
} thread_data;
void set_color(World &, int x, int y, int t, Color);
Color get_color(const World &, int x, int y, int t);
void *update_thread(void *);
void update(World *src, World *dst, Rule, unsigned int thread_count);
Color my_rule(Color, const vector<Color> &);
/*** Customize this rule ***/
Color my_rule(Color c, const vector<Color> &cs) {
float r = 0;
float g = 0;
float b = 0;
for (int i = 0; i < (int)cs.size(); i++) {
r += cs[i][2];
g += cs[i][1];
b += cs[i][0];
}
r /= cs.size();
g /= cs.size();
b /= cs.size();
c[0] = b;
c[1] = g;
c[2] = r;
return c;
}
/***************************/
void set_color(World &w, int x, int y, int t, Color c) {
Mat m = w.at(t);
m.at<Vec3b>(y,x) = c;
}
Color get_color(const World &w, int x, int y, int t) {
Mat m = w.at(t);
return m.at<Vec3b>(y,x);
}
void *update_thread(void *data) {
thread_data *d = (thread_data*)data;
World *src = d->src;
World *dst = d->dst;
Rule r = d->r;
int x_min = 0;
int y_min = 0;
int t_min = 0;
int x_max = src->at(0).cols-1;
int y_max = src->at(0).rows-1;
int t_max = src->size()-1;
for (int t = d->thread_id; t < (int)src->size(); t+=d->thread_count) {
cout << ".";
for (int y = 0; y < src->at(t).rows; y++)
for (int x = 0; x < src->at(t).cols; x++) {
Color c = get_color(*src, x, y, t);
vector<Color> neighbors;
for (int dt = -1; dt <= 1; dt++) {
if (t+dt >= t_min && t+dt <= t_max) {
if (x-1 >= x_min) neighbors.push_back(get_color(*src,x-1,y,t+dt));
if (x+1 <= x_max) neighbors.push_back(get_color(*src,x+1,y,t+dt));
if (y-1 >= y_min) neighbors.push_back(get_color(*src,x,y-1,t+dt));
if (y+1 <= y_max) neighbors.push_back(get_color(*src,x,y+1,t+dt));
if (x-1 >= x_min && y-1 >= y_min) neighbors.push_back(get_color(*src,x-1,y-1,t+dt));
if (x+1 <= x_max && y-1 >= y_min) neighbors.push_back(get_color(*src,x+1,y-1,t+dt));
if (x-1 >= x_min && y+1 <= y_max) neighbors.push_back(get_color(*src,x-1,y+1,t+dt));
if (x+1 <= x_max && y+1 <= y_max) neighbors.push_back(get_color(*src,x+1,y+1,t+dt));
if (dt != 0) neighbors.push_back(get_color(*src,x,y,t+dt));
}
}
set_color(*dst, x, y, t, r(c, neighbors));
}
}
return NULL;
}
void update(World *src, World *dst, Rule r, unsigned int thread_count) {
pthread_t threads[thread_count];
int irets[thread_count];
thread_data data[thread_count];
for (unsigned int i = 0; i < thread_count; i++) {
data[i] = thread_data{i, thread_count, src, dst, my_rule};
irets[i] = pthread_create(&threads[i], NULL, update_thread, &data);
if (irets[i]) {
fprintf(stderr,"Error - pthread_create() return code: %d\n",irets[i]);
exit(EXIT_FAILURE);
}
}
for (unsigned int i = 0; i < thread_count; i++) {
pthread_join(threads[i], NULL);
}
}
int main(int argc, char **argv) {
setbuf(stdout, NULL);
int tvalue = 1;
char *ivalue = NULL;
int c;
opterr = 0;
while ((c = getopt(argc, argv, "t:i:")) != -1) {
switch (c) {
case 't':
tvalue = atoi(optarg);
break;
case 'i':
ivalue = optarg;
break;
case '?':
if (optopt == 'i')
fprintf(stderr, "Option -%c requires an argument.\n", optopt);
else if(isprint(optopt))
fprintf(stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf(stderr,
"Unknown option character `\\x%x'.\n",
optopt);
return 1;
default:
abort();
}
}
cout << argc - optind<< endl;
char usage[] = "usage: %s -i inputfile [-t threadcount] outputfile\n";
if (ivalue == NULL || argc - optind != 1) {
fprintf(stderr, usage, argv[0]);
return 1;
}
VideoCapture vc = VideoCapture(ivalue);
if (!vc.isOpened())
return 1;
vector<Mat> framesFront, framesBack;
Mat f;
for (int i = 0; i < vc.get(CV_CAP_PROP_FRAME_COUNT); i++) {
cout << "Frame " << i << "..." << endl;
vc >> f;
framesFront.push_back(f.clone());
framesBack.push_back(f.clone());
}
VideoWriter vw;
int ex = CV_FOURCC('I', 'Y', 'U', 'V');
vw.open("out.avi", ex, vc.get(CV_CAP_PROP_FPS), f.size());
vector<Mat> *src = &framesFront;
vector<Mat> *dst = &framesBack;
for (int i = 0; i < vc.get(CV_CAP_PROP_FRAME_COUNT); i++) {
cout << "Frame " << i;
update(src, dst, my_rule, tvalue);
cout << "writing...";
vw.write(dst->at(i));
swap(src, dst);
cout << "done." << endl;
}
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <multihash/multihash.h>
#include <boost/program_options.hpp>
#define BOOST_FILESYSTEM_NO_DEPRECATED
#include <boost/filesystem.hpp>
namespace po = boost::program_options;
int main(int argc, char* argv[])
{
// Declare the supported options.
std::ostringstream os;
os << "Usage: multihash [OPTION]... [FILE]...\n"
<< "Print cryptographic digests.\n"
<< "With no FILE or when file is -, read standard input";
po::options_description desc(os.str());
desc.add_options()
("help", "display help message")
("hash-type", po::value<std::string>(), "algorithm, e.g sha1")
("list-hash-types", "list all available algorithms");
po::variables_map vm;
try
{
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
std::cerr << desc << std::endl;
return 1;
}
if (vm.count("help") > 0)
{
std::cout << desc << std::endl;
return 0;
}
if (vm.count("list-hash-types") > 0)
{
for (auto hash_type : multihash::hashTypes())
{
std::cout << hash_type.name() << std::endl;
}
return 0;
}
/** Actually do some work if an algo is specified */
std::string algo;
if (vm.count("hash-type") == 1)
{
algo = vm["hash-type"].as<std::string>();
}
else
{
std::cerr << "Must specify a hash type" << std::endl;
std::cerr << desc << std::endl;
return 1;
}
try
{
auto hash_function = multihash::HashFunction(algo);
std::ios_base::sync_with_stdio(false); //enable fast io
std::vector<std::string> filenames;
if (argc > 3)
{
filenames.assign(&argv[3], &argv[argc-1]);
}
auto num_files = filenames.size();
if ((num_files == 1 && (filenames.front() == "-")) or num_files == 0)
{
auto hash = hash_function(std::cin);
std::cout << hash << " -" << std::endl;
}
else
{
for (auto filename : filenames)
{
if (!boost::filesystem::exists(filename))
{
std::cerr << "multihash: " << filename
<< ": No such file or directory" << std::endl;
continue;
}
else if (boost::filesystem::is_directory(filename))
{
std::cerr << "multihash: " << filename
<< ": Is a directory" << std::endl;
continue;
}
auto filestream = std::ifstream(filename);
if (filestream.good())
{
auto hash = hash_function(filestream);
std::cout << hash << " " << filename << std::endl;
}
else
{
std::cerr << "multihash: " << filename << ": "
<< "Permission denied" << std::endl;
}
}
}
}
catch (multihash::InvalidHashException& e)
{
std::cerr << "ERROR: " << e.what() << std::endl;
std::cout << "Available hash types: " << std::endl;
for (auto hash_type : multihash::hashTypes())
{
std::cout << hash_type.name() << std::endl;
}
}
return 0;
}
<commit_msg>Fixed off-by-one error in filelist<commit_after>#include <iostream>
#include <fstream>
#include <multihash/multihash.h>
#include <boost/program_options.hpp>
#define BOOST_FILESYSTEM_NO_DEPRECATED
#include <boost/filesystem.hpp>
namespace po = boost::program_options;
int main(int argc, char* argv[])
{
// Declare the supported options.
std::ostringstream os;
os << "Usage: multihash [OPTION]... [FILE]...\n"
<< "Print cryptographic digests.\n"
<< "With no FILE or when file is -, read standard input";
po::options_description desc(os.str());
desc.add_options()
("help", "display help message")
("hash-type", po::value<std::string>(), "algorithm, e.g sha1")
("list-hash-types", "list all available algorithms");
po::variables_map vm;
try
{
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
std::cerr << desc << std::endl;
return 1;
}
if (vm.count("help") > 0)
{
std::cout << desc << std::endl;
return 0;
}
if (vm.count("list-hash-types") > 0)
{
for (auto hash_type : multihash::hashTypes())
{
std::cout << hash_type.name() << std::endl;
}
return 0;
}
/** Actually do some work if an algo is specified */
std::string algo;
if (vm.count("hash-type") == 1)
{
algo = vm["hash-type"].as<std::string>();
}
else
{
std::cerr << "Must specify a hash type" << std::endl;
std::cerr << desc << std::endl;
return 1;
}
try
{
auto hash_function = multihash::HashFunction(algo);
std::ios_base::sync_with_stdio(false); //enable fast io
std::vector<std::string> filenames;
if (argc > 3)
{
filenames.assign(&argv[3], &argv[argc]);
}
auto num_files = filenames.size();
if ((num_files == 1 && (filenames.front() == "-")) or num_files == 0)
{
auto hash = hash_function(std::cin);
std::cout << hash << " -" << std::endl;
}
else
{
for (auto filename : filenames)
{
if (!boost::filesystem::exists(filename))
{
std::cerr << "multihash: " << filename
<< ": No such file or directory" << std::endl;
continue;
}
else if (boost::filesystem::is_directory(filename))
{
std::cerr << "multihash: " << filename
<< ": Is a directory" << std::endl;
continue;
}
auto filestream = std::ifstream(filename);
if (filestream.good())
{
auto hash = hash_function(filestream);
std::cout << hash << " " << filename << std::endl;
}
else
{
std::cerr << "multihash: " << filename << ": "
<< "Permission denied" << std::endl;
}
}
}
}
catch (multihash::InvalidHashException& e)
{
std::cerr << "ERROR: " << e.what() << std::endl;
std::cout << "Available hash types: " << std::endl;
for (auto hash_type : multihash::hashTypes())
{
std::cout << hash_type.name() << std::endl;
}
}
return 0;
}
<|endoftext|> |
<commit_before>#include "mainwindow.h"
#include <QApplication>
#include <QMessageBox>
#include "visuserver.h"
#include "visuapplication.h"
#include "exceptions/configloadexception.h"
#define DEFAULT_CONFIG "configs/default.xml"
void showMessageBox(QString message)
{
QMessageBox::warning(
NULL,
"Error",
message);
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
try
{
if (argc > 1 && QString(argv[1]) == "--editor" )
{
new MainWindow();
}
else
{
QString xmlPath = (argc > 1) ? QString(argv[1]) : DEFAULT_CONFIG;
VisuApplication *application = new VisuApplication(xmlPath);
application->show();
application->run();
}
}
catch(ConfigLoadException e)
{
showMessageBox(e.what());
return 1;
}
catch(...)
{
showMessageBox("Unknown exception!");
return 1;
}
return a.exec();
}
<commit_msg>Application starts in editor mode by default<commit_after>#include "mainwindow.h"
#include <QApplication>
#include <QMessageBox>
#include "visuserver.h"
#include "visuapplication.h"
#include "exceptions/configloadexception.h"
#define DEFAULT_CONFIG "configs/default.xml"
void showMessageBox(QString message)
{
QMessageBox::warning(
NULL,
"Error",
message);
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
try
{
if (argc == 1)
{
new MainWindow();
}
else
{
QString xmlPath = (argc > 1) ? QString(argv[1]) : DEFAULT_CONFIG;
VisuApplication *application = new VisuApplication(xmlPath);
application->show();
application->run();
}
}
catch(ConfigLoadException e)
{
showMessageBox(e.what());
return 1;
}
catch(...)
{
showMessageBox("Unknown exception!");
return 1;
}
return a.exec();
}
<|endoftext|> |
<commit_before>// Copyright © 2014-2016 Ryan Leckey, All Rights Reserved.
// Distributed under the MIT License
// See accompanying file LICENSE
#include <cstdio>
#include <deque>
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include "cppformat/format.h"
#include "arrow/tokenizer.hpp"
#include "arrow/command.hpp"
void help(char* binary_path) {
std::printf(
"Usage: \x1b[0;36m%s\x1b[0m [<command>] [<options>] <input-file>\n",
binary_path);
std::printf("\n");
}
int main(int argc, char** argv, char** environ) {
// Register available commands
std::deque<std::shared_ptr<arrow::Command>> commands;
commands.push_back(std::make_shared<arrow::command::Parse>());
commands.push_back(std::make_shared<arrow::command::Tokenize>());
// Check for a specified command
std::vector<char*> args(argv, argv + argc);
unsigned cmd_index = 0;
bool found = false;
if (args.size() >= 2) {
std::string a1(args[1]);
if (a1.size() >= 3 && a1[0] == '-' && a1[1] == '-') {
// The first arguments is `--[...]`
auto command_name = a1.substr(2);
for (unsigned i = 0; i < commands.size(); ++i) {
if (command_name == commands[i]->name()) {
found = true;
cmd_index = i;
break;
}
}
if (found) {
// Remove the command argument
args.erase(args.begin() + 1);
}
}
} else {
// Show help
// help(argv[0], commands);
help(argv[0]);
return 0;
}
if (!found) {
std::string a1(args[1]);
if (a1.substr(2) == "help" || a1.substr(1) == "h") {
// Show help
// help(argv[0], commands);
help(argv[0]);
return 0;
}
}
// Get the requested command
auto cmd = commands.at(cmd_index);
// Run the received command
return (*cmd)(args.size(), args.data(), environ);
}
<commit_msg>Improve help display<commit_after>// Copyright © 2014-2016 Ryan Leckey, All Rights Reserved.
// Distributed under the MIT License
// See accompanying file LICENSE
#include <cstdio>
#include <deque>
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include "cppformat/format.h"
#include "arrow/tokenizer.hpp"
#include "arrow/command.hpp"
void help(char* binary_path,
const std::deque<std::shared_ptr<arrow::Command>>& commands) {
std::printf(
"Usage: \x1b[0;36m%s\x1b[0m [<command>] [<options>] <input-file>\n",
binary_path);
std::printf("Commands:\n");
for (auto& cmd : commands) {
std::printf(" \x1b[0;33m--%-10s\x1b[0m", cmd->name());
std::printf("%s", cmd->description());
std::printf("\n");
}
std::printf(" \x1b[0;33m--%-10s\x1b[0m", "help");
std::printf("Display this help information");
std::printf("\n");
std::printf("\n");
}
int main(int argc, char** argv, char** environ) {
// Register available commands
std::deque<std::shared_ptr<arrow::Command>> commands;
commands.push_back(std::make_shared<arrow::command::Parse>());
commands.push_back(std::make_shared<arrow::command::Tokenize>());
// Check for a specified command
std::vector<char*> args(argv, argv + argc);
unsigned cmd_index = 0;
bool found = false;
if (args.size() >= 2) {
std::string a1(args[1]);
if (a1.size() >= 3 && a1[0] == '-' && a1[1] == '-') {
// The first arguments is `--[...]`
auto command_name = a1.substr(2);
for (unsigned i = 0; i < commands.size(); ++i) {
if (command_name == commands[i]->name()) {
found = true;
cmd_index = i;
break;
}
}
if (found) {
// Remove the command argument
args.erase(args.begin() + 1);
}
}
} else {
// Show help
help(argv[0], commands);
return 0;
}
if (!found) {
std::string a1(args[1]);
if (a1.substr(2) == "help" || a1.substr(1) == "h") {
// Show help
help(argv[0], commands);
return 0;
}
}
// Get the requested command
auto cmd = commands.at(cmd_index);
// Run the received command
return (*cmd)(args.size(), args.data(), environ);
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2016-2017 Genome Research Ltd.
Author: Marcus D. R. Klarqvist <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <iostream>
#include <getopt.h>
#include "utility.h"
#include "calc.h"
#include "import.h"
#include "view.h"
#include "sort.h"
#include "index.h"
#include "concat.h"
#include "stats.h"
int main(int argc, char** argv){
if(Tomahawk::Helpers::isBigEndian()){
std::cerr << Tomahawk::Helpers::timestamp("ERROR") << "Tomahawk does not support big endian systems..." << std::endl;
return(1);
}
if(argc == 1){
programMessage();
programHelpDetailed();
return(1);
}
// Literal string input line
Tomahawk::Constants::LITERAL_COMMAND_LINE = Tomahawk::Constants::PROGRAM_NAME;
for(U32 i = 1; i < argc; ++i)
Tomahawk::Constants::LITERAL_COMMAND_LINE += " " + std::string(&argv[i][0]);
if(strncmp(&argv[1][0], "import", 5) == 0){
return(import(argc, argv));
} else if(strncmp(&argv[1][0], "calc", 4) == 0){
return(calc(argc, argv));
} else if(strncmp(&argv[1][0], "view", 4) == 0){
return(view(argc, argv));
} else if(strncmp(&argv[1][0], "sort", 4) == 0){
return(sort(argc, argv));
} else if(strncmp(&argv[1][0], "index", 5) == 0){
//return(index(argc, argv));
std::cerr << "Not implemented" << std::endl;
return(1);
} else if(strncmp(&argv[1][0], "concat", 6) == 0){
return(concat(argc, argv));
} else if(strncmp(&argv[1][0], "stats", 5) == 0){
return(stats(argc, argv));
//std::cerr << "Not implemented" << std::endl;
//return(1);
} else if(strncmp(&argv[1][0], "--version", 9) == 0 || strncmp(&argv[1][0], "version", 7) == 0){
programMessage(false);
return(0);
} else if(strncmp(&argv[1][0], "--help", 6) == 0 || strncmp(&argv[1][0], "help", 4) == 0){
programMessage();
programHelpDetailed();
return(0);
} else {
programMessage();
programHelpDetailed();
std::cerr << Tomahawk::Helpers::timestamp("ERROR") << "Illegal command" << std::endl;
return(1);
}
return(1);
}
<commit_msg>trigger<commit_after>/*
Copyright (C) 2016-2017 Genome Research Ltd.
Author: Marcus D. R. Klarqvist <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <iostream>
#include <getopt.h>
#include "utility.h"
#include "calc.h"
#include "import.h"
#include "view.h"
#include "sort.h"
#include "index.h"
#include "concat.h"
#include "stats.h"
int main(int argc, char** argv){
if(Tomahawk::Helpers::isBigEndian()){
std::cerr << Tomahawk::Helpers::timestamp("ERROR") << "Tomahawk does not support big endian systems..." << std::endl;
return(1);
}
if(argc == 1){
programMessage();
programHelpDetailed();
return(1);
}
// Literal string input line
Tomahawk::Constants::LITERAL_COMMAND_LINE = Tomahawk::Constants::PROGRAM_NAME;
for(U32 i = 1; i < argc; ++i)
Tomahawk::Constants::LITERAL_COMMAND_LINE += " " + std::string(&argv[i][0]);
if(strncmp(&argv[1][0], "import", 5) == 0){
return(import(argc, argv));
} else if(strncmp(&argv[1][0], "calc", 4) == 0){
return(calc(argc, argv));
} else if(strncmp(&argv[1][0], "view", 4) == 0){
return(view(argc, argv));
} else if(strncmp(&argv[1][0], "sort", 4) == 0){
return(sort(argc, argv));
} else if(strncmp(&argv[1][0], "index", 5) == 0){
//return(index(argc, argv));
std::cerr << "Not implemented" << std::endl;
return(1);
} else if(strncmp(&argv[1][0], "concat", 6) == 0){
return(concat(argc, argv));
} else if(strncmp(&argv[1][0], "stats", 5) == 0){
return(stats(argc, argv));
} else if(strncmp(&argv[1][0], "--version", 9) == 0 || strncmp(&argv[1][0], "version", 7) == 0){
programMessage(false);
return(0);
} else if(strncmp(&argv[1][0], "--help", 6) == 0 || strncmp(&argv[1][0], "help", 4) == 0){
programMessage();
programHelpDetailed();
return(0);
} else {
programMessage();
programHelpDetailed();
std::cerr << Tomahawk::Helpers::timestamp("ERROR") << "Illegal command" << std::endl;
return(1);
}
return(1);
}
<|endoftext|> |
<commit_before>#include <algorithm>
#include <thread>
#include <iostream>
#include <cassert> /* assert */
#include <glm/ext.hpp>
#include <vtkIndent.h>
#include <vtkTable.h>
#include <vtkVariant.h>
#include <vtkUnstructuredGrid.h>
#include "persistence_curve_widget.h"
PersistenceCurveWidget::PersistenceCurveWidget(vtkSmartPointer<vtkXMLImageDataReader> input, unsigned int debug)
: tree_type(ttk::TreeType::Split), debuglevel(debug)
{
diagram = vtkSmartPointer<vtkPersistenceDiagram>::New();
diagram->SetdebugLevel_(debuglevel);
diagram->SetInputConnection(input->GetOutputPort());
// Compute critical points
critical_pairs = vtkSmartPointer<vtkThreshold>::New();
critical_pairs->SetInputConnection(diagram->GetOutputPort());
critical_pairs->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_CELLS, "PairIdentifier");
critical_pairs->ThresholdBetween(-0.1, 999999);
// Select the most persistent pairs
persistent_pairs = vtkSmartPointer<vtkThreshold>::New();
persistent_pairs->SetInputConnection(critical_pairs->GetOutputPort());
persistent_pairs->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_CELLS, "Persistence");
// Start at a persistence above one so we filter out some junk
threshold_range[0] = 4.f;
persistent_pairs->ThresholdBetween(threshold_range[0], 999999);
// Simplifying the input data to remove non-persistent pairs
simplification = vtkSmartPointer<vtkTopologicalSimplification>::New();
simplification->SetdebugLevel_(debuglevel);
simplification->SetUseAllCores(true);
simplification->SetThreadNumber(std::thread::hardware_concurrency());
simplification->SetInputConnection(0, input->GetOutputPort());
simplification->SetInputConnection(1, persistent_pairs->GetOutputPort());
// We always show the full curve, without simplfication for the
// selected tree type
vtkcurve = vtkSmartPointer<vtkPersistenceCurve>::New();
vtkcurve->SetdebugLevel_(debuglevel);
vtkcurve->SetInputConnection(input->GetOutputPort());
vtkcurve->SetComputeSaddleConnectors(false);
vtkcurve->SetUseAllCores(true);
vtkcurve->SetThreadNumber(std::thread::hardware_concurrency());
vtkcurve->Update();
update_persistence_curve();
update_persistence_diagram();
}
vtkTopologicalSimplification* PersistenceCurveWidget::get_simplification() const {
return simplification.Get();
}
void PersistenceCurveWidget::draw_ui() {
if (ImGui::Begin("Persistence Plots"))
{
// we need to tell how large each plot is, so its better to plot sliders here
ImGui::Text("Persistence Range [%.2f, %.2f]", persistence_range.x, persistence_range.y);
ImGui::SliderFloat("Threshold", &threshold_range[0], persistence_range.x, persistence_range.y, "%.3f", glm::e<float>());
// Keep values in range
threshold_range[0] = glm::max(threshold_range[0], persistence_range.x);
// If we changed our selection update the display in the other widgets
if (ImGui::Button("Apply")) {
persistent_pairs->ThresholdBetween(threshold_range[0], threshold_range[1]);
simplification->Update();
update_persistence_diagram(); // update threshold
}
// draw plots
float fullheight = ImGui::GetContentRegionAvail().y;
draw_persistence_curve(fullheight * 0.5);
draw_persistence_diagram(fullheight * 0.5);
}
ImGui::End();
}
void PersistenceCurveWidget::draw_persistence_curve(float ysize) {
// Draw the persistence plot
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, glm::vec2(1));
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, glm::vec2(0));
ImGui::PushStyleColor(ImGuiCol_ChildWindowBg, ImColor(60, 60, 70, 200));
ImGui::BeginChild("pers_curve", glm::vec2(0, ysize), true, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoMove);
const glm::vec2 padding(0.001f, 0.0f);
const glm::vec2 canvas_size(ImGui::GetContentRegionAvail());
const glm::vec2 offset = glm::vec2(ImGui::GetCursorScreenPos().x, ImGui::GetCursorScreenPos().y + canvas_size.y) + padding * glm::vec2(canvas_size.x, -canvas_size.y);
const glm::vec2 axis_range = glm::log(glm::vec2(persistence_range.y, npairs_range.y));
const glm::vec2 view_scale = glm::vec2(canvas_size.x / axis_range.x, -canvas_size.y / axis_range.y) * (1.0f - 2.0f * padding);
ImDrawList *draw_list = ImGui::GetWindowDrawList();
draw_list->PushClipRect(ImGui::GetCursorScreenPos(), glm::vec2(ImGui::GetCursorScreenPos()) + canvas_size);
// Draw curve
for (size_t i = 0; !curve_points.empty() && i < curve_points.size() - 1; ++i) {
const glm::vec2 a = glm::log(curve_points[i]);
const glm::vec2 b = glm::log(curve_points[i + 1]);
draw_list->AddLine(offset + view_scale * a, offset + view_scale * b, ImColor(255, 255, 255), 2.0f);
}
// Draw threshold line
{
const float v = std::log(threshold_range.x) * view_scale.x + offset.x;
const glm::vec2 a = glm::vec2(v, offset.y);
const glm::vec2 b = glm::vec2(v, offset.y - canvas_size.y);
draw_list->AddLine(a, b, ImColor(0.8f, 0.8f, 0.2f, 1.f), 2.f);
}
draw_list->PopClipRect();
ImGui::EndChild();
ImGui::PopStyleColor();
ImGui::PopStyleVar(2);
}
void PersistenceCurveWidget::draw_persistence_diagram(float ysize) {
ImGui::Text("Persistence Diagram...");
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, glm::vec2(1));
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, glm::vec2(0));
ImGui::PushStyleColor(ImGuiCol_ChildWindowBg, ImColor(60, 60, 70, 200));
ImGui::BeginChild("pers_diag", glm::vec2(0, ysize - 20.0f /* text y-offset */), true, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoMove);
// TODO: Persistence Diagram
const glm::vec2 padding(0.005f, 0.02f);
const glm::vec2 canvas_size(ImGui::GetContentRegionAvail());
const glm::vec2 offset = glm::vec2(ImGui::GetCursorScreenPos().x, ImGui::GetCursorScreenPos().y + canvas_size.y) + padding * glm::vec2(canvas_size.x, -canvas_size.y);
const glm::vec2 axis_range = glm::vec2(persistence_range.y);
const glm::vec2 view_scale = glm::vec2(canvas_size.x / axis_range.x, -canvas_size.y / axis_range.y) * (1.0f - 2.0f * padding);
ImDrawList *draw_list = ImGui::GetWindowDrawList();
draw_list->PushClipRect(ImGui::GetCursorScreenPos(), glm::vec2(ImGui::GetCursorScreenPos()) + canvas_size);
// draw diagonal
{
const glm::vec2 a(0); // start from 0 for persistence diagram
const glm::vec2 b(persistence_range.y);
draw_list->AddLine(offset + view_scale * a, offset + view_scale * b, ImColor(255, 255, 255), 2.0f);
}
// Draw threshold line
{
const glm::vec2 a = glm::vec2(0, threshold_range.x);
const glm::vec2 b = glm::vec2(persistence_range.y - threshold_range.x, persistence_range.y);
draw_list->AddLine(offset + view_scale * a, offset + view_scale * b, ImColor(0.8f, 0.8f, 0.2f, 1.f), 2.0f);
}
// draw persistence lines
for (size_t i = 0; i < static_cast<size_t>(diagram_lines.size()); ++i) {
const glm::vec2 a = diagram_lines[i].ps;
const glm::vec2 b = diagram_lines[i].pe;
draw_list->AddLine(offset + view_scale * a, offset + view_scale * b, ImColor(255, 255, 255), 2.0f);
}
draw_list->PopClipRect();
ImGui::EndChild();
ImGui::PopStyleColor();
ImGui::PopStyleVar(2);
}
void PersistenceCurveWidget::set_tree_type(const ttk::TreeType &type) {
if (tree_type != type) {
tree_type = type;
update_persistence_curve();
}
}
void PersistenceCurveWidget::update_persistence_curve() {
// Tree type mapping to persistence curve output index:
// Join Tree: 0
// Morse Smale Curve: 1
// Split Tree: 2
// Contour Tree: 3
int tree = 0;
switch (tree_type) {
case ttk::TreeType::Contour: tree = 3; break;
case ttk::TreeType::Split: tree = 2; break;
case ttk::TreeType::Join: tree = 0; break;
default: break;
}
vtkTable* table = dynamic_cast<vtkTable*>(vtkcurve->GetOutputInformation(tree)->Get(vtkDataObject::DATA_OBJECT()));
vtkDataArray *persistence_col = dynamic_cast<vtkDataArray*>(table->GetColumn(0));
vtkDataArray *npairs_col = dynamic_cast<vtkDataArray*>(table->GetColumn(1));
assert(persistence_col->GetSize() == npairs_col->GetSize());
curve_points.clear();
curve_points.reserve(persistence_col->GetSize());
npairs_range = glm::vec2(std::numeric_limits<float>::infinity(), -std::numeric_limits<float>::infinity());
persistence_range = glm::vec2(1.f, -std::numeric_limits<float>::infinity());
std::map<float, size_t> pers_count;
for (vtkIdType i = 0; i < persistence_col->GetSize(); ++i) {
// It seems that often there are many entries with the same persistence value, count these up instead of making
// a bunch of dot lines
const float p = *persistence_col->GetTuple(i);
if (p > 0.f) {
persistence_range.y = std::max(persistence_range.y, p);
const float n = *npairs_col->GetTuple(i);
npairs_range.x = std::min(npairs_range.x, static_cast<float>(n));
npairs_range.y = std::max(npairs_range.y, static_cast<float>(n));
curve_points.push_back(glm::vec2(p, n));
}
}
threshold_range[1] = persistence_range.y;
persistent_pairs->ThresholdBetween(threshold_range[0], threshold_range[1]);
simplification->Update();
}
void PersistenceCurveWidget::update_persistence_diagram()
{
diagram_lines.clear();
vtkUnstructuredGrid* dcells = vtkUnstructuredGrid::SafeDownCast(diagram->GetOutput());
if (debuglevel >= 1) {
std::cout << "[DrawPersistenceDiagram] persistence range "
<< persistence_range.x << " " << persistence_range.y << std::endl;
dcells->GetPointData()->PrintSelf(std::cout, vtkIndent(0));
dcells->GetCellData()->PrintSelf(std::cout, vtkIndent(0));
}
auto array_PairType = dcells->GetCellData()->GetArray(1); // might be useful for coloring
auto array_Persistence = dcells->GetCellData()->GetArray(2); // threshold_range
auto array_NodeType = dcells->GetPointData()->GetArray(1); // might be useful for coloring
assert(array_PairType->GetNumberOfTuples() == dcells->GetNumberOfCells());
assert(array_Persistence->GetNumberOfTuples() == dcells->GetNumberOfCells());
// yeah vtk wants to make everything more complicated ...
vtkSmartPointer<vtkIdList> pointidx = vtkSmartPointer<vtkIdList>::New();
for (vtkIdType i = 0; i < static_cast<vtkIdType>(dcells->GetNumberOfCells()); ++i) {
double persistence = *array_Persistence->GetTuple(i);
if (persistence >= threshold_range.x && persistence <= threshold_range.y) {
dcells->GetCellPoints(i, pointidx);
double pairtype = *array_PairType->GetTuple(i);
if (pairtype >= 0.0) { // it seems -1 type are all invalid points
double pa[3], pb[3];
dcells->GetPoint(pointidx->GetId(0), pa);
dcells->GetPoint(pointidx->GetId(1), pb);
double pat = *array_NodeType->GetTuple(pointidx->GetId(0));
double pbt = *array_NodeType->GetTuple(pointidx->GetId(1));
if (debuglevel >= 1) {
std::cout << "[DrawPersistenceDiagram] persistence " << persistence << std::endl;
std::cout << "[DrawPersistenceDiagram] -- start " << pa[0] << " " << pa[1] << std::endl;
std::cout << "[DrawPersistenceDiagram] -- end " << pb[0] << " " << pb[1] << std::endl;
}
diagram_lines.emplace_back(pa, pb, pairtype, pat, pbt);
}
}
}
}
<commit_msg>Remove elipses on persistenc diag title<commit_after>#include <algorithm>
#include <thread>
#include <iostream>
#include <cassert> /* assert */
#include <glm/ext.hpp>
#include <vtkIndent.h>
#include <vtkTable.h>
#include <vtkVariant.h>
#include <vtkUnstructuredGrid.h>
#include "persistence_curve_widget.h"
PersistenceCurveWidget::PersistenceCurveWidget(vtkSmartPointer<vtkXMLImageDataReader> input, unsigned int debug)
: tree_type(ttk::TreeType::Split), debuglevel(debug)
{
diagram = vtkSmartPointer<vtkPersistenceDiagram>::New();
diagram->SetdebugLevel_(debuglevel);
diagram->SetInputConnection(input->GetOutputPort());
// Compute critical points
critical_pairs = vtkSmartPointer<vtkThreshold>::New();
critical_pairs->SetInputConnection(diagram->GetOutputPort());
critical_pairs->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_CELLS, "PairIdentifier");
critical_pairs->ThresholdBetween(-0.1, 999999);
// Select the most persistent pairs
persistent_pairs = vtkSmartPointer<vtkThreshold>::New();
persistent_pairs->SetInputConnection(critical_pairs->GetOutputPort());
persistent_pairs->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_CELLS, "Persistence");
// Start at a persistence above one so we filter out some junk
threshold_range[0] = 4.f;
persistent_pairs->ThresholdBetween(threshold_range[0], 999999);
// Simplifying the input data to remove non-persistent pairs
simplification = vtkSmartPointer<vtkTopologicalSimplification>::New();
simplification->SetdebugLevel_(debuglevel);
simplification->SetUseAllCores(true);
simplification->SetThreadNumber(std::thread::hardware_concurrency());
simplification->SetInputConnection(0, input->GetOutputPort());
simplification->SetInputConnection(1, persistent_pairs->GetOutputPort());
// We always show the full curve, without simplfication for the
// selected tree type
vtkcurve = vtkSmartPointer<vtkPersistenceCurve>::New();
vtkcurve->SetdebugLevel_(debuglevel);
vtkcurve->SetInputConnection(input->GetOutputPort());
vtkcurve->SetComputeSaddleConnectors(false);
vtkcurve->SetUseAllCores(true);
vtkcurve->SetThreadNumber(std::thread::hardware_concurrency());
vtkcurve->Update();
update_persistence_curve();
update_persistence_diagram();
}
vtkTopologicalSimplification* PersistenceCurveWidget::get_simplification() const {
return simplification.Get();
}
void PersistenceCurveWidget::draw_ui() {
if (ImGui::Begin("Persistence Plots"))
{
// we need to tell how large each plot is, so its better to plot sliders here
ImGui::Text("Persistence Range [%.2f, %.2f]", persistence_range.x, persistence_range.y);
ImGui::SliderFloat("Threshold", &threshold_range[0], persistence_range.x, persistence_range.y, "%.3f", glm::e<float>());
// Keep values in range
threshold_range[0] = glm::max(threshold_range[0], persistence_range.x);
// If we changed our selection update the display in the other widgets
if (ImGui::Button("Apply")) {
persistent_pairs->ThresholdBetween(threshold_range[0], threshold_range[1]);
simplification->Update();
update_persistence_diagram(); // update threshold
}
// draw plots
float fullheight = ImGui::GetContentRegionAvail().y;
draw_persistence_curve(fullheight * 0.5);
draw_persistence_diagram(fullheight * 0.5);
}
ImGui::End();
}
void PersistenceCurveWidget::draw_persistence_curve(float ysize) {
// Draw the persistence plot
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, glm::vec2(1));
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, glm::vec2(0));
ImGui::PushStyleColor(ImGuiCol_ChildWindowBg, ImColor(60, 60, 70, 200));
ImGui::BeginChild("pers_curve", glm::vec2(0, ysize), true, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoMove);
const glm::vec2 padding(0.001f, 0.0f);
const glm::vec2 canvas_size(ImGui::GetContentRegionAvail());
const glm::vec2 offset = glm::vec2(ImGui::GetCursorScreenPos().x, ImGui::GetCursorScreenPos().y + canvas_size.y) + padding * glm::vec2(canvas_size.x, -canvas_size.y);
const glm::vec2 axis_range = glm::log(glm::vec2(persistence_range.y, npairs_range.y));
const glm::vec2 view_scale = glm::vec2(canvas_size.x / axis_range.x, -canvas_size.y / axis_range.y) * (1.0f - 2.0f * padding);
ImDrawList *draw_list = ImGui::GetWindowDrawList();
draw_list->PushClipRect(ImGui::GetCursorScreenPos(), glm::vec2(ImGui::GetCursorScreenPos()) + canvas_size);
// Draw curve
for (size_t i = 0; !curve_points.empty() && i < curve_points.size() - 1; ++i) {
const glm::vec2 a = glm::log(curve_points[i]);
const glm::vec2 b = glm::log(curve_points[i + 1]);
draw_list->AddLine(offset + view_scale * a, offset + view_scale * b, ImColor(255, 255, 255), 2.0f);
}
// Draw threshold line
{
const float v = std::log(threshold_range.x) * view_scale.x + offset.x;
const glm::vec2 a = glm::vec2(v, offset.y);
const glm::vec2 b = glm::vec2(v, offset.y - canvas_size.y);
draw_list->AddLine(a, b, ImColor(0.8f, 0.8f, 0.2f, 1.f), 2.f);
}
draw_list->PopClipRect();
ImGui::EndChild();
ImGui::PopStyleColor();
ImGui::PopStyleVar(2);
}
void PersistenceCurveWidget::draw_persistence_diagram(float ysize) {
ImGui::Text("Persistence Diagram");
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, glm::vec2(1));
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, glm::vec2(0));
ImGui::PushStyleColor(ImGuiCol_ChildWindowBg, ImColor(60, 60, 70, 200));
ImGui::BeginChild("pers_diag", glm::vec2(0, ysize - 20.0f /* text y-offset */), true, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoMove);
// TODO: Persistence Diagram
const glm::vec2 padding(0.005f, 0.02f);
const glm::vec2 canvas_size(ImGui::GetContentRegionAvail());
const glm::vec2 offset = glm::vec2(ImGui::GetCursorScreenPos().x, ImGui::GetCursorScreenPos().y + canvas_size.y) + padding * glm::vec2(canvas_size.x, -canvas_size.y);
const glm::vec2 axis_range = glm::vec2(persistence_range.y);
const glm::vec2 view_scale = glm::vec2(canvas_size.x / axis_range.x, -canvas_size.y / axis_range.y) * (1.0f - 2.0f * padding);
ImDrawList *draw_list = ImGui::GetWindowDrawList();
draw_list->PushClipRect(ImGui::GetCursorScreenPos(), glm::vec2(ImGui::GetCursorScreenPos()) + canvas_size);
// draw diagonal
{
const glm::vec2 a(0); // start from 0 for persistence diagram
const glm::vec2 b(persistence_range.y);
draw_list->AddLine(offset + view_scale * a, offset + view_scale * b, ImColor(255, 255, 255), 2.0f);
}
// Draw threshold line
{
const glm::vec2 a = glm::vec2(0, threshold_range.x);
const glm::vec2 b = glm::vec2(persistence_range.y - threshold_range.x, persistence_range.y);
draw_list->AddLine(offset + view_scale * a, offset + view_scale * b, ImColor(0.8f, 0.8f, 0.2f, 1.f), 2.0f);
}
// draw persistence lines
for (size_t i = 0; i < static_cast<size_t>(diagram_lines.size()); ++i) {
const glm::vec2 a = diagram_lines[i].ps;
const glm::vec2 b = diagram_lines[i].pe;
draw_list->AddLine(offset + view_scale * a, offset + view_scale * b, ImColor(255, 255, 255), 2.0f);
}
draw_list->PopClipRect();
ImGui::EndChild();
ImGui::PopStyleColor();
ImGui::PopStyleVar(2);
}
void PersistenceCurveWidget::set_tree_type(const ttk::TreeType &type) {
if (tree_type != type) {
tree_type = type;
update_persistence_curve();
}
}
void PersistenceCurveWidget::update_persistence_curve() {
// Tree type mapping to persistence curve output index:
// Join Tree: 0
// Morse Smale Curve: 1
// Split Tree: 2
// Contour Tree: 3
int tree = 0;
switch (tree_type) {
case ttk::TreeType::Contour: tree = 3; break;
case ttk::TreeType::Split: tree = 2; break;
case ttk::TreeType::Join: tree = 0; break;
default: break;
}
vtkTable* table = dynamic_cast<vtkTable*>(vtkcurve->GetOutputInformation(tree)->Get(vtkDataObject::DATA_OBJECT()));
vtkDataArray *persistence_col = dynamic_cast<vtkDataArray*>(table->GetColumn(0));
vtkDataArray *npairs_col = dynamic_cast<vtkDataArray*>(table->GetColumn(1));
assert(persistence_col->GetSize() == npairs_col->GetSize());
curve_points.clear();
curve_points.reserve(persistence_col->GetSize());
npairs_range = glm::vec2(std::numeric_limits<float>::infinity(), -std::numeric_limits<float>::infinity());
persistence_range = glm::vec2(1.f, -std::numeric_limits<float>::infinity());
std::map<float, size_t> pers_count;
for (vtkIdType i = 0; i < persistence_col->GetSize(); ++i) {
// It seems that often there are many entries with the same persistence value, count these up instead of making
// a bunch of dot lines
const float p = *persistence_col->GetTuple(i);
if (p > 0.f) {
persistence_range.y = std::max(persistence_range.y, p);
const float n = *npairs_col->GetTuple(i);
npairs_range.x = std::min(npairs_range.x, static_cast<float>(n));
npairs_range.y = std::max(npairs_range.y, static_cast<float>(n));
curve_points.push_back(glm::vec2(p, n));
}
}
threshold_range[1] = persistence_range.y;
persistent_pairs->ThresholdBetween(threshold_range[0], threshold_range[1]);
simplification->Update();
}
void PersistenceCurveWidget::update_persistence_diagram()
{
diagram_lines.clear();
vtkUnstructuredGrid* dcells = vtkUnstructuredGrid::SafeDownCast(diagram->GetOutput());
if (debuglevel >= 1) {
std::cout << "[DrawPersistenceDiagram] persistence range "
<< persistence_range.x << " " << persistence_range.y << std::endl;
dcells->GetPointData()->PrintSelf(std::cout, vtkIndent(0));
dcells->GetCellData()->PrintSelf(std::cout, vtkIndent(0));
}
auto array_PairType = dcells->GetCellData()->GetArray(1); // might be useful for coloring
auto array_Persistence = dcells->GetCellData()->GetArray(2); // threshold_range
auto array_NodeType = dcells->GetPointData()->GetArray(1); // might be useful for coloring
assert(array_PairType->GetNumberOfTuples() == dcells->GetNumberOfCells());
assert(array_Persistence->GetNumberOfTuples() == dcells->GetNumberOfCells());
// yeah vtk wants to make everything more complicated ...
vtkSmartPointer<vtkIdList> pointidx = vtkSmartPointer<vtkIdList>::New();
for (vtkIdType i = 0; i < static_cast<vtkIdType>(dcells->GetNumberOfCells()); ++i) {
double persistence = *array_Persistence->GetTuple(i);
if (persistence >= threshold_range.x && persistence <= threshold_range.y) {
dcells->GetCellPoints(i, pointidx);
double pairtype = *array_PairType->GetTuple(i);
if (pairtype >= 0.0) { // it seems -1 type are all invalid points
double pa[3], pb[3];
dcells->GetPoint(pointidx->GetId(0), pa);
dcells->GetPoint(pointidx->GetId(1), pb);
double pat = *array_NodeType->GetTuple(pointidx->GetId(0));
double pbt = *array_NodeType->GetTuple(pointidx->GetId(1));
if (debuglevel >= 1) {
std::cout << "[DrawPersistenceDiagram] persistence " << persistence << std::endl;
std::cout << "[DrawPersistenceDiagram] -- start " << pa[0] << " " << pa[1] << std::endl;
std::cout << "[DrawPersistenceDiagram] -- end " << pb[0] << " " << pb[1] << std::endl;
}
diagram_lines.emplace_back(pa, pb, pairtype, pat, pbt);
}
}
}
}
<|endoftext|> |
<commit_before>#include "SDL.h"
#include "SDL_opengl.h"
#include <cmath>
const float kPi = 4.0f * std::atan(1.0f);
const Uint32 kLagThreshold = 1000;
const Uint32 kFrameTime = 10;
const float kPlayerForwardSpeed = 10.0f * (kFrameTime * 0.001f);
const float kPlayerTurnSpeed = 100.0f * (kFrameTime * 0.001f);
const float kGridSpacing = 2.0f;
const int kGridSize = 8;
bool buttonLeft = false, buttonRight = false,
buttonUp = false, buttonDown = false;
float playerX = 0.0f, playerY = 0.0f, playerFace = 0.0f;
struct gradient_point {
float pos;
unsigned char color[3];
};
const gradient_point sky[] = {
{ -0.50f, { 0, 0, 51 } },
{ -0.02f, { 0, 0, 0 } },
{ 0.00f, { 102, 204, 255 } },
{ 0.20f, { 51, 0, 255 } },
{ 0.70f, { 0, 0, 0 } }
};
void drawSky(void)
{
int i;
glPushAttrib(GL_CURRENT_BIT);
glBegin(GL_TRIANGLE_STRIP);
glColor3ubv(sky[0].color);
glVertex3f(-2.0f, 1.0f, -1.0f);
glVertex3f( 2.0f, 1.0f, -1.0f);
for (i = 0; i < sizeof(sky) / sizeof(*sky); ++i) {
glColor3ubv(sky[i].color);
glVertex3f(-2.0f, 1.0f, sky[i].pos);
glVertex3f( 2.0f, 1.0f, sky[i].pos);
}
glVertex3f(-2.0f, 0.0f, 1.0f);
glVertex3f( 2.0f, 0.0f, 1.0f);
glEnd();
glPopAttrib();
}
void drawGround(void)
{
int i;
float px = std::floor(playerX / kGridSpacing + 0.5f) * kGridSpacing;
float py = std::floor(playerY / kGridSpacing + 0.5f) * kGridSpacing;
glPushMatrix();
glTranslatef(px, py, 0.0f);
glScalef(kGridSpacing, kGridSpacing, 1.0f);
glColor3ub(51, 0, 255);
glBegin(GL_LINES);
for (i = -kGridSize; i <= kGridSize; ++i) {
glVertex3f(i, -kGridSize, 0.0f);
glVertex3f(i, kGridSize, 0.0f);
glVertex3f(-kGridSize, i, 0.0f);
glVertex3f( kGridSize, i, 0.0f);
}
glEnd();
glPopAttrib();
glPopMatrix();
}
void drawScene(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-0.1f, 0.1f, -0.075f, 0.075f, 0.1f, 100.0f);
glRotatef(-90.0f, 1.0f, 0.0f, 0.0f);
drawSky();
glRotatef(90.0f - playerFace, 0.0f, 0.0f, 1.0f);
glTranslatef(-playerX, -playerY, -1.0f);
glMatrixMode(GL_MODELVIEW);
drawGround();
SDL_GL_SwapBuffers();
}
void handleKey(SDL_keysym *key, bool state)
{
switch (key->sym) {
case SDLK_ESCAPE:
if (state) {
SDL_Quit();
exit(0);
}
break;
case SDLK_UP:
case SDLK_w:
buttonUp = state;
break;
case SDLK_DOWN:
case SDLK_s:
buttonDown = state;
break;
case SDLK_LEFT:
case SDLK_a:
buttonLeft = state;
break;
case SDLK_RIGHT:
case SDLK_d:
buttonRight = state;
break;
default:
break;
}
}
void advanceFrame(void)
{
float forward = 0.0f, turn = 0.0f, face;
if (buttonLeft)
turn += kPlayerTurnSpeed;
if (buttonRight)
turn -= kPlayerTurnSpeed;
if (buttonUp)
forward += kPlayerForwardSpeed;
if (buttonDown)
forward -= kPlayerForwardSpeed;
playerFace += turn;
face = playerFace * (kPi / 180.0f);
playerX += forward * std::cos(face);
playerY += forward * std::sin(face);
}
int main(int argc, char *argv[])
{
SDL_Surface *screen = NULL;
bool done = false;
SDL_Event event;
int flags;
Uint32 tickref = 0, tick;
if (SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO) < 0) {
fprintf(stderr, "Could not initialize SDL: %s\n",
SDL_GetError());
exit(1);
}
flags = SDL_OPENGL | SDL_GL_DOUBLEBUFFER;
screen = SDL_SetVideoMode(640, 480, 32, flags);
if (!screen) {
fprintf(stderr, "Could not initialize video: %s\n",
SDL_GetError());
SDL_Quit();
exit(1);
}
printf(
"Vendor: %s\n"
"Renderer: %s\n"
"Version: %s\n"
"Extensions: %s\n",
glGetString(GL_VENDOR), glGetString(GL_RENDERER),
glGetString(GL_VERSION), glGetString(GL_EXTENSIONS));
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
while (!done) {
tick = SDL_GetTicks();
if (tick > tickref + kFrameTime) {
do {
advanceFrame();
tickref += kFrameTime;
} while (tick > tickref + kFrameTime);
} else if (tick < tickref)
tickref = tick;
drawScene();
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_KEYDOWN:
handleKey(&event.key.keysym, true);
break;
case SDL_KEYUP:
handleKey(&event.key.keysym, false);
break;
case SDL_QUIT:
done = true;
break;
}
}
}
SDL_Quit();
return 0;
}
<commit_msg>Minor cleanup of drawScene.<commit_after>#include "SDL.h"
#include "SDL_opengl.h"
#include <cmath>
const float kPi = 4.0f * std::atan(1.0f);
const Uint32 kLagThreshold = 1000;
const Uint32 kFrameTime = 10;
const float kPlayerForwardSpeed = 10.0f * (kFrameTime * 0.001f);
const float kPlayerTurnSpeed = 100.0f * (kFrameTime * 0.001f);
const float kGridSpacing = 2.0f;
const int kGridSize = 8;
bool buttonLeft = false, buttonRight = false,
buttonUp = false, buttonDown = false;
float playerX = 0.0f, playerY = 0.0f, playerFace = 0.0f;
struct gradient_point {
float pos;
unsigned char color[3];
};
const gradient_point sky[] = {
{ -0.50f, { 0, 0, 51 } },
{ -0.02f, { 0, 0, 0 } },
{ 0.00f, { 102, 204, 255 } },
{ 0.20f, { 51, 0, 255 } },
{ 0.70f, { 0, 0, 0 } }
};
void drawSky(void)
{
int i;
glPushAttrib(GL_CURRENT_BIT);
glBegin(GL_TRIANGLE_STRIP);
glColor3ubv(sky[0].color);
glVertex3f(-2.0f, 1.0f, -1.0f);
glVertex3f( 2.0f, 1.0f, -1.0f);
for (i = 0; i < sizeof(sky) / sizeof(*sky); ++i) {
glColor3ubv(sky[i].color);
glVertex3f(-2.0f, 1.0f, sky[i].pos);
glVertex3f( 2.0f, 1.0f, sky[i].pos);
}
glVertex3f(-2.0f, 0.0f, 1.0f);
glVertex3f( 2.0f, 0.0f, 1.0f);
glEnd();
glPopAttrib();
}
void drawGround(void)
{
int i;
float px = std::floor(playerX / kGridSpacing + 0.5f) * kGridSpacing;
float py = std::floor(playerY / kGridSpacing + 0.5f) * kGridSpacing;
glPushMatrix();
glTranslatef(px, py, 0.0f);
glScalef(kGridSpacing, kGridSpacing, 1.0f);
glColor3ub(51, 0, 255);
glBegin(GL_LINES);
for (i = -kGridSize; i <= kGridSize; ++i) {
glVertex3f(i, -kGridSize, 0.0f);
glVertex3f(i, kGridSize, 0.0f);
glVertex3f(-kGridSize, i, 0.0f);
glVertex3f( kGridSize, i, 0.0f);
}
glEnd();
glPopAttrib();
glPopMatrix();
}
void drawScene(void)
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-0.1f, 0.1f, -0.075f, 0.075f, 0.1f, 100.0f);
glRotatef(-90.0f, 1.0f, 0.0f, 0.0f);
drawSky();
glRotatef(90.0f - playerFace, 0.0f, 0.0f, 1.0f);
glTranslatef(-playerX, -playerY, -1.0f);
glMatrixMode(GL_MODELVIEW);
drawGround();
SDL_GL_SwapBuffers();
}
void handleKey(SDL_keysym *key, bool state)
{
switch (key->sym) {
case SDLK_ESCAPE:
if (state) {
SDL_Quit();
exit(0);
}
break;
case SDLK_UP:
case SDLK_w:
buttonUp = state;
break;
case SDLK_DOWN:
case SDLK_s:
buttonDown = state;
break;
case SDLK_LEFT:
case SDLK_a:
buttonLeft = state;
break;
case SDLK_RIGHT:
case SDLK_d:
buttonRight = state;
break;
default:
break;
}
}
void advanceFrame(void)
{
float forward = 0.0f, turn = 0.0f, face;
if (buttonLeft)
turn += kPlayerTurnSpeed;
if (buttonRight)
turn -= kPlayerTurnSpeed;
if (buttonUp)
forward += kPlayerForwardSpeed;
if (buttonDown)
forward -= kPlayerForwardSpeed;
playerFace += turn;
face = playerFace * (kPi / 180.0f);
playerX += forward * std::cos(face);
playerY += forward * std::sin(face);
}
int main(int argc, char *argv[])
{
SDL_Surface *screen = NULL;
bool done = false;
SDL_Event event;
int flags;
Uint32 tickref = 0, tick;
if (SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO) < 0) {
fprintf(stderr, "Could not initialize SDL: %s\n",
SDL_GetError());
exit(1);
}
flags = SDL_OPENGL | SDL_GL_DOUBLEBUFFER;
screen = SDL_SetVideoMode(640, 480, 32, flags);
if (!screen) {
fprintf(stderr, "Could not initialize video: %s\n",
SDL_GetError());
SDL_Quit();
exit(1);
}
printf(
"Vendor: %s\n"
"Renderer: %s\n"
"Version: %s\n"
"Extensions: %s\n",
glGetString(GL_VENDOR), glGetString(GL_RENDERER),
glGetString(GL_VERSION), glGetString(GL_EXTENSIONS));
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
while (!done) {
tick = SDL_GetTicks();
if (tick > tickref + kFrameTime) {
do {
advanceFrame();
tickref += kFrameTime;
} while (tick > tickref + kFrameTime);
} else if (tick < tickref)
tickref = tick;
drawScene();
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_KEYDOWN:
handleKey(&event.key.keysym, true);
break;
case SDL_KEYUP:
handleKey(&event.key.keysym, false);
break;
case SDL_QUIT:
done = true;
break;
}
}
}
SDL_Quit();
return 0;
}
<|endoftext|> |
<commit_before>/* nobleNote, a note taking application
* Copyright (C) 2012 Christian Metscher <[email protected]>,
Fabian Deuchler <[email protected]>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* nobleNote is licensed under the MIT, see `http://copyfree.org/licenses/mit/license.txt'.
*/
#include "mainwindow.h"
#include <QApplication>
#include <QTranslator>
#include <QLibraryInfo>
#include <QSettings>
#include <QMessageBox>
#include <welcome.h>
int main (int argc, char *argv[]){
QApplication app(argc, argv);
app.setApplicationName("nobleNote");
app.setOrganizationName("nobleNote");
app.setFont(QFont("DejaVu Sans", 10)); // default font used in note editor
//Qt translations
QTranslator qtTranslator;
qtTranslator.load("qt_" + QLocale::system().name(),
QLibraryInfo::location(QLibraryInfo::TranslationsPath));
app.installTranslator(&qtTranslator);
//NobleNote translations
QTranslator translator;
QString tmp = "/usr/share/noblenote/translations/noblenote_";
translator.load(tmp + QLocale::system().name());
app.installTranslator(&translator);
app.setQuitOnLastWindowClosed(false);
//Configuration file
QSettings settings; // ini format does save but in the executables directory, use native format
if(!settings.isWritable()) // TODO QObject::tr does not work here because there is no Q_OBJECT macro in main
QMessageBox::critical(0,"Settings not writable", QString("%1 settings not writable!").arg(app.applicationName()));
if(!settings.value("import_path").isValid())
settings.setValue("import_path", QDir::homePath());
if(!settings.value("root_path").isValid())
{ // root path has not been set before
QScopedPointer<Welcome> welcome(new Welcome);
if(welcome->exec() == QDialog::Rejected) // welcome writes the root path
return 0; // leave main if the user rejects the welcome dialog, else go on
}
MainWindow window;
window.show();
return app.exec();
}
<commit_msg>added translation file paths for windows in main.cpp<commit_after>/* nobleNote, a note taking application
* Copyright (C) 2012 Christian Metscher <[email protected]>,
Fabian Deuchler <[email protected]>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* nobleNote is licensed under the MIT, see `http://copyfree.org/licenses/mit/license.txt'.
*/
#include "mainwindow.h"
#include <QApplication>
#include <QTranslator>
#include <QLibraryInfo>
#include <QSettings>
#include <QMessageBox>
#include <welcome.h>
int main (int argc, char *argv[]){
QApplication app(argc, argv);
app.setApplicationName("nobleNote");
app.setOrganizationName("nobleNote");
app.setFont(QFont("DejaVu Sans", 10)); // default font used in note editor
//Qt translations
QTranslator qtTranslator;
qtTranslator.load("qt_" + QLocale::system().name(),
QLibraryInfo::location(QLibraryInfo::TranslationsPath));
app.installTranslator(&qtTranslator);
//NobleNote translations
QTranslator translator;
#ifdef Q_OS_WIN32
translator.load(":noblenote_" + QLocale::system().name());
#else
QString tmp = "/usr/share/noblenote/translations/noblenote_";
translator.load(tmp + QLocale::system().name());
#endif
app.installTranslator(&translator);
app.setQuitOnLastWindowClosed(false);
//Configuration file
QSettings settings; // ini format does save but in the executables directory, use native format
if(!settings.isWritable()) // TODO QObject::tr does not work here because there is no Q_OBJECT macro in main
QMessageBox::critical(0,"Settings not writable", QString("%1 settings not writable!").arg(app.applicationName()));
if(!settings.value("import_path").isValid())
settings.setValue("import_path", QDir::homePath());
if(!settings.value("root_path").isValid())
{ // root path has not been set before
QScopedPointer<Welcome> welcome(new Welcome);
if(welcome->exec() == QDialog::Rejected) // welcome writes the root path
return 0; // leave main if the user rejects the welcome dialog, else go on
}
MainWindow window;
window.show();
return app.exec();
}
<|endoftext|> |
<commit_before>#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <unistd.h>
#include <vector>
#include <string>
#include <iostream>
#include "functions.h"
int main(int argc, char** argv)
{
// hold a raw line of input
std::string line;
// print welcome message and prompt
printf("Welcome to rshell!\n");
while (true)
{
// holds a single command and its arguments
Command cmd;
// holds multiple commands
std::vector<Command> cmds;
// print prompt and get a line of text (done in condition)
printf("$ ");
getline(std::cin, line);
// look for comments
if (line.find("#") != std::string::npos)
{
// remove them if necessary (they're useless)
line = line.substr(0, line.find("#"));
}
// remove leading whitespace
while (line.size() > 0 && (line[0] == ' ' || line[0] == ';'))
{
line = line.substr(1, line.size() - 1);
}
if (std::cin.fail())
{
printf("\nGoodbye!\n");
exit(0);
}
int mode = GETWORD;
unsigned begin = 0;
// temporary: show pre-processed input to know what's being dealt with
printf("You entered: \"%s\"\n", line.c_str());
// prepare cmd
cmd.connector = NONE;
// syntax error flag
bool se = false;
// handle the input
for(unsigned i = 0; i < line.size() && !se; ++i)
{
bool con = isConn(line[i]);
bool space = isspace(line[i]);
// if we're getting a word and there's a whitespace or connector here
if (mode == GETWORD && (space || con))
{
// chunk the last term and throw it into the vector
char* c = stocstr(line.substr(begin, i - begin));
if (strlen(c) > 0)
{
cmd.args.push_back(c);
}
else
{
break;
}
if (space)
{
mode = TRIMSPACE;
}
else // it's a connector
{
handleCon(cmds, cmd, line, mode, i, se);
}
}
else if (mode == TRIMSPACE && (!space && con))
{
if (con && cmd.args.empty())
{
se = true;
}
else if (con) // it's a valid connector connector
{
handleCon(cmds, cmd, line, mode, i, se);
}
else
{
mode = GETWORD;
}
}
}
// if there was a syntax error
if (se)
{
printf("Syntax error detected\n");
continue;
}
for(unsigned i = 0; i < cmds.size(); ++i)
{
printf("Command %u:\n", i);
for(unsigned j = 0; j < cmds[i].args.size(); ++j)
{
printf("\t\"%s\"\n", cmds[i].args[j]);
}
switch(cmds[i].connector)
{
case AND:
printf("\t&&\n");
break;
case OR:
printf("\t||\n");
break;
case SEMI:
printf("\t;\n");
break;
case NONE:
printf("\tNo connector\n");
break;
default:
printf("\tERROR: no valid connector specified\n");
}
}
// deallocate allocated memory
for(unsigned i = 0; i < cmds.size(); ++i)
{
for(unsigned j = 0; j < cmds[i].args.size(); ++j)
{
delete[] cmds[i].args[i];
}
}
}
return 0;
}
<commit_msg>Worked on fixing bugs<commit_after>#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <unistd.h>
#include <vector>
#include <string>
#include <iostream>
#include "functions.h"
int main(int argc, char** argv)
{
// hold a raw line of input
std::string line;
// print welcome message and prompt
printf("Welcome to rshell!\n");
while (true)
{
// holds a single command and its arguments
Command cmd;
// holds multiple commands
std::vector<Command> cmds;
// print prompt and get a line of text (done in condition)
printf("$ ");
getline(std::cin, line);
// look for comments
if (line.find("#") != std::string::npos)
{
// remove them if necessary (they're useless)
line = line.substr(0, line.find("#"));
}
// remove leading whitespace
while (line.size() > 0 && (line[0] == ' ' || line[0] == ';'))
{
line = line.substr(1, line.size() - 1);
}
// adding a space to the end makes parsing easier
line += ' ';
if (std::cin.fail())
{
printf("\nGoodbye!\n");
exit(0);
}
int mode = GETWORD;
unsigned begin = 0;
// temporary: show pre-processed input to know what's being dealt with
printf("You entered: \"%s\"\n", line.c_str());
// prepare cmd
cmd.connector = NONE;
// syntax error flag
bool se = false;
if (line.size() > 0 && isConn(line[0]))
{
se = true;
}
// handle the input
for(unsigned i = 0; i < line.size() && !se; ++i)
{
bool con = isConn(line[i]);
bool space = isspace(line[i]);
// if we're getting a word and there's a whitespace or connector here
if (mode == GETWORD && (space || con))
{
// chunk the last term and throw it into the vector
char* c = stocstr(line.substr(begin, i - begin));
if (strlen(c) > 0)
{
cmd.args.push_back(c);
}
else
{
printf("Oh no! Recieved a word with no length\n");
break;
}
if (space)
{
mode = TRIMSPACE;
}
else // it's a connector
{
handleCon(cmds, cmd, line, mode, i, se);
}
}
else if (mode == TRIMSPACE && (!space && con))
{
if (con && cmd.args.empty())
{
se = true;
}
else if (con)
{
handleCon(cmds, cmd, line, mode, i, se);
}
else
{
mode = GETWORD;
begin = i;
}
}
}
// if there was a syntax error
if (se)
{
printf("Syntax error detected\n");
continue;
}
cmds.push_back(cmd);
for(unsigned i = 0; i < cmds.size(); ++i)
{
printf("Command %u:\n", i);
for(unsigned j = 0; j < cmds[i].args.size(); ++j)
{
printf("\t\"%s\"\n", cmds[i].args[j]);
}
switch(cmds[i].connector)
{
case AND:
printf("\t&&\n");
break;
case OR:
printf("\t||\n");
break;
case SEMI:
printf("\t;\n");
break;
case NONE:
printf("\tNo connector\n");
break;
default:
printf("\tERROR: no valid connector specified\n");
}
}
// deallocate allocated memory
for(unsigned i = 0; i < cmds.size(); ++i)
{
for(unsigned j = 0; j < cmds[i].args.size(); ++j)
{
delete[] cmds[i].args[i];
}
}
}
return 0;
}
<|endoftext|> |
<commit_before>
#include "Client.hpp"
#include <onions-common/Log.hpp>
#include <onions-common/Utils.hpp>
#include <botan/botan.h>
#include <popt.h>
// Botan::LibraryInitializer init("thread_safe");
int main(int argc, char** argv)
{
char* logPath = NULL;
bool license = false;
ushort port = 9150;
struct poptOption po[] = {
{"output",
'o',
POPT_ARG_STRING,
&logPath,
0,
"Specifies the filepath for event logging.",
"<path>"},
{"port",
'p',
POPT_ARG_SHORT,
&port,
0,
"SOCKS port to use for Tor communication. The default is 9150.",
"<port>"},
{"license",
'L',
POPT_ARG_NONE,
&license,
0,
"Print software license and exit.",
NULL},
POPT_AUTOHELP{NULL, 0, 0, NULL, 0, NULL, NULL}};
if (!Utils::parse(
poptGetContext(NULL, argc, const_cast<const char**>(argv), po, 0)))
{
std::cout << "Failed to parse command-line arguments. Aborting.\n";
return EXIT_FAILURE;
}
if (license)
{
std::cout << "Modified/New BSD License" << std::endl;
return EXIT_SUCCESS;
}
if (logPath && strcmp(logPath, "-") == 0)
Log::setLogPath(std::string(logPath));
Client::get().listenForDomains(port);
return EXIT_SUCCESS;
}
<commit_msg>Fix #17<commit_after>
#include "Client.hpp"
#include <onions-common/Log.hpp>
#include <onions-common/Utils.hpp>
#include <botan/botan.h>
#include <popt.h>
// Botan::LibraryInitializer init("thread_safe");
int main(int argc, char** argv)
{
char* logPath = NULL;
bool license = false;
ushort port = 9150;
struct poptOption po[] = {
{"output",
'o',
POPT_ARG_STRING,
&logPath,
0,
"Specifies the filepath for event logging.",
"<path>"},
{"port",
'p',
POPT_ARG_SHORT,
&port,
0,
"SOCKS port to use for Tor communication. The default is 9150.",
"<port>"},
{"license",
'L',
POPT_ARG_NONE,
&license,
0,
"Print software license and exit.",
NULL},
POPT_AUTOHELP{NULL, 0, 0, NULL, 0, NULL, NULL}};
if (!Utils::parse(
poptGetContext(NULL, argc, const_cast<const char**>(argv), po, 0)))
{
std::cout << "Failed to parse command-line arguments. Aborting.\n";
return EXIT_FAILURE;
}
if (license)
{
std::cout << "Modified/New BSD License" << std::endl;
return EXIT_SUCCESS;
}
if (logPath && strcmp(logPath, "-") != 0)
Log::setLogPath(std::string(logPath));
Client::get().listenForDomains(port);
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
Dwarf Therapist
Copyright (c) 2009 Trey Stout (chmod)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/*! \mainpage Dwarf Therapist
*
* \section intro_sec Introduction
*
* Dwarf Therapist is written in C++ using Qt 5.1.1. It is meant to be used as
* an addon for the game Dwarf Fortress.
*
*/
#include "dwarftherapist.h"
#include "dfinstance.h"
int main(int argc, char *argv[]) {
if(!DFInstance::authorize()){
return 0;
}
DwarfTherapist d(argc, argv);
return d.exec();
}
<commit_msg>Revert "remove invalid/duplicate setuid from main from #128", because it makes DT not run on Mac.<commit_after>/*
Dwarf Therapist
Copyright (c) 2009 Trey Stout (chmod)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/*! \mainpage Dwarf Therapist
*
* \section intro_sec Introduction
*
* Dwarf Therapist is written in C++ using Qt 5.1.1. It is meant to be used as
* an addon for the game Dwarf Fortress.
*
*/
#include "dwarftherapist.h"
#include "dfinstance.h"
int main(int argc, char *argv[]) {
QCoreApplication::setSetuidAllowed(true);
if(!DFInstance::authorize()){
return 0;
}
DwarfTherapist d(argc, argv);
return d.exec();
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <cstring>
#include <string>
using namespace std;
void lsCom() {
}
bool isDependant = 0;
int main() {
string str;
pid_t pid;
bool hasArg = 0, term = 0;
int strSize = 0;
int pos, arrPos;
bool bexit = false;
char *arg;
char *comm;
while(1) {
cout << "$ ";
getline(cin, str);
string sarg, scomm;
bool success = false;
bool lastOR = false, lastAND = false;
bool lastSuccess = false;
pos = 0;
strSize = str.size();
//cout << strSize << endl;
while(pos < strSize) {
arg = (char*) malloc(256);
comm = (char*) malloc(256);
char* arr[30];
string sarg, scomm;
bool logOR = false, logAND = false;
bool comment = false;
arrPos = 0;
hasArg = 0;
term = false;
hasArg = false;
if(str.at(pos) == ' ') {
while(pos < strSize && str.at(pos) == ' ') {
++pos;
}
if(pos >= strSize) {
break;
}
}
while(pos < strSize && str.at(pos) != ' ') {
if(str.at(pos) == '#') {
comment = true;
break;
}
else if(str.at(pos) == ';') {
term = true;
++pos;
break;
}
else if(str.at(pos) == '|') {
++pos;
if(pos < strSize && str.at(pos) == '|') {
logOR = true;
++pos;
break;
}
}
else if(str.at(pos) == '&') {
++pos;
if(pos < strSize && str.at(pos) == '&') {
logAND = true;
++pos;
break;
}
}
else {
scomm += str.at(pos);
++pos;
}
}
if(comment) {
break;
}
strcpy(comm,scomm.c_str());
//++pos; // This is to ommit the whitespace character following the command
if(pos < strSize && str.at(pos) == ' ' && !(term)) {
while(pos < strSize && str.at(pos) == ' ') {
++pos;
}
if(pos >= strSize) {
break;
}
}
arr[arrPos] = comm;
++arrPos;
while(pos < strSize && !(term) && !(logOR) && !(logAND)) {
if(str.at(pos) == '#') {
break;
}
else if(str.at(pos) == '-' && str.at(pos+1) == ' ') {
sarg += str.at(pos);
++pos;
while(str.at(pos) == ' ') {
++pos;
}
}
else if(str.at(pos) == ';') {
++pos;
break;
}
else if(str.at(pos) == '|') {
++pos;
if(pos < strSize && str.at(pos) == '|') {
logOR = true;
++pos;
break;
}
}
else if(str.at(pos) == '&') {
++pos;
if(pos < strSize && str.at(pos) == '&') {
logAND = true;
++pos;
break;
}
}
else {
sarg += str.at(pos);
++pos;
hasArg = true;
}
}
if(hasArg) {
unsigned int n = 0;
string s;
while(n < sarg.size()) {
if(sarg.at(n) == '-' && n != 0) {
strcpy(arg, s.c_str());
arr[arrPos] = arg;
++arrPos;
s = "";
}
s += sarg.at(n);
++n;
}
n = s.size() -1;
while(s.at(n) == ' ') {
s.at(n) = '\0';
--n;
}
strcpy(arg, s.c_str());
arr[arrPos] = arg;
++arrPos;
}
arr[arrPos] = NULL;
/*for(int i = 0; i < 1; ++i) {
cout << arr[i] << endl;
}*/
if(scomm != "exit") {
pid = fork();
if(pid == 0) {
if(lastSuccess == false) {
cout << "1" << endl;
}
if((!(lastOR) && !(lastAND)) || (lastSuccess == false && lastOR == true) ||
(lastSuccess == true && lastAND == true)) {
if(execvp(arr[0], arr) == -1) {
success = true;
perror("The command could not be executed!");
errno = 0;
}
_exit(0);
}
}
else {
wait(0);
}
}
else {
if((!lastOR && !lastAND) || (!lastSuccess && lastOR) || (lastSuccess && lastAND)) {
cout << "Good-bye!" << endl;
exit(0);
}
}
lastOR = logOR;
lastAND = logAND;
lastSuccess = !(success);
free(comm);
free(arg);
}
if(bexit) {
break;
}
}
return 0;
}
<commit_msg>Forgot to take out test statement<commit_after>#include <iostream>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <cstring>
#include <string>
using namespace std;
void lsCom() {
}
bool isDependant = 0;
int main() {
string str;
pid_t pid;
bool hasArg = 0, term = 0;
int strSize = 0;
int pos, arrPos;
bool bexit = false;
char *arg;
char *comm;
while(1) {
cout << "$ ";
getline(cin, str);
string sarg, scomm;
bool success = false;
bool lastOR = false, lastAND = false;
bool lastSuccess = false;
pos = 0;
strSize = str.size();
//cout << strSize << endl;
while(pos < strSize) {
arg = (char*) malloc(256);
comm = (char*) malloc(256);
char* arr[30];
string sarg, scomm;
bool logOR = false, logAND = false;
bool comment = false;
arrPos = 0;
hasArg = 0;
term = false;
hasArg = false;
if(str.at(pos) == ' ') {
while(pos < strSize && str.at(pos) == ' ') {
++pos;
}
if(pos >= strSize) {
break;
}
}
while(pos < strSize && str.at(pos) != ' ') {
if(str.at(pos) == '#') {
comment = true;
break;
}
else if(str.at(pos) == ';') {
term = true;
++pos;
break;
}
else if(str.at(pos) == '|') {
++pos;
if(pos < strSize && str.at(pos) == '|') {
logOR = true;
++pos;
break;
}
}
else if(str.at(pos) == '&') {
++pos;
if(pos < strSize && str.at(pos) == '&') {
logAND = true;
++pos;
break;
}
}
else {
scomm += str.at(pos);
++pos;
}
}
if(comment) {
break;
}
strcpy(comm,scomm.c_str());
//++pos; // This is to ommit the whitespace character following the command
if(pos < strSize && str.at(pos) == ' ' && !(term)) {
while(pos < strSize && str.at(pos) == ' ') {
++pos;
}
if(pos >= strSize) {
break;
}
}
arr[arrPos] = comm;
++arrPos;
while(pos < strSize && !(term) && !(logOR) && !(logAND)) {
if(str.at(pos) == '#') {
break;
}
else if(str.at(pos) == '-' && str.at(pos+1) == ' ') {
sarg += str.at(pos);
++pos;
while(str.at(pos) == ' ') {
++pos;
}
}
else if(str.at(pos) == ';') {
++pos;
break;
}
else if(str.at(pos) == '|') {
++pos;
if(pos < strSize && str.at(pos) == '|') {
logOR = true;
++pos;
break;
}
}
else if(str.at(pos) == '&') {
++pos;
if(pos < strSize && str.at(pos) == '&') {
logAND = true;
++pos;
break;
}
}
else {
sarg += str.at(pos);
++pos;
hasArg = true;
}
}
if(hasArg) {
unsigned int n = 0;
string s;
while(n < sarg.size()) {
if(sarg.at(n) == '-' && n != 0) {
strcpy(arg, s.c_str());
arr[arrPos] = arg;
++arrPos;
s = "";
}
s += sarg.at(n);
++n;
}
n = s.size() -1;
while(s.at(n) == ' ') {
s.at(n) = '\0';
--n;
}
strcpy(arg, s.c_str());
arr[arrPos] = arg;
++arrPos;
}
arr[arrPos] = NULL;
/*for(int i = 0; i < 1; ++i) {
cout << arr[i] << endl;
}*/
if(scomm != "exit") {
pid = fork();
if(pid == 0) {
if((!(lastOR) && !(lastAND)) || (lastSuccess == false && lastOR == true) ||
(lastSuccess == true && lastAND == true)) {
if(execvp(arr[0], arr) == -1) {
success = true;
perror("The command could not be executed!");
errno = 0;
}
_exit(0);
}
}
else {
wait(0);
}
}
else {
if((!lastOR && !lastAND) || (!lastSuccess && lastOR) || (lastSuccess && lastAND)) {
cout << "Good-bye!" << endl;
exit(0);
}
}
lastOR = logOR;
lastAND = logAND;
lastSuccess = !(success);
free(comm);
free(arg);
}
if(bexit) {
break;
}
}
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <boost/tokenizer.hpp>
#include <string>
#include <unistd.h>
#include <stdio.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdlib.h>
#include <vector>
#include <stack>
using namespace std;
using namespace boost;
//function used to seperate commands
void parseconnect(vector< vector<string> > &cmd, vector<string> &connect, string command)
{
//different connectors
string semicolon = ";";
string needfirst = "&&";
string needfirstfail = "||";
int i = 0;
string comment = "#";
//deleting all comments
if (command.find(comment) != string::npos)
{
int com = command.find(comment);
command = command.substr(0, com);
}
//finding connectors
while (command.size() != 0)
{
int semi = 0;//command.find(semicolon);
int needf = 0;//command.find(needfirst);
int needff = 0;//command.find(needfirstfail);
//test for cases where connectors are gone
if (command.find(semicolon) != string::npos)
{
semi = command.find(semicolon);
}
else
{
semi = 10000;
}
if (command.find(needfirst) != string::npos)
{
needf = command.find(needfirst);
}
else
{
needf = 10000;
}
if (command.find(needfirstfail) != string::npos)
{
needff = command.find(needfirstfail);
}
else
{
needff = 10000;
}
//checks to see which index of the different connectors are first
vector<string> temp;
if (semi > needf)
{
if (needf > needff)
{
connect.push_back(needfirstfail);
temp.push_back(command.substr(0, needff));
command = command.substr(needff + 2, command.size() - needff - 2);
++i;
}
else
{
connect.push_back(needfirst);
temp.push_back(command.substr(0, needf));
command = command.substr(needf + 2, command.size() - needf - 2);
++i;
}
}
else if (needf > semi)
{
if (semi > needff)
{
connect.push_back(needfirstfail);
temp.push_back(command.substr(0, needff));
command = command.substr(needff + 2, command.size() - needff - 2);
++i;
}
else
{
connect.push_back(semicolon);
temp.push_back(command.substr(0, semi));
command = command.substr(semi + 1, command.size() - semi - 1);
++i;
}
}
else if ( (needf == semi) && (needff != 10000) )
{
if (needf > needff)
{
connect.push_back(needfirstfail);
temp.push_back(command.substr(0, needff));
command = command.substr(needff + 2, command.size() - needff - 2);
++i;
}
}
else
{
//used when out of connectors
temp.push_back(command);
cmd.push_back(temp);
return;
}
cmd.push_back(temp);
}
}
//tokenizer function
void token(vector< vector<string> > cmdl, vector< vector<string> > &cmdl2)
{
string f;
int size = cmdl.size();
for (int i = 0; i < size; ++i)
{
int j = 0;
char_separator<char> sep(" ");
tokenizer< char_separator<char> > tok(cmdl.at(i).at(0), sep);
//cout << cmdl.at(i).at(0) << endl;
cmdl2.push_back(vector<string>());
//must seperate vectors or the tokenizer will BREAK
for (tokenizer< char_separator<char> >::iterator iter = tok.begin(); iter != tok.end(); ++iter)
{
//cout << "deref iters: " << *iter << endl;
f = *iter;
cmdl2.at(i).push_back(f);
++j;
}
}
}
void startline()
{
char hostname[128];
//passes in an array named hostname & it basically makes a copy of the hostname stored
int hostnameStatus = gethostname(hostname, sizeof(hostname));
//somewhere else and passes it back by reference (default b/c its an array).
if (hostnameStatus == -1)
{
perror(hostname);
}
else
{
char* login = getlogin();
cout << login << "@" << hostname << " $ ";
}
}
//main run function, will prepare the command line
void run()
{
//sentinel for while loop
while (true)
{
//take in a command into a variable
string command;
startline();
getline(cin, command);
//exit command
if (command == "exit")
{
exit(0);
}
else
{
//call to parse
vector< vector<string> > cmdline;
vector<string> connectors;
parseconnect(cmdline, connectors, command);
//for (int i = 0; i < cmdline.size(); ++i)
//{
// cout << "cmd before tokenizing: " << cmdline.at(i).at(0) << endl;
//}
vector< vector<string> > cmdline2;
token(cmdline, cmdline2);
vector< vector<char*> > commands;
//changes all strings to char pointers
int size = cmdline2.size();
for (int i = 0; i < size; ++i)
{
//cout << cmdline.size() << endl;
commands.push_back( vector<char*>() );
for (unsigned int j = 0; j < cmdline2.at(i).size(); ++j)
{
//cout << endl;
//cout << "before conversion to char*: " << cmdline2.at(i).at(j) << endl;
//cout << "during conversion to char*: " << cmdline2.at(i).at(j).c_str() << endl;
commands.at(i).push_back(const_cast<char*>(cmdline2.at(i).at(j).c_str()));
}
char* temp = NULL;
commands.at(i).push_back(temp);
}
//calls process
unsigned int i = 0;
unsigned int j = 0;
bool sentinel = true;
while (sentinel == true)
{
if (commands.size() == 1)
{
pid_t pid = fork();
if (pid == 0)
{
if (execvp(commands.at(i).at(0), &(commands.at(i).at(0))) == -1)
{
perror("exec");
}
}
if (pid > 0)
{
if (wait(0) == -1)
{
perror("wait");
}
}
sentinel = false;
}
else
{
if (j == connectors.size())
{
--j;
}
//checks for connector logic
string temp = commands.at(i).at(0);
string tempconnectors = connectors.at(j);
if (temp.compare("exit") == 0)
{
exit(0);
}
//forking process to child
pid_t pid = fork();
if (pid == 0)
{
if (execvp(commands.at(i).at(0), &(commands.at(i).at(0))) == -1)
{
if (tempconnectors.compare("&&") == 0)
{
++i;
++j;
if (i < commands.size())
{
continue;
}
//else
//{
// sentinel = false;
//}
}
perror("exec");
}
}
if (pid > 0)
{
int stats;
if (wait(&stats) == -1)
{
perror("wait");
}
else if (WEXITSTATUS(stats) == 0)
{
if ( (tempconnectors.compare("||") == 0) )
{
++i;
++i;
++j;
++j;
if (j < connectors.size())
{
tempconnectors = connectors.at(j);
if (tempconnectors.compare("||") == 0)
{
++i;
++j;
}
}
if (i >= commands.size())
{
sentinel = false;
}
else
{
continue;
}
}
}
}
if (i >= connectors.size())
{
sentinel = false;
}
++i;
++j;
}
}
}
}
}
void parser(string command, vector<string> &cmd)
{
stack<int> parenthesis;
string firstParent = "(";
string closeParent = ")";
int topIndex = -1;
string subCommand = command; //initialized subCommand to command.
if(command.find(firstParent) != string::npos)
{
//ck if there r things before first parenthesis
if(command.find(firstParent) != 0)
{
subCommand = command.substr(0, index);
cmd.push_back(subCommand);
}
for(int i = 0; i < command.size(); i++)
{
if(command.at(i) == firstParent)
{
parenthesis.push(i);
if(
}
if(command.at(i) == closeParent)
{
topIndex = parenthesis.top();
parenthesis.pop();
subCommand = command.substr(topIndex + 1, i - topIndex - 1);
cmd.push_back(subCommand);
}
}
if(!parenthesis.empty())
{
cout << "Error" << endl;
}
}//end if no firstParent
}//end of parser function
//main function, will contain test cases
int main()
{
/*
string command = "ls -a ; echo asdfkasdfjasdf ; echo asdfjjenenc || aasdfaf";
vector<string> connectors;
vector< vector<string> > cmdline;
vector< vector<string> > cmdline2;
parseconnect(cmdline, connectors, command);
for (int i = 0; i < cmdline.size() - 1; ++i)
{
cout << cmdline.at(i).at(0);
for (int j = i; j < i + 1; ++j)
{
cout << connectors.at(j);
}
}
cout << cmdline.at(cmdline.size() - 1).at(0) << endl;
token(cmdline, cmdline2);
for (int i = 0; i < cmdline2.size(); ++i)
{
for (int j = 0; j < cmdline2.at(i).size(); ++j)
{
cout << "<" << cmdline2.at(i).at(j) << ">" << endl;
}
}
*/
run();
return 0;
}
<commit_msg>Changed main file to accept the test function<commit_after>#include <iostream>
#include <boost/tokenizer.hpp>
#include <string>
#include <unistd.h>
#include <stdio.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <vector>
#include <stack>
#include <cstring>
using namespace std;
using namespace boost;
//function used to seperate commands
void parseconnect(vector< vector<string> > &cmd, vector<string> &connect, string command)
{
//different connectors
string semicolon = ";";
string needfirst = "&&";
string needfirstfail = "||";
int i = 0;
string comment = "#";
//deleting all comments
if (command.find(comment) != string::npos)
{
int com = command.find(comment);
command = command.substr(0, com);
}
//finding connectors
while (command.size() != 0)
{
int semi = 0;//command.find(semicolon);
int needf = 0;//command.find(needfirst);
int needff = 0;//command.find(needfirstfail);
//test for cases where connectors are gone
if (command.find(semicolon) != string::npos)
{
semi = command.find(semicolon);
}
else
{
semi = 10000;
}
if (command.find(needfirst) != string::npos)
{
needf = command.find(needfirst);
}
else
{
needf = 10000;
}
if (command.find(needfirstfail) != string::npos)
{
needff = command.find(needfirstfail);
}
else
{
needff = 10000;
}
//checks to see which index of the different connectors are first
vector<string> temp;
if (semi > needf)
{
if (needf > needff)
{
connect.push_back(needfirstfail);
temp.push_back(command.substr(0, needff));
command = command.substr(needff + 2, command.size() - needff - 2);
++i;
}
else
{
connect.push_back(needfirst);
temp.push_back(command.substr(0, needf));
command = command.substr(needf + 2, command.size() - needf - 2);
++i;
}
}
else if (needf > semi)
{
if (semi > needff)
{
connect.push_back(needfirstfail);
temp.push_back(command.substr(0, needff));
command = command.substr(needff + 2, command.size() - needff - 2);
++i;
}
else
{
connect.push_back(semicolon);
temp.push_back(command.substr(0, semi));
command = command.substr(semi + 1, command.size() - semi - 1);
++i;
}
}
else if ( (needf == semi) && (needff != 10000) )
{
if (needf > needff)
{
connect.push_back(needfirstfail);
temp.push_back(command.substr(0, needff));
command = command.substr(needff + 2, command.size() - needff - 2);
++i;
}
}
else
{
//used when out of connectors
temp.push_back(command);
cmd.push_back(temp);
return;
}
cmd.push_back(temp);
}
}
//tokenizer function
void token(vector< vector<string> > cmdl, vector< vector<string> > &cmdl2)
{
string f;
int size = cmdl.size();
for (int i = 0; i < size; ++i)
{
int j = 0;
char_separator<char> sep(" ");
tokenizer< char_separator<char> > tok(cmdl.at(i).at(0), sep);
//cout << cmdl.at(i).at(0) << endl;
cmdl2.push_back(vector<string>());
//must seperate vectors or the tokenizer will BREAK
for (tokenizer< char_separator<char> >::iterator iter = tok.begin(); iter != tok.end(); ++iter)
{
//cout << "deref iters: " << *iter << endl;
f = *iter;
cmdl2.at(i).push_back(f);
++j;
}
}
}
void startline()
{
char hostname[128];
//passes in an array named hostname & it basically makes a copy of the hostname stored
int hostnameStatus = gethostname(hostname, sizeof(hostname));
//somewhere else and passes it back by reference (default b/c its an array).
if (hostnameStatus == -1)
{
perror(hostname);
}
else
{
char* login = getlogin();
cout << login << "@" << hostname << " $ ";
}
}
//-----------------------------------------------------------------------------
void test_func(vector <char*> to_test)
{
//cout << "detects [] or test" << endl;
string e_delim = "-e";
char* ed = const_cast<char*>(e_delim.c_str());
string f_delim = "-f";
char* fd = const_cast<char*>(f_delim.c_str());
string d_delim = "-d";
char* dd = const_cast<char*>(d_delim.c_str());
if (strcmp(to_test.at(1), ed) == 0)
{
struct stat buffer;
//cout << "there we go E" << endl;
int statusstat = stat(to_test.at(2), &buffer);
//cout << "Status of stat: " << statusstat << endl;
if (statusstat == 0)
{
cout << "(true)" << endl;
cout << "Path: Exists." << endl;
}
else
{
cout << "(false)" << endl;
cout << "Path: Does not exist." << endl;
}
}
else if (strcmp(to_test.at(1), fd) == 0)
{
//cout << "there we go F" << endl;
struct stat buffer;
stat(to_test.at(2), &buffer);
//cout << "Status of stat: " << statusstat << endl;
bool tempbool = S_ISREG(buffer.st_mode);
if (tempbool)
{
cout << "(true)" << endl;
cout << "Filename: Is regular file." << endl;
}
else
{
cout << "(false)" << endl;
cout << "Filename: Is not regular file." << endl;
}
}
else if (strcmp(to_test.at(1), dd) == 0)
{
//cout << "there we go D" << endl;
struct stat buffer;
stat(to_test.at(2), &buffer);
//cout << "Status of stat: " << statusstat << endl;
bool tempbool = S_ISDIR(buffer.st_mode);
if (tempbool)
{
cout << "(true)" << endl;
cout << "Filename: Is a directory." << endl;
}
else
{
cout << "(false)" << endl;
cout << "Filename: Is not a directory." << endl;
}
}
else if (to_test.size() == 2)
{
//cout << "auto set: E" << endl;
struct stat buffer;
int statusstat = stat(to_test.at(1), &buffer);
//cout << "Status of stat: " << statusstat << endl;
if (statusstat == 0)
{
cout << "(true)" << endl;
cout << "Path: Exists." << endl;
}
else
{
cout << "(false)" << endl;
cout << "Path: Does not exist." << endl;
}
}
else if (to_test.size() == 1)
{
cout << "Error: invalid use of test" << endl;
}
else
{
//cout << "auto set: E" << endl;
struct stat buffer;
int statusstat = stat(to_test.at(2), &buffer);
//cout << "Status of stat: " << statusstat << endl;
if (statusstat == 0)
{
cout << "(true)" << endl;
cout << "Path: Exists." << endl;
}
else
{
cout << "(false)" << endl;
cout << "Path: Does not exist." << endl;
}
}
}
//-------------------------------------------------------------------------------
//main run function, will prepare the command line
void run()
{
//sentinel for while loop
while (true)
{
//take in a command into a variable
string command;
startline();
getline(cin, command);
//exit command
if (command == "exit")
{
exit(0);
}
else
{
//call to parse
vector< vector<string> > cmdline;
vector<string> connectors;
parseconnect(cmdline, connectors, command);
//for (int i = 0; i < cmdline.size(); ++i)
//{
// cout << "cmd before tokenizing: " << cmdline.at(i).at(0) << endl;
//}
vector< vector<string> > cmdline2;
token(cmdline, cmdline2);
vector< vector<char*> > commands;
//-------------------------------------------------------------------------
//changes
string test1 = "test";
char* test2 = const_cast<char*>(test1.c_str());
string test_openb = "[";
string test_closedb = "]";
char* test3 = const_cast<char*>(test_openb.c_str());
char* test4 = const_cast<char*>(test_closedb.c_str());
//-------------------------------------------------------------------------
//changes all strings to char pointers
int size = cmdline2.size();
for (int i = 0; i < size; ++i)
{
//cout << cmdline.size() << endl;
commands.push_back( vector<char*>() );
for (unsigned int j = 0; j < cmdline2.at(i).size(); ++j)
{
//cout << endl;
//cout << "before conversion to char*: " << cmdline2.at(i).at(j) << endl;
//cout << "during conversion to char*: " << cmdline2.at(i).at(j).c_str() << endl;
commands.at(i).push_back(const_cast<char*>(cmdline2.at(i).at(j).c_str()));
/*--------------------------------------------------------------------------
if (strcmp(commands.at(i).at(0), test2) == 0)
{
cout << "Hello there!" << " " << commands.at(i).at(0) << endl;
}
else if (strcmp(commands.at(i).at(0), test3) == 0)
{
cout << "Hello there!" << " " << commands.at(i).at(0) << endl;
}
*///-------------------------------------------------------------------------
}
char* temp = NULL;
commands.at(i).push_back(temp);
}
//calls process
unsigned int i = 0;
unsigned int j = 0;
bool sentinel = true;
while (sentinel == true)
{
if (strcmp(commands.at(i).at(0), test3) == 0)
{
char* tempcharp = commands.at(i).at(commands.at(i).size() - 1);
if (strcmp(tempcharp, test4) == 0)
{
test_func(commands.at(i));
}
++i;
++j;
if (i == commands.size())
{
break;
}
}
else if (strcmp(commands.at(i).at(0), test2) == 0)
{
test_func(commands.at(i));
++i;
++j;
if (i == commands.size())
{
break;
}
}
else
{
if (commands.size() == 1)
{
pid_t pid = fork();
if (pid == 0)
{
//--------------------------------------------------------------------------
int tempexec = execvp(commands.at(i).at(0), &(commands.at(i).at(0)));
if (tempexec == -1)
{
perror("exec");
}
//-----------------------
}
if (pid > 0)
{
if (wait(0) == -1)
{
perror("wait");
}
}
sentinel = false;
}
else
{
if (j == connectors.size())
{
--j;
}
//checks for connector logic
string temp = commands.at(i).at(0);
string tempconnectors = connectors.at(j);
if (temp.compare("exit") == 0)
{
exit(0);
}
//forking process to child
pid_t pid = fork();
if (pid == 0)
{
if (execvp(commands.at(i).at(0), &(commands.at(i).at(0))) == -1)
{
if (tempconnectors.compare("&&") == 0)
{
++i;
++j;
if (i < commands.size())
{
continue;
}
//else
//{
// sentinel = false;
//}
}
perror("exec");
}
}
if (pid > 0)
{
int stats;
if (wait(&stats) == -1)
{
perror("wait");
}
else if (WEXITSTATUS(stats) == 0)
{
if ( (tempconnectors.compare("||") == 0) )
{
++i;
++i;
++j;
++j;
if (j < connectors.size())
{
tempconnectors = connectors.at(j);
if (tempconnectors.compare("||") == 0)
{
++i;
++j;
}
}
if (i >= commands.size())
{
sentinel = false;
}
else
{
continue;
}
}
}
}
if (i >= connectors.size())
{
sentinel = false;
}
++i;
++j;
}
}
}
}
}
}
/*
void parser(string command, vector<string> &cmd)
{
stack<int> parenthesis;
string firstParent = "(";
string closeParent = ")";
int topIndex = -1;
string subCommand = command; //initialized subCommand to command.
if(command.find(firstParent) != string::npos)
{
//ck if there r things before first parenthesis
if(command.find(firstParent) != 0)
{
subCommand = command.substr(0, index);
cmd.push_back(subCommand);
}
for(int i = 0; i < command.size(); i++)
{
if(command.at(i) == firstParent)
{
parenthesis.push(i);
if(
}
if(command.at(i) == closeParent)
{
topIndex = parenthesis.top();
parenthesis.pop();
subCommand = command.substr(topIndex + 1, i - topIndex - 1);
cmd.push_back(subCommand);
}
}
if(!parenthesis.empty())
{
cout << "Error" << endl;
}
}//end if no firstParent
}//end of parser function
*/
//main function, will contain test cases
int main()
{
/*
string command = "ls -a ; echo asdfkasdfjasdf ; echo asdfjjenenc || aasdfaf";
vector<string> connectors;
vector< vector<string> > cmdline;
vector< vector<string> > cmdline2;
parseconnect(cmdline, connectors, command);
for (int i = 0; i < cmdline.size() - 1; ++i)
{
cout << cmdline.at(i).at(0);
for (int j = i; j < i + 1; ++j)
{
cout << connectors.at(j);
}
}
cout << cmdline.at(cmdline.size() - 1).at(0) << endl;
token(cmdline, cmdline2);
for (int i = 0; i < cmdline2.size(); ++i)
{
for (int j = 0; j < cmdline2.at(i).size(); ++j)
{
cout << "<" << cmdline2.at(i).at(j) << ">" << endl;
}
}
*/
run();
return 0;
}
<|endoftext|> |
<commit_before>/*
main.c
The Knights from Porto
Created by Daniel Monteiro on 11/26/14.
Copyright (c) 2014 Daniel Monteiro. All rights reserved.
*/
#include <utility>
#include <string>
#include <iostream>
#include <memory>
#include <fstream>
#include <vector>
#include "Vec2i.h"
#include "IMapElement.h"
#include "CActor.h"
#include "CMap.h"
#include "IRenderer.h"
#include "CConsoleRenderer.h"
#include "CFalconKnight.h"
#include "CBullKnight.h"
#include "CTurtleKnight.h"
#include "CGame.h"
std::string readMap(const char *mapName) {
std::string entry;
std::ifstream mapFile("res/map1.txt");
char line[80];
while (!mapFile.eof()) {
mapFile >> line;
entry += line;
}
auto position = entry.find('\n');
while (position != std::string::npos) {
entry.replace(position, 1, "");
position = entry.find('\n', position + 1);
}
return entry;
}
int main ( int argc, char **argv ) {
std::string mapData = readMap("res/map1.txt");
Knights::CGame game( mapData, std::make_shared<Knights::CConsoleRenderer>() );
return 0;
}
<commit_msg>Makes the map actually load the file I choose<commit_after>/*
main.c
The Knights from Porto
Created by Daniel Monteiro on 11/26/14.
Copyright (c) 2014 Daniel Monteiro. All rights reserved.
*/
#include <utility>
#include <string>
#include <iostream>
#include <memory>
#include <fstream>
#include <vector>
#include "Vec2i.h"
#include "IMapElement.h"
#include "CActor.h"
#include "CMap.h"
#include "IRenderer.h"
#include "CConsoleRenderer.h"
#include "CFalconKnight.h"
#include "CBullKnight.h"
#include "CTurtleKnight.h"
#include "CGame.h"
std::string readMap(const char *mapName) {
std::string entry;
std::ifstream mapFile(mapName);
char line[80];
while (!mapFile.eof()) {
mapFile >> line;
entry += line;
}
auto position = entry.find('\n');
while (position != std::string::npos) {
entry.replace(position, 1, "");
position = entry.find('\n', position + 1);
}
return entry;
}
int main ( int argc, char **argv ) {
std::string mapData = readMap("res/map1.txt");
Knights::CGame game( mapData, std::make_shared<Knights::CConsoleRenderer>() );
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
//linux system libraries
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
//system libraries end
#include <csignal>
#include <queue>
#define MEMORY 66666
using namespace std;
void parsing(string& cmd)
{
char* parsed = (char*) malloc (MEMORY);
for (int i = 0, j = 0; cmd[i] != '\0'; ++i, ++j)
{
if(cmd[i] == '#')
{
//cout << "made it#" << endl;
cmd[i] = '\0';
parsed[j] = '\0';
}
else if (cmd[i] == ';')
{
//cout << "made it;" << endl;
parsed[j] = ' ';
parsed[++j] = ';';
parsed[++j] = ' ';
//display(parsed);
}
else if (cmd[i] == '|' && cmd[i + 1] == '|')
{
//cout << "made it||" << endl;
parsed[j] = ' ';
parsed[++j] = '|';
parsed[++j] = '|';
parsed[++j] = ' ';
++i;
}
else if (cmd[i] == '&' && cmd[i + 1] == '&')//&& connector
{
//cout << "made it&&" << endl;
parsed[j] = ' ';
parsed[++j] = '&';
parsed[++j] = '&';
parsed[++j] = ' ';
++i;
}
else
{
//cout <<"This is parsed at " << parsed[j] << endl;
parsed[j] = cmd[i];
}
if (cmd[i + 1] == '\0')
{
parsed[j + 1] = '\0';
//cout << "Index of j: " << j << end
}
//display(parsed);
}
cout << "Original: " << cmd << endl;
cout << "parsed commands: " << parsed <<endl;
//display(parsed);
cmd = parsed;
free(parsed);
//cout << "new cmd: " << cmd << endl;
//const char *c = cmd.c_str();
//strcpy(, parsed);
//free(parsed)
}
// queue of strings
//pop strings to an array of char
//point array to c
void commandsort(char* cmd, char* b[] )
{
int i = 0;
char* token = strtok(cmd, " ");
while (token != NULL)
{
b[i] = token;
token = strtok(NULL , " " );
i++;
}
b[i] = '\0';
//cout << "Work\n";
// queue<string> test;
// for(unsigned k = 0; b[k] != '\0'; k++)
// {
// cout << "Pointer " << k << ": ";
// for(unsigned l = 0; b[k][l] != '\0'; l++)
// {
// cout << b[k][l];
// }
// test.push(b[k]);
// cout << endl;
// }
}
//when i hit a connector in char array set it to null and keep track of array
void executecmd(char* array[])
{
pid_t processID, pid; //processID = commands
int status;
int i = 0;
queue<string> connectors;
queue<string> comms;
while(array[i] != '\0')
{
comms.push(array[i]); //pushes commands into queue
i++;
}
i = 0;
//char* temp = new char [100]; //mem = 66666
while (true)
{
//char* temp[100];
if(comms.empty())
{
break;
}
if ((comms.front() != ";") || (comms.front() != "&&")|| //populate array
(comms.front() != "||"))
{
char* temp = new char [100];
strcpy(temp, comms.front().c_str());
array[i] = temp;
comms.pop();
i++;
}
else //comms.front == connector //stop parsing and execvp
{
connectors.push(comms.front());
comms.pop();
break;
}
}
array[i] = '\0';
for(unsigned k = 0; array[k] != '\0'; k++)
{
cout << "Pointer " << k << ": ";
cout << array[k];
// for(unsigned l = 0; array[k][l] != '\0'; l++)
// {
// cout << array[k][l];
// }
cout << endl;
}
cout << "Value of i: " << i <<endl;
processID = fork(); //fork
if(processID < 0) //fork fails
{
cout << "Fork Failed" << endl;
exit(1);
}
else if(processID == 0) // child process
{
cout << "Executing \n";
cout << "Child: executing: \n";
//cout << comms.front() << endl; // switches off the parent
cout << "Work dammit \n";
execvp(array[0], array);
cout << "Execute failed \n";
perror("There was an error with the executable or argument list");
}
else if (processID > 0)
{
if((pid = wait(&status)) < 0)
{
cout << "Process failed\n";
perror("Process failed");
exit(-1);
}
if (WIFEXITED(status))
{
if(WIFEXITED(status) != 0)
{
//bool success = false;
}
}
cout << "Parent: finished" << endl;
}
}
int main (int argc, char **argv)
{
string cmd;
cout << "$ ";
getline(cin, cmd);
parsing(cmd);
//put null after every connector
//tokenize strtok with \0 as a delimiter.
//vector<string> commands;
char* b[MEMORY];
char command[MEMORY];
cout << "Copying \n";
for(unsigned i =0; cmd[i] != '\0'; i++)
{
command[i] = cmd[i];
}
command[cmd.length()] = '\0';
for (unsigned i = 0; command[i] != '\0'; i++)
{
cout << command[i];
}
cout << endl;
commandsort(command, b);
executecmd(b);
//character pointer array
//char *b[MEMORY];
//if i find a space ' ' then everything before that space goes into the first pointer
//of the character array get the address of everything before the space into the chararray
}
// if it fails then child returns -1 //
//perror outputs failure when fork fails
//waitpid(current_pid, &status, 0)
//strtok(string, " ");
//while (string != NULL)<commit_msg>Able to execute multiple commands<commit_after>#include <iostream>
//linux system libraries
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
//system libraries end
#include <csignal>
#include <queue>
#define MEMORY 66666
using namespace std;
void parsing(string& cmd)
{
char* parsed = (char*) malloc (MEMORY);
for (int i = 0, j = 0; cmd[i] != '\0'; ++i, ++j)
{
if(cmd[i] == '#')
{
//cout << "made it#" << endl;
cmd[i] = '\0';
parsed[j] = '\0';
}
else if (cmd[i] == ';')
{
//cout << "made it;" << endl;
parsed[j] = ' ';
parsed[++j] = ';';
parsed[++j] = ' ';
//display(parsed);
}
else if (cmd[i] == '|' && cmd[i + 1] == '|')
{
//cout << "made it||" << endl;
parsed[j] = ' ';
parsed[++j] = '|';
parsed[++j] = '|';
parsed[++j] = ' ';
++i;
}
else if (cmd[i] == '&' && cmd[i + 1] == '&')//&& connector
{
//cout << "made it&&" << endl;
parsed[j] = ' ';
parsed[++j] = '&';
parsed[++j] = '&';
parsed[++j] = ' ';
++i;
}
else
{
//cout <<"This is parsed at " << parsed[j] << endl;
parsed[j] = cmd[i];
}
if (cmd[i + 1] == '\0')
{
parsed[j + 1] = '\0';
//cout << "Index of j: " << j << end
}
//display(parsed);
}
cout << "Original: " << cmd << endl;
cout << "parsed commands: " << parsed <<endl;
//display(parsed);
cmd = parsed;
free(parsed);
//cout << "new cmd: " << cmd << endl;
//const char *c = cmd.c_str();
//strcpy(, parsed);
//free(parsed)
}
// queue of strings
//pop strings to an array of char
//point array to c
void commandsort(char* cmd, char* b[] )
{
int i = 0;
char* token = strtok(cmd, " ");
while (token != NULL)
{
b[i] = token;
token = strtok(NULL , " " );
i++;
}
b[i] = '\0';
//cout << "Work\n";
// queue<string> test;
// for(unsigned k = 0; b[k] != '\0'; k++)
// {
// cout << "Pointer " << k << ": ";
// for(unsigned l = 0; b[k][l] != '\0'; l++)
// {
// cout << b[k][l];
// }
// test.push(b[k]);
// cout << endl;
// }
}
//when i hit a connector in char array set it to null and keep track of array
void executecmd(char* array[])
{
pid_t processID, pid; //processID = commands
int status;
int i = 0;
queue<string> connectors;
queue<string> comms;
while(array[i] != '\0')
{
comms.push(array[i]); //pushes commands into queue
i++;
}
//char* temp = new char [100]; //mem = 66666
while (true)
{
i = 0;
if(comms.empty())
{
break;
}
while (true)
{
//char* temp[100];
if(comms.empty())
{
break;
}
if ((comms.front() != ";") || (comms.front() != "&&")|| //populate array
(comms.front() != "||"))
{
char* temp = new char [100];
strcpy(temp, comms.front().c_str());
array[i] = temp;
comms.pop();
i++;
}
else //comms.front == connector //stop parsing and execvp
{
connectors.push(comms.front());
comms.pop();
break;
}
}
array[i] = '\0';
for(unsigned k = 0; array[k] != '\0'; k++)
{
cout << "Pointer " << k << ": ";
cout << array[k];
// for(unsigned l = 0; array[k][l] != '\0'; l++)
// {
// cout << array[k][l];
// }
cout << endl;
}
cout << "Value of i: " << i <<endl;
processID = fork(); //fork
if(processID < 0) //fork fails
{
cout << "Fork Failed" << endl;
exit(1);
}
else if(processID == 0) // child process
{
cout << "Executing \n";
cout << "Child: executing: \n";
//cout << comms.front() << endl; // switches off the parent
cout << "Work dammit \n";
execvp(array[0], array);
cout << "Execute failed \n";
perror("There was an error with the executable or argument list");
}
else if (processID > 0)
{
if((pid = wait(&status)) < 0)
{
cout << "Process failed\n";
perror("Process failed");
exit(-1);
}
if (WIFEXITED(status))
{
if(WIFEXITED(status) != 0)//command sucess
{
}
}
cout << "Parent: finished" << endl;
}
break;
}
}
int main (int argc, char **argv)
{
string cmd;
cout << "$ ";
getline(cin, cmd);
parsing(cmd);
//put null after every connector
//tokenize strtok with \0 as a delimiter.
//vector<string> commands;
char* b[MEMORY];
char command[MEMORY];
cout << "Copying \n";
for(unsigned i =0; cmd[i] != '\0'; i++)
{
command[i] = cmd[i];
}
command[cmd.length()] = '\0';
for (unsigned i = 0; command[i] != '\0'; i++)
{
cout << command[i];
}
cout << endl;
commandsort(command, b);
executecmd(b);
//character pointer array
//char *b[MEMORY];
//if i find a space ' ' then everything before that space goes into the first pointer
//of the character array get the address of everything before the space into the chararray
}
// if it fails then child returns -1 //
//perror outputs failure when fork fails
//waitpid(current_pid, &status, 0)
//strtok(string, " ");
//while (string != NULL)<|endoftext|> |
<commit_before>#include <vraptor.hpp>
#include <iostream>
#include <fstream>
#include <sstream>
#include "vrtimer.hpp"
#include<codegen.hpp>
#include<iostream>
#include<sstream>
#include<string>
#include<fstream>
#include<cstdlib>
#include<prettyPrinter.hpp>
#include<vector>
#include<string.h>
#include <node-collector.hpp>
#include<getopt.h>
using namespace std;
using namespace VRaptor;
extern bool memOptimise;
extern bool prelim_bounds;
extern bool phase2Optimise;
extern bool enableOpenMp;
string readFile(const string& fname) {
ifstream f(fname.c_str());
stringstream buf;
while (f.good()) {
string line;
getline(f, line);
buf << line << endl;
}
f.close();
return buf.str();
}
string readDataIntoString(const string& fname){
ifstream ifile(fname.c_str());
stringstream ss;
string line;
while(!ifile.eof()){
getline(ifile,line);
ss<<line<<endl;
}
return ss.str();
}
void writeFile(const string& fname , vector<string>& data){
ofstream f(fname.c_str());
for(int i=0;i<data.size();i++){
f<<data[i];
}
}
string getFileNameNoExt(string fname){
std::string fCopy =fname;
char* tok = strtok(const_cast<char*>(fCopy.c_str()),"/");
char* tok1=NULL;
while(tok!=NULL) {
tok1=tok;
tok = strtok(NULL,"/");
}
if(tok1==NULL){
tok1=const_cast<char*>(fname.c_str());
}
return string(const_cast<const char*>(strtok(const_cast<char*>(tok1),".")));
}
void setOptFlags(string optArg) {
if(optArg.compare("mem") == 0) {
memOptimise = true;
}
if(optArg.compare("bounds") == 0) {
prelim_bounds=true;
phase2Optimise = true;
}
if(optArg.compare("par") == 0) {
enableOpenMp = true;
}
}
int main(int argc,char * argv[]){
if(argc<2){
std::cout<<"Usage: <filename>"<<std::endl;
exit(0);
}
static struct option long_options[] =
{
/* These options don’t set a flag.
We distinguish them by their indices. */
{"opt", required_argument,0, 'O'},
{"outFile",required_argument,0, 'f'},
{0, 0, 0, 0}
};
std::string fname;
std::string outFilePath = "";
bool genFile =false;
while(1) {
int option_index = 0;
int c = getopt_long (argc, argv, "O:f:",
long_options, &option_index);
if(c==-1) {
break;
}
switch(c) {
case 0:
printf("probably should not be here\n");
break;
case 'O':
setOptFlags(optarg);
break;
case 'f' :
outFilePath = strdup(optarg);
genFile = true;
break;
default:
break;
}
}
if(optind < argc) {
fname = argv[optind];
}
std::string optionStr="";
initRaptor();
fname = argv[1];
std::string fCopy = fname;
string s =readDataIntoString(fname);
VModule *m=NULL;
m= VModule::readFromString(s);
NodeCollector nc;
nc.analyze(m);
std::string str = getFileNameNoExt(fCopy);
VCompiler vc(str);
vc.setCollector(nc);
Context cntxt=vc.moduleCodeGen(m);
PrettyPrinter pp;
vector<string> vec_cpp = pp.prettyPrint(cntxt.getAllStmt());
vector<string> vec_hpp = pp.prettyPrint(vc.getHeaderContext().getAllStmt());
if(genFile) {
for(int i=0;i<vec_cpp.size();i++){
std::cout<<vec_cpp[i];
}
for(int i=0;i<vec_hpp.size();i++){
std::cout<<vec_hpp[i];
}
} else {
writeFile(str+"Impl.cpp",vec_cpp);
writeFile(str+"Impl.hpp",vec_hpp);
}
}
<commit_msg>Removed bug in main file<commit_after>#include <vraptor.hpp>
#include <iostream>
#include <fstream>
#include <sstream>
#include "vrtimer.hpp"
#include<codegen.hpp>
#include<iostream>
#include<sstream>
#include<string>
#include<fstream>
#include<cstdlib>
#include<prettyPrinter.hpp>
#include<vector>
#include<string.h>
#include <node-collector.hpp>
#include<getopt.h>
using namespace std;
using namespace VRaptor;
extern bool memOptimise;
extern bool prelim_bounds;
extern bool phase2Optimise;
extern bool enableOpenMp;
string readFile(const string& fname) {
ifstream f(fname.c_str());
stringstream buf;
while (f.good()) {
string line;
getline(f, line);
buf << line << endl;
}
f.close();
return buf.str();
}
string readDataIntoString(const string& fname){
ifstream ifile(fname.c_str());
stringstream ss;
string line;
while(!ifile.eof()){
getline(ifile,line);
ss<<line<<endl;
}
return ss.str();
}
void writeFile(const string& fname , vector<string>& data){
ofstream f(fname.c_str());
for(int i=0;i<data.size();i++){
f<<data[i];
}
}
string getFileNameNoExt(string fname){
std::string fCopy =fname;
char* tok = strtok(const_cast<char*>(fCopy.c_str()),"/");
char* tok1=NULL;
while(tok!=NULL) {
tok1=tok;
tok = strtok(NULL,"/");
}
if(tok1==NULL){
tok1=const_cast<char*>(fname.c_str());
}
return string(const_cast<const char*>(strtok(const_cast<char*>(tok1),".")));
}
void setOptFlags(string optArg) {
if(optArg.compare("mem") == 0) {
memOptimise = true;
}
if(optArg.compare("bounds") == 0) {
prelim_bounds=true;
phase2Optimise = true;
}
if(optArg.compare("par") == 0) {
enableOpenMp = true;
}
if(optArg.compare("all") == 0) {
enableOpenMp = true;
}
}
int main(int argc,char * argv[]){
if(argc<2){
std::cout<<"Usage: <filename>"<<std::endl;
exit(0);
}
static struct option long_options[] =
{
/* These options don’t set a flag.
We distinguish them by their indices. */
{"opt", required_argument,0, 'O'},
{"outFile",required_argument,0, 'f'},
{0, 0, 0, 0}
};
std::string fname;
std::string outFilePath = "";
bool genFile =false;
while(1) {
int option_index = 0;
int c = getopt_long (argc, argv, "O:f:",
long_options, &option_index);
if(c==-1) {
break;
}
switch(c) {
case 0:
printf("probably should not be here\n");
break;
case 'O':
setOptFlags(optarg);
break;
case 'f' :
outFilePath = strdup(optarg);
genFile = true;
break;
default:
break;
}
}
if(optind < argc) {
fname = argv[optind];
} else {
printf("atleast one input file required\n");
}
std::string optionStr="";
initRaptor();
std::string fCopy = fname;
string s =readDataIntoString(fname);
VModule *m=NULL;
m= VModule::readFromString(s);
NodeCollector nc;
nc.analyze(m);
std::string str = getFileNameNoExt(fCopy);
VCompiler vc(str);
vc.setCollector(nc);
Context cntxt=vc.moduleCodeGen(m);
PrettyPrinter pp;
vector<string> vec_cpp = pp.prettyPrint(cntxt.getAllStmt());
vector<string> vec_hpp = pp.prettyPrint(vc.getHeaderContext().getAllStmt());
if(!genFile) {
for(int i=0;i<vec_cpp.size();i++){
std::cout<<vec_cpp[i];
}
for(int i=0;i<vec_hpp.size();i++){
std::cout<<vec_hpp[i];
}
} else {
writeFile(str+"Impl.cpp",vec_cpp);
writeFile(str+"Impl.hpp",vec_hpp);
}
}
<|endoftext|> |
<commit_before>#include <irrlicht.h>
#include "events.h"
#include "gui_game.h"
using namespace irr;
namespace ic = irr::core;
namespace is = irr::scene;
namespace iv = irr::video;
namespace ig = irr::gui;
is::ITriangleSelector* createTree(is::IAnimatedMesh *mesh, is::ISceneManager *smgr, EventReceiver receiver, iv::IVideoDriver *driver);
is::ITriangleSelector* createColumn(int position_x, int position_z, int height, is::IAnimatedMeshSceneNode *node, is::IAnimatedMesh *mesh, is::ISceneManager *smgr, std::vector<iv::ITexture*> textures, EventReceiver receiver);
is::ITriangleSelector* createMountain(int nbMountains, is::IAnimatedMeshSceneNode *node, is::IAnimatedMesh *mesh, is::ISceneManager *smgr, std::vector<iv::ITexture*> textures, EventReceiver receiver);
const int ID = 40;
const int cpt = 0;
int main()
{
// Le gestionnaire d'événements
EventReceiver receiver;
std::vector<iv::ITexture*> textures;
// Création de la fenêtre et du système de rendu.
IrrlichtDevice *device = createDevice(iv::EDT_OPENGL,
ic::dimension2d<u32>(640, 480),
16, false, false, false, &receiver);
is::ISceneManager *smgr = device->getSceneManager();
iv::IVideoDriver *driver = device->getVideoDriver();
ig::IGUIEnvironment *gui_game = device->getGUIEnvironment();
// Stockage des textures
textures.push_back(driver->getTexture("data/TXsQk.png"));
// Chargement du cube
is::IAnimatedMesh *mesh = smgr->getMesh("data/cube.obj");
//chargement du santaclaus
is::IAnimatedMesh *mesh_santaclaus = smgr->getMesh("data/Steve.obj");
//chargement du tree
is::IAnimatedMesh *mesh_tree = smgr->getMesh("data/lowpolytree.obj");
// Ajout de la scène
is::IAnimatedMeshSceneNode *node;
int Ni = 100;
int Nj = 100;
is::IMetaTriangleSelector *metaselector = smgr-> createMetaTriangleSelector();
for (int i = 0 ; i < Ni ; i ++)
{
for (int j = 0 ; j < Nj ; j ++)
{
node = smgr->addAnimatedMeshSceneNode(mesh,nullptr,i+j);
node->setMaterialFlag(irr::video::EMF_LIGHTING, false);
node->setPosition (core::vector3df(i,0,j));
textures.push_back(driver->getTexture("data/TXsQk.png"));
node->setMaterialTexture(0, textures[0]);
receiver.set_node(node);
receiver.set_textures(textures);
// Création du triangle selector pour gérer la collision
is::ITriangleSelector *selector = smgr->createTriangleSelector(node->getMesh(),node);
node ->setTriangleSelector (selector);
//meta selector permettant de stocker les selecteurs de tous mes cubes
metaselector->addTriangleSelector(selector);
}
}
//is::ITriangleSelector* selector1 = createTree(mesh, smgr,receiver,driver);
//metaselector->addTriangleSelector(selector1);
//Ajout de reliefs sur la scene
int nbMountains = 2;
is::ITriangleSelector* selector2 = createMountain(nbMountains, node, mesh, smgr, textures, receiver);
metaselector->addTriangleSelector(selector2);
// Ajout du cube à la scène
/*is::IAnimatedMeshSceneNode *node_personnage;
node_personnage = smgr->addAnimatedMeshSceneNode(mesh);
node_personnage->setPosition(core::vector3df(20, 10, 20));
textures.push_back(driver->getTexture("data/rouge.jpg"));
node_personnage->setMaterialTexture(0, textures.back());
node_personnage->setMaterialFlag(irr::video::EMF_LIGHTING, false);
receiver.set_node(node_personnage);
receiver.set_textures(textures);*/
//ajout tree (ou une forêt) à la scene
is::IAnimatedMeshSceneNode *node_tree;
int Nl = 7;
int Nk = 7;
for (int l=0; l<Nl; l++)
{
for (int k=0; k<Nk; k++)
{
node_tree = smgr->addAnimatedMeshSceneNode(mesh_tree,nullptr, l+k);
node_tree->setMaterialFlag(irr::video::EMF_LIGHTING, false);
node_tree->setPosition(core::vector3df(10+4*l, 4.3, 60+4*k));//30+4*l, 4.3, 5+4*l));
node_tree->setScale(core::vector3df(1.5,1.5,1.5));
receiver.set_node(node_tree);
//node_tree->setDebugDataVisible(is::EDS_NORMALS);
//selector sur l'arbre
is::ITriangleSelector *selector = smgr->createTriangleSelector(mesh_tree,node_tree);
node_tree->setTriangleSelector(selector);
selector->drop();
node_tree->setID(ID);
metaselector->addTriangleSelector(selector);
}
}
//ajout santaclaus à la scene
is::IAnimatedMeshSceneNode *node_santaclaus;
node_santaclaus = smgr->addAnimatedMeshSceneNode(mesh_santaclaus);
node_santaclaus->setMaterialFlag(irr::video::EMF_LIGHTING, false);
node_santaclaus->setPosition(core::vector3df(20, 2, 30));
textures.push_back(driver->getTexture("data/Santa.png"));
node_santaclaus->setMaterialTexture(0, textures.back());
node_santaclaus->setScale(core::vector3df(0.5,0.5,0.5));
receiver.set_node(node_santaclaus);
receiver.set_textures(textures);
receiver.set_gui(gui_game);
//Gestion collision
is::ISceneNodeAnimator *anim;
anim = smgr ->createCollisionResponseAnimator(metaselector, node_santaclaus,
ic::vector3df(1, 1, 1), //Rayon de la cam
ic::vector3df(0, -10, 0), //gravité
ic::vector3df(0, 0, 0)); // décalage du centre
node_santaclaus->addAnimator(anim);
//gestionnaire de collision "Selection"
is::ISceneCollisionManager *collision_manager = smgr->getSceneCollisionManager();
//caméra qui va suivre notre personnage
//son parent est donc le noeud qui definit le personnage
//deuxieme paramètre:position de la camera (look From)
//troisieme paramètre: look at (ici c'est la position du personnage) mise a jour dans event.cpp
is::ICameraSceneNode *camera = smgr->addCameraSceneNode(node_santaclaus, ic::vector3df(20,10,0), node_santaclaus->getPosition());
receiver.set_camera(camera);
// La barre de menu
gui_game::create_menu(gui_game);
while(device->run())
{
driver->beginScene(true, true, iv::SColor(0,50,100,255));
//Séléction de l'arbre à couper avec la souris
int mouse_x, mouse_y;
if (receiver.is_mouse_pressed(mouse_x, mouse_y))
{
ic::line3d<f32> ray;
ray = collision_manager->getRayFromScreenCoordinates(ic::position2d<s32>(mouse_x, mouse_y));
ic::vector3df intersection;
ic::triangle3df hit_triangle;
is::ISceneNode *selected_scene_node = collision_manager->getSceneNodeAndCollisionPointFromRay(ray,
intersection, // On récupère ici les coordonnées 3D de l'intersection
hit_triangle, // et le triangle intersecté
ID); // On ne veut que des noeuds avec cet identifiant
//on supprime les arbres
if (selected_scene_node)
{
selected_scene_node->setVisible(false);
cpt ++;
}
}
// Dessin de la scène :
smgr->drawAll();
// Dessin de l'interface utilisateur :
gui_game->drawAll();
driver->endScene();
}
device->drop();
return 0;
}
/*is::ITriangleSelector* createTree(is::IAnimatedMesh *mesh, is::ISceneManager *smgr, EventReceiver receiver, iv::IVideoDriver *driver)
{
std::vector<iv::ITexture*> textures;
is::IAnimatedMeshSceneNode *node_arbre;
int i = 10;
int j = 10;
is::ITriangleSelector *selector;
is::IMetaTriangleSelector *
metaselector = smgr-> createMetaTriangleSelector();;
for (int k = 0 ; k < 15 ; k ++)
{
node_arbre = smgr->addAnimatedMeshSceneNode(mesh,nullptr,i+j+k);
node_arbre->setMaterialFlag(irr::video::EMF_LIGHTING, false);
node_arbre->setPosition (core::vector3df(i,k,j));
textures.push_back(driver->getTexture("data/tree.jpg"));
node_arbre->setMaterialTexture(0, textures[0]);
//node_arbre->setDebugDataVisible(is::EDS_BBOX | is::EDS_HALF_TRANSPARENCY);
receiver.set_node(node_arbre);
receiver.set_textures(textures);
// Création du triangle selector pour gérer la collision
selector = smgr->createTriangleSelector(node_arbre->getMesh(),node_arbre);
node_arbre ->setTriangleSelector (selector);
metaselector->addTriangleSelector(selector);
}
return metaselector;
}*/
//Create a moutain
is::ITriangleSelector* createMountain(int nbMountains, is::IAnimatedMeshSceneNode *node, is::IAnimatedMesh *mesh, is::ISceneManager *smgr, std::vector<iv::ITexture*> textures, EventReceiver receiver)
{
int Ni=100;
int Nj=100;
is::ITriangleSelector *selector;
is::IMetaTriangleSelector *metaselector = smgr-> createMetaTriangleSelector();
for(int i = 0; i<nbMountains; ++i)
{
int delta_max = 20;
int delta = delta_max;
int height = 1;
// Get a random position for the lowest left point of the mountain
int position_x = rand()%Ni;
int position_z = rand()%Nj;
while(delta>2)
{
for (int x=position_x; x<position_x+delta; ++x)
{
for(int z=position_z; z<position_z+delta; ++z)
{
selector = createColumn(x, z, height, node, mesh, smgr, textures, receiver);
metaselector->addTriangleSelector(selector);
}
}
position_x++;
position_z++;
height++;
delta-=2;
}
}
return metaselector;
}
// Given a position on the scene, add cubes to go to the given height
is::ITriangleSelector* createColumn(int position_x, int position_z, int height, is::IAnimatedMeshSceneNode *node, is::IAnimatedMesh *mesh, is::ISceneManager *smgr, std::vector<iv::ITexture*> textures, EventReceiver receiver)
{
is::ITriangleSelector *selector;
is::IMetaTriangleSelector *metaselector = smgr-> createMetaTriangleSelector();
for(int i=1; i<height; ++i)
{
node = smgr->addAnimatedMeshSceneNode(mesh, nullptr, position_x+i+position_z);
node->setMaterialFlag(irr::video::EMF_LIGHTING, false);
node->setPosition (core::vector3df(position_x, i, position_z));
node->setMaterialTexture(0, textures[0]);
receiver.set_node(node);
receiver.set_textures(textures);
selector = smgr->createTriangleSelector(node->getMesh(),node);
node ->setTriangleSelector (selector);
metaselector->addTriangleSelector(selector);
}
return metaselector;
}
<commit_msg>foret_rand<commit_after>#include <irrlicht.h>
#include "events.h"
#include "gui_game.h"
using namespace irr;
namespace ic = irr::core;
namespace is = irr::scene;
namespace iv = irr::video;
namespace ig = irr::gui;
is::ITriangleSelector* createTree(is::IAnimatedMesh *mesh, is::ISceneManager *smgr, EventReceiver receiver, iv::IVideoDriver *driver);
is::ITriangleSelector* createColumn(int position_x, int position_z, int height, is::IAnimatedMeshSceneNode *node, is::IAnimatedMesh *mesh, is::ISceneManager *smgr, std::vector<iv::ITexture*> textures, EventReceiver receiver);
is::ITriangleSelector* createMountain(int nbMountains, is::IAnimatedMeshSceneNode *node, is::IAnimatedMesh *mesh, is::ISceneManager *smgr, std::vector<iv::ITexture*> textures, EventReceiver receiver);
const int ID = 40;
int main()
{
// Le gestionnaire d'événements
EventReceiver receiver;
std::vector<iv::ITexture*> textures;
// Création de la fenêtre et du système de rendu.
IrrlichtDevice *device = createDevice(iv::EDT_OPENGL,
ic::dimension2d<u32>(640, 480),
16, false, false, false, &receiver);
is::ISceneManager *smgr = device->getSceneManager();
iv::IVideoDriver *driver = device->getVideoDriver();
ig::IGUIEnvironment *gui_game = device->getGUIEnvironment();
// Stockage des textures
textures.push_back(driver->getTexture("data/TXsQk.png"));
// Chargement du cube
is::IAnimatedMesh *mesh = smgr->getMesh("data/cube.obj");
//chargement du santaclaus
is::IAnimatedMesh *mesh_santaclaus = smgr->getMesh("data/Steve.obj");
//chargement du tree
is::IAnimatedMesh *mesh_tree = smgr->getMesh("data/lowpolytree.obj");
// Ajout de la scène
is::IAnimatedMeshSceneNode *node;
int Ni = 100;
int Nj = 100;
is::IMetaTriangleSelector *metaselector = smgr-> createMetaTriangleSelector();
for (int i = 0 ; i < Ni ; i ++)
{
for (int j = 0 ; j < Nj ; j ++)
{
node = smgr->addAnimatedMeshSceneNode(mesh,nullptr,i+j);
node->setMaterialFlag(irr::video::EMF_LIGHTING, false);
node->setPosition (core::vector3df(i,0,j));
textures.push_back(driver->getTexture("data/TXsQk.png"));
node->setMaterialTexture(0, textures[0]);
receiver.set_node(node);
receiver.set_textures(textures);
// Création du triangle selector pour gérer la collision
is::ITriangleSelector *selector = smgr->createTriangleSelector(node->getMesh(),node);
node ->setTriangleSelector (selector);
//meta selector permettant de stocker les selecteurs de tous mes cubes
metaselector->addTriangleSelector(selector);
}
}
//is::ITriangleSelector* selector1 = createTree(mesh, smgr,receiver,driver);
//metaselector->addTriangleSelector(selector1);
//Ajout de reliefs sur la scene
int nbMountains = 2;
is::ITriangleSelector* selector2 = createMountain(nbMountains, node, mesh, smgr, textures, receiver);
metaselector->addTriangleSelector(selector2);
// Ajout du cube à la scène
/*is::IAnimatedMeshSceneNode *node_personnage;
node_personnage = smgr->addAnimatedMeshSceneNode(mesh);
node_personnage->setPosition(core::vector3df(20, 10, 20));
textures.push_back(driver->getTexture("data/rouge.jpg"));
node_personnage->setMaterialTexture(0, textures.back());
node_personnage->setMaterialFlag(irr::video::EMF_LIGHTING, false);
receiver.set_node(node_personnage);
receiver.set_textures(textures);*/
//ajout tree (ou une forêt) à la scene
is::IAnimatedMeshSceneNode *node_tree;
int Nl = 7;
int Nk = 7;
int pos_x;
int pos_y;
for (int l=0; l<Nl; l++)
{
for (int k=0; k<Nk; k++)
{
pos_x = rand()%Nl + 8*l;
pos_y = rand()%Nk + 5*k;
node_tree = smgr->addAnimatedMeshSceneNode(mesh_tree,nullptr, l+k);
node_tree->setMaterialFlag(irr::video::EMF_LIGHTING, false);
node_tree->setPosition(core::vector3df(pos_x, 4.3,pos_y));//30+4*l, 4.3, 5+4*l));
node_tree->setScale(core::vector3df(1.5,1.5,1.5));
receiver.set_node(node_tree);
//selector sur l'arbre
is::ITriangleSelector *selector = smgr->createTriangleSelector(mesh_tree,node_tree);
node_tree->setTriangleSelector(selector);
selector->drop();
node_tree->setID(ID);
metaselector->addTriangleSelector(selector);
}
}
//ajout santaclaus à la scene
is::IAnimatedMeshSceneNode *node_santaclaus;
node_santaclaus = smgr->addAnimatedMeshSceneNode(mesh_santaclaus);
node_santaclaus->setMaterialFlag(irr::video::EMF_LIGHTING, false);
node_santaclaus->setPosition(core::vector3df(20,2,60)); //20, 2, 30));
textures.push_back(driver->getTexture("data/Santa.png"));
node_santaclaus->setMaterialTexture(0, textures.back());
node_santaclaus->setScale(core::vector3df(0.5,0.5,0.5));
receiver.set_node(node_santaclaus);
receiver.set_textures(textures);
receiver.set_gui(gui_game);
//Gestion collision
is::ISceneNodeAnimator *anim;
anim = smgr ->createCollisionResponseAnimator(metaselector, node_santaclaus,
ic::vector3df(1, 1, 1), //Rayon de la cam
ic::vector3df(0, -10, 0), //gravité
ic::vector3df(0, 0, 0)); // décalage du centre
node_santaclaus->addAnimator(anim);
//gestionnaire de collision "Selection"
is::ISceneCollisionManager *collision_manager = smgr->getSceneCollisionManager();
//caméra qui va suivre notre personnage
//son parent est donc le noeud qui definit le personnage
//deuxieme paramètre:position de la camera (look From)
//troisieme paramètre: look at (ici c'est la position du personnage) mise a jour dans event.cpp
is::ICameraSceneNode *camera = smgr->addCameraSceneNode(node_santaclaus, ic::vector3df(20,10,0), node_santaclaus->getPosition());
receiver.set_camera(camera);
// La barre de menu
gui_game::create_menu(gui_game);
while(device->run())
{
driver->beginScene(true, true, iv::SColor(0,50,100,255));
//Séléction de l'arbre à couper avec la souris
int mouse_x, mouse_y;
if (receiver.is_mouse_pressed(mouse_x, mouse_y))
{
ic::line3d<f32> ray;
ray = collision_manager->getRayFromScreenCoordinates(ic::position2d<s32>(mouse_x, mouse_y));
ic::vector3df intersection;
ic::triangle3df hit_triangle;
is::ISceneNode *selected_scene_node = collision_manager->getSceneNodeAndCollisionPointFromRay(ray,
intersection, // On récupère ici les coordonnées 3D de l'intersection
hit_triangle, // et le triangle intersecté
ID); // On ne veut que des noeuds avec cet identifiant
//on supprime les arbres
if (selected_scene_node)
{
selected_scene_node->setVisible(false);
}
}
// Dessin de la scène :
smgr->drawAll();
// Dessin de l'interface utilisateur :
gui_game->drawAll();
driver->endScene();
}
device->drop();
return 0;
}
/*is::ITriangleSelector* createTree(is::IAnimatedMesh *mesh, is::ISceneManager *smgr, EventReceiver receiver, iv::IVideoDriver *driver)
{
std::vector<iv::ITexture*> textures;
is::IAnimatedMeshSceneNode *node_arbre;
int i = 10;
int j = 10;
is::ITriangleSelector *selector;
is::IMetaTriangleSelector *
metaselector = smgr-> createMetaTriangleSelector();;
for (int k = 0 ; k < 15 ; k ++)
{
node_arbre = smgr->addAnimatedMeshSceneNode(mesh,nullptr,i+j+k);
node_arbre->setMaterialFlag(irr::video::EMF_LIGHTING, false);
node_arbre->setPosition (core::vector3df(i,k,j));
textures.push_back(driver->getTexture("data/tree.jpg"));
node_arbre->setMaterialTexture(0, textures[0]);
//node_arbre->setDebugDataVisible(is::EDS_BBOX | is::EDS_HALF_TRANSPARENCY);
receiver.set_node(node_arbre);
receiver.set_textures(textures);
// Création du triangle selector pour gérer la collision
selector = smgr->createTriangleSelector(node_arbre->getMesh(),node_arbre);
node_arbre ->setTriangleSelector (selector);
metaselector->addTriangleSelector(selector);
}
return metaselector;
}*/
//Create a moutain
is::ITriangleSelector* createMountain(int nbMountains, is::IAnimatedMeshSceneNode *node, is::IAnimatedMesh *mesh, is::ISceneManager *smgr, std::vector<iv::ITexture*> textures, EventReceiver receiver)
{
int Ni=100;
int Nj=100;
is::ITriangleSelector *selector;
is::IMetaTriangleSelector *metaselector = smgr-> createMetaTriangleSelector();
for(int i = 0; i<nbMountains; ++i)
{
int delta_max = 20;
int delta = delta_max;
int height = 1;
// Get a random position for the lowest left point of the mountain
int position_x = rand()%Ni;
int position_z = rand()%Nj;
while(delta>2)
{
for (int x=position_x; x<position_x+delta; ++x)
{
for(int z=position_z; z<position_z+delta; ++z)
{
selector = createColumn(x, z, height, node, mesh, smgr, textures, receiver);
metaselector->addTriangleSelector(selector);
}
}
position_x++;
position_z++;
height++;
delta-=2;
}
}
return metaselector;
}
// Given a position on the scene, add cubes to go to the given height
is::ITriangleSelector* createColumn(int position_x, int position_z, int height, is::IAnimatedMeshSceneNode *node, is::IAnimatedMesh *mesh, is::ISceneManager *smgr, std::vector<iv::ITexture*> textures, EventReceiver receiver)
{
is::ITriangleSelector *selector;
is::IMetaTriangleSelector *metaselector = smgr-> createMetaTriangleSelector();
for(int i=1; i<height; ++i)
{
node = smgr->addAnimatedMeshSceneNode(mesh, nullptr, position_x+i+position_z);
node->setMaterialFlag(irr::video::EMF_LIGHTING, false);
node->setPosition (core::vector3df(position_x, i, position_z));
node->setMaterialTexture(0, textures[0]);
receiver.set_node(node);
receiver.set_textures(textures);
selector = smgr->createTriangleSelector(node->getMesh(),node);
node ->setTriangleSelector (selector);
metaselector->addTriangleSelector(selector);
}
return metaselector;
}
<|endoftext|> |
<commit_before>//Author: Julian Yi
//Date Started: 14 July 2017, Friday.
//Purpose: This is a project to create a working chess engine and gui using C++.
//File: This is the main file.
#include <iostream>
#include <memory>
#include "board.h"
#include "pawn.h"
#include "knight.h"
#include "bishop.h"
#include "coord.h"
#include "BearLibTerminal.h"
#define sizeY 8
#define sizeX 8
int main()
{
board Chessboard;
board::Square **tile = new board::Square*[sizeY];
for (int index = 0; index < sizeY; ++index)
{
tile[index] = new board::Square[sizeX];
}
Chessboard.initializeBoard(tile);
auto testPawn = new Pawn();
testPawn->setPosition(coord{0, 3}, tile);
std::cout << testPawn->getPieceName() << " " << testPawn->getPosition().x << " " << testPawn->getPosition().y << std::endl;
coordList validMoves;
validMoves = testPawn->calculateMoves(coord{10, 10});
for (auto& move : validMoves) {
std::cout << "Can move to: " << move.x << " " << move.y << std::endl;
}
auto testKnight = new Knight();
testKnight->setPosition(coord{0, 3}, tile);
std::cout << "Knight at: " << testKnight->getPosition().x << " " << testKnight->getPosition().y << std::endl;
validMoves = testKnight->calculateMoves(coord{10, 10});
for (auto& move : validMoves) {
std::cout << "Can move to: " << move.x << " " << move.y << std::endl;
}
auto testBishop = new Bishop();
testBishop->setPosition(coord{2, 2}, tile);
std::cout << "Bishop at: " << testBishop->getPosition().x << " " << testBishop->getPosition().y << std::endl;
validMoves = testBishop->calculateMoves(coord{10, 10});
for (auto& move : validMoves) {
std::cout << "Can move to: " << move.x << " " << move.y << std::endl;
}
//Chessboard.placePiece("Pawn1", testPawn->getPosition().x, testPawn->getPosition().y, tile);
//Chessboard.placePiece("Knight1", testPawn->getPosition().x, testPawn->getPosition().y, tile);
std::cout << "pause here" << std::endl;
for (int index = 0; index < sizeY; ++index)
{
delete[] tile[index];
}
delete[] tile;
terminal_open();
// Printing text
terminal_print(1, 1, "Hello, world!");
terminal_refresh();
// Wait until user close the window
while (terminal_read() != TK_CLOSE);
terminal_close();
return 0;
}
<commit_msg>Added intro to the terminal gui and key press recognition.<commit_after>//Author: Julian Yi
//Date Started: 14 July 2017, Friday.
//Purpose: This is a project to create a working chess engine and gui using C++.
//File: This is the main file.
#include <iostream>
#include "board.h"
#include "pawn.h"
#include "knight.h"
#include "bishop.h"
#include "coord.h"
#include "BearLibTerminal.h"
int main()
{
board Chessboard;
// Do these need to be on the heap?
board::Square **tile = new board::Square*[board::sizeY];
for (int index = 0; index < board::sizeY; ++index)
{
tile[index] = new board::Square[board::sizeX];
}
Chessboard.initializeBoard(tile);
auto testPawn = new Pawn();
testPawn->setPosition(coord{0, 3}, tile);
std::cout << testPawn->getPieceName() << " " << testPawn->getPosition().x << " " << testPawn->getPosition().y << std::endl;
coordList validMoves;
validMoves = testPawn->calculateMoves(coord{10, 10});
for (auto& move : validMoves) {
std::cout << "Can move to: " << move.x << " " << move.y << std::endl;
}
auto testKnight = new Knight();
testKnight->setPosition(coord{0, 3}, tile);
std::cout << "Knight at: " << testKnight->getPosition().x << " " << testKnight->getPosition().y << std::endl;
validMoves = testKnight->calculateMoves(coord{10, 10});
for (auto& move : validMoves) {
std::cout << "Can move to: " << move.x << " " << move.y << std::endl;
}
auto testBishop = new Bishop();
testBishop->setPosition(coord{2, 2}, tile);
std::cout << "Bishop at: " << testBishop->getPosition().x << " " << testBishop->getPosition().y << std::endl;
validMoves = testBishop->calculateMoves(coord{10, 10});
for (auto& move : validMoves) {
std::cout << "Can move to: " << move.x << " " << move.y << std::endl;
}
//Chessboard.placePiece("Pawn1", testPawn->getPosition().x, testPawn->getPosition().y, tile);
//Chessboard.placePiece("Knight1", testPawn->getPosition().x, testPawn->getPosition().y, tile);
// Open the terminal. Since no terminal_set() method is called,
// the terminal will use default settings.
terminal_open();
// Print intro text.
terminal_print(1, 1, "Chess Engine");
terminal_print(4, 2, "by Julian Yi, Sean Brock, and Simon Kim");
terminal_print(1, 4, "Press Enter to start...");
terminal_refresh();
bool running = true;
while (running) {
// Check for input. termnial_read() is blocking, meaning the
// program will wait until it reads a key press.
auto key = terminal_read();
// Reset the terminal to blank state.
terminal_clear();
// Print instructions.
terminal_print(1, 1, "Press Enter to start...");
// Handle key presses.
switch (key) {
case TK_CLOSE:
running = false;
break;
case TK_ESCAPE:
running = false;
break;
case TK_ENTER:
terminal_print(1, 2, "Simon is king; Kylee is queen.");
break;
default:
terminal_print(1, 2, "The key pressed has no function.");
break;
}
// Commit the buffer and draw it.
terminal_refresh();
}
// We're done here.
terminal_close();
// Do we need to delete pointers if we are exiting?
/*
std::cout << "pause here" << std::endl;
for (int index = 0; index < board::sizeY; ++index)
{
delete[] tile[index];
}
delete[] tile;
*/
return 0;
}
<|endoftext|> |
<commit_before>#include <ROOT/RDataFrame.hxx>
#include <ROOT/RArrowDS.hxx>
#include <ROOT/TSeq.hxx>
#include <TROOT.h>
#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wshadow"
#endif
#include <arrow/builder.h>
#include <arrow/memory_pool.h>
#include <arrow/record_batch.h>
#include <arrow/table.h>
#include <arrow/test-util.h>
#if defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
#include <gtest/gtest.h>
#include <iostream>
using namespace ROOT;
using namespace ROOT::RDF;
using namespace arrow;
std::shared_ptr<Schema> exampleSchema()
{
return schema({field("Name", arrow::utf8()), field("Age", arrow::int64()), field("Height", arrow::float64()),
field("Married", arrow::boolean()), field("Babies", arrow::uint32())});
}
std::shared_ptr<Table> createTestTable()
{
auto schema_ = exampleSchema();
std::vector<bool> is_valid(6, true);
std::vector<std::string> names = {"Harry", "Bob,Bob", "\"Joe\"", "Tom", " John ", " Mary Ann "};
std::vector<int64_t> ages = {64, 50, 40, 30, 2, 0};
std::vector<double> heights = {180.0, 200.5, 1.7, 1.9, 1.0, 0.8};
std::vector<bool> marriageStatus = {true, true, false, true, false, false};
std::vector<unsigned int> babies = {1, 0, 2, 3, 4, 21};
std::shared_ptr<Array> arrays_[5];
arrow::ArrayFromVector<StringType, std::string>(names, &arrays_[0]);
arrow::ArrayFromVector<Int64Type, int64_t>(ages, &arrays_[1]);
arrow::ArrayFromVector<DoubleType, double>(heights, &arrays_[2]);
arrow::ArrayFromVector<BooleanType, bool>(marriageStatus, &arrays_[3]);
arrow::ArrayFromVector<UInt32Type, unsigned int>(babies, &arrays_[4]);
std::vector<std::shared_ptr<Column>> columns_ = {
std::make_shared<Column>(schema_->field(0), arrays_[0]), std::make_shared<Column>(schema_->field(1), arrays_[1]),
std::make_shared<Column>(schema_->field(2), arrays_[2]), std::make_shared<Column>(schema_->field(3), arrays_[3]),
std::make_shared<Column>(schema_->field(4), arrays_[4])};
auto table_ = Table::Make(schema_, columns_);
return table_;
}
TEST(RArrowDS, ColTypeNames)
{
RArrowDS tds(createTestTable(), {"Name", "Age", "Height", "Married", "Babies"});
tds.SetNSlots(1);
auto colNames = tds.GetColumnNames();
EXPECT_TRUE(tds.HasColumn("Name"));
EXPECT_TRUE(tds.HasColumn("Age"));
EXPECT_FALSE(tds.HasColumn("Address"));
ASSERT_EQ(colNames.size(), 5U);
EXPECT_STREQ("Height", colNames[2].c_str());
EXPECT_STREQ("Married", colNames[3].c_str());
EXPECT_STREQ("string", tds.GetTypeName("Name").c_str());
EXPECT_STREQ("Long64_t", tds.GetTypeName("Age").c_str());
EXPECT_STREQ("double", tds.GetTypeName("Height").c_str());
EXPECT_STREQ("bool", tds.GetTypeName("Married").c_str());
EXPECT_STREQ("UInt_t", tds.GetTypeName("Babies").c_str());
}
TEST(RArrowDS, EntryRanges)
{
RArrowDS tds(createTestTable(), {});
tds.SetNSlots(3U);
tds.Initialise();
// Still dividing in equal parts...
auto ranges = tds.GetEntryRanges();
ASSERT_EQ(3U, ranges.size());
EXPECT_EQ(0U, ranges[0].first);
EXPECT_EQ(2U, ranges[0].second);
EXPECT_EQ(2U, ranges[1].first);
EXPECT_EQ(4U, ranges[1].second);
EXPECT_EQ(4U, ranges[2].first);
EXPECT_EQ(6U, ranges[2].second);
}
TEST(RArrowDS, ColumnReaders)
{
RArrowDS tds(createTestTable(), {});
const auto nSlots = 3U;
tds.SetNSlots(nSlots);
auto valsAge = tds.GetColumnReaders<Long64_t>("Age");
auto valsBabies = tds.GetColumnReaders<unsigned int>("Babies");
tds.Initialise();
auto ranges = tds.GetEntryRanges();
auto slot = 0U;
std::vector<Long64_t> RefsAge = {64, 50, 40, 30, 2, 0};
std::vector<unsigned int> RefsBabies = {1, 0, 2, 3, 4, 21};
for (auto &&range : ranges) {
tds.InitSlot(slot, range.first);
ASSERT_LT(slot, valsAge.size());
for (auto i : ROOT::TSeq<int>(range.first, range.second)) {
tds.SetEntry(slot, i);
auto valAge = **valsAge[slot];
EXPECT_EQ(RefsAge[i], valAge);
auto valBabies = **valsBabies[slot];
EXPECT_EQ(RefsBabies[i], valBabies);
}
slot++;
}
}
TEST(RArrowDS, ColumnReadersString)
{
RArrowDS tds(createTestTable(), {});
const auto nSlots = 3U;
tds.SetNSlots(nSlots);
auto vals = tds.GetColumnReaders<std::string>("Name");
tds.Initialise();
auto ranges = tds.GetEntryRanges();
auto slot = 0U;
std::vector<std::string> names = {"Harry", "Bob,Bob", "\"Joe\"", "Tom", " John ", " Mary Ann "};
for (auto &&range : ranges) {
tds.InitSlot(slot, range.first);
ASSERT_LT(slot, vals.size());
for (auto i : ROOT::TSeqU(range.first, range.second)) {
tds.SetEntry(slot, i);
auto val = *((std::string *)*vals[slot]);
ASSERT_LT(i, names.size());
EXPECT_EQ(names[i], val);
}
slot++;
}
}
#ifndef NDEBUG
TEST(RArrowDS, SetNSlotsTwice)
{
auto theTest = []() {
RArrowDS tds(createTestTable(), {});
tds.SetNSlots(1);
tds.SetNSlots(1);
};
ASSERT_DEATH(theTest(), "Setting the number of slots even if the number of slots is different from zero.");
}
#endif
#ifdef R__B64
TEST(RArrowDS, FromARDF)
{
std::unique_ptr<RDataSource> tds(new RArrowDS(createTestTable(), {}));
ROOT::RDataFrame rdf(std::move(tds));
auto max = rdf.Max<double>("Height");
auto min = rdf.Min<double>("Height");
auto c = rdf.Count();
EXPECT_EQ(6U, *c);
EXPECT_DOUBLE_EQ(200.5, *max);
EXPECT_DOUBLE_EQ(0.8, *min);
}
TEST(RArrowDS, FromARDFWithJitting)
{
std::unique_ptr<RDataSource> tds(new RArrowDS(createTestTable(), {}));
ROOT::RDataFrame rdf(std::move(tds));
auto max = rdf.Filter("Age<40").Max("Age");
auto min = rdf.Define("Age2", "Age").Filter("Age2>30").Min("Age2");
EXPECT_EQ(30, *max);
EXPECT_EQ(40, *min);
}
// NOW MT!-------------
#ifdef R__USE_IMT
TEST(RArrowDS, DefineSlotCheckMT)
{
const auto nSlots = 4U;
ROOT::EnableImplicitMT(nSlots);
std::vector<unsigned int> ids(nSlots, 0u);
std::unique_ptr<RDataSource> tds(new RArrowDS(createTestTable(), {}));
ROOT::RDataFrame d(std::move(tds));
auto m = d.DefineSlot("x", [&](unsigned int slot) {
ids[slot] = 1u;
return 1;
}).Max("x");
EXPECT_EQ(1, *m); // just in case
const auto nUsedSlots = std::accumulate(ids.begin(), ids.end(), 0u);
EXPECT_GT(nUsedSlots, 0u);
EXPECT_LE(nUsedSlots, nSlots);
}
TEST(RArrowDS, FromARDFMT)
{
std::unique_ptr<RDataSource> tds(new RArrowDS(createTestTable(), {}));
ROOT::RDataFrame tdf(std::move(tds));
auto max = tdf.Max<double>("Height");
auto min = tdf.Min<double>("Height");
auto c = tdf.Count();
EXPECT_EQ(6U, *c);
EXPECT_DOUBLE_EQ(200.5, *max);
EXPECT_DOUBLE_EQ(.8, *min);
}
TEST(RArrowDS, FromARDFWithJittingMT)
{
std::unique_ptr<RDataSource> tds(new RArrowDS(createTestTable(), {}));
ROOT::RDataFrame tdf(std::move(tds));
auto max = tdf.Filter("Age<40").Max("Age");
auto min = tdf.Define("Age2", "Age").Filter("Age2>30").Min("Age2");
EXPECT_EQ(30, *max);
EXPECT_EQ(40, *min);
}
#endif // R__USE_IMT
#endif // R__B64
<commit_msg>Latest binary of Apache Arrow actually has test-utils.h in arrow/compute/<commit_after>#include <ROOT/RDataFrame.hxx>
#include <ROOT/RArrowDS.hxx>
#include <ROOT/TSeq.hxx>
#include <TROOT.h>
#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wshadow"
#endif
#include <arrow/builder.h>
#include <arrow/memory_pool.h>
#include <arrow/record_batch.h>
#include <arrow/table.h>
#include <arrow/compute/test-util.h>
#if defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
#include <gtest/gtest.h>
#include <iostream>
using namespace ROOT;
using namespace ROOT::RDF;
using namespace arrow;
std::shared_ptr<Schema> exampleSchema()
{
return schema({field("Name", arrow::utf8()), field("Age", arrow::int64()), field("Height", arrow::float64()),
field("Married", arrow::boolean()), field("Babies", arrow::uint32())});
}
std::shared_ptr<Table> createTestTable()
{
auto schema_ = exampleSchema();
std::vector<bool> is_valid(6, true);
std::vector<std::string> names = {"Harry", "Bob,Bob", "\"Joe\"", "Tom", " John ", " Mary Ann "};
std::vector<int64_t> ages = {64, 50, 40, 30, 2, 0};
std::vector<double> heights = {180.0, 200.5, 1.7, 1.9, 1.0, 0.8};
std::vector<bool> marriageStatus = {true, true, false, true, false, false};
std::vector<unsigned int> babies = {1, 0, 2, 3, 4, 21};
std::shared_ptr<Array> arrays_[5];
arrow::ArrayFromVector<StringType, std::string>(names, &arrays_[0]);
arrow::ArrayFromVector<Int64Type, int64_t>(ages, &arrays_[1]);
arrow::ArrayFromVector<DoubleType, double>(heights, &arrays_[2]);
arrow::ArrayFromVector<BooleanType, bool>(marriageStatus, &arrays_[3]);
arrow::ArrayFromVector<UInt32Type, unsigned int>(babies, &arrays_[4]);
std::vector<std::shared_ptr<Column>> columns_ = {
std::make_shared<Column>(schema_->field(0), arrays_[0]), std::make_shared<Column>(schema_->field(1), arrays_[1]),
std::make_shared<Column>(schema_->field(2), arrays_[2]), std::make_shared<Column>(schema_->field(3), arrays_[3]),
std::make_shared<Column>(schema_->field(4), arrays_[4])};
auto table_ = Table::Make(schema_, columns_);
return table_;
}
TEST(RArrowDS, ColTypeNames)
{
RArrowDS tds(createTestTable(), {"Name", "Age", "Height", "Married", "Babies"});
tds.SetNSlots(1);
auto colNames = tds.GetColumnNames();
EXPECT_TRUE(tds.HasColumn("Name"));
EXPECT_TRUE(tds.HasColumn("Age"));
EXPECT_FALSE(tds.HasColumn("Address"));
ASSERT_EQ(colNames.size(), 5U);
EXPECT_STREQ("Height", colNames[2].c_str());
EXPECT_STREQ("Married", colNames[3].c_str());
EXPECT_STREQ("string", tds.GetTypeName("Name").c_str());
EXPECT_STREQ("Long64_t", tds.GetTypeName("Age").c_str());
EXPECT_STREQ("double", tds.GetTypeName("Height").c_str());
EXPECT_STREQ("bool", tds.GetTypeName("Married").c_str());
EXPECT_STREQ("UInt_t", tds.GetTypeName("Babies").c_str());
}
TEST(RArrowDS, EntryRanges)
{
RArrowDS tds(createTestTable(), {});
tds.SetNSlots(3U);
tds.Initialise();
// Still dividing in equal parts...
auto ranges = tds.GetEntryRanges();
ASSERT_EQ(3U, ranges.size());
EXPECT_EQ(0U, ranges[0].first);
EXPECT_EQ(2U, ranges[0].second);
EXPECT_EQ(2U, ranges[1].first);
EXPECT_EQ(4U, ranges[1].second);
EXPECT_EQ(4U, ranges[2].first);
EXPECT_EQ(6U, ranges[2].second);
}
TEST(RArrowDS, ColumnReaders)
{
RArrowDS tds(createTestTable(), {});
const auto nSlots = 3U;
tds.SetNSlots(nSlots);
auto valsAge = tds.GetColumnReaders<Long64_t>("Age");
auto valsBabies = tds.GetColumnReaders<unsigned int>("Babies");
tds.Initialise();
auto ranges = tds.GetEntryRanges();
auto slot = 0U;
std::vector<Long64_t> RefsAge = {64, 50, 40, 30, 2, 0};
std::vector<unsigned int> RefsBabies = {1, 0, 2, 3, 4, 21};
for (auto &&range : ranges) {
tds.InitSlot(slot, range.first);
ASSERT_LT(slot, valsAge.size());
for (auto i : ROOT::TSeq<int>(range.first, range.second)) {
tds.SetEntry(slot, i);
auto valAge = **valsAge[slot];
EXPECT_EQ(RefsAge[i], valAge);
auto valBabies = **valsBabies[slot];
EXPECT_EQ(RefsBabies[i], valBabies);
}
slot++;
}
}
TEST(RArrowDS, ColumnReadersString)
{
RArrowDS tds(createTestTable(), {});
const auto nSlots = 3U;
tds.SetNSlots(nSlots);
auto vals = tds.GetColumnReaders<std::string>("Name");
tds.Initialise();
auto ranges = tds.GetEntryRanges();
auto slot = 0U;
std::vector<std::string> names = {"Harry", "Bob,Bob", "\"Joe\"", "Tom", " John ", " Mary Ann "};
for (auto &&range : ranges) {
tds.InitSlot(slot, range.first);
ASSERT_LT(slot, vals.size());
for (auto i : ROOT::TSeqU(range.first, range.second)) {
tds.SetEntry(slot, i);
auto val = *((std::string *)*vals[slot]);
ASSERT_LT(i, names.size());
EXPECT_EQ(names[i], val);
}
slot++;
}
}
#ifndef NDEBUG
TEST(RArrowDS, SetNSlotsTwice)
{
auto theTest = []() {
RArrowDS tds(createTestTable(), {});
tds.SetNSlots(1);
tds.SetNSlots(1);
};
ASSERT_DEATH(theTest(), "Setting the number of slots even if the number of slots is different from zero.");
}
#endif
#ifdef R__B64
TEST(RArrowDS, FromARDF)
{
std::unique_ptr<RDataSource> tds(new RArrowDS(createTestTable(), {}));
ROOT::RDataFrame rdf(std::move(tds));
auto max = rdf.Max<double>("Height");
auto min = rdf.Min<double>("Height");
auto c = rdf.Count();
EXPECT_EQ(6U, *c);
EXPECT_DOUBLE_EQ(200.5, *max);
EXPECT_DOUBLE_EQ(0.8, *min);
}
TEST(RArrowDS, FromARDFWithJitting)
{
std::unique_ptr<RDataSource> tds(new RArrowDS(createTestTable(), {}));
ROOT::RDataFrame rdf(std::move(tds));
auto max = rdf.Filter("Age<40").Max("Age");
auto min = rdf.Define("Age2", "Age").Filter("Age2>30").Min("Age2");
EXPECT_EQ(30, *max);
EXPECT_EQ(40, *min);
}
// NOW MT!-------------
#ifdef R__USE_IMT
TEST(RArrowDS, DefineSlotCheckMT)
{
const auto nSlots = 4U;
ROOT::EnableImplicitMT(nSlots);
std::vector<unsigned int> ids(nSlots, 0u);
std::unique_ptr<RDataSource> tds(new RArrowDS(createTestTable(), {}));
ROOT::RDataFrame d(std::move(tds));
auto m = d.DefineSlot("x", [&](unsigned int slot) {
ids[slot] = 1u;
return 1;
}).Max("x");
EXPECT_EQ(1, *m); // just in case
const auto nUsedSlots = std::accumulate(ids.begin(), ids.end(), 0u);
EXPECT_GT(nUsedSlots, 0u);
EXPECT_LE(nUsedSlots, nSlots);
}
TEST(RArrowDS, FromARDFMT)
{
std::unique_ptr<RDataSource> tds(new RArrowDS(createTestTable(), {}));
ROOT::RDataFrame tdf(std::move(tds));
auto max = tdf.Max<double>("Height");
auto min = tdf.Min<double>("Height");
auto c = tdf.Count();
EXPECT_EQ(6U, *c);
EXPECT_DOUBLE_EQ(200.5, *max);
EXPECT_DOUBLE_EQ(.8, *min);
}
TEST(RArrowDS, FromARDFWithJittingMT)
{
std::unique_ptr<RDataSource> tds(new RArrowDS(createTestTable(), {}));
ROOT::RDataFrame tdf(std::move(tds));
auto max = tdf.Filter("Age<40").Max("Age");
auto min = tdf.Define("Age2", "Age").Filter("Age2>30").Min("Age2");
EXPECT_EQ(30, *max);
EXPECT_EQ(40, *min);
}
#endif // R__USE_IMT
#endif // R__B64
<|endoftext|> |
<commit_before>// @(#)root/treeplayer:$Id$
// Author: Axel Naumann, 2011-09-28
/*************************************************************************
* Copyright (C) 1995-2011, Rene Brun and Fons Rademakers and al. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "TTreeReaderValue.h"
#include "TTreeReader.h"
#include "TBranchClones.h"
#include "TBranchElement.h"
#include "TBranchRef.h"
#include "TBranchSTL.h"
#include "TBranchProxyDirector.h"
#include "TLeaf.h"
#include "TTreeProxyGenerator.h"
#include "TTreeReaderValue.h"
#include "TRegexp.h"
#include "TStreamerInfo.h"
#include "TStreamerElement.h"
#include "TNtuple.h"
////////////////////////////////////////////////////////////////////////////////
// //
// TTreeReaderValue //
// //
// Extracts data from a TTree. //
// //
// //
// //
// //
// //
// //
// //
// //
// //
////////////////////////////////////////////////////////////////////////////////
ClassImp(TTreeReaderValueBase)
//______________________________________________________________________________
ROOT::TTreeReaderValueBase::TTreeReaderValueBase(TTreeReader* reader /*= 0*/,
const char* branchname /*= 0*/,
TDictionary* dict /*= 0*/):
fTreeReader(reader),
fBranchName(branchname),
fDict(dict),
fProxy(0),
fSetupStatus(kSetupNotSetup),
fReadStatus(kReadNothingYet),
fLeaf(NULL),
fTreeLastOffset(-1)
{
// Construct a tree value reader and register it with the reader object.
if (fTreeReader) fTreeReader->RegisterValueReader(this);
}
//______________________________________________________________________________
ROOT::TTreeReaderValueBase::~TTreeReaderValueBase()
{
// Unregister from tree reader, cleanup.
if (fTreeReader) fTreeReader->DeregisterValueReader(this);
}
//______________________________________________________________________________
ROOT::TTreeReaderValueBase::EReadStatus
ROOT::TTreeReaderValueBase::ProxyRead() {
if (!fProxy) return kReadNothingYet;
if (fProxy->Read()) {
fReadStatus = kReadSuccess;
} else {
fReadStatus = kReadError;
}
return fReadStatus;
}
//______________________________________________________________________________
TLeaf* ROOT::TTreeReaderValueBase::GetLeaf() {
if (fLeafName.Length() > 0){
Long64_t newChainOffset = fTreeReader->GetTree()->GetChainOffset();
if (newChainOffset != fTreeLastOffset){
fTreeLastOffset = newChainOffset;
fLeaf = fTreeReader->GetTree()->GetBranch(fBranchName)->GetLeaf(fLeafName);
}
return fLeaf;
}
else {
Error("GetLeaf()", "We are not reading a leaf");
return 0;
}
}
//______________________________________________________________________________
void* ROOT::TTreeReaderValueBase::GetAddress() {
if (ProxyRead() != kReadSuccess) return 0;
if (fLeafName.Length() > 0){
Long64_t newChainOffset = fTreeReader->GetTree()->GetChainOffset();
if (newChainOffset != fTreeLastOffset){
fTreeLastOffset = newChainOffset;
fLeaf = fTreeReader->GetTree()->GetBranch(fBranchName)->GetLeaf(fLeafName);
}
return fLeaf->GetValuePointer();
}
return fProxy ? (Byte_t*)fProxy->GetWhere() : 0;
}
//______________________________________________________________________________
void ROOT::TTreeReaderValueBase::CreateProxy() {
// Create the proxy object for our branch.
if (fProxy) {
return;
}
if (!fTreeReader) {
Error("CreateProxy()", "TTreeReader object not set / available for branch %s!",
fBranchName.Data());
return;
}
if (!fDict) {
TBranch* br = fTreeReader->GetTree()->GetBranch(fBranchName);
const char* brDataType = "{UNDETERMINED}";
if (br) {
TDictionary* brDictUnused = 0;
brDataType = GetBranchDataType(br, brDictUnused);
}
Error("CreateProxy()", "The template argument type T of %s accessing branch %s (which contains data of type %s) is not known to ROOT. You will need to create a dictionary for it.",
IsA()->GetName() ? IsA()->GetName() : "?", fBranchName.Data(), brDataType);
return;
}
// Search for the branchname, determine what it contains, and wire the
// TBranchProxy representing it to us so we can access its data.
ROOT::TNamedBranchProxy* namedProxy
= (ROOT::TNamedBranchProxy*)fTreeReader->FindObject(fBranchName);
if (namedProxy && namedProxy->GetDict() == fDict) {
fProxy = namedProxy->GetProxy();
return;
}
TBranch* branch = fTreeReader->GetTree()->GetBranch(fBranchName);
TLeaf *myLeaf = NULL;
TDictionary* branchActualType = 0;
if (!branch) {
if (fBranchName.Contains(".")){
TRegexp leafNameExpression ("\\.[a-zA-Z0-9]+$");
TString leafName (fBranchName(leafNameExpression));
TString branchName = fBranchName(0, fBranchName.Length() - leafName.Length());
branch = fTreeReader->GetTree()->GetBranch(branchName);
if (!branch){
Error("CreateProxy()", "The tree does not have a branch called %s. You could check with TTree::Print() for available branches.", fBranchName.Data());
fProxy = 0;
return;
}
else {
myLeaf = branch->GetLeaf(TString(leafName(1, leafName.Length())));
if (!myLeaf){
Error("CreateProxy()", "The tree does not have a branch, nor a sub-branch called %s. You could check with TTree::Print() for available branches.", fBranchName.Data());
}
else {
TDictionary *tempDict = TDictionary::GetDictionary(myLeaf->GetTypeName());
if (tempDict && tempDict->IsA() == TDataType::Class() && TDictionary::GetDictionary(((TDataType*)tempDict)->GetTypeName()) == fDict){
//fLeafOffset = myLeaf->GetOffset() / 4;
branchActualType = fDict;
fLeaf = myLeaf;
fBranchName = branchName;
fLeafName = leafName(1, leafName.Length());
}
else {
Error("CreateProxy()", "Leaf of type %s cannot be read by TTreeReaderValue<%s>.", myLeaf->GetTypeName(), fDict->GetName());
}
}
}
}
else {
Error("CreateProxy()", "The tree does not have a branch called %s. You could check with TTree::Print() for available branches.", fBranchName.Data());
fProxy = 0;
return;
}
}
if (!myLeaf){
const char* branchActualTypeName = GetBranchDataType(branch, branchActualType);
if (!branchActualType) {
Error("CreateProxy()", "The branch %s contains data of type %s, which does not have a dictionary.",
fBranchName.Data(), branchActualTypeName ? branchActualTypeName : "{UNDETERMINED TYPE}");
fProxy = 0;
return;
}
if (fDict != branchActualType) {
Error("CreateProxy()", "The branch %s contains data of type %s. It cannot be accessed by a TTreeReaderValue<%s>",
fBranchName.Data(), branchActualType->GetName(), fDict->GetName());
return;
}
}
// Update named proxy's dictionary
if (namedProxy && !namedProxy->GetDict()) {
namedProxy->SetDict(fDict);
fProxy = namedProxy->GetProxy();
return;
}
// Search for the branchname, determine what it contains, and wire the
// TBranchProxy representing it to us so we can access its data.
// A proxy for branch must not have been created before (i.e. check
// fProxies before calling this function!)
TString membername;
bool isTopLevel = branch->GetMother() == branch;
if (!isTopLevel) {
membername = strrchr(branch->GetName(), '.');
if (membername.IsNull()) {
membername = branch->GetName();
}
}
namedProxy = new ROOT::TNamedBranchProxy(fTreeReader->fDirector, branch, membername);
fTreeReader->GetProxies()->Add(namedProxy);
fProxy = namedProxy->GetProxy();
}
//______________________________________________________________________________
const char* ROOT::TTreeReaderValueBase::GetBranchDataType(TBranch* branch,
TDictionary* &dict) const
{
// Retrieve the type of data stored by branch; put its dictionary into
// dict, return its type name. If no dictionary is available, at least
// its type name should be returned.
dict = 0;
if (branch->IsA() == TBranchElement::Class()) {
TBranchElement* brElement = (TBranchElement*)branch;
if (brElement->GetType() == TBranchElement::kSTLNode ||
brElement->GetType() == TBranchElement::kLeafNode ||
brElement->GetType() == TBranchElement::kObjectNode) {
TStreamerInfo *streamerInfo = brElement->GetInfo();
Int_t id = brElement->GetID();
if (id >= 0){
TStreamerElement *element = (TStreamerElement*)streamerInfo->GetElements()->At(id);
if (element->IsA() == TStreamerSTL::Class()){
TStreamerSTL *myStl = (TStreamerSTL*)element;
dict = myStl->GetClass();
return 0;
}
}
if (brElement->GetTypeName()) dict = TDictionary::GetDictionary(brElement->GetTypeName());
if (dict && dict->IsA() == TDataType::Class()){
dict = TDictionary::GetDictionary(((TDataType*)dict)->GetTypeName());
if (dict != fDict){
dict = TClass::GetClass(brElement->GetTypeName());
}
if (dict != fDict){
dict = brElement->GetCurrentClass();
}
}
else if (!dict) {
dict = brElement->GetCurrentClass();
}
return brElement->GetTypeName();
} else if (brElement->GetType() == TBranchElement::kClonesNode) {
dict = TClonesArray::Class();
return "TClonesArray";
} else if (brElement->GetType() == 31
|| brElement->GetType() == 41) {
// it's a member, extract from GetClass()'s streamer info
Error("GetBranchDataType()", "Must use TTreeReaderValueArray to access a member of an object that is stored in a collection.");
}
else {
Error("GetBranchDataType()", "Unknown type and class combination: %i, %s", brElement->GetType(), brElement->GetClassName());
}
return 0;
} else if (branch->IsA() == TBranch::Class()
|| branch->IsA() == TBranchObject::Class()
|| branch->IsA() == TBranchSTL::Class()) {
if (branch->GetTree()->IsA() == TNtuple::Class()){
dict = TDataType::GetDataType(kFloat_t);
return dict->GetName();
}
const char* dataTypeName = branch->GetClassName();
if ((!dataTypeName || !dataTypeName[0])
&& branch->IsA() == TBranch::Class()) {
// leaflist. Can't represent.
Error("GetBranchDataType()", "The branch %s was created using a leaf list and cannot be represented as a C++ type. Please access one of its siblings using a TTreeReaderValueArray:", branch->GetName());
TIter iLeaves(branch->GetListOfLeaves());
TLeaf* leaf = 0;
while ((leaf = (TLeaf*) iLeaves())) {
Error("GetBranchDataType()", " %s.%s", branch->GetName(), leaf->GetName());
}
return 0;
}
if (dataTypeName) dict = TDictionary::GetDictionary(dataTypeName);
return dataTypeName;
} else if (branch->IsA() == TBranchClones::Class()) {
dict = TClonesArray::Class();
return "TClonesArray";
} else if (branch->IsA() == TBranchRef::Class()) {
// Can't represent.
Error("GetBranchDataType()", "The branch %s is a TBranchRef and cannot be represented as a C++ type.", branch->GetName());
return 0;
} else {
Error("GetBranchDataType()", "The branch %s is of type %s - something that is not handled yet.", branch->GetName(), branch->IsA()->GetName());
return 0;
}
return 0;
}
<commit_msg>Fixes for coverity issues 51895, 51894 and 51893<commit_after>// @(#)root/treeplayer:$Id$
// Author: Axel Naumann, 2011-09-28
/*************************************************************************
* Copyright (C) 1995-2011, Rene Brun and Fons Rademakers and al. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "TTreeReaderValue.h"
#include "TTreeReader.h"
#include "TBranchClones.h"
#include "TBranchElement.h"
#include "TBranchRef.h"
#include "TBranchSTL.h"
#include "TBranchProxyDirector.h"
#include "TLeaf.h"
#include "TTreeProxyGenerator.h"
#include "TTreeReaderValue.h"
#include "TRegexp.h"
#include "TStreamerInfo.h"
#include "TStreamerElement.h"
#include "TNtuple.h"
////////////////////////////////////////////////////////////////////////////////
// //
// TTreeReaderValue //
// //
// Extracts data from a TTree. //
// //
// //
// //
// //
// //
// //
// //
// //
// //
////////////////////////////////////////////////////////////////////////////////
ClassImp(TTreeReaderValueBase)
//______________________________________________________________________________
ROOT::TTreeReaderValueBase::TTreeReaderValueBase(TTreeReader* reader /*= 0*/,
const char* branchname /*= 0*/,
TDictionary* dict /*= 0*/):
fTreeReader(reader),
fBranchName(branchname),
fDict(dict),
fProxy(0),
fSetupStatus(kSetupNotSetup),
fReadStatus(kReadNothingYet),
fLeaf(NULL),
fTreeLastOffset(-1)
{
// Construct a tree value reader and register it with the reader object.
if (fTreeReader) fTreeReader->RegisterValueReader(this);
}
//______________________________________________________________________________
ROOT::TTreeReaderValueBase::~TTreeReaderValueBase()
{
// Unregister from tree reader, cleanup.
if (fTreeReader) fTreeReader->DeregisterValueReader(this);
}
//______________________________________________________________________________
ROOT::TTreeReaderValueBase::EReadStatus
ROOT::TTreeReaderValueBase::ProxyRead() {
if (!fProxy) return kReadNothingYet;
if (fProxy->Read()) {
fReadStatus = kReadSuccess;
} else {
fReadStatus = kReadError;
}
return fReadStatus;
}
//______________________________________________________________________________
TLeaf* ROOT::TTreeReaderValueBase::GetLeaf() {
if (fLeafName.Length() > 0){
Long64_t newChainOffset = fTreeReader->GetTree()->GetChainOffset();
if (newChainOffset != fTreeLastOffset){
fTreeLastOffset = newChainOffset;
TTree *myTree = fTreeReader->GetTree();
if (!myTree) {
fReadStatus = kReadError;
Error("GetLeaf()", "Unable to get the tree from the TTreeReader");
return 0;
}
TBranch *myBranch = myTree->GetBranch(fBranchName);
if (!myBranch) {
fReadStatus = kReadError;
Error("GetLeaf()", "Unable to get the branch from the tree");
return 0;
}
fLeaf = myBranch->GetLeaf(fLeafName);
}
return fLeaf;
}
else {
Error("GetLeaf()", "We are not reading a leaf");
return 0;
}
}
//______________________________________________________________________________
void* ROOT::TTreeReaderValueBase::GetAddress() {
if (ProxyRead() != kReadSuccess) return 0;
if (fLeafName.Length() > 0){
if (GetLeaf()){
return fLeaf->GetValuePointer();
}
else {
fReadStatus = kReadError;
Error("GetAddress()", "Unable to get the leaf");
return 0;
}
}
return fProxy ? (Byte_t*)fProxy->GetWhere() : 0;
}
//______________________________________________________________________________
void ROOT::TTreeReaderValueBase::CreateProxy() {
// Create the proxy object for our branch.
if (fProxy) {
return;
}
if (!fTreeReader) {
Error("CreateProxy()", "TTreeReader object not set / available for branch %s!",
fBranchName.Data());
return;
}
if (!fDict) {
TBranch* br = fTreeReader->GetTree()->GetBranch(fBranchName);
const char* brDataType = "{UNDETERMINED}";
if (br) {
TDictionary* brDictUnused = 0;
brDataType = GetBranchDataType(br, brDictUnused);
}
Error("CreateProxy()", "The template argument type T of %s accessing branch %s (which contains data of type %s) is not known to ROOT. You will need to create a dictionary for it.",
IsA()->GetName() ? IsA()->GetName() : "?", fBranchName.Data(), brDataType);
return;
}
// Search for the branchname, determine what it contains, and wire the
// TBranchProxy representing it to us so we can access its data.
ROOT::TNamedBranchProxy* namedProxy
= (ROOT::TNamedBranchProxy*)fTreeReader->FindObject(fBranchName);
if (namedProxy && namedProxy->GetDict() == fDict) {
fProxy = namedProxy->GetProxy();
return;
}
TBranch* branch = fTreeReader->GetTree()->GetBranch(fBranchName);
TLeaf *myLeaf = NULL;
TDictionary* branchActualType = 0;
if (!branch) {
if (fBranchName.Contains(".")){
TRegexp leafNameExpression ("\\.[a-zA-Z0-9]+$");
TString leafName (fBranchName(leafNameExpression));
TString branchName = fBranchName(0, fBranchName.Length() - leafName.Length());
branch = fTreeReader->GetTree()->GetBranch(branchName);
if (!branch){
Error("CreateProxy()", "The tree does not have a branch called %s. You could check with TTree::Print() for available branches.", fBranchName.Data());
fProxy = 0;
return;
}
else {
myLeaf = branch->GetLeaf(TString(leafName(1, leafName.Length())));
if (!myLeaf){
Error("CreateProxy()", "The tree does not have a branch, nor a sub-branch called %s. You could check with TTree::Print() for available branches.", fBranchName.Data());
}
else {
TDictionary *tempDict = TDictionary::GetDictionary(myLeaf->GetTypeName());
if (tempDict && tempDict->IsA() == TDataType::Class() && TDictionary::GetDictionary(((TDataType*)tempDict)->GetTypeName()) == fDict){
//fLeafOffset = myLeaf->GetOffset() / 4;
branchActualType = fDict;
fLeaf = myLeaf;
fBranchName = branchName;
fLeafName = leafName(1, leafName.Length());
}
else {
Error("CreateProxy()", "Leaf of type %s cannot be read by TTreeReaderValue<%s>.", myLeaf->GetTypeName(), fDict->GetName());
}
}
}
}
else {
Error("CreateProxy()", "The tree does not have a branch called %s. You could check with TTree::Print() for available branches.", fBranchName.Data());
fProxy = 0;
return;
}
}
if (!myLeaf){
const char* branchActualTypeName = GetBranchDataType(branch, branchActualType);
if (!branchActualType) {
Error("CreateProxy()", "The branch %s contains data of type %s, which does not have a dictionary.",
fBranchName.Data(), branchActualTypeName ? branchActualTypeName : "{UNDETERMINED TYPE}");
fProxy = 0;
return;
}
if (fDict != branchActualType) {
Error("CreateProxy()", "The branch %s contains data of type %s. It cannot be accessed by a TTreeReaderValue<%s>",
fBranchName.Data(), branchActualType->GetName(), fDict->GetName());
return;
}
}
// Update named proxy's dictionary
if (namedProxy && !namedProxy->GetDict()) {
namedProxy->SetDict(fDict);
fProxy = namedProxy->GetProxy();
return;
}
// Search for the branchname, determine what it contains, and wire the
// TBranchProxy representing it to us so we can access its data.
// A proxy for branch must not have been created before (i.e. check
// fProxies before calling this function!)
TString membername;
bool isTopLevel = branch->GetMother() == branch;
if (!isTopLevel) {
membername = strrchr(branch->GetName(), '.');
if (membername.IsNull()) {
membername = branch->GetName();
}
}
namedProxy = new ROOT::TNamedBranchProxy(fTreeReader->fDirector, branch, membername);
fTreeReader->GetProxies()->Add(namedProxy);
fProxy = namedProxy->GetProxy();
}
//______________________________________________________________________________
const char* ROOT::TTreeReaderValueBase::GetBranchDataType(TBranch* branch,
TDictionary* &dict) const
{
// Retrieve the type of data stored by branch; put its dictionary into
// dict, return its type name. If no dictionary is available, at least
// its type name should be returned.
dict = 0;
if (branch->IsA() == TBranchElement::Class()) {
TBranchElement* brElement = (TBranchElement*)branch;
if (brElement->GetType() == TBranchElement::kSTLNode ||
brElement->GetType() == TBranchElement::kLeafNode ||
brElement->GetType() == TBranchElement::kObjectNode) {
TStreamerInfo *streamerInfo = brElement->GetInfo();
Int_t id = brElement->GetID();
if (id >= 0){
TStreamerElement *element = (TStreamerElement*)streamerInfo->GetElements()->At(id);
if (element->IsA() == TStreamerSTL::Class()){
TStreamerSTL *myStl = (TStreamerSTL*)element;
dict = myStl->GetClass();
return 0;
}
}
if (brElement->GetTypeName()) dict = TDictionary::GetDictionary(brElement->GetTypeName());
if (dict && dict->IsA() == TDataType::Class()){
dict = TDictionary::GetDictionary(((TDataType*)dict)->GetTypeName());
if (dict != fDict){
dict = TClass::GetClass(brElement->GetTypeName());
}
if (dict != fDict){
dict = brElement->GetCurrentClass();
}
}
else if (!dict) {
dict = brElement->GetCurrentClass();
}
return brElement->GetTypeName();
} else if (brElement->GetType() == TBranchElement::kClonesNode) {
dict = TClonesArray::Class();
return "TClonesArray";
} else if (brElement->GetType() == 31
|| brElement->GetType() == 41) {
// it's a member, extract from GetClass()'s streamer info
Error("GetBranchDataType()", "Must use TTreeReaderValueArray to access a member of an object that is stored in a collection.");
}
else {
Error("GetBranchDataType()", "Unknown type and class combination: %i, %s", brElement->GetType(), brElement->GetClassName());
}
return 0;
} else if (branch->IsA() == TBranch::Class()
|| branch->IsA() == TBranchObject::Class()
|| branch->IsA() == TBranchSTL::Class()) {
if (branch->GetTree()->IsA() == TNtuple::Class()){
dict = TDataType::GetDataType(kFloat_t);
return dict->GetName();
}
const char* dataTypeName = branch->GetClassName();
if ((!dataTypeName || !dataTypeName[0])
&& branch->IsA() == TBranch::Class()) {
// leaflist. Can't represent.
Error("GetBranchDataType()", "The branch %s was created using a leaf list and cannot be represented as a C++ type. Please access one of its siblings using a TTreeReaderValueArray:", branch->GetName());
TIter iLeaves(branch->GetListOfLeaves());
TLeaf* leaf = 0;
while ((leaf = (TLeaf*) iLeaves())) {
Error("GetBranchDataType()", " %s.%s", branch->GetName(), leaf->GetName());
}
return 0;
}
if (dataTypeName) dict = TDictionary::GetDictionary(dataTypeName);
return dataTypeName;
} else if (branch->IsA() == TBranchClones::Class()) {
dict = TClonesArray::Class();
return "TClonesArray";
} else if (branch->IsA() == TBranchRef::Class()) {
// Can't represent.
Error("GetBranchDataType()", "The branch %s is a TBranchRef and cannot be represented as a C++ type.", branch->GetName());
return 0;
} else {
Error("GetBranchDataType()", "The branch %s is of type %s - something that is not handled yet.", branch->GetName(), branch->IsA()->GetName());
return 0;
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012 The Backplane Incorporated,
* Vinay Hiremath,
* Zach Tratar
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished
* to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <iostream>
#include <string.h>
using namespace std;
int main(int argc, char *argv[]) {
// the options:
// 1.) search string
// 2.) editor
// 3.) root search path
// 4.) role/extension array
// 5.) maximum results
const unsigned int MAX_OPTIONS = 5;
string options[MAX_OPTIONS];
for (int i = 0; i < MAX_OPTIONS; i++) {
options[i] = "";
}
for (int i = 1; i < argc; i++) {
if (!strcmp(argv[i], "--editor")) {
if (i != (argc - 1)) {
options[1] = argv[i + 1];
i++;
}
} else if (!strcmp(argv[i], "--path")) {
if (i != (argc - 1)) {
options[2] = argv[i + 1];
i++;
}
} else if (!strcmp(argv[i], "--role")) {
if (i != (argc - 1)) {
options[3] = argv[i + 1];
i++;
}
} else if (!strcmp(argv[i], "--max")) {
if (i != (argc - 1)) {
options[4] = argv[i + 1];
i++;
}
} else if (i == 1) {
options[0] = argv[i];
}
}
// 2.) default any options not set or invalid (empty strings)
// 3.) grab the options from external files
// 4.) execv
// 5.) while (1) { TAKE_IN_FILE_TO_OPEN }
return 0;
}
<commit_msg>Parsing Options from Command Line is Finished<commit_after>/*
* Copyright (c) 2012 The Backplane Incorporated,
* Vinay Hiremath,
* Zach Tratar
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished
* to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <iostream>
#include <string.h>
using namespace std;
int main(int argc, char *argv[]) {
// the default options
string query = "";
string editor = "vim";
string path = "./";
string role = "";
string extensions[] = {"*"};
unsigned int results_cap = 25;
// get the options from the command line
for (int i = 1; i < argc; i++) {
if (!strcmp(argv[i], "--editor")) {
if (i != (argc - 1)) {
editor = argv[i + 1];
i++;
}
} else if (!strcmp(argv[i], "--path")) {
if (i != (argc - 1)) {
path = argv[i + 1];
i++;
}
} else if (!strcmp(argv[i], "--role")) {
if (i != (argc - 1)) {
role = argv[i + 1];
i++;
}
} else if (!strcmp(argv[i], "--max")) {
if (i != (argc - 1)) {
results_cap = atoi(argv[i + 1]);
i++;
}
} else if (i == 1) {
query = argv[i];
}
}
if (!query.compare("")) {
cout << "You must provide a search string as the first argument to pill." << endl;
return 0;
}
// 3.) grab the options from external files
// 4.) execv
// 5.) while (1) { TAKE_IN_FILE_TO_OPEN }
return 0;
}
<|endoftext|> |
<commit_before>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2015 Intel Corporation. All Rights Reserved.
#include "image.h"
#include "r200.h"
using namespace rsimpl;
using namespace rsimpl::ds;
namespace rsimpl
{
r200_camera::r200_camera(std::shared_ptr<uvc::device> device, const static_device_info & info)
: ds_device(device, info,
calibration_validator([](rs_stream, rs_stream){return true; }, [](rs_stream){return true; }))
{
}
void r200_camera::start_fw_logger(char fw_log_op_code, int grab_rate_in_ms, std::timed_mutex& mutex)
{
throw std::logic_error("Not implemented");
}
void r200_camera::stop_fw_logger()
{
throw std::logic_error("Not implemented");
}
std::shared_ptr<rs_device> make_r200_device(std::shared_ptr<uvc::device> device)
{
LOG_INFO("Connecting to Intel RealSense R200");
static_device_info info;
info.name = { "Intel RealSense R200" };
auto c = ds::read_camera_info(*device);
ds_device::set_common_ds_config(device, info, c);
// R200 provides Full HD raw 10 format, its descriptors is defined as follows
info.subdevice_modes.push_back({ 2, {2400, 1081}, pf_rw10, 30, c.intrinsicsThird[0], {c.modesThird[0][0]}, {0}});
return std::make_shared<r200_camera>(device, info);
}
std::shared_ptr<rs_device> make_lr200_device(std::shared_ptr<uvc::device> device)
{
LOG_INFO("Connecting to Intel RealSense LR200");
static_device_info info;
info.name = { "Intel RealSense LR200" };
auto c = ds::read_camera_info(*device);
ds_device::set_common_ds_config(device, info, c);
// LR200 provides Full HD raw 16 format as well for the color stream
info.subdevice_modes.push_back({ 2,{ 1920, 1080 }, pf_rw16, 30, c.intrinsicsThird[0],{ c.modesThird[0][0] },{ 0 } });
return std::make_shared<r200_camera>(device, info);
}
}
<commit_msg>removing redundant initialization of calibration validator<commit_after>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2015 Intel Corporation. All Rights Reserved.
#include "image.h"
#include "r200.h"
using namespace rsimpl;
using namespace rsimpl::ds;
namespace rsimpl
{
r200_camera::r200_camera(std::shared_ptr<uvc::device> device, const static_device_info & info)
: ds_device(device, info, calibration_validator())
{
}
void r200_camera::start_fw_logger(char fw_log_op_code, int grab_rate_in_ms, std::timed_mutex& mutex)
{
throw std::logic_error("Not implemented");
}
void r200_camera::stop_fw_logger()
{
throw std::logic_error("Not implemented");
}
std::shared_ptr<rs_device> make_r200_device(std::shared_ptr<uvc::device> device)
{
LOG_INFO("Connecting to Intel RealSense R200");
static_device_info info;
info.name = { "Intel RealSense R200" };
auto c = ds::read_camera_info(*device);
ds_device::set_common_ds_config(device, info, c);
// R200 provides Full HD raw 10 format, its descriptors is defined as follows
info.subdevice_modes.push_back({ 2, {2400, 1081}, pf_rw10, 30, c.intrinsicsThird[0], {c.modesThird[0][0]}, {0}});
return std::make_shared<r200_camera>(device, info);
}
std::shared_ptr<rs_device> make_lr200_device(std::shared_ptr<uvc::device> device)
{
LOG_INFO("Connecting to Intel RealSense LR200");
static_device_info info;
info.name = { "Intel RealSense LR200" };
auto c = ds::read_camera_info(*device);
ds_device::set_common_ds_config(device, info, c);
// LR200 provides Full HD raw 16 format as well for the color stream
info.subdevice_modes.push_back({ 2,{ 1920, 1080 }, pf_rw16, 30, c.intrinsicsThird[0],{ c.modesThird[0][0] },{ 0 } });
return std::make_shared<r200_camera>(device, info);
}
}
<|endoftext|> |
<commit_before>/** Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License */
#include "skin.h"
#include "utils/polygonUtils.h"
#define MIN_AREA_SIZE (0.4 * 0.4)
namespace cura
{
void generateSkins(int layerNr, SliceMeshStorage& storage, int extrusionWidth, int downSkinCount, int upSkinCount, int wall_line_count, int innermost_wall_extrusion_width, int insetCount, bool no_small_gaps_heuristic, bool avoidOverlappingPerimeters_0, bool avoidOverlappingPerimeters)
{
generateSkinAreas(layerNr, storage, innermost_wall_extrusion_width, downSkinCount, upSkinCount, wall_line_count, no_small_gaps_heuristic);
SliceLayer* layer = &storage.layers[layerNr];
for(unsigned int partNr=0; partNr<layer->parts.size(); partNr++)
{
SliceLayerPart* part = &layer->parts[partNr];
generateSkinInsets(part, extrusionWidth, insetCount, avoidOverlappingPerimeters_0, avoidOverlappingPerimeters);
}
}
void generateSkinAreas(int layer_nr, SliceMeshStorage& storage, int innermost_wall_extrusion_width, int downSkinCount, int upSkinCount, int wall_line_count, bool no_small_gaps_heuristic)
{
SliceLayer& layer = storage.layers[layer_nr];
if (downSkinCount == 0 && upSkinCount == 0)
{
return;
}
for(unsigned int partNr = 0; partNr < layer.parts.size(); partNr++)
{
SliceLayerPart& part = layer.parts[partNr];
if (int(part.insets.size()) < wall_line_count)
{
continue; // the last wall is not present, the part should only get inter preimeter gaps, but no skin.
}
Polygons upskin = part.insets.back().offset(-innermost_wall_extrusion_width/2);
Polygons downskin = (downSkinCount == 0)? Polygons() : upskin;
if (upSkinCount == 0) upskin = Polygons();
auto getInsidePolygons = [&part](SliceLayer& layer2)
{
Polygons result;
for(SliceLayerPart& part2 : layer2.parts)
{
if (part.boundaryBox.hit(part2.boundaryBox))
result.add(part2.insets.back());
}
return result;
};
if (no_small_gaps_heuristic)
{
if (static_cast<int>(layer_nr - downSkinCount) >= 0)
{
downskin = downskin.difference(getInsidePolygons(storage.layers[layer_nr - downSkinCount])); // skin overlaps with the walls
}
if (static_cast<int>(layer_nr + upSkinCount) < static_cast<int>(storage.layers.size()))
{
upskin = upskin.difference(getInsidePolygons(storage.layers[layer_nr + upSkinCount])); // skin overlaps with the walls
}
}
else
{
if (layer_nr >= downSkinCount && downSkinCount > 0)
{
Polygons not_air = getInsidePolygons(storage.layers[layer_nr - 1]);
for (int downskin_layer_nr = layer_nr - downSkinCount; downskin_layer_nr < layer_nr - 1; downskin_layer_nr++)
{
not_air = not_air.intersection(getInsidePolygons(storage.layers[downskin_layer_nr]));
}
downskin = downskin.difference(not_air); // skin overlaps with the walls
}
if (layer_nr < static_cast<int>(storage.layers.size()) - downSkinCount && upSkinCount > 0)
{
Polygons not_air = getInsidePolygons(storage.layers[layer_nr + 1]);
for (int upskin_layer_nr = layer_nr + 2; upskin_layer_nr < layer_nr + upSkinCount + 1; upskin_layer_nr++)
{
not_air = not_air.intersection(getInsidePolygons(storage.layers[upskin_layer_nr]));
}
upskin = upskin.difference(not_air); // skin overlaps with the walls
}
}
Polygons skin = upskin.unionPolygons(downskin);
skin.removeSmallAreas(MIN_AREA_SIZE);
for (PolygonsPart& skin_area_part : skin.splitIntoParts())
{
part.skin_parts.emplace_back();
part.skin_parts.back().outline = skin_area_part;
}
}
}
void generateSkinInsets(SliceLayerPart* part, int extrusionWidth, int insetCount, bool avoidOverlappingPerimeters_0, bool avoidOverlappingPerimeters)
{
if (insetCount == 0)
{
return;
}
for (SkinPart& skin_part : part->skin_parts)
{
for(int i=0; i<insetCount; i++)
{
skin_part.insets.push_back(Polygons());
if (i == 0)
{
PolygonUtils::offsetSafe(skin_part.outline, - extrusionWidth/2, extrusionWidth, skin_part.insets[0], avoidOverlappingPerimeters_0);
Polygons in_between = skin_part.outline.difference(skin_part.insets[0].offset(extrusionWidth/2));
skin_part.perimeterGaps.add(in_between);
} else
{
PolygonUtils::offsetExtrusionWidth(skin_part.insets[i-1], true, extrusionWidth, skin_part.insets[i], &skin_part.perimeterGaps, avoidOverlappingPerimeters);
}
// optimize polygons: remove unnnecesary verts
skin_part.insets[i].simplify();
if (skin_part.insets[i].size() < 1)
{
skin_part.insets.pop_back();
break;
}
}
}
}
void generateInfill(int layerNr, SliceMeshStorage& storage, int innermost_wall_extrusion_width, int infill_skin_overlap, int wall_line_count)
{
SliceLayer& layer = storage.layers[layerNr];
for(SliceLayerPart& part : layer.parts)
{
if (int(part.insets.size()) < wall_line_count)
{
part.infill_area.emplace_back(); // put empty polygon as (uncombined) infill
continue; // the last wall is not present, the part should only get inter preimeter gaps, but no infill.
}
Polygons infill = part.insets.back().offset(-innermost_wall_extrusion_width / 2 - infill_skin_overlap);
for(SliceLayerPart& part2 : layer.parts)
{
if (part.boundaryBox.hit(part2.boundaryBox))
{
for(SkinPart& skin_part : part2.skin_parts)
{
infill = infill.difference(skin_part.outline);
}
}
}
infill.removeSmallAreas(MIN_AREA_SIZE);
part.infill_area.push_back(infill.offset(infill_skin_overlap));
}
}
void combineInfillLayers(SliceMeshStorage& storage,unsigned int amount)
{
if(amount <= 1) //If we must combine 1 layer, nothing needs to be combined. Combining 0 layers is invalid.
{
return;
}
if(storage.layers.empty() || storage.layers.size() - 1 < static_cast<size_t>(storage.getSettingAsCount("top_layers")) || storage.getSettingAsCount("infill_line_distance") <= 0) //No infill is even generated.
{
return;
}
/* We need to round down the layer index we start at to the nearest
divisible index. Otherwise we get some parts that have infill at divisible
layers and some at non-divisible layers. Those layers would then miss each
other. */
size_t min_layer = storage.getSettingAsCount("bottom_layers") + amount - 1;
min_layer -= min_layer % amount; //Round upwards to the nearest layer divisible by infill_sparse_combine.
size_t max_layer = storage.layers.size() - 1 - storage.getSettingAsCount("top_layers");
max_layer -= max_layer % amount; //Round downwards to the nearest layer divisible by infill_sparse_combine.
for(size_t layer_idx = min_layer;layer_idx <= max_layer;layer_idx += amount) //Skip every few layers, but extrude more.
{
SliceLayer* layer = &storage.layers[layer_idx];
for(unsigned int n = 1;n < amount;n++)
{
if(layer_idx < n)
{
break;
}
SliceLayer* layer2 = &storage.layers[layer_idx - n];
for(SliceLayerPart& part : layer->parts)
{
Polygons result;
for(SliceLayerPart& part2 : layer2->parts)
{
if(part.boundaryBox.hit(part2.boundaryBox))
{
Polygons intersection = part.infill_area[n - 1].intersection(part2.infill_area[0]).offset(-200).offset(200);
result.add(intersection);
part.infill_area[n - 1] = part.infill_area[n - 1].difference(intersection);
part2.infill_area[0] = part2.infill_area[0].difference(intersection);
}
}
part.infill_area.push_back(result);
}
}
}
}
void generatePerimeterGaps(int layer_nr, SliceMeshStorage& storage, int extrusionWidth, int downSkinCount, int upSkinCount)
{
SliceLayer& layer = storage.layers[layer_nr];
for (SliceLayerPart& part : layer.parts)
{ // handle gaps between perimeters etc.
if (downSkinCount > 0 && upSkinCount > 0 && // note: if both are zero or less, then all gaps will be used
layer_nr >= downSkinCount && layer_nr < static_cast<int>(storage.layers.size() - upSkinCount)) // remove gaps which appear within print, i.e. not on the bottom most or top most skin
{
Polygons outlines_above;
for (SliceLayerPart& part_above : storage.layers[layer_nr + upSkinCount].parts)
{
if (part.boundaryBox.hit(part_above.boundaryBox))
{
outlines_above.add(part_above.outline);
}
}
Polygons outlines_below;
for (SliceLayerPart& part_below : storage.layers[layer_nr - downSkinCount].parts)
{
if (part.boundaryBox.hit(part_below.boundaryBox))
{
outlines_below.add(part_below.outline);
}
}
part.perimeterGaps = part.perimeterGaps.intersection(outlines_above.xorPolygons(outlines_below));
}
part.perimeterGaps.removeSmallAreas(MIN_AREA_SIZE);
}
}
}//namespace cura
<commit_msg>Fix typo. downSkinCount -> upSkinCount<commit_after>/** Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License */
#include "skin.h"
#include "utils/polygonUtils.h"
#define MIN_AREA_SIZE (0.4 * 0.4)
namespace cura
{
void generateSkins(int layerNr, SliceMeshStorage& storage, int extrusionWidth, int downSkinCount, int upSkinCount, int wall_line_count, int innermost_wall_extrusion_width, int insetCount, bool no_small_gaps_heuristic, bool avoidOverlappingPerimeters_0, bool avoidOverlappingPerimeters)
{
generateSkinAreas(layerNr, storage, innermost_wall_extrusion_width, downSkinCount, upSkinCount, wall_line_count, no_small_gaps_heuristic);
SliceLayer* layer = &storage.layers[layerNr];
for(unsigned int partNr=0; partNr<layer->parts.size(); partNr++)
{
SliceLayerPart* part = &layer->parts[partNr];
generateSkinInsets(part, extrusionWidth, insetCount, avoidOverlappingPerimeters_0, avoidOverlappingPerimeters);
}
}
void generateSkinAreas(int layer_nr, SliceMeshStorage& storage, int innermost_wall_extrusion_width, int downSkinCount, int upSkinCount, int wall_line_count, bool no_small_gaps_heuristic)
{
SliceLayer& layer = storage.layers[layer_nr];
if (downSkinCount == 0 && upSkinCount == 0)
{
return;
}
for(unsigned int partNr = 0; partNr < layer.parts.size(); partNr++)
{
SliceLayerPart& part = layer.parts[partNr];
if (int(part.insets.size()) < wall_line_count)
{
continue; // the last wall is not present, the part should only get inter preimeter gaps, but no skin.
}
Polygons upskin = part.insets.back().offset(-innermost_wall_extrusion_width/2);
Polygons downskin = (downSkinCount == 0)? Polygons() : upskin;
if (upSkinCount == 0) upskin = Polygons();
auto getInsidePolygons = [&part](SliceLayer& layer2)
{
Polygons result;
for(SliceLayerPart& part2 : layer2.parts)
{
if (part.boundaryBox.hit(part2.boundaryBox))
result.add(part2.insets.back());
}
return result;
};
if (no_small_gaps_heuristic)
{
if (static_cast<int>(layer_nr - downSkinCount) >= 0)
{
downskin = downskin.difference(getInsidePolygons(storage.layers[layer_nr - downSkinCount])); // skin overlaps with the walls
}
if (static_cast<int>(layer_nr + upSkinCount) < static_cast<int>(storage.layers.size()))
{
upskin = upskin.difference(getInsidePolygons(storage.layers[layer_nr + upSkinCount])); // skin overlaps with the walls
}
}
else
{
if (layer_nr >= downSkinCount && downSkinCount > 0)
{
Polygons not_air = getInsidePolygons(storage.layers[layer_nr - 1]);
for (int downskin_layer_nr = layer_nr - downSkinCount; downskin_layer_nr < layer_nr - 1; downskin_layer_nr++)
{
not_air = not_air.intersection(getInsidePolygons(storage.layers[downskin_layer_nr]));
}
downskin = downskin.difference(not_air); // skin overlaps with the walls
}
if (layer_nr < static_cast<int>(storage.layers.size()) - upSkinCount && upSkinCount > 0)
{
Polygons not_air = getInsidePolygons(storage.layers[layer_nr + 1]);
for (int upskin_layer_nr = layer_nr + 2; upskin_layer_nr < layer_nr + upSkinCount + 1; upskin_layer_nr++)
{
not_air = not_air.intersection(getInsidePolygons(storage.layers[upskin_layer_nr]));
}
upskin = upskin.difference(not_air); // skin overlaps with the walls
}
}
Polygons skin = upskin.unionPolygons(downskin);
skin.removeSmallAreas(MIN_AREA_SIZE);
for (PolygonsPart& skin_area_part : skin.splitIntoParts())
{
part.skin_parts.emplace_back();
part.skin_parts.back().outline = skin_area_part;
}
}
}
void generateSkinInsets(SliceLayerPart* part, int extrusionWidth, int insetCount, bool avoidOverlappingPerimeters_0, bool avoidOverlappingPerimeters)
{
if (insetCount == 0)
{
return;
}
for (SkinPart& skin_part : part->skin_parts)
{
for(int i=0; i<insetCount; i++)
{
skin_part.insets.push_back(Polygons());
if (i == 0)
{
PolygonUtils::offsetSafe(skin_part.outline, - extrusionWidth/2, extrusionWidth, skin_part.insets[0], avoidOverlappingPerimeters_0);
Polygons in_between = skin_part.outline.difference(skin_part.insets[0].offset(extrusionWidth/2));
skin_part.perimeterGaps.add(in_between);
} else
{
PolygonUtils::offsetExtrusionWidth(skin_part.insets[i-1], true, extrusionWidth, skin_part.insets[i], &skin_part.perimeterGaps, avoidOverlappingPerimeters);
}
// optimize polygons: remove unnnecesary verts
skin_part.insets[i].simplify();
if (skin_part.insets[i].size() < 1)
{
skin_part.insets.pop_back();
break;
}
}
}
}
void generateInfill(int layerNr, SliceMeshStorage& storage, int innermost_wall_extrusion_width, int infill_skin_overlap, int wall_line_count)
{
SliceLayer& layer = storage.layers[layerNr];
for(SliceLayerPart& part : layer.parts)
{
if (int(part.insets.size()) < wall_line_count)
{
part.infill_area.emplace_back(); // put empty polygon as (uncombined) infill
continue; // the last wall is not present, the part should only get inter preimeter gaps, but no infill.
}
Polygons infill = part.insets.back().offset(-innermost_wall_extrusion_width / 2 - infill_skin_overlap);
for(SliceLayerPart& part2 : layer.parts)
{
if (part.boundaryBox.hit(part2.boundaryBox))
{
for(SkinPart& skin_part : part2.skin_parts)
{
infill = infill.difference(skin_part.outline);
}
}
}
infill.removeSmallAreas(MIN_AREA_SIZE);
part.infill_area.push_back(infill.offset(infill_skin_overlap));
}
}
void combineInfillLayers(SliceMeshStorage& storage,unsigned int amount)
{
if(amount <= 1) //If we must combine 1 layer, nothing needs to be combined. Combining 0 layers is invalid.
{
return;
}
if(storage.layers.empty() || storage.layers.size() - 1 < static_cast<size_t>(storage.getSettingAsCount("top_layers")) || storage.getSettingAsCount("infill_line_distance") <= 0) //No infill is even generated.
{
return;
}
/* We need to round down the layer index we start at to the nearest
divisible index. Otherwise we get some parts that have infill at divisible
layers and some at non-divisible layers. Those layers would then miss each
other. */
size_t min_layer = storage.getSettingAsCount("bottom_layers") + amount - 1;
min_layer -= min_layer % amount; //Round upwards to the nearest layer divisible by infill_sparse_combine.
size_t max_layer = storage.layers.size() - 1 - storage.getSettingAsCount("top_layers");
max_layer -= max_layer % amount; //Round downwards to the nearest layer divisible by infill_sparse_combine.
for(size_t layer_idx = min_layer;layer_idx <= max_layer;layer_idx += amount) //Skip every few layers, but extrude more.
{
SliceLayer* layer = &storage.layers[layer_idx];
for(unsigned int n = 1;n < amount;n++)
{
if(layer_idx < n)
{
break;
}
SliceLayer* layer2 = &storage.layers[layer_idx - n];
for(SliceLayerPart& part : layer->parts)
{
Polygons result;
for(SliceLayerPart& part2 : layer2->parts)
{
if(part.boundaryBox.hit(part2.boundaryBox))
{
Polygons intersection = part.infill_area[n - 1].intersection(part2.infill_area[0]).offset(-200).offset(200);
result.add(intersection);
part.infill_area[n - 1] = part.infill_area[n - 1].difference(intersection);
part2.infill_area[0] = part2.infill_area[0].difference(intersection);
}
}
part.infill_area.push_back(result);
}
}
}
}
void generatePerimeterGaps(int layer_nr, SliceMeshStorage& storage, int extrusionWidth, int downSkinCount, int upSkinCount)
{
SliceLayer& layer = storage.layers[layer_nr];
for (SliceLayerPart& part : layer.parts)
{ // handle gaps between perimeters etc.
if (downSkinCount > 0 && upSkinCount > 0 && // note: if both are zero or less, then all gaps will be used
layer_nr >= downSkinCount && layer_nr < static_cast<int>(storage.layers.size() - upSkinCount)) // remove gaps which appear within print, i.e. not on the bottom most or top most skin
{
Polygons outlines_above;
for (SliceLayerPart& part_above : storage.layers[layer_nr + upSkinCount].parts)
{
if (part.boundaryBox.hit(part_above.boundaryBox))
{
outlines_above.add(part_above.outline);
}
}
Polygons outlines_below;
for (SliceLayerPart& part_below : storage.layers[layer_nr - downSkinCount].parts)
{
if (part.boundaryBox.hit(part_below.boundaryBox))
{
outlines_below.add(part_below.outline);
}
}
part.perimeterGaps = part.perimeterGaps.intersection(outlines_above.xorPolygons(outlines_below));
}
part.perimeterGaps.removeSmallAreas(MIN_AREA_SIZE);
}
}
}//namespace cura
<|endoftext|> |
<commit_before>#include <stdlib.h>
#ifdef _WIN32
#define _UNICODE 1
#define UNICODE 1
#endif
#include "../include/sliprock.h"
#include "sliprock_internals.h"
#include "stringbuf.h"
#include <csignal>
#include <exception>
#include <mutex>
#define BOOST_TEST_MODULE SlipRock module
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
//#include <boost/thread.hpp>
#include <stdexcept>
#include <thread>
#ifdef _WIN32
#define address pipename
#include <windows.h>
#endif
#ifndef BOOST_TEST
#define BOOST_TEST BOOST_CHECK
#endif
#ifndef _WIN32
typedef int HANDLE;
#include <pthread.h>
#define INVALID_HANDLE_VALUE (-1)
#endif
struct set_on_close {
set_on_close(std::mutex &m, bool &b) : boolean(b), mut(m) {}
~set_on_close() {
std::unique_lock<std::mutex> locker{mut};
boolean = true;
}
private:
bool &boolean;
std::mutex &mut;
};
template <size_t size>
bool client(char (&buf)[size], SliprockConnection *con, bool &finished,
std::mutex &mutex) {
set_on_close closer(mutex, finished);
char buf2[size + 1] = {0};
bool read_succeeded = false;
HANDLE fd = INVALID_HANDLE_VALUE;
(void)system("ls -a ~/.sliprock");
SliprockReceiver *receiver =
sliprock_open("dummy_valr", sizeof("dummy_val") - 1, (uint32_t)getpid());
if (receiver == nullptr) {
perror("sliprock_open");
goto fail;
}
MADE_IT;
fd = (HANDLE)sliprock_connect(receiver);
if (fd == INVALID_HANDLE_VALUE) {
perror("sliprock_connect");
goto fail;
}
MADE_IT;
#ifdef _WIN32
DWORD read;
BOOST_TEST(0 != ReadFile(fd, buf2, sizeof buf, &read, nullptr));
BOOST_TEST(read == sizeof buf);
BOOST_TEST(0 != WriteFile(fd, buf2, sizeof buf, &read, nullptr));
BOOST_TEST(read == sizeof buf);
#else
if (fd >= 0) {
BOOST_TEST(sizeof buf == read(fd, buf2, sizeof buf));
BOOST_TEST(sizeof buf == write(fd, buf2, sizeof buf));
}
#endif
// static_assert(sizeof buf2 == sizeof buf, "Buffer size mismatch");
static_assert(sizeof con->address == sizeof receiver->sock,
"Connection size mismatch");
BOOST_TEST(memcmp(&buf2[0], &buf[0], sizeof buf) == 0);
puts(buf);
puts(buf2);
#ifndef _WIN32
BOOST_TEST(fd > -1);
#endif
read_succeeded = true;
fail:
BOOST_REQUIRE(nullptr != receiver);
BOOST_TEST(0 == memcmp(reinterpret_cast<void *>(&receiver->sock),
reinterpret_cast<void *>(&con->address),
sizeof con->address));
BOOST_TEST(read_succeeded == true);
BOOST_TEST(receiver != static_cast<SliprockReceiver *>(nullptr));
#ifndef _WIN32
BOOST_TEST(close(fd) == 0);
#else
BOOST_TEST(CloseHandle(fd) != 0);
#endif
sliprock_close_receiver(receiver);
return read_succeeded;
}
template <size_t n>
bool server(char (&buf)[n], SliprockConnection *con, bool &finished,
std::mutex &mutex) {
set_on_close closer(mutex, finished);
MADE_IT;
auto handle = (HANDLE)sliprock_accept(con);
MADE_IT;
if (handle == INVALID_HANDLE_VALUE)
return false;
MADE_IT;
char buf3[sizeof buf];
#ifndef _WIN32
if (write(handle, buf, sizeof buf) != sizeof buf)
return false;
MADE_IT;
if (read(handle, buf3, sizeof buf) != sizeof buf)
return false;
MADE_IT;
if (close(handle))
return false;
MADE_IT;
#else
DWORD written;
MADE_IT;
if (WriteFile(handle, buf, sizeof buf, &written, NULL) == 0)
return false;
MADE_IT;
if (written != sizeof buf3)
return false;
MADE_IT;
if (ReadFile(handle, buf3, sizeof buf3, &written, NULL) == 0)
return false;
if (!CloseHandle(handle))
return false;
MADE_IT;
#endif
bool x = !memcmp(buf3, buf, sizeof buf);
finished = true;
return x;
}
#ifndef _WIN32
static void donothing(int _) {
(void)_;
return;
}
static_assert(std::is_same<std::thread::native_handle_type, pthread_t>(),
"Mismatched native handle type!");
#elif 0
static_assert(std::is_same<std::thread::native_handle_type, HANDLE>(),
"Mismatched native handle type!");
#endif
// Interrupt a thread IF read_done is true, ensuring that lock is held
// when reading its value.
static void interrupt_thread(std::mutex &lock, const bool &read_done,
std::thread &thread) {
std::unique_lock<std::mutex> locker(lock);
if (!read_done) {
#ifndef _WIN32
pthread_kill(thread.native_handle(), SIGPIPE);
#else
(void)thread;
//CancelSynchronousIo(thread.native_handle());
#endif
}
}
BOOST_AUTO_TEST_CASE(can_create_connection) {
#ifndef _WIN32
struct sigaction sigact;
memset(&sigact, 0, sizeof sigact);
sigact.sa_handler = donothing;
sigemptyset(&sigact.sa_mask);
sigaddset(&sigact.sa_mask, SIGPIPE);
sigaction(SIGPIPE, &sigact, nullptr);
#endif
(void)system("rm -rf -- \"$HOME/.sliprock\" /tmp/sliprock.*");
SliprockConnection *con =
sliprock_socket("dummy_valq", sizeof("dummy_val") - 1);
BOOST_REQUIRE(con != nullptr);
std::mutex lock, lock2;
bool read_done = false, write_done = false;
char buf[] = "Test message!";
bool write_succeeded = false, read_succeeded = false;
std::thread thread([&]() {
if (!(read_succeeded = server(buf, con, read_done, lock2)))
perror("sliprock_server");
});
std::thread thread2(
[&]() { write_succeeded = client(buf, con, write_done, lock); });
auto interrupter = std::thread{[&]() {
struct timespec q = {1, 0};
nanosleep(&q, nullptr);
interrupt_thread(lock2, read_done, thread);
interrupt_thread(lock, write_done, thread2);
}};
thread.join();
thread2.join();
interrupter.join();
BOOST_TEST(write_succeeded);
BOOST_TEST(read_succeeded);
sliprock_close(con);
}
// BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Use CancelSynchronousIo on Windows<commit_after>#include <stdlib.h>
#ifdef _WIN32
#define _UNICODE 1
#define UNICODE 1
#endif
#include "../include/sliprock.h"
#include "sliprock_internals.h"
#include "stringbuf.h"
#include <csignal>
#include <exception>
#include <mutex>
#define BOOST_TEST_MODULE SlipRock module
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
//#include <boost/thread.hpp>
#include <stdexcept>
#include <thread>
#ifdef _WIN32
#define address pipename
#include <windows.h>
#endif
#ifndef BOOST_TEST
#define BOOST_TEST BOOST_CHECK
#endif
#ifndef _WIN32
typedef int HANDLE;
#include <pthread.h>
#define INVALID_HANDLE_VALUE (-1)
#endif
struct set_on_close {
set_on_close(std::mutex &m, bool &b) : boolean(b), mut(m) {}
~set_on_close() {
std::unique_lock<std::mutex> locker{mut};
boolean = true;
}
private:
bool &boolean;
std::mutex &mut;
};
template <size_t size>
bool client(char (&buf)[size], SliprockConnection *con, bool &finished,
std::mutex &mutex) {
set_on_close closer(mutex, finished);
char buf2[size + 1] = {0};
bool read_succeeded = false;
HANDLE fd = INVALID_HANDLE_VALUE;
(void)system("ls -a ~/.sliprock");
SliprockReceiver *receiver =
sliprock_open("dummy_valr", sizeof("dummy_val") - 1, (uint32_t)getpid());
if (receiver == nullptr) {
perror("sliprock_open");
goto fail;
}
MADE_IT;
fd = (HANDLE)sliprock_connect(receiver);
if (fd == INVALID_HANDLE_VALUE) {
perror("sliprock_connect");
goto fail;
}
MADE_IT;
#ifdef _WIN32
DWORD read;
BOOST_TEST(0 != ReadFile(fd, buf2, sizeof buf, &read, nullptr));
BOOST_TEST(read == sizeof buf);
BOOST_TEST(0 != WriteFile(fd, buf2, sizeof buf, &read, nullptr));
BOOST_TEST(read == sizeof buf);
#else
if (fd >= 0) {
BOOST_TEST(sizeof buf == read(fd, buf2, sizeof buf));
BOOST_TEST(sizeof buf == write(fd, buf2, sizeof buf));
}
#endif
// static_assert(sizeof buf2 == sizeof buf, "Buffer size mismatch");
static_assert(sizeof con->address == sizeof receiver->sock,
"Connection size mismatch");
BOOST_TEST(memcmp(&buf2[0], &buf[0], sizeof buf) == 0);
puts(buf);
puts(buf2);
#ifndef _WIN32
BOOST_TEST(fd > -1);
#endif
read_succeeded = true;
fail:
BOOST_REQUIRE(nullptr != receiver);
BOOST_TEST(0 == memcmp(reinterpret_cast<void *>(&receiver->sock),
reinterpret_cast<void *>(&con->address),
sizeof con->address));
BOOST_TEST(read_succeeded == true);
BOOST_TEST(receiver != static_cast<SliprockReceiver *>(nullptr));
#ifndef _WIN32
BOOST_TEST(close(fd) == 0);
#else
BOOST_TEST(CloseHandle(fd) != 0);
#endif
sliprock_close_receiver(receiver);
return read_succeeded;
}
template <size_t n>
bool server(char (&buf)[n], SliprockConnection *con, bool &finished,
std::mutex &mutex) {
set_on_close closer(mutex, finished);
MADE_IT;
auto handle = (HANDLE)sliprock_accept(con);
MADE_IT;
if (handle == INVALID_HANDLE_VALUE)
return false;
MADE_IT;
char buf3[sizeof buf];
#ifndef _WIN32
if (write(handle, buf, sizeof buf) != sizeof buf)
return false;
MADE_IT;
if (read(handle, buf3, sizeof buf) != sizeof buf)
return false;
MADE_IT;
if (close(handle))
return false;
MADE_IT;
#else
DWORD written;
MADE_IT;
if (WriteFile(handle, buf, sizeof buf, &written, NULL) == 0)
return false;
MADE_IT;
if (written != sizeof buf3)
return false;
MADE_IT;
if (ReadFile(handle, buf3, sizeof buf3, &written, NULL) == 0)
return false;
if (!CloseHandle(handle))
return false;
MADE_IT;
#endif
bool x = !memcmp(buf3, buf, sizeof buf);
finished = true;
return x;
}
#ifndef _WIN32
static void donothing(int _) {
(void)_;
return;
}
static_assert(std::is_same<std::thread::native_handle_type, pthread_t>(),
"Mismatched native handle type!");
#elif 0
static_assert(std::is_same<std::thread::native_handle_type, HANDLE>(),
"Mismatched native handle type!");
#endif
// Interrupt a thread IF read_done is true, ensuring that lock is held
// when reading its value.
static void interrupt_thread(std::mutex &lock, const bool &read_done,
std::thread &thread) {
std::unique_lock<std::mutex> locker(lock);
if (!read_done) {
#ifndef _WIN32
pthread_kill(thread.native_handle(), SIGPIPE);
#elif _MSC_VER
CancelSynchronousIo(thread.native_handle());
#else
(void)thread;
#endif
}
}
BOOST_AUTO_TEST_CASE(can_create_connection) {
#ifndef _WIN32
struct sigaction sigact;
memset(&sigact, 0, sizeof sigact);
sigact.sa_handler = donothing;
sigemptyset(&sigact.sa_mask);
sigaddset(&sigact.sa_mask, SIGPIPE);
sigaction(SIGPIPE, &sigact, nullptr);
#endif
(void)system("rm -rf -- \"$HOME/.sliprock\" /tmp/sliprock.*");
SliprockConnection *con =
sliprock_socket("dummy_valq", sizeof("dummy_val") - 1);
BOOST_REQUIRE(con != nullptr);
std::mutex lock, lock2;
bool read_done = false, write_done = false;
char buf[] = "Test message!";
bool write_succeeded = false, read_succeeded = false;
std::thread thread([&]() {
if (!(read_succeeded = server(buf, con, read_done, lock2)))
perror("sliprock_server");
});
std::thread thread2(
[&]() { write_succeeded = client(buf, con, write_done, lock); });
auto interrupter = std::thread{[&]() {
#ifndef _WIN32
struct timespec q = {1, 0};
nanosleep(&q, nullptr);
#else
Sleep(1000);
#endif
interrupt_thread(lock2, read_done, thread);
interrupt_thread(lock, write_done, thread2);
}};
thread.join();
thread2.join();
interrupter.join();
BOOST_TEST(write_succeeded);
BOOST_TEST(read_succeeded);
sliprock_close(con);
}
// BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>// Lesson 13.cpp : Defines the entry point for the console application.
#include <render_framework\render_framework.h>
#include <chrono>
#pragma comment (lib , "Render Framework" )
using namespace std;
using namespace glm;
using namespace render_framework;
using namespace chrono;
// Global scop box
shared_ptr<mesh> box;
// Keep track of current mode
int MODE = 0;
/*
* key_callback
*
* used for identifying key presses
* and switching the current mode
*/
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
if (key == GLFW_KEY_SPACE && action == GLFW_PRESS) {
switch (MODE) {
case 0:
MODE = 1;
break;
case 1:
MODE = 0;
break;
// case 2:
// MODE = 0;
// break;
default:
MODE = 0;
break;
}
}
} // key_callback
/*
* userTranslation
*
* Moves the object around inside the window using the keyboard arrow keys.
*/
void userTranslation(float deltaTime)
{
// Move the quad when arrow keys are pressed
if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_RIGHT)) {
box->trans.translate(vec3(10.0, 0.0, 0.0) * deltaTime);
}
if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_LEFT)) {
box->trans.translate(vec3(-10.0, 0.0, 0.0) * deltaTime);
}
if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_UP)) {
box->trans.translate(vec3(0.0, 0.0, -10.0) * deltaTime);
}
if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_DOWN)) {
box->trans.translate(vec3(0.0, 0.0, 10.0) * deltaTime);
}
if (glfwGetKey(renderer::get_instance().get_window(), 'W')) {
box->trans.translate(vec3(0.0, 10.0, 0.0) * deltaTime);
}
if (glfwGetKey(renderer::get_instance().get_window(), 'S')) {
box->trans.translate(vec3(0.0, -10.0, 0.0) * deltaTime);
}
} // userTranslation()
/*
* userRotation
*
* rotates the object
*/
void userRotation(float deltaTime) {
if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_UP)) {
box->trans.rotate(vec3(-pi<float>(), 0.0, 0.0f) * deltaTime);
}
if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_DOWN)) {
box->trans.rotate(vec3(pi<float>(), 0.0, 0.0f) * deltaTime);
}
if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_RIGHT)) {
box->trans.rotate(vec3(0.0, -pi<float>(), 0.0f) * deltaTime);
}
if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_LEFT)) {
box->trans.rotate(vec3(0.0, pi<float>(), 0.0f) * deltaTime);
}
if (glfwGetKey(renderer::get_instance().get_window(), 'W')) {
box->trans.rotate(vec3(0.0, 0.0, pi<float>()) * deltaTime);
}
if (glfwGetKey(renderer::get_instance().get_window(), 'S')) {
box->trans.rotate(vec3(0.0, 0.0, -pi<float>()) * deltaTime);
}
} // userRotation
/*
* Update routine
*
* Updates the application state
*/
void update(float deltaTime)
{
switch (MODE) {
case 0:
userTranslation(deltaTime);
break;
case 1:
userRotation(deltaTime);
break;
// case 2:
// userScale(deltaTime);
// break;
default:
break;
}
} // update()
int main()
{
// Initialize the renderer
if (!renderer::get_instance().initialise()) return -1;
// Set the clear colour to cyan
glClearColor(0.0f, 1.0f, 1.0f, 1.0f);
/* Set the projection matrix */
// First get the aspect ratio (width/height)
float aspect = (float)renderer::get_instance().get_screen_width() /
(float)renderer::get_instance().get_screen_width();
// Use this to create projection matrix
auto projection = perspective(
degrees(quarter_pi<float>()), // FOV
aspect, // Aspect ratio
2.414f, // Near plane
10000.0f); // Far plane
// Set the projection matrix
renderer::get_instance().set_projection(projection);
// Set the view matrix
auto view = lookAt(
vec3(20.0f, 20.0f, 20.0f), // Camera position
vec3(0.0f, 0.0f, 0.0f), // Target
vec3(0.0f, 1.0f, 0.0f)); // Up vector
renderer::get_instance().set_view(view);
/* Set the function for the key callback */
glfwSetKeyCallback(renderer::get_instance().get_window(), key_callback);
// Create box
box = make_shared<mesh>();
box->geom = geometry_builder::create_box();
// Load in effect. Start with shaders
auto eff = make_shared<effect>();
eff->add_shader("shader.vert", GL_VERTEX_SHADER);
eff->add_shader("shader.frag", GL_FRAGMENT_SHADER);
if (!effect_loader::build_effect(eff)) {
return -1;
}
// Create material for box
box->mat = make_shared<material>();
box->mat->effect = eff;
box->mat->set_uniform_value("colour", vec4(0.0, 1.0, 0.0, 1.0));
box->mat->set_uniform_value("hue", vec4(1.0, 0.0, 0.0, 1.0));
// Monitor the elapsed time per frame
auto currentTimeStamp = system_clock::now();
auto prevTimeStamp = system_clock::now();
// Main render loop
while (renderer::get_instance().is_running())
{
// Get current time
currentTimeStamp = system_clock::now();
// Calculate elapsed time
auto elapsed = duration_cast<milliseconds>(currentTimeStamp - prevTimeStamp);
// Convert to fractions of a second
auto seconds = float(elapsed.count()) / 1000.0;
// Update Scene
update(seconds);
// Check if running
if (renderer::get_instance().begin_render())
{
// Render Cube
renderer::get_instance().render(box);
// End the render
renderer::get_instance().end_render();
}
prevTimeStamp = currentTimeStamp;
} // Main render loop
}
<commit_msg>Changed box to object<commit_after>// Lesson 13.cpp : Defines the entry point for the console application.
#include <render_framework\render_framework.h>
#include <chrono>
#pragma comment (lib , "Render Framework" )
using namespace std;
using namespace glm;
using namespace render_framework;
using namespace chrono;
// Global scop box
shared_ptr<mesh> object;
// Keep track of current mode
int MODE = 0;
/*
* key_callback
*
* used for identifying key presses
* and switching the current mode
*/
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
if (key == GLFW_KEY_SPACE && action == GLFW_PRESS) {
switch (MODE) {
case 0:
MODE = 1;
break;
case 1:
MODE = 0;
break;
// case 2:
// MODE = 0;
// break;
default:
MODE = 0;
break;
}
}
} // key_callback
/*
* userTranslation
*
* Moves the object around inside the window using the keyboard arrow keys.
*/
void userTranslation(float deltaTime)
{
// Move the quad when arrow keys are pressed
if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_RIGHT)) {
object->trans.translate(vec3(10.0, 0.0, 0.0) * deltaTime);
}
if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_LEFT)) {
object->trans.translate(vec3(-10.0, 0.0, 0.0) * deltaTime);
}
if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_UP)) {
object->trans.translate(vec3(0.0, 0.0, -10.0) * deltaTime);
}
if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_DOWN)) {
object->trans.translate(vec3(0.0, 0.0, 10.0) * deltaTime);
}
if (glfwGetKey(renderer::get_instance().get_window(), 'W')) {
object->trans.translate(vec3(0.0, 10.0, 0.0) * deltaTime);
}
if (glfwGetKey(renderer::get_instance().get_window(), 'S')) {
object->trans.translate(vec3(0.0, -10.0, 0.0) * deltaTime);
}
} // userTranslation()
/*
* userRotation
*
* rotates the object
*/
void userRotation(float deltaTime) {
if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_UP)) {
object->trans.rotate(vec3(-pi<float>(), 0.0, 0.0f) * deltaTime);
}
if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_DOWN)) {
object->trans.rotate(vec3(pi<float>(), 0.0, 0.0f) * deltaTime);
}
if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_RIGHT)) {
object->trans.rotate(vec3(0.0, -pi<float>(), 0.0f) * deltaTime);
}
if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_LEFT)) {
object->trans.rotate(vec3(0.0, pi<float>(), 0.0f) * deltaTime);
}
if (glfwGetKey(renderer::get_instance().get_window(), 'W')) {
object->trans.rotate(vec3(0.0, 0.0, pi<float>()) * deltaTime);
}
if (glfwGetKey(renderer::get_instance().get_window(), 'S')) {
object->trans.rotate(vec3(0.0, 0.0, -pi<float>()) * deltaTime);
}
} // userRotation
/*
* Update routine
*
* Updates the application state
*/
void update(float deltaTime)
{
switch (MODE) {
case 0:
userTranslation(deltaTime);
break;
case 1:
userRotation(deltaTime);
break;
// case 2:
// userScale(deltaTime);
// break;
default:
break;
}
} // update()
int main()
{
// Initialize the renderer
if (!renderer::get_instance().initialise()) return -1;
// Set the clear colour to cyan
glClearColor(0.0f, 1.0f, 1.0f, 1.0f);
/* Set the projection matrix */
// First get the aspect ratio (width/height)
float aspect = (float)renderer::get_instance().get_screen_width() /
(float)renderer::get_instance().get_screen_width();
// Use this to create projection matrix
auto projection = perspective(
degrees(quarter_pi<float>()), // FOV
aspect, // Aspect ratio
2.414f, // Near plane
10000.0f); // Far plane
// Set the projection matrix
renderer::get_instance().set_projection(projection);
// Set the view matrix
auto view = lookAt(
vec3(20.0f, 20.0f, 20.0f), // Camera position
vec3(0.0f, 0.0f, 0.0f), // Target
vec3(0.0f, 1.0f, 0.0f)); // Up vector
renderer::get_instance().set_view(view);
/* Set the function for the key callback */
glfwSetKeyCallback(renderer::get_instance().get_window(), key_callback);
// Create box
object = make_shared<mesh>();
object->geom = geometry_builder::create_box();
// Load in effect. Start with shaders
auto eff = make_shared<effect>();
eff->add_shader("shader.vert", GL_VERTEX_SHADER);
eff->add_shader("shader.frag", GL_FRAGMENT_SHADER);
if (!effect_loader::build_effect(eff)) {
return -1;
}
// Create material for box
object->mat = make_shared<material>();
object->mat->effect = eff;
object->mat->set_uniform_value("colour", vec4(0.0, 1.0, 0.0, 1.0));
object->mat->set_uniform_value("hue", vec4(1.0, 0.0, 0.0, 1.0));
// Monitor the elapsed time per frame
auto currentTimeStamp = system_clock::now();
auto prevTimeStamp = system_clock::now();
// Main render loop
while (renderer::get_instance().is_running())
{
// Get current time
currentTimeStamp = system_clock::now();
// Calculate elapsed time
auto elapsed = duration_cast<milliseconds>(currentTimeStamp - prevTimeStamp);
// Convert to fractions of a second
auto seconds = float(elapsed.count()) / 1000.0;
// Update Scene
update(seconds);
// Check if running
if (renderer::get_instance().begin_render())
{
// Render Cube
renderer::get_instance().render(object);
// End the render
renderer::get_instance().end_render();
}
prevTimeStamp = currentTimeStamp;
} // Main render loop
}
<|endoftext|> |
<commit_before>// Test.cpp
// Sean Jones
#define GLFW_INCLUDE_GLU
#include <GLFW/glfw3.h>
#include <chrono>
#include <glm/glm.hpp>
#include <glm/gtx/constants.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/core/type_vec3.hpp>
using namespace std::chrono;
GLFWwindow* window;
bool running = true;
// Value to keep track of current orientation on axis
glm::vec3 position(0.0f, 0.0f, 0.0f);
bool initialise()
{
// Set Color to cyan
glClearColor(0.0f, 1.0f, 1.0f, 1.0f);
return true;
} // initialise
//updates the application
void update(double deltaTime)
{
// Check if escape pressed or window is closed
running = !glfwGetKey(window, GLFW_KEY_ESCAPE) &&
!glfwWindowShouldClose(window);
// Move the quad when arrow keys are pressed
if (glfwGetKey(window, GLFW_KEY_RIGHT)){
position += glm::vec3(1.0f, 0.0f, 0.0f) * float(deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_LEFT)){
position -= glm::vec3(1.0f, 0.0f, 0.0f) * float(deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_UP)){
position += glm::vec3(0.0f, 1.0f, 0.0f) * float(deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_DOWN)){
position -= glm::vec3(0.0f, 1.0f, 0.0f) * float(deltaTime);
}
} // update
//renders the application
void render()
{
// Create model matrix
auto model = glm::translate(glm::mat4(1.0f), position);
// Set matrix mode
glMatrixMode(GL_MODELVIEW);
// Load model matrix
glLoadMatrixf(glm::value_ptr(model));
// Clear the screen
glClear(GL_COLOR_BUFFER_BIT);
//Set the colour
glColor4f(1.0f, 0.0f, 0.0f, 1.0f);
//Render a Triangel
glBegin(GL_QUADS);
glVertex3f(0.5f, 0.5f, 0.0f);
glVertex3f(-0.5f, 0.5f, 0.0f);
glVertex3f(-0.5f, -0.5f, 0.0f);
glVertex3f(0.5f, -0.5f, 0.0f);
glEnd();
// Swap front and back buffers
glfwSwapBuffers(window);
// Set transform matrix to identity (no transform)
glLoadIdentity();
} // render
int main(void)
{
/* Initialize the library */
if (!glfwInit())
{
return -1;
}
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}
/* Make the window's context current */
glfwMakeContextCurrent(window);
//initialise the window
if (!initialise())
{
glfwTerminate();
return -1;
}
// Monitor the elapsed time per frame
auto currentTimeStamp = system_clock::now();
auto prevTimeStamp = system_clock::now();
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
// Get current time
currentTimeStamp = system_clock::now();
// Calculate elapsed time
auto elapsed = duration_cast<milliseconds>(currentTimeStamp
- prevTimeStamp);
//Convert to fractions of a second
auto seconds = double(elapsed.count()) / 1000.0;
// Update Application
update(seconds);
//Render scene
render();
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
// set the previous time stamp to current time stamp
prevTimeStamp = currentTimeStamp;
} // Main Loop
glfwTerminate();
return 0;
} // main
<commit_msg>Added basic edge detection<commit_after>// Test.cpp
// Sean Jones
#define GLFW_INCLUDE_GLU
#include <GLFW/glfw3.h>
#include <chrono>
#include <glm/glm.hpp>
#include <glm/gtx/constants.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/core/type_vec3.hpp>
using namespace std::chrono;
GLFWwindow* window;
bool running = true;
// Value to keep track of current orientation on axis
glm::vec3 position(0.0f, 0.0f, 0.0f);
bool initialise()
{
// Set Color to cyan
glClearColor(0.0f, 1.0f, 1.0f, 1.0f);
return true;
} // initialise
//updates the application
void update(double deltaTime)
{
// Check if escape pressed or window is closed
running = !glfwGetKey(window, GLFW_KEY_ESCAPE) &&
!glfwWindowShouldClose(window);
// Move the quad when arrow keys are pressed
if (glfwGetKey(window, GLFW_KEY_RIGHT)){
if (position.x < 0.5) {
position += glm::vec3(1.0f, 0.0f, 0.0f) * float(deltaTime);
}
}
if (glfwGetKey(window, GLFW_KEY_LEFT)){
if (position.x > -0.5) {
position -= glm::vec3(1.0f, 0.0f, 0.0f) * float(deltaTime);
}
}
if (glfwGetKey(window, GLFW_KEY_UP)){
if (position.y < 0.5) {
position += glm::vec3(0.0f, 1.0f, 0.0f) * float(deltaTime);
}
}
if (glfwGetKey(window, GLFW_KEY_DOWN)){
if (position.y > -0.5) {
position -= glm::vec3(0.0f, 1.0f, 0.0f) * float(deltaTime);
}
}
} // update
//renders the application
void render()
{
// Create model matrix
auto model = glm::translate(glm::mat4(1.0f), position);
// Set matrix mode
glMatrixMode(GL_MODELVIEW);
// Load model matrix
glLoadMatrixf(glm::value_ptr(model));
// Clear the screen
glClear(GL_COLOR_BUFFER_BIT);
//Set the colour
glColor4f(1.0f, 0.0f, 0.0f, 1.0f);
//Render a Triangel
glBegin(GL_QUADS);
glVertex3f(0.5f, 0.5f, 0.0f);
glVertex3f(-0.5f, 0.5f, 0.0f);
glVertex3f(-0.5f, -0.5f, 0.0f);
glVertex3f(0.5f, -0.5f, 0.0f);
glEnd();
// Swap front and back buffers
glfwSwapBuffers(window);
// Set transform matrix to identity (no transform)
glLoadIdentity();
} // render
int main(void)
{
/* Initialize the library */
if (!glfwInit())
{
return -1;
}
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}
/* Make the window's context current */
glfwMakeContextCurrent(window);
//initialise the window
if (!initialise())
{
glfwTerminate();
return -1;
}
// Monitor the elapsed time per frame
auto currentTimeStamp = system_clock::now();
auto prevTimeStamp = system_clock::now();
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
// Get current time
currentTimeStamp = system_clock::now();
// Calculate elapsed time
auto elapsed = duration_cast<milliseconds>(currentTimeStamp
- prevTimeStamp);
//Convert to fractions of a second
auto seconds = double(elapsed.count()) / 1000.0;
// Update Application
update(seconds);
//Render scene
render();
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
// set the previous time stamp to current time stamp
prevTimeStamp = currentTimeStamp;
} // Main Loop
glfwTerminate();
return 0;
} // main
<|endoftext|> |
<commit_before>///
/// @file test.cpp
/// @brief primecount integration tests.
///
/// Copyright (C) 2014 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primecount.hpp>
#include <primecount-internal.hpp>
#include <primesieve.hpp>
#include <ptypes.hpp>
#include <stdint.h>
#include <iostream>
#include <cstdlib>
#include <string>
#include <stdexcept>
#include <sstream>
#include <ctime>
#ifdef _OPENMP
#include <omp.h>
#endif
/// For types: f1(x) , f2(x)
#define CHECK_11(f1, f2) check_equal(#f1, x, f1 (x), f2 (x))
/// For types: f1(x) , f2(x, threads)
#define CHECK_12(f1, f2) check_equal(#f1, x, f1 (x), f2 (x, get_num_threads()))
/// For types: f1(x, threads) , f2(x, threads)
#define CHECK_22(f1, f2) check_equal(#f1, x, f1 (x, get_num_threads()), f2 (x, get_num_threads()))
#define CHECK_EQUAL(f1, f2, check, iters) \
{ \
cout << "Testing " << #f1 << "(x)" << flush; \
\
/* test for 0 <= x < 10000 */ \
for (int64_t x = 0; x < 10000; x++) \
check(f1, f2); \
\
int64_t x = 0; \
/* test using random increment */ \
for (int64_t i = 0; i < iters; i++, x += get_rand()) \
{ \
check(f1, f2); \
double percent = 100.0 * (i + 1.0) / iters; \
cout << "\rTesting " << #f1 "(x) " << (int) percent << "%" << flush; \
} \
\
cout << endl; \
}
using namespace std;
using namespace primecount;
using primesieve::parallel_nth_prime;
namespace {
int get_rand()
{
// 0 <= get_rand() < 10^7
return (rand() % 10000) * 1000 + 1;
}
void check_equal(const string& f1, int64_t x, int64_t res1, int64_t res2)
{
if (res1 != res2)
{
ostringstream oss;
oss << f1 << "(" << x << ") = " << res1
<< " is an error, the correct result is " << res2;
throw runtime_error(oss.str());
}
}
void test_phi_thread_safety(int64_t iters)
{
#ifdef _OPENMP
cout << "Testing phi(x, a)" << flush;
int nested_threads = 2;
int64_t single_thread_sum = 0;
int64_t multi_thread_sum = 0;
int64_t base = 1000000;
omp_set_nested(true);
#pragma omp parallel for reduction(+: multi_thread_sum)
for (int64_t i = 0; i < iters; i++)
multi_thread_sum += pi_legendre(base + i, nested_threads);
omp_set_nested(false);
for (int64_t i = 0; i < iters; i++)
single_thread_sum += pi_legendre(base + i, 1);
if (multi_thread_sum != single_thread_sum)
throw runtime_error("Error: multi-threaded phi(x, a) is broken.");
std::cout << "\rTesting phi(x, a) 100%" << endl;
#endif
}
} // namespace
namespace primecount {
bool test()
{
srand((unsigned) time(0));
try
{
test_phi_thread_safety(100);
CHECK_EQUAL(pi_legendre, pi_primesieve, CHECK_22, 100);
CHECK_EQUAL(pi_meissel, pi_legendre, CHECK_22, 400);
CHECK_EQUAL(pi_lehmer, pi_meissel, CHECK_22, 400);
CHECK_EQUAL(pi_lehmer2, pi_lehmer, CHECK_22, 200);
CHECK_EQUAL(pi_lmo1, pi_meissel, CHECK_12, 200);
CHECK_EQUAL(pi_lmo2, pi_meissel, CHECK_12, 200);
CHECK_EQUAL(pi_lmo3, pi_meissel, CHECK_12, 300);
CHECK_EQUAL(pi_lmo4, pi_meissel, CHECK_12, 300);
CHECK_EQUAL(pi_lmo5, pi_meissel, CHECK_12, 400);
CHECK_EQUAL(pi_lmo_parallel1, pi_meissel, CHECK_22, 400);
CHECK_EQUAL(pi_lmo_parallel2, pi_meissel, CHECK_22, 400);
CHECK_EQUAL(pi_lmo_parallel3, pi_meissel, CHECK_22, 400);
CHECK_EQUAL(pi_deleglise_rivat1, pi_lmo_parallel3, CHECK_12, 600);
CHECK_EQUAL(pi_deleglise_rivat2, pi_lmo_parallel3, CHECK_12, 600);
CHECK_EQUAL(pi_deleglise_rivat3, pi_lmo_parallel3, CHECK_12, 600);
#ifdef HAVE_INT128_T
CHECK_EQUAL(pi_deleglise_rivat4, pi_lmo_parallel3, CHECK_12, 600);
#endif
CHECK_EQUAL(pi_deleglise_rivat_parallel1, pi_lmo_parallel3, CHECK_22, 900);
CHECK_EQUAL(pi_deleglise_rivat_parallel2, pi_lmo_parallel3, CHECK_22, 900);
CHECK_EQUAL(pi_deleglise_rivat_parallel3, pi_lmo_parallel3, CHECK_22, 900);
#ifdef HAVE_INT128_T
CHECK_EQUAL(pi_deleglise_rivat_parallel4, pi_lmo_parallel3, CHECK_22, 900);
#endif
CHECK_EQUAL(nth_prime, parallel_nth_prime, CHECK_11, 70);
}
catch (runtime_error& e)
{
cerr << endl << e.what() << endl;
return false;
}
cout << "All tests passed successfully!" << endl;
return true;
}
} // namespace primecount
<commit_msg>Do not print status information<commit_after>///
/// @file test.cpp
/// @brief primecount integration tests.
///
/// Copyright (C) 2014 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primecount.hpp>
#include <primecount-internal.hpp>
#include <primesieve.hpp>
#include <ptypes.hpp>
#include <stdint.h>
#include <iostream>
#include <cstdlib>
#include <string>
#include <stdexcept>
#include <sstream>
#include <ctime>
#ifdef _OPENMP
#include <omp.h>
#endif
/// For types: f1(x) , f2(x)
#define CHECK_11(f1, f2) check_equal(#f1, x, f1 (x), f2 (x))
/// For types: f1(x) , f2(x, threads)
#define CHECK_12(f1, f2) check_equal(#f1, x, f1 (x), f2 (x, get_num_threads()))
/// For types: f1(x, threads) , f2(x, threads)
#define CHECK_22(f1, f2) check_equal(#f1, x, f1 (x, get_num_threads()), f2 (x, get_num_threads()))
#define CHECK_EQUAL(f1, f2, check, iters) \
{ \
cout << "Testing " << #f1 << "(x)" << flush; \
\
/* test for 0 <= x < 10000 */ \
for (int64_t x = 0; x < 10000; x++) \
check(f1, f2); \
\
int64_t x = 0; \
/* test using random increment */ \
for (int64_t i = 0; i < iters; i++, x += get_rand()) \
{ \
check(f1, f2); \
double percent = 100.0 * (i + 1.0) / iters; \
cout << "\rTesting " << #f1 "(x) " << (int) percent << "%" << flush; \
} \
\
cout << endl; \
}
using namespace std;
using namespace primecount;
using primesieve::parallel_nth_prime;
namespace {
int get_rand()
{
// 0 <= get_rand() < 10^7
return (rand() % 10000) * 1000 + 1;
}
void check_equal(const string& f1, int64_t x, int64_t res1, int64_t res2)
{
if (res1 != res2)
{
ostringstream oss;
oss << f1 << "(" << x << ") = " << res1
<< " is an error, the correct result is " << res2;
throw runtime_error(oss.str());
}
}
void test_phi_thread_safety(int64_t iters)
{
#ifdef _OPENMP
cout << "Testing phi(x, a)" << flush;
int nested_threads = 2;
int64_t single_thread_sum = 0;
int64_t multi_thread_sum = 0;
int64_t base = 1000000;
omp_set_nested(true);
#pragma omp parallel for reduction(+: multi_thread_sum)
for (int64_t i = 0; i < iters; i++)
multi_thread_sum += pi_legendre(base + i, nested_threads);
omp_set_nested(false);
for (int64_t i = 0; i < iters; i++)
single_thread_sum += pi_legendre(base + i, 1);
if (multi_thread_sum != single_thread_sum)
throw runtime_error("Error: multi-threaded phi(x, a) is broken.");
std::cout << "\rTesting phi(x, a) 100%" << endl;
#endif
}
} // namespace
namespace primecount {
bool test()
{
set_print_status(false);
srand(static_cast<unsigned>(time(0)));
try
{
test_phi_thread_safety(100);
CHECK_EQUAL(pi_legendre, pi_primesieve, CHECK_22, 100);
CHECK_EQUAL(pi_meissel, pi_legendre, CHECK_22, 400);
CHECK_EQUAL(pi_lehmer, pi_meissel, CHECK_22, 400);
CHECK_EQUAL(pi_lehmer2, pi_lehmer, CHECK_22, 200);
CHECK_EQUAL(pi_lmo1, pi_meissel, CHECK_12, 200);
CHECK_EQUAL(pi_lmo2, pi_meissel, CHECK_12, 200);
CHECK_EQUAL(pi_lmo3, pi_meissel, CHECK_12, 300);
CHECK_EQUAL(pi_lmo4, pi_meissel, CHECK_12, 300);
CHECK_EQUAL(pi_lmo5, pi_meissel, CHECK_12, 400);
CHECK_EQUAL(pi_lmo_parallel1, pi_meissel, CHECK_22, 400);
CHECK_EQUAL(pi_lmo_parallel2, pi_meissel, CHECK_22, 400);
CHECK_EQUAL(pi_lmo_parallel3, pi_meissel, CHECK_22, 400);
CHECK_EQUAL(pi_deleglise_rivat1, pi_lmo_parallel3, CHECK_12, 600);
CHECK_EQUAL(pi_deleglise_rivat2, pi_lmo_parallel3, CHECK_12, 600);
CHECK_EQUAL(pi_deleglise_rivat3, pi_lmo_parallel3, CHECK_12, 600);
#ifdef HAVE_INT128_T
CHECK_EQUAL(pi_deleglise_rivat4, pi_lmo_parallel3, CHECK_12, 600);
#endif
CHECK_EQUAL(pi_deleglise_rivat_parallel1, pi_lmo_parallel3, CHECK_22, 900);
CHECK_EQUAL(pi_deleglise_rivat_parallel2, pi_lmo_parallel3, CHECK_22, 900);
CHECK_EQUAL(pi_deleglise_rivat_parallel3, pi_lmo_parallel3, CHECK_22, 900);
#ifdef HAVE_INT128_T
CHECK_EQUAL(pi_deleglise_rivat_parallel4, pi_lmo_parallel3, CHECK_22, 900);
#endif
CHECK_EQUAL(nth_prime, parallel_nth_prime, CHECK_11, 70);
}
catch (runtime_error& e)
{
cerr << endl << e.what() << endl;
return false;
}
cout << "All tests passed successfully!" << endl;
return true;
}
} // namespace primecount
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "txdb.h"
#include "core.h"
#include "pow.h"
#include "uint256.h"
#include <stdint.h>
using namespace std;
void static BatchWriteCoins(CLevelDBBatch &batch, const uint256 &hash, const CCoins &coins) {
if (coins.IsPruned())
batch.Erase(make_pair('c', hash));
else
batch.Write(make_pair('c', hash), coins);
}
void static BatchWriteHashBestChain(CLevelDBBatch &batch, const uint256 &hash) {
batch.Write('B', hash);
}
CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe) {
}
bool CCoinsViewDB::GetCoins(const uint256 &txid, CCoins &coins) {
return db.Read(make_pair('c', txid), coins);
}
bool CCoinsViewDB::SetCoins(const uint256 &txid, const CCoins &coins) {
CLevelDBBatch batch;
BatchWriteCoins(batch, txid, coins);
return db.WriteBatch(batch);
}
bool CCoinsViewDB::HaveCoins(const uint256 &txid) {
return db.Exists(make_pair('c', txid));
}
uint256 CCoinsViewDB::GetBestBlock() {
uint256 hashBestChain;
if (!db.Read('B', hashBestChain))
return uint256(0);
return hashBestChain;
}
bool CCoinsViewDB::SetBestBlock(const uint256 &hashBlock) {
CLevelDBBatch batch;
BatchWriteHashBestChain(batch, hashBlock);
return db.WriteBatch(batch);
}
bool CCoinsViewDB::BatchWrite(const CCoinsMap &mapCoins, const uint256 &hashBlock) {
LogPrint("coindb", "Committing %u changed transactions to coin database...\n", (unsigned int)mapCoins.size());
CLevelDBBatch batch;
for (CCoinsMap::const_iterator it = mapCoins.begin(); it != mapCoins.end(); it++)
BatchWriteCoins(batch, it->first, it->second);
if (hashBlock != uint256(0))
BatchWriteHashBestChain(batch, hashBlock);
return db.WriteBatch(batch);
}
CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CLevelDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) {
}
bool CBlockTreeDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
{
return Write(make_pair('b', blockindex.GetBlockHash()), blockindex);
}
bool CBlockTreeDB::WriteBlockFileInfo(int nFile, const CBlockFileInfo &info) {
return Write(make_pair('f', nFile), info);
}
bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) {
return Read(make_pair('f', nFile), info);
}
bool CBlockTreeDB::WriteLastBlockFile(int nFile) {
return Write('l', nFile);
}
bool CBlockTreeDB::WriteReindexing(bool fReindexing) {
if (fReindexing)
return Write('R', '1');
else
return Erase('R');
}
bool CBlockTreeDB::ReadReindexing(bool &fReindexing) {
fReindexing = Exists('R');
return true;
}
bool CBlockTreeDB::ReadLastBlockFile(int &nFile) {
return Read('l', nFile);
}
bool CCoinsViewDB::GetStats(CCoinsStats &stats) {
leveldb::Iterator *pcursor = db.NewIterator();
pcursor->SeekToFirst();
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
stats.hashBlock = GetBestBlock();
ss << stats.hashBlock;
int64_t nTotalAmount = 0;
while (pcursor->Valid()) {
boost::this_thread::interruption_point();
try {
leveldb::Slice slKey = pcursor->key();
CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
char chType;
ssKey >> chType;
if (chType == 'c') {
leveldb::Slice slValue = pcursor->value();
CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
CCoins coins;
ssValue >> coins;
uint256 txhash;
ssKey >> txhash;
ss << txhash;
ss << VARINT(coins.nVersion);
ss << (coins.fCoinBase ? 'c' : 'n');
ss << VARINT(coins.nHeight);
stats.nTransactions++;
for (unsigned int i=0; i<coins.vout.size(); i++) {
const CTxOut &out = coins.vout[i];
if (!out.IsNull()) {
stats.nTransactionOutputs++;
ss << VARINT(i+1);
ss << out;
nTotalAmount += out.nValue;
}
}
stats.nSerializedSize += 32 + slValue.size();
ss << VARINT(0);
}
pcursor->Next();
} catch (std::exception &e) {
return error("%s : Deserialize or I/O error - %s", __func__, e.what());
}
}
delete pcursor;
stats.nHeight = mapBlockIndex.find(GetBestBlock())->second->nHeight;
stats.hashSerialized = ss.GetHash();
stats.nTotalAmount = nTotalAmount;
return true;
}
bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) {
return Read(make_pair('t', txid), pos);
}
bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) {
CLevelDBBatch batch;
for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++)
batch.Write(make_pair('t', it->first), it->second);
return WriteBatch(batch);
}
bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) {
return Write(std::make_pair('F', name), fValue ? '1' : '0');
}
bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) {
char ch;
if (!Read(std::make_pair('F', name), ch))
return false;
fValue = ch == '1';
return true;
}
bool CBlockTreeDB::LoadBlockIndexGuts()
{
leveldb::Iterator *pcursor = NewIterator();
CDataStream ssKeySet(SER_DISK, CLIENT_VERSION);
ssKeySet << make_pair('b', uint256(0));
pcursor->Seek(ssKeySet.str());
// Load mapBlockIndex
while (pcursor->Valid()) {
boost::this_thread::interruption_point();
try {
leveldb::Slice slKey = pcursor->key();
CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
char chType;
ssKey >> chType;
if (chType == 'b') {
leveldb::Slice slValue = pcursor->value();
CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
CDiskBlockIndex diskindex;
ssValue >> diskindex;
// Construct block index object
CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
pindexNew->nHeight = diskindex.nHeight;
pindexNew->nFile = diskindex.nFile;
pindexNew->nDataPos = diskindex.nDataPos;
pindexNew->nUndoPos = diskindex.nUndoPos;
pindexNew->nVersion = diskindex.nVersion;
pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
pindexNew->nTime = diskindex.nTime;
pindexNew->nBits = diskindex.nBits;
pindexNew->nNonce = diskindex.nNonce;
pindexNew->nStatus = diskindex.nStatus;
pindexNew->nTx = diskindex.nTx;
if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits))
return error("LoadBlockIndex() : CheckProofOfWork failed: %s", pindexNew->ToString());
pcursor->Next();
} else {
break; // if shutdown requested or finished loading block index
}
} catch (std::exception &e) {
return error("%s : Deserialize or I/O error - %s", __func__, e.what());
}
}
delete pcursor;
return true;
}
<commit_msg>Changed LevelDB cursors to use scoped pointers to ensure destruction when going out of scope.<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "txdb.h"
#include "core.h"
#include "pow.h"
#include "uint256.h"
#include <stdint.h>
using namespace std;
void static BatchWriteCoins(CLevelDBBatch &batch, const uint256 &hash, const CCoins &coins) {
if (coins.IsPruned())
batch.Erase(make_pair('c', hash));
else
batch.Write(make_pair('c', hash), coins);
}
void static BatchWriteHashBestChain(CLevelDBBatch &batch, const uint256 &hash) {
batch.Write('B', hash);
}
CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe) {
}
bool CCoinsViewDB::GetCoins(const uint256 &txid, CCoins &coins) {
return db.Read(make_pair('c', txid), coins);
}
bool CCoinsViewDB::SetCoins(const uint256 &txid, const CCoins &coins) {
CLevelDBBatch batch;
BatchWriteCoins(batch, txid, coins);
return db.WriteBatch(batch);
}
bool CCoinsViewDB::HaveCoins(const uint256 &txid) {
return db.Exists(make_pair('c', txid));
}
uint256 CCoinsViewDB::GetBestBlock() {
uint256 hashBestChain;
if (!db.Read('B', hashBestChain))
return uint256(0);
return hashBestChain;
}
bool CCoinsViewDB::SetBestBlock(const uint256 &hashBlock) {
CLevelDBBatch batch;
BatchWriteHashBestChain(batch, hashBlock);
return db.WriteBatch(batch);
}
bool CCoinsViewDB::BatchWrite(const CCoinsMap &mapCoins, const uint256 &hashBlock) {
LogPrint("coindb", "Committing %u changed transactions to coin database...\n", (unsigned int)mapCoins.size());
CLevelDBBatch batch;
for (CCoinsMap::const_iterator it = mapCoins.begin(); it != mapCoins.end(); it++)
BatchWriteCoins(batch, it->first, it->second);
if (hashBlock != uint256(0))
BatchWriteHashBestChain(batch, hashBlock);
return db.WriteBatch(batch);
}
CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CLevelDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) {
}
bool CBlockTreeDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
{
return Write(make_pair('b', blockindex.GetBlockHash()), blockindex);
}
bool CBlockTreeDB::WriteBlockFileInfo(int nFile, const CBlockFileInfo &info) {
return Write(make_pair('f', nFile), info);
}
bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) {
return Read(make_pair('f', nFile), info);
}
bool CBlockTreeDB::WriteLastBlockFile(int nFile) {
return Write('l', nFile);
}
bool CBlockTreeDB::WriteReindexing(bool fReindexing) {
if (fReindexing)
return Write('R', '1');
else
return Erase('R');
}
bool CBlockTreeDB::ReadReindexing(bool &fReindexing) {
fReindexing = Exists('R');
return true;
}
bool CBlockTreeDB::ReadLastBlockFile(int &nFile) {
return Read('l', nFile);
}
bool CCoinsViewDB::GetStats(CCoinsStats &stats) {
boost::scoped_ptr<leveldb::Iterator> pcursor(db.NewIterator());
pcursor->SeekToFirst();
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
stats.hashBlock = GetBestBlock();
ss << stats.hashBlock;
int64_t nTotalAmount = 0;
while (pcursor->Valid()) {
boost::this_thread::interruption_point();
try {
leveldb::Slice slKey = pcursor->key();
CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
char chType;
ssKey >> chType;
if (chType == 'c') {
leveldb::Slice slValue = pcursor->value();
CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
CCoins coins;
ssValue >> coins;
uint256 txhash;
ssKey >> txhash;
ss << txhash;
ss << VARINT(coins.nVersion);
ss << (coins.fCoinBase ? 'c' : 'n');
ss << VARINT(coins.nHeight);
stats.nTransactions++;
for (unsigned int i=0; i<coins.vout.size(); i++) {
const CTxOut &out = coins.vout[i];
if (!out.IsNull()) {
stats.nTransactionOutputs++;
ss << VARINT(i+1);
ss << out;
nTotalAmount += out.nValue;
}
}
stats.nSerializedSize += 32 + slValue.size();
ss << VARINT(0);
}
pcursor->Next();
} catch (std::exception &e) {
return error("%s : Deserialize or I/O error - %s", __func__, e.what());
}
}
stats.nHeight = mapBlockIndex.find(GetBestBlock())->second->nHeight;
stats.hashSerialized = ss.GetHash();
stats.nTotalAmount = nTotalAmount;
return true;
}
bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) {
return Read(make_pair('t', txid), pos);
}
bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) {
CLevelDBBatch batch;
for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++)
batch.Write(make_pair('t', it->first), it->second);
return WriteBatch(batch);
}
bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) {
return Write(std::make_pair('F', name), fValue ? '1' : '0');
}
bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) {
char ch;
if (!Read(std::make_pair('F', name), ch))
return false;
fValue = ch == '1';
return true;
}
bool CBlockTreeDB::LoadBlockIndexGuts()
{
boost::scoped_ptr<leveldb::Iterator> pcursor(NewIterator());
CDataStream ssKeySet(SER_DISK, CLIENT_VERSION);
ssKeySet << make_pair('b', uint256(0));
pcursor->Seek(ssKeySet.str());
// Load mapBlockIndex
while (pcursor->Valid()) {
boost::this_thread::interruption_point();
try {
leveldb::Slice slKey = pcursor->key();
CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
char chType;
ssKey >> chType;
if (chType == 'b') {
leveldb::Slice slValue = pcursor->value();
CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
CDiskBlockIndex diskindex;
ssValue >> diskindex;
// Construct block index object
CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
pindexNew->nHeight = diskindex.nHeight;
pindexNew->nFile = diskindex.nFile;
pindexNew->nDataPos = diskindex.nDataPos;
pindexNew->nUndoPos = diskindex.nUndoPos;
pindexNew->nVersion = diskindex.nVersion;
pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
pindexNew->nTime = diskindex.nTime;
pindexNew->nBits = diskindex.nBits;
pindexNew->nNonce = diskindex.nNonce;
pindexNew->nStatus = diskindex.nStatus;
pindexNew->nTx = diskindex.nTx;
if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits))
return error("LoadBlockIndex() : CheckProofOfWork failed: %s", pindexNew->ToString());
pcursor->Next();
} else {
break; // if shutdown requested or finished loading block index
}
} catch (std::exception &e) {
return error("%s : Deserialize or I/O error - %s", __func__, e.what());
}
}
return true;
}
<|endoftext|> |
<commit_before>/*
* This is part of the FL library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2014 Jan Issac ([email protected])
* Copyright (c) 2014 Manuel Wuthrich ([email protected])
*
* Max-Planck Institute for Intelligent Systems, AMD Lab
* University of Southern California, CLMC Lab
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file t_distribution.hpp
* \date August 2015
* \author Jan Issac ([email protected])
* \author Cristina Garcia Cifuentes ([email protected])
*/
#ifndef FL__DISTRIBUTION__T_DISTRIBUTION_HPP
#define FL__DISTRIBUTION__T_DISTRIBUTION_HPP
#include <Eigen/Dense>
#include <random>
#include <boost/math/distributions.hpp>
#include <fl/util/meta.hpp>
#include <fl/util/types.hpp>
#include <fl/exception/exception.hpp>
#include <fl/distribution/gaussian.hpp>
#include <fl/distribution/chi_squared.hpp>
#include <fl/distribution/interface/evaluation.hpp>
#include <fl/distribution/interface/moments.hpp>
#include <fl/distribution/interface/standard_gaussian_mapping.hpp>
namespace fl
{
/**
* \ingroup distributions
*
* \brief TDistribution represents a multivariate student's t-distribution
* \f$t_\nu(\mu, \Sigma)\f$, where \f$\nu \in \mathbb{R} \f$ is the
* degree-of-freedom, \f$\mu\in \mathbb{R}^n\f$ the distribution location and
* \f$\Sigma \in \mathbb{R}^{n\times n} \f$ the scaling or covariance matrix.
*/
template <typename Variate>
class TDistribution
: public Moments<Variate>,
public Evaluation<Variate>,
public StandardGaussianMapping<
Variate,
JoinSizes<SizeOf<Variate>::Value, 1>::Value>
{
private:
typedef StandardGaussianMapping<
Variate,
JoinSizes<SizeOf<Variate>::Value, 1>::Value
> StdGaussianMappingBase;
public:
/**
* \brief Second moment matrix type, i.e covariance matrix
*/
typedef typename Moments<Variate>::SecondMoment SecondMoment;
/**
* \brief Represents the StandardGaussianMapping standard variate type which
* is of the same dimension as the \c TDistribution \c Variate. The
* StandardVariate type is used to sample from a standard normal
* Gaussian and map it to this \c TDistribution
*/
typedef typename StdGaussianMappingBase::StandardVariate StandardVariate;
public:
/**
* Creates a dynamic or fixed size t-distribution.
*
* \param degrees_of_freedom
* t-distribution degree-of-freedom
* \param dimension Dimension of the distribution. The default is defined by
* the dimension of the variable type \em Vector. If the
* size of the Variate at compile time is fixed, this will
* be adapted. For dynamic-sized Variable the dimension is
* initialized to 0.
*/
explicit TDistribution(Real degrees_of_freedom,
int dim = DimensionOf<Variate>())
: chi2_(degrees_of_freedom),
normal_(dim),
StdGaussianMappingBase(dim + 1)
{
static_assert(Variate::SizeAtCompileTime != 0,
"Illegal static dimension");
normal_.set_standard();
}
/**
* \brief Overridable default destructor
*/
virtual ~TDistribution() { }
/**
* \return a t-distribution sample of the type \c Variate determined by
* mapping a standard normal sample into the t-distribution sample space
*
* \param sample Standard normal sample
*
* \throws See Gaussian<Variate>::map_standard_normal
*/
Variate map_standard_normal(const StandardVariate& sample) const override
{
assert(sample.size() == dimension() + 1);
Real u = chi2_.map_standard_normal(sample.bottomRows(1)(0));
Variate n = normal_.map_standard_normal(sample.topRows(dimension()));
// rvo
Variate v = location() + std::sqrt(degrees_of_freedom() / u) * n;
return v;
}
/**
* \return Log of the probability of the given sample \c variate
*
* Evaluates the t-distribution pdf
*
* \f$ t_\nu(\mu, \Sigma) = \frac{\Gamma\left[(\nu+p)/2\right]}
* {\Gamma(\nu/2)
* \nu^{p/2}\pi^{p/2}
* \left|{\boldsymbol\Sigma}\right|^{1/2}
* \left[1 +
* \frac{1}{\nu}
* ({\mathbf x}-{\boldsymbol\mu})^T
* {\boldsymbol\Sigma}^{-1}
* ({\mathbf x}-{\boldsymbol\mu})\right]^{(\nu+p)/2}} \f$
*
* at location \f${\mathbf x}\f$
*
*
* \param variate sample which should be evaluated
*
* \throws See Gaussian<Variate>::has_full_rank()
*/
Real log_probability(const Variate& x) const override
{
return cached_log_pdf_.log_probability(*this, x);
}
/**
* \return Gaussian dimension
*/
virtual constexpr int dimension() const
{
return normal_.dimension();
}
/**
* \return t-distribution location
*/
const Variate& mean() const override
{
return location();
}
/**
* \return t-distribution scaling matrix
*
* \throws See Gaussian<Variate>::covariance()
*/
const SecondMoment& covariance() const override
{
return normal_.covariance();
}
/**
* \return t-distribution location
*/
virtual const Variate& location() const
{
return normal_.mean();
}
/**
* \return t-distribution degree-of-freedom
*/
virtual Real degrees_of_freedom() const
{
return chi2_.degrees_of_freedom();
}
/**
* Changes the dimension of the dynamic-size t-distribution and sets it to a
* standard distribution with zero mean and identity covariance.
*
* \param new_dimension New dimension of the t-distribution
*
* \throws ResizingFixedSizeEntityException
* see standard_variate_dimension(int)
*/
virtual void dimension(int new_dimension)
{
StdGaussianMappingBase::standard_variate_dimension(new_dimension + 1);
normal_.dimension(new_dimension);
cached_log_pdf_.flag_dirty();
}
/**
* Sets the distribution location
*
* \param location New t-distribution mean
*
* \throws WrongSizeException
*/
virtual void location(const Variate& new_location) noexcept
{
normal_.mean(new_location);
cached_log_pdf_.flag_dirty();
}
/**
* Sets the covariance matrix
* \param covariance New covariance matrix
*
* \throws WrongSizeException
*/
virtual void scaling_matrix(const SecondMoment& scaling_matrix)
{
normal_.covariance(scaling_matrix);
cached_log_pdf_.flag_dirty();
}
/**
* Sets t-distribution degree-of-freedom
*/
virtual void degrees_of_freedom(Real dof) const
{
chi2_.degrees_of_freedom(dof);
cached_log_pdf_.flag_dirty();
}
protected:
/** \cond internal */
ChiSquared chi2_;
Gaussian<Variate> normal_;
/** \endcond */
private:
CachedLogPdf cached_log_pdf_;
private:
class CachedLogPdf
{
public:
CachedLogPdf()
: dirty_(true)
{ }
/**
* Evaluates the t-distribution pdf at a given position \c x
*/
Real log_probability(
const TDistribution<Variate>& t_distr, const Variate& x)
{
if (dirty_) update(t_distr);
Variate z = x - location();
Real dof = t_distr.degrees_of_freedom();
Real quad_term = (z.transpose() * t_distr.normal_.precision() * z);
Real ln_term = std::log(Real(1) + quad_term / dof);
return const_term_ - const_factor_ * ln_term;
}
void flag_dirty() { dirty_ = true; }
private:
void update(const TDistribution<Variate>& t_distr)
{
Real half = Real(1)/Real(2);
Real dim = t_distr.dimension();
Real dof = t_distr.degrees_of_freedom();
const_term_ =
boost::lgamma(half * (dof + dim))
- boost::lgamma(half * dof)
- half * (dim * std::log(M_PI * dof))
- half * (std::log(t_distr.normal_.determinant()));
const_factor_ = half * (dof + dim);
dirty_ = false;
}
bool dirty_;
Real const_factor_;
Real const_term_;
};
friend class CachedLogPdf;
};
}
#endif
<commit_msg>Updated TDistribution<commit_after>/*
* This is part of the FL library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2014 Jan Issac ([email protected])
* Copyright (c) 2014 Manuel Wuthrich ([email protected])
*
* Max-Planck Institute for Intelligent Systems, AMD Lab
* University of Southern California, CLMC Lab
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file t_distribution.hpp
* \date August 2015
* \author Jan Issac ([email protected])
* \author Cristina Garcia Cifuentes ([email protected])
*/
#ifndef FL__DISTRIBUTION__T_DISTRIBUTION_HPP
#define FL__DISTRIBUTION__T_DISTRIBUTION_HPP
#include <Eigen/Dense>
#include <random>
#include <boost/math/distributions.hpp>
#include <fl/util/meta.hpp>
#include <fl/util/types.hpp>
#include <fl/exception/exception.hpp>
#include <fl/distribution/gaussian.hpp>
#include <fl/distribution/chi_squared.hpp>
#include <fl/distribution/interface/evaluation.hpp>
#include <fl/distribution/interface/moments.hpp>
#include <fl/distribution/interface/standard_gaussian_mapping.hpp>
namespace fl
{
/**
* \ingroup distributions
*
* \brief TDistribution represents a multivariate student's t-distribution
* \f$t_\nu(\mu, \Sigma)\f$, where \f$\nu \in \mathbb{R} \f$ is the
* degree-of-freedom, \f$\mu\in \mathbb{R}^n\f$ the distribution location and
* \f$\Sigma \in \mathbb{R}^{n\times n} \f$ the scaling or covariance matrix.
*/
template <typename Variate>
class TDistribution
: public Moments<Variate>,
public Evaluation<Variate>,
public StandardGaussianMapping<
Variate,
JoinSizes<SizeOf<Variate>::Value, 1>::Value>
{
private:
typedef StandardGaussianMapping<
Variate,
JoinSizes<SizeOf<Variate>::Value, 1>::Value
> StdGaussianMappingBase;
public:
/**
* \brief Second moment matrix type, i.e covariance matrix
*/
typedef typename Moments<Variate>::SecondMoment SecondMoment;
/**
* \brief Represents the StandardGaussianMapping standard variate type which
* is of the same dimension as the \c TDistribution \c Variate. The
* StandardVariate type is used to sample from a standard normal
* Gaussian and map it to this \c TDistribution
*/
typedef typename StdGaussianMappingBase::StandardVariate StandardVariate;
public:
/**
* Creates a dynamic or fixed size t-distribution.
*
* \param degrees_of_freedom
* t-distribution degree-of-freedom
* \param dimension Dimension of the distribution. The default is defined by
* the dimension of the variable type \em Vector. If the
* size of the Variate at compile time is fixed, this will
* be adapted. For dynamic-sized Variable the dimension is
* initialized to 0.
*/
explicit TDistribution(Real degrees_of_freedom,
int dim = DimensionOf<Variate>())
: StdGaussianMappingBase(dim + 1),
chi2_(degrees_of_freedom),
normal_(dim)
{
static_assert(Variate::SizeAtCompileTime != 0,
"Illegal static dimension");
normal_.set_standard();
}
/**
* \brief Overridable default destructor
*/
virtual ~TDistribution() { }
/**
* \return a t-distribution sample of the type \c Variate determined by
* mapping a standard normal sample into the t-distribution sample space
*
* \param sample Standard normal sample
*
* \throws See Gaussian<Variate>::map_standard_normal
*/
Variate map_standard_normal(const StandardVariate& sample) const override
{
assert(sample.size() == dimension() + 1);
Real u = chi2_.map_standard_normal(sample.bottomRows(1)(0));
Variate n = normal_.map_standard_normal(sample.topRows(dimension()));
// rvo
Variate v = location() + std::sqrt(degrees_of_freedom() / u) * n;
return v;
}
/**
* \return Log of the probability of the given sample \c variate
*
* Evaluates the t-distribution pdf
*
* \f$ t_\nu(\mu, \Sigma) = \frac{\Gamma\left[(\nu+p)/2\right]}
* {\Gamma(\nu/2)
* \nu^{p/2}\pi^{p/2}
* \left|{\boldsymbol\Sigma}\right|^{1/2}
* \left[1 +
* \frac{1}{\nu}
* ({\mathbf x}-{\boldsymbol\mu})^T
* {\boldsymbol\Sigma}^{-1}
* ({\mathbf x}-{\boldsymbol\mu})\right]^{(\nu+p)/2}} \f$
*
* at location \f${\mathbf x}\f$
*
*
* \param variate sample which should be evaluated
*
* \throws See Gaussian<Variate>::has_full_rank()
*/
Real log_probability(const Variate& x) const override
{
return cached_log_pdf_.log_probability(*this, x);
}
/**
* \return Gaussian dimension
*/
virtual constexpr int dimension() const
{
return normal_.dimension();
}
/**
* \return t-distribution location
*/
const Variate& mean() const override
{
return location();
}
/**
* \return t-distribution scaling matrix
*
* \throws See Gaussian<Variate>::covariance()
*/
const SecondMoment& covariance() const override
{
return normal_.covariance();
}
/**
* \return t-distribution location
*/
virtual const Variate& location() const
{
return normal_.mean();
}
/**
* \return t-distribution degree-of-freedom
*/
virtual Real degrees_of_freedom() const
{
return chi2_.degrees_of_freedom();
}
/**
* Changes the dimension of the dynamic-size t-distribution and sets it to a
* standard distribution with zero mean and identity covariance.
*
* \param new_dimension New dimension of the t-distribution
*
* \throws ResizingFixedSizeEntityException
* see standard_variate_dimension(int)
*/
virtual void dimension(int new_dimension)
{
StdGaussianMappingBase::standard_variate_dimension(new_dimension + 1);
normal_.dimension(new_dimension);
cached_log_pdf_.flag_dirty();
}
/**
* Sets the distribution location
*
* \param location New t-distribution mean
*
* \throws WrongSizeException
*/
virtual void location(const Variate& new_location) noexcept
{
normal_.mean(new_location);
cached_log_pdf_.flag_dirty();
}
/**
* Sets the covariance matrix
* \param covariance New covariance matrix
*
* \throws WrongSizeException
*/
virtual void scaling_matrix(const SecondMoment& scaling_matrix)
{
normal_.covariance(scaling_matrix);
cached_log_pdf_.flag_dirty();
}
/**
* Sets t-distribution degree-of-freedom
*/
virtual void degrees_of_freedom(Real dof)
{
chi2_.degrees_of_freedom(dof);
cached_log_pdf_.flag_dirty();
}
protected:
/** \cond internal */
ChiSquared chi2_;
Gaussian<Variate> normal_;
/** \endcond */
private:
class CachedLogPdf
{
public:
CachedLogPdf()
: dirty_(true)
{ }
/**
* Evaluates the t-distribution pdf at a given position \c x
*/
Real log_probability(
const TDistribution<Variate>& t_distr, const Variate& x)
{
if (dirty_) update(t_distr);
Variate z = x - t_distr.location();
Real dof = t_distr.degrees_of_freedom();
Real quad_term = (z.transpose() * t_distr.normal_.precision() * z);
Real ln_term = std::log(Real(1) + quad_term / dof);
return const_term_ - const_factor_ * ln_term;
}
void flag_dirty() { dirty_ = true; }
private:
void update(const TDistribution<Variate>& t_distr)
{
Real half = Real(1)/Real(2);
Real dim = t_distr.dimension();
Real dof = t_distr.degrees_of_freedom();
const_term_ =
boost::math::lgamma(half * (dof + dim))
- boost::math::lgamma(half * dof)
- half * (dim * std::log(M_PI * dof))
- half * (std::log(t_distr.normal_.covariance_determinant()));
const_factor_ = half * (dof + dim);
dirty_ = false;
}
bool dirty_;
Real const_factor_;
Real const_term_;
};
friend class CachedLogPdf;
mutable CachedLogPdf cached_log_pdf_;
};
}
#endif
<|endoftext|> |
<commit_before>#ifndef KGR_KANGARU_INCLUDE_KANGARU_DETAIL_AUTOWIRE_TRAITS_HPP
#define KGR_KANGARU_INCLUDE_KANGARU_DETAIL_AUTOWIRE_TRAITS_HPP
#include "traits.hpp"
#include "container_service.hpp"
#include "service_map.hpp"
#include "injected.hpp"
#include "../container.hpp"
namespace kgr {
template<typename, typename>
struct service;
namespace detail {
/*
* This class is an object convertible to any mapped service.
* Upon conversion, it calls the container to get that service.
*
* Primarely used for autowire services in constructors.
*/
template<typename For, typename Map>
struct deducer {
explicit deducer(container& c) noexcept : _container{&c} {}
template<typename T, enable_if_t<
!std::is_base_of<For, mapped_service_t<T, Map>>::value &&
!std::is_base_of<mapped_service_t<T, Map>, For>::value &&
!std::is_reference<service_type<mapped_service_t<T, Map>>>::value, int> = 0>
operator T () {
return _container->service<mapped_service_t<T, Map>>();
}
template<typename T, enable_if_t<
!std::is_base_of<For, mapped_service_t<T&, Map>>::value &&
!std::is_base_of<mapped_service_t<T&, Map>, For>::value &&
std::is_lvalue_reference<service_type<mapped_service_t<T&, Map>>>::value, int> = 0>
operator T& () const {
return _container->service<mapped_service_t<T&, Map>>();
}
template<typename T, enable_if_t<
!std::is_base_of<For, mapped_service_t<T&&, Map>>::value &&
!std::is_base_of<mapped_service_t<T&&, Map>, For>::value &&
std::is_rvalue_reference<service_type<mapped_service_t<T&&, Map>>>::value, int> = 0>
operator T&& () const {
return _container->service<mapped_service_t<T&&, Map>>();
}
private:
container* _container;
};
/*
* Alias that simply add a std::size_t parameter so it can be expanded using a sequence.
*/
template<typename For, typename Map, std::size_t>
using deducer_expand_t = deducer<For, Map>;
/*
* Trait that check if a service is constructible using `n` amount of deducers.
*/
template<typename, typename, typename, std::size_t n, typename, typename = typename seq_gen<n>::type, typename = void>
struct is_deductible_from_amount_helper : std::false_type {};
/*
* Specialization of amount_of_deductible_service_helper that exists when a callable constructor is found.
* It also returns the injected result of the construct function (assuming a basic construct function)
*/
template<typename Service, typename T, typename Map, typename... Args, std::size_t... S, std::size_t n>
struct is_deductible_from_amount_helper<Service, T, Map, n, meta_list<Args...>, seq<S...>, enable_if_t<is_someway_constructible<T, deducer_expand_t<Service, Map, S>..., Args...>::value>> : std::true_type {
using default_result_t = inject_result<deducer_expand_t<Service, Map, S>..., Args...>;
};
/*
* Trait that tries to find the amount of deducer required.
* Iterate from 0 to max deducers
*/
template<typename, typename, typename, typename, std::size_t, typename = void>
struct amount_of_deductible_service_helper {
static constexpr bool deductible = false;
static constexpr seq<> amount = {};
using default_result_t = inject_result<>;
};
/*
* Specialization of amount_of_deductible_service used when the service is constructible using the amount `n`
*/
template<typename S, typename T, typename Map, typename... Args, std::size_t n>
struct amount_of_deductible_service_helper<S, T, Map, meta_list<Args...>, n, enable_if_t<is_deductible_from_amount_helper<S, T, Map, n, meta_list<Args...>>::value>> {
static constexpr bool deductible = true;
static constexpr typename seq_gen<n>::type amount = {};
using default_result_t = typename is_deductible_from_amount_helper<S, T, Map, n, meta_list<Args...>>::default_result_t;
};
/*
* Specialization of amount_of_deductible_service_helper used when the service is not constructible with `n` deducer
* Tries the next iteration.
*/
template<typename S, typename T, typename Map, typename... Args, std::size_t n>
struct amount_of_deductible_service_helper<S, T, Map, meta_list<Args...>, n, enable_if_t<!is_deductible_from_amount_helper<S, T, Map, n, meta_list<Args...>>::value && (n != 0)>> :
amount_of_deductible_service_helper<S, T, Map, meta_list<Args...>, n - 1> {};
/*
* The default maximum amount of deducer sent to the construct function when autowiring.
* Tells how many autowired dependencies a service can have by default.
*/
constexpr std::size_t default_max_dependency = 8;
/*
* Alias to amount_of_deductible_service_helper to ease usage
*/
template<typename S, typename T, typename Map, std::size_t max, typename... Args>
using amount_of_deductible_service = detail::amount_of_deductible_service_helper<S, T, Map, detail::meta_list<Args...>, max>;
/*
* A class used for indirect mapping and tranmitting information about autowiring.
*/
template<template<typename, typename> class, template<typename> class, typename, std::size_t>
struct autowire_map;
template<template<typename, typename> class service_type, template<typename> class get_service, typename... Maps, std::size_t max_dependencies>
struct autowire_map<service_type, get_service, kgr::map<Maps...>, max_dependencies> {
template<typename T>
using mapped_service = service_type<detected_t<get_service, T>, autowire_map<service, decay_t, kgr::map<Maps...>, max_dependencies>>;
};
/*
* The default injection function. Will call kgr::inject with all arguments.
*/
struct default_inject_function_t {
template<typename... Args>
constexpr auto operator()(Args&&... args) const -> inject_result<Args...> {
return inject(std::forward<Args>(args)...);
}
}
constexpr default_inject_function{};
/*
* A construct function usable by many service definition implementation.
* Will send as many deducers as there are numbers in S
*/
template<typename Self, typename Map, typename I, std::size_t... S, typename... Args>
inline auto deduce_construct(detail::seq<S...>, I inject, inject_t<container_service> cont, Args&&... args) -> detail::call_result_t<I, detail::deducer_expand_t<Self, Map, S>..., Args...> {
auto& container = cont.forward();
// The expansion of the inject call may be empty. This will silence the warning.
static_cast<void>(container);
return inject((void(S), detail::deducer<Self, Map>{container})..., std::forward<Args>(args)...);
}
/*
* A shortcut for deduce_construct with the default injection function.
*/
template<typename Self, typename Map, std::size_t... S, typename... Args>
inline auto deduce_construct_default(detail::seq<S...> s, inject_t<container_service> cont, Args&&... args) -> detail::call_result_t<default_inject_function_t, detail::deducer_expand_t<Self, Map, S>..., Args...> {
return deduce_construct<Self, Map>(s, default_inject_function, std::move(cont), std::forward<Args>(args)...);
}
/*
* Tag that replaces dependencies in a service defintion. Carries all information on how to autowire.
*/
template<typename Map = map<>, std::size_t max_dependencies = detail::default_max_dependency>
using autowire_tag = detail::autowire_map<service, decay_t, Map, max_dependencies>;
} // namespace detail
} // namespace sbg
#endif
<commit_msg>Fix error detection and cycle detection with autowire<commit_after>#ifndef KGR_KANGARU_INCLUDE_KANGARU_DETAIL_AUTOWIRE_TRAITS_HPP
#define KGR_KANGARU_INCLUDE_KANGARU_DETAIL_AUTOWIRE_TRAITS_HPP
#include "traits.hpp"
#include "container_service.hpp"
#include "service_map.hpp"
#include "injected.hpp"
#include "../container.hpp"
namespace kgr {
template<typename, typename>
struct service;
namespace detail {
template<typename Service1, typename Service2>
using is_different_service = bool_constant<
!std::is_base_of<Service1, Service2>::value &&
!std::is_base_of<Service2, Service1>::value
>;
/*
* This class is an object convertible to any mapped service.
* Upon conversion, it calls the container to get that service.
*
* Primarely used for autowire services in constructors.
*/
template<typename For, typename Map>
struct deducer {
explicit deducer(container& c) noexcept : _container{&c} {}
template<typename T, enable_if_t<
is_different_service<For, mapped_service_t<T, Map>>::value &&
is_service_valid<mapped_service_t<T, Map>>::value &&
!std::is_reference<service_type<mapped_service_t<T, Map>>>::value, int> = 0>
operator T () {
return _container->service<mapped_service_t<T, Map>>();
}
template<typename T, enable_if_t<
is_different_service<For, mapped_service_t<T&, Map>>::value &&
is_service_valid<mapped_service_t<T&, Map>>::value &&
std::is_lvalue_reference<service_type<mapped_service_t<T&, Map>>>::value, int> = 0>
operator T& () const {
return _container->service<mapped_service_t<T&, Map>>();
}
template<typename T, enable_if_t<
is_different_service<For, mapped_service_t<T&&, Map>>::value &&
is_service_valid<mapped_service_t<T&&, Map>>::value &&
std::is_rvalue_reference<service_type<mapped_service_t<T&&, Map>>>::value, int> = 0>
operator T&& () const {
return _container->service<mapped_service_t<T&&, Map>>();
}
private:
container* _container;
};
template<typename For, typename Map>
struct weak_deducer {
template<typename T, enable_if_t<
is_different_service<For, mapped_service_t<T, Map>>::value &&
!std::is_reference<service_type<mapped_service_t<T, Map>>>::value, int> = 0>
operator T ();
template<typename T, enable_if_t<
is_different_service<For, mapped_service_t<T&, Map>>::value &&
std::is_lvalue_reference<service_type<mapped_service_t<T&, Map>>>::value, int> = 0>
operator T& () const;
template<typename T, enable_if_t<
is_different_service<For, mapped_service_t<T&&, Map>>::value &&
std::is_rvalue_reference<service_type<mapped_service_t<T&&, Map>>>::value, int> = 0>
operator T&& () const;
};
/*
* Alias that simply add a std::size_t parameter so it can be expanded using a sequence.
*/
template<typename For, typename Map, std::size_t>
using deducer_expand_t = deducer<For, Map>;
/*
* Alias that simply add a std::size_t parameter so it can be expanded using a sequence.
*/
template<typename For, typename Map, std::size_t>
using weak_deducer_expand_t = weak_deducer<For, Map>;
/*
* Trait that check if a service is constructible using `n` amount of deducers.
*/
template<typename, typename, typename, std::size_t n, typename, typename = typename seq_gen<n>::type, typename = void>
struct is_deductible_from_amount_helper : std::false_type {};
/*
* Specialization of amount_of_deductible_service_helper that exists when a callable constructor is found.
* It also returns the injected result of the construct function (assuming a basic construct function)
*/
template<typename Service, typename T, typename Map, typename... Args, std::size_t... S, std::size_t n>
struct is_deductible_from_amount_helper<Service, T, Map, n, meta_list<Args...>, seq<S...>, enable_if_t<is_someway_constructible<T, weak_deducer_expand_t<Service, Map, S>..., Args...>::value>> : std::true_type {
using default_result_t = inject_result<deducer_expand_t<Service, Map, S>..., Args...>;
};
/*
* Trait that tries to find the amount of deducer required.
* Iterate from 0 to max deducers
*/
template<typename, typename, typename, typename, std::size_t, typename = void>
struct amount_of_deductible_service_helper {
static constexpr bool deductible = false;
static constexpr seq<> amount = {};
using default_result_t = inject_result<>;
};
/*
* Specialization of amount_of_deductible_service used when the service is constructible using the amount `n`
*/
template<typename S, typename T, typename Map, typename... Args, std::size_t n>
struct amount_of_deductible_service_helper<S, T, Map, meta_list<Args...>, n, enable_if_t<is_deductible_from_amount_helper<S, T, Map, n, meta_list<Args...>>::value>> {
static constexpr bool deductible = true;
static constexpr typename seq_gen<n>::type amount = {};
using default_result_t = typename is_deductible_from_amount_helper<S, T, Map, n, meta_list<Args...>>::default_result_t;
};
/*
* Specialization of amount_of_deductible_service_helper used when the service is not constructible with `n` deducer
* Tries the next iteration.
*/
template<typename S, typename T, typename Map, typename... Args, std::size_t n>
struct amount_of_deductible_service_helper<S, T, Map, meta_list<Args...>, n, enable_if_t<!is_deductible_from_amount_helper<S, T, Map, n, meta_list<Args...>>::value && (n != 0)>> :
amount_of_deductible_service_helper<S, T, Map, meta_list<Args...>, n - 1> {};
/*
* The default maximum amount of deducer sent to the construct function when autowiring.
* Tells how many autowired dependencies a service can have by default.
*/
constexpr std::size_t default_max_dependency = 8;
/*
* Alias to amount_of_deductible_service_helper to ease usage
*/
template<typename S, typename T, typename Map, std::size_t max, typename... Args>
using amount_of_deductible_service = detail::amount_of_deductible_service_helper<S, T, Map, detail::meta_list<Args...>, max>;
/*
* A class used for indirect mapping and tranmitting information about autowiring.
*/
template<template<typename, typename> class, template<typename> class, typename, std::size_t>
struct autowire_map;
template<template<typename, typename> class service_type, template<typename> class get_service, typename... Maps, std::size_t max_dependencies>
struct autowire_map<service_type, get_service, kgr::map<Maps...>, max_dependencies> {
template<typename T>
using mapped_service = service_type<detected_t<get_service, T>, autowire_map<service, decay_t, kgr::map<Maps...>, max_dependencies>>;
};
/*
* The default injection function. Will call kgr::inject with all arguments.
*/
struct default_inject_function_t {
template<typename... Args>
constexpr auto operator()(Args&&... args) const -> inject_result<Args...> {
return inject(std::forward<Args>(args)...);
}
}
constexpr default_inject_function{};
/*
* A construct function usable by many service definition implementation.
* Will send as many deducers as there are numbers in S
*/
template<typename Self, typename Map, typename I, std::size_t... S, typename... Args>
inline auto deduce_construct(detail::seq<S...>, I inject, inject_t<container_service> cont, Args&&... args) -> detail::call_result_t<I, detail::deducer_expand_t<Self, Map, S>..., Args...> {
auto& container = cont.forward();
// The expansion of the inject call may be empty. This will silence the warning.
static_cast<void>(container);
return inject((void(S), detail::deducer<Self, Map>{container})..., std::forward<Args>(args)...);
}
/*
* A shortcut for deduce_construct with the default injection function.
*/
template<typename Self, typename Map, std::size_t... S, typename... Args>
inline auto deduce_construct_default(detail::seq<S...> s, inject_t<container_service> cont, Args&&... args) -> detail::call_result_t<default_inject_function_t, detail::deducer_expand_t<Self, Map, S>..., Args...> {
return deduce_construct<Self, Map>(s, default_inject_function, std::move(cont), std::forward<Args>(args)...);
}
/*
* Tag that replaces dependencies in a service defintion. Carries all information on how to autowire.
*/
template<typename Map = map<>, std::size_t max_dependencies = detail::default_max_dependency>
using autowire_tag = detail::autowire_map<service, decay_t, Map, max_dependencies>;
} // namespace detail
} // namespace sbg
#endif
<|endoftext|> |
<commit_before>#ifndef KGR_KANGARU_INCLUDE_KANGARU_DETAIL_OVERRIDE_TRAITS_HPP
#define KGR_KANGARU_INCLUDE_KANGARU_DETAIL_OVERRIDE_TRAITS_HPP
#include "traits.hpp"
#include "meta_list.hpp"
#include "detection.hpp"
namespace kgr {
namespace detail {
/*
* Trait that check if all types specified in overrides are services
*/
template<typename T>
using is_override_services = all_of_traits<parent_types<T>, is_service>;
/*
* Trait that check if the service type returned by
* one override's service definitions can be converted to the service type of the service T definition.
*/
template<typename Parent, typename T>
using is_one_override_convertible = is_explicitly_convertible<service_type<T>, detected_t<service_type, Parent>>;
/*
* Trait that check if the service type returned by
* all overriden service definitions can be converted to the service type of the service T definition.
*/
template<typename T>
using is_override_convertible = all_of_traits<parent_types<T>, is_one_override_convertible, T>;
/*
* Trait that check if all overriden services are polymorphic
*/
template<typename T>
using is_override_polymorphic = all_of_traits<parent_types<T>, is_polymorphic>;
/*
* Trait that check if no overriden services are final
*/
template<typename T>
using is_override_not_final = all_of_traits<parent_types<T>, is_not_final_service>;
/*
* Trait that check if the default service of an abstract service overrides that abstract service
*/
template<typename T>
using is_default_overrides_abstract = bool_constant<
!has_default<T>::value || is_overriden_by<T, detected_t<default_type, T>>::value
>;
/*
* Trait that check if the default service type is convertible to the abstract service type.
*/
template<typename T>
using is_default_convertible = bool_constant<
!has_default<T>::value || is_explicitly_convertible<
detected_t<service_type, detected_t<default_type, T>>,
detected_t<service_type, T>
>::value
>;
} // namespace detail
} // namespace kgr
#endif // KGR_KANGARU_INCLUDE_KANGARU_DETAIL_OVERRIDE_TRAITS_HPP
<commit_msg>Make the new override traits work under visual studio 2015<commit_after>#ifndef KGR_KANGARU_INCLUDE_KANGARU_DETAIL_OVERRIDE_TRAITS_HPP
#define KGR_KANGARU_INCLUDE_KANGARU_DETAIL_OVERRIDE_TRAITS_HPP
#include "traits.hpp"
#include "meta_list.hpp"
#include "detection.hpp"
namespace kgr {
namespace detail {
/*
* Trait that check if all types specified in overrides are services
*/
template<typename T>
using is_override_services = all_of_traits<parent_types<T>, is_service>;
/*
* Trait that check if the service type returned by
* one override's service definitions can be converted to the service type of the service T definition.
*/
template<typename Parent, typename T>
using is_one_override_convertible = is_explicitly_convertible<detected_t<service_type, T>, detected_t<service_type, Parent>>;
/*
* Trait that check if the service type returned by
* all overriden service definitions can be converted to the service type of the service T definition.
*/
template<typename T>
using is_override_convertible = all_of_traits<parent_types<T>, is_one_override_convertible, T>;
/*
* Trait that check if all overriden services are polymorphic
*/
template<typename T>
using is_override_polymorphic = all_of_traits<parent_types<T>, is_polymorphic>;
/*
* Trait that check if no overriden services are final
*/
template<typename T>
using is_override_not_final = all_of_traits<parent_types<T>, is_not_final_service>;
/*
* Trait that check if the default service of an abstract service overrides that abstract service
*/
template<typename T>
using is_default_overrides_abstract = bool_constant<
!has_default<T>::value || is_overriden_by<T, detected_t<default_type, T>>::value
>;
/*
* Trait that check if the default service type is convertible to the abstract service type.
*/
template<typename T>
using is_default_convertible = bool_constant<
!has_default<T>::value || is_explicitly_convertible<
detected_t<service_type, detected_t<default_type, T>>,
detected_t<service_type, T>
>::value
>;
} // namespace detail
} // namespace kgr
#endif // KGR_KANGARU_INCLUDE_KANGARU_DETAIL_OVERRIDE_TRAITS_HPP
<|endoftext|> |
<commit_before>// Copyright 2010-2013 RethinkDB, all rights reserved.
#include <map>
#include <stdexcept>
#include <string>
#include <vector>
namespace options {
struct parse_error_t : public std::runtime_error {
parse_error_t(const std::string &msg) : std::runtime_error(msg) { }
};
struct validation_error_t : public std::runtime_error {
validation_error_t(const std::string &msg) : std::runtime_error(msg) { }
};
struct file_parse_error_t : public std::runtime_error {
file_parse_error_t(const std::string &msg) : std::runtime_error(msg) { }
};
// Represents an option's names. Be sure to include dashes! Usage:
//
// names_t("--max-foobars") // An option name.
// names_t("--cores", "-c") // An option name with an abbreviation
class names_t {
public:
// Include dashes. For example, name might be "--blah".
explicit names_t(std::string name) {
names.push_back(name);
}
// Include the right amount of dashes. For example, official_name might
// be "--help", and other_name might be "-h".
names_t(std::string official_name, std::string other_name) {
names.push_back(official_name);
names.push_back(other_name);
}
private:
friend class option_t;
std::vector<std::string> names;
};
// Pass one of these to the option_t construct to tell what kind of argument you have.
enum appearance_t {
// A mandatory argument that can be passed once.
MANDATORY,
// A mandatory argument that may be repeated.
MANDATORY_REPEAT,
// An optional argument, that may be passed zero or one times.
OPTIONAL,
// An optional argument, that may be repeated.
OPTIONAL_REPEAT,
// An optional argument that doesn't take a parameter. Useful for "--help".
OPTIONAL_NO_PARAMETER
};
// A command line option with a name, specification of how many times it may appear, and whether it
// takes a parameter.
//
// Examples:
// // An option that may be used at most once, with no parameter.
// option_t(names_t("--help", "-h"), OPTIONAL_NO_PARAMETER)
// // An option that may be used at most once, with a default value. The user
// // could pass --cores 3 or -c 3, but not a naked -c.
// option_t(names_t("--cores", "-c"), OPTIONAL, strprintf("%d", get_cpu_count()));
// // An option that must appear one or more times.
// option_t(names_t("--join", "-j"), MANDATORY_REPEAT)
class option_t {
public:
// Creates an option with the appropriate name and appearance specifier,
// with a default value being the empty vector.
explicit option_t(names_t names, appearance_t appearance);
// Creates an option with the appropriate name and appearance specifier,
// with the default value being a vector of size 1. OPTIONAL and
// OPTIONAL_REPEAT are the only valid appearance specifiers.
explicit option_t(names_t names, appearance_t appearance, std::string default_value);
private:
friend std::map<std::string, std::vector<std::string> > default_values_map(const std::vector<option_t> &options);
friend std::map<std::string, std::vector<std::string> > do_parse_command_line(
const int argc, const char *const *const argv, const std::vector<option_t> &options,
std::vector<std::string> *const unrecognized_out);
friend const option_t *find_option(const char *const option_name, const std::vector<option_t> &options);
friend void verify_option_counts(const std::vector<option_t> &options,
const std::map<std::string, std::vector<std::string> > &names_by_values);
// Names for the option, e.g. "-j", "--join"
std::vector<std::string> names;
// How many times must the option appear? If an option appears zero times,
// and if min_appearances is zero, then `default_values` will be used as the
// value-list of the option. Typical combinations of (min_appearances,
// max_appearances) are (0, 1) (with a default_value), (0, SIZE_MAX) (with or
// without a default value), (1, 1) (for mandatory options), (1, SIZE_MAX)
// (for mandatory options with repetition).
//
// It must be the case that 0 <= min_appearances <= max_appearances <=
// SIZE_MAX.
size_t min_appearances;
size_t max_appearances;
// True if an option doesn't take a parameter. For example, "--help" would
// take no parameter.
bool no_parameter;
// The value(s) to use if no appearances of the command line option are
// available. This is only relevant if min_appearances == 0.
std::vector<std::string> default_values;
};
// Parses options from a command line into a return value. Uses empty-string parameter values for
// appearances of OPTIONAL_NO_PARAMETER options. Uses the *official name* of the option (the first
// parameter passed to names_t) for map keys. Does not do any verification that we have the right
// number of option values. (That only happens in `verify_option_counts`.)
std::map<std::string, std::vector<std::string> > parse_command_line(int argc, const char *const *argv, const std::vector<option_t> &options);
// Like `parse_command_line`, except that it tolerates unrecognized options, instead of throwing.
// Out-of-place positional parameters and unrecognized options are output to `*unrecognized_out`, in
// the same order that they appeared in the options list. This can lead to some weird situations,
// if you passed "--recognized-foo 3 --unrecognized --recognized-bar 4 5" on the command line. You
// would get ["--unrecognized", "5"] in `*unrecognized_out`.
std::map<std::string, std::vector<std::string> > parse_command_line_and_collect_unrecognized(
int argc, const char *const *argv, const std::vector<option_t> &options,
std::vector<std::string> *unrecognized_out);
// Merges option values from two different sources together, with higher precedence going to the
// left-hand argument. Example usage:
//
// opts = merge(command_line_values, config_file_values);
std::map<std::string, std::vector<std::string> > merge(
const std::map<std::string, std::vector<std::string> > &high_precedence_values,
const std::map<std::string, std::vector<std::string> > &low_precedence_values);
// Verifies that given options build the right amount of times. This is separate from option
// parsing because we need to accumulate options from both the command line and config file.
void verify_option_counts(const std::vector<option_t> &options,
const std::map<std::string, std::vector<std::string> > &names_by_values);
// Constructs a map of default option values.
std::map<std::string, std::vector<std::string> > default_values_map(const std::vector<option_t> &options);
// Parses the file contents, using filepath solely to help build error messages, retrieving some
// options.
std::map<std::string, std::vector<std::string> > parse_config_file(const std::string &contents,
const std::string &filepath,
const std::vector<option_t> &options);
struct help_line_t {
help_line_t(const std::string &_syntax_description,
const std::string &_blurb)
: syntax_description(_syntax_description), blurb(_blurb) { }
std::string syntax_description;
std::string blurb;
};
struct help_section_t {
help_section_t() { }
help_section_t(const std::string &_section_name)
: section_name(_section_name) { }
help_section_t(const std::string &_section_name, const std::vector<help_line_t> &_help_lines)
: section_name(_section_name), help_lines(_help_lines) { }
void add(const std::string &syntax_description, const std::string &blurb) {
help_lines.push_back(help_line_t(syntax_description, blurb));
}
std::string section_name;
std::vector<help_line_t> help_lines;
};
std::string format_help(const std::vector<help_section_t> &help);
} // namespace options
<commit_msg>Added some const reference parameters and comment strings.<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved.
#include <map>
#include <stdexcept>
#include <string>
#include <vector>
namespace options {
struct parse_error_t : public std::runtime_error {
parse_error_t(const std::string &msg) : std::runtime_error(msg) { }
};
struct validation_error_t : public std::runtime_error {
validation_error_t(const std::string &msg) : std::runtime_error(msg) { }
};
struct file_parse_error_t : public std::runtime_error {
file_parse_error_t(const std::string &msg) : std::runtime_error(msg) { }
};
// Represents an option's names. Be sure to include dashes! Usage:
//
// names_t("--max-foobars") // An option name.
// names_t("--cores", "-c") // An option name with an abbreviation
class names_t {
public:
// Include dashes. For example, name might be "--blah".
explicit names_t(const std::string &name) {
names.push_back(name);
}
// Include the right amount of dashes. For example, official_name might
// be "--help", and other_name might be "-h".
names_t(std::string official_name, std::string other_name) {
names.push_back(official_name);
names.push_back(other_name);
}
private:
friend class option_t;
std::vector<std::string> names;
};
// Pass one of these to the option_t construct to tell what kind of argument you have.
enum appearance_t {
// A mandatory argument that can be passed once.
MANDATORY,
// A mandatory argument that may be repeated.
MANDATORY_REPEAT,
// An optional argument, that may be passed zero or one times.
OPTIONAL,
// An optional argument, that may be repeated.
OPTIONAL_REPEAT,
// An optional argument that doesn't take a parameter. Useful for "--help".
OPTIONAL_NO_PARAMETER
};
// A command line option with a name, specification of how many times it may appear, and whether it
// takes a parameter.
//
// Examples:
// // An option that may be used at most once, with no parameter.
// option_t(names_t("--help", "-h"), OPTIONAL_NO_PARAMETER)
// // An option that may be used at most once, with a default value. The user
// // could pass --cores 3 or -c 3, but not a naked -c.
// option_t(names_t("--cores", "-c"), OPTIONAL, strprintf("%d", get_cpu_count()));
// // An option that must appear one or more times.
// option_t(names_t("--join", "-j"), MANDATORY_REPEAT)
class option_t {
public:
// Creates an option with the appropriate name and appearance specifier,
// with a default value being the empty vector.
explicit option_t(names_t names, appearance_t appearance);
// Creates an option with the appropriate name and appearance specifier,
// with the default value being a vector of size 1. OPTIONAL and
// OPTIONAL_REPEAT are the only valid appearance specifiers.
explicit option_t(names_t names, appearance_t appearance, std::string default_value);
private:
friend std::map<std::string, std::vector<std::string> > default_values_map(const std::vector<option_t> &options);
friend std::map<std::string, std::vector<std::string> > do_parse_command_line(
const int argc, const char *const *const argv, const std::vector<option_t> &options,
std::vector<std::string> *const unrecognized_out);
friend const option_t *find_option(const char *const option_name, const std::vector<option_t> &options);
friend void verify_option_counts(const std::vector<option_t> &options,
const std::map<std::string, std::vector<std::string> > &names_by_values);
// Names for the option, e.g. "-j", "--join"
std::vector<std::string> names;
// How many times must the option appear? If an option appears zero times,
// and if min_appearances is zero, then `default_values` will be used as the
// value-list of the option. Typical combinations of (min_appearances,
// max_appearances) are (0, 1) (with a default_value), (0, SIZE_MAX) (with or
// without a default value), (1, 1) (for mandatory options), (1, SIZE_MAX)
// (for mandatory options with repetition).
//
// It must be the case that 0 <= min_appearances <= max_appearances <=
// SIZE_MAX.
size_t min_appearances;
size_t max_appearances;
// True if an option doesn't take a parameter. For example, "--help" would
// take no parameter.
bool no_parameter;
// The value(s) to use if no appearances of the command line option are
// available. This is only relevant if min_appearances == 0.
std::vector<std::string> default_values;
};
// Parses options from a command line into a return value. Uses empty-string parameter values for
// appearances of OPTIONAL_NO_PARAMETER options. Uses the *official name* of the option (the first
// parameter passed to names_t) for map keys. Does not do any verification that we have the right
// number of option values. (That only happens in `verify_option_counts`.)
std::map<std::string, std::vector<std::string> > parse_command_line(int argc, const char *const *argv, const std::vector<option_t> &options);
// Like `parse_command_line`, except that it tolerates unrecognized options, instead of throwing.
// Out-of-place positional parameters and unrecognized options are output to `*unrecognized_out`, in
// the same order that they appeared in the options list. This can lead to some weird situations,
// if you passed "--recognized-foo 3 --unrecognized --recognized-bar 4 5" on the command line. You
// would get ["--unrecognized", "5"] in `*unrecognized_out`.
std::map<std::string, std::vector<std::string> > parse_command_line_and_collect_unrecognized(
int argc, const char *const *argv, const std::vector<option_t> &options,
std::vector<std::string> *unrecognized_out);
// Merges option values from two different sources together, with higher precedence going to the
// left-hand argument. Example usage:
//
// opts = merge(command_line_values, config_file_values);
std::map<std::string, std::vector<std::string> > merge(
const std::map<std::string, std::vector<std::string> > &high_precedence_values,
const std::map<std::string, std::vector<std::string> > &low_precedence_values);
// Verifies that given options build the right amount of times. This is separate from option
// parsing because we need to accumulate options from both the command line and config file.
void verify_option_counts(const std::vector<option_t> &options,
const std::map<std::string, std::vector<std::string> > &names_by_values);
// Constructs a map of default option values.
std::map<std::string, std::vector<std::string> > default_values_map(const std::vector<option_t> &options);
// Parses the file contents, using filepath solely to help build error messages, retrieving some
// options.
std::map<std::string, std::vector<std::string> > parse_config_file(const std::string &contents,
const std::string &filepath,
const std::vector<option_t> &options);
// A help_line_t is a syntax description and a blurb. When used in a help_section_t, the blurbs get
// aligned and word-wrapped.
struct help_line_t {
help_line_t(const std::string &_syntax_description,
const std::string &_blurb)
: syntax_description(_syntax_description), blurb(_blurb) { }
std::string syntax_description;
std::string blurb;
};
// A help_section_t is a titled list of syntax descriptions and blurbs. When rendered with
// format_help, all the blurbs get aligned and word-wrapped.
struct help_section_t {
help_section_t() { }
help_section_t(const std::string &_section_name)
: section_name(_section_name) { }
help_section_t(const std::string &_section_name, const std::vector<help_line_t> &_help_lines)
: section_name(_section_name), help_lines(_help_lines) { }
void add(const std::string &syntax_description, const std::string &blurb) {
help_lines.push_back(help_line_t(syntax_description, blurb));
}
std::string section_name;
std::vector<help_line_t> help_lines;
};
// Creates a help string suitable for output from --help, aligning and word-wrapping the blurbs.
std::string format_help(const std::vector<help_section_t> &help);
} // namespace options
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2020 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <seastar/core/condition-variable.hh>
#include "raft.hh"
#include "progress.hh"
#include "log.hh"
namespace raft {
// State of the FSM that needs logging & sending.
struct fsm_output {
term_t term;
server_id vote;
std::vector<log_entry_ptr> log_entries;
std::vector<std::pair<server_id, rpc_message>> messages;
// Entries to apply.
std::vector<log_entry_ptr> committed;
};
struct fsm_config {
// max size of appended entries in bytes
size_t append_request_threshold;
};
// 3.4 Leader election
// If a follower receives no communication over a period of
// time called the election timeout, then it assumes there is
// no viable leader and begins an election to choose a new
// leader.
static constexpr logical_clock::duration ELECTION_TIMEOUT = logical_clock::duration{10};
// 3.3 Raft Basics
// At any given time each server is in one of three states:
// leader, follower, or candidate.
// In normal operation there is exactly one leader and all of the
// other servers are followers. Followers are passive: they issue
// no requests on their own but simply respond to requests from
// leaders and candidates. The leader handles all client requests
// (if a client contacts a follower, the follower redirects it to
// the leader). The third state, candidate, is used to elect a new
// leader.
class follower {};
class candidate {};
class leader {};
// Raft protocol finite state machine
//
// Most libraries separate themselves from implementations by
// providing an API to the environment of the Raft protocol, such
// as the database, the write ahead log and the RPC to peers.
// This callback based design has some drawbacks:
// - some callbacks may be defined in blocking model; e.g.
// writing log entries to disk, or persisting the current
// term in the database; Seastar has no blocking IO and
// would have to emulate it with fibers;
// - the API calls are spread over the state machine
// implementation, which makes reasoning about the correctness
// more difficult (what happens if the library is is accessed
// concurrently by multiple users, which of these accesses have
// to be synchronized; what if the callback fails, is the state
// machine handling the error correctly?)
// - while using callbacks allow testing without a real network or disk,
// it still complicates it, since one has to implement meaningful
// mocks for most of the APIs.
//
// Seastar Raft instead implements an instance of Raft as
// in-memory state machine with a catch-all API step(message)
// method. The method handles any kind of input and performs the
// needed state machine state transitions. To get state machine output
// poll_output() function has to be called. This call produces an output
// object, which encapsulates a list of actions that must be
// performed until the next poll_output() call can be made. The time is
// represented with a logical timer. The client is responsible for
// periodically invoking tick() method, which advances the state
// machine time and allows it to track such events as election or
// heartbeat timeouts.
class fsm {
// id of this node
server_id _my_id;
// id of the current leader
server_id _current_leader;
// What state the server is in. The default is follower.
std::variant<follower, candidate, leader> _state;
// _current_term, _voted_for && _log are persisted in storage
// The latest term the server has seen.
term_t _current_term;
// Candidate id that received a vote in the current term (or
// nil if none).
server_id _voted_for;
// Index of the highest log entry known to be committed.
// Currently not persisted.
index_t _commit_idx = index_t(0);
// Log entries; each entry contains a command for state machine,
// and the term when the entry was received by the leader.
log _log;
// A possibly shared server failure detector.
failure_detector& _failure_detector;
// fsm configuration
fsm_config _config;
// Stores the last state observed by get_output().
// Is updated with the actual state of the FSM after
// fsm_output is created.
struct last_observed_state {
term_t _current_term;
server_id _voted_for;
index_t _commit_idx;
bool is_equal(const fsm& fsm) const {
return _current_term == fsm._current_term && _voted_for == fsm._voted_for &&
_commit_idx == fsm._commit_idx;
}
void advance(const fsm& fsm) {
_current_term = fsm._current_term;
_voted_for = fsm._voted_for;
_commit_idx = fsm._commit_idx;
}
} _observed;
logical_clock _clock;
// Start of the current election epoch - a time point relative
// to which we expire election timeout.
logical_clock::time_point _last_election_time = logical_clock::min();
// A random value in range [election_timeout, 2 * election_timeout),
// reset on each term change.
logical_clock::duration _randomized_election_timeout = ELECTION_TIMEOUT;
// Votes received during an election round. Available only in
// candidate state.
std::optional<votes> _votes;
// A state for each follower, maintained only on the leader.
std::optional<tracker> _tracker;
// Holds all replies to AppendEntries RPC which are not
// yet sent out. If AppendEntries request is accepted, we must
// withhold a reply until the respective entry is persisted in
// the log. Otherwise, e.g. when we receive AppendEntries with
// an older term, we may reject it immediately.
// Either way all replies are appended to this queue first.
//
// 3.3 Raft Basics
// If a server receives a request with a stale term number, it
// rejects the request.
// TLA+ line 328
std::vector<std::pair<server_id, rpc_message>> _messages;
// Currently used configuration, may be different from
// the committed during a configuration change.
configuration _current_config;
// Signaled when there is a IO event to process.
seastar::condition_variable _sm_events;
// Called when one of the replicas advances its match index
// so it may be the case that some entries are committed now.
// Signals _sm_events.
void check_committed();
// Check if the randomized election timeout has expired.
bool is_past_election_timeout() const {
return _clock.now() - _last_election_time >= _randomized_election_timeout;
}
// How much time has passed since last election or last
// time we heard from a valid leader.
logical_clock::duration election_elapsed() const {
return _clock.now() - _last_election_time;
}
// A helper to send any kind of RPC message.
template <typename Message>
void send_to(server_id to, Message&& m) {
static_assert(std::is_rvalue_reference<decltype(m)>::value, "must be rvalue");
_messages.push_back(std::make_pair(to, std::move(m)));
_sm_events.signal();
}
// A helper to update the FSM's current term.
void update_current_term(term_t current_term);
void check_is_leader() const {
if (!is_leader()) {
throw not_a_leader(_current_leader);
}
}
void become_candidate();
void become_follower(server_id leader);
// Controls whether the follower has been responsive recently,
// so it makes sense to send more data to it.
bool can_send_to(const follower_progress& progress);
// Replicate entries to a follower. If there are no entries to send
// and allow_empty is true, send a heartbeat.
void replicate_to(follower_progress& progress, bool allow_empty);
void replicate();
void append_entries(server_id from, append_request_recv&& append_request);
void append_entries_reply(server_id from, append_reply&& reply);
void request_vote(server_id from, vote_request&& vote_request);
void request_vote_reply(server_id from, vote_reply&& vote_reply);
// Called on a follower with a new known leader commit index.
// Advances the follower's commit index up to all log-stable
// entries, known to be committed.
void advance_commit_idx(index_t leader_commit_idx);
// Called after log entries in FSM output are considered persisted.
// Produces new FSM output.
void advance_stable_idx(index_t idx);
// Tick implementation on a leader
void tick_leader();
// Set cluster configuration
void set_configuration(const configuration& config) {
_current_config = config;
// We unconditionally access _current_config
// to identify which entries are committed.
assert(_current_config.servers.size() > 0);
if (is_leader()) {
_tracker->set_configuration(_current_config.servers, _log.next_idx());
} else if (is_candidate()) {
_votes->set_configuration(_current_config.servers);
}
}
public:
explicit fsm(server_id id, term_t current_term, server_id voted_for, log log,
failure_detector& failure_detector, fsm_config conf);
bool is_leader() const {
return std::holds_alternative<leader>(_state);
}
bool is_follower() const {
return std::holds_alternative<follower>(_state);
}
bool is_candidate() const {
return std::holds_alternative<candidate>(_state);
}
void become_leader();
// Add an entry to in-memory log. The entry has to be
// committed to the persistent Raft log afterwards.
template<typename T> const log_entry& add_entry(T command);
// Wait until there is, and return state machine output that
// needs to be handled.
// This includes a list of the entries that need
// to be logged. The logged entries are eventually
// discarded from the state machine after snapshotting.
future<fsm_output> poll_output();
// Get state machine output, if there is any. Doesn't
// wait. It is public for use in testing.
// May throw on allocation failure, but leaves state machine
// in the same state in that case
fsm_output get_output();
// Called to advance virtual clock of the protocol state machine.
void tick();
// Feed one Raft RPC message into the state machine.
// Advances the state machine state and generates output,
// accessible via poll_output().
template <typename Message>
void step(server_id from, Message&& msg);
void stop();
// @sa can_read()
term_t get_current_term() const {
return _current_term;
}
// Should be called on leader only, throws otherwise.
// Returns true if the current leader has at least one entry
// committed and a quorum of followers was alive in the last
// tick period.
bool can_read();
friend std::ostream& operator<<(std::ostream& os, const fsm& f);
};
template <typename Message>
void fsm::step(server_id from, Message&& msg) {
static_assert(std::is_rvalue_reference<decltype(msg)>::value, "must be rvalue");
// 4.1. Safety
// Servers process incoming RPC requests without consulting
// their current configurations.
// 3.3. Raft basics.
//
// Current terms are exchanged whenever servers
// communicate; if one server’s current term is smaller
// than the other’s, then it updates its current term to
// the larger value. If a candidate or leader discovers
// that its term is out of date, it immediately reverts to
// follower state. If a server receives a request with
// a stale term number, it rejects the request.
if (msg.current_term > _current_term) {
logger.trace("{} [term: {}] received a message with higher term from {} [term: {}]",
_my_id, _current_term, from, msg.current_term);
if constexpr (std::is_same_v<Message, append_request_recv>) {
become_follower(from);
} else {
if constexpr (std::is_same_v<Message, vote_request>) {
if (_current_leader != server_id{} && election_elapsed() < ELECTION_TIMEOUT) {
// 4.2.3 Disruptive servers
// If a server receives a RequestVote request
// within the minimum election timeout of
// hearing from a current leader, it does not
// update its term or grant its vote.
logger.trace("{} [term: {}] not granting a vote within a minimum election timeout, elapsed {}",
_my_id, _current_term, election_elapsed());
return;
}
}
become_follower(server_id{});
}
update_current_term(msg.current_term);
} else if (msg.current_term < _current_term) {
if constexpr (std::is_same_v<Message, append_request_recv>) {
// Instructs the leader to step down.
append_reply reply{_current_term, _commit_idx, append_reply::rejected{msg.prev_log_idx, _log.last_idx()}};
send_to(from, std::move(reply));
} else {
// Ignore other cases
logger.trace("{} [term: {}] ignored a message with lower term from {} [term: {}]",
_my_id, _current_term, from, msg.current_term);
}
return;
} else /* _current_term == msg.current_term */ {
if constexpr (std::is_same_v<Message, append_request_recv> ||
std::is_same_v<Message, install_snapshot>) {
if (is_candidate()) {
// 3.4 Leader Election
// While waiting for votes, a candidate may receive an AppendEntries
// RPC from another server claiming to be leader. If the
// leader’s term (included in its RPC) is at least as large as the
// candidate’s current term, then the candidate recognizes the
// leader as legitimate and returns to follower state.
become_follower(from);
} else if (_current_leader == server_id{}) {
// Earlier we changed our term to match a candidate's
// term. Now we get the first message from the
// newly elected leader. Keep track of the current
// leader to avoid starting an election if the
// leader becomes idle.
_current_leader = from;
}
assert(_current_leader == from);
}
}
auto visitor = [this, from, msg = std::move(msg)](auto state) mutable {
using State = decltype(state);
if constexpr (std::is_same_v<Message, append_request_recv>) {
// Got AppendEntries RPC from self
append_entries(from, std::move(msg));
} else if constexpr (std::is_same_v<Message, append_reply>) {
if constexpr (!std::is_same_v<State, leader>) {
// Ignore stray reply if we're not a leader.
return;
}
append_entries_reply(from, std::move(msg));
} else if constexpr (std::is_same_v<Message, vote_request>) {
request_vote(from, std::move(msg));
} else if constexpr (std::is_same_v<Message, vote_reply>) {
if constexpr (!std::is_same_v<State, candidate>) {
// Ignore stray reply if we're not a candidate.
return;
}
request_vote_reply(from, std::move(msg));
}
};
std::visit(visitor, _state);
}
} // namespace raft
<commit_msg>raft: make election_elapsed public for testing<commit_after>/*
* Copyright (C) 2020 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <seastar/core/condition-variable.hh>
#include "raft.hh"
#include "progress.hh"
#include "log.hh"
namespace raft {
// State of the FSM that needs logging & sending.
struct fsm_output {
term_t term;
server_id vote;
std::vector<log_entry_ptr> log_entries;
std::vector<std::pair<server_id, rpc_message>> messages;
// Entries to apply.
std::vector<log_entry_ptr> committed;
};
struct fsm_config {
// max size of appended entries in bytes
size_t append_request_threshold;
};
// 3.4 Leader election
// If a follower receives no communication over a period of
// time called the election timeout, then it assumes there is
// no viable leader and begins an election to choose a new
// leader.
static constexpr logical_clock::duration ELECTION_TIMEOUT = logical_clock::duration{10};
// 3.3 Raft Basics
// At any given time each server is in one of three states:
// leader, follower, or candidate.
// In normal operation there is exactly one leader and all of the
// other servers are followers. Followers are passive: they issue
// no requests on their own but simply respond to requests from
// leaders and candidates. The leader handles all client requests
// (if a client contacts a follower, the follower redirects it to
// the leader). The third state, candidate, is used to elect a new
// leader.
class follower {};
class candidate {};
class leader {};
// Raft protocol finite state machine
//
// Most libraries separate themselves from implementations by
// providing an API to the environment of the Raft protocol, such
// as the database, the write ahead log and the RPC to peers.
// This callback based design has some drawbacks:
// - some callbacks may be defined in blocking model; e.g.
// writing log entries to disk, or persisting the current
// term in the database; Seastar has no blocking IO and
// would have to emulate it with fibers;
// - the API calls are spread over the state machine
// implementation, which makes reasoning about the correctness
// more difficult (what happens if the library is is accessed
// concurrently by multiple users, which of these accesses have
// to be synchronized; what if the callback fails, is the state
// machine handling the error correctly?)
// - while using callbacks allow testing without a real network or disk,
// it still complicates it, since one has to implement meaningful
// mocks for most of the APIs.
//
// Seastar Raft instead implements an instance of Raft as
// in-memory state machine with a catch-all API step(message)
// method. The method handles any kind of input and performs the
// needed state machine state transitions. To get state machine output
// poll_output() function has to be called. This call produces an output
// object, which encapsulates a list of actions that must be
// performed until the next poll_output() call can be made. The time is
// represented with a logical timer. The client is responsible for
// periodically invoking tick() method, which advances the state
// machine time and allows it to track such events as election or
// heartbeat timeouts.
class fsm {
// id of this node
server_id _my_id;
// id of the current leader
server_id _current_leader;
// What state the server is in. The default is follower.
std::variant<follower, candidate, leader> _state;
// _current_term, _voted_for && _log are persisted in storage
// The latest term the server has seen.
term_t _current_term;
// Candidate id that received a vote in the current term (or
// nil if none).
server_id _voted_for;
// Index of the highest log entry known to be committed.
// Currently not persisted.
index_t _commit_idx = index_t(0);
// Log entries; each entry contains a command for state machine,
// and the term when the entry was received by the leader.
log _log;
// A possibly shared server failure detector.
failure_detector& _failure_detector;
// fsm configuration
fsm_config _config;
// Stores the last state observed by get_output().
// Is updated with the actual state of the FSM after
// fsm_output is created.
struct last_observed_state {
term_t _current_term;
server_id _voted_for;
index_t _commit_idx;
bool is_equal(const fsm& fsm) const {
return _current_term == fsm._current_term && _voted_for == fsm._voted_for &&
_commit_idx == fsm._commit_idx;
}
void advance(const fsm& fsm) {
_current_term = fsm._current_term;
_voted_for = fsm._voted_for;
_commit_idx = fsm._commit_idx;
}
} _observed;
logical_clock _clock;
// Start of the current election epoch - a time point relative
// to which we expire election timeout.
logical_clock::time_point _last_election_time = logical_clock::min();
// A random value in range [election_timeout, 2 * election_timeout),
// reset on each term change.
logical_clock::duration _randomized_election_timeout = ELECTION_TIMEOUT;
// Votes received during an election round. Available only in
// candidate state.
std::optional<votes> _votes;
// A state for each follower, maintained only on the leader.
std::optional<tracker> _tracker;
// Holds all replies to AppendEntries RPC which are not
// yet sent out. If AppendEntries request is accepted, we must
// withhold a reply until the respective entry is persisted in
// the log. Otherwise, e.g. when we receive AppendEntries with
// an older term, we may reject it immediately.
// Either way all replies are appended to this queue first.
//
// 3.3 Raft Basics
// If a server receives a request with a stale term number, it
// rejects the request.
// TLA+ line 328
std::vector<std::pair<server_id, rpc_message>> _messages;
// Currently used configuration, may be different from
// the committed during a configuration change.
configuration _current_config;
// Signaled when there is a IO event to process.
seastar::condition_variable _sm_events;
// Called when one of the replicas advances its match index
// so it may be the case that some entries are committed now.
// Signals _sm_events.
void check_committed();
// Check if the randomized election timeout has expired.
bool is_past_election_timeout() const {
return _clock.now() - _last_election_time >= _randomized_election_timeout;
}
// A helper to send any kind of RPC message.
template <typename Message>
void send_to(server_id to, Message&& m) {
static_assert(std::is_rvalue_reference<decltype(m)>::value, "must be rvalue");
_messages.push_back(std::make_pair(to, std::move(m)));
_sm_events.signal();
}
// A helper to update the FSM's current term.
void update_current_term(term_t current_term);
void check_is_leader() const {
if (!is_leader()) {
throw not_a_leader(_current_leader);
}
}
void become_candidate();
void become_follower(server_id leader);
// Controls whether the follower has been responsive recently,
// so it makes sense to send more data to it.
bool can_send_to(const follower_progress& progress);
// Replicate entries to a follower. If there are no entries to send
// and allow_empty is true, send a heartbeat.
void replicate_to(follower_progress& progress, bool allow_empty);
void replicate();
void append_entries(server_id from, append_request_recv&& append_request);
void append_entries_reply(server_id from, append_reply&& reply);
void request_vote(server_id from, vote_request&& vote_request);
void request_vote_reply(server_id from, vote_reply&& vote_reply);
// Called on a follower with a new known leader commit index.
// Advances the follower's commit index up to all log-stable
// entries, known to be committed.
void advance_commit_idx(index_t leader_commit_idx);
// Called after log entries in FSM output are considered persisted.
// Produces new FSM output.
void advance_stable_idx(index_t idx);
// Tick implementation on a leader
void tick_leader();
// Set cluster configuration
void set_configuration(const configuration& config) {
_current_config = config;
// We unconditionally access _current_config
// to identify which entries are committed.
assert(_current_config.servers.size() > 0);
if (is_leader()) {
_tracker->set_configuration(_current_config.servers, _log.next_idx());
} else if (is_candidate()) {
_votes->set_configuration(_current_config.servers);
}
}
public:
explicit fsm(server_id id, term_t current_term, server_id voted_for, log log,
failure_detector& failure_detector, fsm_config conf);
bool is_leader() const {
return std::holds_alternative<leader>(_state);
}
bool is_follower() const {
return std::holds_alternative<follower>(_state);
}
bool is_candidate() const {
return std::holds_alternative<candidate>(_state);
}
void become_leader();
// Add an entry to in-memory log. The entry has to be
// committed to the persistent Raft log afterwards.
template<typename T> const log_entry& add_entry(T command);
// Wait until there is, and return state machine output that
// needs to be handled.
// This includes a list of the entries that need
// to be logged. The logged entries are eventually
// discarded from the state machine after snapshotting.
future<fsm_output> poll_output();
// Get state machine output, if there is any. Doesn't
// wait. It is public for use in testing.
// May throw on allocation failure, but leaves state machine
// in the same state in that case
fsm_output get_output();
// Called to advance virtual clock of the protocol state machine.
void tick();
// Feed one Raft RPC message into the state machine.
// Advances the state machine state and generates output,
// accessible via poll_output().
template <typename Message>
void step(server_id from, Message&& msg);
void stop();
// @sa can_read()
term_t get_current_term() const {
return _current_term;
}
// How much time has passed since last election or last
// time we heard from a valid leader.
logical_clock::duration election_elapsed() const {
return _clock.now() - _last_election_time;
}
// Should be called on leader only, throws otherwise.
// Returns true if the current leader has at least one entry
// committed and a quorum of followers was alive in the last
// tick period.
bool can_read();
friend std::ostream& operator<<(std::ostream& os, const fsm& f);
};
template <typename Message>
void fsm::step(server_id from, Message&& msg) {
static_assert(std::is_rvalue_reference<decltype(msg)>::value, "must be rvalue");
// 4.1. Safety
// Servers process incoming RPC requests without consulting
// their current configurations.
// 3.3. Raft basics.
//
// Current terms are exchanged whenever servers
// communicate; if one server’s current term is smaller
// than the other’s, then it updates its current term to
// the larger value. If a candidate or leader discovers
// that its term is out of date, it immediately reverts to
// follower state. If a server receives a request with
// a stale term number, it rejects the request.
if (msg.current_term > _current_term) {
logger.trace("{} [term: {}] received a message with higher term from {} [term: {}]",
_my_id, _current_term, from, msg.current_term);
if constexpr (std::is_same_v<Message, append_request_recv>) {
become_follower(from);
} else {
if constexpr (std::is_same_v<Message, vote_request>) {
if (_current_leader != server_id{} && election_elapsed() < ELECTION_TIMEOUT) {
// 4.2.3 Disruptive servers
// If a server receives a RequestVote request
// within the minimum election timeout of
// hearing from a current leader, it does not
// update its term or grant its vote.
logger.trace("{} [term: {}] not granting a vote within a minimum election timeout, elapsed {}",
_my_id, _current_term, election_elapsed());
return;
}
}
become_follower(server_id{});
}
update_current_term(msg.current_term);
} else if (msg.current_term < _current_term) {
if constexpr (std::is_same_v<Message, append_request_recv>) {
// Instructs the leader to step down.
append_reply reply{_current_term, _commit_idx, append_reply::rejected{msg.prev_log_idx, _log.last_idx()}};
send_to(from, std::move(reply));
} else {
// Ignore other cases
logger.trace("{} [term: {}] ignored a message with lower term from {} [term: {}]",
_my_id, _current_term, from, msg.current_term);
}
return;
} else /* _current_term == msg.current_term */ {
if constexpr (std::is_same_v<Message, append_request_recv> ||
std::is_same_v<Message, install_snapshot>) {
if (is_candidate()) {
// 3.4 Leader Election
// While waiting for votes, a candidate may receive an AppendEntries
// RPC from another server claiming to be leader. If the
// leader’s term (included in its RPC) is at least as large as the
// candidate’s current term, then the candidate recognizes the
// leader as legitimate and returns to follower state.
become_follower(from);
} else if (_current_leader == server_id{}) {
// Earlier we changed our term to match a candidate's
// term. Now we get the first message from the
// newly elected leader. Keep track of the current
// leader to avoid starting an election if the
// leader becomes idle.
_current_leader = from;
}
assert(_current_leader == from);
}
}
auto visitor = [this, from, msg = std::move(msg)](auto state) mutable {
using State = decltype(state);
if constexpr (std::is_same_v<Message, append_request_recv>) {
// Got AppendEntries RPC from self
append_entries(from, std::move(msg));
} else if constexpr (std::is_same_v<Message, append_reply>) {
if constexpr (!std::is_same_v<State, leader>) {
// Ignore stray reply if we're not a leader.
return;
}
append_entries_reply(from, std::move(msg));
} else if constexpr (std::is_same_v<Message, vote_request>) {
request_vote(from, std::move(msg));
} else if constexpr (std::is_same_v<Message, vote_reply>) {
if constexpr (!std::is_same_v<State, candidate>) {
// Ignore stray reply if we're not a candidate.
return;
}
request_vote_reply(from, std::move(msg));
}
};
std::visit(visitor, _state);
}
} // namespace raft
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#ifndef FEATURE_STYLE_PROCESSOR_HPP
#define FEATURE_STYLE_PROCESSOR_HPP
// mapnik
#include <mapnik/box2d.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/layer.hpp>
#include <mapnik/map.hpp>
#include <mapnik/attribute_collector.hpp>
#include <mapnik/expression_evaluator.hpp>
#include <mapnik/utils.hpp>
#include <mapnik/projection.hpp>
#include <mapnik/scale_denominator.hpp>
#include <mapnik/memory_datasource.hpp>
#ifdef MAPNIK_DEBUG
//#include <mapnik/wall_clock_timer.hpp>
#endif
//stl
#include <vector>
namespace mapnik
{
template <typename Processor>
class feature_style_processor
{
/** Calls the renderer's process function,
* \param output Renderer
* \param f Feature to process
* \param prj_trans Projection
* \param sym Symbolizer object
*/
struct symbol_dispatch : public boost::static_visitor<>
{
symbol_dispatch (Processor & output,
Feature const& f,
proj_transform const& prj_trans)
: output_(output),
f_(f),
prj_trans_(prj_trans) {}
template <typename T>
void operator () (T const& sym) const
{
output_.process(sym,f_,prj_trans_);
}
Processor & output_;
Feature const& f_;
proj_transform const& prj_trans_;
};
public:
explicit feature_style_processor(Map const& m, double scale_factor = 1.0)
: m_(m),
scale_factor_(scale_factor) {}
void apply()
{
#ifdef MAPNIK_DEBUG
//mapnik::wall_clock_progress_timer t(std::clog, "map rendering took: ");
#endif
Processor & p = static_cast<Processor&>(*this);
p.start_map_processing(m_);
Map::const_metawriter_iterator metaItr = m_.begin_metawriters();
Map::const_metawriter_iterator metaItrEnd = m_.end_metawriters();
for (;metaItr!=metaItrEnd; ++metaItr)
{
metaItr->second->start();
}
try
{
projection proj(m_.srs()); // map projection
double scale_denom = mapnik::scale_denominator(m_,proj.is_geographic());
scale_denom *= scale_factor_;
#ifdef MAPNIK_DEBUG
std::clog << "scale denominator = " << scale_denom << "\n";
#endif
std::vector<layer>::const_iterator itr = m_.layers().begin();
std::vector<layer>::const_iterator end = m_.layers().end();
while (itr != end)
{
if (itr->isVisible(scale_denom))
{
apply_to_layer(*itr, p, proj, scale_denom);
}
++itr;
}
}
catch (proj_init_error& ex)
{
std::clog << "proj_init_error:" << ex.what() << "\n";
}
metaItr = m_.begin_metawriters();
for (;metaItr!=metaItrEnd; ++metaItr)
{
metaItr->second->stop();
}
p.end_map_processing(m_);
}
private:
void apply_to_layer(layer const& lay, Processor & p,
projection const& proj0, double scale_denom)
{
#ifdef MAPNIK_DEBUG
//wall_clock_progress_timer timer(clog, "end layer rendering: ");
#endif
boost::shared_ptr<datasource> ds = lay.datasource();
if (!ds) {
std::clog << "WARNING: No datasource for layer '" << lay.name() << "'\n";
return;
}
p.start_layer_processing(lay);
if (ds)
{
box2d<double> ext = m_.get_buffered_extent();
projection proj1(lay.srs());
proj_transform prj_trans(proj0,proj1);
box2d<double> layer_ext = lay.envelope();
double lx0 = layer_ext.minx();
double ly0 = layer_ext.miny();
double lz0 = 0.0;
double lx1 = layer_ext.maxx();
double ly1 = layer_ext.maxy();
double lz1 = 0.0;
// back project layers extent into main map projection
prj_trans.backward(lx0,ly0,lz0);
prj_trans.backward(lx1,ly1,lz1);
// if no intersection then nothing to do for layer
if ( lx0 > ext.maxx() || lx1 < ext.minx() || ly0 > ext.maxy() || ly1 < ext.miny() )
{
return;
}
// clip query bbox
lx0 = std::max(ext.minx(),lx0);
ly0 = std::max(ext.miny(),ly0);
lx1 = std::min(ext.maxx(),lx1);
ly1 = std::min(ext.maxy(),ly1);
prj_trans.forward(lx0,ly0,lz0);
prj_trans.forward(lx1,ly1,lz1);
box2d<double> bbox(lx0,ly0,lx1,ly1);
query::resolution_type res(m_.width()/m_.get_current_extent().width(),m_.height()/m_.get_current_extent().height());
query q(bbox,res,scale_denom); //BBOX query
std::vector<std::string> const& style_names = lay.styles();
std::vector<std::string>::const_iterator stylesIter = style_names.begin();
std::vector<std::string>::const_iterator stylesEnd = style_names.end();
memory_datasource cache;
bool cache_features = style_names.size()>1?true:false;
bool first = true;
for (;stylesIter != stylesEnd; ++stylesIter)
{
std::set<std::string> names;
attribute_collector collector(names);
std::vector<rule_type*> if_rules;
std::vector<rule_type*> else_rules;
bool active_rules=false;
boost::optional<feature_type_style const&> style=m_.find_style(*stylesIter);
if (!style) {
std::clog << "WARNING: style '" << *stylesIter << "' required for layer '" << lay.name() << "' does not exist.\n";
continue;
}
const std::vector<rule_type>& rules=(*style).get_rules();
std::vector<rule_type>::const_iterator ruleIter=rules.begin();
std::vector<rule_type>::const_iterator ruleEnd=rules.end();
for (;ruleIter!=ruleEnd;++ruleIter)
{
if (ruleIter->active(scale_denom))
{
active_rules=true;
// collect unique attribute names
// TODO - in the future rasters should be able to be filtered...
if (ds->type() == datasource::Vector)
{
collector(*ruleIter);
}
if (ruleIter->has_else_filter())
{
else_rules.push_back(const_cast<rule_type*>(&(*ruleIter)));
}
else
{
if_rules.push_back(const_cast<rule_type*>(&(*ruleIter)));
}
if (ds->type() == datasource::Raster)
{
if (ds->params().get<double>("filter_factor",0.0) == 0.0)
{
const rule_type::symbolizers& symbols = ruleIter->get_symbolizers();
rule_type::symbolizers::const_iterator symIter = symbols.begin();
rule_type::symbolizers::const_iterator symEnd = symbols.end();
for (;symIter != symEnd;++symIter)
{
try
{
raster_symbolizer sym = boost::get<raster_symbolizer>(*symIter);
std::string scaling = sym.get_scaling();
if (scaling == "bilinear" || scaling == "bilinear8" )
{
// todo - allow setting custom value in symbolizer property?
q.filter_factor(2.0);
}
}
catch (const boost::bad_get &v)
{
// case where useless symbolizer is attached to raster layer
//throw config_error("Invalid Symbolizer type supplied, only RasterSymbolizer is supported");
}
}
}
}
}
}
std::set<std::string>::const_iterator namesIter=names.begin();
std::set<std::string>::const_iterator namesEnd =names.end();
// push all property names
for (;namesIter!=namesEnd;++namesIter)
{
q.add_property_name(*namesIter);
}
if (active_rules)
{
featureset_ptr fs;
if (first)
{
first = false;
fs = ds->features(q);
}
else
{
fs = cache.features(q);
}
if (fs)
{
feature_ptr feature;
while ((feature = fs->next()))
{
bool do_else=true;
if (cache_features)
{
cache.push(feature);
}
std::vector<rule_type*>::const_iterator itr=if_rules.begin();
std::vector<rule_type*>::const_iterator end=if_rules.end();
for (;itr != end;++itr)
{
expression_ptr const& expr=(*itr)->get_filter();
value_type result = boost::apply_visitor(evaluate<Feature,value_type>(*feature),*expr);
if (result.to_bool())
{
do_else=false;
const rule_type::symbolizers& symbols = (*itr)->get_symbolizers();
rule_type::symbolizers::const_iterator symIter=symbols.begin();
rule_type::symbolizers::const_iterator symEnd =symbols.end();
for (;symIter != symEnd;++symIter)
{
boost::apply_visitor
(symbol_dispatch(p,*feature,prj_trans),*symIter);
}
}
}
if (do_else)
{
//else filter
std::vector<rule_type*>::const_iterator itr=
else_rules.begin();
std::vector<rule_type*>::const_iterator end=
else_rules.end();
for (;itr != end;++itr)
{
const rule_type::symbolizers& symbols = (*itr)->get_symbolizers();
rule_type::symbolizers::const_iterator symIter= symbols.begin();
rule_type::symbolizers::const_iterator symEnd = symbols.end();
for (;symIter!=symEnd;++symIter)
{
boost::apply_visitor
(symbol_dispatch(p,*feature,prj_trans),*symIter);
}
}
}
}
cache_features = false;
}
}
}
}
p.end_layer_processing(lay);
}
Map const& m_;
double scale_factor_;
};
}
#endif //FEATURE_STYLE_PROCESSOR_HPP
<commit_msg>+ fix feature caching implementation - collect attributes names from all active styles<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#ifndef FEATURE_STYLE_PROCESSOR_HPP
#define FEATURE_STYLE_PROCESSOR_HPP
// mapnik
#include <mapnik/box2d.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/layer.hpp>
#include <mapnik/map.hpp>
#include <mapnik/attribute_collector.hpp>
#include <mapnik/expression_evaluator.hpp>
#include <mapnik/utils.hpp>
#include <mapnik/projection.hpp>
#include <mapnik/scale_denominator.hpp>
#include <mapnik/memory_datasource.hpp>
#ifdef MAPNIK_DEBUG
//#include <mapnik/wall_clock_timer.hpp>
#endif
// boost
#include <boost/foreach.hpp>
//stl
#include <vector>
namespace mapnik
{
template <typename Processor>
class feature_style_processor
{
/** Calls the renderer's process function,
* \param output Renderer
* \param f Feature to process
* \param prj_trans Projection
* \param sym Symbolizer object
*/
struct symbol_dispatch : public boost::static_visitor<>
{
symbol_dispatch (Processor & output,
Feature const& f,
proj_transform const& prj_trans)
: output_(output),
f_(f),
prj_trans_(prj_trans) {}
template <typename T>
void operator () (T const& sym) const
{
output_.process(sym,f_,prj_trans_);
}
Processor & output_;
Feature const& f_;
proj_transform const& prj_trans_;
};
public:
explicit feature_style_processor(Map const& m, double scale_factor = 1.0)
: m_(m),
scale_factor_(scale_factor) {}
void apply()
{
#ifdef MAPNIK_DEBUG
//mapnik::wall_clock_progress_timer t(std::clog, "map rendering took: ");
#endif
Processor & p = static_cast<Processor&>(*this);
p.start_map_processing(m_);
Map::const_metawriter_iterator metaItr = m_.begin_metawriters();
Map::const_metawriter_iterator metaItrEnd = m_.end_metawriters();
for (;metaItr!=metaItrEnd; ++metaItr)
{
metaItr->second->start();
}
try
{
projection proj(m_.srs()); // map projection
double scale_denom = mapnik::scale_denominator(m_,proj.is_geographic());
scale_denom *= scale_factor_;
#ifdef MAPNIK_DEBUG
std::clog << "scale denominator = " << scale_denom << "\n";
#endif
BOOST_FOREACH ( layer const& lyr, m_.layers() )
{
if (lyr.isVisible(scale_denom))
{
apply_to_layer(lyr, p, proj, scale_denom);
}
}
}
catch (proj_init_error& ex)
{
std::clog << "proj_init_error:" << ex.what() << "\n";
}
metaItr = m_.begin_metawriters();
for (;metaItr!=metaItrEnd; ++metaItr)
{
metaItr->second->stop();
}
p.end_map_processing(m_);
}
private:
void apply_to_layer(layer const& lay, Processor & p,
projection const& proj0, double scale_denom)
{
#ifdef MAPNIK_DEBUG
//wall_clock_progress_timer timer(clog, "end layer rendering: ");
#endif
boost::shared_ptr<datasource> ds = lay.datasource();
if (!ds) {
std::clog << "WARNING: No datasource for layer '" << lay.name() << "'\n";
return;
}
p.start_layer_processing(lay);
if (ds)
{
box2d<double> ext = m_.get_buffered_extent();
projection proj1(lay.srs());
proj_transform prj_trans(proj0,proj1);
box2d<double> layer_ext = lay.envelope();
double lx0 = layer_ext.minx();
double ly0 = layer_ext.miny();
double lz0 = 0.0;
double lx1 = layer_ext.maxx();
double ly1 = layer_ext.maxy();
double lz1 = 0.0;
// back project layers extent into main map projection
prj_trans.backward(lx0,ly0,lz0);
prj_trans.backward(lx1,ly1,lz1);
// if no intersection then nothing to do for layer
if ( lx0 > ext.maxx() || lx1 < ext.minx() || ly0 > ext.maxy() || ly1 < ext.miny() )
{
return;
}
// clip query bbox
lx0 = std::max(ext.minx(),lx0);
ly0 = std::max(ext.miny(),ly0);
lx1 = std::min(ext.maxx(),lx1);
ly1 = std::min(ext.maxy(),ly1);
prj_trans.forward(lx0,ly0,lz0);
prj_trans.forward(lx1,ly1,lz1);
box2d<double> bbox(lx0,ly0,lx1,ly1);
query::resolution_type res(m_.width()/m_.get_current_extent().width(),m_.height()/m_.get_current_extent().height());
query q(bbox,res,scale_denom); //BBOX query
std::vector<feature_type_style*> active_styles;
std::set<std::string> names;
attribute_collector collector(names);
std::vector<std::string> const& style_names = lay.styles();
// iterate through all named styles collecting active styles and attribute names
BOOST_FOREACH(std::string const& style_name, style_names)
{
boost::optional<feature_type_style const&> style=m_.find_style(style_name);
if (!style)
{
std::clog << "WARNING: style '" << style_name << "' required for layer '" << lay.name() << "' does not exist.\n";
continue;
}
const std::vector<rule_type>& rules=(*style).get_rules();
bool active_rules=false;
BOOST_FOREACH(rule_type const& rule, rules)
{
if (rule.active(scale_denom))
{
active_rules = true;
if (ds->type() == datasource::Vector)
{
collector(rule);
}
// TODO - in the future rasters should be able to be filtered.
}
}
if (active_rules)
{
active_styles.push_back(const_cast<feature_type_style*>(&(*style)));
}
}
// push all property names
BOOST_FOREACH(std::string const& name, names)
{
q.add_property_name(name);
}
memory_datasource cache;
bool cache_features = style_names.size()>1?true:false;
bool first = true;
BOOST_FOREACH (feature_type_style * style, active_styles)
{
std::vector<rule_type*> if_rules;
std::vector<rule_type*> else_rules;
std::vector<rule_type> const& rules=style->get_rules();
BOOST_FOREACH(rule_type const& rule, rules)
{
if (rule.active(scale_denom))
{
if (rule.has_else_filter())
{
else_rules.push_back(const_cast<rule_type*>(&rule));
}
else
{
if_rules.push_back(const_cast<rule_type*>(&rule));
}
if (ds->type() == datasource::Raster)
{
if (ds->params().get<double>("filter_factor",0.0) == 0.0)
{
rule_type::symbolizers const& symbols = rule.get_symbolizers();
rule_type::symbolizers::const_iterator symIter = symbols.begin();
rule_type::symbolizers::const_iterator symEnd = symbols.end();
for (;symIter != symEnd;++symIter)
{
try
{
raster_symbolizer const& sym = boost::get<raster_symbolizer>(*symIter);
std::string const& scaling = sym.get_scaling();
if (scaling == "bilinear" || scaling == "bilinear8" )
{
// todo - allow setting custom value in symbolizer property?
q.filter_factor(2.0);
}
}
catch (const boost::bad_get &v)
{
// case where useless symbolizer is attached to raster layer
//throw config_error("Invalid Symbolizer type supplied, only RasterSymbolizer is supported");
}
}
}
}
}
}
// process features
featureset_ptr fs;
if (first)
{
first = false;
fs = ds->features(q);
}
else
{
fs = cache.features(q);
}
if (fs)
{
feature_ptr feature;
while ((feature = fs->next()))
{
bool do_else=true;
if (cache_features)
{
cache.push(feature);
}
BOOST_FOREACH(rule_type * rule, if_rules )
{
expression_ptr const& expr=rule->get_filter();
value_type result = boost::apply_visitor(evaluate<Feature,value_type>(*feature),*expr);
if (result.to_bool())
{
do_else=false;
rule_type::symbolizers const& symbols = rule->get_symbolizers();
BOOST_FOREACH (symbolizer const& sym, symbols)
{
boost::apply_visitor
(symbol_dispatch(p,*feature,prj_trans),sym);
}
}
}
if (do_else)
{
BOOST_FOREACH( rule_type * rule, else_rules )
{
rule_type::symbolizers const& symbols = rule->get_symbolizers();
BOOST_FOREACH (symbolizer const& sym, symbols)
{
boost::apply_visitor
(symbol_dispatch(p,*feature,prj_trans),sym);
}
}
}
}
cache_features = false;
}
}
}
p.end_layer_processing(lay);
}
Map const& m_;
double scale_factor_;
};
}
#endif //FEATURE_STYLE_PROCESSOR_HPP
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2017 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_BOOST_GEOMETRY_ADAPTERS_HPP
#define MAPNIK_BOOST_GEOMETRY_ADAPTERS_HPP
#include <mapnik/config.hpp>
// undef B0 to workaround https://svn.boost.org/trac/boost/ticket/10467
#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#undef B0
#include <boost/geometry/geometry.hpp>
#include <boost/geometry/geometries/register/point.hpp>
#include <boost/geometry/geometries/register/ring.hpp>
#include <boost/geometry/geometries/register/linestring.hpp>
#pragma GCC diagnostic pop
// mapnik
#include <mapnik/geometry.hpp>
#include <mapnik/coord.hpp>
#include <mapnik/geometry/box2d.hpp>
BOOST_GEOMETRY_REGISTER_POINT_2D(mapnik::geometry::point<double>, double, boost::geometry::cs::cartesian, x, y)
BOOST_GEOMETRY_REGISTER_POINT_2D (mapnik::geometry::point<std::int64_t>, std::int64_t, boost::geometry::cs::cartesian, x, y)
BOOST_GEOMETRY_REGISTER_LINESTRING_TEMPLATED(mapnik::geometry::line_string)
BOOST_GEOMETRY_REGISTER_RING_TEMPLATED(mapnik::geometry::linear_ring)
// needed by box2d<T>
BOOST_GEOMETRY_REGISTER_POINT_2D(mapnik::coord2d, double, boost::geometry::cs::cartesian, x, y)
BOOST_GEOMETRY_REGISTER_POINT_2D(mapnik::coord2f, float, boost::geometry::cs::cartesian, x, y)
namespace mapnik {
template <typename CoordinateType>
struct interior_rings
{
using polygon_type = mapnik::geometry::polygon<CoordinateType>;
using iterator = typename polygon_type::iterator;
using const_iterator = typename polygon_type::const_iterator;
using value_type = typename polygon_type::value_type;
interior_rings(polygon_type & poly)
: poly_(poly) {}
iterator begin()
{
auto itr = poly_.begin();
std::advance(itr, 1);
return itr;
}
iterator end() { return poly_.end();}
const_iterator begin() const
{
auto itr = poly_.begin();
std::advance(itr, 1);
return itr;
}
const_iterator end() const { return poly_.end();}
void clear()
{
poly_.resize(1);
}
void resize(std::size_t size)
{
poly_.resize(size + 1);
}
std::size_t size() const
{
return poly_.empty() ? 0 : poly_.size() - 1;
}
void push_back(value_type const& val) { poly_.push_back(val); }
value_type& back() { return poly_.back(); }
value_type const& back() const { return poly_.back(); }
polygon_type & poly_;
};
} // ns mapnik
namespace boost { namespace geometry { namespace traits {
template<> struct tag<mapnik::box2d<double> > { using type = box_tag; };
template<> struct point_type<mapnik::box2d<double> > { using type = mapnik::coord2d; };
template <>
struct indexed_access<mapnik::box2d<double>, min_corner, 0>
{
using ct = coordinate_type<mapnik::coord2d>::type;
static inline ct get(mapnik::box2d<double> const& b) { return b.minx();}
static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_minx(value); }
};
template <>
struct indexed_access<mapnik::box2d<double>, min_corner, 1>
{
using ct = coordinate_type<mapnik::coord2d>::type;
static inline ct get(mapnik::box2d<double> const& b) { return b.miny();}
static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_miny(value); }
};
template <>
struct indexed_access<mapnik::box2d<double>, max_corner, 0>
{
using ct = coordinate_type<mapnik::coord2d>::type;
static inline ct get(mapnik::box2d<double> const& b) { return b.maxx();}
static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_maxx(value); }
};
template <>
struct indexed_access<mapnik::box2d<double>, max_corner, 1>
{
using ct = coordinate_type<mapnik::coord2d>::type;
static inline ct get(mapnik::box2d<double> const& b) { return b.maxy();}
static inline void set(mapnik::box2d<double> &b , ct const& value) { b.set_maxy(value); }
};
template<typename CoordinateType>
struct tag<mapnik::geometry::polygon<CoordinateType> >
{
using type = polygon_tag;
};
template <typename CoordinateType>
struct point_order<mapnik::geometry::linear_ring<CoordinateType> >
{
static const order_selector value = counterclockwise;
};
template<typename CoordinateType>
struct tag<mapnik::geometry::multi_point<CoordinateType> >
{
using type = multi_point_tag;
};
template<typename CoordinateType>
struct tag<mapnik::geometry::multi_line_string<CoordinateType> >
{
using type = multi_linestring_tag;
};
template<typename CoordinateType>
struct tag<mapnik::geometry::multi_polygon<CoordinateType> >
{
using type = multi_polygon_tag;
};
// ring
template <typename CoordinateType>
struct ring_const_type<mapnik::geometry::polygon<CoordinateType> >
{
using type = typename mapnik::geometry::linear_ring<CoordinateType> const&;
};
template <typename CoordinateType>
struct ring_mutable_type<mapnik::geometry::polygon<CoordinateType> >
{
using type = typename mapnik::geometry::linear_ring<CoordinateType>&;
};
// interior
template <typename CoordinateType>
struct interior_const_type<mapnik::geometry::polygon<CoordinateType> >
{
using type = typename mapnik::interior_rings<CoordinateType> const;
};
template <typename CoordinateType>
struct interior_mutable_type<mapnik::geometry::polygon<CoordinateType> >
{
using type = typename mapnik::interior_rings<CoordinateType> ;
};
template <typename CoordinateType>
struct exterior_ring<mapnik::geometry::polygon<CoordinateType> >
{
using ring_const_type = typename ring_const_type<mapnik::geometry::polygon<CoordinateType> >::type;
using ring_mutable_type = typename ring_mutable_type<mapnik::geometry::polygon<CoordinateType> >::type;
static ring_mutable_type get(mapnik::geometry::polygon<CoordinateType> & p)
{
if (p.empty()) p.resize(1);
return p[0];
}
static ring_const_type get(mapnik::geometry::polygon<CoordinateType> const& p)
{
if (p.empty()) throw std::runtime_error("Exterior ring must be initialized!");
return p[0];
}
};
template <typename CoordinateType>
struct interior_rings<mapnik::geometry::polygon<CoordinateType> >
{
using interior_const_type = typename interior_const_type<mapnik::geometry::polygon<CoordinateType> >::type;
using interior_mutable_type = typename interior_mutable_type<mapnik::geometry::polygon<CoordinateType> >::type;
static interior_const_type get(mapnik::geometry::polygon<CoordinateType> const& p)
{
return mapnik::interior_rings<CoordinateType>(const_cast<mapnik::geometry::polygon<CoordinateType>&>(p));
}
static interior_mutable_type get(mapnik::geometry::polygon<CoordinateType>& p)
{
return mapnik::interior_rings<CoordinateType>(p);
}
};
template <typename CoordinateType>
struct resize<mapnik::interior_rings<CoordinateType>>
{
static inline void apply(mapnik::interior_rings<CoordinateType> interiors, std::size_t new_size)
{
interiors.resize(new_size);
}
};
template <typename CoordinateType>
struct clear<mapnik::interior_rings<CoordinateType>>
{
static inline void apply(mapnik::interior_rings<CoordinateType> interiors)
{
interiors.clear();
}
};
template <typename CoordinateType>
struct push_back<mapnik::interior_rings<CoordinateType>>
{
template <typename Ring>
static inline void apply(mapnik::interior_rings<CoordinateType> interiors, Ring const& ring)
{
interiors.push_back(ring);
}
};
}}}
#endif //MAPNIK_BOOST_GEOMETRY_ADAPTERS_HPP
<commit_msg>add `const_interior_rings` type and stop abusing type system. (NOTE: iterator/const_iterator types are required by boost::range_iterator)<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2017 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_BOOST_GEOMETRY_ADAPTERS_HPP
#define MAPNIK_BOOST_GEOMETRY_ADAPTERS_HPP
#include <mapnik/config.hpp>
// undef B0 to workaround https://svn.boost.org/trac/boost/ticket/10467
#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#undef B0
#include <boost/geometry/geometry.hpp>
#include <boost/geometry/geometries/register/point.hpp>
#include <boost/geometry/geometries/register/ring.hpp>
#include <boost/geometry/geometries/register/linestring.hpp>
#pragma GCC diagnostic pop
// mapnik
#include <mapnik/geometry.hpp>
#include <mapnik/coord.hpp>
#include <mapnik/geometry/box2d.hpp>
BOOST_GEOMETRY_REGISTER_POINT_2D(mapnik::geometry::point<double>, double, boost::geometry::cs::cartesian, x, y)
BOOST_GEOMETRY_REGISTER_POINT_2D (mapnik::geometry::point<std::int64_t>, std::int64_t, boost::geometry::cs::cartesian, x, y)
BOOST_GEOMETRY_REGISTER_LINESTRING_TEMPLATED(mapnik::geometry::line_string)
BOOST_GEOMETRY_REGISTER_RING_TEMPLATED(mapnik::geometry::linear_ring)
// needed by box2d<T>
BOOST_GEOMETRY_REGISTER_POINT_2D(mapnik::coord2d, double, boost::geometry::cs::cartesian, x, y)
BOOST_GEOMETRY_REGISTER_POINT_2D(mapnik::coord2f, float, boost::geometry::cs::cartesian, x, y)
namespace mapnik {
template <typename CoordinateType>
struct const_interior_rings
{
using polygon_type = mapnik::geometry::polygon<CoordinateType> const;
using const_iterator = typename polygon_type::const_iterator;
using iterator = const_iterator; // needed by boost::range_iterator
using value_type = typename polygon_type::value_type;
const_interior_rings(polygon_type const& poly)
: poly_(poly) {}
const_iterator begin() const
{
auto itr = poly_.cbegin();
std::advance(itr, 1);
return itr;
}
const_iterator end() const { return poly_.cend();}
std::size_t size() const
{
return poly_.empty() ? 0 : poly_.size() - 1;
}
value_type const& back() const { return poly_.back(); }
polygon_type const& poly_;
};
template <typename CoordinateType>
struct interior_rings
{
using polygon_type = mapnik::geometry::polygon<CoordinateType>;
using iterator = typename polygon_type::iterator;
using const_iterator = typename polygon_type::const_iterator;
using value_type = typename polygon_type::value_type;
interior_rings(polygon_type & poly)
: poly_(poly) {}
iterator begin()
{
auto itr = poly_.begin();
std::advance(itr, 1);
return itr;
}
iterator end() { return poly_.end();}
const_iterator begin() const
{
auto itr = poly_.cbegin();
std::advance(itr, 1);
return itr;
}
const_iterator end() const { return poly_.cend();}
void clear()
{
poly_.resize(1);
}
void resize(std::size_t size)
{
poly_.resize(size + 1);
}
std::size_t size() const
{
return poly_.empty() ? 0 : poly_.size() - 1;
}
void push_back(value_type const& val) { poly_.push_back(val); }
value_type& back() { return poly_.back(); }
value_type const& back() const { return poly_.back(); }
polygon_type & poly_;
};
} // ns mapnik
namespace boost { namespace geometry { namespace traits {
template<> struct tag<mapnik::box2d<double> > { using type = box_tag; };
template<> struct point_type<mapnik::box2d<double> > { using type = mapnik::coord2d; };
template <>
struct indexed_access<mapnik::box2d<double>, min_corner, 0>
{
using ct = coordinate_type<mapnik::coord2d>::type;
static inline ct get(mapnik::box2d<double> const& b) { return b.minx();}
static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_minx(value); }
};
template <>
struct indexed_access<mapnik::box2d<double>, min_corner, 1>
{
using ct = coordinate_type<mapnik::coord2d>::type;
static inline ct get(mapnik::box2d<double> const& b) { return b.miny();}
static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_miny(value); }
};
template <>
struct indexed_access<mapnik::box2d<double>, max_corner, 0>
{
using ct = coordinate_type<mapnik::coord2d>::type;
static inline ct get(mapnik::box2d<double> const& b) { return b.maxx();}
static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_maxx(value); }
};
template <>
struct indexed_access<mapnik::box2d<double>, max_corner, 1>
{
using ct = coordinate_type<mapnik::coord2d>::type;
static inline ct get(mapnik::box2d<double> const& b) { return b.maxy();}
static inline void set(mapnik::box2d<double> &b , ct const& value) { b.set_maxy(value); }
};
template<typename CoordinateType>
struct tag<mapnik::geometry::polygon<CoordinateType> >
{
using type = polygon_tag;
};
template <typename CoordinateType>
struct point_order<mapnik::geometry::linear_ring<CoordinateType> >
{
static const order_selector value = counterclockwise;
};
template<typename CoordinateType>
struct tag<mapnik::geometry::multi_point<CoordinateType> >
{
using type = multi_point_tag;
};
template<typename CoordinateType>
struct tag<mapnik::geometry::multi_line_string<CoordinateType> >
{
using type = multi_linestring_tag;
};
template<typename CoordinateType>
struct tag<mapnik::geometry::multi_polygon<CoordinateType> >
{
using type = multi_polygon_tag;
};
// ring
template <typename CoordinateType>
struct ring_const_type<mapnik::geometry::polygon<CoordinateType> >
{
using type = typename mapnik::geometry::linear_ring<CoordinateType> const&;
};
template <typename CoordinateType>
struct ring_mutable_type<mapnik::geometry::polygon<CoordinateType> >
{
using type = typename mapnik::geometry::linear_ring<CoordinateType>&;
};
// interior
template <typename CoordinateType>
struct interior_const_type<mapnik::geometry::polygon<CoordinateType>>
{
using type = typename mapnik::const_interior_rings<CoordinateType> const;
};
template <typename CoordinateType>
struct interior_mutable_type<mapnik::geometry::polygon<CoordinateType> >
{
using type = typename mapnik::interior_rings<CoordinateType> ;
};
template <typename CoordinateType>
struct exterior_ring<mapnik::geometry::polygon<CoordinateType> >
{
using ring_const_type = typename ring_const_type<mapnik::geometry::polygon<CoordinateType> >::type;
using ring_mutable_type = typename ring_mutable_type<mapnik::geometry::polygon<CoordinateType> >::type;
static ring_mutable_type get(mapnik::geometry::polygon<CoordinateType> & p)
{
if (p.empty()) p.resize(1);
return p[0];
}
static ring_const_type get(mapnik::geometry::polygon<CoordinateType> const& p)
{
if (p.empty()) throw std::runtime_error("Exterior ring must be initialized!");
return p[0];
}
};
template <typename CoordinateType>
struct interior_rings<mapnik::geometry::polygon<CoordinateType> >
{
using interior_const_type = typename interior_const_type<mapnik::geometry::polygon<CoordinateType> >::type;
using interior_mutable_type = typename interior_mutable_type<mapnik::geometry::polygon<CoordinateType> >::type;
static interior_const_type get(mapnik::geometry::polygon<CoordinateType> const& p)
{
return mapnik::const_interior_rings<CoordinateType>(p);
}
static interior_mutable_type get(mapnik::geometry::polygon<CoordinateType>& p)
{
return mapnik::interior_rings<CoordinateType>(p);
}
};
template <typename CoordinateType>
struct resize<mapnik::interior_rings<CoordinateType>>
{
static inline void apply(mapnik::interior_rings<CoordinateType> interiors, std::size_t new_size)
{
interiors.resize(new_size);
}
};
template <typename CoordinateType>
struct clear<mapnik::interior_rings<CoordinateType>>
{
static inline void apply(mapnik::interior_rings<CoordinateType> interiors)
{
interiors.clear();
}
};
template <typename CoordinateType>
struct push_back<mapnik::interior_rings<CoordinateType>>
{
template <typename Ring>
static inline void apply(mapnik::interior_rings<CoordinateType> interiors, Ring const& ring)
{
interiors.push_back(ring);
}
};
}}}
#endif //MAPNIK_BOOST_GEOMETRY_ADAPTERS_HPP
<|endoftext|> |
<commit_before>#pragma once
#include <optional>
#include <string>
#include <string_view>
#include <variant>
namespace sdbusplus
{
namespace message
{
namespace details
{
/** Simple wrapper class for std::string to allow conversion to and from an
* alternative typename. */
struct string_wrapper
{
std::string str;
string_wrapper() = default;
string_wrapper(const string_wrapper&) = default;
string_wrapper& operator=(const string_wrapper&) = default;
string_wrapper(string_wrapper&&) = default;
string_wrapper& operator=(string_wrapper&&) = default;
~string_wrapper() = default;
string_wrapper(const std::string& str) : str(str)
{}
string_wrapper(std::string&& str) : str(std::move(str))
{}
operator const std::string&() const volatile&
{
return const_cast<const string_wrapper*>(this)->str;
}
operator std::string&&() &&
{
return std::move(str);
}
bool operator==(const string_wrapper& r) const
{
return str == r.str;
}
bool operator!=(const string_wrapper& r) const
{
return str != r.str;
}
bool operator<(const string_wrapper& r) const
{
return str < r.str;
}
bool operator==(const std::string& r) const
{
return str == r;
}
bool operator!=(const std::string& r) const
{
return str != r;
}
bool operator<(const std::string& r) const
{
return str < r;
}
friend bool operator==(const std::string& l, const string_wrapper& r)
{
return l == r.str;
}
friend bool operator!=(const std::string& l, const string_wrapper& r)
{
return l != r.str;
}
friend bool operator<(const std::string& l, const string_wrapper& r)
{
return l < r.str;
}
};
/** Simple wrapper class for std::string to allow conversion to and from an
* alternative typename. */
struct string_path_wrapper
{
std::string str;
string_path_wrapper() = default;
string_path_wrapper(const string_path_wrapper&) = default;
string_path_wrapper& operator=(const string_path_wrapper&) = default;
string_path_wrapper(string_path_wrapper&&) = default;
string_path_wrapper& operator=(string_path_wrapper&&) = default;
~string_path_wrapper() = default;
string_path_wrapper(const std::string& str) : str(str)
{}
string_path_wrapper(std::string&& str) : str(std::move(str))
{}
operator const std::string&() const volatile&
{
return const_cast<const string_path_wrapper*>(this)->str;
}
operator std::string&&() &&
{
return std::move(str);
}
bool operator==(const string_path_wrapper& r) const
{
return str == r.str;
}
bool operator!=(const string_path_wrapper& r) const
{
return str != r.str;
}
bool operator<(const string_path_wrapper& r) const
{
return str < r.str;
}
bool operator==(const std::string& r) const
{
return str == r;
}
bool operator!=(const std::string& r) const
{
return str != r;
}
bool operator<(const std::string& r) const
{
return str < r;
}
friend bool operator==(const std::string& l, const string_path_wrapper& r)
{
return l == r.str;
}
friend bool operator!=(const std::string& l, const string_path_wrapper& r)
{
return l != r.str;
}
friend bool operator<(const std::string& l, const string_path_wrapper& r)
{
return l < r.str;
}
std::string filename() const;
string_path_wrapper parent_path() const;
string_path_wrapper operator/(std::string_view) const;
string_path_wrapper& operator/=(std::string_view);
};
/** Typename for sdbus SIGNATURE types. */
struct signature_type
{};
/** Typename for sdbus UNIX_FD types. */
struct unix_fd_type
{
int fd;
unix_fd_type() = default;
unix_fd_type(int f) : fd(f)
{}
operator int() const
{
return fd;
}
};
} // namespace details
/** std::string wrapper for OBJECT_PATH. */
using object_path = details::string_path_wrapper;
/** std::string wrapper for SIGNATURE. */
using signature = details::string_wrapper;
using unix_fd = details::unix_fd_type;
namespace details
{
template <typename T>
struct convert_from_string
{
static auto op(const std::string&) noexcept = delete;
};
template <typename T>
struct convert_to_string
{
static std::string op(T) = delete;
};
} // namespace details
/** @brief Convert from a string to a native type.
*
* Some C++ types cannot be represented directly on dbus, so we encode
* them as strings. Enums are the primary example of this. This is a
* template function prototype for the conversion from string functions.
*
* @return A std::optional<T> containing the value if conversion is possible.
*/
template <typename T>
auto convert_from_string(const std::string& str) noexcept
{
return details::convert_from_string<T>::op(str);
};
/** @brief Convert from a native type to a string.
*
* Some C++ types cannot be represented directly on dbus, so we encode
* them as strings. Enums are the primary example of this. This is a
* template function prototype for the conversion to string functions.
*
* @return A std::string containing an encoding of the value, if conversion is
* possible.
*/
template <typename T>
std::string convert_to_string(T t)
{
return details::convert_to_string<T>::op(t);
}
namespace details
{
// SFINAE templates to determine if convert_from_string exists for a type.
template <typename T>
auto has_convert_from_string_helper(T)
-> decltype(convert_from_string<T>::op(std::declval<std::string>()),
std::true_type());
auto has_convert_from_string_helper(...) -> std::false_type;
template <typename T>
struct has_convert_from_string :
decltype(has_convert_from_string_helper(std::declval<T>()))
{};
template <typename T>
inline constexpr bool has_convert_from_string_v =
has_convert_from_string<T>::value;
// Specialization of 'convert_from_string' for variant.
template <typename... Types>
struct convert_from_string<std::variant<Types...>>
{
static auto op(const std::string& str)
-> std::optional<std::variant<Types...>>
{
if constexpr (0 < sizeof...(Types))
{
return process<Types...>(str);
}
return {};
}
// We need to iterate through all the variant types and find
// the one which matches the contents of the string. Often,
// a variant can contain both a convertible-type (ie. enum) and
// a string, so we need to iterate through all the convertible-types
// first and convert to string as a last resort.
template <typename T, typename... Args>
static auto process(const std::string& str)
-> std::optional<std::variant<Types...>>
{
// If convert_from_string exists for the type, attempt it.
if constexpr (has_convert_from_string_v<T>)
{
auto r = convert_from_string<T>::op(str);
if (r)
{
return r;
}
}
// If there are any more types in the variant, try them.
if constexpr (0 < sizeof...(Args))
{
auto r = process<Args...>(str);
if (r)
{
return r;
}
}
// Otherwise, if this is a string, do last-resort conversion.
if constexpr (std::is_same_v<std::string, std::remove_cv_t<T>>)
{
return str;
}
return {};
}
};
} // namespace details
/** Export template helper to determine if a type has convert_from_string. */
template <typename T>
inline constexpr bool has_convert_from_string_v =
details::has_convert_from_string_v<T>;
} // namespace message
} // namespace sdbusplus
namespace std
{
/** Overload of std::hash for details::string_wrappers */
template <>
struct hash<sdbusplus::message::details::string_wrapper>
{
using argument_type = sdbusplus::message::details::string_wrapper;
using result_type = std::size_t;
result_type operator()(argument_type const& s) const
{
return hash<std::string>()(s.str);
}
};
/** Overload of std::hash for details::string_wrappers */
template <>
struct hash<sdbusplus::message::details::string_path_wrapper>
{
using argument_type = sdbusplus::message::details::string_path_wrapper;
using result_type = std::size_t;
result_type operator()(argument_type const& s) const
{
return hash<std::string>()(s.str);
}
};
} // namespace std
<commit_msg>native_types: Fix pendantic error<commit_after>#pragma once
#include <optional>
#include <string>
#include <string_view>
#include <variant>
namespace sdbusplus
{
namespace message
{
namespace details
{
/** Simple wrapper class for std::string to allow conversion to and from an
* alternative typename. */
struct string_wrapper
{
std::string str;
string_wrapper() = default;
string_wrapper(const string_wrapper&) = default;
string_wrapper& operator=(const string_wrapper&) = default;
string_wrapper(string_wrapper&&) = default;
string_wrapper& operator=(string_wrapper&&) = default;
~string_wrapper() = default;
string_wrapper(const std::string& str) : str(str)
{}
string_wrapper(std::string&& str) : str(std::move(str))
{}
operator const std::string&() const volatile&
{
return const_cast<const string_wrapper*>(this)->str;
}
operator std::string&&() &&
{
return std::move(str);
}
bool operator==(const string_wrapper& r) const
{
return str == r.str;
}
bool operator!=(const string_wrapper& r) const
{
return str != r.str;
}
bool operator<(const string_wrapper& r) const
{
return str < r.str;
}
bool operator==(const std::string& r) const
{
return str == r;
}
bool operator!=(const std::string& r) const
{
return str != r;
}
bool operator<(const std::string& r) const
{
return str < r;
}
friend bool operator==(const std::string& l, const string_wrapper& r)
{
return l == r.str;
}
friend bool operator!=(const std::string& l, const string_wrapper& r)
{
return l != r.str;
}
friend bool operator<(const std::string& l, const string_wrapper& r)
{
return l < r.str;
}
};
/** Simple wrapper class for std::string to allow conversion to and from an
* alternative typename. */
struct string_path_wrapper
{
std::string str;
string_path_wrapper() = default;
string_path_wrapper(const string_path_wrapper&) = default;
string_path_wrapper& operator=(const string_path_wrapper&) = default;
string_path_wrapper(string_path_wrapper&&) = default;
string_path_wrapper& operator=(string_path_wrapper&&) = default;
~string_path_wrapper() = default;
string_path_wrapper(const std::string& str) : str(str)
{}
string_path_wrapper(std::string&& str) : str(std::move(str))
{}
operator const std::string&() const volatile&
{
return const_cast<const string_path_wrapper*>(this)->str;
}
operator std::string&&() &&
{
return std::move(str);
}
bool operator==(const string_path_wrapper& r) const
{
return str == r.str;
}
bool operator!=(const string_path_wrapper& r) const
{
return str != r.str;
}
bool operator<(const string_path_wrapper& r) const
{
return str < r.str;
}
bool operator==(const std::string& r) const
{
return str == r;
}
bool operator!=(const std::string& r) const
{
return str != r;
}
bool operator<(const std::string& r) const
{
return str < r;
}
friend bool operator==(const std::string& l, const string_path_wrapper& r)
{
return l == r.str;
}
friend bool operator!=(const std::string& l, const string_path_wrapper& r)
{
return l != r.str;
}
friend bool operator<(const std::string& l, const string_path_wrapper& r)
{
return l < r.str;
}
std::string filename() const;
string_path_wrapper parent_path() const;
string_path_wrapper operator/(std::string_view) const;
string_path_wrapper& operator/=(std::string_view);
};
/** Typename for sdbus SIGNATURE types. */
struct signature_type
{};
/** Typename for sdbus UNIX_FD types. */
struct unix_fd_type
{
int fd;
unix_fd_type() = default;
unix_fd_type(int f) : fd(f)
{}
operator int() const
{
return fd;
}
};
} // namespace details
/** std::string wrapper for OBJECT_PATH. */
using object_path = details::string_path_wrapper;
/** std::string wrapper for SIGNATURE. */
using signature = details::string_wrapper;
using unix_fd = details::unix_fd_type;
namespace details
{
template <typename T>
struct convert_from_string
{
static auto op(const std::string&) noexcept = delete;
};
template <typename T>
struct convert_to_string
{
static std::string op(T) = delete;
};
} // namespace details
/** @brief Convert from a string to a native type.
*
* Some C++ types cannot be represented directly on dbus, so we encode
* them as strings. Enums are the primary example of this. This is a
* template function prototype for the conversion from string functions.
*
* @return A std::optional<T> containing the value if conversion is possible.
*/
template <typename T>
auto convert_from_string(const std::string& str) noexcept
{
return details::convert_from_string<T>::op(str);
}
/** @brief Convert from a native type to a string.
*
* Some C++ types cannot be represented directly on dbus, so we encode
* them as strings. Enums are the primary example of this. This is a
* template function prototype for the conversion to string functions.
*
* @return A std::string containing an encoding of the value, if conversion is
* possible.
*/
template <typename T>
std::string convert_to_string(T t)
{
return details::convert_to_string<T>::op(t);
}
namespace details
{
// SFINAE templates to determine if convert_from_string exists for a type.
template <typename T>
auto has_convert_from_string_helper(T)
-> decltype(convert_from_string<T>::op(std::declval<std::string>()),
std::true_type());
auto has_convert_from_string_helper(...) -> std::false_type;
template <typename T>
struct has_convert_from_string :
decltype(has_convert_from_string_helper(std::declval<T>()))
{};
template <typename T>
inline constexpr bool has_convert_from_string_v =
has_convert_from_string<T>::value;
// Specialization of 'convert_from_string' for variant.
template <typename... Types>
struct convert_from_string<std::variant<Types...>>
{
static auto op(const std::string& str)
-> std::optional<std::variant<Types...>>
{
if constexpr (0 < sizeof...(Types))
{
return process<Types...>(str);
}
return {};
}
// We need to iterate through all the variant types and find
// the one which matches the contents of the string. Often,
// a variant can contain both a convertible-type (ie. enum) and
// a string, so we need to iterate through all the convertible-types
// first and convert to string as a last resort.
template <typename T, typename... Args>
static auto process(const std::string& str)
-> std::optional<std::variant<Types...>>
{
// If convert_from_string exists for the type, attempt it.
if constexpr (has_convert_from_string_v<T>)
{
auto r = convert_from_string<T>::op(str);
if (r)
{
return r;
}
}
// If there are any more types in the variant, try them.
if constexpr (0 < sizeof...(Args))
{
auto r = process<Args...>(str);
if (r)
{
return r;
}
}
// Otherwise, if this is a string, do last-resort conversion.
if constexpr (std::is_same_v<std::string, std::remove_cv_t<T>>)
{
return str;
}
return {};
}
};
} // namespace details
/** Export template helper to determine if a type has convert_from_string. */
template <typename T>
inline constexpr bool has_convert_from_string_v =
details::has_convert_from_string_v<T>;
} // namespace message
} // namespace sdbusplus
namespace std
{
/** Overload of std::hash for details::string_wrappers */
template <>
struct hash<sdbusplus::message::details::string_wrapper>
{
using argument_type = sdbusplus::message::details::string_wrapper;
using result_type = std::size_t;
result_type operator()(argument_type const& s) const
{
return hash<std::string>()(s.str);
}
};
/** Overload of std::hash for details::string_wrappers */
template <>
struct hash<sdbusplus::message::details::string_path_wrapper>
{
using argument_type = sdbusplus::message::details::string_path_wrapper;
using result_type = std::size_t;
result_type operator()(argument_type const& s) const
{
return hash<std::string>()(s.str);
}
};
} // namespace std
<|endoftext|> |
<commit_before>#include "UniformNegativeSampleGenerator.h"
vector<int>* UniformNegativeSampleGenerator::generate(RecDat* rec_dat){
if(!filter_repeats_){
int learnt = 0;
samples.clear();
int user_activity = train_matrix_->row_size(rec_dat->user);
while(learnt < negative_rate_ && learnt<(int)items_->size()-user_activity){
int item = items_->at((int)(rnd_.get()*(items_->size())));
if(!train_matrix_->has_value(rec_dat->user,item)){
learnt++;
samples.push_back(item);
}
}
return &samples;
} else { //no repeating items in the negative sample set
for(int i=indices_.size();i<items_->size();i++){
indices_.push_back(i);
}
int number_of_generated = 0;
int available = items_->size(); //==indices_.size()
samples.clear();
while(number_of_generated < negative_rate_ && available>0){
int idx_idx = ((int)(rnd_.get()*available));
int idx = indices_[idx_idx];
int item = items_->at(idx);
if(!train_matrix_->has_value(rec_dat->user,item)){
number_of_generated++;
samples.push_back(item);
}
indices_[idx_idx]=indices_[available-1];
indices_[available-1] = idx;
available--;
}
return &samples;
}
}
<commit_msg>remove unsigned warning<commit_after>#include "UniformNegativeSampleGenerator.h"
vector<int>* UniformNegativeSampleGenerator::generate(RecDat* rec_dat){
if(!filter_repeats_){
int learnt = 0;
samples.clear();
int user_activity = train_matrix_->row_size(rec_dat->user);
while(learnt < negative_rate_ && learnt<(int)items_->size()-user_activity){
int item = items_->at((int)(rnd_.get()*(items_->size())));
if(!train_matrix_->has_value(rec_dat->user,item)){
learnt++;
samples.push_back(item);
}
}
return &samples;
} else { //no repeating items in the negative sample set
for(uint i=indices_.size();i<items_->size();i++){
indices_.push_back(i);
}
int number_of_generated = 0;
int available = items_->size(); //==indices_.size()
samples.clear();
while(number_of_generated < negative_rate_ && available>0){
int idx_idx = ((int)(rnd_.get()*available));
int idx = indices_[idx_idx];
int item = items_->at(idx);
if(!train_matrix_->has_value(rec_dat->user,item)){
number_of_generated++;
samples.push_back(item);
}
indices_[idx_idx]=indices_[available-1];
indices_[available-1] = idx;
available--;
}
return &samples;
}
}
<|endoftext|> |
<commit_before>#include <QString>
#include <QtTest>
#include <Arangodbdriver.h>
#include <QueryBuilder.h>
#include <QBSelect.h>
class QueriesTest : public QObject
{
Q_OBJECT
public:
QueriesTest();
~QueriesTest();
private Q_SLOTS:
void initTestCase();
void cleanupTestCase();
void testGetAllDocuments();
void testLoadMoreResults();
void testGetDocByWhere();
void testGetMultipleDocsByWhere();
void testGetAllDocumentsFromTwoCollections();
private:
arangodb::Arangodbdriver driver;
arangodb::QueryBuilder qb;
arangodb::Collection * tempCollection = Q_NULLPTR;
arangodb::Collection * temp2Collection = Q_NULLPTR;
};
QueriesTest::QueriesTest()
{
tempCollection = driver.createCollection("temp");
tempCollection->save();
temp2Collection = driver.createCollection("temp2");
temp2Collection->save();
driver.waitUntilFinished(tempCollection, temp2Collection);
arangodb::Document * doc1 = tempCollection->createDocument();
doc1->set("test", true);
arangodb::Document * doc2 = tempCollection->createDocument();
doc2->set("test", false);
arangodb::Document * doc3 = tempCollection->createDocument();
doc3->set("test", true);
doc1->save();
doc2->save();
doc3->save();
driver.waitUntilFinished(doc1, doc2, doc3);
}
QueriesTest::~QueriesTest()
{
tempCollection->deleteAll();
tempCollection->waitUntilDeleted();
temp2Collection->deleteAll();
temp2Collection->waitUntilDeleted();
}
void QueriesTest::initTestCase()
{
}
void QueriesTest::cleanupTestCase()
{
}
void QueriesTest::testGetAllDocuments()
{
auto select = qb.createSelect(QStringLiteral("test"));
QCOMPARE(select->collections().first(), QStringLiteral("test"));
QCOMPARE(select->batchSize(), 15);
QCOMPARE(select->isCounting(), false);
auto cursor = driver.executeSelect(select);
cursor->waitForResult();
QVERIFY2(cursor->hasErrorOccurred() == false, cursor->errorMessage().toLocal8Bit());
QCOMPARE(cursor->count(), 4);
}
void QueriesTest::testLoadMoreResults()
{
auto select = qb.createSelect(QStringLiteral("test"), 2);
QCOMPARE(select->collections().first(), QStringLiteral("test"));
QCOMPARE(select->batchSize(), 2);
QCOMPARE(select->isCounting(), false);
auto cursor = driver.executeSelect(select);
cursor->waitForResult();
QVERIFY2(cursor->hasErrorOccurred() == false, cursor->errorMessage().toLocal8Bit());
QCOMPARE(cursor->hasMore(), true);
QCOMPARE(cursor->count(), 2);
cursor->getMoreData();
cursor->waitForResult();
QCOMPARE(cursor->hasErrorOccurred(), false);
QCOMPARE(cursor->hasMore(), false);
QCOMPARE(cursor->count(), 4);
}
void QueriesTest::testGetDocByWhere()
{
auto select = qb.createSelect(QStringLiteral("test"), 2);
QCOMPARE(select->collections().first(), QStringLiteral("test"));
QCOMPARE(select->batchSize(), 2);
QCOMPARE(select->isCounting(), false);
select->setWhere(QStringLiteral("name"), QStringLiteral("ll"));
auto cursor = driver.executeSelect(select);
cursor->waitForResult();
QVERIFY2(cursor->hasErrorOccurred() == false, cursor->errorMessage().toLocal8Bit());
QCOMPARE(cursor->hasMore(), false);
QCOMPARE(cursor->count(), 1);
}
void QueriesTest::testGetMultipleDocsByWhere()
{
auto select = qb.createSelect(QStringLiteral("webuser"), 2);
QCOMPARE(select->collections().first(), QStringLiteral("webuser"));
QCOMPARE(select->batchSize(), 2);
QCOMPARE(select->isCounting(), false);
QStringList vars;
vars << "saeschdivara" << "root";
select->setWhere(QStringLiteral("username"), vars);
auto cursor = driver.executeSelect(select);
cursor->waitForResult();
QVERIFY2(cursor->hasErrorOccurred() == false, cursor->errorMessage().toLocal8Bit());
QCOMPARE(cursor->hasMore(), false);
QCOMPARE(cursor->count(), 1);
}
void QueriesTest::testGetAllDocumentsFromTwoCollections()
{
auto select = qb.createSelect(tempCollection->name(), 2);
}
QTEST_MAIN(QueriesTest)
#include "tst_QueriesTest.moc"
<commit_msg>Added testGetAllDocumentsFromTwoCollections<commit_after>#include <QString>
#include <QtTest>
#include <Arangodbdriver.h>
#include <QueryBuilder.h>
#include <QBSelect.h>
class QueriesTest : public QObject
{
Q_OBJECT
public:
QueriesTest();
~QueriesTest();
private Q_SLOTS:
void initTestCase();
void cleanupTestCase();
void testGetAllDocuments();
void testLoadMoreResults();
void testGetDocByWhere();
void testGetMultipleDocsByWhere();
void testGetAllDocumentsFromTwoCollections();
private:
arangodb::Arangodbdriver driver;
arangodb::QueryBuilder qb;
arangodb::Collection * tempCollection = Q_NULLPTR;
arangodb::Collection * temp2Collection = Q_NULLPTR;
};
QueriesTest::QueriesTest()
{
tempCollection = driver.createCollection("temp");
tempCollection->save();
temp2Collection = driver.createCollection("temp2");
temp2Collection->save();
driver.waitUntilFinished(tempCollection, temp2Collection);
arangodb::Document * doc1 = tempCollection->createDocument();
doc1->set("test", true);
arangodb::Document * doc2 = tempCollection->createDocument();
doc2->set("test", false);
arangodb::Document * doc3 = tempCollection->createDocument();
doc3->set("test", true);
doc1->save();
doc2->save();
doc3->save();
driver.waitUntilFinished(doc1, doc2, doc3);
arangodb::Document * doc4 = temp2Collection->createDocument();
doc4->set("con", doc1->docID());
arangodb::Document * doc5 = temp2Collection->createDocument();
doc5->set("con", doc2->docID());
doc4->save();
doc5->save();
driver.waitUntilFinished(doc4, doc5);
}
QueriesTest::~QueriesTest()
{
tempCollection->deleteAll();
tempCollection->waitUntilDeleted();
temp2Collection->deleteAll();
temp2Collection->waitUntilDeleted();
}
void QueriesTest::initTestCase()
{
}
void QueriesTest::cleanupTestCase()
{
}
void QueriesTest::testGetAllDocuments()
{
auto select = qb.createSelect(QStringLiteral("test"));
QCOMPARE(select->collections().first(), QStringLiteral("test"));
QCOMPARE(select->batchSize(), 15);
QCOMPARE(select->isCounting(), false);
auto cursor = driver.executeSelect(select);
cursor->waitForResult();
QVERIFY2(cursor->hasErrorOccurred() == false, cursor->errorMessage().toLocal8Bit());
QCOMPARE(cursor->count(), 4);
}
void QueriesTest::testLoadMoreResults()
{
auto select = qb.createSelect(QStringLiteral("test"), 2);
QCOMPARE(select->collections().first(), QStringLiteral("test"));
QCOMPARE(select->batchSize(), 2);
QCOMPARE(select->isCounting(), false);
auto cursor = driver.executeSelect(select);
cursor->waitForResult();
QVERIFY2(cursor->hasErrorOccurred() == false, cursor->errorMessage().toLocal8Bit());
QCOMPARE(cursor->hasMore(), true);
QCOMPARE(cursor->count(), 2);
cursor->getMoreData();
cursor->waitForResult();
QCOMPARE(cursor->hasErrorOccurred(), false);
QCOMPARE(cursor->hasMore(), false);
QCOMPARE(cursor->count(), 4);
}
void QueriesTest::testGetDocByWhere()
{
auto select = qb.createSelect(QStringLiteral("test"), 2);
QCOMPARE(select->collections().first(), QStringLiteral("test"));
QCOMPARE(select->batchSize(), 2);
QCOMPARE(select->isCounting(), false);
select->setWhere(QStringLiteral("name"), QStringLiteral("ll"));
auto cursor = driver.executeSelect(select);
cursor->waitForResult();
QVERIFY2(cursor->hasErrorOccurred() == false, cursor->errorMessage().toLocal8Bit());
QCOMPARE(cursor->hasMore(), false);
QCOMPARE(cursor->count(), 1);
}
void QueriesTest::testGetMultipleDocsByWhere()
{
auto select = qb.createSelect(QStringLiteral("webuser"), 2);
QCOMPARE(select->collections().first(), QStringLiteral("webuser"));
QCOMPARE(select->batchSize(), 2);
QCOMPARE(select->isCounting(), false);
QStringList vars;
vars << "saeschdivara" << "root";
select->setWhere(QStringLiteral("username"), vars);
auto cursor = driver.executeSelect(select);
cursor->waitForResult();
QVERIFY2(cursor->hasErrorOccurred() == false, cursor->errorMessage().toLocal8Bit());
QCOMPARE(cursor->hasMore(), false);
QCOMPARE(cursor->count(), 1);
}
void QueriesTest::testGetAllDocumentsFromTwoCollections()
{
auto select = qb.createSelect(tempCollection->name(), 2);
select->addNewCollection(temp2Collection->name());
QCOMPARE(select->collections().size(), 2);
QCOMPARE(select->collections().at(0), QStringLiteral("temp"));
QCOMPARE(select->collections().at(1), QStringLiteral("temp2"));
auto cursor = driver.executeSelect(select);
cursor->waitForResult();
QVERIFY2(cursor->hasErrorOccurred() == false, cursor->errorMessage().toLocal8Bit());
QCOMPARE(cursor->hasMore(), true);
cursor->getMoreData();
cursor->waitForResult();
QVERIFY2(cursor->hasErrorOccurred() == false, cursor->errorMessage().toLocal8Bit());
QCOMPARE(cursor->hasMore(), true);
cursor->getMoreData();
cursor->waitForResult();
QVERIFY2(cursor->hasErrorOccurred() == false, cursor->errorMessage().toLocal8Bit());
QCOMPARE(cursor->hasMore(), false);
QCOMPARE(cursor->data().size(), 5);
}
QTEST_MAIN(QueriesTest)
#include "tst_QueriesTest.moc"
<|endoftext|> |
<commit_before>/* **********************************************************
* Copyright (c) 2012 Google, Inc. All rights reserved.
* **********************************************************/
/* Dr. Memory: the memory debugger
*
* 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;
* version 2.1 of the License, and no 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 Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <windows.h>
#include <objbase.h>
#include <stdlib.h>
// For shell link stuff.
#include <shobjidl.h>
#include <shlguid.h>
#pragma comment(lib, "ole32.lib")
#include "gtest/gtest.h"
// Ensure that CoInitializeEx test comes first, because many of the leaks
// happen once per process, and the callstacks through CoInitializeEx are
// harder to suppress due its tail call.
TEST(OleTest, CoInitializeEx) {
HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
ASSERT_TRUE(SUCCEEDED(hr));
CoUninitialize();
}
TEST(OleTest, CoInitialize) {
HRESULT hr = CoInitialize(NULL);
ASSERT_TRUE(SUCCEEDED(hr));
CoUninitialize();
}
TEST(OleTest, CoCreateInstance) {
HRESULT hr = CoInitialize(NULL);
ASSERT_TRUE(SUCCEEDED(hr));
// Some COM object for creating shortcut files. We just use it as an
// arbitrary object that we can create.
IShellLink* shell_link = NULL;
hr = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
IID_IShellLink, (LPVOID*)&shell_link);
ASSERT_TRUE(SUCCEEDED(hr));
shell_link->Release();
CoUninitialize();
}
<commit_msg>fixes issue 746 + dos2unix on ole_tests_win.cpp + fix build error for ole_tests_win.cpp with VS2005<commit_after>/* **********************************************************
* Copyright (c) 2012 Google, Inc. All rights reserved.
* **********************************************************/
/* Dr. Memory: the memory debugger
*
* 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;
* version 2.1 of the License, and no 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 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.
*/
#if _MSC_VER <= 1400
# define _WIN32_WINNT 0x0400 /* == NT4 */ /* not set for VS2005 */
#endif
#include <windows.h>
#include <objbase.h>
#include <stdlib.h>
// For shell link stuff.
#include <shobjidl.h>
#include <shlguid.h>
#pragma comment(lib, "ole32.lib")
#include "gtest/gtest.h"
// Ensure that CoInitializeEx test comes first, because many of the leaks
// happen once per process, and the callstacks through CoInitializeEx are
// harder to suppress due its tail call.
TEST(OleTest, CoInitializeEx) {
HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
ASSERT_TRUE(SUCCEEDED(hr));
CoUninitialize();
}
TEST(OleTest, CoInitialize) {
HRESULT hr = CoInitialize(NULL);
ASSERT_TRUE(SUCCEEDED(hr));
CoUninitialize();
}
TEST(OleTest, CoCreateInstance) {
HRESULT hr = CoInitialize(NULL);
ASSERT_TRUE(SUCCEEDED(hr));
// Some COM object for creating shortcut files. We just use it as an
// arbitrary object that we can create.
IShellLink* shell_link = NULL;
hr = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
IID_IShellLink, (LPVOID*)&shell_link);
ASSERT_TRUE(SUCCEEDED(hr));
shell_link->Release();
CoUninitialize();
}
<|endoftext|> |
<commit_before>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#define DUNE_STUFF_FUNCTIONS_DISABLE_CHECKS
// This one has to come first (includes the config.h)!
#include <dune/stuff/test/test_common.hh>
#ifdef HAVE_FASP
#undef HAVE_FASP
#endif
#include <dune/common/exceptions.hh>
#if HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H
#define ENABLE_ALUGRID 1
#include <dune/grid/alugrid.hh>
#else
#error This test requires ALUGrid!
#endif
#include <dune/stuff/common/color.hh>
#include <dune/stuff/common/print.hh>
#include <dune/stuff/common/float_cmp.hh>
#include "elliptic-testcases.hh"
#include "elliptic-cg-discretization.hh"
//#include "elliptic-sipdg-discretization.hh"
//#include "elliptic-swipdg-discretization.hh"
class errors_are_not_as_expected : public Dune::Exception
{
};
typedef Dune::ALUConformGrid<2, 2> AluConform2dGridType;
// change this to toggle output
std::ostream& test_out = std::cout;
// std::ostream& test_out = DSC_LOG.devnull();
typedef testing::Types<EllipticTestCase::ESV07<AluConform2dGridType>,
EllipticTestCase::LocalThermalBlock<AluConform2dGridType>,
EllipticTestCase::ER07<AluConform2dGridType>,
EllipticTestCase::MixedBoundaryTypes<AluConform2dGridType>,
EllipticTestCase::Spe10Model1<AluConform2dGridType>> AluConform2dTestCases;
std::vector<double> truncate_vector(const std::vector<double>& in, const size_t size)
{
assert(size <= in.size());
if (size == in.size())
return in;
else {
std::vector<double> out(size);
for (size_t ii = 0; ii < size; ++ii)
out[ii] = in[ii];
return out;
}
} // ... truncate_vector(...)
template <class TestCase>
struct EllipticCGDiscretization : public ::testing::Test
{
void produces_correct_results() const
{
const TestCase test_case;
test_case.print_header(test_out);
test_out << std::endl;
EllipticCG::EocStudy<TestCase, 1> eoc_study(test_case);
auto errors = eoc_study.run(test_out);
for (const auto& norm : eoc_study.provided_norms()) {
if (!Dune::Stuff::Common::FloatCmp::lt(errors[norm],
truncate_vector(eoc_study.expected_results(norm), errors[norm].size()))) {
std::stringstream ss;
Dune::Stuff::Common::print(errors[norm], "errors (" + norm + ")", ss);
Dune::Stuff::Common::print(eoc_study.expected_results(norm), " expected results (" + norm + ")", ss);
DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
}
}
}
}; // EllipticCGDiscretization
// template< class TestCase >
// struct EllipticSIPDGDiscretization
// : public ::testing::Test
//{
// void produces_correct_results() const
// {
// if (std::is_same< TestCase, EllipticTestCase::Spe10Model1< Dune::ALUConformGrid< 2, 2 > > >::value) {
// std::cerr
// << Dune::Stuff::Common::colorStringRed("EllipticSIPDGDiscretization does not work for "
// "EllipticTestCase::Spe10Model1< Dune::ALUConformGrid< 2, 2 > >!")
// << std::endl;
// } else {
// const TestCase test_case;
// test_case.print_header(test_out);
// test_out << std::endl;
// EllipticSIPDG::EocStudy< TestCase, 1 > eoc_study_1(test_case);
// auto errors_1 = eoc_study_1.run(test_out);
// for (const auto& norm : eoc_study_1.provided_norms()) {
// if (!Dune::Stuff::Common::FloatCmp::lt(errors_1[norm], eoc_study_1.expected_results(norm))) {
// std::stringstream ss;
// Dune::Stuff::Common::print(errors_1[norm], "errors (" + norm + ")", ss);
// Dune::Stuff::Common::print(eoc_study_1.expected_results(norm), " expected results (" + norm + ")", ss);
// DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
// }
// }
// test_out << std::endl;
// EllipticSIPDG::EocStudy< TestCase, 2 > eoc_study_2(test_case);
// auto errors_2 = eoc_study_2.run(test_out);
// for (const auto& norm : eoc_study_2.provided_norms())
// if (!Dune::Stuff::Common::FloatCmp::lt(errors_2[norm], eoc_study_2.expected_results(norm))) {
// std::stringstream ss;
// Dune::Stuff::Common::print(errors_2[norm], "errors (" + norm + ")", ss);
// Dune::Stuff::Common::print(eoc_study_2.expected_results(norm), " expected results (" + norm + ")", ss);
// DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
// }
// }
// }
//}; // EllipticSIPDGDiscretization
// template< class TestCase >
// struct EllipticSWIPDGDiscretization
// : public ::testing::Test
//{
// void produces_correct_results() const
// {
// const TestCase test_case;
// test_case.print_header(test_out);
// test_out << std::endl;
// EllipticSWIPDG::EocStudy< TestCase, 1 > eoc_study_1(test_case);
// auto errors_1 = eoc_study_1.run(test_out);
// for (const auto& norm : eoc_study_1.provided_norms()) {
// if (!Dune::Stuff::Common::FloatCmp::lt(errors_1[norm], eoc_study_1.expected_results(norm))) {
// std::stringstream ss;
// Dune::Stuff::Common::print(errors_1[norm], "errors (" + norm + ")", ss);
// Dune::Stuff::Common::print(eoc_study_1.expected_results(norm), " expected results (" + norm + ")", ss);
// DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
// }
// }
// test_out << std::endl;
// EllipticSWIPDG::EocStudy< TestCase, 2 > eoc_study_2(test_case);
// auto errors_2 = eoc_study_2.run(test_out);
// for (const auto& norm : eoc_study_2.provided_norms())
// if (!Dune::Stuff::Common::FloatCmp::lt(errors_2[norm], eoc_study_2.expected_results(norm))) {
// std::stringstream ss;
// Dune::Stuff::Common::print(errors_2[norm], "errors (" + norm + ")", ss);
// Dune::Stuff::Common::print(eoc_study_2.expected_results(norm), " expected results (" + norm + ")", ss);
// DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
// }
// }
//};
TYPED_TEST_CASE(EllipticCGDiscretization, AluConform2dTestCases);
TYPED_TEST(EllipticCGDiscretization, produces_correct_results)
{
this->produces_correct_results();
}
// TYPED_TEST_CASE(EllipticSIPDGDiscretization, AluConform2dTestCases);
// TYPED_TEST(EllipticSIPDGDiscretization, produces_correct_results) {
// this->produces_correct_results();
//}
// TYPED_TEST_CASE(EllipticSWIPDGDiscretization, AluConform2dTestCases);
// TYPED_TEST(EllipticSWIPDGDiscretization, produces_correct_results) {
// this->produces_correct_results();
//}
int main(int argc, char** argv)
{
try {
test_init(argc, argv);
return RUN_ALL_TESTS();
} catch (Dune::Exception& e) {
std::cerr << "\nDune reported error: " << e.what() << std::endl;
std::abort();
} catch (std::exception& e) {
std::cerr << "\n" << e.what() << std::endl;
std::abort();
} catch (...) {
std::cerr << "Unknown exception thrown!" << std::endl;
std::abort();
} // try
}
<commit_msg>[tests.elliptic-discretizations] reenabled sipdg<commit_after>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#define DUNE_STUFF_FUNCTIONS_DISABLE_CHECKS
// This one has to come first (includes the config.h)!
#include <dune/stuff/test/test_common.hh>
#ifdef HAVE_FASP
#undef HAVE_FASP
#endif
#include <dune/common/exceptions.hh>
#if HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H
#define ENABLE_ALUGRID 1
#include <dune/grid/alugrid.hh>
#else
#error This test requires ALUGrid!
#endif
#include <dune/stuff/common/color.hh>
#include <dune/stuff/common/print.hh>
#include <dune/stuff/common/float_cmp.hh>
#include "elliptic-testcases.hh"
#include "elliptic-cg-discretization.hh"
#include "elliptic-sipdg-discretization.hh"
//#include "elliptic-swipdg-discretization.hh"
class errors_are_not_as_expected : public Dune::Exception
{
};
typedef Dune::ALUConformGrid<2, 2> AluConform2dGridType;
// change this to toggle output
std::ostream& test_out = std::cout;
// std::ostream& test_out = DSC_LOG.devnull();
typedef testing::Types<EllipticTestCase::ESV07<AluConform2dGridType>,
EllipticTestCase::LocalThermalBlock<AluConform2dGridType>,
EllipticTestCase::ER07<AluConform2dGridType>,
EllipticTestCase::MixedBoundaryTypes<AluConform2dGridType>,
EllipticTestCase::Spe10Model1<AluConform2dGridType>> AluConform2dTestCases;
std::vector<double> truncate_vector(const std::vector<double>& in, const size_t size)
{
assert(size <= in.size());
if (size == in.size())
return in;
else {
std::vector<double> out(size);
for (size_t ii = 0; ii < size; ++ii)
out[ii] = in[ii];
return out;
}
} // ... truncate_vector(...)
template <class TestCase>
struct EllipticCGDiscretization : public ::testing::Test
{
void produces_correct_results() const
{
const TestCase test_case;
test_case.print_header(test_out);
test_out << std::endl;
EllipticCG::EocStudy<TestCase, 1> eoc_study(test_case);
auto errors = eoc_study.run(test_out);
for (const auto& norm : eoc_study.provided_norms()) {
if (!Dune::Stuff::Common::FloatCmp::lt(errors[norm],
truncate_vector(eoc_study.expected_results(norm), errors[norm].size()))) {
std::stringstream ss;
Dune::Stuff::Common::print(errors[norm], "errors (" + norm + ")", ss);
Dune::Stuff::Common::print(eoc_study.expected_results(norm), " expected results (" + norm + ")", ss);
DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
}
}
}
}; // EllipticCGDiscretization
template <class TestCase>
struct EllipticSIPDGDiscretization : public ::testing::Test
{
void produces_correct_results() const
{
if (std::is_same<TestCase, EllipticTestCase::Spe10Model1<Dune::ALUConformGrid<2, 2>>>::value) {
std::cerr << Dune::Stuff::Common::colorStringRed("EllipticSIPDGDiscretization does not work for "
"EllipticTestCase::Spe10Model1< Dune::ALUConformGrid< 2, 2 > >!")
<< std::endl;
} else {
const TestCase test_case;
test_case.print_header(test_out);
test_out << std::endl;
EllipticSIPDG::EocStudy<TestCase, 1> eoc_study_1(test_case);
auto errors_1 = eoc_study_1.run(test_out);
for (const auto& norm : eoc_study_1.provided_norms())
if (!Dune::Stuff::Common::FloatCmp::lt(errors_1[norm], eoc_study_1.expected_results(norm))) {
std::stringstream ss;
Dune::Stuff::Common::print(errors_1[norm], "errors (" + norm + ")", ss);
Dune::Stuff::Common::print(eoc_study_1.expected_results(norm), " expected results (" + norm + ")", ss);
DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
}
test_out << std::endl;
EllipticSIPDG::EocStudy<TestCase, 2> eoc_study_2(test_case);
auto errors_2 = eoc_study_2.run(test_out);
for (const auto& norm : eoc_study_2.provided_norms())
if (!Dune::Stuff::Common::FloatCmp::lt(errors_2[norm], eoc_study_2.expected_results(norm))) {
std::stringstream ss;
Dune::Stuff::Common::print(errors_2[norm], "errors (" + norm + ")", ss);
Dune::Stuff::Common::print(eoc_study_2.expected_results(norm), " expected results (" + norm + ")", ss);
DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
}
}
}
}; // EllipticSIPDGDiscretization
// template< class TestCase >
// struct EllipticSWIPDGDiscretization
// : public ::testing::Test
//{
// void produces_correct_results() const
// {
// const TestCase test_case;
// test_case.print_header(test_out);
// test_out << std::endl;
// EllipticSWIPDG::EocStudy< TestCase, 1 > eoc_study_1(test_case);
// auto errors_1 = eoc_study_1.run(test_out);
// for (const auto& norm : eoc_study_1.provided_norms()) {
// if (!Dune::Stuff::Common::FloatCmp::lt(errors_1[norm], eoc_study_1.expected_results(norm))) {
// std::stringstream ss;
// Dune::Stuff::Common::print(errors_1[norm], "errors (" + norm + ")", ss);
// Dune::Stuff::Common::print(eoc_study_1.expected_results(norm), " expected results (" + norm + ")", ss);
// DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
// }
// }
// test_out << std::endl;
// EllipticSWIPDG::EocStudy< TestCase, 2 > eoc_study_2(test_case);
// auto errors_2 = eoc_study_2.run(test_out);
// for (const auto& norm : eoc_study_2.provided_norms())
// if (!Dune::Stuff::Common::FloatCmp::lt(errors_2[norm], eoc_study_2.expected_results(norm))) {
// std::stringstream ss;
// Dune::Stuff::Common::print(errors_2[norm], "errors (" + norm + ")", ss);
// Dune::Stuff::Common::print(eoc_study_2.expected_results(norm), " expected results (" + norm + ")", ss);
// DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
// }
// }
//};
TYPED_TEST_CASE(EllipticCGDiscretization, AluConform2dTestCases);
TYPED_TEST(EllipticCGDiscretization, produces_correct_results)
{
this->produces_correct_results();
}
TYPED_TEST_CASE(EllipticSIPDGDiscretization, AluConform2dTestCases);
TYPED_TEST(EllipticSIPDGDiscretization, produces_correct_results)
{
this->produces_correct_results();
}
// TYPED_TEST_CASE(EllipticSWIPDGDiscretization, AluConform2dTestCases);
// TYPED_TEST(EllipticSWIPDGDiscretization, produces_correct_results) {
// this->produces_correct_results();
//}
int main(int argc, char** argv)
{
try {
test_init(argc, argv);
return RUN_ALL_TESTS();
} catch (Dune::Exception& e) {
std::cerr << "\nDune reported error: " << e.what() << std::endl;
std::abort();
} catch (std::exception& e) {
std::cerr << "\n" << e.what() << std::endl;
std::abort();
} catch (...) {
std::cerr << "Unknown exception thrown!" << std::endl;
std::abort();
} // try
}
<|endoftext|> |
<commit_before>//
// PROJECT CHRONO - http://projectchrono.org
//
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file at the top level of the distribution
// and at http://projectchrono.org/license-chrono.txt.
//
///////////////////////////////////////////////////
//
// A tracked vehicle, M113, built and simulated using the trackedVehicle library.
// Build the vehicle using a hierarchy of subsystems.
// Simulate by GUI input to an irrlicht EventReceiver.
// - similar to demo_tracks:
// - model track shoes with simple or complex collision geometry
// - using clones of collision shapes
// - use SetFamilyMaskNoCollisionWithFamily, SetFamily etc., to avoid collisions between different families of bodies.
//
// Author: Justin Madsen, (c) 2014
///////////////////////////////////////////////////
#include "physics/ChSystem.h"
#include "particlefactory/ChParticleEmitter.h"
#include "assets/ChTexture.h"
#include "assets/ChColorAsset.h"
#include "unit_IRRLICHT/ChIrrApp.h"
#include "subsys/driver/ChIrrGuiTrack.h"
#include "subsys/trackVehicle/trackVehicle.h"
// Use the main namespace of Chrono, and other chrono namespaces
using namespace chrono;
using namespace chrono::geometry;
// Use the main namespaces of Irrlicht
using namespace irr;
using namespace core;
using namespace scene;
using namespace video;
using namespace io;
using namespace gui;
#include <irrlicht.h>
int main(int argc, char* argv[])
{
// no system to create, it's in the trackVehicle
// ..the tank (this class - see above - is a 'set' of bodies and links, automatically added at creation)
TrackVehicle vehicle("name");
// Create the Irrlicht visualization applicaiton
ChIrrApp application(&vehicle, L"Modeling a simplified tank",core::dimension2d<u32>(800,600),false, true);
// Easy shortcuts to add logo, camera, lights and sky in Irrlicht scene:
ChIrrWizard::add_typical_Logo(application.GetDevice());
ChIrrWizard::add_typical_Sky(application.GetDevice());
ChIrrWizard::add_typical_Lights(application.GetDevice());
ChIrrWizard::add_typical_Camera(application.GetDevice(), core::vector3df(0,0,-6), core::vector3df(-2,2,0));
// ground plate
ChSharedPtr<ChBody> ground(new ChBodyEasyBox(60.0, 1.0, 100.0, 1000.0, true, true);
ground->SetFriction(1.0);
my_system.Add(ground); // add this body to the system
// ..some obstacles on the ground:
for (int i=0; i<50; i++)
{
ChBodySceneNode* my_obstacle = (ChBodySceneNode*)addChBodySceneNode_easyBox(
&my_system, application.GetSceneManager(),
3.0,
ChVector<>(-6+6*ChRandom(),2+1*ChRandom(), 6*ChRandom()),
Q_from_AngAxis(ChRandom()*CH_C_PI, VECT_Y),
ChVector<>(0.6*(1-0.4*ChRandom()),
0.08,
0.3*(1-0.4*ChRandom()) ) );
my_obstacle->addShadowVolumeSceneNode();
}
//
// USER INTERFACE
//
// Create some graphical-user-interface (GUI) items to show on the screen.
// This requires an event receiver object.
MyEventReceiver receiver(&application, vehicle);
// note how to add the custom event receiver to the default interface:
application.SetUserEventReceiver(&receiver);
//
// SETTINGS
//
my_system.SetIterLCPmaxItersSpeed(100); // the higher, the easier to keep the constraints 'mounted'.
my_system.SetLcpSolverType(ChSystem::LCP_ITERATIVE_SOR);
//
// THE SOFT-REAL-TIME CYCLE, SHOWING THE SIMULATION
//
application.SetStepManage(true);
application.SetTimestep(0.03);
application.SetTryRealtime(true);
while(application.GetDevice()->run())
{
// Irrlicht must prepare frame to draw
application.GetVideoDriver()->beginScene(true, true, SColor(255,140,161,192));
// .. draw solid 3D items (boxes, cylinders, shapes) belonging to Irrlicht scene, if any
application.DrawAll();
// .. draw also a grid (rotated so that it's horizontal)
ChIrrTools::drawGrid(application.GetVideoDriver(), 2, 2, 30,30,
ChCoordsys<>(ChVector<>(0,0.01,0), Q_from_AngX(CH_C_PI_2) ),
video::SColor(255, 60,60,60), true);
// HERE CHRONO INTEGRATION IS PERFORMED:
application.DoStep();
application.GetVideoDriver()->endScene();
}
if (mytank) delete mytank;
return 0;
}
<commit_msg>updating the includes to use with a tracked vehicle demo<commit_after>//
// PROJECT CHRONO - http://projectchrono.org
//
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file at the top level of the distribution
// and at http://projectchrono.org/license-chrono.txt.
//
///////////////////////////////////////////////////
//
// A tracked vehicle, M113, built and simulated using the trackedVehicle library.
// Build the vehicle using a hierarchy of subsystems.
// Simulate by GUI input to an irrlicht EventReceiver.
// - similar to demo_tracks:
// - model track shoes with simple or complex collision geometry
// - using clones of collision shapes
// - use SetFamilyMaskNoCollisionWithFamily, SetFamily etc., to avoid collisions between different families of bodies.
//
// Author: Justin Madsen, (c) 2014
///////////////////////////////////////////////////
#include "physics/ChSystem.h"
// #include "particlefactory/ChParticleEmitter.h"
#include "core/ChFileutils.h"
#include "core/ChStream.h"
#include "core/ChRealtimeStep.h"
#include "physics/ChSystem.h"
#include "physics/ChLinkDistance.h"
#include "utils/ChUtilsInputOutput.h"
#include "utils/ChUtilsData.h"
#include "assets/ChTexture.h"
#include "assets/ChColorAsset.h"
/*
#if IRRLICHT_ENABLED
*/
#include "unit_IRRLICHT/ChIrrApp.h"
#include "subsys/driver/ChIrrGuiTrack.h"
/*
# define USE_IRRLICHT
#endif
*/
#include "subsys/trackVehicle/trackVehicle.h"
// Use the main namespace of Chrono
using namespace chrono;
// Use the main namespaces of Irrlicht
using namespace irr;
using namespace core;
// // Initial vehicle position
ChVector<> initLoc(0, 1.0, 0);
// Initial vehicle orientation
ChQuaternion<> initRot(1, 0, 0, 0);
//ChQuaternion<> initRot(0.866025, 0, 0, 0.5);
//ChQuaternion<> initRot(0.7071068, 0, 0, 0.7071068);
//ChQuaternion<> initRot(0.25882, 0, 0, 0.965926);
//ChQuaternion<> initRot(0, 0, 0, 1);
// Simulation step size
double step_size = 0.001;
// Time interval between two render frames
int FPS = 50;
double render_step_size = 1.0 / FPS; // FPS = 50
// #ifdef USE_IRRLICHT
// Point on chassis tracked by the camera
ChVector<> trackPoint(0.0, 0.0, .75);
/*
#else
double tend = 20.0;
const std::string out_dir = "../HMMWV9";
const std::string pov_dir = out_dir + "/POVRAY";
#endif
*/
int main(int argc, char* argv[])
{
// no system to create, it's in the TrackVehicle
TrackVehicle vehicle("name");
vehicle.Initialize(ChCoordsys<>(initLoc, initRot));
/*
#ifdef USE_IRRLICHT
*/
// Create the Irrlicht visualization applicaiton
ChIrrApp application(&vehicle,
L"HMMWV 9-body demo",
dimension2d<u32>(1000, 800),
false,
true);
// make a skybox that has Z pointing up (default application.AddTypicalSky() makes Y up)
std::string mtexturedir = GetChronoDataFile("skybox/");
std::string str_lf = mtexturedir + "sky_lf.jpg";
std::string str_up = mtexturedir + "sky_up.jpg";
std::string str_dn = mtexturedir + "sky_dn.jpg";
irr::video::ITexture* map_skybox_side =
application.GetVideoDriver()->getTexture(str_lf.c_str());
irr::scene::ISceneNode* mbox = application.GetSceneManager()->addSkyBoxSceneNode(
application.GetVideoDriver()->getTexture(str_up.c_str()),
application.GetVideoDriver()->getTexture(str_dn.c_str()),
map_skybox_side,
map_skybox_side,
map_skybox_side,
map_skybox_side);
mbox->setRotation( irr::core::vector3df(0,0,0));
bool do_shadows = true; // shadow map is experimental
irr::scene::ILightSceneNode* mlight = 0;
if (do_shadows)
{
mlight = application.AddLightWithShadow(
irr::core::vector3df(10.f, 30.f, 60.f),
irr::core::vector3df(0.f, 0.f, 0.f),
150, 60, 80, 15, 512, irr::video::SColorf(1, 1, 1), false, false);
}
else
{
application.AddTypicalLights(
irr::core::vector3df(30.f, -30.f, 100.f),
irr::core::vector3df(30.f, 50.f, 100.f),
250, 130);
}
application.SetTimestep(step_size);
ChIrrGuiTrack driver();
// ground plate
ChSharedPtr<ChBody> ground(new ChBodyEasyBox(60.0, 1.0, 100.0, 1000.0, true, true);
ground->SetFriction(1.0);
my_system.Add(ground); // add this body to the system
// ..some obstacles on the ground:
for (int i=0; i<50; i++)
{
ChBodySceneNode* my_obstacle = (ChBodySceneNode*)addChBodySceneNode_easyBox(
&my_system, application.GetSceneManager(),
3.0,
ChVector<>(-6+6*ChRandom(),2+1*ChRandom(), 6*ChRandom()),
Q_from_AngAxis(ChRandom()*CH_C_PI, VECT_Y),
ChVector<>(0.6*(1-0.4*ChRandom()),
0.08,
0.3*(1-0.4*ChRandom()) ) );
my_obstacle->addShadowVolumeSceneNode();
}
//
// USER INTERFACE
//
// Create some graphical-user-interface (GUI) items to show on the screen.
// This requires an event receiver object.
MyEventReceiver receiver(&application, vehicle);
// note how to add the custom event receiver to the default interface:
application.SetUserEventReceiver(&receiver);
//
// SETTINGS
//
my_system.SetIterLCPmaxItersSpeed(100); // the higher, the easier to keep the constraints 'mounted'.
my_system.SetLcpSolverType(ChSystem::LCP_ITERATIVE_SOR);
//
// THE SOFT-REAL-TIME CYCLE, SHOWING THE SIMULATION
//
application.SetStepManage(true);
application.SetTimestep(0.03);
application.SetTryRealtime(true);
while(application.GetDevice()->run())
{
// Irrlicht must prepare frame to draw
application.GetVideoDriver()->beginScene(true, true, SColor(255,140,161,192));
// .. draw solid 3D items (boxes, cylinders, shapes) belonging to Irrlicht scene, if any
application.DrawAll();
// .. draw also a grid (rotated so that it's horizontal)
ChIrrTools::drawGrid(application.GetVideoDriver(), 2, 2, 30,30,
ChCoordsys<>(ChVector<>(0,0.01,0), Q_from_AngX(CH_C_PI_2) ),
video::SColor(255, 60,60,60), true);
// HERE CHRONO INTEGRATION IS PERFORMED:
application.DoStep();
application.GetVideoDriver()->endScene();
}
if (mytank) delete mytank;
return 0;
}
<|endoftext|> |
<commit_before>#ifndef DUNE_STUFF_WALK_HH_INCLUDED
#define DUNE_STUFF_WALK_HH_INCLUDED
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#else
#include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG
#include <dune/common/static_assert.hh>
#include <dune/common/fvector.hh>
#include <dune/common/deprecated.hh>
#include <dune/stuff/common/math.hh>
#include <dune/stuff/common/misc.hh>
#include <dune/stuff/common/ranges.hh>
#include <dune/grid/common/geometry.hh>
#include <vector>
#include <boost/format.hpp>
namespace Dune {
namespace Stuff {
namespace Grid {
using namespace Dune::Stuff::Common;
/** \brief Useful dummy functor if you don't have anything to do on entities/intersections
**/
struct GridWalkDummyFunctor {
GridWalkDummyFunctor(){}
template < class Entity >
void operator() ( const Entity&, const int) const
{}
template < class Entity, class Intersection >
void operator() ( const Entity&, const Intersection&) const
{}
};
namespace {
/** \brief global \ref GridWalkDummyFunctor instance
**/
const GridWalkDummyFunctor gridWalkDummyFunctor;
}
/** \brief applies Functors on each \ref Entity/\ref Intersection of a given \ref GridView
* \todo allow stacking of functor to save gridwalks?
* \tparam GridViewType any \ref GridView interface compliant type
* \tparam codim determines the codim of the Entities that are iterated on
**/
template < class GridViewImp, int codim = 0 >
class GridWalk {
typedef Dune::GridView<typename GridViewImp::Traits> GridViewType;
public:
GridWalk ( const GridViewType& gp )
: gridView_( gp )
{}
/** \param entityFunctor is applied on all codim 0 entities presented by \var gridView_
* \param intersectionFunctor is applied on all Intersections of all codim 0 entities
* presented by \var gridView_
* \note only instantiable for codim == 0
*/
template < class EntityFunctor, class IntersectionFunctor >
void operator () ( EntityFunctor& entityFunctor, IntersectionFunctor& intersectionFunctor ) const
{
dune_static_assert( codim == 0, "walking intersections is only possible for codim 0 entities" );
for (const auto& entity : Common::viewRange(gridView_)) {
const int entityIndex = gridView_.indexSet().index(entity);
entityFunctor( entity, entityIndex);
for (const auto& intersection : intersectionRange(gridView_, entity)) {
intersectionFunctor( entity, intersection);
}
}
}
/** \param entityFunctor is applied on all codim entities presented by \var gridView_
* \note only instantiable for codim < GridView::dimension
*/
template < class EntityFunctor >
void operator () ( EntityFunctor& entityFunctor ) const
{
dune_static_assert( codim <= GridViewType::dimension, "codim too high to walk" );
for (const auto& entity : viewRange(gridView_)) {
const int entityIndex = gridView_.indexSet().index(entity);
entityFunctor( entity, entityIndex);
}
}
template< class Functor >
void walkCodim0(Functor& f) const DUNE_DEPRECATED_MSG("use operator()(Functor) instead ");
private:
const GridViewType& gridView_;
};
template< class V, int i >
template< class Functor >
void GridWalk<V,i>::walkCodim0(Functor& f) const {
this->operator()(f);
}
} // namespace Grid
} // namespace Stuff
} // namespace Dune
#endif // ifndef DUNE_STUFF_WALK_HH_INCLUDED
/** Copyright (c) 2012, Felix Albrecht, Rene Milk
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the FreeBSD Project.
**/
<commit_msg>[grid] adds GridWalk generator function<commit_after>#ifndef DUNE_STUFF_WALK_HH_INCLUDED
#define DUNE_STUFF_WALK_HH_INCLUDED
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#else
#include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG
#include <dune/common/static_assert.hh>
#include <dune/common/fvector.hh>
#include <dune/common/deprecated.hh>
#include <dune/stuff/common/math.hh>
#include <dune/stuff/common/misc.hh>
#include <dune/stuff/common/ranges.hh>
#include <dune/grid/common/geometry.hh>
#include <vector>
#include <boost/format.hpp>
namespace Dune {
namespace Stuff {
namespace Grid {
using namespace Dune::Stuff::Common;
/** \brief Useful dummy functor if you don't have anything to do on entities/intersections
**/
struct GridWalkDummyFunctor {
GridWalkDummyFunctor(){}
template < class Entity >
void operator() ( const Entity&, const int) const
{}
template < class Entity, class Intersection >
void operator() ( const Entity&, const Intersection&) const
{}
};
namespace {
/** \brief global \ref GridWalkDummyFunctor instance
**/
const GridWalkDummyFunctor gridWalkDummyFunctor;
}
/** \brief applies Functors on each \ref Entity/\ref Intersection of a given \ref GridView
* \todo allow stacking of functor to save gridwalks?
* \tparam GridViewType any \ref GridView interface compliant type
* \tparam codim determines the codim of the Entities that are iterated on
**/
template < class GridViewImp, int codim = 0 >
class GridWalk {
typedef Dune::GridView<typename GridViewImp::Traits> GridViewType;
public:
GridWalk ( const GridViewType& gp )
: gridView_( gp )
{}
/** \param entityFunctor is applied on all codim 0 entities presented by \var gridView_
* \param intersectionFunctor is applied on all Intersections of all codim 0 entities
* presented by \var gridView_
* \note only instantiable for codim == 0
*/
template < class EntityFunctor, class IntersectionFunctor >
void operator () ( EntityFunctor& entityFunctor, IntersectionFunctor& intersectionFunctor ) const
{
dune_static_assert( codim == 0, "walking intersections is only possible for codim 0 entities" );
for (const auto& entity : Common::viewRange(gridView_)) {
const int entityIndex = gridView_.indexSet().index(entity);
entityFunctor( entity, entityIndex);
for (const auto& intersection : intersectionRange(gridView_, entity)) {
intersectionFunctor( entity, intersection);
}
}
}
/** \param entityFunctor is applied on all codim entities presented by \var gridView_
* \note only instantiable for codim < GridView::dimension
*/
template < class EntityFunctor >
void operator () ( EntityFunctor& entityFunctor ) const
{
dune_static_assert( codim <= GridViewType::dimension, "codim too high to walk" );
for (const auto& entity : viewRange(gridView_)) {
const int entityIndex = gridView_.indexSet().index(entity);
entityFunctor( entity, entityIndex);
}
}
template< class Functor >
void walkCodim0(Functor& f) const DUNE_DEPRECATED_MSG("use operator()(Functor) instead ");
private:
const GridViewType& gridView_;
};
template< class V, int i >
template< class Functor >
void GridWalk<V,i>::walkCodim0(Functor& f) const {
this->operator()(f);
}
//!
template <class ViewImp, int codim = 0>
GridWalk< Dune::GridView<ViewImp>, codim > make_gridwalk(const Dune::GridView<ViewImp>& view) {
return GridWalk< Dune::GridView<ViewImp>, codim >(view);
}
} // namespace Grid
} // namespace Stuff
} // namespace Dune
#endif // ifndef DUNE_STUFF_WALK_HH_INCLUDED
/** Copyright (c) 2012, Felix Albrecht, Rene Milk
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the FreeBSD Project.
**/
<|endoftext|> |
<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
#include <BALL/DOCKING/COMMON/poseClustering.h>
#include <BALL/FORMAT/DCDFile.h>
#include <BALL/FORMAT/PDBFile.h>
#include <BALL/DOCKING/COMMON/conformationSet.h>
#include <BALL/FORMAT/commandlineParser.h>
#include <iostream>
#include "version.h"
using namespace std;
using namespace BALL;
int main (int argc, char **argv)
{
// instantiate CommandlineParser object supplying
// - tool name
// - short description
// - version string
// - build date
// - category
CommandlineParser parpars("DockPoseClustering", "clusters docking poses ", VERSION, String(__DATE__), "Docking");
// we register an input file parameter
// - CLI switch
// - description
// - Inputfile
// - required
parpars.registerParameter("i_dcd", "input dcd-file", INFILE, true);
parpars.registerParameter("i_pdb", "input pdb-file", INFILE, true);
// we register an output file parameter
// - description
// - Outputfile
// - required
parpars.registerParameter("o", "output dcd-file name for first solution", STRING, true, "", true);
parpars.registerParameter("o_id", "output id", STRING, true, "", true);
parpars.registerParameter("o_dir", "output directory for 2nd to last solution", STRING, true, "", true);
// register String parameter for supplying max number of solutions
parpars.registerParameter("rmsd_cutoff", "minimal rmsd between the final clusters (default 5.0) ", DOUBLE, false, 5.0);
parpars.setParameterRestrictions("rmsd_cutoff", 0, 100);
// choice of atom rmsd scope
parpars.registerParameter("rmsd_scope", "atoms to be considered for rmsd score (C_ALPHA, BACKBONE, ALL_ATOMS) ", STRING, false, "C_ALPHA");
list<String> rmsd_levels;
rmsd_levels.push_back("C_ALPHA");
//rmsd_levels.push_back("HEAVY_ATOMS"); //TODO
rmsd_levels.push_back("BACKBONE");
rmsd_levels.push_back("ALL_ATOMS");
parpars.setParameterRestrictions("rmsd_scope", rmsd_levels);
// the manual
String man = "This tool computes clusters of docking poses given as conformation set using a complete linkage algorithm.\n\nParameters are the input ConformationSet (-i_dcd), one corresponding pdb file (-i_pdb) and a naming schema for the results (-o). Optional parameters the minimal rmsd between the final clusters (-rmsd_cutoff) and the scope/level of detail of the rmsd computation (-rmsd_scope).\n\nOutput of this tool is a number of dcd files each containing one ConformationSet.";
parpars.setToolManual(man);
// here we set the types of I/O files, for example sdf is also allowed
parpars.setSupportedFormats("i_dcd","dcd");
parpars.setSupportedFormats("i_pdb","pdb");
parpars.setSupportedFormats("o","dcd");
parpars.parse(argc, argv);
//////////////////////////////////////////////////
// read the input
PDBFile pdb;
pdb.open(parpars.get("i_pdb"));
System sys;
pdb.read(sys);
ConformationSet cs;
cs.setup(sys);
cs.readDCDFile(parpars.get("i_dcd"));
cs.resetScoring();
PoseClustering pc;
if (parpars.has("rmsd_cutoff"))
{
float rmsd = parpars.get("rmsd_cutoff").toInt();
pc.options.setReal(PoseClustering::Option::RMSD_THRESHOLD, rmsd);
}
if (parpars.has("rmsd_scope"))
{
String scope = parpars.get("rmsd_scope");
if (scope == "C_ALPHA")
pc.options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::RMSDLevelOfDetail::C_ALPHA);
else if (scope == "BACKBONE")
pc.options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::RMSDLevelOfDetail::BACKBONE);
else if (scope == "ALL_ATOMS")
pc.options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::RMSDLevelOfDetail::ALL_ATOMS);
}
pc.setConformationSet(&cs);
pc.compute();
Size num_clusters = pc.getNumberOfClusters();
for (Size i = 0; i < num_clusters; i++)
{
Log << " Cluster " << i << " has " << pc.getClusterSize(i) << " members." << endl;
boost::shared_ptr<ConformationSet> new_cs = pc.getClusterConformationSet(i);
String outfile_name = (i == 0) ? String(parpars.get("o"))
: String(parpars.get("o_dir")) + "/primary_"
+ String(parpars.get("o_id")) + "_cluster" + String(i)
+ "_visible_dcd";
//Log << " Writing solution " << String(i) << " as " << outfile_name << endl;
// GenericMolFile* outfile = MolFileFactory::open(outfile_name, ios::out);
//DCD2File outfile(outfile_name, ios::out);
//outfile << new_cs;
//outfile.close();
new_cs->writeDCDFile(outfile_name);
}
Log << "done." << endl;
return 0;
}
<commit_msg>added parameter for tool DockPoseClustering<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
#include <BALL/DOCKING/COMMON/poseClustering.h>
#include <BALL/FORMAT/DCDFile.h>
#include <BALL/FORMAT/PDBFile.h>
#include <BALL/DOCKING/COMMON/conformationSet.h>
#include <BALL/FORMAT/commandlineParser.h>
#include <iostream>
#include "version.h"
using namespace std;
using namespace BALL;
int main (int argc, char **argv)
{
// instantiate CommandlineParser object supplying
// - tool name
// - short description
// - version string
// - build date
// - category
CommandlineParser parpars("DockPoseClustering", "clusters docking poses ", VERSION, String(__DATE__), "Docking");
// we register an input file parameter
// - CLI switch
// - description
// - Inputfile
// - required
parpars.registerParameter("i_dcd", "input dcd-file", INFILE, true);
parpars.registerParameter("i_pdb", "input pdb-file", INFILE, true);
// we register an output file parameter
// - description
// - Outputfile
// - required
parpars.registerParameter("o", "output dcd-file name for first solution ", STRING, true, "", true);
parpars.registerParameter("o_id", "output id ", STRING, true, "", true);
parpars.registerParameter("o_dir", "output directory for 2nd to last solution ", STRING, true, "", true);
parpars.registerParameter("o_dcd", "output directory for the reduced cluster set (one structure per final cluster) ", STRING, false, "", true);
// register String parameter for supplying minimal rmsd between clusters
parpars.registerParameter("rmsd_cutoff", "minimal rmsd between the final clusters (default 5.0) ", DOUBLE, false, 5.0);
parpars.setParameterRestrictions("rmsd_cutoff", 0, 100);
// choice of atom rmsd scope
parpars.registerParameter("rmsd_scope", "atoms to be considered for rmsd score (C_ALPHA, BACKBONE, ALL_ATOMS) ", STRING, false, "C_ALPHA");
list<String> rmsd_levels;
rmsd_levels.push_back("C_ALPHA");
//rmsd_levels.push_back("HEAVY_ATOMS"); //TODO
rmsd_levels.push_back("BACKBONE");
rmsd_levels.push_back("ALL_ATOMS");
parpars.setParameterRestrictions("rmsd_scope", rmsd_levels);
// the manual
String man = "This tool computes clusters of docking poses given as conformation set using a complete linkage algorithm.\n\nParameters are the input ConformationSet (-i_dcd), one corresponding pdb file (-i_pdb) and a naming schema for the results (-o). Optional parameters are the minimal rmsd between the final clusters (-rmsd_cutoff) and the scope/level of detail of the rmsd computation (-rmsd_scope). The optional parameter (-o_dcd)\n\nOutput of this tool is a number of dcd files each containing one ConformationSet.";
parpars.setToolManual(man);
// here we set the types of I/O files
parpars.setSupportedFormats("i_dcd","dcd");
parpars.setSupportedFormats("i_pdb","pdb");
parpars.setSupportedFormats("o","dcd");
parpars.setSupportedFormats("o_dcd","dcd");
parpars.parse(argc, argv);
//////////////////////////////////////////////////
// read the input
PDBFile pdb;
pdb.open(parpars.get("i_pdb"));
System sys;
pdb.read(sys);
ConformationSet cs;
cs.setup(sys);
cs.readDCDFile(parpars.get("i_dcd"));
cs.resetScoring();
PoseClustering pc;
if (parpars.has("rmsd_cutoff"))
{
float rmsd = parpars.get("rmsd_cutoff").toInt();
pc.options.setReal(PoseClustering::Option::RMSD_THRESHOLD, rmsd);
}
if (parpars.has("rmsd_scope"))
{
String scope = parpars.get("rmsd_scope");
if (scope == "C_ALPHA")
pc.options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::RMSDLevelOfDetail::C_ALPHA);
else if (scope == "BACKBONE")
pc.options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::RMSDLevelOfDetail::BACKBONE);
else if (scope == "ALL_ATOMS")
pc.options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::RMSDLevelOfDetail::ALL_ATOMS);
}
pc.setConformationSet(&cs);
pc.compute();
Size num_clusters = pc.getNumberOfClusters();
for (Size i = 0; i < num_clusters; i++)
{
Log << " Cluster " << i << " has " << pc.getClusterSize(i) << " members." << endl;
boost::shared_ptr<ConformationSet> new_cs = pc.getClusterConformationSet(i);
String outfile_name = (i == 0) ? String(parpars.get("o"))
: String(parpars.get("o_dir")) + "/primary_"
+ String(parpars.get("o_id")) + "_cluster" + String(i)
+ "_visible_dcd";
//Log << " Writing solution " << String(i) << " as " << outfile_name << endl;
new_cs->writeDCDFile(outfile_name);
}
if (parpars.has("o_dcd"))
{
String outfile_name = String(parpars.get("o_dcd"));
boost::shared_ptr<ConformationSet> cs = pc.getReducedConformationSet();
cs->writeDCDFile(outfile_name);
}
Log << "done." << endl;
return 0;
}
<|endoftext|> |
<commit_before>#include <iterator>
#include "kernel.h"
#include "coverage.h"
#include "numericrange.h"
#include "numericdomain.h"
#include "columndefinition.h"
#include "table.h"
#include "attributerecord.h"
#include "geometry.h"
#include "feature.h"
#include "featurecoverage.h"
#include "featureiterator.h"
using namespace Ilwis;
FeatureIterator::FeatureIterator(const IFeatureCoverage& fcoverage) : _fcoverage(fcoverage), _isInitial(true), _trackCounter(0),_flow(fFEATURES)
{
}
FeatureIterator::FeatureIterator(const Ilwis::IFeatureCoverage &fcoverage, const Box3D<double>& envelope) :
_fcoverage(fcoverage),
_isInitial(true),
_envelope(envelope),
_trackCounter(0),
_flow(fFEATURES)
{
}
FeatureIterator::FeatureIterator(const FeatureIterator &iter)
{
_fcoverage = iter._fcoverage;
_isInitial = iter._isInitial;
_iterFeatures = iter._iterFeatures;
_trackCounter = iter._trackCounter;
_flow = iter._flow;
}
FeatureIterator &FeatureIterator::operator ++()
{
if (!init()){
move();
}
return *this;
}
FeatureIterator FeatureIterator::operator ++(int)
{
init();
FeatureIterator temp(*this);
if(!move())
return end();
return temp;
}
FeatureIterator &FeatureIterator::operator +(int distance)
{
init();
_iterFeatures = _iterFeatures + distance;
return *this;
}
FeatureIterator &FeatureIterator::operator -(int distance)
{
init();
_iterFeatures = _iterFeatures - distance;
return *this;
}
bool FeatureIterator::operator ==(const FeatureIterator &iter)
{
return _iterFeatures == iter._iterFeatures;
}
bool FeatureIterator::operator !=(const FeatureIterator &iter)
{
return _iterFeatures != iter._iterFeatures;
}
FeatureInterface &FeatureIterator::operator *()
{
init();
_proxy.setProxy(*_iterFeatures, _trackCounter);
return _proxy;
}
FeatureIterator FeatureIterator::end() const
{
FeatureIterator temp(*this);
temp._iterFeatures = _fcoverage->_features.end();
return temp;
}
void FeatureIterator::flow(FeatureIterator::Flow f)
{
_flow = f;
}
bool FeatureIterator::init()
{
if ( _isInitial) {
_isInitial = false;
_fcoverage->connector()->loadBinaryData(_fcoverage.ptr());
if ( _fcoverage->_features.size() > 0 ) {
_iterFeatures = _fcoverage->_features.begin();
_trackCounter = 0;
}
} else
return false;
return true;
}
bool FeatureIterator::move() {
if ( _flow == fFEATURES) {
++_iterFeatures;
if ( _iterFeatures == _fcoverage->_features.end()) {
_iterFeatures = _fcoverage->_features.begin();
++_trackCounter;
}
while((*_iterFeatures)->_track.size() < _trackCounter) {
++_iterFeatures;
if (_iterFeatures == _fcoverage->_features.end())
return false;
}
} else if (_flow == fTRACK) {
++_trackCounter;
if ( _trackCounter >= (*_iterFeatures)->_track.size()) {
++_iterFeatures;
_trackCounter = 0;
if ( _iterFeatures == _fcoverage->_features.end())
return false;
}
}
return true;
}
<commit_msg>added guard<commit_after>#include <iterator>
#include "kernel.h"
#include "coverage.h"
#include "numericrange.h"
#include "numericdomain.h"
#include "columndefinition.h"
#include "table.h"
#include "attributerecord.h"
#include "geometry.h"
#include "feature.h"
#include "featurecoverage.h"
#include "featureiterator.h"
using namespace Ilwis;
FeatureIterator::FeatureIterator(const IFeatureCoverage& fcoverage) : _fcoverage(fcoverage), _isInitial(true), _trackCounter(0),_flow(fFEATURES)
{
}
FeatureIterator::FeatureIterator(const Ilwis::IFeatureCoverage &fcoverage, const Box3D<double>& envelope) :
_fcoverage(fcoverage),
_isInitial(true),
_envelope(envelope),
_trackCounter(0),
_flow(fFEATURES)
{
}
FeatureIterator::FeatureIterator(const FeatureIterator &iter)
{
_fcoverage = iter._fcoverage;
_isInitial = iter._isInitial;
_iterFeatures = iter._iterFeatures;
_trackCounter = iter._trackCounter;
_flow = iter._flow;
}
FeatureIterator &FeatureIterator::operator ++()
{
if (!init()){
move();
}
return *this;
}
FeatureIterator FeatureIterator::operator ++(int)
{
init();
FeatureIterator temp(*this);
if(!move())
return end();
return temp;
}
FeatureIterator &FeatureIterator::operator +(int distance)
{
init();
_iterFeatures = _iterFeatures + distance;
return *this;
}
FeatureIterator &FeatureIterator::operator -(int distance)
{
init();
_iterFeatures = _iterFeatures - distance;
return *this;
}
bool FeatureIterator::operator ==(const FeatureIterator &iter)
{
return _iterFeatures == iter._iterFeatures;
}
bool FeatureIterator::operator !=(const FeatureIterator &iter)
{
return _iterFeatures != iter._iterFeatures;
}
FeatureInterface &FeatureIterator::operator *()
{
init();
_proxy.setProxy(*_iterFeatures, _trackCounter);
return _proxy;
}
FeatureIterator FeatureIterator::end() const
{
FeatureIterator temp(*this);
temp._iterFeatures = _fcoverage->_features.end();
return temp;
}
void FeatureIterator::flow(FeatureIterator::Flow f)
{
_flow = f;
}
bool FeatureIterator::init()
{
if ( _isInitial) {
_isInitial = false;
bool ok = _fcoverage->connector()->loadBinaryData(_fcoverage.ptr());
if (!ok)
return false;
if ( _fcoverage->_features.size() > 0 ) {
_iterFeatures = _fcoverage->_features.begin();
_trackCounter = 0;
}
} else
return false;
return true;
}
bool FeatureIterator::move() {
if ( _flow == fFEATURES) {
++_iterFeatures;
if ( _iterFeatures == _fcoverage->_features.end()) {
_iterFeatures = _fcoverage->_features.begin();
++_trackCounter;
}
while((*_iterFeatures)->_track.size() < _trackCounter) {
++_iterFeatures;
if (_iterFeatures == _fcoverage->_features.end())
return false;
}
} else if (_flow == fTRACK) {
++_trackCounter;
if ( _trackCounter >= (*_iterFeatures)->_track.size()) {
++_iterFeatures;
_trackCounter = 0;
if ( _iterFeatures == _fcoverage->_features.end())
return false;
}
}
return true;
}
<|endoftext|> |
<commit_before>#include <robocup2Dsim/common/action.hpp>
#include <robocup2Dsim/common/action.capnp.h>
#include <capnp/message.h>
#include <gtest/gtest.h>
#include <turbo/memory/slab_allocator.hpp>
#include <turbo/memory/slab_allocator.hxx>
#include <robocup2Dsim/runtime/db_access.hpp>
#include <robocup2Dsim/engine/physics.hxx>
#include <robocup2Dsim/engine/inventory.hxx>
namespace rco = robocup2Dsim::common;
namespace ren = robocup2Dsim::engine;
namespace red = robocup2Dsim::engine::dynamics;
namespace rru = robocup2Dsim::runtime;
TEST(action_test, local_allocator_basic)
{
EXPECT_TRUE(rru::update_local_db().component_allocator().in_configured_range(4U));
}
TEST(action_test, act_move_foot_basic)
{
ren::energy original_energy1{rco::MoveFootAction::MAX_COST};
ren::inventory inventory1({0U, 100U});
ren::physics physics1(ren::physics::vec2(0.0, 0.0), {8U, 4U});
ren::energy stock1{original_energy1.quantity};
ren::physics::body_def body_def1;
body_def1.type = b2_dynamicBody;
body_def1.position.Set(20.0, 20.0);
body_def1.angle = 0.0;
ren::physics_ptr<red::body> torso1 = physics1.make_body(0U, body_def1);
ren::physics_ptr<red::body> foot1 = physics1.make_body(0U, body_def1);
capnp::MallocMessageBuilder arena1;
rco::MoveFootAction::Builder action1 = arena1.initRoot<rco::MoveFootAction>();
action1.setVelocity(rco::MoveFootAction::MAX_VELOCITY);
ren::physics::vec2 original_position1 = foot1->GetPosition();
EXPECT_EQ(ren::inventory::spend_result::success,
rco::act(inventory1, stock1, physics1, *torso1, *foot1, action1.asReader()))
<< "failed to act";
EXPECT_NE(original_energy1.quantity, stock1.quantity) << "energy stock quantity is the same after successful action";
physics1.step(10.0,
[&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { },
[&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { });
ren::physics::vec2 new_position1 = foot1->GetPosition();
EXPECT_TRUE(original_position1.x != new_position1.x || original_position1.y != new_position1.y)
<< "action had no effect on simulation";
}
<commit_msg>added more test cases for MoveFootAction<commit_after>#include <robocup2Dsim/common/action.hpp>
#include <robocup2Dsim/common/action.capnp.h>
#include <capnp/message.h>
#include <gtest/gtest.h>
#include <turbo/memory/slab_allocator.hpp>
#include <turbo/memory/slab_allocator.hxx>
#include <robocup2Dsim/runtime/db_access.hpp>
#include <robocup2Dsim/engine/physics.hxx>
#include <robocup2Dsim/engine/inventory.hxx>
namespace rco = robocup2Dsim::common;
namespace ren = robocup2Dsim::engine;
namespace red = robocup2Dsim::engine::dynamics;
namespace rru = robocup2Dsim::runtime;
TEST(action_test, local_allocator_basic)
{
EXPECT_TRUE(rru::update_local_db().component_allocator().in_configured_range(4U));
}
TEST(action_test, act_move_foot_forward_understock)
{
ren::energy original_energy1{rco::MoveFootAction::MAX_COST / 2};
ren::inventory inventory1({0U, rco::MoveFootAction::MAX_COST * 2});
ren::physics physics1(ren::physics::vec2(0.0, 0.0), {8U, 4U});
ren::energy stock1{original_energy1.quantity};
ren::physics::body_def body_def1;
body_def1.type = b2_dynamicBody;
body_def1.position.Set(20.0, 20.0);
body_def1.angle = 0.0;
ren::physics_ptr<red::body> torso1 = physics1.make_body(0U, body_def1);
ren::physics_ptr<red::body> foot1 = physics1.make_body(0U, body_def1);
capnp::MallocMessageBuilder arena1;
rco::MoveFootAction::Builder action1 = arena1.initRoot<rco::MoveFootAction>();
action1.setVelocity(rco::MoveFootAction::MAX_VELOCITY);
ren::physics::vec2 original_position1 = foot1->GetPosition();
EXPECT_EQ(ren::inventory::spend_result::understock,
rco::act(inventory1, stock1, physics1, *torso1, *foot1, action1.asReader()))
<< "act succeeded when stock was insufficient";
EXPECT_EQ(original_energy1.quantity, stock1.quantity) << "act failed but energy was still spent";
physics1.step(10.0,
[&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { },
[&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { });
ren::physics::vec2 new_position1 = foot1->GetPosition();
EXPECT_TRUE(original_position1.x == new_position1.x && original_position1.y == new_position1.y)
<< "unsuccessful act affected the simulation";
}
TEST(action_test, act_move_foot_backward_understock)
{
ren::energy original_energy1{rco::MoveFootAction::MAX_COST / 2};
ren::inventory inventory1({0U, rco::MoveFootAction::MAX_COST * 2});
ren::physics physics1(ren::physics::vec2(0.0, 0.0), {8U, 4U});
ren::energy stock1{original_energy1.quantity};
ren::physics::body_def body_def1;
body_def1.type = b2_dynamicBody;
body_def1.position.Set(20.0, 20.0);
body_def1.angle = 0.0;
ren::physics_ptr<red::body> torso1 = physics1.make_body(0U, body_def1);
ren::physics_ptr<red::body> foot1 = physics1.make_body(0U, body_def1);
capnp::MallocMessageBuilder arena1;
rco::MoveFootAction::Builder action1 = arena1.initRoot<rco::MoveFootAction>();
action1.setVelocity(-rco::MoveFootAction::MAX_VELOCITY);
ren::physics::vec2 original_position1 = foot1->GetPosition();
EXPECT_EQ(ren::inventory::spend_result::understock,
rco::act(inventory1, stock1, physics1, *torso1, *foot1, action1.asReader()))
<< "act succeeded when stock was insufficient";
EXPECT_EQ(original_energy1.quantity, stock1.quantity) << "act failed but energy was still spent";
physics1.step(10.0,
[&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { },
[&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { });
ren::physics::vec2 new_position1 = foot1->GetPosition();
EXPECT_TRUE(original_position1.x == new_position1.x && original_position1.y == new_position1.y)
<< "unsuccessful act affected the simulation";
}
TEST(action_test, act_move_foot_forward_basic)
{
ren::energy original_energy1{rco::MoveFootAction::MAX_COST * 2};
ren::inventory inventory1({0U, rco::MoveFootAction::MAX_COST * 2});
ren::physics physics1(ren::physics::vec2(0.0, 0.0), {8U, 4U});
ren::energy stock1{original_energy1.quantity};
ren::physics::body_def body_def1;
body_def1.type = b2_dynamicBody;
body_def1.position.Set(20.0, 20.0);
body_def1.angle = 0.0;
ren::physics_ptr<red::body> torso1 = physics1.make_body(0U, body_def1);
ren::physics_ptr<red::body> foot1 = physics1.make_body(0U, body_def1);
capnp::MallocMessageBuilder arena1;
rco::MoveFootAction::Builder action1 = arena1.initRoot<rco::MoveFootAction>();
action1.setVelocity(rco::MoveFootAction::MAX_VELOCITY);
ren::physics::vec2 original_position1 = foot1->GetPosition();
EXPECT_EQ(ren::inventory::spend_result::success,
rco::act(inventory1, stock1, physics1, *torso1, *foot1, action1.asReader()))
<< "failed to act";
EXPECT_NE(original_energy1.quantity, stock1.quantity) << "energy stock quantity is the same after successful action";
physics1.step(10.0,
[&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { },
[&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { });
ren::physics::vec2 new_position1 = foot1->GetPosition();
EXPECT_TRUE(original_position1.x != new_position1.x || original_position1.y != new_position1.y)
<< "action had no effect on simulation";
}
TEST(action_test, act_move_foot_backward_basic)
{
ren::energy original_energy1{rco::MoveFootAction::MAX_COST * 2};
ren::inventory inventory1({0U, rco::MoveFootAction::MAX_COST * 2});
ren::physics physics1(ren::physics::vec2(0.0, 0.0), {8U, 4U});
ren::energy stock1{original_energy1.quantity};
ren::physics::body_def body_def1;
body_def1.type = b2_dynamicBody;
body_def1.position.Set(20.0, 20.0);
body_def1.angle = 0.0;
ren::physics_ptr<red::body> torso1 = physics1.make_body(0U, body_def1);
ren::physics_ptr<red::body> foot1 = physics1.make_body(0U, body_def1);
capnp::MallocMessageBuilder arena1;
rco::MoveFootAction::Builder action1 = arena1.initRoot<rco::MoveFootAction>();
action1.setVelocity(-rco::MoveFootAction::MAX_VELOCITY);
ren::physics::vec2 original_position1 = foot1->GetPosition();
EXPECT_EQ(ren::inventory::spend_result::success,
rco::act(inventory1, stock1, physics1, *torso1, *foot1, action1.asReader()))
<< "failed to act";
EXPECT_NE(original_energy1.quantity, stock1.quantity) << "energy stock quantity is the same after successful action";
physics1.step(10.0,
[&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { },
[&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { });
ren::physics::vec2 new_position1 = foot1->GetPosition();
EXPECT_TRUE(original_position1.x != new_position1.x || original_position1.y != new_position1.y)
<< "action had no effect on simulation";
}
TEST(action_test, act_move_foot_half_forward_velocity)
{
ren::inventory inventory1({0U, rco::MoveFootAction::MAX_COST * 2});
ren::physics physics1(ren::physics::vec2(0.0, 0.0), {8U, 4U});
ren::energy stock1{rco::MoveFootAction::MAX_COST};
ren::physics::body_def body_def1;
body_def1.type = b2_dynamicBody;
body_def1.position.Set(20.0, 20.0);
body_def1.angle = 0.0;
ren::physics_ptr<red::body> torso1 = physics1.make_body(0U, body_def1);
ren::physics_ptr<red::body> foot1 = physics1.make_body(0U, body_def1);
capnp::MallocMessageBuilder arena1;
rco::MoveFootAction::Builder action1 = arena1.initRoot<rco::MoveFootAction>();
action1.setVelocity(rco::MoveFootAction::MAX_VELOCITY / 2);
ren::physics::vec2 original_position1 = foot1->GetPosition();
EXPECT_EQ(ren::inventory::spend_result::success,
rco::act(inventory1, stock1, physics1, *torso1, *foot1, action1.asReader()))
<< "failed to act";
EXPECT_EQ(rco::MoveFootAction::MAX_COST / 2, stock1.quantity) << "energy spent was not proportional to the specified velocity";
physics1.step(10.0,
[&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { },
[&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { });
ren::physics::vec2 new_position1 = foot1->GetPosition();
EXPECT_TRUE(original_position1.x != new_position1.x || original_position1.y != new_position1.y)
<< "action had no effect on simulation";
}
TEST(action_test, act_move_foot_half_backward_velocity)
{
ren::inventory inventory1({0U, rco::MoveFootAction::MAX_COST * 2});
ren::physics physics1(ren::physics::vec2(0.0, 0.0), {8U, 4U});
ren::energy stock1{rco::MoveFootAction::MAX_COST};
ren::physics::body_def body_def1;
body_def1.type = b2_dynamicBody;
body_def1.position.Set(20.0, 20.0);
body_def1.angle = 0.0;
ren::physics_ptr<red::body> torso1 = physics1.make_body(0U, body_def1);
ren::physics_ptr<red::body> foot1 = physics1.make_body(0U, body_def1);
capnp::MallocMessageBuilder arena1;
rco::MoveFootAction::Builder action1 = arena1.initRoot<rco::MoveFootAction>();
action1.setVelocity(-rco::MoveFootAction::MAX_VELOCITY / 2);
ren::physics::vec2 original_position1 = foot1->GetPosition();
EXPECT_EQ(ren::inventory::spend_result::success,
rco::act(inventory1, stock1, physics1, *torso1, *foot1, action1.asReader()))
<< "failed to act";
EXPECT_EQ(rco::MoveFootAction::MAX_COST / 2, stock1.quantity) << "energy spent was not proportional to the specified velocity";
physics1.step(10.0,
[&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { },
[&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { });
ren::physics::vec2 new_position1 = foot1->GetPosition();
EXPECT_TRUE(original_position1.x != new_position1.x || original_position1.y != new_position1.y)
<< "action had no effect on simulation";
}
TEST(action_test, act_move_foot_excess_forward_velocity)
{
ren::inventory inventory1({0U, rco::MoveFootAction::MAX_COST * 2});
ren::physics physics1(ren::physics::vec2(0.0, 0.0), {8U, 4U});
ren::energy stock1{rco::MoveFootAction::MAX_COST};
ren::physics::body_def body_def1;
body_def1.type = b2_dynamicBody;
body_def1.position.Set(20.0, 20.0);
body_def1.angle = 0.0;
ren::physics_ptr<red::body> torso1 = physics1.make_body(0U, body_def1);
ren::physics_ptr<red::body> foot1 = physics1.make_body(0U, body_def1);
capnp::MallocMessageBuilder arena1;
rco::MoveFootAction::Builder action1 = arena1.initRoot<rco::MoveFootAction>();
action1.setVelocity(rco::MoveFootAction::MAX_VELOCITY + 10);
ren::physics::vec2 original_position1 = foot1->GetPosition();
EXPECT_EQ(ren::inventory::spend_result::success,
rco::act(inventory1, stock1, physics1, *torso1, *foot1, action1.asReader()))
<< "failed to act";
EXPECT_EQ(0U, stock1.quantity) << "energy spent was not equal to the max cost";
physics1.step(10.0,
[&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { },
[&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { });
ren::physics::vec2 new_position1 = foot1->GetPosition();
EXPECT_TRUE(original_position1.x != new_position1.x || original_position1.y != new_position1.y)
<< "action had no effect on simulation";
}
TEST(action_test, act_move_foot_excess_backward_velocity)
{
ren::inventory inventory1({0U, rco::MoveFootAction::MAX_COST * 2});
ren::physics physics1(ren::physics::vec2(0.0, 0.0), {8U, 4U});
ren::energy stock1{rco::MoveFootAction::MAX_COST};
ren::physics::body_def body_def1;
body_def1.type = b2_dynamicBody;
body_def1.position.Set(20.0, 20.0);
body_def1.angle = 0.0;
ren::physics_ptr<red::body> torso1 = physics1.make_body(0U, body_def1);
ren::physics_ptr<red::body> foot1 = physics1.make_body(0U, body_def1);
capnp::MallocMessageBuilder arena1;
rco::MoveFootAction::Builder action1 = arena1.initRoot<rco::MoveFootAction>();
action1.setVelocity(-rco::MoveFootAction::MAX_VELOCITY - 10);
ren::physics::vec2 original_position1 = foot1->GetPosition();
EXPECT_EQ(ren::inventory::spend_result::success,
rco::act(inventory1, stock1, physics1, *torso1, *foot1, action1.asReader()))
<< "failed to act";
EXPECT_EQ(0U, stock1.quantity) << "energy spent was not equal to the max cost";
physics1.step(10.0,
[&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { },
[&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { });
ren::physics::vec2 new_position1 = foot1->GetPosition();
EXPECT_TRUE(original_position1.x != new_position1.x || original_position1.y != new_position1.y)
<< "action had no effect on simulation";
}
<|endoftext|> |
<commit_before>/*
*
* Copyright 2015, 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 <cassert>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
#include <sstream>
#include <sys/signal.h>
#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/histogram.h>
#include <grpc/support/log.h>
#include <grpc/support/host_port.h>
#include <gflags/gflags.h>
#include <grpc++/client_context.h>
#include <grpc++/server.h>
#include <grpc++/server_builder.h>
#include <grpc++/status.h>
#include <grpc++/stream.h>
#include <gtest/gtest.h>
#include "test/core/util/grpc_profiler.h"
#include "test/cpp/util/create_test_channel.h"
#include "test/cpp/qps/client.h"
#include "test/cpp/qps/qpstest.pb.h"
#include "test/cpp/qps/histogram.h"
#include "test/cpp/qps/timer.h"
namespace grpc {
namespace testing {
class SynchronousClient : public Client {
public:
SynchronousClient(const ClientConfig& config) : Client(config) {
num_threads_ =
config.outstanding_rpcs_per_channel() * config.client_channels();
responses_.resize(num_threads_);
}
virtual ~SynchronousClient() { EndThreads(); }
protected:
size_t num_threads_;
std::vector<SimpleResponse> responses_;
};
class SynchronousUnaryClient GRPC_FINAL : public SynchronousClient {
public:
SynchronousUnaryClient(const ClientConfig& config):
SynchronousClient(config) {StartThreads(num_threads_);}
~SynchronousUnaryClient() {}
void ThreadFunc(Histogram* histogram, size_t thread_idx) GRPC_OVERRIDE {
auto* stub = channels_[thread_idx % channels_.size()].get_stub();
double start = Timer::Now();
grpc::ClientContext context;
grpc::Status s =
stub->UnaryCall(&context, request_, &responses_[thread_idx]);
histogram->Add((Timer::Now() - start) * 1e9);
}
};
class SynchronousStreamingClient GRPC_FINAL : public SynchronousClient {
public:
SynchronousStreamingClient(const ClientConfig& config):
SynchronousClient(config) {
for (size_t thread_idx=0;thread_idx<num_threads_;thread_idx++){
auto* stub = channels_[thread_idx % channels_.size()].get_stub();
stream_ = stub->StreamingCall(&context_);
}
StartThreads(num_threads_);
}
~SynchronousStreamingClient() {
if (stream_) {
SimpleResponse response;
stream_->WritesDone();
EXPECT_FALSE(stream_->Read(&response));
Status s = stream_->Finish();
EXPECT_TRUE(s.IsOk());
}
}
void ThreadFunc(Histogram* histogram, size_t thread_idx) GRPC_OVERRIDE {
double start = Timer::Now();
EXPECT_TRUE(stream_->Write(request_));
EXPECT_TRUE(stream_->Read(&responses_[thread_idx]));
histogram->Add((Timer::Now() - start) * 1e9);
}
private:
grpc::ClientContext context_;
std::unique_ptr<grpc::ClientReaderWriter<SimpleRequest,SimpleResponse>> stream_;
};
std::unique_ptr<Client>
CreateSynchronousUnaryClient(const ClientConfig& config) {
return std::unique_ptr<Client>(new SynchronousUnaryClient(config));
}
std::unique_ptr<Client>
CreateSynchronousStreamingClient(const ClientConfig& config) {
return std::unique_ptr<Client>(new SynchronousStreamingClient(config));
}
} // namespace testing
} // namespace grpc
<commit_msg>No need to do an extra read<commit_after>/*
*
* Copyright 2015, 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 <cassert>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
#include <sstream>
#include <sys/signal.h>
#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/histogram.h>
#include <grpc/support/log.h>
#include <grpc/support/host_port.h>
#include <gflags/gflags.h>
#include <grpc++/client_context.h>
#include <grpc++/server.h>
#include <grpc++/server_builder.h>
#include <grpc++/status.h>
#include <grpc++/stream.h>
#include <gtest/gtest.h>
#include "test/core/util/grpc_profiler.h"
#include "test/cpp/util/create_test_channel.h"
#include "test/cpp/qps/client.h"
#include "test/cpp/qps/qpstest.pb.h"
#include "test/cpp/qps/histogram.h"
#include "test/cpp/qps/timer.h"
namespace grpc {
namespace testing {
class SynchronousClient : public Client {
public:
SynchronousClient(const ClientConfig& config) : Client(config) {
num_threads_ =
config.outstanding_rpcs_per_channel() * config.client_channels();
responses_.resize(num_threads_);
}
virtual ~SynchronousClient() { EndThreads(); }
protected:
size_t num_threads_;
std::vector<SimpleResponse> responses_;
};
class SynchronousUnaryClient GRPC_FINAL : public SynchronousClient {
public:
SynchronousUnaryClient(const ClientConfig& config):
SynchronousClient(config) {StartThreads(num_threads_);}
~SynchronousUnaryClient() {}
void ThreadFunc(Histogram* histogram, size_t thread_idx) GRPC_OVERRIDE {
auto* stub = channels_[thread_idx % channels_.size()].get_stub();
double start = Timer::Now();
grpc::ClientContext context;
grpc::Status s =
stub->UnaryCall(&context, request_, &responses_[thread_idx]);
histogram->Add((Timer::Now() - start) * 1e9);
}
};
class SynchronousStreamingClient GRPC_FINAL : public SynchronousClient {
public:
SynchronousStreamingClient(const ClientConfig& config):
SynchronousClient(config) {
for (size_t thread_idx=0;thread_idx<num_threads_;thread_idx++){
auto* stub = channels_[thread_idx % channels_.size()].get_stub();
stream_ = stub->StreamingCall(&context_);
}
StartThreads(num_threads_);
}
~SynchronousStreamingClient() {
if (stream_) {
SimpleResponse response;
stream_->WritesDone();
EXPECT_TRUE(stream_->Finish().IsOk());
}
}
void ThreadFunc(Histogram* histogram, size_t thread_idx) GRPC_OVERRIDE {
double start = Timer::Now();
EXPECT_TRUE(stream_->Write(request_));
EXPECT_TRUE(stream_->Read(&responses_[thread_idx]));
histogram->Add((Timer::Now() - start) * 1e9);
}
private:
grpc::ClientContext context_;
std::unique_ptr<grpc::ClientReaderWriter<SimpleRequest,
SimpleResponse>> stream_;
};
std::unique_ptr<Client>
CreateSynchronousUnaryClient(const ClientConfig& config) {
return std::unique_ptr<Client>(new SynchronousUnaryClient(config));
}
std::unique_ptr<Client>
CreateSynchronousStreamingClient(const ClientConfig& config) {
return std::unique_ptr<Client>(new SynchronousStreamingClient(config));
}
} // namespace testing
} // namespace grpc
<|endoftext|> |
<commit_before>// This is core/vnl/tests/test_cholesky.cxx
#include <testlib/testlib_test.h>
#include <vcl_iostream.h>
#include <vnl/vnl_matrix.h>
#include <vnl/algo/vnl_cholesky.h>
#include <vnl/algo/vnl_svd.h>
#include <vcl_ctime.h>
#include <vnl/vnl_sample.h>
#include "test_util.h"
void test_cholesky()
{
vnl_matrix<double> A(3,3);
test_util_fill_random(A.begin(), A.end());
A = A * A.transpose();
vnl_matrix<double> I(3,3);
I.set_identity();
{
vnl_cholesky chol(A);
vnl_svd<double> svd(A);
vcl_cout << "cholesky inverse:\n" << chol.inverse() << '\n'
<< "svd inverse:\n" << svd.inverse() << '\n';
testlib_test_assert_near("svd.inverse() ~= cholesky.inverse()",
(chol.inverse() - svd.inverse()).fro_norm());
}
{
vnl_cholesky chol(A);
testlib_test_assert_near("Ai * A - I", (chol.inverse() * A - I).fro_norm());
testlib_test_assert_near("Ai * A - I", (A * chol.inverse() - I).fro_norm());
}
{
vnl_cholesky chol(A, vnl_cholesky::estimate_condition);
testlib_test_assert_near("Ai * A - I", (chol.inverse() * A - I).fro_norm());
testlib_test_assert_near("Ai * A - I", (A * chol.inverse() - I).fro_norm());
}
}
TESTMAIN(test_cholesky);
<commit_msg>COMP: Supply default seed on cygwin<commit_after>// This is core/vnl/tests/test_cholesky.cxx
#include <testlib/testlib_test.h>
#include <vcl_iostream.h>
#include <vnl/vnl_matrix.h>
#include <vnl/algo/vnl_cholesky.h>
#include <vnl/algo/vnl_svd.h>
#include <vnl/vnl_sample.h>
#include "test_util.h"
void test_cholesky()
{
vnl_matrix<double> A(3,3);
vnl_sample_reseed(0x1234abcd);
test_util_fill_random(A.begin(), A.end());
A = A * A.transpose();
vnl_matrix<double> I(3,3);
I.set_identity();
{
vnl_cholesky chol(A);
vnl_svd<double> svd(A);
vcl_cout << "cholesky inverse:\n" << chol.inverse() << '\n'
<< "svd inverse:\n" << svd.inverse() << '\n';
testlib_test_assert_near("svd.inverse() ~= cholesky.inverse()",
(chol.inverse() - svd.inverse()).fro_norm());
}
{
vnl_cholesky chol(A);
testlib_test_assert_near("Ai * A - I", (chol.inverse() * A - I).fro_norm());
testlib_test_assert_near("Ai * A - I", (A * chol.inverse() - I).fro_norm());
}
{
vnl_cholesky chol(A, vnl_cholesky::estimate_condition);
testlib_test_assert_near("Ai * A - I", (chol.inverse() * A - I).fro_norm());
testlib_test_assert_near("Ai * A - I", (A * chol.inverse() - I).fro_norm());
}
}
TESTMAIN(test_cholesky);
<|endoftext|> |
<commit_before>#include "GHIElectronics_TinyCLR_Devices.h"
#include "GHIElectronics_TinyCLR_InteropUtil.h"
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Storage_Provider_StorageControllerApiWrapper::get_IsPresent___BOOLEAN(const TinyCLR_Interop_MethodData md) {
return TinyCLR_Result::NotImplemented;
}
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Storage_Provider_StorageControllerApiWrapper::get_Descriptor___GHIElectronicsTinyCLRDevicesStorageStorageDescriptor(const TinyCLR_Interop_MethodData md) {
return TinyCLR_Result::NotImplemented;
}
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Storage_Provider_StorageControllerApiWrapper::Open___VOID(const TinyCLR_Interop_MethodData md) {
return TinyCLR_Result::NotImplemented;
}
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Storage_Provider_StorageControllerApiWrapper::Close___VOID(const TinyCLR_Interop_MethodData md) {
return TinyCLR_Result::NotImplemented;
}
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Storage_Provider_StorageControllerApiWrapper::Read___I4__I8__I4__SZARRAY_U1__I4__I8(const TinyCLR_Interop_MethodData md) {
auto api = reinterpret_cast<const TinyCLR_Storage_Controller*>(TinyCLR_Interop_GetApi(md, FIELD___impl___I));
TinyCLR_Interop_ClrValue arg0, arg1, arg2, arg3, arg4;
md.InteropManager->GetArgument(md.InteropManager, md.Stack, 0, arg0);
md.InteropManager->GetArgument(md.InteropManager, md.Stack, 1, arg1);
md.InteropManager->GetArgument(md.InteropManager, md.Stack, 2, arg2);
md.InteropManager->GetArgument(md.InteropManager, md.Stack, 3, arg3);
md.InteropManager->GetArgument(md.InteropManager, md.Stack, 4, arg4);
auto sector = static_cast<uint64_t>(arg0.Data.Numeric->I8);
auto count = static_cast<size_t>(arg1.Data.Numeric->I4);
auto buffer = reinterpret_cast<uint8_t*>(arg2.Data.SzArray.Data);
auto offset = arg3.Data.Numeric->I8;
auto timeout = arg4.Data.Numeric->I4;
buffer += offset;
auto result = api->Read(api, sector, count, buffer, timeout);
TinyCLR_Interop_ClrValue ret;
md.InteropManager->GetReturn(md.InteropManager, md.Stack, ret);
ret.Data.Numeric->I4 = count;
return result;
}
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Storage_Provider_StorageControllerApiWrapper::Write___I4__I8__I4__SZARRAY_U1__I4__I8(const TinyCLR_Interop_MethodData md) {
auto api = reinterpret_cast<const TinyCLR_Storage_Controller*>(TinyCLR_Interop_GetApi(md, FIELD___impl___I));
TinyCLR_Interop_ClrValue arg0, arg1, arg2, arg3, arg4;
md.InteropManager->GetArgument(md.InteropManager, md.Stack, 0, arg0);
md.InteropManager->GetArgument(md.InteropManager, md.Stack, 1, arg1);
md.InteropManager->GetArgument(md.InteropManager, md.Stack, 2, arg2);
md.InteropManager->GetArgument(md.InteropManager, md.Stack, 3, arg3);
md.InteropManager->GetArgument(md.InteropManager, md.Stack, 4, arg4);
auto sector = static_cast<uint64_t>(arg0.Data.Numeric->I8);
auto count = static_cast<size_t>(arg1.Data.Numeric->I4);
auto buffer = reinterpret_cast<uint8_t*>(arg2.Data.SzArray.Data);
auto offset = arg3.Data.Numeric->I4;
auto timeout = arg4.Data.Numeric->I8;
buffer += offset;
auto result = api->Write(api, sector, count, buffer, timeout);
TinyCLR_Interop_ClrValue ret;
md.InteropManager->GetReturn(md.InteropManager, md.Stack, ret);
ret.Data.Numeric->I4 = count;
return result;
}
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Storage_Provider_StorageControllerApiWrapper::Erase___I4__I8__I4__I8(const TinyCLR_Interop_MethodData md) {
auto api = reinterpret_cast<const TinyCLR_Storage_Controller*>(TinyCLR_Interop_GetApi(md, FIELD___impl___I));
TinyCLR_Interop_ClrValue arg0, arg1, arg2;
md.InteropManager->GetArgument(md.InteropManager, md.Stack, 0, arg0);
md.InteropManager->GetArgument(md.InteropManager, md.Stack, 1, arg1);
md.InteropManager->GetArgument(md.InteropManager, md.Stack, 2, arg2);
auto sector = static_cast<uint64_t>(arg0.Data.Numeric->I8);
auto count = static_cast<size_t>(arg1.Data.Numeric->I4);
auto timeout = arg2.Data.Numeric->I8;
auto result = api->Erase(api, sector, count, timeout);
TinyCLR_Interop_ClrValue ret;
md.InteropManager->GetReturn(md.InteropManager, md.Stack, ret);
ret.Data.Numeric->I4 = count;
return result;
}
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Storage_Provider_StorageControllerApiWrapper::IsErased___BOOLEAN__I8__I4(const TinyCLR_Interop_MethodData md) {
return TinyCLR_Result::NotImplemented;
}
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Storage_Provider_StorageControllerApiWrapper::Acquire___VOID(const TinyCLR_Interop_MethodData md) {
auto api = reinterpret_cast<const TinyCLR_Storage_Controller*>(TinyCLR_Interop_GetApi(md, FIELD___impl___I));
return api->Acquire(api);
}
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Storage_Provider_StorageControllerApiWrapper::Release___VOID(const TinyCLR_Interop_MethodData md) {
auto api = reinterpret_cast<const TinyCLR_Storage_Controller*>(TinyCLR_Interop_GetApi(md, FIELD___impl___I));
return api->Release(api);
}
<commit_msg>Implement some sdCard stuff<commit_after>#include "GHIElectronics_TinyCLR_Devices.h"
#include "GHIElectronics_TinyCLR_InteropUtil.h"
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Storage_Provider_StorageControllerApiWrapper::get_IsPresent___BOOLEAN(const TinyCLR_Interop_MethodData md) {
auto api = reinterpret_cast<const TinyCLR_Storage_Controller*>(TinyCLR_Interop_GetApi(md, FIELD___impl___I));
TinyCLR_Interop_ClrValue ret;
md.InteropManager->GetReturn(md.InteropManager, md.Stack, ret);
return api->IsPresent(api, ret.Data.Numeric->Boolean);
}
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Storage_Provider_StorageControllerApiWrapper::get_Descriptor___GHIElectronicsTinyCLRDevicesStorageStorageDescriptor(const TinyCLR_Interop_MethodData md) {
return TinyCLR_Result::NotImplemented;
}
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Storage_Provider_StorageControllerApiWrapper::Open___VOID(const TinyCLR_Interop_MethodData md) {
auto api = reinterpret_cast<const TinyCLR_Storage_Controller*>(TinyCLR_Interop_GetApi(md, FIELD___impl___I));
return api->Open(api);
}
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Storage_Provider_StorageControllerApiWrapper::Close___VOID(const TinyCLR_Interop_MethodData md) {
auto api = reinterpret_cast<const TinyCLR_Storage_Controller*>(TinyCLR_Interop_GetApi(md, FIELD___impl___I));
return api->Close(api);
}
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Storage_Provider_StorageControllerApiWrapper::Read___I4__I8__I4__SZARRAY_U1__I4__I8(const TinyCLR_Interop_MethodData md) {
auto api = reinterpret_cast<const TinyCLR_Storage_Controller*>(TinyCLR_Interop_GetApi(md, FIELD___impl___I));
TinyCLR_Interop_ClrValue arg0, arg1, arg2, arg3, arg4;
md.InteropManager->GetArgument(md.InteropManager, md.Stack, 0, arg0);
md.InteropManager->GetArgument(md.InteropManager, md.Stack, 1, arg1);
md.InteropManager->GetArgument(md.InteropManager, md.Stack, 2, arg2);
md.InteropManager->GetArgument(md.InteropManager, md.Stack, 3, arg3);
md.InteropManager->GetArgument(md.InteropManager, md.Stack, 4, arg4);
auto sector = static_cast<uint64_t>(arg0.Data.Numeric->I8);
auto count = static_cast<size_t>(arg1.Data.Numeric->I4);
auto buffer = reinterpret_cast<uint8_t*>(arg2.Data.SzArray.Data);
auto offset = arg3.Data.Numeric->I8;
auto timeout = arg4.Data.Numeric->I4;
buffer += offset;
auto result = api->Read(api, sector, count, buffer, timeout);
TinyCLR_Interop_ClrValue ret;
md.InteropManager->GetReturn(md.InteropManager, md.Stack, ret);
ret.Data.Numeric->I4 = count;
return result;
}
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Storage_Provider_StorageControllerApiWrapper::Write___I4__I8__I4__SZARRAY_U1__I4__I8(const TinyCLR_Interop_MethodData md) {
auto api = reinterpret_cast<const TinyCLR_Storage_Controller*>(TinyCLR_Interop_GetApi(md, FIELD___impl___I));
TinyCLR_Interop_ClrValue arg0, arg1, arg2, arg3, arg4;
md.InteropManager->GetArgument(md.InteropManager, md.Stack, 0, arg0);
md.InteropManager->GetArgument(md.InteropManager, md.Stack, 1, arg1);
md.InteropManager->GetArgument(md.InteropManager, md.Stack, 2, arg2);
md.InteropManager->GetArgument(md.InteropManager, md.Stack, 3, arg3);
md.InteropManager->GetArgument(md.InteropManager, md.Stack, 4, arg4);
auto sector = static_cast<uint64_t>(arg0.Data.Numeric->I8);
auto count = static_cast<size_t>(arg1.Data.Numeric->I4);
auto buffer = reinterpret_cast<uint8_t*>(arg2.Data.SzArray.Data);
auto offset = arg3.Data.Numeric->I4;
auto timeout = arg4.Data.Numeric->I8;
buffer += offset;
auto result = api->Write(api, sector, count, buffer, timeout);
TinyCLR_Interop_ClrValue ret;
md.InteropManager->GetReturn(md.InteropManager, md.Stack, ret);
ret.Data.Numeric->I4 = count;
return result;
}
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Storage_Provider_StorageControllerApiWrapper::Erase___I4__I8__I4__I8(const TinyCLR_Interop_MethodData md) {
auto api = reinterpret_cast<const TinyCLR_Storage_Controller*>(TinyCLR_Interop_GetApi(md, FIELD___impl___I));
TinyCLR_Interop_ClrValue arg0, arg1, arg2;
md.InteropManager->GetArgument(md.InteropManager, md.Stack, 0, arg0);
md.InteropManager->GetArgument(md.InteropManager, md.Stack, 1, arg1);
md.InteropManager->GetArgument(md.InteropManager, md.Stack, 2, arg2);
auto sector = static_cast<uint64_t>(arg0.Data.Numeric->I8);
auto count = static_cast<size_t>(arg1.Data.Numeric->I4);
auto timeout = arg2.Data.Numeric->I8;
auto result = api->Erase(api, sector, count, timeout);
TinyCLR_Interop_ClrValue ret;
md.InteropManager->GetReturn(md.InteropManager, md.Stack, ret);
ret.Data.Numeric->I4 = count;
return result;
}
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Storage_Provider_StorageControllerApiWrapper::IsErased___BOOLEAN__I8__I4(const TinyCLR_Interop_MethodData md) {
auto api = reinterpret_cast<const TinyCLR_Storage_Controller*>(TinyCLR_Interop_GetApi(md, FIELD___impl___I));
TinyCLR_Interop_ClrValue arg0, arg1, ret;
md.InteropManager->GetArgument(md.InteropManager, md.Stack, 0, arg0);
md.InteropManager->GetArgument(md.InteropManager, md.Stack, 1, arg1);
md.InteropManager->GetReturn(md.InteropManager, md.Stack, ret);
size_t count = arg1.Data.Numeric->I4;
return api->IsErased(api, arg0.Data.Numeric->I8, count, ret.Data.Numeric->Boolean);
}
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Storage_Provider_StorageControllerApiWrapper::Acquire___VOID(const TinyCLR_Interop_MethodData md) {
auto api = reinterpret_cast<const TinyCLR_Storage_Controller*>(TinyCLR_Interop_GetApi(md, FIELD___impl___I));
return api->Acquire(api);
}
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Storage_Provider_StorageControllerApiWrapper::Release___VOID(const TinyCLR_Interop_MethodData md) {
auto api = reinterpret_cast<const TinyCLR_Storage_Controller*>(TinyCLR_Interop_GetApi(md, FIELD___impl___I));
return api->Release(api);
}
<|endoftext|> |
<commit_before>/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
*/
#include "VisualBench.h"
#include "ProcStats.h"
#include "SkApplication.h"
#include "SkCanvas.h"
#include "SkCommandLineFlags.h"
#include "SkForceLinking.h"
#include "SkGraphics.h"
#include "SkGr.h"
#include "SkImageDecoder.h"
#include "SkOSFile.h"
#include "SkStream.h"
#include "Stats.h"
#include "gl/GrGLInterface.h"
__SK_FORCE_IMAGE_DECODER_LINKING;
// Between samples we reset context
// Between frames we swap buffers
// Between flushes we call flush on GrContext
DEFINE_int32(gpuFrameLag, 5, "Overestimate of maximum number of frames GPU allows to lag.");
DEFINE_int32(samples, 10, "Number of times to time each skp.");
DEFINE_int32(frames, 5, "Number of frames of each skp to render per sample.");
DEFINE_double(flushMs, 20, "Target flush time in millseconds.");
DEFINE_double(loopMs, 5, "Target loop time in millseconds.");
DEFINE_int32(msaa, 0, "Number of msaa samples.");
DEFINE_bool2(fullscreen, f, true, "Run fullscreen.");
DEFINE_bool2(verbose, v, false, "enable verbose output from the test driver.");
static SkString humanize(double ms) {
if (FLAGS_verbose) {
return SkStringPrintf("%llu", (uint64_t)(ms*1e6));
}
return HumanizeMs(ms);
}
#define HUMANIZE(time) humanize(time).c_str()
VisualBench::VisualBench(void* hwnd, int argc, char** argv)
: INHERITED(hwnd)
, fCurrentSample(0)
, fCurrentFrame(0)
, fFlushes(1)
, fLoops(1)
, fState(kPreWarmLoops_State)
, fBenchmark(NULL) {
SkCommandLineFlags::Parse(argc, argv);
this->setTitle();
this->setupBackend();
fBenchmarkStream.reset(SkNEW(VisualBenchmarkStream));
// Print header
SkDebugf("curr/maxrss\tloops\tflushes\tmin\tmedian\tmean\tmax\tstddev\tbench\n");
}
VisualBench::~VisualBench() {
INHERITED::detach();
}
void VisualBench::setTitle() {
SkString title("VisualBench");
INHERITED::setTitle(title.c_str());
}
SkSurface* VisualBench::createSurface() {
SkSurfaceProps props(INHERITED::getSurfaceProps());
return SkSurface::NewRenderTargetDirect(fRenderTarget, &props);
}
bool VisualBench::setupBackend() {
this->setColorType(kRGBA_8888_SkColorType);
this->setVisibleP(true);
this->setClipToBounds(false);
if (FLAGS_fullscreen) {
if (!this->makeFullscreen()) {
SkDebugf("Could not go fullscreen!");
}
}
if (!this->attach(kNativeGL_BackEndType, FLAGS_msaa, &fAttachmentInfo)) {
SkDebugf("Not possible to create backend.\n");
INHERITED::detach();
return false;
}
this->setVsync(false);
this->resetContext();
return true;
}
void VisualBench::resetContext() {
fInterface.reset(GrGLCreateNativeInterface());
SkASSERT(fInterface);
// setup contexts
fContext.reset(GrContext::Create(kOpenGL_GrBackend, (GrBackendContext)fInterface.get()));
SkASSERT(fContext);
// setup rendertargets
this->setupRenderTarget();
}
void VisualBench::setupRenderTarget() {
if (fContext) {
fRenderTarget.reset(this->renderTarget(fAttachmentInfo, fInterface, fContext));
}
}
inline void VisualBench::renderFrame(SkCanvas* canvas) {
for (int flush = 0; flush < fFlushes; flush++) {
fBenchmark->draw(fLoops, canvas);
canvas->flush();
}
INHERITED::present();
}
void VisualBench::printStats() {
const SkTArray<double>& measurements = fRecords.back().fMeasurements;
const char* shortName = fBenchmark->getUniqueName();
if (FLAGS_verbose) {
for (int i = 0; i < measurements.count(); i++) {
SkDebugf("%s ", HUMANIZE(measurements[i]));
}
SkDebugf("%s\n", shortName);
} else {
SkASSERT(measurements.count());
Stats stats(measurements);
const double stdDevPercent = 100 * sqrt(stats.var) / stats.mean;
SkDebugf("%4d/%-4dMB\t%d\t%d\t%s\t%s\t%s\t%s\t%.0f%%\t%s\n",
sk_tools::getCurrResidentSetSizeMB(),
sk_tools::getMaxResidentSetSizeMB(),
fLoops,
fFlushes,
HUMANIZE(stats.min),
HUMANIZE(stats.median),
HUMANIZE(stats.mean),
HUMANIZE(stats.max),
stdDevPercent,
shortName);
}
}
bool VisualBench::advanceRecordIfNecessary(SkCanvas* canvas) {
if (fBenchmark) {
return true;
}
while ((fBenchmark = fBenchmarkStream->next()) &&
(SkCommandLineFlags::ShouldSkip(FLAGS_match, fBenchmark->getUniqueName()) ||
!fBenchmark->isSuitableFor(Benchmark::kGPU_Backend))) {}
if (!fBenchmark) {
return false;
}
canvas->clear(0xffffffff);
fBenchmark->preDraw();
fBenchmark->perCanvasPreDraw(canvas);
fRecords.push_back();
return true;
}
void VisualBench::preWarm(State nextState) {
if (fCurrentFrame >= FLAGS_gpuFrameLag) {
// we currently time across all frames to make sure we capture all GPU work
fState = nextState;
fCurrentFrame = 0;
fTimer.start();
} else {
fCurrentFrame++;
}
}
void VisualBench::draw(SkCanvas* canvas) {
if (!this->advanceRecordIfNecessary(canvas)) {
this->closeWindow();
return;
}
this->renderFrame(canvas);
switch (fState) {
case kPreWarmLoops_State: {
this->preWarm(kTuneLoops_State);
break;
}
case kTuneLoops_State: {
if (1 << 30 == fLoops) {
// We're about to wrap. Something's wrong with the bench.
SkDebugf("InnerLoops wrapped\n");
fLoops = 0;
} else {
fTimer.end();
double elapsed = fTimer.fWall;
if (elapsed > FLAGS_loopMs) {
fState = kPreWarmTiming_State;
// Scale back the number of loops
fLoops = (int)ceil(fLoops * FLAGS_loopMs / elapsed);
fFlushes = (int)ceil(FLAGS_flushMs / elapsed);
} else {
fState = kPreWarmLoops_State;
fLoops *= 2;
}
fCurrentFrame = 0;
fTimer = WallTimer();
this->resetContext();
}
break;
}
case kPreWarmTiming_State: {
this->preWarm(kTiming_State);
break;
}
case kTiming_State: {
if (fCurrentFrame >= FLAGS_frames) {
fTimer.end();
fRecords.back().fMeasurements.push_back(
fTimer.fWall / (FLAGS_frames * fLoops * fFlushes));
if (fCurrentSample++ >= FLAGS_samples) {
fState = kPreWarmLoops_State;
this->printStats();
fBenchmark->perCanvasPostDraw(canvas);
fBenchmark = NULL;
fCurrentSample = 0;
fFlushes = 1;
fLoops = 1;
} else {
fState = kPreWarmTiming_State;
}
fTimer = WallTimer();
this->resetContext();
fCurrentFrame = 0;
} else {
fCurrentFrame++;
}
break;
}
}
// Invalidate the window to force a redraw. Poor man's animation mechanism.
this->inval(NULL);
}
void VisualBench::onSizeChange() {
this->setupRenderTarget();
}
bool VisualBench::onHandleChar(SkUnichar unichar) {
return true;
}
// Externally declared entry points
void application_init() {
SkGraphics::Init();
SkEvent::Init();
}
void application_term() {
SkEvent::Term();
SkGraphics::Term();
}
SkOSWindow* create_sk_window(void* hwnd, int argc, char** argv) {
return new VisualBench(hwnd, argc, argv);
}
<commit_msg>Fix VisualBench to hold onto a surface<commit_after>/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
*/
#include "VisualBench.h"
#include "ProcStats.h"
#include "SkApplication.h"
#include "SkCanvas.h"
#include "SkCommandLineFlags.h"
#include "SkForceLinking.h"
#include "SkGraphics.h"
#include "SkGr.h"
#include "SkImageDecoder.h"
#include "SkOSFile.h"
#include "SkStream.h"
#include "Stats.h"
#include "gl/GrGLInterface.h"
__SK_FORCE_IMAGE_DECODER_LINKING;
// Between samples we reset context
// Between frames we swap buffers
// Between flushes we call flush on GrContext
DEFINE_int32(gpuFrameLag, 5, "Overestimate of maximum number of frames GPU allows to lag.");
DEFINE_int32(samples, 10, "Number of times to time each skp.");
DEFINE_int32(frames, 5, "Number of frames of each skp to render per sample.");
DEFINE_double(flushMs, 20, "Target flush time in millseconds.");
DEFINE_double(loopMs, 5, "Target loop time in millseconds.");
DEFINE_int32(msaa, 0, "Number of msaa samples.");
DEFINE_bool2(fullscreen, f, true, "Run fullscreen.");
DEFINE_bool2(verbose, v, false, "enable verbose output from the test driver.");
static SkString humanize(double ms) {
if (FLAGS_verbose) {
return SkStringPrintf("%llu", (uint64_t)(ms*1e6));
}
return HumanizeMs(ms);
}
#define HUMANIZE(time) humanize(time).c_str()
VisualBench::VisualBench(void* hwnd, int argc, char** argv)
: INHERITED(hwnd)
, fCurrentSample(0)
, fCurrentFrame(0)
, fFlushes(1)
, fLoops(1)
, fState(kPreWarmLoops_State)
, fBenchmark(NULL) {
SkCommandLineFlags::Parse(argc, argv);
this->setTitle();
this->setupBackend();
fBenchmarkStream.reset(SkNEW(VisualBenchmarkStream));
// Print header
SkDebugf("curr/maxrss\tloops\tflushes\tmin\tmedian\tmean\tmax\tstddev\tbench\n");
}
VisualBench::~VisualBench() {
INHERITED::detach();
}
void VisualBench::setTitle() {
SkString title("VisualBench");
INHERITED::setTitle(title.c_str());
}
SkSurface* VisualBench::createSurface() {
if (!fSurface) {
SkSurfaceProps props(INHERITED::getSurfaceProps());
fSurface.reset(SkSurface::NewRenderTargetDirect(fRenderTarget, &props));
}
// The caller will wrap the SkSurface in an SkAutoTUnref
return SkRef(fSurface.get());
}
bool VisualBench::setupBackend() {
this->setColorType(kRGBA_8888_SkColorType);
this->setVisibleP(true);
this->setClipToBounds(false);
if (FLAGS_fullscreen) {
if (!this->makeFullscreen()) {
SkDebugf("Could not go fullscreen!");
}
}
if (!this->attach(kNativeGL_BackEndType, FLAGS_msaa, &fAttachmentInfo)) {
SkDebugf("Not possible to create backend.\n");
INHERITED::detach();
return false;
}
this->setVsync(false);
this->resetContext();
return true;
}
void VisualBench::resetContext() {
fInterface.reset(GrGLCreateNativeInterface());
SkASSERT(fInterface);
// setup contexts
fContext.reset(GrContext::Create(kOpenGL_GrBackend, (GrBackendContext)fInterface.get()));
SkASSERT(fContext);
// setup rendertargets
this->setupRenderTarget();
}
void VisualBench::setupRenderTarget() {
if (fContext) {
fRenderTarget.reset(this->renderTarget(fAttachmentInfo, fInterface, fContext));
}
}
inline void VisualBench::renderFrame(SkCanvas* canvas) {
for (int flush = 0; flush < fFlushes; flush++) {
fBenchmark->draw(fLoops, canvas);
canvas->flush();
}
INHERITED::present();
}
void VisualBench::printStats() {
const SkTArray<double>& measurements = fRecords.back().fMeasurements;
const char* shortName = fBenchmark->getUniqueName();
if (FLAGS_verbose) {
for (int i = 0; i < measurements.count(); i++) {
SkDebugf("%s ", HUMANIZE(measurements[i]));
}
SkDebugf("%s\n", shortName);
} else {
SkASSERT(measurements.count());
Stats stats(measurements);
const double stdDevPercent = 100 * sqrt(stats.var) / stats.mean;
SkDebugf("%4d/%-4dMB\t%d\t%d\t%s\t%s\t%s\t%s\t%.0f%%\t%s\n",
sk_tools::getCurrResidentSetSizeMB(),
sk_tools::getMaxResidentSetSizeMB(),
fLoops,
fFlushes,
HUMANIZE(stats.min),
HUMANIZE(stats.median),
HUMANIZE(stats.mean),
HUMANIZE(stats.max),
stdDevPercent,
shortName);
}
}
bool VisualBench::advanceRecordIfNecessary(SkCanvas* canvas) {
if (fBenchmark) {
return true;
}
while ((fBenchmark = fBenchmarkStream->next()) &&
(SkCommandLineFlags::ShouldSkip(FLAGS_match, fBenchmark->getUniqueName()) ||
!fBenchmark->isSuitableFor(Benchmark::kGPU_Backend))) {}
if (!fBenchmark) {
return false;
}
canvas->clear(0xffffffff);
fBenchmark->preDraw();
fBenchmark->perCanvasPreDraw(canvas);
fRecords.push_back();
return true;
}
void VisualBench::preWarm(State nextState) {
if (fCurrentFrame >= FLAGS_gpuFrameLag) {
// we currently time across all frames to make sure we capture all GPU work
fState = nextState;
fCurrentFrame = 0;
fTimer.start();
} else {
fCurrentFrame++;
}
}
void VisualBench::draw(SkCanvas* canvas) {
if (!this->advanceRecordIfNecessary(canvas)) {
this->closeWindow();
return;
}
this->renderFrame(canvas);
switch (fState) {
case kPreWarmLoops_State: {
this->preWarm(kTuneLoops_State);
break;
}
case kTuneLoops_State: {
if (1 << 30 == fLoops) {
// We're about to wrap. Something's wrong with the bench.
SkDebugf("InnerLoops wrapped\n");
fLoops = 0;
} else {
fTimer.end();
double elapsed = fTimer.fWall;
if (elapsed > FLAGS_loopMs) {
fState = kPreWarmTiming_State;
// Scale back the number of loops
fLoops = (int)ceil(fLoops * FLAGS_loopMs / elapsed);
fFlushes = (int)ceil(FLAGS_flushMs / elapsed);
} else {
fState = kPreWarmLoops_State;
fLoops *= 2;
}
fCurrentFrame = 0;
fTimer = WallTimer();
this->resetContext();
}
break;
}
case kPreWarmTiming_State: {
this->preWarm(kTiming_State);
break;
}
case kTiming_State: {
if (fCurrentFrame >= FLAGS_frames) {
fTimer.end();
fRecords.back().fMeasurements.push_back(
fTimer.fWall / (FLAGS_frames * fLoops * fFlushes));
if (fCurrentSample++ >= FLAGS_samples) {
fState = kPreWarmLoops_State;
this->printStats();
fBenchmark->perCanvasPostDraw(canvas);
fBenchmark = NULL;
fCurrentSample = 0;
fFlushes = 1;
fLoops = 1;
} else {
fState = kPreWarmTiming_State;
}
fTimer = WallTimer();
this->resetContext();
fCurrentFrame = 0;
} else {
fCurrentFrame++;
}
break;
}
}
// Invalidate the window to force a redraw. Poor man's animation mechanism.
this->inval(NULL);
}
void VisualBench::onSizeChange() {
this->setupRenderTarget();
}
bool VisualBench::onHandleChar(SkUnichar unichar) {
return true;
}
// Externally declared entry points
void application_init() {
SkGraphics::Init();
SkEvent::Init();
}
void application_term() {
SkEvent::Term();
SkGraphics::Term();
}
SkOSWindow* create_sk_window(void* hwnd, int argc, char** argv) {
return new VisualBench(hwnd, argc, argv);
}
<|endoftext|> |
<commit_before>/*
__ _____ _____ _____
__| | __| | | | JSON for Modern C++ (test suite)
| | |__ | | | | | | version 3.7.3
|_____|_____|_____|_|___| https://github.com/nlohmann/json
Licensed under the MIT License <http://opensource.org/licenses/MIT>.
SPDX-License-Identifier: MIT
Copyright (c) 2013-2019 Niels Lohmann <http://nlohmann.me>.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "doctest_compatibility.h"
#define private public
#include <nlohmann/json.hpp>
using nlohmann::json;
#undef private
namespace
{
// special test case to check if memory is leaked if constructor throws
template<class T>
struct bad_allocator : std::allocator<T>
{
template<class... Args>
void construct(T*, Args&& ...)
{
throw std::bad_alloc();
}
};
}
TEST_CASE("bad_alloc")
{
SECTION("bad_alloc")
{
// create JSON type using the throwing allocator
using bad_json = nlohmann::basic_json<std::map,
std::vector,
std::string,
bool,
std::int64_t,
std::uint64_t,
double,
bad_allocator>;
// creating an object should throw
CHECK_THROWS_AS(bad_json(bad_json::value_t::object), std::bad_alloc&);
}
}
namespace
{
bool next_construct_fails = false;
bool next_destroy_fails = false;
bool next_deallocate_fails = false;
template<class T>
struct my_allocator : std::allocator<T>
{
using std::allocator<T>::allocator;
template<class... Args>
void construct(T* p, Args&& ... args)
{
if (next_construct_fails)
{
next_construct_fails = false;
throw std::bad_alloc();
}
else
{
::new (reinterpret_cast<void*>(p)) T(std::forward<Args>(args)...);
}
}
void deallocate(T* p, std::size_t n)
{
if (next_deallocate_fails)
{
next_deallocate_fails = false;
throw std::bad_alloc();
}
else
{
std::allocator<T>::deallocate(p, n);
}
}
void destroy(T* p)
{
if (next_destroy_fails)
{
next_destroy_fails = false;
throw std::bad_alloc();
}
else
{
p->~T();
}
}
template <class U>
struct rebind
{
using other = my_allocator<U>;
};
};
// allows deletion of raw pointer, usually hold by json_value
template<class T>
void my_allocator_clean_up(T* p)
{
assert(p != nullptr);
my_allocator<T> alloc;
alloc.destroy(p);
alloc.deallocate(p, 1);
}
}
TEST_CASE("controlled bad_alloc")
{
// create JSON type using the throwing allocator
using my_json = nlohmann::basic_json<std::map,
std::vector,
std::string,
bool,
std::int64_t,
std::uint64_t,
double,
my_allocator>;
SECTION("class json_value")
{
SECTION("json_value(value_t)")
{
SECTION("object")
{
next_construct_fails = false;
auto t = my_json::value_t::object;
CHECK_NOTHROW(my_allocator_clean_up(my_json::json_value(t).object));
next_construct_fails = true;
CHECK_THROWS_AS(my_json::json_value(t), std::bad_alloc&);
next_construct_fails = false;
}
SECTION("array")
{
next_construct_fails = false;
auto t = my_json::value_t::array;
CHECK_NOTHROW(my_allocator_clean_up(my_json::json_value(t).array));
next_construct_fails = true;
CHECK_THROWS_AS(my_json::json_value(t), std::bad_alloc&);
next_construct_fails = false;
}
SECTION("string")
{
next_construct_fails = false;
auto t = my_json::value_t::string;
CHECK_NOTHROW(my_allocator_clean_up(my_json::json_value(t).string));
next_construct_fails = true;
CHECK_THROWS_AS(my_json::json_value(t), std::bad_alloc&);
next_construct_fails = false;
}
}
SECTION("json_value(const string_t&)")
{
next_construct_fails = false;
my_json::string_t v("foo");
CHECK_NOTHROW(my_allocator_clean_up(my_json::json_value(v).string));
next_construct_fails = true;
CHECK_THROWS_AS(my_json::json_value(v), std::bad_alloc&);
next_construct_fails = false;
}
}
SECTION("class basic_json")
{
SECTION("basic_json(const CompatibleObjectType&)")
{
next_construct_fails = false;
std::map<std::string, std::string> v {{"foo", "bar"}};
CHECK_NOTHROW(my_json(v));
next_construct_fails = true;
CHECK_THROWS_AS(my_json(v), std::bad_alloc&);
next_construct_fails = false;
}
SECTION("basic_json(const CompatibleArrayType&)")
{
next_construct_fails = false;
std::vector<std::string> v {"foo", "bar", "baz"};
CHECK_NOTHROW(my_json(v));
next_construct_fails = true;
CHECK_THROWS_AS(my_json(v), std::bad_alloc&);
next_construct_fails = false;
}
SECTION("basic_json(const typename string_t::value_type*)")
{
next_construct_fails = false;
CHECK_NOTHROW(my_json("foo"));
next_construct_fails = true;
CHECK_THROWS_AS(my_json("foo"), std::bad_alloc&);
next_construct_fails = false;
}
SECTION("basic_json(const typename string_t::value_type*)")
{
next_construct_fails = false;
std::string s("foo");
CHECK_NOTHROW(my_json(s));
next_construct_fails = true;
CHECK_THROWS_AS(my_json(s), std::bad_alloc&);
next_construct_fails = false;
}
}
}
namespace
{
template<class T>
struct allocator_no_forward : std::allocator<T>
{
template <typename U>
struct rebind {
typedef allocator_no_forward<U> other;
};
template <class... Args>
void construct(T* p, const Args&... args)
{
::new (static_cast<void*>(p)) T(args...);
}
};
}
TEST_CASE("bad my_allocator::construct")
{
SECTION("my_allocator::construct doesn't forward")
{
using bad_alloc_json = nlohmann::basic_json<std::map,
std::vector,
std::string,
bool,
std::int64_t,
std::uint64_t,
double,
allocator_no_forward>;
bad_alloc_json json;
json["test"] = bad_alloc_json::array_t();
json["test"].push_back("should not leak");
}
}
<commit_msg>still fixing<commit_after>/*
__ _____ _____ _____
__| | __| | | | JSON for Modern C++ (test suite)
| | |__ | | | | | | version 3.7.3
|_____|_____|_____|_|___| https://github.com/nlohmann/json
Licensed under the MIT License <http://opensource.org/licenses/MIT>.
SPDX-License-Identifier: MIT
Copyright (c) 2013-2019 Niels Lohmann <http://nlohmann.me>.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "doctest_compatibility.h"
#define private public
#include <nlohmann/json.hpp>
using nlohmann::json;
#undef private
namespace
{
// special test case to check if memory is leaked if constructor throws
template<class T>
struct bad_allocator : std::allocator<T>
{
template<class... Args>
void construct(T*, Args&& ...)
{
throw std::bad_alloc();
}
};
}
TEST_CASE("bad_alloc")
{
SECTION("bad_alloc")
{
// create JSON type using the throwing allocator
using bad_json = nlohmann::basic_json<std::map,
std::vector,
std::string,
bool,
std::int64_t,
std::uint64_t,
double,
bad_allocator>;
// creating an object should throw
CHECK_THROWS_AS(bad_json(bad_json::value_t::object), std::bad_alloc&);
}
}
namespace
{
bool next_construct_fails = false;
bool next_destroy_fails = false;
bool next_deallocate_fails = false;
template<class T>
struct my_allocator : std::allocator<T>
{
using std::allocator<T>::allocator;
template<class... Args>
void construct(T* p, Args&& ... args)
{
if (next_construct_fails)
{
next_construct_fails = false;
throw std::bad_alloc();
}
else
{
::new (reinterpret_cast<void*>(p)) T(std::forward<Args>(args)...);
}
}
void deallocate(T* p, std::size_t n)
{
if (next_deallocate_fails)
{
next_deallocate_fails = false;
throw std::bad_alloc();
}
else
{
std::allocator<T>::deallocate(p, n);
}
}
void destroy(T* p)
{
if (next_destroy_fails)
{
next_destroy_fails = false;
throw std::bad_alloc();
}
else
{
p->~T();
}
}
template <class U>
struct rebind
{
using other = my_allocator<U>;
};
};
// allows deletion of raw pointer, usually hold by json_value
template<class T>
void my_allocator_clean_up(T* p)
{
assert(p != nullptr);
my_allocator<T> alloc;
alloc.destroy(p);
alloc.deallocate(p, 1);
}
}
TEST_CASE("controlled bad_alloc")
{
// create JSON type using the throwing allocator
using my_json = nlohmann::basic_json<std::map,
std::vector,
std::string,
bool,
std::int64_t,
std::uint64_t,
double,
my_allocator>;
SECTION("class json_value")
{
SECTION("json_value(value_t)")
{
SECTION("object")
{
next_construct_fails = false;
auto t = my_json::value_t::object;
CHECK_NOTHROW(my_allocator_clean_up(my_json::json_value(t).object));
next_construct_fails = true;
CHECK_THROWS_AS(my_json::json_value(t), std::bad_alloc&);
next_construct_fails = false;
}
SECTION("array")
{
next_construct_fails = false;
auto t = my_json::value_t::array;
CHECK_NOTHROW(my_allocator_clean_up(my_json::json_value(t).array));
next_construct_fails = true;
CHECK_THROWS_AS(my_json::json_value(t), std::bad_alloc&);
next_construct_fails = false;
}
SECTION("string")
{
next_construct_fails = false;
auto t = my_json::value_t::string;
CHECK_NOTHROW(my_allocator_clean_up(my_json::json_value(t).string));
next_construct_fails = true;
CHECK_THROWS_AS(my_json::json_value(t), std::bad_alloc&);
next_construct_fails = false;
}
}
SECTION("json_value(const string_t&)")
{
next_construct_fails = false;
my_json::string_t v("foo");
CHECK_NOTHROW(my_allocator_clean_up(my_json::json_value(v).string));
next_construct_fails = true;
CHECK_THROWS_AS(my_json::json_value(v), std::bad_alloc&);
next_construct_fails = false;
}
}
SECTION("class basic_json")
{
SECTION("basic_json(const CompatibleObjectType&)")
{
next_construct_fails = false;
std::map<std::string, std::string> v {{"foo", "bar"}};
CHECK_NOTHROW(my_json(v));
next_construct_fails = true;
CHECK_THROWS_AS(my_json(v), std::bad_alloc&);
next_construct_fails = false;
}
SECTION("basic_json(const CompatibleArrayType&)")
{
next_construct_fails = false;
std::vector<std::string> v {"foo", "bar", "baz"};
CHECK_NOTHROW(my_json(v));
next_construct_fails = true;
CHECK_THROWS_AS(my_json(v), std::bad_alloc&);
next_construct_fails = false;
}
SECTION("basic_json(const typename string_t::value_type*)")
{
next_construct_fails = false;
CHECK_NOTHROW(my_json("foo"));
next_construct_fails = true;
CHECK_THROWS_AS(my_json("foo"), std::bad_alloc&);
next_construct_fails = false;
}
SECTION("basic_json(const typename string_t::value_type*)")
{
next_construct_fails = false;
std::string s("foo");
CHECK_NOTHROW(my_json(s));
next_construct_fails = true;
CHECK_THROWS_AS(my_json(s), std::bad_alloc&);
next_construct_fails = false;
}
}
}
namespace
{
template<class T>
struct allocator_no_forward : std::allocator<T>
{
using std::allocator<T>::allocator;
template <class U>
allocator_no_forward(allocator_no_forward<U>) {}
template <class U>
struct rebind {
using other = allocator_no_forward<U>;
};
template <class... Args>
void construct(T* p, const Args&... args)
{
::new (static_cast<void*>(p)) T(args...);
}
};
}
TEST_CASE("bad my_allocator::construct")
{
SECTION("my_allocator::construct doesn't forward")
{
using bad_alloc_json = nlohmann::basic_json<std::map,
std::vector,
std::string,
bool,
std::int64_t,
std::uint64_t,
double,
allocator_no_forward>;
bad_alloc_json json;
json["test"] = bad_alloc_json::array_t();
json["test"].push_back("should not leak");
}
}
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include <ros/ros.h>
#include <actionlib/client/simple_action_client.h>
#include <actionlib/client/terminal_state.h>
#include <move_base_msgs/MoveBaseAction.h>
#include <move_basic/queued_action_server.h>
#include <queue>
#include <memory>
#include <mutex>
#include <condition_variable>
class GoalQueueSuite : public ::testing::Test {
protected:
virtual void SetUp() {
resetFlags();
ros::NodeHandle actionNh("");
qserv.reset(new actionlib::QueuedActionServer<move_base_msgs::MoveBaseAction> (actionNh, "queue_server", boost::bind(&GoalQueueSuite::executeCallback, this, _1)));
cli.reset(new actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> ("queue_server", true)); // true -> don't need ros::spin()
qserv->start();
}
virtual void TearDown() {
// Kill the executeCallback if it is running
// New Scope so that lock_guard destructs and unlocks
{
std::lock_guard<std::mutex> lk1(execute_lock);
finish_executing = true;
execute_cv.notify_one(); // Releases one waiting thread
}
qserv->shutdown();
}
void executeCallback(const move_base_msgs::MoveBaseGoalConstPtr &msg) {
resetFlags();
got_goal = true;
received_goal = msg;
while (true) {
goal_preempted = qserv->isPreemptRequested() ? true : false;
next_goal_available = qserv->isNewGoalAvailable() ? true : false;
// Test fixture can continue
execution = true;
sleep_cv.notify_one();
// Wait until signalled to end
std::unique_lock<std::mutex> lk(execute_lock);
execute_cv.wait(lk,
//lambda function to wait on our bool variables
[this](){return finish_executing || resume_executing;} // blocks only if lambda returns false
);
execution = false;
// We were requested to stop, so we stop
if (finish_executing) {
break;
}
}
// Signal that we are done here
std::lock_guard<std::mutex> lk(execute_done_lock);
execute_done = true;
execute_done_cv.notify_all();
}
// Helper function to signal the executeCallback to end
void finishExecuting() {
// New Scope so that lock_guard destructs and unlocks
{
std::lock_guard<std::mutex> lk1(execute_lock);
finish_executing = true;
execute_cv.notify_one(); //unlocks lambda waiting function in ExecuteCallback
}
// Wait for execute callback to actually finish
std::unique_lock<std::mutex> lk2(execute_done_lock);
execute_done_cv.wait(lk2, [this]() {return execute_done;}); // at the end of ExecuteCallback
}
// Helper function to signal the executeCallback to resume
// This is useful for seeing if the callback code sees a preempt
void resumeExecuting() {
std::lock_guard<std::mutex> lk(execute_lock);
resume_executing = true;
execute_cv.notify_one();
}
// Helper function to wait to for flags to update in ExecuteCallback
void sleepExecuting() {
std::unique_lock<std::mutex> slk(sleep_lock);
sleep_cv.wait(slk,
[this](){return execution;}
);
}
void resetFlags() {
got_goal = false;
goal_preempted = false;
next_goal_available = false;
received_goal = nullptr;
// Signal flags
execution = false;
finish_executing = false;
resume_executing = false;
execute_done = false;
}
// Flags for assertions
bool got_goal;
bool goal_preempted;
bool next_goal_available;
move_base_msgs::MoveBaseGoalConstPtr received_goal;
// Signaling variables
bool execution;
bool finish_executing;
bool resume_executing;
bool execute_done;
std::mutex sleep_lock;
std::mutex execute_lock;
std::mutex execute_done_lock;
std::condition_variable sleep_cv;
std::condition_variable execute_cv;
std::condition_variable execute_done_cv;
std::unique_ptr<actionlib::QueuedActionServer<move_base_msgs::MoveBaseAction>> qserv;
std::unique_ptr<actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction>> cli;
};
TEST_F(GoalQueueSuite, establishDuplex) {
move_base_msgs::MoveBaseGoal goal;
goal.target_pose.pose.position.x = 3.0;
cli->sendGoal(goal);
ros::spinOnce();
sleepExecuting();
EXPECT_TRUE(got_goal);
EXPECT_FALSE(goal_preempted);
EXPECT_FALSE(next_goal_available);
EXPECT_EQ(3.0, received_goal->target_pose.pose.position.x);
finishExecuting();
}
/*
TEST_F(GoalQueueSuite, addGoalWhileExecuting) {
move_base_msgs::MoveBaseGoal goal;
// First goal
goal.target_pose.pose.position.x = 3.0;
cli->sendGoal(goal);
ros::spinOnce();
sleepExecuting();
EXPECT_TRUE(got_goal);
EXPECT_FALSE(goal_preempted);
EXPECT_FALSE(next_goal_available);
EXPECT_EQ(3.0, received_goal->target_pose.pose.position.x);
// Second goal
goal.target_pose.pose.position.x = 7.0;
cli->sendGoal(goal);
ros::spinOnce();
sleepExecuting();
// ASSERT_TRUE(next_goal_available); // TODO: Why is this failling?
// Cancelling the last goal - TODO: Doesnt work!
cli->cancelGoal(); // Cancels the last goal sent
ros::spinOnce();
ros::Duration(1.0).sleep();
EXPECT_EQ(3.0, received_goal->target_pose.pose.position.x);
finishExecuting(); // Finish 1st goal
ros::Duration(3.0).sleep();
// ASSERT_TRUE(goal_preempted); // TODO: Why is this failling?
finishExecuting(); // Finish 2nd (canceled) goal
ros::Duration(3.0).sleep();
// New goal
goal.target_pose.pose.position.x = 13.0;
cli->sendGoal(goal);
ros::spinOnce();
sleepExecuting();
EXPECT_TRUE(got_goal);
EXPECT_FALSE(goal_preempted);
EXPECT_EQ(13.0, received_goal->target_pose.pose.position.x); // BUG: X=7 (from canceled goal)
finishExecuting(); // Finish new goal
// - if another goal is received add it to the queue (DONE)
// - if the queue full, set the next goal as preempted - explicitly called! - so cancelling the next goal and adding new to the queue
// - start executing the new goal in queue (after the current)
}
TEST_F(GoalQueueSuite, goalPreempting) {
move_base_msgs::MoveBaseGoal goal;
// One goal -> Cancel request -> Stop
goal.target_pose.pose.position.x = 3.0;
cli->sendGoal(goal);
ros::spinOnce();
sleepExecuting();
ASSERT_TRUE(got_goal);
ASSERT_EQ(3.0, received_goal->target_pose.pose.position.x);
cli->cancelGoal();
ros::spinOnce();
resumeExecuting();
// ros::spinOnce();
sleepExecuting();
// ASSERT_TRUE(goal_preempted);
finishExecuting(); // Finish the goal
ros::spinOnce();
sleepExecuting();
// ASSERT_FALSE(qserv->isActive());
// Two goals -> Cancel current goal -> Start executing the second
// First goal
cli->sendGoal(goal);
ros::spinOnce();
sleepExecuting();
// ASSERT_TRUE(qserv->isActive());
ASSERT_TRUE(got_goal);
ASSERT_EQ(3.0, received_goal->target_pose.pose.position.x);
// Cancelling the first goal - PITFALL
cli->cancelGoal();
ros::spinOnce();
resumeExecuting();
sleepExecuting();
// ros::spinOnce();
// ASSERT_TRUE(goal_preempted);
// Finish the preempted goal
finishExecuting(); // Finish 1st goal
// "Second" goal
goal.target_pose.pose.position.x = 7.0;
cli->sendGoal(goal);
ros::spinOnce();
sleepExecuting();
ASSERT_TRUE(got_goal);
// ASSERT_EQ(7.0, received_goal->target_pose.pose.position.x); // call FINISH!
finishExecuting(); // Finish 2nd goal
// - if a cancel request is received for the current goal, set it as preempted (DONE)
// - if there another goal, start executing it
// - if no goal, stop (DONE)
}
*/
TEST_F(GoalQueueSuite, goalCancelling) {
move_base_msgs::MoveBaseGoal goal;
goal.target_pose.pose.position.x = 3.0;
// Two goals -> Cancel current goal -> Start executing the second
cli->sendGoal(goal);
ros::spinOnce();
sleepExecuting();
ASSERT_TRUE(got_goal);
ASSERT_EQ(3.0, received_goal->target_pose.pose.position.x);
// Second goal
goal.target_pose.pose.position.x = 7.0;
cli->sendGoal(goal);
ros::spinOnce();
resumeExecuting();
ros::Duration(0.5).sleep(); // Needs to wait so the execution variable can update
sleepExecuting();
ASSERT_EQ(3.0, received_goal->target_pose.pose.position.x);
EXPECT_TRUE(next_goal_available);
// Cancelling the second goal
EXPECT_TRUE(qserv->isActive());
cli->cancelGoal();
ros::Duration(1.0).sleep();
ros::spinOnce();
finishExecuting(); // finish 1st goal
ros::Duration(1.0).sleep(); // Needs to wait so the executeCallback can finish
EXPECT_TRUE(goal_preempted); // Must be checked in the goal-thread that is cancelled
finishExecuting(); // Finish the cancelled goal
ros::Duration(1.0).sleep();
ASSERT_FALSE(qserv->isActive());
// - if a cancel request on the "next_goal" received, remove it from the queue and set it as cancelled
}
// Two more TEST_F missing
int main(int argc, char **argv) {
ros::init(argc, argv, "goal_queueing_test");
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>addGoalWhileExecuting works.<commit_after>#include <gtest/gtest.h>
#include <ros/ros.h>
#include <actionlib/client/simple_action_client.h>
#include <actionlib/client/terminal_state.h>
#include <move_base_msgs/MoveBaseAction.h>
#include <move_basic/queued_action_server.h>
#include <queue>
#include <memory>
#include <mutex>
#include <condition_variable>
class GoalQueueSuite : public ::testing::Test {
protected:
virtual void SetUp() {
resetFlags();
ros::NodeHandle actionNh("");
qserv.reset(new actionlib::QueuedActionServer<move_base_msgs::MoveBaseAction> (actionNh, "queue_server", boost::bind(&GoalQueueSuite::executeCallback, this, _1)));
cli.reset(new actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> ("queue_server", true)); // true -> don't need ros::spin()
qserv->start();
}
virtual void TearDown() {
// Kill the executeCallback if it is running
// New Scope so that lock_guard destructs and unlocks
{
std::lock_guard<std::mutex> lk1(execute_lock);
finish_executing = true;
execute_cv.notify_one(); // Releases one waiting thread
}
qserv->shutdown();
}
void executeCallback(const move_base_msgs::MoveBaseGoalConstPtr &msg) {
resetFlags();
got_goal = true;
received_goal = msg;
while (true) {
goal_preempted = qserv->isPreemptRequested() ? true : false;
next_goal_available = qserv->isNewGoalAvailable() ? true : false;
// Test fixture can continue
execution = true;
sleep_cv.notify_one();
// Wait until signalled to end
std::unique_lock<std::mutex> lk(execute_lock);
execute_cv.wait(lk,
//lambda function to wait on our bool variables
[this](){return finish_executing || resume_executing;} // blocks only if lambda returns false
);
execution = false;
// We were requested to stop, so we stop
if (finish_executing) {
break;
}
}
// Signal that we are done here
std::lock_guard<std::mutex> lk(execute_done_lock);
execute_done = true;
execute_done_cv.notify_all();
}
// Helper function to signal the executeCallback to end
void finishExecuting() {
// New Scope so that lock_guard destructs and unlocks
{
std::lock_guard<std::mutex> lk1(execute_lock);
finish_executing = true;
execute_cv.notify_one(); //unlocks lambda waiting function in ExecuteCallback
}
// Wait for execute callback to actually finish
std::unique_lock<std::mutex> lk2(execute_done_lock);
execute_done_cv.wait(lk2, [this]() {return execute_done;}); // at the end of ExecuteCallback
}
// Helper function to signal the executeCallback to resume
// This is useful for seeing if the callback code sees a preempt
void resumeExecuting() {
std::lock_guard<std::mutex> lk(execute_lock);
resume_executing = true;
execute_cv.notify_one();
}
// Helper function to wait to for flags to update in ExecuteCallback
void sleepExecuting() {
std::unique_lock<std::mutex> slk(sleep_lock);
sleep_cv.wait(slk,
[this](){return execution;}
);
}
void resetFlags() {
got_goal = false;
goal_preempted = false;
next_goal_available = false;
received_goal = nullptr;
// Signal flags
execution = false;
finish_executing = false;
resume_executing = false;
execute_done = false;
}
// Flags for assertions
bool got_goal;
bool goal_preempted;
bool next_goal_available;
move_base_msgs::MoveBaseGoalConstPtr received_goal;
// Signaling variables
bool execution;
bool finish_executing;
bool resume_executing;
bool execute_done;
std::mutex sleep_lock;
std::mutex execute_lock;
std::mutex execute_done_lock;
std::condition_variable sleep_cv;
std::condition_variable execute_cv;
std::condition_variable execute_done_cv;
std::unique_ptr<actionlib::QueuedActionServer<move_base_msgs::MoveBaseAction>> qserv;
std::unique_ptr<actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction>> cli;
};
TEST_F(GoalQueueSuite, establishDuplex) {
move_base_msgs::MoveBaseGoal goal;
goal.target_pose.pose.position.x = 3.0;
cli->sendGoal(goal);
ros::spinOnce();
sleepExecuting();
EXPECT_TRUE(got_goal);
EXPECT_FALSE(goal_preempted);
EXPECT_FALSE(next_goal_available);
EXPECT_EQ(3.0, received_goal->target_pose.pose.position.x);
finishExecuting();
ros::Duration(0.5).sleep();
EXPECT_FALSE(qserv->isActive());
}
TEST_F(GoalQueueSuite, addGoalWhileExecuting) {
move_base_msgs::MoveBaseGoal goal;
// First goal
goal.target_pose.pose.position.x = 3.0;
cli->sendGoal(goal);
ros::spinOnce();
sleepExecuting();
EXPECT_TRUE(got_goal);
EXPECT_FALSE(goal_preempted);
EXPECT_FALSE(next_goal_available);
EXPECT_EQ(3.0, received_goal->target_pose.pose.position.x);
// Second goal
goal.target_pose.pose.position.x = 7.0;
cli->sendGoal(goal);
ros::spinOnce();
resumeExecuting();
ros::Duration(0.5).sleep();
sleepExecuting();
EXPECT_TRUE(next_goal_available);
// Cancel the last goal sent
cli->cancelGoal();
ros::Duration(1.0).sleep();
ros::spinOnce();
EXPECT_EQ(3.0, received_goal->target_pose.pose.position.x); // Making sure we are in the first goal thread
finishExecuting(); // Finish 1st goal
ros::Duration(0.5).sleep();
EXPECT_TRUE(goal_preempted);
finishExecuting(); // Finish 2nd (canceled) goal
ros::Duration(0.5).sleep();
// New goal
goal.target_pose.pose.position.x = 13.0;
cli->sendGoal(goal);
ros::spinOnce();
sleepExecuting();
EXPECT_TRUE(got_goal);
EXPECT_FALSE(goal_preempted);
EXPECT_EQ(13.0, received_goal->target_pose.pose.position.x);
finishExecuting(); // Finish new goal
// - if another goal is received add it to the queue (DONE)
// - if the queue full, set the next goal as preempted - explicitly called! - so cancelling the next goal and adding new to the queue
// - start executing the new goal in queue (after the current)
}
/*
TEST_F(GoalQueueSuite, goalPreempting) {
move_base_msgs::MoveBaseGoal goal;
// One goal -> Cancel request -> Stop
goal.target_pose.pose.position.x = 3.0;
cli->sendGoal(goal);
ros::spinOnce();
sleepExecuting();
ASSERT_TRUE(got_goal);
ASSERT_EQ(3.0, received_goal->target_pose.pose.position.x);
cli->cancelGoal();
ros::spinOnce();
resumeExecuting();
// ros::spinOnce();
sleepExecuting();
// ASSERT_TRUE(goal_preempted);
finishExecuting(); // Finish the goal
ros::spinOnce();
sleepExecuting();
// ASSERT_FALSE(qserv->isActive());
// Two goals -> Cancel current goal -> Start executing the second
// First goal
cli->sendGoal(goal);
ros::spinOnce();
sleepExecuting();
// ASSERT_TRUE(qserv->isActive());
ASSERT_TRUE(got_goal);
ASSERT_EQ(3.0, received_goal->target_pose.pose.position.x);
// Cancelling the first goal - PITFALL
cli->cancelGoal();
ros::spinOnce();
resumeExecuting();
sleepExecuting();
// ros::spinOnce();
// ASSERT_TRUE(goal_preempted);
// Finish the preempted goal
finishExecuting(); // Finish 1st goal
// "Second" goal
goal.target_pose.pose.position.x = 7.0;
cli->sendGoal(goal);
ros::spinOnce();
sleepExecuting();
ASSERT_TRUE(got_goal);
// ASSERT_EQ(7.0, received_goal->target_pose.pose.position.x); // call FINISH!
finishExecuting(); // Finish 2nd goal
// - if a cancel request is received for the current goal, set it as preempted (DONE)
// - if there another goal, start executing it
// - if no goal, stop (DONE)
}
*/
TEST_F(GoalQueueSuite, goalCancelling) {
move_base_msgs::MoveBaseGoal goal;
goal.target_pose.pose.position.x = 3.0;
// Two goals -> Cancel current goal -> Start executing the second
cli->sendGoal(goal);
ros::spinOnce();
sleepExecuting();
ASSERT_TRUE(got_goal);
ASSERT_EQ(3.0, received_goal->target_pose.pose.position.x);
// Second goal
goal.target_pose.pose.position.x = 7.0;
cli->sendGoal(goal);
ros::spinOnce();
resumeExecuting();
ros::Duration(0.5).sleep(); // Needs to wait so the execution variable can update
sleepExecuting();
ASSERT_EQ(3.0, received_goal->target_pose.pose.position.x);
EXPECT_TRUE(next_goal_available);
// Cancelling the second goal
EXPECT_TRUE(qserv->isActive());
cli->cancelGoal();
ros::Duration(1.0).sleep();
ros::spinOnce();
finishExecuting(); // finish 1st goal
ros::Duration(0.5).sleep(); // Needs to wait so the executeCallback can finish
EXPECT_TRUE(goal_preempted); // Must be checked in the goal-thread that is cancelled
finishExecuting(); // Finish the cancelled goal
ros::Duration(0.5).sleep();
ASSERT_FALSE(qserv->isActive());
// - if a cancel request on the "next_goal" received, remove it from the queue and set it as cancelled
}
// Two more TEST_F missing
int main(int argc, char **argv) {
ros::init(argc, argv, "goal_queueing_test");
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>//===- CoverageReport.cpp - Code coverage report -------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This class implements rendering of a code coverage report.
//
//===----------------------------------------------------------------------===//
#include "CoverageReport.h"
#include "RenderingSupport.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/Path.h"
#include <numeric>
using namespace llvm;
namespace {
/// \brief Helper struct which prints trimmed and aligned columns.
struct Column {
enum TrimKind { NoTrim, WidthTrim, RightTrim };
enum AlignmentKind { LeftAlignment, RightAlignment };
StringRef Str;
unsigned Width;
TrimKind Trim;
AlignmentKind Alignment;
Column(StringRef Str, unsigned Width)
: Str(Str), Width(Width), Trim(WidthTrim), Alignment(LeftAlignment) {}
Column &set(TrimKind Value) {
Trim = Value;
return *this;
}
Column &set(AlignmentKind Value) {
Alignment = Value;
return *this;
}
void render(raw_ostream &OS) const {
if (Str.size() <= Width) {
if (Alignment == RightAlignment) {
OS.indent(Width - Str.size());
OS << Str;
return;
}
OS << Str;
OS.indent(Width - Str.size());
return;
}
switch (Trim) {
case NoTrim:
OS << Str;
break;
case WidthTrim:
OS << Str.substr(0, Width);
break;
case RightTrim:
OS << Str.substr(0, Width - 3) << "...";
break;
}
}
};
raw_ostream &operator<<(raw_ostream &OS, const Column &Value) {
Value.render(OS);
return OS;
}
Column column(StringRef Str, unsigned Width) { return Column(Str, Width); }
template <typename T>
Column column(StringRef Str, unsigned Width, const T &Value) {
return Column(Str, Width).set(Value);
}
// Specify the default column widths.
size_t FileReportColumns[] = {25, 12, 18, 10, 12, 18, 10, 12, 18, 10};
size_t FunctionReportColumns[] = {25, 10, 8, 8, 10, 8, 8};
/// \brief Adjust column widths to fit long file paths and function names.
void adjustColumnWidths(const coverage::CoverageMapping &CM) {
for (StringRef Filename : CM.getUniqueSourceFiles()) {
FileReportColumns[0] = std::max(FileReportColumns[0], Filename.size());
for (const auto &F : CM.getCoveredFunctions(Filename)) {
FunctionReportColumns[0] =
std::max(FunctionReportColumns[0], F.Name.size());
}
}
}
/// \brief Prints a horizontal divider long enough to cover the given column
/// widths.
void renderDivider(ArrayRef<size_t> ColumnWidths, raw_ostream &OS) {
size_t Length = std::accumulate(ColumnWidths.begin(), ColumnWidths.end(), 0);
for (size_t I = 0; I < Length; ++I)
OS << '-';
}
/// \brief Return the color which correponds to the coverage percentage of a
/// certain metric.
template <typename T>
raw_ostream::Colors determineCoveragePercentageColor(const T &Info) {
if (Info.isFullyCovered())
return raw_ostream::GREEN;
return Info.getPercentCovered() >= 80.0 ? raw_ostream::YELLOW
: raw_ostream::RED;
}
/// \brief Determine the length of the longest common prefix of the strings in
/// \p Strings.
unsigned getLongestCommonPrefixLen(ArrayRef<StringRef> Strings) {
unsigned LCP = Strings[0].size();
for (unsigned I = 1, E = Strings.size(); LCP > 0 && I < E; ++I) {
auto Mismatch =
std::mismatch(Strings[0].begin(), Strings[0].end(), Strings[I].begin())
.first;
LCP = std::min(LCP, (unsigned)std::distance(Strings[0].begin(), Mismatch));
}
return LCP;
}
} // end anonymous namespace
namespace llvm {
void CoverageReport::render(const FileCoverageSummary &File,
raw_ostream &OS) const {
auto FileCoverageColor =
determineCoveragePercentageColor(File.RegionCoverage);
auto FuncCoverageColor =
determineCoveragePercentageColor(File.FunctionCoverage);
auto LineCoverageColor = determineCoveragePercentageColor(File.LineCoverage);
SmallString<256> FileName = File.Name;
sys::path::remove_dots(FileName, /*remove_dot_dots=*/true);
sys::path::native(FileName);
OS << column(FileName, FileReportColumns[0], Column::NoTrim)
<< format("%*u", FileReportColumns[1],
(unsigned)File.RegionCoverage.NumRegions);
Options.colored_ostream(OS, FileCoverageColor) << format(
"%*u", FileReportColumns[2], (unsigned)File.RegionCoverage.NotCovered);
Options.colored_ostream(OS, FileCoverageColor)
<< format("%*.2f", FileReportColumns[3] - 1,
File.RegionCoverage.getPercentCovered())
<< '%';
OS << format("%*u", FileReportColumns[4],
(unsigned)File.FunctionCoverage.NumFunctions);
OS << format("%*u", FileReportColumns[5],
(unsigned)(File.FunctionCoverage.NumFunctions -
File.FunctionCoverage.Executed));
Options.colored_ostream(OS, FuncCoverageColor)
<< format("%*.2f", FileReportColumns[6] - 1,
File.FunctionCoverage.getPercentCovered())
<< '%';
OS << format("%*u", FileReportColumns[7],
(unsigned)File.LineCoverage.NumLines);
Options.colored_ostream(OS, LineCoverageColor) << format(
"%*u", FileReportColumns[8], (unsigned)File.LineCoverage.NotCovered);
Options.colored_ostream(OS, LineCoverageColor)
<< format("%*.2f", FileReportColumns[9] - 1,
File.LineCoverage.getPercentCovered())
<< '%';
OS << "\n";
}
void CoverageReport::render(const FunctionCoverageSummary &Function,
raw_ostream &OS) const {
auto FuncCoverageColor =
determineCoveragePercentageColor(Function.RegionCoverage);
auto LineCoverageColor =
determineCoveragePercentageColor(Function.LineCoverage);
OS << column(Function.Name, FunctionReportColumns[0], Column::RightTrim)
<< format("%*u", FunctionReportColumns[1],
(unsigned)Function.RegionCoverage.NumRegions);
Options.colored_ostream(OS, FuncCoverageColor)
<< format("%*u", FunctionReportColumns[2],
(unsigned)Function.RegionCoverage.NotCovered);
Options.colored_ostream(
OS, determineCoveragePercentageColor(Function.RegionCoverage))
<< format("%*.2f", FunctionReportColumns[3] - 1,
Function.RegionCoverage.getPercentCovered())
<< '%';
OS << format("%*u", FunctionReportColumns[4],
(unsigned)Function.LineCoverage.NumLines);
Options.colored_ostream(OS, LineCoverageColor)
<< format("%*u", FunctionReportColumns[5],
(unsigned)Function.LineCoverage.NotCovered);
Options.colored_ostream(
OS, determineCoveragePercentageColor(Function.LineCoverage))
<< format("%*.2f", FunctionReportColumns[6] - 1,
Function.LineCoverage.getPercentCovered())
<< '%';
OS << "\n";
}
void CoverageReport::renderFunctionReports(ArrayRef<StringRef> Files,
raw_ostream &OS) {
adjustColumnWidths(Coverage);
bool isFirst = true;
for (StringRef Filename : Files) {
if (isFirst)
isFirst = false;
else
OS << "\n";
OS << "File '" << Filename << "':\n";
OS << column("Name", FunctionReportColumns[0])
<< column("Regions", FunctionReportColumns[1], Column::RightAlignment)
<< column("Miss", FunctionReportColumns[2], Column::RightAlignment)
<< column("Cover", FunctionReportColumns[3], Column::RightAlignment)
<< column("Lines", FunctionReportColumns[4], Column::RightAlignment)
<< column("Miss", FunctionReportColumns[5], Column::RightAlignment)
<< column("Cover", FunctionReportColumns[6], Column::RightAlignment);
OS << "\n";
renderDivider(FunctionReportColumns, OS);
OS << "\n";
FunctionCoverageSummary Totals("TOTAL");
for (const auto &F : Coverage.getCoveredFunctions(Filename)) {
FunctionCoverageSummary Function = FunctionCoverageSummary::get(F);
++Totals.ExecutionCount;
Totals.RegionCoverage += Function.RegionCoverage;
Totals.LineCoverage += Function.LineCoverage;
render(Function, OS);
}
if (Totals.ExecutionCount) {
renderDivider(FunctionReportColumns, OS);
OS << "\n";
render(Totals, OS);
}
}
}
std::vector<FileCoverageSummary>
CoverageReport::prepareFileReports(FileCoverageSummary &Totals,
ArrayRef<StringRef> Files) const {
std::vector<FileCoverageSummary> FileReports;
unsigned LCP = 0;
if (Files.size() > 1)
LCP = getLongestCommonPrefixLen(Files);
for (StringRef Filename : Files) {
FileCoverageSummary Summary(Filename.drop_front(LCP));
for (const auto &F : Coverage.getCoveredFunctions(Filename)) {
FunctionCoverageSummary Function = FunctionCoverageSummary::get(F);
Summary.addFunction(Function);
Totals.addFunction(Function);
}
FileReports.push_back(Summary);
}
return FileReports;
}
void CoverageReport::renderFileReports(raw_ostream &OS) const {
std::vector<StringRef> UniqueSourceFiles = Coverage.getUniqueSourceFiles();
renderFileReports(OS, UniqueSourceFiles);
}
void CoverageReport::renderFileReports(raw_ostream &OS,
ArrayRef<StringRef> Files) const {
adjustColumnWidths(Coverage);
OS << column("Filename", FileReportColumns[0])
<< column("Regions", FileReportColumns[1], Column::RightAlignment)
<< column("Missed Regions", FileReportColumns[2], Column::RightAlignment)
<< column("Cover", FileReportColumns[3], Column::RightAlignment)
<< column("Functions", FileReportColumns[4], Column::RightAlignment)
<< column("Missed Functions", FileReportColumns[5], Column::RightAlignment)
<< column("Executed", FileReportColumns[6], Column::RightAlignment)
<< column("Lines", FileReportColumns[7], Column::RightAlignment)
<< column("Missed Lines", FileReportColumns[8], Column::RightAlignment)
<< column("Cover", FileReportColumns[9], Column::RightAlignment) << "\n";
renderDivider(FileReportColumns, OS);
OS << "\n";
FileCoverageSummary Totals("TOTAL");
auto FileReports = prepareFileReports(Totals, Files);
for (const FileCoverageSummary &FCS : FileReports)
render(FCS, OS);
renderDivider(FileReportColumns, OS);
OS << "\n";
render(Totals, OS);
}
} // end namespace llvm
<commit_msg>[llvm-cov] Make 'adjustColumnWidths' do less work<commit_after>//===- CoverageReport.cpp - Code coverage report -------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This class implements rendering of a code coverage report.
//
//===----------------------------------------------------------------------===//
#include "CoverageReport.h"
#include "RenderingSupport.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/Path.h"
#include <numeric>
using namespace llvm;
namespace {
/// \brief Helper struct which prints trimmed and aligned columns.
struct Column {
enum TrimKind { NoTrim, WidthTrim, RightTrim };
enum AlignmentKind { LeftAlignment, RightAlignment };
StringRef Str;
unsigned Width;
TrimKind Trim;
AlignmentKind Alignment;
Column(StringRef Str, unsigned Width)
: Str(Str), Width(Width), Trim(WidthTrim), Alignment(LeftAlignment) {}
Column &set(TrimKind Value) {
Trim = Value;
return *this;
}
Column &set(AlignmentKind Value) {
Alignment = Value;
return *this;
}
void render(raw_ostream &OS) const {
if (Str.size() <= Width) {
if (Alignment == RightAlignment) {
OS.indent(Width - Str.size());
OS << Str;
return;
}
OS << Str;
OS.indent(Width - Str.size());
return;
}
switch (Trim) {
case NoTrim:
OS << Str;
break;
case WidthTrim:
OS << Str.substr(0, Width);
break;
case RightTrim:
OS << Str.substr(0, Width - 3) << "...";
break;
}
}
};
raw_ostream &operator<<(raw_ostream &OS, const Column &Value) {
Value.render(OS);
return OS;
}
Column column(StringRef Str, unsigned Width) { return Column(Str, Width); }
template <typename T>
Column column(StringRef Str, unsigned Width, const T &Value) {
return Column(Str, Width).set(Value);
}
// Specify the default column widths.
size_t FileReportColumns[] = {25, 12, 18, 10, 12, 18, 10, 12, 18, 10};
size_t FunctionReportColumns[] = {25, 10, 8, 8, 10, 8, 8};
/// \brief Adjust column widths to fit long file paths and function names.
void adjustColumnWidths(ArrayRef<StringRef> Files,
ArrayRef<StringRef> Functions) {
for (StringRef Filename : Files)
FileReportColumns[0] = std::max(FileReportColumns[0], Filename.size());
for (StringRef Funcname : Functions)
FunctionReportColumns[0] =
std::max(FunctionReportColumns[0], Funcname.size());
}
/// \brief Prints a horizontal divider long enough to cover the given column
/// widths.
void renderDivider(ArrayRef<size_t> ColumnWidths, raw_ostream &OS) {
size_t Length = std::accumulate(ColumnWidths.begin(), ColumnWidths.end(), 0);
for (size_t I = 0; I < Length; ++I)
OS << '-';
}
/// \brief Return the color which correponds to the coverage percentage of a
/// certain metric.
template <typename T>
raw_ostream::Colors determineCoveragePercentageColor(const T &Info) {
if (Info.isFullyCovered())
return raw_ostream::GREEN;
return Info.getPercentCovered() >= 80.0 ? raw_ostream::YELLOW
: raw_ostream::RED;
}
/// \brief Determine the length of the longest common prefix of the strings in
/// \p Strings.
unsigned getLongestCommonPrefixLen(ArrayRef<StringRef> Strings) {
unsigned LCP = Strings[0].size();
for (unsigned I = 1, E = Strings.size(); LCP > 0 && I < E; ++I) {
auto Mismatch =
std::mismatch(Strings[0].begin(), Strings[0].end(), Strings[I].begin())
.first;
LCP = std::min(LCP, (unsigned)std::distance(Strings[0].begin(), Mismatch));
}
return LCP;
}
} // end anonymous namespace
namespace llvm {
void CoverageReport::render(const FileCoverageSummary &File,
raw_ostream &OS) const {
auto FileCoverageColor =
determineCoveragePercentageColor(File.RegionCoverage);
auto FuncCoverageColor =
determineCoveragePercentageColor(File.FunctionCoverage);
auto LineCoverageColor = determineCoveragePercentageColor(File.LineCoverage);
SmallString<256> FileName = File.Name;
sys::path::remove_dots(FileName, /*remove_dot_dots=*/true);
sys::path::native(FileName);
OS << column(FileName, FileReportColumns[0], Column::NoTrim)
<< format("%*u", FileReportColumns[1],
(unsigned)File.RegionCoverage.NumRegions);
Options.colored_ostream(OS, FileCoverageColor) << format(
"%*u", FileReportColumns[2], (unsigned)File.RegionCoverage.NotCovered);
Options.colored_ostream(OS, FileCoverageColor)
<< format("%*.2f", FileReportColumns[3] - 1,
File.RegionCoverage.getPercentCovered())
<< '%';
OS << format("%*u", FileReportColumns[4],
(unsigned)File.FunctionCoverage.NumFunctions);
OS << format("%*u", FileReportColumns[5],
(unsigned)(File.FunctionCoverage.NumFunctions -
File.FunctionCoverage.Executed));
Options.colored_ostream(OS, FuncCoverageColor)
<< format("%*.2f", FileReportColumns[6] - 1,
File.FunctionCoverage.getPercentCovered())
<< '%';
OS << format("%*u", FileReportColumns[7],
(unsigned)File.LineCoverage.NumLines);
Options.colored_ostream(OS, LineCoverageColor) << format(
"%*u", FileReportColumns[8], (unsigned)File.LineCoverage.NotCovered);
Options.colored_ostream(OS, LineCoverageColor)
<< format("%*.2f", FileReportColumns[9] - 1,
File.LineCoverage.getPercentCovered())
<< '%';
OS << "\n";
}
void CoverageReport::render(const FunctionCoverageSummary &Function,
raw_ostream &OS) const {
auto FuncCoverageColor =
determineCoveragePercentageColor(Function.RegionCoverage);
auto LineCoverageColor =
determineCoveragePercentageColor(Function.LineCoverage);
OS << column(Function.Name, FunctionReportColumns[0], Column::RightTrim)
<< format("%*u", FunctionReportColumns[1],
(unsigned)Function.RegionCoverage.NumRegions);
Options.colored_ostream(OS, FuncCoverageColor)
<< format("%*u", FunctionReportColumns[2],
(unsigned)Function.RegionCoverage.NotCovered);
Options.colored_ostream(
OS, determineCoveragePercentageColor(Function.RegionCoverage))
<< format("%*.2f", FunctionReportColumns[3] - 1,
Function.RegionCoverage.getPercentCovered())
<< '%';
OS << format("%*u", FunctionReportColumns[4],
(unsigned)Function.LineCoverage.NumLines);
Options.colored_ostream(OS, LineCoverageColor)
<< format("%*u", FunctionReportColumns[5],
(unsigned)Function.LineCoverage.NotCovered);
Options.colored_ostream(
OS, determineCoveragePercentageColor(Function.LineCoverage))
<< format("%*.2f", FunctionReportColumns[6] - 1,
Function.LineCoverage.getPercentCovered())
<< '%';
OS << "\n";
}
void CoverageReport::renderFunctionReports(ArrayRef<StringRef> Files,
raw_ostream &OS) {
bool isFirst = true;
for (StringRef Filename : Files) {
auto Functions = Coverage.getCoveredFunctions(Filename);
if (isFirst)
isFirst = false;
else
OS << "\n";
std::vector<StringRef> Funcnames;
for (const auto &F : Functions)
Funcnames.emplace_back(F.Name);
adjustColumnWidths({}, Funcnames);
OS << "File '" << Filename << "':\n";
OS << column("Name", FunctionReportColumns[0])
<< column("Regions", FunctionReportColumns[1], Column::RightAlignment)
<< column("Miss", FunctionReportColumns[2], Column::RightAlignment)
<< column("Cover", FunctionReportColumns[3], Column::RightAlignment)
<< column("Lines", FunctionReportColumns[4], Column::RightAlignment)
<< column("Miss", FunctionReportColumns[5], Column::RightAlignment)
<< column("Cover", FunctionReportColumns[6], Column::RightAlignment);
OS << "\n";
renderDivider(FunctionReportColumns, OS);
OS << "\n";
FunctionCoverageSummary Totals("TOTAL");
for (const auto &F : Functions) {
FunctionCoverageSummary Function = FunctionCoverageSummary::get(F);
++Totals.ExecutionCount;
Totals.RegionCoverage += Function.RegionCoverage;
Totals.LineCoverage += Function.LineCoverage;
render(Function, OS);
}
if (Totals.ExecutionCount) {
renderDivider(FunctionReportColumns, OS);
OS << "\n";
render(Totals, OS);
}
}
}
std::vector<FileCoverageSummary>
CoverageReport::prepareFileReports(FileCoverageSummary &Totals,
ArrayRef<StringRef> Files) const {
std::vector<FileCoverageSummary> FileReports;
unsigned LCP = 0;
if (Files.size() > 1)
LCP = getLongestCommonPrefixLen(Files);
for (StringRef Filename : Files) {
FileCoverageSummary Summary(Filename.drop_front(LCP));
for (const auto &F : Coverage.getCoveredFunctions(Filename)) {
FunctionCoverageSummary Function = FunctionCoverageSummary::get(F);
Summary.addFunction(Function);
Totals.addFunction(Function);
}
FileReports.push_back(Summary);
}
return FileReports;
}
void CoverageReport::renderFileReports(raw_ostream &OS) const {
std::vector<StringRef> UniqueSourceFiles = Coverage.getUniqueSourceFiles();
renderFileReports(OS, UniqueSourceFiles);
}
void CoverageReport::renderFileReports(raw_ostream &OS,
ArrayRef<StringRef> Files) const {
FileCoverageSummary Totals("TOTAL");
auto FileReports = prepareFileReports(Totals, Files);
std::vector<StringRef> Filenames;
for (const FileCoverageSummary &FCS : FileReports)
Filenames.emplace_back(FCS.Name);
adjustColumnWidths(Filenames, {});
OS << column("Filename", FileReportColumns[0])
<< column("Regions", FileReportColumns[1], Column::RightAlignment)
<< column("Missed Regions", FileReportColumns[2], Column::RightAlignment)
<< column("Cover", FileReportColumns[3], Column::RightAlignment)
<< column("Functions", FileReportColumns[4], Column::RightAlignment)
<< column("Missed Functions", FileReportColumns[5], Column::RightAlignment)
<< column("Executed", FileReportColumns[6], Column::RightAlignment)
<< column("Lines", FileReportColumns[7], Column::RightAlignment)
<< column("Missed Lines", FileReportColumns[8], Column::RightAlignment)
<< column("Cover", FileReportColumns[9], Column::RightAlignment) << "\n";
renderDivider(FileReportColumns, OS);
OS << "\n";
for (const FileCoverageSummary &FCS : FileReports)
render(FCS, OS);
renderDivider(FileReportColumns, OS);
OS << "\n";
render(Totals, OS);
}
} // end namespace llvm
<|endoftext|> |
<commit_before>// Copyright © 2011, Université catholique de Louvain
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#ifndef __STORE_H
#define __STORE_H
#include "core-forward-decl.hh"
#include "memword.hh"
#include "storage.hh"
#include "type.hh"
/**
* A value node in the store.
* The store is entirely made of nodes. A node is basically a typed value.
* Non-atomic values, such as records, contain references to other nodes in the
* store, hence forming a graph, and the name "node".
* There are two kinds of node: stable and unstable node. A stable node is
* guaranteed never to change, whereas unstable node can change. In order to
* maintain consistency in the store, non-atomic values are only allowed to
* reference stable nodes. Unstable nodes are used for working data, and
* inherently mutable data (such as the contents of a cell).
*/
class Node {
public:
template<class T, class... Args>
void make(VM vm, Args... args) {
typedef Accessor<T, typename Storage<T>::Type> Access;
Access::init(type, value, vm, args...);
}
inline void reset(VM vm);
union {
// Regular structure of a node
struct {
const Type* type;
MemWord value;
};
// Garbage collector hack
struct {
Node* gcNext;
Node* gcFrom;
};
};
};
/**
* Stable node, which is guaranteed never to change
*/
class StableNode {
public:
inline void init(VM vm, UnstableNode& from);
private:
friend class UnstableNode;
public: // TODO make it private once the development has been bootstrapped
Node node;
};
/**
* Unstable node, which is allowed to change over time
*/
class UnstableNode {
public:
UnstableNode() {}
UnstableNode(VM vm, StableNode& from) {
copy(vm, from);
}
UnstableNode(VM vm, UnstableNode& from) {
copy(vm, from);
}
inline void copy(VM vm, StableNode& from);
inline void copy(VM vm, UnstableNode& from);
inline void swap(UnstableNode& from);
inline void reset(VM vm);
template<class T, class... Args>
void make(VM vm, Args... args) {
node.make<T>(vm, args...);
}
private:
friend class StableNode;
public: // TODO make it private once the development has been bootstrapped
Node node;
};
/**
* Base class for Self types
*/
template <class T>
class BaseSelf {
protected:
typedef typename Storage<T>::Type StorageType;
typedef Accessor<T, StorageType> Access;
public:
BaseSelf(Node* node) : _node(node) {}
template<class U, class... Args>
void make(VM vm, Args... args) {
_node->make<U>(vm, args...);
}
operator Node*() {
return _node;
}
Node& operator*() {
return *_node;
}
protected:
auto getBase() -> decltype(Access::get(MemWord())) {
return Access::get(_node->value);
}
Node* _node;
};
/**
* Self type for custom storage-based types
*/
template <class T>
class CustomStorageSelf: public BaseSelf<T> {
private:
typedef Implementation<T> Impl;
public:
CustomStorageSelf(Node* node) : BaseSelf<T>(node) {}
Impl get() {
return this->getBase();
}
};
/**
* Self type for default storage-based types
*/
template <class T>
class DefaultStorageSelf: public BaseSelf<T> {
private:
typedef Implementation<T> Impl;
public:
DefaultStorageSelf(Node* node) : BaseSelf<T>(node) {}
Impl* operator->() {
return &this->getBase();
}
};
/**
* Extractor function for the template parameters of ImplWithArray
* Given
* typedef ImplWithArray<I, E> T;
* this provides
* ExtractImplWithArray<T>::Impl === I
* ExtractImplWithArray<T>::Elem === E
*/
template <class S>
struct ExtractImplWithArray {};
template <class I, class E>
struct ExtractImplWithArray<ImplWithArray<I, E>> {
typedef I Impl;
typedef E Elem;
};
/**
* Self type for ImplWithArray-based types
*/
template <class T>
class ImplWithArraySelf: public BaseSelf<T> {
private:
typedef typename BaseSelf<T>::StorageType StorageType;
typedef typename ExtractImplWithArray<StorageType>::Impl Impl;
typedef typename ExtractImplWithArray<StorageType>::Elem Elem;
public:
ImplWithArraySelf(Node* node) : BaseSelf<T>(node) {}
Impl* operator->() {
return get().operator->();
}
Elem& operator[](size_t i) {
return get().operator[](i);
}
StaticArray<Elem> getArray(size_t size) {
return get().getArray(size);
}
private:
ImplWithArray<Impl, Elem> get() {
return ImplWithArray<Impl, Elem>(&this->getBase());
}
};
/**
* Helper for the metafunction SelfType
*/
template <class T, class S>
struct SelfTypeInner {
typedef CustomStorageSelf<T> Self;
};
/**
* Helper for the metafunction SelfType
*/
template <class T>
struct SelfTypeInner<T, DefaultStorage<T>> {
typedef DefaultStorageSelf<T> Self;
};
/**
* Helper for the metafunction SelfType
*/
template <class T, class I, class E>
struct SelfTypeInner<T, ImplWithArray<I, E>> {
typedef ImplWithArraySelf<T> Self;
};
/**
* Metafunction from type to its Self type
* Use as SelfType<T>::Self
*/
template <class T>
struct SelfType {
typedef typename SelfTypeInner<T, typename Storage<T>::Type>::Self Self;
};
/**
* Result of the call to a builtin.
* It always represents a node that must be waited upon. The value 'nullptr' is
* valid, and denotes that no value must be waited upon, i.e., the execution can
* continue.
* Throwing an exception is achieved by pointing to a failed value.
*/
typedef Node* BuiltinResult;
const BuiltinResult BuiltinResultContinue = nullptr;
/**
* Strange and magical class that allows to call methods on storage-typed nodes
*/
template<class T, class R, class M, M m>
class Impl {
public:
typedef Accessor<T, typename Storage<T>::Type> Type;
template<class... Args>
static R f(Node* it, Args... args) {
return (Type::get(it->value).*m)(typename SelfType<T>::Self(it), args...);
}
};
#define IMPL(ResType, Type, method, args...) \
(Impl<Type, ResType, decltype(&Implementation<Type>::method), \
&Implementation<Type>::method>::f(args))
/**
* Strange and magical class that allows to call methods on storage-typed nodes
*/
template<class T, class R, class M, M m>
class ImplNoSelf {
public:
typedef Accessor<T, typename Storage<T>::Type> Type;
template<class... Args>
static R f(Node* it, Args... args) {
return (Type::get(it->value).*m)(args...);
}
};
#define IMPLNOSELF(ResType, Type, method, args...) \
(ImplNoSelf<Type, ResType, decltype(&Implementation<Type>::method), \
&Implementation<Type>::method>::f(args))
///////////////
// Reference //
///////////////
class Reference;
template <>
class Storage<Reference> {
public:
typedef StableNode* Type;
};
template <>
class Implementation<Reference> {
public:
Implementation<Reference>(StableNode* dest) : _dest(dest) {}
static StableNode* build(VM, StableNode* dest) { return dest; }
StableNode* dest() const { return _dest; }
private:
StableNode* _dest;
};
/**
* Type of a reference
*/
class Reference: public Type {
public:
Reference() : Type("Reference", true) {}
typedef Node* Self;
static const Reference* const type() {
static const Reference rawType;
return &rawType;
}
// This is optimized for the 0- and 1-dereference paths
// Normally it would have been only a while loop
static Node& dereference(Node& node) {
if (node.type != type())
return node;
else {
Node* result = &IMPLNOSELF(StableNode*, Reference, dest, &node)->node;
if (result->type != type())
return *result;
else
return dereferenceLoop(result);
}
}
static void makeFor(VM vm, UnstableNode& node) {
StableNode* stable = new (vm) StableNode;
stable->init(vm, node);
}
static void makeFor(VM vm, Node& node) {
UnstableNode temp;
temp.node = node;
makeFor(vm, temp);
node = temp.node;
}
// This is optimized for the 0- and 1-dereference paths
// Normally the else case would have been only a while loop
static StableNode* getStableRefFor(VM vm, Node& node) {
if (node.type != type()) {
makeFor(vm, node);
return IMPLNOSELF(StableNode*, Reference, dest, &node);
} else {
StableNode* result = IMPLNOSELF(StableNode*, Reference, dest, &node);
if (result->node.type != type())
return result;
else
return getStableRefForLoop(result);
}
}
static StableNode* getStableRefFor(VM vm, UnstableNode& node) {
return getStableRefFor(vm, node.node);
}
static StableNode* getStableRefFor(VM vm, StableNode& node) {
if (node.node.type != type())
return &node;
else
return getStableRefFor(vm, node.node);
}
private:
static Node& dereferenceLoop(Node* node) {
while (node->type == type())
node = &(IMPLNOSELF(StableNode*, Reference, dest, node)->node);
return *node;
}
static StableNode* getStableRefForLoop(StableNode* node) {
do {
node = IMPLNOSELF(StableNode*, Reference, dest, &node->node);
} while (node->node.type == type());
return node;
}
};
/////////////////////////
// Node implementation //
/////////////////////////
void Node::reset(VM vm) {
type = nullptr;
value.init<void*>(vm, nullptr);
}
void StableNode::init(VM vm, UnstableNode& from) {
node = from.node;
if (!node.type->isCopiable())
from.make<Reference>(vm, this);
}
void UnstableNode::copy(VM vm, StableNode& from) {
if (from.node.type->isCopiable())
node = from.node;
else
make<Reference>(vm, &from);
}
void UnstableNode::copy(VM vm, UnstableNode& from) {
if (!from.node.type->isCopiable())
Reference::makeFor(vm, from);
node = from.node;
}
void UnstableNode::reset(VM vm) {
node.reset(vm);
}
void UnstableNode::swap(UnstableNode& from) {
Node temp = node;
node = from.node;
from.node = temp;
}
#include "vm.hh"
#endif // __STORE_H
<commit_msg>In Nodes, GC-related fields exported in Stable- and UnstableNode instead of Node.<commit_after>// Copyright © 2011, Université catholique de Louvain
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#ifndef __STORE_H
#define __STORE_H
#include "core-forward-decl.hh"
#include "memword.hh"
#include "storage.hh"
#include "type.hh"
/**
* A value node in the store.
* The store is entirely made of nodes. A node is basically a typed value.
* Non-atomic values, such as records, contain references to other nodes in the
* store, hence forming a graph, and the name "node".
* There are two kinds of node: stable and unstable node. A stable node is
* guaranteed never to change, whereas unstable node can change. In order to
* maintain consistency in the store, non-atomic values are only allowed to
* reference stable nodes. Unstable nodes are used for working data, and
* inherently mutable data (such as the contents of a cell).
*/
class Node {
public:
template<class T, class... Args>
void make(VM vm, Args... args) {
typedef Accessor<T, typename Storage<T>::Type> Access;
Access::init(type, value, vm, args...);
}
inline void reset(VM vm);
const Type* type;
MemWord value;
};
/**
* Stable node, which is guaranteed never to change
*/
class StableNode {
public:
inline void init(VM vm, UnstableNode& from);
private:
friend class UnstableNode;
public: // TODO make it private once the development has been bootstrapped
union {
Node node;
// Garbage collector hack
struct {
StableNode* gcNext;
Node* gcFrom;
};
};
};
/**
* Unstable node, which is allowed to change over time
*/
class UnstableNode {
public:
UnstableNode() {}
UnstableNode(VM vm, StableNode& from) {
copy(vm, from);
}
UnstableNode(VM vm, UnstableNode& from) {
copy(vm, from);
}
inline void copy(VM vm, StableNode& from);
inline void copy(VM vm, UnstableNode& from);
inline void swap(UnstableNode& from);
inline void reset(VM vm);
template<class T, class... Args>
void make(VM vm, Args... args) {
node.make<T>(vm, args...);
}
private:
friend class StableNode;
public: // TODO make it private once the development has been bootstrapped
union {
Node node;
// Garbage collector hack
struct {
UnstableNode* gcNext;
Node* gcFrom;
};
};
};
/**
* Base class for Self types
*/
template <class T>
class BaseSelf {
protected:
typedef typename Storage<T>::Type StorageType;
typedef Accessor<T, StorageType> Access;
public:
BaseSelf(Node* node) : _node(node) {}
template<class U, class... Args>
void make(VM vm, Args... args) {
_node->make<U>(vm, args...);
}
operator Node*() {
return _node;
}
Node& operator*() {
return *_node;
}
protected:
auto getBase() -> decltype(Access::get(MemWord())) {
return Access::get(_node->value);
}
Node* _node;
};
/**
* Self type for custom storage-based types
*/
template <class T>
class CustomStorageSelf: public BaseSelf<T> {
private:
typedef Implementation<T> Impl;
public:
CustomStorageSelf(Node* node) : BaseSelf<T>(node) {}
Impl get() {
return this->getBase();
}
};
/**
* Self type for default storage-based types
*/
template <class T>
class DefaultStorageSelf: public BaseSelf<T> {
private:
typedef Implementation<T> Impl;
public:
DefaultStorageSelf(Node* node) : BaseSelf<T>(node) {}
Impl* operator->() {
return &this->getBase();
}
};
/**
* Extractor function for the template parameters of ImplWithArray
* Given
* typedef ImplWithArray<I, E> T;
* this provides
* ExtractImplWithArray<T>::Impl === I
* ExtractImplWithArray<T>::Elem === E
*/
template <class S>
struct ExtractImplWithArray {};
template <class I, class E>
struct ExtractImplWithArray<ImplWithArray<I, E>> {
typedef I Impl;
typedef E Elem;
};
/**
* Self type for ImplWithArray-based types
*/
template <class T>
class ImplWithArraySelf: public BaseSelf<T> {
private:
typedef typename BaseSelf<T>::StorageType StorageType;
typedef typename ExtractImplWithArray<StorageType>::Impl Impl;
typedef typename ExtractImplWithArray<StorageType>::Elem Elem;
public:
ImplWithArraySelf(Node* node) : BaseSelf<T>(node) {}
Impl* operator->() {
return get().operator->();
}
Elem& operator[](size_t i) {
return get().operator[](i);
}
StaticArray<Elem> getArray(size_t size) {
return get().getArray(size);
}
private:
ImplWithArray<Impl, Elem> get() {
return ImplWithArray<Impl, Elem>(&this->getBase());
}
};
/**
* Helper for the metafunction SelfType
*/
template <class T, class S>
struct SelfTypeInner {
typedef CustomStorageSelf<T> Self;
};
/**
* Helper for the metafunction SelfType
*/
template <class T>
struct SelfTypeInner<T, DefaultStorage<T>> {
typedef DefaultStorageSelf<T> Self;
};
/**
* Helper for the metafunction SelfType
*/
template <class T, class I, class E>
struct SelfTypeInner<T, ImplWithArray<I, E>> {
typedef ImplWithArraySelf<T> Self;
};
/**
* Metafunction from type to its Self type
* Use as SelfType<T>::Self
*/
template <class T>
struct SelfType {
typedef typename SelfTypeInner<T, typename Storage<T>::Type>::Self Self;
};
/**
* Result of the call to a builtin.
* It always represents a node that must be waited upon. The value 'nullptr' is
* valid, and denotes that no value must be waited upon, i.e., the execution can
* continue.
* Throwing an exception is achieved by pointing to a failed value.
*/
typedef Node* BuiltinResult;
const BuiltinResult BuiltinResultContinue = nullptr;
/**
* Strange and magical class that allows to call methods on storage-typed nodes
*/
template<class T, class R, class M, M m>
class Impl {
public:
typedef Accessor<T, typename Storage<T>::Type> Type;
template<class... Args>
static R f(Node* it, Args... args) {
return (Type::get(it->value).*m)(typename SelfType<T>::Self(it), args...);
}
};
#define IMPL(ResType, Type, method, args...) \
(Impl<Type, ResType, decltype(&Implementation<Type>::method), \
&Implementation<Type>::method>::f(args))
/**
* Strange and magical class that allows to call methods on storage-typed nodes
*/
template<class T, class R, class M, M m>
class ImplNoSelf {
public:
typedef Accessor<T, typename Storage<T>::Type> Type;
template<class... Args>
static R f(Node* it, Args... args) {
return (Type::get(it->value).*m)(args...);
}
};
#define IMPLNOSELF(ResType, Type, method, args...) \
(ImplNoSelf<Type, ResType, decltype(&Implementation<Type>::method), \
&Implementation<Type>::method>::f(args))
///////////////
// Reference //
///////////////
class Reference;
template <>
class Storage<Reference> {
public:
typedef StableNode* Type;
};
template <>
class Implementation<Reference> {
public:
Implementation<Reference>(StableNode* dest) : _dest(dest) {}
static StableNode* build(VM, StableNode* dest) { return dest; }
StableNode* dest() const { return _dest; }
private:
StableNode* _dest;
};
/**
* Type of a reference
*/
class Reference: public Type {
public:
Reference() : Type("Reference", true) {}
typedef Node* Self;
static const Reference* const type() {
static const Reference rawType;
return &rawType;
}
// This is optimized for the 0- and 1-dereference paths
// Normally it would have been only a while loop
static Node& dereference(Node& node) {
if (node.type != type())
return node;
else {
Node* result = &IMPLNOSELF(StableNode*, Reference, dest, &node)->node;
if (result->type != type())
return *result;
else
return dereferenceLoop(result);
}
}
static void makeFor(VM vm, UnstableNode& node) {
StableNode* stable = new (vm) StableNode;
stable->init(vm, node);
}
static void makeFor(VM vm, Node& node) {
UnstableNode temp;
temp.node = node;
makeFor(vm, temp);
node = temp.node;
}
// This is optimized for the 0- and 1-dereference paths
// Normally the else case would have been only a while loop
static StableNode* getStableRefFor(VM vm, Node& node) {
if (node.type != type()) {
makeFor(vm, node);
return IMPLNOSELF(StableNode*, Reference, dest, &node);
} else {
StableNode* result = IMPLNOSELF(StableNode*, Reference, dest, &node);
if (result->node.type != type())
return result;
else
return getStableRefForLoop(result);
}
}
static StableNode* getStableRefFor(VM vm, UnstableNode& node) {
return getStableRefFor(vm, node.node);
}
static StableNode* getStableRefFor(VM vm, StableNode& node) {
if (node.node.type != type())
return &node;
else
return getStableRefFor(vm, node.node);
}
private:
static Node& dereferenceLoop(Node* node) {
while (node->type == type())
node = &(IMPLNOSELF(StableNode*, Reference, dest, node)->node);
return *node;
}
static StableNode* getStableRefForLoop(StableNode* node) {
do {
node = IMPLNOSELF(StableNode*, Reference, dest, &node->node);
} while (node->node.type == type());
return node;
}
};
/////////////////////////
// Node implementation //
/////////////////////////
void Node::reset(VM vm) {
type = nullptr;
value.init<void*>(vm, nullptr);
}
void StableNode::init(VM vm, UnstableNode& from) {
node = from.node;
if (!node.type->isCopiable())
from.make<Reference>(vm, this);
}
void UnstableNode::copy(VM vm, StableNode& from) {
if (from.node.type->isCopiable())
node = from.node;
else
make<Reference>(vm, &from);
}
void UnstableNode::copy(VM vm, UnstableNode& from) {
if (!from.node.type->isCopiable())
Reference::makeFor(vm, from);
node = from.node;
}
void UnstableNode::reset(VM vm) {
node.reset(vm);
}
void UnstableNode::swap(UnstableNode& from) {
Node temp = node;
node = from.node;
from.node = temp;
}
#include "vm.hh"
#endif // __STORE_H
<|endoftext|> |
<commit_before>#include "voxel_buffer.h"
#include <string.h>
//#define VOXEL_AT(_data, x, y, z) data[z][x][y]
#define VOXEL_AT(_data, _x, _y, _z) _data[index(_x,_y,_z)]
VoxelBuffer::VoxelBuffer() {
}
VoxelBuffer::~VoxelBuffer() {
clear();
}
void VoxelBuffer::create(int sx, int sy, int sz) {
if (sx <= 0 || sy <= 0 || sz <= 0) {
return;
}
Vector3i new_size(sx, sy, sz);
if (new_size != _size) {
for (unsigned int i = 0; i < MAX_CHANNELS; ++i) {
Channel & channel = _channels[i];
if (channel.data) {
// TODO Optimize with realloc
delete_channel(i, _size);
create_channel(i, new_size);
}
}
_size = new_size;
}
}
void VoxelBuffer::clear() {
for (unsigned int i = 0; i < MAX_CHANNELS; ++i) {
Channel & channel = _channels[i];
if (channel.data) {
delete_channel(i, _size);
}
}
}
void VoxelBuffer::clear_channel(unsigned int channel_index, int clear_value) {
ERR_FAIL_INDEX(channel_index, MAX_CHANNELS);
delete_channel(channel_index, _size);
_channels[channel_index].defval = clear_value;
}
int VoxelBuffer::get_voxel(int x, int y, int z, unsigned int channel_index) const {
ERR_FAIL_INDEX_V(channel_index, MAX_CHANNELS, 0);
const Channel & channel = _channels[channel_index];
if (validate_pos(x, y, z) && channel.data) {
return VOXEL_AT(channel.data, x,y,z);
}
else {
return channel.defval;
}
}
void VoxelBuffer::set_voxel(int value, int x, int y, int z, unsigned int channel_index) {
ERR_FAIL_INDEX(channel_index, MAX_CHANNELS);
ERR_FAIL_COND(!validate_pos(x, y, z));
Channel & channel = _channels[channel_index];
if (channel.defval != value) {
if (channel.data == NULL) {
create_channel(channel_index, _size);
}
VOXEL_AT(channel.data, x, y, z) = value;
}
}
void VoxelBuffer::set_voxel_v(int value, Vector3 pos, unsigned int channel_index) {
set_voxel(value, pos.x, pos.y, pos.z, channel_index);
}
void VoxelBuffer::fill(int defval, unsigned int channel_index) {
ERR_FAIL_INDEX(channel_index, MAX_CHANNELS);
Channel & channel = _channels[channel_index];
if (channel.data == NULL && channel.defval == defval)
return;
else
create_channel_noinit(channel_index, _size);
unsigned int volume = get_volume();
memset(channel.data, defval, volume);
}
void VoxelBuffer::fill_area(int defval, Vector3i min, Vector3i max, unsigned int channel_index) {
ERR_FAIL_INDEX(channel_index, MAX_CHANNELS);
Vector3i::sort_min_max(min, max);
min.clamp_to(Vector3i(0, 0, 0), _size);
max.clamp_to(Vector3i(0, 0, 0), _size + Vector3i(1,1,1));
Vector3i area_size = max - min;
Channel & channel = _channels[channel_index];
if (channel.data == NULL) {
if (channel.defval == defval)
return;
else
create_channel(channel_index, _size);
}
Vector3i pos;
for (pos.z = min.z; pos.z < max.z; ++pos.z) {
for (pos.x = min.x; pos.x < max.x; ++pos.x) {
unsigned int dst_ri = index(pos.x, pos.y + min.y, pos.z);
memset(&channel.data[dst_ri], defval, area_size.y * sizeof(uint8_t));
}
}
}
bool VoxelBuffer::is_uniform(unsigned int channel_index) {
ERR_FAIL_INDEX_V(channel_index, MAX_CHANNELS, true);
Channel & channel = _channels[channel_index];
if (channel.data == NULL)
return true;
uint8_t voxel = channel.data[0];
unsigned int volume = get_volume();
for (unsigned int i = 0; i < volume; ++i) {
if (channel.data[i] != voxel) {
return false;
}
}
return true;
}
void VoxelBuffer::optimize() {
for (unsigned int i = 0; i < MAX_CHANNELS; ++i) {
if (_channels[i].data && is_uniform(i)) {
clear_channel(i, _channels[i].data[0]);
}
}
}
void VoxelBuffer::copy_from(const VoxelBuffer & other, unsigned int channel_index) {
ERR_FAIL_INDEX(channel_index, MAX_CHANNELS);
ERR_FAIL_COND(other._size == _size);
Channel & channel = _channels[channel_index];
const Channel & other_channel = other._channels[channel_index];
if (other_channel.data) {
if (channel.data == NULL) {
create_channel_noinit(channel_index, _size);
}
memcpy(channel.data, other_channel.data, get_volume() * sizeof(uint8_t));
}
else if(channel.data) {
delete_channel(channel_index, _size);
}
channel.defval = other_channel.defval;
}
void VoxelBuffer::copy_from(const VoxelBuffer & other, Vector3i src_min, Vector3i src_max, Vector3i dst_min, unsigned int channel_index) {
ERR_FAIL_INDEX(channel_index, MAX_CHANNELS);
Channel & channel = _channels[channel_index];
const Channel & other_channel = other._channels[channel_index];
Vector3i::sort_min_max(src_min, src_max);
src_min.clamp_to(Vector3i(0, 0, 0), other._size);
src_max.clamp_to(Vector3i(0, 0, 0), other._size + Vector3i(1,1,1));
dst_min.clamp_to(Vector3i(0, 0, 0), _size);
Vector3i area_size = src_max - src_min;
//Vector3i dst_max = dst_min + area_size;
if (area_size == _size) {
copy_from(other, channel_index);
}
else {
if (other_channel.data) {
if (channel.data == NULL) {
create_channel(channel_index, _size);
}
// Copy row by row
Vector3i pos;
for (pos.z = 0; pos.z < area_size.z; ++pos.z) {
for (pos.x = 0; pos.x < area_size.x; ++pos.x) {
// Row direction is Y
unsigned int src_ri = other.index(pos.x + src_min.x, pos.y + src_min.y, pos.z + src_min.z);
unsigned int dst_ri = index(pos.x + dst_min.x, pos.y + dst_min.y, pos.z + dst_min.z);
memcpy(&channel.data[dst_ri], &other_channel.data[src_ri], area_size.y * sizeof(uint8_t));
}
}
}
else if (channel.defval != other_channel.defval) {
if (channel.data == NULL) {
create_channel(channel_index, _size);
}
// Set row by row
Vector3i pos;
for (pos.z = 0; pos.z < area_size.z; ++pos.z) {
for (pos.x = 0; pos.x < area_size.x; ++pos.x) {
unsigned int dst_ri = index(pos.x + dst_min.x, pos.y + dst_min.y, pos.z + dst_min.z);
memset(&channel.data[dst_ri], other_channel.defval, area_size.y * sizeof(uint8_t));
}
}
}
}
}
void VoxelBuffer::create_channel(int i, Vector3i size, uint8_t defval) {
create_channel_noinit(i, size);
memset(_channels[i].data, defval, get_volume() * sizeof(uint8_t));
}
void VoxelBuffer::create_channel_noinit(int i, Vector3i size) {
Channel & channel = _channels[i];
unsigned int volume = size.x * size.y * size.z;
channel.data = (uint8_t*)memalloc(volume * sizeof(uint8_t));
}
void VoxelBuffer::delete_channel(int i, Vector3i size) {
Channel & channel = _channels[i];
memfree(channel.data);
channel.data = NULL;
}
void VoxelBuffer::_bind_methods() {
ObjectTypeDB::bind_method(_MD("create", "sx", "sy", "sz"), &VoxelBuffer::create);
ObjectTypeDB::bind_method(_MD("clear"), &VoxelBuffer::clear);
ObjectTypeDB::bind_method(_MD("get_size_x"), &VoxelBuffer::get_size_x);
ObjectTypeDB::bind_method(_MD("get_size_y"), &VoxelBuffer::get_size_y);
ObjectTypeDB::bind_method(_MD("get_size_z"), &VoxelBuffer::get_size_z);
ObjectTypeDB::bind_method(_MD("set_voxel", "value", "x", "y", "z", "channel"), &VoxelBuffer::_set_voxel_binding, DEFVAL(0));
ObjectTypeDB::bind_method(_MD("set_voxel_v", "value", "pos", "channel"), &VoxelBuffer::set_voxel_v, DEFVAL(0));
ObjectTypeDB::bind_method(_MD("get_voxel", "x", "y", "z", "channel"), &VoxelBuffer::_get_voxel_binding, DEFVAL(0));
ObjectTypeDB::bind_method(_MD("fill", "value", "channel"), &VoxelBuffer::fill, DEFVAL(0));
ObjectTypeDB::bind_method(_MD("fill_area", "value", "min", "max", "channel"), &VoxelBuffer::_fill_area_binding, DEFVAL(0));
ObjectTypeDB::bind_method(_MD("copy_from", "other:VoxelBuffer", "channel"), &VoxelBuffer::_copy_from_binding, DEFVAL(0));
ObjectTypeDB::bind_method(_MD("copy_from_area", "other:VoxelBuffer", "src_min", "src_max", "dst_min", "channel"), &VoxelBuffer::_copy_from_area_binding, DEFVAL(0));
ObjectTypeDB::bind_method(_MD("is_uniform", "channel"), &VoxelBuffer::is_uniform, DEFVAL(0));
ObjectTypeDB::bind_method(_MD("optimize"), &VoxelBuffer::optimize);
}
void VoxelBuffer::_copy_from_binding(Ref<VoxelBuffer> other, unsigned int channel) {
ERR_FAIL_COND(other.is_null());
copy_from(**other, channel);
}
void VoxelBuffer::_copy_from_area_binding(Ref<VoxelBuffer> other, Vector3 src_min, Vector3 src_max, Vector3 dst_min, unsigned int channel) {
ERR_FAIL_COND(other.is_null());
copy_from(**other, Vector3i(src_min), Vector3i(src_max), Vector3i(dst_min), channel);
}
<commit_msg>Fixed change voxel type in VoxelBuffer<commit_after>#include "voxel_buffer.h"
#include <string.h>
//#define VOXEL_AT(_data, x, y, z) data[z][x][y]
#define VOXEL_AT(_data, _x, _y, _z) _data[index(_x,_y,_z)]
VoxelBuffer::VoxelBuffer() {
}
VoxelBuffer::~VoxelBuffer() {
clear();
}
void VoxelBuffer::create(int sx, int sy, int sz) {
if (sx <= 0 || sy <= 0 || sz <= 0) {
return;
}
Vector3i new_size(sx, sy, sz);
if (new_size != _size) {
for (unsigned int i = 0; i < MAX_CHANNELS; ++i) {
Channel & channel = _channels[i];
if (channel.data) {
// TODO Optimize with realloc
delete_channel(i, _size);
create_channel(i, new_size);
}
}
_size = new_size;
}
}
void VoxelBuffer::clear() {
for (unsigned int i = 0; i < MAX_CHANNELS; ++i) {
Channel & channel = _channels[i];
if (channel.data) {
delete_channel(i, _size);
}
}
}
void VoxelBuffer::clear_channel(unsigned int channel_index, int clear_value) {
ERR_FAIL_INDEX(channel_index, MAX_CHANNELS);
delete_channel(channel_index, _size);
_channels[channel_index].defval = clear_value;
}
int VoxelBuffer::get_voxel(int x, int y, int z, unsigned int channel_index) const {
ERR_FAIL_INDEX_V(channel_index, MAX_CHANNELS, 0);
const Channel & channel = _channels[channel_index];
if (validate_pos(x, y, z) && channel.data) {
return VOXEL_AT(channel.data, x,y,z);
}
else {
return channel.defval;
}
}
void VoxelBuffer::set_voxel(int value, int x, int y, int z, unsigned int channel_index) {
ERR_FAIL_INDEX(channel_index, MAX_CHANNELS);
ERR_FAIL_COND(!validate_pos(x, y, z));
Channel & channel = _channels[channel_index];
//FIX: if VOXEL_AT(channel.data, x, y, z) is not channel.defval we have to set that voxel nethertheless
//if (channel.defval != value) {
if (channel.data == NULL) {
create_channel(channel_index, _size);
}
VOXEL_AT(channel.data, x, y, z) = value;
//}
}
void VoxelBuffer::set_voxel_v(int value, Vector3 pos, unsigned int channel_index) {
set_voxel(value, pos.x, pos.y, pos.z, channel_index);
}
void VoxelBuffer::fill(int defval, unsigned int channel_index) {
ERR_FAIL_INDEX(channel_index, MAX_CHANNELS);
Channel & channel = _channels[channel_index];
if (channel.data == NULL && channel.defval == defval)
return;
else
create_channel_noinit(channel_index, _size);
unsigned int volume = get_volume();
memset(channel.data, defval, volume);
}
void VoxelBuffer::fill_area(int defval, Vector3i min, Vector3i max, unsigned int channel_index) {
ERR_FAIL_INDEX(channel_index, MAX_CHANNELS);
Vector3i::sort_min_max(min, max);
min.clamp_to(Vector3i(0, 0, 0), _size);
max.clamp_to(Vector3i(0, 0, 0), _size + Vector3i(1,1,1));
Vector3i area_size = max - min;
Channel & channel = _channels[channel_index];
if (channel.data == NULL) {
if (channel.defval == defval)
return;
else
create_channel(channel_index, _size);
}
Vector3i pos;
for (pos.z = min.z; pos.z < max.z; ++pos.z) {
for (pos.x = min.x; pos.x < max.x; ++pos.x) {
unsigned int dst_ri = index(pos.x, pos.y + min.y, pos.z);
memset(&channel.data[dst_ri], defval, area_size.y * sizeof(uint8_t));
}
}
}
bool VoxelBuffer::is_uniform(unsigned int channel_index) {
ERR_FAIL_INDEX_V(channel_index, MAX_CHANNELS, true);
Channel & channel = _channels[channel_index];
if (channel.data == NULL)
return true;
uint8_t voxel = channel.data[0];
unsigned int volume = get_volume();
for (unsigned int i = 0; i < volume; ++i) {
if (channel.data[i] != voxel) {
return false;
}
}
return true;
}
void VoxelBuffer::optimize() {
for (unsigned int i = 0; i < MAX_CHANNELS; ++i) {
if (_channels[i].data && is_uniform(i)) {
clear_channel(i, _channels[i].data[0]);
}
}
}
void VoxelBuffer::copy_from(const VoxelBuffer & other, unsigned int channel_index) {
ERR_FAIL_INDEX(channel_index, MAX_CHANNELS);
ERR_FAIL_COND(other._size == _size);
Channel & channel = _channels[channel_index];
const Channel & other_channel = other._channels[channel_index];
if (other_channel.data) {
if (channel.data == NULL) {
create_channel_noinit(channel_index, _size);
}
memcpy(channel.data, other_channel.data, get_volume() * sizeof(uint8_t));
}
else if(channel.data) {
delete_channel(channel_index, _size);
}
channel.defval = other_channel.defval;
}
void VoxelBuffer::copy_from(const VoxelBuffer & other, Vector3i src_min, Vector3i src_max, Vector3i dst_min, unsigned int channel_index) {
ERR_FAIL_INDEX(channel_index, MAX_CHANNELS);
Channel & channel = _channels[channel_index];
const Channel & other_channel = other._channels[channel_index];
Vector3i::sort_min_max(src_min, src_max);
src_min.clamp_to(Vector3i(0, 0, 0), other._size);
src_max.clamp_to(Vector3i(0, 0, 0), other._size + Vector3i(1,1,1));
dst_min.clamp_to(Vector3i(0, 0, 0), _size);
Vector3i area_size = src_max - src_min;
//Vector3i dst_max = dst_min + area_size;
if (area_size == _size) {
copy_from(other, channel_index);
}
else {
if (other_channel.data) {
if (channel.data == NULL) {
create_channel(channel_index, _size);
}
// Copy row by row
Vector3i pos;
for (pos.z = 0; pos.z < area_size.z; ++pos.z) {
for (pos.x = 0; pos.x < area_size.x; ++pos.x) {
// Row direction is Y
unsigned int src_ri = other.index(pos.x + src_min.x, pos.y + src_min.y, pos.z + src_min.z);
unsigned int dst_ri = index(pos.x + dst_min.x, pos.y + dst_min.y, pos.z + dst_min.z);
memcpy(&channel.data[dst_ri], &other_channel.data[src_ri], area_size.y * sizeof(uint8_t));
}
}
}
else if (channel.defval != other_channel.defval) {
if (channel.data == NULL) {
create_channel(channel_index, _size);
}
// Set row by row
Vector3i pos;
for (pos.z = 0; pos.z < area_size.z; ++pos.z) {
for (pos.x = 0; pos.x < area_size.x; ++pos.x) {
unsigned int dst_ri = index(pos.x + dst_min.x, pos.y + dst_min.y, pos.z + dst_min.z);
memset(&channel.data[dst_ri], other_channel.defval, area_size.y * sizeof(uint8_t));
}
}
}
}
}
void VoxelBuffer::create_channel(int i, Vector3i size, uint8_t defval) {
create_channel_noinit(i, size);
memset(_channels[i].data, defval, get_volume() * sizeof(uint8_t));
}
void VoxelBuffer::create_channel_noinit(int i, Vector3i size) {
Channel & channel = _channels[i];
unsigned int volume = size.x * size.y * size.z;
channel.data = (uint8_t*)memalloc(volume * sizeof(uint8_t));
}
void VoxelBuffer::delete_channel(int i, Vector3i size) {
Channel & channel = _channels[i];
memfree(channel.data);
channel.data = NULL;
}
void VoxelBuffer::_bind_methods() {
ObjectTypeDB::bind_method(_MD("create", "sx", "sy", "sz"), &VoxelBuffer::create);
ObjectTypeDB::bind_method(_MD("clear"), &VoxelBuffer::clear);
ObjectTypeDB::bind_method(_MD("get_size_x"), &VoxelBuffer::get_size_x);
ObjectTypeDB::bind_method(_MD("get_size_y"), &VoxelBuffer::get_size_y);
ObjectTypeDB::bind_method(_MD("get_size_z"), &VoxelBuffer::get_size_z);
ObjectTypeDB::bind_method(_MD("set_voxel", "value", "x", "y", "z", "channel"), &VoxelBuffer::_set_voxel_binding, DEFVAL(0));
ObjectTypeDB::bind_method(_MD("set_voxel_v", "value", "pos", "channel"), &VoxelBuffer::set_voxel_v, DEFVAL(0));
ObjectTypeDB::bind_method(_MD("get_voxel", "x", "y", "z", "channel"), &VoxelBuffer::_get_voxel_binding, DEFVAL(0));
ObjectTypeDB::bind_method(_MD("fill", "value", "channel"), &VoxelBuffer::fill, DEFVAL(0));
ObjectTypeDB::bind_method(_MD("fill_area", "value", "min", "max", "channel"), &VoxelBuffer::_fill_area_binding, DEFVAL(0));
ObjectTypeDB::bind_method(_MD("copy_from", "other:VoxelBuffer", "channel"), &VoxelBuffer::_copy_from_binding, DEFVAL(0));
ObjectTypeDB::bind_method(_MD("copy_from_area", "other:VoxelBuffer", "src_min", "src_max", "dst_min", "channel"), &VoxelBuffer::_copy_from_area_binding, DEFVAL(0));
ObjectTypeDB::bind_method(_MD("is_uniform", "channel"), &VoxelBuffer::is_uniform, DEFVAL(0));
ObjectTypeDB::bind_method(_MD("optimize"), &VoxelBuffer::optimize);
}
void VoxelBuffer::_copy_from_binding(Ref<VoxelBuffer> other, unsigned int channel) {
ERR_FAIL_COND(other.is_null());
copy_from(**other, channel);
}
void VoxelBuffer::_copy_from_area_binding(Ref<VoxelBuffer> other, Vector3 src_min, Vector3 src_max, Vector3 dst_min, unsigned int channel) {
ERR_FAIL_COND(other.is_null());
copy_from(**other, Vector3i(src_min), Vector3i(src_max), Vector3i(dst_min), channel);
}
<|endoftext|> |
<commit_before>#include "audio_filter_resample.h"
#include "halley/support/debug.h"
using namespace Halley;
AudioFilterResample::AudioFilterResample(std::shared_ptr<AudioSource> source, int fromHz, int toHz, AudioBufferPool& pool)
: pool(pool)
, source(std::move(source))
, fromHz(fromHz)
, toHz(toHz)
{
}
uint8_t AudioFilterResample::getNumberOfChannels() const
{
return source->getNumberOfChannels();
}
bool AudioFilterResample::isReady() const
{
return source->isReady();
}
bool AudioFilterResample::getAudioData(size_t numSamples, AudioMultiChannelSamples dstBuffers)
{
const size_t nChannels = source->getNumberOfChannels();
const size_t additionalPaddingSamples = 2;
const size_t nLeftOver = leftoverSamples[0].n;
const size_t samplesToGenerate = numSamples - nLeftOver;
const size_t numSamplesSrc = samplesToGenerate * fromHz / toHz + additionalPaddingSamples;
if (resamplers.empty()) {
for (size_t i = 0; i < nChannels; ++i) {
resamplers.push_back(std::make_unique<AudioResampler>(fromHz, toHz, 1, Debug::isDebug() ? 0.0f : 0.3f));
}
}
// Read upstream data
auto srcBuffers = pool.getBuffers(nChannels, numSamplesSrc);
auto srcs = srcBuffers.getSampleSpans();
bool playing = source->getAudioData(numSamplesSrc, srcs);
// Prepare temporary destination data
auto tmpBuffer = pool.getBuffer(numSamples + 32); // Is this +32 needed?
auto tmp = tmpBuffer.getSpan();
// Resample
for (size_t channel = 0; channel < nChannels; ++channel) {
// First copy any leftovers
Expects(leftoverSamples[channel].n == nLeftOver);
for (size_t i = 0; i < nLeftOver; ++i) {
tmp[i] = leftoverSamples[channel].samples[i];
}
auto result = resamplers[channel]->resample(srcs[channel].subspan(0, numSamplesSrc), tmp.subspan(nLeftOver), 0);
Expects(result.nRead == numSamplesSrc);
Expects(result.nWritten >= samplesToGenerate);
// Store left overs
size_t leftOver = result.nWritten + nLeftOver - numSamples;
for (size_t i = 0; i < leftOver; ++i) {
leftoverSamples[channel].samples[i] = tmp[i + numSamples];
}
leftoverSamples[channel].n = leftOver;
// Copy to destination
memcpy(dstBuffers[channel].data(), tmp.data(), numSamples * sizeof(AudioSample));
}
return playing;
}
size_t AudioFilterResample::getSamplesLeft() const
{
return source->getSamplesLeft() * toHz / fromHz;
}
void AudioFilterResample::setFromHz(int fromHz)
{
for (auto& r: resamplers) {
r->setFromHz(fromHz);
}
}
<commit_msg>Lower audio resample quality<commit_after>#include "audio_filter_resample.h"
#include "halley/support/debug.h"
using namespace Halley;
AudioFilterResample::AudioFilterResample(std::shared_ptr<AudioSource> source, int fromHz, int toHz, AudioBufferPool& pool)
: pool(pool)
, source(std::move(source))
, fromHz(fromHz)
, toHz(toHz)
{
}
uint8_t AudioFilterResample::getNumberOfChannels() const
{
return source->getNumberOfChannels();
}
bool AudioFilterResample::isReady() const
{
return source->isReady();
}
bool AudioFilterResample::getAudioData(size_t numSamples, AudioMultiChannelSamples dstBuffers)
{
const size_t nChannels = source->getNumberOfChannels();
const size_t additionalPaddingSamples = 2;
const size_t nLeftOver = leftoverSamples[0].n;
const size_t samplesToGenerate = numSamples - nLeftOver;
const size_t numSamplesSrc = samplesToGenerate * fromHz / toHz + additionalPaddingSamples;
if (resamplers.empty()) {
for (size_t i = 0; i < nChannels; ++i) {
resamplers.push_back(std::make_unique<AudioResampler>(fromHz, toHz, 1, 0.0f));
}
}
// Read upstream data
auto srcBuffers = pool.getBuffers(nChannels, numSamplesSrc);
auto srcs = srcBuffers.getSampleSpans();
bool playing = source->getAudioData(numSamplesSrc, srcs);
// Prepare temporary destination data
auto tmpBuffer = pool.getBuffer(numSamples + 32); // Is this +32 needed?
auto tmp = tmpBuffer.getSpan();
// Resample
for (size_t channel = 0; channel < nChannels; ++channel) {
// First copy any leftovers
Expects(leftoverSamples[channel].n == nLeftOver);
for (size_t i = 0; i < nLeftOver; ++i) {
tmp[i] = leftoverSamples[channel].samples[i];
}
auto result = resamplers[channel]->resample(srcs[channel].subspan(0, numSamplesSrc), tmp.subspan(nLeftOver), 0);
Expects(result.nRead == numSamplesSrc);
Expects(result.nWritten >= samplesToGenerate);
// Store left overs
size_t leftOver = result.nWritten + nLeftOver - numSamples;
for (size_t i = 0; i < leftOver; ++i) {
leftoverSamples[channel].samples[i] = tmp[i + numSamples];
}
leftoverSamples[channel].n = leftOver;
// Copy to destination
memcpy(dstBuffers[channel].data(), tmp.data(), numSamples * sizeof(AudioSample));
}
return playing;
}
size_t AudioFilterResample::getSamplesLeft() const
{
return source->getSamplesLeft() * toHz / fromHz;
}
void AudioFilterResample::setFromHz(int fromHz)
{
for (auto& r: resamplers) {
r->setFromHz(fromHz);
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2014 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 "gl/GrGLAssembleInterface.h"
#include "gl/GrGLUtil.h"
#include <EGL/egl.h>
#ifndef GL_GLEXT_PROTOTYPES
#define GL_GLEXT_PROTOTYPES
#endif
#include <GLES2/gl2.h>
static GrGLFuncPtr egl_get_gl_proc(void* ctx, const char name[]) {
SkASSERT(nullptr == ctx);
// https://www.khronos.org/registry/EGL/extensions/KHR/EGL_KHR_get_all_proc_addresses.txt
// eglGetProcAddress() is not guaranteed to support the querying of non-extension EGL functions.
#define M(X) if (0 == strcmp(#X, name)) { return (GrGLFuncPtr) X; }
M(eglGetCurrentDisplay);
M(eglQueryString);
M(glActiveTexture);
M(glAttachShader);
M(glBindAttribLocation);
M(glBindBuffer);
M(glBindFramebuffer);
M(glBindRenderbuffer);
M(glBindTexture);
M(glBlendColor);
M(glBlendEquation);
M(glBlendFunc);
M(glBufferData);
M(glBufferSubData);
M(glCheckFramebufferStatus);
M(glClear);
M(glClearColor);
M(glClearStencil);
M(glColorMask);
M(glCompileShader);
M(glCompressedTexImage2D);
M(glCompressedTexSubImage2D);
M(glCopyTexSubImage2D);
M(glCreateProgram);
M(glCreateShader);
M(glCullFace);
M(glDeleteBuffers);
M(glDeleteFramebuffers);
M(glDeleteProgram);
M(glDeleteRenderbuffers);
M(glDeleteShader);
M(glDeleteTextures);
M(glDepthMask);
M(glDisable);
M(glDisableVertexAttribArray);
M(glDrawArrays);
M(glDrawElements);
M(glEnable);
M(glEnableVertexAttribArray);
M(glFinish);
M(glFlush);
M(glFramebufferRenderbuffer);
M(glFramebufferTexture2D);
M(glFrontFace);
M(glGenBuffers);
M(glGenFramebuffers);
M(glGenRenderbuffers);
M(glGenTextures);
M(glGenerateMipmap);
M(glGetBufferParameteriv);
M(glGetError);
M(glGetFramebufferAttachmentParameteriv);
M(glGetIntegerv);
M(glGetProgramInfoLog);
M(glGetProgramiv);
M(glGetRenderbufferParameteriv);
M(glGetShaderInfoLog);
M(glGetShaderPrecisionFormat);
M(glGetShaderiv);
M(glGetString);
M(glGetUniformLocation);
M(glIsTexture);
M(glLineWidth);
M(glLinkProgram);
M(glPixelStorei);
M(glReadPixels);
M(glRenderbufferStorage);
M(glScissor);
M(glShaderSource);
M(glStencilFunc);
M(glStencilFuncSeparate);
M(glStencilMask);
M(glStencilMaskSeparate);
M(glStencilOp);
M(glStencilOpSeparate);
M(glTexImage2D);
M(glTexParameterf);
M(glTexParameterfv);
M(glTexParameteri);
M(glTexParameteriv);
M(glTexSubImage2D);
M(glUniform1f);
M(glUniform1fv);
M(glUniform1i);
M(glUniform1iv);
M(glUniform2f);
M(glUniform2fv);
M(glUniform2i);
M(glUniform2iv);
M(glUniform3f);
M(glUniform3fv);
M(glUniform3i);
M(glUniform3iv);
M(glUniform4f);
M(glUniform4fv);
M(glUniform4i);
M(glUniform4iv);
M(glUniformMatrix2fv);
M(glUniformMatrix3fv);
M(glUniformMatrix4fv);
M(glUseProgram);
M(glVertexAttrib1f);
M(glVertexAttrib2fv);
M(glVertexAttrib3fv);
M(glVertexAttrib4fv);
M(glVertexAttribPointer);
M(glViewport);
#undef M
return eglGetProcAddress(name);
}
sk_sp<const GrGLInterface> GrGLMakeNativeInterface() {
return GrGLMakeAssembledInterface(nullptr, egl_get_gl_proc);
}
const GrGLInterface* GrGLCreateNativeInterface() { return GrGLMakeNativeInterface().release(); }
<commit_msg>Remove extra semi-colons<commit_after>/*
* Copyright 2014 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 "gl/GrGLAssembleInterface.h"
#include "gl/GrGLUtil.h"
#include <EGL/egl.h>
#ifndef GL_GLEXT_PROTOTYPES
#define GL_GLEXT_PROTOTYPES
#endif
#include <GLES2/gl2.h>
static GrGLFuncPtr egl_get_gl_proc(void* ctx, const char name[]) {
SkASSERT(nullptr == ctx);
// https://www.khronos.org/registry/EGL/extensions/KHR/EGL_KHR_get_all_proc_addresses.txt
// eglGetProcAddress() is not guaranteed to support the querying of non-extension EGL functions.
#define M(X) if (0 == strcmp(#X, name)) { return (GrGLFuncPtr) X; }
M(eglGetCurrentDisplay)
M(eglQueryString)
M(glActiveTexture)
M(glAttachShader)
M(glBindAttribLocation)
M(glBindBuffer)
M(glBindFramebuffer)
M(glBindRenderbuffer)
M(glBindTexture)
M(glBlendColor)
M(glBlendEquation)
M(glBlendFunc)
M(glBufferData)
M(glBufferSubData)
M(glCheckFramebufferStatus)
M(glClear)
M(glClearColor)
M(glClearStencil)
M(glColorMask)
M(glCompileShader)
M(glCompressedTexImage2D)
M(glCompressedTexSubImage2D)
M(glCopyTexSubImage2D)
M(glCreateProgram)
M(glCreateShader)
M(glCullFace)
M(glDeleteBuffers)
M(glDeleteFramebuffers)
M(glDeleteProgram)
M(glDeleteRenderbuffers)
M(glDeleteShader)
M(glDeleteTextures)
M(glDepthMask)
M(glDisable)
M(glDisableVertexAttribArray)
M(glDrawArrays)
M(glDrawElements)
M(glEnable)
M(glEnableVertexAttribArray)
M(glFinish)
M(glFlush)
M(glFramebufferRenderbuffer)
M(glFramebufferTexture2D)
M(glFrontFace)
M(glGenBuffers)
M(glGenFramebuffers)
M(glGenRenderbuffers)
M(glGenTextures)
M(glGenerateMipmap)
M(glGetBufferParameteriv)
M(glGetError)
M(glGetFramebufferAttachmentParameteriv)
M(glGetIntegerv)
M(glGetProgramInfoLog)
M(glGetProgramiv)
M(glGetRenderbufferParameteriv)
M(glGetShaderInfoLog)
M(glGetShaderPrecisionFormat)
M(glGetShaderiv)
M(glGetString)
M(glGetUniformLocation)
M(glIsTexture)
M(glLineWidth)
M(glLinkProgram)
M(glPixelStorei)
M(glReadPixels)
M(glRenderbufferStorage)
M(glScissor)
M(glShaderSource)
M(glStencilFunc)
M(glStencilFuncSeparate)
M(glStencilMask)
M(glStencilMaskSeparate)
M(glStencilOp)
M(glStencilOpSeparate)
M(glTexImage2D)
M(glTexParameterf)
M(glTexParameterfv)
M(glTexParameteri)
M(glTexParameteriv)
M(glTexSubImage2D)
M(glUniform1f)
M(glUniform1fv)
M(glUniform1i)
M(glUniform1iv)
M(glUniform2f)
M(glUniform2fv)
M(glUniform2i)
M(glUniform2iv)
M(glUniform3f)
M(glUniform3fv)
M(glUniform3i)
M(glUniform3iv)
M(glUniform4f)
M(glUniform4fv)
M(glUniform4i)
M(glUniform4iv)
M(glUniformMatrix2fv)
M(glUniformMatrix3fv)
M(glUniformMatrix4fv)
M(glUseProgram)
M(glVertexAttrib1f)
M(glVertexAttrib2fv)
M(glVertexAttrib3fv)
M(glVertexAttrib4fv)
M(glVertexAttribPointer)
M(glViewport)
#undef M
return eglGetProcAddress(name);
}
sk_sp<const GrGLInterface> GrGLMakeNativeInterface() {
return GrGLMakeAssembledInterface(nullptr, egl_get_gl_proc);
}
const GrGLInterface* GrGLCreateNativeInterface() { return GrGLMakeNativeInterface().release(); }
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (C) 2012 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 mixer.cpp
*
* Control channel input/output mixer and failsafe.
*/
#include <nuttx/config.h>
#include <nuttx/arch.h>
#include <sys/types.h>
#include <stdbool.h>
#include <string.h>
#include <assert.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <debug.h>
#include <drivers/drv_pwm_output.h>
#include <drivers/drv_hrt.h>
#include <systemlib/mixer/mixer.h>
extern "C" {
//#define DEBUG
#include "px4io.h"
}
/*
* Maximum interval in us before FMU signal is considered lost
*/
#define FMU_INPUT_DROP_LIMIT_US 200000
/* current servo arm/disarm state */
bool mixer_servos_armed = false;
/* selected control values and count for mixing */
static uint16_t *control_values;
static int control_count;
static int mixer_callback(uintptr_t handle,
uint8_t control_group,
uint8_t control_index,
float &control);
static MixerGroup mixer_group(mixer_callback, 0);
void
mixer_tick(void)
{
bool should_arm;
/* check that we are receiving fresh data from the FMU */
if ((hrt_absolute_time() - system_state.fmu_data_received_time) > FMU_INPUT_DROP_LIMIT_US) {
/* too many frames without FMU input, time to go to failsafe */
system_state.mixer_manual_override = true;
system_state.mixer_fmu_available = false;
lib_lowprintf("RX timeout\n");
}
/*
* Decide which set of inputs we're using.
*/
/* this is for planes, where manual override makes sense */
if(system_state.manual_override_ok) {
/* if everything is ok */
if (!system_state.mixer_manual_override && system_state.mixer_fmu_available) {
/* we have recent control data from the FMU */
control_count = PX4IO_CONTROL_CHANNELS;
control_values = &system_state.fmu_channel_data[0];
} else if (system_state.rc_channels > 0) {
/* when override is on or the fmu is not available, but RC is present */
control_count = system_state.rc_channels;
control_values = &system_state.rc_channel_data[0];
} else {
/* we have no control input (no FMU, no RC) */
// XXX builtin failsafe would activate here
control_count = 0;
}
/* this is for multicopters, etc. where manual override does not make sense */
} else {
/* if the fmu is available whe are good */
if(system_state.mixer_fmu_available) {
control_count = PX4IO_CONTROL_CHANNELS;
control_values = &system_state.fmu_channel_data[0];
/* we better shut everything off */
} else {
control_count = 0;
}
}
/*
* Run the mixers if we have any control data at all.
*/
if (control_count > 0) {
float outputs[IO_SERVO_COUNT];
unsigned mixed;
/* mix */
mixed = mixer_group.mix(&outputs[0], IO_SERVO_COUNT);
/* scale to PWM and update the servo outputs as required */
for (unsigned i = 0; i < IO_SERVO_COUNT; i++) {
if (i < mixed) {
/* scale to servo output */
system_state.servos[i] = (outputs[i] * 500.0f) + 1500;
} else {
/* set to zero to inhibit PWM pulse output */
system_state.servos[i] = 0;
}
/*
* If we are armed, update the servo output.
*/
if (system_state.armed && system_state.arm_ok)
up_pwm_servo_set(i, system_state.servos[i]);
}
}
/*
* Decide whether the servos should be armed right now.
* A sufficient reason is armed state and either FMU or RC control inputs
*/
should_arm = system_state.armed && system_state.arm_ok && (control_count > 0);
if (should_arm && !mixer_servos_armed) {
/* need to arm, but not armed */
up_pwm_servo_arm(true);
mixer_servos_armed = true;
} else if (!should_arm && mixer_servos_armed) {
/* armed but need to disarm */
up_pwm_servo_arm(false);
mixer_servos_armed = false;
}
}
static int
mixer_callback(uintptr_t handle,
uint8_t control_group,
uint8_t control_index,
float &control)
{
/* if the control index refers to an input that's not valid, we can't return it */
if (control_index >= control_count)
return -1;
/* scale from current PWM units (1000-2000) to mixer input values */
control = ((float)control_values[control_index] - 1500.0f) / 500.0f;
return 0;
}
static char mixer_text[256];
static unsigned mixer_text_length = 0;
void
mixer_handle_text(const void *buffer, size_t length)
{
px4io_mixdata *msg = (px4io_mixdata *)buffer;
debug("mixer text %u", length);
if (length < sizeof(px4io_mixdata))
return;
unsigned text_length = length - sizeof(px4io_mixdata);
switch (msg->action) {
case F2I_MIXER_ACTION_RESET:
debug("reset");
mixer_group.reset();
mixer_text_length = 0;
/* FALLTHROUGH */
case F2I_MIXER_ACTION_APPEND:
debug("append %d", length);
/* check for overflow - this is really fatal */
if ((mixer_text_length + text_length + 1) > sizeof(mixer_text))
return;
/* append mixer text and nul-terminate */
memcpy(&mixer_text[mixer_text_length], msg->text, text_length);
mixer_text_length += text_length;
mixer_text[mixer_text_length] = '\0';
debug("buflen %u", mixer_text_length);
/* process the text buffer, adding new mixers as their descriptions can be parsed */
unsigned resid = mixer_text_length;
mixer_group.load_from_buf(&mixer_text[0], resid);
/* if anything was parsed */
if (resid != mixer_text_length) {
debug("used %u", mixer_text_length - resid);
/* copy any leftover text to the base of the buffer for re-use */
if (resid > 0)
memcpy(&mixer_text[0], &mixer_text[mixer_text_length - resid], resid);
mixer_text_length = resid;
}
break;
}
}
<commit_msg>Code style fix<commit_after>/****************************************************************************
*
* Copyright (C) 2012 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 mixer.cpp
*
* Control channel input/output mixer and failsafe.
*/
#include <nuttx/config.h>
#include <nuttx/arch.h>
#include <sys/types.h>
#include <stdbool.h>
#include <string.h>
#include <assert.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <debug.h>
#include <drivers/drv_pwm_output.h>
#include <drivers/drv_hrt.h>
#include <systemlib/mixer/mixer.h>
extern "C" {
//#define DEBUG
#include "px4io.h"
}
/*
* Maximum interval in us before FMU signal is considered lost
*/
#define FMU_INPUT_DROP_LIMIT_US 200000
/* current servo arm/disarm state */
bool mixer_servos_armed = false;
/* selected control values and count for mixing */
static uint16_t *control_values;
static int control_count;
static int mixer_callback(uintptr_t handle,
uint8_t control_group,
uint8_t control_index,
float &control);
static MixerGroup mixer_group(mixer_callback, 0);
void
mixer_tick(void)
{
bool should_arm;
/* check that we are receiving fresh data from the FMU */
if ((hrt_absolute_time() - system_state.fmu_data_received_time) > FMU_INPUT_DROP_LIMIT_US) {
/* too many frames without FMU input, time to go to failsafe */
system_state.mixer_manual_override = true;
system_state.mixer_fmu_available = false;
lib_lowprintf("RX timeout\n");
}
/*
* Decide which set of inputs we're using.
*/
/* this is for planes, where manual override makes sense */
if (system_state.manual_override_ok) {
/* if everything is ok */
if (!system_state.mixer_manual_override && system_state.mixer_fmu_available) {
/* we have recent control data from the FMU */
control_count = PX4IO_CONTROL_CHANNELS;
control_values = &system_state.fmu_channel_data[0];
} else if (system_state.rc_channels > 0) {
/* when override is on or the fmu is not available, but RC is present */
control_count = system_state.rc_channels;
control_values = &system_state.rc_channel_data[0];
} else {
/* we have no control input (no FMU, no RC) */
// XXX builtin failsafe would activate here
control_count = 0;
}
/* this is for multicopters, etc. where manual override does not make sense */
} else {
/* if the fmu is available whe are good */
if (system_state.mixer_fmu_available) {
control_count = PX4IO_CONTROL_CHANNELS;
control_values = &system_state.fmu_channel_data[0];
/* we better shut everything off */
} else {
control_count = 0;
}
}
/*
* Run the mixers if we have any control data at all.
*/
if (control_count > 0) {
float outputs[IO_SERVO_COUNT];
unsigned mixed;
/* mix */
mixed = mixer_group.mix(&outputs[0], IO_SERVO_COUNT);
/* scale to PWM and update the servo outputs as required */
for (unsigned i = 0; i < IO_SERVO_COUNT; i++) {
if (i < mixed) {
/* scale to servo output */
system_state.servos[i] = (outputs[i] * 500.0f) + 1500;
} else {
/* set to zero to inhibit PWM pulse output */
system_state.servos[i] = 0;
}
/*
* If we are armed, update the servo output.
*/
if (system_state.armed && system_state.arm_ok)
up_pwm_servo_set(i, system_state.servos[i]);
}
}
/*
* Decide whether the servos should be armed right now.
* A sufficient reason is armed state and either FMU or RC control inputs
*/
should_arm = system_state.armed && system_state.arm_ok && (control_count > 0);
if (should_arm && !mixer_servos_armed) {
/* need to arm, but not armed */
up_pwm_servo_arm(true);
mixer_servos_armed = true;
} else if (!should_arm && mixer_servos_armed) {
/* armed but need to disarm */
up_pwm_servo_arm(false);
mixer_servos_armed = false;
}
}
static int
mixer_callback(uintptr_t handle,
uint8_t control_group,
uint8_t control_index,
float &control)
{
/* if the control index refers to an input that's not valid, we can't return it */
if (control_index >= control_count)
return -1;
/* scale from current PWM units (1000-2000) to mixer input values */
control = ((float)control_values[control_index] - 1500.0f) / 500.0f;
return 0;
}
static char mixer_text[256];
static unsigned mixer_text_length = 0;
void
mixer_handle_text(const void *buffer, size_t length)
{
px4io_mixdata *msg = (px4io_mixdata *)buffer;
debug("mixer text %u", length);
if (length < sizeof(px4io_mixdata))
return;
unsigned text_length = length - sizeof(px4io_mixdata);
switch (msg->action) {
case F2I_MIXER_ACTION_RESET:
debug("reset");
mixer_group.reset();
mixer_text_length = 0;
/* FALLTHROUGH */
case F2I_MIXER_ACTION_APPEND:
debug("append %d", length);
/* check for overflow - this is really fatal */
if ((mixer_text_length + text_length + 1) > sizeof(mixer_text))
return;
/* append mixer text and nul-terminate */
memcpy(&mixer_text[mixer_text_length], msg->text, text_length);
mixer_text_length += text_length;
mixer_text[mixer_text_length] = '\0';
debug("buflen %u", mixer_text_length);
/* process the text buffer, adding new mixers as their descriptions can be parsed */
unsigned resid = mixer_text_length;
mixer_group.load_from_buf(&mixer_text[0], resid);
/* if anything was parsed */
if (resid != mixer_text_length) {
debug("used %u", mixer_text_length - resid);
/* copy any leftover text to the base of the buffer for re-use */
if (resid > 0)
memcpy(&mixer_text[0], &mixer_text[mixer_text_length - resid], resid);
mixer_text_length = resid;
}
break;
}
}
<|endoftext|> |
<commit_before>// $Id: reissCavFreeEnergyProcessor.C,v 1.8 2001/06/05 15:53:29 anker Exp $
#include <BALL/SOLVATION/reissCavFreeEnergyProcessor.h>
#include <BALL/STRUCTURE/numericalSAS.h>
using namespace std;
namespace BALL
{
const char* ReissCavFreeEnergyProcessor::Option::VERBOSITY = "verbosity";
const char* ReissCavFreeEnergyProcessor::Option::SOLVENT_NUMBER_DENSITY
= "solvent_number_density";
const char* ReissCavFreeEnergyProcessor::Option::PRESSURE = "pressure";
const char* ReissCavFreeEnergyProcessor::Option::ABSOLUTE_TEMPERATURE
= "absolute_temperature";
const char* ReissCavFreeEnergyProcessor::Option::PROBE_RADIUS
= "probe_radius";
const int ReissCavFreeEnergyProcessor::Default::VERBOSITY = 0;
const float ReissCavFreeEnergyProcessor::Default::SOLVENT_NUMBER_DENSITY
= 3.33253e-2;
const float ReissCavFreeEnergyProcessor::Default::PRESSURE = 1.01325e5;
const float ReissCavFreeEnergyProcessor::Default::ABSOLUTE_TEMPERATURE
= 298.0;
const float ReissCavFreeEnergyProcessor::Default::PROBE_RADIUS = 1.385;
ReissCavFreeEnergyProcessor::ReissCavFreeEnergyProcessor() throw()
: EnergyProcessor()
{
setDefaultOptions();
valid_ = true;
}
ReissCavFreeEnergyProcessor::ReissCavFreeEnergyProcessor
(const ReissCavFreeEnergyProcessor& proc) throw()
: EnergyProcessor(proc)
{
}
ReissCavFreeEnergyProcessor::~ReissCavFreeEnergyProcessor() throw()
{
clear();
valid_ = false;
}
void ReissCavFreeEnergyProcessor::clear() throw()
{
EnergyProcessor::clear();
setDefaultOptions();
valid_ = true;
}
bool ReissCavFreeEnergyProcessor::finish() throw()
{
// first check for user settings
int verbosity = (int) options.getInteger(Option::VERBOSITY);
// rho is the number density of the solvent (i. e. water) [1/m^3]
double rho = options.getReal(Option::SOLVENT_NUMBER_DENSITY) * 1e30;
// the pressure [ Pa ]
double P = options.getReal(Option::PRESSURE);
// the temperature [ K ]
double T = options.getReal(Option::ABSOLUTE_TEMPERATURE);
// the solvent radius [ A ]
double solvent_radius = options.getReal(Option::PROBE_RADIUS);
if (verbosity > 0)
{
Log.info() << "Using a probe radius of " << solvent_radius << " A" <<
endl;
}
// now compute some constant terms (names as in Pierotti, Chem. Rev.
// 76(6):717--726, 1976)
double sigma1 = 2 * solvent_radius * 1e-10; // [ m ]
double sigma1_2 = sigma1 * sigma1; // [ m^2 ]
double sigma1_3 = sigma1 * sigma1 * sigma1; // [ m^3 ]
double y = Constants::PI * sigma1_3 * (rho/6); // [ 1 ]
double y_frac = y/(1-y); // [ 1 ]
double y_frac_2 = y_frac * y_frac; // [ 1 ]
double NkT = Constants::AVOGADRO * Constants::BOLTZMANN * T; // [ J/mol ]
double NpiP = Constants::AVOGADRO * Constants::PI * P; // [ ? ]
if (verbosity > 0)
{
Log.info() << "y = " << y << endl;
Log.info() << "y_frac = " << y_frac << endl;
}
HashMap<const Atom*,float> atom_areas;
calculateSASAtomAreas(*fragment_, atom_areas, solvent_radius);
// R is the sum of atom radius and probe radius [ m ]
double R;
// deltaGspher is the cavitatonal energy of a spherical solute [ J/mol ]
double deltaGspher;
// deltaGcav is the cavitatonal energy of the molecule [ J/mol ]
double deltaGcav = 0;
// now iterate over the atoms.
HashMap<const Atom*,float>::Iterator it = atom_areas.begin();
for (; +it; ++it)
{
R = it->first->getRadius() * 1e-10 + sigma1 / 2.0;
deltaGspher =
NkT * (-log(1.0 - y) + 4.5 * y_frac_2) - (NpiP * sigma1_3 / 6.0)
- (NkT * ((6.0 * y_frac + 18 * y_frac_2) / sigma1)
+ (NpiP * sigma1_2)) * R
+ (NkT * ((12.0 * y_frac + 18 * y_frac_2) / sigma1_2)
- (2.0 * NpiP * sigma1)) * (R * R)
+ 4.0 / 3.0 * NpiP * (R * R * R);
deltaGcav += it->second * 1e-20 /
( 4 * Constants::PI * R * R ) * deltaGspher;
}
// return energy in units of kJ/mol
energy_ = deltaGcav/1000;
return 1;
}
void ReissCavFreeEnergyProcessor::setDefaultOptions() throw()
{
options.setDefaultInteger(Option::VERBOSITY, Default::VERBOSITY);
options.setDefaultReal(Option::SOLVENT_NUMBER_DENSITY,
Default::SOLVENT_NUMBER_DENSITY);
options.setDefaultReal(Option::PRESSURE, Default::PRESSURE);
options.setDefaultReal(Option::ABSOLUTE_TEMPERATURE,
Default::ABSOLUTE_TEMPERATURE);
options.setDefaultReal(Option::PROBE_RADIUS, Default::PROBE_RADIUS);
}
} // namespace BALL
<commit_msg>added operators = and ==<commit_after>// $Id: reissCavFreeEnergyProcessor.C,v 1.9 2001/09/11 10:00:05 aubertin Exp $
#include <BALL/SOLVATION/reissCavFreeEnergyProcessor.h>
#include <BALL/STRUCTURE/numericalSAS.h>
using namespace std;
namespace BALL
{
const char* ReissCavFreeEnergyProcessor::Option::VERBOSITY = "verbosity";
const char* ReissCavFreeEnergyProcessor::Option::SOLVENT_NUMBER_DENSITY
= "solvent_number_density";
const char* ReissCavFreeEnergyProcessor::Option::PRESSURE = "pressure";
const char* ReissCavFreeEnergyProcessor::Option::ABSOLUTE_TEMPERATURE
= "absolute_temperature";
const char* ReissCavFreeEnergyProcessor::Option::PROBE_RADIUS
= "probe_radius";
const int ReissCavFreeEnergyProcessor::Default::VERBOSITY = 0;
const float ReissCavFreeEnergyProcessor::Default::SOLVENT_NUMBER_DENSITY
= 3.33253e-2;
const float ReissCavFreeEnergyProcessor::Default::PRESSURE = 1.01325e5;
const float ReissCavFreeEnergyProcessor::Default::ABSOLUTE_TEMPERATURE
= 298.0;
const float ReissCavFreeEnergyProcessor::Default::PROBE_RADIUS = 1.385;
ReissCavFreeEnergyProcessor::ReissCavFreeEnergyProcessor() throw()
: EnergyProcessor()
{
setDefaultOptions();
valid_ = true;
}
ReissCavFreeEnergyProcessor::ReissCavFreeEnergyProcessor
(const ReissCavFreeEnergyProcessor& proc) throw()
: EnergyProcessor(proc)
{
}
ReissCavFreeEnergyProcessor::~ReissCavFreeEnergyProcessor() throw()
{
clear();
valid_ = false;
}
void ReissCavFreeEnergyProcessor::clear() throw()
{
EnergyProcessor::clear();
setDefaultOptions();
valid_ = true;
}
const ReissCavFreeEnergyProcessor& ReissCavFreeEnergyProcessor::operator = (const ReissCavFreeEnergyProcessor& proc) throw()
{
valid_=proc.valid_;
energy_=proc.energy_;
fragment_=proc.fragment_;
return *this;
}
bool ReissCavFreeEnergyProcessor::operator == (const ReissCavFreeEnergyProcessor& proc) const throw()
{
bool result;
if ((fragment_ == 0) && (proc.fragment_ == 0))
{
result = ((energy_ == proc.energy_) && (valid_ == proc.valid_));
}
else
{
if ((fragment_ == 0) || (proc.fragment_ == 0))
{
result = false;
}
else
{
result = ((*fragment_ == *proc.fragment_)
&& (energy_ == proc.energy_)
&& (valid_ == proc.valid_));
}
}
return result;
}
bool ReissCavFreeEnergyProcessor::finish() throw()
{
// first check for user settings
int verbosity = (int) options.getInteger(Option::VERBOSITY);
// rho is the number density of the solvent (i. e. water) [1/m^3]
double rho = options.getReal(Option::SOLVENT_NUMBER_DENSITY) * 1e30;
// the pressure [ Pa ]
double P = options.getReal(Option::PRESSURE);
// the temperature [ K ]
double T = options.getReal(Option::ABSOLUTE_TEMPERATURE);
// the solvent radius [ A ]
double solvent_radius = options.getReal(Option::PROBE_RADIUS);
if (verbosity > 0)
{
Log.info() << "Using a probe radius of " << solvent_radius << " A" <<
endl;
}
// now compute some constant terms (names as in Pierotti, Chem. Rev.
// 76(6):717--726, 1976)
double sigma1 = 2 * solvent_radius * 1e-10; // [ m ]
double sigma1_2 = sigma1 * sigma1; // [ m^2 ]
double sigma1_3 = sigma1 * sigma1 * sigma1; // [ m^3 ]
double y = Constants::PI * sigma1_3 * (rho/6); // [ 1 ]
double y_frac = y/(1-y); // [ 1 ]
double y_frac_2 = y_frac * y_frac; // [ 1 ]
double NkT = Constants::AVOGADRO * Constants::BOLTZMANN * T; // [ J/mol ]
double NpiP = Constants::AVOGADRO * Constants::PI * P; // [ ? ]
if (verbosity > 0)
{
Log.info() << "y = " << y << endl;
Log.info() << "y_frac = " << y_frac << endl;
}
HashMap<const Atom*,float> atom_areas;
calculateSASAtomAreas(*fragment_, atom_areas, solvent_radius);
// R is the sum of atom radius and probe radius [ m ]
double R;
// deltaGspher is the cavitatonal energy of a spherical solute [ J/mol ]
double deltaGspher;
// deltaGcav is the cavitatonal energy of the molecule [ J/mol ]
double deltaGcav = 0;
// now iterate over the atoms.
HashMap<const Atom*,float>::Iterator it = atom_areas.begin();
for (; +it; ++it)
{
R = it->first->getRadius() * 1e-10 + sigma1 / 2.0;
deltaGspher =
NkT * (-log(1.0 - y) + 4.5 * y_frac_2) - (NpiP * sigma1_3 / 6.0)
- (NkT * ((6.0 * y_frac + 18 * y_frac_2) / sigma1)
+ (NpiP * sigma1_2)) * R
+ (NkT * ((12.0 * y_frac + 18 * y_frac_2) / sigma1_2)
- (2.0 * NpiP * sigma1)) * (R * R)
+ 4.0 / 3.0 * NpiP * (R * R * R);
deltaGcav += it->second * 1e-20 /
( 4 * Constants::PI * R * R ) * deltaGspher;
}
// return energy in units of kJ/mol
energy_ = deltaGcav/1000;
return 1;
}
void ReissCavFreeEnergyProcessor::setDefaultOptions() throw()
{
options.setDefaultInteger(Option::VERBOSITY, Default::VERBOSITY);
options.setDefaultReal(Option::SOLVENT_NUMBER_DENSITY,
Default::SOLVENT_NUMBER_DENSITY);
options.setDefaultReal(Option::PRESSURE, Default::PRESSURE);
options.setDefaultReal(Option::ABSOLUTE_TEMPERATURE,
Default::ABSOLUTE_TEMPERATURE);
options.setDefaultReal(Option::PROBE_RADIUS, Default::PROBE_RADIUS);
}
} // namespace BALL
<|endoftext|> |
<commit_before>#include "core/global.h"
#include "DBStateServer.h"
#include "LoadingObject.h"
// RoleConfig
static ConfigVariable<channel_t> database_channel("database", INVALID_CHANNEL);
// RangesConfig
static ConfigVariable<uint32_t> range_min("min", INVALID_DO_ID);
static ConfigVariable<uint32_t> range_max("max", UINT32_MAX);
DBStateServer::DBStateServer(RoleConfig roleconfig) : StateServer(roleconfig),
m_db_channel(database_channel.get_rval(m_roleconfig)), m_next_context(0)
{
RangesConfig ranges = roleconfig["ranges"];
for(auto it = ranges.begin(); it != ranges.end(); ++it)
{
channel_t min = range_min.get_rval(*it);
channel_t max = range_max.get_rval(*it);
MessageDirector::singleton.subscribe_range(this, min, max);
}
std::stringstream name;
name << "DBSS(Database: " << m_db_channel << ")";
m_log = new LogCategory("dbss", name.str());
}
DBStateServer::~DBStateServer()
{
delete m_log;
}
void DBStateServer::handle_activate(DatagramIterator &dgi, bool has_other)
{
uint32_t do_id = dgi.read_uint32();
uint32_t parent_id = dgi.read_uint32();
uint32_t zone_id = dgi.read_uint32();
// Check object is not already active
if(m_objs.find(do_id) != m_objs.end() || m_loading.find(do_id) != m_loading.end())
{
m_log->warning() << "Received activate for already-active object"
<< " - id:" << do_id << std::endl;
return;
}
if(!has_other)
{
m_loading[do_id] = new LoadingObject(this, do_id, parent_id, zone_id);
}
else
{
uint16_t dc_id = dgi.read_uint16();
// Check dclass is valid
if(dc_id >= g_dcf->get_num_classes())
{
m_log->error() << "Received activate_other with unknown dclass"
<< " - id:" << dc_id << std::endl;
return;
}
DCClass *dclass = g_dcf->get_class(dc_id);
m_loading[do_id] = new LoadingObject(this, do_id, parent_id, zone_id, dclass, dgi);
}
}
void DBStateServer::handle_datagram(Datagram &in_dg, DatagramIterator &dgi)
{
channel_t sender = dgi.read_uint64();
uint16_t msgtype = dgi.read_uint16();
switch(msgtype)
{
case DBSS_OBJECT_ACTIVATE_WITH_DEFAULTS:
{
handle_activate(dgi, false);
break;
}
case DBSS_OBJECT_ACTIVATE_WITH_DEFAULTS_OTHER:
{
handle_activate(dgi, true);
break;
}
case DBSS_OBJECT_DELETE_DISK:
{
uint32_t do_id = dgi.read_uint32();
auto obj_keyval = m_objs.find(do_id);
if(obj_keyval != m_objs.end())
{
// TODO: Handle broadcast behavior
}
Datagram dg(m_db_channel, do_id, DBSERVER_OBJECT_DELETE);
dg.add_uint32(do_id);
send(dg);
break;
}
case STATESERVER_OBJECT_GET_ALL:
{
uint32_t r_context = dgi.read_uint32();
uint32_t r_do_id = dgi.read_uint32();
// If object is active or loading, the Object or Loader will handle it
if(m_objs.find(r_do_id) != m_objs.end() ||
m_loading.find(r_do_id) != m_loading.end())
{
break;
}
m_log->spam() << "Received GetAll for inactive object with id " << r_do_id
<< ", sending query to database." << std::endl;
// Get context for db query, and remember reply with it
uint32_t db_context = m_next_context++;
m_resp_context[db_context] = GetRecord(sender, r_context, r_do_id);
// Send query to database
Datagram dg(m_db_channel, r_do_id, DBSERVER_OBJECT_GET_ALL);
dg.add_uint32(db_context);
dg.add_uint32(r_do_id);
send(dg);
break;
}
case DBSERVER_OBJECT_GET_ALL_RESP:
{
uint32_t db_context = dgi.read_uint32();
// Check context
auto caller_keyval = m_resp_context.find(db_context);
if(caller_keyval == m_resp_context.end())
{
break; // Not meant for me, handled by LoadingObject
}
GetRecord caller = caller_keyval->second;
m_log->spam() << "Received GetAllResp from database"
" for object with id " << caller.do_id << std::endl;
// Cleanup the context first, so it is removed if any exceptions occur
m_resp_context.erase(db_context);
// If object not found, just cleanup the context map
if(dgi.read_uint8() != true)
{
break; // Object not found
}
// Read object class
uint16_t dc_id = dgi.read_uint16();
if(!dc_id)
{
m_log->error() << "Received object from database with unknown dclass"
<< " - id:" << dc_id << std::endl;
break;
}
DCClass* r_dclass = g_dcf->get_class(dc_id);
// Get fields from database
std::unordered_map<DCField*, std::vector<uint8_t>> required_fields;
std::unordered_map<DCField*, std::vector<uint8_t>> ram_fields;
if(!unpack_db_fields(dgi, r_dclass, required_fields, ram_fields))
{
m_log->error() << "Error while unpacking fields from database." << std::endl;
break;
}
// Prepare SSGetAllResp
Datagram dg(caller.sender, caller.do_id, STATESERVER_OBJECT_GET_ALL_RESP);
dg.add_uint32(caller.do_id);
dg.add_uint32(INVALID_DO_ID);
dg.add_uint32(INVALID_ZONE);
dg.add_uint16(r_dclass->get_number());
// Add required fields to datagram
int dcc_field_count = r_dclass->get_num_inherited_fields();
for(int i = 0; i < dcc_field_count; ++i)
{
DCField *field = r_dclass->get_inherited_field(i);
if(!field->as_molecular_field() && field->is_required())
{
auto req_it = required_fields.find(field);
if(req_it != required_fields.end())
{
dg.add_data(req_it->second);
}
else
{
dg.add_data(field->get_default_value());
}
}
}
// Add ram fields to datagram
dg.add_uint16(ram_fields.size());
for(auto it = ram_fields.begin(); it != ram_fields.end(); ++it)
{
dg.add_uint16(it->first->get_number());
dg.add_data(it->second);
}
// Send response back to caller
send(dg);
}
default:
{
if(msgtype < STATESERVER_MSGTYPE_MIN || msgtype > DBSERVER_MSGTYPE_MAX)
{
m_log->warning() << "Received unknown message of type " << msgtype << std::endl;
}
else
{
m_log->spam() << "Ignoring stateserver or database message"
<< " of type " << msgtype << std::endl;
}
}
}
}
void DBStateServer::receive_object(DistributedObject* obj)
{
m_objs[obj->get_id()] = obj;
}
void DBStateServer::discard_loader(uint32_t do_id)
{
m_loading.erase(do_id);
}
bool unpack_db_fields(DatagramIterator &dgi, DCClass* dclass,
std::unordered_map<DCField*, std::vector<uint8_t>> &required,
std::unordered_map<DCField*, std::vector<uint8_t>> &ram)
{
// Unload ram and required fields from database resp
uint16_t db_field_count = dgi.read_uint16();
for(uint16_t i = 0; i < db_field_count; ++i)
{
uint16_t field_id = dgi.read_uint16();
DCField *field = dclass->get_field_by_index(field_id);
if(!field)
{
return false;
}
if(field->is_ram())
{
dgi.unpack_field(field, ram[field]);
}
else if(field->is_required())
{
dgi.unpack_field(field, required[field]);
}
else
{
dgi.skip_field(field);
}
}
return true;
}
RoleFactoryItem<DBStateServer> dbss_fact("dbss");
<commit_msg>Stateserver: Fix get_all for non-loaded objects (needs to have context)<commit_after>#include "core/global.h"
#include "DBStateServer.h"
#include "LoadingObject.h"
// RoleConfig
static ConfigVariable<channel_t> database_channel("database", INVALID_CHANNEL);
// RangesConfig
static ConfigVariable<uint32_t> range_min("min", INVALID_DO_ID);
static ConfigVariable<uint32_t> range_max("max", UINT32_MAX);
DBStateServer::DBStateServer(RoleConfig roleconfig) : StateServer(roleconfig),
m_db_channel(database_channel.get_rval(m_roleconfig)), m_next_context(0)
{
RangesConfig ranges = roleconfig["ranges"];
for(auto it = ranges.begin(); it != ranges.end(); ++it)
{
channel_t min = range_min.get_rval(*it);
channel_t max = range_max.get_rval(*it);
MessageDirector::singleton.subscribe_range(this, min, max);
}
std::stringstream name;
name << "DBSS(Database: " << m_db_channel << ")";
m_log = new LogCategory("dbss", name.str());
}
DBStateServer::~DBStateServer()
{
delete m_log;
}
void DBStateServer::handle_activate(DatagramIterator &dgi, bool has_other)
{
uint32_t do_id = dgi.read_uint32();
uint32_t parent_id = dgi.read_uint32();
uint32_t zone_id = dgi.read_uint32();
// Check object is not already active
if(m_objs.find(do_id) != m_objs.end() || m_loading.find(do_id) != m_loading.end())
{
m_log->warning() << "Received activate for already-active object"
<< " - id:" << do_id << std::endl;
return;
}
if(!has_other)
{
m_loading[do_id] = new LoadingObject(this, do_id, parent_id, zone_id);
}
else
{
uint16_t dc_id = dgi.read_uint16();
// Check dclass is valid
if(dc_id >= g_dcf->get_num_classes())
{
m_log->error() << "Received activate_other with unknown dclass"
<< " - id:" << dc_id << std::endl;
return;
}
DCClass *dclass = g_dcf->get_class(dc_id);
m_loading[do_id] = new LoadingObject(this, do_id, parent_id, zone_id, dclass, dgi);
}
}
void DBStateServer::handle_datagram(Datagram &in_dg, DatagramIterator &dgi)
{
channel_t sender = dgi.read_uint64();
uint16_t msgtype = dgi.read_uint16();
switch(msgtype)
{
case DBSS_OBJECT_ACTIVATE_WITH_DEFAULTS:
{
handle_activate(dgi, false);
break;
}
case DBSS_OBJECT_ACTIVATE_WITH_DEFAULTS_OTHER:
{
handle_activate(dgi, true);
break;
}
case DBSS_OBJECT_DELETE_DISK:
{
uint32_t do_id = dgi.read_uint32();
auto obj_keyval = m_objs.find(do_id);
if(obj_keyval != m_objs.end())
{
// TODO: Handle broadcast behavior
}
Datagram dg(m_db_channel, do_id, DBSERVER_OBJECT_DELETE);
dg.add_uint32(do_id);
send(dg);
break;
}
case STATESERVER_OBJECT_GET_ALL:
{
uint32_t r_context = dgi.read_uint32();
uint32_t r_do_id = dgi.read_uint32();
// If object is active or loading, the Object or Loader will handle it
if(m_objs.find(r_do_id) != m_objs.end() ||
m_loading.find(r_do_id) != m_loading.end())
{
break;
}
m_log->spam() << "Received GetAll for inactive object with id " << r_do_id
<< ", sending query to database." << std::endl;
// Get context for db query, and remember reply with it
uint32_t db_context = m_next_context++;
m_resp_context[db_context] = GetRecord(sender, r_context, r_do_id);
// Send query to database
Datagram dg(m_db_channel, r_do_id, DBSERVER_OBJECT_GET_ALL);
dg.add_uint32(db_context);
dg.add_uint32(r_do_id);
send(dg);
break;
}
case DBSERVER_OBJECT_GET_ALL_RESP:
{
uint32_t db_context = dgi.read_uint32();
// Check context
auto caller_keyval = m_resp_context.find(db_context);
if(caller_keyval == m_resp_context.end())
{
break; // Not meant for me, handled by LoadingObject
}
GetRecord caller = caller_keyval->second;
m_log->spam() << "Received GetAllResp from database"
" for object with id " << caller.do_id << std::endl;
// Cleanup the context first, so it is removed if any exceptions occur
m_resp_context.erase(db_context);
// If object not found, just cleanup the context map
if(dgi.read_uint8() != true)
{
break; // Object not found
}
// Read object class
uint16_t dc_id = dgi.read_uint16();
if(!dc_id)
{
m_log->error() << "Received object from database with unknown dclass"
<< " - id:" << dc_id << std::endl;
break;
}
DCClass* r_dclass = g_dcf->get_class(dc_id);
// Get fields from database
std::unordered_map<DCField*, std::vector<uint8_t>> required_fields;
std::unordered_map<DCField*, std::vector<uint8_t>> ram_fields;
if(!unpack_db_fields(dgi, r_dclass, required_fields, ram_fields))
{
m_log->error() << "Error while unpacking fields from database." << std::endl;
break;
}
// Prepare SSGetAllResp
Datagram dg(caller.sender, caller.do_id, STATESERVER_OBJECT_GET_ALL_RESP);
dg.add_uint32(caller.context);
dg.add_uint32(caller.do_id);
dg.add_uint32(INVALID_DO_ID);
dg.add_uint32(INVALID_ZONE);
dg.add_uint16(r_dclass->get_number());
// Add required fields to datagram
int dcc_field_count = r_dclass->get_num_inherited_fields();
for(int i = 0; i < dcc_field_count; ++i)
{
DCField *field = r_dclass->get_inherited_field(i);
if(!field->as_molecular_field() && field->is_required())
{
auto req_it = required_fields.find(field);
if(req_it != required_fields.end())
{
dg.add_data(req_it->second);
}
else
{
dg.add_data(field->get_default_value());
}
}
}
// Add ram fields to datagram
dg.add_uint16(ram_fields.size());
for(auto it = ram_fields.begin(); it != ram_fields.end(); ++it)
{
dg.add_uint16(it->first->get_number());
dg.add_data(it->second);
}
// Send response back to caller
send(dg);
}
default:
{
if(msgtype < STATESERVER_MSGTYPE_MIN || msgtype > DBSERVER_MSGTYPE_MAX)
{
m_log->warning() << "Received unknown message of type " << msgtype << std::endl;
}
else
{
m_log->spam() << "Ignoring stateserver or database message"
<< " of type " << msgtype << std::endl;
}
}
}
}
void DBStateServer::receive_object(DistributedObject* obj)
{
m_objs[obj->get_id()] = obj;
}
void DBStateServer::discard_loader(uint32_t do_id)
{
m_loading.erase(do_id);
}
bool unpack_db_fields(DatagramIterator &dgi, DCClass* dclass,
std::unordered_map<DCField*, std::vector<uint8_t>> &required,
std::unordered_map<DCField*, std::vector<uint8_t>> &ram)
{
// Unload ram and required fields from database resp
uint16_t db_field_count = dgi.read_uint16();
for(uint16_t i = 0; i < db_field_count; ++i)
{
uint16_t field_id = dgi.read_uint16();
DCField *field = dclass->get_field_by_index(field_id);
if(!field)
{
return false;
}
if(field->is_ram())
{
dgi.unpack_field(field, ram[field]);
}
else if(field->is_required())
{
dgi.unpack_field(field, required[field]);
}
else
{
dgi.skip_field(field);
}
}
return true;
}
RoleFactoryItem<DBStateServer> dbss_fact("dbss");
<|endoftext|> |
<commit_before>#include "GUI_TFT.h"
Guitft::~Guitft(){
}
void Guitft::fillRectangle(uint16_t poX, uint16_t poY, uint16_t length, uint16_t width, uint16_t color)
{
this->fillRect(poX,poY,length,width,color);
}
/*
* Implement a drawRectangle function
*/
void Guitft::drawRectangle(uint16_t poX, uint16_t poY, uint16_t length, uint16_t width,uint16_t color)
{
drawFastHLine(poX,poY,length,color);
drawFastHLine(poX, poY+width, length, color);
drawFastVLine(poX, poY, width,color);
drawFastVLine(poX+length,poY,width,color);
}
/*
* Wrapper for drawing strings on the canvas
*/
void Guitft::drawString(char* string,uint16_t poX, uint16_t poY,uint16_t size,uint16_t fgcolor){
setCursor(poX,poY);
setTextSize(size);
setTextColor(fgcolor);
print(string);
}
/*
* Wrapper method for drawing vertical lines
*/
void Guitft::drawVerticalLine(uint16_t poX, uint16_t poY,uint16_t length,uint16_t color){
drawFastVLine(poX,poY,length,color);
}
/*
* Wrapper method for drawing horizontal lines
*/
void Guitft::drawHorizontalLine(uint16_t poX, uint16_t poY,uint16_t length,uint16_t color){
drawFastHLine(poX,poY,length,color);
}
/*
* Wrapper method for drawing numbers
*/
uint8_t Guitft::drawNumber(long long_num,uint16_t poX, uint16_t poY,uint16_t size,uint16_t fgcolor){
setCursor(poX,poY);
setTextSize(size);
setTextColor(fgcolor);
print(long_num);
}
// Needed to declare in GUI_TFT.h as extern
// and instance it here
// to avoid compiler issues with redeclarations
Guitft Tft = Guitft(5, 6, -1); // Use hardware SPI
<commit_msg>Fixed a fundamental bug in the GUI_TFT.cpp drawRectangle routine, by using the inherited method.<commit_after>#include "GUI_TFT.h"
Guitft::~Guitft(){
}
void Guitft::fillRectangle(uint16_t poX, uint16_t poY, uint16_t length, uint16_t width, uint16_t color)
{
this->fillRect(poX,poY,length,width,color);
}
/*
* Implement a drawRectangle function
*/
void Guitft::drawRectangle(uint16_t poX, uint16_t poY, uint16_t length, uint16_t width,uint16_t color)
{
this->drawRect(poX,poY,length,width,color);
//drawFastHLine(poX,poY,length,color);
//drawFastHLine(poX, poY+width, length, color);
//drawFastVLine(poX, poY, width,color);
//drawFastVLine(poX+length,poY,width,color);
}
/*
* Wrapper for drawing strings on the canvas
*/
void Guitft::drawString(char* string,uint16_t poX, uint16_t poY,uint16_t size,uint16_t fgcolor){
setCursor(poX,poY);
setTextSize(size);
setTextColor(fgcolor);
print(string);
}
/*
* Wrapper method for drawing vertical lines
*/
void Guitft::drawVerticalLine(uint16_t poX, uint16_t poY,uint16_t length,uint16_t color){
drawFastVLine(poX,poY,length,color);
}
/*
* Wrapper method for drawing horizontal lines
*/
void Guitft::drawHorizontalLine(uint16_t poX, uint16_t poY,uint16_t length,uint16_t color){
drawFastHLine(poX,poY,length,color);
}
/*
* Wrapper method for drawing numbers
*/
uint8_t Guitft::drawNumber(long long_num,uint16_t poX, uint16_t poY,uint16_t size,uint16_t fgcolor){
setCursor(poX,poY);
setTextSize(size);
setTextColor(fgcolor);
print(long_num);
}
// Needed to declare in GUI_TFT.h as extern
// and instance it here
// to avoid compiler issues with redeclarations
Guitft Tft = Guitft(5, 6, -1); // Use hardware SPI
<|endoftext|> |
<commit_before>/*
* This file is part of Clockwork.
*
* Copyright (c) 2013-2016 Jeremy Othieno.
*
* The MIT License (MIT)
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "ApplicationSettings.hh"
#include "Application.hh"
#include "Framebuffer.hh"
#include "toString.hh"
#include <QStandardPaths>
using clockwork::ApplicationSettings;
ApplicationSettings::ApplicationSettings() :
QSettings(QString("./clockwork-preferences.pro.user"), Format::IniFormat) {
//QSettings(QString("%1/configuration.ini").arg(QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation)), Format::IniFormat) {
}
bool
ApplicationSettings::isFpsCounterVisible() const {
return value(Key::ShowFramesPerSecond, false).toBool();
}
void
ApplicationSettings::showFpsCounter(const bool visible) {
if (isFpsCounterVisible() != visible) {
setValue(Key::ShowFramesPerSecond, visible);
emit fpsCounterVisibilityChanged(visible);
}
}
bool
ApplicationSettings::isWindowBorderless() const {
return value(Key::ShowBorderlessWindow, false).toBool();
}
void
ApplicationSettings::showBorderlessWindow(const bool visible) {
if (isWindowBorderless() != visible) {
setValue(Key::ShowBorderlessWindow, visible);
emit windowBorderVisibilityChanged(visible);
}
}
int
ApplicationSettings::getPrimitiveTopologyOrdinal() const {
static_assert(std::is_same<int, clockwork::enum_traits<clockwork::PrimitiveTopology>::Ordinal>::value);
return value(
Key::PrimitiveTopology,
enum_traits<PrimitiveTopology>::ordinal(PrimitiveTopology::Triangle)
).toInt();
}
void
ApplicationSettings::setPrimitiveTopology(const int topology) {
if (getPrimitiveTopologyOrdinal() != topology) {
setValue(Key::PrimitiveTopology, topology);
emit primitiveTopologyChanged_(topology);
emit primitiveTopologyChanged(enum_traits<PrimitiveTopology>::enumerator(topology));
}
}
bool
ApplicationSettings::isClippingEnabled() const {
return value(Key::EnableClipping, true).toBool();
}
void
ApplicationSettings::enableClipping(const bool enable) {
if (isClippingEnabled() != enable) {
setValue(Key::EnableClipping, enable);
emit clippingToggled(enable);
}
}
bool
ApplicationSettings::isBackfaceCullingEnabled() const {
return value(Key::EnableBackfaceCulling, true).toBool();
}
void
ApplicationSettings::enableBackfaceCulling(const bool enable) {
if (isBackfaceCullingEnabled() != enable) {
setValue(Key::EnableBackfaceCulling, enable);
emit backfaceCullingToggled(enable);
}
}
int
ApplicationSettings::getPolygonModeOrdinal() const {
return value(
Key::PolygonMode,
enum_traits<PolygonMode>::ordinal(PolygonMode::Fill)
).toInt();
}
void
ApplicationSettings::setPolygonMode(const int mode) {
if (getPolygonModeOrdinal() != mode) {
setValue(Key::PolygonMode, mode);
emit polygonModeChanged_(mode);
emit polygonModeChanged(enum_traits<PolygonMode>::enumerator(mode));
}
}
int
ApplicationSettings::getShadeModelOrdinal() const {
return value(
Key::ShadeModel,
enum_traits<ShadeModel>::ordinal(ShadeModel::Flat)
).toInt();
}
void
ApplicationSettings::setShadeModel(const int model) {
if (getShadeModelOrdinal() != model) {
setValue(Key::ShadeModel, model);
emit shadeModelChanged_(model);
emit shadeModelChanged(enum_traits<ShadeModel>::enumerator(model));
}
}
bool
ApplicationSettings::isScissorTestEnabled() const {
return value(Key::EnableScissorTest, false).toBool();
}
void
ApplicationSettings::enableScissorTest(const bool enable) {
if (isScissorTestEnabled() != enable) {
setValue(Key::EnableScissorTest, enable);
emit scissorTestChanged(enable);
}
}
bool
ApplicationSettings::isStencilTestEnabled() const {
return value(Key::EnableStencilTest, false).toBool();
}
void
ApplicationSettings::enableStencilTest(const bool enable) {
if (isStencilTestEnabled() != enable) {
setValue(Key::EnableStencilTest, enable);
emit stencilTestChanged(enable);
}
}
bool
ApplicationSettings::isDepthTestEnabled() const {
return value(Key::EnableDepthTest, true).toBool();
}
void
ApplicationSettings::enableDepthTest(const bool enable) {
if (isDepthTestEnabled() != enable) {
setValue(Key::EnableDepthTest, enable);
emit depthTestChanged(enable);
}
}
QStringList
ApplicationSettings::getAvailableLanguages() {
QStringList languages;
languages.append("English");
return languages;
}
QStringList
ApplicationSettings::getAvailableFramebufferResolutions() {
QStringList resolutions;
for (const auto resolution : Framebuffer::getAvailableResolutions()) {
resolutions.append(toString(resolution));
}
return resolutions;
}
bool
ApplicationSettings::contains(const Key key) const {
return QSettings::contains(ApplicationSettings::keyToString(key));
}
QVariant
ApplicationSettings::value(const Key key, const QVariant& defaultValue) const {
return QSettings::value(ApplicationSettings::keyToString(key), defaultValue);
}
void
ApplicationSettings::setValue(const Key key, const QVariant& value) {
QSettings::setValue(ApplicationSettings::keyToString(key), value);
}
QString
ApplicationSettings::keyToString(const Key key) {
switch (key) {
case Key::ShowBorderlessWindow:
return "showBorderlessWindow";
case Key::ShowFramesPerSecond:
return "showFramesPerSecond";
case Key::PrimitiveTopology:
return "primitiveTopology";
case Key::EnableClipping:
return "enableClipping";
case Key::EnableBackfaceCulling:
return "enableBackfaceCulling";
case Key::PolygonMode:
return "polygonMode";
case Key::ShadeModel:
return "shadeModel";
case Key::EnableScissorTest:
return "enableScissorTest";
case Key::EnableStencilTest:
return "enableStencilTest";
case Key::EnableDepthTest:
return "enableDepthTest";
default:
qFatal("[ApplicationSettings::keyToString] Undefined key!");
}
}
<commit_msg>Group application settings<commit_after>/*
* This file is part of Clockwork.
*
* Copyright (c) 2013-2016 Jeremy Othieno.
*
* The MIT License (MIT)
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "ApplicationSettings.hh"
#include "Application.hh"
#include "Framebuffer.hh"
#include "toString.hh"
#include <QStandardPaths>
using clockwork::ApplicationSettings;
ApplicationSettings::ApplicationSettings() :
QSettings(QString("./clockwork-preferences.pro.user"), Format::IniFormat) {
//QSettings(QString("%1/configuration.ini").arg(QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation)), Format::IniFormat) {
}
bool
ApplicationSettings::isFpsCounterVisible() const {
return value(Key::ShowFramesPerSecond, false).toBool();
}
void
ApplicationSettings::showFpsCounter(const bool visible) {
if (isFpsCounterVisible() != visible) {
setValue(Key::ShowFramesPerSecond, visible);
emit fpsCounterVisibilityChanged(visible);
}
}
bool
ApplicationSettings::isWindowBorderless() const {
return value(Key::ShowBorderlessWindow, false).toBool();
}
void
ApplicationSettings::showBorderlessWindow(const bool visible) {
if (isWindowBorderless() != visible) {
setValue(Key::ShowBorderlessWindow, visible);
emit windowBorderVisibilityChanged(visible);
}
}
int
ApplicationSettings::getPrimitiveTopologyOrdinal() const {
static_assert(std::is_same<int, clockwork::enum_traits<clockwork::PrimitiveTopology>::Ordinal>::value);
return value(
Key::PrimitiveTopology,
enum_traits<PrimitiveTopology>::ordinal(PrimitiveTopology::Triangle)
).toInt();
}
void
ApplicationSettings::setPrimitiveTopology(const int topology) {
if (getPrimitiveTopologyOrdinal() != topology) {
setValue(Key::PrimitiveTopology, topology);
emit primitiveTopologyChanged_(topology);
emit primitiveTopologyChanged(enum_traits<PrimitiveTopology>::enumerator(topology));
}
}
bool
ApplicationSettings::isClippingEnabled() const {
return value(Key::EnableClipping, true).toBool();
}
void
ApplicationSettings::enableClipping(const bool enable) {
if (isClippingEnabled() != enable) {
setValue(Key::EnableClipping, enable);
emit clippingToggled(enable);
}
}
bool
ApplicationSettings::isBackfaceCullingEnabled() const {
return value(Key::EnableBackfaceCulling, true).toBool();
}
void
ApplicationSettings::enableBackfaceCulling(const bool enable) {
if (isBackfaceCullingEnabled() != enable) {
setValue(Key::EnableBackfaceCulling, enable);
emit backfaceCullingToggled(enable);
}
}
int
ApplicationSettings::getPolygonModeOrdinal() const {
return value(
Key::PolygonMode,
enum_traits<PolygonMode>::ordinal(PolygonMode::Fill)
).toInt();
}
void
ApplicationSettings::setPolygonMode(const int mode) {
if (getPolygonModeOrdinal() != mode) {
setValue(Key::PolygonMode, mode);
emit polygonModeChanged_(mode);
emit polygonModeChanged(enum_traits<PolygonMode>::enumerator(mode));
}
}
int
ApplicationSettings::getShadeModelOrdinal() const {
return value(
Key::ShadeModel,
enum_traits<ShadeModel>::ordinal(ShadeModel::Flat)
).toInt();
}
void
ApplicationSettings::setShadeModel(const int model) {
if (getShadeModelOrdinal() != model) {
setValue(Key::ShadeModel, model);
emit shadeModelChanged_(model);
emit shadeModelChanged(enum_traits<ShadeModel>::enumerator(model));
}
}
bool
ApplicationSettings::isScissorTestEnabled() const {
return value(Key::EnableScissorTest, false).toBool();
}
void
ApplicationSettings::enableScissorTest(const bool enable) {
if (isScissorTestEnabled() != enable) {
setValue(Key::EnableScissorTest, enable);
emit scissorTestChanged(enable);
}
}
bool
ApplicationSettings::isStencilTestEnabled() const {
return value(Key::EnableStencilTest, false).toBool();
}
void
ApplicationSettings::enableStencilTest(const bool enable) {
if (isStencilTestEnabled() != enable) {
setValue(Key::EnableStencilTest, enable);
emit stencilTestChanged(enable);
}
}
bool
ApplicationSettings::isDepthTestEnabled() const {
return value(Key::EnableDepthTest, true).toBool();
}
void
ApplicationSettings::enableDepthTest(const bool enable) {
if (isDepthTestEnabled() != enable) {
setValue(Key::EnableDepthTest, enable);
emit depthTestChanged(enable);
}
}
QStringList
ApplicationSettings::getAvailableLanguages() {
QStringList languages;
languages.append("English");
return languages;
}
QStringList
ApplicationSettings::getAvailableFramebufferResolutions() {
QStringList resolutions;
for (const auto resolution : Framebuffer::getAvailableResolutions()) {
resolutions.append(toString(resolution));
}
return resolutions;
}
bool
ApplicationSettings::contains(const Key key) const {
return QSettings::contains(ApplicationSettings::keyToString(key));
}
QVariant
ApplicationSettings::value(const Key key, const QVariant& defaultValue) const {
return QSettings::value(ApplicationSettings::keyToString(key), defaultValue);
}
void
ApplicationSettings::setValue(const Key key, const QVariant& value) {
QSettings::setValue(ApplicationSettings::keyToString(key), value);
}
QString
ApplicationSettings::keyToString(const Key key) {
switch (key) {
case Key::ShowBorderlessWindow:
return "theme/ShowBorderlessWindow";
case Key::ShowFramesPerSecond:
return "debug/ShowFramesPerSecond";
case Key::PrimitiveTopology:
return "renderingcontext/PrimitiveTopology";
case Key::EnableClipping:
return "renderingcontext/EnableClipping";
case Key::EnableBackfaceCulling:
return "renderingcontext/EnableBackfaceCulling";
case Key::PolygonMode:
return "renderingcontext/PolygonMode";
case Key::ShadeModel:
return "renderingcontext/ShadeModel";
case Key::EnableScissorTest:
return "renderingcontext/EnableScissorTest";
case Key::EnableStencilTest:
return "renderingcontext/EnableStencilTest";
case Key::EnableDepthTest:
return "renderingcontext/EnableDepthTest";
default:
qFatal("[ApplicationSettings::keyToString] Undefined key!");
}
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* This file is part of the libkeynote 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 <cmath>
#include "KNTransformation.h"
#include "KNTransformationTest.h"
namespace test
{
using libkeynote::KNTransformation;
void KNTransformationTest::setUp()
{
}
void KNTransformationTest::tearDown()
{
}
void KNTransformationTest::testApplication()
{
using namespace libkeynote::transformations;
// identity - point
{
double x = 20;
double y = 40;
KNTransformation tr;
tr(x, y);
CPPUNIT_ASSERT_EQUAL(20.0, x);
CPPUNIT_ASSERT_EQUAL(40.0, y);
}
// identity - distance
{
double x = 20;
double y = 40;
KNTransformation tr;
tr(x, y, true);
CPPUNIT_ASSERT_EQUAL(20.0, x);
CPPUNIT_ASSERT_EQUAL(40.0, y);
}
// translation - point
{
double x = 20;
double y = 40;
KNTransformation tr = translate(10, 20);
tr(x, y);
CPPUNIT_ASSERT_EQUAL(30.0, x);
CPPUNIT_ASSERT_EQUAL(60.0, y);
}
// translation - distance
{
double x = 20;
double y = 40;
KNTransformation tr = translate(10, 20);
tr(x, y, true);
CPPUNIT_ASSERT_EQUAL(20.0, x);
CPPUNIT_ASSERT_EQUAL(40.0, y);
}
// non-translating transformation - point
{
double x = 20;
double y = 40;
KNTransformation tr = flip(true, false) * scale(0.25, 0.5);
tr(x, y);
CPPUNIT_ASSERT_EQUAL(-5.0, x);
CPPUNIT_ASSERT_EQUAL(20.0, y);
}
// non-translating transformation - distance
{
double x = 20;
double y = 40;
KNTransformation tr = flip(true, false) * scale(0.25, 0.5);
tr(x, y, true);
CPPUNIT_ASSERT_EQUAL(-5.0, x);
CPPUNIT_ASSERT_EQUAL(20.0, y);
}
}
void KNTransformationTest::testConstruction()
{
// identity
CPPUNIT_ASSERT(KNTransformation() == KNTransformation(1, 0, 0, 1, 0, 0));
using namespace libkeynote::transformations;
// centering
CPPUNIT_ASSERT(center(200, 100) == KNTransformation(1, 0, 0, 1, 100, 50));
CPPUNIT_ASSERT(decenter(200, 100) == KNTransformation(1, 0, 0, 1, -100, -50));
// flipping
CPPUNIT_ASSERT(flip(true, false) == KNTransformation(-1, 0, 0, 1, 0, 0));
CPPUNIT_ASSERT(flip(false, true) == KNTransformation(1, 0, 0, -1, 0, 0));
CPPUNIT_ASSERT(flip(true, true) == KNTransformation(-1, 0, 0, -1, 0, 0));
// rotating
CPPUNIT_ASSERT(rotate(M_PI / 2) == KNTransformation(0, 1, -1, 0, 0, 0));
// scaling
CPPUNIT_ASSERT(scale(2, 1) == KNTransformation(2, 0, 0, 1, 0, 0));
CPPUNIT_ASSERT(scale(1, 2) == KNTransformation(1, 0, 0, 2, 0, 0));
CPPUNIT_ASSERT(scale(3, 2) == KNTransformation(3, 0, 0, 2, 0, 0));
// shearing
CPPUNIT_ASSERT(shear(M_PI / 4, 0) == KNTransformation(1, 2, 0, 1, 0, 0));
CPPUNIT_ASSERT(shear(0, M_PI / 4) == KNTransformation(1, 0, 2, 1, 0, 0));
CPPUNIT_ASSERT(shear(M_PI / 4, M_PI / 4) == KNTransformation(1, 2, 2, 1, 0, 0));
// translating
CPPUNIT_ASSERT(translate(100, 0) == KNTransformation(1, 0, 0, 1, 100, 0));
CPPUNIT_ASSERT(translate(0, 100) == KNTransformation(1, 0, 0, 1, 0, 100));
CPPUNIT_ASSERT(translate(300, 100) == KNTransformation(1, 0, 0, 1, 300, 100));
}
void KNTransformationTest::testConstructionIdentity()
{
using namespace libkeynote::transformations;
CPPUNIT_ASSERT(center(0, 0) == KNTransformation());
CPPUNIT_ASSERT(decenter(0, 0) == KNTransformation());
CPPUNIT_ASSERT(flip(false, false) == KNTransformation());
CPPUNIT_ASSERT(rotate(0) == KNTransformation());
CPPUNIT_ASSERT(rotate(2 * M_PI) == KNTransformation());
CPPUNIT_ASSERT(scale(1, 1) == KNTransformation());
CPPUNIT_ASSERT(shear(0, 0) == KNTransformation());
CPPUNIT_ASSERT(translate(0, 0) == KNTransformation());
}
void KNTransformationTest::testConstructionFromGeometry()
{
// TODO: implement me
}
void KNTransformationTest::testIdentities()
{
// TODO: implement me
}
void KNTransformationTest::testInverseOperations()
{
using namespace libkeynote::transformations;
CPPUNIT_ASSERT(center(10, 20) * decenter(10, 20) == KNTransformation());
CPPUNIT_ASSERT(decenter(10, 20) * center(10, 20) == KNTransformation());
CPPUNIT_ASSERT(flip(true, false) * flip(true, false) == KNTransformation());
CPPUNIT_ASSERT(flip(false, true) * flip(false, true) == KNTransformation());
CPPUNIT_ASSERT(flip(true, true) * flip(true, true) == KNTransformation());
CPPUNIT_ASSERT(rotate(M_PI) * rotate(-M_PI) == KNTransformation());
CPPUNIT_ASSERT(scale(2, 1) * scale(0.5, 1) == KNTransformation());
CPPUNIT_ASSERT(scale(1, 2) * scale(1, 0.5) == KNTransformation());
CPPUNIT_ASSERT(scale(3, 2) * scale(1.0 / 3, 0.5) == KNTransformation());
// CPPUNIT_ASSERT(shear() == KNTransformation());
CPPUNIT_ASSERT(translate(10, 20) * translate(-10, -20) == KNTransformation());
}
void KNTransformationTest::testMultiplication()
{
using namespace libkeynote::transformations;
CPPUNIT_ASSERT(KNTransformation() * KNTransformation() == KNTransformation());
CPPUNIT_ASSERT(KNTransformation() * KNTransformation(1, 2, 3, 4, 5, 6) == KNTransformation(1, 2, 3, 4, 5, 6));
CPPUNIT_ASSERT(KNTransformation(1, 2, 3, 4, 5, 6) * KNTransformation() == KNTransformation(1, 2, 3, 4, 5, 6));
CPPUNIT_ASSERT(KNTransformation(1, 2, 3, 4, 5, 6) * KNTransformation(6, 5, 4, 3, 2, 1) == KNTransformation(14, 11, 34, 27, 56, 44));
}
CPPUNIT_TEST_SUITE_REGISTRATION(KNTransformationTest);
}
/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<commit_msg>disable temporarily<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* This file is part of the libkeynote 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 <cmath>
#include "KNTransformation.h"
#include "KNTransformationTest.h"
namespace test
{
using libkeynote::KNTransformation;
void KNTransformationTest::setUp()
{
}
void KNTransformationTest::tearDown()
{
}
void KNTransformationTest::testApplication()
{
using namespace libkeynote::transformations;
// identity - point
{
double x = 20;
double y = 40;
KNTransformation tr;
tr(x, y);
CPPUNIT_ASSERT_EQUAL(20.0, x);
CPPUNIT_ASSERT_EQUAL(40.0, y);
}
// identity - distance
{
double x = 20;
double y = 40;
KNTransformation tr;
tr(x, y, true);
CPPUNIT_ASSERT_EQUAL(20.0, x);
CPPUNIT_ASSERT_EQUAL(40.0, y);
}
// translation - point
{
double x = 20;
double y = 40;
KNTransformation tr = translate(10, 20);
tr(x, y);
CPPUNIT_ASSERT_EQUAL(30.0, x);
CPPUNIT_ASSERT_EQUAL(60.0, y);
}
// translation - distance
{
double x = 20;
double y = 40;
KNTransformation tr = translate(10, 20);
tr(x, y, true);
CPPUNIT_ASSERT_EQUAL(20.0, x);
CPPUNIT_ASSERT_EQUAL(40.0, y);
}
// non-translating transformation - point
{
double x = 20;
double y = 40;
KNTransformation tr = flip(true, false) * scale(0.25, 0.5);
tr(x, y);
CPPUNIT_ASSERT_EQUAL(-5.0, x);
CPPUNIT_ASSERT_EQUAL(20.0, y);
}
// non-translating transformation - distance
{
double x = 20;
double y = 40;
KNTransformation tr = flip(true, false) * scale(0.25, 0.5);
tr(x, y, true);
CPPUNIT_ASSERT_EQUAL(-5.0, x);
CPPUNIT_ASSERT_EQUAL(20.0, y);
}
}
void KNTransformationTest::testConstruction()
{
// identity
CPPUNIT_ASSERT(KNTransformation() == KNTransformation(1, 0, 0, 1, 0, 0));
using namespace libkeynote::transformations;
// centering
CPPUNIT_ASSERT(center(200, 100) == KNTransformation(1, 0, 0, 1, 100, 50));
CPPUNIT_ASSERT(decenter(200, 100) == KNTransformation(1, 0, 0, 1, -100, -50));
// flipping
CPPUNIT_ASSERT(flip(true, false) == KNTransformation(-1, 0, 0, 1, 0, 0));
CPPUNIT_ASSERT(flip(false, true) == KNTransformation(1, 0, 0, -1, 0, 0));
CPPUNIT_ASSERT(flip(true, true) == KNTransformation(-1, 0, 0, -1, 0, 0));
// rotating
CPPUNIT_ASSERT(rotate(M_PI / 2) == KNTransformation(0, 1, -1, 0, 0, 0));
// scaling
CPPUNIT_ASSERT(scale(2, 1) == KNTransformation(2, 0, 0, 1, 0, 0));
CPPUNIT_ASSERT(scale(1, 2) == KNTransformation(1, 0, 0, 2, 0, 0));
CPPUNIT_ASSERT(scale(3, 2) == KNTransformation(3, 0, 0, 2, 0, 0));
// shearing
// FIXME: find the problem and enable
// CPPUNIT_ASSERT(shear(M_PI / 4, 0) == KNTransformation(1, 2, 0, 1, 0, 0));
// CPPUNIT_ASSERT(shear(0, M_PI / 4) == KNTransformation(1, 0, 2, 1, 0, 0));
// CPPUNIT_ASSERT(shear(M_PI / 4, M_PI / 4) == KNTransformation(1, 2, 2, 1, 0, 0));
// translating
CPPUNIT_ASSERT(translate(100, 0) == KNTransformation(1, 0, 0, 1, 100, 0));
CPPUNIT_ASSERT(translate(0, 100) == KNTransformation(1, 0, 0, 1, 0, 100));
CPPUNIT_ASSERT(translate(300, 100) == KNTransformation(1, 0, 0, 1, 300, 100));
}
void KNTransformationTest::testConstructionIdentity()
{
using namespace libkeynote::transformations;
CPPUNIT_ASSERT(center(0, 0) == KNTransformation());
CPPUNIT_ASSERT(decenter(0, 0) == KNTransformation());
CPPUNIT_ASSERT(flip(false, false) == KNTransformation());
CPPUNIT_ASSERT(rotate(0) == KNTransformation());
CPPUNIT_ASSERT(rotate(2 * M_PI) == KNTransformation());
CPPUNIT_ASSERT(scale(1, 1) == KNTransformation());
CPPUNIT_ASSERT(shear(0, 0) == KNTransformation());
CPPUNIT_ASSERT(translate(0, 0) == KNTransformation());
}
void KNTransformationTest::testConstructionFromGeometry()
{
// TODO: implement me
}
void KNTransformationTest::testIdentities()
{
// TODO: implement me
}
void KNTransformationTest::testInverseOperations()
{
using namespace libkeynote::transformations;
CPPUNIT_ASSERT(center(10, 20) * decenter(10, 20) == KNTransformation());
CPPUNIT_ASSERT(decenter(10, 20) * center(10, 20) == KNTransformation());
CPPUNIT_ASSERT(flip(true, false) * flip(true, false) == KNTransformation());
CPPUNIT_ASSERT(flip(false, true) * flip(false, true) == KNTransformation());
CPPUNIT_ASSERT(flip(true, true) * flip(true, true) == KNTransformation());
CPPUNIT_ASSERT(rotate(M_PI) * rotate(-M_PI) == KNTransformation());
CPPUNIT_ASSERT(scale(2, 1) * scale(0.5, 1) == KNTransformation());
CPPUNIT_ASSERT(scale(1, 2) * scale(1, 0.5) == KNTransformation());
CPPUNIT_ASSERT(scale(3, 2) * scale(1.0 / 3, 0.5) == KNTransformation());
// CPPUNIT_ASSERT(shear() == KNTransformation());
CPPUNIT_ASSERT(translate(10, 20) * translate(-10, -20) == KNTransformation());
}
void KNTransformationTest::testMultiplication()
{
using namespace libkeynote::transformations;
CPPUNIT_ASSERT(KNTransformation() * KNTransformation() == KNTransformation());
CPPUNIT_ASSERT(KNTransformation() * KNTransformation(1, 2, 3, 4, 5, 6) == KNTransformation(1, 2, 3, 4, 5, 6));
CPPUNIT_ASSERT(KNTransformation(1, 2, 3, 4, 5, 6) * KNTransformation() == KNTransformation(1, 2, 3, 4, 5, 6));
CPPUNIT_ASSERT(KNTransformation(1, 2, 3, 4, 5, 6) * KNTransformation(6, 5, 4, 3, 2, 1) == KNTransformation(14, 11, 34, 27, 56, 44));
}
CPPUNIT_TEST_SUITE_REGISTRATION(KNTransformationTest);
}
/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<|endoftext|> |
<commit_before>// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "src/main/cpp/util/strings.h"
#include <wchar.h>
#include <memory>
#include <string>
#include <vector>
#include "googletest/include/gtest/gtest.h"
namespace blaze_util {
using std::string;
using std::unique_ptr;
using std::vector;
TEST(BlazeUtil, JoinStrings) {
vector<string> pieces;
string output;
JoinStrings(pieces, ' ', &output);
ASSERT_EQ("", output);
pieces.push_back("abc");
JoinStrings(pieces, ' ', &output);
ASSERT_EQ("abc", output);
pieces.push_back("");
JoinStrings(pieces, ' ', &output);
ASSERT_EQ("abc ", output);
pieces.push_back("def");
JoinStrings(pieces, ' ', &output);
ASSERT_EQ("abc def", output);
}
TEST(BlazeUtil, Split) {
string lines = "";
vector<string> pieces = Split(lines, '\n');
ASSERT_EQ(size_t(0), pieces.size());
lines = "foo";
pieces = Split(lines, '\n');
ASSERT_EQ(size_t(1), pieces.size());
ASSERT_EQ("foo", pieces[0]);
lines = "\nfoo";
pieces = Split(lines, '\n');
ASSERT_EQ(size_t(1), pieces.size());
ASSERT_EQ("foo", pieces[0]);
lines = "\n\n\nfoo";
pieces = Split(lines, '\n');
ASSERT_EQ(size_t(1), pieces.size());
ASSERT_EQ("foo", pieces[0]);
lines = "foo\n";
pieces = Split(lines, '\n');
ASSERT_EQ(size_t(1), pieces.size());
ASSERT_EQ("foo", pieces[0]);
lines = "foo\n\n\n";
pieces = Split(lines, '\n');
ASSERT_EQ(size_t(1), pieces.size());
ASSERT_EQ("foo", pieces[0]);
lines = "foo\nbar";
pieces = Split(lines, '\n');
ASSERT_EQ(size_t(2), pieces.size());
ASSERT_EQ("foo", pieces[0]);
ASSERT_EQ("bar", pieces[1]);
lines = "foo\n\nbar";
pieces = Split(lines, '\n');
ASSERT_EQ(size_t(2), pieces.size());
ASSERT_EQ("foo", pieces[0]);
ASSERT_EQ("bar", pieces[1]);
}
TEST(BlazeUtil, Replace) {
string line = "foo\\\nbar\nbaz";
Replace("\\\n", "", &line);
ASSERT_EQ("foobar\nbaz", line);
line = "foo\\\n\\\nbar";
Replace("\\\n", "", &line);
ASSERT_EQ("foobar", line);
line = "foo\\\r\nbar";
Replace("\\\r\n", "", &line);
ASSERT_EQ("foobar", line);
line = "\\\n\\\r\n";
Replace("\\\n", "", &line);
Replace("\\\r\n", "", &line);
ASSERT_EQ("", line);
line = "x:y:z";
Replace(":", "_C", &line);
ASSERT_EQ("x_Cy_Cz", line);
line = "x_::y_:__z";
Replace("_", "_U", &line);
Replace(":", "_C", &line);
ASSERT_EQ("x_U_C_Cy_U_C_U_Uz", line);
}
TEST(BlazeUtil, StripWhitespace) {
string str = " ";
StripWhitespace(&str);
ASSERT_EQ("", str);
str = " abc ";
StripWhitespace(&str);
ASSERT_EQ("abc", str);
str = "abc";
StripWhitespace(&str);
ASSERT_EQ("abc", str);
}
TEST(BlazeUtil, Tokenize) {
vector<string> result;
string str = "a b c";
Tokenize(str, '#', &result);
ASSERT_EQ(size_t(3), result.size());
EXPECT_EQ("a", result[0]);
EXPECT_EQ("b", result[1]);
EXPECT_EQ("c", result[2]);
str = "a 'b c'";
Tokenize(str, '#', &result);
ASSERT_EQ(size_t(2), result.size());
EXPECT_EQ("a", result[0]);
EXPECT_EQ("b c", result[1]);
str = "foo# bar baz";
Tokenize(str, '#', &result);
ASSERT_EQ(size_t(1), result.size());
EXPECT_EQ("foo", result[0]);
str = "foo # bar baz";
Tokenize(str, '#', &result);
ASSERT_EQ(size_t(1), result.size());
EXPECT_EQ("foo", result[0]);
str = "#bar baz";
Tokenize(str, '#', &result);
ASSERT_EQ(size_t(0), result.size());
str = "#";
Tokenize(str, '#', &result);
ASSERT_EQ(size_t(0), result.size());
str = " \tfirst second / ";
Tokenize(str, 0, &result);
ASSERT_EQ(size_t(3), result.size());
EXPECT_EQ("first", result[0]);
EXPECT_EQ("second", result[1]);
EXPECT_EQ("/", result[2]);
str = " \tfirst second / ";
Tokenize(str, '/', &result);
ASSERT_EQ(size_t(2), result.size());
EXPECT_EQ("first", result[0]);
EXPECT_EQ("second", result[1]);
str = "first \"second' third\" fourth";
Tokenize(str, '/', &result);
ASSERT_EQ(size_t(3), result.size());
EXPECT_EQ("first", result[0]);
EXPECT_EQ("second' third", result[1]);
EXPECT_EQ("fourth", result[2]);
str = "first 'second\" third' fourth";
Tokenize(str, '/', &result);
ASSERT_EQ(size_t(3), result.size());
EXPECT_EQ("first", result[0]);
EXPECT_EQ("second\" third", result[1]);
EXPECT_EQ("fourth", result[2]);
str = "\\ this\\ is\\ one\\'\\ token";
Tokenize(str, 0, &result);
ASSERT_EQ(size_t(1), result.size());
EXPECT_EQ(" this is one' token", result[0]);
str = "\\ this\\ is\\ one\\'\\ token\\";
Tokenize(str, 0, &result);
ASSERT_EQ(size_t(1), result.size());
EXPECT_EQ(" this is one' token", result[0]);
str = "unterminated \" runs to end of line";
Tokenize(str, 0, &result);
ASSERT_EQ(size_t(2), result.size());
EXPECT_EQ("unterminated", result[0]);
EXPECT_EQ(" runs to end of line", result[1]);
str = "";
Tokenize(str, 0, &result);
ASSERT_EQ(size_t(0), result.size());
str = "one two\'s three";
Tokenize(str, 0, &result);
ASSERT_EQ(size_t(2), result.size());
EXPECT_EQ("one", result[0]);
EXPECT_EQ("twos three", result[1]);
str = "one \'two three";
Tokenize(str, 0, &result);
ASSERT_EQ(size_t(2), result.size());
EXPECT_EQ("one", result[0]);
EXPECT_EQ("two three", result[1]);
}
static vector<string> SplitQuoted(const string &contents,
const char delimeter) {
vector<string> result;
SplitQuotedStringUsing(contents, delimeter, &result);
return result;
}
TEST(BlazeUtil, SplitQuoted) {
string lines = "";
vector<string> pieces = SplitQuoted(lines, '\n');
ASSERT_EQ(size_t(0), pieces.size());
// Same behaviour without quotes as Split
lines = "foo";
pieces = SplitQuoted(lines, ' ');
ASSERT_EQ(size_t(1), pieces.size());
ASSERT_EQ("foo", pieces[0]);
lines = " foo";
pieces = SplitQuoted(lines, ' ');
ASSERT_EQ(size_t(1), pieces.size());
ASSERT_EQ("foo", pieces[0]);
lines = " foo";
pieces = SplitQuoted(lines, ' ');
ASSERT_EQ(size_t(1), pieces.size());
ASSERT_EQ("foo", pieces[0]);
lines = "foo ";
pieces = SplitQuoted(lines, ' ');
ASSERT_EQ(size_t(1), pieces.size());
ASSERT_EQ("foo", pieces[0]);
lines = "foo ";
pieces = SplitQuoted(lines, ' ');
ASSERT_EQ(size_t(1), pieces.size());
ASSERT_EQ("foo", pieces[0]);
lines = "foo bar";
pieces = SplitQuoted(lines, ' ');
ASSERT_EQ(size_t(2), pieces.size());
ASSERT_EQ("foo", pieces[0]);
ASSERT_EQ("bar", pieces[1]);
lines = "foo bar";
pieces = SplitQuoted(lines, ' ');
ASSERT_EQ(size_t(2), pieces.size());
ASSERT_EQ("foo", pieces[0]);
ASSERT_EQ("bar", pieces[1]);
// Test with quotes
lines = "' 'foo";
pieces = SplitQuoted(lines, ' ');
ASSERT_EQ(size_t(1), pieces.size());
ASSERT_EQ("' 'foo", pieces[0]);
lines = " ' ' foo";
pieces = SplitQuoted(lines, ' ');
ASSERT_EQ(size_t(2), pieces.size());
ASSERT_EQ("' '", pieces[0]);
ASSERT_EQ("foo", pieces[1]);
lines = "foo' \\' ' ";
pieces = SplitQuoted(lines, ' ');
ASSERT_EQ(size_t(1), pieces.size());
ASSERT_EQ("foo' \\' '", pieces[0]);
lines = "foo'\\'\" ' ";
pieces = SplitQuoted(lines, ' ');
ASSERT_EQ(size_t(1), pieces.size());
ASSERT_EQ("foo'\\'\" '", pieces[0]);
}
TEST(BlazeUtil, StringPrintf) {
string out;
StringPrintf(&out, "%s %s", "a", "b");
EXPECT_EQ("a b", out);
}
TEST(BlazeUtil, EndsWithTest) {
ASSERT_TRUE(ends_with("", ""));
ASSERT_TRUE(ends_with(L"", L""));
ASSERT_TRUE(ends_with("abc", "bc"));
ASSERT_TRUE(ends_with(L"abc", L"bc"));
// prefix matches but suffix doesn't
ASSERT_FALSE(ends_with("abc", "bd"));
ASSERT_FALSE(ends_with(L"abc", L"bd"));
// suffix matches but prefix doesn't
ASSERT_FALSE(ends_with("abc", "dc"));
ASSERT_FALSE(ends_with(L"abc", L"dc"));
// full match
ASSERT_TRUE(ends_with("abc", "abc"));
ASSERT_TRUE(ends_with(L"abc", L"abc"));
// bigger "needle" than "haystack"
ASSERT_FALSE(ends_with("bc", "abc"));
ASSERT_FALSE(ends_with(L"bc", L"abc"));
ASSERT_FALSE(ends_with("bc", "def"));
ASSERT_FALSE(ends_with(L"bc", L"def"));
}
} // namespace blaze_util
<commit_msg>Automatic code cleanup.<commit_after>// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "src/main/cpp/util/strings.h"
#include <wchar.h>
#include <memory>
#include <string>
#include <vector>
#include "googletest/include/gtest/gtest.h"
namespace blaze_util {
using std::string;
using std::vector;
TEST(BlazeUtil, JoinStrings) {
vector<string> pieces;
string output;
JoinStrings(pieces, ' ', &output);
ASSERT_EQ("", output);
pieces.push_back("abc");
JoinStrings(pieces, ' ', &output);
ASSERT_EQ("abc", output);
pieces.push_back("");
JoinStrings(pieces, ' ', &output);
ASSERT_EQ("abc ", output);
pieces.push_back("def");
JoinStrings(pieces, ' ', &output);
ASSERT_EQ("abc def", output);
}
TEST(BlazeUtil, Split) {
string lines = "";
vector<string> pieces = Split(lines, '\n');
ASSERT_EQ(size_t(0), pieces.size());
lines = "foo";
pieces = Split(lines, '\n');
ASSERT_EQ(size_t(1), pieces.size());
ASSERT_EQ("foo", pieces[0]);
lines = "\nfoo";
pieces = Split(lines, '\n');
ASSERT_EQ(size_t(1), pieces.size());
ASSERT_EQ("foo", pieces[0]);
lines = "\n\n\nfoo";
pieces = Split(lines, '\n');
ASSERT_EQ(size_t(1), pieces.size());
ASSERT_EQ("foo", pieces[0]);
lines = "foo\n";
pieces = Split(lines, '\n');
ASSERT_EQ(size_t(1), pieces.size());
ASSERT_EQ("foo", pieces[0]);
lines = "foo\n\n\n";
pieces = Split(lines, '\n');
ASSERT_EQ(size_t(1), pieces.size());
ASSERT_EQ("foo", pieces[0]);
lines = "foo\nbar";
pieces = Split(lines, '\n');
ASSERT_EQ(size_t(2), pieces.size());
ASSERT_EQ("foo", pieces[0]);
ASSERT_EQ("bar", pieces[1]);
lines = "foo\n\nbar";
pieces = Split(lines, '\n');
ASSERT_EQ(size_t(2), pieces.size());
ASSERT_EQ("foo", pieces[0]);
ASSERT_EQ("bar", pieces[1]);
}
TEST(BlazeUtil, Replace) {
string line = "foo\\\nbar\nbaz";
Replace("\\\n", "", &line);
ASSERT_EQ("foobar\nbaz", line);
line = "foo\\\n\\\nbar";
Replace("\\\n", "", &line);
ASSERT_EQ("foobar", line);
line = "foo\\\r\nbar";
Replace("\\\r\n", "", &line);
ASSERT_EQ("foobar", line);
line = "\\\n\\\r\n";
Replace("\\\n", "", &line);
Replace("\\\r\n", "", &line);
ASSERT_EQ("", line);
line = "x:y:z";
Replace(":", "_C", &line);
ASSERT_EQ("x_Cy_Cz", line);
line = "x_::y_:__z";
Replace("_", "_U", &line);
Replace(":", "_C", &line);
ASSERT_EQ("x_U_C_Cy_U_C_U_Uz", line);
}
TEST(BlazeUtil, StripWhitespace) {
string str = " ";
StripWhitespace(&str);
ASSERT_EQ("", str);
str = " abc ";
StripWhitespace(&str);
ASSERT_EQ("abc", str);
str = "abc";
StripWhitespace(&str);
ASSERT_EQ("abc", str);
}
TEST(BlazeUtil, Tokenize) {
vector<string> result;
string str = "a b c";
Tokenize(str, '#', &result);
ASSERT_EQ(size_t(3), result.size());
EXPECT_EQ("a", result[0]);
EXPECT_EQ("b", result[1]);
EXPECT_EQ("c", result[2]);
str = "a 'b c'";
Tokenize(str, '#', &result);
ASSERT_EQ(size_t(2), result.size());
EXPECT_EQ("a", result[0]);
EXPECT_EQ("b c", result[1]);
str = "foo# bar baz";
Tokenize(str, '#', &result);
ASSERT_EQ(size_t(1), result.size());
EXPECT_EQ("foo", result[0]);
str = "foo # bar baz";
Tokenize(str, '#', &result);
ASSERT_EQ(size_t(1), result.size());
EXPECT_EQ("foo", result[0]);
str = "#bar baz";
Tokenize(str, '#', &result);
ASSERT_EQ(size_t(0), result.size());
str = "#";
Tokenize(str, '#', &result);
ASSERT_EQ(size_t(0), result.size());
str = " \tfirst second / ";
Tokenize(str, 0, &result);
ASSERT_EQ(size_t(3), result.size());
EXPECT_EQ("first", result[0]);
EXPECT_EQ("second", result[1]);
EXPECT_EQ("/", result[2]);
str = " \tfirst second / ";
Tokenize(str, '/', &result);
ASSERT_EQ(size_t(2), result.size());
EXPECT_EQ("first", result[0]);
EXPECT_EQ("second", result[1]);
str = "first \"second' third\" fourth";
Tokenize(str, '/', &result);
ASSERT_EQ(size_t(3), result.size());
EXPECT_EQ("first", result[0]);
EXPECT_EQ("second' third", result[1]);
EXPECT_EQ("fourth", result[2]);
str = "first 'second\" third' fourth";
Tokenize(str, '/', &result);
ASSERT_EQ(size_t(3), result.size());
EXPECT_EQ("first", result[0]);
EXPECT_EQ("second\" third", result[1]);
EXPECT_EQ("fourth", result[2]);
str = "\\ this\\ is\\ one\\'\\ token";
Tokenize(str, 0, &result);
ASSERT_EQ(size_t(1), result.size());
EXPECT_EQ(" this is one' token", result[0]);
str = "\\ this\\ is\\ one\\'\\ token\\";
Tokenize(str, 0, &result);
ASSERT_EQ(size_t(1), result.size());
EXPECT_EQ(" this is one' token", result[0]);
str = "unterminated \" runs to end of line";
Tokenize(str, 0, &result);
ASSERT_EQ(size_t(2), result.size());
EXPECT_EQ("unterminated", result[0]);
EXPECT_EQ(" runs to end of line", result[1]);
str = "";
Tokenize(str, 0, &result);
ASSERT_EQ(size_t(0), result.size());
str = "one two\'s three";
Tokenize(str, 0, &result);
ASSERT_EQ(size_t(2), result.size());
EXPECT_EQ("one", result[0]);
EXPECT_EQ("twos three", result[1]);
str = "one \'two three";
Tokenize(str, 0, &result);
ASSERT_EQ(size_t(2), result.size());
EXPECT_EQ("one", result[0]);
EXPECT_EQ("two three", result[1]);
}
static vector<string> SplitQuoted(const string &contents,
const char delimeter) {
vector<string> result;
SplitQuotedStringUsing(contents, delimeter, &result);
return result;
}
TEST(BlazeUtil, SplitQuoted) {
string lines = "";
vector<string> pieces = SplitQuoted(lines, '\n');
ASSERT_EQ(size_t(0), pieces.size());
// Same behaviour without quotes as Split
lines = "foo";
pieces = SplitQuoted(lines, ' ');
ASSERT_EQ(size_t(1), pieces.size());
ASSERT_EQ("foo", pieces[0]);
lines = " foo";
pieces = SplitQuoted(lines, ' ');
ASSERT_EQ(size_t(1), pieces.size());
ASSERT_EQ("foo", pieces[0]);
lines = " foo";
pieces = SplitQuoted(lines, ' ');
ASSERT_EQ(size_t(1), pieces.size());
ASSERT_EQ("foo", pieces[0]);
lines = "foo ";
pieces = SplitQuoted(lines, ' ');
ASSERT_EQ(size_t(1), pieces.size());
ASSERT_EQ("foo", pieces[0]);
lines = "foo ";
pieces = SplitQuoted(lines, ' ');
ASSERT_EQ(size_t(1), pieces.size());
ASSERT_EQ("foo", pieces[0]);
lines = "foo bar";
pieces = SplitQuoted(lines, ' ');
ASSERT_EQ(size_t(2), pieces.size());
ASSERT_EQ("foo", pieces[0]);
ASSERT_EQ("bar", pieces[1]);
lines = "foo bar";
pieces = SplitQuoted(lines, ' ');
ASSERT_EQ(size_t(2), pieces.size());
ASSERT_EQ("foo", pieces[0]);
ASSERT_EQ("bar", pieces[1]);
// Test with quotes
lines = "' 'foo";
pieces = SplitQuoted(lines, ' ');
ASSERT_EQ(size_t(1), pieces.size());
ASSERT_EQ("' 'foo", pieces[0]);
lines = " ' ' foo";
pieces = SplitQuoted(lines, ' ');
ASSERT_EQ(size_t(2), pieces.size());
ASSERT_EQ("' '", pieces[0]);
ASSERT_EQ("foo", pieces[1]);
lines = "foo' \\' ' ";
pieces = SplitQuoted(lines, ' ');
ASSERT_EQ(size_t(1), pieces.size());
ASSERT_EQ("foo' \\' '", pieces[0]);
lines = "foo'\\'\" ' ";
pieces = SplitQuoted(lines, ' ');
ASSERT_EQ(size_t(1), pieces.size());
ASSERT_EQ("foo'\\'\" '", pieces[0]);
}
TEST(BlazeUtil, StringPrintf) {
string out;
StringPrintf(&out, "%s %s", "a", "b");
EXPECT_EQ("a b", out);
}
TEST(BlazeUtil, EndsWithTest) {
ASSERT_TRUE(ends_with("", ""));
ASSERT_TRUE(ends_with(L"", L""));
ASSERT_TRUE(ends_with("abc", "bc"));
ASSERT_TRUE(ends_with(L"abc", L"bc"));
// prefix matches but suffix doesn't
ASSERT_FALSE(ends_with("abc", "bd"));
ASSERT_FALSE(ends_with(L"abc", L"bd"));
// suffix matches but prefix doesn't
ASSERT_FALSE(ends_with("abc", "dc"));
ASSERT_FALSE(ends_with(L"abc", L"dc"));
// full match
ASSERT_TRUE(ends_with("abc", "abc"));
ASSERT_TRUE(ends_with(L"abc", L"abc"));
// bigger "needle" than "haystack"
ASSERT_FALSE(ends_with("bc", "abc"));
ASSERT_FALSE(ends_with(L"bc", L"abc"));
ASSERT_FALSE(ends_with("bc", "def"));
ASSERT_FALSE(ends_with(L"bc", L"def"));
}
} // namespace blaze_util
<|endoftext|> |
<commit_before>/*"name": "sensorflare",
Author: "LPFraile <[email protected]>",
License: "BSD",
Version: "0.0.1",
Description: "Include your Particle Core on Sensorflare"
File: source file
*/
#include "sensorflare.h"
//Structure to keep in EEPROM memory the value of uotput pins
struct dataStruct
{
int digitalPin[8];
struct pwmPin{
int pin;
int value;
};
pwmPin pwmoutput[8];
};
union {
dataStruct outputData;
char eeArray[sizeof(outputData)];
} EEPROMData;
char stringvalue[40];
// Constructor
//Constructor of Digital Output controler elements
SensorFlare::DigitalOut::DigitalOut(int _number)
{
number = _number;
state = LOW;
}
//Constructor of PWM Output controler elements
SensorFlare::PWMOut::PWMOut(int _number)
{
number = _number;
}
//Constructor of Variable publish element by defult PUBLIC
SensorFlare::VarPublish::VarPublish(String _name)
{
name = _name;
lastTime=0UL;
property="PUBLIC";
}
//Constructor of Variable publish element by choose between PUBLIC and PRIVATE
SensorFlare::VarPublish::VarPublish(String _name,String _property)
{
name = _name;
lastTime=0UL;
property=_property;
}
// Initializers that should be called in the `setup()` function
//Initizalize the pin as output and the last value received
void SensorFlare::DigitalOut::begin()
{
pinMode(number, OUTPUT);
Spark.function("digital",controlPin);
//Initialize the output with the last receive value from SensorFlare
readEEPROM();
digitalWrite(number,EEPROMData.outputData.digitalPin[number]);
}
//Initizalize the pin as PWM output and the last value received
void SensorFlare::PWMOut::begin()
{
pinMode(number, OUTPUT);
Spark.function("pwm",controlPWM);
//Initialize the output with the last receive value from SensorFlare
readEEPROM();
analogWrite(number,EEPROMData.outputData.digitalPin[number]);
for (int i=0;i<8;i++){
if (EEPROMData.outputData.pwmoutput[i].pin==number)
{
analogWrite(number,EEPROMData.outputData.pwmoutput[i].value);
value=EEPROMData.outputData.pwmoutput[i].value;
}
}
}
// Main API functions that the library provides
// typically called in `loop()`
//Method that publish the variable (int) _val every _period time
int SensorFlare::VarPublish::Publish(int _val, int _periode)
{
var_int=_val;
periode=_periode*1000;
unsigned long now = millis();
if (property=="PRIVATE"){
if (now-lastTime>periode) {
lastTime = now;
sprintf(stringvalue,"%u",var_int);
Spark.publish(name,stringvalue,60,PRIVATE);
}
return 0;
}
else if (property=="PUBLIC"){
if (now-lastTime>periode) {
lastTime = now;
sprintf(stringvalue,"%u",var_int);
Spark.publish(name,stringvalue);
}
return 1;
}
else{
return -1;//Return -1 if the variable could be publish because a mistake on the property
}
}
//Method that publish the variable (float) _val every _period time
int SensorFlare::VarPublish::Publish(float _val, int _periode)
{
var_float=_val;
periode=_periode*1000;
unsigned long now = millis();
if (property=="PRIVATE"){
if (now-lastTime>periode) {
lastTime = now;
sprintf(stringvalue,"%f",var_float);
Spark.publish(name,stringvalue,60,PRIVATE);
}
return 0;
}
else if (property=="PUBLIC"){
if (now-lastTime>periode) {
lastTime = now;
sprintf(stringvalue,"%f",var_float);
Spark.publish(name,stringvalue);
}
return 1;
}
else{
return -1;
}
}
//Function for open/close pin
//The structure of the receive command is pin:state where state is on or off
int controlPin(String command) {
int index=command.indexOf(":");
String pinout=command.substring(0,index);
String state=command.substring(index+1);
int pin=pinout.toInt();
if (state=="on") {
digitalWrite(pin,HIGH);
EEPROMData.outputData.digitalPin[pin]=1;
writeEEPROM();
return 1;
}
else if (state=="off") {
digitalWrite(pin,LOW);
EEPROMData.outputData.digitalPin[pin]=0;
writeEEPROM();
return 0;
}
else {
//EEPROMData.eevar.state[pin]=-1;
return -1;//return -1 if the command received has not the correct structure
}
}
//Function that control the specific brightness of the led conected to specific pwmpin.
//the structure of the command is pwmpin:brightness
int controlPWM(String command) {
int index=command.indexOf(":");
String pwmpin=command.substring(0,index);
String val=command.substring(index+1);
int pin=pwmpin.toInt();
int value=val.toInt();
if (value<256&&value>=0){
analogWrite(pin,value);
if (pin==10){
EEPROMData.outputData.pwmoutput[2].pin=pin;
EEPROMData.outputData.pwmoutput[2].value=value;
}
else if (pin==11){
EEPROMData.outputData.pwmoutput[3].pin=pin;
EEPROMData.outputData.pwmoutput[3].value=value;
}
else if (pin>13&&pin<18){
EEPROMData.outputData.pwmoutput[pin-10].pin=pin;
EEPROMData.outputData.pwmoutput[pin-10].value=value;
}
else if (pin<2){
EEPROMData.outputData.pwmoutput[pin].pin=pin;
EEPROMData.outputData.pwmoutput[pin].value=value;
}
writeEEPROM();
return value;
}
else{
return -1;// return -1 if the pin sended on the command is not the PWM output ones
}
}
//function to read from the EEPROM
void readEEPROM(void) {
for (int i=0; i<sizeof(dataStruct); i++) {
EEPROMData.eeArray[i] = EEPROM.read(i);
}
}
//function to write on the EEPROM
void writeEEPROM(void) {
for (int i=0; i<sizeof(dataStruct); i++) {
EEPROM.write(i, EEPROMData.eeArray[i]);
}
}
<commit_msg>Update sensorflare.cpp<commit_after>/*"name": "sensorflare",
Author: "LPFraile <[email protected]>",
License: "BSD",
Version: "0.0.1",
Description: "Include your Particle Core on Sensorflare"
File: source file
*/
#include "sensorflare.h"
//Structure to keep in EEPROM memory the value of output pins
struct dataStruct
{
int digitalPin[8];
struct pwmPin{
int pin;
int value;
};
pwmPin pwmoutput[8];
};
union {
dataStruct outputData;
char eeArray[sizeof(outputData)];
} EEPROMData;
char stringvalue[40];
// Constructor
//Constructor of Digital Output controller elements
SensorFlare::DigitalOut::DigitalOut(int _number)
{
number = _number;
state = LOW;
}
//Constructor of PWM Output controller elements
SensorFlare::PWMOut::PWMOut(int _number)
{
number = _number;
}
//Constructor of Variable publish element by defult PUBLIC
SensorFlare::VarPublish::VarPublish(String _name)
{
name = _name;
lastTime=0UL;
property="PUBLIC";
}
//Constructor of Variable publish element by choose between PUBLIC and PRIVATE
SensorFlare::VarPublish::VarPublish(String _name,String _property)
{
name = _name;
lastTime=0UL;
property=_property;
}
//Initializers that should be called in the `setup()` function
//Initizalize the pin as output and the last value received
void SensorFlare::DigitalOut::begin()
{
pinMode(number, OUTPUT);
Spark.function("digital",controlPin);
//Initialize the output with the last receive value from SensorFlare
readEEPROM();
digitalWrite(number,EEPROMData.outputData.digitalPin[number]);
}
//Initizalize the pin as PWM output and the last value received
void SensorFlare::PWMOut::begin()
{
pinMode(number, OUTPUT);
Spark.function("pwm",controlPWM);
//Initialize the output with the last receive value from Sensorflare
readEEPROM();
analogWrite(number,EEPROMData.outputData.digitalPin[number]);
for (int i=0;i<8;i++){
if (EEPROMData.outputData.pwmoutput[i].pin==number)
{
analogWrite(number,EEPROMData.outputData.pwmoutput[i].value);
value=EEPROMData.outputData.pwmoutput[i].value;
}
}
}
// Main API functions that the library provides
// typically called in `loop()`
//Method that publish the variable (int) _val every _period time
int SensorFlare::VarPublish::Publish(int _val, int _periode)
{
var_int=_val;
periode=_periode*1000;
unsigned long now = millis();
if (property=="PRIVATE"){
if (now-lastTime>periode) {
lastTime = now;
sprintf(stringvalue,"%u",var_int);
Spark.publish(name,stringvalue,60,PRIVATE);
}
return 0;
}
else if (property=="PUBLIC"){
if (now-lastTime>periode) {
lastTime = now;
sprintf(stringvalue,"%u",var_int);
Spark.publish(name,stringvalue);
}
return 1;
}
else{
return -1;//Return -1 if the variable could be publish because a mistake on the property
}
}
//Method that publish the variable (float) _val every _period time
int SensorFlare::VarPublish::Publish(float _val, int _periode)
{
var_float=_val;
periode=_periode*1000;
unsigned long now = millis();
if (property=="PRIVATE"){
if (now-lastTime>periode) {
lastTime = now;
sprintf(stringvalue,"%f",var_float);
Spark.publish(name,stringvalue,60,PRIVATE);
}
return 0;
}
else if (property=="PUBLIC"){
if (now-lastTime>periode) {
lastTime = now;
sprintf(stringvalue,"%f",var_float);
Spark.publish(name,stringvalue);
}
return 1;
}
else{
return -1;
}
}
//Function for open/close pin
//The structure of the receive command is pin: state where state is on or off
int controlPin(String command) {
int index=command.indexOf(":");
String pinout=command.substring(0,index);
String state=command.substring(index+1);
int pin=pinout.toInt();
if (state=="on") {
digitalWrite(pin,HIGH);
EEPROMData.outputData.digitalPin[pin]=1;
writeEEPROM();
return 1;
}
else if (state=="off") {
digitalWrite(pin,LOW);
EEPROMData.outputData.digitalPin[pin]=0;
writeEEPROM();
return 0;
}
else {
//EEPROMData.eevar.state[pin]=-1;
return -1;//return -1 if the command received has not the correct structure
}
}
//Function that control the specific brightness of the led conected to specific pwmpin.
//the structure of the command is pwmpin:brightness
int controlPWM(String command) {
int index=command.indexOf(":");
String pwmpin=command.substring(0,index);
String val=command.substring(index+1);
int pin=pwmpin.toInt();
int value=val.toInt();
if (value<256&&value>=0){
analogWrite(pin,value);
if (pin==10){
EEPROMData.outputData.pwmoutput[2].pin=pin;
EEPROMData.outputData.pwmoutput[2].value=value;
}
else if (pin==11){
EEPROMData.outputData.pwmoutput[3].pin=pin;
EEPROMData.outputData.pwmoutput[3].value=value;
}
else if (pin>13&&pin<18){
EEPROMData.outputData.pwmoutput[pin-10].pin=pin;
EEPROMData.outputData.pwmoutput[pin-10].value=value;
}
else if (pin<2){
EEPROMData.outputData.pwmoutput[pin].pin=pin;
EEPROMData.outputData.pwmoutput[pin].value=value;
}
writeEEPROM();
return value;
}
else{
return -1;// return -1 if the pin sended on the command is not the PWM output ones
}
}
//function to read from the EEPROM
void readEEPROM(void) {
for (int i=0; i<sizeof(dataStruct); i++) {
EEPROMData.eeArray[i] = EEPROM.read(i);
}
}
//function to write on the EEPROM
void writeEEPROM(void) {
for (int i=0; i<sizeof(dataStruct); i++) {
EEPROM.write(i, EEPROMData.eeArray[i]);
}
}
<|endoftext|> |
<commit_before>
#include <GameData.h>
#include <File.h>
#include <DatCat.h>
#include <ExdData.h>
#include <ExdCat.h>
#include <Exd.h>
#include <Exh.h>
#include <iostream>
#include <cctype>
#include <set>
#include <src/servers/Server_Common/Exd/ExdData.h>
#include <src/servers/Server_Common/Logging/Logger.h>
#include <boost/range/algorithm/remove_if.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <fstream>
Core::Logger g_log;
Core::Data::ExdData g_exdData;
const std::string datLocation( "/opt/sapphire_3_15_0/bin/sqpack" );
//const std::string datLocation( "C:\\SquareEnix\\FINAL FANTASY XIV - A Realm Reborn\\game\\sqpack\\ffxiv" );
std::string generateEnum( const std::string& exd )
{
auto& cat = g_exdData.m_exd_data->get_category( exd );
auto exh = cat.get_header();
auto exhMem = exh.get_exh_members();
for( auto member : exhMem )
{
g_log.info( std::to_string( static_cast< uint8_t >( member.type ) ) + "\n" );
}
return "";
}
int main()
{
g_log.init();
g_log.info( "Setting up EXD data" );
if( !g_exdData.init( datLocation ) )
{
g_log.fatal( "Error setting up EXD data " );
return 0;
}
std::string result =
"/* This file has been automatically generated.\n Changes will be lost upon regeneration.\n To change the content edit tools/exd_struct_gen */\n";
result += generateEnum( "Quest" );
g_log.info( result );
return 0;
}
<commit_msg>Actually generate a pseudostruct<commit_after>
#include <GameData.h>
#include <File.h>
#include <DatCat.h>
#include <ExdData.h>
#include <ExdCat.h>
#include <Exd.h>
#include <Exh.h>
#include <iostream>
#include <cctype>
#include <set>
#include <src/servers/Server_Common/Exd/ExdData.h>
#include <src/servers/Server_Common/Logging/Logger.h>
#include <boost/range/algorithm/remove_if.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <fstream>
Core::Logger g_log;
Core::Data::ExdData g_exdData;
const std::string datLocation( "/opt/sapphire_3_15_0/bin/sqpack" );
//const std::string datLocation( "C:\\SquareEnix\\FINAL FANTASY XIV - A Realm Reborn\\game\\sqpack\\ffxiv" );
std::map< uint8_t, std::string > g_typeMap;
std::string generateEnum( const std::string& exd )
{
auto& cat = g_exdData.m_exd_data->get_category( exd );
auto exh = cat.get_header();
auto exhMem = exh.get_exh_members();
int count = 0;
std::string result = "struct " + exd +"\n{\n";
for( auto member : exhMem )
{
auto typei = static_cast< uint8_t >( member.type );
auto it = g_typeMap.find( typei );
std::string type;
if( it != g_typeMap.end() )
type = it->second;
else
type = "bool(" + std::to_string( static_cast< uint8_t >( member.type ) ) + ")";
result += " " + type + " field" + std::to_string( count ) + ";\n";
count++;
}
result += "};\n";
return result;
}
int main()
{
g_typeMap[0] = "char";
g_typeMap[1] = "bool";
g_typeMap[2] = "int8_t";
g_typeMap[3] = "uint8_t";
g_typeMap[4] = "int16_t";
g_typeMap[5] = "uint16_t";
g_typeMap[6] = "int32";
g_typeMap[7] = "uint32_t";
g_typeMap[9] = "float";
g_typeMap[11] = "uint64_t";
g_log.init();
g_log.info( "Setting up EXD data" );
if( !g_exdData.init( datLocation ) )
{
g_log.fatal( "Error setting up EXD data " );
return 0;
}
std::string result =
"/* This file has been automatically generated.\n Changes will be lost upon regeneration.\n To change the content edit tools/exd_struct_gen */\n";
result += generateEnum( "TerritoryType" );
g_log.info( result );
return 0;
}
<|endoftext|> |
<commit_before>//Copyright (c) 2017 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "MinimumSpanningTree.h"
namespace cura
{
MinimumSpanningTree::MinimumSpanningTree(std::unordered_set<Point> vertices) : adjacency_graph(prim(vertices))
{
//Just copy over the fields.
}
MinimumSpanningTree::Edge::Edge(const Point start, const Point end) : start(start), end(end)
{
//Just copy over the fields.
}
auto MinimumSpanningTree::prim(std::unordered_set<Point> vertices) const -> AdjacencyGraph_t
{
AdjacencyGraph_t result;
if (vertices.empty())
{
return result; //No vertices, so we can't create edges either.
}
result.reserve(vertices.size());
std::vector<Point> vertices_list;
for (Point vertex : vertices)
{
vertices_list.push_back(vertex);
}
Point first_point = vertices_list[0];
result[first_point] = std::vector<MinimumSpanningTree::Edge>(); //Start with one vertex in the tree.
if (vertices_list.size() == 1)
{
return result; //If there's only one vertex, we can't go creating any edges.
}
std::unordered_map<Point*, coord_t> smallest_distance; //The shortest distance to the current tree.
smallest_distance.reserve(vertices_list.size());
std::unordered_map<Point*, Point*> smallest_distance_to; //Which point the shortest distance goes towards.
smallest_distance_to.reserve(vertices_list.size());
for (size_t vertex_index = 0; vertex_index < vertices_list.size(); vertex_index++)
{
if (vertices_list[vertex_index] == first_point)
{
continue;
}
smallest_distance[&vertices_list[vertex_index]] = vSize2(vertices_list[vertex_index] - first_point);
smallest_distance_to[&vertices_list[vertex_index]] = &vertices_list[0];
}
while(result.size() < vertices_list.size()) //All of the vertices need to be in the tree at the end.
{
//Choose the closest vertex to connect to that is not yet in the tree.
//This search is O(V) right now, which can be made down to O(log(V)). This reduces the overall time complexity from O(V*V) to O(V*log(E)).
//However that requires an implementation of a heap that supports the decreaseKey operation, which is not in the std library.
//TODO: Implement this?
Point* closest_point = nullptr;
coord_t closest_distance = std::numeric_limits<coord_t>::max();
for(std::pair<Point*, coord_t> point_and_distance : smallest_distance)
{
if (point_and_distance.second < closest_distance) //This one's closer!
{
closest_point = point_and_distance.first;
closest_distance = point_and_distance.second;
}
}
//Add this point to the graph and remove it from the candidates.
Point closest_point_local = *closest_point;
Point other_end = *smallest_distance_to[closest_point];
if (result.find(closest_point_local) == result.end())
{
result[closest_point_local] = std::vector<Edge>();
}
result[closest_point_local].emplace_back(closest_point_local, other_end);
if (result.find(other_end) == result.end())
{
result[other_end] = std::vector<Edge>();
}
result[other_end].emplace_back(other_end, closest_point_local);
smallest_distance.erase(closest_point); //Remove it so we don't check for these points again.
smallest_distance_to.erase(closest_point);
//Update the distances of all points that are not in the graph.
for (std::pair<Point*, coord_t> point_and_distance : smallest_distance)
{
coord_t new_distance = vSize2(*closest_point - *point_and_distance.first);
if (new_distance < point_and_distance.second) //New point is closer.
{
smallest_distance[point_and_distance.first] = new_distance;
smallest_distance_to[point_and_distance.first] = closest_point;
}
}
}
return result;
}
std::vector<Point> MinimumSpanningTree::adjacentNodes(Point node) const
{
std::vector<Point> result;
AdjacencyGraph_t::const_iterator adjacency_entry = adjacency_graph.find(node);
if (adjacency_entry != adjacency_graph.end())
{
for (const Edge edge : (*adjacency_entry).second)
{
//Get the opposite side.
if (edge.start == node)
{
result.push_back(edge.end);
}
else
{
result.push_back(edge.start);
}
}
}
return result;
}
std::vector<Point> MinimumSpanningTree::leaves() const
{
std::vector<Point> result;
for (std::pair<Point, std::vector<Edge>> node : adjacency_graph)
{
if (node.second.size() <= 1) //Leaves are nodes that have only one adjacent edge, or just the one node if the tree contains one node.
{
result.push_back(node.first);
}
}
return result;
}
std::vector<Point> MinimumSpanningTree::vertices() const
{
std::vector<Point> result;
for (std::pair<Point, std::vector<Edge>> node : adjacency_graph)
{
result.push_back(node.first);
}
return result;
}
}<commit_msg>[MinimumSpanningTree] Simplify vector building<commit_after>//Copyright (c) 2017 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "MinimumSpanningTree.h"
#include <iterator>
namespace cura
{
MinimumSpanningTree::MinimumSpanningTree(std::unordered_set<Point> vertices) : adjacency_graph(prim(vertices))
{
//Just copy over the fields.
}
MinimumSpanningTree::Edge::Edge(const Point start, const Point end) : start(start), end(end)
{
//Just copy over the fields.
}
auto MinimumSpanningTree::prim(std::unordered_set<Point> vertices) const -> AdjacencyGraph_t
{
AdjacencyGraph_t result;
if (vertices.empty())
{
return result; //No vertices, so we can't create edges either.
}
result.reserve(vertices.size());
std::vector<Point> vertices_list(vertices.begin(), vertices.end());
Point first_point = vertices_list[0];
result[first_point] = std::vector<MinimumSpanningTree::Edge>(); //Start with one vertex in the tree.
if (vertices_list.size() == 1)
{
return result; //If there's only one vertex, we can't go creating any edges.
}
std::unordered_map<Point*, coord_t> smallest_distance; //The shortest distance to the current tree.
smallest_distance.reserve(vertices_list.size());
std::unordered_map<Point*, Point*> smallest_distance_to; //Which point the shortest distance goes towards.
smallest_distance_to.reserve(vertices_list.size());
for (size_t vertex_index = 0; vertex_index < vertices_list.size(); vertex_index++)
{
if (vertices_list[vertex_index] == first_point)
{
continue;
}
smallest_distance[&vertices_list[vertex_index]] = vSize2(vertices_list[vertex_index] - first_point);
smallest_distance_to[&vertices_list[vertex_index]] = &vertices_list[0];
}
while(result.size() < vertices_list.size()) //All of the vertices need to be in the tree at the end.
{
//Choose the closest vertex to connect to that is not yet in the tree.
//This search is O(V) right now, which can be made down to O(log(V)). This reduces the overall time complexity from O(V*V) to O(V*log(E)).
//However that requires an implementation of a heap that supports the decreaseKey operation, which is not in the std library.
//TODO: Implement this?
Point* closest_point = nullptr;
coord_t closest_distance = std::numeric_limits<coord_t>::max();
for(std::pair<Point*, coord_t> point_and_distance : smallest_distance)
{
if (point_and_distance.second < closest_distance) //This one's closer!
{
closest_point = point_and_distance.first;
closest_distance = point_and_distance.second;
}
}
//Add this point to the graph and remove it from the candidates.
Point closest_point_local = *closest_point;
Point other_end = *smallest_distance_to[closest_point];
if (result.find(closest_point_local) == result.end())
{
result[closest_point_local] = std::vector<Edge>();
}
result[closest_point_local].emplace_back(closest_point_local, other_end);
if (result.find(other_end) == result.end())
{
result[other_end] = std::vector<Edge>();
}
result[other_end].emplace_back(other_end, closest_point_local);
smallest_distance.erase(closest_point); //Remove it so we don't check for these points again.
smallest_distance_to.erase(closest_point);
//Update the distances of all points that are not in the graph.
for (std::pair<Point*, coord_t> point_and_distance : smallest_distance)
{
coord_t new_distance = vSize2(*closest_point - *point_and_distance.first);
if (new_distance < point_and_distance.second) //New point is closer.
{
smallest_distance[point_and_distance.first] = new_distance;
smallest_distance_to[point_and_distance.first] = closest_point;
}
}
}
return result;
}
std::vector<Point> MinimumSpanningTree::adjacentNodes(Point node) const
{
std::vector<Point> result;
AdjacencyGraph_t::const_iterator adjacency_entry = adjacency_graph.find(node);
if (adjacency_entry != adjacency_graph.end())
{
const auto& edges = adjacency_entry->second;
std::transform(edges.begin(), edges.end(), std::back_inserter(result),
[&node](const Edge& e) { return (e.start == node) ? e.end : e.start; });
}
return result;
}
std::vector<Point> MinimumSpanningTree::leaves() const
{
std::vector<Point> result;
for (std::pair<Point, std::vector<Edge>> node : adjacency_graph)
{
if (node.second.size() <= 1) //Leaves are nodes that have only one adjacent edge, or just the one node if the tree contains one node.
{
result.push_back(node.first);
}
}
return result;
}
std::vector<Point> MinimumSpanningTree::vertices() const
{
std::vector<Point> result;
using MapValue = std::pair<Point, std::vector<Edge>>;
std::transform(adjacency_graph.begin(), adjacency_graph.end(), std::back_inserter(result),
[](const MapValue& node) { return node.first; });
return result;
}
}<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2002-2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "<WebSig>" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 2001, Institute for
* Data Communications Systems, <http://www.nue.et-inf.uni-siegen.de/>.
* The development of this software was partly funded by the European
* Commission in the <WebSig> project in the ISIS Programme.
* For more information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* XSEC
*
* XENCEncryptionMethod := Interface definition for EncryptionMethod element
*
* $Id$
*
*/
#ifndef XENCENCRYPTIONMETHOD_INCLUDE
#define XENCENCRYPTIONMETHOD_INCLUDE
// XSEC Includes
#include <xsec/framework/XSECDefs.hpp>
/**
* @ingroup xenc
* @{
*/
/**
* @brief Interface definition for the EncryptionMethod object
*
* The \<EncryptionMethod\> element holds information about the
* encryption algorithm being used.
*
* This element is optional within an EncryptedType derivative,
* but applications not making use of this need to know the
* this information, otherwise the library will not be able to
* decrypt the data.
*
* It is defined as :
*
* <complexType name='EncryptionMethodType' mixed='true'>
* <sequence>
* <element name='KeySize' minOccurs='0' type='xenc:KeySizeType'/>
* <element name='OAEPparams' minOccurs='0' type='base64Binary'/>
* <any namespace='##other' minOccurs='0' maxOccurs='unbounded'/>
* </sequence>
* <attribute name='Algorithm' type='anyURI' use='required'/>
* </complexType>
*
*/
class XENCEncryptionMethod {
public:
XENCEncryptionMethod() {};
virtual ~XENCEncryptionMethod() {};
/** @name Getter Methods */
//@{
/**
* \brief Get the algorithm
*
* Return the Algorithm URI representing the encryption type for this
* encrypted data
*
* @returns the URI representing the algorithm
*/
virtual const XMLCh * getAlgorithm(void) = 0;
/**
* \brief Get the digest method URI
*
* Return the Algorithm URI represtenting the Digest Method for those
* encryption algorithms that require it (such as RSA with OAEP padding)
*
* @returns the URI representing the digest method algorithm
*/
virtual const XMLCh * getDigestMethod(void) = 0;
/**
* \brief Get the value of the OAEPparams string
*
* The OAEP RSA padding method allows a user to set an optional
* params string (that will be used as input to the Digest algorithm).
*
* @returns The string (base64 encoded value) representing the OAEP params
*/
virtual const XMLCh * getOAEPparams(void) = 0;
/**
* \brief Get the KeySize that was set in this EncryptionMethod.
*
* This field would not normally be used for the encryption algorithms
* explicitly referenced in the XML Encryption standard. It is provided
* mainly for stream ciphers that have a variable key length
*/
virtual int getKeySize(void) = 0;
/**
* \brief Get the DOM Element Node of this structure
*
* @returns the DOM Element Node representing the <EncryptionMethod> element
*/
virtual XERCES_CPP_NAMESPACE_QUALIFIER DOMElement * getElement(void) = 0;
//@}
/** @name Setter Methods */
//@{
/**
* \brief Set the value of the DigestMethod
*
* Sets the DigestMethod element's Algorithm attribute to the passed in
* value - should be a URI string
*
* @param method String to set in the Algorithm attribute. Will create a
* \<DigestMethod\> element if one does not already exist
*/
virtual void setDigestMethod(const XMLCh * method) = 0;
/**
* \brief Set the value of the OAEPparams string
*
* Sets the OAEPparams element's Text node child to the passed in
* value - should be a base64 encoded value
*
* @param params String to set in the OAEPparams text node. Will create a
* \<OAEPparams\> element if one does not already exist
*/
virtual void setOAEPparams(const XMLCh * params) = 0;
/**
* \brief Set the KeySize that in this EncryptionMethod.
*
* This field would not normally be used for the encryption algorithms
* explicitly referenced in the XML Encryption standard. It is provided
* mainly for stream ciphers that have a variable key length
*/
virtual void setKeySize(int size) = 0;
//@}
private:
// Unimplemented
XENCEncryptionMethod(const XENCEncryptionMethod &);
XENCEncryptionMethod & operator = (const XENCEncryptionMethod &);
};
#endif /* XENCENCRYPTIONMETHOD_INCLUDE */
<commit_msg>Fixed doxygen compile problem<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2002-2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "<WebSig>" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 2001, Institute for
* Data Communications Systems, <http://www.nue.et-inf.uni-siegen.de/>.
* The development of this software was partly funded by the European
* Commission in the <WebSig> project in the ISIS Programme.
* For more information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* XSEC
*
* XENCEncryptionMethod := Interface definition for EncryptionMethod element
*
* $Id$
*
*/
#ifndef XENCENCRYPTIONMETHOD_INCLUDE
#define XENCENCRYPTIONMETHOD_INCLUDE
// XSEC Includes
#include <xsec/framework/XSECDefs.hpp>
/**
* @ingroup xenc
* @{
*/
/**
* @brief Interface definition for the EncryptionMethod object
*
* The \<EncryptionMethod\> element holds information about the
* encryption algorithm being used.
*
* This element is optional within an EncryptedType derivative,
* but applications not making use of this need to know the
* this information, otherwise the library will not be able to
* decrypt the data.
*
* It is defined as :
* \verbatim
<complexType name='EncryptionMethodType' mixed='true'>
<sequence>
<element name='KeySize' minOccurs='0' type='xenc:KeySizeType'/>
<element name='OAEPparams' minOccurs='0' type='base64Binary'/>
<any namespace='##other' minOccurs='0' maxOccurs='unbounded'/>
</sequence>
<attribute name='Algorithm' type='anyURI' use='required'/>
</complexType>
\endverbatim
*/
class XENCEncryptionMethod {
public:
XENCEncryptionMethod() {};
virtual ~XENCEncryptionMethod() {};
/** @name Getter Methods */
//@{
/**
* \brief Get the algorithm
*
* Return the Algorithm URI representing the encryption type for this
* encrypted data
*
* @returns the URI representing the algorithm
*/
virtual const XMLCh * getAlgorithm(void) = 0;
/**
* \brief Get the digest method URI
*
* Return the Algorithm URI represtenting the Digest Method for those
* encryption algorithms that require it (such as RSA with OAEP padding)
*
* @returns the URI representing the digest method algorithm
*/
virtual const XMLCh * getDigestMethod(void) = 0;
/**
* \brief Get the value of the OAEPparams string
*
* The OAEP RSA padding method allows a user to set an optional
* params string (that will be used as input to the Digest algorithm).
*
* @returns The string (base64 encoded value) representing the OAEP params
*/
virtual const XMLCh * getOAEPparams(void) = 0;
/**
* \brief Get the KeySize that was set in this EncryptionMethod.
*
* This field would not normally be used for the encryption algorithms
* explicitly referenced in the XML Encryption standard. It is provided
* mainly for stream ciphers that have a variable key length
*/
virtual int getKeySize(void) = 0;
/**
* \brief Get the DOM Element Node of this structure
*
* @returns the DOM Element Node representing the \<EncryptionMethod\> element
*/
virtual XERCES_CPP_NAMESPACE_QUALIFIER DOMElement * getElement(void) = 0;
//@}
/** @name Setter Methods */
//@{
/**
* \brief Set the value of the DigestMethod
*
* Sets the DigestMethod element's Algorithm attribute to the passed in
* value - should be a URI string
*
* @param method String to set in the Algorithm attribute. Will create a
* \<DigestMethod\> element if one does not already exist
*/
virtual void setDigestMethod(const XMLCh * method) = 0;
/**
* \brief Set the value of the OAEPparams string
*
* Sets the OAEPparams element's Text node child to the passed in
* value - should be a base64 encoded value
*
* @param params String to set in the OAEPparams text node. Will create a
* \<OAEPparams\> element if one does not already exist
*/
virtual void setOAEPparams(const XMLCh * params) = 0;
/**
* \brief Set the KeySize that in this EncryptionMethod.
*
* This field would not normally be used for the encryption algorithms
* explicitly referenced in the XML Encryption standard. It is provided
* mainly for stream ciphers that have a variable key length
*/
virtual void setKeySize(int size) = 0;
//@}
private:
// Unimplemented
XENCEncryptionMethod(const XENCEncryptionMethod &);
XENCEncryptionMethod & operator = (const XENCEncryptionMethod &);
};
#endif /* XENCENCRYPTIONMETHOD_INCLUDE */
<|endoftext|> |
<commit_before>#ifndef DOMCasts_HEADER_GUARD_
#define DOMCasts_HEADER_GUARD_
/*
* Copyright 2001-2002,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id$
*/
//
// This file is part of the internal implementation of the C++ XML DOM.
// It should NOT be included or used directly by application programs.
//
// Applications should include the file <xercesc/dom/DOM.hpp> for the entire
// DOM API, or xercesc/dom/DOM*.hpp for individual DOM classes, where the class
// name is substituded for the *.
//
//
// Define inline casting functions to convert from
// (DOMNode *) to DOMParentNode or DOMChildNode *.
//
// This requires knowledge of the structure of the fields of
// for all node types. There are three categories -
//
// Nodetypes that can have children and can be a child themselves.
// e.g. Elements
//
// Object
// DOMNodeImpl fNode;
// DOMParentNode fParent;
// DOMChildNode fChild;
// ... // other fields, depending on node type.
//
// Nodetypes that can not have children, e.g. TEXT
//
// Object
// DOMNodeImpl fNode;
// DOMChildNode fChild;
// ... // other fields, depending on node type
//
// Nodetypes that can not be a child of other nodes, but that can
// have children (are a parent) e.g. ATTR
// Object
// DOMNodeImpl fNode;
// DOMParentNode fParent
// ... // other fields, depending on node type
//
// The casting functions make these assumptions:
// 1. The cast is possible. Using code will not attempt to
// cast to something that does not exist, such as the child
// part of an ATTR
//
// 2. The nodes belong to this implementation.
//
// Some of the casts use the LEAFNODE flag in the common fNode part to
// determine whether an fParent field exists, and thus the
// position of the fChild part within the node.
//
// These functions also cast off const. It was either do that, or make
// a second overloaded set that took and returned const arguements.
//
#include "DOMElementImpl.hpp"
#include "DOMTextImpl.hpp"
XERCES_CPP_NAMESPACE_BEGIN
static inline DOMNodeImpl *castToNodeImpl(const DOMNode *p)
{
DOMElementImpl *pE = (DOMElementImpl *)p;
return &(pE->fNode);
}
static inline DOMParentNode *castToParentImpl(const DOMNode *p) {
DOMElementImpl *pE = (DOMElementImpl *)p;
return &(pE->fParent);
}
static inline DOMChildNode *castToChildImpl(const DOMNode *p) {
DOMElementImpl *pE = (DOMElementImpl *)p;
if (pE->fNode.isLeafNode()) {
DOMTextImpl *pT = (DOMTextImpl *)p;
return &(pT->fChild);
}
return &(pE->fChild);
}
static inline DOMNode *castToNode(const DOMParentNode *p ) {
int parentOffset = (char *)&(((DOMElementImpl *)0)->fParent) - (char *)0;
char *retPtr = (char *)p - parentOffset;
return (DOMNode *)retPtr;
}
static inline DOMNode *castToNode(const DOMNodeImpl *p) {
int nodeImplOffset = (char *)&(((DOMElementImpl *)0)->fNode) - (char *)0;
char *retPtr = (char *)p - nodeImplOffset;
return (DOMNode *)retPtr;
}
static inline DOMNodeImpl *castToNodeImpl(const DOMParentNode *p)
{
int nodeImplOffset = (char *)&(((DOMElementImpl *)0)->fNode) - (char *)0;
int parentOffset = (char *)&(((DOMElementImpl *)0)->fParent) - (char *)0;
char *retPtr = (char *)p - parentOffset + nodeImplOffset;
return (DOMNodeImpl *)retPtr;
}
XERCES_CPP_NAMESPACE_END
#endif
<commit_msg>Bugfix: XERCESC-1074; get rid of warnings in newer gcc on offset calculations in DOMCasts.h ...hope I didn't break anybody...<commit_after>#ifndef DOMCasts_HEADER_GUARD_
#define DOMCasts_HEADER_GUARD_
/*
* Copyright 2001-2002,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id$
*/
//
// This file is part of the internal implementation of the C++ XML DOM.
// It should NOT be included or used directly by application programs.
//
// Applications should include the file <xercesc/dom/DOM.hpp> for the entire
// DOM API, or xercesc/dom/DOM*.hpp for individual DOM classes, where the class
// name is substituded for the *.
//
//
// Define inline casting functions to convert from
// (DOMNode *) to DOMParentNode or DOMChildNode *.
//
// This requires knowledge of the structure of the fields of
// for all node types. There are three categories -
//
// Nodetypes that can have children and can be a child themselves.
// e.g. Elements
//
// Object
// DOMNodeImpl fNode;
// DOMParentNode fParent;
// DOMChildNode fChild;
// ... // other fields, depending on node type.
//
// Nodetypes that can not have children, e.g. TEXT
//
// Object
// DOMNodeImpl fNode;
// DOMChildNode fChild;
// ... // other fields, depending on node type
//
// Nodetypes that can not be a child of other nodes, but that can
// have children (are a parent) e.g. ATTR
// Object
// DOMNodeImpl fNode;
// DOMParentNode fParent
// ... // other fields, depending on node type
//
// The casting functions make these assumptions:
// 1. The cast is possible. Using code will not attempt to
// cast to something that does not exist, such as the child
// part of an ATTR
//
// 2. The nodes belong to this implementation.
//
// Some of the casts use the LEAFNODE flag in the common fNode part to
// determine whether an fParent field exists, and thus the
// position of the fChild part within the node.
//
// These functions also cast off const. It was either do that, or make
// a second overloaded set that took and returned const arguements.
//
//
// Note that using offsetof, or taking the offset of an object member at
// a 0 address, is now undefined in C++. And gcc now warns about this behavior.
// This is because doing do so is unreliable for some types of objects.
// See: http://gcc.gnu.org/ml/gcc/2004-06/msg00227.html
// : http://gcc.gnu.org/ml/gcc-bugs/2000-03/msg00805.html
// The casting code below works around gcc's warnings by using a dummy
// pointer, which the compiler cannot tell is null. The defeats the warning,
// but also masks the potential problem.
// The gcc option -Wno-invalid-offsetof may also be used to turn off this warning.
//
#include "DOMElementImpl.hpp"
#include "DOMTextImpl.hpp"
XERCES_CPP_NAMESPACE_BEGIN
static inline DOMNodeImpl *castToNodeImpl(const DOMNode *p)
{
DOMElementImpl *pE = (DOMElementImpl *)p;
return &(pE->fNode);
}
static inline DOMParentNode *castToParentImpl(const DOMNode *p) {
DOMElementImpl *pE = (DOMElementImpl *)p;
return &(pE->fParent);
}
static inline DOMChildNode *castToChildImpl(const DOMNode *p) {
DOMElementImpl *pE = (DOMElementImpl *)p;
if (pE->fNode.isLeafNode()) {
DOMTextImpl *pT = (DOMTextImpl *)p;
return &(pT->fChild);
}
return &(pE->fChild);
}
static inline DOMNode *castToNode(const DOMParentNode *p ) {
DOMElementImpl* dummy = 0;
size_t parentOffset = (char *)&(dummy->fParent) - (char *)dummy;
char *retPtr = (char *)p - parentOffset;
return (DOMNode *)retPtr;
}
static inline DOMNode *castToNode(const DOMNodeImpl *p) {
DOMElementImpl* dummy = 0;
size_t nodeImplOffset = (char *)&(dummy->fNode) - (char *)dummy;
char *retPtr = (char *)p - nodeImplOffset;
return (DOMNode *)retPtr;
}
static inline DOMNodeImpl *castToNodeImpl(const DOMParentNode *p)
{
DOMElementImpl* dummy = 0;
size_t nodeImplOffset = (char *)&(dummy->fNode) - (char *)dummy;
size_t parentOffset = (char *)&(dummy->fParent) - (char *)dummy;
char *retPtr = (char *)p - parentOffset + nodeImplOffset;
return (DOMNodeImpl *)retPtr;
}
XERCES_CPP_NAMESPACE_END
#endif
<|endoftext|> |
<commit_before>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Jos van den Oever <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "strigiconfig.h"
#include "fileinputstream.h"
#include "bz2inputstream.h"
#include "diranalyzer.h"
#include "analyzerconfiguration.h"
#include "streamendanalyzer.h"
#include "streamthroughanalyzer.h"
#include "streamlineanalyzer.h"
#include "streamsaxanalyzer.h"
#include "streameventanalyzer.h"
#include "xmlindexwriter.h"
#include <cstdio>
#include <cstring>
#include <algorithm>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_DIRECT_H
#include <direct.h>
#endif
#include <iostream>
#include <sstream>
#include <fstream>
#include <set>
using namespace Strigi;
using namespace std;
class SelectedAnalyzerConfiguration : public Strigi::AnalyzerConfiguration {
public:
const set<string> requiredAnalyzers;
mutable set<string> usedAnalyzers;
mutable set<string> availableAnalyzers;
explicit SelectedAnalyzerConfiguration(const set<string> an)
: requiredAnalyzers(an) {}
bool valid() const {
return requiredAnalyzers.size() == usedAnalyzers.size()
|| requiredAnalyzers.size() == 0;
}
bool useFactory(const string& name) const {
bool use = requiredAnalyzers.find(name) != requiredAnalyzers.end()
|| requiredAnalyzers.size() == 0;
if (use) {
usedAnalyzers.insert(name);
}
availableAnalyzers.insert(name);
return use;
}
bool useFactory(StreamEndAnalyzerFactory* f) const {
return useFactory(f->name());
}
bool useFactory(StreamThroughAnalyzerFactory* f) const {
return useFactory(f->name());
}
bool useFactory(StreamSaxAnalyzerFactory* f) const {
return useFactory(f->name());
}
bool useFactory(StreamEventAnalyzerFactory* f) const {
return useFactory(f->name());
}
bool useFactory(StreamLineAnalyzerFactory* f) const {
return useFactory(f->name());
}
};
void
printUsage(char** argv) {
fprintf(stderr, "Usage: %s [OPTIONS] SOURCE\n"
"Analyze the given file and output the result as XML.\n"
" -c configuration file\n"
" -a comma-separated list of analyzers\n"
" -r reference output, when specified, the reference output is \n"
" compared to the given output and the first difference is \n"
" reported.\n",
argv[0]);
}
bool
containsHelp(int argc, char **argv) {
for (int i=1; i<argc; ++i) {
if (strcmp(argv[i], "--help") == 0
|| strcmp(argv[i], "-h") == 0) return true;
}
return false;
}
set<string>
parseAnalyzerNames(const char* names) {
set<string> n;
string ns(names);
string::size_type start = 0, p = ns.find(',');
while (p != string::npos) {
n.insert(ns.substr(start, p-start));
start = p + 1;
p = ns.find(',', start);
}
n.insert(ns.substr(start));
return n;
}
set<string>
parseConfig(const char* config) {
set<string> n;
ifstream f(config);
string line;
while (f.good()) {
getline(f, line);
if (strncmp("analyzer=", line.c_str(), 9) == 0) {
n.insert(line.substr(9));
}
}
return n;
}
/**
* Usage: $0 [OPTIONS] SOURCE
**/
int
main(int argc, char** argv) {
// there are 2 optional options that both require an argument.
// one can specify 1 source, so the number of arguments must be
// 2, 4 or 6
if (containsHelp(argc, argv) || (argc != 2 && argc != 4 && argc != 6)) {
printUsage(argv);
return -1;
}
set<string> analyzers;
const char* targetFile;
const char* referenceFile = 0;
if (argc == 4) {
if (strcmp(argv[1],"-a") == 0) {
analyzers = parseAnalyzerNames(argv[2]);
} else if (strcmp(argv[1], "-r") == 0) {
referenceFile = argv[2];
} else if (strcmp(argv[1], "-c") == 0) {
analyzers = parseConfig(argv[2]);
} else {
printUsage(argv);
return -1;
}
targetFile = argv[3];
} else if (argc == 6) {
if (strcmp(argv[1], "-a") == 0) {
analyzers = parseAnalyzerNames(argv[2]);
if (strcmp(argv[3], "-r") == 0) {
referenceFile = argv[4];
}
} else if (strcmp(argv[1], "-c") == 0) {
analyzers = parseConfig(argv[2]);
if (strcmp(argv[3], "-r") == 0) {
referenceFile = argv[4];
}
} else if (strcmp(argv[1], "-r") == 0) {
referenceFile = argv[2];
if (strcmp(argv[3], "-a") == 0) {
analyzers = parseAnalyzerNames(argv[4]);
} else if (strcmp(argv[3], "-c") == 0) {
analyzers = parseConfig(argv[4]);
}
} else {
printUsage(argv);
return -1;
}
targetFile = argv[5];
} else {
targetFile = argv[1];
}
const char* mappingFile = 0;
// check that the target file exists
{
ifstream filetest(targetFile);
if (!filetest.good()) {
cerr << "The file '" << targetFile << "' cannot be read." << endl;
return 1;
}
}
// check that the result file is ok
FileInputStream f(referenceFile);
// BZ2InputStream bz2(&f);
if (referenceFile != 0 && f.status() != Ok) {
cerr << "The file '" << referenceFile << "' cannot be read." << endl;
return 1;
}
const TagMapping mapping(mappingFile);
ostringstream out;
out << "<?xml version='1.0' encoding='UTF-8'?>\n<"
<< mapping.map("metadata");
map<string, string>::const_iterator i = mapping.namespaces().begin();
while (i != mapping.namespaces().end()) {
out << " xmlns:" << i->first << "='" << i->second << "'";
i++;
}
out << ">\n";
SelectedAnalyzerConfiguration ic(analyzers);
XmlIndexWriter writer(out, mapping);
DirAnalyzer analyzer(writer, &ic);
if (!ic.valid()) {
set<string>::const_iterator i;
set<string> missing;
set_difference(analyzers.begin(), analyzers.end(),
ic.availableAnalyzers.begin(), ic.availableAnalyzers.end(),
insert_iterator<set<string> >(missing, missing.begin()));
if (missing.size() == 1) {
fprintf(stderr, "No analyzer with name %s was found.\n",
missing.begin()->c_str());
} else {
cerr << "The analyzers";
for (i = missing.begin(); i != missing.end(); ++i) {
cerr << ", " << *i;
}
cerr << " were not found." << endl;
}
fprintf(stderr, "Choose from:\n");
for (i = ic.availableAnalyzers.begin(); i != ic.availableAnalyzers.end(); ++i) {
cerr << " " << *i << endl;
}
return 1;
}
// change to the directory of the file to analyze
// this ensures a consistent naming of the file uris, regardless of cwd
string targetPath(targetFile);
string::size_type slashpos = targetPath.rfind('/');
if (slashpos == string::npos) {
analyzer.analyzeDir(targetFile);
} else {
chdir(targetPath.substr(0,slashpos).c_str());
analyzer.analyzeDir(targetPath.substr(slashpos+1).c_str());
}
string str = out.str();
int32_t n = 2*str.length();
// if no reference file was specified, we output the analysis
if (referenceFile == 0) {
cout << str;
return 0;
}
// load the file to compare with
const char* c;
n = f.read(c, n, n);
if (n < 0) {
fprintf(stderr, "Error: %s\n", f.error());
return -1;
}
if (n != (int32_t)out.str().length()) {
printf("output length differs %i instead of %i\n", n, out.str().length());
}
const char* p1 = c;
const char* p2 = str.c_str();
int32_t n1 = n;
int32_t n2 = str.length();
while (n1-- && n2-- && *p1 == *p2) {
p1++;
p2++;
}
if (n1 ==0 && (*p1 || *p2)) {
printf("difference at position %i\n", p1-c);
int32_t m = (80 > str.length())?str.length():80;
printf("%i %.*s\n", m, m, str.c_str());
m = (80 > n)?n:80;
printf("%i %.*s\n", m, m, c);
return -1;
}
return 0;
}
<commit_msg>fix error output: numbers were in the wrong order<commit_after>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Jos van den Oever <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "strigiconfig.h"
#include "fileinputstream.h"
#include "bz2inputstream.h"
#include "diranalyzer.h"
#include "analyzerconfiguration.h"
#include "streamendanalyzer.h"
#include "streamthroughanalyzer.h"
#include "streamlineanalyzer.h"
#include "streamsaxanalyzer.h"
#include "streameventanalyzer.h"
#include "xmlindexwriter.h"
#include <cstdio>
#include <cstring>
#include <algorithm>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_DIRECT_H
#include <direct.h>
#endif
#include <iostream>
#include <sstream>
#include <fstream>
#include <set>
using namespace Strigi;
using namespace std;
class SelectedAnalyzerConfiguration : public Strigi::AnalyzerConfiguration {
public:
const set<string> requiredAnalyzers;
mutable set<string> usedAnalyzers;
mutable set<string> availableAnalyzers;
explicit SelectedAnalyzerConfiguration(const set<string> an)
: requiredAnalyzers(an) {}
bool valid() const {
return requiredAnalyzers.size() == usedAnalyzers.size()
|| requiredAnalyzers.size() == 0;
}
bool useFactory(const string& name) const {
bool use = requiredAnalyzers.find(name) != requiredAnalyzers.end()
|| requiredAnalyzers.size() == 0;
if (use) {
usedAnalyzers.insert(name);
}
availableAnalyzers.insert(name);
return use;
}
bool useFactory(StreamEndAnalyzerFactory* f) const {
return useFactory(f->name());
}
bool useFactory(StreamThroughAnalyzerFactory* f) const {
return useFactory(f->name());
}
bool useFactory(StreamSaxAnalyzerFactory* f) const {
return useFactory(f->name());
}
bool useFactory(StreamEventAnalyzerFactory* f) const {
return useFactory(f->name());
}
bool useFactory(StreamLineAnalyzerFactory* f) const {
return useFactory(f->name());
}
};
void
printUsage(char** argv) {
fprintf(stderr, "Usage: %s [OPTIONS] SOURCE\n"
"Analyze the given file and output the result as XML.\n"
" -c configuration file\n"
" -a comma-separated list of analyzers\n"
" -r reference output, when specified, the reference output is \n"
" compared to the given output and the first difference is \n"
" reported.\n",
argv[0]);
}
bool
containsHelp(int argc, char **argv) {
for (int i=1; i<argc; ++i) {
if (strcmp(argv[i], "--help") == 0
|| strcmp(argv[i], "-h") == 0) return true;
}
return false;
}
set<string>
parseAnalyzerNames(const char* names) {
set<string> n;
string ns(names);
string::size_type start = 0, p = ns.find(',');
while (p != string::npos) {
n.insert(ns.substr(start, p-start));
start = p + 1;
p = ns.find(',', start);
}
n.insert(ns.substr(start));
return n;
}
set<string>
parseConfig(const char* config) {
set<string> n;
ifstream f(config);
string line;
while (f.good()) {
getline(f, line);
if (strncmp("analyzer=", line.c_str(), 9) == 0) {
n.insert(line.substr(9));
}
}
return n;
}
/**
* Usage: $0 [OPTIONS] SOURCE
**/
int
main(int argc, char** argv) {
// there are 2 optional options that both require an argument.
// one can specify 1 source, so the number of arguments must be
// 2, 4 or 6
if (containsHelp(argc, argv) || (argc != 2 && argc != 4 && argc != 6)) {
printUsage(argv);
return -1;
}
set<string> analyzers;
const char* targetFile;
const char* referenceFile = 0;
if (argc == 4) {
if (strcmp(argv[1],"-a") == 0) {
analyzers = parseAnalyzerNames(argv[2]);
} else if (strcmp(argv[1], "-r") == 0) {
referenceFile = argv[2];
} else if (strcmp(argv[1], "-c") == 0) {
analyzers = parseConfig(argv[2]);
} else {
printUsage(argv);
return -1;
}
targetFile = argv[3];
} else if (argc == 6) {
if (strcmp(argv[1], "-a") == 0) {
analyzers = parseAnalyzerNames(argv[2]);
if (strcmp(argv[3], "-r") == 0) {
referenceFile = argv[4];
}
} else if (strcmp(argv[1], "-c") == 0) {
analyzers = parseConfig(argv[2]);
if (strcmp(argv[3], "-r") == 0) {
referenceFile = argv[4];
}
} else if (strcmp(argv[1], "-r") == 0) {
referenceFile = argv[2];
if (strcmp(argv[3], "-a") == 0) {
analyzers = parseAnalyzerNames(argv[4]);
} else if (strcmp(argv[3], "-c") == 0) {
analyzers = parseConfig(argv[4]);
}
} else {
printUsage(argv);
return -1;
}
targetFile = argv[5];
} else {
targetFile = argv[1];
}
const char* mappingFile = 0;
// check that the target file exists
{
ifstream filetest(targetFile);
if (!filetest.good()) {
cerr << "The file '" << targetFile << "' cannot be read." << endl;
return 1;
}
}
// check that the result file is ok
FileInputStream f(referenceFile);
// BZ2InputStream bz2(&f);
if (referenceFile != 0 && f.status() != Ok) {
cerr << "The file '" << referenceFile << "' cannot be read." << endl;
return 1;
}
const TagMapping mapping(mappingFile);
ostringstream out;
out << "<?xml version='1.0' encoding='UTF-8'?>\n<"
<< mapping.map("metadata");
map<string, string>::const_iterator i = mapping.namespaces().begin();
while (i != mapping.namespaces().end()) {
out << " xmlns:" << i->first << "='" << i->second << "'";
i++;
}
out << ">\n";
SelectedAnalyzerConfiguration ic(analyzers);
XmlIndexWriter writer(out, mapping);
DirAnalyzer analyzer(writer, &ic);
if (!ic.valid()) {
set<string>::const_iterator i;
set<string> missing;
set_difference(analyzers.begin(), analyzers.end(),
ic.availableAnalyzers.begin(), ic.availableAnalyzers.end(),
insert_iterator<set<string> >(missing, missing.begin()));
if (missing.size() == 1) {
fprintf(stderr, "No analyzer with name %s was found.\n",
missing.begin()->c_str());
} else {
cerr << "The analyzers";
for (i = missing.begin(); i != missing.end(); ++i) {
cerr << ", " << *i;
}
cerr << " were not found." << endl;
}
fprintf(stderr, "Choose from:\n");
for (i = ic.availableAnalyzers.begin(); i != ic.availableAnalyzers.end(); ++i) {
cerr << " " << *i << endl;
}
return 1;
}
// change to the directory of the file to analyze
// this ensures a consistent naming of the file uris, regardless of cwd
string targetPath(targetFile);
string::size_type slashpos = targetPath.rfind('/');
if (slashpos == string::npos) {
analyzer.analyzeDir(targetFile);
} else {
chdir(targetPath.substr(0,slashpos).c_str());
analyzer.analyzeDir(targetPath.substr(slashpos+1).c_str());
}
string str = out.str();
int32_t n = 2*str.length();
// if no reference file was specified, we output the analysis
if (referenceFile == 0) {
cout << str;
return 0;
}
// load the file to compare with
const char* c;
n = f.read(c, n, n);
if (n < 0) {
fprintf(stderr, "Error: %s\n", f.error());
return -1;
}
if (n != (int32_t)out.str().length()) {
printf("output length differs %i instead of %i\n", out.str().length(),
n);
}
const char* p1 = c;
const char* p2 = str.c_str();
int32_t n1 = n;
int32_t n2 = str.length();
while (n1-- && n2-- && *p1 == *p2) {
p1++;
p2++;
}
if (n1 ==0 && (*p1 || *p2)) {
printf("difference at position %i\n", p1-c);
int32_t m = (80 > str.length())?str.length():80;
printf("%i %.*s\n", m, m, str.c_str());
m = (80 > n)?n:80;
printf("%i %.*s\n", m, m, c);
return -1;
}
return 0;
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
//_________________________________________________________________________
// EMCAL digit:
// A Digit is the sum of the energy lost in an EMCAL Tower
// It also stores information on Primary, and enterring particle
// tracknumbers Digits are created using AliEMCALSDigitizer, followed
// by AliEMCALDigitizer
//
//*-- Author: Sahal Yacoob (LBL)
// based on : AliPHOSDigit
//__________________________________________________________________________
// --- ROOT system ---
#include <Riostream.h>
#include <TMath.h>
// --- Standard library ---
// --- AliRoot header files ---
#include "AliEMCALDigit.h"
#include "AliEMCALGeometry.h"
ClassImp(AliEMCALDigit)
//____________________________________________________________________________
AliEMCALDigit::AliEMCALDigit() :
AliDigitNew(),
fNprimary(0),
fNMaxPrimary(5),
fPrimary(0x0),
fDEPrimary(0x0),
fNiparent(0),
fNMaxiparent(5),
fIparent(0x0),
fDEParent(0x0),
fMaxIter(0),
fTime(0.),
fTimeR(0.)
{
// default ctor
// Need to initialise for reading old files
fPrimary = new Int_t[fNMaxPrimary] ;
fDEPrimary = new Float_t[fNMaxPrimary] ;
fIparent = new Int_t[fNMaxiparent] ;
fDEParent = new Float_t[fNMaxiparent] ;
for ( Int_t i = 0; i < fNMaxPrimary ; i++) {
fPrimary[i] = -1 ;
fDEPrimary[i] = 0 ;
}
for ( Int_t i = 0; i < fNMaxiparent ; i++) {
fIparent[i] = -1 ;
fDEParent[i] = 0 ;
}
}
//____________________________________________________________________________
AliEMCALDigit::AliEMCALDigit(Int_t primary, Int_t iparent, Int_t id, Int_t DigEnergy, Float_t time, Int_t index, Float_t dE)
: AliDigitNew(),
fNprimary(0),
fNMaxPrimary(25),
fPrimary(0x0),
fDEPrimary(0x0),
fNiparent(0),
fNMaxiparent(150),
fIparent(0x0),
fDEParent(0x0),
fMaxIter(5),
fTime(time),
fTimeR(time)
{
// ctor with all data
// data memebrs of the base class (AliNewDigit)
fAmp = DigEnergy ;
fId = id ;
fIndexInList = index ;
// data members
fPrimary = new Int_t[fNMaxPrimary] ;
fDEPrimary = new Float_t[fNMaxPrimary] ;
fIparent = new Int_t[fNMaxiparent] ;
fDEParent = new Float_t[fNMaxiparent] ;
if( primary != -1){
fNprimary = 1 ;
fPrimary[0] = primary ;
fDEPrimary[0] = dE ;
fNiparent = 1 ;
fIparent[0] = iparent ;
fDEParent[0] = dE ;
}
else{ //If the contribution of this primary smaller than fDigitThreshold (AliEMCALv1)
fNprimary = 0 ;
fPrimary[0] = -1 ;
fDEPrimary[0] = 0 ;
fNiparent = 0 ;
fIparent[0] = -1 ;
fDEParent[0] = 0 ;
}
Int_t i ;
for ( i = 1; i < fNMaxPrimary ; i++) {
fPrimary[i] = -1 ;
fDEPrimary[i] = 0 ;
}
for ( i = 1; i< fNMaxiparent ; i++) {
fIparent[i] = -1 ;
fDEParent[i] = 0 ;
}
}
//____________________________________________________________________________
AliEMCALDigit::AliEMCALDigit(const AliEMCALDigit & digit)
: AliDigitNew(digit),
fNprimary(digit.fNprimary),
fNMaxPrimary(digit.fNMaxPrimary),
fPrimary(0x0),
fDEPrimary(0x0),
fNiparent(digit.fNiparent),
fNMaxiparent(digit.fNMaxiparent),
fIparent(0x0),
fDEParent(0x0),
fMaxIter(digit.fMaxIter),
fTime(digit.fTime),
fTimeR(digit.fTimeR)
{
// copy ctor
// data memebrs of the base class (AliNewDigit)
fAmp = digit.fAmp ;
fId = digit.fId;
fIndexInList = digit.fIndexInList ;
// data members
fPrimary = new Int_t[fNMaxPrimary] ;
fDEPrimary = new Float_t[fNMaxPrimary] ;
fIparent = new Int_t[fNMaxiparent] ;
fDEParent = new Float_t[fNMaxiparent] ;
Int_t i ;
for ( i = 0; i < fNprimary ; i++) {
fPrimary[i] = digit.fPrimary[i] ;
fDEPrimary[i] = digit.fDEPrimary[i] ;
}
Int_t j ;
for (j = 0; j< fNiparent ; j++) {
fIparent[j] = digit.fIparent[j] ;
fDEParent[j] = digit.fDEParent[j] ;
}
}
//____________________________________________________________________________
AliEMCALDigit::~AliEMCALDigit()
{
// Delete array of primiries if any
delete [] fPrimary ;
delete [] fDEPrimary ;
delete [] fIparent ;
delete [] fDEParent ;
}
//____________________________________________________________________________
Int_t AliEMCALDigit::Compare(const TObject * obj) const
{
// Compares two digits with respect to its Id
// to sort according increasing Id
Int_t rv ;
AliEMCALDigit * digit = (AliEMCALDigit *)obj ;
Int_t iddiff = fId - digit->GetId() ;
if ( iddiff > 0 )
rv = 1 ;
else if ( iddiff < 0 )
rv = -1 ;
else
rv = 0 ;
return rv ;
}
//____________________________________________________________________________
Float_t AliEMCALDigit::GetEta() const
{
//return pseudorapidity for this digit
// should be change in EMCALGeometry - 19-nov-04
Float_t eta=-10., phi=-10.;
Int_t id = GetId();
const AliEMCALGeometry *g = AliEMCALGeometry::GetInstance();
g->EtaPhiFromIndex(id,eta,phi);
return eta ;
}
//____________________________________________________________________________
Float_t AliEMCALDigit::GetPhi() const
{
//return phi coordinate of digit
// should be change in EMCALGeometry - 19-nov-04
Float_t eta=-10., phi=-10.;
Int_t id = GetId();
const AliEMCALGeometry *g = AliEMCALGeometry::GetInstance();
g->EtaPhiFromIndex(id,eta,phi);
return phi ;
}
//____________________________________________________________________________
Int_t AliEMCALDigit::GetPrimary(Int_t index) const
{
// retrieves the primary particle number given its index in the list
if ( (index <= fNprimary) && (index > 0)){
return fPrimary[index-1] ;
}
return -1 ;
}
//____________________________________________________________________________
Float_t AliEMCALDigit::GetDEPrimary(Int_t index) const
{
// retrieves the primary particle energy contribution
// given its index in the list
if ( (index <= fNprimary) && (index > 0)){
return fDEPrimary[index-1] ;
}
return 0 ;
}
//____________________________________________________________________________
Int_t AliEMCALDigit::GetIparent(Int_t index) const
{
// retrieves the primary particle number given its index in the list
if ( index <= fNiparent && index > 0){
return fIparent[index-1] ;
}
return -1 ;
}
//____________________________________________________________________________
Float_t AliEMCALDigit::GetDEParent(Int_t index) const
{
// retrieves the parent particle energy contribution
// given its index in the list
if ( (index <= fNiparent) && (index > 0)){
return fDEParent[index-1] ;
}
return 0;
}
//____________________________________________________________________________
void AliEMCALDigit::ShiftPrimary(Int_t shift){
//shifts primary number to BIG offset, to separate primary in different TreeK
Int_t index ;
for(index = 0; index <fNprimary; index++ ){
fPrimary[index] = fPrimary[index]+ shift * 10000000 ;}
for(index =0; index <fNiparent; index++){
fIparent[index] = fIparent[index] + shift * 10000000 ;}
}
//____________________________________________________________________________
Bool_t AliEMCALDigit::operator==(AliEMCALDigit const & digit) const
{
// Two digits are equal if they have the same Id
if ( fId == digit.fId )
return kTRUE ;
else
return kFALSE ;
}
//____________________________________________________________________________
AliEMCALDigit AliEMCALDigit::operator+(const AliEMCALDigit &digit)
{
// Adds the amplitude of digits and completes the list of primary particles
// if amplitude is larger than
fAmp += digit.fAmp ;
if(fTime > digit.fTime)
fTime = digit.fTime ;
if (digit.fTimeR < fTimeR)
fTimeR = digit.fTimeR ;
Int_t max1 = fNprimary ;
Int_t max2 = fNiparent ;
Int_t index ;
for (index = 0 ; index < digit.fNprimary ; index++){
Bool_t newPrim = kTRUE ;
Int_t old ;
for ( old = 0 ; (old < max1) && newPrim; old++) { //already have this primary?
if(fPrimary[old] == digit.fPrimary[index]) {
newPrim = kFALSE;
fDEPrimary[old] += digit.fDEPrimary[index];
}
}
if (newPrim) {
if(max1<fNMaxPrimary){
fPrimary[max1] = digit.fPrimary[index] ;
fDEPrimary[max1] = digit.fDEPrimary[index] ;
fNprimary++ ;
max1++;
}
if(fNprimary==fNMaxPrimary) {
TString mess = " NMaxPrimary = " ;
mess += fNMaxPrimary ;
mess += " is too small" ;
Fatal("AliEMCALDigit::Operator+ -->" , mess.Data()) ;
}
}
}
for (index = 0 ; index < digit.fNiparent ; index++){
Bool_t newParent = kTRUE ;
Int_t old ;
for ( old = 0 ; (old < max2) && newParent; old++) { //already have this primary?
if(fIparent[old] == digit.fIparent[index]) {
newParent = kFALSE;
fDEParent[old] += digit.fDEParent[index];
}
}
if(newParent){
if(max2<fNMaxiparent) {
fIparent[max2] = digit.fIparent[index] ;
fDEParent[max2] = digit.fDEParent[index] ;
fNiparent++ ;
max2++;
}
if(fNiparent==fNMaxiparent) {
TString mess = " NMaxiparent = " ;
mess += fNMaxiparent ;
mess += " is too small" ;
Fatal("AliEMCALDigit::Operator+ -->", mess.Data()) ;
}
}
}
return *this ;
}
//____________________________________________________________________________
AliEMCALDigit AliEMCALDigit::operator*(Float_t factor)
{
// Multiplies the amplitude by a factor
Float_t tempo = static_cast<Float_t>(fAmp) ;
tempo *= factor ;
fAmp = static_cast<Int_t>(TMath::Ceil(tempo)) ;
for(Int_t i=0; i < fNprimary; i++)
fDEPrimary[i] *= factor;
for(Int_t i=0; i < fNiparent; i++)
fDEParent[i] *= factor;
return *this ;
}
//____________________________________________________________________________
ostream& operator << ( ostream& out , const AliEMCALDigit & digit)
{
// Prints the data of the digit
out << "ID " << digit.fId << " Energy = " << digit.fAmp << " Time = " << digit.fTime << endl ;
Int_t i,j ;
for(i=0;i<digit.fNprimary;i++)
out << "Primary " << i+1 << " = " << digit.fPrimary[i]
<< " : DE " << digit.fDEPrimary[i] << endl ;
for(j=0;j<digit.fNiparent;j++)
out << "Iparent " << j+1 << " = " << digit.fIparent[j]
<< " : DE " << digit.fDEParent[j] << endl ;
out << "Position in list = " << digit.fIndexInList << endl ;
return out ;
}
<commit_msg>Corrected initialization of arrays in the copy constructor (Opteron)<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
//_________________________________________________________________________
// EMCAL digit:
// A Digit is the sum of the energy lost in an EMCAL Tower
// It also stores information on Primary, and enterring particle
// tracknumbers Digits are created using AliEMCALSDigitizer, followed
// by AliEMCALDigitizer
//
//*-- Author: Sahal Yacoob (LBL)
// based on : AliPHOSDigit
//__________________________________________________________________________
// --- ROOT system ---
#include <Riostream.h>
#include <TMath.h>
// --- Standard library ---
// --- AliRoot header files ---
#include "AliEMCALDigit.h"
#include "AliEMCALGeometry.h"
ClassImp(AliEMCALDigit)
//____________________________________________________________________________
AliEMCALDigit::AliEMCALDigit() :
AliDigitNew(),
fNprimary(0),
fNMaxPrimary(5),
fPrimary(0x0),
fDEPrimary(0x0),
fNiparent(0),
fNMaxiparent(5),
fIparent(0x0),
fDEParent(0x0),
fMaxIter(0),
fTime(0.),
fTimeR(0.)
{
// default ctor
// Need to initialise for reading old files
fPrimary = new Int_t[fNMaxPrimary] ;
fDEPrimary = new Float_t[fNMaxPrimary] ;
fIparent = new Int_t[fNMaxiparent] ;
fDEParent = new Float_t[fNMaxiparent] ;
for ( Int_t i = 0; i < fNMaxPrimary ; i++) {
fPrimary[i] = -1 ;
fDEPrimary[i] = 0 ;
}
for ( Int_t i = 0; i < fNMaxiparent ; i++) {
fIparent[i] = -1 ;
fDEParent[i] = 0 ;
}
}
//____________________________________________________________________________
AliEMCALDigit::AliEMCALDigit(Int_t primary, Int_t iparent, Int_t id, Int_t DigEnergy, Float_t time, Int_t index, Float_t dE)
: AliDigitNew(),
fNprimary(0),
fNMaxPrimary(25),
fPrimary(0x0),
fDEPrimary(0x0),
fNiparent(0),
fNMaxiparent(150),
fIparent(0x0),
fDEParent(0x0),
fMaxIter(5),
fTime(time),
fTimeR(time)
{
// ctor with all data
// data memebrs of the base class (AliNewDigit)
fAmp = DigEnergy ;
fId = id ;
fIndexInList = index ;
// data members
fPrimary = new Int_t[fNMaxPrimary] ;
fDEPrimary = new Float_t[fNMaxPrimary] ;
fIparent = new Int_t[fNMaxiparent] ;
fDEParent = new Float_t[fNMaxiparent] ;
if( primary != -1){
fNprimary = 1 ;
fPrimary[0] = primary ;
fDEPrimary[0] = dE ;
fNiparent = 1 ;
fIparent[0] = iparent ;
fDEParent[0] = dE ;
}
else{ //If the contribution of this primary smaller than fDigitThreshold (AliEMCALv1)
fNprimary = 0 ;
fPrimary[0] = -1 ;
fDEPrimary[0] = 0 ;
fNiparent = 0 ;
fIparent[0] = -1 ;
fDEParent[0] = 0 ;
}
Int_t i ;
for ( i = 1; i < fNMaxPrimary ; i++) {
fPrimary[i] = -1 ;
fDEPrimary[i] = 0 ;
}
for ( i = 1; i< fNMaxiparent ; i++) {
fIparent[i] = -1 ;
fDEParent[i] = 0 ;
}
}
//____________________________________________________________________________
AliEMCALDigit::AliEMCALDigit(const AliEMCALDigit & digit)
: AliDigitNew(digit),
fNprimary(digit.fNprimary),
fNMaxPrimary(digit.fNMaxPrimary),
fPrimary(0x0),
fDEPrimary(0x0),
fNiparent(digit.fNiparent),
fNMaxiparent(digit.fNMaxiparent),
fIparent(0x0),
fDEParent(0x0),
fMaxIter(digit.fMaxIter),
fTime(digit.fTime),
fTimeR(digit.fTimeR)
{
// copy ctor
// data memebrs of the base class (AliNewDigit)
fAmp = digit.fAmp ;
fId = digit.fId;
fIndexInList = digit.fIndexInList ;
// data members
fPrimary = new Int_t[fNMaxPrimary] ;
fDEPrimary = new Float_t[fNMaxPrimary] ;
fIparent = new Int_t[fNMaxiparent] ;
fDEParent = new Float_t[fNMaxiparent] ;
Int_t i ;
for ( i = 0; i < fNMaxPrimary ; i++) {
fPrimary[i] = digit.fPrimary[i] ;
fDEPrimary[i] = digit.fDEPrimary[i] ;
}
Int_t j ;
for (j = 0; j< fNMaxiparent ; j++) {
fIparent[j] = digit.fIparent[j] ;
fDEParent[j] = digit.fDEParent[j] ;
}
}
//____________________________________________________________________________
AliEMCALDigit::~AliEMCALDigit()
{
// Delete array of primiries if any
delete [] fPrimary ;
delete [] fDEPrimary ;
delete [] fIparent ;
delete [] fDEParent ;
}
//____________________________________________________________________________
Int_t AliEMCALDigit::Compare(const TObject * obj) const
{
// Compares two digits with respect to its Id
// to sort according increasing Id
Int_t rv ;
AliEMCALDigit * digit = (AliEMCALDigit *)obj ;
Int_t iddiff = fId - digit->GetId() ;
if ( iddiff > 0 )
rv = 1 ;
else if ( iddiff < 0 )
rv = -1 ;
else
rv = 0 ;
return rv ;
}
//____________________________________________________________________________
Float_t AliEMCALDigit::GetEta() const
{
//return pseudorapidity for this digit
// should be change in EMCALGeometry - 19-nov-04
Float_t eta=-10., phi=-10.;
Int_t id = GetId();
const AliEMCALGeometry *g = AliEMCALGeometry::GetInstance();
g->EtaPhiFromIndex(id,eta,phi);
return eta ;
}
//____________________________________________________________________________
Float_t AliEMCALDigit::GetPhi() const
{
//return phi coordinate of digit
// should be change in EMCALGeometry - 19-nov-04
Float_t eta=-10., phi=-10.;
Int_t id = GetId();
const AliEMCALGeometry *g = AliEMCALGeometry::GetInstance();
g->EtaPhiFromIndex(id,eta,phi);
return phi ;
}
//____________________________________________________________________________
Int_t AliEMCALDigit::GetPrimary(Int_t index) const
{
// retrieves the primary particle number given its index in the list
if ( (index <= fNprimary) && (index > 0)){
return fPrimary[index-1] ;
}
return -1 ;
}
//____________________________________________________________________________
Float_t AliEMCALDigit::GetDEPrimary(Int_t index) const
{
// retrieves the primary particle energy contribution
// given its index in the list
if ( (index <= fNprimary) && (index > 0)){
return fDEPrimary[index-1] ;
}
return 0 ;
}
//____________________________________________________________________________
Int_t AliEMCALDigit::GetIparent(Int_t index) const
{
// retrieves the primary particle number given its index in the list
if ( index <= fNiparent && index > 0){
return fIparent[index-1] ;
}
return -1 ;
}
//____________________________________________________________________________
Float_t AliEMCALDigit::GetDEParent(Int_t index) const
{
// retrieves the parent particle energy contribution
// given its index in the list
if ( (index <= fNiparent) && (index > 0)){
return fDEParent[index-1] ;
}
return 0;
}
//____________________________________________________________________________
void AliEMCALDigit::ShiftPrimary(Int_t shift){
//shifts primary number to BIG offset, to separate primary in different TreeK
Int_t index ;
for(index = 0; index <fNprimary; index++ ){
fPrimary[index] = fPrimary[index]+ shift * 10000000 ;}
for(index =0; index <fNiparent; index++){
fIparent[index] = fIparent[index] + shift * 10000000 ;}
}
//____________________________________________________________________________
Bool_t AliEMCALDigit::operator==(AliEMCALDigit const & digit) const
{
// Two digits are equal if they have the same Id
if ( fId == digit.fId )
return kTRUE ;
else
return kFALSE ;
}
//____________________________________________________________________________
AliEMCALDigit AliEMCALDigit::operator+(const AliEMCALDigit &digit)
{
// Adds the amplitude of digits and completes the list of primary particles
// if amplitude is larger than
fAmp += digit.fAmp ;
if(fTime > digit.fTime)
fTime = digit.fTime ;
if (digit.fTimeR < fTimeR)
fTimeR = digit.fTimeR ;
Int_t max1 = fNprimary ;
Int_t max2 = fNiparent ;
Int_t index ;
for (index = 0 ; index < digit.fNprimary ; index++){
Bool_t newPrim = kTRUE ;
Int_t old ;
for ( old = 0 ; (old < max1) && newPrim; old++) { //already have this primary?
if(fPrimary[old] == digit.fPrimary[index]) {
newPrim = kFALSE;
fDEPrimary[old] += digit.fDEPrimary[index];
}
}
if (newPrim) {
if(max1<fNMaxPrimary){
fPrimary[max1] = digit.fPrimary[index] ;
fDEPrimary[max1] = digit.fDEPrimary[index] ;
fNprimary++ ;
max1++;
}
if(fNprimary==fNMaxPrimary) {
TString mess = " NMaxPrimary = " ;
mess += fNMaxPrimary ;
mess += " is too small" ;
Fatal("AliEMCALDigit::Operator+ -->" , mess.Data()) ;
}
}
}
for (index = 0 ; index < digit.fNiparent ; index++){
Bool_t newParent = kTRUE ;
Int_t old ;
for ( old = 0 ; (old < max2) && newParent; old++) { //already have this primary?
if(fIparent[old] == digit.fIparent[index]) {
newParent = kFALSE;
fDEParent[old] += digit.fDEParent[index];
}
}
if(newParent){
if(max2<fNMaxiparent) {
fIparent[max2] = digit.fIparent[index] ;
fDEParent[max2] = digit.fDEParent[index] ;
fNiparent++ ;
max2++;
}
if(fNiparent==fNMaxiparent) {
TString mess = " NMaxiparent = " ;
mess += fNMaxiparent ;
mess += " is too small" ;
Fatal("AliEMCALDigit::Operator+ -->", mess.Data()) ;
}
}
}
return *this ;
}
//____________________________________________________________________________
AliEMCALDigit AliEMCALDigit::operator*(Float_t factor)
{
// Multiplies the amplitude by a factor
Float_t tempo = static_cast<Float_t>(fAmp) ;
tempo *= factor ;
fAmp = static_cast<Int_t>(TMath::Ceil(tempo)) ;
for(Int_t i=0; i < fNprimary; i++)
fDEPrimary[i] *= factor;
for(Int_t i=0; i < fNiparent; i++)
fDEParent[i] *= factor;
return *this ;
}
//____________________________________________________________________________
ostream& operator << ( ostream& out , const AliEMCALDigit & digit)
{
// Prints the data of the digit
out << "ID " << digit.fId << " Energy = " << digit.fAmp << " Time = " << digit.fTime << endl ;
Int_t i,j ;
for(i=0;i<digit.fNprimary;i++)
out << "Primary " << i+1 << " = " << digit.fPrimary[i]
<< " : DE " << digit.fDEPrimary[i] << endl ;
for(j=0;j<digit.fNiparent;j++)
out << "Iparent " << j+1 << " = " << digit.fIparent[j]
<< " : DE " << digit.fDEParent[j] << endl ;
out << "Position in list = " << digit.fIndexInList << endl ;
return out ;
}
<|endoftext|> |
<commit_before>#include "BBE/BrotBoxEngine.h"
#include <iostream>
#define PERFORMANCETEST 0
#if PERFORMANCETEST
#define AMOUNTOFFRAMES (1000 * 10)
#define AMOUNTOFBATCHES (1000)
#endif
class MyGame : public bbe::Game
{
public:
#if PERFORMANCETEST
float renderTimes[AMOUNTOFFRAMES * AMOUNTOFBATCHES];
float cpuTimes[AMOUNTOFFRAMES * AMOUNTOFBATCHES];
float frameTimes[AMOUNTOFFRAMES * AMOUNTOFBATCHES];
float avg_renderTimes[AMOUNTOFBATCHES];
float avg_cpuTimes[AMOUNTOFBATCHES];
float avg_frameTimes[AMOUNTOFBATCHES];
#endif
#if !PERFORMANCETEST
bbe::CameraControlNoClip ccnc = bbe::CameraControlNoClip(this);
#endif
bbe::Random rand;
bbe::TerrainSingle terrain; //Terrain Single Draw Call (Tessellation)
//bbe::Terrain terrain; //Terrain Multi Draw Call (Tessellation)
//bbe::TerrainMesh terrain; //Meshimplementation
bbe::PointLight sunLight;
bool wireframe = false;
#if PERFORMANCETEST
int frameNumber = 0;
int batch = 0;
#endif
MyGame()
:terrain(8 * 1024, 8 * 1024, "../Third-Party/textures/dryDirt.png", 12)
{
#if !PERFORMANCETEST
ccnc.setCameraPos(bbe::Vector3(1000, 1000, 500));
#endif
terrain.setBaseTextureMult(bbe::Vector2(2, 2));
terrain.setMaxHeight(350);
float *weightsGrass = new float[terrain.getWidth() * terrain.getHeight()];
float *weightsSand = new float[terrain.getWidth() * terrain.getHeight()];
for (int i = 0; i < terrain.getHeight(); i++)
{
for (int k = 0; k < terrain.getWidth(); k++)
{
int index = i * terrain.getWidth() + k;
float heightValue = (float)terrain.projectOnTerrain(bbe::Vector3(k, i, 0)).z / 350;
float weightSand = bbe::Math::normalDist(heightValue, 0, 0.3);
float weightGras = bbe::Math::normalDist(heightValue, 0.5, 0.3);
float weightStone = bbe::Math::normalDist(heightValue, 1, 0.3);
float weightSum = weightSand + weightGras + weightStone;
weightSand /= weightSum;
weightGras /= weightSum;
weightStone /= weightSum;
weightsGrass[index] = weightGras;
weightsSand[index] = weightSand;
}
}
terrain.addTexture("../Third-Party/textures/sand.png", weightsSand);
terrain.addTexture("../Third-Party/textures/cf_ter_gcs_01.png", weightsGrass);
delete[] weightsGrass;
delete[] weightsSand;
}
virtual void onStart() override
{
sunLight.setPosition(bbe::Vector3(10000, 20000, 40000));
sunLight.setLightColor(bbe::Color(1, 1, 0.9f));
sunLight.setLightStrength(0.9f);
sunLight.setFalloffMode(bbe::LightFalloffMode::LIGHT_FALLOFF_NONE);
terrain.setBaseTextureMult(bbe::Vector2(128, 128));
}
virtual void update(float timeSinceLastFrame) override
{
#if !PERFORMANCETEST
std::cout << "FPS: " << 1 / timeSinceLastFrame << "\n";
ccnc.update(timeSinceLastFrame);
#endif
if (isKeyPressed(bbe::Key::I))
{
wireframe = !wireframe;
}
#if PERFORMANCETEST
if (frameNumber < AMOUNTOFFRAMES)
{
frameTimes[frameNumber + batch * AMOUNTOFFRAMES] = timeSinceLastFrame;
}
#endif
}
int height = 2;
virtual void draw3D(bbe::PrimitiveBrush3D & brush) override
{
brush.setFillMode(wireframe ? bbe::FillMode::WIREFRAME : bbe::FillMode::SOLID);
#if !PERFORMANCETEST
brush.setCamera(ccnc.getCameraPos(), ccnc.getCameraTarget());
#endif
#if PERFORMANCETEST
float angle = (float)frameNumber / (float)AMOUNTOFFRAMES * bbe::Math::PI * 2;
bbe::Vector3 center(4 * 1024, 4 * 1024, 0);
bbe::Vector3 distTo(2 * 1024, 4 * 1024, 0);
distTo = distTo.rotate(angle, bbe::Vector3(0, 0, 1), center);
bbe::Vector3 pos = terrain.projectOnTerrain(distTo) + bbe::Vector3(0, 0, height);
brush.setCamera(pos, center);
#endif
brush.drawTerrain(terrain);
#if PERFORMANCETEST
if (frameNumber < AMOUNTOFFRAMES)
{
renderTimes[frameNumber + batch * AMOUNTOFFRAMES] = bbe::Profiler::getRenderTime();
cpuTimes[frameNumber + batch * AMOUNTOFFRAMES] = bbe::Profiler::getCPUTime();
}
else if(frameNumber == AMOUNTOFFRAMES)
{
float avgRenderTime = 0;
float avgCpuTime = 0;
float avgFrameTime = 0;
for (int i = 3; i < AMOUNTOFFRAMES; i++)
{
avgRenderTime += renderTimes[i + batch * AMOUNTOFFRAMES];
avgCpuTime += cpuTimes[i + batch * AMOUNTOFFRAMES];
avgFrameTime += frameTimes[i + batch * AMOUNTOFFRAMES];
}
avgRenderTime /= (AMOUNTOFFRAMES - 3);
avgCpuTime /= (AMOUNTOFFRAMES - 3);
avgFrameTime /= (AMOUNTOFFRAMES - 3);
avg_renderTimes[batch] = avgRenderTime;
avg_cpuTimes[batch] = avgCpuTime;
avg_frameTimes[batch] = avgFrameTime;
frameNumber = 0;
std::cout << batch << "\n";
batch++;
height++;
if (batch == AMOUNTOFBATCHES)
{
bbe::simpleFile::writeFloatArrToFile(bbe::String("__REALrenderTimes") + height + ".txt", renderTimes, AMOUNTOFBATCHES * AMOUNTOFFRAMES);
bbe::simpleFile::writeFloatArrToFile(bbe::String("__REALcpuTimes") + height + ".txt", cpuTimes, AMOUNTOFBATCHES * AMOUNTOFFRAMES);
bbe::simpleFile::writeFloatArrToFile(bbe::String("__REALframeTimes") + height + ".txt", frameTimes, AMOUNTOFBATCHES * AMOUNTOFFRAMES);
bbe::simpleFile::writeFloatArrToFile(bbe::String("__AVGrenderTimes") + height + ".txt", avg_renderTimes, AMOUNTOFBATCHES);
bbe::simpleFile::writeFloatArrToFile(bbe::String("__AVGcpuTimes") + height + ".txt", avg_cpuTimes, AMOUNTOFBATCHES);
bbe::simpleFile::writeFloatArrToFile(bbe::String("__AVGframeTimes") + height + ".txt", avg_frameTimes, AMOUNTOFBATCHES);
std::exit(0);
}
return;
}
frameNumber++;
#endif
}
virtual void draw2D(bbe::PrimitiveBrush2D & brush) override
{
}
virtual void onEnd() override
{
}
};
int main()
{
bbe::Settings::setAmountOfLightSources(5);
MyGame *mg = new MyGame();
mg->start(1280, 720, "3D Test");
delete mg;
return 0;
}
<commit_msg>Giving some hint to the user.<commit_after>#include "BBE/BrotBoxEngine.h"
#include <iostream>
#define PERFORMANCETEST 0
#if PERFORMANCETEST
#define AMOUNTOFFRAMES (1000 * 10)
#define AMOUNTOFBATCHES (1000)
#endif
class MyGame : public bbe::Game
{
public:
#if PERFORMANCETEST
float renderTimes[AMOUNTOFFRAMES * AMOUNTOFBATCHES];
float cpuTimes[AMOUNTOFFRAMES * AMOUNTOFBATCHES];
float frameTimes[AMOUNTOFFRAMES * AMOUNTOFBATCHES];
float avg_renderTimes[AMOUNTOFBATCHES];
float avg_cpuTimes[AMOUNTOFBATCHES];
float avg_frameTimes[AMOUNTOFBATCHES];
#endif
#if !PERFORMANCETEST
bbe::CameraControlNoClip ccnc = bbe::CameraControlNoClip(this);
#endif
bbe::Random rand;
bbe::TerrainSingle terrain; //Terrain Single Draw Call (Tessellation)
//bbe::Terrain terrain; //Terrain Multi Draw Call (Tessellation)
//bbe::TerrainMesh terrain; //Meshimplementation
bbe::PointLight sunLight;
bool wireframe = false;
#if PERFORMANCETEST
int frameNumber = 0;
int batch = 0;
#endif
MyGame()
:terrain(8 * 1024, 8 * 1024, "../Third-Party/textures/dryDirt.png", 12)
{
#if !PERFORMANCETEST
ccnc.setCameraPos(bbe::Vector3(1000, 1000, 500));
#endif
terrain.setBaseTextureMult(bbe::Vector2(2, 2));
terrain.setMaxHeight(350);
float *weightsGrass = new float[terrain.getWidth() * terrain.getHeight()];
float *weightsSand = new float[terrain.getWidth() * terrain.getHeight()];
for (int i = 0; i < terrain.getHeight(); i++)
{
for (int k = 0; k < terrain.getWidth(); k++)
{
int index = i * terrain.getWidth() + k;
float heightValue = (float)terrain.projectOnTerrain(bbe::Vector3(k, i, 0)).z / 350;
float weightSand = bbe::Math::normalDist(heightValue, 0, 0.3);
float weightGras = bbe::Math::normalDist(heightValue, 0.5, 0.3);
float weightStone = bbe::Math::normalDist(heightValue, 1, 0.3);
float weightSum = weightSand + weightGras + weightStone;
weightSand /= weightSum;
weightGras /= weightSum;
weightStone /= weightSum;
weightsGrass[index] = weightGras;
weightsSand[index] = weightSand;
}
}
terrain.addTexture("../Third-Party/textures/sand.png", weightsSand);
terrain.addTexture("../Third-Party/textures/cf_ter_gcs_01.png", weightsGrass);
delete[] weightsGrass;
delete[] weightsSand;
}
virtual void onStart() override
{
sunLight.setPosition(bbe::Vector3(10000, 20000, 40000));
sunLight.setLightColor(bbe::Color(1, 1, 0.9f));
sunLight.setLightStrength(0.9f);
sunLight.setFalloffMode(bbe::LightFalloffMode::LIGHT_FALLOFF_NONE);
terrain.setBaseTextureMult(bbe::Vector2(128, 128));
}
virtual void update(float timeSinceLastFrame) override
{
#if !PERFORMANCETEST
std::cout << "FPS: " << 1 / timeSinceLastFrame << "\n";
ccnc.update(timeSinceLastFrame);
#endif
if (isKeyPressed(bbe::Key::I))
{
wireframe = !wireframe;
}
#if PERFORMANCETEST
if (frameNumber < AMOUNTOFFRAMES)
{
frameTimes[frameNumber + batch * AMOUNTOFFRAMES] = timeSinceLastFrame;
}
#endif
}
int height = 2;
virtual void draw3D(bbe::PrimitiveBrush3D & brush) override
{
brush.setFillMode(wireframe ? bbe::FillMode::WIREFRAME : bbe::FillMode::SOLID);
#if !PERFORMANCETEST
brush.setCamera(ccnc.getCameraPos(), ccnc.getCameraTarget());
#endif
#if PERFORMANCETEST
float angle = (float)frameNumber / (float)AMOUNTOFFRAMES * bbe::Math::PI * 2;
bbe::Vector3 center(4 * 1024, 4 * 1024, 0);
bbe::Vector3 distTo(2 * 1024, 4 * 1024, 0);
distTo = distTo.rotate(angle, bbe::Vector3(0, 0, 1), center);
bbe::Vector3 pos = terrain.projectOnTerrain(distTo) + bbe::Vector3(0, 0, height);
brush.setCamera(pos, center);
#endif
brush.drawTerrain(terrain);
#if PERFORMANCETEST
if (frameNumber < AMOUNTOFFRAMES)
{
renderTimes[frameNumber + batch * AMOUNTOFFRAMES] = bbe::Profiler::getRenderTime();
cpuTimes[frameNumber + batch * AMOUNTOFFRAMES] = bbe::Profiler::getCPUTime();
}
else if(frameNumber == AMOUNTOFFRAMES)
{
float avgRenderTime = 0;
float avgCpuTime = 0;
float avgFrameTime = 0;
for (int i = 3; i < AMOUNTOFFRAMES; i++)
{
avgRenderTime += renderTimes[i + batch * AMOUNTOFFRAMES];
avgCpuTime += cpuTimes[i + batch * AMOUNTOFFRAMES];
avgFrameTime += frameTimes[i + batch * AMOUNTOFFRAMES];
}
avgRenderTime /= (AMOUNTOFFRAMES - 3);
avgCpuTime /= (AMOUNTOFFRAMES - 3);
avgFrameTime /= (AMOUNTOFFRAMES - 3);
avg_renderTimes[batch] = avgRenderTime;
avg_cpuTimes[batch] = avgCpuTime;
avg_frameTimes[batch] = avgFrameTime;
frameNumber = 0;
std::cout << batch << "\n";
batch++;
height++;
if (batch == AMOUNTOFBATCHES)
{
bbe::simpleFile::writeFloatArrToFile(bbe::String("__REALrenderTimes") + height + ".txt", renderTimes, AMOUNTOFBATCHES * AMOUNTOFFRAMES);
bbe::simpleFile::writeFloatArrToFile(bbe::String("__REALcpuTimes") + height + ".txt", cpuTimes, AMOUNTOFBATCHES * AMOUNTOFFRAMES);
bbe::simpleFile::writeFloatArrToFile(bbe::String("__REALframeTimes") + height + ".txt", frameTimes, AMOUNTOFBATCHES * AMOUNTOFFRAMES);
bbe::simpleFile::writeFloatArrToFile(bbe::String("__AVGrenderTimes") + height + ".txt", avg_renderTimes, AMOUNTOFBATCHES);
bbe::simpleFile::writeFloatArrToFile(bbe::String("__AVGcpuTimes") + height + ".txt", avg_cpuTimes, AMOUNTOFBATCHES);
bbe::simpleFile::writeFloatArrToFile(bbe::String("__AVGframeTimes") + height + ".txt", avg_frameTimes, AMOUNTOFBATCHES);
std::exit(0);
}
return;
}
frameNumber++;
#endif
}
virtual void draw2D(bbe::PrimitiveBrush2D & brush) override
{
}
virtual void onEnd() override
{
}
};
int main()
{
std::cout << "Loading. Please wait. This might take a while." << std::endl;
bbe::Settings::setAmountOfLightSources(5);
MyGame *mg = new MyGame();
mg->start(1280, 720, "3D Test");
delete mg;
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Run all of our test shell tests. This is just an entry point
// to kick off gTest's RUN_ALL_TESTS().
#include "base/basictypes.h"
#if defined(OS_WIN)
#include <windows.h>
#include <commctrl.h>
#endif
#include "base/at_exit.h"
#include "base/icu_util.h"
#include "base/message_loop.h"
#include "base/process_util.h"
#include "webkit/tools/test_shell/simple_resource_loader_bridge.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_test.h"
#include "testing/gtest/include/gtest/gtest.h"
const char* TestShellTest::kJavascriptDelayExitScript =
"<script>"
"window.layoutTestController.waitUntilDone();"
"window.addEventListener('load', function() {"
" var x = document.body.clientWidth;" // Force a document layout
" window.layoutTestController.notifyDone();"
"});"
"</script>";
int main(int argc, char* argv[]) {
process_util::EnableTerminationOnHeapCorruption();
// Some unittests may use base::Singleton<>, thus we need to instanciate
// the AtExitManager or else we will leak objects.
base::AtExitManager at_exit_manager;
#if defined(OS_WIN)
TestShell::InitLogging(true); // suppress error dialogs
// Initialize test shell in non-interactive mode, which will let us load one
// request than automatically quit.
TestShell::InitializeTestShell(false);
// Some of the individual tests wind up calling TestShell::WaitTestFinished
// which has a timeout in it. For these tests, we don't care about a timeout
// so just set it to be a really large number. This is necessary because
// when running under Purify, we were hitting those timeouts.
TestShell::SetFileTestTimeout(USER_TIMER_MAXIMUM);
#endif
// Allocate a message loop for this thread. Although it is not used
// directly, its constructor sets up some necessary state.
MessageLoop main_message_loop;
// Load ICU data tables
icu_util::Initialize();
#if defined(OS_WIN)
INITCOMMONCONTROLSEX InitCtrlEx;
InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX);
InitCtrlEx.dwICC = ICC_STANDARD_CLASSES;
InitCommonControlsEx(&InitCtrlEx);
#endif
// Run the actual tests
testing::InitGoogleTest(&argc, argv);
int result = RUN_ALL_TESTS();
#if defined(OS_WIN)
TestShell::ShutdownTestShell();
TestShell::CleanupLogging();
#endif
return result;
}
<commit_msg>fix bustage, use new api<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Run all of our test shell tests. This is just an entry point
// to kick off gTest's RUN_ALL_TESTS().
#include "base/basictypes.h"
#if defined(OS_WIN)
#include <windows.h>
#include <commctrl.h>
#endif
#include "base/at_exit.h"
#include "base/icu_util.h"
#include "base/message_loop.h"
#include "base/process_util.h"
#include "webkit/tools/test_shell/simple_resource_loader_bridge.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_test.h"
#include "testing/gtest/include/gtest/gtest.h"
const char* TestShellTest::kJavascriptDelayExitScript =
"<script>"
"window.layoutTestController.waitUntilDone();"
"window.addEventListener('load', function() {"
" var x = document.body.clientWidth;" // Force a document layout
" window.layoutTestController.notifyDone();"
"});"
"</script>";
int main(int argc, char* argv[]) {
process_util::EnableTerminationOnHeapCorruption();
// Some unittests may use base::Singleton<>, thus we need to instanciate
// the AtExitManager or else we will leak objects.
base::AtExitManager at_exit_manager;
#if defined(OS_WIN)
TestShell::InitLogging(true, false); // suppress error dialogs
// Initialize test shell in non-interactive mode, which will let us load one
// request than automatically quit.
TestShell::InitializeTestShell(false);
// Some of the individual tests wind up calling TestShell::WaitTestFinished
// which has a timeout in it. For these tests, we don't care about a timeout
// so just set it to be a really large number. This is necessary because
// when running under Purify, we were hitting those timeouts.
TestShell::SetFileTestTimeout(USER_TIMER_MAXIMUM);
#endif
// Allocate a message loop for this thread. Although it is not used
// directly, its constructor sets up some necessary state.
MessageLoop main_message_loop;
// Load ICU data tables
icu_util::Initialize();
#if defined(OS_WIN)
INITCOMMONCONTROLSEX InitCtrlEx;
InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX);
InitCtrlEx.dwICC = ICC_STANDARD_CLASSES;
InitCommonControlsEx(&InitCtrlEx);
#endif
// Run the actual tests
testing::InitGoogleTest(&argc, argv);
int result = RUN_ALL_TESTS();
#if defined(OS_WIN)
TestShell::ShutdownTestShell();
TestShell::CleanupLogging();
#endif
return result;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: XMLTextColumnsExport.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2004-07-13 08:36:14 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _COM_SUN_STAR_TEXT_XTEXTCOLUMNS_HPP_
#include <com/sun/star/text/XTextColumns.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_TEXTCOLUMN_HPP_
#include <com/sun/star/text/TextColumn.hpp>
#endif
#ifndef _COM_SUN_STAR_STYLE_VERTICALALIGNMENT_HPP_
#include <com/sun/star/style/VerticalAlignment.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include "xmlexp.hxx"
#endif
#ifndef _XMLOFF_XMLTEXTCOLUMNSEXPORT_HXX
#include "XMLTextColumnsExport.hxx"
#endif
using namespace ::com::sun::star::style;
using namespace ::com::sun::star::text;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::rtl;
using namespace ::xmloff::token;
XMLTextColumnsExport::XMLTextColumnsExport( SvXMLExport& rExp ) :
rExport( rExp ),
sSeparatorLineIsOn(RTL_CONSTASCII_USTRINGPARAM("SeparatorLineIsOn")),
sSeparatorLineWidth(RTL_CONSTASCII_USTRINGPARAM("SeparatorLineWidth")),
sSeparatorLineColor(RTL_CONSTASCII_USTRINGPARAM("SeparatorLineColor")),
sSeparatorLineRelativeHeight(RTL_CONSTASCII_USTRINGPARAM("SeparatorLineRelativeHeight")),
sSeparatorLineVerticalAlignment(RTL_CONSTASCII_USTRINGPARAM("SeparatorLineVerticalAlignment")),
sIsAutomatic(RTL_CONSTASCII_USTRINGPARAM("IsAutomatic")),
sAutomaticDistance(RTL_CONSTASCII_USTRINGPARAM("AutomaticDistance"))
{
}
void XMLTextColumnsExport::exportXML( const Any& rAny )
{
Reference < XTextColumns > xColumns;
rAny >>= xColumns;
Sequence < TextColumn > aColumns = xColumns->getColumns();
const TextColumn *pColumns = aColumns.getArray();
sal_Int32 nCount = aColumns.getLength();
OUStringBuffer sValue;
GetExport().GetMM100UnitConverter().convertNumber( sValue, nCount );
GetExport().AddAttribute( XML_NAMESPACE_FO, XML_COLUMN_COUNT,
sValue.makeStringAndClear() );
// handle 'automatic' columns
Reference < XPropertySet > xPropSet( xColumns, UNO_QUERY );
if( xPropSet.is() )
{
Any aAny = xPropSet->getPropertyValue( sIsAutomatic );
if ( *(sal_Bool*)aAny.getValue() )
{
aAny = xPropSet->getPropertyValue( sAutomaticDistance );
sal_Int32 nDistance = 0;
aAny >>= nDistance;
OUStringBuffer aBuffer;
GetExport().GetMM100UnitConverter().convertMeasure(
aBuffer, nDistance );
GetExport().AddAttribute( XML_NAMESPACE_FO,
XML_COLUMN_GAP,
aBuffer.makeStringAndClear() );
}
}
SvXMLElementExport aElem( GetExport(), XML_NAMESPACE_STYLE, XML_COLUMNS,
sal_True, sal_True );
if( xPropSet.is() )
{
Any aAny = xPropSet->getPropertyValue( sSeparatorLineIsOn );
if( *(sal_Bool *)aAny.getValue() )
{
// style:width
aAny = xPropSet->getPropertyValue( sSeparatorLineWidth );
sal_Int32 nWidth;
aAny >>= nWidth;
GetExport().GetMM100UnitConverter().convertMeasure( sValue,
nWidth );
GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_WIDTH,
sValue.makeStringAndClear() );
// style:color
aAny = xPropSet->getPropertyValue( sSeparatorLineColor );
sal_Int32 nColor;
aAny >>= nColor;
GetExport().GetMM100UnitConverter().convertColor( sValue,
nColor );
GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_COLOR,
sValue.makeStringAndClear() );
// style:height
aAny = xPropSet->getPropertyValue( sSeparatorLineRelativeHeight );
sal_Int8 nHeight;
aAny >>= nHeight;
GetExport().GetMM100UnitConverter().convertPercent( sValue,
nHeight );
GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_HEIGHT,
sValue.makeStringAndClear() );
// style:vertical-align
aAny = xPropSet->getPropertyValue( sSeparatorLineVerticalAlignment );
VerticalAlignment eVertAlign;
aAny >>= eVertAlign;
enum XMLTokenEnum eStr = XML_TOKEN_INVALID;
switch( eVertAlign )
{
// case VerticalAlignment_TOP: eStr = XML_TOP;
case VerticalAlignment_MIDDLE: eStr = XML_MIDDLE; break;
case VerticalAlignment_BOTTOM: eStr = XML_BOTTOM; break;
}
if( eStr != XML_TOKEN_INVALID)
GetExport().AddAttribute( XML_NAMESPACE_STYLE,
XML_VERTICAL_ALIGN, eStr );
// style:column-sep
SvXMLElementExport aElem( GetExport(), XML_NAMESPACE_STYLE,
XML_COLUMN_SEP,
sal_True, sal_True );
}
}
while( nCount-- )
{
// style:rel-width
GetExport().GetMM100UnitConverter().convertNumber( sValue,
pColumns->Width );
sValue.append( (sal_Unicode)'*' );
GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_REL_WIDTH,
sValue.makeStringAndClear() );
// fo:margin-left
GetExport().GetMM100UnitConverter().convertMeasure( sValue,
pColumns->LeftMargin );
GetExport().AddAttribute( XML_NAMESPACE_FO, XML_START_INDENT,
sValue.makeStringAndClear() );
// fo:margin-right
GetExport().GetMM100UnitConverter().convertMeasure( sValue,
pColumns->RightMargin );
GetExport().AddAttribute( XML_NAMESPACE_FO, XML_END_INDENT,
sValue.makeStringAndClear() );
// style:column
SvXMLElementExport aElem( GetExport(), XML_NAMESPACE_STYLE, XML_COLUMN,
sal_True, sal_True );
pColumns++;
}
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.6.298); FILE MERGED 2005/09/05 14:40:02 rt 1.6.298.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XMLTextColumnsExport.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-09 15:20:24 $
*
* 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 _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _COM_SUN_STAR_TEXT_XTEXTCOLUMNS_HPP_
#include <com/sun/star/text/XTextColumns.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_TEXTCOLUMN_HPP_
#include <com/sun/star/text/TextColumn.hpp>
#endif
#ifndef _COM_SUN_STAR_STYLE_VERTICALALIGNMENT_HPP_
#include <com/sun/star/style/VerticalAlignment.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include "xmlexp.hxx"
#endif
#ifndef _XMLOFF_XMLTEXTCOLUMNSEXPORT_HXX
#include "XMLTextColumnsExport.hxx"
#endif
using namespace ::com::sun::star::style;
using namespace ::com::sun::star::text;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::rtl;
using namespace ::xmloff::token;
XMLTextColumnsExport::XMLTextColumnsExport( SvXMLExport& rExp ) :
rExport( rExp ),
sSeparatorLineIsOn(RTL_CONSTASCII_USTRINGPARAM("SeparatorLineIsOn")),
sSeparatorLineWidth(RTL_CONSTASCII_USTRINGPARAM("SeparatorLineWidth")),
sSeparatorLineColor(RTL_CONSTASCII_USTRINGPARAM("SeparatorLineColor")),
sSeparatorLineRelativeHeight(RTL_CONSTASCII_USTRINGPARAM("SeparatorLineRelativeHeight")),
sSeparatorLineVerticalAlignment(RTL_CONSTASCII_USTRINGPARAM("SeparatorLineVerticalAlignment")),
sIsAutomatic(RTL_CONSTASCII_USTRINGPARAM("IsAutomatic")),
sAutomaticDistance(RTL_CONSTASCII_USTRINGPARAM("AutomaticDistance"))
{
}
void XMLTextColumnsExport::exportXML( const Any& rAny )
{
Reference < XTextColumns > xColumns;
rAny >>= xColumns;
Sequence < TextColumn > aColumns = xColumns->getColumns();
const TextColumn *pColumns = aColumns.getArray();
sal_Int32 nCount = aColumns.getLength();
OUStringBuffer sValue;
GetExport().GetMM100UnitConverter().convertNumber( sValue, nCount );
GetExport().AddAttribute( XML_NAMESPACE_FO, XML_COLUMN_COUNT,
sValue.makeStringAndClear() );
// handle 'automatic' columns
Reference < XPropertySet > xPropSet( xColumns, UNO_QUERY );
if( xPropSet.is() )
{
Any aAny = xPropSet->getPropertyValue( sIsAutomatic );
if ( *(sal_Bool*)aAny.getValue() )
{
aAny = xPropSet->getPropertyValue( sAutomaticDistance );
sal_Int32 nDistance = 0;
aAny >>= nDistance;
OUStringBuffer aBuffer;
GetExport().GetMM100UnitConverter().convertMeasure(
aBuffer, nDistance );
GetExport().AddAttribute( XML_NAMESPACE_FO,
XML_COLUMN_GAP,
aBuffer.makeStringAndClear() );
}
}
SvXMLElementExport aElem( GetExport(), XML_NAMESPACE_STYLE, XML_COLUMNS,
sal_True, sal_True );
if( xPropSet.is() )
{
Any aAny = xPropSet->getPropertyValue( sSeparatorLineIsOn );
if( *(sal_Bool *)aAny.getValue() )
{
// style:width
aAny = xPropSet->getPropertyValue( sSeparatorLineWidth );
sal_Int32 nWidth;
aAny >>= nWidth;
GetExport().GetMM100UnitConverter().convertMeasure( sValue,
nWidth );
GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_WIDTH,
sValue.makeStringAndClear() );
// style:color
aAny = xPropSet->getPropertyValue( sSeparatorLineColor );
sal_Int32 nColor;
aAny >>= nColor;
GetExport().GetMM100UnitConverter().convertColor( sValue,
nColor );
GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_COLOR,
sValue.makeStringAndClear() );
// style:height
aAny = xPropSet->getPropertyValue( sSeparatorLineRelativeHeight );
sal_Int8 nHeight;
aAny >>= nHeight;
GetExport().GetMM100UnitConverter().convertPercent( sValue,
nHeight );
GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_HEIGHT,
sValue.makeStringAndClear() );
// style:vertical-align
aAny = xPropSet->getPropertyValue( sSeparatorLineVerticalAlignment );
VerticalAlignment eVertAlign;
aAny >>= eVertAlign;
enum XMLTokenEnum eStr = XML_TOKEN_INVALID;
switch( eVertAlign )
{
// case VerticalAlignment_TOP: eStr = XML_TOP;
case VerticalAlignment_MIDDLE: eStr = XML_MIDDLE; break;
case VerticalAlignment_BOTTOM: eStr = XML_BOTTOM; break;
}
if( eStr != XML_TOKEN_INVALID)
GetExport().AddAttribute( XML_NAMESPACE_STYLE,
XML_VERTICAL_ALIGN, eStr );
// style:column-sep
SvXMLElementExport aElem( GetExport(), XML_NAMESPACE_STYLE,
XML_COLUMN_SEP,
sal_True, sal_True );
}
}
while( nCount-- )
{
// style:rel-width
GetExport().GetMM100UnitConverter().convertNumber( sValue,
pColumns->Width );
sValue.append( (sal_Unicode)'*' );
GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_REL_WIDTH,
sValue.makeStringAndClear() );
// fo:margin-left
GetExport().GetMM100UnitConverter().convertMeasure( sValue,
pColumns->LeftMargin );
GetExport().AddAttribute( XML_NAMESPACE_FO, XML_START_INDENT,
sValue.makeStringAndClear() );
// fo:margin-right
GetExport().GetMM100UnitConverter().convertMeasure( sValue,
pColumns->RightMargin );
GetExport().AddAttribute( XML_NAMESPACE_FO, XML_END_INDENT,
sValue.makeStringAndClear() );
// style:column
SvXMLElementExport aElem( GetExport(), XML_NAMESPACE_STYLE, XML_COLUMN,
sal_True, sal_True );
pColumns++;
}
}
<|endoftext|> |
<commit_before>// Copyright 2015 Project Vogue. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <vector>
#include "elang/lir/transforms/parallel_copy_expander.h"
#include "base/logging.h"
#include "elang/lir/editor.h"
#include "elang/lir/factory.h"
#include "elang/lir/instructions.h"
#include "elang/lir/literals.h"
#include "elang/lir/target.h"
#include "elang/lir/value.h"
namespace elang {
namespace lir {
namespace {
bool IsImmediate(Value value) {
return !value.is_physical() && !value.is_virtual() &&
value.kind != Value::Kind::Argument &&
value.kind != Value::Kind::Parameter && !value.is_stack_slot();
}
} // namespace
//////////////////////////////////////////////////////////////////////
//
// ParallelCopyExpander::Task
//
struct ParallelCopyExpander::Task {
Value output;
Value input;
};
//////////////////////////////////////////////////////////////////////
//
// ParallelCopyExpander
//
ParallelCopyExpander::ParallelCopyExpander(Factory* factory, Value type)
: FactoryUser(factory), type_(type) {
}
ParallelCopyExpander::~ParallelCopyExpander() {
}
void ParallelCopyExpander::AddScratch(Value scratch) {
DCHECK(scratch.is_physical());
DCHECK(scratch.type == type_.type);
if (scratch1_.is_void()) {
DCHECK_NE(scratch1_, scratch);
scratch1_ = scratch;
return;
}
DCHECK_NE(scratch1_, scratch);
DCHECK(scratch2_.is_void());
scratch2_ = scratch;
}
void ParallelCopyExpander::AddTask(Value output, Value input) {
if (output == input)
return;
DCHECK_NE(output, input);
DCHECK_EQ(output.type, type_.type);
DCHECK_EQ(input.type, type_.type);
DCHECK_EQ(output.size, input.size);
if (!IsImmediate(input))
dependency_graph_.AddEdge(output, input);
tasks_.push_back({output, input});
}
void ParallelCopyExpander::EmitCopy(Value output, Value input) {
if (input.is_physical()) {
instructions_.push_back(factory()->NewCopyInstruction(output, input));
return;
}
if (IsImmediate(input)) {
if (output.is_physical() || Target::HasCopyImmediateToMemory(type_)) {
instructions_.push_back(factory()->NewLiteralInstruction(output, input));
return;
}
}
if (output.is_physical()) {
instructions_.push_back(factory()->NewCopyInstruction(output, input));
return;
}
EmitCopy(scratch1_, input);
EmitCopy(output, scratch1_);
}
ParallelCopyExpander::Task ParallelCopyExpander::EmitSwap(Value output,
Value input) {
dependency_graph_.RemoveEdge(output, input);
if (!output.is_physical() || !input.is_physical()) {
if (output.is_physical() || input.is_physical()) {
EmitCopy(output, input);
return {input, input};
}
EmitCopy(scratch1_, input);
EmitCopy(scratch2_, output);
EmitCopy(input, scratch2_);
EmitCopy(output, scratch1_);
return {scratch2_, input};
}
DCHECK(output.is_physical() && input.is_physical());
if (Target::HasSwapInstruction(type_)) {
instructions_.push_back(
factory()->NewPCopyInstruction({output, input}, {input, output}));
return {input, input};
}
EmitCopy(scratch1_, input);
EmitCopy(input, output);
EmitCopy(output, scratch1_);
return {input, input};
}
std::vector<Instruction*> ParallelCopyExpander::Expand() {
if (!Prepare())
return {};
DCHECK(instructions_.empty());
while (!tasks_.empty()) {
std::vector<Task> pending_tasks;
for (auto const& task : tasks_) {
if (dependency_graph_.HasInEdge(task.output)) {
pending_tasks.push_back(task);
continue;
}
if (!IsImmediate(task.input))
dependency_graph_.RemoveEdge(task.output, task.input);
EmitCopy(task.output, task.input);
}
if (pending_tasks.empty())
break;
DCHECK_GE(pending_tasks.size(), 2u);
// Emit swap for one task and rewrite rest of tasks using swapped output.
auto const swap = pending_tasks.back();
pending_tasks.pop_back();
auto const swapped = EmitSwap(swap.output, swap.input);
tasks_.clear();
for (auto& task : pending_tasks) {
if (task.input != swap.output) {
tasks_.push_back(task);
continue;
}
// Rewrite task to use new input.
dependency_graph_.RemoveEdge(task.output, task.input);
if (task.output == swapped.input)
continue;
tasks_.push_back({task.output, swapped.output});
dependency_graph_.AddEdge(task.output, swapped.output);
}
}
return std::move(instructions_);
}
bool ParallelCopyExpander::Prepare() {
if (scratch2_.is_physical())
return true;
auto number_of_scratches = scratch1_.is_physical() ? 1 : 0;
auto number_of_required_scratches = 0;
for (auto const& task : tasks_) {
auto const output = task.output;
if (output.is_physical()) {
if (dependency_graph_.HasInEdge(output))
continue;
if (scratch1_.is_void()) {
DCHECK_EQ(number_of_scratches, 0);
scratch1_ = output;
number_of_scratches = 1;
continue;
}
// Since, we can do all variation of copy by two scratch registers,
// we don't need to check rest of tasks.
DCHECK_EQ(number_of_scratches, 1);
DCHECK_NE(scratch1_, scratch2_);
scratch2_ = output;
return true;
}
if (number_of_required_scratches == 2)
continue;
auto const input = task.input;
if (input.is_physical())
continue;
if (IsImmediate(input)) {
if (Target::HasCopyImmediateToMemory(input))
continue;
number_of_required_scratches = 1;
continue;
}
if (!dependency_graph_.HasInEdge(output)) {
number_of_required_scratches = 1;
continue;
}
// Memory rotation requires two scratch registers.
number_of_required_scratches = 2;
}
return number_of_scratches >= number_of_required_scratches;
}
} // namespace lir
} // namespace elang
<commit_msg>elang/lir/transform: Change code layout of |ParallelCopyExpander::EmitSwap()| for ease of reading.<commit_after>// Copyright 2015 Project Vogue. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <vector>
#include "elang/lir/transforms/parallel_copy_expander.h"
#include "base/logging.h"
#include "elang/lir/editor.h"
#include "elang/lir/factory.h"
#include "elang/lir/instructions.h"
#include "elang/lir/literals.h"
#include "elang/lir/target.h"
#include "elang/lir/value.h"
namespace elang {
namespace lir {
namespace {
bool IsImmediate(Value value) {
return !value.is_physical() && !value.is_virtual() &&
value.kind != Value::Kind::Argument &&
value.kind != Value::Kind::Parameter && !value.is_stack_slot();
}
} // namespace
//////////////////////////////////////////////////////////////////////
//
// ParallelCopyExpander::Task
//
struct ParallelCopyExpander::Task {
Value output;
Value input;
};
//////////////////////////////////////////////////////////////////////
//
// ParallelCopyExpander
//
ParallelCopyExpander::ParallelCopyExpander(Factory* factory, Value type)
: FactoryUser(factory), type_(type) {
}
ParallelCopyExpander::~ParallelCopyExpander() {
}
void ParallelCopyExpander::AddScratch(Value scratch) {
DCHECK(scratch.is_physical());
DCHECK(scratch.type == type_.type);
if (scratch1_.is_void()) {
DCHECK_NE(scratch1_, scratch);
scratch1_ = scratch;
return;
}
DCHECK_NE(scratch1_, scratch);
DCHECK(scratch2_.is_void());
scratch2_ = scratch;
}
void ParallelCopyExpander::AddTask(Value output, Value input) {
if (output == input)
return;
DCHECK_NE(output, input);
DCHECK_EQ(output.type, type_.type);
DCHECK_EQ(input.type, type_.type);
DCHECK_EQ(output.size, input.size);
if (!IsImmediate(input))
dependency_graph_.AddEdge(output, input);
tasks_.push_back({output, input});
}
void ParallelCopyExpander::EmitCopy(Value output, Value input) {
if (input.is_physical()) {
instructions_.push_back(factory()->NewCopyInstruction(output, input));
return;
}
if (IsImmediate(input)) {
if (output.is_physical() || Target::HasCopyImmediateToMemory(type_)) {
instructions_.push_back(factory()->NewLiteralInstruction(output, input));
return;
}
}
if (output.is_physical()) {
instructions_.push_back(factory()->NewCopyInstruction(output, input));
return;
}
EmitCopy(scratch1_, input);
EmitCopy(output, scratch1_);
}
ParallelCopyExpander::Task ParallelCopyExpander::EmitSwap(Value output,
Value input) {
dependency_graph_.RemoveEdge(output, input);
if (output.is_physical() && input.is_physical()) {
if (Target::HasSwapInstruction(type_)) {
instructions_.push_back(
factory()->NewPCopyInstruction({output, input}, {input, output}));
return {input, input};
}
EmitCopy(scratch1_, input);
EmitCopy(input, output);
EmitCopy(output, scratch1_);
return {input, input};
}
if (output.is_physical()) {
EmitCopy(scratch1_, input);
EmitCopy(input, output);
EmitCopy(output, scratch1_);
return {scratch1_, input};
}
if (input.is_physical()) {
EmitCopy(scratch1_, output);
EmitCopy(output, input);
EmitCopy(input, scratch1_);
return {scratch1_, input};
}
EmitCopy(scratch1_, input);
EmitCopy(scratch2_, output);
EmitCopy(input, scratch2_);
EmitCopy(output, scratch1_);
return {scratch2_, input};
}
std::vector<Instruction*> ParallelCopyExpander::Expand() {
if (!Prepare())
return {};
DCHECK(instructions_.empty());
while (!tasks_.empty()) {
std::vector<Task> pending_tasks;
for (auto const& task : tasks_) {
if (dependency_graph_.HasInEdge(task.output)) {
pending_tasks.push_back(task);
continue;
}
if (!IsImmediate(task.input))
dependency_graph_.RemoveEdge(task.output, task.input);
EmitCopy(task.output, task.input);
}
if (pending_tasks.empty())
break;
DCHECK_GE(pending_tasks.size(), 2u);
// Emit swap for one task and rewrite rest of tasks using swapped output.
auto const swap = pending_tasks.back();
pending_tasks.pop_back();
auto const swapped = EmitSwap(swap.output, swap.input);
tasks_.clear();
for (auto& task : pending_tasks) {
if (task.input != swap.output) {
tasks_.push_back(task);
continue;
}
// Rewrite task to use new input.
dependency_graph_.RemoveEdge(task.output, task.input);
if (task.output == swapped.input)
continue;
tasks_.push_back({task.output, swapped.output});
dependency_graph_.AddEdge(task.output, swapped.output);
}
}
return std::move(instructions_);
}
bool ParallelCopyExpander::Prepare() {
if (scratch2_.is_physical())
return true;
auto number_of_scratches = scratch1_.is_physical() ? 1 : 0;
auto number_of_required_scratches = 0;
for (auto const& task : tasks_) {
auto const output = task.output;
if (output.is_physical()) {
if (dependency_graph_.HasInEdge(output))
continue;
if (scratch1_.is_void()) {
DCHECK_EQ(number_of_scratches, 0);
scratch1_ = output;
number_of_scratches = 1;
continue;
}
// Since, we can do all variation of copy by two scratch registers,
// we don't need to check rest of tasks.
DCHECK_EQ(number_of_scratches, 1);
DCHECK_NE(scratch1_, scratch2_);
scratch2_ = output;
return true;
}
if (number_of_required_scratches == 2)
continue;
auto const input = task.input;
if (input.is_physical())
continue;
if (IsImmediate(input)) {
if (Target::HasCopyImmediateToMemory(input))
continue;
number_of_required_scratches = 1;
continue;
}
if (!dependency_graph_.HasInEdge(output)) {
number_of_required_scratches = 1;
continue;
}
// Memory rotation requires two scratch registers.
number_of_required_scratches = 2;
}
return number_of_scratches >= number_of_required_scratches;
}
} // namespace lir
} // namespace elang
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: ViewShellImplementation.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: pjunck $ $Date: 2004-10-28 13:27:31 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SD_VIEW_SHELL_IMPLEMENTATION_HXX
#define SD_VIEW_SHELL_IMPLEMENTATION_HXX
#include "ViewShell.hxx"
namespace sd {
/** This class contains (will contain) the implementation of methods that
have not be accessible from the outside.
*/
class ViewShell::Implementation
{
public:
bool mbIsShowingUIControls;
bool mbIsMainViewShell;
/// Set to true when the ViewShell::Init() method has been called.
bool mbIsInitialized;
Implementation (ViewShell& rViewShell);
~Implementation (void);
/** Process the SID_MODIFY slot.
*/
void ProcessModifyPageSlot (
SfxRequest& rRequest,
SdPage* pCurrentPage,
PageKind ePageKind);
private:
ViewShell& mrViewShell;
};
} // end of namespace sd
#endif
<commit_msg>INTEGRATION: CWS impress15 (1.3.66); FILE MERGED 2004/11/01 09:47:29 af 1.3.66.1: #i31283# Added new method GetViewId.<commit_after>/*************************************************************************
*
* $RCSfile: ViewShellImplementation.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2004-11-16 16:35:23 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SD_VIEW_SHELL_IMPLEMENTATION_HXX
#define SD_VIEW_SHELL_IMPLEMENTATION_HXX
#include "ViewShell.hxx"
namespace sd {
/** This class contains (will contain) the implementation of methods that
have not be accessible from the outside.
*/
class ViewShell::Implementation
{
public:
bool mbIsShowingUIControls;
bool mbIsMainViewShell;
/// Set to true when the ViewShell::Init() method has been called.
bool mbIsInitialized;
Implementation (ViewShell& rViewShell);
~Implementation (void);
/** Process the SID_MODIFY slot.
*/
void ProcessModifyPageSlot (
SfxRequest& rRequest,
SdPage* pCurrentPage,
PageKind ePageKind);
/** Determine the view id of the view shell. This corresponds to the
view id stored in the SfxViewFrame class.
We can not use the view of that class because with the introduction
of the multi pane GUI we do not switch the SfxViewShell anymore when
switching the view in the center pane. The view id of the
SfxViewFrame is thus not modified and we can not set it from the
outside.
The view id is still needed for the SFX to determine on start up
(e.g. after loading a document) which ViewShellBase sub class to
use. These sub classes--like OutlineViewShellBase--exist only to be
used by the SFX as factories. They only set the initial pane
configuration, nothing more.
So what we do here in essence is to return on of the
ViewShellFactoryIds that can be used to select the factory that
creates the ViewShellBase subclass with the initial pane
configuration that has in the center pane a view shell of the same
type as mrViewShell.
*/
sal_uInt16 GetViewId (void);
private:
ViewShell& mrViewShell;
};
} // end of namespace sd
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include "gtest/gtest.h"
#include <Rosetta/Cards/Cards.hpp>
#include <Rosetta/Enums/CardEnums.hpp>
using namespace RosettaStone;
TEST(Cards, GetAllCards)
{
const std::vector<Card> cards1 = Cards::GetInstance().GetAllCards();
ASSERT_FALSE(cards1.empty());
EXPECT_EQ(cards1.size(), 6086u);
}
TEST(Cards, FindCardByID)
{
const Card card1 = Cards::GetInstance().FindCardByID("AT_001");
const Card card2 = Cards::GetInstance().FindCardByID("");
EXPECT_EQ(card1.id, "AT_001");
EXPECT_EQ(card2.id, "");
}
TEST(Cards, FindCardByRarity)
{
Cards& instance = Cards::GetInstance();
std::vector<Card> cards1 = instance.FindCardByRarity(Rarity::COMMON);
std::vector<Card> cards2 = instance.FindCardByRarity(Rarity::RARE);
std::vector<Card> cards3 = instance.FindCardByRarity(Rarity::EPIC);
std::vector<Card> cards4 = instance.FindCardByRarity(Rarity::LEGENDARY);
std::vector<Card> cards5 = instance.FindCardByRarity(Rarity::FREE);
std::vector<Card> cards6 = instance.FindCardByRarity(Rarity::INVALID);
std::vector<Card> cards7 = instance.FindCardByRarity(Rarity::UNKNOWN_6);
EXPECT_EQ(Rarity::COMMON, cards1.front().GetRarity());
EXPECT_EQ(Rarity::RARE, cards2.front().GetRarity());
EXPECT_EQ(Rarity::EPIC, cards3.front().GetRarity());
EXPECT_EQ(Rarity::LEGENDARY, cards4.front().GetRarity());
EXPECT_EQ(Rarity::FREE, cards5.front().GetRarity());
EXPECT_EQ(Rarity::INVALID, cards6.front().GetRarity());
EXPECT_TRUE(cards7.empty());
}
TEST(Cards, FindCardByClass)
{
Cards& instance = Cards::GetInstance();
std::vector<Card> cards1 = instance.FindCardByClass(CardClass::DEATHKNIGHT);
std::vector<Card> cards2 = instance.FindCardByClass(CardClass::DREAM);
std::vector<Card> cards3 = instance.FindCardByClass(CardClass::DRUID);
std::vector<Card> cards4 = instance.FindCardByClass(CardClass::HUNTER);
std::vector<Card> cards5 = instance.FindCardByClass(CardClass::MAGE);
std::vector<Card> cards6 = instance.FindCardByClass(CardClass::NEUTRAL);
std::vector<Card> cards7 = instance.FindCardByClass(CardClass::PALADIN);
std::vector<Card> cards8 = instance.FindCardByClass(CardClass::PRIEST);
std::vector<Card> cards9 = instance.FindCardByClass(CardClass::INVALID);
EXPECT_EQ(CardClass::DEATHKNIGHT, cards1.front().GetCardClass());
EXPECT_EQ(CardClass::DREAM, cards2.front().GetCardClass());
EXPECT_EQ(CardClass::DRUID, cards3.front().GetCardClass());
EXPECT_EQ(CardClass::HUNTER, cards4.front().GetCardClass());
EXPECT_EQ(CardClass::MAGE, cards5.front().GetCardClass());
EXPECT_EQ(CardClass::NEUTRAL, cards6.front().GetCardClass());
EXPECT_EQ(CardClass::PALADIN, cards7.front().GetCardClass());
EXPECT_EQ(CardClass::PRIEST, cards8.front().GetCardClass());
EXPECT_EQ(CardClass::INVALID, cards9.front().GetCardClass());
}
TEST(Cards, FindCardBySet)
{
Cards& instance = Cards::GetInstance();
std::vector<Card> cards1 = instance.FindCardBySet(CardSet::CORE);
std::vector<Card> cards2 = instance.FindCardBySet(CardSet::EXPERT1);
std::vector<Card> cards3 = instance.FindCardBySet(CardSet::HOF);
std::vector<Card> cards4 = instance.FindCardBySet(CardSet::NAXX);
std::vector<Card> cards5 = instance.FindCardBySet(CardSet::GVG);
std::vector<Card> cards6 = instance.FindCardBySet(CardSet::BRM);
std::vector<Card> cards7 = instance.FindCardBySet(CardSet::TGT);
std::vector<Card> cards8 = instance.FindCardBySet(CardSet::LOE);
std::vector<Card> cards9 = instance.FindCardBySet(CardSet::OG);
std::vector<Card> cards10 = instance.FindCardBySet(CardSet::KARA);
std::vector<Card> cards11 = instance.FindCardBySet(CardSet::GANGS);
std::vector<Card> cards12 = instance.FindCardBySet(CardSet::UNGORO);
std::vector<Card> cards13 = instance.FindCardBySet(CardSet::ICECROWN);
std::vector<Card> cards14 = instance.FindCardBySet(CardSet::LOOTAPALOOZA);
std::vector<Card> cards15 = instance.FindCardBySet(CardSet::GILNEAS);
std::vector<Card> cards16 = instance.FindCardBySet(CardSet::BOOMSDAY);
std::vector<Card> cards17 = instance.FindCardBySet(CardSet::INVALID);
EXPECT_EQ(CardSet::CORE, cards1.front().GetCardSet());
EXPECT_EQ(CardSet::EXPERT1, cards2.front().GetCardSet());
EXPECT_EQ(CardSet::HOF, cards3.front().GetCardSet());
EXPECT_EQ(CardSet::NAXX, cards4.front().GetCardSet());
EXPECT_EQ(CardSet::GVG, cards5.front().GetCardSet());
EXPECT_EQ(CardSet::BRM, cards6.front().GetCardSet());
EXPECT_EQ(CardSet::TGT, cards7.front().GetCardSet());
EXPECT_EQ(CardSet::LOE, cards8.front().GetCardSet());
EXPECT_EQ(CardSet::OG, cards9.front().GetCardSet());
EXPECT_EQ(CardSet::KARA, cards10.front().GetCardSet());
EXPECT_EQ(CardSet::GANGS, cards11.front().GetCardSet());
EXPECT_EQ(CardSet::UNGORO, cards12.front().GetCardSet());
EXPECT_EQ(CardSet::ICECROWN, cards13.front().GetCardSet());
EXPECT_EQ(CardSet::LOOTAPALOOZA, cards14.front().GetCardSet());
EXPECT_EQ(CardSet::GILNEAS, cards15.front().GetCardSet());
EXPECT_EQ(CardSet::BOOMSDAY, cards16.front().GetCardSet());
EXPECT_TRUE(cards17.empty());
}
TEST(Cards, FindCardByType)
{
Cards& instance = Cards::GetInstance();
std::vector<Card> cards1 = instance.FindCardByType(CardType::WEAPON);
std::vector<Card> cards2 = instance.FindCardByType(CardType::GAME);
std::vector<Card> cards3 = instance.FindCardByType(CardType::HERO);
std::vector<Card> cards4 = instance.FindCardByType(CardType::HERO_POWER);
std::vector<Card> cards5 = instance.FindCardByType(CardType::ENCHANTMENT);
std::vector<Card> cards6 = instance.FindCardByType(CardType::ITEM);
std::vector<Card> cards7 = instance.FindCardByType(CardType::MINION);
std::vector<Card> cards8 = instance.FindCardByType(CardType::PLAYER);
std::vector<Card> cards9 = instance.FindCardByType(CardType::SPELL);
std::vector<Card> cards10 = instance.FindCardByType(CardType::TOKEN);
std::vector<Card> cards11 = instance.FindCardByType(CardType::INVALID);
EXPECT_EQ(CardType::WEAPON, cards1.front().GetCardType());
EXPECT_EQ(CardType::HERO, cards3.front().GetCardType());
EXPECT_EQ(CardType::HERO_POWER, cards4.front().GetCardType());
EXPECT_EQ(CardType::ENCHANTMENT, cards5.front().GetCardType());
EXPECT_EQ(CardType::MINION, cards7.front().GetCardType());
EXPECT_EQ(CardType::SPELL, cards9.front().GetCardType());
EXPECT_TRUE(cards2.empty());
EXPECT_TRUE(cards6.empty());
EXPECT_TRUE(cards8.empty());
EXPECT_TRUE(cards10.empty());
EXPECT_TRUE(cards11.empty());
}
TEST(Cards, FindCardByRace)
{
Cards& instance = Cards::GetInstance();
std::vector<Card> cards = instance.FindCardByRace(Race::INVALID);
EXPECT_FALSE(cards.empty());
EXPECT_NO_THROW(instance.FindCardByRace(Race::ALL));
}
TEST(Cards, FindCardByName)
{
Cards& instance = Cards::GetInstance();
const Card card = instance.FindCardByName("Flame Lance");
EXPECT_EQ("Flame Lance", card.name);
}
TEST(Cards, FindCardByCost)
{
Cards& instance = Cards::GetInstance();
std::vector<Card> cards1 = instance.FindCardByCost(0, 1);
std::vector<Card> cards2 = instance.FindCardByCost(2, 1);
EXPECT_FALSE(cards1.empty());
EXPECT_TRUE(cards2.empty());
}
TEST(Cards, FindCardByAttack)
{
Cards& instance = Cards::GetInstance();
std::vector<Card> cards1 = instance.FindCardByAttack(0, 1);
std::vector<Card> cards2 = instance.FindCardByAttack(2, 1);
EXPECT_FALSE(cards1.empty());
EXPECT_TRUE(cards2.empty());
}
TEST(Cards, FindCardByHealth)
{
Cards& instance = Cards::GetInstance();
std::vector<Card> cards1 = instance.FindCardByHealth(0, 1);
std::vector<Card> cards2 = instance.FindCardByHealth(2, 1);
EXPECT_FALSE(cards1.empty());
EXPECT_TRUE(cards2.empty());
}
TEST(Cards, FindCardByGameTag)
{
Cards& instance = Cards::GetInstance();
std::vector<GameTag> tags1;
const std::vector<GameTag> tags2;
tags1.emplace_back(GameTag::CANT_ATTACK);
std::vector<Card> cards1 = instance.FindCardByGameTag(tags1);
std::vector<Card> cards2 = instance.FindCardByGameTag(tags2);
auto gameTags = cards1.front().gameTags;
EXPECT_TRUE(gameTags.find(GameTag::CANT_ATTACK) != gameTags.end());
EXPECT_TRUE(cards2.empty());
}
TEST(Cards, GetHeroCard)
{
Cards& instance = Cards::GetInstance();
EXPECT_EQ(instance.FindCardByID("HERO_06").id,
instance.GetHeroCard(CardClass::DRUID).id);
EXPECT_EQ(instance.FindCardByID("HERO_05").id,
instance.GetHeroCard(CardClass::HUNTER).id);
EXPECT_EQ(instance.FindCardByID("HERO_08").id,
instance.GetHeroCard(CardClass::MAGE).id);
EXPECT_EQ(instance.FindCardByID("HERO_04").id,
instance.GetHeroCard(CardClass::PALADIN).id);
EXPECT_EQ(instance.FindCardByID("HERO_09").id,
instance.GetHeroCard(CardClass::PRIEST).id);
EXPECT_EQ(instance.FindCardByID("HERO_03").id,
instance.GetHeroCard(CardClass::ROGUE).id);
EXPECT_EQ(instance.FindCardByID("HERO_02").id,
instance.GetHeroCard(CardClass::SHAMAN).id);
EXPECT_EQ(instance.FindCardByID("HERO_07").id,
instance.GetHeroCard(CardClass::WARLOCK).id);
EXPECT_EQ(instance.FindCardByID("HERO_01").id,
instance.GetHeroCard(CardClass::WARRIOR).id);
EXPECT_EQ(instance.GetHeroCard(CardClass::DEATHKNIGHT).id, "");
}
TEST(Cards, GetDefaultHeroPower)
{
Cards& instance = Cards::GetInstance();
EXPECT_EQ(instance.FindCardByID("CS2_017").id,
instance.GetDefaultHeroPower(CardClass::DRUID).id);
EXPECT_EQ(instance.FindCardByID("DS1h_292").id,
instance.GetDefaultHeroPower(CardClass::HUNTER).id);
EXPECT_EQ(instance.FindCardByID("CS2_034").id,
instance.GetDefaultHeroPower(CardClass::MAGE).id);
EXPECT_EQ(instance.FindCardByID("CS2_101").id,
instance.GetDefaultHeroPower(CardClass::PALADIN).id);
EXPECT_EQ(instance.FindCardByID("CS1h_001").id,
instance.GetDefaultHeroPower(CardClass::PRIEST).id);
EXPECT_EQ(instance.FindCardByID("CS2_083b").id,
instance.GetDefaultHeroPower(CardClass::ROGUE).id);
EXPECT_EQ(instance.FindCardByID("CS2_049").id,
instance.GetDefaultHeroPower(CardClass::SHAMAN).id);
EXPECT_EQ(instance.FindCardByID("CS2_056").id,
instance.GetDefaultHeroPower(CardClass::WARLOCK).id);
EXPECT_EQ(instance.FindCardByID("CS2_102").id,
instance.GetDefaultHeroPower(CardClass::WARRIOR).id);
EXPECT_EQ(instance.GetDefaultHeroPower(CardClass::DEATHKNIGHT).id, "");
}
TEST(Cards, FindCardBySpellDamage)
{
Cards& instance = Cards::GetInstance();
std::vector<Card> cards1 = instance.FindCardBySpellPower(1, 1);
std::vector<Card> cards2 = instance.FindCardBySpellPower(2, 1);
EXPECT_FALSE(cards1.empty());
EXPECT_TRUE(cards2.empty());
}
<commit_msg>test: Update the size of all cards<commit_after>// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include "gtest/gtest.h"
#include <Rosetta/Cards/Cards.hpp>
#include <Rosetta/Enums/CardEnums.hpp>
using namespace RosettaStone;
TEST(Cards, GetAllCards)
{
const std::vector<Card> cards = Cards::GetInstance().GetAllCards();
ASSERT_FALSE(cards.empty());
EXPECT_EQ(cards.size(), 6717u);
}
TEST(Cards, FindCardByID)
{
const Card card1 = Cards::GetInstance().FindCardByID("AT_001");
const Card card2 = Cards::GetInstance().FindCardByID("");
EXPECT_EQ(card1.id, "AT_001");
EXPECT_EQ(card2.id, "");
}
TEST(Cards, FindCardByRarity)
{
Cards& instance = Cards::GetInstance();
std::vector<Card> cards1 = instance.FindCardByRarity(Rarity::COMMON);
std::vector<Card> cards2 = instance.FindCardByRarity(Rarity::RARE);
std::vector<Card> cards3 = instance.FindCardByRarity(Rarity::EPIC);
std::vector<Card> cards4 = instance.FindCardByRarity(Rarity::LEGENDARY);
std::vector<Card> cards5 = instance.FindCardByRarity(Rarity::FREE);
std::vector<Card> cards6 = instance.FindCardByRarity(Rarity::INVALID);
std::vector<Card> cards7 = instance.FindCardByRarity(Rarity::UNKNOWN_6);
EXPECT_EQ(Rarity::COMMON, cards1.front().GetRarity());
EXPECT_EQ(Rarity::RARE, cards2.front().GetRarity());
EXPECT_EQ(Rarity::EPIC, cards3.front().GetRarity());
EXPECT_EQ(Rarity::LEGENDARY, cards4.front().GetRarity());
EXPECT_EQ(Rarity::FREE, cards5.front().GetRarity());
EXPECT_EQ(Rarity::INVALID, cards6.front().GetRarity());
EXPECT_TRUE(cards7.empty());
}
TEST(Cards, FindCardByClass)
{
Cards& instance = Cards::GetInstance();
std::vector<Card> cards1 = instance.FindCardByClass(CardClass::DEATHKNIGHT);
std::vector<Card> cards2 = instance.FindCardByClass(CardClass::DREAM);
std::vector<Card> cards3 = instance.FindCardByClass(CardClass::DRUID);
std::vector<Card> cards4 = instance.FindCardByClass(CardClass::HUNTER);
std::vector<Card> cards5 = instance.FindCardByClass(CardClass::MAGE);
std::vector<Card> cards6 = instance.FindCardByClass(CardClass::NEUTRAL);
std::vector<Card> cards7 = instance.FindCardByClass(CardClass::PALADIN);
std::vector<Card> cards8 = instance.FindCardByClass(CardClass::PRIEST);
std::vector<Card> cards9 = instance.FindCardByClass(CardClass::INVALID);
EXPECT_EQ(CardClass::DEATHKNIGHT, cards1.front().GetCardClass());
EXPECT_EQ(CardClass::DREAM, cards2.front().GetCardClass());
EXPECT_EQ(CardClass::DRUID, cards3.front().GetCardClass());
EXPECT_EQ(CardClass::HUNTER, cards4.front().GetCardClass());
EXPECT_EQ(CardClass::MAGE, cards5.front().GetCardClass());
EXPECT_EQ(CardClass::NEUTRAL, cards6.front().GetCardClass());
EXPECT_EQ(CardClass::PALADIN, cards7.front().GetCardClass());
EXPECT_EQ(CardClass::PRIEST, cards8.front().GetCardClass());
EXPECT_EQ(CardClass::INVALID, cards9.front().GetCardClass());
}
TEST(Cards, FindCardBySet)
{
Cards& instance = Cards::GetInstance();
std::vector<Card> cards1 = instance.FindCardBySet(CardSet::CORE);
std::vector<Card> cards2 = instance.FindCardBySet(CardSet::EXPERT1);
std::vector<Card> cards3 = instance.FindCardBySet(CardSet::HOF);
std::vector<Card> cards4 = instance.FindCardBySet(CardSet::NAXX);
std::vector<Card> cards5 = instance.FindCardBySet(CardSet::GVG);
std::vector<Card> cards6 = instance.FindCardBySet(CardSet::BRM);
std::vector<Card> cards7 = instance.FindCardBySet(CardSet::TGT);
std::vector<Card> cards8 = instance.FindCardBySet(CardSet::LOE);
std::vector<Card> cards9 = instance.FindCardBySet(CardSet::OG);
std::vector<Card> cards10 = instance.FindCardBySet(CardSet::KARA);
std::vector<Card> cards11 = instance.FindCardBySet(CardSet::GANGS);
std::vector<Card> cards12 = instance.FindCardBySet(CardSet::UNGORO);
std::vector<Card> cards13 = instance.FindCardBySet(CardSet::ICECROWN);
std::vector<Card> cards14 = instance.FindCardBySet(CardSet::LOOTAPALOOZA);
std::vector<Card> cards15 = instance.FindCardBySet(CardSet::GILNEAS);
std::vector<Card> cards16 = instance.FindCardBySet(CardSet::BOOMSDAY);
std::vector<Card> cards17 = instance.FindCardBySet(CardSet::INVALID);
EXPECT_EQ(CardSet::CORE, cards1.front().GetCardSet());
EXPECT_EQ(CardSet::EXPERT1, cards2.front().GetCardSet());
EXPECT_EQ(CardSet::HOF, cards3.front().GetCardSet());
EXPECT_EQ(CardSet::NAXX, cards4.front().GetCardSet());
EXPECT_EQ(CardSet::GVG, cards5.front().GetCardSet());
EXPECT_EQ(CardSet::BRM, cards6.front().GetCardSet());
EXPECT_EQ(CardSet::TGT, cards7.front().GetCardSet());
EXPECT_EQ(CardSet::LOE, cards8.front().GetCardSet());
EXPECT_EQ(CardSet::OG, cards9.front().GetCardSet());
EXPECT_EQ(CardSet::KARA, cards10.front().GetCardSet());
EXPECT_EQ(CardSet::GANGS, cards11.front().GetCardSet());
EXPECT_EQ(CardSet::UNGORO, cards12.front().GetCardSet());
EXPECT_EQ(CardSet::ICECROWN, cards13.front().GetCardSet());
EXPECT_EQ(CardSet::LOOTAPALOOZA, cards14.front().GetCardSet());
EXPECT_EQ(CardSet::GILNEAS, cards15.front().GetCardSet());
EXPECT_EQ(CardSet::BOOMSDAY, cards16.front().GetCardSet());
EXPECT_TRUE(cards17.empty());
}
TEST(Cards, FindCardByType)
{
Cards& instance = Cards::GetInstance();
std::vector<Card> cards1 = instance.FindCardByType(CardType::WEAPON);
std::vector<Card> cards2 = instance.FindCardByType(CardType::GAME);
std::vector<Card> cards3 = instance.FindCardByType(CardType::HERO);
std::vector<Card> cards4 = instance.FindCardByType(CardType::HERO_POWER);
std::vector<Card> cards5 = instance.FindCardByType(CardType::ENCHANTMENT);
std::vector<Card> cards6 = instance.FindCardByType(CardType::ITEM);
std::vector<Card> cards7 = instance.FindCardByType(CardType::MINION);
std::vector<Card> cards8 = instance.FindCardByType(CardType::PLAYER);
std::vector<Card> cards9 = instance.FindCardByType(CardType::SPELL);
std::vector<Card> cards10 = instance.FindCardByType(CardType::TOKEN);
std::vector<Card> cards11 = instance.FindCardByType(CardType::INVALID);
EXPECT_EQ(CardType::WEAPON, cards1.front().GetCardType());
EXPECT_EQ(CardType::HERO, cards3.front().GetCardType());
EXPECT_EQ(CardType::HERO_POWER, cards4.front().GetCardType());
EXPECT_EQ(CardType::ENCHANTMENT, cards5.front().GetCardType());
EXPECT_EQ(CardType::MINION, cards7.front().GetCardType());
EXPECT_EQ(CardType::SPELL, cards9.front().GetCardType());
EXPECT_TRUE(cards2.empty());
EXPECT_TRUE(cards6.empty());
EXPECT_TRUE(cards8.empty());
EXPECT_TRUE(cards10.empty());
EXPECT_TRUE(cards11.empty());
}
TEST(Cards, FindCardByRace)
{
Cards& instance = Cards::GetInstance();
std::vector<Card> cards = instance.FindCardByRace(Race::INVALID);
EXPECT_FALSE(cards.empty());
EXPECT_NO_THROW(instance.FindCardByRace(Race::ALL));
}
TEST(Cards, FindCardByName)
{
Cards& instance = Cards::GetInstance();
const Card card = instance.FindCardByName("Flame Lance");
EXPECT_EQ("Flame Lance", card.name);
}
TEST(Cards, FindCardByCost)
{
Cards& instance = Cards::GetInstance();
std::vector<Card> cards1 = instance.FindCardByCost(0, 1);
std::vector<Card> cards2 = instance.FindCardByCost(2, 1);
EXPECT_FALSE(cards1.empty());
EXPECT_TRUE(cards2.empty());
}
TEST(Cards, FindCardByAttack)
{
Cards& instance = Cards::GetInstance();
std::vector<Card> cards1 = instance.FindCardByAttack(0, 1);
std::vector<Card> cards2 = instance.FindCardByAttack(2, 1);
EXPECT_FALSE(cards1.empty());
EXPECT_TRUE(cards2.empty());
}
TEST(Cards, FindCardByHealth)
{
Cards& instance = Cards::GetInstance();
std::vector<Card> cards1 = instance.FindCardByHealth(0, 1);
std::vector<Card> cards2 = instance.FindCardByHealth(2, 1);
EXPECT_FALSE(cards1.empty());
EXPECT_TRUE(cards2.empty());
}
TEST(Cards, FindCardByGameTag)
{
Cards& instance = Cards::GetInstance();
std::vector<GameTag> tags1;
const std::vector<GameTag> tags2;
tags1.emplace_back(GameTag::CANT_ATTACK);
std::vector<Card> cards1 = instance.FindCardByGameTag(tags1);
std::vector<Card> cards2 = instance.FindCardByGameTag(tags2);
auto gameTags = cards1.front().gameTags;
EXPECT_TRUE(gameTags.find(GameTag::CANT_ATTACK) != gameTags.end());
EXPECT_TRUE(cards2.empty());
}
TEST(Cards, GetHeroCard)
{
Cards& instance = Cards::GetInstance();
EXPECT_EQ(instance.FindCardByID("HERO_06").id,
instance.GetHeroCard(CardClass::DRUID).id);
EXPECT_EQ(instance.FindCardByID("HERO_05").id,
instance.GetHeroCard(CardClass::HUNTER).id);
EXPECT_EQ(instance.FindCardByID("HERO_08").id,
instance.GetHeroCard(CardClass::MAGE).id);
EXPECT_EQ(instance.FindCardByID("HERO_04").id,
instance.GetHeroCard(CardClass::PALADIN).id);
EXPECT_EQ(instance.FindCardByID("HERO_09").id,
instance.GetHeroCard(CardClass::PRIEST).id);
EXPECT_EQ(instance.FindCardByID("HERO_03").id,
instance.GetHeroCard(CardClass::ROGUE).id);
EXPECT_EQ(instance.FindCardByID("HERO_02").id,
instance.GetHeroCard(CardClass::SHAMAN).id);
EXPECT_EQ(instance.FindCardByID("HERO_07").id,
instance.GetHeroCard(CardClass::WARLOCK).id);
EXPECT_EQ(instance.FindCardByID("HERO_01").id,
instance.GetHeroCard(CardClass::WARRIOR).id);
EXPECT_EQ(instance.GetHeroCard(CardClass::DEATHKNIGHT).id, "");
}
TEST(Cards, GetDefaultHeroPower)
{
Cards& instance = Cards::GetInstance();
EXPECT_EQ(instance.FindCardByID("CS2_017").id,
instance.GetDefaultHeroPower(CardClass::DRUID).id);
EXPECT_EQ(instance.FindCardByID("DS1h_292").id,
instance.GetDefaultHeroPower(CardClass::HUNTER).id);
EXPECT_EQ(instance.FindCardByID("CS2_034").id,
instance.GetDefaultHeroPower(CardClass::MAGE).id);
EXPECT_EQ(instance.FindCardByID("CS2_101").id,
instance.GetDefaultHeroPower(CardClass::PALADIN).id);
EXPECT_EQ(instance.FindCardByID("CS1h_001").id,
instance.GetDefaultHeroPower(CardClass::PRIEST).id);
EXPECT_EQ(instance.FindCardByID("CS2_083b").id,
instance.GetDefaultHeroPower(CardClass::ROGUE).id);
EXPECT_EQ(instance.FindCardByID("CS2_049").id,
instance.GetDefaultHeroPower(CardClass::SHAMAN).id);
EXPECT_EQ(instance.FindCardByID("CS2_056").id,
instance.GetDefaultHeroPower(CardClass::WARLOCK).id);
EXPECT_EQ(instance.FindCardByID("CS2_102").id,
instance.GetDefaultHeroPower(CardClass::WARRIOR).id);
EXPECT_EQ(instance.GetDefaultHeroPower(CardClass::DEATHKNIGHT).id, "");
}
TEST(Cards, FindCardBySpellDamage)
{
Cards& instance = Cards::GetInstance();
std::vector<Card> cards1 = instance.FindCardBySpellPower(1, 1);
std::vector<Card> cards2 = instance.FindCardBySpellPower(2, 1);
EXPECT_FALSE(cards1.empty());
EXPECT_TRUE(cards2.empty());
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <stdexcept>
#include <string>
#include <boost/tr1/memory.hpp>
#include <boost/iterator/filter_iterator.hpp>
#include <boost/scoped_ptr.hpp>
extern "C" {
#include <libxslt/xslt.h>
#include <libxml/parser.h>
#include <libxml/xpath.h>
#include <libexslt/exslt.h>
}
#include <AlpinoCorpus/CorpusReader.hh>
#include <AlpinoCorpus/Error.hh>
#include <util/textfile.hh>
#include <EqualsPrevious.hh>
#include <ProgramOptions.hh>
#include <Stylesheet.hh>
#include <util.hh>
using alpinocorpus::CorpusReader;
namespace tr1 = std::tr1;
typedef boost::filter_iterator<NotEqualsPrevious<std::string>, CorpusReader::EntryIterator>
UniqueFilterIter;
void transformCorpus(tr1::shared_ptr<CorpusReader> reader,
tr1::shared_ptr<std::string const> query, tr1::shared_ptr<Stylesheet> stylesheet)
{
std::list<CorpusReader::MarkerQuery> markerQueries;
if (query) {
// Markers
CorpusReader::MarkerQuery activeMarker(*query, "active", "1");
markerQueries.push_back(activeMarker);
}
CorpusReader::EntryIterator i, end(reader->end());
if (query)
i = reader->query(CorpusReader::XPATH, *query);
else
i = reader->begin();
NotEqualsPrevious<std::string> pred;
for (UniqueFilterIter iter(pred, i, end); iter != UniqueFilterIter(pred, end, end);
++iter)
try {
std::cout << stylesheet->transform(reader->readMarkQueries(*iter, markerQueries));
} catch (std::runtime_error &e) {
std::cerr << "Could not apply stylesheet to: " << *iter << std::endl;
}
}
void transformEntry(tr1::shared_ptr<CorpusReader> reader,
tr1::shared_ptr<std::string const> query, tr1::shared_ptr<Stylesheet> stylesheet,
std::string const &entry)
{
std::list<CorpusReader::MarkerQuery> markerQueries;
if (query) {
// Markers
CorpusReader::MarkerQuery activeMarker(*query, "active", "1");
markerQueries.push_back(activeMarker);
}
std::cout << stylesheet->transform(reader->readMarkQueries(entry, markerQueries));
}
void usage(std::string const &programName)
{
std::cerr << "Usage: " << programName << " [OPTION] stylesheet treebanks" <<
std::endl << std::endl <<
" -g entry\tApply the stylesheet to a single entry" << std::endl <<
" -q query\tFilter the treebank using the given query" << std::endl <<
" -r\t\tProcess a directory of corpora recursively" << std::endl << std::endl;
}
int main (int argc, char *argv[])
{
xmlInitMemory();
xmlInitParser();
// EXSLT extensions
exsltRegisterAll();
// XPath
xmlXPathInit();
boost::scoped_ptr<ProgramOptions> opts;
try {
opts.reset(new ProgramOptions(argc, const_cast<char const **>(argv),
"g:q:r"));
} catch (std::exception &e) {
std::cerr << e.what() << std::endl;
return 1;
}
if (opts->arguments().size() < 2)
{
usage(opts->programName());
return 1;
}
tr1::shared_ptr<Stylesheet> stylesheet;
try {
std::string stylesheetData = alpinocorpus::util::readFile(opts->arguments().at(0));
stylesheet.reset(new Stylesheet(stylesheetData));
} catch (std::runtime_error &e) {
std::cerr << "Could not parse stylesheet: " << e.what() << std::endl;
return 1;
}
tr1::shared_ptr<CorpusReader> reader;
try {
if (opts->arguments().size() == 2)
reader = tr1::shared_ptr<CorpusReader>(
openCorpus(opts->arguments().at(1), opts->option('r')));
else
reader = tr1::shared_ptr<CorpusReader>(
openCorpora(opts->arguments().begin() + 1,
opts->arguments().end(), opts->option('r')));
} catch (std::runtime_error &e) {
std::cerr << "Could not open corpus: " << e.what() << std::endl;
return 1;
}
tr1::shared_ptr<std::string> query;
if (opts->option('q')) {
query.reset(new std::string(opts->optionValue('q')));
if (!reader->isValidQuery(CorpusReader::XPATH, false, *query)) {
std::cerr << "Invalid (or unwanted) query: " << *query << std::endl;
return 1;
}
}
try {
if (opts->option('g'))
transformEntry(reader, query, stylesheet, opts->optionValue('g'));
else
transformCorpus(reader, query, stylesheet);
} catch (std::runtime_error &e) {
std::cerr << "Error while transforming corpus: " << e.what() << std::endl;
}
}
<commit_msg>ac-xslt: update for new overloaded read() method.<commit_after>#include <iostream>
#include <stdexcept>
#include <string>
#include <boost/tr1/memory.hpp>
#include <boost/iterator/filter_iterator.hpp>
#include <boost/scoped_ptr.hpp>
extern "C" {
#include <libxslt/xslt.h>
#include <libxml/parser.h>
#include <libxml/xpath.h>
#include <libexslt/exslt.h>
}
#include <AlpinoCorpus/CorpusReader.hh>
#include <AlpinoCorpus/Error.hh>
#include <util/textfile.hh>
#include <EqualsPrevious.hh>
#include <ProgramOptions.hh>
#include <Stylesheet.hh>
#include <util.hh>
using alpinocorpus::CorpusReader;
namespace tr1 = std::tr1;
typedef boost::filter_iterator<NotEqualsPrevious<std::string>, CorpusReader::EntryIterator>
UniqueFilterIter;
void transformCorpus(tr1::shared_ptr<CorpusReader> reader,
tr1::shared_ptr<std::string const> query, std::string const &stylesheet)
{
std::list<CorpusReader::MarkerQuery> markerQueries;
if (query) {
// Markers
CorpusReader::MarkerQuery activeMarker(*query, "active", "1");
markerQueries.push_back(activeMarker);
}
CorpusReader::EntryIterator i, end(reader->end());
if (query)
i = reader->queryWithStylesheet(CorpusReader::XPATH, *query,
stylesheet, markerQueries);
else
i = reader->beginWithStylesheet(stylesheet);
NotEqualsPrevious<std::string> pred;
for (UniqueFilterIter iter(pred, i, end); iter != UniqueFilterIter(pred, end, end);
++iter)
try {
std::cout << i.contents(*reader);
} catch (std::runtime_error &e) {
std::cerr << "Could not apply stylesheet to: " << *iter << std::endl;
}
}
void transformEntry(tr1::shared_ptr<CorpusReader> reader,
tr1::shared_ptr<std::string const> query, std::string stylesheet,
std::string const &entry)
{
Stylesheet compiledStylesheet(stylesheet);
std::list<CorpusReader::MarkerQuery> markerQueries;
if (query) {
// Markers
CorpusReader::MarkerQuery activeMarker(*query, "active", "1");
markerQueries.push_back(activeMarker);
}
std::cout << compiledStylesheet.transform(reader->read(entry, markerQueries));
}
void usage(std::string const &programName)
{
std::cerr << "Usage: " << programName << " [OPTION] stylesheet treebanks" <<
std::endl << std::endl <<
" -g entry\tApply the stylesheet to a single entry" << std::endl <<
" -q query\tFilter the treebank using the given query" << std::endl <<
" -r\t\tProcess a directory of corpora recursively" << std::endl << std::endl;
}
int main (int argc, char *argv[])
{
xmlInitMemory();
xmlInitParser();
// EXSLT extensions
exsltRegisterAll();
// XPath
xmlXPathInit();
boost::scoped_ptr<ProgramOptions> opts;
try {
opts.reset(new ProgramOptions(argc, const_cast<char const **>(argv),
"g:q:r"));
} catch (std::exception &e) {
std::cerr << e.what() << std::endl;
return 1;
}
if (opts->arguments().size() < 2)
{
usage(opts->programName());
return 1;
}
std::string stylesheet;
try {
stylesheet = alpinocorpus::util::readFile(opts->arguments().at(0));
} catch (std::runtime_error &e) {
std::cerr << "Could not read stylesheet: " << e.what() << std::endl;
return 1;
}
tr1::shared_ptr<CorpusReader> reader;
try {
if (opts->arguments().size() == 2)
reader = tr1::shared_ptr<CorpusReader>(
openCorpus(opts->arguments().at(1), opts->option('r')));
else
reader = tr1::shared_ptr<CorpusReader>(
openCorpora(opts->arguments().begin() + 1,
opts->arguments().end(), opts->option('r')));
} catch (std::runtime_error &e) {
std::cerr << "Could not open corpus: " << e.what() << std::endl;
return 1;
}
tr1::shared_ptr<std::string> query;
if (opts->option('q')) {
query.reset(new std::string(opts->optionValue('q')));
if (!reader->isValidQuery(CorpusReader::XPATH, false, *query)) {
std::cerr << "Invalid (or unwanted) query: " << *query << std::endl;
return 1;
}
}
try {
if (opts->option('g'))
transformEntry(reader, query, stylesheet, opts->optionValue('g'));
else
transformCorpus(reader, query, stylesheet);
} catch (std::runtime_error &e) {
std::cerr << "Error while transforming corpus: " << e.what() << std::endl;
}
}
<|endoftext|> |
<commit_before>//Copyright (c) 2020 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include <cassert>
#include "LimitedBeadingStrategy.h"
namespace cura
{
LimitedBeadingStrategy::Beading LimitedBeadingStrategy::compute(coord_t thickness, coord_t bead_count) const
{
if (bead_count <= max_bead_count)
{
return parent->compute(thickness, bead_count);
}
assert(bead_count == max_bead_count + 1);
coord_t optimal_thickness = parent->getOptimalThickness(max_bead_count);
Beading ret = parent->compute(optimal_thickness, max_bead_count);
ret.left_over += thickness - ret.total_thickness;
ret.total_thickness = thickness;
// Enforce symmetry
if (bead_count % 2 == 1)
{
ret.toolpath_locations[bead_count / 2] = thickness / 2;
ret.bead_widths[bead_count / 2] = thickness - optimal_thickness;
}
for (coord_t bead_idx = 0; bead_idx < (bead_count + 1) / 2; bead_idx++)
{
ret.toolpath_locations[bead_count - 1 - bead_idx] = thickness - ret.toolpath_locations[bead_idx];
}
//Create a "fake" inner wall with 0 width to indicate the edge of the walled area.
//This wall can then be used by other structures to e.g. fill the infill area adjacent to the variable-width walls.
coord_t innermost_toolpath_location = ret.toolpath_locations[max_bead_count / 2 - 1];
coord_t innermost_toolpath_width = ret.bead_widths[max_bead_count / 2 - 1];
ret.toolpath_locations.insert(ret.toolpath_locations.begin() + max_bead_count / 2, innermost_toolpath_location + innermost_toolpath_width / 2);
ret.bead_widths.insert(ret.bead_widths.begin() + max_bead_count / 2, 0);
//Symmetry on both sides. Symmetry is guaranteed since this code is stopped early if the bead_count <= max_bead_count, and never reaches this point then.
innermost_toolpath_location = ret.toolpath_locations[bead_count - (max_bead_count / 2 - 1)];
innermost_toolpath_width = ret.bead_widths[bead_count - (max_bead_count / 2 - 1)];
ret.toolpath_locations.insert(ret.toolpath_locations.begin() + bead_count - (max_bead_count / 2 - 1), innermost_toolpath_location - innermost_toolpath_width / 2);
ret.bead_widths.insert(ret.bead_widths.begin() + bead_count - (max_bead_count / 2 - 1), 0);
return ret;
}
coord_t LimitedBeadingStrategy::getOptimalThickness(coord_t bead_count) const
{
if (bead_count <= max_bead_count)
{
return parent->getOptimalThickness(bead_count);
}
return 10000000; // 10 meter
}
coord_t LimitedBeadingStrategy::getTransitionThickness(coord_t lower_bead_count) const
{
if (lower_bead_count < max_bead_count)
{
return parent->getTransitionThickness(lower_bead_count);
}
if (lower_bead_count == max_bead_count)
{
return parent->getOptimalThickness(lower_bead_count + 1) - 10;
}
return 9000000; // 9 meter
}
coord_t LimitedBeadingStrategy::getOptimalBeadCount(coord_t thickness) const
{
coord_t parent_bead_count = parent->getOptimalBeadCount(thickness);
if (parent_bead_count <= max_bead_count)
{
return parent->getOptimalBeadCount(thickness);
}
else if (parent_bead_count == max_bead_count + 1)
{
if (thickness < parent->getOptimalThickness(max_bead_count + 1) - 10)
return max_bead_count;
else
return max_bead_count + 1;
}
else return max_bead_count + 1;
}
} // namespace cura
<commit_msg>Workaround: add a 0-width wall in locations where there are maximum walls<commit_after>//Copyright (c) 2020 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include <cassert>
#include "LimitedBeadingStrategy.h"
namespace cura
{
LimitedBeadingStrategy::Beading LimitedBeadingStrategy::compute(coord_t thickness, coord_t bead_count) const
{
if (bead_count <= max_bead_count)
{
Beading ret = parent->compute(thickness, bead_count);
if (bead_count % 2 == 0 && bead_count == max_bead_count)
{
const coord_t innermost_toolpath_location = ret.toolpath_locations[max_bead_count / 2 - 1];
const coord_t innermost_toolpath_width = ret.bead_widths[max_bead_count / 2 - 1];
ret.toolpath_locations.insert(ret.toolpath_locations.begin() + max_bead_count / 2, innermost_toolpath_location + innermost_toolpath_width / 2);
ret.bead_widths.insert(ret.bead_widths.begin() + max_bead_count / 2, 0);
}
return ret;
}
assert(bead_count == max_bead_count + 1);
coord_t optimal_thickness = parent->getOptimalThickness(max_bead_count);
Beading ret = parent->compute(optimal_thickness, max_bead_count);
ret.left_over += thickness - ret.total_thickness;
ret.total_thickness = thickness;
// Enforce symmetry
if (bead_count % 2 == 1)
{
ret.toolpath_locations[bead_count / 2] = thickness / 2;
ret.bead_widths[bead_count / 2] = thickness - optimal_thickness;
}
for (coord_t bead_idx = 0; bead_idx < (bead_count + 1) / 2; bead_idx++)
{
ret.toolpath_locations[bead_count - 1 - bead_idx] = thickness - ret.toolpath_locations[bead_idx];
}
//Create a "fake" inner wall with 0 width to indicate the edge of the walled area.
//This wall can then be used by other structures to e.g. fill the infill area adjacent to the variable-width walls.
coord_t innermost_toolpath_location = ret.toolpath_locations[max_bead_count / 2 - 1];
coord_t innermost_toolpath_width = ret.bead_widths[max_bead_count / 2 - 1];
ret.toolpath_locations.insert(ret.toolpath_locations.begin() + max_bead_count / 2, innermost_toolpath_location + innermost_toolpath_width / 2);
ret.bead_widths.insert(ret.bead_widths.begin() + max_bead_count / 2, 0);
//Symmetry on both sides. Symmetry is guaranteed since this code is stopped early if the bead_count <= max_bead_count, and never reaches this point then.
innermost_toolpath_location = ret.toolpath_locations[bead_count - (max_bead_count / 2 - 1)];
innermost_toolpath_width = ret.bead_widths[bead_count - (max_bead_count / 2 - 1)];
ret.toolpath_locations.insert(ret.toolpath_locations.begin() + bead_count - (max_bead_count / 2 - 1), innermost_toolpath_location - innermost_toolpath_width / 2);
ret.bead_widths.insert(ret.bead_widths.begin() + bead_count - (max_bead_count / 2 - 1), 0);
return ret;
}
coord_t LimitedBeadingStrategy::getOptimalThickness(coord_t bead_count) const
{
if (bead_count <= max_bead_count)
{
return parent->getOptimalThickness(bead_count);
}
return 10000000; // 10 meter
}
coord_t LimitedBeadingStrategy::getTransitionThickness(coord_t lower_bead_count) const
{
if (lower_bead_count < max_bead_count)
{
return parent->getTransitionThickness(lower_bead_count);
}
if (lower_bead_count == max_bead_count)
{
return parent->getOptimalThickness(lower_bead_count + 1) - 10;
}
return 9000000; // 9 meter
}
coord_t LimitedBeadingStrategy::getOptimalBeadCount(coord_t thickness) const
{
coord_t parent_bead_count = parent->getOptimalBeadCount(thickness);
if (parent_bead_count <= max_bead_count)
{
return parent->getOptimalBeadCount(thickness);
}
else if (parent_bead_count == max_bead_count + 1)
{
if (thickness < parent->getOptimalThickness(max_bead_count + 1) - 10)
return max_bead_count;
else
return max_bead_count + 1;
}
else return max_bead_count + 1;
}
} // namespace cura
<|endoftext|> |
<commit_before>
#include "coring.hpp"
#include "logger.hpp"
#include "tools.hpp"
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <boost/program_options.hpp>
#include <omp.h>
WTDMap
compute_wtd(std::list<std::size_t> streaks) {
WTDMap wtd;
if (streaks.size() > 0) {
streaks.sort(std::greater<std::size_t>());
std::size_t max_streak = streaks.front();
for (std::size_t i=0; i <= max_streak; ++i) {
float n_steps = 0.0f;
for (auto s: streaks) {
if (i > s) {
break;
}
n_steps += 1.0f;
}
wtd[i] = n_steps / ((float) streaks.size());
}
}
return wtd;
}
int main(int argc, char* argv[]) {
using namespace Clustering::Tools;
namespace b_po = boost::program_options;
b_po::variables_map args;
b_po::options_description desc (std::string(argv[0]).append(
"\n\n"
"compute boundary corrections for clustering results."
"\n"
"options"));
desc.add_options()
("help,h", b_po::bool_switch()->default_value(false),
"show this help.")
// optional
("states,s", b_po::value<std::string>()->required(),
"(required): file with state information (i.e. clustered trajectory")
("windows,w", b_po::value<std::string>()->required(),
"(required): file with window sizes."
"format is space-separated lines of\n\n"
"STATE_ID WINDOW_SIZE\n\n"
"use * as STATE_ID to match all (other) states.\n"
"e.g.:\n\n"
"* 20\n"
"3 40\n"
"4 60\n\n"
"matches 40 frames to state 3, 60 frames to state 4 and 20 frames to all the other states")
("output,o", b_po::value<std::string>(),
"(optional): cored trajectory")
("distribution,d", b_po::value<std::string>(),
"(optional): write waiting time distributions to file.")
("cores,c", b_po::value<std::string>(),
"(optional): write core information to file, i.e. trajectory with state name if in core region or -1 if not in core region")
// defaults
("verbose,v", b_po::bool_switch()->default_value(false),
"verbose mode: print runtime information to STDOUT.")
;
// parse cmd arguments
try {
b_po::store(b_po::command_line_parser(argc, argv).options(desc).run(), args);
b_po::notify(args);
} catch (b_po::error& e) {
if ( ! args["help"].as<bool>()) {
std::cerr << "\n" << e.what() << "\n\n" << std::endl;
}
std::cerr << desc << std::endl;
return EXIT_FAILURE;
}
if (args["help"].as<bool>()) {
std::cout << desc << std::endl;
return EXIT_SUCCESS;
}
// setup general flags / options
Clustering::verbose = args["verbose"].as<bool>();
// load states
std::vector<std::size_t> states = Clustering::Tools::read_clustered_trajectory(args["states"].as<std::string>());
std::set<std::size_t> state_names(states.begin(), states.end());
std::size_t n_frames = states.size();
if (args.count("output") || args.count("distribution") || args.count("cores")) {
// load window size information
std::map<std::size_t, std::size_t> coring_windows;
{
std::ifstream ifs(args["windows"].as<std::string>());
std::string buf1, buf2;
std::size_t size_for_all = 1;
while (ifs.good()) {
ifs >> buf1;
ifs >> buf2;
if (ifs.good()) {
if (buf1 == "*") {
size_for_all = string_to_num<std::size_t>(buf2);
} else {
coring_windows[string_to_num<std::size_t>(buf1)] = string_to_num<std::size_t>(buf2);
}
}
}
// fill remaining, not explicitly defined states with common window size
for (std::size_t name: state_names) {
if ( ! coring_windows.count(name)){
coring_windows[name] = size_for_all;
}
}
}
// core trajectory
std::vector<std::size_t> cored_traj(n_frames);
std::size_t current_core = states[0];
std::vector<long> cores(n_frames);
for (std::size_t i=0; i < states.size(); ++i) {
std::size_t w = coring_windows[states[i]];
bool is_in_core = true;
for (std::size_t j=i+1; j < i+w; ++j) {
if (states[j] != states[i]) {
is_in_core = false;
break;
}
}
if (is_in_core) {
current_core = states[i];
cores[i] = current_core;
} else {
cores[i] = -1;
}
cored_traj[i] = current_core;
}
// write cored trajectory to file
if (args.count("output")) {
Clustering::Tools::write_clustered_trajectory(args["output"].as<std::string>(), cored_traj);
}
// write core information to file
if (args.count("cores")) {
Clustering::Tools::write_single_column<long>(args["cores"].as<std::string>(), cores, false);
}
// compute/save escape time distributions
if (args.count("distribution")) {
std::map<std::size_t, std::list<std::size_t>> streaks;
std::size_t current_state = cored_traj[0];
long n_counts = 0;
for (std::size_t state: cored_traj) {
if (state == current_state) {
++n_counts;
} else {
streaks[current_state].push_back(n_counts);
current_state = state;
n_counts = 1;
}
}
streaks[current_state].push_back(n_counts);
std::map<std::size_t, WTDMap> etds;
for (std::size_t state: state_names) {
etds[state] = compute_wtd(streaks[state]);
}
// write WTDs to file
for (auto state_etd: etds) {
std::string fname = Clustering::Tools::stringprintf(args["distribution"].as<std::string>() + "_%d", state_etd.first);
Clustering::Tools::write_map<std::size_t, float>(fname, state_etd.second);
}
}
} else {
std::cerr << "\n" << "nothing to do! please define '--output', '--distribution' or both!" << "\n\n";
std::cerr << desc << std::endl;
}
return EXIT_SUCCESS;
}
<commit_msg>support concatenated trajectories in coring (unfinished)<commit_after>
#include "coring.hpp"
#include "logger.hpp"
#include "tools.hpp"
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <boost/program_options.hpp>
#include <omp.h>
WTDMap
compute_wtd(std::list<std::size_t> streaks) {
WTDMap wtd;
if (streaks.size() > 0) {
streaks.sort(std::greater<std::size_t>());
std::size_t max_streak = streaks.front();
for (std::size_t i=0; i <= max_streak; ++i) {
float n_steps = 0.0f;
for (auto s: streaks) {
if (i > s) {
break;
}
n_steps += 1.0f;
}
wtd[i] = n_steps / ((float) streaks.size());
}
}
return wtd;
}
int main(int argc, char* argv[]) {
using namespace Clustering::Tools;
namespace b_po = boost::program_options;
b_po::variables_map args;
b_po::options_description desc (std::string(argv[0]).append(
"\n\n"
"compute boundary corrections for clustering results."
"\n"
"options"));
desc.add_options()
("help,h", b_po::bool_switch()->default_value(false),
"show this help.")
// optional
("states,s", b_po::value<std::string>()->required(),
"(required): file with state information (i.e. clustered trajectory")
("windows,w", b_po::value<std::string>()->required(),
"(required): file with window sizes."
"format is space-separated lines of\n\n"
"STATE_ID WINDOW_SIZE\n\n"
"use * as STATE_ID to match all (other) states.\n"
"e.g.:\n\n"
"* 20\n"
"3 40\n"
"4 60\n\n"
"matches 40 frames to state 3, 60 frames to state 4 and 20 frames to all the other states")
("output,o", b_po::value<std::string>(),
"(optional): cored trajectory")
("distribution,d", b_po::value<std::string>(),
"(optional): write waiting time distributions to file.")
("cores,c", b_po::value<std::string>(),
"(optional): write core information to file, i.e. trajectory with state name if in core region or -1 if not in core region")
("concat-nframes", b_po::value<std::size_t>(),
"input (optional parameter): no. of frames per (equally sized) sub-trajectory for concatenated trajectory files.")
("concat-limits", b_po::value<std::string>(),
"input (optional, file): file with frame ids (base 0) of first frames per (not equally sized) sub-trajectory for concatenated trajectory files.")
// defaults
("verbose,v", b_po::bool_switch()->default_value(false),
"verbose mode: print runtime information to STDOUT.")
;
// parse cmd arguments
try {
b_po::store(b_po::command_line_parser(argc, argv).options(desc).run(), args);
b_po::notify(args);
} catch (b_po::error& e) {
if ( ! args["help"].as<bool>()) {
std::cerr << "\n" << e.what() << "\n\n" << std::endl;
}
std::cerr << desc << std::endl;
return EXIT_FAILURE;
}
if (args["help"].as<bool>()) {
std::cout << desc << std::endl;
return EXIT_SUCCESS;
}
// setup general flags / options
Clustering::verbose = args["verbose"].as<bool>();
// load states
std::vector<std::size_t> states = Clustering::Tools::read_clustered_trajectory(args["states"].as<std::string>());
std::set<std::size_t> state_names(states.begin(), states.end());
std::size_t n_frames = states.size();
if (args.count("output") || args.count("distribution") || args.count("cores")) {
// load concatenation limits to treat concatenated trajectories correctly
// when performing dynamical corrections
std::vector<std::size_t> concat_limits;
if (args.count("concat-limits")) {
concat_limits = Clustering::Tools::read_single_column<std::size_t>(args["concat-limits"].as<std::string>());
} else if (args.count("concat-nframes")) {
std::size_t n_frames_per_subtraj = args["concat-nframes"].as<std::size_t>();
for (std::size_t i=n_frames_per_subtraj; i < traj.size(); i += n_frames_per_subtraj) {
concat_limits.push_back(i);
}
}
//TODO use concat limits
// load window size information
std::map<std::size_t, std::size_t> coring_windows;
{
std::ifstream ifs(args["windows"].as<std::string>());
std::string buf1, buf2;
std::size_t size_for_all = 1;
while (ifs.good()) {
ifs >> buf1;
ifs >> buf2;
if (ifs.good()) {
if (buf1 == "*") {
size_for_all = string_to_num<std::size_t>(buf2);
} else {
coring_windows[string_to_num<std::size_t>(buf1)] = string_to_num<std::size_t>(buf2);
}
}
}
// fill remaining, not explicitly defined states with common window size
for (std::size_t name: state_names) {
if ( ! coring_windows.count(name)){
coring_windows[name] = size_for_all;
}
}
}
// core trajectory
std::vector<std::size_t> cored_traj(n_frames);
std::size_t current_core = states[0];
std::vector<long> cores(n_frames);
for (std::size_t i=0; i < states.size(); ++i) {
std::size_t w = coring_windows[states[i]];
bool is_in_core = true;
for (std::size_t j=i+1; j < i+w; ++j) {
if (states[j] != states[i]) {
is_in_core = false;
break;
}
}
if (is_in_core) {
current_core = states[i];
cores[i] = current_core;
} else {
cores[i] = -1;
}
cored_traj[i] = current_core;
}
// write cored trajectory to file
if (args.count("output")) {
Clustering::Tools::write_clustered_trajectory(args["output"].as<std::string>(), cored_traj);
}
// write core information to file
if (args.count("cores")) {
Clustering::Tools::write_single_column<long>(args["cores"].as<std::string>(), cores, false);
}
// compute/save escape time distributions
if (args.count("distribution")) {
std::map<std::size_t, std::list<std::size_t>> streaks;
std::size_t current_state = cored_traj[0];
long n_counts = 0;
for (std::size_t state: cored_traj) {
if (state == current_state) {
++n_counts;
} else {
streaks[current_state].push_back(n_counts);
current_state = state;
n_counts = 1;
}
}
streaks[current_state].push_back(n_counts);
std::map<std::size_t, WTDMap> etds;
for (std::size_t state: state_names) {
etds[state] = compute_wtd(streaks[state]);
}
// write WTDs to file
for (auto state_etd: etds) {
std::string fname = Clustering::Tools::stringprintf(args["distribution"].as<std::string>() + "_%d", state_etd.first);
Clustering::Tools::write_map<std::size_t, float>(fname, state_etd.second);
}
}
} else {
std::cerr << "\n" << "nothing to do! please define '--output', '--distribution' or both!" << "\n\n";
std::cerr << desc << std::endl;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3297
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from 3297 to 3298<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3298
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3222
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from 3222 to 3223<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3223
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3482
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from 3482 to 3483<commit_after>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3483
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.