text
stringlengths
54
60.6k
<commit_before>#include <windows.h> #include "overlay.h" #include <OvRender.h> #include "osd.h" #include "menu.h" #include <stdio.h> BOOLEAN g_FontInited = FALSE; BOOLEAN IsStableFramerate; BOOLEAN IsStableFrametime; BOOLEAN IsLimitedFrametime; BOOLEAN DisableAutoOverclock; UINT16 DiskResponseTime; UINT64 CyclesWaited; HANDLE RenderThreadHandle; UINT32 DisplayFrequency; double FrameTimeAvg; double FrameRate; UINT8 FrameLimit = 80; //80 fps int debugInt = 1; VOID DebugRec(); VOID InitializeKeyboardHook(); double PCFreq = 0.0; __int64 CounterStart = 0; typedef enum _OVERCLOCK_UNIT { OC_ENGINE, OC_MEMORY }OVERCLOCK_UNIT; VOID Overclock(OVERCLOCK_UNIT Unit); extern "C" LONG __stdcall NtQueryPerformanceCounter( LARGE_INTEGER* PerformanceCounter, LARGE_INTEGER* PerformanceFrequency ); VOID StartCounter() { LARGE_INTEGER perfCount; LARGE_INTEGER frequency; NtQueryPerformanceCounter(&perfCount, &frequency); PCFreq = (double)frequency.QuadPart / 1000.0;; } double GetPerformanceCounter() { LARGE_INTEGER li; NtQueryPerformanceCounter(&li, NULL); return (double)li.QuadPart / PCFreq; } BOOLEAN IsGpuLag() { if (PushSharedMemory->HarwareInformation.DisplayDevice.Load > 95) { return TRUE; } return FALSE; } #define TSAMP 60 double garb[TSAMP]; int addint = 0; double GetAverageFrameTime() { UINT32 i; double total = 0; for (i = 0; i < TSAMP; i++) total += garb[i]; return total / TSAMP; } #include <math.h> bool approximatelyEqual(double a, double b, double epsilon) { return fabs(a - b) < epsilon; } VOID RunFrameStatistics() { static double newTickCount = 0.0, lastTickCount_FrameLimiter = 0.0, oldTick = 0.0, delta = 0.0, oldTick2 = 0.0, frameTime = 0.0, acceptableFrameTime = 0.0, lastTickCount; static BOOLEAN inited = FALSE; if (!inited) { DEVMODE devMode; StartCounter(); inited = TRUE; EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &devMode); DisplayFrequency = devMode.dmDisplayFrequency; acceptableFrameTime = (double)1000 / (double)(devMode.dmDisplayFrequency - 1); if (PushSharedMemory->FrameLimit > 1) FrameLimit = PushSharedMemory->FrameLimit; newTickCount = oldTick = lastTickCount_FrameLimiter = GetPerformanceCounter(); } newTickCount = GetPerformanceCounter(); delta = newTickCount - oldTick; frameTime = newTickCount - lastTickCount; lastTickCount = newTickCount; IsLimitedFrametime = FALSE; garb[addint] = frameTime; addint++; if (addint == TSAMP) addint = 0; FrameTimeAvg = GetAverageFrameTime(); static double OldfFPS = 0.0f; FrameRate = 1000.0f / FrameTimeAvg; FrameRate = FrameRate * 0.1 + OldfFPS * 0.9; //FrameRate = FrameRate * 0.01 + OldfFPS * 0.99; even slower damping OldfFPS = FrameRate; // Every second. if (delta > 1000) { oldTick = newTickCount; //if (PushSharedMemory->ThreadOptimization || PushSharedMemory->OSDFlags & OSD_MTU) //{ PushRefreshThreadMonitor(); //if (PushSharedMemory->OSDFlags & OSD_MTU) PushSharedMemory->HarwareInformation.Processor.MaxThreadUsage = PushGetMaxThreadUsage(); //} RenderThreadHandle = GetCurrentThread(); } // Simple Diagnostics. if (frameTime > acceptableFrameTime) { if (PushSharedMemory->HarwareInformation.Processor.Load > 95) PushSharedMemory->Overloads |= OSD_CPU_LOAD; if (PushSharedMemory->HarwareInformation.Processor.MaxCoreUsage > 95) PushSharedMemory->Overloads |= OSD_MCU; if (PushSharedMemory->HarwareInformation.Processor.MaxThreadUsage > 95) PushSharedMemory->Overloads |= OSD_MTU; if (IsGpuLag()) PushSharedMemory->Overloads |= OSD_GPU_LOAD; if (PushSharedMemory->HarwareInformation.Memory.Used > PushSharedMemory->HarwareInformation.Memory.Total) PushSharedMemory->Overloads |= OSD_RAM; PushSharedMemory->HarwareInformation.Disk.ResponseTime = DiskResponseTime; if (PushSharedMemory->HarwareInformation.Disk.ResponseTime > 4000) { PushSharedMemory->Overloads |= OSD_DISK_RESPONSE; PushSharedMemory->OSDFlags |= OSD_DISK_RESPONSE; } if (PushSharedMemory->AutoLogFileIo) PushSharedMemory->LogFileIo = TRUE; if (PushSharedMemory->HarwareInformation.Processor.MaxThreadUsage > 95) { PushSharedMemory->Overloads |= OSD_MTU; PushSharedMemory->OSDFlags |= OSD_MTU; } } if (newTickCount - oldTick2 > 30000) //frame rate has been stable for at least 30 seconds. IsStableFramerate = TRUE; else IsStableFramerate = FALSE; if (FrameTimeAvg > acceptableFrameTime) { //reset the timer oldTick2 = newTickCount; // Lazy overclock if (debugInt++ % DisplayFrequency == 0) { if (!DisableAutoOverclock && IsGpuLag()) { PushSharedMemory->OSDFlags |= OSD_GPU_E_CLK; PushSharedMemory->OSDFlags |= OSD_GPU_M_CLK; PushSharedMemory->Overloads |= OSD_GPU_E_CLK; PushSharedMemory->Overloads |= OSD_GPU_M_CLK; if (PushSharedMemory->HarwareInformation.DisplayDevice.EngineClockMax < PushSharedMemory->HarwareInformation.DisplayDevice.EngineOverclock) Overclock(OC_ENGINE); if (PushSharedMemory->HarwareInformation.DisplayDevice.MemoryClockMax < PushSharedMemory->HarwareInformation.DisplayDevice.MemoryOverclock) Overclock(OC_MEMORY); } } } double frameTimeDamped = 1000.0f / FrameRate; if (frameTimeDamped > acceptableFrameTime) IsStableFrametime = FALSE; else IsStableFrametime = TRUE; if (PushSharedMemory->FrameLimit) { double frameTimeMin = (double)1000 / (double)FrameLimit; frameTime = newTickCount - lastTickCount_FrameLimiter; if (approximatelyEqual(frameTimeDamped, frameTimeMin, 0.100)) { IsLimitedFrametime = TRUE; } if (frameTime < frameTimeMin) { UINT64 cyclesStart, cyclesStop; RenderThreadHandle = GetCurrentThread(); QueryThreadCycleTime(RenderThreadHandle, &cyclesStart); lastTickCount_FrameLimiter = newTickCount; while (frameTime < frameTimeMin) { newTickCount = GetPerformanceCounter(); frameTime += (newTickCount - lastTickCount_FrameLimiter); lastTickCount_FrameLimiter = newTickCount; } QueryThreadCycleTime(RenderThreadHandle, &cyclesStop); CyclesWaited += cyclesStop - cyclesStart; } lastTickCount_FrameLimiter = newTickCount; } } VOID RnRender( OvOverlay* Overlay ) { static BOOLEAN rendering = FALSE; if (!rendering) { rendering = TRUE; InitializeKeyboardHook(); } Osd_Draw( Overlay ); MnuRender( Overlay ); RunFrameStatistics(); //Overlay->DrawText(L"u can draw anything in this render loop!\n"); } <commit_msg>adopt acceptableFrameTime to FrameLimit<commit_after>#include <windows.h> #include "overlay.h" #include <OvRender.h> #include "osd.h" #include "menu.h" #include <stdio.h> BOOLEAN g_FontInited = FALSE; BOOLEAN IsStableFramerate; BOOLEAN IsStableFrametime; BOOLEAN IsLimitedFrametime; BOOLEAN DisableAutoOverclock; UINT16 DiskResponseTime; UINT64 CyclesWaited; HANDLE RenderThreadHandle; UINT32 DisplayFrequency; double FrameTimeAvg; double FrameRate; UINT8 FrameLimit = 80; //80 fps int debugInt = 1; VOID DebugRec(); VOID InitializeKeyboardHook(); double PCFreq = 0.0; __int64 CounterStart = 0; typedef enum _OVERCLOCK_UNIT { OC_ENGINE, OC_MEMORY }OVERCLOCK_UNIT; VOID Overclock(OVERCLOCK_UNIT Unit); extern "C" LONG __stdcall NtQueryPerformanceCounter( LARGE_INTEGER* PerformanceCounter, LARGE_INTEGER* PerformanceFrequency ); VOID StartCounter() { LARGE_INTEGER perfCount; LARGE_INTEGER frequency; NtQueryPerformanceCounter(&perfCount, &frequency); PCFreq = (double)frequency.QuadPart / 1000.0;; } double GetPerformanceCounter() { LARGE_INTEGER li; NtQueryPerformanceCounter(&li, NULL); return (double)li.QuadPart / PCFreq; } BOOLEAN IsGpuLag() { if (PushSharedMemory->HarwareInformation.DisplayDevice.Load > 95) { return TRUE; } return FALSE; } #define TSAMP 60 double garb[TSAMP]; int addint = 0; double GetAverageFrameTime() { UINT32 i; double total = 0; for (i = 0; i < TSAMP; i++) total += garb[i]; return total / TSAMP; } #include <math.h> bool approximatelyEqual(double a, double b, double epsilon) { return fabs(a - b) < epsilon; } VOID RunFrameStatistics() { static double newTickCount = 0.0, lastTickCount_FrameLimiter = 0.0, oldTick = 0.0, delta = 0.0, oldTick2 = 0.0, frameTime = 0.0, acceptableFrameTime = 0.0, lastTickCount; static BOOLEAN inited = FALSE; if (!inited) { DEVMODE devMode; StartCounter(); inited = TRUE; EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &devMode); DisplayFrequency = devMode.dmDisplayFrequency; acceptableFrameTime = (double)1000 / (double)(devMode.dmDisplayFrequency - 1); if (PushSharedMemory->FrameLimit > 1) { FrameLimit = PushSharedMemory->FrameLimit; acceptableFrameTime = 1000.0f / (double)(FrameLimit - 1); } newTickCount = oldTick = lastTickCount_FrameLimiter = GetPerformanceCounter(); } newTickCount = GetPerformanceCounter(); delta = newTickCount - oldTick; frameTime = newTickCount - lastTickCount; lastTickCount = newTickCount; IsLimitedFrametime = FALSE; garb[addint] = frameTime; addint++; if (addint == TSAMP) addint = 0; FrameTimeAvg = GetAverageFrameTime(); static double OldfFPS = 0.0f; FrameRate = 1000.0f / FrameTimeAvg; FrameRate = FrameRate * 0.1 + OldfFPS * 0.9; //FrameRate = FrameRate * 0.01 + OldfFPS * 0.99; even slower damping OldfFPS = FrameRate; // Every second. if (delta > 1000) { oldTick = newTickCount; //if (PushSharedMemory->ThreadOptimization || PushSharedMemory->OSDFlags & OSD_MTU) //{ PushRefreshThreadMonitor(); //if (PushSharedMemory->OSDFlags & OSD_MTU) PushSharedMemory->HarwareInformation.Processor.MaxThreadUsage = PushGetMaxThreadUsage(); //} RenderThreadHandle = GetCurrentThread(); } // Simple Diagnostics. if (frameTime > acceptableFrameTime) { if (PushSharedMemory->HarwareInformation.Processor.Load > 95) PushSharedMemory->Overloads |= OSD_CPU_LOAD; if (PushSharedMemory->HarwareInformation.Processor.MaxCoreUsage > 95) PushSharedMemory->Overloads |= OSD_MCU; if (PushSharedMemory->HarwareInformation.Processor.MaxThreadUsage > 95) PushSharedMemory->Overloads |= OSD_MTU; if (IsGpuLag()) PushSharedMemory->Overloads |= OSD_GPU_LOAD; if (PushSharedMemory->HarwareInformation.Memory.Used > PushSharedMemory->HarwareInformation.Memory.Total) PushSharedMemory->Overloads |= OSD_RAM; PushSharedMemory->HarwareInformation.Disk.ResponseTime = DiskResponseTime; if (PushSharedMemory->HarwareInformation.Disk.ResponseTime > 4000) { PushSharedMemory->Overloads |= OSD_DISK_RESPONSE; PushSharedMemory->OSDFlags |= OSD_DISK_RESPONSE; } if (PushSharedMemory->AutoLogFileIo) PushSharedMemory->LogFileIo = TRUE; if (PushSharedMemory->HarwareInformation.Processor.MaxThreadUsage > 95) { PushSharedMemory->Overloads |= OSD_MTU; PushSharedMemory->OSDFlags |= OSD_MTU; } } if (newTickCount - oldTick2 > 30000) //frame rate has been stable for at least 30 seconds. IsStableFramerate = TRUE; else IsStableFramerate = FALSE; if (FrameTimeAvg > acceptableFrameTime) { //reset the timer oldTick2 = newTickCount; // Lazy overclock if (debugInt++ % DisplayFrequency == 0) { if (!DisableAutoOverclock && IsGpuLag()) { PushSharedMemory->OSDFlags |= OSD_GPU_E_CLK; PushSharedMemory->OSDFlags |= OSD_GPU_M_CLK; PushSharedMemory->Overloads |= OSD_GPU_E_CLK; PushSharedMemory->Overloads |= OSD_GPU_M_CLK; if (PushSharedMemory->HarwareInformation.DisplayDevice.EngineClockMax < PushSharedMemory->HarwareInformation.DisplayDevice.EngineOverclock) Overclock(OC_ENGINE); if (PushSharedMemory->HarwareInformation.DisplayDevice.MemoryClockMax < PushSharedMemory->HarwareInformation.DisplayDevice.MemoryOverclock) Overclock(OC_MEMORY); } } } double frameTimeDamped = 1000.0f / FrameRate; if (frameTimeDamped > acceptableFrameTime) IsStableFrametime = FALSE; else IsStableFrametime = TRUE; if (PushSharedMemory->FrameLimit) { double frameTimeMin = (double)1000 / (double)FrameLimit; frameTime = newTickCount - lastTickCount_FrameLimiter; if (approximatelyEqual(frameTimeDamped, frameTimeMin, 0.100)) { IsLimitedFrametime = TRUE; } if (frameTime < frameTimeMin) { UINT64 cyclesStart, cyclesStop; RenderThreadHandle = GetCurrentThread(); QueryThreadCycleTime(RenderThreadHandle, &cyclesStart); lastTickCount_FrameLimiter = newTickCount; while (frameTime < frameTimeMin) { newTickCount = GetPerformanceCounter(); frameTime += (newTickCount - lastTickCount_FrameLimiter); lastTickCount_FrameLimiter = newTickCount; } QueryThreadCycleTime(RenderThreadHandle, &cyclesStop); CyclesWaited += cyclesStop - cyclesStart; } lastTickCount_FrameLimiter = newTickCount; } } VOID RnRender( OvOverlay* Overlay ) { static BOOLEAN rendering = FALSE; if (!rendering) { rendering = TRUE; InitializeKeyboardHook(); } Osd_Draw( Overlay ); MnuRender( Overlay ); RunFrameStatistics(); //Overlay->DrawText(L"u can draw anything in this render loop!\n"); } <|endoftext|>
<commit_before>// Copyright (c) 2009 Roman Neuhauser // Distributed under the MIT license (see LICENSE file) // vim: sw=4 sts=4 et fdm=marker cms=\ //\ %s #include "php_iniphile.hpp" #include "iniphile.hpp" #include "zend_exceptions.h" zend_class_entry *iniphile_ce; zend_object_handlers iniphile_object_handlers; struct phpini // {{{ { zend_object std; iniphile_bridge *impl; }; // }}} #define PHPTHIS() \ static_cast<phpini *>( \ zend_object_store_get_object(getThis() TSRMLS_CC) \ ) void iniphile_free_storage(void *object TSRMLS_DC) // {{{ { phpini *obj = static_cast<phpini *>(object); delete obj->impl; zend_hash_destroy(obj->std.properties); FREE_HASHTABLE(obj->std.properties); efree(obj); } // }}} static void init(zend_object *zob, zend_class_entry *type TSRMLS_DC) // {{{ { zob->ce = type; ALLOC_HASHTABLE(zob->properties); zend_hash_init( zob->properties , 0 , 0 , ZVAL_PTR_DTOR , 0 ); zval *tmp; zend_hash_copy( zob->properties , &(zob->ce)->default_properties , reinterpret_cast<copy_ctor_func_t>(zval_add_ref) , static_cast<void *>(&tmp) , sizeof(zval *) ); } // }}} zend_object_value iniphile_create_handler(zend_class_entry *type TSRMLS_DC) // {{{ { phpini *obj = static_cast<phpini *>( emalloc(sizeof(phpini)) ); memset(obj, 0, sizeof(phpini)); zend_object *zob(&obj->std); init(zob, type TSRMLS_CC); zend_object_value retval; retval.handle = zend_objects_store_put( obj , 0 , iniphile_free_storage , 0 TSRMLS_CC ); retval.handlers = &iniphile_object_handlers; return retval; } // }}} static void get_strings(zval *dst, zval const *src, phpini *obj, char const *path) // {{{ { typedef std::vector<std::string> Strings; zval **elm; HashPosition i; HashTable *hash = Z_ARRVAL_P(src); Strings dv; dv.reserve(zend_hash_num_elements(hash)); for ( zend_hash_internal_pointer_reset_ex(hash, &i); SUCCESS == zend_hash_get_current_data_ex(hash, (void**) &elm, &i); zend_hash_move_forward_ex(hash, &i) ) { dv.push_back(Z_STRVAL_PP(elm)); } Strings rv(obj->impl->get(path, dv)); array_init(dst); for (int i = 0; i < rv.size(); ++i) { add_next_index_string(dst, estrdup(rv[i].c_str()), 0); } } // }}} #define PHPINI_THROW(m) \ zend_throw_exception( \ zend_exception_get_default(TSRMLS_C) \ , m \ , 0 TSRMLS_CC \ ); #if ZEND_MODULE_API_NO >= 20090626 #define PHPINI_EH_DECL zend_error_handling error_handling #define PHPINI_EH_THROWING \ zend_replace_error_handling( \ EH_THROW \ , NULL \ , &error_handling TSRMLS_CC \ ) #define PHPINI_EH_NORMAL zend_restore_error_handling(&error_handling TSRMLS_CC) #else #define PHPINI_EH_DECL #define PHPINI_EH_THROWING \ php_set_error_handling( \ EH_THROW \ , zend_exception_get_default(TSRMLS_C) TSRMLS_CC \ ) #define PHPINI_EH_NORMAL php_std_error_handling() #endif PHP_METHOD(iniphile, __construct) // {{{ { char *path; int pathlen; PHPINI_EH_DECL; PHPINI_EH_THROWING; if (FAILURE == zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC , "s" , &path , &pathlen )) { PHPINI_EH_NORMAL; return; } PHPINI_EH_NORMAL; phpini *obj = PHPTHIS(); try { obj->impl = new iniphile_bridge(path); } catch (std::exception &e) { zend_throw_exception_ex( zend_exception_get_default(TSRMLS_C) , 0 TSRMLS_CC , "'%s' could not be open" , path ); } } // }}} PHP_METHOD(iniphile, path) // {{{ { phpini *obj = PHPTHIS(); RETURN_STRING(estrdup(obj->impl->path().c_str()), 0); } // }}} PHP_METHOD(iniphile, get) // {{{ { phpini *obj = PHPTHIS(); char *path; int path_len; zval *dflt; if (FAILURE == zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC , "sz" , &path , &path_len , &dflt )) { RETURN_NULL(); } switch (Z_TYPE_P(dflt)) { case IS_BOOL: RETURN_BOOL(obj->impl->get(path, !!Z_LVAL_P(dflt))); case IS_LONG: RETURN_LONG(obj->impl->get(path, Z_LVAL_P(dflt))); case IS_DOUBLE: RETURN_DOUBLE(obj->impl->get(path, Z_DVAL_P(dflt))); case IS_STRING: RETURN_STRING(estrdup(obj->impl->get(path, std::string(Z_STRVAL_P(dflt))).c_str()), 0); case IS_ARRAY: get_strings(return_value, dflt, obj, path); } } // }}} function_entry iniphile_methods[] = // {{{ { PHP_ME(iniphile, __construct, 0, ZEND_ACC_PUBLIC | ZEND_ACC_CTOR) PHP_ME(iniphile, path, 0, ZEND_ACC_PUBLIC) PHP_ME(iniphile, get, 0, ZEND_ACC_PUBLIC) {0, 0, 0} }; // }}} PHP_MINIT_FUNCTION(iniphile) // {{{ { zend_class_entry ce; INIT_CLASS_ENTRY(ce, "iniphile", iniphile_methods); iniphile_ce = zend_register_internal_class(&ce TSRMLS_CC); iniphile_ce->create_object = &iniphile_create_handler; memcpy( &iniphile_object_handlers , zend_get_std_object_handlers() , sizeof(zend_object_handlers) ); iniphile_object_handlers.clone_obj = 0; return SUCCESS; } // }}} zend_module_entry iniphile_module_entry = // {{{ { STANDARD_MODULE_HEADER, PHP_INIPHILE_EXTNAME, 0, // functions PHP_MINIT(iniphile), 0, // MSHUTDOWN 0, // RINIT 0, // RSHUTDOWN 0, // MINFO PHP_INIPHILE_EXTVER, STANDARD_MODULE_PROPERTIES }; // }}} #ifdef COMPILE_DL_INIPHILE extern "C" { ZEND_GET_MODULE(iniphile) } #endif <commit_msg>userland iniphile::get throws on unsupported value types<commit_after>// Copyright (c) 2009 Roman Neuhauser // Distributed under the MIT license (see LICENSE file) // vim: sw=4 sts=4 et fdm=marker cms=\ //\ %s #include "php_iniphile.hpp" #include "iniphile.hpp" #include "zend_exceptions.h" zend_class_entry *iniphile_ce; zend_object_handlers iniphile_object_handlers; struct phpini // {{{ { zend_object std; iniphile_bridge *impl; }; // }}} #define PHPTHIS() \ static_cast<phpini *>( \ zend_object_store_get_object(getThis() TSRMLS_CC) \ ) void iniphile_free_storage(void *object TSRMLS_DC) // {{{ { phpini *obj = static_cast<phpini *>(object); delete obj->impl; zend_hash_destroy(obj->std.properties); FREE_HASHTABLE(obj->std.properties); efree(obj); } // }}} static void init(zend_object *zob, zend_class_entry *type TSRMLS_DC) // {{{ { zob->ce = type; ALLOC_HASHTABLE(zob->properties); zend_hash_init( zob->properties , 0 , 0 , ZVAL_PTR_DTOR , 0 ); zval *tmp; zend_hash_copy( zob->properties , &(zob->ce)->default_properties , reinterpret_cast<copy_ctor_func_t>(zval_add_ref) , static_cast<void *>(&tmp) , sizeof(zval *) ); } // }}} zend_object_value iniphile_create_handler(zend_class_entry *type TSRMLS_DC) // {{{ { phpini *obj = static_cast<phpini *>( emalloc(sizeof(phpini)) ); memset(obj, 0, sizeof(phpini)); zend_object *zob(&obj->std); init(zob, type TSRMLS_CC); zend_object_value retval; retval.handle = zend_objects_store_put( obj , 0 , iniphile_free_storage , 0 TSRMLS_CC ); retval.handlers = &iniphile_object_handlers; return retval; } // }}} static void get_strings(zval *dst, zval const *src, phpini *obj, char const *path) // {{{ { typedef std::vector<std::string> Strings; zval **elm; HashPosition i; HashTable *hash = Z_ARRVAL_P(src); Strings dv; dv.reserve(zend_hash_num_elements(hash)); for ( zend_hash_internal_pointer_reset_ex(hash, &i); SUCCESS == zend_hash_get_current_data_ex(hash, (void**) &elm, &i); zend_hash_move_forward_ex(hash, &i) ) { dv.push_back(Z_STRVAL_PP(elm)); } Strings rv(obj->impl->get(path, dv)); array_init(dst); for (int i = 0; i < rv.size(); ++i) { add_next_index_string(dst, estrdup(rv[i].c_str()), 0); } } // }}} #define PHPINI_THROW(m) \ zend_throw_exception( \ zend_exception_get_default(TSRMLS_C) \ , m \ , 0 TSRMLS_CC \ ); #if ZEND_MODULE_API_NO >= 20090626 #define PHPINI_EH_DECL zend_error_handling error_handling #define PHPINI_EH_THROWING \ zend_replace_error_handling( \ EH_THROW \ , NULL \ , &error_handling TSRMLS_CC \ ) #define PHPINI_EH_NORMAL zend_restore_error_handling(&error_handling TSRMLS_CC) #else #define PHPINI_EH_DECL #define PHPINI_EH_THROWING \ php_set_error_handling( \ EH_THROW \ , zend_exception_get_default(TSRMLS_C) TSRMLS_CC \ ) #define PHPINI_EH_NORMAL php_std_error_handling() #endif PHP_METHOD(iniphile, __construct) // {{{ { char *path; int pathlen; PHPINI_EH_DECL; PHPINI_EH_THROWING; if (FAILURE == zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC , "s" , &path , &pathlen )) { PHPINI_EH_NORMAL; return; } PHPINI_EH_NORMAL; phpini *obj = PHPTHIS(); try { obj->impl = new iniphile_bridge(path); } catch (std::exception &e) { zend_throw_exception_ex( zend_exception_get_default(TSRMLS_C) , 0 TSRMLS_CC , "'%s' could not be open" , path ); } } // }}} PHP_METHOD(iniphile, path) // {{{ { phpini *obj = PHPTHIS(); RETURN_STRING(estrdup(obj->impl->path().c_str()), 0); } // }}} PHP_METHOD(iniphile, get) // {{{ { phpini *obj = PHPTHIS(); char *path; int path_len; zval *dflt; if (FAILURE == zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC , "sz" , &path , &path_len , &dflt )) { RETURN_NULL(); } switch (Z_TYPE_P(dflt)) { case IS_BOOL: RETURN_BOOL(obj->impl->get(path, !!Z_LVAL_P(dflt))); case IS_LONG: RETURN_LONG(obj->impl->get(path, Z_LVAL_P(dflt))); case IS_DOUBLE: RETURN_DOUBLE(obj->impl->get(path, Z_DVAL_P(dflt))); case IS_STRING: RETURN_STRING(estrdup(obj->impl->get(path, std::string(Z_STRVAL_P(dflt))).c_str()), 0); case IS_ARRAY: get_strings(return_value, dflt, obj, path); break; default: PHPINI_THROW("Unsupported value type"); } } // }}} function_entry iniphile_methods[] = // {{{ { PHP_ME(iniphile, __construct, 0, ZEND_ACC_PUBLIC | ZEND_ACC_CTOR) PHP_ME(iniphile, path, 0, ZEND_ACC_PUBLIC) PHP_ME(iniphile, get, 0, ZEND_ACC_PUBLIC) {0, 0, 0} }; // }}} PHP_MINIT_FUNCTION(iniphile) // {{{ { zend_class_entry ce; INIT_CLASS_ENTRY(ce, "iniphile", iniphile_methods); iniphile_ce = zend_register_internal_class(&ce TSRMLS_CC); iniphile_ce->create_object = &iniphile_create_handler; memcpy( &iniphile_object_handlers , zend_get_std_object_handlers() , sizeof(zend_object_handlers) ); iniphile_object_handlers.clone_obj = 0; return SUCCESS; } // }}} zend_module_entry iniphile_module_entry = // {{{ { STANDARD_MODULE_HEADER, PHP_INIPHILE_EXTNAME, 0, // functions PHP_MINIT(iniphile), 0, // MSHUTDOWN 0, // RINIT 0, // RSHUTDOWN 0, // MINFO PHP_INIPHILE_EXTVER, STANDARD_MODULE_PROPERTIES }; // }}} #ifdef COMPILE_DL_INIPHILE extern "C" { ZEND_GET_MODULE(iniphile) } #endif <|endoftext|>
<commit_before>/** * \file * \brief Scheduler class implementation * * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * 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/. * * \date 2014-08-01 */ #include "distortos/scheduler/Scheduler.hpp" #include "distortos/scheduler/idleThreadControlBlock.hpp" #include "distortos/architecture/InterruptMaskingLock.hpp" #include "distortos/distortosConfiguration.h" namespace distortos { namespace scheduler { /*---------------------------------------------------------------------------------------------------------------------+ | public functions +---------------------------------------------------------------------------------------------------------------------*/ Scheduler::Scheduler() : currentThreadControlBlock_{}, runnableList_{ThreadControlBlock::State::Runnable}, sleepingList_{ThreadControlBlock::State::Sleeping}, tickCount_{0} { } void Scheduler::add(ThreadControlBlock &thread_control_block) { architecture::InterruptMaskingLock lock; runnableList_.sortedEmplace(thread_control_block); } uint64_t Scheduler::getTickCount() const { architecture::InterruptMaskingLock lock; return tickCount_; } Scheduler::TimePoint Scheduler::getTimePoint() const { using TickDuration = std::chrono::duration<TimePoint::duration::rep, std::ratio<1, CONFIG_TICK_RATE_HZ>>; const auto tick_count = getTickCount(); const TickDuration duration {tick_count}; const TimePoint time_point {duration}; return time_point; } void Scheduler::sleepFor(const uint64_t ticks) { sleepUntil(getTickCount() + ticks + 1); } void Scheduler::sleepUntil(const uint64_t tick_value) { architecture::InterruptMaskingLock lock; getCurrentThreadControlBlock().setSleepUntil(tick_value); sleepingList_.sortedSplice(runnableList_, currentThreadControlBlock_); yield(); } void Scheduler::start() { add(idleThreadControlBlock); currentThreadControlBlock_ = runnableList_.begin(); architecture::startScheduling(); } void * Scheduler::switchContext(void *stack_pointer) { architecture::InterruptMaskingLock lock; getCurrentThreadControlBlock().getStack().setStackPointer(stack_pointer); // if the object is on the "runnable" list do the rotation - move current thread to the end of same-priority group // to implement round-robin scheduling if (getCurrentThreadControlBlock().getState() == ThreadControlBlock::State::Runnable) runnableList_.sortedSplice(runnableList_, currentThreadControlBlock_); currentThreadControlBlock_ = runnableList_.begin(); return getCurrentThreadControlBlock().getStack().getStackPointer(); } bool Scheduler::tickInterruptHandler() { architecture::InterruptMaskingLock lock; ++tickCount_; auto iterator = sleepingList_.begin(); // wake all threads that reached their timeout while (iterator != sleepingList_.end() && iterator->get().getSleepUntil() <= tickCount_) { runnableList_.sortedSplice(sleepingList_, iterator); ++iterator; } return isContextSwitchRequired_(); } void Scheduler::yield() const { if (isContextSwitchRequired_() == true) architecture::requestContextSwitch(); } /*---------------------------------------------------------------------------------------------------------------------+ | private functions +---------------------------------------------------------------------------------------------------------------------*/ bool Scheduler::isContextSwitchRequired_() const { if (getCurrentThreadControlBlock().getState() != ThreadControlBlock::State::Runnable) return true; if (runnableList_.size() == 1) // single thread available? return false; // no context switch possible if (runnableList_.begin() != currentThreadControlBlock_) // is there a higher-priority thread available? return true; const auto next_thread = ++runnableList_.begin(); const auto next_thread_priority = next_thread->get().getPriority(); if (getCurrentThreadControlBlock().getPriority() == next_thread_priority) // next thread has the same priority? return true; // switch context to do round-robin scheduling return false; } } // namespace scheduler } // namespace distortos <commit_msg>scheduler: fix loop that wakes sleeping threads in Scheduler::tickInterruptHandler() - after the transfer the iterator no longer points to the sleeping list<commit_after>/** * \file * \brief Scheduler class implementation * * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * 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/. * * \date 2014-08-01 */ #include "distortos/scheduler/Scheduler.hpp" #include "distortos/scheduler/idleThreadControlBlock.hpp" #include "distortos/architecture/InterruptMaskingLock.hpp" #include "distortos/distortosConfiguration.h" namespace distortos { namespace scheduler { /*---------------------------------------------------------------------------------------------------------------------+ | public functions +---------------------------------------------------------------------------------------------------------------------*/ Scheduler::Scheduler() : currentThreadControlBlock_{}, runnableList_{ThreadControlBlock::State::Runnable}, sleepingList_{ThreadControlBlock::State::Sleeping}, tickCount_{0} { } void Scheduler::add(ThreadControlBlock &thread_control_block) { architecture::InterruptMaskingLock lock; runnableList_.sortedEmplace(thread_control_block); } uint64_t Scheduler::getTickCount() const { architecture::InterruptMaskingLock lock; return tickCount_; } Scheduler::TimePoint Scheduler::getTimePoint() const { using TickDuration = std::chrono::duration<TimePoint::duration::rep, std::ratio<1, CONFIG_TICK_RATE_HZ>>; const auto tick_count = getTickCount(); const TickDuration duration {tick_count}; const TimePoint time_point {duration}; return time_point; } void Scheduler::sleepFor(const uint64_t ticks) { sleepUntil(getTickCount() + ticks + 1); } void Scheduler::sleepUntil(const uint64_t tick_value) { architecture::InterruptMaskingLock lock; getCurrentThreadControlBlock().setSleepUntil(tick_value); sleepingList_.sortedSplice(runnableList_, currentThreadControlBlock_); yield(); } void Scheduler::start() { add(idleThreadControlBlock); currentThreadControlBlock_ = runnableList_.begin(); architecture::startScheduling(); } void * Scheduler::switchContext(void *stack_pointer) { architecture::InterruptMaskingLock lock; getCurrentThreadControlBlock().getStack().setStackPointer(stack_pointer); // if the object is on the "runnable" list do the rotation - move current thread to the end of same-priority group // to implement round-robin scheduling if (getCurrentThreadControlBlock().getState() == ThreadControlBlock::State::Runnable) runnableList_.sortedSplice(runnableList_, currentThreadControlBlock_); currentThreadControlBlock_ = runnableList_.begin(); return getCurrentThreadControlBlock().getStack().getStackPointer(); } bool Scheduler::tickInterruptHandler() { architecture::InterruptMaskingLock lock; ++tickCount_; // wake all threads that reached their timeout for (auto iterator = sleepingList_.begin(); iterator != sleepingList_.end() && iterator->get().getSleepUntil() <= tickCount_; iterator = sleepingList_.begin()) runnableList_.sortedSplice(sleepingList_, iterator); return isContextSwitchRequired_(); } void Scheduler::yield() const { if (isContextSwitchRequired_() == true) architecture::requestContextSwitch(); } /*---------------------------------------------------------------------------------------------------------------------+ | private functions +---------------------------------------------------------------------------------------------------------------------*/ bool Scheduler::isContextSwitchRequired_() const { if (getCurrentThreadControlBlock().getState() != ThreadControlBlock::State::Runnable) return true; if (runnableList_.size() == 1) // single thread available? return false; // no context switch possible if (runnableList_.begin() != currentThreadControlBlock_) // is there a higher-priority thread available? return true; const auto next_thread = ++runnableList_.begin(); const auto next_thread_priority = next_thread->get().getPriority(); if (getCurrentThreadControlBlock().getPriority() == next_thread_priority) // next thread has the same priority? return true; // switch context to do round-robin scheduling return false; } } // namespace scheduler } // namespace distortos <|endoftext|>
<commit_before>#include <VMDE/VMDE.hpp> #ifndef _INCLUDE_TILES_H #define _INCLUDE_TILES_H namespace VM76 { class Tile { public: GDrawable* obj[6] = {NULL, NULL, NULL, NULL, NULL, NULL}; private: GLfloat *vtx[6] = {NULL, NULL, NULL, NULL, NULL, NULL}; GLuint *itx[6] = {NULL, NULL, NULL, NULL, NULL, NULL}; glm::mat4 *mat = NULL; public: Tile(int tid); void render(); void dispose(); }; } #endif <commit_msg>.....<commit_after>#include "global.hpp" #ifndef _INCLUDE_TILES_H #define _INCLUDE_TILES_H namespace VM76 { class Tile { public: GDrawable* obj[6] = {NULL, NULL, NULL, NULL, NULL, NULL}; private: GLfloat *vtx[6] = {NULL, NULL, NULL, NULL, NULL, NULL}; GLuint *itx[6] = {NULL, NULL, NULL, NULL, NULL, NULL}; glm::mat4 *mat = NULL; public: Tile(int tid); void render(); void dispose(); }; } #endif <|endoftext|>
<commit_before>/************************************************************************** * * Copyright 2010 VMware, Inc. * Copyright 2011 Intel corporation * All Rights Reserved. * * 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 <string.h> #include <limits.h> // for CHAR_MAX #include <getopt.h> #include "cli.hpp" #include "os_string.hpp" #include "trace_callset.hpp" #include "trace_parser.hpp" #include "trace_writer.hpp" static const char *synopsis = "Create a new trace by trimming an existing trace."; static void usage(void) { std::cout << "usage: apitrace trim [OPTIONS] TRACE_FILE...\n" << synopsis << "\n" "\n" " -h, --help show this help message and exit\n" " --calls=CALLSET only retain specified calls\n" " --thread=THREAD_ID only retain calls from specified thread\n" " -o, --output=TRACE_FILE output trace file\n" "\n" ; } enum { CALLS_OPT = CHAR_MAX + 1, THREAD_OPT, }; const static char * shortOptions = "ho:"; const static struct option longOptions[] = { {"help", no_argument, 0, 'h'}, {"calls", required_argument, 0, CALLS_OPT}, {"thread", required_argument, 0, THREAD_OPT}, {"output", required_argument, 0, 'o'}, {0, 0, 0, 0} }; static int command(int argc, char *argv[]) { std::string output; trace::CallSet calls(trace::FREQUENCY_ALL); int thread = -1; int i; int opt; while ((opt = getopt_long(argc, argv, shortOptions, longOptions, NULL)) != -1) { switch (opt) { case 'h': usage(); return 0; case CALLS_OPT: calls = trace::CallSet(optarg); break; case THREAD_OPT: thread = atoi(optarg); break; case 'o': output = optarg; break; default: std::cerr << "error: unexpected option `" << opt << "`\n"; usage(); return 1; } } if (optind >= argc) { std::cerr << "error: apitrace trim requires a trace file as an argument.\n"; usage(); return 1; } for (i = optind; i < argc; ++i) { trace::Parser p; if (!p.open(argv[i])) { return 1; } if (output.empty()) { os::String base(argv[i]); base.trimExtension(); output = std::string(base.str()) + std::string("-trim.trace"); } trace::Writer writer; if (!writer.open(output.c_str())) { std::cerr << "error: failed to create " << argv[i] << "\n"; return 1; } trace::Call *call; while ((call = p.parse_call())) { if (calls.contains(*call) && (thread == -1 || call->thread_id == thread)) { writer.writeCall(call); } delete call; } std::cout << "Trimmed trace is available as " << output << "\n"; } return 0; } const Command trim_command = { "trim", synopsis, usage, command }; <commit_msg>trim: Add framework for performing dependency analysis while trimming<commit_after>/************************************************************************** * * Copyright 2010 VMware, Inc. * Copyright 2011 Intel corporation * All Rights Reserved. * * 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 <string.h> #include <limits.h> // for CHAR_MAX #include <getopt.h> #include <set> #include "cli.hpp" #include "os_string.hpp" #include "trace_callset.hpp" #include "trace_parser.hpp" #include "trace_writer.hpp" static const char *synopsis = "Create a new trace by trimming an existing trace."; static void usage(void) { std::cout << "usage: apitrace trim [OPTIONS] TRACE_FILE...\n" << synopsis << "\n" "\n" " -h, --help Show this help message and exit\n" " --calls=CALLSET Include specified calls in the trimmed output\n" " --deps Perform dependency analysis and include dependent\n" " calls as needed. This is the default behavior.\n" " --no-deps Do not perform dependency analysis. Include only\n" " those calls explicitly listed in --calls\n" " --thread=THREAD_ID Only retain calls from specified thread\n" " -o, --output=TRACE_FILE Output trace file\n" "\n" ; } enum { CALLS_OPT = CHAR_MAX + 1, DEPS_OPT, NO_DEPS_OPT, THREAD_OPT, }; const static char * shortOptions = "ho:"; const static struct option longOptions[] = { {"help", no_argument, 0, 'h'}, {"calls", required_argument, 0, CALLS_OPT}, {"deps", no_argument, 0, DEPS_OPT}, {"no-deps", no_argument, 0, NO_DEPS_OPT}, {"thread", required_argument, 0, THREAD_OPT}, {"output", required_argument, 0, 'o'}, {0, 0, 0, 0} }; struct stringCompare { bool operator() (const char *a, const char *b) const { return strcmp(a, b) < 0; } }; class TraceAnalyzer { /* Map for tracking resource dependencies between calls. */ std::map<const char *, std::set<unsigned>, stringCompare > resources; /* The final set of calls required. This consists of calls added * explicitly with the require() method as well as all calls * implicitly required by those through resource dependencies. */ std::set<unsigned> required; public: TraceAnalyzer() {} ~TraceAnalyzer() {} /* Compute and record all the resources provided by this call. */ void analyze(trace::Call *call) { resources["state"].insert(call->no); } /* Require this call and all of its dependencies to be included in * the final trace. */ void require(trace::Call *call) { std::set<unsigned> *dependencies; std::set<unsigned>::iterator i; /* First, find and insert all calls that this call depends on. */ dependencies = &resources["state"]; for (i = dependencies->begin(); i != dependencies->end(); i++) { required.insert(*i); } resources["state"].clear(); /* Then insert this call itself. */ required.insert(call->no); } /* Return a set of all the required calls, (both those calls added * explicitly with require() and those implicitly depended * upon. */ std::set<unsigned> *get_required(void) { return &required; } }; struct trim_options { /* Calls to be included in trace. */ trace::CallSet calls; /* Whether dependency analysis should be performed. */ bool dependency_analysis; /* Output filename */ std::string output; /* Emit only calls from this thread (-1 == all threads) */ int thread; }; static int trim_trace(const char *filename, struct trim_options *options) { trace::ParseBookmark beginning; trace::Parser p; TraceAnalyzer analyzer; std::set<unsigned> *required; if (!p.open(filename)) { std::cerr << "error: failed to open " << filename << "\n"; return 1; } /* Mark the beginning so we can return here for pass 2. */ p.getBookmark(beginning); /* In pass 1, analyze which calls are needed. */ trace::Call *call; while ((call = p.parse_call())) { /* If requested, ignore all calls not belonging to the specified thread. */ if (options->thread != -1 && call->thread_id != options->thread) continue; /* If this call is included in the user-specified call * set, then we don't need to perform any analysis on * it. We know it must be included. */ if (options->calls.contains(*call)) { analyzer.require(call); } else { if (options->dependency_analysis) analyzer.analyze(call); } } /* Prepare output file and writer for output. */ if (options->output.empty()) { os::String base(filename); base.trimExtension(); options->output = std::string(base.str()) + std::string("-trim.trace"); } trace::Writer writer; if (!writer.open(options->output.c_str())) { std::cerr << "error: failed to create " << filename << "\n"; return 1; } /* Reset bookmark for pass 2. */ p.setBookmark(beginning); /* In pass 2, emit the calls that are required. */ required = analyzer.get_required(); while ((call = p.parse_call())) { if (required->find(call->no) != required->end()) { writer.writeCall(call); } delete call; } std::cout << "Trimmed trace is available as " << options->output << "\n"; return 0; } static int command(int argc, char *argv[]) { struct trim_options options; options.calls = trace::CallSet(trace::FREQUENCY_ALL); options.dependency_analysis = true; options.output = ""; options.thread = -1; int opt; while ((opt = getopt_long(argc, argv, shortOptions, longOptions, NULL)) != -1) { switch (opt) { case 'h': usage(); return 0; case CALLS_OPT: options.calls = trace::CallSet(optarg); break; case DEPS_OPT: options.dependency_analysis = true; break; case NO_DEPS_OPT: options.dependency_analysis = false; break; case THREAD_OPT: options.thread = atoi(optarg); break; case 'o': options.output = optarg; break; default: std::cerr << "error: unexpected option `" << opt << "`\n"; usage(); return 1; } } if (optind >= argc) { std::cerr << "error: apitrace trim requires a trace file as an argument.\n"; usage(); return 1; } return trim_trace(argv[optind], &options); } const Command trim_command = { "trim", synopsis, usage, command }; <|endoftext|>
<commit_before>#include <ap_int.h> #include "spbits.h" #include "match_seg.h" using namespace std; #define add if(this->pr==1) void match_seg::find_segment_n1_62( ap_uint<bpow+1> ph_pat_p, // ph detected in pattern ap_uint<6> ph_pat_q_p, // pattern valid /* ph from segments [bx_history][chamber][segment]segments are coming from chambers in the interesting zone onlyfor example, in zone 0 ME1 segments should come from chambers subsector1: 1,2,3, subsector2: 1,2,3*/ ap_uint<bw_fph> ph_seg_p[max_drift][zone_cham][seg_ch], // valid flags for segments ap_uint<seg_ch> ph_seg_v_p[max_drift][zone_cham], ap_uint<bw_th> th_seg_p[max_drift][zone_cham][zone_seg], ap_uint<4> cpat_seg_p[max_drift][zone_cham][seg_ch], // indexes of best match ap_uint<seg_ch> *vid, // match valid, each flag shows validity of th coord ap_uint<2> *hid, // history id ap_uint<3> *cid, // chamber id ap_uint<1> *sid, // segment id ap_uint<bw_fph> *ph_match, // ph from matching segment // all th's from matching chamber, we don't know which one will fit best ap_uint<bw_th> th_match[zone_seg], ap_uint<4> *cpat_match // pattern from matching segment ) { #pragma HLS ARRAY_PARTITION variable=th_match complete dim=0 #pragma HLS ARRAY_PARTITION variable=cpat_seg_p complete dim=0 #pragma HLS ARRAY_PARTITION variable=th_seg_p complete dim=0 #pragma HLS ARRAY_PARTITION variable=ph_seg_v_p complete dim=0 #pragma HLS ARRAY_PARTITION variable=ph_seg_p complete dim=0 const int tot_diff = max_drift*6/*zone_cham*/*seg_ch; const int max_ph_diff=7; const int bw_phdiff=4; const int nodiff=15; int i,j,k,di; ap_uint<bpow+1> ph_pat; // ph detected in pattern ap_uint<1> ph_pat_v; // pattern valid ap_uint<bw_fph> ph_seg [max_drift][zone_cham][seg_ch]; ap_uint<seg_ch> ph_seg_v [max_drift][zone_cham]; ap_uint<bw_th> th_seg [max_drift][zone_cham][zone_seg]; ap_uint<4> cpat_seg [max_drift][zone_cham][seg_ch]; ap_uint<bpow+1> ph_segr; ap_uint<bpow+1> ph_diff_tmp; ap_uint<bw_phdiff> ph_diff [tot_diff]; ap_uint<2> rcomp; ap_uint<6> diffi0 [tot_diff]; ap_uint<bw_phdiff> cmp1 [tot_diff/3]; ap_uint<6> diffi1 [tot_diff/3]; ap_uint<bw_phdiff> cmp2 [tot_diff/9]; ap_uint<6> diffi2 [tot_diff/9]; ap_uint<bw_phdiff> cmp3 [tot_diff/18]; ap_uint<6> diffi3 [tot_diff/18]; ap_uint<bw_phdiff> cmp4; ap_uint<6> diffi4; ap_uint<2> ri; ap_uint<3> rj; ap_uint<1> rk; ap_uint<seg_ch> a_vid; // match valid, each flag shows validity of th coord ap_uint<2> a_hid; // history id ap_uint<3> a_cid; // chamber id ap_uint<1> a_sid; /*for(int i=0;i<3;i++){ for(int j=0;j<3zone_cham;j++){ for(int k=0;k<2zone_seg;k++){ cout<<hex<<"th_seg_p["<<i<<"]["<<j<<"]["<<k<<"]= "<<th_seg_p[i][j][k]<<hex<<endl; } } }*/ if(this->pr==1){ cout<<"ph_pat_p= "<<ph_pat_p<<endl; cout<<"ph_pat_q_p= "<<ph_pat_q_p<<endl; for(int i=0;i<3;i++){ for(int j=0;j<6/*zone_cham*/;j++){ for(int k=0;k<2;k++){ cout<<hex<<"ph_seg_p["<<i<<"]["<<j<<"]["<<k<<"]= "<<ph_seg_p[i][j][k]<<hex<<endl; } } } } ph_pat = ph_pat_p; ph_pat_v = ph_pat_q_p != 0; // non-zero quality means valid pattern find_segment_st1_label0:for(int i=0;i<max_drift;i++){ #pragma HLS UNROLL find_segment_st1_label1:for(int j=0;j<6/*zone_cham*/;j++){ #pragma HLS UNROLL find_segment_st1_label2:for(int k=0;k<seg_ch;k++){ #pragma HLS UNROLL ph_seg[i][j][k] = ph_seg_p[i][j][k]; } ph_seg_v[i][j] = ph_seg_v_p[i][j]; find_segment_st1_label3:for(int k=0;k<2/*zone_seg*/;k++){ #pragma HLS UNROLL th_seg[i][j][k] = th_seg_p[i][j][k]; if(this->pr==1 && ph_pat_p==0x49){ //for(int i=0;i<36;i++){ // cout<<"th_seg_p["<<i<<"]["<<j<<"]["<<k<<"]= "<<th_seg_p[i][j][k]<<hex<<endl; } } find_segment_st1_label4:for(int k=0;k<seg_ch;k++){ #pragma HLS UNROLL cpat_seg[i][j][k] = cpat_seg_p[i][j][k]; } } } // calculate abs differences di = 0; find_segment_st1_label5:for (i = 0; i < max_drift; i = i+1){ // history loop #pragma HLS UNROLL find_segment_st1_label6:for (j = 0; j < 6/*zone_cham*/; j = j+1){ // chamber loop #pragma HLS UNROLL find_segment_st1_label7:for (k = 0; k < seg_ch; k = k+1){ // segment loop #pragma HLS UNROLL // remove unused low bits from segment ph ph_segr = ph_seg[i][j][k](bw_fph-1 , bw_fph-bpow-1); // get abs difference if (ph_seg_v[i][j][k]) ph_diff_tmp = (ph_pat > ph_segr) ? ph_pat - ph_segr : ph_segr - ph_pat; else ph_diff_tmp = nodiff; // if segment invalid put max value into diff if((ph_diff_tmp) > (max_ph_diff)) ph_diff[i*6/*zone_cham*/*seg_ch + j*seg_ch + k] = nodiff; // difference is too high, cannot be the same pattern else ph_diff[i*6/*zone_cham*/*seg_ch + j*seg_ch + k] = ph_diff_tmp(bw_phdiff-1,0); ri = i; rj = j; rk = k; // diffi variables carry track indexes diffi0[i*6/*zone_cham*/*seg_ch + j*seg_ch + k] = (ri, rj, rk); } } } // for (i = 0; i < max_drift; i = i+1) /*************sort differences*****************/ // first stage find_segment_st1_label8:for (i = 0; i < tot_diff/3; i = i+1){ #pragma HLS UNROLL // compare 3 values rcomp = comp3(ph_diff[i*3], ph_diff[i*3+1], ph_diff[i*3+2]); // fill outputs switch(rcomp){ case 0: cmp1[i] = ph_diff[i*3+0]; diffi1[i] = diffi0[i*3+0]; break; case 1: cmp1[i] = ph_diff[i*3+1]; diffi1[i] = diffi0[i*3+1]; break; case 2: cmp1[i] = ph_diff[i*3+2]; diffi1[i] = diffi0[i*3+2]; break; default: break; } } // second stage find_segment_st1_label9:for (i = 0; i < tot_diff/9; i = i+1){ #pragma HLS UNROLL // compare 3 values rcomp = comp3(cmp1[i*3], cmp1[i*3+1], cmp1[i*3+2]); // fill outputs switch(rcomp){ case 0: cmp2[i] = cmp1[i*3+0]; diffi2[i] = diffi1[i*3+0]; break; case 1: cmp2[i] = cmp1[i*3+1]; diffi2[i] = diffi1[i*3+1]; break; case 2: cmp2[i] = cmp1[i*3+2]; diffi2[i] = diffi1[i*3+2]; break; default: break; } } // third stage find_segment_st1_label10:for (i = 0; i < tot_diff/18; i = i+1){ #pragma HLS UNROLL // compare 2 values rcomp[0] = cmp2[i*2] >= cmp2[i*2+1]; // fill outputs switch(int(rcomp[0])){ case 0: cmp3[i] = cmp2[i*2+0]; diffi3[i] = diffi2[i*2+0]; break; case 1: cmp3[i] = cmp2[i*2+1]; diffi3[i] = diffi2[i*2+1]; break; default: break; } } // last stage depends on number of input segments if (tot_diff == 36) { // compare 2 values rcomp[0] = cmp3[0] >= cmp3[1]; // fill outputs switch(int(rcomp[0])){ case 0: cmp4 = cmp3[0]; diffi4 = diffi3[0]; break; case 1: cmp4 = cmp3[1]; diffi4 = diffi3[1]; break; default: break; } } else { cmp4 = cmp3[0]; diffi4 = diffi3[0]; } a_hid=diffi4(5,4); a_cid=diffi4(3,1); a_sid = diffi4[0]; a_vid = ph_seg_v[a_hid][a_cid][a_sid]; // if pattern invalid or all differences invalid remove valid flags if (!ph_pat_v || cmp4 == nodiff) a_vid = 0; *ph_match = ph_seg[a_hid][a_cid][a_sid]; // route best matching phi to output find_segment_st1_label11:for(int i=0;i<2/*zone_seg*/;i++) { #pragma HLS UNROLL th_match[i] = th_seg[a_hid][a_cid][i]; // route all th coords from matching chamber to output } *cpat_match = cpat_seg[a_hid][a_cid][a_sid]; // route pattern to output *hid=a_hid; *cid=a_cid; *sid=a_sid; *vid=a_vid; } <commit_msg>Delete find_segment_n1_62.cpp<commit_after><|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #ifndef ITEM_HH #define ITEM_HH #include "config.h" #include "mutex.hh" #include <string> #include <string.h> #include <stdio.h> #include <memcached/engine.h> /** * The Item structure we use to pass information between the memcached * core and the backend. Please note that the kvstore don't store these * objects, so we do have an extra layer of memory copying :( */ class Item { public: Item() { initialize("", 0, 0, NULL, 0, 0); } Item(const void* k, const size_t nk, const size_t nb, const int fl, const rel_time_t exp) { std::string _k(static_cast<const char*>(k), nk); initialize(_k, fl, exp, NULL, nb, 0); } Item(const void* k, const size_t nk, const size_t nb, const int fl, const rel_time_t exp, uint64_t theCas) { std::string _k(static_cast<const char*>(k), nk); initialize(_k, fl, exp, NULL, nb, theCas); } Item(const std::string &k, const int fl, const rel_time_t exp, const void *dta, const size_t nb) { initialize(k, fl, exp, static_cast<const char*>(dta), nb, 0); } Item(const std::string &k, const int fl, const rel_time_t exp, const void *dta, const size_t nb, uint64_t theCas) { initialize(k, fl, exp, static_cast<const char*>(dta), nb, theCas); } Item(const std::string &k, const int fl, const rel_time_t exp, const std::string &val) { initialize(k, fl, exp, val.c_str(), val.size(), 0); } Item(const std::string &k, const int fl, const rel_time_t exp, const std::string &val, uint64_t theCas) { initialize(k, fl, exp, val.c_str(), val.size(), theCas); } Item(const void *k, uint16_t nk, const int fl, const rel_time_t exp, const void *dta, const size_t nb) : key(static_cast<const char*>(k), nk) { std::string _k(static_cast<const char*>(k), nk); initialize(_k, fl, exp, static_cast<const char*>(dta), nb, 0); } Item(const void *k, uint16_t nk, const int fl, const rel_time_t exp, const void *dta, const size_t nb, uint64_t theCas) : key(static_cast<const char*>(k), nk) { std::string _k(static_cast<const char*>(k), nk); initialize(_k, fl, exp, static_cast<const char*>(dta), nb, theCas); } ~Item() { delete []data; } Item(const Item &itm) { initialize(itm.key, itm.flags, itm.exptime, itm.data, itm.nbytes, itm.cas); } Item* clone() { return new Item(key, flags, exptime, data, nbytes, cas); } char *getData() { return data; } const std::string &getKey() const { return key; } int getNKey() const { return key.length(); } uint32_t getNBytes() const { return nbytes; } rel_time_t getExptime() const { return exptime; } int getFlags() const { return flags; } uint64_t getCas() const { return cas; } void setCas() { cas = nextCas(); } void setCas(uint64_t ncas) { cas = ncas; } private: /** * Initialize all of the members in this object. Unfortunately the items * needs to end with "\r\n". Initialize adds this sequence if you pass * data along and append this sequence. */ void initialize(const std::string &k, const int fl, const rel_time_t exp, const char *dta, const size_t nb, uint64_t theCas) { key.assign(k); nbytes = static_cast<uint32_t>(nb); flags = fl; exptime = exp; cas = theCas; if (dta != NULL) { if (nbytes < 2 || memcmp(dta + nb - 2, "\r\n", 2) != 0) { nbytes += 2; } } if (nbytes > 0) { data = new char[nbytes]; } else { data = NULL; } if (data && dta) { memcpy(data, dta, nbytes); if (nb != nbytes) { memcpy(data + nb, "\r\n", 2); } } } int flags; rel_time_t exptime; uint32_t nbytes; std::string key; char *data; uint64_t cas; static uint64_t nextCas(void) { uint64_t ret; casMutex.aquire(); ret = casCounter++; casMutex.release(); if ((ret % casNotificationFrequency) == 0) { casNotifier(ret); } return ret; } static void initializeCas(uint64_t initial, void (*notifier)(uint64_t current), uint64_t frequency) { casCounter = initial; casNotifier = notifier; casNotificationFrequency = frequency; } static uint64_t casNotificationFrequency; static void (*casNotifier)(uint64_t); static uint64_t casCounter; static Mutex casMutex; }; #endif <commit_msg>Refactor Item constructors.<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #ifndef ITEM_HH #define ITEM_HH #include "config.h" #include "mutex.hh" #include <string> #include <string.h> #include <stdio.h> #include <memcached/engine.h> /** * The Item structure we use to pass information between the memcached * core and the backend. Please note that the kvstore don't store these * objects, so we do have an extra layer of memory copying :( */ class Item { public: Item() : flags(0), exptime(0), cas(0) { key.assign(""); setData(NULL, 0); } Item(const void* k, const size_t nk, const size_t nb, const int fl, const rel_time_t exp, uint64_t theCas = 0) : flags(fl), exptime(exp), cas(theCas) { key.assign(static_cast<const char*>(k), nk); setData(NULL, nb); } Item(const std::string &k, const int fl, const rel_time_t exp, const void *dta, const size_t nb, uint64_t theCas = 0) : flags(fl), exptime(exp), cas(theCas) { key.assign(k); setData(static_cast<const char*>(dta), nb); } Item(const std::string &k, const int fl, const rel_time_t exp, const std::string &val, uint64_t theCas = 0) : flags(fl), exptime(exp), cas(theCas) { key.assign(k); setData(val.c_str(), val.size()); } Item(const void *k, uint16_t nk, const int fl, const rel_time_t exp, const void *dta, const size_t nb, uint64_t theCas = 0) : flags(fl), exptime(exp), cas(theCas) { key.assign(static_cast<const char*>(k), nk); setData(static_cast<const char*>(dta), nb); } Item(const Item &itm) : flags(itm.flags), exptime(itm.exptime), cas(itm.cas) { key.assign(itm.key); setData(itm.data, itm.nbytes); } ~Item() { delete []data; } Item* clone() { return new Item(key, flags, exptime, data, nbytes, cas); } char *getData() { return data; } const std::string &getKey() const { return key; } int getNKey() const { return key.length(); } uint32_t getNBytes() const { return nbytes; } rel_time_t getExptime() const { return exptime; } int getFlags() const { return flags; } uint64_t getCas() const { return cas; } void setCas() { cas = nextCas(); } void setCas(uint64_t ncas) { cas = ncas; } private: /** * Set the item's data. This is only used by constructors, so we * make it private. */ void setData(const char *dta, const size_t nb) { nbytes = static_cast<uint32_t>(nb); if (dta != NULL) { if (nbytes < 2 || memcmp(dta + nb - 2, "\r\n", 2) != 0) { nbytes += 2; } } if (nbytes > 0) { data = new char[nbytes]; } else { data = NULL; } if (data && dta) { memcpy(data, dta, nbytes); if (nb != nbytes) { memcpy(data + nb, "\r\n", 2); } } } int flags; rel_time_t exptime; uint32_t nbytes; std::string key; char *data; uint64_t cas; static uint64_t nextCas(void) { uint64_t ret; casMutex.aquire(); ret = casCounter++; casMutex.release(); if ((ret % casNotificationFrequency) == 0) { casNotifier(ret); } return ret; } static void initializeCas(uint64_t initial, void (*notifier)(uint64_t current), uint64_t frequency) { casCounter = initial; casNotifier = notifier; casNotificationFrequency = frequency; } static uint64_t casNotificationFrequency; static void (*casNotifier)(uint64_t); static uint64_t casCounter; static Mutex casMutex; }; #endif <|endoftext|>
<commit_before>/* Copyright (C) 2011 by Ivan Safrin 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. */ #define PI 3.14159265 #include "PolyPhysicsScreenEntity.h" #include "PolyLogger.h" #include "PolyMesh.h" #include "PolyPolygon.h" #include "PolyScreenEntity.h" #include "PolyScreenMesh.h" using namespace Polycode; PhysicsScreenEntity::PhysicsScreenEntity(ScreenEntity *entity, b2World *world, Number worldScale, int entType, bool isStatic, Number friction, Number density, Number restitution, bool isSensor, bool fixedRotation, int groupIndex) { screenEntity = entity; Vector3 entityScale = entity->getCompoundScale(); Matrix4 compoundMatrix = screenEntity->getConcatenatedMatrix(); entity->ignoreParentMatrix = true; entity->scale = entityScale; this->worldScale = worldScale; collisionOnly = false; // Create body definition--------------------------------------- b2BodyDef bodyDef; bodyDef.position.Set(compoundMatrix.getPosition().x/worldScale, compoundMatrix.getPosition().y/worldScale); bodyDef.angle = screenEntity->getRotation()*(PI/180.0f); bodyDef.bullet = isSensor; bodyDef.fixedRotation = fixedRotation; if(isStatic) bodyDef.type = b2_staticBody; else bodyDef.type = b2_dynamicBody; // Create the body body = world->CreateBody(&bodyDef); body->SetUserData(this); // Create fixture definition--------------------------------------------- b2FixtureDef fDef; fDef.friction = friction; fDef.restitution = restitution; fDef.density = density; fDef.isSensor = isSensor; fDef.filter.groupIndex = groupIndex; // Create Shape definition (Circle/Rectangle/Polygon)--------------------------- switch(entType) { case ENTITY_CIRCLE: { b2CircleShape Shape; fDef.shape = &Shape; // Set the shape Shape.m_radius = screenEntity->getWidth()/(worldScale*2.0f); // Create the fixture fixture = body->CreateFixture(&fDef); break; } case ENTITY_RECT: { b2PolygonShape Shape; fDef.shape = &Shape; // Set the shape Shape.SetAsBox(screenEntity->getWidth()/(worldScale*2.0f) * entityScale.x, screenEntity->getHeight()/(worldScale*2.0f) * entityScale.y); // Create the fixture fixture = body->CreateFixture(&fDef); break; } case ENTITY_EDGE: { b2PolygonShape Shape; Shape.SetAsEdge(b2Vec2(-screenEntity->getWidth()/(worldScale*2.0f),-screenEntity->getHeight()/(2.0*worldScale)), b2Vec2(screenEntity->getWidth()/(worldScale*2.0f),-screenEntity->getHeight()/(2.0*worldScale))); fDef.shape = &Shape; fixture = body->CreateFixture(&fDef); break; } break; case ENTITY_MESH: { b2PolygonShape Shape; fDef.shape = &Shape; ScreenMesh* screenMesh = dynamic_cast<ScreenMesh*>(entity); if(screenMesh) { for(short i=0, polycount=screenMesh->getMesh()->getPolygonCount(); i < polycount; i++) { Polygon* poly = screenMesh->getMesh()->getPolygon(i); unsigned short vertexcount = poly->getVertexCount(); if (vertexcount >= 3 && vertexcount <= 8) { b2Vec2* vertices = new b2Vec2[vertexcount]; for(short index=0; index < vertexcount; index++) { vertices[index].x = poly->getVertex(index)->x/worldScale; vertices[index].y = poly->getVertex(index)->y/worldScale; } // Set the shape Shape.Set(vertices, vertexcount); // Create the fixture fixture = body->CreateFixture(&fDef); delete []vertices; } else { Logger::log("Between 3 and 8 vertices allowed per polygon\n"); } } } else { Logger::log("Tried to make a mesh collision object from a non-mesh\n"); } } } } void PhysicsScreenEntity::applyTorque(Number torque) { body->ApplyTorque(torque); } void PhysicsScreenEntity::applyForce(Vector2 force){ body->SetAwake(true); body->ApplyForce(b2Vec2(force.x,force.y), b2Vec2(body->GetPosition().x,body->GetPosition().y)); } ScreenEntity *PhysicsScreenEntity::getScreenEntity() { return screenEntity; } void PhysicsScreenEntity::setVelocity(Number fx, Number fy) { body->SetAwake(true); b2Vec2 f = body->GetLinearVelocity(); if(fx != 0) f.x = fx; if(fy != 0) f.y = fy; body->SetLinearVelocity(f); } void PhysicsScreenEntity::setVelocityX( Number fx) { body->SetAwake(true); b2Vec2 f = body->GetLinearVelocity(); f.x = fx; body->SetLinearVelocity(f); } void PhysicsScreenEntity::setVelocityY(Number fy) { body->SetAwake(true); b2Vec2 f = body->GetLinearVelocity(); f.y = fy; body->SetLinearVelocity(f); } void PhysicsScreenEntity::setCollisionCategory(int categoryBits) { b2Filter filter=fixture->GetFilterData(); filter.categoryBits = categoryBits; fixture->SetFilterData(filter); } void PhysicsScreenEntity::setCollisionMask(int maskBits) { b2Filter filter=fixture->GetFilterData(); filter.maskBits = maskBits; fixture->SetFilterData(filter); } void PhysicsScreenEntity::setCollisionGroupIndex(int group) { b2Filter filter=fixture->GetFilterData(); filter.groupIndex = group; fixture->SetFilterData(filter); } void PhysicsScreenEntity::setLinearDamping(Number damping) { body->SetLinearDamping(damping); } void PhysicsScreenEntity::setAngularDamping(Number damping) { body->SetAngularDamping(damping); } void PhysicsScreenEntity::setFriction(Number friction) { if(fixture) { fixture->SetFriction(friction); } } void PhysicsScreenEntity::setDensity(Number density) { if(fixture) { fixture->SetDensity(density); } } Number PhysicsScreenEntity::getLinearDamping() { return body->GetLinearDamping(); } Number PhysicsScreenEntity::getAngularDamping() { return body->GetAngularDamping(); } Number PhysicsScreenEntity::getFriction() { return fixture->GetFriction(); } Number PhysicsScreenEntity::getDensity() { return fixture->GetDensity(); } void PhysicsScreenEntity::applyImpulse(Number fx, Number fy) { body->SetAwake(true); b2Vec2 f = b2Vec2(fx,fy); b2Vec2 p = body->GetWorldPoint(b2Vec2(0.0f, 0.0f)); body->ApplyLinearImpulse(f, p); } void PhysicsScreenEntity::setTransform(Vector2 pos, Number angle) { body->SetTransform(b2Vec2(pos.x/worldScale, pos.y/worldScale), angle*(PI/180.0f)); screenEntity->setPosition(pos); } void PhysicsScreenEntity::Update() { if(collisionOnly) { Matrix4 matrix = screenEntity->getConcatenatedMatrix(); b2Vec2 newPos; Number newRotation; Vector3 pos = matrix.getPosition(); newPos.x = pos.x/worldScale; newPos.y = pos.y/worldScale; Number rx,ry,rz; matrix.getEulerAngles(&rx, &ry, &rz); newRotation = rz; body->SetAwake(true); body->SetTransform(newPos, newRotation * TORADIANS); } else { b2Vec2 position = body->GetPosition(); Number angle = body->GetAngle(); screenEntity->setRotation(angle*(180.0f/PI)); screenEntity->setPosition(position.x*worldScale, position.y*worldScale); screenEntity->rebuildTransformMatrix(); } } b2Fixture* PhysicsScreenEntity::getFixture(unsigned short index) { if(fixture) { short i = 0; for (b2Fixture* f = body->GetFixtureList(); f; f = f->GetNext()) { if (i = index) { fixture = f; return fixture; } else {i++;} } Logger::log("That fixture index does not exist\n"); return fixture = NULL; } Logger::log("Fixturelist is for mesh only\n"); return fixture = NULL; } b2Fixture* PhysicsScreenEntity::getFixture() { return fixture; } // I believe that at runtime you are not supposed to edit Shapes; However you still can // by getting a fixture(above) and then adding "->GetShape()" on the end to get the fixtures shape PhysicsScreenEntity::~PhysicsScreenEntity() { if(body) body->GetWorld()->DestroyBody(body); // DestroyBody deletes fixtures and shapes automaticaly according to box2d documentation }<commit_msg>Fixed collision only entity not setting rotation correctly<commit_after>/* Copyright (C) 2011 by Ivan Safrin 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. */ #define PI 3.14159265 #include "PolyPhysicsScreenEntity.h" #include "PolyLogger.h" #include "PolyMesh.h" #include "PolyPolygon.h" #include "PolyScreenEntity.h" #include "PolyScreenMesh.h" using namespace Polycode; PhysicsScreenEntity::PhysicsScreenEntity(ScreenEntity *entity, b2World *world, Number worldScale, int entType, bool isStatic, Number friction, Number density, Number restitution, bool isSensor, bool fixedRotation, int groupIndex) { screenEntity = entity; Vector3 entityScale = entity->getCompoundScale(); Matrix4 compoundMatrix = screenEntity->getConcatenatedMatrix(); entity->ignoreParentMatrix = true; entity->scale = entityScale; this->worldScale = worldScale; collisionOnly = false; // Create body definition--------------------------------------- b2BodyDef bodyDef; bodyDef.position.Set(compoundMatrix.getPosition().x/worldScale, compoundMatrix.getPosition().y/worldScale); bodyDef.angle = screenEntity->getRotation()*(PI/180.0f); bodyDef.bullet = isSensor; bodyDef.fixedRotation = fixedRotation; if(isStatic) bodyDef.type = b2_staticBody; else bodyDef.type = b2_dynamicBody; // Create the body body = world->CreateBody(&bodyDef); body->SetUserData(this); // Create fixture definition--------------------------------------------- b2FixtureDef fDef; fDef.friction = friction; fDef.restitution = restitution; fDef.density = density; fDef.isSensor = isSensor; fDef.filter.groupIndex = groupIndex; // Create Shape definition (Circle/Rectangle/Polygon)--------------------------- switch(entType) { case ENTITY_CIRCLE: { b2CircleShape Shape; fDef.shape = &Shape; // Set the shape Shape.m_radius = screenEntity->getWidth()/(worldScale*2.0f); // Create the fixture fixture = body->CreateFixture(&fDef); break; } case ENTITY_RECT: { b2PolygonShape Shape; fDef.shape = &Shape; // Set the shape Shape.SetAsBox(screenEntity->getWidth()/(worldScale*2.0f) * entityScale.x, screenEntity->getHeight()/(worldScale*2.0f) * entityScale.y); // Create the fixture fixture = body->CreateFixture(&fDef); break; } case ENTITY_EDGE: { b2PolygonShape Shape; Shape.SetAsEdge(b2Vec2(-screenEntity->getWidth()/(worldScale*2.0f),-screenEntity->getHeight()/(2.0*worldScale)), b2Vec2(screenEntity->getWidth()/(worldScale*2.0f),-screenEntity->getHeight()/(2.0*worldScale))); fDef.shape = &Shape; fixture = body->CreateFixture(&fDef); break; } break; case ENTITY_MESH: { b2PolygonShape Shape; fDef.shape = &Shape; ScreenMesh* screenMesh = dynamic_cast<ScreenMesh*>(entity); if(screenMesh) { for(short i=0, polycount=screenMesh->getMesh()->getPolygonCount(); i < polycount; i++) { Polygon* poly = screenMesh->getMesh()->getPolygon(i); unsigned short vertexcount = poly->getVertexCount(); if (vertexcount >= 3 && vertexcount <= 8) { b2Vec2* vertices = new b2Vec2[vertexcount]; for(short index=0; index < vertexcount; index++) { vertices[index].x = poly->getVertex(index)->x/worldScale; vertices[index].y = poly->getVertex(index)->y/worldScale; } // Set the shape Shape.Set(vertices, vertexcount); // Create the fixture fixture = body->CreateFixture(&fDef); delete []vertices; } else { Logger::log("Between 3 and 8 vertices allowed per polygon\n"); } } } else { Logger::log("Tried to make a mesh collision object from a non-mesh\n"); } } } } void PhysicsScreenEntity::applyTorque(Number torque) { body->ApplyTorque(torque); } void PhysicsScreenEntity::applyForce(Vector2 force){ body->SetAwake(true); body->ApplyForce(b2Vec2(force.x,force.y), b2Vec2(body->GetPosition().x,body->GetPosition().y)); } ScreenEntity *PhysicsScreenEntity::getScreenEntity() { return screenEntity; } void PhysicsScreenEntity::setVelocity(Number fx, Number fy) { body->SetAwake(true); b2Vec2 f = body->GetLinearVelocity(); if(fx != 0) f.x = fx; if(fy != 0) f.y = fy; body->SetLinearVelocity(f); } void PhysicsScreenEntity::setVelocityX( Number fx) { body->SetAwake(true); b2Vec2 f = body->GetLinearVelocity(); f.x = fx; body->SetLinearVelocity(f); } void PhysicsScreenEntity::setVelocityY(Number fy) { body->SetAwake(true); b2Vec2 f = body->GetLinearVelocity(); f.y = fy; body->SetLinearVelocity(f); } void PhysicsScreenEntity::setCollisionCategory(int categoryBits) { b2Filter filter=fixture->GetFilterData(); filter.categoryBits = categoryBits; fixture->SetFilterData(filter); } void PhysicsScreenEntity::setCollisionMask(int maskBits) { b2Filter filter=fixture->GetFilterData(); filter.maskBits = maskBits; fixture->SetFilterData(filter); } void PhysicsScreenEntity::setCollisionGroupIndex(int group) { b2Filter filter=fixture->GetFilterData(); filter.groupIndex = group; fixture->SetFilterData(filter); } void PhysicsScreenEntity::setLinearDamping(Number damping) { body->SetLinearDamping(damping); } void PhysicsScreenEntity::setAngularDamping(Number damping) { body->SetAngularDamping(damping); } void PhysicsScreenEntity::setFriction(Number friction) { if(fixture) { fixture->SetFriction(friction); } } void PhysicsScreenEntity::setDensity(Number density) { if(fixture) { fixture->SetDensity(density); } } Number PhysicsScreenEntity::getLinearDamping() { return body->GetLinearDamping(); } Number PhysicsScreenEntity::getAngularDamping() { return body->GetAngularDamping(); } Number PhysicsScreenEntity::getFriction() { return fixture->GetFriction(); } Number PhysicsScreenEntity::getDensity() { return fixture->GetDensity(); } void PhysicsScreenEntity::applyImpulse(Number fx, Number fy) { body->SetAwake(true); b2Vec2 f = b2Vec2(fx,fy); b2Vec2 p = body->GetWorldPoint(b2Vec2(0.0f, 0.0f)); body->ApplyLinearImpulse(f, p); } void PhysicsScreenEntity::setTransform(Vector2 pos, Number angle) { body->SetTransform(b2Vec2(pos.x/worldScale, pos.y/worldScale), angle*(PI/180.0f)); screenEntity->setPosition(pos); } void PhysicsScreenEntity::Update() { if(collisionOnly) { b2Vec2 newPos; newPos.x = screenEntity->position.x/worldScale;; newPos.y = screenEntity->position.y/worldScale;; body->SetAwake(true); body->SetTransform(newPos, screenEntity->rotation.roll * TORADIANS); } else { b2Vec2 position = body->GetPosition(); Number angle = body->GetAngle(); screenEntity->setRotation(angle*(180.0f/PI)); screenEntity->setPosition(position.x*worldScale, position.y*worldScale); screenEntity->rebuildTransformMatrix(); } } b2Fixture* PhysicsScreenEntity::getFixture(unsigned short index) { if(fixture) { short i = 0; for (b2Fixture* f = body->GetFixtureList(); f; f = f->GetNext()) { if (i = index) { fixture = f; return fixture; } else {i++;} } Logger::log("That fixture index does not exist\n"); return fixture = NULL; } Logger::log("Fixturelist is for mesh only\n"); return fixture = NULL; } b2Fixture* PhysicsScreenEntity::getFixture() { return fixture; } // I believe that at runtime you are not supposed to edit Shapes; However you still can // by getting a fixture(above) and then adding "->GetShape()" on the end to get the fixtures shape PhysicsScreenEntity::~PhysicsScreenEntity() { if(body) body->GetWorld()->DestroyBody(body); // DestroyBody deletes fixtures and shapes automaticaly according to box2d documentation }<|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2008-02-25 17:27:17 +0100 (Mo, 25 Feb 2008) $ Version: $Revision: 7837 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ //Poco headers #include "Poco/Path.h" //mitk headers #include "mitkNavigationToolWriter.h" #include "mitkCommon.h" #include "mitkTestingMacros.h" #include "mitkStandardFileLocations.h" #include "mitkNavigationTool.h" #include "mitkSTLFileReader.h" #include "mitkBaseData.h" #include "mitkDataTreeNode.h" #include "mitkSurface.h" #include "mitkStandaloneDataStorage.h" #include "mitkDataStorage.h" #include "mitkNavigationToolReader.h" #include <sstream> class mitkNavigationToolReaderAndWriterTestClass { private: static mitk::Surface::Pointer testSurface; public: static void TestInstantiation() { // let's create an object of our class mitk::NavigationToolWriter::Pointer myWriter = mitk::NavigationToolWriter::New(); MITK_TEST_CONDITION_REQUIRED(myWriter.IsNotNull(),"Testing instantiation") } static void TestWrite() { //create a NavigationTool which we can write on the harddisc std::string toolFileName = mitk::StandardFileLocations::GetInstance()->FindFile("ClaronTool", "Modules/IGT/Testing/Data"); MITK_TEST_CONDITION(toolFileName.empty() == false, "Check if tool calibration file exists"); mitk::NavigationTool::Pointer myNavigationTool = mitk::NavigationTool::New(); myNavigationTool->SetCalibrationFile(toolFileName); mitk::DataTreeNode::Pointer myNode = mitk::DataTreeNode::New(); myNode->SetName("ClaronTool"); //load an stl File mitk::STLFileReader::Pointer stlReader = mitk::STLFileReader::New(); try { stlReader->SetFileName( mitk::StandardFileLocations::GetInstance()->FindFile("ClaronTool.stl", "Testing/Data/").c_str() ); stlReader->Update(); } catch (...) { MITK_TEST_FAILED_MSG(<<"Cannot read stl file."); } if ( stlReader->GetOutput() == NULL ) { MITK_TEST_FAILED_MSG(<<"Cannot read stl file."); } else { testSurface = stlReader->GetOutput(); myNode->SetData(testSurface); } myNavigationTool->SetDataTreeNode(myNode); myNavigationTool->SetIdentifier("ClaronTool#1"); myNavigationTool->SetSerialNumber("0815"); myNavigationTool->SetTrackingDeviceType(mitk::ClaronMicron); myNavigationTool->SetType(mitk::NavigationTool::Fiducial); //now create a writer and write it to the harddisc mitk::NavigationToolWriter::Pointer myWriter = mitk::NavigationToolWriter::New(); std::string filename = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+".."+Poco::Path::separator()+"TestTool.tool"; MITK_TEST_OUTPUT(<<"---- Testing navigation tool writer ----"); bool test = myWriter->DoWrite(filename,myNavigationTool); MITK_TEST_CONDITION_REQUIRED(test,"OK"); } static void TestRead() { mitk::DataStorage::Pointer testStorage = mitk::StandaloneDataStorage::New(); mitk::NavigationToolReader::Pointer myReader = mitk::NavigationToolReader::New(testStorage); mitk::NavigationTool::Pointer readTool = myReader->DoRead(mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+".."+Poco::Path::separator()+"TestTool.tool"); MITK_TEST_OUTPUT(<<"---- Testing navigation tool reader ----"); MITK_TEST_CONDITION_REQUIRED(readTool->GetDataTreeNode() == testStorage->GetNamedNode(readTool->GetDataTreeNode()->GetName()),"Test if tool was added to storage..."); MITK_TEST_CONDITION_REQUIRED(readTool->GetDataTreeNode()->GetData()==testSurface,"Test if surface was restored correctly ..."); //MITK_TEST_CONDITION_REQUIRED(); } static void CleanUp() { std::remove((mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+".."+Poco::Path::separator()+"TestTool.tool").c_str()); } }; mitk::Surface::Pointer mitkNavigationToolReaderAndWriterTestClass::testSurface = NULL; /** This function is testing the TrackingVolume class. */ int mitkNavigationToolReaderAndWriterTest(int /* argc */, char* /*argv*/[]) { MITK_TEST_BEGIN("NavigationToolWriter") mitkNavigationToolReaderAndWriterTestClass::TestInstantiation(); mitkNavigationToolReaderAndWriterTestClass::TestWrite(); //mitkNavigationToolReaderAndWriterTestClass::TestRead(); mitkNavigationToolReaderAndWriterTestClass::CleanUp(); MITK_TEST_END() } <commit_msg>COMP: commented out some non-compiling code for while.<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2008-02-25 17:27:17 +0100 (Mo, 25 Feb 2008) $ Version: $Revision: 7837 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ //Poco headers #include "Poco/Path.h" //mitk headers #include "mitkNavigationToolWriter.h" #include "mitkCommon.h" #include "mitkTestingMacros.h" #include "mitkStandardFileLocations.h" #include "mitkNavigationTool.h" #include "mitkSTLFileReader.h" #include "mitkBaseData.h" #include "mitkDataTreeNode.h" #include "mitkSurface.h" #include "mitkStandaloneDataStorage.h" #include "mitkDataStorage.h" #include "mitkNavigationToolReader.h" #include <sstream> class mitkNavigationToolReaderAndWriterTestClass { private: static mitk::Surface::Pointer testSurface; public: static void TestInstantiation() { // let's create an object of our class mitk::NavigationToolWriter::Pointer myWriter = mitk::NavigationToolWriter::New(); MITK_TEST_CONDITION_REQUIRED(myWriter.IsNotNull(),"Testing instantiation") } static void TestWrite() { //create a NavigationTool which we can write on the harddisc std::string toolFileName = mitk::StandardFileLocations::GetInstance()->FindFile("ClaronTool", "Modules/IGT/Testing/Data"); MITK_TEST_CONDITION(toolFileName.empty() == false, "Check if tool calibration file exists"); mitk::NavigationTool::Pointer myNavigationTool = mitk::NavigationTool::New(); myNavigationTool->SetCalibrationFile(toolFileName); mitk::DataTreeNode::Pointer myNode = mitk::DataTreeNode::New(); myNode->SetName("ClaronTool"); //load an stl File mitk::STLFileReader::Pointer stlReader = mitk::STLFileReader::New(); try { stlReader->SetFileName( mitk::StandardFileLocations::GetInstance()->FindFile("ClaronTool.stl", "Testing/Data/").c_str() ); stlReader->Update(); } catch (...) { MITK_TEST_FAILED_MSG(<<"Cannot read stl file."); } if ( stlReader->GetOutput() == NULL ) { MITK_TEST_FAILED_MSG(<<"Cannot read stl file."); } else { testSurface = stlReader->GetOutput(); myNode->SetData(testSurface); } myNavigationTool->SetDataTreeNode(myNode); myNavigationTool->SetIdentifier("ClaronTool#1"); myNavigationTool->SetSerialNumber("0815"); myNavigationTool->SetTrackingDeviceType(mitk::ClaronMicron); myNavigationTool->SetType(mitk::NavigationTool::Fiducial); //now create a writer and write it to the harddisc mitk::NavigationToolWriter::Pointer myWriter = mitk::NavigationToolWriter::New(); std::string filename = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+".."+Poco::Path::separator()+"TestTool.tool"; MITK_TEST_OUTPUT(<<"---- Testing navigation tool writer ----"); bool test = myWriter->DoWrite(filename,myNavigationTool); MITK_TEST_CONDITION_REQUIRED(test,"OK"); } static void TestRead() { /* mitk::DataStorage::Pointer testStorage = mitk::StandaloneDataStorage::New(); TODO: DIESE STELLE UNTER LINUX ZUM LAUFEN BRINGEN mitk::NavigationToolReader::Pointer myReader = mitk::NavigationToolReader::New(testStorage); mitk::NavigationTool::Pointer readTool = myReader->DoRead(mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+".."+Poco::Path::separator()+"TestTool.tool"); MITK_TEST_OUTPUT(<<"---- Testing navigation tool reader ----"); MITK_TEST_CONDITION_REQUIRED(readTool->GetDataTreeNode() == testStorage->GetNamedNode(readTool->GetDataTreeNode()->GetName()),"Test if tool was added to storage..."); MITK_TEST_CONDITION_REQUIRED(readTool->GetDataTreeNode()->GetData()==testSurface,"Test if surface was restored correctly ..."); */ //MITK_TEST_CONDITION_REQUIRED(); } static void CleanUp() { std::remove((mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+".."+Poco::Path::separator()+"TestTool.tool").c_str()); } }; mitk::Surface::Pointer mitkNavigationToolReaderAndWriterTestClass::testSurface = NULL; /** This function is testing the TrackingVolume class. */ int mitkNavigationToolReaderAndWriterTest(int /* argc */, char* /*argv*/[]) { MITK_TEST_BEGIN("NavigationToolWriter") mitkNavigationToolReaderAndWriterTestClass::TestInstantiation(); mitkNavigationToolReaderAndWriterTestClass::TestWrite(); //mitkNavigationToolReaderAndWriterTestClass::TestRead(); mitkNavigationToolReaderAndWriterTestClass::CleanUp(); MITK_TEST_END() } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkToFDistanceImageToSurfaceFilter.h> #include <mitkInstantiateAccessFunctions.h> #include <mitkSurface.h> #include "mitkImageReadAccessor.h" #include <itkImage.h> #include <vtkCellArray.h> #include <vtkPoints.h> #include <vtkPolyData.h> #include <vtkPointData.h> #include <vtkFloatArray.h> #include <vtkSmartPointer.h> #include <vtkIdList.h> #include <math.h> #include <vtkMath.h> mitk::ToFDistanceImageToSurfaceFilter::ToFDistanceImageToSurfaceFilter() : m_IplScalarImage(NULL), m_CameraIntrinsics(), m_TextureImageWidth(0), m_TextureImageHeight(0), m_InterPixelDistance(), m_TextureIndex(0), m_GenerateTriangularMesh(true), m_TriangulationThreshold(0.0) { m_InterPixelDistance.Fill(0.045); m_CameraIntrinsics = mitk::CameraIntrinsics::New(); m_CameraIntrinsics->SetFocalLength(273.138946533,273.485900879); m_CameraIntrinsics->SetPrincipalPoint(107.867935181,98.3807373047); m_CameraIntrinsics->SetDistorsionCoeffs(-0.486690014601f,0.553943634033f,0.00222016777843f,-0.00300851115026f); m_ReconstructionMode = WithInterPixelDistance; } mitk::ToFDistanceImageToSurfaceFilter::~ToFDistanceImageToSurfaceFilter() { } void mitk::ToFDistanceImageToSurfaceFilter::SetInput( Image* distanceImage, mitk::CameraIntrinsics::Pointer cameraIntrinsics ) { this->SetCameraIntrinsics(cameraIntrinsics); this->SetInput(0,distanceImage); } void mitk::ToFDistanceImageToSurfaceFilter::SetInput( unsigned int idx, Image* distanceImage, mitk::CameraIntrinsics::Pointer cameraIntrinsics ) { this->SetCameraIntrinsics(cameraIntrinsics); this->SetInput(idx,distanceImage); } void mitk::ToFDistanceImageToSurfaceFilter::SetInput( mitk::Image* distanceImage ) { this->SetInput(0,distanceImage); } void mitk::ToFDistanceImageToSurfaceFilter::SetInput( unsigned int idx, mitk::Image* distanceImage ) { if ((distanceImage == NULL) && (idx == this->GetNumberOfInputs() - 1)) // if the last input is set to NULL, reduce the number of inputs by one this->SetNumberOfInputs(this->GetNumberOfInputs() - 1); else this->ProcessObject::SetNthInput(idx, distanceImage); // Process object is not const-correct so the const_cast is required here this->CreateOutputsForAllInputs(); } mitk::Image* mitk::ToFDistanceImageToSurfaceFilter::GetInput() { return this->GetInput(0); } mitk::Image* mitk::ToFDistanceImageToSurfaceFilter::GetInput( unsigned int idx ) { if (this->GetNumberOfInputs() < 1) { mitkThrow() << "No input given for ToFDistanceImageToSurfaceFilter"; } return static_cast< mitk::Image*>(this->ProcessObject::GetInput(idx)); } void mitk::ToFDistanceImageToSurfaceFilter::GenerateData() { mitk::Surface::Pointer output = this->GetOutput(); assert(output); mitk::Image::Pointer input = this->GetInput(); assert(input); // mesh points int xDimension = input->GetDimension(0); int yDimension = input->GetDimension(1); unsigned int size = xDimension*yDimension; //size of the image-array std::vector<bool> isPointValid; isPointValid.resize(size); vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); points->SetDataTypeToDouble(); vtkSmartPointer<vtkCellArray> polys = vtkSmartPointer<vtkCellArray>::New(); vtkSmartPointer<vtkCellArray> vertices = vtkSmartPointer<vtkCellArray>::New(); vtkSmartPointer<vtkFloatArray> scalarArray = vtkSmartPointer<vtkFloatArray>::New(); vtkSmartPointer<vtkFloatArray> textureCoords = vtkSmartPointer<vtkFloatArray>::New(); textureCoords->SetNumberOfComponents(2); textureCoords->Allocate(size); //Make a vtkIdList to save the ID's of the polyData corresponding to the image //pixel ID's. See below for more documentation. m_VertexIdList = vtkSmartPointer<vtkIdList>::New(); //Allocate the object once else it would automatically allocate new memory //for every vertex and perform a copy which is expensive. m_VertexIdList->Allocate(size); m_VertexIdList->SetNumberOfIds(size); for(unsigned int i = 0; i < size; ++i) { m_VertexIdList->SetId(i, 0); } float* scalarFloatData = NULL; if (this->m_IplScalarImage) // if scalar image is defined use it for texturing { scalarFloatData = (float*)this->m_IplScalarImage->imageData; } else if (this->GetInput(m_TextureIndex)) // otherwise use intensity image (input(2)) { ImageReadAccessor inputAcc(this->GetInput(m_TextureIndex)); scalarFloatData = (float*)inputAcc.GetData(); } ImageReadAccessor inputAcc(input, input->GetSliceData(0,0,0)); float* inputFloatData = (float*)inputAcc.GetData(); //calculate world coordinates mitk::ToFProcessingCommon::ToFPoint2D focalLengthInPixelUnits; mitk::ToFProcessingCommon::ToFScalarType focalLengthInMm; if((m_ReconstructionMode == WithOutInterPixelDistance) || (m_ReconstructionMode == Kinect)) { focalLengthInPixelUnits[0] = m_CameraIntrinsics->GetFocalLengthX(); focalLengthInPixelUnits[1] = m_CameraIntrinsics->GetFocalLengthY(); } else if( m_ReconstructionMode == WithInterPixelDistance) { //convert focallength from pixel to mm focalLengthInMm = (m_CameraIntrinsics->GetFocalLengthX()*m_InterPixelDistance[0]+m_CameraIntrinsics->GetFocalLengthY()*m_InterPixelDistance[1])/2.0; } mitk::ToFProcessingCommon::ToFPoint2D principalPoint; principalPoint[0] = m_CameraIntrinsics->GetPrincipalPointX(); principalPoint[1] = m_CameraIntrinsics->GetPrincipalPointY(); mitk::Point3D origin = input->GetGeometry()->GetOrigin(); for (int j=0; j<yDimension; j++) { for (int i=0; i<xDimension; i++) { unsigned int pixelID = i+j*xDimension; mitk::ToFProcessingCommon::ToFScalarType distance = (double)inputFloatData[pixelID]; mitk::ToFProcessingCommon::ToFPoint3D cartesianCoordinates; switch (m_ReconstructionMode) { case WithOutInterPixelDistance: { cartesianCoordinates = mitk::ToFProcessingCommon::IndexToCartesianCoordinates(i+origin[0],j+origin[1],distance,focalLengthInPixelUnits,principalPoint); break; } case WithInterPixelDistance: { cartesianCoordinates = mitk::ToFProcessingCommon::IndexToCartesianCoordinatesWithInterpixdist(i+origin[0],j+origin[1],distance,focalLengthInMm,m_InterPixelDistance,principalPoint); break; } case Kinect: { cartesianCoordinates = mitk::ToFProcessingCommon::KinectIndexToCartesianCoordinates(i+origin[0],j+origin[1],distance,focalLengthInPixelUnits,principalPoint); break; } default: { MITK_ERROR << "Incorrect reconstruction mode!"; } } //Epsilon here, because we may have small float values like 0.00000001 which in fact represents 0. if (distance<=mitk::eps) { isPointValid[pixelID] = false; } else { isPointValid[pixelID] = true; //VTK would insert empty points into the polydata if we use //points->InsertPoint(pixelID, cartesianCoordinates.GetDataPointer()). //If we use points->InsertNextPoint(...) instead, the ID's do not //correspond to the image pixel ID's. Thus, we have to save them //in the vertexIdList. m_VertexIdList->SetId(pixelID, points->InsertNextPoint(cartesianCoordinates.GetDataPointer())); if (m_GenerateTriangularMesh) { if((i >= 1) && (j >= 1)) { //This little piece of art explains the ID's: // // P(x_1y_1)---P(xy_1) // | | // | | // | | // P(x_1y)-----P(xy) // //We can only start triangulation if we are at vertex (1,1), //because we need the other 3 vertices near this one. //To go one pixel line back in the image array, we have to //subtract 1x xDimension. vtkIdType xy = pixelID; vtkIdType x_1y = pixelID-1; vtkIdType xy_1 = pixelID-xDimension; vtkIdType x_1y_1 = xy_1-1; //Find the corresponding vertex ID's in the saved vertexIdList: vtkIdType xyV = m_VertexIdList->GetId(xy); vtkIdType x_1yV = m_VertexIdList->GetId(x_1y); vtkIdType xy_1V = m_VertexIdList->GetId(xy_1); vtkIdType x_1y_1V = m_VertexIdList->GetId(x_1y_1); if (isPointValid[xy]&&isPointValid[x_1y]&&isPointValid[x_1y_1]&&isPointValid[xy_1]) // check if points of cell are valid { double pointXY[3], pointX_1Y[3], pointXY_1[3], pointX_1Y_1[3]; points->GetPoint(xyV, pointXY); points->GetPoint(x_1yV, pointX_1Y); points->GetPoint(xy_1V, pointXY_1); points->GetPoint(x_1y_1V, pointX_1Y_1); if( (mitk::Equal(m_TriangulationThreshold, 0.0)) || ((vtkMath::Distance2BetweenPoints(pointXY, pointX_1Y) <= m_TriangulationThreshold) && (vtkMath::Distance2BetweenPoints(pointXY, pointXY_1) <= m_TriangulationThreshold) && (vtkMath::Distance2BetweenPoints(pointX_1Y, pointX_1Y_1) <= m_TriangulationThreshold) && (vtkMath::Distance2BetweenPoints(pointXY_1, pointX_1Y_1) <= m_TriangulationThreshold))) { polys->InsertNextCell(3); polys->InsertCellPoint(x_1yV); polys->InsertCellPoint(xyV); polys->InsertCellPoint(x_1y_1V); polys->InsertNextCell(3); polys->InsertCellPoint(x_1y_1V); polys->InsertCellPoint(xyV); polys->InsertCellPoint(xy_1V); } else { //We dont want triangulation, but we want to keep the vertex vertices->InsertNextCell(1); vertices->InsertCellPoint(xyV); } } //Scalar values are necessary for mapping colors/texture onto the surface if (scalarFloatData) { scalarArray->InsertTuple1(m_VertexIdList->GetId(pixelID), scalarFloatData[pixelID]); } //These Texture Coordinates will map color pixel and vertices 1:1 (e.g. for Kinect). float xNorm = (((float)i)/xDimension);// correct video texture scale for kinect float yNorm = ((float)j)/yDimension; //don't flip. we don't need to flip. textureCoords->InsertTuple2(m_VertexIdList->GetId(pixelID), xNorm, yNorm); } } else { //We dont want triangulation, we only want vertices vertices->InsertNextCell(1); vertices->InsertCellPoint(m_VertexIdList->GetId(pixelID)); } } } } vtkSmartPointer<vtkPolyData> mesh = vtkSmartPointer<vtkPolyData>::New(); mesh->SetPoints(points); mesh->SetPolys(polys); mesh->SetVerts(vertices); //Pass the scalars to the polydata (if they were set). if (scalarArray->GetNumberOfTuples()>0) { mesh->GetPointData()->SetScalars(scalarArray); } //Pass the TextureCoords to the polydata anyway (to save them). mesh->GetPointData()->SetTCoords(textureCoords); output->SetVtkPolyData(mesh); } void mitk::ToFDistanceImageToSurfaceFilter::CreateOutputsForAllInputs() { this->SetNumberOfOutputs(this->GetNumberOfInputs()); // create outputs for all inputs for (unsigned int idx = 0; idx < this->GetNumberOfOutputs(); ++idx) if (this->GetOutput(idx) == NULL) { DataObjectPointer newOutput = this->MakeOutput(idx); this->SetNthOutput(idx, newOutput); } this->Modified(); } void mitk::ToFDistanceImageToSurfaceFilter::GenerateOutputInformation() { this->GetOutput(); itkDebugMacro(<<"GenerateOutputInformation()"); } void mitk::ToFDistanceImageToSurfaceFilter::SetScalarImage(IplImage* iplScalarImage) { this->m_IplScalarImage = iplScalarImage; this->Modified(); } IplImage* mitk::ToFDistanceImageToSurfaceFilter::GetScalarImage() { return this->m_IplScalarImage; } void mitk::ToFDistanceImageToSurfaceFilter::SetTextureImageWidth(int width) { this->m_TextureImageWidth = width; } void mitk::ToFDistanceImageToSurfaceFilter::SetTextureImageHeight(int height) { this->m_TextureImageHeight = height; } void mitk::ToFDistanceImageToSurfaceFilter::SetTriangulationThreshold(double triangulationThreshold) { //vtkMath::Distance2BetweenPoints returns the squared distance between two points and //hence we square m_TriangulationThreshold in order to save run-time. this->m_TriangulationThreshold = triangulationThreshold*triangulationThreshold; } <commit_msg>In TofDistanceImageToSurfaceFilter float* were used which created subtle errors since they pointed to double values.<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkToFDistanceImageToSurfaceFilter.h> #include <mitkInstantiateAccessFunctions.h> #include <mitkSurface.h> #include "mitkImageReadAccessor.h" #include <itkImage.h> #include <vtkCellArray.h> #include <vtkPoints.h> #include <vtkPolyData.h> #include <vtkPointData.h> #include <vtkFloatArray.h> #include <vtkSmartPointer.h> #include <vtkIdList.h> #include <math.h> #include <vtkMath.h> mitk::ToFDistanceImageToSurfaceFilter::ToFDistanceImageToSurfaceFilter() : m_IplScalarImage(NULL), m_CameraIntrinsics(), m_TextureImageWidth(0), m_TextureImageHeight(0), m_InterPixelDistance(), m_TextureIndex(0), m_GenerateTriangularMesh(true), m_TriangulationThreshold(0.0) { m_InterPixelDistance.Fill(0.045); m_CameraIntrinsics = mitk::CameraIntrinsics::New(); m_CameraIntrinsics->SetFocalLength(273.138946533,273.485900879); m_CameraIntrinsics->SetPrincipalPoint(107.867935181,98.3807373047); m_CameraIntrinsics->SetDistorsionCoeffs(-0.486690014601f,0.553943634033f,0.00222016777843f,-0.00300851115026f); m_ReconstructionMode = WithInterPixelDistance; } mitk::ToFDistanceImageToSurfaceFilter::~ToFDistanceImageToSurfaceFilter() { } void mitk::ToFDistanceImageToSurfaceFilter::SetInput( Image* distanceImage, mitk::CameraIntrinsics::Pointer cameraIntrinsics ) { this->SetCameraIntrinsics(cameraIntrinsics); this->SetInput(0,distanceImage); } void mitk::ToFDistanceImageToSurfaceFilter::SetInput( unsigned int idx, Image* distanceImage, mitk::CameraIntrinsics::Pointer cameraIntrinsics ) { this->SetCameraIntrinsics(cameraIntrinsics); this->SetInput(idx,distanceImage); } void mitk::ToFDistanceImageToSurfaceFilter::SetInput( mitk::Image* distanceImage ) { this->SetInput(0,distanceImage); } void mitk::ToFDistanceImageToSurfaceFilter::SetInput( unsigned int idx, mitk::Image* distanceImage ) { if ((distanceImage == NULL) && (idx == this->GetNumberOfInputs() - 1)) // if the last input is set to NULL, reduce the number of inputs by one this->SetNumberOfInputs(this->GetNumberOfInputs() - 1); else this->ProcessObject::SetNthInput(idx, distanceImage); // Process object is not const-correct so the const_cast is required here this->CreateOutputsForAllInputs(); } mitk::Image* mitk::ToFDistanceImageToSurfaceFilter::GetInput() { return this->GetInput(0); } mitk::Image* mitk::ToFDistanceImageToSurfaceFilter::GetInput( unsigned int idx ) { if (this->GetNumberOfInputs() < 1) { mitkThrow() << "No input given for ToFDistanceImageToSurfaceFilter"; } return static_cast< mitk::Image*>(this->ProcessObject::GetInput(idx)); } void mitk::ToFDistanceImageToSurfaceFilter::GenerateData() { mitk::Surface::Pointer output = this->GetOutput(); assert(output); mitk::Image::Pointer input = this->GetInput(); assert(input); // mesh points int xDimension = input->GetDimension(0); int yDimension = input->GetDimension(1); unsigned int size = xDimension*yDimension; //size of the image-array std::vector<bool> isPointValid; isPointValid.resize(size); vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); points->SetDataTypeToDouble(); vtkSmartPointer<vtkCellArray> polys = vtkSmartPointer<vtkCellArray>::New(); vtkSmartPointer<vtkCellArray> vertices = vtkSmartPointer<vtkCellArray>::New(); vtkSmartPointer<vtkFloatArray> scalarArray = vtkSmartPointer<vtkFloatArray>::New(); vtkSmartPointer<vtkFloatArray> textureCoords = vtkSmartPointer<vtkFloatArray>::New(); textureCoords->SetNumberOfComponents(2); textureCoords->Allocate(size); //Make a vtkIdList to save the ID's of the polyData corresponding to the image //pixel ID's. See below for more documentation. m_VertexIdList = vtkSmartPointer<vtkIdList>::New(); //Allocate the object once else it would automatically allocate new memory //for every vertex and perform a copy which is expensive. m_VertexIdList->Allocate(size); m_VertexIdList->SetNumberOfIds(size); for(unsigned int i = 0; i < size; ++i) { m_VertexIdList->SetId(i, 0); } ScalarType* scalarFloatData = NULL; if (this->m_IplScalarImage) // if scalar image is defined use it for texturing { scalarFloatData = (ScalarType*)this->m_IplScalarImage->imageData; } else if (this->GetInput(m_TextureIndex)) // otherwise use intensity image (input(2)) { ImageReadAccessor inputAcc(this->GetInput(m_TextureIndex)); scalarFloatData = (ScalarType*)inputAcc.GetData(); } ImageReadAccessor inputAcc(input, input->GetSliceData(0,0,0)); ScalarType* inputFloatData = (ScalarType*)inputAcc.GetData(); //calculate world coordinates mitk::ToFProcessingCommon::ToFPoint2D focalLengthInPixelUnits; mitk::ToFProcessingCommon::ToFScalarType focalLengthInMm; if((m_ReconstructionMode == WithOutInterPixelDistance) || (m_ReconstructionMode == Kinect)) { focalLengthInPixelUnits[0] = m_CameraIntrinsics->GetFocalLengthX(); focalLengthInPixelUnits[1] = m_CameraIntrinsics->GetFocalLengthY(); } else if( m_ReconstructionMode == WithInterPixelDistance) { //convert focallength from pixel to mm focalLengthInMm = (m_CameraIntrinsics->GetFocalLengthX()*m_InterPixelDistance[0]+m_CameraIntrinsics->GetFocalLengthY()*m_InterPixelDistance[1])/2.0; } mitk::ToFProcessingCommon::ToFPoint2D principalPoint; principalPoint[0] = m_CameraIntrinsics->GetPrincipalPointX(); principalPoint[1] = m_CameraIntrinsics->GetPrincipalPointY(); mitk::Point3D origin = input->GetGeometry()->GetOrigin(); for (int j=0; j<yDimension; j++) { for (int i=0; i<xDimension; i++) { unsigned int pixelID = i+j*xDimension; mitk::ToFProcessingCommon::ToFScalarType distance = (double)inputFloatData[pixelID]; mitk::ToFProcessingCommon::ToFPoint3D cartesianCoordinates; switch (m_ReconstructionMode) { case WithOutInterPixelDistance: { cartesianCoordinates = mitk::ToFProcessingCommon::IndexToCartesianCoordinates(i+origin[0],j+origin[1],distance,focalLengthInPixelUnits,principalPoint); break; } case WithInterPixelDistance: { cartesianCoordinates = mitk::ToFProcessingCommon::IndexToCartesianCoordinatesWithInterpixdist(i+origin[0],j+origin[1],distance,focalLengthInMm,m_InterPixelDistance,principalPoint); break; } case Kinect: { cartesianCoordinates = mitk::ToFProcessingCommon::KinectIndexToCartesianCoordinates(i+origin[0],j+origin[1],distance,focalLengthInPixelUnits,principalPoint); break; } default: { MITK_ERROR << "Incorrect reconstruction mode!"; } } //Epsilon here, because we may have small ScalarType values like 0.00000001 which in fact represents 0. if (distance<=mitk::eps) { isPointValid[pixelID] = false; } else { isPointValid[pixelID] = true; //VTK would insert empty points into the polydata if we use //points->InsertPoint(pixelID, cartesianCoordinates.GetDataPointer()). //If we use points->InsertNextPoint(...) instead, the ID's do not //correspond to the image pixel ID's. Thus, we have to save them //in the vertexIdList. m_VertexIdList->SetId(pixelID, points->InsertNextPoint(cartesianCoordinates.GetDataPointer())); if (m_GenerateTriangularMesh) { if((i >= 1) && (j >= 1)) { //This little piece of art explains the ID's: // // P(x_1y_1)---P(xy_1) // | | // | | // | | // P(x_1y)-----P(xy) // //We can only start triangulation if we are at vertex (1,1), //because we need the other 3 vertices near this one. //To go one pixel line back in the image array, we have to //subtract 1x xDimension. vtkIdType xy = pixelID; vtkIdType x_1y = pixelID-1; vtkIdType xy_1 = pixelID-xDimension; vtkIdType x_1y_1 = xy_1-1; //Find the corresponding vertex ID's in the saved vertexIdList: vtkIdType xyV = m_VertexIdList->GetId(xy); vtkIdType x_1yV = m_VertexIdList->GetId(x_1y); vtkIdType xy_1V = m_VertexIdList->GetId(xy_1); vtkIdType x_1y_1V = m_VertexIdList->GetId(x_1y_1); if (isPointValid[xy]&&isPointValid[x_1y]&&isPointValid[x_1y_1]&&isPointValid[xy_1]) // check if points of cell are valid { double pointXY[3], pointX_1Y[3], pointXY_1[3], pointX_1Y_1[3]; points->GetPoint(xyV, pointXY); points->GetPoint(x_1yV, pointX_1Y); points->GetPoint(xy_1V, pointXY_1); points->GetPoint(x_1y_1V, pointX_1Y_1); if( (mitk::Equal(m_TriangulationThreshold, 0.0)) || ((vtkMath::Distance2BetweenPoints(pointXY, pointX_1Y) <= m_TriangulationThreshold) && (vtkMath::Distance2BetweenPoints(pointXY, pointXY_1) <= m_TriangulationThreshold) && (vtkMath::Distance2BetweenPoints(pointX_1Y, pointX_1Y_1) <= m_TriangulationThreshold) && (vtkMath::Distance2BetweenPoints(pointXY_1, pointX_1Y_1) <= m_TriangulationThreshold))) { polys->InsertNextCell(3); polys->InsertCellPoint(x_1yV); polys->InsertCellPoint(xyV); polys->InsertCellPoint(x_1y_1V); polys->InsertNextCell(3); polys->InsertCellPoint(x_1y_1V); polys->InsertCellPoint(xyV); polys->InsertCellPoint(xy_1V); } else { //We dont want triangulation, but we want to keep the vertex vertices->InsertNextCell(1); vertices->InsertCellPoint(xyV); } } //Scalar values are necessary for mapping colors/texture onto the surface if (scalarFloatData) { scalarArray->InsertTuple1(m_VertexIdList->GetId(pixelID), scalarFloatData[pixelID]); } //These Texture Coordinates will map color pixel and vertices 1:1 (e.g. for Kinect). ScalarType xNorm = (((ScalarType)i)/xDimension);// correct video texture scale for kinect ScalarType yNorm = ((ScalarType)j)/yDimension; //don't flip. we don't need to flip. textureCoords->InsertTuple2(m_VertexIdList->GetId(pixelID), xNorm, yNorm); } } else { //We dont want triangulation, we only want vertices vertices->InsertNextCell(1); vertices->InsertCellPoint(m_VertexIdList->GetId(pixelID)); } } } } vtkSmartPointer<vtkPolyData> mesh = vtkSmartPointer<vtkPolyData>::New(); mesh->SetPoints(points); mesh->SetPolys(polys); mesh->SetVerts(vertices); //Pass the scalars to the polydata (if they were set). if (scalarArray->GetNumberOfTuples()>0) { mesh->GetPointData()->SetScalars(scalarArray); } //Pass the TextureCoords to the polydata anyway (to save them). mesh->GetPointData()->SetTCoords(textureCoords); output->SetVtkPolyData(mesh); } void mitk::ToFDistanceImageToSurfaceFilter::CreateOutputsForAllInputs() { this->SetNumberOfOutputs(this->GetNumberOfInputs()); // create outputs for all inputs for (unsigned int idx = 0; idx < this->GetNumberOfOutputs(); ++idx) if (this->GetOutput(idx) == NULL) { DataObjectPointer newOutput = this->MakeOutput(idx); this->SetNthOutput(idx, newOutput); } this->Modified(); } void mitk::ToFDistanceImageToSurfaceFilter::GenerateOutputInformation() { this->GetOutput(); itkDebugMacro(<<"GenerateOutputInformation()"); } void mitk::ToFDistanceImageToSurfaceFilter::SetScalarImage(IplImage* iplScalarImage) { this->m_IplScalarImage = iplScalarImage; this->Modified(); } IplImage* mitk::ToFDistanceImageToSurfaceFilter::GetScalarImage() { return this->m_IplScalarImage; } void mitk::ToFDistanceImageToSurfaceFilter::SetTextureImageWidth(int width) { this->m_TextureImageWidth = width; } void mitk::ToFDistanceImageToSurfaceFilter::SetTextureImageHeight(int height) { this->m_TextureImageHeight = height; } void mitk::ToFDistanceImageToSurfaceFilter::SetTriangulationThreshold(double triangulationThreshold) { //vtkMath::Distance2BetweenPoints returns the squared distance between two points and //hence we square m_TriangulationThreshold in order to save run-time. this->m_TriangulationThreshold = triangulationThreshold*triangulationThreshold; } <|endoftext|>
<commit_before>#include <Windows.h> #include <stdint.h> // Types indpendent de la plateforme // Pour bien comprendre la diffrence de fonctionnement des variables statiques en C en fonction du scope #define internal static // fonctions non visible depuis l'extrieur de ce fichier #define local_persist static // variable visibles juste dans le scope o elle dfinie #define global_variable static // variable visible dans tous le fichiers (globale) typedef unsigned char uint8; typedef uint8_t uint8; // comme un unsigned char, un 8 bits typedef int16_t uint16; typedef int32_t uint32; typedef int64_t uint64; // variable globale pour le moment, on grera autrement plus tard global_variable bool Running; global_variable BITMAPINFO BitmapInfo; global_variable void *BitmapMemory; global_variable int BitmapWidth; global_variable int BitmapHeight; global_variable int BytesPerPixel = 4; internal void RenderWeirdGradient(int XOffset, int YOffset) { int Width = BitmapWidth; int Height = BitmapHeight; int Pitch = Width * BytesPerPixel; // Pitch reprsente la taille d'une ligne en octets uint8 *Row = (uint8 *)BitmapMemory; // on va se dplacer dans la mmoire par pas de 8 bits for (int Y = 0; Y < BitmapHeight; ++Y) { uint32 *Pixel = (uint32 *)Row; // Pixel par pixel, on commence par le premier de la ligne for (int X = 0; X < BitmapWidth; ++X) { /* Pixels en little endian architecture 0 1 2 3 ... Pixels en mmoire : 00 00 00 00 ... Couleur BB GG RR XX en hexa: 0xXXRRGGBB */ uint8 Blue = (X + XOffset); uint8 Green = (Y + YOffset); // *Pixel = 0xFF00FF00; *Pixel = ((Green << 8) | Blue); // ce qui quivaut en hexa 0x00BBGG00 ++Pixel; // Faon de faire si on prend pixel par pixel } Row += Pitch; // Ligne suivante } } /** * DIB: Device Independent Bitmap **/ internal void Win32ResizeDIBSection(int Width, int Height) { if (BitmapMemory) { VirtualFree(BitmapMemory, 0, MEM_RELEASE); // cf. VirtualProtect, utile pour debug } BitmapWidth = Width; BitmapHeight = Height; BitmapInfo.bmiHeader.biSize = sizeof(BitmapInfo.bmiHeader); BitmapInfo.bmiHeader.biWidth = BitmapWidth; BitmapInfo.bmiHeader.biHeight = -BitmapHeight; // Atention au sens des coordonnes BitmapInfo.bmiHeader.biPlanes = 1; BitmapInfo.bmiHeader.biBitCount = 32; BitmapInfo.bmiHeader.biCompression = BI_RGB; int BitmapMemorySize = (BitmapWidth * BitmapHeight) * BytesPerPixel; BitmapMemory = VirtualAlloc(0, BitmapMemorySize, MEM_COMMIT, PAGE_READWRITE); // cf. aussi HeapAlloc } internal void Win32UpdateWindow(HDC DeviceContext, RECT *ClientRect, int X, int Y, int Width, int Height) { int WindowWidth = ClientRect->right - ClientRect->left; int WindowHeight = ClientRect->bottom - ClientRect->top; StretchDIBits( // copie d'un rectangle vers un autre (scaling si ncessaire, bit oprations...) DeviceContext, /*X, Y, Width, Height, X, Y, Width, Height,*/ 0, 0, BitmapWidth, BitmapHeight, 0, 0, WindowWidth, WindowHeight, BitmapMemory, &BitmapInfo, DIB_RGB_COLORS, SRCCOPY // BitBlt: bit-block transfer of the color data => voir les autres modes dans la MSDN ); } LRESULT CALLBACK Win32MainWindowCallback( HWND Window, UINT Message, WPARAM WParam, LPARAM LParam) { LRESULT Result = 0; switch(Message) { case WM_SIZE: { RECT ClientRect; GetClientRect(Window, &ClientRect); int Width = ClientRect.right - ClientRect.left; int Height = ClientRect.bottom - ClientRect.top; Win32ResizeDIBSection(Width, Height); OutputDebugStringA("WM_SIZE\n"); } break; case WM_DESTROY: { // PostQuitMessage(0); // Va permettre de sortir de la boucle infinie en dessous Running = false; OutputDebugStringA("WM_DESTROY\n"); } break; case WM_CLOSE: { // DestroyWindow(Window); Running = false; OutputDebugStringA("WM_CLOSE\n"); } break; case WM_ACTIVATEAPP: { OutputDebugStringA("WM_ACTIVATEAPP\n"); } break; case WM_PAINT: { PAINTSTRUCT Paint; HDC DeviceContext = BeginPaint(Window, &Paint); int X = Paint.rcPaint.left; int Y = Paint.rcPaint.top; int Width = Paint.rcPaint.right - Paint.rcPaint.left; int Height = Paint.rcPaint.bottom - Paint.rcPaint.top; RECT ClientRect; GetClientRect(Window, &ClientRect); Win32UpdateWindow(DeviceContext, &ClientRect, X, Y, Width, Height); EndPaint(Window, &Paint); } break; default: { // OutputDebugStringA("default\n"); Result = DefWindowProc(Window, Message, WParam, LParam); } break; } return(Result); } int CALLBACK WinMain( HINSTANCE Instance, HINSTANCE PrevInstance, LPSTR CommandLine, int ShowCode) { // Cration de la fentre principale WNDCLASSA WindowClass = {}; // initialisation par dfaut, ANSI version de WNDCLASSA // On ne configure que les membres que l'on veut WindowClass.style = CS_OWNDC|CS_HREDRAW|CS_VREDRAW; WindowClass.lpfnWndProc = Win32MainWindowCallback; WindowClass.hInstance = Instance; // WindowClass.hIcon; WindowClass.lpszClassName = "FaitmainHerosWindowClass"; // nom pour retrouver la fentre // Ouverture de la fentre if (RegisterClassA(&WindowClass)) { HWND Window = CreateWindowExA( // ANSI version de CreateWindowEx 0, // dwExStyle : options de la fentre WindowClass.lpszClassName, "FaitmainHeros", WS_OVERLAPPEDWINDOW|WS_VISIBLE, //dwStyle : overlapped window, visible par dfaut CW_USEDEFAULT, // X CW_USEDEFAULT, // Y CW_USEDEFAULT, // nWidth CW_USEDEFAULT, // nHeight 0, // hWndParent : 0 pour dire que c'est une fentre top 0, // hMenu : 0 pour dire pas de menu Instance, 0 // Pas de passage de paramtres la fentre ); if (Window) { int XOffset = 0; int YOffset = 0; MSG Message; Running = true; while (Running) // boucle infinie pour traiter tous les messages { while(PeekMessageA(&Message, 0, 0, 0, PM_REMOVE)) // On utilise PeekMessage au lieu de GetMessage qui est bloquant { if (Message.message == WM_QUIT) Running = false; TranslateMessage(&Message); // On demande Windows de traiter le message DispatchMessage(&Message); // Envoie le message au main WindowCallback, que l'on a dfini et dclar au dessus } // Grce PeekMessage on a tout le temps CPU que l'on veut et on peut dessiner ici RenderWeirdGradient(XOffset, YOffset); ++XOffset; // On doit alors crire dans la fentre chaque fois que l'on veut rendre // On en fera une fonction propre HDC DeviceContext = GetDC(Window); RECT ClientRect; GetClientRect(Window, &ClientRect); int WindowWidth = ClientRect.right - ClientRect.left; int WindowHeight = ClientRect.bottom - ClientRect.top; Win32UpdateWindow(DeviceContext, &ClientRect, 0, 0, WindowWidth, WindowHeight); ReleaseDC(Window, DeviceContext); } } else { OutputDebugStringA("Error: CreateWindowEx\n"); } } else { OutputDebugStringA("Error: RegisterClass\n"); } return(0); };<commit_msg>Refactorisation du code du backbuffer<commit_after>#include <Windows.h> #include <stdint.h> // Types indpendent de la plateforme // Pour bien comprendre la diffrence de fonctionnement des variables statiques en C en fonction du scope #define internal static // fonctions non visible depuis l'extrieur de ce fichier #define local_persist static // variable visibles juste dans le scope o elle dfinie #define global_variable static // variable visible dans tous le fichiers (globale) typedef unsigned char uint8; typedef uint8_t uint8; // comme un unsigned char, un 8 bits typedef int16_t uint16; typedef int32_t uint32; typedef int64_t uint64; /* Struct sui reprsente un backbuffer qui nous permet de dessiner */ struct win32_offscreen_buffer { BITMAPINFO Info; void *Memory; int Width; int Height; int BytesPerPixel; int Pitch; // Pitch reprsente la taille d'une ligne en octets }; // variables globales pour le moment, on grera autrement plus tard global_variable bool Running; global_variable win32_offscreen_buffer GlobalBackBuffer; struct win32_window_dimension { int Width; int Height; }; win32_window_dimension GetWindowDimension(HWND Window) { win32_window_dimension Result; RECT ClientRect; GetClientRect(Window, &ClientRect); Result.Width = ClientRect.right - ClientRect.left; Result.Height = ClientRect.bottom - ClientRect.top; return(Result); } internal void RenderWeirdGradient(win32_offscreen_buffer *Buffer, int XOffset, int YOffset) { uint8 *Row = (uint8 *)Buffer->Memory; // on va se dplacer dans la mmoire par pas de 8 bits for (int Y = 0; Y < Buffer->Height; ++Y) { uint32 *Pixel = (uint32 *)Row; // Pixel par pixel, on commence par le premier de la ligne for (int X = 0; X < Buffer->Width; ++X) { /* Pixels en little endian architecture 0 1 2 3 ... Pixels en mmoire : 00 00 00 00 ... Couleur BB GG RR XX en hexa: 0xXXRRGGBB */ uint8 Blue = (X + XOffset); uint8 Green = (Y + YOffset); // *Pixel = 0xFF00FF00; *Pixel = ((Green << 8) | Blue); // ce qui quivaut en hexa 0x00BBGG00 ++Pixel; // Faon de faire si on prend pixel par pixel } Row += Buffer->Pitch; // Ligne suivante } } /** * DIB: Device Independent Bitmap **/ internal void Win32ResizeDIBSection(win32_offscreen_buffer *Buffer, int Width, int Height) { if (Buffer->Memory) { VirtualFree(Buffer->Memory, 0, MEM_RELEASE); // cf. VirtualProtect, utile pour debug } Buffer->Width = Width; Buffer->Height = Height; Buffer->BytesPerPixel = 4; Buffer->Info.bmiHeader.biSize = sizeof(Buffer->Info.bmiHeader); Buffer->Info.bmiHeader.biWidth = Buffer->Width; Buffer->Info.bmiHeader.biHeight = -Buffer->Height; // Atention au sens des coordonnes Buffer->Info.bmiHeader.biPlanes = 1; Buffer->Info.bmiHeader.biBitCount = 32; Buffer->Info.bmiHeader.biCompression = BI_RGB; int BitmapMemorySize = (Buffer->Width * Buffer->Height) * Buffer->BytesPerPixel; Buffer->Memory = VirtualAlloc(0, BitmapMemorySize, MEM_COMMIT, PAGE_READWRITE); // cf. aussi HeapAlloc Buffer->Pitch = Width * Buffer->BytesPerPixel; } /** * Ici au dbut on passait ClientRect par rfrence avec un pointeur (*ClientRect) * cependant comme la structure est petite le passer par valeur est suffisant **/ internal void Win32DisplayBufferInWindow( HDC DeviceContext, int WindowWidth, int WindowHeight, win32_offscreen_buffer *Buffer, int X, int Y, int Width, int Height) { StretchDIBits( // copie d'un rectangle vers un autre (scaling si ncessaire, bit oprations...) DeviceContext, /*X, Y, Width, Height, X, Y, Width, Height,*/ 0, 0, Buffer->Width, Buffer->Height, 0, 0, WindowWidth, WindowHeight, Buffer->Memory, &Buffer->Info, DIB_RGB_COLORS, SRCCOPY // BitBlt: bit-block transfer of the color data => voir les autres modes dans la MSDN ); } LRESULT CALLBACK Win32MainWindowCallback( HWND Window, UINT Message, WPARAM WParam, LPARAM LParam) { LRESULT Result = 0; switch(Message) { case WM_SIZE: { win32_window_dimension Dimension = GetWindowDimension(Window); Win32ResizeDIBSection(&GlobalBackBuffer, Dimension.Width, Dimension.Height); OutputDebugStringA("WM_SIZE\n"); } break; case WM_DESTROY: { // PostQuitMessage(0); // Va permettre de sortir de la boucle infinie en dessous Running = false; OutputDebugStringA("WM_DESTROY\n"); } break; case WM_CLOSE: { // DestroyWindow(Window); Running = false; OutputDebugStringA("WM_CLOSE\n"); } break; case WM_ACTIVATEAPP: { OutputDebugStringA("WM_ACTIVATEAPP\n"); } break; case WM_PAINT: { PAINTSTRUCT Paint; HDC DeviceContext = BeginPaint(Window, &Paint); int X = Paint.rcPaint.left; int Y = Paint.rcPaint.top; int Width = Paint.rcPaint.right - Paint.rcPaint.left; int Height = Paint.rcPaint.bottom - Paint.rcPaint.top; win32_window_dimension Dimension = GetWindowDimension(Window); Win32DisplayBufferInWindow(DeviceContext, Dimension.Width, Dimension.Height, &GlobalBackBuffer, X, Y, Width, Height); EndPaint(Window, &Paint); } break; default: { // OutputDebugStringA("default\n"); Result = DefWindowProc(Window, Message, WParam, LParam); } break; } return(Result); } int CALLBACK WinMain( HINSTANCE Instance, HINSTANCE PrevInstance, LPSTR CommandLine, int ShowCode) { // Cration de la fentre principale WNDCLASSA WindowClass = {}; // initialisation par dfaut, ANSI version de WNDCLASSA // On ne configure que les membres que l'on veut WindowClass.style = CS_HREDRAW|CS_VREDRAW; // indique que l'on veut rafraichir la fentre entire lors d'un resize (horizontal et vertical) WindowClass.lpfnWndProc = Win32MainWindowCallback; WindowClass.hInstance = Instance; // WindowClass.hIcon; WindowClass.lpszClassName = "FaitmainHerosWindowClass"; // nom pour retrouver la fentre // Ouverture de la fentre if (RegisterClassA(&WindowClass)) { HWND Window = CreateWindowExA( // ANSI version de CreateWindowEx 0, // dwExStyle : options de la fentre WindowClass.lpszClassName, "FaitmainHeros", WS_OVERLAPPEDWINDOW|WS_VISIBLE, //dwStyle : overlapped window, visible par dfaut CW_USEDEFAULT, // X CW_USEDEFAULT, // Y CW_USEDEFAULT, // nWidth CW_USEDEFAULT, // nHeight 0, // hWndParent : 0 pour dire que c'est une fentre top 0, // hMenu : 0 pour dire pas de menu Instance, 0 // Pas de passage de paramtres la fentre ); if (Window) { int XOffset = 0; int YOffset = 0; MSG Message; Running = true; while (Running) // boucle infinie pour traiter tous les messages { while(PeekMessageA(&Message, 0, 0, 0, PM_REMOVE)) // On utilise PeekMessage au lieu de GetMessage qui est bloquant { if (Message.message == WM_QUIT) Running = false; TranslateMessage(&Message); // On demande Windows de traiter le message DispatchMessage(&Message); // Envoie le message au main WindowCallback, que l'on a dfini et dclar au dessus } // Grce PeekMessage on a tout le temps CPU que l'on veut et on peut dessiner ici RenderWeirdGradient(&GlobalBackBuffer, XOffset, YOffset); ++XOffset; // On doit alors crire dans la fentre chaque fois que l'on veut rendre // On en fera une fonction propre HDC DeviceContext = GetDC(Window); win32_window_dimension Dimension = GetWindowDimension(Window); Win32DisplayBufferInWindow(DeviceContext, Dimension.Width, Dimension.Height, &GlobalBackBuffer, 0, 0, Dimension.Width, Dimension.Height); ReleaseDC(Window, DeviceContext); } } else { OutputDebugStringA("Error: CreateWindowEx\n"); } } else { OutputDebugStringA("Error: RegisterClass\n"); } return(0); };<|endoftext|>
<commit_before>/* Copyright 2016-2017 CyberTech Labs Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <QtCore/QTimer> #include <QtCore/QEventLoop> #include <QtCore/QThread> #include <trikKitInterpreterCommon/trikbrick.h> #include <utils/abstractTimer.h> #include <kitBase/robotModel/robotModelUtils.h> #include <trikKit/robotModel/parts/trikShell.h> #include <trikKit/robotModel/parts/trikLineSensor.h> #include <kitBase/robotModel/robotParts/gyroscopeSensor.h> #include <kitBase/robotModel/robotParts/encoderSensor.h> #include <kitBase/robotModel/robotParts/random.h> #include <kitBase/robotModel/robotParts/random.h> #include <twoDModel/robotModel/parts/marker.h> #include <twoDModel/engine/model/timeline.h> ///todo: temporary #include <trikKitInterpreterCommon/robotModel/twoD/parts/twoDDisplay.h> using namespace trik; TrikBrick::TrikBrick(const QSharedPointer<robotModel::twoD::TrikTwoDRobotModel> &model) : mTwoDRobotModel(model) , mDisplay(model) , mKeys(model) , mSensorUpdater(model->timeline().produceTimer()) { connect(this, &TrikBrick::log, this, &TrikBrick::printToShell); mSensorUpdater->setRepeatable(true); mSensorUpdater->setInterval(model->updateIntervalForInterpretation()); // seems to be x2 of timeline tick connect(mSensorUpdater.data(), &utils::AbstractTimer::timeout, [model](){ model->updateSensorsValues(); /// @todo: maybe connect to model directly? }); } TrikBrick::~TrikBrick() { qDeleteAll(mMotors); qDeleteAll(mSensors); qDeleteAll(mEncoders); qDeleteAll(mLineSensors); qDeleteAll(mTimers); } void TrikBrick::reset() { mKeys.reset();///@todo: reset motos/device maps? //mDisplay.reset(); - is actually needed? Crashes app at exit emit stopWaiting(); for (const auto &m : mMotors) { m->powerOff(); } for (const auto &e : mEncoders) { e->reset(); } for (const auto &t : mTimers) { t->stop(); } qDeleteAll(mTimers); mTimers.clear(); QMetaObject::invokeMethod(mSensorUpdater.data(), "stop"); // failproof against timer manipulation in another thread } void TrikBrick::printToShell(const QString &msg) { using namespace kitBase::robotModel; using namespace trik::robotModel; parts::TrikShell* sh = RobotModelUtils::findDevice<parts::TrikShell>(*mTwoDRobotModel, "ShellPort"); if (sh == nullptr) { qDebug("Error: 2d model shell part was not found"); return; } sh->print(msg); } void TrikBrick::init() { mDisplay.init(); // for (const auto &m : mMotors) { // m->powerOff(); // } // for (const auto &e : mEncoders) { // e->read(); // } // for (const auto &s : mSensors) { // s->read(); // } mTwoDRobotModel->updateSensorsValues(); mMotors.clear(); // needed? reset? mSensors.clear(); mEncoders.clear(); mKeys.init(); mGyroscope.reset(); // for some reason it won't reconnect to the robot parts otherwise. QMetaObject::invokeMethod(mSensorUpdater.data(), "start"); // failproof against timer manipulation in another thread //mSensorUpdater.start(); } void TrikBrick::setCurrentDir(const QString &dir) { mCurrentDir = QFileInfo(dir).dir(); // maybe can be constructed directly } void TrikBrick::setCurrentInputs(const QString &f) { mIsExcerciseMode = true; if (f.isEmpty()) { return; // no inputs has been passed, no need to complain } QString file(f); QFile in(file); if (!in.open(QIODevice::ReadOnly | QIODevice::Text)) { emit warning(tr("Trying to read from file %1 failed").arg(file)); // todo: remove? It's only in exercise. //not really an error, usually } QStringList result; while (!in.atEnd()) { const auto line = in.readLine(); result << QString::fromUtf8(line); } mInputs = result; } void TrikBrick::say(const QString &msg) { using namespace kitBase::robotModel; using namespace trik::robotModel; parts::TrikShell* sh = RobotModelUtils::findDevice<parts::TrikShell>(*mTwoDRobotModel, "ShellPort"); if (sh == nullptr) { qDebug("Error: 2d model shell part was not found"); return; } QMetaObject::invokeMethod(sh, "say", Q_ARG(const QString &, msg)); } void TrikBrick::stop() { /// @todo: properly implement this? mTwoDRobotModel->stopRobot(); // for (const auto &m : mMotors) { // m->powerOff(); // } // for (const auto &e : mEncoders) { // e->reset(); // } } trikControl::MotorInterface *TrikBrick::motor(const QString &port) { using namespace kitBase::robotModel; if (!mMotors.contains(port)) { robotParts::Motor * mot = RobotModelUtils::findDevice<robotParts::Motor>(*mTwoDRobotModel, port); if (mot == nullptr) { emit error(tr("No configured motor on port: %1").arg(port)); return nullptr; } mMotors[port] = new TrikMotorEmu(mot); } return mMotors[port]; } trikControl::MarkerInterface *TrikBrick::marker() { kitBase::robotModel::PortInfo markerPort = kitBase::robotModel::RobotModelUtils::findPort(*mTwoDRobotModel , "MarkerPort" , kitBase::robotModel::Direction::output); if (markerPort.isValid()) { using Marker = twoDModel::robotModel::parts::Marker; Marker* marker = kitBase::robotModel::RobotModelUtils::findDevice<Marker>(*mTwoDRobotModel, markerPort); mTrikProxyMarker.reset(new TrikProxyMarker(marker)); return mTrikProxyMarker.data(); } return nullptr; } trikControl::SensorInterface *TrikBrick::sensor(const QString &port) { //testing using namespace kitBase::robotModel; if (!mSensors.contains(port)) { robotParts::ScalarSensor * sens = RobotModelUtils::findDevice<robotParts::ScalarSensor>(*mTwoDRobotModel, port); if (sens == nullptr) { emit error(tr("No configured sensor on port: %1").arg(port)); return nullptr; } mSensors[port] = new TrikSensorEmu(sens); } return mSensors[port]; } QStringList TrikBrick::motorPorts(trikControl::MotorInterface::Type type) const { Q_UNUSED(type) // QLOG_INFO() << "Motor type is ignored"; return mMotors.keys(); } QStringList TrikBrick::sensorPorts(trikControl::SensorInterface::Type type) const { Q_UNUSED(type) // QLOG_INFO() << "Sensor type is ignored"; return mMotors.keys(); } QStringList TrikBrick::encoderPorts() const { return mEncoders.keys(); } trikControl::VectorSensorInterface *TrikBrick::accelerometer() { using namespace kitBase::robotModel; if (mAccelerometer.isNull()) { auto a = RobotModelUtils::findDevice<robotParts::AccelerometerSensor>(*mTwoDRobotModel , "AccelerometerPort"); if (a == nullptr) { emit error(tr("No configured accelerometer")); return nullptr; } mAccelerometer.reset(new TrikAccelerometerAdapter(a)); } return mAccelerometer.data(); } trikControl::GyroSensorInterface *TrikBrick::gyroscope() { using namespace kitBase::robotModel; if (mGyroscope.isNull()) { auto a = RobotModelUtils::findDevice<robotParts::GyroscopeSensor>(*mTwoDRobotModel , "GyroscopePort"); if (a == nullptr) { emit error(tr("No configured gyroscope")); return nullptr; } mGyroscope.reset(new TrikGyroscopeAdapter(a, mTwoDRobotModel)); } return mGyroscope.data(); } trikControl::LineSensorInterface *TrikBrick::lineSensor(const QString &port) { using namespace trik::robotModel::parts; using namespace kitBase::robotModel; if (port == "video0") { return lineSensor("LineSensorPort"); // seems to be the case for 2d model } if (!mLineSensors.contains(port)) { TrikLineSensor * sens = RobotModelUtils::findDevice<TrikLineSensor>(*mTwoDRobotModel, port); if (sens == nullptr) { emit error(tr("No configured LineSensor on port: %1").arg(port)); return nullptr; } mLineSensors[port] = new TrikLineSensorAdapter(sens); } return mLineSensors[port]; } trikControl::EncoderInterface *TrikBrick::encoder(const QString &port) { using namespace kitBase::robotModel; if (!mEncoders.contains(port)) { robotParts::EncoderSensor * enc = RobotModelUtils::findDevice<robotParts::EncoderSensor>(*mTwoDRobotModel, port); if (enc == nullptr) { emit error(tr("No configured encoder on port: %1").arg(port)); return nullptr; } mEncoders[port] = new TrikEncoderAdapter(enc->port(), mTwoDRobotModel->engine()); } return mEncoders[port]; } trikControl::DisplayInterface *TrikBrick::display() { // trik::robotModel::parts::TrikDisplay * const display = // kitBase::robotModel::RobotModelUtils::findDevice<trik::robotModel::parts::TrikDisplay>(*mTwoDRobotModel // , "DisplayPort"); // if (display) { // bool res = QMetaObject::invokeMethod(display, // "drawSmile", // Qt::QueuedConnection, // connection type, auto? // Q_ARG(bool, false)); // //display->drawSmile(false); // printf(res ? "true" : "false"); // } // return nullptr; return &mDisplay; } trikControl::LedInterface *TrikBrick::led() { using namespace trik::robotModel::parts; using namespace kitBase::robotModel; if (mLed.isNull()) { auto l = RobotModelUtils::findDevice<TrikLed>(*mTwoDRobotModel, "LedPort"); if (l == nullptr) { emit error(tr("No configured led")); return nullptr; } mLed.reset(new TrikLedAdapter(l)); } return mLed.data(); } int TrikBrick::random(int from, int to) { using namespace kitBase::robotModel; auto r = RobotModelUtils::findDevice<robotParts::Random>(*mTwoDRobotModel, "RandomPort"); // maybe store it later, like the others if (!r) { emit error(tr("No cofigured random device")); return -1; } return r->random(from, to); } void TrikBrick::wait(int milliseconds) { auto timeline = dynamic_cast<twoDModel::model::Timeline *> (&mTwoDRobotModel->timeline()); if (timeline->isStarted()) { QSharedPointer<utils::AbstractTimer> t(timeline->produceTimer()); QTimer abortTimer; QMetaObject::Connection abortConnection; QSharedPointer<QEventLoop> loop (new QEventLoop()); auto mainHandler = [=]() { disconnect(abortConnection); disconnect(this, &TrikBrick::stopWaiting, nullptr, nullptr); disconnect(timeline, &twoDModel::model::Timeline::beforeStop, nullptr, nullptr); disconnect(t.data(), &utils::AbstractTimer::timeout, nullptr, nullptr); loop->quit(); }; auto abortHandler = [=]() { if (!timeline->isStarted()) { mainHandler(); } }; connect(t.data(), &utils::AbstractTimer::timeout, mainHandler); connect(this, &TrikBrick::stopWaiting, mainHandler); // timers that are produced by produceTimer() doesn't use stop singal // be careful, one who use just utils::AbstractTimer can stuck connect(timeline, &twoDModel::model::Timeline::beforeStop, mainHandler); abortConnection = connect(&abortTimer, &QTimer::timeout, abortHandler); // because timer is depends on twoDModel::model::Timeline if (timeline->isStarted()) { t->start(milliseconds); abortTimer.start(10); loop->exec(); } else { mainHandler(); } } } quint64 TrikBrick::time() const { return mTwoDRobotModel->timeline().timestamp(); } QStringList TrikBrick::readAll(const QString &path) { if (mIsExcerciseMode) { return mInputs; } //if (mCurrentDir) todo: check that the current working dir is a save dir QFileInfo normalizedPath(mCurrentDir.absoluteFilePath(path)); // absoluteDir? QString file = normalizedPath.filePath(); QFile in(file); if (!in.open(QIODevice::ReadOnly | QIODevice::Text)) { emit error(tr("Trying to read from file %1 failed").arg(file)); return {}; } QStringList result; while (!in.atEnd()) { const auto line = in.readLine(); result << QString::fromUtf8(line); } return result; } utils::AbstractTimer *TrikBrick::timer(int milliseconds) { utils::AbstractTimer *result = mTwoDRobotModel->timeline().produceTimer(); mTimers.append(result); result->setRepeatable(true); // seems to be the case result->start(milliseconds); return result; } <commit_msg>"this" in connect was returned<commit_after>/* Copyright 2016-2017 CyberTech Labs Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <QtCore/QTimer> #include <QtCore/QEventLoop> #include <QtCore/QThread> #include <trikKitInterpreterCommon/trikbrick.h> #include <utils/abstractTimer.h> #include <kitBase/robotModel/robotModelUtils.h> #include <trikKit/robotModel/parts/trikShell.h> #include <trikKit/robotModel/parts/trikLineSensor.h> #include <kitBase/robotModel/robotParts/gyroscopeSensor.h> #include <kitBase/robotModel/robotParts/encoderSensor.h> #include <kitBase/robotModel/robotParts/random.h> #include <kitBase/robotModel/robotParts/random.h> #include <twoDModel/robotModel/parts/marker.h> #include <twoDModel/engine/model/timeline.h> ///todo: temporary #include <trikKitInterpreterCommon/robotModel/twoD/parts/twoDDisplay.h> using namespace trik; TrikBrick::TrikBrick(const QSharedPointer<robotModel::twoD::TrikTwoDRobotModel> &model) : mTwoDRobotModel(model) , mDisplay(model) , mKeys(model) , mSensorUpdater(model->timeline().produceTimer()) { connect(this, &TrikBrick::log, this, &TrikBrick::printToShell); mSensorUpdater->setRepeatable(true); mSensorUpdater->setInterval(model->updateIntervalForInterpretation()); // seems to be x2 of timeline tick connect(mSensorUpdater.data(), &utils::AbstractTimer::timeout, [model](){ model->updateSensorsValues(); /// @todo: maybe connect to model directly? }); } TrikBrick::~TrikBrick() { qDeleteAll(mMotors); qDeleteAll(mSensors); qDeleteAll(mEncoders); qDeleteAll(mLineSensors); qDeleteAll(mTimers); } void TrikBrick::reset() { mKeys.reset();///@todo: reset motos/device maps? //mDisplay.reset(); - is actually needed? Crashes app at exit emit stopWaiting(); for (const auto &m : mMotors) { m->powerOff(); } for (const auto &e : mEncoders) { e->reset(); } for (const auto &t : mTimers) { t->stop(); } qDeleteAll(mTimers); mTimers.clear(); QMetaObject::invokeMethod(mSensorUpdater.data(), "stop"); // failproof against timer manipulation in another thread } void TrikBrick::printToShell(const QString &msg) { using namespace kitBase::robotModel; using namespace trik::robotModel; parts::TrikShell* sh = RobotModelUtils::findDevice<parts::TrikShell>(*mTwoDRobotModel, "ShellPort"); if (sh == nullptr) { qDebug("Error: 2d model shell part was not found"); return; } sh->print(msg); } void TrikBrick::init() { mDisplay.init(); // for (const auto &m : mMotors) { // m->powerOff(); // } // for (const auto &e : mEncoders) { // e->read(); // } // for (const auto &s : mSensors) { // s->read(); // } mTwoDRobotModel->updateSensorsValues(); mMotors.clear(); // needed? reset? mSensors.clear(); mEncoders.clear(); mKeys.init(); mGyroscope.reset(); // for some reason it won't reconnect to the robot parts otherwise. QMetaObject::invokeMethod(mSensorUpdater.data(), "start"); // failproof against timer manipulation in another thread //mSensorUpdater.start(); } void TrikBrick::setCurrentDir(const QString &dir) { mCurrentDir = QFileInfo(dir).dir(); // maybe can be constructed directly } void TrikBrick::setCurrentInputs(const QString &f) { mIsExcerciseMode = true; if (f.isEmpty()) { return; // no inputs has been passed, no need to complain } QString file(f); QFile in(file); if (!in.open(QIODevice::ReadOnly | QIODevice::Text)) { emit warning(tr("Trying to read from file %1 failed").arg(file)); // todo: remove? It's only in exercise. //not really an error, usually } QStringList result; while (!in.atEnd()) { const auto line = in.readLine(); result << QString::fromUtf8(line); } mInputs = result; } void TrikBrick::say(const QString &msg) { using namespace kitBase::robotModel; using namespace trik::robotModel; parts::TrikShell* sh = RobotModelUtils::findDevice<parts::TrikShell>(*mTwoDRobotModel, "ShellPort"); if (sh == nullptr) { qDebug("Error: 2d model shell part was not found"); return; } QMetaObject::invokeMethod(sh, "say", Q_ARG(const QString &, msg)); } void TrikBrick::stop() { /// @todo: properly implement this? mTwoDRobotModel->stopRobot(); // for (const auto &m : mMotors) { // m->powerOff(); // } // for (const auto &e : mEncoders) { // e->reset(); // } } trikControl::MotorInterface *TrikBrick::motor(const QString &port) { using namespace kitBase::robotModel; if (!mMotors.contains(port)) { robotParts::Motor * mot = RobotModelUtils::findDevice<robotParts::Motor>(*mTwoDRobotModel, port); if (mot == nullptr) { emit error(tr("No configured motor on port: %1").arg(port)); return nullptr; } mMotors[port] = new TrikMotorEmu(mot); } return mMotors[port]; } trikControl::MarkerInterface *TrikBrick::marker() { kitBase::robotModel::PortInfo markerPort = kitBase::robotModel::RobotModelUtils::findPort(*mTwoDRobotModel , "MarkerPort" , kitBase::robotModel::Direction::output); if (markerPort.isValid()) { using Marker = twoDModel::robotModel::parts::Marker; Marker* marker = kitBase::robotModel::RobotModelUtils::findDevice<Marker>(*mTwoDRobotModel, markerPort); mTrikProxyMarker.reset(new TrikProxyMarker(marker)); return mTrikProxyMarker.data(); } return nullptr; } trikControl::SensorInterface *TrikBrick::sensor(const QString &port) { //testing using namespace kitBase::robotModel; if (!mSensors.contains(port)) { robotParts::ScalarSensor * sens = RobotModelUtils::findDevice<robotParts::ScalarSensor>(*mTwoDRobotModel, port); if (sens == nullptr) { emit error(tr("No configured sensor on port: %1").arg(port)); return nullptr; } mSensors[port] = new TrikSensorEmu(sens); } return mSensors[port]; } QStringList TrikBrick::motorPorts(trikControl::MotorInterface::Type type) const { Q_UNUSED(type) // QLOG_INFO() << "Motor type is ignored"; return mMotors.keys(); } QStringList TrikBrick::sensorPorts(trikControl::SensorInterface::Type type) const { Q_UNUSED(type) // QLOG_INFO() << "Sensor type is ignored"; return mMotors.keys(); } QStringList TrikBrick::encoderPorts() const { return mEncoders.keys(); } trikControl::VectorSensorInterface *TrikBrick::accelerometer() { using namespace kitBase::robotModel; if (mAccelerometer.isNull()) { auto a = RobotModelUtils::findDevice<robotParts::AccelerometerSensor>(*mTwoDRobotModel , "AccelerometerPort"); if (a == nullptr) { emit error(tr("No configured accelerometer")); return nullptr; } mAccelerometer.reset(new TrikAccelerometerAdapter(a)); } return mAccelerometer.data(); } trikControl::GyroSensorInterface *TrikBrick::gyroscope() { using namespace kitBase::robotModel; if (mGyroscope.isNull()) { auto a = RobotModelUtils::findDevice<robotParts::GyroscopeSensor>(*mTwoDRobotModel , "GyroscopePort"); if (a == nullptr) { emit error(tr("No configured gyroscope")); return nullptr; } mGyroscope.reset(new TrikGyroscopeAdapter(a, mTwoDRobotModel)); } return mGyroscope.data(); } trikControl::LineSensorInterface *TrikBrick::lineSensor(const QString &port) { using namespace trik::robotModel::parts; using namespace kitBase::robotModel; if (port == "video0") { return lineSensor("LineSensorPort"); // seems to be the case for 2d model } if (!mLineSensors.contains(port)) { TrikLineSensor * sens = RobotModelUtils::findDevice<TrikLineSensor>(*mTwoDRobotModel, port); if (sens == nullptr) { emit error(tr("No configured LineSensor on port: %1").arg(port)); return nullptr; } mLineSensors[port] = new TrikLineSensorAdapter(sens); } return mLineSensors[port]; } trikControl::EncoderInterface *TrikBrick::encoder(const QString &port) { using namespace kitBase::robotModel; if (!mEncoders.contains(port)) { robotParts::EncoderSensor * enc = RobotModelUtils::findDevice<robotParts::EncoderSensor>(*mTwoDRobotModel, port); if (enc == nullptr) { emit error(tr("No configured encoder on port: %1").arg(port)); return nullptr; } mEncoders[port] = new TrikEncoderAdapter(enc->port(), mTwoDRobotModel->engine()); } return mEncoders[port]; } trikControl::DisplayInterface *TrikBrick::display() { // trik::robotModel::parts::TrikDisplay * const display = // kitBase::robotModel::RobotModelUtils::findDevice<trik::robotModel::parts::TrikDisplay>(*mTwoDRobotModel // , "DisplayPort"); // if (display) { // bool res = QMetaObject::invokeMethod(display, // "drawSmile", // Qt::QueuedConnection, // connection type, auto? // Q_ARG(bool, false)); // //display->drawSmile(false); // printf(res ? "true" : "false"); // } // return nullptr; return &mDisplay; } trikControl::LedInterface *TrikBrick::led() { using namespace trik::robotModel::parts; using namespace kitBase::robotModel; if (mLed.isNull()) { auto l = RobotModelUtils::findDevice<TrikLed>(*mTwoDRobotModel, "LedPort"); if (l == nullptr) { emit error(tr("No configured led")); return nullptr; } mLed.reset(new TrikLedAdapter(l)); } return mLed.data(); } int TrikBrick::random(int from, int to) { using namespace kitBase::robotModel; auto r = RobotModelUtils::findDevice<robotParts::Random>(*mTwoDRobotModel, "RandomPort"); // maybe store it later, like the others if (!r) { emit error(tr("No cofigured random device")); return -1; } return r->random(from, to); } void TrikBrick::wait(int milliseconds) { auto timeline = dynamic_cast<twoDModel::model::Timeline *> (&mTwoDRobotModel->timeline()); if (timeline->isStarted()) { QSharedPointer<utils::AbstractTimer> t(timeline->produceTimer()); QTimer abortTimer; QMetaObject::Connection abortConnection; QSharedPointer<QEventLoop> loop (new QEventLoop()); auto mainHandler = [=]() { disconnect(abortConnection); disconnect(this, &TrikBrick::stopWaiting, nullptr, nullptr); disconnect(timeline, &twoDModel::model::Timeline::beforeStop, nullptr, nullptr); disconnect(t.data(), &utils::AbstractTimer::timeout, nullptr, nullptr); loop->quit(); }; auto abortHandler = [=]() { if (!timeline->isStarted()) { mainHandler(); } }; connect(t.data(), &utils::AbstractTimer::timeout, mainHandler); connect(this, &TrikBrick::stopWaiting, mainHandler); // timers that are produced by produceTimer() doesn't use stop singal // be careful, one who use just utils::AbstractTimer can stuck connect(timeline, &twoDModel::model::Timeline::beforeStop, this, mainHandler); abortConnection = connect(&abortTimer, &QTimer::timeout, this, abortHandler); // because timer is depends on twoDModel::model::Timeline if (timeline->isStarted()) { t->start(milliseconds); abortTimer.start(10); loop->exec(); } else { mainHandler(); } } } quint64 TrikBrick::time() const { return mTwoDRobotModel->timeline().timestamp(); } QStringList TrikBrick::readAll(const QString &path) { if (mIsExcerciseMode) { return mInputs; } //if (mCurrentDir) todo: check that the current working dir is a save dir QFileInfo normalizedPath(mCurrentDir.absoluteFilePath(path)); // absoluteDir? QString file = normalizedPath.filePath(); QFile in(file); if (!in.open(QIODevice::ReadOnly | QIODevice::Text)) { emit error(tr("Trying to read from file %1 failed").arg(file)); return {}; } QStringList result; while (!in.atEnd()) { const auto line = in.readLine(); result << QString::fromUtf8(line); } return result; } utils::AbstractTimer *TrikBrick::timer(int milliseconds) { utils::AbstractTimer *result = mTwoDRobotModel->timeline().produceTimer(); mTimers.append(result); result->setRepeatable(true); // seems to be the case result->start(milliseconds); return result; } <|endoftext|>
<commit_before>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2008-2013, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and / or other materials provided with the distribution. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #include "test_precomp.hpp" #include "opencv2/core/affine.hpp" #include "opencv2/calib3d.hpp" #include <iostream> TEST(Calib3d_Affine3f, accuracy) { cv::Vec3d rvec(0.2, 0.5, 0.3); cv::Affine3d affine(rvec); cv::Mat expected; cv::Rodrigues(rvec, expected); ASSERT_EQ(0, cvtest::norm(cv::Mat(affine.matrix, false).colRange(0, 3).rowRange(0, 3) != expected, cv::NORM_L2)); ASSERT_EQ(0, cvtest::norm(cv::Mat(affine.linear()) != expected, cv::NORM_L2)); cv::Matx33d R = cv::Matx33d::eye(); double angle = 50; R.val[0] = R.val[4] = std::cos(CV_PI*angle/180.0); R.val[3] = std::sin(CV_PI*angle/180.0); R.val[1] = -R.val[3]; cv::Affine3d affine1(cv::Mat(cv::Vec3d(0.2, 0.5, 0.3)).reshape(1, 1), cv::Vec3d(4, 5, 6)); cv::Affine3d affine2(R, cv::Vec3d(1, 1, 0.4)); cv::Affine3d result = affine1.inv() * affine2; expected = cv::Mat(affine1.matrix.inv(cv::DECOMP_SVD)) * cv::Mat(affine2.matrix, false); cv::Mat diff; cv::absdiff(expected, result.matrix, diff); ASSERT_LT(cvtest::norm(diff, cv::NORM_INF), 1e-15); } TEST(Calib3d_Affine3f, accuracy_rvec) { cv::RNG rng; typedef float T; cv::Affine3<T>::Vec3 w; cv::Affine3<T>::Mat3 u, vt, R; for(int i = 0; i < 100; ++i) { rng.fill(R, cv::RNG::UNIFORM, -10, 10, true); cv::SVD::compute(R, w, u, vt, cv::SVD::FULL_UV + cv::SVD::MODIFY_A); R = u * vt; //double s = (double)cv::getTickCount(); cv::Affine3<T>::Vec3 va = cv::Affine3<T>(R).rvec(); //std::cout << "M:" <<(cv::getTickCount() - s)*1000/cv::getTickFrequency() << std::endl; cv::Affine3<T>::Vec3 vo; //s = (double)cv::getTickCount(); cv::Rodrigues(R, vo); //std::cout << "O:" <<(cv::getTickCount() - s)*1000/cv::getTickFrequency() << std::endl; ASSERT_LT(cvtest::norm(va, vo, cv::NORM_L2), 1e-9); } } <commit_msg>fixing spaces for conformance<commit_after>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2008-2013, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #include "test_precomp.hpp" #include "opencv2/core/affine.hpp" #include "opencv2/calib3d.hpp" #include <iostream> TEST(Calib3d_Affine3f, accuracy) { cv::Vec3d rvec(0.2, 0.5, 0.3); cv::Affine3d affine(rvec); cv::Mat expected; cv::Rodrigues(rvec, expected); ASSERT_EQ(0, cvtest::norm(cv::Mat(affine.matrix, false).colRange(0, 3).rowRange(0, 3) != expected, cv::NORM_L2)); ASSERT_EQ(0, cvtest::norm(cv::Mat(affine.linear()) != expected, cv::NORM_L2)); cv::Matx33d R = cv::Matx33d::eye(); double angle = 50; R.val[0] = R.val[4] = std::cos(CV_PI*angle/180.0); R.val[3] = std::sin(CV_PI*angle/180.0); R.val[1] = -R.val[3]; cv::Affine3d affine1(cv::Mat(cv::Vec3d(0.2, 0.5, 0.3)).reshape(1, 1), cv::Vec3d(4, 5, 6)); cv::Affine3d affine2(R, cv::Vec3d(1, 1, 0.4)); cv::Affine3d result = affine1.inv() * affine2; expected = cv::Mat(affine1.matrix.inv(cv::DECOMP_SVD)) * cv::Mat(affine2.matrix, false); cv::Mat diff; cv::absdiff(expected, result.matrix, diff); ASSERT_LT(cvtest::norm(diff, cv::NORM_INF), 1e-15); } TEST(Calib3d_Affine3f, accuracy_rvec) { cv::RNG rng; typedef float T; cv::Affine3<T>::Vec3 w; cv::Affine3<T>::Mat3 u, vt, R; for(int i = 0; i < 100; ++i) { rng.fill(R, cv::RNG::UNIFORM, -10, 10, true); cv::SVD::compute(R, w, u, vt, cv::SVD::FULL_UV + cv::SVD::MODIFY_A); R = u * vt; //double s = (double)cv::getTickCount(); cv::Affine3<T>::Vec3 va = cv::Affine3<T>(R).rvec(); //std::cout << "M:" <<(cv::getTickCount() - s)*1000/cv::getTickFrequency() << std::endl; cv::Affine3<T>::Vec3 vo; //s = (double)cv::getTickCount(); cv::Rodrigues(R, vo); //std::cout << "O:" <<(cv::getTickCount() - s)*1000/cv::getTickFrequency() << std::endl; ASSERT_LT(cvtest::norm(va, vo, cv::NORM_L2), 1e-9); } } <|endoftext|>
<commit_before>/** * File: main.cpp * Project: tsc - TinyStarChart * Creator: jbangelo * * Description: The entry point to the program * * The MIT License (MIT) * * Copyright (c) 2014 jbangelo * * 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 <iomanip> #include "sqlite3.h" #include "Math/Degree.h" #include "Time/Stardate.h" #include "SkyObject/Planet.h" using tsc::Math::Degree; using tsc::Time::Stardate; using tsc::Time::ChristianDate; using tsc::SkyObject::Planet; using namespace std; int main(int argc, char** argv) { Degree d1(90.0), d2(-90.0); cout.setf(ostream::fixed); cout << std::setprecision(10); cout << "d1 = " << d1.degStr() << endl; cout << "d2 = " << d2.hmsStr() << endl; cout << "d1 + d2 = " << (d1+d2).degStr() << endl; cout << "d1 - d2 = " << (d1-d2).degStr() << endl; cout << "d1 * d2 = " << (d1*d2).degStr() << endl; cout << "d1 / d2 = " << (d1/d2).degStr() << endl; Stardate sd1 = Stardate::fromDate(ChristianDate(2000, 1, 1, 12, 0, 0)); Stardate sd2(2451179.5); Stardate sd3 = Stardate::fromDate(ChristianDate(1987, 1, 27)); Stardate sd4(2446966.0); Stardate sd5 = Stardate::fromDate(ChristianDate(1988, 1, 27)); Stardate sd6(2447332.0); Stardate sd7 = Stardate::fromDate(ChristianDate(1900, 1, 1)); Stardate sd8(2305447.5); Stardate sd9 = Stardate::fromDate(ChristianDate(1600, 12, 31)); Stardate sd10(2026871.8); Stardate sd11 = Stardate::fromDate(ChristianDate(-123, 12, 31)); Stardate sd12(1676497.5); Stardate sd13 = Stardate::fromDate(ChristianDate(-1000, 7, 12, 12, 0, 0)); Stardate sd14(1355866.5); Stardate sd15(1355671.4); Stardate sd16 = Stardate::fromDate(ChristianDate(-4712, 1, 1, 12, 0, 0)); Stardate sd17(2436116.31); cout << "sd1 = " << sd1.toGregorianDateStr() << ", " << sd1.toJD() << endl; cout << "sd2 = " << sd2.toGregorianDateStr() << ", " << sd2.toJD() << endl; cout << "sd3 = " << sd3.toGregorianDateStr() << ", " << sd3.toJD() << endl; cout << "sd4 = " << sd4.toGregorianDateStr() << ", " << sd4.toJD() << endl; cout << "sd5 = " << sd5.toGregorianDateStr() << ", " << sd5.toJD() << endl; cout << "sd6 = " << sd6.toGregorianDateStr() << ", " << sd6.toJD() << endl; cout << "sd7 = " << sd7.toGregorianDateStr() << ", " << sd7.toJD() << endl; cout << "sd8 = " << sd8.toGregorianDateStr() << ", " << sd8.toJD() << endl; cout << "sd9 = " << sd9.toGregorianDateStr() << ", " << sd9.toJD() << endl; cout << "sd10 = " << sd10.toGregorianDateStr() << ", " << sd10.toJD() << endl; cout << "sd11 = " << sd11.toGregorianDateStr() << ", " << sd11.toJD() << endl; cout << "sd12 = " << sd12.toGregorianDateStr() << ", " << sd12.toJD() << endl; cout << "sd13 = " << sd13.toGregorianDateStr() << ", " << sd13.toJD() << endl; cout << "sd14 = " << sd14.toGregorianDateStr() << ", " << sd14.toJD() << endl; cout << "sd15 = " << sd15.toGregorianDateStr() << ", " << sd15.toJD() << endl; cout << "sd16 = " << sd16.toGregorianDateStr() << ", " << sd16.toJD() << endl; cout << "sd16 = " << sd17.toGregorianDateStr() << ", " << sd17.toJD() << endl; sqlite3* db; if (sqlite3_open_v2("../resources/tsc.db", &db, SQLITE_OPEN_READONLY, NULL) != SQLITE_OK) { cout << "Error opening up the database file!" << endl; return 1; } cout << "Loading planetary data..." << endl; Planet earth(Planet::EARTH, db, NULL); Planet mercury(Planet::MERCURY, db, &earth); Planet venus(Planet::VENUS, db, &earth); Planet mars(Planet::MARS, db, &earth); Planet jupiter(Planet::JUPITER, db, &earth); Planet saturn(Planet::SATURN, db, &earth); Planet uranus(Planet::URANUS, db, &earth); Planet neptune(Planet::NEPTUNE, db, &earth); Stardate mercDate(2305445.0); cout << "Calculateing the position of Mercury at " << mercDate.toGregorianDateStr() << endl; mercury.calculatePosition(mercDate); EclipticCoords mercCoords = mercury.getHeliocentricEclipticCoords(); cout << "L = " << mercCoords.lambda.rad() << endl; cout << "B = " << mercCoords.beta.rad() << endl; cout << "R = " << mercCoords.delta << endl << endl; Stardate venusDate(2378495.0); cout << "Calculateing the position of Venus at " << venusDate.toGregorianDateStr() << endl; venus.calculatePosition(venusDate); EclipticCoords venusCoords = venus.getHeliocentricEclipticCoords(); cout << "L = " << venusCoords.lambda.rad() << endl; cout << "B = " << venusCoords.beta.rad() << endl; cout << "R = " << venusCoords.delta << endl; Stardate earthDate(2341970.0); cout << "Calculateing the position of Earth at " << earthDate.toGregorianDateStr() << endl; earth.calculatePosition(earthDate); EclipticCoords earthCoords = earth.getHeliocentricEclipticCoords(); cout << "L = " << earthCoords.lambda.rad() << endl; cout << "B = " << earthCoords.beta.rad() << endl; cout << "R = " << earthCoords.delta << endl; sqlite3_close(db); return 0; } <commit_msg>Started changing the main function to parse arguments<commit_after>/** * File: main.cpp * Project: tsc - TinyStarChart * Creator: jbangelo * * Description: The entry point to the program * * The MIT License (MIT) * * Copyright (c) 2014 jbangelo * * 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 <iomanip> #include <stdlib.h> #include "sqlite3.h" #include "Math/Degree.h" #include "Time/Stardate.h" #include "SkyObject/Planet.h" using tsc::Math::Degree; using tsc::Time::Stardate; using tsc::Time::ChristianDate; using tsc::SkyObject::Planet; using namespace std; int main(int argc, char** argv) { char *cvalue = NULL; int c; Stardate *date = NULL; opterr = 0; while ((c = getopt(argc, argv, "j:")) != -1) { switch (c) { case 'j': cvalue = optarg; date = new Stardate(::atof(cvalue)); break; case '?': if (isprint(optopt)) { cerr << "Unkown option '-" << optopt << "'\n"; } else { cerr << "Unkown option character '0x" << optopt << "'\n"; } return 1; default: return 1; } } if (date != NULL) { cout << "Using date " << *date << endl; } return 0; } <|endoftext|>
<commit_before>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #include "test_precomp.hpp" #include <string> #include <iostream> using namespace std; using namespace cv; class CV_GrabcutTest : public cvtest::BaseTest { public: CV_GrabcutTest(); ~CV_GrabcutTest(); protected: bool verify(const Mat& mask, const Mat& exp); void run(int); }; CV_GrabcutTest::CV_GrabcutTest() {} CV_GrabcutTest::~CV_GrabcutTest() {} bool CV_GrabcutTest::verify(const Mat& mask, const Mat& exp) { const float maxDiffRatio = 0.005f; int expArea = countNonZero( exp ); int nonIntersectArea = countNonZero( mask != exp ); float curRatio = (float)nonIntersectArea / (float)expArea; ts->printf( cvtest::TS::LOG, "nonIntersectArea/expArea = %f\n", curRatio ); return curRatio < maxDiffRatio; } void CV_GrabcutTest::run( int /* start_from */) { cvtest::DefaultRngAuto defRng; Mat img = imread(string(ts->get_data_path()) + "shared/airplane.jpg"); Mat mask_prob = imread(string(ts->get_data_path()) + "grabcut/mask_prob.png", 0); Mat exp_mask1 = imread(string(ts->get_data_path()) + "grabcut/exp_mask1.png", 0); Mat exp_mask2 = imread(string(ts->get_data_path()) + "grabcut/exp_mask2.png", 0); if (img.empty() || (!mask_prob.empty() && img.size() != mask_prob.size()) || (!exp_mask1.empty() && img.size() != exp_mask1.size()) || (!exp_mask2.empty() && img.size() != exp_mask2.size()) ) { ts->set_failed_test_info(cvtest::TS::FAIL_MISSING_TEST_DATA); return; } Rect rect(Point(24, 126), Point(483, 294)); Mat exp_bgdModel, exp_fgdModel; Mat mask; mask = Scalar(0); Mat bgdModel, fgdModel; grabCut( img, mask, rect, bgdModel, fgdModel, 0, GC_INIT_WITH_RECT ); grabCut( img, mask, rect, bgdModel, fgdModel, 2, GC_EVAL ); // Multiply images by 255 for more visuality of test data. if( mask_prob.empty() ) { mask.copyTo( mask_prob ); imwrite(string(ts->get_data_path()) + "grabcut/mask_prob.png", mask_prob); } if( exp_mask1.empty() ) { exp_mask1 = (mask & 1) * 255; imwrite(string(ts->get_data_path()) + "grabcut/exp_mask1.png", exp_mask1); } if (!verify((mask & 1) * 255, exp_mask1)) { ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH); return; } mask = mask_prob; bgdModel.release(); fgdModel.release(); rect = Rect(); grabCut( img, mask, rect, bgdModel, fgdModel, 0, GC_INIT_WITH_MASK ); grabCut( img, mask, rect, bgdModel, fgdModel, 1, GC_EVAL ); if( exp_mask2.empty() ) { exp_mask2 = (mask & 1) * 255; imwrite(string(ts->get_data_path()) + "grabcut/exp_mask2.png", exp_mask2); } if (!verify((mask & 1) * 255, exp_mask2)) { ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH); return; } ts->set_failed_test_info(cvtest::TS::OK); } TEST(Imgproc_GrabCut, regression) { CV_GrabcutTest test; test.safe_run(); } <commit_msg>Added regression test for #1652<commit_after>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #include "test_precomp.hpp" #include <string> #include <iostream> using namespace std; using namespace cv; class CV_GrabcutTest : public cvtest::BaseTest { public: CV_GrabcutTest(); ~CV_GrabcutTest(); protected: bool verify(const Mat& mask, const Mat& exp); void run(int); }; CV_GrabcutTest::CV_GrabcutTest() {} CV_GrabcutTest::~CV_GrabcutTest() {} bool CV_GrabcutTest::verify(const Mat& mask, const Mat& exp) { const float maxDiffRatio = 0.005f; int expArea = countNonZero( exp ); int nonIntersectArea = countNonZero( mask != exp ); float curRatio = (float)nonIntersectArea / (float)expArea; ts->printf( cvtest::TS::LOG, "nonIntersectArea/expArea = %f\n", curRatio ); return curRatio < maxDiffRatio; } void CV_GrabcutTest::run( int /* start_from */) { cvtest::DefaultRngAuto defRng; Mat img = imread(string(ts->get_data_path()) + "shared/airplane.jpg"); Mat mask_prob = imread(string(ts->get_data_path()) + "grabcut/mask_prob.png", 0); Mat exp_mask1 = imread(string(ts->get_data_path()) + "grabcut/exp_mask1.png", 0); Mat exp_mask2 = imread(string(ts->get_data_path()) + "grabcut/exp_mask2.png", 0); if (img.empty() || (!mask_prob.empty() && img.size() != mask_prob.size()) || (!exp_mask1.empty() && img.size() != exp_mask1.size()) || (!exp_mask2.empty() && img.size() != exp_mask2.size()) ) { ts->set_failed_test_info(cvtest::TS::FAIL_MISSING_TEST_DATA); return; } Rect rect(Point(24, 126), Point(483, 294)); Mat exp_bgdModel, exp_fgdModel; Mat mask; mask = Scalar(0); Mat bgdModel, fgdModel; grabCut( img, mask, rect, bgdModel, fgdModel, 0, GC_INIT_WITH_RECT ); grabCut( img, mask, rect, bgdModel, fgdModel, 2, GC_EVAL ); // Multiply images by 255 for more visuality of test data. if( mask_prob.empty() ) { mask.copyTo( mask_prob ); imwrite(string(ts->get_data_path()) + "grabcut/mask_prob.png", mask_prob); } if( exp_mask1.empty() ) { exp_mask1 = (mask & 1) * 255; imwrite(string(ts->get_data_path()) + "grabcut/exp_mask1.png", exp_mask1); } if (!verify((mask & 1) * 255, exp_mask1)) { ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH); return; } mask = mask_prob; bgdModel.release(); fgdModel.release(); rect = Rect(); grabCut( img, mask, rect, bgdModel, fgdModel, 0, GC_INIT_WITH_MASK ); grabCut( img, mask, rect, bgdModel, fgdModel, 1, GC_EVAL ); if( exp_mask2.empty() ) { exp_mask2 = (mask & 1) * 255; imwrite(string(ts->get_data_path()) + "grabcut/exp_mask2.png", exp_mask2); } if (!verify((mask & 1) * 255, exp_mask2)) { ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH); return; } ts->set_failed_test_info(cvtest::TS::OK); } TEST(Imgproc_GrabCut, regression) { CV_GrabcutTest test; test.safe_run(); } TEST(Imgproc_GrabCut, repeatability) { cvtest::TS& ts = *cvtest::TS::ptr(); Mat image_1 = imread(ts.get_data_path() + "grabcut/image1652.ppm", CV_LOAD_IMAGE_COLOR); Mat mask_1 = imread(ts.get_data_path() + "grabcut/mask1652.ppm", CV_LOAD_IMAGE_GRAYSCALE); Rect roi_1(0, 0, 150, 150); Mat image_2 = image_1.clone(); Mat mask_2 = mask_1.clone(); Rect roi_2 = roi_1; Mat image_3 = image_1.clone(); Mat mask_3 = mask_1.clone(); Rect roi_3 = roi_1; Mat bgdModel_1, fgdModel_1; Mat bgdModel_2, fgdModel_2; Mat bgdModel_3, fgdModel_3; theRNG().state = 12378213; grabCut(image_1, mask_1, roi_1, bgdModel_1, fgdModel_1, 1, GC_INIT_WITH_MASK); theRNG().state = 12378213; grabCut(image_2, mask_2, roi_2, bgdModel_2, fgdModel_2, 1, GC_INIT_WITH_MASK); theRNG().state = 12378213; grabCut(image_3, mask_3, roi_3, bgdModel_3, fgdModel_3, 1, GC_INIT_WITH_MASK); EXPECT_EQ(0, countNonZero(mask_1 != mask_2)); EXPECT_EQ(0, countNonZero(mask_1 != mask_3)); EXPECT_EQ(0, countNonZero(mask_2 != mask_3)); } <|endoftext|>
<commit_before> /*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998, 1999, 2000, 2001 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * 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; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ /****************** <SNX heading BEGIN do not edit this line> ***************** * * Juggler Juggler * * Original Authors: * Kevin Meinert, Carolina Cruz-Neira * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * ****************** <SNX heading END do not edit this line> ******************/ // Kevin Meinert // simple glut skeleton application: look for the !!!TODO!!!s, // and fill in your code // there as needed // #ifdef WIN32 #include <windows.h> // make the app win32 friendly. :) #endif #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #include <snx/sonix.h> // interface #include <snx/SoundHandle.h> #include "StopWatch.h" #include <iostream.h> #include <stdlib.h> // a place to store application data... class AppWindow { public: static int width, height; static int mainWin_contextID; }; int AppWindow::width = 0, AppWindow::height = 0; int AppWindow::mainWin_contextID = -1; StopWatch stopWatch; int soundpos = 0; float pitchbend = 1.0f; float cutoff = 0.2f; float volume = 1.0f; // our sound object... snx::SoundHandle kevinSound; void drawGrid() { glBegin( GL_LINES ); for ( int x = -1000; x < 1000; ++x) { glVertex3f( -1000, 0, x ); glVertex3f( 1000, 0, x ); glVertex3f( x, 0, -1000 ); glVertex3f( x, 0, 1000 ); } glEnd(); } ////////////////////////////////////////////////// // This is called on a glutPostRedisplay ////////////////////////////////////////////////// static void OnRedisplay() { glClearColor( 0.0f, 0.0f, 0.0f, 1.0f ); glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT ); glEnable( GL_DEPTH_TEST ); glEnable( GL_BLEND ); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); // set up the projection matrix glMatrixMode( GL_PROJECTION ); glLoadIdentity(); gluPerspective( 80.0f, AppWindow::width / AppWindow::height, 0.01f, 1000.0f ); // initialize your matrix stack used for transforming your models glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); // !!!TODO!!!: replace the following with your own opengl commands! glTranslatef( 0, -10, 0 ); drawGrid(); // !!!TODO!!!: //////////////////////////////////////// // swaps the front and back frame buffers. // hint: you've been drawing on the back, offscreen, buffer. // This command then brings that framebuffer onscreen. glutSwapBuffers(); } ////////////////////////////////////////////////// // This is called repeatedly, as fast as possible ////////////////////////////////////////////////// #include "unistd.h" static void OnIdle() { // According to the GLUT specification, the current window is // undefined during an idle callback. So we need to explicitly change // it if necessary if ( glutGetWindow() != AppWindow::mainWin_contextID ) glutSetWindow( AppWindow::mainWin_contextID ); // tell glut to call redisplay (which then calls OnRedisplay) glutPostRedisplay(); sonix::instance()->step( stopWatch.timeInstant() ); stopWatch.pulse(); } ///////////////////////////////////////////// // This is called on a Resize of the glut window ///////////////////////////////////////////// static void OnReshape( int width, int height ) { // save these params in case your app needs them AppWindow::width = width; AppWindow::height = height; // set your viewport to the extents of the window glViewport( 0, 0, width, height ); // let the app run idle, while resizing, // glut does not do this for us automatically, so call OnIdle explicitly. OnIdle(); } //////////////////////////////// // This is called on a Down Keypress //////////////////////////////// static void OnKeyboardDown( unsigned char k, int x, int y ) { switch (k) { // If user pressed 'q' or 'ESC', then exit the app. // this is really ungraceful, but necessary since GLUT does a while(1) // as it's control loop. There is no GLUT method to exit, unfortunately. case 'q': case 27: exit( 0 ); break; case '1': { sonix::instance()->changeAPI( "Stub" ); snx::SoundInfo si; si.filename = "../../../data/sol.wav"; si.ambient = false; si.datasource = snx::SoundInfo::FILESYSTEM; kevinSound.configure( si ); sonix::instance()->changeAPI( "OpenAL" ); } break; case '2': { sonix::instance()->changeAPI( "Stub" ); snx::SoundInfo si; si.filename = "../../../data/sep.wav"; si.ambient = false; si.datasource = snx::SoundInfo::FILESYSTEM; kevinSound.configure( si ); sonix::instance()->changeAPI( "AudioWorks" ); } break; case '3': { sonix::instance()->changeAPI( "Stub" ); } break; case 'a': { snx::SoundInfo si; si.ambient = false; si.filename = "../../../data/sol.wav"; si.datasource = snx::SoundInfo::FILESYSTEM; kevinSound.configure( si ); std::cout<<"positional"<<std::endl; } break; case 'b': { snx::SoundInfo si; si.ambient = true; si.filename = "../../../data/sep.wav"; si.datasource = snx::SoundInfo::FILESYSTEM; kevinSound.configure( si ); kevinSound.setAmbient( true ); std::cout<<"ambient"<<std::endl; } break; case 'c': { snx::SoundInfo si; si.ambient = false; si.filename = "../../../data/suck.wav"; si.datasource = snx::SoundInfo::FILESYSTEM; kevinSound.configure( si ); std::cout<<"positional"<<std::endl; } break; case 't': { kevinSound.trigger(); } break; case 'p': { kevinSound.pause(); } break; case 's': { kevinSound.stop(); } break; case ',': { soundpos -= 1; kevinSound.setPosition( soundpos, 0, 0 ); std::cout<<"soundpos: "<<soundpos<<std::endl; } break; case '.': { soundpos += 1; kevinSound.setPosition( soundpos, 0, 0 ); std::cout<<"soundpos: "<<soundpos<<std::endl; } break; case '[': { pitchbend -= 0.1; kevinSound.setPitchBend( pitchbend ); std::cout<<"pitchbend: "<<pitchbend<<std::endl; } break; case ']': { pitchbend += 0.1; kevinSound.setPitchBend( pitchbend ); std::cout<<"pitchbend: "<<pitchbend<<std::endl; } break; case ';': { cutoff -= 0.01; kevinSound.setCutoff( cutoff ); std::cout<<"Cutoff: "<<cutoff<<std::endl; } break; case '\'': { cutoff += 0.01; kevinSound.setCutoff( cutoff ); std::cout<<"Cutoff: "<<cutoff<<std::endl; } break; case '-': { volume -= 0.1; kevinSound.setVolume( volume ); std::cout<<"volume: "<<volume<<std::endl; } break; case '=': { volume += 0.1; kevinSound.setVolume( volume ); std::cout<<"volume: "<<volume<<std::endl; } break; default: // do nothing if no key is pressed break; } } //////////////////////////////// // This is called on a Up Keypress //////////////////////////////// static void OnKeyboardUp( unsigned char k, int x, int y ) { switch (k) { case 'a': // !!!TODO!!!: add handler for when UP is released break; case 'z': // !!!TODO!!!: add handler for when DOWN is released break; default: // do nothing if no key is pressed break; } } //////////////////////////////// // This is called on a Down Keypress // of a "special" key such as the grey arrows. //////////////////////////////// static void OnSpecialKeyboardDown(int k, int x, int y) { switch (k) { case GLUT_KEY_UP: // !!!TODO!!!: add handler for when UP is pressed break; case GLUT_KEY_DOWN: // !!!TODO!!!: add handler for when DOWN is pressed break; default: // do nothing if no special key pressed break; } } //////////////////////////////// // This is called on a Up Keypress //////////////////////////////// static void OnSpecialKeyboardUp( int k, int x, int y ) { switch (k) { case GLUT_KEY_UP: // !!!TODO!!!: add handler for when UP is released break; case GLUT_KEY_DOWN: // !!!TODO!!!: add handler for when DOWN is released break; default: // do nothing if no special key pressed break; } } //////////////////////////////// // This is called when mouse changes position // x and y are the screen position // in your 2D window's coordinate frame //////////////////////////////// static void OnMousePos( int x, int y ) { // !!!TODO!!!: do something based on mouse position } //////////////////////////////// // This is called when mouse clicks //////////////////////////////// static void OnMouseClick( int a, int b, int c, int d ) { // !!!TODO!!!: Need mouse interaction? // read the glut docs/manpage to find out how to query // which button was pressed... // you may have to get this from the glut website // (use www.google.com to search for it) } // Initialize the application // initialize the state of your app here if needed... static void OnApplicationInit() { // Don't put open GL code here, this func may be called at anytime // even before the API is initialized // (like before a graphics context is obtained) kevinSound.init( "kevin" ); stopWatch.pulse(); } int main(int argc, char* argv[]) { // Initialize the application // initialize the state of your app here if needed... OnApplicationInit(); // Set the window's initial size ::glutInitWindowSize( 640, 480 ); ::glutInit( &argc, argv ); // Set to double buffer to reduce flicker ::glutInitDisplayMode( GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE ); // Set the window title AppWindow::mainWin_contextID = ::glutCreateWindow( "GLUT application" ); cout<<"\n"<<flush; cout<<"sonix sample OpenGL+sound app - by kevin - kevn@vrjuggler.org\n"<<flush; cout<<" usage: t - trigger\n"<<flush; cout<<" p - pause\n"<<flush; cout<<" s - stop\n"<<flush; cout<<" , - put 3d sound source to the left\n"<<flush; cout<<" . - put 3d sound source to the right\n"<<flush; cout<<" 1 - Change subsystem to OpenAL\n"<<flush; cout<<" 2 - Change subsystem to AudioWorks\n"<<flush; cout<<" 3 - Change subsystem to None\n"<<flush; cout<<" a - configure sound object to sample.wav (OpenAL only)\n"<<flush; cout<<" b - configure sound object to drumsolo.wav (OpenAL only)\n"<<flush; cout<<"\n"<<flush; // display callbacks. ::glutReshapeFunc( OnReshape ); ::glutIdleFunc( OnIdle ); ::glutDisplayFunc( OnRedisplay ); // tell glut to not call the keyboard callback repeatedly // when holding down a key. (uses edge triggering, like the mouse) ::glutIgnoreKeyRepeat( 1 ); // keyboard callback functions. ::glutKeyboardFunc( OnKeyboardDown ); ::glutKeyboardUpFunc( OnKeyboardUp ); ::glutSpecialFunc( OnSpecialKeyboardDown ); ::glutSpecialUpFunc( OnSpecialKeyboardUp ); // mouse callback functions... ::glutMouseFunc( OnMouseClick ); ::glutMotionFunc( OnMousePos ); ::glutPassiveMotionFunc( OnMousePos ); // start the application loop, your callbacks will now be called // time for glut to sit and spin. ::glutMainLoop(); return 1; } <commit_msg>look for wav files in current dir. this means you'll have to ln -s them here ... :(<commit_after> /*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998, 1999, 2000, 2001 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * 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; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ /****************** <SNX heading BEGIN do not edit this line> ***************** * * Juggler Juggler * * Original Authors: * Kevin Meinert, Carolina Cruz-Neira * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * ****************** <SNX heading END do not edit this line> ******************/ // Kevin Meinert // simple glut skeleton application: look for the !!!TODO!!!s, // and fill in your code // there as needed // #ifdef WIN32 #include <windows.h> // make the app win32 friendly. :) #endif #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #include <snx/sonix.h> // interface #include <snx/SoundHandle.h> #include "StopWatch.h" #include <iostream.h> #include <stdlib.h> // a place to store application data... class AppWindow { public: static int width, height; static int mainWin_contextID; }; int AppWindow::width = 0, AppWindow::height = 0; int AppWindow::mainWin_contextID = -1; StopWatch stopWatch; int soundpos = 0; float pitchbend = 1.0f; float cutoff = 0.2f; float volume = 1.0f; // our sound object... snx::SoundHandle kevinSound; void drawGrid() { glBegin( GL_LINES ); for ( int x = -1000; x < 1000; ++x) { glVertex3f( -1000, 0, x ); glVertex3f( 1000, 0, x ); glVertex3f( x, 0, -1000 ); glVertex3f( x, 0, 1000 ); } glEnd(); } ////////////////////////////////////////////////// // This is called on a glutPostRedisplay ////////////////////////////////////////////////// static void OnRedisplay() { glClearColor( 0.0f, 0.0f, 0.0f, 1.0f ); glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT ); glEnable( GL_DEPTH_TEST ); glEnable( GL_BLEND ); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); // set up the projection matrix glMatrixMode( GL_PROJECTION ); glLoadIdentity(); gluPerspective( 80.0f, AppWindow::width / AppWindow::height, 0.01f, 1000.0f ); // initialize your matrix stack used for transforming your models glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); // !!!TODO!!!: replace the following with your own opengl commands! glTranslatef( 0, -10, 0 ); drawGrid(); // !!!TODO!!!: //////////////////////////////////////// // swaps the front and back frame buffers. // hint: you've been drawing on the back, offscreen, buffer. // This command then brings that framebuffer onscreen. glutSwapBuffers(); } ////////////////////////////////////////////////// // This is called repeatedly, as fast as possible ////////////////////////////////////////////////// #include "unistd.h" static void OnIdle() { // According to the GLUT specification, the current window is // undefined during an idle callback. So we need to explicitly change // it if necessary if ( glutGetWindow() != AppWindow::mainWin_contextID ) glutSetWindow( AppWindow::mainWin_contextID ); // tell glut to call redisplay (which then calls OnRedisplay) glutPostRedisplay(); sonix::instance()->step( stopWatch.timeInstant() ); stopWatch.pulse(); } ///////////////////////////////////////////// // This is called on a Resize of the glut window ///////////////////////////////////////////// static void OnReshape( int width, int height ) { // save these params in case your app needs them AppWindow::width = width; AppWindow::height = height; // set your viewport to the extents of the window glViewport( 0, 0, width, height ); // let the app run idle, while resizing, // glut does not do this for us automatically, so call OnIdle explicitly. OnIdle(); } //////////////////////////////// // This is called on a Down Keypress //////////////////////////////// static void OnKeyboardDown( unsigned char k, int x, int y ) { switch (k) { // If user pressed 'q' or 'ESC', then exit the app. // this is really ungraceful, but necessary since GLUT does a while(1) // as it's control loop. There is no GLUT method to exit, unfortunately. case 'q': case 27: exit( 0 ); break; case '1': { sonix::instance()->changeAPI( "Stub" ); snx::SoundInfo si; si.filename = "sol.wav"; si.ambient = false; si.datasource = snx::SoundInfo::FILESYSTEM; kevinSound.configure( si ); sonix::instance()->changeAPI( "OpenAL" ); } break; case '2': { sonix::instance()->changeAPI( "Stub" ); snx::SoundInfo si; si.filename = "sep.wav"; si.ambient = false; si.datasource = snx::SoundInfo::FILESYSTEM; kevinSound.configure( si ); sonix::instance()->changeAPI( "AudioWorks" ); } break; case '3': { sonix::instance()->changeAPI( "Stub" ); } break; case 'a': { snx::SoundInfo si; si.ambient = false; si.filename = "sol.wav"; si.datasource = snx::SoundInfo::FILESYSTEM; kevinSound.configure( si ); std::cout<<"positional"<<std::endl; } break; case 'b': { snx::SoundInfo si; si.ambient = true; si.filename = "sep.wav"; si.datasource = snx::SoundInfo::FILESYSTEM; kevinSound.configure( si ); kevinSound.setAmbient( true ); std::cout<<"ambient"<<std::endl; } break; case 'c': { snx::SoundInfo si; si.ambient = false; si.filename = "suck.wav"; si.datasource = snx::SoundInfo::FILESYSTEM; kevinSound.configure( si ); std::cout<<"positional"<<std::endl; } break; case 't': { kevinSound.trigger(); } break; case 'p': { kevinSound.pause(); } break; case 's': { kevinSound.stop(); } break; case ',': { soundpos -= 1; kevinSound.setPosition( soundpos, 0, 0 ); std::cout<<"soundpos: "<<soundpos<<std::endl; } break; case '.': { soundpos += 1; kevinSound.setPosition( soundpos, 0, 0 ); std::cout<<"soundpos: "<<soundpos<<std::endl; } break; case '[': { pitchbend -= 0.1; kevinSound.setPitchBend( pitchbend ); std::cout<<"pitchbend: "<<pitchbend<<std::endl; } break; case ']': { pitchbend += 0.1; kevinSound.setPitchBend( pitchbend ); std::cout<<"pitchbend: "<<pitchbend<<std::endl; } break; case ';': { cutoff -= 0.01; kevinSound.setCutoff( cutoff ); std::cout<<"Cutoff: "<<cutoff<<std::endl; } break; case '\'': { cutoff += 0.01; kevinSound.setCutoff( cutoff ); std::cout<<"Cutoff: "<<cutoff<<std::endl; } break; case '-': { volume -= 0.1; kevinSound.setVolume( volume ); std::cout<<"volume: "<<volume<<std::endl; } break; case '=': { volume += 0.1; kevinSound.setVolume( volume ); std::cout<<"volume: "<<volume<<std::endl; } break; default: // do nothing if no key is pressed break; } } //////////////////////////////// // This is called on a Up Keypress //////////////////////////////// static void OnKeyboardUp( unsigned char k, int x, int y ) { switch (k) { case 'a': // !!!TODO!!!: add handler for when UP is released break; case 'z': // !!!TODO!!!: add handler for when DOWN is released break; default: // do nothing if no key is pressed break; } } //////////////////////////////// // This is called on a Down Keypress // of a "special" key such as the grey arrows. //////////////////////////////// static void OnSpecialKeyboardDown(int k, int x, int y) { switch (k) { case GLUT_KEY_UP: // !!!TODO!!!: add handler for when UP is pressed break; case GLUT_KEY_DOWN: // !!!TODO!!!: add handler for when DOWN is pressed break; default: // do nothing if no special key pressed break; } } //////////////////////////////// // This is called on a Up Keypress //////////////////////////////// static void OnSpecialKeyboardUp( int k, int x, int y ) { switch (k) { case GLUT_KEY_UP: // !!!TODO!!!: add handler for when UP is released break; case GLUT_KEY_DOWN: // !!!TODO!!!: add handler for when DOWN is released break; default: // do nothing if no special key pressed break; } } //////////////////////////////// // This is called when mouse changes position // x and y are the screen position // in your 2D window's coordinate frame //////////////////////////////// static void OnMousePos( int x, int y ) { // !!!TODO!!!: do something based on mouse position } //////////////////////////////// // This is called when mouse clicks //////////////////////////////// static void OnMouseClick( int a, int b, int c, int d ) { // !!!TODO!!!: Need mouse interaction? // read the glut docs/manpage to find out how to query // which button was pressed... // you may have to get this from the glut website // (use www.google.com to search for it) } // Initialize the application // initialize the state of your app here if needed... static void OnApplicationInit() { // Don't put open GL code here, this func may be called at anytime // even before the API is initialized // (like before a graphics context is obtained) kevinSound.init( "kevin" ); stopWatch.pulse(); } int main(int argc, char* argv[]) { // Initialize the application // initialize the state of your app here if needed... OnApplicationInit(); // Set the window's initial size ::glutInitWindowSize( 640, 480 ); ::glutInit( &argc, argv ); // Set to double buffer to reduce flicker ::glutInitDisplayMode( GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE ); // Set the window title AppWindow::mainWin_contextID = ::glutCreateWindow( "GLUT application" ); cout<<"\n"<<flush; cout<<"sonix sample OpenGL+sound app - by kevin - kevn@vrjuggler.org\n"<<flush; cout<<" usage: t - trigger\n"<<flush; cout<<" p - pause\n"<<flush; cout<<" s - stop\n"<<flush; cout<<" , - put 3d sound source to the left\n"<<flush; cout<<" . - put 3d sound source to the right\n"<<flush; cout<<" 1 - Change subsystem to OpenAL\n"<<flush; cout<<" 2 - Change subsystem to AudioWorks\n"<<flush; cout<<" 3 - Change subsystem to None\n"<<flush; cout<<" a - configure sound object to sample.wav (OpenAL only)\n"<<flush; cout<<" b - configure sound object to drumsolo.wav (OpenAL only)\n"<<flush; cout<<"\n"<<flush; // display callbacks. ::glutReshapeFunc( OnReshape ); ::glutIdleFunc( OnIdle ); ::glutDisplayFunc( OnRedisplay ); // tell glut to not call the keyboard callback repeatedly // when holding down a key. (uses edge triggering, like the mouse) ::glutIgnoreKeyRepeat( 1 ); // keyboard callback functions. ::glutKeyboardFunc( OnKeyboardDown ); ::glutKeyboardUpFunc( OnKeyboardUp ); ::glutSpecialFunc( OnSpecialKeyboardDown ); ::glutSpecialUpFunc( OnSpecialKeyboardUp ); // mouse callback functions... ::glutMouseFunc( OnMouseClick ); ::glutMotionFunc( OnMousePos ); ::glutPassiveMotionFunc( OnMousePos ); // start the application loop, your callbacks will now be called // time for glut to sit and spin. ::glutMainLoop(); return 1; } <|endoftext|>
<commit_before>// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_FEMEOC_HH #define DUNE_STUFF_FEMEOC_HH #if HAVE_DUNE_FEM #include <cassert> #include <sstream> #include <fstream> #include <vector> #include <limits> #include <boost/format.hpp> #include <boost/numeric/conversion/cast.hpp> #include <dune/common/fvector.hh> #include <dune/fem/io/file/iointerface.hh> namespace Dune { namespace Stuff { namespace Fem { /** * @ingroup HelperClasses * \brief Write a self contained tex table * for eoc runs with timing information. * * Constructor takes base name (filename) of file and * generates two files: * filename.tex and filename_body.tex. * The file filename_body.tex hold the actual body * of the eoc table which is included in filename.tex * but can also be used to combine e.g. runs with different * parameters or for plotting using gnuplot. * * The class is singleton and thus new errors for eoc * computations can be added in any part of the program. * To add a new entry for eoc computations use one of the * addEntry methods. These return a unique unsinged int * which can be used to add error values to the table * with the setErrors methods. * The method write is used to write a single line * to the eoc table. * \note copy/paste from fem with certain adjustments */ class FemEoc { std::ofstream outputFile_; int level_; std::vector< double > prevError_; std::vector< double > error_; std::vector< std::string > description_; double prevh_; bool initial_; std::vector< int > pos_; FemEoc(); void init(const std::string& path, const std::string& name, const std::string& descript, const std::string& inputFile); void init(const std::string& name, const std::string& descript, const std::string& inputFile); template< class VectorType > void seterrors(size_t id, const VectorType& err, size_t size) { int pos = pos_[id]; for (size_t i = 0; i < size; ++i) error_[pos + i] = err[i]; } template< int SIZE > void seterrors(size_t id, const Dune::FieldVector< double, SIZE >& err) { int pos = pos_[id]; for (int i = 0; i < SIZE; ++i) error_[pos + i] = err[i]; } void seterrors(size_t id, const double& err); void writeerr(double h, double size, double time, int counter); template< class Writer > void writeerr(Writer& writer, bool last) { if (initial_) { writer.putHeader(outputFile_); } writer.putStaticCols(outputFile_); for (size_t i = 0; i < 2; ++i) { writer.putErrorCol(outputFile_, prevError_[i], error_[i], prevh_, initial_); prevError_[i] = error_[i]; error_[i] = -1; // uninitialized } writer.putLineEnd(outputFile_); if (last) writer.endTable(outputFile_); prevh_ = writer.get_h(); level_++; initial_ = false; } // writeerr template< class StrVectorType > size_t addentry(const StrVectorType& descript, size_t size) { if (!initial_) DUNE_THROW(Dune::InvalidStateException, ""); assert(error_.size() < std::numeric_limits< int >::max()); pos_.push_back( boost::numeric_convertion< int >(error_.size()) ); for (size_t i = 0; i < size; ++i) { error_.push_back(0); prevError_.push_back(0); description_.push_back(descript[i]); } return pos_.size() - 1; } // addentry size_t addentry(const std::string& descript); public: ~FemEoc(); static FemEoc& instance() { static FemEoc instance_; return instance_; } //! open file path/name and write a description string into tex file static void initialize(const std::string& path, const std::string& name, const std::string& descript, const std::string& templateFilename) { instance().init(path, name, descript, templateFilename); } //! open file name and write description string into tex file static void initialize(const std::string& name, const std::string& descript, const std::string& templateFilename) { instance().init(name, descript, templateFilename); } /** \brief add a vector of new eoc values * * \tparam StrVectorType a vector type with operator[] * returning a string (a C style array can be used) * the size of the vector is given as parameter * \return a unique index used to add the error values */ template< class StrVectorType > static size_t addEntry(const StrVectorType& descript, size_t size) { return instance().addentry(descript, size); } /** \brief add a vector of new eoc values * * \tparam StrVectorType a vector type with size() and operator[] * returning a string * \return a unique index used to add the error values */ template< class StrVectorType > static size_t addEntry(const StrVectorType& descript) { return instance().addentry( descript, descript.size() ); } /** \brief add a single new eoc output * * \return a unique index used to add the error values */ static size_t addEntry(const std::string& descript) { return instance().addentry(descript); } /** \brief add a single new eoc output * * \return a unique index used to add the error values */ static size_t addEntry(const char* descript) { return addEntry( std::string(descript) ); } /** \brief add a vector of error values for the given id (returned by * addEntry) * \tparam VectorType a vector type with an operator[] * returning a double (C style array can be used) */ template< class VectorType > static void setErrors(size_t id, const VectorType& err, int size) { instance().seterrors(id, err, size); } /** \brief add a vector of error values for the given id (returned bywrite(GridWidth::calcGridWidth(gridPart), * grid.size(0),runTime,0); * * addEntry) * \tparam VectorType a vector type with a size() and an operator[] * returning a double */ template< class VectorType > static void setErrors(size_t id, const VectorType& err) { instance().seterrors( id, err, err.size() ); } /** \brief add a vector in a FieldVector of error values for the given id (returned by * addEntry) */ template< int SIZE > static void setErrors(size_t id, const Dune::FieldVector< double, SIZE >& err) { instance().seterrors(id, err); } /** \brief add a single error value for the given id (returned by * addEntry) */ static void setErrors(size_t id, const double& err) { instance().seterrors(id, err); } /** \brief commit a line to the eoc file */ static void write(double h, double size, double time, int counter) { instance().writeerr(h, size, time, counter); } template< class Writer > static void write(Writer& writer, bool last = false) { instance().writeerr(writer, last); } }; } // namespace Stuff } // namespace Fem } // namespace Dune #endif // HAVE_DUNE_FEM #endif // ifndef DUNE_STUFF_FEMEOC_HH <commit_msg>[femfemeoc] remove useless code<commit_after>// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_FEMEOC_HH #define DUNE_STUFF_FEMEOC_HH #if HAVE_DUNE_FEM #include <cassert> #include <sstream> #include <fstream> #include <vector> #include <limits> #include <boost/format.hpp> #include <boost/numeric/conversion/cast.hpp> #include <dune/common/fvector.hh> #include <dune/fem/io/file/iointerface.hh> namespace Dune { namespace Stuff { namespace Fem { /** * @ingroup HelperClasses * \brief Write a self contained tex table * for eoc runs with timing information. * * Constructor takes base name (filename) of file and * generates two files: * filename.tex and filename_body.tex. * The file filename_body.tex hold the actual body * of the eoc table which is included in filename.tex * but can also be used to combine e.g. runs with different * parameters or for plotting using gnuplot. * * The class is singleton and thus new errors for eoc * computations can be added in any part of the program. * To add a new entry for eoc computations use one of the * addEntry methods. These return a unique unsinged int * which can be used to add error values to the table * with the setErrors methods. * The method write is used to write a single line * to the eoc table. * \note copy/paste from fem with certain adjustments */ class FemEoc { std::ofstream outputFile_; int level_; std::vector< double > prevError_; std::vector< double > error_; std::vector< std::string > description_; double prevh_; bool initial_; std::vector< int > pos_; FemEoc(); void init(const std::string& path, const std::string& name, const std::string& descript, const std::string& inputFile); void init(const std::string& name, const std::string& descript, const std::string& inputFile); template< class VectorType > void seterrors(size_t id, const VectorType& err, size_t size) { int pos = pos_[id]; for (size_t i = 0; i < size; ++i) error_[pos + i] = err[i]; } template< int SIZE > void seterrors(size_t id, const Dune::FieldVector< double, SIZE >& err) { int pos = pos_[id]; for (int i = 0; i < SIZE; ++i) error_[pos + i] = err[i]; } void seterrors(size_t id, const double& err); void writeerr(double h, double size, double time, int counter); template< class Writer > void writeerr(Writer& writer, bool last) { if (initial_) { writer.putHeader(outputFile_); } writer.putStaticCols(outputFile_); for (size_t i = 0; i < 2; ++i) { writer.putErrorCol(outputFile_, prevError_[i], error_[i], prevh_, initial_); prevError_[i] = error_[i]; error_[i] = -1; // uninitialized } writer.putLineEnd(outputFile_); if (last) writer.endTable(outputFile_); prevh_ = writer.get_h(); level_++; initial_ = false; } // writeerr template< class StrVectorType > size_t addentry(const StrVectorType& descript, size_t size) { if (!initial_) DUNE_THROW(Dune::InvalidStateException, ""); pos_.push_back( boost::numeric_convertion< int >(error_.size()) ); for (size_t i = 0; i < size; ++i) { error_.push_back(0); prevError_.push_back(0); description_.push_back(descript[i]); } return pos_.size() - 1; } // addentry size_t addentry(const std::string& descript); public: ~FemEoc(); static FemEoc& instance() { static FemEoc instance_; return instance_; } //! open file path/name and write a description string into tex file static void initialize(const std::string& path, const std::string& name, const std::string& descript, const std::string& templateFilename) { instance().init(path, name, descript, templateFilename); } //! open file name and write description string into tex file static void initialize(const std::string& name, const std::string& descript, const std::string& templateFilename) { instance().init(name, descript, templateFilename); } /** \brief add a vector of new eoc values * * \tparam StrVectorType a vector type with operator[] * returning a string (a C style array can be used) * the size of the vector is given as parameter * \return a unique index used to add the error values */ template< class StrVectorType > static size_t addEntry(const StrVectorType& descript, size_t size) { return instance().addentry(descript, size); } /** \brief add a vector of new eoc values * * \tparam StrVectorType a vector type with size() and operator[] * returning a string * \return a unique index used to add the error values */ template< class StrVectorType > static size_t addEntry(const StrVectorType& descript) { return instance().addentry( descript, descript.size() ); } /** \brief add a single new eoc output * * \return a unique index used to add the error values */ static size_t addEntry(const std::string& descript) { return instance().addentry(descript); } /** \brief add a single new eoc output * * \return a unique index used to add the error values */ static size_t addEntry(const char* descript) { return addEntry( std::string(descript) ); } /** \brief add a vector of error values for the given id (returned by * addEntry) * \tparam VectorType a vector type with an operator[] * returning a double (C style array can be used) */ template< class VectorType > static void setErrors(size_t id, const VectorType& err, int size) { instance().seterrors(id, err, size); } /** \brief add a vector of error values for the given id (returned bywrite(GridWidth::calcGridWidth(gridPart), * grid.size(0),runTime,0); * * addEntry) * \tparam VectorType a vector type with a size() and an operator[] * returning a double */ template< class VectorType > static void setErrors(size_t id, const VectorType& err) { instance().seterrors( id, err, err.size() ); } /** \brief add a vector in a FieldVector of error values for the given id (returned by * addEntry) */ template< int SIZE > static void setErrors(size_t id, const Dune::FieldVector< double, SIZE >& err) { instance().seterrors(id, err); } /** \brief add a single error value for the given id (returned by * addEntry) */ static void setErrors(size_t id, const double& err) { instance().seterrors(id, err); } /** \brief commit a line to the eoc file */ static void write(double h, double size, double time, int counter) { instance().writeerr(h, size, time, counter); } template< class Writer > static void write(Writer& writer, bool last = false) { instance().writeerr(writer, last); } }; } // namespace Stuff } // namespace Fem } // namespace Dune #endif // HAVE_DUNE_FEM #endif // ifndef DUNE_STUFF_FEMEOC_HH <|endoftext|>
<commit_before>/** * @file CameraMatrixProvider.cpp * * @author <a href="mailto:mellmann@informatik.hu-berlin.de">Heinrich Mellmann</a> * Implementation of class CameraMatrixProvider */ #include "CameraMatrixCorrectorV2.h" CameraMatrixCorrectorV2::CameraMatrixCorrectorV2() { DEBUG_REQUEST_REGISTER("CameraMatrixV2:calibrate_camera_matrix_line_matching", "calculates the roll and tilt offset of the camera using field lines (it. shoult be exactely 3000mm in front of the robot)", false); DEBUG_REQUEST_REGISTER("CameraMatrixV2:reset_calibration", "set the calibration offsets of the CM to 0", false); DEBUG_REQUEST_REGISTER("CameraMatrixV2:collect_calibration_data", "collect the data for calibration", false); DEBUG_REQUEST_REGISTER("CameraMatrixV2:clear_calibration_data", "clears the data used for calibration", false); DEBUG_REQUEST_REGISTER("CameraMatrixV2:enable_CamMatErrorFunction_drawings", "needed to be activated for error function drawings", false); theCamMatErrorFunction = registerModule<CamMatErrorFunction>("CamMatErrorFunction", true); last_idx_yaw = 0; last_idx_pitch = 0; damping = 0.1; head_state = look_left; last_head_state = initial; } CameraMatrixCorrectorV2::~CameraMatrixCorrectorV2() { } void CameraMatrixCorrectorV2::execute() { DEBUG_REQUEST("CameraMatrixV2:clear_calibration_data", (theCamMatErrorFunction->getModuleT())->calibrationData.clear(); ); bool collect_data = false; DEBUG_REQUEST("CameraMatrixV2:collect_calibration_data", collect_data = true; ); DEBUG_REQUEST_ON_DEACTIVE("CameraMatrixV2:collect_calibration_data", head_state = look_left; last_head_state = initial; ); if(collect_data){ // head control states getHeadMotionRequest().id = HeadMotionRequest::goto_angle; double yaw = 0; double pitch = 0; bool target_reached = false; switch (head_state){ case look_left: yaw = 88; pitch = 0; break; case look_right: yaw = -88; pitch = 0; break; case look_left_down: yaw = 88; pitch = -14; break; case look_right_down: yaw = -88; pitch = -14; break; default: break; } getHeadMotionRequest().id = HeadMotionRequest::goto_angle; getHeadMotionRequest().targetJointPosition.x = Math::fromDegrees(yaw); getHeadMotionRequest().targetJointPosition.y = Math::fromDegrees(pitch); getHeadMotionRequest().velocity = 30; // state transitions target_reached = (fabs(Math::toDegrees(getSensorJointData().position[JointData::HeadYaw]) - yaw) < 1) && (fabs(Math::toDegrees(getSensorJointData().position[JointData::HeadPitch]) - pitch) < 1); if(target_reached){ if(head_state == look_left && last_head_state == initial){ head_state = look_right; last_head_state = look_left; } else if (head_state == look_right && last_head_state == look_left){ head_state = look_left; last_head_state = look_right; } else if (head_state == look_left && last_head_state == look_right){ head_state = look_left_down; last_head_state = look_left; } else if (head_state == look_left_down && last_head_state == look_left){ head_state = look_right_down; last_head_state = look_left_down; } else if (head_state == look_right_down && last_head_state == look_left_down){ head_state = look_left_down; last_head_state = look_right_down; } else if (head_state == look_left_down && last_head_state == look_right_down){ head_state = look_left; last_head_state = look_left_down; } else if (head_state == look_left && last_head_state == look_left_down){ head_state = look_right; last_head_state = look_left; } } // collecting data if(last_head_state != initial) { CamMatErrorFunction::CalibrationData& c_data = (theCamMatErrorFunction->getModuleT())->calibrationData; int current_index_yaw = static_cast<int>((Math::toDegrees(getSensorJointData().position[JointData::HeadYaw])/20.0) + 0.5); int current_index_pitch = static_cast<int>((Math::toDegrees(getSensorJointData().position[JointData::HeadPitch])/5.0) + 0.5); std::pair<int,int> index; index.first = current_index_yaw; index.second = current_index_pitch; if(last_idx_pitch != current_index_pitch || last_idx_yaw != current_index_yaw) { std::vector<CamMatErrorFunction::CalibrationDataSample>& data = c_data[index]; data.push_back((struct CamMatErrorFunction::CalibrationDataSample){getKinematicChain().theLinks[KinematicChain::Torso].M, getLineGraphPercept(),getInertialModel(), getSensorJointData().position[JointData::HeadYaw], getSensorJointData().position[JointData::HeadPitch] }); // c_data[index].chestPose = getKinematicChain().theLinks[KinematicChain::Torso].M; // c_data[index].lineGraphPercept = getLineGraphPercept(); // c_data[index].headYaw = getSensorJointData().position[JointData::HeadYaw]; // c_data[index].headPitch = getSensorJointData().position[JointData::HeadPitch]; // c_data[index].inertialModel = getInertialModel(); last_idx_pitch = current_index_pitch; last_idx_yaw = current_index_yaw; } } } MODIFY("CameraMatrixV2:OffsetRollTop",getCameraMatrixOffset().correctionOffset[naoth::CameraInfo::Top].x); MODIFY("CameraMatrixV2:OffsetTiltTop",getCameraMatrixOffset().correctionOffset[naoth::CameraInfo::Top].y); MODIFY("CameraMatrixV2:OffsetRollBottom",getCameraMatrixOffset().correctionOffset[naoth::CameraInfo::Bottom].x); MODIFY("CameraMatrixV2:OffsetTiltBottom",getCameraMatrixOffset().correctionOffset[naoth::CameraInfo::Bottom].y); MODIFY("CameraMatrixV2:Body:Roll", getCameraMatrixOffset().body_rot.x); MODIFY("CameraMatrixV2:Body:Pitch", getCameraMatrixOffset().body_rot.y); MODIFY("CameraMatrixV2:Head:Roll", getCameraMatrixOffset().head_rot.x); MODIFY("CameraMatrixV2:Head:Pitch", getCameraMatrixOffset().head_rot.y); MODIFY("CameraMatrixV2:Head:Yaw", getCameraMatrixOffset().head_rot.z); MODIFY("CameraMatrixV2:Cam:Top:Roll", getCameraMatrixOffset().cam_rot[naoth::CameraInfo::Top].x); MODIFY("CameraMatrixV2:Cam:Top:Pitch", getCameraMatrixOffset().cam_rot[naoth::CameraInfo::Top].y); MODIFY("CameraMatrixV2:Cam:Top:Yaw", getCameraMatrixOffset().cam_rot[naoth::CameraInfo::Top].z); MODIFY("CameraMatrixV2:Cam:Bottom:Roll", getCameraMatrixOffset().cam_rot[naoth::CameraInfo::Bottom].x); MODIFY("CameraMatrixV2:Cam:Bottom:Pitch", getCameraMatrixOffset().cam_rot[naoth::CameraInfo::Bottom].y); MODIFY("CameraMatrixV2:Cam:Bottom:Yaw", getCameraMatrixOffset().cam_rot[naoth::CameraInfo::Bottom].z); DEBUG_REQUEST("CameraMatrixV2:enable_CamMatErrorFunction_drawings", theCamMatErrorFunction->getModuleT()->plot_CalibrationData(); ); DEBUG_REQUEST("CameraMatrixV2:calibrate_camera_matrix_line_matching", calibrate(); ); DEBUG_REQUEST_ON_DEACTIVE("CameraMatrixV2:calibrate_camera_matrix_line_matching", getCameraMatrixOffset().saveToConfig(); ); DEBUG_REQUEST("CameraMatrixV2:reset_calibration", reset_calibration(); ); DEBUG_REQUEST_ON_DEACTIVE("CameraMatrixV2:reset_calibration", getCameraMatrixOffset().saveToConfig(); ); }//end execute void CameraMatrixCorrectorV2::reset_calibration() { getCameraMatrixOffset().body_rot = Vector2d(); getCameraMatrixOffset().head_rot = Vector3d(); getCameraMatrixOffset().cam_rot[CameraInfo::Top] = Vector3d(); getCameraMatrixOffset().cam_rot[CameraInfo::Bottom] = Vector3d(); } void CameraMatrixCorrectorV2::calibrate() { // calibrate the camera matrix Eigen::Matrix<double, 11, 1> offset; offset = gn_minimizer.minimizeOneStep(*(theCamMatErrorFunction->getModuleT()),1e-4); MODIFY("CameraMatrixV2:damping_factor", damping); getCameraMatrixOffset().body_rot = getCameraMatrixOffset().body_rot * (1-damping) + (getCameraMatrixOffset().body_rot + Vector2d(offset(0),offset(1))) * damping; getCameraMatrixOffset().head_rot = getCameraMatrixOffset().head_rot * (1-damping) + (getCameraMatrixOffset().head_rot + Vector3d(offset(2),offset(3),offset(4))) * damping; getCameraMatrixOffset().cam_rot[CameraInfo::Top] = getCameraMatrixOffset().cam_rot[CameraInfo::Top] * (1-damping) + (getCameraMatrixOffset().cam_rot[CameraInfo::Top] + Vector3d(offset(5),offset(6),offset(7))) * damping; getCameraMatrixOffset().cam_rot[CameraInfo::Bottom] = getCameraMatrixOffset().cam_rot[CameraInfo::Bottom] * (1-damping) + (getCameraMatrixOffset().cam_rot[CameraInfo::Bottom] + Vector3d(offset(8),offset(9),offset(10))) * damping; }//end calibrate <commit_msg>increase number of horizontal bins change pitch angle in collecting stuff<commit_after>/** * @file CameraMatrixProvider.cpp * * @author <a href="mailto:mellmann@informatik.hu-berlin.de">Heinrich Mellmann</a> * Implementation of class CameraMatrixProvider */ #include "CameraMatrixCorrectorV2.h" CameraMatrixCorrectorV2::CameraMatrixCorrectorV2() { DEBUG_REQUEST_REGISTER("CameraMatrixV2:calibrate_camera_matrix_line_matching", "calculates the roll and tilt offset of the camera using field lines (it. shoult be exactely 3000mm in front of the robot)", false); DEBUG_REQUEST_REGISTER("CameraMatrixV2:reset_calibration", "set the calibration offsets of the CM to 0", false); DEBUG_REQUEST_REGISTER("CameraMatrixV2:collect_calibration_data", "collect the data for calibration", false); DEBUG_REQUEST_REGISTER("CameraMatrixV2:clear_calibration_data", "clears the data used for calibration", false); DEBUG_REQUEST_REGISTER("CameraMatrixV2:enable_CamMatErrorFunction_drawings", "needed to be activated for error function drawings", false); theCamMatErrorFunction = registerModule<CamMatErrorFunction>("CamMatErrorFunction", true); last_idx_yaw = 0; last_idx_pitch = 0; damping = 0.1; head_state = look_left; last_head_state = initial; } CameraMatrixCorrectorV2::~CameraMatrixCorrectorV2() { } void CameraMatrixCorrectorV2::execute() { DEBUG_REQUEST("CameraMatrixV2:clear_calibration_data", (theCamMatErrorFunction->getModuleT())->calibrationData.clear(); ); bool collect_data = false; DEBUG_REQUEST("CameraMatrixV2:collect_calibration_data", collect_data = true; ); DEBUG_REQUEST_ON_DEACTIVE("CameraMatrixV2:collect_calibration_data", head_state = look_left; last_head_state = initial; getHeadMotionRequest().id = HeadMotionRequest::hold; ); if(collect_data){ // head control states double yaw = 0; double pitch = 0; bool target_reached = false; switch (head_state){ case look_left: yaw = 88; pitch = 0; break; case look_right: yaw = -88; pitch = 0; break; case look_left_down: yaw = 88; pitch = 10; break; case look_right_down: yaw = -88; pitch = 10; break; default: break; } getHeadMotionRequest().id = HeadMotionRequest::goto_angle; getHeadMotionRequest().targetJointPosition.x = Math::fromDegrees(yaw); getHeadMotionRequest().targetJointPosition.y = Math::fromDegrees(pitch); getHeadMotionRequest().velocity = 10; MODIFY("CameraMatrixV2:collecting_velocity", getHeadMotionRequest().velocity); // state transitions target_reached = (fabs(Math::toDegrees(getSensorJointData().position[JointData::HeadYaw]) - yaw) < 2) && (fabs(Math::toDegrees(getSensorJointData().position[JointData::HeadPitch]) - pitch) < 2); if(target_reached){ if(head_state == look_left && last_head_state == initial){ head_state = look_right; last_head_state = look_left; } else if (head_state == look_right && last_head_state == look_left){ head_state = look_left; last_head_state = look_right; } else if (head_state == look_left && last_head_state == look_right){ head_state = look_left_down; last_head_state = look_left; } else if (head_state == look_left_down && last_head_state == look_left){ head_state = look_right_down; last_head_state = look_left_down; } else if (head_state == look_right_down && last_head_state == look_left_down){ head_state = look_left_down; last_head_state = look_right_down; } else if (head_state == look_left_down && last_head_state == look_right_down){ head_state = look_left; last_head_state = look_left_down; } else if (head_state == look_left && last_head_state == look_left_down){ head_state = look_right; last_head_state = look_left; } } // collecting data if(last_head_state != initial) { CamMatErrorFunction::CalibrationData& c_data = (theCamMatErrorFunction->getModuleT())->calibrationData; int current_index_yaw = static_cast<int>((Math::toDegrees(getSensorJointData().position[JointData::HeadYaw])/15.0) + 0.5); int current_index_pitch = static_cast<int>((Math::toDegrees(getSensorJointData().position[JointData::HeadPitch])/5.0) + 0.5); std::pair<int,int> index; index.first = current_index_yaw; index.second = current_index_pitch; if(last_idx_pitch != current_index_pitch || last_idx_yaw != current_index_yaw) { std::vector<CamMatErrorFunction::CalibrationDataSample>& data = c_data[index]; data.push_back((struct CamMatErrorFunction::CalibrationDataSample){getKinematicChain().theLinks[KinematicChain::Torso].M, getLineGraphPercept(),getInertialModel(), getSensorJointData().position[JointData::HeadYaw], getSensorJointData().position[JointData::HeadPitch] }); // c_data[index].chestPose = getKinematicChain().theLinks[KinematicChain::Torso].M; // c_data[index].lineGraphPercept = getLineGraphPercept(); // c_data[index].headYaw = getSensorJointData().position[JointData::HeadYaw]; // c_data[index].headPitch = getSensorJointData().position[JointData::HeadPitch]; // c_data[index].inertialModel = getInertialModel(); last_idx_pitch = current_index_pitch; last_idx_yaw = current_index_yaw; } } } MODIFY("CameraMatrixV2:OffsetRollTop",getCameraMatrixOffset().correctionOffset[naoth::CameraInfo::Top].x); MODIFY("CameraMatrixV2:OffsetTiltTop",getCameraMatrixOffset().correctionOffset[naoth::CameraInfo::Top].y); MODIFY("CameraMatrixV2:OffsetRollBottom",getCameraMatrixOffset().correctionOffset[naoth::CameraInfo::Bottom].x); MODIFY("CameraMatrixV2:OffsetTiltBottom",getCameraMatrixOffset().correctionOffset[naoth::CameraInfo::Bottom].y); MODIFY("CameraMatrixV2:Body:Roll", getCameraMatrixOffset().body_rot.x); MODIFY("CameraMatrixV2:Body:Pitch", getCameraMatrixOffset().body_rot.y); MODIFY("CameraMatrixV2:Head:Roll", getCameraMatrixOffset().head_rot.x); MODIFY("CameraMatrixV2:Head:Pitch", getCameraMatrixOffset().head_rot.y); MODIFY("CameraMatrixV2:Head:Yaw", getCameraMatrixOffset().head_rot.z); MODIFY("CameraMatrixV2:Cam:Top:Roll", getCameraMatrixOffset().cam_rot[naoth::CameraInfo::Top].x); MODIFY("CameraMatrixV2:Cam:Top:Pitch", getCameraMatrixOffset().cam_rot[naoth::CameraInfo::Top].y); MODIFY("CameraMatrixV2:Cam:Top:Yaw", getCameraMatrixOffset().cam_rot[naoth::CameraInfo::Top].z); MODIFY("CameraMatrixV2:Cam:Bottom:Roll", getCameraMatrixOffset().cam_rot[naoth::CameraInfo::Bottom].x); MODIFY("CameraMatrixV2:Cam:Bottom:Pitch", getCameraMatrixOffset().cam_rot[naoth::CameraInfo::Bottom].y); MODIFY("CameraMatrixV2:Cam:Bottom:Yaw", getCameraMatrixOffset().cam_rot[naoth::CameraInfo::Bottom].z); DEBUG_REQUEST("CameraMatrixV2:enable_CamMatErrorFunction_drawings", theCamMatErrorFunction->getModuleT()->plot_CalibrationData(); ); DEBUG_REQUEST("CameraMatrixV2:calibrate_camera_matrix_line_matching", calibrate(); ); DEBUG_REQUEST_ON_DEACTIVE("CameraMatrixV2:calibrate_camera_matrix_line_matching", getCameraMatrixOffset().saveToConfig(); ); DEBUG_REQUEST("CameraMatrixV2:reset_calibration", reset_calibration(); ); DEBUG_REQUEST_ON_DEACTIVE("CameraMatrixV2:reset_calibration", getCameraMatrixOffset().saveToConfig(); ); }//end execute void CameraMatrixCorrectorV2::reset_calibration() { getCameraMatrixOffset().body_rot = Vector2d(); getCameraMatrixOffset().head_rot = Vector3d(); getCameraMatrixOffset().cam_rot[CameraInfo::Top] = Vector3d(); getCameraMatrixOffset().cam_rot[CameraInfo::Bottom] = Vector3d(); } void CameraMatrixCorrectorV2::calibrate() { // calibrate the camera matrix Eigen::Matrix<double, 11, 1> offset; offset = gn_minimizer.minimizeOneStep(*(theCamMatErrorFunction->getModuleT()),1e-4); MODIFY("CameraMatrixV2:damping_factor", damping); getCameraMatrixOffset().body_rot = getCameraMatrixOffset().body_rot * (1-damping) + (getCameraMatrixOffset().body_rot + Vector2d(offset(0),offset(1))) * damping; getCameraMatrixOffset().head_rot = getCameraMatrixOffset().head_rot * (1-damping) + (getCameraMatrixOffset().head_rot + Vector3d(offset(2),offset(3),offset(4))) * damping; getCameraMatrixOffset().cam_rot[CameraInfo::Top] = getCameraMatrixOffset().cam_rot[CameraInfo::Top] * (1-damping) + (getCameraMatrixOffset().cam_rot[CameraInfo::Top] + Vector3d(offset(5),offset(6),offset(7))) * damping; getCameraMatrixOffset().cam_rot[CameraInfo::Bottom] = getCameraMatrixOffset().cam_rot[CameraInfo::Bottom] * (1-damping) + (getCameraMatrixOffset().cam_rot[CameraInfo::Bottom] + Vector3d(offset(8),offset(9),offset(10))) * damping; }//end calibrate <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: itkImageToImageAffineMeanSquaresRegularStepGradientDescentRegistrationTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #include "itkPhysicalImage.h" #include "itkSimpleImageRegionIterator.h" #include "itkImageToImageAffineMeanSquaresRegularStepGradientDescentRegistration.h" /** * This test uses two 2D-Gaussians (standard deviation RegionSize/2) * One is shifted by 7,3 pixels from the other. * therefore the solution of the registration is |-7 -3| * This test uses LevenbergMarquart Optimizer but * conjugate gradient optimizer tolerances are also defined * in the itkImageToImageAffineMeanSquaresRegularStepGradientDescentRegistration.txx file * (you need to change the type of the optimizer in the header file * ie itkImageToImageAffineMeanSquaresRegularStepGradientDescentRegistration.h) */ int main() { /*Allocate Images*/ typedef itk::PhysicalImage<unsigned char,2> ReferenceType; typedef itk::PhysicalImage<unsigned char,2> TargetType; typedef itk::ImageToImageAffineMeanSquaresRegularStepGradientDescentRegistration<ReferenceType,TargetType> RegistrationType; ReferenceType::SizeType size = {{100,100}}; ReferenceType::IndexType index = {{0,0}}; ReferenceType::RegionType region; region.SetSize( size ); region.SetIndex( index ); ReferenceType::Pointer imgReference = ReferenceType::New(); imgReference->SetLargestPossibleRegion( region ); imgReference->SetBufferedRegion( region ); imgReference->SetRequestedRegion( region ); imgReference->Allocate(); TargetType::Pointer imgTarget = TargetType::New(); imgTarget->SetLargestPossibleRegion( region ); imgTarget->SetBufferedRegion( region ); imgTarget->SetRequestedRegion( region ); imgTarget->Allocate(); /* Fill images with a 2D gaussian*/ typedef itk::SimpleImageRegionIterator<ReferenceType> ReferenceIteratorType; typedef itk::SimpleImageRegionIterator<TargetType> TargetIteratorType; itk::Point<double,2> center; center[0] = (double)region.GetSize()[0]/2.0; center[1] = (double)region.GetSize()[1]/2.0; const double s = (double)region.GetSize()[0]/2.0; itk::Point<double,2> p; itk::Vector<double,2> d; /* Set the displacement */ itk::Vector<double,2> displacement; displacement[0] = 7; displacement[1] = 3; ReferenceIteratorType ri(imgReference,region); TargetIteratorType ti(imgTarget,region); ri.Begin(); while(!ri.IsAtEnd()) { p[0] = ri.GetIndex()[0]; p[1] = ri.GetIndex()[1]; d = p-center; d += displacement; const double x = d[0]; const double y = d[1]; ri.Set( 200.0 * exp( - ( x*x + y*y )/(s*s) ) ); ++ri; } ti.Begin(); while(!ti.IsAtEnd()) { p[0] = ti.GetIndex()[0]; p[1] = ti.GetIndex()[1]; d = p-center; const double x = d[0]; const double y = d[1]; ti.Set( 200.0 * exp( - ( x*x + y*y )/(s*s) ) ); ++ti; } RegistrationType::Pointer registrationMethod = RegistrationType::New(); registrationMethod->SetReference(imgReference); registrationMethod->SetTarget(imgTarget); registrationMethod->SetTranslationScale( 1e4 ); registrationMethod->StartRegistration(); std::cout << "The correct answer should be : " << std::endl; std::cout << " 1.0 0.0 0.0 1.0 "; std::cout << -displacement << std::endl; return EXIT_SUCCESS; } <commit_msg>ERR: Optimizer initialization missing. Added quantitative test<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: itkImageToImageAffineMeanSquaresRegularStepGradientDescentRegistrationTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #include "itkPhysicalImage.h" #include "itkSimpleImageRegionIterator.h" #include "itkImageToImageAffineMeanSquaresRegularStepGradientDescentRegistration.h" /** * This test uses two 2D-Gaussians (standard deviation RegionSize/2) * One is shifted by 7,3 pixels from the other. * therefore the solution of the registration is |-7 -3| * This test uses LevenbergMarquart Optimizer but * conjugate gradient optimizer tolerances are also defined * in the itkImageToImageAffineMeanSquaresRegularStepGradientDescentRegistration.txx file * (you need to change the type of the optimizer in the header file * ie itkImageToImageAffineMeanSquaresRegularStepGradientDescentRegistration.h) */ int main() { /*Allocate Images*/ typedef itk::PhysicalImage<unsigned char,2> ReferenceType; typedef itk::PhysicalImage<unsigned char,2> TargetType; typedef itk::ImageToImageAffineMeanSquaresRegularStepGradientDescentRegistration<ReferenceType,TargetType> RegistrationType; ReferenceType::SizeType size = {{100,100}}; ReferenceType::IndexType index = {{0,0}}; ReferenceType::RegionType region; region.SetSize( size ); region.SetIndex( index ); ReferenceType::Pointer imgReference = ReferenceType::New(); imgReference->SetLargestPossibleRegion( region ); imgReference->SetBufferedRegion( region ); imgReference->SetRequestedRegion( region ); imgReference->Allocate(); TargetType::Pointer imgTarget = TargetType::New(); imgTarget->SetLargestPossibleRegion( region ); imgTarget->SetBufferedRegion( region ); imgTarget->SetRequestedRegion( region ); imgTarget->Allocate(); /* Fill images with a 2D gaussian*/ typedef itk::SimpleImageRegionIterator<ReferenceType> ReferenceIteratorType; typedef itk::SimpleImageRegionIterator<TargetType> TargetIteratorType; itk::Point<double,2> center; center[0] = (double)region.GetSize()[0]/2.0; center[1] = (double)region.GetSize()[1]/2.0; const double s = (double)region.GetSize()[0]/2.0; itk::Point<double,2> p; itk::Vector<double,2> d; /* Set the displacement */ itk::Vector<double,2> displacement; displacement[0] = 7; displacement[1] = 3; ReferenceIteratorType ri(imgReference,region); TargetIteratorType ti(imgTarget,region); ri.Begin(); while(!ri.IsAtEnd()) { p[0] = ri.GetIndex()[0]; p[1] = ri.GetIndex()[1]; d = p-center; d += displacement; const double x = d[0]; const double y = d[1]; ri.Set( 200.0 * exp( - ( x*x + y*y )/(s*s) ) ); ++ri; } ti.Begin(); while(!ti.IsAtEnd()) { p[0] = ti.GetIndex()[0]; p[1] = ti.GetIndex()[1]; d = p-center; const double x = d[0]; const double y = d[1]; ti.Set( 200.0 * exp( - ( x*x + y*y )/(s*s) ) ); ++ti; } const double translationScale = 1e4; RegistrationType::Pointer registrationMethod = RegistrationType::New(); registrationMethod->SetReference(imgReference); registrationMethod->SetTarget(imgTarget); registrationMethod->SetTranslationScale( translationScale ); registrationMethod->GetOptimizer()->SetMaximumStepLength( 1.0 ); registrationMethod->GetOptimizer()->SetMinimumStepLength( 1e-3 ); registrationMethod->GetOptimizer()->SetGradientMagnitudeTolerance( 1e-8 ); registrationMethod->GetOptimizer()->SetMaximumNumberOfIterations( 200 ); registrationMethod->StartRegistration(); // get the results RegistrationType::ParametersType solution = registrationMethod->GetOptimizer()->GetCurrentPosition(); std::cout << "Solution is: " << solution << std::endl; // // check results to see if it is within range // bool pass = true; double trueParameters[6] = { 1, 0, 0, 1, -7, -3 }; for( unsigned int j = 0; j < 4; j++ ) { if( vnl_math_abs( solution[j] - trueParameters[j] ) > 0.02 ) pass = false; } for( unsigned int j = 4; j < 6; j++ ) { if( vnl_math_abs( solution[j] * translationScale - trueParameters[j] ) > 1.0 ) pass = false; } if( !pass ) { std::cout << "Test failed." << std::endl; return EXIT_FAILURE; } std::cout << "Test passed." << std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #ifndef FLUSHER_H #define FLUSHER_H 1 #include "common.hh" #include "ep.hh" #include "dispatcher.hh" enum flusher_state { initializing, running, pausing, paused, stopping, stopped }; class Flusher; class FlusherStepper : public DispatcherCallback { public: FlusherStepper(Flusher* f) : flusher(f) { } bool callback(Dispatcher &d, TaskId t); private: Flusher *flusher; }; class Flusher { public: Flusher(EventuallyPersistentStore *st, Dispatcher *d) : store(st), _state(initializing), dispatcher(d), flushQueue(NULL) { } ~Flusher() { if (_state != stopped) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Flusher being destroyed in state %s\n", stateName(_state)); } } bool stop(); void wait(); bool pause(); bool resume(); void initialize(TaskId); void start(void); void wake(void); bool step(Dispatcher&, TaskId); bool transition_state(enum flusher_state to); enum flusher_state state() const; const char * stateName() const; private: int doFlush(); void completeFlush(); void schedule_UNLOCKED(); EventuallyPersistentStore *store; volatile enum flusher_state _state; Mutex taskMutex; TaskId task; Dispatcher *dispatcher; const char * stateName(enum flusher_state st) const; // Current flush cycle state. int flushRv; std::queue<QueuedItem> *flushQueue; std::queue<QueuedItem> *rejectQueue; rel_time_t flushStart; DISALLOW_COPY_AND_ASSIGN(Flusher); }; #endif /* FLUSHER_H */ <commit_msg>Some flusher doc updates.<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #ifndef FLUSHER_H #define FLUSHER_H 1 #include "common.hh" #include "ep.hh" #include "dispatcher.hh" enum flusher_state { initializing, running, pausing, paused, stopping, stopped }; class Flusher; /** * A DispatcherCallback adaptor over Flusher. */ class FlusherStepper : public DispatcherCallback { public: FlusherStepper(Flusher* f) : flusher(f) { } bool callback(Dispatcher &d, TaskId t); private: Flusher *flusher; }; /** * Manage persistence of data for an EventuallyPersistentStore. */ class Flusher { public: Flusher(EventuallyPersistentStore *st, Dispatcher *d) : store(st), _state(initializing), dispatcher(d), flushQueue(NULL) { } ~Flusher() { if (_state != stopped) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Flusher being destroyed in state %s\n", stateName(_state)); } } bool stop(); void wait(); bool pause(); bool resume(); void initialize(TaskId); void start(void); void wake(void); bool step(Dispatcher&, TaskId); bool transition_state(enum flusher_state to); enum flusher_state state() const; const char * stateName() const; private: int doFlush(); void completeFlush(); void schedule_UNLOCKED(); EventuallyPersistentStore *store; volatile enum flusher_state _state; Mutex taskMutex; TaskId task; Dispatcher *dispatcher; const char * stateName(enum flusher_state st) const; // Current flush cycle state. int flushRv; std::queue<QueuedItem> *flushQueue; std::queue<QueuedItem> *rejectQueue; rel_time_t flushStart; DISALLOW_COPY_AND_ASSIGN(Flusher); }; #endif /* FLUSHER_H */ <|endoftext|>
<commit_before>// // calcPWP.cpp // // // Created by Evan McCartney-Melstad on 1/10/15. // // #include "calcPWP.h" #include <iostream> #include <vector> #include <fstream> #include <thread> #include <string> int calcPWPfromBinaryFile (std::string binaryFile, unsigned long long int numLoci, const int numIndividuals, std::string outFile, int numThreads) { //****MODIFY THIS TO ONLY READ IN N LOCI AT A TIME, INSTEAD OF USING THE ENTIRE FILE**** std::cout << "Number of threads: " << numThreads << std::endl; std::streampos size; std::ifstream file (binaryFile, std::ios::in|std::ios::binary|std::ios::ate); //ifstream file ("test500k.binary8bitunsigned", ios::in|ios::binary|ios::ate); if (file.is_open()) { size = file.tellg(); // Just a variable that shows position of stream--at end since ios::ate, so it's the file size. PROBABLY WON'T WORK FOR FILES LARGER THAN ~ 2GB! file.seekg (0, std::ios::beg); // Go back to the beginning of the file //file.read((char*)readCounts, size); // cast to a char* to give to file.read //unsigned char* readCounts; //readCounts = new unsigned char[size]; std::vector<unsigned char> readCounts(size); file.read((char*) &readCounts[0], size); file.close(); std::cout << "the entire file content is in memory" << std::endl; std::cout << "the total size of the file is " << size << std::endl; std::cout << "the number of elements in the readCounts vector is: " << readCounts.size() << std::endl; // Will give the total size bytes divided by the size of one element--so it gives the number of elements /* We are going to split the loci between numThreads threads. Each thread will modify two multidimensional vectors of the forms std::vector< std::vector<long double> > pwp(numIndividuals, std::vector<long double>(numIndividuals,0)) and std::vector< std::vector<unsigned long long int> > weightings(numIndividuals, std::vector<unsigned long long int>(numIndividuals,0)) First, we'll generate all of these vectors, which apparently in C++ needs to be constructed of a vector of two-dimensional vectors... */ std::vector<std::vector<std::vector<long double>>> pwpThreads(numThreads, std::vector<std::vector<long double>> (numIndividuals, std::vector<long double> (numIndividuals,0) ) ); //pwpThreads[0] is the first 2D array for the first thread, etc... std::vector<std::vector<std::vector<unsigned long long int>>> weightingsThreads(numThreads, std::vector<std::vector<unsigned long long int> > (numIndividuals, std::vector<unsigned long long int> (numIndividuals,0) ) ); std::cout << "Initialized the 3d vectors" << std::endl; // Now we need to determine how many loci for each thread. If we want to use the entire binary file, instead of numLoci loci, then change this to lociPerThread = (size/(numIndividuals*2))/numThreads //unsigned long long int lociPerThread = numLoci / numThreads; //unsigned long long int lociPerThread = (readCounts.size()-1)/numThreads; // loci starts with 0, so need to subtract 1 from numLoci unsigned long long int lociPerThread; if (numLoci == 0) { lociPerThread = (unsigned long long)(size/(numIndividuals*2))/(unsigned long long)numThreads; } else { lociPerThread = (unsigned long long)numLoci/(unsigned long long)numThreads; } std::cout << "Initialized lociPerThread with " << numLoci << std::endl; std::vector<std::thread> threadsVec; for (int threadRunning = 0; threadRunning < numThreads; threadRunning++) { std::cout << "Got to the function call. Running thread # " << threadRunning << std::endl; unsigned long long int firstLocus = (unsigned long long int) threadRunning * lociPerThread; unsigned long long int finishingLocus = ((unsigned long long int) threadRunning * lociPerThread) + lociPerThread - (unsigned long long)1.0; std::cout << "Set firstLocus to " << firstLocus << " and finishingLocus to " << finishingLocus << std::endl; threadsVec.push_back(std::thread(calcPWPforRange, firstLocus, finishingLocus, numIndividuals, std::ref(readCounts), std::ref(pwpThreads[threadRunning]), std::ref(weightingsThreads[threadRunning]))); } // Wait on threads to finish for (int i = 0; i < numThreads; ++i) { threadsVec[i].join(); std::cout << "Joined thread " << i << std::endl; } std::cout << "All threads completed running" << std::endl; // Now aggregate the results of the threads and print final results std::vector<std::vector<long double>> weightingsSum(numIndividuals, std::vector<long double>(numIndividuals,0)); std::vector<std::vector<long double>> pwpSum(numIndividuals, std::vector<long double>(numIndividuals,0)); for (int tortoise = 0; tortoise < numIndividuals; tortoise++) { for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) { for (int threadVector = 0; threadVector < numThreads; threadVector++) { weightingsSum[tortoise][comparisonTortoise] += weightingsThreads[threadVector][tortoise][comparisonTortoise]; pwpSum[tortoise][comparisonTortoise] += pwpThreads[threadVector][tortoise][comparisonTortoise]; } } } std::cout << "Finished summing the threads vectors" << std::endl; // Now print out the final output to the pairwise pi file: std::ofstream pwpOUT (outFile); int rowCounter = 0; if (!pwpOUT) { std::cerr << "Crap, " << outFile << "didn't open!" << std::endl; } else { for (int tortoise=0; tortoise < numIndividuals; tortoise++) { for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) { rowCounter++; //std::cout << "Made it past the beginning of the last end for loop" << std::endl; //std::cout << "Tortoise numbers: " << tortoise << " and " << comparisonTortoise << std::endl; if (weightingsSum[tortoise][comparisonTortoise] > 0) { //std::cout << weightings[tortoise][comparisonTortoise] << std::endl; //std::cout << pwp[tortoise][comparisonTortoise] / weightings[tortoise][comparisonTortoise] << std::endl; std::cout << std::fixed; std::cout << "Weightings for tortoise " << tortoise << " and comparisonTortoise " << comparisonTortoise << " : " << weightingsSum[tortoise][comparisonTortoise] << std::endl; std::cout << "PWP for tortoise " << tortoise << " and comparisonTortoise " << comparisonTortoise << " : " << pwpSum[tortoise][comparisonTortoise] << std::endl; std::cout << std::scientific; pwpOUT << pwpSum[tortoise][comparisonTortoise] / weightingsSum[tortoise][comparisonTortoise] << std::endl; } else { pwpOUT << "NA" << std::endl; } } } } } else std::cout << "Unable to open file"; return 0; } //int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, const std::vector<BYTE>& mainReadCountVector, std::vector< std::vector<long double> > & threadPWP, std::vector< std::vector<long double> > & threadWeightings) { int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, std::vector<unsigned char>& mainReadCountVector, std::vector<std::vector<long double>>& threadPWP, std::vector<std::vector<unsigned long long int>>& threadWeightings) { std::cout << "Calculating PWP for the following locus range: " << startingLocus << " to " << endingLocus << std::endl; for( unsigned long long locus = startingLocus; locus < endingLocus; locus++) { //std::cout << "Processing locus # " << locus << std::endl; if (locus % 100000 == 0) { std::cout << locus << " loci processed through calcPWPfromBinaryFile" << std::endl; } unsigned long long coverages[numIndividuals]; long double *majorAlleleFreqs = new long double[numIndividuals]; // This will hold the major allele frequencies for that locus for each tortoise for( int tortoise = 0; tortoise < numIndividuals; tortoise++ ) { unsigned long long majorIndex = locus * (numIndividuals*2) + 2 * tortoise; unsigned long long minorIndex = locus * (numIndividuals*2) + 2 * tortoise + 1; coverages[tortoise] = int(mainReadCountVector[majorIndex]) + int(mainReadCountVector[minorIndex]); // Hold the coverages for each locus if ( coverages[tortoise] > 0 ) { //std::cout << "Made it to line 222 for locus " << locus << std::endl; majorAlleleFreqs[tortoise] = (long double)mainReadCountVector[majorIndex] / (long double)coverages[tortoise]; // Not necessarily an int, but could be 0 or 1 if (coverages[tortoise] > 1) { unsigned long long locusWeighting = (unsigned long long) (coverages[tortoise]*(coverages[tortoise]-1)); threadWeightings[tortoise][tortoise] += (unsigned long long)locusWeighting; // This is an int--discrete number of reads //threadPWP[tortoise][tortoise] += (long double)(locusWeighting) * ((long double)2.0 * majorAlleleFreqs[tortoise] * ((long double)(coverages[tortoise]) - (long double)(mainReadCountVector[majorIndex]))) / (long double)((coverages[tortoise])-(long double)1.0); threadPWP[tortoise][tortoise] += (long double)(locusWeighting) * ((long double)2.0 * majorAlleleFreqs[tortoise] * ((long double)(coverages[tortoise]) - (long double)(mainReadCountVector[majorIndex]))) / (long double)((coverages[tortoise])); //threadPWP[tortoise][tortoise] += locusWeighting*(2*majorAlleleFreqs[tortoise] * (coverages[tortoise]-majorReadCounts)) / (coverages[tortoise]-1) } for( int comparisonTortoise = 0; comparisonTortoise < tortoise; comparisonTortoise++) { if (coverages[comparisonTortoise] > 0) { long double locusWeighting = (long double)coverages[tortoise] * (long double)(coverages[comparisonTortoise]-1.0); threadWeightings[tortoise][comparisonTortoise] += locusWeighting; threadPWP[tortoise][comparisonTortoise] += (long double)locusWeighting * (majorAlleleFreqs[tortoise] * ((long double)1.0-majorAlleleFreqs[comparisonTortoise]) + majorAlleleFreqs[comparisonTortoise] * ((long double)1.0-majorAlleleFreqs[tortoise])); } } } } delete[] majorAlleleFreqs; // Needed to avoid memory leaks } std::cout << "Finished thread ending on locus " << endingLocus << std::endl; return 0; } <commit_msg>Minor changes<commit_after>// // calcPWP.cpp // // // Created by Evan McCartney-Melstad on 1/10/15. // // #include "calcPWP.h" #include <iostream> #include <vector> #include <fstream> #include <thread> #include <string> int calcPWPfromBinaryFile (std::string binaryFile, unsigned long long int numLoci, const int numIndividuals, std::string outFile, int numThreads) { //****MODIFY THIS TO ONLY READ IN N LOCI AT A TIME, INSTEAD OF USING THE ENTIRE FILE**** std::cout << "Number of threads: " << numThreads << std::endl; std::streampos size; std::ifstream file (binaryFile, std::ios::in|std::ios::binary|std::ios::ate); //ifstream file ("test500k.binary8bitunsigned", ios::in|ios::binary|ios::ate); if (file.is_open()) { size = file.tellg(); // Just a variable that shows position of stream--at end since ios::ate, so it's the file size. PROBABLY WON'T WORK FOR FILES LARGER THAN ~ 2GB! file.seekg (0, std::ios::beg); // Go back to the beginning of the file //file.read((char*)readCounts, size); // cast to a char* to give to file.read //unsigned char* readCounts; //readCounts = new unsigned char[size]; std::vector<unsigned char> readCounts(size); file.read((char*) &readCounts[0], size); file.close(); std::cout << "the entire file content is in memory" << std::endl; std::cout << "the total size of the file is " << size << std::endl; std::cout << "the number of elements in the readCounts vector is: " << readCounts.size() << std::endl; // Will give the total size bytes divided by the size of one element--so it gives the number of elements /* We are going to split the loci between numThreads threads. Each thread will modify two multidimensional vectors of the forms std::vector< std::vector<long double> > pwp(numIndividuals, std::vector<long double>(numIndividuals,0)) and std::vector< std::vector<unsigned long long int> > weightings(numIndividuals, std::vector<unsigned long long int>(numIndividuals,0)) First, we'll generate all of these vectors, which apparently in C++ needs to be constructed of a vector of two-dimensional vectors... */ std::vector<std::vector<std::vector<long double>>> pwpThreads(numThreads, std::vector<std::vector<long double>> (numIndividuals, std::vector<long double> (numIndividuals,0) ) ); //pwpThreads[0] is the first 2D array for the first thread, etc... std::vector<std::vector<std::vector<unsigned long long int>>> weightingsThreads(numThreads, std::vector<std::vector<unsigned long long int> > (numIndividuals, std::vector<unsigned long long int> (numIndividuals,0) ) ); std::cout << "Initialized the 3d vectors" << std::endl; // Now we need to determine how many loci for each thread. If we want to use the entire binary file, instead of numLoci loci, then change this to lociPerThread = (size/(numIndividuals*2))/numThreads //unsigned long long int lociPerThread = numLoci / numThreads; //unsigned long long int lociPerThread = (readCounts.size()-1)/numThreads; // loci starts with 0, so need to subtract 1 from numLoci unsigned long long int lociPerThread; if (numLoci == 0) { lociPerThread = (unsigned long long)(size/(numIndividuals*2))/(unsigned long long)numThreads; } else { lociPerThread = (unsigned long long)numLoci/(unsigned long long)numThreads; } std::cout << "Initialized lociPerThread with " << numLoci << std::endl; std::vector<std::thread> threadsVec; for (int threadRunning = 0; threadRunning < numThreads; threadRunning++) { std::cout << "Got to the function call. Running thread # " << threadRunning << std::endl; unsigned long long int firstLocus = (unsigned long long int) threadRunning * lociPerThread; unsigned long long int finishingLocus = ((unsigned long long int) threadRunning * lociPerThread) + lociPerThread - (unsigned long long)1.0; std::cout << "Set firstLocus to " << firstLocus << " and finishingLocus to " << finishingLocus << std::endl; threadsVec.push_back(std::thread(calcPWPforRange, firstLocus, finishingLocus, numIndividuals, std::ref(readCounts), std::ref(pwpThreads[threadRunning]), std::ref(weightingsThreads[threadRunning]))); } // Wait on threads to finish for (int i = 0; i < numThreads; ++i) { threadsVec[i].join(); std::cout << "Joined thread " << i << std::endl; } std::cout << "All threads completed running" << std::endl; // Now aggregate the results of the threads and print final results std::vector<std::vector<long double>> weightingsSum(numIndividuals, std::vector<long double>(numIndividuals,0)); std::vector<std::vector<long double>> pwpSum(numIndividuals, std::vector<long double>(numIndividuals,0)); for (int tortoise = 0; tortoise < numIndividuals; tortoise++) { for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) { for (int threadVector = 0; threadVector < numThreads; threadVector++) { weightingsSum[tortoise][comparisonTortoise] += weightingsThreads[threadVector][tortoise][comparisonTortoise]; pwpSum[tortoise][comparisonTortoise] += pwpThreads[threadVector][tortoise][comparisonTortoise]; } } } std::cout << "Finished summing the threads vectors" << std::endl; // Now print out the final output to the pairwise pi file: std::ofstream pwpOUT (outFile); int rowCounter = 0; if (!pwpOUT) { std::cerr << "Crap, " << outFile << "didn't open!" << std::endl; } else { for (int tortoise=0; tortoise < numIndividuals; tortoise++) { for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) { rowCounter++; //std::cout << "Made it past the beginning of the last end for loop" << std::endl; //std::cout << "Tortoise numbers: " << tortoise << " and " << comparisonTortoise << std::endl; if (weightingsSum[tortoise][comparisonTortoise] > 0) { //std::cout << weightings[tortoise][comparisonTortoise] << std::endl; //std::cout << pwp[tortoise][comparisonTortoise] / weightings[tortoise][comparisonTortoise] << std::endl; std::cout << std::fixed; std::cout << "Weightings for tortoise " << tortoise << " and comparisonTortoise " << comparisonTortoise << " : " << weightingsSum[tortoise][comparisonTortoise] << std::endl; std::cout << "PWP for tortoise " << tortoise << " and comparisonTortoise " << comparisonTortoise << " : " << pwpSum[tortoise][comparisonTortoise] << std::endl; std::cout << std::scientific; pwpOUT << pwpSum[tortoise][comparisonTortoise] / weightingsSum[tortoise][comparisonTortoise] << std::endl; } else { pwpOUT << "NA" << std::endl; } } } } } else std::cout << "Unable to open file"; return 0; } //int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, const std::vector<BYTE>& mainReadCountVector, std::vector< std::vector<long double> > & threadPWP, std::vector< std::vector<long double> > & threadWeightings) { int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, std::vector<unsigned char>& mainReadCountVector, std::vector<std::vector<long double>>& threadPWP, std::vector<std::vector<unsigned long long int>>& threadWeightings) { std::cout << "Calculating PWP for the following locus range: " << startingLocus << " to " << endingLocus << std::endl; for( unsigned long long locus = startingLocus; locus < endingLocus; locus++) { //std::cout << "Processing locus # " << locus << std::endl; if (locus % 100000 == 0) { std::cout << locus << " loci processed through calcPWPfromBinaryFile" << std::endl; } unsigned long long coverages[numIndividuals]; long double *majorAlleleFreqs = new long double[numIndividuals]; // This will hold the major allele frequencies for that locus for each tortoise for( int tortoise = 0; tortoise < numIndividuals; tortoise++ ) { unsigned long long majorIndex = locus * (numIndividuals*2) + 2 * tortoise; unsigned long long minorIndex = locus * (numIndividuals*2) + 2 * tortoise + 1; coverages[tortoise] = int(mainReadCountVector[majorIndex]) + int(mainReadCountVector[minorIndex]); // Hold the coverages for each locus if ( coverages[tortoise] > 0 ) { //std::cout << "Made it to line 222 for locus " << locus << std::endl; majorAlleleFreqs[tortoise] = (long double)mainReadCountVector[majorIndex] / (long double)coverages[tortoise]; // Not necessarily an int, but could be 0 or 1 if (coverages[tortoise] > 1) { unsigned long long locusWeighting = (unsigned long long) (coverages[tortoise]*(coverages[tortoise]-1)); threadWeightings[tortoise][tortoise] += (unsigned long long)locusWeighting; // This is an int--discrete number of reads //threadPWP[tortoise][tortoise] += (long double)(locusWeighting) * ((long double)2.0 * majorAlleleFreqs[tortoise] * ((long double)(coverages[tortoise]) - (long double)(mainReadCountVector[majorIndex]))) / (long double)((coverages[tortoise])-(long double)1.0); //Cancel out the "coverages[tortoise]-1" threadPWP[tortoise][tortoise] += (long double)(coverages[tortoise]) * ((long double)2.0 * majorAlleleFreqs[tortoise] * ((long double)(coverages[tortoise]) - (long double)(mainReadCountVector[majorIndex]))); //threadPWP[tortoise][tortoise] += (long double)(locusWeighting) * ((long double)2.0 * majorAlleleFreqs[tortoise] * ((long double)(coverages[tortoise]) - (long double)(mainReadCountVector[majorIndex]))) / (long double)((coverages[tortoise])); //threadPWP[tortoise][tortoise] += locusWeighting*(2*majorAlleleFreqs[tortoise] * (coverages[tortoise]-majorReadCounts)) / (coverages[tortoise]-1) } for( int comparisonTortoise = 0; comparisonTortoise < tortoise; comparisonTortoise++) { if (coverages[comparisonTortoise] > 0) { long double locusWeighting = (long double)coverages[tortoise] * (long double)(coverages[comparisonTortoise]-1.0); threadWeightings[tortoise][comparisonTortoise] += locusWeighting; threadPWP[tortoise][comparisonTortoise] += (long double)locusWeighting * (majorAlleleFreqs[tortoise] * ((long double)1.0-majorAlleleFreqs[comparisonTortoise]) + majorAlleleFreqs[comparisonTortoise] * ((long double)1.0-majorAlleleFreqs[tortoise])); } } } } delete[] majorAlleleFreqs; // Needed to avoid memory leaks } std::cout << "Finished thread ending on locus " << endingLocus << std::endl; return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/mac/libdispatch_task_runner.h" #include "base/bind.h" #include "base/mac/bind_objc_block.h" #include "base/message_loop.h" #include "base/stringprintf.h" #include "testing/gtest/include/gtest/gtest.h" class LibDispatchTaskRunnerTest : public testing::Test { public: virtual void SetUp() OVERRIDE { task_runner_ = new base::mac::LibDispatchTaskRunner( "org.chromium.LibDispatchTaskRunnerTest"); } // DispatchLastTask is used to run the main test thread's MessageLoop until // all non-delayed tasks are run on the LibDispatchTaskRunner. void DispatchLastTask() { dispatch_async(task_runner_->GetDispatchQueue(), ^{ (&message_loop_)->PostTask(FROM_HERE, MessageLoop::QuitClosure()); }); message_loop_.Run(); } // VerifyTaskOrder takes the expectations from TaskOrderMarkers and compares // them against the recorded values. void VerifyTaskOrder(const char* const expectations[], size_t num_expectations) { size_t actual_size = task_order_.size(); for (size_t i = 0; i < num_expectations; ++i) { if (i >= actual_size) { EXPECT_LT(i, actual_size) << "Expected " << expectations[i]; continue; } EXPECT_EQ(expectations[i], task_order_[i]); } if (actual_size > num_expectations) { EXPECT_LE(actual_size, num_expectations) << "Extra tasks were run:"; for (size_t i = num_expectations; i < actual_size; ++i) { EXPECT_EQ("<none>", task_order_[i]) << " (i=" << i << ")"; } } } // The message loop for the test main thread. MessageLoop message_loop_; // The task runner under test. scoped_refptr<base::mac::LibDispatchTaskRunner> task_runner_; // Vector that records data from TaskOrderMarker. std::vector<std::string> task_order_; }; // Scoper that records the beginning and end of a running task. class TaskOrderMarker { public: TaskOrderMarker(LibDispatchTaskRunnerTest* test, const std::string& name) : test_(test), name_(name) { test->task_order_.push_back(std::string("BEGIN ") + name); } ~TaskOrderMarker() { test_->task_order_.push_back(std::string("END ") + name_); } private: LibDispatchTaskRunnerTest* test_; std::string name_; }; void RecordTaskOrder(LibDispatchTaskRunnerTest* test, const std::string& name) { TaskOrderMarker marker(test, name); } // Returns a closure that records the task order. base::Closure BoundRecordTaskOrder(LibDispatchTaskRunnerTest* test, const std::string& name) { return base::Bind(&RecordTaskOrder, base::Unretained(test), name); } TEST_F(LibDispatchTaskRunnerTest, PostTask) { task_runner_->PostTask(FROM_HERE, BoundRecordTaskOrder(this, "Basic Task")); DispatchLastTask(); const char* const expectations[] = { "BEGIN Basic Task", "END Basic Task" }; VerifyTaskOrder(expectations, arraysize(expectations)); } TEST_F(LibDispatchTaskRunnerTest, PostTaskWithinTask) { task_runner_->PostTask(FROM_HERE, base::BindBlock(^{ TaskOrderMarker marker(this, "Outer"); task_runner_->PostTask(FROM_HERE, BoundRecordTaskOrder(this, "Inner")); })); DispatchLastTask(); const char* const expectations[] = { "BEGIN Outer", "END Outer", "BEGIN Inner", "END Inner" }; VerifyTaskOrder(expectations, arraysize(expectations)); } TEST_F(LibDispatchTaskRunnerTest, NoMessageLoop) { task_runner_->PostTask(FROM_HERE, base::BindBlock(^{ TaskOrderMarker marker(this, base::StringPrintf("MessageLoop = %p", MessageLoop::current())); })); DispatchLastTask(); const char* const expectations[] = { "BEGIN MessageLoop = 0x0", "END MessageLoop = 0x0" }; VerifyTaskOrder(expectations, arraysize(expectations)); } TEST_F(LibDispatchTaskRunnerTest, DispatchAndPostTasks) { dispatch_async(task_runner_->GetDispatchQueue(), ^{ TaskOrderMarker marker(this, "First Block"); task_runner_->PostTask(FROM_HERE, BoundRecordTaskOrder(this, "Second Task")); }); task_runner_->PostTask(FROM_HERE, BoundRecordTaskOrder(this, "First Task")); dispatch_async(task_runner_->GetDispatchQueue(), ^{ TaskOrderMarker marker(this, "Second Block"); }); DispatchLastTask(); const char* const expectations[] = { "BEGIN First Block", "END First Block", "BEGIN First Task", "END First Task", "BEGIN Second Block", "END Second Block", "BEGIN Second Task", "END Second Task", }; VerifyTaskOrder(expectations, arraysize(expectations)); } TEST_F(LibDispatchTaskRunnerTest, NonNestable) { task_runner_->PostTask(FROM_HERE, base::BindBlock(^{ TaskOrderMarker marker(this, "First"); task_runner_->PostNonNestableTask(FROM_HERE, base::BindBlock(^{ TaskOrderMarker marker(this, "Third NonNestable"); })); })); task_runner_->PostTask(FROM_HERE, BoundRecordTaskOrder(this, "Second")); DispatchLastTask(); const char* const expectations[] = { "BEGIN First", "END First", "BEGIN Second", "END Second", "BEGIN Third NonNestable", "END Third NonNestable" }; VerifyTaskOrder(expectations, arraysize(expectations)); } TEST_F(LibDispatchTaskRunnerTest, PostDelayed) { base::TimeTicks post_time; __block base::TimeTicks run_time; const base::TimeDelta delta = base::TimeDelta::FromMilliseconds(50); task_runner_->PostTask(FROM_HERE, BoundRecordTaskOrder(this, "First")); post_time = base::TimeTicks::Now(); task_runner_->PostDelayedTask(FROM_HERE, base::BindBlock(^{ TaskOrderMarker marker(this, "Timed"); run_time = base::TimeTicks::Now(); (&message_loop_)->PostTask(FROM_HERE, MessageLoop::QuitClosure()); }), delta); task_runner_->PostTask(FROM_HERE, BoundRecordTaskOrder(this, "Second")); message_loop_.Run(); const char* const expectations[] = { "BEGIN First", "END First", "BEGIN Second", "END Second", "BEGIN Timed", "END Timed", }; VerifyTaskOrder(expectations, arraysize(expectations)); EXPECT_GE(run_time, post_time + delta); } <commit_msg>Mark LibDispatchTaskRunnerTest.DispatchAndPostTasks as flaky<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/mac/libdispatch_task_runner.h" #include "base/bind.h" #include "base/mac/bind_objc_block.h" #include "base/message_loop.h" #include "base/stringprintf.h" #include "testing/gtest/include/gtest/gtest.h" class LibDispatchTaskRunnerTest : public testing::Test { public: virtual void SetUp() OVERRIDE { task_runner_ = new base::mac::LibDispatchTaskRunner( "org.chromium.LibDispatchTaskRunnerTest"); } // DispatchLastTask is used to run the main test thread's MessageLoop until // all non-delayed tasks are run on the LibDispatchTaskRunner. void DispatchLastTask() { dispatch_async(task_runner_->GetDispatchQueue(), ^{ (&message_loop_)->PostTask(FROM_HERE, MessageLoop::QuitClosure()); }); message_loop_.Run(); } // VerifyTaskOrder takes the expectations from TaskOrderMarkers and compares // them against the recorded values. void VerifyTaskOrder(const char* const expectations[], size_t num_expectations) { size_t actual_size = task_order_.size(); for (size_t i = 0; i < num_expectations; ++i) { if (i >= actual_size) { EXPECT_LT(i, actual_size) << "Expected " << expectations[i]; continue; } EXPECT_EQ(expectations[i], task_order_[i]); } if (actual_size > num_expectations) { EXPECT_LE(actual_size, num_expectations) << "Extra tasks were run:"; for (size_t i = num_expectations; i < actual_size; ++i) { EXPECT_EQ("<none>", task_order_[i]) << " (i=" << i << ")"; } } } // The message loop for the test main thread. MessageLoop message_loop_; // The task runner under test. scoped_refptr<base::mac::LibDispatchTaskRunner> task_runner_; // Vector that records data from TaskOrderMarker. std::vector<std::string> task_order_; }; // Scoper that records the beginning and end of a running task. class TaskOrderMarker { public: TaskOrderMarker(LibDispatchTaskRunnerTest* test, const std::string& name) : test_(test), name_(name) { test->task_order_.push_back(std::string("BEGIN ") + name); } ~TaskOrderMarker() { test_->task_order_.push_back(std::string("END ") + name_); } private: LibDispatchTaskRunnerTest* test_; std::string name_; }; void RecordTaskOrder(LibDispatchTaskRunnerTest* test, const std::string& name) { TaskOrderMarker marker(test, name); } // Returns a closure that records the task order. base::Closure BoundRecordTaskOrder(LibDispatchTaskRunnerTest* test, const std::string& name) { return base::Bind(&RecordTaskOrder, base::Unretained(test), name); } TEST_F(LibDispatchTaskRunnerTest, PostTask) { task_runner_->PostTask(FROM_HERE, BoundRecordTaskOrder(this, "Basic Task")); DispatchLastTask(); const char* const expectations[] = { "BEGIN Basic Task", "END Basic Task" }; VerifyTaskOrder(expectations, arraysize(expectations)); } TEST_F(LibDispatchTaskRunnerTest, PostTaskWithinTask) { task_runner_->PostTask(FROM_HERE, base::BindBlock(^{ TaskOrderMarker marker(this, "Outer"); task_runner_->PostTask(FROM_HERE, BoundRecordTaskOrder(this, "Inner")); })); DispatchLastTask(); const char* const expectations[] = { "BEGIN Outer", "END Outer", "BEGIN Inner", "END Inner" }; VerifyTaskOrder(expectations, arraysize(expectations)); } TEST_F(LibDispatchTaskRunnerTest, NoMessageLoop) { task_runner_->PostTask(FROM_HERE, base::BindBlock(^{ TaskOrderMarker marker(this, base::StringPrintf("MessageLoop = %p", MessageLoop::current())); })); DispatchLastTask(); const char* const expectations[] = { "BEGIN MessageLoop = 0x0", "END MessageLoop = 0x0" }; VerifyTaskOrder(expectations, arraysize(expectations)); } // This test is flaky, see http://crbug.com/165117. TEST_F(LibDispatchTaskRunnerTest, FLAKY_DispatchAndPostTasks) { dispatch_async(task_runner_->GetDispatchQueue(), ^{ TaskOrderMarker marker(this, "First Block"); task_runner_->PostTask(FROM_HERE, BoundRecordTaskOrder(this, "Second Task")); }); task_runner_->PostTask(FROM_HERE, BoundRecordTaskOrder(this, "First Task")); dispatch_async(task_runner_->GetDispatchQueue(), ^{ TaskOrderMarker marker(this, "Second Block"); }); DispatchLastTask(); const char* const expectations[] = { "BEGIN First Block", "END First Block", "BEGIN First Task", "END First Task", "BEGIN Second Block", "END Second Block", "BEGIN Second Task", "END Second Task", }; VerifyTaskOrder(expectations, arraysize(expectations)); } TEST_F(LibDispatchTaskRunnerTest, NonNestable) { task_runner_->PostTask(FROM_HERE, base::BindBlock(^{ TaskOrderMarker marker(this, "First"); task_runner_->PostNonNestableTask(FROM_HERE, base::BindBlock(^{ TaskOrderMarker marker(this, "Third NonNestable"); })); })); task_runner_->PostTask(FROM_HERE, BoundRecordTaskOrder(this, "Second")); DispatchLastTask(); const char* const expectations[] = { "BEGIN First", "END First", "BEGIN Second", "END Second", "BEGIN Third NonNestable", "END Third NonNestable" }; VerifyTaskOrder(expectations, arraysize(expectations)); } TEST_F(LibDispatchTaskRunnerTest, PostDelayed) { base::TimeTicks post_time; __block base::TimeTicks run_time; const base::TimeDelta delta = base::TimeDelta::FromMilliseconds(50); task_runner_->PostTask(FROM_HERE, BoundRecordTaskOrder(this, "First")); post_time = base::TimeTicks::Now(); task_runner_->PostDelayedTask(FROM_HERE, base::BindBlock(^{ TaskOrderMarker marker(this, "Timed"); run_time = base::TimeTicks::Now(); (&message_loop_)->PostTask(FROM_HERE, MessageLoop::QuitClosure()); }), delta); task_runner_->PostTask(FROM_HERE, BoundRecordTaskOrder(this, "Second")); message_loop_.Run(); const char* const expectations[] = { "BEGIN First", "END First", "BEGIN Second", "END Second", "BEGIN Timed", "END Timed", }; VerifyTaskOrder(expectations, arraysize(expectations)); EXPECT_GE(run_time, post_time + delta); } <|endoftext|>
<commit_before>/* * this file is part of the oxygen gtk engine * Copyright (c) 2011 Hugo Pereira Da Costa <hugo@oxygen-icons.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or( at your option ) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "oxygencairocontext.h" #include "oxygencairoutils.h" #include "oxygengtkutils.h" #include "oxygenmetrics.h" #include "oxygenrgba.h" #include "oxygenshadowhelper.h" #include <iostream> #include <cairo/cairo.h> #include <cairo/cairo-xlib.h> #include <gdk/gdkx.h> #include <X11/Xatom.h> namespace Oxygen { //______________________________________________ ShadowHelper::ShadowHelper( void ): _size(0), _atom(0), _hooksInitialized( false ) {} //______________________________________________ ShadowHelper::~ShadowHelper( void ) { reset(); } //______________________________________________ void ShadowHelper::reset( void ) { GdkScreen* screen = gdk_screen_get_default(); Display* display( GDK_DISPLAY_XDISPLAY( gdk_screen_get_display( screen ) ) ); // round pixmaps for( PixmapList::const_iterator iter = _roundPixmaps.begin(); iter != _roundPixmaps.end(); ++iter ) { XFreePixmap(display, *iter); } _roundPixmaps.clear(); // square pixmaps for( PixmapList::const_iterator iter = _squarePixmaps.begin(); iter != _squarePixmaps.end(); ++iter ) { XFreePixmap(display, *iter); } _squarePixmaps.clear(); } //______________________________________________ void ShadowHelper::initializeHooks( void ) { if( _hooksInitialized ) return; // install hooks _realizeHook.connect( "realize", (GSignalEmissionHook)realizeHook, this ); _hooksInitialized = true; } //______________________________________________ void ShadowHelper::initialize( const ColorUtils::Rgba& color, const WindowShadow& shadow ) { reset(); _size = int(shadow.shadowSize()) - WindowShadow::Overlap; // round tiles WindowShadowKey key; key.hasTopBorder = true; key.hasBottomBorder = true; _roundTiles = shadow.tileSet( color, key ); // square tiles key.hasTopBorder = false; key.hasBottomBorder = false; _squareTiles = shadow.tileSet( color, key ); // re-install shadows for all windowId for( WidgetMap::const_iterator iter = _widgets.begin(); iter != _widgets.end(); ++iter ) { installX11Shadows( iter->first ); } } //______________________________________________ bool ShadowHelper::registerWidget( GtkWidget* widget ) { // check widget if( !( widget && GTK_IS_WINDOW( widget ) ) ) return false; // make sure that widget is not already registered if( _widgets.find( widget ) != _widgets.end() ) return false; // check if window is accepted if( !acceptWindow( GTK_WINDOW( widget ) ) ) return false; // try install shadows installX11Shadows( widget ); // register in map and returns success WidgetData data; data._destroyId.connect( G_OBJECT( widget ), "destroy", G_CALLBACK( destroyNotifyEvent ), this ); _widgets.insert( std::make_pair( widget, data ) ); return true; } //______________________________________________ void ShadowHelper::unregisterWidget( GtkWidget* widget ) { // find matching data in map WidgetMap::iterator iter( _widgets.find( widget ) ); if( iter == _widgets.end() ) return; // disconnect iter->second._destroyId.disconnect(); // remove from map _widgets.erase( iter ); } //______________________________________________ void ShadowHelper::createPixmapHandles( void ) { // create atom if( !_atom ) { GdkScreen* screen = gdk_screen_get_default(); Display* display( GDK_DISPLAY_XDISPLAY( gdk_screen_get_display( screen ) ) ); _atom = XInternAtom( display, "_KDE_NET_WM_SHADOW", False); } // make sure size is valid if( _size <= 0 ) return; // make sure pixmaps are not already initialized if( _roundPixmaps.empty() ) { _roundPixmaps.push_back( createPixmap( _roundTiles.surface( 1 ) ) ); _roundPixmaps.push_back( createPixmap( _roundTiles.surface( 2 ) ) ); _roundPixmaps.push_back( createPixmap( _roundTiles.surface( 5 ) ) ); _roundPixmaps.push_back( createPixmap( _roundTiles.surface( 8 ) ) ); _roundPixmaps.push_back( createPixmap( _roundTiles.surface( 7 ) ) ); _roundPixmaps.push_back( createPixmap( _roundTiles.surface( 6 ) ) ); _roundPixmaps.push_back( createPixmap( _roundTiles.surface( 3 ) ) ); _roundPixmaps.push_back( createPixmap( _roundTiles.surface( 0 ) ) ); } if( _squarePixmaps.empty() ) { _squarePixmaps.push_back( createPixmap( _squareTiles.surface( 1 ) ) ); _squarePixmaps.push_back( createPixmap( _squareTiles.surface( 2 ) ) ); _squarePixmaps.push_back( createPixmap( _squareTiles.surface( 5 ) ) ); _squarePixmaps.push_back( createPixmap( _squareTiles.surface( 8 ) ) ); _squarePixmaps.push_back( createPixmap( _squareTiles.surface( 7 ) ) ); _squarePixmaps.push_back( createPixmap( _squareTiles.surface( 6 ) ) ); _squarePixmaps.push_back( createPixmap( _squareTiles.surface( 3 ) ) ); _squarePixmaps.push_back( createPixmap( _squareTiles.surface( 0 ) ) ); } } //______________________________________________ Pixmap ShadowHelper::createPixmap( const Cairo::Surface& surface ) const { assert( surface.isValid() ); const int width( cairo_surface_get_width( surface ) ); const int height( cairo_surface_get_height( surface ) ); GdkScreen* screen = gdk_screen_get_default(); Display* display( GDK_DISPLAY_XDISPLAY( gdk_screen_get_display( screen ) ) ); Window root( GDK_WINDOW_XID( gdk_screen_get_root_window( screen ) ) ); Pixmap pixmap = XCreatePixmap( display, root, width, height, 32 ); // create surface for pixmap { Cairo::Surface dest( cairo_xlib_surface_create( display, pixmap, GDK_VISUAL_XVISUAL( gdk_screen_get_rgba_visual( screen ) ), width, height ) ); Cairo::Context context( dest ); cairo_set_operator( context, CAIRO_OPERATOR_SOURCE ); cairo_rectangle( context, 0, 0, width, height ); cairo_set_source_surface( context, surface, 0, 0 ); cairo_fill( context ); } return pixmap; } //______________________________________________ void ShadowHelper::installX11Shadows( GtkWidget* widget ) { // check screen composited // TODO: check whether this is necessary // if( !Gtk::gdk_default_screen_is_composited() ) return; // make sure handles and atom are defined createPixmapHandles(); // check data size if( _roundPixmaps.size() != numPixmaps ) { std::cerr << "ShadowHelper::installX11Shadows - incorrect _roundPixmaps size: " << _roundPixmaps.size() << std::endl; return; } GdkWindow *window = gtk_widget_get_window( widget ); GdkDisplay *display = gtk_widget_get_display( widget ); std::vector<unsigned long> data; const bool isMenu( this->isMenu( widget ) ); if( _applicationName.isOpenOffice() || ( isMenu && _applicationName.isMozilla( widget ) ) ) { data = _squarePixmaps; data.push_back( _size ); data.push_back( _size ); data.push_back( _size ); data.push_back( _size ); } else { data = _roundPixmaps; if( isMenu ) { /* for menus, need to shrink top and bottom shadow size, since body is done likely with respect to real size in painting method (Oxygen::Style::renderMenuBackground) */ data.push_back( _size - Menu_VerticalOffset ); data.push_back( _size ); data.push_back( _size - Menu_VerticalOffset ); data.push_back( _size ); } else { // all sides have same sizz data.push_back( _size ); data.push_back( _size ); data.push_back( _size ); data.push_back( _size ); } } // change property XChangeProperty( GDK_DISPLAY_XDISPLAY( display ), GDK_WINDOW_XID(window), _atom, XA_CARDINAL, 32, PropModeReplace, reinterpret_cast<const unsigned char *>(&data[0]), data.size() ); } //_______________________________________________________ void ShadowHelper::uninstallX11Shadows( GtkWidget* widget ) const { if( !widget ) return; GdkWindow *window = gtk_widget_get_window( widget ); GdkDisplay *display = gtk_widget_get_display( widget ); XDeleteProperty( GDK_DISPLAY_XDISPLAY( display ), GDK_WINDOW_XID(window), _atom); } //_______________________________________________________ gboolean ShadowHelper::realizeHook( GSignalInvocationHint*, guint, const GValue* params, gpointer data ) { // get widget from params GtkWidget* widget( GTK_WIDGET( g_value_get_object( params ) ) ); // check type if( !GTK_IS_WIDGET( widget ) ) return FALSE; static_cast<ShadowHelper*>(data)->registerWidget( widget ); return TRUE; } //____________________________________________________________________________________________ gboolean ShadowHelper::destroyNotifyEvent( GtkWidget* widget, gpointer data ) { static_cast<ShadowHelper*>(data)->unregisterWidget( widget ); return FALSE; } } <commit_msg>cleanup.<commit_after>/* * this file is part of the oxygen gtk engine * Copyright (c) 2011 Hugo Pereira Da Costa <hugo@oxygen-icons.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or( at your option ) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "oxygencairocontext.h" #include "oxygencairoutils.h" #include "oxygengtkutils.h" #include "oxygenmetrics.h" #include "oxygenrgba.h" #include "oxygenshadowhelper.h" #include <iostream> #include <cairo/cairo.h> #include <cairo/cairo-xlib.h> #include <gdk/gdkx.h> #include <X11/Xatom.h> namespace Oxygen { //______________________________________________ ShadowHelper::ShadowHelper( void ): _size(0), _atom(0), _hooksInitialized( false ) {} //______________________________________________ ShadowHelper::~ShadowHelper( void ) { reset(); } //______________________________________________ void ShadowHelper::reset( void ) { GdkScreen* screen = gdk_screen_get_default(); Display* display( GDK_DISPLAY_XDISPLAY( gdk_screen_get_display( screen ) ) ); // round pixmaps for( PixmapList::const_iterator iter = _roundPixmaps.begin(); iter != _roundPixmaps.end(); ++iter ) { XFreePixmap(display, *iter); } _roundPixmaps.clear(); // square pixmaps for( PixmapList::const_iterator iter = _squarePixmaps.begin(); iter != _squarePixmaps.end(); ++iter ) { XFreePixmap(display, *iter); } _squarePixmaps.clear(); // reset size _size = 0; } //______________________________________________ void ShadowHelper::initializeHooks( void ) { if( _hooksInitialized ) return; // install hooks _realizeHook.connect( "realize", (GSignalEmissionHook)realizeHook, this ); _hooksInitialized = true; } //______________________________________________ void ShadowHelper::initialize( const ColorUtils::Rgba& color, const WindowShadow& shadow ) { reset(); _size = int(shadow.shadowSize()) - WindowShadow::Overlap; // round tiles WindowShadowKey key; key.hasTopBorder = true; key.hasBottomBorder = true; _roundTiles = shadow.tileSet( color, key ); // square tiles key.hasTopBorder = false; key.hasBottomBorder = false; _squareTiles = shadow.tileSet( color, key ); // re-install shadows for all windowId for( WidgetMap::const_iterator iter = _widgets.begin(); iter != _widgets.end(); ++iter ) { installX11Shadows( iter->first ); } } //______________________________________________ bool ShadowHelper::registerWidget( GtkWidget* widget ) { // check widget if( !( widget && GTK_IS_WINDOW( widget ) ) ) return false; // make sure that widget is not already registered if( _widgets.find( widget ) != _widgets.end() ) return false; // check if window is accepted if( !acceptWindow( GTK_WINDOW( widget ) ) ) return false; // try install shadows installX11Shadows( widget ); // register in map and returns success WidgetData data; data._destroyId.connect( G_OBJECT( widget ), "destroy", G_CALLBACK( destroyNotifyEvent ), this ); _widgets.insert( std::make_pair( widget, data ) ); return true; } //______________________________________________ void ShadowHelper::unregisterWidget( GtkWidget* widget ) { // find matching data in map WidgetMap::iterator iter( _widgets.find( widget ) ); if( iter == _widgets.end() ) return; // disconnect iter->second._destroyId.disconnect(); // remove from map _widgets.erase( iter ); } //______________________________________________ void ShadowHelper::createPixmapHandles( void ) { // create atom if( !_atom ) { GdkScreen* screen = gdk_screen_get_default(); Display* display( GDK_DISPLAY_XDISPLAY( gdk_screen_get_display( screen ) ) ); _atom = XInternAtom( display, "_KDE_NET_WM_SHADOW", False); } // make sure size is valid if( _size <= 0 ) return; // make sure pixmaps are not already initialized if( _roundPixmaps.empty() ) { _roundPixmaps.push_back( createPixmap( _roundTiles.surface( 1 ) ) ); _roundPixmaps.push_back( createPixmap( _roundTiles.surface( 2 ) ) ); _roundPixmaps.push_back( createPixmap( _roundTiles.surface( 5 ) ) ); _roundPixmaps.push_back( createPixmap( _roundTiles.surface( 8 ) ) ); _roundPixmaps.push_back( createPixmap( _roundTiles.surface( 7 ) ) ); _roundPixmaps.push_back( createPixmap( _roundTiles.surface( 6 ) ) ); _roundPixmaps.push_back( createPixmap( _roundTiles.surface( 3 ) ) ); _roundPixmaps.push_back( createPixmap( _roundTiles.surface( 0 ) ) ); } if( _squarePixmaps.empty() ) { _squarePixmaps.push_back( createPixmap( _squareTiles.surface( 1 ) ) ); _squarePixmaps.push_back( createPixmap( _squareTiles.surface( 2 ) ) ); _squarePixmaps.push_back( createPixmap( _squareTiles.surface( 5 ) ) ); _squarePixmaps.push_back( createPixmap( _squareTiles.surface( 8 ) ) ); _squarePixmaps.push_back( createPixmap( _squareTiles.surface( 7 ) ) ); _squarePixmaps.push_back( createPixmap( _squareTiles.surface( 6 ) ) ); _squarePixmaps.push_back( createPixmap( _squareTiles.surface( 3 ) ) ); _squarePixmaps.push_back( createPixmap( _squareTiles.surface( 0 ) ) ); } } //______________________________________________ Pixmap ShadowHelper::createPixmap( const Cairo::Surface& surface ) const { assert( surface.isValid() ); const int width( cairo_surface_get_width( surface ) ); const int height( cairo_surface_get_height( surface ) ); GdkScreen* screen = gdk_screen_get_default(); Display* display( GDK_DISPLAY_XDISPLAY( gdk_screen_get_display( screen ) ) ); Window root( GDK_WINDOW_XID( gdk_screen_get_root_window( screen ) ) ); Pixmap pixmap = XCreatePixmap( display, root, width, height, 32 ); // create surface for pixmap { Cairo::Surface dest( cairo_xlib_surface_create( display, pixmap, GDK_VISUAL_XVISUAL( gdk_screen_get_rgba_visual( screen ) ), width, height ) ); Cairo::Context context( dest ); cairo_set_operator( context, CAIRO_OPERATOR_SOURCE ); cairo_rectangle( context, 0, 0, width, height ); cairo_set_source_surface( context, surface, 0, 0 ); cairo_fill( context ); } return pixmap; } //______________________________________________ void ShadowHelper::installX11Shadows( GtkWidget* widget ) { // make sure handles and atom are defined createPixmapHandles(); GdkWindow *window = gtk_widget_get_window( widget ); GdkDisplay *display = gtk_widget_get_display( widget ); std::vector<unsigned long> data; const bool isMenu( this->isMenu( widget ) ); if( _applicationName.isOpenOffice() || ( isMenu && _applicationName.isMozilla( widget ) ) ) { data = _squarePixmaps; data.push_back( _size ); data.push_back( _size ); data.push_back( _size ); data.push_back( _size ); } else { data = _roundPixmaps; if( isMenu ) { /* for menus, need to shrink top and bottom shadow size, since body is done likely with respect to real size in painting method (Oxygen::Style::renderMenuBackground) */ data.push_back( _size - Menu_VerticalOffset ); data.push_back( _size ); data.push_back( _size - Menu_VerticalOffset ); data.push_back( _size ); } else { // all sides have same sizz data.push_back( _size ); data.push_back( _size ); data.push_back( _size ); data.push_back( _size ); } } // change property XChangeProperty( GDK_DISPLAY_XDISPLAY( display ), GDK_WINDOW_XID(window), _atom, XA_CARDINAL, 32, PropModeReplace, reinterpret_cast<const unsigned char *>(&data[0]), data.size() ); } //_______________________________________________________ void ShadowHelper::uninstallX11Shadows( GtkWidget* widget ) const { if( !widget ) return; GdkWindow *window = gtk_widget_get_window( widget ); GdkDisplay *display = gtk_widget_get_display( widget ); XDeleteProperty( GDK_DISPLAY_XDISPLAY( display ), GDK_WINDOW_XID(window), _atom); } //_______________________________________________________ gboolean ShadowHelper::realizeHook( GSignalInvocationHint*, guint, const GValue* params, gpointer data ) { // get widget from params GtkWidget* widget( GTK_WIDGET( g_value_get_object( params ) ) ); // check type if( !GTK_IS_WIDGET( widget ) ) return FALSE; static_cast<ShadowHelper*>(data)->registerWidget( widget ); return TRUE; } //____________________________________________________________________________________________ gboolean ShadowHelper::destroyNotifyEvent( GtkWidget* widget, gpointer data ) { static_cast<ShadowHelper*>(data)->unregisterWidget( widget ); return FALSE; } } <|endoftext|>
<commit_before>#include "forces.h" int granular_force(iREAL n[3], iREAL vij[3], iREAL oij[3], iREAL depth, int i, int j, iREAL mass[], iREAL invm[], iREAL *iparam[NINT], int ij, iREAL f[3]) { iREAL ma; if (j >= 0) ma = 1.0 / (invm[i] + invm[j]); else ma = mass[i]; iREAL kn = iparam[SPRING][ij]; iREAL en = iparam[DAMPER][ij] * 2.0 * sqrt(kn*ma); iREAL vn = DOT(vij,n); iREAL fn = kn*depth + en*vn; f[0] = fn*n[0]; f[1] = fn*n[1]; f[2] = fn*n[2]; /* TODO */ return depth < 0.0 ? 1 : 0; } /* return pairing index based on (i,j) pairing of colors */ int pairing (int nummat, int pairs[], int i, int j) { int p[2] = {i, j}, start = 1, end = nummat; if (i > j) { p[0] = j; p[1] = i; } while (start < end) { int mid = ((end-start)>>1) + start; if (p[0] > pairs[2*mid]) start = mid; else if(p[0] == pairs[2*mid]) { if (p[1] > pairs[2*mid+1]) start = mid; else if (p[1] == pairs[2*mid+1]) return mid; else end = mid; } else end = mid; } return 0; /* default material */ } void forces (master_conpnt master[], slave_conpnt slave[], int nt, int nb, bd *b, iREAL * angular[6], iREAL * linear[3], iREAL mass[], iREAL invm[], int parmat[], iREAL * mparam[NMAT], int pairnum, int pairs[], int ikind[], iREAL * iparam[NINT]) { for (int i = 0; i < nt; i++) { iREAL oi[3], v[3], x[3]; oi[0] = angular[3][i]; oi[1] = angular[4][i]; oi[2] = angular[5][i]; v[0] = linear[0][i]; v[1] = linear[1][i]; v[2] = linear[2][i]; x[0] = position[0][i]; x[1] = position[1][i]; x[2] = position[2][i]; /* update contact forces */ for (master_conpnt * con = &master[i]; con; con = con->next) { int gone[CONBUF]; for(int k = 0; k<con->size; k++) { iREAL p[3], n[3], z[3], vi[3], vj[3], oj[3], vij[3], oij[3]; p[0] = con->point[0][k]; p[1] = con->point[1][k]; p[2] = con->point[2][k]; n[0] = con->normal[0][k]; n[1] = con->normal[1][k]; n[2] = con->normal[2][k]; z[0] = p[0]-x[0]; z[1] = p[1]-x[1]; z[2] = p[2]-x[2]; vi[0] = oi[1]*z[2]-oi[2]*z[1] + v[0]; vi[1] = oi[2]*z[0]-oi[0]*z[2] + v[1]; vi[2] = oi[0]*z[1]-oi[1]*z[0] + v[2]; int j = con->slave[0][k]; if (j >= 0) // particle-particle { z[0] = p[0]-position[0][j]; z[1] = p[1]-position[1][j]; z[2] = p[2]-position[2][j]; oj[0] = angular[3][j]; oj[1] = angular[4][j]; oj[2] = angular[5][j]; vj[0] = oj[1]*z[2]-oj[2]*z[1] + linear[0][j]; vj[1] = oj[2]*z[0]-oj[0]*z[2] + linear[1][j]; vj[2] = oj[0]*z[1]-oj[1]*z[0] + linear[2][j]; } SUB (vj, vi, vij); // relative linear velocity SUB (oj, oi, oij); // relative angular velocity int ij = pairing (pairnum, pairs, con->color[0][k], con->color[1][k]); iREAL f[3]; switch (ikind[ij]) { case GRANULAR: gone[k] = granular_force (n, vij, oij, con->depth[k], i, j, mass, invm, iparam, ij, f); break; case BONDED: /* TODO */ break; case UFORCE: /* TODO */ break; default: //printf ("ERROR: invalid pairing kind"); break; } con->force[0][k] = f[0]; con->force[1][k] = f[1]; con->force[2][k] = f[2]; } int ngone = 0; for (int k = 0; k < con->size; k ++) { if (gone[k] != 0) { int j = k+1; while (j < con->size && gone[j] != 0) j ++; if (j < con->size) { con->master[k] = con->master[j]; con->slave[0][k] = con->slave[0][j]; con->slave[1][k] = con->slave[1][j]; con->color[0][k] = con->color[0][j]; con->color[1][k] = con->color[1][j]; con->point[0][k] = con->point[0][j]; con->point[1][k] = con->point[1][j]; con->point[2][k] = con->point[2][j]; con->normal[0][k] = con->normal[0][j]; con->normal[1][k] = con->normal[1][j]; con->normal[2][k] = con->normal[2][j]; con->depth[k] = con->depth[j]; con->force[0][k] = con->force[0][j]; con->force[1][k] = con->force[1][j]; con->force[2][k] = con->force[2][j]; gone[j] = -1; // not to be used again } if (gone[k] > 0) ngone ++; } } con->size -= ngone; } master_conpnt * con = master[i].next; while (con && con->next) // delete empty items { master_conpnt * next = con->next; if (next->size == 0) { con->next = next->next; delete next; } con = con->next; } /* symmetrical copy into slave contact points */ for (master_conpnt * con = &master[i]; con; con = con->next) { for (int j = 0; j < con->size; j ++) { slave_conpnt *ptr; int k=0; if (con->slave[0][j] >= 0) /* particle-particle contact */ { ptr = newcon (&slave[con->slave[0][j]], &k); ptr->master[0][k] = i; ptr->master[1][k] = con->master[j]; ptr->point[0][k] = con->point[0][j]; ptr->point[1][k] = con->point[1][j]; ptr->point[2][k] = con->point[2][j]; ptr->force[0][k] = -con->force[0][j]; ptr->force[1][k] = -con->force[1][j]; ptr->force[2][k] = -con->force[2][j]; } } } } } <commit_msg>master<commit_after>#include "forces.h" int granular_force(iREAL n[3], iREAL vij[3], iREAL oij[3], iREAL depth, int i, int j, iREAL mass[], iREAL invm[], iREAL *iparam[NINT], int ij, iREAL f[3]) { iREAL ma; if (j >= 0) ma = 1.0 / (invm[i] + invm[j]); else ma = mass[i]; iREAL kn = iparam[SPRING][ij]; iREAL en = iparam[DAMPER][ij] * 2.0 * sqrt(kn*ma); iREAL vn = DOT(vij,n); iREAL fn = kn*depth + en*vn; f[0] = fn*n[0]; f[1] = fn*n[1]; f[2] = fn*n[2]; /* TODO */ return depth < 0.0 ? 1 : 0; } /* return pairing index based on (i,j) pairing of colors */ int pairing (int nummat, int pairs[], int i, int j) { int p[2] = {i, j}, start = 1, end = nummat; if (i > j) { p[0] = j; p[1] = i; } while (start < end) { int mid = ((end-start)>>1) + start; if (p[0] > pairs[2*mid]) start = mid; else if(p[0] == pairs[2*mid]) { if (p[1] > pairs[2*mid+1]) start = mid; else if (p[1] == pairs[2*mid+1]) return mid; else end = mid; } else end = mid; } return 0; /* default material */ } void forces (master_conpnt master[], slave_conpnt slave[], int nt, int nb, bd *b, iREAL * angular[6], iREAL * linear[3], iREAL mass[], iREAL invm[], int parmat[], iREAL * mparam[NMAT], int pairnum, int pairs[], int ikind[], iREAL * iparam[NINT]) { for (int i = 0; i < nt; i++) { iREAL oi[3], v[3], x[3]; oi[0] = angular[3][i]; oi[1] = angular[4][i]; oi[2] = angular[5][i]; v[0] = linear[0][i]; v[1] = linear[1][i]; v[2] = linear[2][i]; x[0] = position[0][i]; x[1] = position[1][i]; x[2] = position[2][i]; /* update contact forces */ for (master_conpnt * con = &master[i]; con; con = con->next) { int gone[CONBUF]; for(int k = 0; k<con->size; k++) { iREAL p[3], n[3], z[3], vi[3], vj[3], oj[3], vij[3], oij[3]; p[0] = con->point[0][k]; p[1] = con->point[1][k]; p[2] = con->point[2][k]; n[0] = con->normal[0][k]; n[1] = con->normal[1][k]; n[2] = con->normal[2][k]; z[0] = p[0]-x[0]; z[1] = p[1]-x[1]; z[2] = p[2]-x[2]; vi[0] = oi[1]*z[2]-oi[2]*z[1] + v[0]; vi[1] = oi[2]*z[0]-oi[0]*z[2] + v[1]; vi[2] = oi[0]*z[1]-oi[1]*z[0] + v[2]; int j = con->slave[0][k]; if (j >= 0) // particle-particle { z[0] = p[0]-position[0][j]; z[1] = p[1]-position[1][j]; z[2] = p[2]-position[2][j]; oj[0] = angular[3][j]; oj[1] = angular[4][j]; oj[2] = angular[5][j]; vj[0] = oj[1]*z[2]-oj[2]*z[1] + linear[0][j]; vj[1] = oj[2]*z[0]-oj[0]*z[2] + linear[1][j]; vj[2] = oj[0]*z[1]-oj[1]*z[0] + linear[2][j]; } SUB (vj, vi, vij); // relative linear velocity SUB (oj, oi, oij); // relative angular velocity int ij = pairing (pairnum, pairs, con->color[0][k], con->color[1][k]); iREAL f[3]; switch (ikind[ij]) { case GRANULAR: gone[k] = granular_force (n, vij, oij, con->depth[k], i, j, mass, invm, iparam, ij, f); break; case BONDED: /* TODO */ break; case UFORCE: /* TODO */ break; default: //printf ("ERROR: invalid pairing kind"); break; } con->force[0][k] = f[0]; con->force[1][k] = f[1]; con->force[2][k] = f[2]; } int ngone = 0; for (int k = 0; k < con->size; k ++) { if (gone[k] != 0) { int j = k+1; while (j < con->size && gone[j] != 0) j ++; if (j < con->size) { con->master[k] = con->master[j]; con->slave[0][k] = con->slave[0][j]; con->slave[1][k] = con->slave[1][j]; con->color[0][k] = con->color[0][j]; con->color[1][k] = con->color[1][j]; con->point[0][k] = con->point[0][j]; con->point[1][k] = con->point[1][j]; con->point[2][k] = con->point[2][j]; con->normal[0][k] = con->normal[0][j]; con->normal[1][k] = con->normal[1][j]; con->normal[2][k] = con->normal[2][j]; con->depth[k] = con->depth[j]; con->force[0][k] = con->force[0][j]; con->force[1][k] = con->force[1][j]; con->force[2][k] = con->force[2][j]; gone[j] = -1; // not to be used again } if (gone[k] > 0) ngone ++; } } con->size -= ngone; } master_conpnt * con = master[i].next; while (con && con->next) // delete empty items { master_conpnt * next = con->next; if (next->size == 0) { con->next = next->next; delete next; } con = con->next; } /* symmetrical copy into slave contact points */ for (master_conpnt * con = &master[i]; con; con = con->next) { for (int j = 0; j < con->size; j ++) { slave_conpnt *ptr; int k=0; if (con->slave[0][j] >= 0) /* particle-particle contact */ { ptr = newcon (&slave[con->slave[0][j]], &k); ptr->master[0][k] = i; ptr->master[1][k] = con->master[j]; ptr->point[0][k] = con->point[0][j]; ptr->point[1][k] = con->point[1][j]; ptr->point[2][k] = con->point[2][j]; ptr->force[0][k] = -con->force[0][j]; ptr->force[1][k] = -con->force[1][j]; ptr->force[2][k] = -con->force[2][j]; } } } } } <|endoftext|>
<commit_before>/***************************************************************************** * Number Plate Recognition using SVM and Neural Networks ****************************************************************************** * by David Milln Escriv, 5th Dec 2012 * http://blog.damiles.com ****************************************************************************** * Ch5 of the book "Mastering OpenCV with Practical Computer Vision Projects" * Copyright Packt Publishing 2012. * http://www.packtpub.com/cool-projects-with-opencv/book *****************************************************************************/ // Main entry code OpenCV #include <cv.h> #include <highgui.h> #include <cvaux.h> #include "OCR.h" #include <iostream> #include <vector> using namespace std; using namespace cv; const int numFilesChars[]={35, 40, 42, 41, 42, 33, 30, 31, 49, 44, 30, 24, 21, 20, 34, 9, 10, 3, 11, 3, 15, 4, 9, 12, 10, 21, 18, 8, 15, 7}; int main ( int argc, char** argv ) { cout << "OpenCV Training OCR Automatic Number Plate Recognition\n"; cout << "\n"; char* path; //Check if user specify image to process if(argc >= 1 ) { path= argv[1]; }else{ cout << "Usage:\n" << argv[0] << " <path to chars folders files> \n"; return 0; } Mat classes; Mat trainingDataf5; Mat trainingDataf10; Mat trainingDataf15; Mat trainingDataf20; vector<int> trainingLabels; OCR ocr; for(int i=0; i< OCR::numCharacters; i++) { int numFiles=numFilesChars[i]; for(int j=0; j< numFiles; j++){ cout << "Character "<< OCR::strCharacters[i] << " file: " << j << "\n"; stringstream ss(stringstream::in | stringstream::out); ss << path << OCR::strCharacters[i] << "/" << j << ".jpg"; Mat img=imread(ss.str(), 0); Mat f5=ocr.features(img, 5); Mat f10=ocr.features(img, 10); Mat f15=ocr.features(img, 15); Mat f20=ocr.features(img, 20); trainingDataf5.push_back(f5); trainingDataf10.push_back(f10); trainingDataf15.push_back(f15); trainingDataf20.push_back(f20); trainingLabels.push_back(i); } } trainingDataf5.convertTo(trainingDataf5, CV_32FC1); trainingDataf10.convertTo(trainingDataf10, CV_32FC1); trainingDataf15.convertTo(trainingDataf15, CV_32FC1); trainingDataf20.convertTo(trainingDataf20, CV_32FC1); Mat(trainingLabels).copyTo(classes); FileStorage fs("OCR.xml", FileStorage::WRITE); fs << "TrainingDataF5" << trainingDataf5; fs << "TrainingDataF10" << trainingDataf10; fs << "TrainingDataF15" << trainingDataf15; fs << "TrainingDataF20" << trainingDataf20; fs << "classes" << classes; fs.release(); return 0; } <commit_msg>OCR train<commit_after>/***************************************************************************** * Number Plate Recognition using SVM and Neural Networks ****************************************************************************** */ // Main entry code OpenCV #include <cv.h> #include <highgui.h> #include <cvaux.h> #include "OCR.h" #include <iostream> #include <vector> using namespace std; using namespace cv; const int numFilesChars[]={35, 40, 42, 41, 42, 33, 30, 31, 49, 44, 30, 24, 21, 20, 34, 9, 10, 3, 11, 3, 15, 4, 9, 12, 10, 21, 18, 8, 15, 7}; int main ( int argc, char** argv ) { cout << "OpenCV Training OCR Automatic Number Plate Recognition\n"; cout << "\n"; char* path; //Check if user specify image to process if(argc >= 1 ) { path= argv[1]; }else{ cout << "Usage:\n" << argv[0] << " <path to chars folders files> \n"; return 0; } Mat classes; Mat trainingDataf5; Mat trainingDataf10; Mat trainingDataf15; Mat trainingDataf20; vector<int> trainingLabels; OCR ocr; for(int i=0; i< OCR::numCharacters; i++) { int numFiles=numFilesChars[i]; for(int j=0; j< numFiles; j++){ cout << "Character "<< OCR::strCharacters[i] << " file: " << j << "\n"; stringstream ss(stringstream::in | stringstream::out); ss << path << OCR::strCharacters[i] << "/" << j << ".jpg"; Mat img=imread(ss.str(), 0); Mat f5=ocr.features(img, 5); Mat f10=ocr.features(img, 10); Mat f15=ocr.features(img, 15); Mat f20=ocr.features(img, 20); trainingDataf5.push_back(f5); trainingDataf10.push_back(f10); trainingDataf15.push_back(f15); trainingDataf20.push_back(f20); trainingLabels.push_back(i); } } trainingDataf5.convertTo(trainingDataf5, CV_32FC1); trainingDataf10.convertTo(trainingDataf10, CV_32FC1); trainingDataf15.convertTo(trainingDataf15, CV_32FC1); trainingDataf20.convertTo(trainingDataf20, CV_32FC1); Mat(trainingLabels).copyTo(classes); FileStorage fs("OCR.xml", FileStorage::WRITE); fs << "TrainingDataF5" << trainingDataf5; fs << "TrainingDataF10" << trainingDataf10; fs << "TrainingDataF15" << trainingDataf15; fs << "TrainingDataF20" << trainingDataf20; fs << "classes" << classes; fs.release(); return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #ifdef __BORLANDC__ #define ITK_LEAN_AND_MEAN #endif // Software Guide : BeginCommandLineArgs // INPUTS: {NDVI_2.hdr} , {NDVI_3.hdr} // OUTPUTS: {NDVIRAndNIRVegetationIndex.tif} , {pretty_Red.png} , {pretty_NIR.png} , {pretty_NDVIRAndNIRVegetationIndex.png} // Software Guide : EndCommandLineArgs // Software Guide : BeginLatex // // \index{otb::RAndNIRVegetationIndexImageFilter} // \index{otb::VegetationIndex} // \index{otb::VegetationIndex!header} // // The following example illustrates the use of the // \doxygen{otb}{RAndNIRVegetationIndexImageFilter} with the use of the Normalized // Difference Vegatation Index (NDVI). // NDVI computes the difference between the NIR channel, noted $L_{NIR}$, and the red channel, // noted $L_{r}$ radiances reflected from the surface and transmitted through the atmosphere: // // \begin{equation} // \mathbf{NDVI} = \frac{L_{NIR}-L_{r}}{L_{NIR}+L_{r}} // \end{equation} // // With the \doxygen{otb}{RAndNIRVegetationIndexImageFilter} class the filter // inputs are one channel images: one inmage represents the NIR channel, the // the other the NIR channel. // // Let's look at the minimal code required to use this algorithm. First, the following header // defining the \doxygen{otb}{RAndNIRVegetationIndexImageFilter} // class must be included. // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "otbRAndNIRVegetationIndexImageFilter.h" // Software Guide : EndCodeSnippet #include "itkExceptionObject.h" #include "otbImage.h" #include "otbImageFileReader.h" #include "otbImageFileWriter.h" #include "itkRescaleIntensityImageFilter.h" int main( int argc, char *argv[] ) { if ( argc < 6 ) { std::cerr << "Missing Parameters " << std::endl; std::cerr << "Usage: " << argv[0]; std::cerr << " inputImage1 , inputImage2 , outputImage , prettyinputImage1 , prettyinputImage2 , prettyOutput" << std::endl; return 1; } // Software Guide : BeginLatex // // The image types are now defined using pixel types the // dimension. Input and output images are defined as \doxygen{otb}{Image}. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet const unsigned int Dimension = 2; typedef double InputPixelType; typedef float OutputPixelType; typedef otb::Image<InputPixelType,Dimension> InputRImageType; typedef otb::Image<InputPixelType,Dimension> InputNIRImageType; typedef otb::Image<OutputPixelType,Dimension> OutputImageType; // Software Guide : EndCodeSnippet // We instantiate reader and writer types typedef otb::ImageFileReader<InputRImageType> RReaderType; typedef otb::ImageFileReader<InputNIRImageType> NIRReaderType; typedef otb::ImageFileWriter<OutputImageType> WriterType; // Software Guide : BeginLatex // // The NDVI (Normalized Difference Vegetation Index) is instantiated using // the images pixel type as template parameters. It is // implemented as a functor class which will be passed as a // parameter to an \doxygen{otb}{RAndNIRVegetationIndexImageFilter}. // Note that we also can use other functors which operate with the // Red and Nir channels, such as PVI, RVI, SAVI, MSAVI, TSAVI, GEMI, // WDVI, IPVI, and TNDVI. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::Functor::NDVI< InputPixelType, InputPixelType, OutputPixelType> FunctorType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The \doxygen{otb}{RAndNIRVegetationIndexImageFilter} type is instantiated using the images // types and the NDVI functor as template parameters. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::RAndNIRVegetationIndexImageFilter<InputRImageType, InputNIRImageType, OutputImageType, FunctorType> RAndNIRVegetationIndexImageFilterType; // Software Guide : EndCodeSnippet // Instantiating object RAndNIRVegetationIndexImageFilterType::Pointer filter = RAndNIRVegetationIndexImageFilterType::New(); RReaderType::Pointer readerR = RReaderType::New(); NIRReaderType::Pointer readerNIR = NIRReaderType::New(); WriterType::Pointer writer = WriterType::New(); // Software Guide : BeginLatex // // Now the input images are set and a name is given to the output image. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet readerR->SetFileName( argv[1] ); readerNIR->SetFileName( argv[2] ); writer->SetFileName( argv[3] ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We set the processing pipeline: filter inputs are linked to // the reader output and the filter output is linked to the writer // input. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet filter->SetInputR( readerR->GetOutput() ); filter->SetInputNIR( readerNIR->GetOutput() ); writer->SetInput( filter->GetOutput() ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Invocation of the \code{Update()} method on the writer triggers the // execution of the pipeline. It is recommended to place \code{update()} calls in a // \code{try/catch} block in case errors occur and exceptions are thrown. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet try { writer->Update(); } catch ( itk::ExceptionObject & excep ) { std::cerr << "Exception caught !" << std::endl; std::cerr << excep << std::endl; } // Software Guide : EndCodeSnippet catch ( ... ) { std::cout << "Unknown exception !" << std::endl; return EXIT_FAILURE; } // Pretty image creation for the printing typedef otb::Image<unsigned char, Dimension> OutputPrettyImageType; typedef otb::ImageFileWriter<OutputPrettyImageType> WriterPrettyType; typedef itk::RescaleIntensityImageFilter< OutputImageType, OutputPrettyImageType> RescalerType; typedef itk::RescaleIntensityImageFilter< InputRImageType, OutputPrettyImageType> RescalerRType; typedef itk::RescaleIntensityImageFilter< InputNIRImageType, OutputPrettyImageType> RescalerNIRType; RescalerType::Pointer rescaler = RescalerType::New(); WriterPrettyType::Pointer prettyWriter = WriterPrettyType::New(); rescaler->SetInput( filter->GetOutput() ); rescaler->SetOutputMinimum(0); rescaler->SetOutputMaximum(255); prettyWriter->SetFileName( argv[6] ); prettyWriter->SetInput( rescaler->GetOutput() ); RescalerRType::Pointer rescalerR = RescalerRType::New(); RescalerNIRType::Pointer rescalerNIR = RescalerNIRType::New(); WriterPrettyType::Pointer prettyWriterR = WriterPrettyType::New(); WriterPrettyType::Pointer prettyWriterNIR = WriterPrettyType::New(); rescalerR->SetInput( readerR->GetOutput() ); rescalerR->SetOutputMinimum(0); rescalerR->SetOutputMaximum(255); prettyWriterR->SetFileName( argv[4] ); prettyWriterR->SetInput( rescalerR->GetOutput() ); rescalerNIR->SetInput( readerNIR->GetOutput() ); rescalerNIR->SetOutputMinimum(0); rescalerNIR->SetOutputMaximum(255); prettyWriterNIR->SetFileName( argv[5] ); prettyWriterNIR->SetInput( rescalerNIR->GetOutput() ); try { prettyWriter->Update(); prettyWriterNIR->Update(); prettyWriterR->Update(); } catch ( itk::ExceptionObject & excep ) { std::cerr << "Exception caught !" << std::endl; std::cerr << excep << std::endl; } catch ( ... ) { std::cout << "Unknown exception !" << std::endl; return EXIT_FAILURE; } // Software Guide : BeginLatex // // Let's now run this example using as input the images // \code{NDVI\_3.hdr} and \code{NDVI\_4.hdr} (images kindly and free of charge given by SISA and CNES) // provided in the directory \code{Examples/Data}. // // // \begin{figure} \center // \includegraphics[width=0.24\textwidth]{pretty_Red.eps} // \includegraphics[width=0.24\textwidth]{pretty_NIR.eps} // \includegraphics[width=0.24\textwidth]{pretty_NDVIRAndNIRVegetationIndex.eps} // \itkcaption[ARVI Example]{NDVI input images on the left (Red channel and NIR channel), on the right the result of the algorithm.} // \label{fig:NDVIRAndNIRVegetationIndex} // \end{figure} // // Software Guide : EndLatex return EXIT_SUCCESS; } <commit_msg>DOC: Added related classes to NDVI<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #ifdef __BORLANDC__ #define ITK_LEAN_AND_MEAN #endif // Software Guide : BeginCommandLineArgs // INPUTS: {NDVI_2.hdr} , {NDVI_3.hdr} // OUTPUTS: {NDVIRAndNIRVegetationIndex.tif} , {pretty_Red.png} , {pretty_NIR.png} , {pretty_NDVIRAndNIRVegetationIndex.png} // Software Guide : EndCommandLineArgs // Software Guide : BeginLatex // // \index{otb::RAndNIRVegetationIndexImageFilter} // \index{otb::VegetationIndex} // \index{otb::VegetationIndex!header} // // The following example illustrates the use of the // \doxygen{otb}{RAndNIRVegetationIndexImageFilter} with the use of the Normalized // Difference Vegatation Index (NDVI). // NDVI computes the difference between the NIR channel, noted $L_{NIR}$, and the red channel, // noted $L_{r}$ radiances reflected from the surface and transmitted through the atmosphere: // // \begin{equation} // \mathbf{NDVI} = \frac{L_{NIR}-L_{r}}{L_{NIR}+L_{r}} // \end{equation} // // \relatedClasses // \begin{itemize} // \item \subdoxygen{otb}{Functor}{RVI} // \item \subdoxygen{otb}{Functor}{PVI} // \item \subdoxygen{otb}{Functor}{SAVI} // \item \subdoxygen{otb}{Functor}{TSAVI} // \item \subdoxygen{otb}{Functor}{MSAVI} // \item \subdoxygen{otb}{Functor}{GEMI} // \item \subdoxygen{otb}{Functor}{WDVI} // \item \subdoxygen{otb}{Functor}{IPVI} // \item \subdoxygen{otb}{Functor}{TNDVI} // \end{itemize} // With the \doxygen{otb}{RAndNIRVegetationIndexImageFilter} class the filter // inputs are one channel images: one inmage represents the NIR channel, the // the other the NIR channel. // // Let's look at the minimal code required to use this algorithm. First, the following header // defining the \doxygen{otb}{RAndNIRVegetationIndexImageFilter} // class must be included. // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "otbRAndNIRVegetationIndexImageFilter.h" // Software Guide : EndCodeSnippet #include "itkExceptionObject.h" #include "otbImage.h" #include "otbImageFileReader.h" #include "otbImageFileWriter.h" #include "itkRescaleIntensityImageFilter.h" int main( int argc, char *argv[] ) { if ( argc < 6 ) { std::cerr << "Missing Parameters " << std::endl; std::cerr << "Usage: " << argv[0]; std::cerr << " inputImage1 , inputImage2 , outputImage , prettyinputImage1 , prettyinputImage2 , prettyOutput" << std::endl; return 1; } // Software Guide : BeginLatex // // The image types are now defined using pixel types the // dimension. Input and output images are defined as \doxygen{otb}{Image}. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet const unsigned int Dimension = 2; typedef double InputPixelType; typedef float OutputPixelType; typedef otb::Image<InputPixelType,Dimension> InputRImageType; typedef otb::Image<InputPixelType,Dimension> InputNIRImageType; typedef otb::Image<OutputPixelType,Dimension> OutputImageType; // Software Guide : EndCodeSnippet // We instantiate reader and writer types typedef otb::ImageFileReader<InputRImageType> RReaderType; typedef otb::ImageFileReader<InputNIRImageType> NIRReaderType; typedef otb::ImageFileWriter<OutputImageType> WriterType; // Software Guide : BeginLatex // // The NDVI (Normalized Difference Vegetation Index) is instantiated using // the images pixel type as template parameters. It is // implemented as a functor class which will be passed as a // parameter to an \doxygen{otb}{RAndNIRVegetationIndexImageFilter}. // Note that we also can use other functors which operate with the // Red and Nir channels, such as PVI, RVI, SAVI, MSAVI, TSAVI, GEMI, // WDVI, IPVI, and TNDVI. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::Functor::NDVI< InputPixelType, InputPixelType, OutputPixelType> FunctorType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The \doxygen{otb}{RAndNIRVegetationIndexImageFilter} type is instantiated using the images // types and the NDVI functor as template parameters. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::RAndNIRVegetationIndexImageFilter<InputRImageType, InputNIRImageType, OutputImageType, FunctorType> RAndNIRVegetationIndexImageFilterType; // Software Guide : EndCodeSnippet // Instantiating object RAndNIRVegetationIndexImageFilterType::Pointer filter = RAndNIRVegetationIndexImageFilterType::New(); RReaderType::Pointer readerR = RReaderType::New(); NIRReaderType::Pointer readerNIR = NIRReaderType::New(); WriterType::Pointer writer = WriterType::New(); // Software Guide : BeginLatex // // Now the input images are set and a name is given to the output image. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet readerR->SetFileName( argv[1] ); readerNIR->SetFileName( argv[2] ); writer->SetFileName( argv[3] ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We set the processing pipeline: filter inputs are linked to // the reader output and the filter output is linked to the writer // input. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet filter->SetInputR( readerR->GetOutput() ); filter->SetInputNIR( readerNIR->GetOutput() ); writer->SetInput( filter->GetOutput() ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Invocation of the \code{Update()} method on the writer triggers the // execution of the pipeline. It is recommended to place \code{update()} calls in a // \code{try/catch} block in case errors occur and exceptions are thrown. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet try { writer->Update(); } catch ( itk::ExceptionObject & excep ) { std::cerr << "Exception caught !" << std::endl; std::cerr << excep << std::endl; } // Software Guide : EndCodeSnippet catch ( ... ) { std::cout << "Unknown exception !" << std::endl; return EXIT_FAILURE; } // Pretty image creation for the printing typedef otb::Image<unsigned char, Dimension> OutputPrettyImageType; typedef otb::ImageFileWriter<OutputPrettyImageType> WriterPrettyType; typedef itk::RescaleIntensityImageFilter< OutputImageType, OutputPrettyImageType> RescalerType; typedef itk::RescaleIntensityImageFilter< InputRImageType, OutputPrettyImageType> RescalerRType; typedef itk::RescaleIntensityImageFilter< InputNIRImageType, OutputPrettyImageType> RescalerNIRType; RescalerType::Pointer rescaler = RescalerType::New(); WriterPrettyType::Pointer prettyWriter = WriterPrettyType::New(); rescaler->SetInput( filter->GetOutput() ); rescaler->SetOutputMinimum(0); rescaler->SetOutputMaximum(255); prettyWriter->SetFileName( argv[6] ); prettyWriter->SetInput( rescaler->GetOutput() ); RescalerRType::Pointer rescalerR = RescalerRType::New(); RescalerNIRType::Pointer rescalerNIR = RescalerNIRType::New(); WriterPrettyType::Pointer prettyWriterR = WriterPrettyType::New(); WriterPrettyType::Pointer prettyWriterNIR = WriterPrettyType::New(); rescalerR->SetInput( readerR->GetOutput() ); rescalerR->SetOutputMinimum(0); rescalerR->SetOutputMaximum(255); prettyWriterR->SetFileName( argv[4] ); prettyWriterR->SetInput( rescalerR->GetOutput() ); rescalerNIR->SetInput( readerNIR->GetOutput() ); rescalerNIR->SetOutputMinimum(0); rescalerNIR->SetOutputMaximum(255); prettyWriterNIR->SetFileName( argv[5] ); prettyWriterNIR->SetInput( rescalerNIR->GetOutput() ); try { prettyWriter->Update(); prettyWriterNIR->Update(); prettyWriterR->Update(); } catch ( itk::ExceptionObject & excep ) { std::cerr << "Exception caught !" << std::endl; std::cerr << excep << std::endl; } catch ( ... ) { std::cout << "Unknown exception !" << std::endl; return EXIT_FAILURE; } // Software Guide : BeginLatex // // Let's now run this example using as input the images // \code{NDVI\_3.hdr} and \code{NDVI\_4.hdr} (images kindly and free of charge given by SISA and CNES) // provided in the directory \code{Examples/Data}. // // // \begin{figure} \center // \includegraphics[width=0.24\textwidth]{pretty_Red.eps} // \includegraphics[width=0.24\textwidth]{pretty_NIR.eps} // \includegraphics[width=0.24\textwidth]{pretty_NDVIRAndNIRVegetationIndex.eps} // \itkcaption[ARVI Example]{NDVI input images on the left (Red channel and NIR channel), on the right the result of the algorithm.} // \label{fig:NDVIRAndNIRVegetationIndex} // \end{figure} // // Software Guide : EndLatex return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "TypeDefinition.h" fint fwcslen(fwchar_t* str) { fint counter=0; fwchar_t* tmpstr = str; while(*tmpstr != 0) { tmpstr++; counter++; } return counter; } fint fwcscmp(fwchar_t* str1, fwchar_t* str2) { fwchar_t* tmpstr1 = str1; fwchar_t* tmpstr2 = str2; while(*tmpstr1 != 0 || *tmpstr2 !=0) { if (*tmpstr1 != *tmpstr2) return -1; tmpstr1++; tmpstr2++; } return 0; }<commit_msg>Fontlib crash on em64t fix<commit_after>#include "TypeDefinition.h" fint fwcslen(fwchar_t* str) { if (!str) return 0; fint counter=0; fwchar_t* tmpstr = str; while(*tmpstr != 0) { tmpstr++; counter++; } return counter; } fint fwcscmp(fwchar_t* str1, fwchar_t* str2) { if (str1 == 0 || str2 == 0) return str1 - str2; fwchar_t* tmpstr1 = str1; fwchar_t* tmpstr2 = str2; while(*tmpstr1 != 0 || *tmpstr2 !=0) { if (*tmpstr1 != *tmpstr2) return -1; tmpstr1++; tmpstr2++; } return 0; }<|endoftext|>
<commit_before>/** * Copyright (C) 2013 Regents of the University of California. * @author: Jeff Thompson <jefft0@remap.ucla.edu> * See COPYING for copyright and distribution information. */ #ifndef NDN_SHA256_WITH_RSA_SIGNATURE_HPP #define NDN_SHA256_WITH_RSA_SIGNATURE_HPP #include "data.hpp" #include "publisher-public-key-digest.hpp" namespace ndn { /** * A Sha256WithRsaSignature extends Signature and holds the signature bits and other info representing a * SHA256-with-RSA signature in a data packet. */ class Sha256WithRsaSignature : public Signature { public: /** * Return a pointer to a new Sha256WithRsaSignature which is a copy of this signature. */ virtual ptr_lib::shared_ptr<Signature> clone() const; /** * Set the signatureStruct to point to the values in this signature object, without copying any memory. * WARNING: The resulting pointers in signatureStruct are invalid after a further use of this object which could reallocate memory. * @param signatureStruct a C ndn_Signature struct where the name components array is already allocated. */ virtual void get(struct ndn_Signature& signatureStruct) const; /** * Clear this signature, and set the values by copying from the ndn_Signature struct. * @param signatureStruct a C ndn_Signature struct */ virtual void set(const struct ndn_Signature& signatureStruct); const Blob& getDigestAlgorithm() const { return digestAlgorithm_; } const Blob& getWitness() const { return witness_; } const Blob& getSignature() const { return signature_; } const PublisherPublicKeyDigest& getPublisherPublicKeyDigest() const { return publisherPublicKeyDigest_; } PublisherPublicKeyDigest& getPublisherPublicKeyDigest() { return publisherPublicKeyDigest_; } const KeyLocator& getKeyLocator() const { return keyLocator_; } KeyLocator& getKeyLocator() { return keyLocator_; } void setDigestAlgorithm(const std::vector<unsigned char>& digestAlgorithm) { digestAlgorithm_ = digestAlgorithm; } void setDigestAlgorithm(const unsigned char *digestAlgorithm, unsigned int digestAlgorithmLength) { digestAlgorithm_ = Blob(digestAlgorithm, digestAlgorithmLength); } void setWitness(const std::vector<unsigned char>& witness) { witness_ = witness; } void setWitness(const unsigned char *witness, unsigned int witnessLength) { witness_ = Blob(witness, witnessLength); } void setSignature(const std::vector<unsigned char>& signature) { signature_ = signature; } void setSignature(const unsigned char *signature, unsigned int signatureLength) { signature_ = Blob(signature, signatureLength); } void setPublisherPublicKeyDigest(const PublisherPublicKeyDigest& publisherPublicKeyDigest) { publisherPublicKeyDigest_ = publisherPublicKeyDigest; } void setKeyLocator(const KeyLocator& keyLocator) { keyLocator_ = keyLocator; } /** * Clear all the fields. */ void clear() { digestAlgorithm_.reset(); witness_.reset(); signature_.reset(); publisherPublicKeyDigest_.clear(); keyLocator_.clear(); } private: Blob digestAlgorithm_; /**< if empty, the default is 2.16.840.1.101.3.4.2.1 (sha-256) */ Blob witness_; Blob signature_; PublisherPublicKeyDigest publisherPublicKeyDigest_; KeyLocator keyLocator_; }; } #endif <commit_msg>security: Added setSignature for Blob.<commit_after>/** * Copyright (C) 2013 Regents of the University of California. * @author: Jeff Thompson <jefft0@remap.ucla.edu> * See COPYING for copyright and distribution information. */ #ifndef NDN_SHA256_WITH_RSA_SIGNATURE_HPP #define NDN_SHA256_WITH_RSA_SIGNATURE_HPP #include "data.hpp" #include "key.hpp" #include "publisher-public-key-digest.hpp" namespace ndn { /** * A Sha256WithRsaSignature extends Signature and holds the signature bits and other info representing a * SHA256-with-RSA signature in a data packet. */ class Sha256WithRsaSignature : public Signature { public: /** * Return a pointer to a new Sha256WithRsaSignature which is a copy of this signature. */ virtual ptr_lib::shared_ptr<Signature> clone() const; /** * Set the signatureStruct to point to the values in this signature object, without copying any memory. * WARNING: The resulting pointers in signatureStruct are invalid after a further use of this object which could reallocate memory. * @param signatureStruct a C ndn_Signature struct where the name components array is already allocated. */ virtual void get(struct ndn_Signature& signatureStruct) const; /** * Clear this signature, and set the values by copying from the ndn_Signature struct. * @param signatureStruct a C ndn_Signature struct */ virtual void set(const struct ndn_Signature& signatureStruct); const Blob& getDigestAlgorithm() const { return digestAlgorithm_; } const Blob& getWitness() const { return witness_; } const Blob& getSignature() const { return signature_; } const PublisherPublicKeyDigest& getPublisherPublicKeyDigest() const { return publisherPublicKeyDigest_; } PublisherPublicKeyDigest& getPublisherPublicKeyDigest() { return publisherPublicKeyDigest_; } const KeyLocator& getKeyLocator() const { return keyLocator_; } KeyLocator& getKeyLocator() { return keyLocator_; } void setDigestAlgorithm(const std::vector<unsigned char>& digestAlgorithm) { digestAlgorithm_ = digestAlgorithm; } void setDigestAlgorithm(const unsigned char *digestAlgorithm, unsigned int digestAlgorithmLength) { digestAlgorithm_ = Blob(digestAlgorithm, digestAlgorithmLength); } void setWitness(const std::vector<unsigned char>& witness) { witness_ = witness; } void setWitness(const unsigned char *witness, unsigned int witnessLength) { witness_ = Blob(witness, witnessLength); } void setSignature(const std::vector<unsigned char>& signature) { signature_ = signature; } void setSignature(const unsigned char *signature, unsigned int signatureLength) { signature_ = Blob(signature, signatureLength); } /** * Set signature to point to an existing byte array. IMPORTANT: After calling this, * if you keep a pointer to the array then you must treat the array as immutable and promise not to change it. * @param signature A pointer to a vector with the byte array. This takes another reference and does not copy the bytes. */ void setSignature(const ptr_lib::shared_ptr<std::vector<unsigned char> > &signature) { signature_ = signature; } void setSignature(const ptr_lib::shared_ptr<const std::vector<unsigned char> > &signature) { signature_ = signature; } void setPublisherPublicKeyDigest(const PublisherPublicKeyDigest& publisherPublicKeyDigest) { publisherPublicKeyDigest_ = publisherPublicKeyDigest; } void setKeyLocator(const KeyLocator& keyLocator) { keyLocator_ = keyLocator; } /** * Clear all the fields. */ void clear() { digestAlgorithm_.reset(); witness_.reset(); signature_.reset(); publisherPublicKeyDigest_.clear(); keyLocator_.clear(); } private: Blob digestAlgorithm_; /**< if empty, the default is 2.16.840.1.101.3.4.2.1 (sha-256) */ Blob witness_; Blob signature_; PublisherPublicKeyDigest publisherPublicKeyDigest_; KeyLocator keyLocator_; }; } #endif <|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. #include "base/perftimer.h" #include "base/scoped_handle.h" #include "base/timer.h" #include "net/base/net_errors.h" #include "net/disk_cache/block_files.h" #include "net/disk_cache/disk_cache.h" #include "net/disk_cache/disk_cache_test_base.h" #include "net/disk_cache/disk_cache_test_util.h" #include "net/disk_cache/hash.h" #include "testing/gtest/include/gtest/gtest.h" extern int g_cache_tests_max_id; extern volatile int g_cache_tests_received; extern volatile bool g_cache_tests_error; namespace { bool EvictFileFromSystemCache(const wchar_t* name) { // Overwrite it with no buffering. ScopedHandle file(CreateFile(name, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_NO_BUFFERING, NULL)); if (!file.IsValid()) return false; // Execute in chunks. It could be optimized. We want to do few of these since // these opterations will be slow without the cache. char buffer[128 * 1024]; int total_bytes = 0; DWORD bytes_read; for (;;) { if (!ReadFile(file, buffer, sizeof(buffer), &bytes_read, NULL)) return false; if (bytes_read == 0) break; bool final = false; if (bytes_read < sizeof(buffer)) final = true; DWORD to_write = final ? sizeof(buffer) : bytes_read; DWORD actual; SetFilePointer(file, total_bytes, 0, FILE_BEGIN); if (!WriteFile(file, buffer, to_write, &actual, NULL)) return false; total_bytes += bytes_read; if (final) { SetFilePointer(file, total_bytes, 0, FILE_BEGIN); SetEndOfFile(file); break; } } return true; } struct TestEntry { std::string key; int data_len; }; typedef std::vector<TestEntry> TestEntries; const int kMaxSize = 16 * 1024 - 1; // Creates num_entries on the cache, and writes 200 bytes of metadata and up // to kMaxSize of data to each entry. int TimeWrite(int num_entries, disk_cache::Backend* cache, TestEntries* entries) { char buffer1[200]; char buffer2[kMaxSize]; CacheTestFillBuffer(buffer1, sizeof(buffer1), false); CacheTestFillBuffer(buffer2, sizeof(buffer2), false); CallbackTest callback(1); g_cache_tests_error = false; g_cache_tests_max_id = 1; g_cache_tests_received = 0; int expected = 0; MessageLoopHelper helper; PerfTimeLogger timer("Write disk cache entries"); for (int i = 0; i < num_entries; i++) { TestEntry entry; entry.key = GenerateKey(true); entry.data_len = rand() % sizeof(buffer2); entries->push_back(entry); disk_cache::Entry* cache_entry; if (!cache->CreateEntry(entry.key, &cache_entry)) break; int ret = cache_entry->WriteData(0, 0, buffer1, sizeof(buffer1), &callback, false); if (net::ERR_IO_PENDING == ret) expected++; else if (sizeof(buffer1) != ret) break; ret = cache_entry->WriteData(1, 0, buffer2, entry.data_len, &callback, false); if (net::ERR_IO_PENDING == ret) expected++; else if (entry.data_len != ret) break; cache_entry->Close(); } helper.WaitUntilCacheIoFinished(expected); timer.Done(); return expected; } // Reads the data and metadata from each entry listed on |entries|. int TimeRead(int num_entries, disk_cache::Backend* cache, const TestEntries& entries, bool cold) { char buffer1[200]; char buffer2[kMaxSize]; CacheTestFillBuffer(buffer1, sizeof(buffer1), false); CacheTestFillBuffer(buffer2, sizeof(buffer2), false); CallbackTest callback(1); g_cache_tests_error = false; g_cache_tests_max_id = 1; g_cache_tests_received = 0; int expected = 0; MessageLoopHelper helper; const char* message = cold ? "Read disk cache entries (cold)" : "Read disk cache entries (warm)"; PerfTimeLogger timer(message); for (int i = 0; i < num_entries; i++) { disk_cache::Entry* cache_entry; if (!cache->OpenEntry(entries[i].key, &cache_entry)) break; int ret = cache_entry->ReadData(0, 0, buffer1, sizeof(buffer1), &callback); if (net::ERR_IO_PENDING == ret) expected++; else if (sizeof(buffer1) != ret) break; ret = cache_entry->ReadData(1, 0, buffer2, entries[i].data_len, &callback); if (net::ERR_IO_PENDING == ret) expected++; else if (entries[i].data_len != ret) break; cache_entry->Close(); } helper.WaitUntilCacheIoFinished(expected); timer.Done(); return expected; } int BlockSize() { // We can use form 1 to 4 blocks. return (rand() & 0x3) + 1; } } // namespace TEST_F(DiskCacheTest, Hash) { int seed = static_cast<int>(Time::Now().ToInternalValue()); srand(seed); PerfTimeLogger timer("Hash disk cache keys"); for (int i = 0; i < 300000; i++) { std::string key = GenerateKey(true); uint32 hash = disk_cache::Hash(key); } timer.Done(); } TEST_F(DiskCacheTest, CacheBackendPerformance) { MessageLoopForIO message_loop; std::wstring path = GetCachePath(); ASSERT_TRUE(DeleteCache(path.c_str())); disk_cache::Backend* cache = disk_cache::CreateCacheBackend(path, false, 0); ASSERT_TRUE(NULL != cache); int seed = static_cast<int>(Time::Now().ToInternalValue()); srand(seed); TestEntries entries; int num_entries = 1000; int ret = TimeWrite(num_entries, cache, &entries); EXPECT_EQ(ret, g_cache_tests_received); delete cache; ASSERT_TRUE(EvictFileFromSystemCache((path + L"\\index").c_str())); ASSERT_TRUE(EvictFileFromSystemCache((path + L"\\data_0").c_str())); ASSERT_TRUE(EvictFileFromSystemCache((path + L"\\data_1").c_str())); ASSERT_TRUE(EvictFileFromSystemCache((path + L"\\data_2").c_str())); ASSERT_TRUE(EvictFileFromSystemCache((path + L"\\data_3").c_str())); cache = disk_cache::CreateCacheBackend(path, false, 0); ASSERT_TRUE(NULL != cache); ret = TimeRead(num_entries, cache, entries, true); EXPECT_EQ(ret, g_cache_tests_received); ret = TimeRead(num_entries, cache, entries, false); EXPECT_EQ(ret, g_cache_tests_received); delete cache; } TEST_F(DiskCacheTest, BlockFilesPerformance) { std::wstring path = GetCachePath(); ASSERT_TRUE(DeleteCache(path.c_str())); disk_cache::BlockFiles files(path); ASSERT_TRUE(files.Init(true)); int seed = static_cast<int>(Time::Now().ToInternalValue()); srand(seed); const int kNumEntries = 60000; int32 buffer[kNumEntries]; memset(buffer, 0, sizeof(buffer)); disk_cache::Addr* address = reinterpret_cast<disk_cache::Addr*>(buffer); ASSERT_EQ(sizeof(*address), sizeof(*buffer)); PerfTimeLogger timer1("Fill three block-files"); // Fill up the 32-byte block file (use three files). for (int i = 0; i < kNumEntries; i++) { EXPECT_TRUE(files.CreateBlock(disk_cache::RANKINGS, BlockSize(), &address[i])); } timer1.Done(); PerfTimeLogger timer2("Create and delete blocks"); for (int i = 0; i < 200000; i++) { int entry = rand() * (kNumEntries / RAND_MAX + 1); if (entry >= kNumEntries) entry = 0; files.DeleteBlock(address[entry], false); EXPECT_TRUE(files.CreateBlock(disk_cache::RANKINGS, BlockSize(), &address[entry])); } timer2.Done(); } <commit_msg>Fixing the comment that was not included with the last cl.<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. #include "base/perftimer.h" #include "base/scoped_handle.h" #include "base/timer.h" #include "net/base/net_errors.h" #include "net/disk_cache/block_files.h" #include "net/disk_cache/disk_cache.h" #include "net/disk_cache/disk_cache_test_base.h" #include "net/disk_cache/disk_cache_test_util.h" #include "net/disk_cache/hash.h" #include "testing/gtest/include/gtest/gtest.h" extern int g_cache_tests_max_id; extern volatile int g_cache_tests_received; extern volatile bool g_cache_tests_error; namespace { bool EvictFileFromSystemCache(const wchar_t* name) { // Overwrite it with no buffering. ScopedHandle file(CreateFile(name, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_NO_BUFFERING, NULL)); if (!file.IsValid()) return false; // Execute in chunks. It could be optimized. We want to do few of these since // these opterations will be slow without the cache. char buffer[128 * 1024]; int total_bytes = 0; DWORD bytes_read; for (;;) { if (!ReadFile(file, buffer, sizeof(buffer), &bytes_read, NULL)) return false; if (bytes_read == 0) break; bool final = false; if (bytes_read < sizeof(buffer)) final = true; DWORD to_write = final ? sizeof(buffer) : bytes_read; DWORD actual; SetFilePointer(file, total_bytes, 0, FILE_BEGIN); if (!WriteFile(file, buffer, to_write, &actual, NULL)) return false; total_bytes += bytes_read; if (final) { SetFilePointer(file, total_bytes, 0, FILE_BEGIN); SetEndOfFile(file); break; } } return true; } struct TestEntry { std::string key; int data_len; }; typedef std::vector<TestEntry> TestEntries; const int kMaxSize = 16 * 1024 - 1; // Creates num_entries on the cache, and writes 200 bytes of metadata and up // to kMaxSize of data to each entry. int TimeWrite(int num_entries, disk_cache::Backend* cache, TestEntries* entries) { char buffer1[200]; char buffer2[kMaxSize]; CacheTestFillBuffer(buffer1, sizeof(buffer1), false); CacheTestFillBuffer(buffer2, sizeof(buffer2), false); CallbackTest callback(1); g_cache_tests_error = false; g_cache_tests_max_id = 1; g_cache_tests_received = 0; int expected = 0; MessageLoopHelper helper; PerfTimeLogger timer("Write disk cache entries"); for (int i = 0; i < num_entries; i++) { TestEntry entry; entry.key = GenerateKey(true); entry.data_len = rand() % sizeof(buffer2); entries->push_back(entry); disk_cache::Entry* cache_entry; if (!cache->CreateEntry(entry.key, &cache_entry)) break; int ret = cache_entry->WriteData(0, 0, buffer1, sizeof(buffer1), &callback, false); if (net::ERR_IO_PENDING == ret) expected++; else if (sizeof(buffer1) != ret) break; ret = cache_entry->WriteData(1, 0, buffer2, entry.data_len, &callback, false); if (net::ERR_IO_PENDING == ret) expected++; else if (entry.data_len != ret) break; cache_entry->Close(); } helper.WaitUntilCacheIoFinished(expected); timer.Done(); return expected; } // Reads the data and metadata from each entry listed on |entries|. int TimeRead(int num_entries, disk_cache::Backend* cache, const TestEntries& entries, bool cold) { char buffer1[200]; char buffer2[kMaxSize]; CacheTestFillBuffer(buffer1, sizeof(buffer1), false); CacheTestFillBuffer(buffer2, sizeof(buffer2), false); CallbackTest callback(1); g_cache_tests_error = false; g_cache_tests_max_id = 1; g_cache_tests_received = 0; int expected = 0; MessageLoopHelper helper; const char* message = cold ? "Read disk cache entries (cold)" : "Read disk cache entries (warm)"; PerfTimeLogger timer(message); for (int i = 0; i < num_entries; i++) { disk_cache::Entry* cache_entry; if (!cache->OpenEntry(entries[i].key, &cache_entry)) break; int ret = cache_entry->ReadData(0, 0, buffer1, sizeof(buffer1), &callback); if (net::ERR_IO_PENDING == ret) expected++; else if (sizeof(buffer1) != ret) break; ret = cache_entry->ReadData(1, 0, buffer2, entries[i].data_len, &callback); if (net::ERR_IO_PENDING == ret) expected++; else if (entries[i].data_len != ret) break; cache_entry->Close(); } helper.WaitUntilCacheIoFinished(expected); timer.Done(); return expected; } int BlockSize() { // We can use form 1 to 4 blocks. return (rand() & 0x3) + 1; } } // namespace TEST_F(DiskCacheTest, Hash) { int seed = static_cast<int>(Time::Now().ToInternalValue()); srand(seed); PerfTimeLogger timer("Hash disk cache keys"); for (int i = 0; i < 300000; i++) { std::string key = GenerateKey(true); uint32 hash = disk_cache::Hash(key); } timer.Done(); } TEST_F(DiskCacheTest, CacheBackendPerformance) { MessageLoopForIO message_loop; std::wstring path = GetCachePath(); ASSERT_TRUE(DeleteCache(path.c_str())); disk_cache::Backend* cache = disk_cache::CreateCacheBackend(path, false, 0); ASSERT_TRUE(NULL != cache); int seed = static_cast<int>(Time::Now().ToInternalValue()); srand(seed); TestEntries entries; int num_entries = 1000; int ret = TimeWrite(num_entries, cache, &entries); EXPECT_EQ(ret, g_cache_tests_received); delete cache; ASSERT_TRUE(EvictFileFromSystemCache((path + L"\\index").c_str())); ASSERT_TRUE(EvictFileFromSystemCache((path + L"\\data_0").c_str())); ASSERT_TRUE(EvictFileFromSystemCache((path + L"\\data_1").c_str())); ASSERT_TRUE(EvictFileFromSystemCache((path + L"\\data_2").c_str())); ASSERT_TRUE(EvictFileFromSystemCache((path + L"\\data_3").c_str())); cache = disk_cache::CreateCacheBackend(path, false, 0); ASSERT_TRUE(NULL != cache); ret = TimeRead(num_entries, cache, entries, true); EXPECT_EQ(ret, g_cache_tests_received); ret = TimeRead(num_entries, cache, entries, false); EXPECT_EQ(ret, g_cache_tests_received); delete cache; } // Creating and deleting "entries" on a block-file is something quite frequent // (after all, almost everything is stored on block files). The operation is // almost free when the file is empty, but can be expensive if the file gets // fragmented, or if we have multiple files. This test measures that scenario, // by using multiple, highly fragmented files. TEST_F(DiskCacheTest, BlockFilesPerformance) { std::wstring path = GetCachePath(); ASSERT_TRUE(DeleteCache(path.c_str())); disk_cache::BlockFiles files(path); ASSERT_TRUE(files.Init(true)); int seed = static_cast<int>(Time::Now().ToInternalValue()); srand(seed); const int kNumEntries = 60000; int32 buffer[kNumEntries]; memset(buffer, 0, sizeof(buffer)); disk_cache::Addr* address = reinterpret_cast<disk_cache::Addr*>(buffer); ASSERT_EQ(sizeof(*address), sizeof(*buffer)); PerfTimeLogger timer1("Fill three block-files"); // Fill up the 32-byte block file (use three files). for (int i = 0; i < kNumEntries; i++) { EXPECT_TRUE(files.CreateBlock(disk_cache::RANKINGS, BlockSize(), &address[i])); } timer1.Done(); PerfTimeLogger timer2("Create and delete blocks"); for (int i = 0; i < 200000; i++) { int entry = rand() * (kNumEntries / RAND_MAX + 1); if (entry >= kNumEntries) entry = 0; files.DeleteBlock(address[entry], false); EXPECT_TRUE(files.CreateBlock(disk_cache::RANKINGS, BlockSize(), &address[entry])); } timer2.Done(); } <|endoftext|>
<commit_before>#include "streams.h" #include <algorithm> #include <core/json.h> #include <core/memory.h> #include <core/stream.h> #include <fstream> #include <limits> #include <pcg/pcg_random.hpp> #include <random> #include <string> #ifdef BUILD_estream #include <streams/estream/estream_stream.h> #endif #ifdef BUILD_sha3 #include <streams/sha3/sha3_stream.h> #endif #ifdef BUILD_block #include <streams/block/block_stream.h> #endif namespace _impl { template <std::uint8_t value> struct const_stream : stream { const_stream(const std::size_t osize) : stream(osize) , _data(osize) { std::fill_n(_data.begin(), osize, value); } vec_view next() override { return make_cview(_data); } private: std::vector<value_type> _data; }; template <typename Generator> struct rng_stream : stream { template <typename Seeder> rng_stream(Seeder&& seeder, const std::size_t osize) : stream(osize) , _rng(std::forward<Seeder>(seeder)) , _data(osize) { } vec_view next() override { std::generate_n(_data.data(), osize(), [this]() { return std::uniform_int_distribution<std::uint8_t>()(_rng); }); return make_cview(_data); } private: Generator _rng; std::vector<value_type> _data; }; } // namespace _impl /** * \brief Stream of true bits */ using true_stream = _impl::const_stream<std::numeric_limits<std::uint8_t>::max()>; /** * \brief Stream of false bits */ using false_stream = _impl::const_stream<std::numeric_limits<std::uint8_t>::min()>; /** * \brief Stream of data produced by Merseine Twister */ using mt19937_stream = _impl::rng_stream<std::mt19937>; /** * \brief Stream of data produced by PCG (Permutation Congruential Generator) */ using pcg32_stream = _impl::rng_stream<pcg32>; /** * @brief Stream of data read from a file */ struct file_stream : stream { file_stream(const json& config, const std::size_t osize) : stream(osize) , _path(config.at("path").get<std::string>()) , _istream(_path, std::ios::binary) , _data(osize) {} vec_view next() override { _istream.read(_data.data(), osize()); if (_istream.fail()) throw std::runtime_error("I/O error while reading a file " + _path); if (_istream.eof()) throw std::runtime_error("end of file " + _path + " reached, not enough data!"); return make_cview(_data); } private: const std::string _path; std::basic_ifstream<std::uint8_t> _istream; std::vector<value_type> _data; }; /** * @brief Stream of counter */ struct counter : stream { counter(const std::size_t osize) : stream(osize) , _data(osize) { std::fill(_data.begin(), _data.end(), std::numeric_limits<value_type>::min()); } vec_view next() override { for (value_type& value : _data) { if (value != std::numeric_limits<value_type>::max()) { ++value; break; } value = std::numeric_limits<value_type>::min(); } return make_cview(_data); } private: std::vector<value_type> _data; }; std::unique_ptr<stream> make_stream(const json& config, default_seed_source& seeder, std::size_t osize = 0) { const std::string type = config.at("type"); if (osize == 0) throw std::runtime_error("Stream's osize " + type + " is not set in parent stream."); if (type == "file-stream") return std::make_unique<file_stream>(config, osize); else if (type == "true-stream") return std::make_unique<true_stream>(osize); else if (type == "false-stream") return std::make_unique<false_stream>(osize); else if (type == "counter") return std::make_unique<counter>(osize); else if (type == "mt19937-stream") return std::make_unique<mt19937_stream>(seeder, osize); else if (type == "pcg32-stream") return std::make_unique<pcg32_stream>(seeder, osize); #ifdef BUILD_estream else if (type == "estream") return std::make_unique<estream_stream>(config, seeder, osize); #endif #ifdef BUILD_sha3 else if (type == "sha3") return std::make_unique<sha3_stream>(config, seeder, osize); #endif #ifdef BUILD_block else if (type == "block") return std::make_unique<block::block_stream>(config, seeder, osize); #endif throw std::runtime_error("requested stream named \"" + type + "\" does not exist"); } void stream_to_dataset(dataset& set, std::unique_ptr<stream>& source) { auto beg = set.rawdata(); auto end = set.rawdata() + set.rawsize(); for (; beg != end;) { vec_view n = source->next(); beg = std::copy(n.begin(), n.end(), beg); } } <commit_msg>Streams: strict avalanche criterion<commit_after>#include "streams.h" #include <algorithm> #include <core/json.h> #include <core/memory.h> #include <core/stream.h> #include <fstream> #include <limits> #include <pcg/pcg_random.hpp> #include <random> #include <string> #ifdef BUILD_estream #include <streams/estream/estream_stream.h> #endif #ifdef BUILD_sha3 #include <streams/sha3/sha3_stream.h> #endif #ifdef BUILD_block #include <streams/block/block_stream.h> #endif namespace _impl { template <std::uint8_t value> struct const_stream : stream { const_stream(const std::size_t osize) : stream(osize) , _data(osize) { std::fill_n(_data.begin(), osize, value); } vec_view next() override { return make_cview(_data); } private: std::vector<value_type> _data; }; template <typename Generator> struct rng_stream : stream { template <typename Seeder> rng_stream(Seeder&& seeder, const std::size_t osize) : stream(osize) , _rng(std::forward<Seeder>(seeder)) , _data(osize) {} vec_view next() override { std::generate_n(_data.data(), osize(), [this]() { return std::uniform_int_distribution<std::uint8_t>()(_rng); }); return make_cview(_data); } private: Generator _rng; std::vector<value_type> _data; }; } // namespace _impl /** * \brief Stream of true bits */ using true_stream = _impl::const_stream<std::numeric_limits<std::uint8_t>::max()>; /** * \brief Stream of false bits */ using false_stream = _impl::const_stream<std::numeric_limits<std::uint8_t>::min()>; /** * \brief Stream of data produced by Merseine Twister */ using mt19937_stream = _impl::rng_stream<std::mt19937>; /** * \brief Stream of data produced by PCG (Permutation Congruential Generator) */ using pcg32_stream = _impl::rng_stream<pcg32>; /** * @brief Stream of data read from a file */ struct file_stream : stream { file_stream(const json& config, const std::size_t osize) : stream(osize) , _path(config.at("path").get<std::string>()) , _istream(_path, std::ios::binary) , _data(osize) {} vec_view next() override { _istream.read(_data.data(), osize()); if (_istream.fail()) throw std::runtime_error("I/O error while reading a file " + _path); if (_istream.eof()) throw std::runtime_error("end of file " + _path + " reached, not enough data!"); return make_cview(_data); } private: const std::string _path; std::basic_ifstream<std::uint8_t> _istream; std::vector<value_type> _data; }; /** * @brief Stream of counter */ struct counter : stream { counter(const std::size_t osize) : stream(osize) , _data(osize) { std::fill(_data.begin(), _data.end(), std::numeric_limits<value_type>::min()); } vec_view next() override { for (value_type& value : _data) { if (value != std::numeric_limits<value_type>::max()) { ++value; break; } value = std::numeric_limits<value_type>::min(); } return make_cview(_data); } private: std::vector<value_type> _data; }; /** * @brief Stream for testing strict avalanche criterion * * The vector consists 2 parts of same length. The first part is random, * the second is copy of the first with one flipped bit */ template <typename Generator> struct rng_stream : stream { template <typename Seeder> rng_stream(Seeder&& seeder, const std::size_t osize) : stream(osize) , _rng(std::forward<Seeder>(seeder)) , _data(osize) { if (osize % 2 == 1) throw std::runtime_error( "Stream's osize has to be even (so it contains 2 vectors of same legth)."); } vec_view next() override { std::generate_n(_data.data(), osize() / 2, [this]() { return std::uniform_int_distribution<std::uint8_t>()(_rng); }); std::copy_n(_data.begin(), osize() / 2, _data.begin() + osize() / 2); std::uniform_int_distribution<std::size_t> dist{0, osize() / 2 * 8}; std::size_t pos = dist(_rng) + osize() / 2 * 8; _data[pos / 8] ^= (1 << (pos % 8)); return make_cview(_data); } private: Generator _rng; std::vector<value_type> _data; }; std::unique_ptr<stream> make_stream(const json& config, default_seed_source& seeder, std::size_t osize = 0) { const std::string type = config.at("type"); if (osize == 0) throw std::runtime_error("Stream's osize " + type + " is not set in parent stream."); if (type == "file-stream") return std::make_unique<file_stream>(config, osize); else if (type == "true-stream") return std::make_unique<true_stream>(osize); else if (type == "false-stream") return std::make_unique<false_stream>(osize); else if (type == "counter") return std::make_unique<counter>(osize); else if (type == "mt19937-stream") return std::make_unique<mt19937_stream>(seeder, osize); else if (type == "pcg32-stream") return std::make_unique<pcg32_stream>(seeder, osize); else if (type == "sac-pcg32") return std::make_unique<pcg32_stream>(seeder, osize); #ifdef BUILD_estream else if (type == "estream") return std::make_unique<estream_stream>(config, seeder, osize); #endif #ifdef BUILD_sha3 else if (type == "sha3") return std::make_unique<sha3_stream>(config, seeder, osize); #endif #ifdef BUILD_block else if (type == "block") return std::make_unique<block::block_stream>(config, seeder, osize); #endif throw std::runtime_error("requested stream named \"" + type + "\" does not exist"); } void stream_to_dataset(dataset& set, std::unique_ptr<stream>& source) { auto beg = set.rawdata(); auto end = set.rawdata() + set.rawsize(); for (; beg != end;) { vec_view n = source->next(); beg = std::copy(n.begin(), n.end(), beg); } } <|endoftext|>
<commit_before>// This file is part of UDPipe <http://github.com/ufal/udpipe/>. // // Copyright 2015 Institute of Formal and Applied Linguistics, Faculty of // Mathematics and Physics, Charles University in Prague, Czech Republic. // // 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 "output_format.h" #include "utils/parse_int.h" #include "utils/split.h" #include "utils/xml_encoded.h" namespace ufal { namespace udpipe { // CoNLL-U output format class output_format_conllu : public output_format { public: virtual void write_sentence(const sentence& s, ostream& os) override; private: static const string underscore; const string& underscore_on_empty(const string& str) const { return str.empty() ? underscore : str; } }; const string output_format_conllu::underscore = "_"; void output_format_conllu::write_sentence(const sentence& s, ostream& os) { // Comments for (auto&& comment : s.comments) os << comment << '\n'; // Words and multiword tokens size_t multiword_token = 0, empty_node = 0; for (int i = 0; i < int(s.words.size()); i++) { // Write non-root nodes if (i > 0) { // Multiword token if present if (multiword_token < s.multiword_tokens.size() && i == s.multiword_tokens[multiword_token].id_first) { os << s.multiword_tokens[multiword_token].id_first << '-' << s.multiword_tokens[multiword_token].id_last << '\t' << s.multiword_tokens[multiword_token].form << "\t_\t_\t_\t_\t_\t_\t_\t" << underscore_on_empty(s.multiword_tokens[multiword_token].misc) << '\n'; multiword_token++; } // Write the word os << i << '\t' << s.words[i].form << '\t' << underscore_on_empty(s.words[i].lemma) << '\t' << underscore_on_empty(s.words[i].upostag) << '\t' << underscore_on_empty(s.words[i].xpostag) << '\t' << underscore_on_empty(s.words[i].feats) << '\t'; if (s.words[i].head < 0) os << '_'; else os << s.words[i].head; os << '\t' << underscore_on_empty(s.words[i].deprel) << '\t' << underscore_on_empty(s.words[i].deps) << '\t' << underscore_on_empty(s.words[i].misc) << '\n'; } // Empty nodes for (; empty_node < s.empty_nodes.size() && i == s.empty_nodes[empty_node].id; empty_node++) { os << i << '.' << s.empty_nodes[empty_node].index << '\t' << s.empty_nodes[empty_node].form << '\t' << underscore_on_empty(s.empty_nodes[empty_node].lemma) << '\t' << underscore_on_empty(s.empty_nodes[empty_node].upostag) << '\t' << underscore_on_empty(s.empty_nodes[empty_node].xpostag) << '\t' << underscore_on_empty(s.empty_nodes[empty_node].feats) << '\t' << "_\t" << "_\t" << underscore_on_empty(s.empty_nodes[empty_node].deps) << '\t' << underscore_on_empty(s.empty_nodes[empty_node].misc) << '\n'; } } os << endl; } // Matxin output format class output_format_matxin : public output_format { public: virtual void write_sentence(const sentence& s, ostream& os) override; virtual void finish_document(ostream& os) override; private: void write_node(const sentence& s, int node, string& pad, ostream& os); int sentences = 0; }; void output_format_matxin::write_sentence(const sentence& s, ostream& os) { if (!sentences) { os << "<corpus>"; } os << "\n<SENTENCE ord=\"" << ++sentences << "\" alloc=\"" << 0 << "\">\n"; string pad; for (auto&& node : s.words[0].children) write_node(s, node, pad, os); os << "</SENTENCE>" << endl; } void output_format_matxin::finish_document(ostream& os) { os << "</corpus>\n"; sentences = 0; } void output_format_matxin::write_node(const sentence& s, int node, string& pad, ostream& os) { // <NODE ord="%d" alloc="%d" form="%s" lem="%s" mi="%s" si="%s"> pad.push_back(' '); os << pad << "<NODE ord=\"" << node << "\" alloc=\"" << 0 << "\" form=\"" << xml_encoded(s.words[node].form, true) << "\" lem=\"" << xml_encoded(s.words[node].lemma, true) << "\" mi=\"" << xml_encoded(s.words[node].feats, true) << "\" si=\"" << xml_encoded(s.words[node].deprel, true) << '"'; if (s.words[node].children.empty()) { os << "/>\n"; } else { os << ">\n"; for (auto&& child : s.words[node].children) write_node(s, child, pad, os); os << pad << "</NODE>\n"; } pad.pop_back(); } // Horizontal output format class output_format_horizontal : public output_format { public: virtual void write_sentence(const sentence& s, ostream& os) override; }; void output_format_horizontal::write_sentence(const sentence& s, ostream& os) { string line; for (size_t i = 1; i < s.words.size(); i++) { // Append word, but replace spaces by &nbsp;s for (auto&& chr : s.words[i].form) if (chr == ' ') line.append("\302\240"); else line.push_back(chr); if (i+1 < s.words.size()) line.push_back(' '); } os << line << endl; } // Plaintext output format class output_format_plaintext : public output_format { public: output_format_plaintext(bool normalized): normalized(normalized) {} virtual void write_sentence(const sentence& s, ostream& os) override; private: bool normalized; }; void output_format_plaintext::write_sentence(const sentence& s, ostream& os) { if (normalized) { for (size_t i = 1, j = 0; i < s.words.size(); i++) { const token& tok = j < s.multiword_tokens.size() && s.multiword_tokens[j].id_first == int(i) ? (const token&)s.multiword_tokens[j] : (const token&)s.words[i]; if (i > 1 && tok.get_space_after()) os << ' '; os << tok.form; if (j < s.multiword_tokens.size() && s.multiword_tokens[j].id_first == int(i)) i = s.multiword_tokens[j++].id_last; } os << endl; } else { string spaces; for (size_t i = 1; i < s.words.size(); i++) { s.words[i].get_spaces_before(spaces); os << spaces; s.words[i].get_spaces_in_token(spaces); os << (!spaces.empty() ? spaces : s.words[i].form); s.words[i].get_spaces_after(spaces); os << spaces; } os << flush; } } // Vertical output format class output_format_vertical : public output_format { public: virtual void write_sentence(const sentence& s, ostream& os) override; }; void output_format_vertical::write_sentence(const sentence& s, ostream& os) { for (size_t i = 1; i < s.words.size(); i++) os << s.words[i].form << '\n'; os << endl; } // Static factory methods output_format* output_format::new_conllu_output_format() { return new output_format_conllu(); } output_format* output_format::new_matxin_output_format() { return new output_format_matxin(); } output_format* output_format::new_horizontal_output_format() { return new output_format_horizontal(); } output_format* output_format::new_plaintext_output_format() { return new output_format_plaintext(false); } output_format* output_format::new_plaintext_normalized_output_format() { return new output_format_plaintext(true); } output_format* output_format::new_vertical_output_format() { return new output_format_vertical(); } output_format* output_format::new_output_format(const string& name) { if (name == "conllu") return new_conllu_output_format(); if (name == "matxin") return new_matxin_output_format(); if (name == "horizontal") return new_horizontal_output_format(); if (name == "plaintext") return new_plaintext_output_format(); if (name == "plaintext_normalized") return new_plaintext_normalized_output_format(); if (name == "vertical") return new_vertical_output_format(); return nullptr; } } // namespace udpipe } // namespace ufal <commit_msg>Utilize newdoc and newpar comments in plaintext_normalized output format.<commit_after>// This file is part of UDPipe <http://github.com/ufal/udpipe/>. // // Copyright 2015 Institute of Formal and Applied Linguistics, Faculty of // Mathematics and Physics, Charles University in Prague, Czech Republic. // // 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 "output_format.h" #include "utils/parse_int.h" #include "utils/split.h" #include "utils/xml_encoded.h" namespace ufal { namespace udpipe { // CoNLL-U output format class output_format_conllu : public output_format { public: virtual void write_sentence(const sentence& s, ostream& os) override; private: static const string underscore; const string& underscore_on_empty(const string& str) const { return str.empty() ? underscore : str; } }; const string output_format_conllu::underscore = "_"; void output_format_conllu::write_sentence(const sentence& s, ostream& os) { // Comments for (auto&& comment : s.comments) os << comment << '\n'; // Words and multiword tokens size_t multiword_token = 0, empty_node = 0; for (int i = 0; i < int(s.words.size()); i++) { // Write non-root nodes if (i > 0) { // Multiword token if present if (multiword_token < s.multiword_tokens.size() && i == s.multiword_tokens[multiword_token].id_first) { os << s.multiword_tokens[multiword_token].id_first << '-' << s.multiword_tokens[multiword_token].id_last << '\t' << s.multiword_tokens[multiword_token].form << "\t_\t_\t_\t_\t_\t_\t_\t" << underscore_on_empty(s.multiword_tokens[multiword_token].misc) << '\n'; multiword_token++; } // Write the word os << i << '\t' << s.words[i].form << '\t' << underscore_on_empty(s.words[i].lemma) << '\t' << underscore_on_empty(s.words[i].upostag) << '\t' << underscore_on_empty(s.words[i].xpostag) << '\t' << underscore_on_empty(s.words[i].feats) << '\t'; if (s.words[i].head < 0) os << '_'; else os << s.words[i].head; os << '\t' << underscore_on_empty(s.words[i].deprel) << '\t' << underscore_on_empty(s.words[i].deps) << '\t' << underscore_on_empty(s.words[i].misc) << '\n'; } // Empty nodes for (; empty_node < s.empty_nodes.size() && i == s.empty_nodes[empty_node].id; empty_node++) { os << i << '.' << s.empty_nodes[empty_node].index << '\t' << s.empty_nodes[empty_node].form << '\t' << underscore_on_empty(s.empty_nodes[empty_node].lemma) << '\t' << underscore_on_empty(s.empty_nodes[empty_node].upostag) << '\t' << underscore_on_empty(s.empty_nodes[empty_node].xpostag) << '\t' << underscore_on_empty(s.empty_nodes[empty_node].feats) << '\t' << "_\t" << "_\t" << underscore_on_empty(s.empty_nodes[empty_node].deps) << '\t' << underscore_on_empty(s.empty_nodes[empty_node].misc) << '\n'; } } os << endl; } // Matxin output format class output_format_matxin : public output_format { public: virtual void write_sentence(const sentence& s, ostream& os) override; virtual void finish_document(ostream& os) override; private: void write_node(const sentence& s, int node, string& pad, ostream& os); int sentences = 0; }; void output_format_matxin::write_sentence(const sentence& s, ostream& os) { if (!sentences) { os << "<corpus>"; } os << "\n<SENTENCE ord=\"" << ++sentences << "\" alloc=\"" << 0 << "\">\n"; string pad; for (auto&& node : s.words[0].children) write_node(s, node, pad, os); os << "</SENTENCE>" << endl; } void output_format_matxin::finish_document(ostream& os) { os << "</corpus>\n"; sentences = 0; } void output_format_matxin::write_node(const sentence& s, int node, string& pad, ostream& os) { // <NODE ord="%d" alloc="%d" form="%s" lem="%s" mi="%s" si="%s"> pad.push_back(' '); os << pad << "<NODE ord=\"" << node << "\" alloc=\"" << 0 << "\" form=\"" << xml_encoded(s.words[node].form, true) << "\" lem=\"" << xml_encoded(s.words[node].lemma, true) << "\" mi=\"" << xml_encoded(s.words[node].feats, true) << "\" si=\"" << xml_encoded(s.words[node].deprel, true) << '"'; if (s.words[node].children.empty()) { os << "/>\n"; } else { os << ">\n"; for (auto&& child : s.words[node].children) write_node(s, child, pad, os); os << pad << "</NODE>\n"; } pad.pop_back(); } // Horizontal output format class output_format_horizontal : public output_format { public: virtual void write_sentence(const sentence& s, ostream& os) override; }; void output_format_horizontal::write_sentence(const sentence& s, ostream& os) { string line; for (size_t i = 1; i < s.words.size(); i++) { // Append word, but replace spaces by &nbsp;s for (auto&& chr : s.words[i].form) if (chr == ' ') line.append("\302\240"); else line.push_back(chr); if (i+1 < s.words.size()) line.push_back(' '); } os << line << endl; } // Plaintext output format class output_format_plaintext : public output_format { public: output_format_plaintext(bool normalized): normalized(normalized), empty(true) {} virtual void write_sentence(const sentence& s, ostream& os) override; virtual void finish_document(ostream& /*os*/) override { empty = true; } private: bool normalized; bool empty; }; void output_format_plaintext::write_sentence(const sentence& s, ostream& os) { if (normalized) { string doc_par_id; if (!empty && (s.get_new_doc(doc_par_id) || s.get_new_par(doc_par_id))) os << '\n'; for (size_t i = 1, j = 0; i < s.words.size(); i++) { const token& tok = j < s.multiword_tokens.size() && s.multiword_tokens[j].id_first == int(i) ? (const token&)s.multiword_tokens[j] : (const token&)s.words[i]; if (i > 1 && tok.get_space_after()) os << ' '; os << tok.form; if (j < s.multiword_tokens.size() && s.multiword_tokens[j].id_first == int(i)) i = s.multiword_tokens[j++].id_last; } os << endl; } else { string spaces; for (size_t i = 1; i < s.words.size(); i++) { s.words[i].get_spaces_before(spaces); os << spaces; s.words[i].get_spaces_in_token(spaces); os << (!spaces.empty() ? spaces : s.words[i].form); s.words[i].get_spaces_after(spaces); os << spaces; } os << flush; } empty = false; } // Vertical output format class output_format_vertical : public output_format { public: virtual void write_sentence(const sentence& s, ostream& os) override; }; void output_format_vertical::write_sentence(const sentence& s, ostream& os) { for (size_t i = 1; i < s.words.size(); i++) os << s.words[i].form << '\n'; os << endl; } // Static factory methods output_format* output_format::new_conllu_output_format() { return new output_format_conllu(); } output_format* output_format::new_matxin_output_format() { return new output_format_matxin(); } output_format* output_format::new_horizontal_output_format() { return new output_format_horizontal(); } output_format* output_format::new_plaintext_output_format() { return new output_format_plaintext(false); } output_format* output_format::new_plaintext_normalized_output_format() { return new output_format_plaintext(true); } output_format* output_format::new_vertical_output_format() { return new output_format_vertical(); } output_format* output_format::new_output_format(const string& name) { if (name == "conllu") return new_conllu_output_format(); if (name == "matxin") return new_matxin_output_format(); if (name == "horizontal") return new_horizontal_output_format(); if (name == "plaintext") return new_plaintext_output_format(); if (name == "plaintext_normalized") return new_plaintext_normalized_output_format(); if (name == "vertical") return new_vertical_output_format(); return nullptr; } } // namespace udpipe } // namespace ufal <|endoftext|>
<commit_before>#ifndef __LIBEVENT_SSL_SOCKET_HPP__ #define __LIBEVENT_SSL_SOCKET_HPP__ #include <event2/buffer.h> #include <event2/bufferevent_ssl.h> #include <event2/event.h> #include <event2/listener.h> #include <event2/util.h> #include <atomic> #include <memory> #include <process/queue.hpp> #include <process/socket.hpp> namespace process { namespace network { class LibeventSSLSocketImpl : public Socket::Impl { public: // See 'Socket::create()'. static Try<std::shared_ptr<Socket::Impl>> create(int s); LibeventSSLSocketImpl(int _s); virtual ~LibeventSSLSocketImpl(); // Implement 'Socket::Impl' interface. virtual Future<Nothing> connect(const Address& address); virtual Future<size_t> recv(char* data, size_t size); // Send does not currently support discard. See implementation. virtual Future<size_t> send(const char* data, size_t size); virtual Future<size_t> sendfile(int fd, off_t offset, size_t size); virtual Try<Nothing> listen(int backlog); virtual Future<Socket> accept(); virtual Socket::Kind kind() const { return Socket::SSL; } // This call is used to do the equivalent of shutting down the read // end. This means finishing the future of any outstanding read // request. virtual void shutdown(); // We need a post-initializer because 'shared_from_this()' is not // valid until the constructor has finished. void initialize(); private: // A set of helper functions that transitions an accepted socket to // an SSL connected socket. With the libevent-openssl library, once // we return from the 'accept_callback()' which is scheduled by // 'listen' then we still need to wait for the 'BEV_EVENT_CONNECTED' // state before we know the SSL connection has been established. struct AcceptRequest { AcceptRequest( int _socket, evconnlistener* _listener, const Option<net::IP>& _ip) : listener(_listener), socket(_socket), ip(_ip) {} Promise<Socket> promise; evconnlistener* listener; int socket; Option<net::IP> ip; }; struct RecvRequest { RecvRequest(char* _data, size_t _size) : data(_data), size(_size) {} Promise<size_t> promise; char* data; size_t size; }; struct SendRequest { SendRequest(size_t _size) : size(_size) {} Promise<size_t> promise; size_t size; }; struct ConnectRequest { Promise<Nothing> promise; }; // This is a private constructor used by the accept helper // functions. LibeventSSLSocketImpl( int _s, bufferevent* bev, Option<std::string>&& peer_hostname); // This is called when the equivalent of 'accept' returns. The role // of this function is to set up the SSL object and bev. void accept_callback(AcceptRequest* request); // The following are function pairs of static functions to member // functions. The static functions test and hold the weak pointer to // the socket before calling the member functions. This protects // against the socket being destroyed before the event loop calls // the callbacks. static void recv_callback(bufferevent* bev, void* arg); void recv_callback(); static void send_callback(bufferevent* bev, void* arg); void send_callback(); static void event_callback(bufferevent* bev, short events, void* arg); void event_callback(short events); bufferevent* bev; evconnlistener* listener; // Protects the following instance variables. std::atomic_flag lock = ATOMIC_LOCK_INIT; Owned<RecvRequest> recv_request; Owned<SendRequest> send_request; Owned<ConnectRequest> connect_request; // This is a weak pointer to 'this', i.e., ourselves, this class // instance. We need this for our event loop callbacks because it's // possible that we'll actually want to cleanup this socket impl // before the event loop callback gets executed ... and we'll check // in each event loop callback whether or not this weak_ptr is valid // by attempting to upgrade it to shared_ptr. It is the // responsibility of the event loop through the deferred lambda in // the destructor to clean up this pointer. // 1) It is a 'weak_ptr' as opposed to a 'shared_ptr' because we // want to test whether the object is still around from within the // event loop. If it was a 'shared_ptr' then we would be // contributing to the lifetime of the object and would no longer be // able to test the lifetime correctly. // 2) This is a pointer to a 'weak_ptr' so that we can pass this // through to the event loop through the C-interface. We need access // to the 'weak_ptr' from outside the object (in the event loop) to // test if the object is still alive. By maintaining this 'weak_ptr' // on the heap we can be sure it is safe to access from the // event loop until it is destroyed. std::weak_ptr<LibeventSSLSocketImpl>* event_loop_handle; // This queue stores buffered accepted sockets. 'Queue' is a thread // safe queue implementation, and the event loop pushes connected // sockets onto it, the 'accept()' call pops them off. We wrap these // sockets with futures so that we can pass errors through and chain // futures as well. Queue<Future<Socket>> accept_queue; // This bool represents whether this socket was created through an // 'accept' flow. We use this in the destructor to change // the clean-up behavior for the SSL context object. bool accepted; Option<std::string> peer_hostname; }; } // namespace network { } // namespace process { #endif // __LIBEVENT_SSL_SOCKET_HPP__ <commit_msg>Fix ATOMIC_FLAG_INIT typo.<commit_after>#ifndef __LIBEVENT_SSL_SOCKET_HPP__ #define __LIBEVENT_SSL_SOCKET_HPP__ #include <event2/buffer.h> #include <event2/bufferevent_ssl.h> #include <event2/event.h> #include <event2/listener.h> #include <event2/util.h> #include <atomic> #include <memory> #include <process/queue.hpp> #include <process/socket.hpp> namespace process { namespace network { class LibeventSSLSocketImpl : public Socket::Impl { public: // See 'Socket::create()'. static Try<std::shared_ptr<Socket::Impl>> create(int s); LibeventSSLSocketImpl(int _s); virtual ~LibeventSSLSocketImpl(); // Implement 'Socket::Impl' interface. virtual Future<Nothing> connect(const Address& address); virtual Future<size_t> recv(char* data, size_t size); // Send does not currently support discard. See implementation. virtual Future<size_t> send(const char* data, size_t size); virtual Future<size_t> sendfile(int fd, off_t offset, size_t size); virtual Try<Nothing> listen(int backlog); virtual Future<Socket> accept(); virtual Socket::Kind kind() const { return Socket::SSL; } // This call is used to do the equivalent of shutting down the read // end. This means finishing the future of any outstanding read // request. virtual void shutdown(); // We need a post-initializer because 'shared_from_this()' is not // valid until the constructor has finished. void initialize(); private: // A set of helper functions that transitions an accepted socket to // an SSL connected socket. With the libevent-openssl library, once // we return from the 'accept_callback()' which is scheduled by // 'listen' then we still need to wait for the 'BEV_EVENT_CONNECTED' // state before we know the SSL connection has been established. struct AcceptRequest { AcceptRequest( int _socket, evconnlistener* _listener, const Option<net::IP>& _ip) : listener(_listener), socket(_socket), ip(_ip) {} Promise<Socket> promise; evconnlistener* listener; int socket; Option<net::IP> ip; }; struct RecvRequest { RecvRequest(char* _data, size_t _size) : data(_data), size(_size) {} Promise<size_t> promise; char* data; size_t size; }; struct SendRequest { SendRequest(size_t _size) : size(_size) {} Promise<size_t> promise; size_t size; }; struct ConnectRequest { Promise<Nothing> promise; }; // This is a private constructor used by the accept helper // functions. LibeventSSLSocketImpl( int _s, bufferevent* bev, Option<std::string>&& peer_hostname); // This is called when the equivalent of 'accept' returns. The role // of this function is to set up the SSL object and bev. void accept_callback(AcceptRequest* request); // The following are function pairs of static functions to member // functions. The static functions test and hold the weak pointer to // the socket before calling the member functions. This protects // against the socket being destroyed before the event loop calls // the callbacks. static void recv_callback(bufferevent* bev, void* arg); void recv_callback(); static void send_callback(bufferevent* bev, void* arg); void send_callback(); static void event_callback(bufferevent* bev, short events, void* arg); void event_callback(short events); bufferevent* bev; evconnlistener* listener; // Protects the following instance variables. std::atomic_flag lock = ATOMIC_FLAG_INIT; Owned<RecvRequest> recv_request; Owned<SendRequest> send_request; Owned<ConnectRequest> connect_request; // This is a weak pointer to 'this', i.e., ourselves, this class // instance. We need this for our event loop callbacks because it's // possible that we'll actually want to cleanup this socket impl // before the event loop callback gets executed ... and we'll check // in each event loop callback whether or not this weak_ptr is valid // by attempting to upgrade it to shared_ptr. It is the // responsibility of the event loop through the deferred lambda in // the destructor to clean up this pointer. // 1) It is a 'weak_ptr' as opposed to a 'shared_ptr' because we // want to test whether the object is still around from within the // event loop. If it was a 'shared_ptr' then we would be // contributing to the lifetime of the object and would no longer be // able to test the lifetime correctly. // 2) This is a pointer to a 'weak_ptr' so that we can pass this // through to the event loop through the C-interface. We need access // to the 'weak_ptr' from outside the object (in the event loop) to // test if the object is still alive. By maintaining this 'weak_ptr' // on the heap we can be sure it is safe to access from the // event loop until it is destroyed. std::weak_ptr<LibeventSSLSocketImpl>* event_loop_handle; // This queue stores buffered accepted sockets. 'Queue' is a thread // safe queue implementation, and the event loop pushes connected // sockets onto it, the 'accept()' call pops them off. We wrap these // sockets with futures so that we can pass errors through and chain // futures as well. Queue<Future<Socket>> accept_queue; // This bool represents whether this socket was created through an // 'accept' flow. We use this in the destructor to change // the clean-up behavior for the SSL context object. bool accepted; Option<std::string> peer_hostname; }; } // namespace network { } // namespace process { #endif // __LIBEVENT_SSL_SOCKET_HPP__ <|endoftext|>
<commit_before>#include <znc/Client.h> #include <znc/Modules.h> #include <znc/IRCNetwork.h> #include <znc/IRCSock.h> class CPrioritySend : public CModule { public: MODCONSTRUCTOR(CPrioritySend) {} virtual EModRet OnUserNotice(CString& sTarget, CString& sMessage) override { return ProcessMessage("NOTICE", sTarget, sMessage); } virtual EModRet OnUserMsg(CString& sTarget, CString& sMessage) override { return ProcessMessage("PRIVMSG", sTarget, sMessage); } EModRet ProcessMessage(const CString& sFunction, CString& sTarget, CString& sMessage) { if (!sMessage.TrimPrefix("(p!)")) // TODO: This could be a config variable return CONTINUE; CIRCSock* pIRCSock = GetNetwork()->GetIRCSock(); if (!pIRCSock) return CONTINUE; pIRCSock->PutIRCQuick(sFunction + " " + sTarget + " :" + sMessage); return HALT; } }; NETWORKMODULEDEFS(CPrioritySend, "Allows certain messages to be placed in front of the send queue") <commit_msg>Make sure GetNetwork doesn't return null<commit_after>#include <znc/Client.h> #include <znc/Modules.h> #include <znc/IRCNetwork.h> #include <znc/IRCSock.h> class CPrioritySend : public CModule { public: MODCONSTRUCTOR(CPrioritySend) {} virtual EModRet OnUserNotice(CString& sTarget, CString& sMessage) override { return ProcessMessage("NOTICE", sTarget, sMessage); } virtual EModRet OnUserMsg(CString& sTarget, CString& sMessage) override { return ProcessMessage("PRIVMSG", sTarget, sMessage); } EModRet ProcessMessage(const CString& sFunction, CString& sTarget, CString& sMessage) { if (!sMessage.TrimPrefix("(p!)")) // TODO: This could be a config variable return CONTINUE; CIRCNetwork* pNetwork = GetNetwork(); if (!pNetwork) return CONTINUE; CIRCSock* pIRCSock = pNetwork->GetIRCSock(); if (!pIRCSock) return CONTINUE; pIRCSock->PutIRCQuick(sFunction + " " + sTarget + " :" + sMessage); return HALT; } }; NETWORKMODULEDEFS(CPrioritySend, "Allows certain messages to be placed in front of the send queue") <|endoftext|>
<commit_before>/** * 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 <gmock/gmock.h> #include <deque> #include <string> #include <process/socket.hpp> #include <stout/gtest.hpp> #include "decoder.hpp" using namespace process; using namespace process::http; using std::deque; using std::string; using process::network::Socket; TEST(DecoderTest, Request) { Try<Socket> socket = Socket::create(); ASSERT_SOME(socket); DataDecoder decoder = DataDecoder(socket.get()); const string data = "GET /path/file.json?key1=value1&key2=value2#fragment HTTP/1.1\r\n" "Host: localhost\r\n" "Connection: close\r\n" "Accept-Encoding: compress, gzip\r\n" "\r\n"; deque<Request*> requests = decoder.decode(data.data(), data.length()); ASSERT_FALSE(decoder.failed()); ASSERT_EQ(1, requests.size()); Request* request = requests[0]; EXPECT_EQ("GET", request->method); EXPECT_EQ("/path/file.json", request->url.path); EXPECT_SOME_EQ("fragment", request->url.fragment); EXPECT_EQ(2u, request->url.query.size()); EXPECT_SOME_EQ("value1", request->url.query.get("key1")); EXPECT_SOME_EQ("value2", request->url.query.get("key2")); EXPECT_TRUE(request->body.empty()); EXPECT_FALSE(request->keepAlive); EXPECT_EQ(3u, request->headers.size()); EXPECT_SOME_EQ("localhost", request->headers.get("Host")); EXPECT_SOME_EQ("close", request->headers.get("Connection")); EXPECT_SOME_EQ("compress, gzip", request->headers.get("Accept-Encoding")); delete request; } TEST(DecoderTest, RequestHeaderContinuation) { Try<Socket> socket = Socket::create(); ASSERT_SOME(socket); DataDecoder decoder = DataDecoder(socket.get()); const string data = "GET /path/file.json HTTP/1.1\r\n" "Host: localhost\r\n" "Connection: close\r\n" "Accept-Encoding: compress," " gzip\r\n" "\r\n"; deque<Request*> requests = decoder.decode(data.data(), data.length()); ASSERT_FALSE(decoder.failed()); ASSERT_EQ(1, requests.size()); Request* request = requests[0]; EXPECT_SOME_EQ("compress, gzip", request->headers.get("Accept-Encoding")); delete request; } // This is expected to fail for now, see my TODO(bmahler) on http::Request. TEST(DecoderTest, DISABLED_RequestHeaderCaseInsensitive) { Try<Socket> socket = Socket::create(); ASSERT_SOME(socket); DataDecoder decoder = DataDecoder(socket.get()); const string data = "GET /path/file.json HTTP/1.1\r\n" "Host: localhost\r\n" "cOnnECtioN: close\r\n" "accept-ENCODING: compress, gzip\r\n" "\r\n"; deque<Request*> requests = decoder.decode(data.data(), data.length()); ASSERT_FALSE(decoder.failed()); ASSERT_EQ(1, requests.size()); Request* request = requests[0]; EXPECT_FALSE(request->keepAlive); EXPECT_SOME_EQ("compress, gzip", request->headers.get("Accept-Encoding")); delete request; } TEST(DecoderTest, Response) { ResponseDecoder decoder; const string data = "HTTP/1.1 200 OK\r\n" "Date: Fri, 31 Dec 1999 23:59:59 GMT\r\n" "Content-Type: text/plain\r\n" "Content-Length: 2\r\n" "\r\n" "hi"; deque<Response*> responses = decoder.decode(data.data(), data.length()); ASSERT_FALSE(decoder.failed()); ASSERT_EQ(1, responses.size()); Response* response = responses[0]; EXPECT_EQ("200 OK", response->status); EXPECT_EQ(Response::BODY, response->type); EXPECT_EQ("hi", response->body); EXPECT_EQ(3, response->headers.size()); delete response; } TEST(DecoderTest, StreamingResponse) { StreamingResponseDecoder decoder; const string headers = "HTTP/1.1 200 OK\r\n" "Date: Fri, 31 Dec 1999 23:59:59 GMT\r\n" "Content-Type: text/plain\r\n" "Content-Length: 2\r\n" "\r\n"; const string body = "hi"; deque<Response*> responses = decoder.decode(headers.data(), headers.length()); ASSERT_FALSE(decoder.failed()); ASSERT_EQ(1, responses.size()); Response* response = responses[0]; EXPECT_EQ("200 OK", response->status); EXPECT_EQ(3, response->headers.size()); ASSERT_EQ(Response::PIPE, response->type); ASSERT_SOME(response->reader); http::Pipe::Reader reader = response->reader.get(); Future<string> read = reader.read(); EXPECT_TRUE(read.isPending()); decoder.decode(body.data(), body.length()); // Feeding EOF to the decoder should be ok. decoder.decode("", 0); EXPECT_TRUE(read.isReady()); EXPECT_EQ("hi", read.get()); // Response should be complete. read = reader.read(); EXPECT_TRUE(read.isReady()); EXPECT_EQ("", read.get()); } TEST(DecoderTest, StreamingResponseFailure) { StreamingResponseDecoder decoder; const string headers = "HTTP/1.1 200 OK\r\n" "Date: Fri, 31 Dec 1999 23:59:59 GMT\r\n" "Content-Type: text/plain\r\n" "Content-Length: 2\r\n" "\r\n"; // The body is shorter than the content length! const string body = "1"; deque<Response*> responses = decoder.decode(headers.data(), headers.length()); ASSERT_FALSE(decoder.failed()); ASSERT_EQ(1, responses.size()); Response* response = responses[0]; EXPECT_EQ("200 OK", response->status); EXPECT_EQ(3, response->headers.size()); ASSERT_EQ(Response::PIPE, response->type); ASSERT_SOME(response->reader); http::Pipe::Reader reader = response->reader.get(); Future<string> read = reader.read(); EXPECT_TRUE(read.isPending()); decoder.decode(body.data(), body.length()); EXPECT_TRUE(read.isReady()); EXPECT_EQ("1", read.get()); // Body is not yet complete. read = reader.read(); EXPECT_TRUE(read.isPending()); // Feeding EOF to the decoder should trigger a failure! decoder.decode("", 0); EXPECT_TRUE(read.isFailed()); EXPECT_EQ("failed to decode body", read.failure()); } <commit_msg>Re-enabled decoder test for case insensitive headers.<commit_after>/** * 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 <gmock/gmock.h> #include <deque> #include <string> #include <process/socket.hpp> #include <stout/gtest.hpp> #include "decoder.hpp" using namespace process; using namespace process::http; using std::deque; using std::string; using process::network::Socket; TEST(DecoderTest, Request) { Try<Socket> socket = Socket::create(); ASSERT_SOME(socket); DataDecoder decoder = DataDecoder(socket.get()); const string data = "GET /path/file.json?key1=value1&key2=value2#fragment HTTP/1.1\r\n" "Host: localhost\r\n" "Connection: close\r\n" "Accept-Encoding: compress, gzip\r\n" "\r\n"; deque<Request*> requests = decoder.decode(data.data(), data.length()); ASSERT_FALSE(decoder.failed()); ASSERT_EQ(1, requests.size()); Request* request = requests[0]; EXPECT_EQ("GET", request->method); EXPECT_EQ("/path/file.json", request->url.path); EXPECT_SOME_EQ("fragment", request->url.fragment); EXPECT_EQ(2u, request->url.query.size()); EXPECT_SOME_EQ("value1", request->url.query.get("key1")); EXPECT_SOME_EQ("value2", request->url.query.get("key2")); EXPECT_TRUE(request->body.empty()); EXPECT_FALSE(request->keepAlive); EXPECT_EQ(3u, request->headers.size()); EXPECT_SOME_EQ("localhost", request->headers.get("Host")); EXPECT_SOME_EQ("close", request->headers.get("Connection")); EXPECT_SOME_EQ("compress, gzip", request->headers.get("Accept-Encoding")); delete request; } TEST(DecoderTest, RequestHeaderContinuation) { Try<Socket> socket = Socket::create(); ASSERT_SOME(socket); DataDecoder decoder = DataDecoder(socket.get()); const string data = "GET /path/file.json HTTP/1.1\r\n" "Host: localhost\r\n" "Connection: close\r\n" "Accept-Encoding: compress," " gzip\r\n" "\r\n"; deque<Request*> requests = decoder.decode(data.data(), data.length()); ASSERT_FALSE(decoder.failed()); ASSERT_EQ(1, requests.size()); Request* request = requests[0]; EXPECT_SOME_EQ("compress, gzip", request->headers.get("Accept-Encoding")); delete request; } TEST(DecoderTest, RequestHeaderCaseInsensitive) { Try<Socket> socket = Socket::create(); ASSERT_SOME(socket); DataDecoder decoder = DataDecoder(socket.get()); const string data = "GET /path/file.json HTTP/1.1\r\n" "Host: localhost\r\n" "cOnnECtioN: close\r\n" "accept-ENCODING: compress, gzip\r\n" "\r\n"; deque<Request*> requests = decoder.decode(data.data(), data.length()); ASSERT_FALSE(decoder.failed()); ASSERT_EQ(1, requests.size()); Request* request = requests[0]; EXPECT_FALSE(request->keepAlive); EXPECT_SOME_EQ("compress, gzip", request->headers.get("Accept-Encoding")); delete request; } TEST(DecoderTest, Response) { ResponseDecoder decoder; const string data = "HTTP/1.1 200 OK\r\n" "Date: Fri, 31 Dec 1999 23:59:59 GMT\r\n" "Content-Type: text/plain\r\n" "Content-Length: 2\r\n" "\r\n" "hi"; deque<Response*> responses = decoder.decode(data.data(), data.length()); ASSERT_FALSE(decoder.failed()); ASSERT_EQ(1, responses.size()); Response* response = responses[0]; EXPECT_EQ("200 OK", response->status); EXPECT_EQ(Response::BODY, response->type); EXPECT_EQ("hi", response->body); EXPECT_EQ(3, response->headers.size()); delete response; } TEST(DecoderTest, StreamingResponse) { StreamingResponseDecoder decoder; const string headers = "HTTP/1.1 200 OK\r\n" "Date: Fri, 31 Dec 1999 23:59:59 GMT\r\n" "Content-Type: text/plain\r\n" "Content-Length: 2\r\n" "\r\n"; const string body = "hi"; deque<Response*> responses = decoder.decode(headers.data(), headers.length()); ASSERT_FALSE(decoder.failed()); ASSERT_EQ(1, responses.size()); Response* response = responses[0]; EXPECT_EQ("200 OK", response->status); EXPECT_EQ(3, response->headers.size()); ASSERT_EQ(Response::PIPE, response->type); ASSERT_SOME(response->reader); http::Pipe::Reader reader = response->reader.get(); Future<string> read = reader.read(); EXPECT_TRUE(read.isPending()); decoder.decode(body.data(), body.length()); // Feeding EOF to the decoder should be ok. decoder.decode("", 0); EXPECT_TRUE(read.isReady()); EXPECT_EQ("hi", read.get()); // Response should be complete. read = reader.read(); EXPECT_TRUE(read.isReady()); EXPECT_EQ("", read.get()); } TEST(DecoderTest, StreamingResponseFailure) { StreamingResponseDecoder decoder; const string headers = "HTTP/1.1 200 OK\r\n" "Date: Fri, 31 Dec 1999 23:59:59 GMT\r\n" "Content-Type: text/plain\r\n" "Content-Length: 2\r\n" "\r\n"; // The body is shorter than the content length! const string body = "1"; deque<Response*> responses = decoder.decode(headers.data(), headers.length()); ASSERT_FALSE(decoder.failed()); ASSERT_EQ(1, responses.size()); Response* response = responses[0]; EXPECT_EQ("200 OK", response->status); EXPECT_EQ(3, response->headers.size()); ASSERT_EQ(Response::PIPE, response->type); ASSERT_SOME(response->reader); http::Pipe::Reader reader = response->reader.get(); Future<string> read = reader.read(); EXPECT_TRUE(read.isPending()); decoder.decode(body.data(), body.length()); EXPECT_TRUE(read.isReady()); EXPECT_EQ("1", read.get()); // Body is not yet complete. read = reader.read(); EXPECT_TRUE(read.isPending()); // Feeding EOF to the decoder should trigger a failure! decoder.decode("", 0); EXPECT_TRUE(read.isFailed()); EXPECT_EQ("failed to decode body", read.failure()); } <|endoftext|>
<commit_before><commit_msg>11581 - Grid Successors<commit_after><|endoftext|>
<commit_before>/* * GoForward.cpp * * Created on: Mar 25, 2014 * Author: user */ #include "GoBackward.h" GoBackward::GoBackward(Robot* robot):Behavior(robot) { // TODO Auto-generated constructor stub } bool GoBackward::startCondition() { return false; } void GoBackward::action() { } bool GoBackward::stopCondition() { return false; } GoBackward::~GoBackward() { // TODO Auto-generated destructor stub } <commit_msg>Add logic to this behavior<commit_after>/* * GoForward.cpp * * Created on: Mar 25, 2014 * Author: user */ #include "GoBackward.h" GoBackward::GoBackward(Robot* robot):Behavior(robot), _steps_count(0) { } bool GoBackward::startCondition() { return true; } void GoBackward::action() { ++_steps_count; _robot->setSpeed(-0.1,0.0); } bool GoBackward::stopCondition() { if (_steps_count < 10) { return false; } else { _steps_count = 0; _robot->setSpeed(0.0, 0.0); return true; } } GoBackward::~GoBackward() { } <|endoftext|>
<commit_before>#include "ofMain.h" #include "Fisheye.h" #include "ofxTiming.h" #include "ofxOculusDK2.h" #include "ofxOsc.h" #include "ofxSyphon.h" class ofApp : public ofBaseApp { public: ofxSyphonClient cam; Fisheye fisheye; RateTimer cameraTimer, renderTimer; ofCamera camera; ofxOculusDK2 oculusRift; ofxOscReceiver osc; float targetLookAngle = 0; float lookAngle = 0; bool debug = false; void setup() { ofBackground(0); ofHideCursor(); ofSetWindowPosition(1920, 0); ofToggleFullscreen(); ofViewport(ofGetNativeViewport()); cam.setup(); cam.set("","Black Syphon"); fisheye.setup(); ofXml config; config.load("config.xml"); osc.setup(config.getIntValue("osc/port")); oculusRift.baseCamera = &camera; oculusRift.setup(); } void update() { renderTimer.tick(); while(osc.hasWaitingMessages()) { ofxOscMessage msg; osc.getNextMessage(&msg); if(msg.getAddress() == "/lookAngle") { targetLookAngle = msg.getArgAsFloat(0); } } lookAngle = ofLerp(lookAngle, targetLookAngle, .1); } void draw() { ofEnableDepthTest(); oculusRift.beginLeftEye(); drawScene(); oculusRift.endLeftEye(); oculusRift.beginRightEye(); drawScene(); oculusRift.endRightEye(); oculusRift.draw(); // this is essential for setting up the texture cam.bind(); cam.unbind(); } void drawScene() { ofPushMatrix(); ofScale(100, 100, 100); // avoid clipping ofRotateX(-90); ofRotateZ(-lookAngle); fisheye.draw(cam.getTexture()); ofPopMatrix(); if(debug) { ofDisableDepthTest(); ofTranslate(-50, 0, -100); ofScale(1, -1, 1); ofSetDrawBitmapMode(OF_BITMAPMODE_MODEL); ofDrawBitmapStringHighlight("Camera: " + ofToString((int) cameraTimer.getFramerate()), 0, 0); ofSetDrawBitmapMode(OF_BITMAPMODE_MODEL); ofDrawBitmapStringHighlight("Render: " + ofToString((int) renderTimer.getFramerate()), 0, 40); } } void keyPressed(int key) { if(key == 'd') { debug = !debug; } if(key == 'f') { ofToggleFullscreen(); } if(key == ' ') { string path = ofGetTimestampString() + ".jpg"; // ofSaveImage(cam.getColorPixels(), path); } } }; int main() { ofGLWindowSettings settings; settings.width = 1280; settings.height = 800; settings.setGLVersion(4, 1); ofCreateWindow(settings); ofRunApp(new ofApp()); } <commit_msg>correct orientation and rotation<commit_after>#include "ofMain.h" #include "Fisheye.h" #include "ofxTiming.h" #include "ofxOculusDK2.h" #include "ofxOsc.h" #include "ofxSyphon.h" class ofApp : public ofBaseApp { public: ofxSyphonClient cam; Fisheye fisheye; RateTimer cameraTimer, renderTimer; ofCamera camera; ofxOculusDK2 oculusRift; ofxOscReceiver osc; float targetLookAngle = 0; float lookAngle = 0; bool debug = false; void setup() { ofBackground(0); ofHideCursor(); ofSetWindowPosition(1920, 0); ofToggleFullscreen(); ofViewport(ofGetNativeViewport()); cam.setup(); cam.set("","Black Syphon"); fisheye.setup(); ofXml config; config.load("config.xml"); osc.setup(config.getIntValue("osc/port")); oculusRift.baseCamera = &camera; oculusRift.setup(); } void update() { renderTimer.tick(); while(osc.hasWaitingMessages()) { ofxOscMessage msg; osc.getNextMessage(&msg); if(msg.getAddress() == "/lookAngle") { targetLookAngle = msg.getArgAsFloat(0); } } lookAngle = ofLerp(lookAngle, targetLookAngle, .1); } void draw() { ofEnableDepthTest(); oculusRift.beginLeftEye(); drawScene(); oculusRift.endLeftEye(); oculusRift.beginRightEye(); drawScene(); oculusRift.endRightEye(); oculusRift.draw(); // this is essential for setting up the texture cam.bind(); cam.unbind(); } void drawScene() { ofPushMatrix(); ofScale(100, -100, 100); // avoid clipping ofRotateX(+90); ofRotateZ(+lookAngle); fisheye.draw(cam.getTexture()); ofPopMatrix(); if(debug) { ofDisableDepthTest(); ofTranslate(-50, 0, -100); ofScale(1, -1, 1); ofSetDrawBitmapMode(OF_BITMAPMODE_MODEL); ofDrawBitmapStringHighlight("Camera: " + ofToString((int) cameraTimer.getFramerate()), 0, 0); ofSetDrawBitmapMode(OF_BITMAPMODE_MODEL); ofDrawBitmapStringHighlight("Render: " + ofToString((int) renderTimer.getFramerate()), 0, 40); } } void keyPressed(int key) { if(key == 'd') { debug = !debug; } if(key == 'f') { ofToggleFullscreen(); } if(key == ' ') { string path = ofGetTimestampString() + ".jpg"; // ofSaveImage(cam.getColorPixels(), path); } } }; int main() { ofGLWindowSettings settings; settings.width = 1280; settings.height = 800; settings.setGLVersion(4, 1); ofCreateWindow(settings); ofRunApp(new ofApp()); } <|endoftext|>
<commit_before>// __BEGIN_LICENSE__ // Copyright (C) 2006-2011 United States Government as represented by // the Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. // __END_LICENSE__ /// \file disparitydebug.cc /// #ifdef _MSC_VER #pragma warning(disable:4244) #pragma warning(disable:4267) #pragma warning(disable:4996) #endif #ifdef NDEBUG #undef NDEBUG #endif #include <stdlib.h> #include <vw/FileIO.h> #include <vw/Image.h> #include <vw/Stereo/DisparityMap.h> #include <vw/tools/Common.h> #include <asp/Core/Macros.h> #include <asp/Core/Common.h> using namespace vw; using namespace vw::stereo; namespace po = boost::program_options; namespace fs = boost::filesystem; struct Options : asp::BaseOptions { // Input std::string input_file_name; // Output std::string output_prefix, output_file_type; }; void handle_arguments( int argc, char *argv[], Options& opt ) { po::options_description general_options(""); general_options.add_options() ("output-prefix,o", po::value(&opt.output_prefix), "Specify the output prefix") ("output-filetype,t", po::value(&opt.output_file_type)->default_value("tif"), "Specify the output file"); general_options.add( asp::BaseOptionsDescription(opt) ); po::options_description positional(""); positional.add_options() ("input-file", po::value(&opt.input_file_name), "Input disparity map"); po::positional_options_description positional_desc; positional_desc.add("input-file", 1); std::ostringstream usage; usage << "Usage: " << argv[0] << " [options] <input disparity map> \n"; po::variables_map vm = asp::check_command_line( argc, argv, opt, general_options, positional, positional_desc, usage.str() ); if ( opt.input_file_name.empty() ) vw_throw( ArgumentErr() << "Missing input file!\n" << usage.str() << general_options ); if ( opt.output_prefix.empty() ) opt.output_prefix = fs::path(opt.input_file_name).stem(); } template <class PixelT> void do_disparity_visualization(Options& opt) { DiskImageView<PixelT > disk_disparity_map(opt.input_file_name); vw_out() << "\t--> Computing disparity range \n"; BBox2 disp_range = get_disparity_range(disk_disparity_map); vw_out() << "\t Horizontal - [" << disp_range.min().x() << " " << disp_range.max().x() << "] Vertical: [" << disp_range.min().y() << " " << disp_range.max().y() << "]\n"; typedef typename PixelChannelType<PixelT>::type ChannelT; ImageViewRef<ChannelT> horizontal = apply_mask(copy_mask(clamp(normalize(select_channel(disk_disparity_map,0), disp_range.min().x(), disp_range.max().x())),disk_disparity_map)); ImageViewRef<ChannelT> vertical = apply_mask(copy_mask(clamp(normalize(select_channel(disk_disparity_map,1), disp_range.min().y(), disp_range.max().y())),disk_disparity_map)); vw_out() << "\t--> Saving disparity debug images\n"; block_write_gdal_image( opt.output_prefix+"-H."+opt.output_file_type, channel_cast_rescale<uint8>(horizontal), opt, TerminalProgressCallback("asp","\t Left : ")); block_write_gdal_image( opt.output_prefix + "-V." + opt.output_file_type, channel_cast_rescale<uint8>(vertical), opt, TerminalProgressCallback("asp","\t Right : ")); } int main( int argc, char *argv[] ) { Options opt; try { handle_arguments( argc, argv, opt ); vw_out() << "Opening " << opt.input_file_name << "\n"; ImageFormat fmt = tools::taste_image(opt.input_file_name); switch(fmt.pixel_format) { case VW_PIXEL_GENERIC_2_CHANNEL: switch (fmt.channel_type) { case VW_CHANNEL_INT32: do_disparity_visualization<Vector2i>(opt); break; default: do_disparity_visualization<Vector2f>(opt); break; } break; case VW_PIXEL_RGB: case VW_PIXEL_GENERIC_3_CHANNEL: switch (fmt.channel_type) { case VW_CHANNEL_INT32: do_disparity_visualization<PixelMask<Vector2i> >(opt); break; default: do_disparity_visualization<PixelMask<Vector2f> >(opt); break; } break; default: vw_throw( ArgumentErr() << "Unsupported pixel format. Expected GENERIC 2 or 3 CHANNEL image." ); } } ASP_STANDARD_CATCHES; return 0; } <commit_msg>Correct the normalization in disparity debug<commit_after>// __BEGIN_LICENSE__ // Copyright (C) 2006-2011 United States Government as represented by // the Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. // __END_LICENSE__ /// \file disparitydebug.cc /// #ifdef _MSC_VER #pragma warning(disable:4244) #pragma warning(disable:4267) #pragma warning(disable:4996) #endif #ifdef NDEBUG #undef NDEBUG #endif #include <stdlib.h> #include <vw/FileIO.h> #include <vw/Image.h> #include <vw/Stereo/DisparityMap.h> #include <vw/tools/Common.h> #include <asp/Core/Macros.h> #include <asp/Core/Common.h> using namespace vw; using namespace vw::stereo; namespace po = boost::program_options; namespace fs = boost::filesystem; struct Options : asp::BaseOptions { // Input std::string input_file_name; // Output std::string output_prefix, output_file_type; }; void handle_arguments( int argc, char *argv[], Options& opt ) { po::options_description general_options(""); general_options.add_options() ("output-prefix,o", po::value(&opt.output_prefix), "Specify the output prefix") ("output-filetype,t", po::value(&opt.output_file_type)->default_value("tif"), "Specify the output file"); general_options.add( asp::BaseOptionsDescription(opt) ); po::options_description positional(""); positional.add_options() ("input-file", po::value(&opt.input_file_name), "Input disparity map"); po::positional_options_description positional_desc; positional_desc.add("input-file", 1); std::ostringstream usage; usage << "Usage: " << argv[0] << " [options] <input disparity map> \n"; po::variables_map vm = asp::check_command_line( argc, argv, opt, general_options, positional, positional_desc, usage.str() ); if ( opt.input_file_name.empty() ) vw_throw( ArgumentErr() << "Missing input file!\n" << usage.str() << general_options ); if ( opt.output_prefix.empty() ) opt.output_prefix = fs::path(opt.input_file_name).stem(); } template <class PixelT> void do_disparity_visualization(Options& opt) { DiskImageView<PixelT > disk_disparity_map(opt.input_file_name); vw_out() << "\t--> Computing disparity range \n"; BBox2 disp_range = get_disparity_range(disk_disparity_map); vw_out() << "\t Horizontal - [" << disp_range.min().x() << " " << disp_range.max().x() << "] Vertical: [" << disp_range.min().y() << " " << disp_range.max().y() << "]\n"; typedef typename PixelChannelType<PixelT>::type ChannelT; ImageViewRef<ChannelT> horizontal = apply_mask(copy_mask(clamp(normalize(select_channel(disk_disparity_map,0), disp_range.min().x(), disp_range.max().x(), ChannelRange<ChannelT>::min(),ChannelRange<ChannelT>::max())), disk_disparity_map)); ImageViewRef<ChannelT> vertical = apply_mask(copy_mask(clamp(normalize(select_channel(disk_disparity_map,1), disp_range.min().y(), disp_range.max().y(), ChannelRange<ChannelT>::min(),ChannelRange<ChannelT>::max())), disk_disparity_map)); vw_out() << "\t--> Saving disparity debug images\n"; block_write_gdal_image( opt.output_prefix+"-H."+opt.output_file_type, channel_cast_rescale<uint8>(horizontal), opt, TerminalProgressCallback("asp","\t Left : ")); block_write_gdal_image( opt.output_prefix + "-V." + opt.output_file_type, channel_cast_rescale<uint8>(vertical), opt, TerminalProgressCallback("asp","\t Right : ")); } int main( int argc, char *argv[] ) { Options opt; try { handle_arguments( argc, argv, opt ); vw_out() << "Opening " << opt.input_file_name << "\n"; ImageFormat fmt = tools::taste_image(opt.input_file_name); switch(fmt.pixel_format) { case VW_PIXEL_GENERIC_2_CHANNEL: switch (fmt.channel_type) { case VW_CHANNEL_INT32: do_disparity_visualization<Vector2i>(opt); break; default: do_disparity_visualization<Vector2f>(opt); break; } break; case VW_PIXEL_RGB: case VW_PIXEL_GENERIC_3_CHANNEL: switch (fmt.channel_type) { case VW_CHANNEL_INT32: do_disparity_visualization<PixelMask<Vector2i> >(opt); break; default: do_disparity_visualization<PixelMask<Vector2f> >(opt); break; } break; default: vw_throw( ArgumentErr() << "Unsupported pixel format. Expected GENERIC 2 or 3 CHANNEL image." ); } } ASP_STANDARD_CATCHES; return 0; } <|endoftext|>
<commit_before>/* This file is part of Strigi Desktop Search * * Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "jstreamsconfig.h" #include "rpminputstream.h" #include "cpioinputstream.h" #include "gzipinputstream.h" #include "bz2inputstream.h" #include "subinputstream.h" #include <list> using namespace jstreams; using namespace std; class RpmInputStream::RpmHeaderInfo { }; /** * RPM files as specified here: * http://www.freestandards.org/spec/refspecs/LSB_1.3.0/gLSB/gLSB/swinstall.html * and here: * http://www.rpm.org/max-rpm-snapshot/s1-rpm-file-format-rpm-file-format.html **/ bool RpmInputStream::checkHeader(const char* data, int32_t datasize) { static const char unsigned magic[] = {0xed,0xab,0xee,0xdb,0x03,0x00}; if (datasize < 6) return false; // this check could be more strict bool ok = memcmp(data, magic, 6) == 0; return ok; } RpmInputStream::RpmInputStream(StreamBase<char>* input) : SubStreamProvider(input), headerinfo(0) { uncompressionStream = 0; cpio = 0; // skip the header const char* b; // lead:96 bytes if (input->read(b, 96, 96) != 96) { status = Error; error = "File is too small to be an RPM file."; return; } // read signature const unsigned char headmagic[] = {0x8e,0xad,0xe8,0x01}; if (input->read(b, 16, 16) != 16 || memcmp(b, headmagic, 4)!=0) { error = "error in signature\n"; status = Error; return; } int32_t nindex = read4bytes((const unsigned char*)(b+8)); int32_t hsize = read4bytes((const unsigned char*)(b+12)); int32_t sz = nindex*16+hsize; if (sz%8) { sz+=8-sz%8; } input->read(b, sz, sz); // read header if (input->read(b, 16, 16) != 16 || memcmp(b, headmagic, 4)!=0) { error = "error in header\n"; status = Error; return; } nindex = read4bytes((const unsigned char*)(b+8)); hsize = read4bytes((const unsigned char*)(b+12)); int32_t size = nindex*16+hsize; if (input->read(b, size, size) != size) { error = "could not read header\n"; status = Error; return; } for (int32_t i=0; i<nindex; ++i) { const unsigned char* e = (const unsigned char*)b+i*16; int32_t tag = read4bytes(e); int32_t type = read4bytes(e+4); int32_t offset = read4bytes(e+8); if (offset < 0 || offset >= hsize) { // error: invalid offset } int32_t count = read4bytes(e+12); int32_t end = hsize; if (i < nindex-1) { end = read4bytes(e+8+16); } if (end < offset) end = offset; if (end > hsize) end = hsize; // TODO actually put the data into the objects so the analyzers can use them /* if (type == 6) { string s(b+nindex*16+offset, end-offset); printf("%s\n", s.c_str()); } else if (type == 8 || type == 9) { list<string> v; // TODO handle string arrays } printf("%i\t%i\t%i\t%i\n", tag, type, offset, count);*/ } int64_t pos = input->getPosition(); if (input->read(b, 16, 16) != 16) { error = "could not read payload\n"; status = Error; return; } input->reset(pos); if (BZ2InputStream::checkHeader(b, 16)) { uncompressionStream = new BZ2InputStream(input); } else { uncompressionStream = new GZipInputStream(input); } if (uncompressionStream->getStatus() == Error) { error = uncompressionStream->getError(); status = Error; return; } cpio = new CpioInputStream(uncompressionStream); status = cpio->getStatus(); } RpmInputStream::~RpmInputStream() { if (uncompressionStream) { delete uncompressionStream; } if (cpio) { delete cpio; } if (headerinfo) { delete headerinfo; } } StreamBase<char>* RpmInputStream::nextEntry() { if (status) return 0; StreamBase<char>* entry = cpio->nextEntry(); status = cpio->getStatus(); if (status == Error) { error = cpio->getError(); } return entry; } int32_t RpmInputStream::read4bytes(const unsigned char *b) { return (b[0]<<24) + (b[1]<<16) + (b[2]<<8) + b[3]; } <commit_msg>Fix regression caused by split of rpm and cpio streams.<commit_after>/* This file is part of Strigi Desktop Search * * Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "jstreamsconfig.h" #include "rpminputstream.h" #include "cpioinputstream.h" #include "gzipinputstream.h" #include "bz2inputstream.h" #include "subinputstream.h" #include <list> using namespace jstreams; using namespace std; class RpmInputStream::RpmHeaderInfo { }; /** * RPM files as specified here: * http://www.freestandards.org/spec/refspecs/LSB_1.3.0/gLSB/gLSB/swinstall.html * and here: * http://www.rpm.org/max-rpm-snapshot/s1-rpm-file-format-rpm-file-format.html **/ bool RpmInputStream::checkHeader(const char* data, int32_t datasize) { static const char unsigned magic[] = {0xed,0xab,0xee,0xdb,0x03,0x00}; if (datasize < 6) return false; // this check could be more strict bool ok = memcmp(data, magic, 6) == 0; return ok; } RpmInputStream::RpmInputStream(StreamBase<char>* input) : SubStreamProvider(input), headerinfo(0) { uncompressionStream = 0; cpio = 0; // skip the header const char* b; // lead:96 bytes if (input->read(b, 96, 96) != 96) { status = Error; error = "File is too small to be an RPM file."; return; } // read signature const unsigned char headmagic[] = {0x8e,0xad,0xe8,0x01}; if (input->read(b, 16, 16) != 16 || memcmp(b, headmagic, 4)!=0) { error = "error in signature\n"; status = Error; return; } int32_t nindex = read4bytes((const unsigned char*)(b+8)); int32_t hsize = read4bytes((const unsigned char*)(b+12)); int32_t sz = nindex*16+hsize; if (sz%8) { sz+=8-sz%8; } input->read(b, sz, sz); // read header if (input->read(b, 16, 16) != 16 || memcmp(b, headmagic, 4)!=0) { error = "error in header\n"; status = Error; return; } nindex = read4bytes((const unsigned char*)(b+8)); hsize = read4bytes((const unsigned char*)(b+12)); int32_t size = nindex*16+hsize; if (input->read(b, size, size) != size) { error = "could not read header\n"; status = Error; return; } for (int32_t i=0; i<nindex; ++i) { const unsigned char* e = (const unsigned char*)b+i*16; int32_t tag = read4bytes(e); int32_t type = read4bytes(e+4); int32_t offset = read4bytes(e+8); if (offset < 0 || offset >= hsize) { // error: invalid offset } int32_t count = read4bytes(e+12); int32_t end = hsize; if (i < nindex-1) { end = read4bytes(e+8+16); } if (end < offset) end = offset; if (end > hsize) end = hsize; // TODO actually put the data into the objects so the analyzers can use them /* if (type == 6) { string s(b+nindex*16+offset, end-offset); printf("%s\n", s.c_str()); } else if (type == 8 || type == 9) { list<string> v; // TODO handle string arrays } printf("%i\t%i\t%i\t%i\n", tag, type, offset, count);*/ } int64_t pos = input->getPosition(); if (input->read(b, 16, 16) != 16) { error = "could not read payload\n"; status = Error; return; } input->reset(pos); if (BZ2InputStream::checkHeader(b, 16)) { uncompressionStream = new BZ2InputStream(input); } else { uncompressionStream = new GZipInputStream(input); } if (uncompressionStream->getStatus() == Error) { error = uncompressionStream->getError(); status = Error; return; } cpio = new CpioInputStream(uncompressionStream); status = cpio->getStatus(); } RpmInputStream::~RpmInputStream() { if (uncompressionStream) { delete uncompressionStream; } if (cpio) { delete cpio; } if (headerinfo) { delete headerinfo; } } StreamBase<char>* RpmInputStream::nextEntry() { if (status) return 0; StreamBase<char>* entry = cpio->nextEntry(); status = cpio->getStatus(); if (status == Ok) { entryinfo = cpio->getEntryInfo(); } else if (status == Error) { error = cpio->getError(); } return entry; } int32_t RpmInputStream::read4bytes(const unsigned char *b) { return (b[0]<<24) + (b[1]<<16) + (b[2]<<8) + b[3]; } <|endoftext|>
<commit_before>/* * This material contains unpublished, proprietary software of * Entropic Research Laboratory, Inc. Any reproduction, distribution, * or publication of this work must be authorized in writing by Entropic * Research Laboratory, Inc., and must bear the notice: * * "Copyright (c) 1990-1996 Entropic Research Laboratory, Inc. * All rights reserved" * * The copyright notice above does not evidence any actual or intended * publication of this source code. * * Written by: Derek Lin * Checked by: * Revised by: David Talkin * * Brief description: Estimates F0 using normalized cross correlation and * dynamic programming. * */ #include <math.h> #include <stdlib.h> #include <string.h> #include <malloc.h> #include <limits.h> #include <stdexcept> #include <sstream> #include <vector> #include "f0.h" int debug_level = 0; // ---------------------------------------- // Externs extern "C" { int init_dp_f0(double freq, F0_params *par, long *buffsize, long *sdstep); int dp_f0(float *fdata, int buff_size, int sdstep, double freq, F0_params *par, float **f0p_pt, float **vuvp_pt, float **rms_speech_pt, float **acpkp_pt, int *vecsize, int last_time); } struct f0_params; namespace GetF0 { // EXCEPTIONS #define CREATE_ERROR(_Name, _Base) \ class _Name : public _Base { \ public: \ explicit _Name(const std::string &what_arg) : _Base(what_arg) {} \ }; CREATE_ERROR(RuntimeError, std::runtime_error); CREATE_ERROR(LogicError, std::logic_error); CREATE_ERROR(ParameterError, RuntimeError); CREATE_ERROR(ProcessingError, RuntimeError); #undef CREATE_ERROR #define THROW_ERROR(condition, exception, s) \ do { \ if (condition) { \ std::stringstream ss; \ ss << s; \ throw exception(ss.str()); \ } \ } while (0); class GetF0 { public: typedef double SampleFrequency; typedef int DebugLevel; GetF0(SampleFrequency sampleFrequency, DebugLevel debugLevel = 0); void resetParameters(); /// @brief Some consistency checks on parameter values. Throws /// ParameterError if there's something wrong. void checkParameters(); void init(); void run(); // ---------------------------------------- // Getters/setters float& paramCandThresh() { return m_par.cand_thresh; } // only correlation peaks above this are considered float& paramLagWeight() { return m_par.lag_weight; } // degree to which shorter lags are weighted float& paramFreqWeight() { return m_par.freq_weight; } // weighting given to F0 trajectory smoothness float& paramTransCost() { return m_par.trans_cost; } // fixed cost for a voicing-state transition float& paramTransAmp() { return m_par.trans_amp; } // amplitude-change-modulated VUV trans. cost float& paramTransSpec() { return m_par.trans_spec; } // spectral-change-modulated VUV trans. cost float& paramVoiceBias() { return m_par.voice_bias; } // fixed bias towards the voiced hypothesis float& paramDoubleCost() { return m_par.double_cost; } // cost for octave F0 jumps float& paramMeanF0() { return m_par.mean_f0; } // talker-specific mean F0 (Hz) float& paramMeanF0Weight() { return m_par.mean_f0_weight; } // weight to be given to deviations from mean F0 float& paramMinF0() { return m_par.min_f0; } // min. F0 to search for (Hz) float& paramMaxF0() { return m_par.max_f0; } // max. F0 to search for (Hz) float& paramFrameStep() { return m_par.frame_step; } // inter-frame-interval (sec) float& paramWindDur() { return m_par.wind_dur; } // duration of correlation window (sec) int & paramNCands() { return m_par.n_cands; } // max. # of F0 cands. to consider at each frame int & paramConditioning() { return m_par.conditioning; } // Specify optional signal pre-conditioning. SampleFrequency &sampleFrequency() { return m_sampleFrequency; }; DebugLevel &debugLevel() { return m_debugLevel; }; protected: /// @brief Provide a `buffer` we can read `num_records` samples /// from, returning how many samples we can read. Returning less /// than requested samples is a termination condition. /// /// `buffer` is not guaranteed to not be written to. (TODO: check to /// see if buffer can be written to.) virtual long read_samples(float **buffer, long num_records) { return 0; } /// @brief Like `read_samples`, but read `step` samples from /// previous buffer. virtual long read_samples_overlap(float **buffer, long num_records, long step) { return 0; } virtual void writeOutput(float *f0p, float *vuvp, float *rms_speech, float *acpkp, int vecsize) { } private: f0_params m_par; SampleFrequency m_sampleFrequency; DebugLevel m_debugLevel; bool m_initialized; long m_buffSize; long m_sdstep; }; GetF0::GetF0(SampleFrequency sampleFrequency, DebugLevel debugLevel) : m_sampleFrequency(sampleFrequency), m_debugLevel(debugLevel), m_initialized(false), m_buffSize(0), m_sdstep(0) { resetParameters(); } void GetF0::resetParameters() { m_par.cand_thresh = 0.3; m_par.lag_weight = 0.3; m_par.freq_weight = 0.02; m_par.trans_cost = 0.005; m_par.trans_amp = 0.5; m_par.trans_spec = 0.5; m_par.voice_bias = 0.0; m_par.double_cost = 0.35; m_par.min_f0 = 50; m_par.max_f0 = 550; m_par.frame_step = 0.01; m_par.wind_dur = 0.0075; m_par.n_cands = 20; m_par.mean_f0 = 200; /* unused */ m_par.mean_f0_weight = 0.0; /* unused */ m_par.conditioning = 0; /*unused */ } void GetF0::init() { checkParameters(); /*SW: Removed range restricter, but this may be interesting: if (total_samps < ((par->frame_step * 2.0) + par->wind_dur) * sf), then input range too small*/ // double output_starts = m_par.wind_dur/2.0; /* Average delay due to loc. of ref. window center. */ // SW: I think this is the time delay until output actually // starts. In other words, we'll have some dropped frames. // double frame_rate = 1.0 / m_par.frame_step; /* Initialize variables in get_f0.c; allocate data structures; * determine length and overlap of input frames to read. * * sw: Looks like init_dp_f0 never returns errors via rcode, but put * under assertion. */ THROW_ERROR(init_dp_f0(m_sampleFrequency, &m_par, &m_buffSize, &m_sdstep) || m_buffSize > INT_MAX || m_sdstep > INT_MAX, LogicError, "problem in init_dp_f0()."); m_initialized = true; } void GetF0::run() { THROW_ERROR(!m_initialized, LogicError, "Not initialized"); float* fdata = nullptr; float *f0p, *vuvp, *rms_speech, *acpkp; int done; int i, vecsize; long actsize = read_samples(&fdata, m_buffSize); while (true) { done = (actsize < m_buffSize); THROW_ERROR(dp_f0(fdata, (int)actsize, (int)m_sdstep, m_sampleFrequency, &m_par, &f0p, &vuvp, &rms_speech, &acpkp, &vecsize, done), ProcessingError, "problem in dp_f0()."); writeOutput(f0p, vuvp, rms_speech, acpkp, vecsize); if (done) break; actsize = read_samples_overlap(&fdata, m_buffSize, m_sdstep); } } void GetF0::checkParameters() { std::vector<std::string> errors; if ((m_par.cand_thresh < 0.01) || (m_par.cand_thresh > 0.99)) { errors.push_back("cand_thresh parameter must be between [0.01, 0.99]."); } if ((m_par.wind_dur > .1) || (m_par.wind_dur < .0001)) { errors.push_back("wind_dur parameter must be between [0.0001, 0.1]."); } if ((m_par.n_cands > 100) || (m_par.n_cands < 3)) { errors.push_back("n_cands parameter must be between [3,100]."); } if ((m_par.max_f0 <= m_par.min_f0) || (m_par.max_f0 >= (m_sampleFrequency / 2.0)) || (m_par.min_f0 < (m_sampleFrequency / 10000.0))) { errors.push_back( "min(max)_f0 parameter inconsistent with sampling frequency."); } double dstep = ((double)((int)(0.5 + (m_sampleFrequency * m_par.frame_step)))) / m_sampleFrequency; if (dstep != m_par.frame_step) { if (debug_level) Fprintf(stderr, "Frame step set to %f to exactly match signal sample rate.\n", dstep); m_par.frame_step = dstep; } if ((m_par.frame_step > 0.1) || (m_par.frame_step < (1.0 / m_sampleFrequency))) { errors.push_back( "frame_step parameter must be between [1/sampling rate, " "0.1]."); } if (!errors.empty()) { std::stringstream ss; bool first = true; for (auto &error : errors) { if (!first) ss << " "; ss << error; } THROW_ERROR(true, ParameterError, ss.str()); } } } // namespace GetF0 <commit_msg>StreamBufferSize and StreamOverlapSize<commit_after>/* * This material contains unpublished, proprietary software of * Entropic Research Laboratory, Inc. Any reproduction, distribution, * or publication of this work must be authorized in writing by Entropic * Research Laboratory, Inc., and must bear the notice: * * "Copyright (c) 1990-1996 Entropic Research Laboratory, Inc. * All rights reserved" * * The copyright notice above does not evidence any actual or intended * publication of this source code. * * Written by: Derek Lin * Checked by: * Revised by: David Talkin * * Brief description: Estimates F0 using normalized cross correlation and * dynamic programming. * */ #include <math.h> #include <stdlib.h> #include <string.h> #include <malloc.h> #include <limits.h> #include <stdexcept> #include <sstream> #include <vector> #include "f0.h" int debug_level = 0; // ---------------------------------------- // Externs extern "C" { int init_dp_f0(double freq, F0_params *par, long *buffsize, long *sdstep); int dp_f0(float *fdata, int buff_size, int sdstep, double freq, F0_params *par, float **f0p_pt, float **vuvp_pt, float **rms_speech_pt, float **acpkp_pt, int *vecsize, int last_time); } struct f0_params; namespace GetF0 { // EXCEPTIONS #define CREATE_ERROR(_Name, _Base) \ class _Name : public _Base { \ public: \ explicit _Name(const std::string &what_arg) : _Base(what_arg) {} \ }; CREATE_ERROR(RuntimeError, std::runtime_error); CREATE_ERROR(LogicError, std::logic_error); CREATE_ERROR(ParameterError, RuntimeError); CREATE_ERROR(ProcessingError, RuntimeError); #undef CREATE_ERROR #define THROW_ERROR(condition, exception, s) \ do { \ if (condition) { \ std::stringstream ss; \ ss << s; \ throw exception(ss.str()); \ } \ } while (0); class GetF0 { public: typedef double SampleFrequency; typedef int DebugLevel; GetF0(SampleFrequency sampleFrequency, DebugLevel debugLevel = 0); void resetParameters(); /// @brief Some consistency checks on parameter values. Throws /// ParameterError if there's something wrong. void checkParameters(); void init(); void run(); // ---------------------------------------- // Calculations available after init long streamBufferSize() const; long streamOverlapSize() const; // ---------------------------------------- // Getters/setters float& paramCandThresh() { return m_par.cand_thresh; } // only correlation peaks above this are considered float& paramLagWeight() { return m_par.lag_weight; } // degree to which shorter lags are weighted float& paramFreqWeight() { return m_par.freq_weight; } // weighting given to F0 trajectory smoothness float& paramTransCost() { return m_par.trans_cost; } // fixed cost for a voicing-state transition float& paramTransAmp() { return m_par.trans_amp; } // amplitude-change-modulated VUV trans. cost float& paramTransSpec() { return m_par.trans_spec; } // spectral-change-modulated VUV trans. cost float& paramVoiceBias() { return m_par.voice_bias; } // fixed bias towards the voiced hypothesis float& paramDoubleCost() { return m_par.double_cost; } // cost for octave F0 jumps float& paramMeanF0() { return m_par.mean_f0; } // talker-specific mean F0 (Hz) float& paramMeanF0Weight() { return m_par.mean_f0_weight; } // weight to be given to deviations from mean F0 float& paramMinF0() { return m_par.min_f0; } // min. F0 to search for (Hz) float& paramMaxF0() { return m_par.max_f0; } // max. F0 to search for (Hz) float& paramFrameStep() { return m_par.frame_step; } // inter-frame-interval (sec) float& paramWindDur() { return m_par.wind_dur; } // duration of correlation window (sec) int & paramNCands() { return m_par.n_cands; } // max. # of F0 cands. to consider at each frame int & paramConditioning() { return m_par.conditioning; } // Specify optional signal pre-conditioning. SampleFrequency &sampleFrequency() { return m_sampleFrequency; }; DebugLevel &debugLevel() { return m_debugLevel; }; protected: /// @brief Provide a `buffer` we can read `num_records` samples /// from, returning how many samples we can read. Returning less /// than requested samples is a termination condition. /// /// `buffer` is not guaranteed to not be written to. (TODO: check to /// see if buffer can be written to.) virtual long read_samples(float **buffer, long num_records) { return 0; } /// @brief Like `read_samples`, but read `step` samples from /// previous buffer. virtual long read_samples_overlap(float **buffer, long num_records, long step) { return 0; } virtual void writeOutput(float *f0p, float *vuvp, float *rms_speech, float *acpkp, int vecsize) { } private: f0_params m_par; SampleFrequency m_sampleFrequency; DebugLevel m_debugLevel; bool m_initialized; long m_streamBufferSize; long m_streamOverlapSize; }; GetF0::GetF0(SampleFrequency sampleFrequency, DebugLevel debugLevel) : m_sampleFrequency(sampleFrequency), m_debugLevel(debugLevel), m_initialized(false), m_streamBufferSize(0), m_streamOverlapSize(0) { resetParameters(); } void GetF0::resetParameters() { m_par.cand_thresh = 0.3; m_par.lag_weight = 0.3; m_par.freq_weight = 0.02; m_par.trans_cost = 0.005; m_par.trans_amp = 0.5; m_par.trans_spec = 0.5; m_par.voice_bias = 0.0; m_par.double_cost = 0.35; m_par.min_f0 = 50; m_par.max_f0 = 550; m_par.frame_step = 0.01; m_par.wind_dur = 0.0075; m_par.n_cands = 20; m_par.mean_f0 = 200; /* unused */ m_par.mean_f0_weight = 0.0; /* unused */ m_par.conditioning = 0; /*unused */ } void GetF0::init() { checkParameters(); /*SW: Removed range restricter, but this may be interesting: if (total_samps < ((par->frame_step * 2.0) + par->wind_dur) * sf), then input range too small*/ // double output_starts = m_par.wind_dur/2.0; /* Average delay due to loc. of ref. window center. */ // SW: I think this is the time delay until output actually // starts. In other words, we'll have some dropped frames. // double frame_rate = 1.0 / m_par.frame_step; /* Initialize variables in get_f0.c; allocate data structures; * determine length and overlap of input frames to read. * * sw: Looks like init_dp_f0 never returns errors via rcode, but put * under assertion. */ THROW_ERROR(init_dp_f0(m_sampleFrequency, &m_par, &m_streamBufferSize, &m_streamOverlapSize) || m_streamBufferSize > INT_MAX || m_streamOverlapSize > INT_MAX, LogicError, "problem in init_dp_f0()."); m_initialized = true; } void GetF0::run() { THROW_ERROR(!m_initialized, LogicError, "Not initialized"); float *fdata = nullptr; float *f0p, *vuvp, *rms_speech, *acpkp; int done; int i, vecsize; long actsize = read_samples(&fdata, m_streamBufferSize); while (true) { done = (actsize < m_streamBufferSize); THROW_ERROR( dp_f0(fdata, (int)actsize, (int)m_streamOverlapSize, m_sampleFrequency, &m_par, &f0p, &vuvp, &rms_speech, &acpkp, &vecsize, done), ProcessingError, "problem in dp_f0()."); writeOutput(f0p, vuvp, rms_speech, acpkp, vecsize); if (done) break; actsize = read_samples_overlap(&fdata, m_streamBufferSize, m_streamOverlapSize); } } void GetF0::checkParameters() { std::vector<std::string> errors; if ((m_par.cand_thresh < 0.01) || (m_par.cand_thresh > 0.99)) { errors.push_back("cand_thresh parameter must be between [0.01, 0.99]."); } if ((m_par.wind_dur > .1) || (m_par.wind_dur < .0001)) { errors.push_back("wind_dur parameter must be between [0.0001, 0.1]."); } if ((m_par.n_cands > 100) || (m_par.n_cands < 3)) { errors.push_back("n_cands parameter must be between [3,100]."); } if ((m_par.max_f0 <= m_par.min_f0) || (m_par.max_f0 >= (m_sampleFrequency / 2.0)) || (m_par.min_f0 < (m_sampleFrequency / 10000.0))) { errors.push_back( "min(max)_f0 parameter inconsistent with sampling frequency."); } double dstep = ((double)((int)(0.5 + (m_sampleFrequency * m_par.frame_step)))) / m_sampleFrequency; if (dstep != m_par.frame_step) { if (debug_level) Fprintf(stderr, "Frame step set to %f to exactly match signal sample rate.\n", dstep); m_par.frame_step = dstep; } if ((m_par.frame_step > 0.1) || (m_par.frame_step < (1.0 / m_sampleFrequency))) { errors.push_back( "frame_step parameter must be between [1/sampling rate, " "0.1]."); } if (!errors.empty()) { std::stringstream ss; bool first = true; for (auto &error : errors) { if (!first) ss << " "; ss << error; } THROW_ERROR(true, ParameterError, ss.str()); } } long GetF0::streamBufferSize() const { THROW_ERROR(!m_initialized, LogicError, "Not initialized"); return m_streamBufferSize; } long GetF0::streamOverlapSize() const { THROW_ERROR(!m_initialized, LogicError, "Not initialized"); return m_streamOverlapSize; } } // namespace GetF0 <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "URIPool.h" #include <memory> #include <decaf/util/Random.h> #include <decaf/lang/System.h> using namespace activemq; using namespace activemq::transport; using namespace activemq::transport::failover; using namespace decaf; using namespace decaf::net; using namespace decaf::util; using namespace decaf::lang; using namespace decaf::lang::exceptions; //////////////////////////////////////////////////////////////////////////////// URIPool::URIPool() : uriPool(), randomize( false ) { } //////////////////////////////////////////////////////////////////////////////// URIPool::URIPool(const decaf::util::List<URI>& uris) : uriPool(), randomize( false ) { this->uriPool.copy( uris ); } //////////////////////////////////////////////////////////////////////////////// URIPool::~URIPool() { } //////////////////////////////////////////////////////////////////////////////// URI URIPool::getURI() { synchronized(&uriPool) { if( !uriPool.isEmpty() ) { int index = 0; // Take the first one in the list unless random is on. if( isRandomize() ) { Random rand; rand.setSeed( decaf::lang::System::currentTimeMillis() ); index = rand.nextInt( (int)uriPool.size() ); } return uriPool.removeAt( index ); } } throw NoSuchElementException( __FILE__, __LINE__, "URI Pool is currently empty." ); } //////////////////////////////////////////////////////////////////////////////// bool URIPool::addURI(const URI& uri) { synchronized(&uriPool) { if (!uriPool.contains(uri)) { uriPool.add(uri); return true; } } return false; } //////////////////////////////////////////////////////////////////////////////// bool URIPool::addURIs(const LinkedList<URI>& uris) { bool result = false; synchronized(&uriPool) { std::auto_ptr<Iterator<URI> > iter(uris.iterator()); while (iter->hasNext()) { URI uri = iter->next(); if (!uriPool.contains(uri)) { uriPool.add(uri); result = true; } } } return result; } //////////////////////////////////////////////////////////////////////////////// bool URIPool::removeURI(const URI& uri) { synchronized(&uriPool) { if (uriPool.contains(uri)) { uriPool.remove(uri); return true; } } return false; } //////////////////////////////////////////////////////////////////////////////// bool URIPool::contains(const decaf::net::URI& uri) const { synchronized(&uriPool) { return uriPool.contains(uri); } } //////////////////////////////////////////////////////////////////////////////// bool URIPool::isPriority(const decaf::net::URI& uri) const { synchronized(&uriPool) { if (uriPool.isEmpty()) { return false; } return uriPool.getFirst().equals(uri); } } //////////////////////////////////////////////////////////////////////////////// void URIPool::clear() { synchronized(&uriPool) { this->uriPool.clear(); } } <commit_msg>clear a couple warnings<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "URIPool.h" #include <memory> #include <decaf/util/Random.h> #include <decaf/lang/System.h> using namespace activemq; using namespace activemq::transport; using namespace activemq::transport::failover; using namespace decaf; using namespace decaf::net; using namespace decaf::util; using namespace decaf::lang; using namespace decaf::lang::exceptions; //////////////////////////////////////////////////////////////////////////////// URIPool::URIPool() : uriPool(), randomize( false ) { } //////////////////////////////////////////////////////////////////////////////// URIPool::URIPool(const decaf::util::List<URI>& uris) : uriPool(), randomize( false ) { this->uriPool.copy( uris ); } //////////////////////////////////////////////////////////////////////////////// URIPool::~URIPool() { } //////////////////////////////////////////////////////////////////////////////// URI URIPool::getURI() { synchronized(&uriPool) { if( !uriPool.isEmpty() ) { int index = 0; // Take the first one in the list unless random is on. if( isRandomize() ) { Random rand; rand.setSeed( decaf::lang::System::currentTimeMillis() ); index = rand.nextInt( (int)uriPool.size() ); } return uriPool.removeAt( index ); } } throw NoSuchElementException( __FILE__, __LINE__, "URI Pool is currently empty." ); } //////////////////////////////////////////////////////////////////////////////// bool URIPool::addURI(const URI& uri) { synchronized(&uriPool) { if (!uriPool.contains(uri)) { uriPool.add(uri); return true; } } return false; } //////////////////////////////////////////////////////////////////////////////// bool URIPool::addURIs(const LinkedList<URI>& uris) { bool result = false; synchronized(&uriPool) { std::auto_ptr<Iterator<URI> > iter(uris.iterator()); while (iter->hasNext()) { URI uri = iter->next(); if (!uriPool.contains(uri)) { uriPool.add(uri); result = true; } } } return result; } //////////////////////////////////////////////////////////////////////////////// bool URIPool::removeURI(const URI& uri) { synchronized(&uriPool) { if (uriPool.contains(uri)) { uriPool.remove(uri); return true; } } return false; } //////////////////////////////////////////////////////////////////////////////// bool URIPool::contains(const decaf::net::URI& uri) const { bool result = false; synchronized(&uriPool) { result = uriPool.contains(uri); } return result; } //////////////////////////////////////////////////////////////////////////////// bool URIPool::isPriority(const decaf::net::URI& uri) const { synchronized(&uriPool) { if (!uriPool.isEmpty()) { return uriPool.getFirst().equals(uri); } } return false; } //////////////////////////////////////////////////////////////////////////////// void URIPool::clear() { synchronized(&uriPool) { this->uriPool.clear(); } } <|endoftext|>
<commit_before>/* ============================================================================== OscProcessor.cpp Created: 22 Jan 2015 10:56:59pm Author: Daniel Lindenfelser ============================================================================== */ #include "OscProcessor.h" OscProcessor::OscProcessor() : oscServer(this) { } OscProcessor::~OscProcessor() { managedOscParameters.clear(); } void OscProcessor::handleOscMessage(osc::ReceivedPacket packet) { parseOscPacket(packet); } void OscProcessor::changeListenerCallback(ChangeBroadcaster* source) { OscParameter* parameter = static_cast<OscParameter*>(source); if (parameter) { char buffer[1024]; osc::OutboundPacketStream packet(buffer, 1024); parameter->appendOscMessageToStream(packet); oscServer.sendMessage(packet); } } void OscProcessor::addOscParameter(OscParameter* parameter, bool internal) { if (parameter) { managedOscParameters.addIfNotAlreadyThere(parameter); if (!internal) { //parameter->addChangeListener(this); } } } void OscProcessor::removeOscParameter(OscParameter* p) { managedOscParameters.removeObject(p); } void OscProcessor::removeOscParameter(String regex) { Array<OscParameter*> toRemove; for (int index = 0; index < managedOscParameters.size(); index++) { if (managedOscParameters[index]->addressMatch(regex)) { toRemove.add(managedOscParameters[index]); } } for (int index = 0; index < toRemove.size(); index++) { managedOscParameters.removeObject(toRemove[index]); } } Array<OscParameter*> OscProcessor::getAllOscParameter(String regex) { Array<OscParameter*> parameters; for (int index = 0; index < managedOscParameters.size(); index++) { if (managedOscParameters[index]->addressMatch(regex)) { parameters.add(managedOscParameters[index]); } } return parameters; } OscParameter* OscProcessor::getOscParameter(String address) { for (int index = 0; index < managedOscParameters.size(); index++) { if (managedOscParameters[index]->getAddress() == address) { return managedOscParameters[index]; } } return nullptr; } Array<OscParameter*> OscProcessor::getAllOscParameter() { Array<OscParameter*> parameters; for (int index = 0; index < managedOscParameters.size(); index++) { parameters.add(managedOscParameters[index]); } return parameters; } void OscProcessor::dumpOscParameters() { for (int index = 0; index < managedOscParameters.size(); index++) { char buffer[1024]; osc::OutboundPacketStream packet(buffer, 1024); managedOscParameters[index]->appendOscMessageToStream(packet); oscServer.sendMessage(packet); } } var OscProcessor::getOscParameterValue(String address) { for (int index = 0; index < managedOscParameters.size(); index++) { if (managedOscParameters[index]->getAddress() == address) { return var(managedOscParameters[index]->getValue()); } } return var::null; } void OscProcessor::setOscParameterValue(String address, var value) { for (int index = 0; index < managedOscParameters.size(); index++) { if (managedOscParameters[index]->getAddress() == address) { managedOscParameters[index]->setValue(value); return; } } } void OscProcessor::addOscParameterListener(OscParameterListener* listener, OscParameter* parameter) { parameter->addOscParameterListener(listener); } void OscProcessor::addOscParameterListener(OscParameterListener* listener, String regex) { auto parameters = getAllOscParameter(regex); for (int index = 0; index < parameters.size(); index++) { parameters[index]->addOscParameterListener(listener); } } void OscProcessor::removeOscParameterListener(OscParameterListener* listener) { auto parameters = getAllOscParameter(); for (int index = 0; index < parameters.size(); index++) { parameters[index]->removeOscParameterListener(listener); } } void OscProcessor::parseOscPacket(osc::ReceivedPacket packet) { if (packet.Size()) { if (packet.IsBundle()) { osc::ReceivedBundle bundle(packet); parseOscBundle(bundle); } else { osc::ReceivedMessage message(packet); parseOscMessage(message); } } } void OscProcessor::parseOscMessage(osc::ReceivedMessage message) { String address(message.AddressPattern()); OscParameter* parameter = getOscParameter(address); if (parameter) { osc::ReceivedMessage::const_iterator arg = message.ArgumentsBegin(); while (arg != message.ArgumentsEnd()) { if (arg->IsFloat()) { parameter->setValue(var(arg->AsFloat())); } else if (arg->IsBool()) { parameter->setValue(var(arg->IsBool())); } else if (arg->IsInt32()) { parameter->setValue(var(arg->AsInt32())); } else if (arg->IsChar()) { parameter->setValue(var(String(arg->AsChar()))); } else if (arg->IsDouble()) { parameter->setValue(var(arg->AsDouble())); } else if (arg->IsString()) { parameter->setValue(var(String(arg->AsString()))); } else if (arg->IsSymbol()) { parameter->setValue(var(String(arg->IsSymbol()))); } arg++; } } } void OscProcessor::parseOscBundle(osc::ReceivedBundle bundle) { osc::ReceivedBundleElementIterator initiator = bundle.ElementsBegin(); for (int i = 0; i < bundle.ElementCount(); i++) { initiator++; if (initiator->IsBundle()) { osc::ReceivedBundle bundle(*initiator); parseOscBundle(bundle); } else { osc::ReceivedMessage message(*initiator); parseOscMessage(message); } } } OscServer* OscProcessor::getOscServer() { return &oscServer; } <commit_msg>enable changelistener<commit_after>/* ============================================================================== OscProcessor.cpp Created: 22 Jan 2015 10:56:59pm Author: Daniel Lindenfelser ============================================================================== */ #include "OscProcessor.h" OscProcessor::OscProcessor() : oscServer(this) { } OscProcessor::~OscProcessor() { managedOscParameters.clear(); } void OscProcessor::handleOscMessage(osc::ReceivedPacket packet) { parseOscPacket(packet); } void OscProcessor::changeListenerCallback(ChangeBroadcaster* source) { OscParameter* parameter = static_cast<OscParameter*>(source); if (parameter) { char buffer[1024]; osc::OutboundPacketStream packet(buffer, 1024); parameter->appendOscMessageToStream(packet); oscServer.sendMessage(packet); } } void OscProcessor::addOscParameter(OscParameter* parameter, bool internal) { if (parameter) { managedOscParameters.addIfNotAlreadyThere(parameter); if (!internal) { parameter->addChangeListener(this); } } } void OscProcessor::removeOscParameter(OscParameter* p) { managedOscParameters.removeObject(p); } void OscProcessor::removeOscParameter(String regex) { Array<OscParameter*> toRemove; for (int index = 0; index < managedOscParameters.size(); index++) { if (managedOscParameters[index]->addressMatch(regex)) { toRemove.add(managedOscParameters[index]); } } for (int index = 0; index < toRemove.size(); index++) { managedOscParameters.removeObject(toRemove[index]); } } Array<OscParameter*> OscProcessor::getAllOscParameter(String regex) { Array<OscParameter*> parameters; for (int index = 0; index < managedOscParameters.size(); index++) { if (managedOscParameters[index]->addressMatch(regex)) { parameters.add(managedOscParameters[index]); } } return parameters; } OscParameter* OscProcessor::getOscParameter(String address) { for (int index = 0; index < managedOscParameters.size(); index++) { if (managedOscParameters[index]->getAddress() == address) { return managedOscParameters[index]; } } return nullptr; } Array<OscParameter*> OscProcessor::getAllOscParameter() { Array<OscParameter*> parameters; for (int index = 0; index < managedOscParameters.size(); index++) { parameters.add(managedOscParameters[index]); } return parameters; } void OscProcessor::dumpOscParameters() { for (int index = 0; index < managedOscParameters.size(); index++) { char buffer[1024]; osc::OutboundPacketStream packet(buffer, 1024); managedOscParameters[index]->appendOscMessageToStream(packet); oscServer.sendMessage(packet); } } var OscProcessor::getOscParameterValue(String address) { for (int index = 0; index < managedOscParameters.size(); index++) { if (managedOscParameters[index]->getAddress() == address) { return var(managedOscParameters[index]->getValue()); } } return var::null; } void OscProcessor::setOscParameterValue(String address, var value) { for (int index = 0; index < managedOscParameters.size(); index++) { if (managedOscParameters[index]->getAddress() == address) { managedOscParameters[index]->setValue(value); return; } } } void OscProcessor::addOscParameterListener(OscParameterListener* listener, OscParameter* parameter) { parameter->addOscParameterListener(listener); } void OscProcessor::addOscParameterListener(OscParameterListener* listener, String regex) { auto parameters = getAllOscParameter(regex); for (int index = 0; index < parameters.size(); index++) { parameters[index]->addOscParameterListener(listener); } } void OscProcessor::removeOscParameterListener(OscParameterListener* listener) { auto parameters = getAllOscParameter(); for (int index = 0; index < parameters.size(); index++) { parameters[index]->removeOscParameterListener(listener); } } void OscProcessor::parseOscPacket(osc::ReceivedPacket packet) { if (packet.Size()) { if (packet.IsBundle()) { osc::ReceivedBundle bundle(packet); parseOscBundle(bundle); } else { osc::ReceivedMessage message(packet); parseOscMessage(message); } } } void OscProcessor::parseOscMessage(osc::ReceivedMessage message) { String address(message.AddressPattern()); OscParameter* parameter = getOscParameter(address); if (parameter) { osc::ReceivedMessage::const_iterator arg = message.ArgumentsBegin(); while (arg != message.ArgumentsEnd()) { if (arg->IsFloat()) { parameter->setValue(var(arg->AsFloat())); } else if (arg->IsBool()) { parameter->setValue(var(arg->IsBool())); } else if (arg->IsInt32()) { parameter->setValue(var(arg->AsInt32())); } else if (arg->IsChar()) { parameter->setValue(var(String(arg->AsChar()))); } else if (arg->IsDouble()) { parameter->setValue(var(arg->AsDouble())); } else if (arg->IsString()) { parameter->setValue(var(String(arg->AsString()))); } else if (arg->IsSymbol()) { parameter->setValue(var(String(arg->IsSymbol()))); } arg++; } } } void OscProcessor::parseOscBundle(osc::ReceivedBundle bundle) { osc::ReceivedBundleElementIterator initiator = bundle.ElementsBegin(); for (int i = 0; i < bundle.ElementCount(); i++) { initiator++; if (initiator->IsBundle()) { osc::ReceivedBundle bundle(*initiator); parseOscBundle(bundle); } else { osc::ReceivedMessage message(*initiator); parseOscMessage(message); } } } OscServer* OscProcessor::getOscServer() { return &oscServer; } <|endoftext|>
<commit_before>#include <stdio.h> #include <inttypes.h> #include <lcm/lcm.h> #include <iostream> #include <limits> #include "joints2frames.hpp" #include <ConciseArgs> using namespace std; using namespace boost; using namespace boost::assign; #define DO_TIMING_PROFILE FALSE ///////////////////////////////////// joints2frames::joints2frames(boost::shared_ptr<lcm::LCM> &lcm_, bool show_labels_, bool show_triads_, bool standalone_head_, bool ground_height_, bool bdi_motion_estimate_): lcm_(lcm_), show_labels_(show_labels_), show_triads_(show_triads_), standalone_head_(standalone_head_), ground_height_(ground_height_), bdi_motion_estimate_(bdi_motion_estimate_){ model_ = boost::shared_ptr<ModelClient>(new ModelClient(lcm_->getUnderlyingLCM(), 0)); KDL::Tree tree; if (!kdl_parser::treeFromString( model_->getURDFString() ,tree)){ cerr << "ERROR: Failed to extract kdl tree from xml robot description" << endl; exit(-1); } fksolver_ = shared_ptr<KDL::TreeFkSolverPosFull_recursive>(new KDL::TreeFkSolverPosFull_recursive(tree)); // Vis Config: pc_vis_ = new pointcloud_vis( lcm_->getUnderlyingLCM()); // obj: id name type reset pc_vis_->obj_cfg_list.push_back( obj_cfg(6001,"Frames",5,1) ); lcm_->subscribe("EST_ROBOT_STATE",&joints2frames::robot_state_handler,this); pc_vis_->obj_cfg_list.push_back( obj_cfg(6003,"BDI Feet",5,1) ); lcm_->subscribe("ATLAS_FOOT_POS_EST",&joints2frames::foot_pos_est_handler,this); last_ground_publish_utime_ =0; } Eigen::Isometry3d KDLToEigen(KDL::Frame tf){ Eigen::Isometry3d tf_out; tf_out.setIdentity(); tf_out.translation() << tf.p[0], tf.p[1], tf.p[2]; Eigen::Quaterniond q; tf.M.GetQuaternion( q.x() , q.y(), q.z(), q.w()); tf_out.rotate(q); return tf_out; } void joints2frames::publishPose(Eigen::Isometry3d pose, int64_t utime, std::string channel){ bot_core::pose_t pose_msg; pose_msg.utime = utime; pose_msg.pos[0] = pose.translation().x(); pose_msg.pos[1] = pose.translation().y(); pose_msg.pos[2] = pose.translation().z(); Eigen::Quaterniond r_x(pose.rotation()); pose_msg.orientation[0] = r_x.w(); pose_msg.orientation[1] = r_x.x(); pose_msg.orientation[2] = r_x.y(); pose_msg.orientation[3] = r_x.z(); lcm_->publish( channel, &pose_msg); } void joints2frames::publishRigidTransform(Eigen::Isometry3d pose, int64_t utime, std::string channel){ bot_core::rigid_transform_t tf; tf.utime = utime; tf.trans[0] = pose.translation().x(); tf.trans[1] = pose.translation().y(); tf.trans[2] = pose.translation().z(); Eigen::Quaterniond quat(pose.rotation()); tf.quat[0] = quat.w(); tf.quat[1] = quat.x(); tf.quat[2] = quat.y(); tf.quat[3] = quat.z(); lcm_->publish(channel, &tf); } void joints2frames::robot_state_handler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const drc::robot_state_t* msg){ // 0. Extract World Pose of body: Eigen::Isometry3d world_to_body; world_to_body.setIdentity(); world_to_body.translation() << msg->pose.translation.x, msg->pose.translation.y, msg->pose.translation.z; Eigen::Quaterniond quat = Eigen::Quaterniond(msg->pose.rotation.w, msg->pose.rotation.x, msg->pose.rotation.y, msg->pose.rotation.z); world_to_body.rotate(quat); publishPose(world_to_body, msg->utime, "POSE_BODY" ); // 1. Solve for Forward Kinematics: // call a routine that calculates the transforms the joint_state_t* msg. map<string, double> jointpos_in; map<string, KDL::Frame > cartpos_out; for (uint i=0; i< (uint) msg->num_joints; i++) //cast to uint to suppress compiler warning jointpos_in.insert(make_pair(msg->joint_name[i], msg->joint_position[i])); // Calculate forward position kinematics bool kinematics_status; bool flatten_tree=true; // determines absolute transforms to robot origin, otherwise relative transforms between joints. kinematics_status = fksolver_->JntToCart(jointpos_in,cartpos_out,flatten_tree); if(kinematics_status>=0){ // cout << "Success!" <<endl; }else{ cerr << "Error: could not calculate forward kinematics!" <<endl; return; } // 2a. Determine the required BOT_FRAMES transforms: Eigen::Isometry3d body_to_head, body_to_hokuyo_link; bool body_to_head_found =false; bool body_to_hokuyo_link_found = false; for( map<string, KDL::Frame >::iterator ii=cartpos_out.begin(); ii!=cartpos_out.end(); ++ii){ std::string joint = (*ii).first; if ( (*ii).first.compare( "head" ) == 0 ){ body_to_head = KDLToEigen( (*ii).second ); body_to_head_found=true; }else if( (*ii).first.compare( "hokuyo_link" ) == 0 ){ body_to_hokuyo_link = KDLToEigen( (*ii).second ); body_to_hokuyo_link_found=true; }else if( (*ii).first.compare( "right_palm_left_camera_optical_frame" ) == 0 ){ publishRigidTransform( KDLToEigen( (*ii).second ) , msg->utime, "BODY_TO_CAMERARHAND_LEFT" ); }else if( (*ii).first.compare( "left_palm_left_camera_optical_frame" ) == 0 ){ publishRigidTransform( KDLToEigen( (*ii).second ) , msg->utime, "BODY_TO_CAMERALHAND_LEFT" ); } } // 2b. Republish the required BOT_FRAMES transforms: if (body_to_head_found){ /* * DONT PUBLISH THIS FOR SIMULATOR - CURRENTLY PUBLISHED BY LEGODO PROCESS */ if (bdi_motion_estimate_){ publishRigidTransform(body_to_head.inverse(), msg->utime, "HEAD_TO_BODY"); Eigen::Isometry3d world_to_head = world_to_body * body_to_head ; publishPose(world_to_head, msg->utime, "POSE_HEAD" ); } if (body_to_hokuyo_link_found){ Eigen::Isometry3d head_to_hokuyo_link = body_to_head.inverse() * body_to_hokuyo_link ; publishRigidTransform(head_to_hokuyo_link, msg->utime, "HEAD_TO_HOKUYO_LINK"); } } if (standalone_head_){ // If publishing from the head alone, then the head is also the body link: publishRigidTransform(body_to_hokuyo_link, msg->utime, "HEAD_TO_HOKUYO_LINK" ); } if (ground_height_){ // Publish a pose at the lower of the feet - assumed to be on the ground // TODO: This doesnt need to be published at 1000Hz Eigen::Isometry3d body_to_l_foot = KDLToEigen(cartpos_out.find("l_foot")->second); Eigen::Isometry3d body_to_r_foot = KDLToEigen(cartpos_out.find("r_foot")->second); Eigen::Isometry3d foot_to_sole; foot_to_sole.setIdentity(); foot_to_sole.translation() << 0.0,0.,-0.0811; //distance between foot link and sole of foot Eigen::Isometry3d world_to_l_sole = world_to_body * body_to_l_foot * foot_to_sole; Eigen::Isometry3d world_to_r_sole = world_to_body * body_to_r_foot * foot_to_sole; // Publish lower of the soles at the ground occasionally if (msg->utime - last_ground_publish_utime_ > 5E5){ // every 0.5sec last_ground_publish_utime_ =msg->utime; if ( world_to_l_sole.translation().z() < world_to_r_sole.translation().z() ){ publishPose(world_to_l_sole, msg->utime,"POSE_GROUND"); }else{ publishPose(world_to_r_sole, msg->utime,"POSE_GROUND"); } } } Eigen::Isometry3d body_to_utorso = KDLToEigen(cartpos_out.find("utorso")->second); publishRigidTransform(body_to_utorso, msg->utime, "BODY_TO_UTORSO"); // 4. Loop through joints and extract world positions: if (show_triads_){ int counter =msg->utime; std::vector<Isometry3dTime> body_to_jointTs, world_to_jointsT; std::vector< int64_t > body_to_joint_utimes; std::vector< std::string > joint_names; for( map<string, KDL::Frame >::iterator ii=cartpos_out.begin(); ii!=cartpos_out.end(); ++ii){ std::string joint = (*ii).first; //cout << joint << ": \n"; joint_names.push_back( joint ); body_to_joint_utimes.push_back( counter); Eigen::Isometry3d body_to_joint = KDLToEigen( (*ii).second ); Isometry3dTime body_to_jointT(counter, body_to_joint); body_to_jointTs.push_back(body_to_jointT); // convert to world positions Isometry3dTime world_to_jointT(counter, world_to_body*body_to_joint); world_to_jointsT.push_back(world_to_jointT); counter++; } pc_vis_->pose_collection_to_lcm_from_list(6001, world_to_jointsT); // all joints in world frame if (show_labels_) pc_vis_->text_collection_to_lcm(6002, 6001, "Frames [Labels]", joint_names, body_to_joint_utimes ); } } void joints2frames::foot_pos_est_handler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const drc::atlas_foot_pos_est_t* msg){ std::cout << "got em\n"; Eigen::Isometry3d left_pos; left_pos.setIdentity(); left_pos.translation() << msg->left_position[0], msg->left_position[1], msg->left_position[2]; Eigen::Isometry3d right_pos; right_pos.setIdentity(); right_pos.translation() << msg->right_position[0], msg->right_position[1], msg->right_position[2]; std::vector<Isometry3dTime> feet_posT; feet_posT.push_back( Isometry3dTime(msg->utime , left_pos ) ); feet_posT.push_back( Isometry3dTime(msg->utime+1 , right_pos ) ); pc_vis_->pose_collection_to_lcm_from_list(6003, feet_posT); } int main(int argc, char ** argv){ string role = "robot"; bool labels = false; bool triads = false; bool standalone_head = false; bool ground_height = false; bool bdi_motion_estimate = false; ConciseArgs opt(argc, (char**)argv); opt.add(role, "r", "role","Role - robot or base"); opt.add(triads, "t", "triads","Frame Triads - show no not"); opt.add(labels, "l", "labels","Frame Labels - show no not"); opt.add(ground_height, "g", "ground", "Publish the grounded foot pose"); opt.add(standalone_head, "s", "standalone_head","Standalone Sensor Head"); opt.add(bdi_motion_estimate, "b", "bdi","Use POSE_BDI to make frames [Temporary!]"); opt.parse(); if (labels){ // require triads if labels is to be published triads=true; } std::cout << "triads: " << triads << "\n"; std::cout << "labels: " << labels << "\n"; std::cout << "role: " << role << "\n"; string lcm_url=""; std::string role_upper; for(short i = 0; i < role.size(); ++i) role_upper+= (std::toupper(role[i])); if((role.compare("robot") == 0) || (role.compare("base") == 0) ){ for(short i = 0; i < role_upper.size(); ++i) role_upper[i] = (std::toupper(role_upper[i])); string env_variable_name = string("LCM_URL_DRC_" + role_upper); char* env_variable; env_variable = getenv (env_variable_name.c_str()); if (env_variable!=NULL){ //printf ("The env_variable is: %s\n",env_variable); lcm_url = string(env_variable); }else{ std::cout << env_variable_name << " environment variable has not been set ["<< lcm_url <<"]\n"; exit(-1); } }else{ std::cout << "Role not understood, choose: robot or base\n"; return 1; } boost::shared_ptr<lcm::LCM> lcm(new lcm::LCM(lcm_url) ); if(!lcm->good()) return 1; joints2frames app(lcm,labels,triads, standalone_head, ground_height, bdi_motion_estimate); while(0 == lcm->handle()); return 0; } <commit_msg>adding BDI foot position rendering<commit_after>#include <stdio.h> #include <inttypes.h> #include <lcm/lcm.h> #include <iostream> #include <limits> #include "joints2frames.hpp" #include <ConciseArgs> using namespace std; using namespace boost; using namespace boost::assign; #define DO_TIMING_PROFILE FALSE ///////////////////////////////////// joints2frames::joints2frames(boost::shared_ptr<lcm::LCM> &lcm_, bool show_labels_, bool show_triads_, bool standalone_head_, bool ground_height_, bool bdi_motion_estimate_): lcm_(lcm_), show_labels_(show_labels_), show_triads_(show_triads_), standalone_head_(standalone_head_), ground_height_(ground_height_), bdi_motion_estimate_(bdi_motion_estimate_){ model_ = boost::shared_ptr<ModelClient>(new ModelClient(lcm_->getUnderlyingLCM(), 0)); KDL::Tree tree; if (!kdl_parser::treeFromString( model_->getURDFString() ,tree)){ cerr << "ERROR: Failed to extract kdl tree from xml robot description" << endl; exit(-1); } fksolver_ = shared_ptr<KDL::TreeFkSolverPosFull_recursive>(new KDL::TreeFkSolverPosFull_recursive(tree)); // Vis Config: pc_vis_ = new pointcloud_vis( lcm_->getUnderlyingLCM()); // obj: id name type reset pc_vis_->obj_cfg_list.push_back( obj_cfg(6001,"Frames",5,1) ); lcm_->subscribe("EST_ROBOT_STATE",&joints2frames::robot_state_handler,this); pc_vis_->obj_cfg_list.push_back( obj_cfg(6003,"BDI Feet",5,1) ); lcm_->subscribe("ATLAS_FOOT_POS_EST",&joints2frames::foot_pos_est_handler,this); last_ground_publish_utime_ =0; } Eigen::Isometry3d KDLToEigen(KDL::Frame tf){ Eigen::Isometry3d tf_out; tf_out.setIdentity(); tf_out.translation() << tf.p[0], tf.p[1], tf.p[2]; Eigen::Quaterniond q; tf.M.GetQuaternion( q.x() , q.y(), q.z(), q.w()); tf_out.rotate(q); return tf_out; } void joints2frames::publishPose(Eigen::Isometry3d pose, int64_t utime, std::string channel){ bot_core::pose_t pose_msg; pose_msg.utime = utime; pose_msg.pos[0] = pose.translation().x(); pose_msg.pos[1] = pose.translation().y(); pose_msg.pos[2] = pose.translation().z(); Eigen::Quaterniond r_x(pose.rotation()); pose_msg.orientation[0] = r_x.w(); pose_msg.orientation[1] = r_x.x(); pose_msg.orientation[2] = r_x.y(); pose_msg.orientation[3] = r_x.z(); lcm_->publish( channel, &pose_msg); } void joints2frames::publishRigidTransform(Eigen::Isometry3d pose, int64_t utime, std::string channel){ bot_core::rigid_transform_t tf; tf.utime = utime; tf.trans[0] = pose.translation().x(); tf.trans[1] = pose.translation().y(); tf.trans[2] = pose.translation().z(); Eigen::Quaterniond quat(pose.rotation()); tf.quat[0] = quat.w(); tf.quat[1] = quat.x(); tf.quat[2] = quat.y(); tf.quat[3] = quat.z(); lcm_->publish(channel, &tf); } void joints2frames::robot_state_handler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const drc::robot_state_t* msg){ // 0. Extract World Pose of body: Eigen::Isometry3d world_to_body; world_to_body.setIdentity(); world_to_body.translation() << msg->pose.translation.x, msg->pose.translation.y, msg->pose.translation.z; Eigen::Quaterniond quat = Eigen::Quaterniond(msg->pose.rotation.w, msg->pose.rotation.x, msg->pose.rotation.y, msg->pose.rotation.z); world_to_body.rotate(quat); publishPose(world_to_body, msg->utime, "POSE_BODY" ); // 1. Solve for Forward Kinematics: // call a routine that calculates the transforms the joint_state_t* msg. map<string, double> jointpos_in; map<string, KDL::Frame > cartpos_out; for (uint i=0; i< (uint) msg->num_joints; i++) //cast to uint to suppress compiler warning jointpos_in.insert(make_pair(msg->joint_name[i], msg->joint_position[i])); // Calculate forward position kinematics bool kinematics_status; bool flatten_tree=true; // determines absolute transforms to robot origin, otherwise relative transforms between joints. kinematics_status = fksolver_->JntToCart(jointpos_in,cartpos_out,flatten_tree); if(kinematics_status>=0){ // cout << "Success!" <<endl; }else{ cerr << "Error: could not calculate forward kinematics!" <<endl; return; } // 2a. Determine the required BOT_FRAMES transforms: Eigen::Isometry3d body_to_head, body_to_hokuyo_link; bool body_to_head_found =false; bool body_to_hokuyo_link_found = false; for( map<string, KDL::Frame >::iterator ii=cartpos_out.begin(); ii!=cartpos_out.end(); ++ii){ std::string joint = (*ii).first; if ( (*ii).first.compare( "head" ) == 0 ){ body_to_head = KDLToEigen( (*ii).second ); body_to_head_found=true; }else if( (*ii).first.compare( "hokuyo_link" ) == 0 ){ body_to_hokuyo_link = KDLToEigen( (*ii).second ); body_to_hokuyo_link_found=true; }else if( (*ii).first.compare( "right_palm_left_camera_optical_frame" ) == 0 ){ publishRigidTransform( KDLToEigen( (*ii).second ) , msg->utime, "BODY_TO_CAMERARHAND_LEFT" ); }else if( (*ii).first.compare( "left_palm_left_camera_optical_frame" ) == 0 ){ publishRigidTransform( KDLToEigen( (*ii).second ) , msg->utime, "BODY_TO_CAMERALHAND_LEFT" ); } } // 2b. Republish the required BOT_FRAMES transforms: if (body_to_head_found){ /* * DONT PUBLISH THIS FOR SIMULATOR - CURRENTLY PUBLISHED BY LEGODO PROCESS */ if (bdi_motion_estimate_){ publishRigidTransform(body_to_head.inverse(), msg->utime, "HEAD_TO_BODY"); Eigen::Isometry3d world_to_head = world_to_body * body_to_head ; publishPose(world_to_head, msg->utime, "POSE_HEAD" ); } if (body_to_hokuyo_link_found){ Eigen::Isometry3d head_to_hokuyo_link = body_to_head.inverse() * body_to_hokuyo_link ; publishRigidTransform(head_to_hokuyo_link, msg->utime, "HEAD_TO_HOKUYO_LINK"); } } if (standalone_head_){ // If publishing from the head alone, then the head is also the body link: publishRigidTransform(body_to_hokuyo_link, msg->utime, "HEAD_TO_HOKUYO_LINK" ); } if (ground_height_){ // Publish a pose at the lower of the feet - assumed to be on the ground // TODO: This doesnt need to be published at 1000Hz Eigen::Isometry3d body_to_l_foot = KDLToEigen(cartpos_out.find("l_foot")->second); Eigen::Isometry3d body_to_r_foot = KDLToEigen(cartpos_out.find("r_foot")->second); Eigen::Isometry3d foot_to_sole; foot_to_sole.setIdentity(); foot_to_sole.translation() << 0.0,0.,-0.0811; //distance between foot link and sole of foot Eigen::Isometry3d world_to_l_sole = world_to_body * body_to_l_foot * foot_to_sole; Eigen::Isometry3d world_to_r_sole = world_to_body * body_to_r_foot * foot_to_sole; // Publish lower of the soles at the ground occasionally if (msg->utime - last_ground_publish_utime_ > 5E5){ // every 0.5sec last_ground_publish_utime_ =msg->utime; if ( world_to_l_sole.translation().z() < world_to_r_sole.translation().z() ){ publishPose(world_to_l_sole, msg->utime,"POSE_GROUND"); }else{ publishPose(world_to_r_sole, msg->utime,"POSE_GROUND"); } } } Eigen::Isometry3d body_to_utorso = KDLToEigen(cartpos_out.find("utorso")->second); publishRigidTransform(body_to_utorso, msg->utime, "BODY_TO_UTORSO"); // 4. Loop through joints and extract world positions: if (show_triads_){ int counter =msg->utime; std::vector<Isometry3dTime> body_to_jointTs, world_to_jointsT; std::vector< int64_t > body_to_joint_utimes; std::vector< std::string > joint_names; for( map<string, KDL::Frame >::iterator ii=cartpos_out.begin(); ii!=cartpos_out.end(); ++ii){ std::string joint = (*ii).first; //cout << joint << ": \n"; joint_names.push_back( joint ); body_to_joint_utimes.push_back( counter); Eigen::Isometry3d body_to_joint = KDLToEigen( (*ii).second ); Isometry3dTime body_to_jointT(counter, body_to_joint); body_to_jointTs.push_back(body_to_jointT); // convert to world positions Isometry3dTime world_to_jointT(counter, world_to_body*body_to_joint); world_to_jointsT.push_back(world_to_jointT); counter++; } pc_vis_->pose_collection_to_lcm_from_list(6001, world_to_jointsT); // all joints in world frame if (show_labels_) pc_vis_->text_collection_to_lcm(6002, 6001, "Frames [Labels]", joint_names, body_to_joint_utimes ); } } // Visualize the foot positions from BDI: // This can be turnned off if necessary - its not important void joints2frames::foot_pos_est_handler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const drc::atlas_foot_pos_est_t* msg){ Eigen::Isometry3d left_pos; left_pos.setIdentity(); left_pos.translation() << msg->left_position[0], msg->left_position[1], msg->left_position[2]; Eigen::Isometry3d right_pos; right_pos.setIdentity(); right_pos.translation() << msg->right_position[0], msg->right_position[1], msg->right_position[2]; std::vector<Isometry3dTime> feet_posT; feet_posT.push_back( Isometry3dTime(msg->utime , left_pos ) ); feet_posT.push_back( Isometry3dTime(msg->utime+1 , right_pos ) ); pc_vis_->pose_collection_to_lcm_from_list(6003, feet_posT); } int main(int argc, char ** argv){ string role = "robot"; bool labels = false; bool triads = false; bool standalone_head = false; bool ground_height = false; bool bdi_motion_estimate = false; ConciseArgs opt(argc, (char**)argv); opt.add(role, "r", "role","Role - robot or base"); opt.add(triads, "t", "triads","Frame Triads - show no not"); opt.add(labels, "l", "labels","Frame Labels - show no not"); opt.add(ground_height, "g", "ground", "Publish the grounded foot pose"); opt.add(standalone_head, "s", "standalone_head","Standalone Sensor Head"); opt.add(bdi_motion_estimate, "b", "bdi","Use POSE_BDI to make frames [Temporary!]"); opt.parse(); if (labels){ // require triads if labels is to be published triads=true; } std::cout << "triads: " << triads << "\n"; std::cout << "labels: " << labels << "\n"; std::cout << "role: " << role << "\n"; string lcm_url=""; std::string role_upper; for(short i = 0; i < role.size(); ++i) role_upper+= (std::toupper(role[i])); if((role.compare("robot") == 0) || (role.compare("base") == 0) ){ for(short i = 0; i < role_upper.size(); ++i) role_upper[i] = (std::toupper(role_upper[i])); string env_variable_name = string("LCM_URL_DRC_" + role_upper); char* env_variable; env_variable = getenv (env_variable_name.c_str()); if (env_variable!=NULL){ //printf ("The env_variable is: %s\n",env_variable); lcm_url = string(env_variable); }else{ std::cout << env_variable_name << " environment variable has not been set ["<< lcm_url <<"]\n"; exit(-1); } }else{ std::cout << "Role not understood, choose: robot or base\n"; return 1; } boost::shared_ptr<lcm::LCM> lcm(new lcm::LCM(lcm_url) ); if(!lcm->good()) return 1; joints2frames app(lcm,labels,triads, standalone_head, ground_height, bdi_motion_estimate); while(0 == lcm->handle()); return 0; } <|endoftext|>
<commit_before>// Copyright 2019 DeepMind Technologies Ltd. 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 "open_spiel/algorithms/is_mcts.h" #include <random> #include "open_spiel/abseil-cpp/absl/random/distributions.h" #include "open_spiel/algorithms/mcts.h" #include "open_spiel/spiel.h" #include "open_spiel/spiel_bots.h" #include "open_spiel/spiel_utils.h" namespace open_spiel { namespace { constexpr const int kSeed = 93879211; void PlayGame(const Game& game, algorithms::ISMCTSBot* bot, std::mt19937* rng) { std::unique_ptr<State> state = game.NewInitialState(); while (!state->IsTerminal()) { std::cout << "State:" << std::endl; std::cout << state->ToString() << std::endl; Action chosen_action = kInvalidAction; if (state->IsChanceNode()) { chosen_action = SampleAction(state->ChanceOutcomes(), absl::Uniform(*rng, 0.0, 1.0)) .first; } else { chosen_action = bot->Step(*state); } std::cout << "Chosen action: " << state->ActionToString(chosen_action) << std::endl; state->ApplyAction(chosen_action); } std::cout << "Terminal state:" << std::endl; std::cout << state->ToString() << std::endl; std::cout << "Returns: " << absl::StrJoin(state->Returns(), " ") << std::endl; } void ISMCTSTest_PlayGame(const std::string& game_name) { std::shared_ptr<const Game> game = LoadGame(game_name); auto evaluator = std::make_shared<algorithms::RandomRolloutEvaluator>(1, kSeed); for (algorithms::ISMCTSFinalPolicyType type: {algorithms::ISMCTSFinalPolicyType::kNormalizedVisitCount, algorithms::ISMCTSFinalPolicyType::kMaxVisitCount, algorithms::ISMCTSFinalPolicyType::kMaxValue}) { auto bot1 = std::make_unique<algorithms::ISMCTSBot>( kSeed, evaluator, 5.0, 1000, algorithms::kUnlimitedNumWorldSamples, type, false, false); std::mt19937 rng(kSeed); std::cout << "Testing " << game_name << ", bot 1" << std::endl; PlayGame(*game, bot1.get(), &rng); auto bot2 = std::make_unique<algorithms::ISMCTSBot>( kSeed, evaluator, 5.0, 1000, 10, type, false, false); std::cout << "Testing " << game_name << ", bot 2" << std::endl; PlayGame(*game, bot2.get(), &rng); } } void ISMCTS_BasicPlayGameTest_Kuhn() { ISMCTSTest_PlayGame("kuhn_poker"); ISMCTSTest_PlayGame("kuhn_poker(players=3)"); } void ISMCTS_BasicPlayGameTest_Leduc() { ISMCTSTest_PlayGame("leduc_poker"); ISMCTSTest_PlayGame("leduc_poker(players=3)"); } void ISMCTS_LeducObservationTest() { std::mt19937 rng(kSeed); std::shared_ptr<const Game> game = LoadGame("leduc_poker"); auto evaluator = std::make_shared<algorithms::RandomRolloutEvaluator>(1, kSeed); auto bot = std::make_unique<algorithms::ISMCTSBot>( kSeed, evaluator, 10.0, 1000, algorithms::kUnlimitedNumWorldSamples, algorithms::ISMCTSFinalPolicyType::kNormalizedVisitCount, true, true); PlayGame(*game, bot.get(), &rng); } } // namespace } // namespace open_spiel int main(int argc, char** argv) { open_spiel::ISMCTS_BasicPlayGameTest_Kuhn(); open_spiel::ISMCTS_BasicPlayGameTest_Leduc(); open_spiel::ISMCTS_LeducObservationTest(); }<commit_msg>Fix is_mcts whitespace formatting<commit_after>// Copyright 2019 DeepMind Technologies Ltd. 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 "open_spiel/algorithms/is_mcts.h" #include <random> #include "open_spiel/abseil-cpp/absl/random/distributions.h" #include "open_spiel/algorithms/mcts.h" #include "open_spiel/spiel.h" #include "open_spiel/spiel_bots.h" #include "open_spiel/spiel_utils.h" namespace open_spiel { namespace { constexpr const int kSeed = 93879211; void PlayGame(const Game& game, algorithms::ISMCTSBot* bot, std::mt19937* rng) { std::unique_ptr<State> state = game.NewInitialState(); while (!state->IsTerminal()) { std::cout << "State:" << std::endl; std::cout << state->ToString() << std::endl; Action chosen_action = kInvalidAction; if (state->IsChanceNode()) { chosen_action = SampleAction(state->ChanceOutcomes(), absl::Uniform(*rng, 0.0, 1.0)) .first; } else { chosen_action = bot->Step(*state); } std::cout << "Chosen action: " << state->ActionToString(chosen_action) << std::endl; state->ApplyAction(chosen_action); } std::cout << "Terminal state:" << std::endl; std::cout << state->ToString() << std::endl; std::cout << "Returns: " << absl::StrJoin(state->Returns(), " ") << std::endl; } void ISMCTSTest_PlayGame(const std::string& game_name) { std::shared_ptr<const Game> game = LoadGame(game_name); auto evaluator = std::make_shared<algorithms::RandomRolloutEvaluator>(1, kSeed); for (algorithms::ISMCTSFinalPolicyType type : {algorithms::ISMCTSFinalPolicyType::kNormalizedVisitCount, algorithms::ISMCTSFinalPolicyType::kMaxVisitCount, algorithms::ISMCTSFinalPolicyType::kMaxValue}) { auto bot1 = std::make_unique<algorithms::ISMCTSBot>( kSeed, evaluator, 5.0, 1000, algorithms::kUnlimitedNumWorldSamples, type, false, false); std::mt19937 rng(kSeed); std::cout << "Testing " << game_name << ", bot 1" << std::endl; PlayGame(*game, bot1.get(), &rng); auto bot2 = std::make_unique<algorithms::ISMCTSBot>( kSeed, evaluator, 5.0, 1000, 10, type, false, false); std::cout << "Testing " << game_name << ", bot 2" << std::endl; PlayGame(*game, bot2.get(), &rng); } } void ISMCTS_BasicPlayGameTest_Kuhn() { ISMCTSTest_PlayGame("kuhn_poker"); ISMCTSTest_PlayGame("kuhn_poker(players=3)"); } void ISMCTS_BasicPlayGameTest_Leduc() { ISMCTSTest_PlayGame("leduc_poker"); ISMCTSTest_PlayGame("leduc_poker(players=3)"); } void ISMCTS_LeducObservationTest() { std::mt19937 rng(kSeed); std::shared_ptr<const Game> game = LoadGame("leduc_poker"); auto evaluator = std::make_shared<algorithms::RandomRolloutEvaluator>(1, kSeed); auto bot = std::make_unique<algorithms::ISMCTSBot>( kSeed, evaluator, 10.0, 1000, algorithms::kUnlimitedNumWorldSamples, algorithms::ISMCTSFinalPolicyType::kNormalizedVisitCount, true, true); PlayGame(*game, bot.get(), &rng); } } // namespace } // namespace open_spiel int main(int argc, char** argv) { open_spiel::ISMCTS_BasicPlayGameTest_Kuhn(); open_spiel::ISMCTS_BasicPlayGameTest_Leduc(); open_spiel::ISMCTS_LeducObservationTest(); } <|endoftext|>
<commit_before>// // main.cpp // HashTables // // Created by Sunil on 4/28/17. // Copyright © 2017 Sunil. All rights reserved. // #include <string> #include <chrono> #include <fstream> #include <sstream> #include <iomanip> #include <iostream> #include "HashTable.hpp" #include "PlayerInfo.hpp" using namespace std; void die(string message) { cout << message << endl; exit(0); } void PopulateHashTable(string filename, HashTable* map) { ifstream file(filename); // non-existant or corrupted file if(file.fail()) { die("Could not open file"); } string line; string ignoreHeader; std::getline(file, ignoreHeader); // cout << ignoreHeader << endl; // std::setiosflags(ios::fixed); while(std::getline(file, line)) { auto playerInfo = PlayerInfo::ConstructFrom(line); // add playerInfo to the hash table. auto key = PlayerInfo::MakeKey(playerInfo); map->put(key, playerInfo); } } int getTableSize(string size) { char multiplier = ' '; float number; istringstream ss(size); ss >> number >> multiplier; switch (multiplier) { case 'k': case 'K': // Kilo number *= 1000; break; case ' ': break; default: cout << "Only K/k multiplier is supported!" << endl; break; } return number; } int main(int argc, const char * argv[]) { string dmenu = "1. Query hash table\n" "2. Quit program\n"; string help = "usage: $executable [input file] [hashtable size]\n" "example: $exe PlayerData.txt 5072"; if (argc < 3) { cout << "Missing arguments to the program!" << endl; die(help); } int choice = 0; bool done = false; string filename {argv[1]}; int hashSize = getTableSize(argv[2]); std::chrono::time_point<std::chrono::system_clock> start, end; // create collision counter variables CollisionCounter linearProbeStats("(linear probe)"); CollisionCounter chainingStats("(chaining)"); HashTable* map = new HashTable(hashSize, new ChainingResolver(&chainingStats)); HashTable* map2 = new HashTable(hashSize, new LinearProbingResolver(&linearProbeStats)); PopulateHashTable(filename, map); PopulateHashTable(filename, map2); cout << "Hash table size: " << hashSize << endl; cout << "Collisions using open addressing: " << linearProbeStats.addCollisions << endl; cout << "Collisions using chaining: " << chainingStats.addCollisions << endl; linearProbeStats.resetCounters(); chainingStats.resetCounters(); do { cout << dmenu; cin >> choice; // flush the newlines and other characters cin.clear(); cin.ignore(); switch (choice) { case 1: { string firstName, lastName; cout << "Enter first name: " << endl; std::getline(cin, firstName); cout << "Enter last name: " << endl; std::getline(cin, lastName); auto key = PlayerInfo::MakeKey(firstName, lastName); // look up with chaining { auto found = map->get(key); if (found) found->show(); else cout << "Record not found!" << endl; cout << "Search operations using chaining: " << chainingStats.lookupCollisions << endl; chainingStats.resetCounters(); } // look up with linear probing { auto found = map2->get(key); if (found) found->show(); else cout << "Record not found!" << endl; cout << "Search operations using open addressing: " << linearProbeStats.lookupCollisions << endl; linearProbeStats.resetCounters(); } break; } case 2: { done = true; break; } default: { // ignore unrecognized input. // and let program continue. } } } while(!done); cout << "Goodbye!" << endl; delete map; delete map2; return 0; } <commit_msg>format output<commit_after>// // main.cpp // HashTables // // Created by Sunil on 4/28/17. // Copyright © 2017 Sunil. All rights reserved. // #include <string> #include <chrono> #include <fstream> #include <sstream> #include <iomanip> #include <iostream> #include "HashTable.hpp" #include "PlayerInfo.hpp" using namespace std; void die(string message) { cout << message << endl; exit(0); } void PopulateHashTable(string filename, HashTable* map) { ifstream file(filename); // non-existant or corrupted file if(file.fail()) { die("Could not open file"); } string line; string ignoreHeader; std::getline(file, ignoreHeader); // cout << ignoreHeader << endl; // std::setiosflags(ios::fixed); while(std::getline(file, line)) { auto playerInfo = PlayerInfo::ConstructFrom(line); // add playerInfo to the hash table. auto key = PlayerInfo::MakeKey(playerInfo); map->put(key, playerInfo); } } int getTableSize(string size) { char multiplier = ' '; float number; istringstream ss(size); ss >> number >> multiplier; switch (multiplier) { case 'k': case 'K': // Kilo number *= 1000; break; case ' ': break; default: cout << "Only K/k multiplier is supported!" << endl; break; } return number; } int main(int argc, const char * argv[]) { string dmenu = "1. Query hash table\n" "2. Quit program\n"; string help = "usage: $executable [input file] [hashtable size]\n" "example: $exe PlayerData.txt 5072"; if (argc < 3) { cout << "Missing arguments to the program!" << endl; die(help); } int choice = 0; bool done = false; string filename {argv[1]}; int hashSize = getTableSize(argv[2]); std::chrono::time_point<std::chrono::system_clock> start, end; // create collision counter variables CollisionCounter linearProbeStats("(linear probe)"); CollisionCounter chainingStats("(chaining)"); HashTable* map = new HashTable(hashSize, new ChainingResolver(&chainingStats)); HashTable* map2 = new HashTable(hashSize, new LinearProbingResolver(&linearProbeStats)); PopulateHashTable(filename, map); PopulateHashTable(filename, map2); cout << "Hash table size: " << hashSize << endl; cout << "Collisions using open addressing: " << linearProbeStats.addCollisions << endl; cout << "Collisions using chaining: " << chainingStats.addCollisions << endl; linearProbeStats.resetCounters(); chainingStats.resetCounters(); do { cout << dmenu; cin >> choice; // flush the newlines and other characters cin.clear(); cin.ignore(); switch (choice) { case 1: { string firstName, lastName; cout << "Enter first name: "; std::getline(cin, firstName); cout << "Enter last name: "; std::getline(cin, lastName); auto key = PlayerInfo::MakeKey(firstName, lastName); // look up with chaining { auto found = map->get(key); cout << endl << "Search operations using chaining: " << chainingStats.lookupCollisions << endl; if (found) found->show(); else cout << "Record not found!" << endl; chainingStats.resetCounters(); } // look up with linear probing { auto found = map2->get(key); cout << "Search operations using open addressing: " << linearProbeStats.lookupCollisions << endl; if (found) found->show(); else cout << "Record not found!" << endl; linearProbeStats.resetCounters(); } break; } case 2: { done = true; break; } default: { // ignore unrecognized input. // and let program continue. } } } while(!done); cout << "Goodbye!" << endl; delete map; delete map2; return 0; } <|endoftext|>
<commit_before>/* * opencog/atomspace/SimpleTruthValue.cc * * Copyright (C) 2002-2007 Novamente LLC * All Rights Reserved * * Written by Welter Silva <welter@vettalabs.com> * Guilherme Lamacie * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * */ #include <math.h> #include <typeinfo> #include <opencog/util/platform.h> #include <opencog/util/exceptions.h> #include "SimpleTruthValue.h" //#define DPRINTF printf #define DPRINTF(...) using namespace opencog; #define KKK 800.0f #define CVAL 0.2f SimpleTruthValue::SimpleTruthValue(strength_t m, count_t c) { mean = m; count = c; } SimpleTruthValue::SimpleTruthValue(const TruthValue& source) { mean = source.getMean(); count = source.getCount(); } SimpleTruthValue::SimpleTruthValue(SimpleTruthValue const& source) { mean = source.mean; count = source.count; } strength_t SimpleTruthValue::getMean() const { return mean; } count_t SimpleTruthValue::getCount() const { return count; } confidence_t SimpleTruthValue::getConfidence() const { return countToConfidence(count); } // This is the merge formula appropriate for PLN. TruthValuePtr SimpleTruthValue::merge(TruthValuePtr other,TVMergeStyle ms/*=DEFAULT*/) const { switch(ms){ case DEFAULT: { if (other->getType() != SIMPLE_TRUTH_VALUE) throw RuntimeException(TRACE_INFO, "Don't know how to merge %s into a SimpleTruthValue using the default style", typeid(*other).name()); auto count2 = other->getCount(); auto count_new = count+ count2 - std::min(count,count2)*CVAL; auto mean_new = (mean*count + other->getMean()*count2)/(count+count2); return std::make_shared<SimpleTruthValue>(mean_new,count_new); } default: throw RuntimeException(TRACE_INFO, "Unknown or not yet implemented merge strategy"); } } std::string SimpleTruthValue::toString() const { char buf[1024]; sprintf(buf, "(stv %f %f)", static_cast<float>(getMean()), static_cast<float>(getConfidence())); return buf; } bool SimpleTruthValue::operator==(const TruthValue& rhs) const { const SimpleTruthValue *stv = dynamic_cast<const SimpleTruthValue *>(&rhs); if (NULL == stv) return false; #define FLOAT_ACCEPTABLE_MEAN_ERROR 0.000001 if (FLOAT_ACCEPTABLE_MEAN_ERROR < fabs(mean - stv->mean)) return false; // Converting from confidence to count and back again using single-precision // float is a real accuracy killer. In particular, 2/802 = 0.002494 but // converting back gives 800*0.002494/(1.0-0.002494) = 2.000188 and so // comparison tests can only be accurate to about 0.000188 or // thereabouts. #define FLOAT_ACCEPTABLE_COUNT_ERROR 0.0002 if (FLOAT_ACCEPTABLE_COUNT_ERROR < fabs(1.0 - (stv->count/count))) return false; return true; } TruthValueType SimpleTruthValue::getType() const { return SIMPLE_TRUTH_VALUE; } count_t SimpleTruthValue::confidenceToCount(confidence_t cf) { // There are not quite 16 digits in double precision // not quite 7 in single-precision float cf = std::min(cf, 0.9999998f); return static_cast<count_t>(KKK * cf / (1.0f - cf)); } confidence_t SimpleTruthValue::countToConfidence(count_t cn) { return static_cast<confidence_t>(cn / (cn + KKK)); } <commit_msg>added reference<commit_after>/* * opencog/atomspace/SimpleTruthValue.cc * * Copyright (C) 2002-2007 Novamente LLC * All Rights Reserved * * Written by Welter Silva <welter@vettalabs.com> * Guilherme Lamacie * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * */ #include <math.h> #include <typeinfo> #include <opencog/util/platform.h> #include <opencog/util/exceptions.h> #include "SimpleTruthValue.h" //#define DPRINTF printf #define DPRINTF(...) using namespace opencog; #define KKK 800.0f #define CVAL 0.2f SimpleTruthValue::SimpleTruthValue(strength_t m, count_t c) { mean = m; count = c; } SimpleTruthValue::SimpleTruthValue(const TruthValue& source) { mean = source.getMean(); count = source.getCount(); } SimpleTruthValue::SimpleTruthValue(SimpleTruthValue const& source) { mean = source.mean; count = source.count; } strength_t SimpleTruthValue::getMean() const { return mean; } count_t SimpleTruthValue::getCount() const { return count; } confidence_t SimpleTruthValue::getConfidence() const { return countToConfidence(count); } // This is the merge formula appropriate for PLN. TruthValuePtr SimpleTruthValue::merge(TruthValuePtr other,TVMergeStyle ms/*=DEFAULT*/) const { switch(ms){ case DEFAULT: { //Based on section 5.10.2(A heuristic revision rule for STV) of the PLN book if (other->getType() != SIMPLE_TRUTH_VALUE) throw RuntimeException(TRACE_INFO, "Don't know how to merge %s into a SimpleTruthValue using the default style", typeid(*other).name()); auto count2 = other->getCount(); auto count_new = count+ count2 - std::min(count,count2)*CVAL; auto mean_new = (mean*count + other->getMean()*count2)/(count+count2); return std::make_shared<SimpleTruthValue>(mean_new,count_new); } default: throw RuntimeException(TRACE_INFO, "Unknown or not yet implemented merge strategy"); } } std::string SimpleTruthValue::toString() const { char buf[1024]; sprintf(buf, "(stv %f %f)", static_cast<float>(getMean()), static_cast<float>(getConfidence())); return buf; } bool SimpleTruthValue::operator==(const TruthValue& rhs) const { const SimpleTruthValue *stv = dynamic_cast<const SimpleTruthValue *>(&rhs); if (NULL == stv) return false; #define FLOAT_ACCEPTABLE_MEAN_ERROR 0.000001 if (FLOAT_ACCEPTABLE_MEAN_ERROR < fabs(mean - stv->mean)) return false; // Converting from confidence to count and back again using single-precision // float is a real accuracy killer. In particular, 2/802 = 0.002494 but // converting back gives 800*0.002494/(1.0-0.002494) = 2.000188 and so // comparison tests can only be accurate to about 0.000188 or // thereabouts. #define FLOAT_ACCEPTABLE_COUNT_ERROR 0.0002 if (FLOAT_ACCEPTABLE_COUNT_ERROR < fabs(1.0 - (stv->count/count))) return false; return true; } TruthValueType SimpleTruthValue::getType() const { return SIMPLE_TRUTH_VALUE; } count_t SimpleTruthValue::confidenceToCount(confidence_t cf) { // There are not quite 16 digits in double precision // not quite 7 in single-precision float cf = std::min(cf, 0.9999998f); return static_cast<count_t>(KKK * cf / (1.0f - cf)); } confidence_t SimpleTruthValue::countToConfidence(count_t cn) { return static_cast<confidence_t>(cn / (cn + KKK)); } <|endoftext|>
<commit_before>/** Copyright 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Roland Olbricht et al. * * This file is part of Overpass_API. * * Overpass_API 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. * * Overpass_API is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Overpass_API. If not, see <http://www.gnu.org/licenses/>. */ #include "lz4_wrapper.h" #include <cstring> #include <iomanip> #include <iostream> #include <sstream> #include <stdexcept> namespace { template < typename T > std::string to_string(T t) { std::ostringstream out; out<<std::setprecision(14)<<t; return out.str(); } } LZ4_Deflate::Error::Error(int error_code_) : std::runtime_error("LZ4_Deflate: " + to_string(error_code_)), error_code(error_code_) {} LZ4_Deflate::LZ4_Deflate() { } LZ4_Deflate::~LZ4_Deflate() { } int LZ4_Deflate::compress(const void* in, int in_size, void* out, int out_buffer_size) { #ifdef HAVE_LZ4 int ret = LZ4_compress_limitedOutput((const char*) in, (char *) out + 4, in_size, out_buffer_size - 4); if (ret == 0 || ret > in_size) { // compression failed, or result size increased during compression if (in_size > out_buffer_size - 4) throw std::runtime_error("LZ4: output buffer too small during compression"); *(int*)out = in_size * -1; std::memcpy ((char *) out + 4, (const char*)in, in_size); ret = in_size; } else *(int*)out = ret; return ret + 4; #else throw std::runtime_error("Overpass API was compiled without lz4 compression library support"); #endif } LZ4_Inflate::Error::Error(int error_code_) : std::runtime_error("LZ4_Inflate: " + to_string(error_code_)), error_code(error_code_) {} LZ4_Inflate::LZ4_Inflate() { } LZ4_Inflate::~LZ4_Inflate() { } int LZ4_Inflate::decompress(const void* in, int in_size, void* out, int out_buffer_size) { #ifdef HAVE_LZ4 int ret; int in_buffer_size = *(int*)in; if (in_buffer_size > 0) { ret = LZ4_decompress_safe((const char*) in + 4, (char*) out, in_buffer_size, out_buffer_size); if (ret < 0) throw std::runtime_error("LZ4_decompress_safe failed"); } else { in_buffer_size *= -1; if (in_buffer_size > out_buffer_size) throw std::runtime_error ("LZ4: output buffer too small during decompression"); std::memcpy ((char*) out, (const char*) in + 4, in_buffer_size); ret = in_buffer_size; } return ret; #else throw std::runtime_error("Overpass API was compiled without lz4 compression library support"); #endif } <commit_msg>Use LZ4_compress_default to avoid deprecation warning<commit_after>/** Copyright 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Roland Olbricht et al. * * This file is part of Overpass_API. * * Overpass_API 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. * * Overpass_API is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Overpass_API. If not, see <http://www.gnu.org/licenses/>. */ #include "lz4_wrapper.h" #include <cstring> #include <iomanip> #include <iostream> #include <sstream> #include <stdexcept> namespace { template < typename T > std::string to_string(T t) { std::ostringstream out; out<<std::setprecision(14)<<t; return out.str(); } } LZ4_Deflate::Error::Error(int error_code_) : std::runtime_error("LZ4_Deflate: " + to_string(error_code_)), error_code(error_code_) {} LZ4_Deflate::LZ4_Deflate() { } LZ4_Deflate::~LZ4_Deflate() { } int LZ4_Deflate::compress(const void* in, int in_size, void* out, int out_buffer_size) { #ifdef HAVE_LZ4 int ret = LZ4_compress_default((const char*) in, (char *) out + 4, in_size, out_buffer_size - 4); if (ret == 0 || ret > in_size) { // compression failed, or result size increased during compression if (in_size > out_buffer_size - 4) throw std::runtime_error("LZ4: output buffer too small during compression"); *(int*)out = in_size * -1; std::memcpy ((char *) out + 4, (const char*)in, in_size); ret = in_size; } else *(int*)out = ret; return ret + 4; #else throw std::runtime_error("Overpass API was compiled without lz4 compression library support"); #endif } LZ4_Inflate::Error::Error(int error_code_) : std::runtime_error("LZ4_Inflate: " + to_string(error_code_)), error_code(error_code_) {} LZ4_Inflate::LZ4_Inflate() { } LZ4_Inflate::~LZ4_Inflate() { } int LZ4_Inflate::decompress(const void* in, int in_size, void* out, int out_buffer_size) { #ifdef HAVE_LZ4 int ret; int in_buffer_size = *(int*)in; if (in_buffer_size > 0) { ret = LZ4_decompress_safe((const char*) in + 4, (char*) out, in_buffer_size, out_buffer_size); if (ret < 0) throw std::runtime_error("LZ4_decompress_safe failed"); } else { in_buffer_size *= -1; if (in_buffer_size > out_buffer_size) throw std::runtime_error ("LZ4: output buffer too small during decompression"); std::memcpy ((char*) out, (const char*) in + 4, in_buffer_size); ret = in_buffer_size; } return ret; #else throw std::runtime_error("Overpass API was compiled without lz4 compression library support"); #endif } <|endoftext|>
<commit_before><commit_msg>EXTRA THREEDEEE<commit_after><|endoftext|>
<commit_before><commit_msg>jibby<commit_after><|endoftext|>
<commit_before>/* * Copyright (C) 2006, 2007, 2008 Apple 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: * 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h" #include "ScrollView.h" #include "Scrollbar.h" using std::max; namespace WebCore { void ScrollView::init() { m_canBlitOnScroll = true; if (platformWidget()) platformSetCanBlitOnScroll(); } void ScrollView::addChild(Widget* child) { ASSERT(child != this && !child->parent()); child->setParent(this); m_children.add(child); if (!child->platformWidget()) { child->setContainingWindow(containingWindow()); return; } platformAddChild(child); } void ScrollView::removeChild(Widget* child) { ASSERT(child->parent() == this); child->setParent(0); m_children.remove(child); if (child->platformWidget()) platformRemoveChild(child); } void ScrollView::setCanBlitOnScroll(bool b) { if (m_canBlitOnScroll == b) return; m_canBlitOnScroll = b; if (platformWidget()) platformSetCanBlitOnScroll(); } IntRect ScrollView::visibleContentRect(bool includeScrollbars) const { if (platformWidget()) return platformVisibleContentRect(includeScrollbars); return IntRect(IntPoint(m_scrollOffset.width(), m_scrollOffset.height()), IntSize(max(0, width() - (verticalScrollbar() && !includeScrollbars ? verticalScrollbar()->width() : 0)), max(0, height() - (horizontalScrollbar() && !includeScrollbars ? horizontalScrollbar()->height() : 0)))); } IntSize ScrollView::contentsSize() const { if (platformWidget()) return platformContentsSize(); return m_contentsSize; } void ScrollView::setContentsSize(const IntSize& newSize) { if (contentsSize() == newSize) return; m_contentsSize = newSize; if (platformWidget()) platformSetContentsSize(); else updateScrollbars(scrollOffset()); } IntPoint ScrollView::maximumScrollPosition() const { IntSize maximumOffset = contentsSize() - visibleContentRect().size(); maximumOffset.clampNegativeToZero(); return IntPoint(maximumOffset.width(), maximumOffset.height()); } void ScrollView::scrollRectIntoViewRecursively(const IntRect& r) { IntPoint p(max(0, r.x()), max(0, r.y())); ScrollView* view = this; while (view) { view->setScrollPosition(p); p.move(view->x() - view->scrollOffset().width(), view->y() - view->scrollOffset().height()); view = view->parent(); } } #if !PLATFORM(MAC) void ScrollView::platformSetCanBlitOnScroll() { } #endif #if !PLATFORM(MAC) && !PLATFORM(WX) IntRect ScrollView::platformVisibleContentRect(bool) const { return IntRect(); } IntSize ScrollView::platformContentsSize() const { return IntSize(); } #endif } <commit_msg>Fix Win, Gtk, Qt bustage.<commit_after>/* * Copyright (C) 2006, 2007, 2008 Apple 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: * 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h" #include "ScrollView.h" #include "Scrollbar.h" using std::max; namespace WebCore { void ScrollView::init() { m_canBlitOnScroll = true; if (platformWidget()) platformSetCanBlitOnScroll(); } void ScrollView::addChild(Widget* child) { ASSERT(child != this && !child->parent()); child->setParent(this); m_children.add(child); if (!child->platformWidget()) { child->setContainingWindow(containingWindow()); return; } platformAddChild(child); } void ScrollView::removeChild(Widget* child) { ASSERT(child->parent() == this); child->setParent(0); m_children.remove(child); if (child->platformWidget()) platformRemoveChild(child); } void ScrollView::setCanBlitOnScroll(bool b) { if (m_canBlitOnScroll == b) return; m_canBlitOnScroll = b; if (platformWidget()) platformSetCanBlitOnScroll(); } IntRect ScrollView::visibleContentRect(bool includeScrollbars) const { if (platformWidget()) return platformVisibleContentRect(includeScrollbars); return IntRect(IntPoint(m_scrollOffset.width(), m_scrollOffset.height()), IntSize(max(0, width() - (verticalScrollbar() && !includeScrollbars ? verticalScrollbar()->width() : 0)), max(0, height() - (horizontalScrollbar() && !includeScrollbars ? horizontalScrollbar()->height() : 0)))); } IntSize ScrollView::contentsSize() const { if (platformWidget()) return platformContentsSize(); return m_contentsSize; } void ScrollView::setContentsSize(const IntSize& newSize) { if (contentsSize() == newSize) return; m_contentsSize = newSize; if (platformWidget()) platformSetContentsSize(); else updateScrollbars(scrollOffset()); } IntPoint ScrollView::maximumScrollPosition() const { IntSize maximumOffset = contentsSize() - visibleContentRect().size(); maximumOffset.clampNegativeToZero(); return IntPoint(maximumOffset.width(), maximumOffset.height()); } void ScrollView::scrollRectIntoViewRecursively(const IntRect& r) { IntPoint p(max(0, r.x()), max(0, r.y())); ScrollView* view = this; while (view) { view->setScrollPosition(p); p.move(view->x() - view->scrollOffset().width(), view->y() - view->scrollOffset().height()); view = view->parent(); } } #if !PLATFORM(MAC) void ScrollView::platformSetCanBlitOnScroll() { } #endif #if !PLATFORM(MAC) && !PLATFORM(WX) IntRect ScrollView::platformVisibleContentRect(bool) const { return IntRect(); } IntSize ScrollView::platformContentsSize() const { return IntSize(); } void ScrollView::platformSetContentsSize() { } #endif } <|endoftext|>
<commit_before>// Filename: audio_linux_traits.C // Created by: cary (02Oct00) // //////////////////////////////////////////////////////////////////// #include "audio_linux_traits.h" #ifdef AUDIO_USE_LINUX #include "audio_manager.h" #include "config_audio.h" #include <ipc_thread.h> #include <ipc_mutex.h> #include <set> #include <fcntl.h> #include <sys/soundcard.h> #include <sys/ioctl.h> typedef set<Buffer*> BufferSet; static bool have_initialized = false; static mutex buffer_mutex; static byte* buffer1; static byte* buffer2; static byte* current_buffer; static byte* back_buffer; byte* zero_buffer; static byte* scratch_buffer; static byte* fetch_buffer; static int want_buffers = 0, have_buffers = 0; static bool initializing = true; static bool stop_mixing = false; static int output_fd; static thread* update_thread; static int sample_size = sizeof(short); BufferSet buffers; static void swap_buffers(void) { byte *tmp = current_buffer; current_buffer = back_buffer; back_buffer = tmp; } INLINE static signed short read_buffer(byte* buf, int idx) { signed short ret = 0; switch (sample_size) { case 1: ret = *((signed char *)(&buf[idx])); break; case 2: ret = *((signed short *)(&buf[idx*2])); break; default: audio_cat->debug() << "unknown sample size (" << sample_size << ")" << endl; break; } return ret; } INLINE static void write_buffer(byte* buf, int idx, signed short val) { switch (sample_size) { case 1: *((signed char *)(&buf[idx])) = val & 0xff; break; case 2: *((signed short *)(&buf[idx*2])) = val; break; default: audio_cat->debug() << "unknown sample size (" << sample_size << ")" << endl; break; } } INLINE static signed short sound_clamp(signed int value) { signed short ret = 0; switch (sample_size) { case 1: ret = (value > 127)?127:((value < -128)?(-128):(value)); break; case 2: ret = (value > 32767)?32767:((value < -32768)?(-32768):(value)); break; default: audio_cat->debug() << "unknown sample size (" << sample_size << ")" << endl; break; } return ret; } static void mix_in(byte* buf, byte* from, float vol, float pan) { int done = audio_buffer_size / sample_size; for (int i=0; i<done; i+=2) { signed short left = read_buffer(buf, i); signed short right = read_buffer(buf, i+1); // now get the incoming data signed short in_left = read_buffer(from, i); signed short in_right = read_buffer(from, i+1); // figure out panning at some point in_left = (short int)(in_left * vol); in_right = (short int)(in_right * vol); // compute mixed values left = sound_clamp(left+in_left); right = sound_clamp(right+in_right); // write it back to the buffer write_buffer(buf, i, left); write_buffer(buf, i+1, right); } } static void mix_buffer(byte* buf) { memcpy(scratch_buffer, zero_buffer, audio_buffer_size); // do stuff for (BufferSet::iterator i=buffers.begin(); i!=buffers.end(); ++i) mix_in(scratch_buffer, (*i)->get_buffer(fetch_buffer), 1., 0.); BufferSet to_del; for (BufferSet::iterator j=buffers.begin(); j!=buffers.end(); ++j) if ((*j)->is_done()) to_del.insert(*j); { mutex_lock m(buffer_mutex); memcpy(buf, scratch_buffer, audio_buffer_size); --want_buffers; ++have_buffers; for (BufferSet::iterator k=to_del.begin(); k!=to_del.end(); ++k) { buffers.erase(*k); (*k)->reset(); } } } static void update_linux(void) { if (buffers.empty()) return; switch (want_buffers) { case 0: // all buffers are full right now. This is a good state. break; case 1: // mix a buffer and put it in place. mix_buffer(back_buffer); break; case 2: if (!initializing) audio_cat->warning() << "audio buffers are being starved" << endl; mix_buffer(current_buffer); mix_buffer(back_buffer); initializing = false; break; default: audio_cat->error() << "audio system wants more then 2 buffers!" << endl; } } static void* internal_update(void*) { if ((output_fd = open(audio_device->c_str(), O_WRONLY, 0)) == -1) { audio_cat->error() << "could not open '" << audio_device << "'" << endl; return (void*)0L; } // this one I don't know about int fragsize = 0x0004000c; if (ioctl(output_fd, SNDCTL_DSP_SETFRAGMENT, &fragsize) == -1) { audio_cat->error() << "faied to set fragment size" << endl; return (void*)0L; } // for now signed, 16-bit, little endian int format = AFMT_S16_LE; if (ioctl(output_fd, SNDCTL_DSP_SETFMT, &format) == -1) { audio_cat->error() << "failed to set format on the dsp" << endl; return (void*)0L; } // set stereo int stereo = 1; if (ioctl(output_fd, SNDCTL_DSP_STEREO, &stereo) == -1) { audio_cat->error() << "failed to set stereo on the dsp" << endl; return (void*)0L; } // set the frequency if (ioctl(output_fd, SNDCTL_DSP_SPEED, &audio_mix_freq) == -1) { audio_cat->error() << "failed to set frequency on the dsp" << endl; return (void*)0L; } while (!stop_mixing) { if (have_buffers == 0) { ipc_traits::sleep(0, audio_auto_update_delay); } else { write(output_fd, current_buffer, audio_buffer_size); { mutex_lock m(buffer_mutex); swap_buffers(); --have_buffers; ++want_buffers; } } } delete [] buffer1; delete [] buffer2; delete [] scratch_buffer; delete [] fetch_buffer; delete [] zero_buffer; stop_mixing = false; audio_cat->debug() << "exiting internal thread" << endl; return (void*)0L; } static void shutdown_linux(void) { stop_mixing = true; while (stop_mixing); audio_cat->debug() << "I believe the internal thread has exited" << endl; } static void initialize(void) { if (have_initialized) return; buffer1 = new byte[audio_buffer_size]; buffer2 = new byte[audio_buffer_size]; scratch_buffer = new byte[audio_buffer_size]; fetch_buffer = new byte[audio_buffer_size]; zero_buffer = new byte[audio_buffer_size]; for (int i=0; i<audio_buffer_size; ++i) zero_buffer[i] = 0; current_buffer = buffer1; back_buffer = buffer2; want_buffers = 2; have_buffers = 0; initializing = true; stop_mixing = false; audio_cat->info() << "spawning internal update thread" << endl; update_thread = thread::create(internal_update, (void*)0L, thread::PRIORITY_NORMAL); AudioManager::set_update_func(update_linux); AudioManager::set_shutdown_func(shutdown_linux); have_initialized = true; } LinuxSample::~LinuxSample(void) { } float LinuxSample::length(void) { return (_data->get_size()) / (audio_mix_freq * sample_size); } AudioTraits::SampleClass::SampleStatus LinuxSample::status(void) { BufferSet::iterator i = buffers.find(_data); if (i != buffers.end()) return AudioTraits::SampleClass::PLAYING; return AudioTraits::SampleClass::READY; } LinuxPlaying* LinuxSample::get_state(void) { return new LinuxPlaying(); } void LinuxSample::destroy(AudioTraits::SampleClass* sample) { delete sample; } LinuxSample* LinuxSample::load_raw(byte* data, unsigned long size) { LinuxSample* ret = new LinuxSample(new Buffer(data, size)); return ret; } LinuxMusic::~LinuxMusic(void) { } AudioTraits::MusicClass::MusicStatus LinuxMusic::status(void) { return AudioTraits::MusicClass::READY; } LinuxPlaying* LinuxMusic::get_state(void) { return new LinuxPlaying(); } void LinuxMusic::destroy(AudioTraits::MusicClass* music) { delete music; } LinuxPlaying::~LinuxPlaying(void) { } AudioTraits::PlayingClass::PlayingStatus LinuxPlaying::status(void) { return AudioTraits::PlayingClass::BAD; } LinuxPlayer* LinuxPlayer::_global_instance = (LinuxPlayer*)0L; LinuxPlayer::~LinuxPlayer(void) { } void LinuxPlayer::play_sample(AudioTraits::SampleClass* sample) { initialize(); LinuxSample* lsample = (LinuxSample*)sample; buffers.insert(lsample->get_data()); } void LinuxPlayer::play_music(AudioTraits::MusicClass*) { } void LinuxPlayer::set_volume(AudioTraits::SampleClass*, int) { } void LinuxPlayer::set_volume(AudioTraits::MusicClass*, int) { } LinuxPlayer* LinuxPlayer::get_instance(void) { if (_global_instance == (LinuxPlayer*)0L) _global_instance = new LinuxPlayer(); return _global_instance; } #endif /* AUDIO_USE_LINUX */ <commit_msg>make the starving warning a debug message<commit_after>// Filename: audio_linux_traits.C // Created by: cary (02Oct00) // //////////////////////////////////////////////////////////////////// #include "audio_linux_traits.h" #ifdef AUDIO_USE_LINUX #include "audio_manager.h" #include "config_audio.h" #include <ipc_thread.h> #include <ipc_mutex.h> #include <set> #include <fcntl.h> #include <sys/soundcard.h> #include <sys/ioctl.h> typedef set<Buffer*> BufferSet; static bool have_initialized = false; static mutex buffer_mutex; static byte* buffer1; static byte* buffer2; static byte* current_buffer; static byte* back_buffer; byte* zero_buffer; static byte* scratch_buffer; static byte* fetch_buffer; static int want_buffers = 0, have_buffers = 0; static bool initializing = true; static bool stop_mixing = false; static int output_fd; static thread* update_thread; static int sample_size = sizeof(short); BufferSet buffers; static void swap_buffers(void) { byte *tmp = current_buffer; current_buffer = back_buffer; back_buffer = tmp; } INLINE static signed short read_buffer(byte* buf, int idx) { signed short ret = 0; switch (sample_size) { case 1: ret = *((signed char *)(&buf[idx])); break; case 2: ret = *((signed short *)(&buf[idx*2])); break; default: audio_cat->debug() << "unknown sample size (" << sample_size << ")" << endl; break; } return ret; } INLINE static void write_buffer(byte* buf, int idx, signed short val) { switch (sample_size) { case 1: *((signed char *)(&buf[idx])) = val & 0xff; break; case 2: *((signed short *)(&buf[idx*2])) = val; break; default: audio_cat->debug() << "unknown sample size (" << sample_size << ")" << endl; break; } } INLINE static signed short sound_clamp(signed int value) { signed short ret = 0; switch (sample_size) { case 1: ret = (value > 127)?127:((value < -128)?(-128):(value)); break; case 2: ret = (value > 32767)?32767:((value < -32768)?(-32768):(value)); break; default: audio_cat->debug() << "unknown sample size (" << sample_size << ")" << endl; break; } return ret; } static void mix_in(byte* buf, byte* from, float vol, float pan) { int done = audio_buffer_size / sample_size; for (int i=0; i<done; i+=2) { signed short left = read_buffer(buf, i); signed short right = read_buffer(buf, i+1); // now get the incoming data signed short in_left = read_buffer(from, i); signed short in_right = read_buffer(from, i+1); // figure out panning at some point in_left = (short int)(in_left * vol); in_right = (short int)(in_right * vol); // compute mixed values left = sound_clamp(left+in_left); right = sound_clamp(right+in_right); // write it back to the buffer write_buffer(buf, i, left); write_buffer(buf, i+1, right); } } static void mix_buffer(byte* buf) { memcpy(scratch_buffer, zero_buffer, audio_buffer_size); // do stuff for (BufferSet::iterator i=buffers.begin(); i!=buffers.end(); ++i) mix_in(scratch_buffer, (*i)->get_buffer(fetch_buffer), 1., 0.); BufferSet to_del; for (BufferSet::iterator j=buffers.begin(); j!=buffers.end(); ++j) if ((*j)->is_done()) to_del.insert(*j); { mutex_lock m(buffer_mutex); memcpy(buf, scratch_buffer, audio_buffer_size); --want_buffers; ++have_buffers; for (BufferSet::iterator k=to_del.begin(); k!=to_del.end(); ++k) { buffers.erase(*k); (*k)->reset(); } } } static void update_linux(void) { if (buffers.empty()) return; switch (want_buffers) { case 0: // all buffers are full right now. This is a good state. break; case 1: // mix a buffer and put it in place. mix_buffer(back_buffer); break; case 2: if (!initializing) audio_cat->debug() << "audio buffers are being starved" << endl; mix_buffer(current_buffer); mix_buffer(back_buffer); initializing = false; break; default: audio_cat->error() << "audio system wants more then 2 buffers!" << endl; } } static void* internal_update(void*) { if ((output_fd = open(audio_device->c_str(), O_WRONLY, 0)) == -1) { audio_cat->error() << "could not open '" << audio_device << "'" << endl; return (void*)0L; } // this one I don't know about int fragsize = 0x0004000c; if (ioctl(output_fd, SNDCTL_DSP_SETFRAGMENT, &fragsize) == -1) { audio_cat->error() << "faied to set fragment size" << endl; return (void*)0L; } // for now signed, 16-bit, little endian int format = AFMT_S16_LE; if (ioctl(output_fd, SNDCTL_DSP_SETFMT, &format) == -1) { audio_cat->error() << "failed to set format on the dsp" << endl; return (void*)0L; } // set stereo int stereo = 1; if (ioctl(output_fd, SNDCTL_DSP_STEREO, &stereo) == -1) { audio_cat->error() << "failed to set stereo on the dsp" << endl; return (void*)0L; } // set the frequency if (ioctl(output_fd, SNDCTL_DSP_SPEED, &audio_mix_freq) == -1) { audio_cat->error() << "failed to set frequency on the dsp" << endl; return (void*)0L; } while (!stop_mixing) { if (have_buffers == 0) { ipc_traits::sleep(0, audio_auto_update_delay); } else { write(output_fd, current_buffer, audio_buffer_size); { mutex_lock m(buffer_mutex); swap_buffers(); --have_buffers; ++want_buffers; } } } delete [] buffer1; delete [] buffer2; delete [] scratch_buffer; delete [] fetch_buffer; delete [] zero_buffer; stop_mixing = false; audio_cat->debug() << "exiting internal thread" << endl; return (void*)0L; } static void shutdown_linux(void) { stop_mixing = true; while (stop_mixing); audio_cat->debug() << "I believe the internal thread has exited" << endl; } static void initialize(void) { if (have_initialized) return; buffer1 = new byte[audio_buffer_size]; buffer2 = new byte[audio_buffer_size]; scratch_buffer = new byte[audio_buffer_size]; fetch_buffer = new byte[audio_buffer_size]; zero_buffer = new byte[audio_buffer_size]; for (int i=0; i<audio_buffer_size; ++i) zero_buffer[i] = 0; current_buffer = buffer1; back_buffer = buffer2; want_buffers = 2; have_buffers = 0; initializing = true; stop_mixing = false; audio_cat->info() << "spawning internal update thread" << endl; update_thread = thread::create(internal_update, (void*)0L, thread::PRIORITY_NORMAL); AudioManager::set_update_func(update_linux); AudioManager::set_shutdown_func(shutdown_linux); have_initialized = true; } LinuxSample::~LinuxSample(void) { } float LinuxSample::length(void) { return (_data->get_size()) / (audio_mix_freq * sample_size); } AudioTraits::SampleClass::SampleStatus LinuxSample::status(void) { BufferSet::iterator i = buffers.find(_data); if (i != buffers.end()) return AudioTraits::SampleClass::PLAYING; return AudioTraits::SampleClass::READY; } LinuxPlaying* LinuxSample::get_state(void) { return new LinuxPlaying(); } void LinuxSample::destroy(AudioTraits::SampleClass* sample) { delete sample; } LinuxSample* LinuxSample::load_raw(byte* data, unsigned long size) { LinuxSample* ret = new LinuxSample(new Buffer(data, size)); return ret; } LinuxMusic::~LinuxMusic(void) { } AudioTraits::MusicClass::MusicStatus LinuxMusic::status(void) { return AudioTraits::MusicClass::READY; } LinuxPlaying* LinuxMusic::get_state(void) { return new LinuxPlaying(); } void LinuxMusic::destroy(AudioTraits::MusicClass* music) { delete music; } LinuxPlaying::~LinuxPlaying(void) { } AudioTraits::PlayingClass::PlayingStatus LinuxPlaying::status(void) { return AudioTraits::PlayingClass::BAD; } LinuxPlayer* LinuxPlayer::_global_instance = (LinuxPlayer*)0L; LinuxPlayer::~LinuxPlayer(void) { } void LinuxPlayer::play_sample(AudioTraits::SampleClass* sample) { initialize(); LinuxSample* lsample = (LinuxSample*)sample; buffers.insert(lsample->get_data()); } void LinuxPlayer::play_music(AudioTraits::MusicClass*) { } void LinuxPlayer::set_volume(AudioTraits::SampleClass*, int) { } void LinuxPlayer::set_volume(AudioTraits::MusicClass*, int) { } LinuxPlayer* LinuxPlayer::get_instance(void) { if (_global_instance == (LinuxPlayer*)0L) _global_instance = new LinuxPlayer(); return _global_instance; } #endif /* AUDIO_USE_LINUX */ <|endoftext|>
<commit_before>// Filename: ffmpegVirtualFile.cxx // Created by: jyelon (02Jul07) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) Carnegie Mellon University. All rights reserved. // // All use of this software is subject to the terms of the revised BSD // license. You should have received a copy of this license along // with this source code in a file named "LICENSE." // //////////////////////////////////////////////////////////////////// #ifdef HAVE_FFMPEG #include "pandabase.h" #include "config_movies.h" #include "ffmpegVirtualFile.h" #include "virtualFileSystem.h" extern "C" { #include "libavformat/avio.h" } #ifndef AVSEEK_SIZE #define AVSEEK_SIZE 0x10000 #endif //////////////////////////////////////////////////////////////////// // These functions need to use C calling conventions. //////////////////////////////////////////////////////////////////// extern "C" { static int pandavfs_open(URLContext *h, const char *filename, int flags); static int pandavfs_read(URLContext *h, unsigned char *buf, int size); // This change happened a few days before 52.68.0 #if LIBAVFORMAT_VERSION_INT < 3425280 static int pandavfs_write(URLContext *h, unsigned char *buf, int size); #else static int pandavfs_write(URLContext *h, const unsigned char *buf, int size); #endif static int64_t pandavfs_seek(URLContext *h, int64_t pos, int whence); static int pandavfs_close(URLContext *h); } //////////////////////////////////////////////////////////////////// // Function: pandavfs_open // Access: Static Function // Description: A hook to open a panda VFS file. //////////////////////////////////////////////////////////////////// static int pandavfs_open(URLContext *h, const char *filename, int flags) { if (flags != 0) { movies_cat.error() << "ffmpeg is trying to write to the VFS.\n"; return -1; } filename += 9; // Skip over "pandavfs:" VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); istream *s = vfs->open_read_file(filename, true); if (s == 0) { return -1; } // Test whether seek works. s->seekg(1, ios::beg); int tel1 = s->tellg(); s->seekg(0, ios::beg); int tel2 = s->tellg(); if (s->fail() || (tel1!=1) || (tel2!=0)) { movies_cat.error() << "cannot play movie (not seekable): " << h->filename << "\n"; delete s; return -1; } h->priv_data = s; return 0; } //////////////////////////////////////////////////////////////////// // Function: pandavfs_read // Access: Static Function // Description: A hook to read a panda VFS file. //////////////////////////////////////////////////////////////////// static int pandavfs_read(URLContext *h, unsigned char *buf, int size) { istream *s = (istream*)(h->priv_data); s->read((char*)buf, size); int gc = s->gcount(); s->clear(); return gc; } //////////////////////////////////////////////////////////////////// // Function: pandavfs_write // Access: Static Function // Description: A hook to write a panda VFS file. //////////////////////////////////////////////////////////////////// static int #if LIBAVFORMAT_VERSION_INT < 3425280 pandavfs_write(URLContext *h, unsigned char *buf, int size) { #else pandavfs_write(URLContext *h, const unsigned char *buf, int size) { #endif movies_cat.error() << "ffmpeg is trying to write to the VFS.\n"; return -1; } //////////////////////////////////////////////////////////////////// // Function: pandavfs_seek // Access: Static Function // Description: A hook to seek a panda VFS file. //////////////////////////////////////////////////////////////////// static int64_t pandavfs_seek(URLContext *h, int64_t pos, int whence) { istream *s = (istream*)(h->priv_data); switch(whence) { case SEEK_SET: s->seekg(pos, ios::beg); break; case SEEK_CUR: s->seekg(pos, ios::cur); break; case SEEK_END: s->seekg(pos, ios::end); break; case AVSEEK_SIZE: { s->seekg(0, ios::cur); int p = s->tellg(); s->seekg(-1, ios::end); int size = s->tellg(); if (size < 0) { movies_cat.error() << "Failed to determine filesize in ffmpegVirtualFile\n"; s->clear(); return -1; } size++; s->seekg(p, ios::beg); s->clear(); return size; } default: movies_cat.error() << "Illegal parameter to seek in ffmpegVirtualFile\n"; s->clear(); return -1; } s->clear(); int tl = s->tellg(); return tl; } //////////////////////////////////////////////////////////////////// // Function: pandavfs_close // Access: Static Function // Description: A hook to close a panda VFS file. //////////////////////////////////////////////////////////////////// static int pandavfs_close(URLContext *h) { istream *s = (istream*)(h->priv_data); delete s; h->priv_data = 0; return 0; } //////////////////////////////////////////////////////////////////// // Function: FfmpegVirtualFile::register_protocol // Access: Public, Static // Description: Enables ffmpeg to access panda's VFS. // // After calling this method, ffmpeg will be // able to open "URLs" that look like this: // // pandavfs:/c/mygame/foo.avi // //////////////////////////////////////////////////////////////////// void FfmpegVirtualFile:: register_protocol() { static bool initialized = false; if (initialized) { return; } static URLProtocol protocol; protocol.name = "pandavfs"; protocol.url_open = pandavfs_open; protocol.url_read = pandavfs_read; protocol.url_write = pandavfs_write; protocol.url_seek = pandavfs_seek; protocol.url_close = pandavfs_close; #if LIBAVFORMAT_VERSION_INT < 3415296 ::register_protocol(&protocol); #else av_register_protocol(&protocol); #endif } #endif // HAVE_FFMPEG <commit_msg>include stdint.h<commit_after>// Filename: ffmpegVirtualFile.cxx // Created by: jyelon (02Jul07) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) Carnegie Mellon University. All rights reserved. // // All use of this software is subject to the terms of the revised BSD // license. You should have received a copy of this license along // with this source code in a file named "LICENSE." // //////////////////////////////////////////////////////////////////// #ifdef HAVE_FFMPEG #include "pandabase.h" #include "config_movies.h" #include "ffmpegVirtualFile.h" #include "virtualFileSystem.h" extern "C" { #include "libavformat/avio.h" } #include <stdint.h> #ifndef AVSEEK_SIZE #define AVSEEK_SIZE 0x10000 #endif //////////////////////////////////////////////////////////////////// // These functions need to use C calling conventions. //////////////////////////////////////////////////////////////////// extern "C" { static int pandavfs_open(URLContext *h, const char *filename, int flags); static int pandavfs_read(URLContext *h, unsigned char *buf, int size); // This change happened a few days before 52.68.0 #if LIBAVFORMAT_VERSION_INT < 3425280 static int pandavfs_write(URLContext *h, unsigned char *buf, int size); #else static int pandavfs_write(URLContext *h, const unsigned char *buf, int size); #endif static int64_t pandavfs_seek(URLContext *h, int64_t pos, int whence); static int pandavfs_close(URLContext *h); } //////////////////////////////////////////////////////////////////// // Function: pandavfs_open // Access: Static Function // Description: A hook to open a panda VFS file. //////////////////////////////////////////////////////////////////// static int pandavfs_open(URLContext *h, const char *filename, int flags) { if (flags != 0) { movies_cat.error() << "ffmpeg is trying to write to the VFS.\n"; return -1; } filename += 9; // Skip over "pandavfs:" VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); istream *s = vfs->open_read_file(filename, true); if (s == 0) { return -1; } // Test whether seek works. s->seekg(1, ios::beg); int tel1 = s->tellg(); s->seekg(0, ios::beg); int tel2 = s->tellg(); if (s->fail() || (tel1!=1) || (tel2!=0)) { movies_cat.error() << "cannot play movie (not seekable): " << h->filename << "\n"; delete s; return -1; } h->priv_data = s; return 0; } //////////////////////////////////////////////////////////////////// // Function: pandavfs_read // Access: Static Function // Description: A hook to read a panda VFS file. //////////////////////////////////////////////////////////////////// static int pandavfs_read(URLContext *h, unsigned char *buf, int size) { istream *s = (istream*)(h->priv_data); s->read((char*)buf, size); int gc = s->gcount(); s->clear(); return gc; } //////////////////////////////////////////////////////////////////// // Function: pandavfs_write // Access: Static Function // Description: A hook to write a panda VFS file. //////////////////////////////////////////////////////////////////// static int #if LIBAVFORMAT_VERSION_INT < 3425280 pandavfs_write(URLContext *h, unsigned char *buf, int size) { #else pandavfs_write(URLContext *h, const unsigned char *buf, int size) { #endif movies_cat.error() << "ffmpeg is trying to write to the VFS.\n"; return -1; } //////////////////////////////////////////////////////////////////// // Function: pandavfs_seek // Access: Static Function // Description: A hook to seek a panda VFS file. //////////////////////////////////////////////////////////////////// static int64_t pandavfs_seek(URLContext *h, int64_t pos, int whence) { istream *s = (istream*)(h->priv_data); switch(whence) { case SEEK_SET: s->seekg(pos, ios::beg); break; case SEEK_CUR: s->seekg(pos, ios::cur); break; case SEEK_END: s->seekg(pos, ios::end); break; case AVSEEK_SIZE: { s->seekg(0, ios::cur); int p = s->tellg(); s->seekg(-1, ios::end); int size = s->tellg(); if (size < 0) { movies_cat.error() << "Failed to determine filesize in ffmpegVirtualFile\n"; s->clear(); return -1; } size++; s->seekg(p, ios::beg); s->clear(); return size; } default: movies_cat.error() << "Illegal parameter to seek in ffmpegVirtualFile\n"; s->clear(); return -1; } s->clear(); int tl = s->tellg(); return tl; } //////////////////////////////////////////////////////////////////// // Function: pandavfs_close // Access: Static Function // Description: A hook to close a panda VFS file. //////////////////////////////////////////////////////////////////// static int pandavfs_close(URLContext *h) { istream *s = (istream*)(h->priv_data); delete s; h->priv_data = 0; return 0; } //////////////////////////////////////////////////////////////////// // Function: FfmpegVirtualFile::register_protocol // Access: Public, Static // Description: Enables ffmpeg to access panda's VFS. // // After calling this method, ffmpeg will be // able to open "URLs" that look like this: // // pandavfs:/c/mygame/foo.avi // //////////////////////////////////////////////////////////////////// void FfmpegVirtualFile:: register_protocol() { static bool initialized = false; if (initialized) { return; } static URLProtocol protocol; protocol.name = "pandavfs"; protocol.url_open = pandavfs_open; protocol.url_read = pandavfs_read; protocol.url_write = pandavfs_write; protocol.url_seek = pandavfs_seek; protocol.url_close = pandavfs_close; #if LIBAVFORMAT_VERSION_INT < 3415296 ::register_protocol(&protocol); #else av_register_protocol(&protocol); #endif } #endif // HAVE_FFMPEG <|endoftext|>
<commit_before>//@author A0094446X #include "stdafx.h" #include <QApplication> #include <QList> #include "you_main_gui.h" #include "system_tray_manager.h" YouMainGUI::SystemTrayManager::~SystemTrayManager() { } void YouMainGUI::SystemTrayManager::setup() { createActions(); setIcon(); makeContextMenu(); connectTrayActivatedSlot(); parentGUI->setVisible(true); } void YouMainGUI::SystemTrayManager::setIcon() { QIcon icon(":/Icon.png"); trayIcon.setIcon(icon); parentGUI->setWindowIcon(icon); trayIcon.show(); } void YouMainGUI::SystemTrayManager::makeContextMenu() { trayIconMenu = new QMenu(parentGUI); trayIconMenu->addAction(minimizeAction); trayIconMenu->addAction(maximizeAction); trayIconMenu->addAction(restoreAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(quitAction); trayIcon.setContextMenu(trayIconMenu); } void YouMainGUI::SystemTrayManager::connectTrayActivatedSlot() { connect(&trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason))); } void YouMainGUI::SystemTrayManager::iconActivated( QSystemTrayIcon::ActivationReason reason) { if (reason == QSystemTrayIcon::Trigger) { if (parentGUI->isVisible() == true) parentGUI->hide(); else parentGUI->show(); } } void YouMainGUI::SystemTrayManager::createActions() { minimizeAction = new QAction(tr("Minimize"), parentGUI); connect(minimizeAction, SIGNAL(triggered()), parentGUI, SLOT(hide())); maximizeAction = new QAction(tr("Maximize"), parentGUI); connect(maximizeAction, SIGNAL(triggered()), parentGUI, SLOT(showMaximized())); restoreAction = new QAction(tr("Restore"), parentGUI); connect(restoreAction, SIGNAL(triggered()), parentGUI, SLOT(showNormal())); quitAction = new QAction(tr("Quit"), parentGUI); connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); } <commit_msg>Logic fix for icon activation.<commit_after>//@author A0094446X #include "stdafx.h" #include <QApplication> #include <QList> #include "you_main_gui.h" #include "system_tray_manager.h" YouMainGUI::SystemTrayManager::~SystemTrayManager() { } void YouMainGUI::SystemTrayManager::setup() { createActions(); setIcon(); makeContextMenu(); connectTrayActivatedSlot(); parentGUI->setVisible(true); } void YouMainGUI::SystemTrayManager::setIcon() { QIcon icon(":/Icon.png"); trayIcon.setIcon(icon); parentGUI->setWindowIcon(icon); trayIcon.show(); } void YouMainGUI::SystemTrayManager::makeContextMenu() { trayIconMenu = new QMenu(parentGUI); trayIconMenu->addAction(minimizeAction); trayIconMenu->addAction(maximizeAction); trayIconMenu->addAction(restoreAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(quitAction); trayIcon.setContextMenu(trayIconMenu); } void YouMainGUI::SystemTrayManager::connectTrayActivatedSlot() { connect(&trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason))); } void YouMainGUI::SystemTrayManager::iconActivated( QSystemTrayIcon::ActivationReason reason) { if (reason == QSystemTrayIcon::Trigger) { bool visible = parentGUI->isVisible(); bool minimized = parentGUI->isMinimized(); assert( (visible == true && minimized == true) || (visible == true && minimized == false) || (visible == false)); Qt::WindowStates toggleState (parentGUI->windowState() & ~Qt::WindowMinimized); // Visible and minimized if (visible && minimized) { parentGUI->setWindowState(toggleState | Qt::WindowActive); } // Visible and not minimized else if (visible && !minimized) { parentGUI->setWindowState(toggleState | Qt::WindowActive); parentGUI->hide(); } else if (!visible) { // Not visible parentGUI->show(); parentGUI->setWindowState(toggleState | Qt::WindowActive); } } } void YouMainGUI::SystemTrayManager::createActions() { minimizeAction = new QAction(tr("Minimize"), parentGUI); connect(minimizeAction, SIGNAL(triggered()), parentGUI, SLOT(hide())); maximizeAction = new QAction(tr("Maximize"), parentGUI); connect(maximizeAction, SIGNAL(triggered()), parentGUI, SLOT(showMaximized())); restoreAction = new QAction(tr("Restore"), parentGUI); connect(restoreAction, SIGNAL(triggered()), parentGUI, SLOT(showNormal())); quitAction = new QAction(tr("Quit"), parentGUI); connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); } <|endoftext|>
<commit_before>#include "../gtest/include/gtest/gtest.h" #include <string.h> // use memset/memcmp #include "../codec/encoder/core/inc/memory_align.h" using namespace WelsSVCEnc; //Tests of WelsGetCacheLineSize Begin TEST(MemoryAlignTest, GetCacheLineSize_LoopWithin16K) { const unsigned int kuiTestBoundary16K = 16 * 1024; unsigned int uiTargetAlign = 1; while (uiTargetAlign < kuiTestBoundary16K) { CMemoryAlign cTestMa(uiTargetAlign); ASSERT_EQ( (uiTargetAlign & 0x0F)?16:uiTargetAlign, cTestMa.WelsGetCacheLineSize() ); ++ uiTargetAlign; } } TEST(MemoryAlignTest, GetCacheLineSize_Zero) { CMemoryAlign cTestMa(0); ASSERT_EQ( 16, cTestMa.WelsGetCacheLineSize() ); } TEST(MemoryAlignTest, GetCacheLineSize_MaxUINT) { CMemoryAlign cTestMa(0xFFFFFFFF); ASSERT_EQ( 16, cTestMa.WelsGetCacheLineSize() ); } //Tests of WelsGetCacheLineSize End //Tests of WelsMallocAndFree Begin TEST(MemoryAlignTest, WelsMallocAndFreeOnceFunctionVerify) { const uint32_t kuiTargetAlignSize[4] = {32, 16, 64, 8}; srand((uint32_t)time(NULL)); for (int i=0; i<4; i++) { const uint32_t kuiTestAlignSize = kuiTargetAlignSize[i]; const uint32_t kuiTestDataSize = abs(rand()); CMemoryAlign cTestMa(kuiTestAlignSize); const uint32_t uiSize = kuiTestDataSize; const char strUnitTestTag[100] = "pUnitTestData"; const uint32_t kuiUsedCacheLineSize = ((kuiTestAlignSize == 0) || (kuiTestAlignSize & 0x0F)) ? (16) : (kuiTestAlignSize); const uint32_t kuiExtraAlignSize = kuiUsedCacheLineSize-1; const uint32_t kuiExpectedSize = sizeof( void ** ) + sizeof( int32_t ) + kuiExtraAlignSize + uiSize; uint8_t *pUnitTestData = static_cast<uint8_t *>(cTestMa.WelsMalloc(uiSize, strUnitTestTag)); if ( pUnitTestData != NULL ) { ASSERT_TRUE( (((int64_t)(static_cast<void *>(pUnitTestData))) & kuiExtraAlignSize) == 0 ); EXPECT_EQ( kuiExpectedSize, cTestMa.WelsGetMemoryUsage() ); cTestMa.WelsFree( pUnitTestData, strUnitTestTag ); EXPECT_EQ( 0, cTestMa.WelsGetMemoryUsage() ); } else { EXPECT_EQ( NULL, pUnitTestData ); EXPECT_EQ( 0, cTestMa.WelsGetMemoryUsage() ); cTestMa.WelsFree( pUnitTestData, strUnitTestTag ); EXPECT_EQ( 0, cTestMa.WelsGetMemoryUsage() ); } } } <commit_msg>Include time.h in the MemoryAlloc test<commit_after>#include "../gtest/include/gtest/gtest.h" #include <string.h> // use memset/memcmp #include <time.h> #include "../codec/encoder/core/inc/memory_align.h" using namespace WelsSVCEnc; //Tests of WelsGetCacheLineSize Begin TEST(MemoryAlignTest, GetCacheLineSize_LoopWithin16K) { const unsigned int kuiTestBoundary16K = 16 * 1024; unsigned int uiTargetAlign = 1; while (uiTargetAlign < kuiTestBoundary16K) { CMemoryAlign cTestMa(uiTargetAlign); ASSERT_EQ( (uiTargetAlign & 0x0F)?16:uiTargetAlign, cTestMa.WelsGetCacheLineSize() ); ++ uiTargetAlign; } } TEST(MemoryAlignTest, GetCacheLineSize_Zero) { CMemoryAlign cTestMa(0); ASSERT_EQ( 16, cTestMa.WelsGetCacheLineSize() ); } TEST(MemoryAlignTest, GetCacheLineSize_MaxUINT) { CMemoryAlign cTestMa(0xFFFFFFFF); ASSERT_EQ( 16, cTestMa.WelsGetCacheLineSize() ); } //Tests of WelsGetCacheLineSize End //Tests of WelsMallocAndFree Begin TEST(MemoryAlignTest, WelsMallocAndFreeOnceFunctionVerify) { const uint32_t kuiTargetAlignSize[4] = {32, 16, 64, 8}; srand((uint32_t)time(NULL)); for (int i=0; i<4; i++) { const uint32_t kuiTestAlignSize = kuiTargetAlignSize[i]; const uint32_t kuiTestDataSize = abs(rand()); CMemoryAlign cTestMa(kuiTestAlignSize); const uint32_t uiSize = kuiTestDataSize; const char strUnitTestTag[100] = "pUnitTestData"; const uint32_t kuiUsedCacheLineSize = ((kuiTestAlignSize == 0) || (kuiTestAlignSize & 0x0F)) ? (16) : (kuiTestAlignSize); const uint32_t kuiExtraAlignSize = kuiUsedCacheLineSize-1; const uint32_t kuiExpectedSize = sizeof( void ** ) + sizeof( int32_t ) + kuiExtraAlignSize + uiSize; uint8_t *pUnitTestData = static_cast<uint8_t *>(cTestMa.WelsMalloc(uiSize, strUnitTestTag)); if ( pUnitTestData != NULL ) { ASSERT_TRUE( (((int64_t)(static_cast<void *>(pUnitTestData))) & kuiExtraAlignSize) == 0 ); EXPECT_EQ( kuiExpectedSize, cTestMa.WelsGetMemoryUsage() ); cTestMa.WelsFree( pUnitTestData, strUnitTestTag ); EXPECT_EQ( 0, cTestMa.WelsGetMemoryUsage() ); } else { EXPECT_EQ( NULL, pUnitTestData ); EXPECT_EQ( 0, cTestMa.WelsGetMemoryUsage() ); cTestMa.WelsFree( pUnitTestData, strUnitTestTag ); EXPECT_EQ( 0, cTestMa.WelsGetMemoryUsage() ); } } } <|endoftext|>
<commit_before>/*************************************************************************/ /* gdscript_cache.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "gdscript_cache.h" #include "core/io/file_access.h" #include "core/templates/vector.h" #include "gdscript.h" #include "gdscript_analyzer.h" #include "gdscript_parser.h" bool GDScriptParserRef::is_valid() const { return parser != nullptr; } GDScriptParserRef::Status GDScriptParserRef::get_status() const { return status; } GDScriptParser *GDScriptParserRef::get_parser() const { return parser; } Error GDScriptParserRef::raise_status(Status p_new_status) { ERR_FAIL_COND_V(parser == nullptr, ERR_INVALID_DATA); if (result != OK) { return result; } while (p_new_status > status) { switch (status) { case EMPTY: status = PARSED; result = parser->parse(GDScriptCache::get_source_code(path), path, false); break; case PARSED: { analyzer = memnew(GDScriptAnalyzer(parser)); status = INHERITANCE_SOLVED; Error inheritance_result = analyzer->resolve_inheritance(); if (result == OK) { result = inheritance_result; } } break; case INHERITANCE_SOLVED: { status = INTERFACE_SOLVED; Error interface_result = analyzer->resolve_interface(); if (result == OK) { result = interface_result; } } break; case INTERFACE_SOLVED: { status = FULLY_SOLVED; Error body_result = analyzer->resolve_body(); if (result == OK) { result = body_result; } } break; case FULLY_SOLVED: { return result; } } if (result != OK) { return result; } } return result; } GDScriptParserRef::~GDScriptParserRef() { if (parser != nullptr) { memdelete(parser); } if (analyzer != nullptr) { memdelete(analyzer); } MutexLock lock(GDScriptCache::singleton->lock); GDScriptCache::singleton->parser_map.erase(path); } GDScriptCache *GDScriptCache::singleton = nullptr; void GDScriptCache::remove_script(const String &p_path) { MutexLock lock(singleton->lock); singleton->shallow_gdscript_cache.erase(p_path); singleton->full_gdscript_cache.erase(p_path); } Ref<GDScriptParserRef> GDScriptCache::get_parser(const String &p_path, GDScriptParserRef::Status p_status, Error &r_error, const String &p_owner) { MutexLock lock(singleton->lock); Ref<GDScriptParserRef> ref; if (!p_owner.is_empty()) { singleton->dependencies[p_owner].insert(p_path); } if (singleton->parser_map.has(p_path)) { ref = Ref<GDScriptParserRef>(singleton->parser_map[p_path]); } else { if (!FileAccess::exists(p_path)) { r_error = ERR_FILE_NOT_FOUND; return ref; } GDScriptParser *parser = memnew(GDScriptParser); ref.instantiate(); ref->parser = parser; ref->path = p_path; singleton->parser_map[p_path] = ref.ptr(); } r_error = ref->raise_status(p_status); return ref; } String GDScriptCache::get_source_code(const String &p_path) { Vector<uint8_t> source_file; Error err; FileAccessRef f = FileAccess::open(p_path, FileAccess::READ, &err); if (err) { ERR_FAIL_COND_V(err, ""); } uint64_t len = f->get_length(); source_file.resize(len + 1); uint64_t r = f->get_buffer(source_file.ptrw(), len); f->close(); ERR_FAIL_COND_V(r != len, ""); source_file.write[len] = 0; String source; if (source.parse_utf8((const char *)source_file.ptr())) { ERR_FAIL_V_MSG("", "Script '" + p_path + "' contains invalid unicode (UTF-8), so it was not loaded. Please ensure that scripts are saved in valid UTF-8 unicode."); } return source; } Ref<GDScript> GDScriptCache::get_shallow_script(const String &p_path, const String &p_owner) { MutexLock lock(singleton->lock); if (!p_owner.is_empty()) { singleton->dependencies[p_owner].insert(p_path); } if (singleton->full_gdscript_cache.has(p_path)) { return singleton->full_gdscript_cache[p_path]; } if (singleton->shallow_gdscript_cache.has(p_path)) { return singleton->shallow_gdscript_cache[p_path]; } Ref<GDScript> script; script.instantiate(); script->set_path(p_path, true); script->set_script_path(p_path); script->load_source_code(p_path); singleton->shallow_gdscript_cache[p_path] = script.ptr(); return script; } Ref<GDScript> GDScriptCache::get_full_script(const String &p_path, Error &r_error, const String &p_owner) { MutexLock lock(singleton->lock); if (!p_owner.is_empty()) { singleton->dependencies[p_owner].insert(p_path); } r_error = OK; if (singleton->full_gdscript_cache.has(p_path)) { Ref<GDScript> script = singleton->full_gdscript_cache[p_path]; #ifdef TOOLS_ENABLED uint64_t mt = FileAccess::get_modified_time(p_path); if (script->get_last_modified_time() == mt) { return script; } #else return script; #endif //TOOLS_ENABLED } Ref<GDScript> script = get_shallow_script(p_path); ERR_FAIL_COND_V(script.is_null(), Ref<GDScript>()); r_error = script->load_source_code(p_path); if (r_error) { return script; } r_error = script->reload(); if (r_error) { return script; } singleton->full_gdscript_cache[p_path] = script.ptr(); singleton->shallow_gdscript_cache.erase(p_path); return script; } Error GDScriptCache::finish_compiling(const String &p_owner) { // Mark this as compiled. Ref<GDScript> script = get_shallow_script(p_owner); singleton->full_gdscript_cache[p_owner] = script.ptr(); singleton->shallow_gdscript_cache.erase(p_owner); Set<String> depends = singleton->dependencies[p_owner]; Error err = OK; for (const Set<String>::Element *E = depends.front(); E != nullptr; E = E->next()) { Error this_err = OK; // No need to save the script. We assume it's already referenced in the owner. get_full_script(E->get(), this_err); if (this_err != OK) { err = this_err; } } singleton->dependencies.erase(p_owner); return err; } GDScriptCache::GDScriptCache() { singleton = this; } GDScriptCache::~GDScriptCache() { parser_map.clear(); shallow_gdscript_cache.clear(); full_gdscript_cache.clear(); singleton = nullptr; } <commit_msg>Revert "Fix auto reload scripts on external change"<commit_after>/*************************************************************************/ /* gdscript_cache.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "gdscript_cache.h" #include "core/io/file_access.h" #include "core/templates/vector.h" #include "gdscript.h" #include "gdscript_analyzer.h" #include "gdscript_parser.h" bool GDScriptParserRef::is_valid() const { return parser != nullptr; } GDScriptParserRef::Status GDScriptParserRef::get_status() const { return status; } GDScriptParser *GDScriptParserRef::get_parser() const { return parser; } Error GDScriptParserRef::raise_status(Status p_new_status) { ERR_FAIL_COND_V(parser == nullptr, ERR_INVALID_DATA); if (result != OK) { return result; } while (p_new_status > status) { switch (status) { case EMPTY: status = PARSED; result = parser->parse(GDScriptCache::get_source_code(path), path, false); break; case PARSED: { analyzer = memnew(GDScriptAnalyzer(parser)); status = INHERITANCE_SOLVED; Error inheritance_result = analyzer->resolve_inheritance(); if (result == OK) { result = inheritance_result; } } break; case INHERITANCE_SOLVED: { status = INTERFACE_SOLVED; Error interface_result = analyzer->resolve_interface(); if (result == OK) { result = interface_result; } } break; case INTERFACE_SOLVED: { status = FULLY_SOLVED; Error body_result = analyzer->resolve_body(); if (result == OK) { result = body_result; } } break; case FULLY_SOLVED: { return result; } } if (result != OK) { return result; } } return result; } GDScriptParserRef::~GDScriptParserRef() { if (parser != nullptr) { memdelete(parser); } if (analyzer != nullptr) { memdelete(analyzer); } MutexLock lock(GDScriptCache::singleton->lock); GDScriptCache::singleton->parser_map.erase(path); } GDScriptCache *GDScriptCache::singleton = nullptr; void GDScriptCache::remove_script(const String &p_path) { MutexLock lock(singleton->lock); singleton->shallow_gdscript_cache.erase(p_path); singleton->full_gdscript_cache.erase(p_path); } Ref<GDScriptParserRef> GDScriptCache::get_parser(const String &p_path, GDScriptParserRef::Status p_status, Error &r_error, const String &p_owner) { MutexLock lock(singleton->lock); Ref<GDScriptParserRef> ref; if (!p_owner.is_empty()) { singleton->dependencies[p_owner].insert(p_path); } if (singleton->parser_map.has(p_path)) { ref = Ref<GDScriptParserRef>(singleton->parser_map[p_path]); } else { if (!FileAccess::exists(p_path)) { r_error = ERR_FILE_NOT_FOUND; return ref; } GDScriptParser *parser = memnew(GDScriptParser); ref.instantiate(); ref->parser = parser; ref->path = p_path; singleton->parser_map[p_path] = ref.ptr(); } r_error = ref->raise_status(p_status); return ref; } String GDScriptCache::get_source_code(const String &p_path) { Vector<uint8_t> source_file; Error err; FileAccessRef f = FileAccess::open(p_path, FileAccess::READ, &err); if (err) { ERR_FAIL_COND_V(err, ""); } uint64_t len = f->get_length(); source_file.resize(len + 1); uint64_t r = f->get_buffer(source_file.ptrw(), len); f->close(); ERR_FAIL_COND_V(r != len, ""); source_file.write[len] = 0; String source; if (source.parse_utf8((const char *)source_file.ptr())) { ERR_FAIL_V_MSG("", "Script '" + p_path + "' contains invalid unicode (UTF-8), so it was not loaded. Please ensure that scripts are saved in valid UTF-8 unicode."); } return source; } Ref<GDScript> GDScriptCache::get_shallow_script(const String &p_path, const String &p_owner) { MutexLock lock(singleton->lock); if (!p_owner.is_empty()) { singleton->dependencies[p_owner].insert(p_path); } if (singleton->full_gdscript_cache.has(p_path)) { return singleton->full_gdscript_cache[p_path]; } if (singleton->shallow_gdscript_cache.has(p_path)) { return singleton->shallow_gdscript_cache[p_path]; } Ref<GDScript> script; script.instantiate(); script->set_path(p_path, true); script->set_script_path(p_path); script->load_source_code(p_path); singleton->shallow_gdscript_cache[p_path] = script.ptr(); return script; } Ref<GDScript> GDScriptCache::get_full_script(const String &p_path, Error &r_error, const String &p_owner) { MutexLock lock(singleton->lock); if (!p_owner.is_empty()) { singleton->dependencies[p_owner].insert(p_path); } r_error = OK; if (singleton->full_gdscript_cache.has(p_path)) { return singleton->full_gdscript_cache[p_path]; } Ref<GDScript> script = get_shallow_script(p_path); ERR_FAIL_COND_V(script.is_null(), Ref<GDScript>()); r_error = script->load_source_code(p_path); if (r_error) { return script; } r_error = script->reload(); if (r_error) { return script; } singleton->full_gdscript_cache[p_path] = script.ptr(); singleton->shallow_gdscript_cache.erase(p_path); return script; } Error GDScriptCache::finish_compiling(const String &p_owner) { // Mark this as compiled. Ref<GDScript> script = get_shallow_script(p_owner); singleton->full_gdscript_cache[p_owner] = script.ptr(); singleton->shallow_gdscript_cache.erase(p_owner); Set<String> depends = singleton->dependencies[p_owner]; Error err = OK; for (const Set<String>::Element *E = depends.front(); E != nullptr; E = E->next()) { Error this_err = OK; // No need to save the script. We assume it's already referenced in the owner. get_full_script(E->get(), this_err); if (this_err != OK) { err = this_err; } } singleton->dependencies.erase(p_owner); return err; } GDScriptCache::GDScriptCache() { singleton = this; } GDScriptCache::~GDScriptCache() { parser_map.clear(); shallow_gdscript_cache.clear(); full_gdscript_cache.clear(); singleton = nullptr; } <|endoftext|>
<commit_before>#include "adaptive_load/adaptive_load_controller_impl.h" #include <chrono> #include "envoy/common/exception.h" #include "envoy/config/core/v3/base.pb.h" #include "nighthawk/adaptive_load/adaptive_load_controller.h" #include "nighthawk/adaptive_load/metrics_plugin.h" #include "nighthawk/adaptive_load/scoring_function.h" #include "nighthawk/adaptive_load/step_controller.h" #include "external/envoy/source/common/common/logger.h" #include "external/envoy/source/common/common/statusor.h" #include "external/envoy/source/common/protobuf/protobuf.h" #include "api/adaptive_load/adaptive_load.pb.h" #include "api/adaptive_load/benchmark_result.pb.h" #include "api/adaptive_load/metric_spec.pb.h" #include "api/client/options.pb.h" #include "api/client/output.pb.h" #include "api/client/service.grpc.pb.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "adaptive_load/metrics_plugin_impl.h" #include "adaptive_load/plugin_loader.h" namespace Nighthawk { namespace { using nighthawk::adaptive_load::AdaptiveLoadSessionOutput; using nighthawk::adaptive_load::AdaptiveLoadSessionSpec; using nighthawk::adaptive_load::BenchmarkResult; using nighthawk::adaptive_load::MetricEvaluation; using nighthawk::adaptive_load::MetricSpec; using nighthawk::adaptive_load::MetricSpecWithThreshold; using nighthawk::adaptive_load::ThresholdSpec; /** * Loads and initializes MetricsPlugins requested in the session spec. Assumes the spec has already * been validated; crashes the process otherwise. * * @param spec Adaptive load session spec proto that has already been validated. * * @return Map from MetricsPlugin names to initialized plugins, to be used in the course of a single * adaptive load session based on the session spec. */ absl::flat_hash_map<std::string, MetricsPluginPtr> LoadMetricsPlugins(const AdaptiveLoadSessionSpec& spec) { absl::flat_hash_map<std::string, MetricsPluginPtr> name_to_custom_metrics_plugin_map; for (const envoy::config::core::v3::TypedExtensionConfig& config : spec.metrics_plugin_configs()) { absl::StatusOr<MetricsPluginPtr> metrics_plugin_or = LoadMetricsPlugin(config); RELEASE_ASSERT( metrics_plugin_or.ok(), absl::StrCat( "MetricsPlugin loading error should have been caught during input validation: ", metrics_plugin_or.status().message())); name_to_custom_metrics_plugin_map[config.name()] = std::move(metrics_plugin_or.value()); } return name_to_custom_metrics_plugin_map; } /** * Loads and initializes a StepController plugin requested in the session spec. Assumes * the spec has already been validated; crashes the process otherwise. * * @param spec Adaptive load session spec proto that has already been validated. * * @return unique_ptr<StepController> Initialized StepController plugin. */ StepControllerPtr LoadStepControllerPluginFromSpec(const AdaptiveLoadSessionSpec& spec) { absl::StatusOr<StepControllerPtr> step_controller_or = LoadStepControllerPlugin(spec.step_controller_config(), spec.nighthawk_traffic_template()); RELEASE_ASSERT( step_controller_or.ok(), absl::StrCat( "StepController plugin loading error should have been caught during input validation: ", step_controller_or.status().message())); return std::move(step_controller_or.value()); } } // namespace AdaptiveLoadControllerImpl::AdaptiveLoadControllerImpl( const NighthawkServiceClient& nighthawk_service_client, const MetricsEvaluator& metrics_evaluator, const AdaptiveLoadSessionSpecProtoHelper& session_spec_proto_helper, Envoy::TimeSource& time_source) : nighthawk_service_client_{nighthawk_service_client}, metrics_evaluator_{metrics_evaluator}, session_spec_proto_helper_{session_spec_proto_helper}, time_source_{time_source} {} absl::StatusOr<BenchmarkResult> AdaptiveLoadControllerImpl::PerformAndAnalyzeNighthawkBenchmark( nighthawk::client::NighthawkService::StubInterface* nighthawk_service_stub, const AdaptiveLoadSessionSpec& spec, const absl::flat_hash_map<std::string, MetricsPluginPtr>& name_to_custom_plugin_map, StepController& step_controller, Envoy::ProtobufWkt::Duration duration) { absl::StatusOr<nighthawk::client::CommandLineOptions> command_line_options_or = step_controller.GetCurrentCommandLineOptions(); if (!command_line_options_or.ok()) { ENVOY_LOG_MISC(error, "Error constructing Nighthawk input: {}: {}", command_line_options_or.status().code(), command_line_options_or.status().message()); return command_line_options_or.status(); } nighthawk::client::CommandLineOptions command_line_options = command_line_options_or.value(); // Overwrite the duration in the traffic template with the specified duration of the adjusting // or testing stage. *command_line_options.mutable_duration() = std::move(duration); ENVOY_LOG_MISC(info, "Sending load: {}", command_line_options.DebugString()); absl::StatusOr<nighthawk::client::ExecutionResponse> nighthawk_response_or = nighthawk_service_client_.PerformNighthawkBenchmark(nighthawk_service_stub, command_line_options); if (!nighthawk_response_or.ok()) { ENVOY_LOG_MISC(error, "Nighthawk Service error: {}: {}", nighthawk_response_or.status().code(), nighthawk_response_or.status().message()); return nighthawk_response_or.status(); } nighthawk::client::ExecutionResponse nighthawk_response = nighthawk_response_or.value(); absl::StatusOr<BenchmarkResult> benchmark_result_or = metrics_evaluator_.AnalyzeNighthawkBenchmark(nighthawk_response, spec, name_to_custom_plugin_map); if (!benchmark_result_or.ok()) { ENVOY_LOG_MISC(error, "Benchmark scoring error: {}: {}", benchmark_result_or.status().code(), benchmark_result_or.status().message()); return benchmark_result_or.status(); } BenchmarkResult benchmark_result = benchmark_result_or.value(); for (const MetricEvaluation& evaluation : benchmark_result.metric_evaluations()) { ENVOY_LOG_MISC(info, "Evaluation: {}", evaluation.DebugString()); } step_controller.UpdateAndRecompute(benchmark_result); return benchmark_result; } absl::StatusOr<AdaptiveLoadSessionOutput> AdaptiveLoadControllerImpl::PerformAdaptiveLoadSession( nighthawk::client::NighthawkService::StubInterface* nighthawk_service_stub, const AdaptiveLoadSessionSpec& input_spec) { AdaptiveLoadSessionSpec spec = session_spec_proto_helper_.SetSessionSpecDefaults(input_spec); absl::Status validation_status = session_spec_proto_helper_.CheckSessionSpec(spec); if (!validation_status.ok()) { ENVOY_LOG_MISC(error, "Validation failed: {}", validation_status.message()); return validation_status; } absl::flat_hash_map<std::string, MetricsPluginPtr> name_to_custom_metrics_plugin_map = LoadMetricsPlugins(spec); StepControllerPtr step_controller = LoadStepControllerPluginFromSpec(spec); AdaptiveLoadSessionOutput output; // Threshold specs are reproduced in the output proto for convenience. for (const nighthawk::adaptive_load::MetricSpecWithThreshold& threshold : spec.metric_thresholds()) { *output.mutable_metric_thresholds()->Add() = threshold; } // Perform adjusting stage: Envoy::MonotonicTime start_time = time_source_.monotonicTime(); std::string doom_reason; do { absl::StatusOr<BenchmarkResult> result_or = PerformAndAnalyzeNighthawkBenchmark( nighthawk_service_stub, spec, name_to_custom_metrics_plugin_map, *step_controller, spec.measuring_period()); if (!result_or.ok()) { return result_or.status(); } BenchmarkResult result = result_or.value(); *output.mutable_adjusting_stage_results()->Add() = result; if (spec.has_benchmark_cooldown_duration()) { ENVOY_LOG_MISC(info, "Cooling down before the next benchmark for duration: {}", spec.benchmark_cooldown_duration()); uint64_t sleep_time_ms = Envoy::Protobuf::util::TimeUtil::DurationToMilliseconds( spec.benchmark_cooldown_duration()); absl::SleepFor(absl::Milliseconds(sleep_time_ms)); } const std::chrono::nanoseconds time_limit_ns( Envoy::Protobuf::util::TimeUtil::DurationToNanoseconds(spec.convergence_deadline())); const auto elapsed_time_ns = std::chrono::duration_cast<std::chrono::nanoseconds>( time_source_.monotonicTime() - start_time); if (elapsed_time_ns > time_limit_ns) { std::string message = absl::StrFormat("Failed to converge before deadline of %.2f seconds.", time_limit_ns.count() / 1e9); ENVOY_LOG_MISC(error, message); return absl::DeadlineExceededError(message); } } while (!step_controller->IsConverged() && !step_controller->IsDoomed(doom_reason)); if (step_controller->IsDoomed(doom_reason)) { std::string message = absl::StrCat("Step controller determined that it can never converge: ", doom_reason); ENVOY_LOG_MISC(error, message); return absl::AbortedError(message); } // Perform testing stage: absl::StatusOr<BenchmarkResult> result_or = PerformAndAnalyzeNighthawkBenchmark( nighthawk_service_stub, spec, name_to_custom_metrics_plugin_map, *step_controller, spec.testing_stage_duration()); if (!result_or.ok()) { return result_or.status(); } *output.mutable_testing_stage_result() = result_or.value(); return output; } } // namespace Nighthawk <commit_msg>Log a stripped down version of the NH output for the adaptive load session. (#680)<commit_after>#include "adaptive_load/adaptive_load_controller_impl.h" #include <chrono> #include "envoy/common/exception.h" #include "envoy/config/core/v3/base.pb.h" #include "nighthawk/adaptive_load/adaptive_load_controller.h" #include "nighthawk/adaptive_load/metrics_plugin.h" #include "nighthawk/adaptive_load/scoring_function.h" #include "nighthawk/adaptive_load/step_controller.h" #include "external/envoy/source/common/common/logger.h" #include "external/envoy/source/common/common/statusor.h" #include "external/envoy/source/common/protobuf/protobuf.h" #include "api/adaptive_load/adaptive_load.pb.h" #include "api/adaptive_load/benchmark_result.pb.h" #include "api/adaptive_load/metric_spec.pb.h" #include "api/client/options.pb.h" #include "api/client/output.pb.h" #include "api/client/service.grpc.pb.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "adaptive_load/metrics_plugin_impl.h" #include "adaptive_load/plugin_loader.h" namespace Nighthawk { namespace { using nighthawk::adaptive_load::AdaptiveLoadSessionOutput; using nighthawk::adaptive_load::AdaptiveLoadSessionSpec; using nighthawk::adaptive_load::BenchmarkResult; using nighthawk::adaptive_load::MetricEvaluation; using nighthawk::adaptive_load::MetricSpec; using nighthawk::adaptive_load::MetricSpecWithThreshold; using nighthawk::adaptive_load::ThresholdSpec; /** * Loads and initializes MetricsPlugins requested in the session spec. Assumes the spec has already * been validated; crashes the process otherwise. * * @param spec Adaptive load session spec proto that has already been validated. * * @return Map from MetricsPlugin names to initialized plugins, to be used in the course of a single * adaptive load session based on the session spec. */ absl::flat_hash_map<std::string, MetricsPluginPtr> LoadMetricsPlugins(const AdaptiveLoadSessionSpec& spec) { absl::flat_hash_map<std::string, MetricsPluginPtr> name_to_custom_metrics_plugin_map; for (const envoy::config::core::v3::TypedExtensionConfig& config : spec.metrics_plugin_configs()) { absl::StatusOr<MetricsPluginPtr> metrics_plugin_or = LoadMetricsPlugin(config); RELEASE_ASSERT( metrics_plugin_or.ok(), absl::StrCat( "MetricsPlugin loading error should have been caught during input validation: ", metrics_plugin_or.status().message())); name_to_custom_metrics_plugin_map[config.name()] = std::move(metrics_plugin_or.value()); } return name_to_custom_metrics_plugin_map; } /** * Logs the execution response excluding all non-global results and the * statistics from the global result. * * @param response is the execution response that should be logged. */ void LogGlobalResultExcludingStatistics(const nighthawk::client::ExecutionResponse& response) { nighthawk::client::ExecutionResponse stripped = response; stripped.mutable_output()->clear_results(); for (const nighthawk::client::Result& result : response.output().results()) { if (result.name() != "global") { continue; } nighthawk::client::Result* stripped_result = stripped.mutable_output()->add_results(); *stripped_result = result; stripped_result->clear_statistics(); } ENVOY_LOG_MISC(info, "Got result (stripped to just the global result excluding " "statistics): {}", stripped.DebugString()); } /** * Loads and initializes a StepController plugin requested in the session spec. Assumes * the spec has already been validated; crashes the process otherwise. * * @param spec Adaptive load session spec proto that has already been validated. * * @return unique_ptr<StepController> Initialized StepController plugin. */ StepControllerPtr LoadStepControllerPluginFromSpec(const AdaptiveLoadSessionSpec& spec) { absl::StatusOr<StepControllerPtr> step_controller_or = LoadStepControllerPlugin(spec.step_controller_config(), spec.nighthawk_traffic_template()); RELEASE_ASSERT( step_controller_or.ok(), absl::StrCat( "StepController plugin loading error should have been caught during input validation: ", step_controller_or.status().message())); return std::move(step_controller_or.value()); } } // namespace AdaptiveLoadControllerImpl::AdaptiveLoadControllerImpl( const NighthawkServiceClient& nighthawk_service_client, const MetricsEvaluator& metrics_evaluator, const AdaptiveLoadSessionSpecProtoHelper& session_spec_proto_helper, Envoy::TimeSource& time_source) : nighthawk_service_client_{nighthawk_service_client}, metrics_evaluator_{metrics_evaluator}, session_spec_proto_helper_{session_spec_proto_helper}, time_source_{time_source} {} absl::StatusOr<BenchmarkResult> AdaptiveLoadControllerImpl::PerformAndAnalyzeNighthawkBenchmark( nighthawk::client::NighthawkService::StubInterface* nighthawk_service_stub, const AdaptiveLoadSessionSpec& spec, const absl::flat_hash_map<std::string, MetricsPluginPtr>& name_to_custom_plugin_map, StepController& step_controller, Envoy::ProtobufWkt::Duration duration) { absl::StatusOr<nighthawk::client::CommandLineOptions> command_line_options_or = step_controller.GetCurrentCommandLineOptions(); if (!command_line_options_or.ok()) { ENVOY_LOG_MISC(error, "Error constructing Nighthawk input: {}: {}", command_line_options_or.status().code(), command_line_options_or.status().message()); return command_line_options_or.status(); } nighthawk::client::CommandLineOptions command_line_options = command_line_options_or.value(); // Overwrite the duration in the traffic template with the specified duration of the adjusting // or testing stage. *command_line_options.mutable_duration() = std::move(duration); ENVOY_LOG_MISC(info, "Sending load: {}", command_line_options.DebugString()); absl::StatusOr<nighthawk::client::ExecutionResponse> nighthawk_response_or = nighthawk_service_client_.PerformNighthawkBenchmark(nighthawk_service_stub, command_line_options); if (!nighthawk_response_or.ok()) { ENVOY_LOG_MISC(error, "Nighthawk Service error: {}: {}", nighthawk_response_or.status().code(), nighthawk_response_or.status().message()); return nighthawk_response_or.status(); } nighthawk::client::ExecutionResponse nighthawk_response = nighthawk_response_or.value(); LogGlobalResultExcludingStatistics(nighthawk_response); absl::StatusOr<BenchmarkResult> benchmark_result_or = metrics_evaluator_.AnalyzeNighthawkBenchmark(nighthawk_response, spec, name_to_custom_plugin_map); if (!benchmark_result_or.ok()) { ENVOY_LOG_MISC(error, "Benchmark scoring error: {}: {}", benchmark_result_or.status().code(), benchmark_result_or.status().message()); return benchmark_result_or.status(); } BenchmarkResult benchmark_result = benchmark_result_or.value(); for (const MetricEvaluation& evaluation : benchmark_result.metric_evaluations()) { ENVOY_LOG_MISC(info, "Evaluation: {}", evaluation.DebugString()); } step_controller.UpdateAndRecompute(benchmark_result); return benchmark_result; } absl::StatusOr<AdaptiveLoadSessionOutput> AdaptiveLoadControllerImpl::PerformAdaptiveLoadSession( nighthawk::client::NighthawkService::StubInterface* nighthawk_service_stub, const AdaptiveLoadSessionSpec& input_spec) { AdaptiveLoadSessionSpec spec = session_spec_proto_helper_.SetSessionSpecDefaults(input_spec); absl::Status validation_status = session_spec_proto_helper_.CheckSessionSpec(spec); if (!validation_status.ok()) { ENVOY_LOG_MISC(error, "Validation failed: {}", validation_status.message()); return validation_status; } absl::flat_hash_map<std::string, MetricsPluginPtr> name_to_custom_metrics_plugin_map = LoadMetricsPlugins(spec); StepControllerPtr step_controller = LoadStepControllerPluginFromSpec(spec); AdaptiveLoadSessionOutput output; // Threshold specs are reproduced in the output proto for convenience. for (const nighthawk::adaptive_load::MetricSpecWithThreshold& threshold : spec.metric_thresholds()) { *output.mutable_metric_thresholds()->Add() = threshold; } // Perform adjusting stage: Envoy::MonotonicTime start_time = time_source_.monotonicTime(); std::string doom_reason; do { absl::StatusOr<BenchmarkResult> result_or = PerformAndAnalyzeNighthawkBenchmark( nighthawk_service_stub, spec, name_to_custom_metrics_plugin_map, *step_controller, spec.measuring_period()); if (!result_or.ok()) { return result_or.status(); } BenchmarkResult result = result_or.value(); *output.mutable_adjusting_stage_results()->Add() = result; if (spec.has_benchmark_cooldown_duration()) { ENVOY_LOG_MISC(info, "Cooling down before the next benchmark for duration: {}", spec.benchmark_cooldown_duration()); uint64_t sleep_time_ms = Envoy::Protobuf::util::TimeUtil::DurationToMilliseconds( spec.benchmark_cooldown_duration()); absl::SleepFor(absl::Milliseconds(sleep_time_ms)); } const std::chrono::nanoseconds time_limit_ns( Envoy::Protobuf::util::TimeUtil::DurationToNanoseconds(spec.convergence_deadline())); const auto elapsed_time_ns = std::chrono::duration_cast<std::chrono::nanoseconds>( time_source_.monotonicTime() - start_time); if (elapsed_time_ns > time_limit_ns) { std::string message = absl::StrFormat("Failed to converge before deadline of %.2f seconds.", time_limit_ns.count() / 1e9); ENVOY_LOG_MISC(error, message); return absl::DeadlineExceededError(message); } } while (!step_controller->IsConverged() && !step_controller->IsDoomed(doom_reason)); if (step_controller->IsDoomed(doom_reason)) { std::string message = absl::StrCat("Step controller determined that it can never converge: ", doom_reason); ENVOY_LOG_MISC(error, message); return absl::AbortedError(message); } // Perform testing stage: absl::StatusOr<BenchmarkResult> result_or = PerformAndAnalyzeNighthawkBenchmark( nighthawk_service_stub, spec, name_to_custom_metrics_plugin_map, *step_controller, spec.testing_stage_duration()); if (!result_or.ok()) { return result_or.status(); } *output.mutable_testing_stage_result() = result_or.value(); return output; } } // namespace Nighthawk <|endoftext|>
<commit_before>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * InSituMPISchedules.cpp * common functions for in situ MPI Writer and Reader * It requires MPI * * Created on: Dec 25, 2017 * Author: Norbert Podhorszki pnorbert@ornl.gov */ #include "InSituMPISchedules.h" #include "adios2/helper/adiosMath.h" #include "adios2/helper/adiosMemory.h" #include <iostream> namespace adios2 { namespace insitumpi { int GetNumberOfRequests( const std::map<std::string, SubFileInfoMap> &variablesSubFileInfo) noexcept { int n = 0; for (const auto &variableNamePair : variablesSubFileInfo) { // <writer, <steps, <SubFileInfo>>> for (const auto &subFileIndexPair : variableNamePair.second) { // <steps, <SubFileInfo>> but there is only one step for (const auto &stepPair : subFileIndexPair.second) { // <SubFileInfo> for (const auto &sfi : stepPair.second) { n++; } } } } return n; } int FixSeeksToZeroOffset( std::map<std::string, SubFileInfoMap> &variablesSubFileInfo) noexcept { int n = 0; for (auto &variableNamePair : variablesSubFileInfo) { // <writer, <steps, <SubFileInfo>>> for (auto &subFileIndexPair : variableNamePair.second) { // <steps, <SubFileInfo>> but there is only one step for (auto &stepPair : subFileIndexPair.second) { // <SubFileInfo> for (auto &sfi : stepPair.second) { FixSeeksToZeroOffset(sfi); n++; } } } } return n; } void FixSeeksToZeroOffset(SubFileInfo &record) noexcept { size_t nElements = record.Seeks.second - record.Seeks.first + 1; size_t pos = LinearIndex(record.BlockBox, record.IntersectionBox.first, true); record.Seeks.first = pos; record.Seeks.second = pos + nElements - 1; } std::vector<std::vector<char>> SerializeLocalReadSchedule( const int nWriters, const std::map<std::string, SubFileInfoMap> &variablesSubFileInfo) noexcept { std::vector<std::vector<char>> buffers(nWriters); // Create a buffer for each writer std::vector<int> nVarPerWriter(nWriters); for (size_t i = 0; i < nWriters; i++) { nVarPerWriter[i] = 0; InsertToBuffer(buffers[i], &nVarPerWriter[i], 1); // allocate first 4 bytes } for (const auto &variableNamePair : variablesSubFileInfo) { const std::string variableName(variableNamePair.first); // <writer, <steps, <SubFileInfo>>> for (const auto &subFileIndexPair : variableNamePair.second) { const size_t subFileIndex = subFileIndexPair.first; // writer auto &lrs = buffers[subFileIndex]; // <steps, <SubFileInfo>> but there is only one step for (const auto &stepPair : subFileIndexPair.second) { // LocalReadSchedule sfi = subFileIndexPair.second[0]; const std::vector<SubFileInfo> &sfi = stepPair.second; SerializeLocalReadSchedule(buffers[subFileIndex], variableName, sfi); ++nVarPerWriter[subFileIndex]; break; // there is only one step here } } } // Record the number of actually requested variables for each buffer for (int i = 0; i < nWriters; i++) { size_t pos = 0; CopyToBuffer(buffers[i], pos, &nVarPerWriter[i]); } return buffers; } void SerializeLocalReadSchedule(std::vector<char> &buffer, const std::string varName, const LocalReadSchedule lrs) noexcept { const int nameLen = varName.size(); InsertToBuffer(buffer, &nameLen, 1); InsertToBuffer(buffer, varName.data(), nameLen); const int nSubFileInfos = lrs.size(); InsertToBuffer(buffer, &nSubFileInfos, 1); for (const auto &blockInfo : lrs) { SerializeSubFileInfo(buffer, blockInfo); } } void SerializeSubFileInfo(std::vector<char> &buffer, const SubFileInfo record) noexcept { SerializeBox(buffer, record.BlockBox); SerializeBox(buffer, record.IntersectionBox); SerializeBox(buffer, record.Seeks); } void SerializeBox(std::vector<char> &buffer, const Box<Dims> box) noexcept { const int nDims = box.first.size(); InsertToBuffer(buffer, &nDims, 1); InsertToBuffer(buffer, box.first.data(), nDims); InsertToBuffer(buffer, box.second.data(), nDims); } void SerializeBox(std::vector<char> &buffer, const Box<size_t> box) noexcept { InsertToBuffer(buffer, &box.first, 1); InsertToBuffer(buffer, &box.second, 1); } int GetNumberOfRequestsInWriteScheduleMap(WriteScheduleMap &map) noexcept { int n; //<variable <reader, <SubFileInfo>>> for (auto &variableNamePair : map) { // <reader, <SubFileInfo>> for (auto &readerPair : variableNamePair.second) { // <SubFileInfo> for (auto &sfi : readerPair.second) { n++; } } } return n; } WriteScheduleMap DeserializeReadSchedule(const std::vector<std::vector<char>> &buffers) noexcept { WriteScheduleMap map; for (int i = 0; i < buffers.size(); i++) { const auto &buffer = buffers[i]; LocalReadScheduleMap lrsm = DeserializeReadSchedule(buffer); for (const auto &varSchedule : lrsm) { map[varSchedule.first][i] = varSchedule.second; } } return map; } LocalReadScheduleMap DeserializeReadSchedule(const std::vector<char> &buffer) noexcept { LocalReadScheduleMap map; size_t pos = 0; int nVars = ReadValue<int>(buffer, pos); for (int i = 0; i < nVars; i++) { int nameLen = ReadValue<int>(buffer, pos); char name[nameLen + 1]; CopyFromBuffer(buffer, pos, name, nameLen); name[nameLen] = '\0'; int nSubFileInfos = ReadValue<int>(buffer, pos); std::vector<SubFileInfo> sfis; sfis.reserve(nSubFileInfos); for (int j = 0; j < nSubFileInfos; j++) { sfis.push_back(DeserializeSubFileInfo(buffer, pos)); } map[name] = sfis; } return map; } SubFileInfo DeserializeSubFileInfo(const std::vector<char> &buffer, size_t &position) noexcept { SubFileInfo record; record.BlockBox = DeserializeBoxDims(buffer, position); record.IntersectionBox = DeserializeBoxDims(buffer, position); record.Seeks = DeserializeBoxSizet(buffer, position); return record; } Box<Dims> DeserializeBoxDims(const std::vector<char> &buffer, size_t &position) noexcept { Box<Dims> box; int nDims = ReadValue<int>(buffer, position); std::vector<size_t> start(nDims); std::vector<size_t> count(nDims); CopyFromBuffer(buffer, position, start.data(), nDims); CopyFromBuffer(buffer, position, count.data(), nDims); return Box<Dims>(start, count); } Box<size_t> DeserializeBoxSizet(const std::vector<char> &buffer, size_t &position) noexcept { size_t first, second; CopyFromBuffer(buffer, position, &first, 1); CopyFromBuffer(buffer, position, &second, 1); return Box<size_t>(first, second); } void PrintReadScheduleMap(const WriteScheduleMap &map) noexcept { // <variableName, <reader, <SubFileInfo>>> for (const auto &variableNamePair : map) { std::cout << "{ var = " << variableNamePair.first << " "; // <reader, <SubFileInfo>> for (const auto &readerPair : variableNamePair.second) { const size_t readerRank = readerPair.first; std::cout << "{ reader = " << readerPair.first << " "; const std::vector<SubFileInfo> &sfis = readerPair.second; for (const auto &sfi : sfis) { std::cout << "<"; PrintSubFileInfo(sfi); std::cout << "> "; } std::cout << "} "; } std::cout << "} "; } } void PrintSubFileInfo(const SubFileInfo &sfi) noexcept { std::cout << "(block="; PrintBox(sfi.BlockBox); std::cout << ", intersection="; PrintBox(sfi.IntersectionBox); std::cout << ", seeks="; PrintBox(sfi.Seeks); std::cout << ")"; } void PrintBox(const Box<Dims> &box) noexcept { std::cout << "["; PrintDims(box.first); std::cout << ","; PrintDims(box.second); std::cout << "]"; } void PrintBox(const Box<size_t> &box) noexcept { std::cout << "{" << box.first << "," << box.second << "}"; } void PrintDims(const Dims &dims) noexcept { std::cout << "{"; for (int i = 0; i < dims.size(); i++) { std::cout << dims[i]; if (i < dims.size() - 1) std::cout << ","; } std::cout << "}"; } } // end namespace insitumpi } // end namespace adios2 <commit_msg>Fix uninitialized variable<commit_after>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * InSituMPISchedules.cpp * common functions for in situ MPI Writer and Reader * It requires MPI * * Created on: Dec 25, 2017 * Author: Norbert Podhorszki pnorbert@ornl.gov */ #include "InSituMPISchedules.h" #include "adios2/helper/adiosMath.h" #include "adios2/helper/adiosMemory.h" #include <iostream> namespace adios2 { namespace insitumpi { int GetNumberOfRequests( const std::map<std::string, SubFileInfoMap> &variablesSubFileInfo) noexcept { int n = 0; for (const auto &variableNamePair : variablesSubFileInfo) { // <writer, <steps, <SubFileInfo>>> for (const auto &subFileIndexPair : variableNamePair.second) { // <steps, <SubFileInfo>> but there is only one step for (const auto &stepPair : subFileIndexPair.second) { // <SubFileInfo> for (const auto &sfi : stepPair.second) { n++; } } } } return n; } int FixSeeksToZeroOffset( std::map<std::string, SubFileInfoMap> &variablesSubFileInfo) noexcept { int n = 0; for (auto &variableNamePair : variablesSubFileInfo) { // <writer, <steps, <SubFileInfo>>> for (auto &subFileIndexPair : variableNamePair.second) { // <steps, <SubFileInfo>> but there is only one step for (auto &stepPair : subFileIndexPair.second) { // <SubFileInfo> for (auto &sfi : stepPair.second) { FixSeeksToZeroOffset(sfi); n++; } } } } return n; } void FixSeeksToZeroOffset(SubFileInfo &record) noexcept { size_t nElements = record.Seeks.second - record.Seeks.first + 1; size_t pos = LinearIndex(record.BlockBox, record.IntersectionBox.first, true); record.Seeks.first = pos; record.Seeks.second = pos + nElements - 1; } std::vector<std::vector<char>> SerializeLocalReadSchedule( const int nWriters, const std::map<std::string, SubFileInfoMap> &variablesSubFileInfo) noexcept { std::vector<std::vector<char>> buffers(nWriters); // Create a buffer for each writer std::vector<int> nVarPerWriter(nWriters); for (size_t i = 0; i < nWriters; i++) { nVarPerWriter[i] = 0; InsertToBuffer(buffers[i], &nVarPerWriter[i], 1); // allocate first 4 bytes } for (const auto &variableNamePair : variablesSubFileInfo) { const std::string variableName(variableNamePair.first); // <writer, <steps, <SubFileInfo>>> for (const auto &subFileIndexPair : variableNamePair.second) { const size_t subFileIndex = subFileIndexPair.first; // writer auto &lrs = buffers[subFileIndex]; // <steps, <SubFileInfo>> but there is only one step for (const auto &stepPair : subFileIndexPair.second) { // LocalReadSchedule sfi = subFileIndexPair.second[0]; const std::vector<SubFileInfo> &sfi = stepPair.second; SerializeLocalReadSchedule(buffers[subFileIndex], variableName, sfi); ++nVarPerWriter[subFileIndex]; break; // there is only one step here } } } // Record the number of actually requested variables for each buffer for (int i = 0; i < nWriters; i++) { size_t pos = 0; CopyToBuffer(buffers[i], pos, &nVarPerWriter[i]); } return buffers; } void SerializeLocalReadSchedule(std::vector<char> &buffer, const std::string varName, const LocalReadSchedule lrs) noexcept { const int nameLen = varName.size(); InsertToBuffer(buffer, &nameLen, 1); InsertToBuffer(buffer, varName.data(), nameLen); const int nSubFileInfos = lrs.size(); InsertToBuffer(buffer, &nSubFileInfos, 1); for (const auto &blockInfo : lrs) { SerializeSubFileInfo(buffer, blockInfo); } } void SerializeSubFileInfo(std::vector<char> &buffer, const SubFileInfo record) noexcept { SerializeBox(buffer, record.BlockBox); SerializeBox(buffer, record.IntersectionBox); SerializeBox(buffer, record.Seeks); } void SerializeBox(std::vector<char> &buffer, const Box<Dims> box) noexcept { const int nDims = box.first.size(); InsertToBuffer(buffer, &nDims, 1); InsertToBuffer(buffer, box.first.data(), nDims); InsertToBuffer(buffer, box.second.data(), nDims); } void SerializeBox(std::vector<char> &buffer, const Box<size_t> box) noexcept { InsertToBuffer(buffer, &box.first, 1); InsertToBuffer(buffer, &box.second, 1); } int GetNumberOfRequestsInWriteScheduleMap(WriteScheduleMap &map) noexcept { int n = 0; //<variable <reader, <SubFileInfo>>> for (auto &variableNamePair : map) { // <reader, <SubFileInfo>> for (auto &readerPair : variableNamePair.second) { // <SubFileInfo> for (auto &sfi : readerPair.second) { n++; } } } return n; } WriteScheduleMap DeserializeReadSchedule(const std::vector<std::vector<char>> &buffers) noexcept { WriteScheduleMap map; for (int i = 0; i < buffers.size(); i++) { const auto &buffer = buffers[i]; LocalReadScheduleMap lrsm = DeserializeReadSchedule(buffer); for (const auto &varSchedule : lrsm) { map[varSchedule.first][i] = varSchedule.second; } } return map; } LocalReadScheduleMap DeserializeReadSchedule(const std::vector<char> &buffer) noexcept { LocalReadScheduleMap map; size_t pos = 0; int nVars = ReadValue<int>(buffer, pos); for (int i = 0; i < nVars; i++) { int nameLen = ReadValue<int>(buffer, pos); char name[nameLen + 1]; CopyFromBuffer(buffer, pos, name, nameLen); name[nameLen] = '\0'; int nSubFileInfos = ReadValue<int>(buffer, pos); std::vector<SubFileInfo> sfis; sfis.reserve(nSubFileInfos); for (int j = 0; j < nSubFileInfos; j++) { sfis.push_back(DeserializeSubFileInfo(buffer, pos)); } map[name] = sfis; } return map; } SubFileInfo DeserializeSubFileInfo(const std::vector<char> &buffer, size_t &position) noexcept { SubFileInfo record; record.BlockBox = DeserializeBoxDims(buffer, position); record.IntersectionBox = DeserializeBoxDims(buffer, position); record.Seeks = DeserializeBoxSizet(buffer, position); return record; } Box<Dims> DeserializeBoxDims(const std::vector<char> &buffer, size_t &position) noexcept { Box<Dims> box; int nDims = ReadValue<int>(buffer, position); std::vector<size_t> start(nDims); std::vector<size_t> count(nDims); CopyFromBuffer(buffer, position, start.data(), nDims); CopyFromBuffer(buffer, position, count.data(), nDims); return Box<Dims>(start, count); } Box<size_t> DeserializeBoxSizet(const std::vector<char> &buffer, size_t &position) noexcept { size_t first, second; CopyFromBuffer(buffer, position, &first, 1); CopyFromBuffer(buffer, position, &second, 1); return Box<size_t>(first, second); } void PrintReadScheduleMap(const WriteScheduleMap &map) noexcept { // <variableName, <reader, <SubFileInfo>>> for (const auto &variableNamePair : map) { std::cout << "{ var = " << variableNamePair.first << " "; // <reader, <SubFileInfo>> for (const auto &readerPair : variableNamePair.second) { const size_t readerRank = readerPair.first; std::cout << "{ reader = " << readerPair.first << " "; const std::vector<SubFileInfo> &sfis = readerPair.second; for (const auto &sfi : sfis) { std::cout << "<"; PrintSubFileInfo(sfi); std::cout << "> "; } std::cout << "} "; } std::cout << "} "; } } void PrintSubFileInfo(const SubFileInfo &sfi) noexcept { std::cout << "(block="; PrintBox(sfi.BlockBox); std::cout << ", intersection="; PrintBox(sfi.IntersectionBox); std::cout << ", seeks="; PrintBox(sfi.Seeks); std::cout << ")"; } void PrintBox(const Box<Dims> &box) noexcept { std::cout << "["; PrintDims(box.first); std::cout << ","; PrintDims(box.second); std::cout << "]"; } void PrintBox(const Box<size_t> &box) noexcept { std::cout << "{" << box.first << "," << box.second << "}"; } void PrintDims(const Dims &dims) noexcept { std::cout << "{"; for (int i = 0; i < dims.size(); i++) { std::cout << dims[i]; if (i < dims.size() - 1) std::cout << ","; } std::cout << "}"; } } // end namespace insitumpi } // end namespace adios2 <|endoftext|>
<commit_before>#include "SuffixMatchManager.hpp" #include <document-manager/DocumentManager.h> #include <boost/filesystem.hpp> #include <glog/logging.h> namespace sf1r { SuffixMatchManager::SuffixMatchManager( const std::string& homePath, const std::string& property, boost::shared_ptr<DocumentManager>& document_manager) : fm_index_path_(homePath + "/" + property + ".fm_idx") , property_(property) , document_manager_(document_manager) , fmi_(new FMIndexType(32)) { if (!boost::filesystem::exists(homePath)) { boost::filesystem::create_directories(homePath); } else { std::ifstream ifs(fm_index_path_.c_str()); if (ifs) fmi_->load(ifs); } } SuffixMatchManager::~SuffixMatchManager() { } void SuffixMatchManager::buildCollection() { FMIndexType* new_fmi = new FMIndexType(32); size_t last_docid = fmi_->docCount(); if (last_docid) { std::vector<uint16_t> orig_text; std::vector<uint32_t> del_docid_list; document_manager_->getDeletedDocIdList(del_docid_list); fmi_->reconstructText(del_docid_list, orig_text); new_fmi->setOrigText(orig_text); } for (size_t i = last_docid + 1; i <= document_manager_->getMaxDocId(); ++i) { if (i % 100000 == 0) { LOG(INFO) << "inserted docs: " << i; } Document doc; document_manager_->getDocument(i, doc); Document::property_const_iterator it = doc.findProperty(property_); if (it == doc.propertyEnd()) { new_fmi->addDoc(NULL, 0); continue; } const izenelib::util::UString& text = it->second.get<UString>(); new_fmi->addDoc(text.data(), text.length()); } LOG(INFO) << "inserted docs: " << document_manager_->getMaxDocId(); LOG(INFO) << "building fm-index"; new_fmi->build(); { WriteLock lock(mutex_); fmi_.reset(new_fmi); } std::ofstream ofs(fm_index_path_.c_str()); fmi_->save(ofs); } size_t SuffixMatchManager::longestSuffixMatch(const izenelib::util::UString& pattern, size_t max_docs, std::vector<uint32_t>& docid_list, std::vector<float>& score_list) const { std::vector<std::pair<size_t, size_t> >match_ranges; std::vector<size_t> doclen_list; size_t max_match; { ReadLock lock(mutex_); if ((max_match = fmi_->longestSuffixMatch(pattern.data(), pattern.length(), match_ranges)) == 0) return 0; fmi_->getMatchedDocIdList(match_ranges, max_docs, docid_list, doclen_list); } score_list.resize(doclen_list.size()); for (size_t i = 0; i < doclen_list.size(); ++i) { score_list[i] = float(max_match) / float(doclen_list[i]); } size_t total_match = 0; for (size_t i = 0; i < match_ranges.size(); ++i) { total_match += match_ranges[i].second - match_ranges[i].first; } return total_match; } } <commit_msg>fix segfault<commit_after>#include "SuffixMatchManager.hpp" #include <document-manager/DocumentManager.h> #include <boost/filesystem.hpp> #include <glog/logging.h> namespace sf1r { SuffixMatchManager::SuffixMatchManager( const std::string& homePath, const std::string& property, boost::shared_ptr<DocumentManager>& document_manager) : fm_index_path_(homePath + "/" + property + ".fm_idx") , property_(property) , document_manager_(document_manager) , fmi_(new FMIndexType(32)) { if (!boost::filesystem::exists(homePath)) { boost::filesystem::create_directories(homePath); } else { std::ifstream ifs(fm_index_path_.c_str()); if (ifs) fmi_->load(ifs); } } SuffixMatchManager::~SuffixMatchManager() { } void SuffixMatchManager::buildCollection() { FMIndexType* new_fmi = new FMIndexType(32); size_t last_docid = fmi_->docCount(); if (last_docid) { std::vector<uint16_t> orig_text; std::vector<uint32_t> del_docid_list; document_manager_->getDeletedDocIdList(del_docid_list); fmi_->reconstructText(del_docid_list, orig_text); new_fmi->setOrigText(orig_text); } for (size_t i = last_docid + 1; i <= document_manager_->getMaxDocId(); ++i) { if (i % 100000 == 0) { LOG(INFO) << "inserted docs: " << i; } Document doc; document_manager_->getDocument(i, doc); Document::property_const_iterator it = doc.findProperty(property_); if (it == doc.propertyEnd()) { new_fmi->addDoc(NULL, 0); continue; } const izenelib::util::UString& text = it->second.get<UString>(); new_fmi->addDoc(text.data(), text.length()); } LOG(INFO) << "inserted docs: " << document_manager_->getMaxDocId(); LOG(INFO) << "building fm-index"; new_fmi->build(); { WriteLock lock(mutex_); fmi_.reset(new_fmi); } std::ofstream ofs(fm_index_path_.c_str()); fmi_->save(ofs); } size_t SuffixMatchManager::longestSuffixMatch(const izenelib::util::UString& pattern, size_t max_docs, std::vector<uint32_t>& docid_list, std::vector<float>& score_list) const { if (!fmi_) return 0; std::vector<std::pair<size_t, size_t> >match_ranges; std::vector<size_t> doclen_list; size_t max_match; { ReadLock lock(mutex_); if ((max_match = fmi_->longestSuffixMatch(pattern.data(), pattern.length(), match_ranges)) == 0) return 0; fmi_->getMatchedDocIdList(match_ranges, max_docs, docid_list, doclen_list); } score_list.resize(doclen_list.size()); for (size_t i = 0; i < doclen_list.size(); ++i) { score_list[i] = float(max_match) / float(doclen_list[i]); } size_t total_match = 0; for (size_t i = 0; i < match_ranges.size(); ++i) { total_match += match_ranges[i].second - match_ranges[i].first; } return total_match; } } <|endoftext|>
<commit_before>#include <GL/glew.h> #include <GLFW/glfw3.h> #define GLM_FORCE_RADIANS #include <glm/glm.hpp> #include <iostream> #include <iomanip> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <nanovg.h> #define NANOVG_GL3_IMPLEMENTATION #include <nanovg_gl.h> #include "gfx/Renderer.hpp" #include "gfx/SceneGraph.hpp" #include "gfx/Entity.hpp" #include "gfx/VertexArray.hpp" #include "gfx/SkyBox.hpp" #include "gfx/importer/ObjLoader.hpp" #include "gfx/lights/Light.hpp" #include "gfx/lights/PointLight.hpp" #include "gfx/lights/DirLight.hpp" #include "gfx/shader/SimpleShader.hpp" #include "input/Actions.hpp" #include "input/Input.hpp" #include "ui/DebugText.hpp" #include "DebugUtils.h" void glDebugCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *msg, void *data) { std::cout << "debug call: " << msg << std::endl; } glm::vec3 get_random_color() { auto r = ((rand() % 100)/100.0); auto g = ((rand() % 100)/100.0); auto b = ((rand() % 100)/100.0); return glm::normalize(glm::vec3{r, g, b}); } glm::vec3 pos; glm::vec3 scale; std::vector<std::pair<glm::vec3, glm::vec3>> rain; void draw_rain(Renderer* r) { static float speed = 0.75; //if((rand() % 100)/100.0 < 0.5) { //for(int i = 0; i < 5; i++) { { auto x = ((rand() % 100)/100.0) * -34 + 14; auto y = 22 + pos.y; auto z = ((rand() % 100)/100.0) * -10 + 3.1; glm::vec3 from = glm::vec3(x,y,z); glm::vec3 to = from + glm::vec3{5, -16, 5}; rain.push_back(std::make_pair(from, to)); } std::vector<std::pair<glm::vec3, glm::vec3>> new_rain; for(auto& rain_pos: rain) { auto& from = std::get<0>(rain_pos); auto& to = std::get<1>(rain_pos); auto dir = glm::normalize(to - from); from += dir * speed; to += dir * speed; if(from.y > 0) { new_rain.push_back(rain_pos); } } r->draw_lines(rain, {0.1, 0.1, 0.1}); rain = new_rain; } static void error_callback(int error, const char* description) { fputs(description, stderr); } float step = 0.01f; int selected_light = -1; static void scroll_callback(GLFWwindow* window, double x_offset, double y_offset) { step = fmax(0.01f, fmin(step * pow(1.5, y_offset), 5)); } double target_x = 0; double target_y = 0; double current_x = 0; double current_y = 0; double MOUSE_X_SENSITIVITY = 20; double MOUSE_Y_SENSITIVITY = 20; double PANNING_SPEED = 15; void rotate_camera(Camera& camera) { if(Input::is_mouse_locked()) { const auto x = Input::get_mouse_dx() / MOUSE_X_SENSITIVITY; const auto y = Input::get_mouse_dy() / MOUSE_Y_SENSITIVITY; target_x += x; target_y += y; auto dx = (target_x - current_x) / PANNING_SPEED; auto dy = (target_y - current_y) / PANNING_SPEED; if(fabs(dx) < 0.001 && fabs(dy) < 0.001) { return; } current_x += dx + copysign(0.01, dx); current_y += dy + copysign(0.01, dy); camera.rotate(-dx, camera.up); camera.rotate(dy, glm::cross(camera.up, camera.dir)); } else { target_x = current_x; target_y = current_y; } } int width = 1920; int height = 1080; int main(int argc, char ** argv) { glfwSetErrorCallback(error_callback); if (!glfwInit()) exit(EXIT_FAILURE); bool fullscreen = false; for(int i = 0; i < argc; i++) { //std::cout << argv[i] << "\n"; if(!strcmp(argv[i], "-w")) { width = atoi(argv[i+1]); } if(!strcmp(argv[i], "-h")) { height = atoi(argv[i+1]); } if(!strcmp(argv[i], "-f")) { fullscreen = true; } } std::cout << "w: " << width << "\nheight: " << height << "\n"; glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint( GLFW_OPENGL_DEBUG_CONTEXT, true ); GLFWwindow* window = nullptr; if(fullscreen) { const auto& monitor = glfwGetPrimaryMonitor(); const GLFWvidmode* mode = glfwGetVideoMode(monitor); glfwWindowHint(GLFW_RED_BITS, mode->redBits); glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits); glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits); glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate); window = glfwCreateWindow(mode->width, mode->height, "Hondo", monitor, NULL); } else { window = glfwCreateWindow(width, height, "Hondo", NULL, NULL); } if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); glewExperimental = GL_TRUE; GLenum err = glewInit(); //To discard error 1280 from glewInit(). glGetError(); if(GLEW_OK != err) std::cout << glewGetErrorString(err) << std::endl; { const GLubyte* renderer = glGetString(GL_RENDERER); const GLubyte* version = glGetString(GL_VERSION); printf("Renderer: %s\n", renderer); printf("Version: %s\n", version); glfwSetCursorPosCallback(window, Input::cursor_pos_callback); glfwSetKeyCallback(window, Input::key_callback); glfwSetScrollCallback(window, scroll_callback); Input::set_active_window(window); } Renderer renderer(width, height); struct NVGcontext* vg = nvgCreateGL3(NVG_ANTIALIAS | NVG_DEBUG); glDebugMessageCallback(glDebugCallback, NULL ); auto& camera = renderer.get_camera(); Input::on(Actions::Forward, [&]() { camera.move_forward(step); }); Input::on(Actions::Backward, [&]() { camera.move_forward(-step); }); Input::on(Actions::Left, [&]() { camera.move_right(-step); }); Input::on(Actions::Right, [&]() { camera.move_right(step); }); Input::on(Actions::Up, [&]() { camera.translate({0, step, 0}); }); Input::on(Actions::Down, [&]() { camera.translate({0, -step, 0}); }); Input::on(GLFW_KEY_Z, [&] { renderer.toggle_wireframe(); }); Input::on(GLFW_KEY_G, []() { Input::lock_mouse(); }); ObjLoader loader; loader.preload_file("assets/sponza-minus.obj"); loader.preload_file("assets/Cube.obj"); loader.preload_file("assets/sphere.obj"); loader.preload_file("assets/SkyDome16.obj"); loader.load_files(); Mesh skydome_mesh = loader.get_meshes("assets/SkyDome16.obj")[0]; Mesh cube_mesh = loader.get_meshes("assets/Cube.obj")[0]; Mesh sphere_mesh = loader.get_meshes("assets/sphere.obj")[0]; std::vector<Mesh> sponza_meshes = loader.get_meshes("assets/sponza-minus.obj"); auto pl2 = std::make_shared<DirLight>(glm::vec3{-1, -1, -1}, glm::vec3{1, 1, 1}); pl2->ambient_intensity = 0.15f; //pl2->set_casts_shadow(true); pl2->diffuse_intensity = 0.2f; renderer.add_light(pl2); SceneGraph scene; Entity sponza = scene.create_entity(); for(auto& sponza_mesh: sponza_meshes) { scene.create_entity(sponza, RenderObject(sponza_mesh)); } scene.scale(sponza, {0.05, 0.05, 0.05}); Entity cube = scene.create_entity(RenderObject(cube_mesh)); scene.scale(cube, glm::vec3{0.5, 0.5, 0.5}); scene.translate(cube, glm::vec3{0, 2, 0}); Entity sphere1 = scene.create_entity(cube, RenderObject(sphere_mesh)); scene.translate(sphere1, glm::vec3{2, 0, 0}); Entity sphere2 = scene.create_entity(cube, RenderObject(sphere_mesh)); scene.translate(sphere2, glm::vec3{-2, 0, 0}); Entity sphere3 = scene.create_entity(cube, RenderObject(sphere_mesh)); scene.translate(sphere3, glm::vec3{0, 0, 2}); Entity sphere6 = scene.create_entity(sphere3, RenderObject(sphere_mesh)); scene.translate(sphere6, glm::vec3{0, 2, 0}); scene.scale(sphere6, glm::vec3{0.5, 0.5, 0.5}); Entity sphere4 = scene.create_entity(cube, RenderObject(sphere_mesh)); scene.translate(sphere4, glm::vec3{0, 0, -2}); Entity sphere5 = scene.create_entity(sphere4, RenderObject(sphere_mesh)); scene.translate(sphere5, glm::vec3{0, 2, 0}); scene.scale(sphere5, glm::vec3{0.5, 0.5, 0.5}); renderer.set_skybox(RenderObject(skydome_mesh)); Input::on(GLFW_KEY_I, [&] { renderer.get_shown_light()->translate({ 0.01f, 0, 0}); }, true); Input::on(GLFW_KEY_K, [&] { renderer.get_shown_light()->translate({-0.01f, 0, 0}); }, true); Input::on(GLFW_KEY_J, [&] { renderer.get_shown_light()->translate({0, 0, 0.01f}); }, true); Input::on(GLFW_KEY_L, [&] { renderer.get_shown_light()->translate({0, 0, -0.01f}); }, true); Input::on(GLFW_KEY_O, [&] { renderer.get_shown_light()->translate({0, 0.01f, 0}); }, true); Input::on(GLFW_KEY_U, [&] { renderer.get_shown_light()->translate({0, -0.01f, 0}); }, true); Input::on(GLFW_KEY_PAGE_UP, [&] { if(selected_light < renderer.light_count()) { renderer.show_single_light(++selected_light); } }, false); Input::on(GLFW_KEY_DELETE, [&] { renderer.clear_lights(); }, false); Input::on(GLFW_KEY_PAGE_DOWN, [&] { if(selected_light > 0) { renderer.show_single_light(--selected_light); } }, false); Input::on(GLFW_KEY_1, [&] { renderer.toggle_shadow_map(); }, false); Input::on(GLFW_KEY_P, [&] { if(Input::is_alt_down()) { auto light = std::make_shared<PointLight>(camera.pos, get_random_color()); light->set_casts_shadow(false); light->ambient_intensity = 0.0f; light->diffuse_intensity = 0.2f; renderer.add_light(light); } else { auto light = std::make_shared<SpotLight>(camera.pos, camera.dir, glm::vec3{1,1,1}); light->set_casts_shadow(true); light->ambient_intensity = 0.0f; light->diffuse_intensity = 2.0f; renderer.add_light(light); } std::cout << "Amount of lights: " << renderer.light_count() << "\n"; }, false); Input::on(GLFW_KEY_RIGHT_CONTROL, [&] { renderer.show_single_light(-1); }, false); bool draw_main = true; Input::on(GLFW_KEY_T, [&] { draw_main = !draw_main; }, false); Input::on(GLFW_KEY_Q, [&] { step = fmax(0.01f, fmin(step * pow(1.5, -1), 5)); }, false); Input::on(GLFW_KEY_E, [&] { step = fmax(0.01f, fmin(step * pow(1.5, 1), 5)); }, false); nvgCreateFont(vg, "sans", "/usr/share/fonts/truetype/freefont/FreeSans.ttf"); DebugText::set_context(vg); camera.translate({0, 2, 0}); while (!glfwWindowShouldClose(window)) { glfwPollEvents(); Input::handle_input(); rotate_camera(camera); renderer.render(scene); if(draw_main) { scene.rotate(cube, 0.01, glm::vec3{1, 1, 0}); scene.rotate(sphere1, -0.01, glm::vec3{0, 1, 0}); scene.rotate(sphere2, -0.01, glm::vec3{0, 1, 0}); scene.rotate(sphere3, -0.01, glm::vec3{0, 0, 1}); scene.rotate(sphere4, 0.01, glm::vec3{0, 0, 1}); } std::stringstream str; str << std::fixed << std::setprecision(1) << calcFPS(1.0); DebugText::set_value("fps", str.str().c_str()); nvgBeginFrame(vg, width, height, 1); DebugText::draw(); nvgEndFrame(vg); glfwSwapBuffers(window); Input::reset_delta(); checkForGlError(); } glfwDestroyWindow(window); glfwTerminate(); return 0; } <commit_msg>Changed default screen size, fixed fullscreen<commit_after>#include <GL/glew.h> #include <GLFW/glfw3.h> #define GLM_FORCE_RADIANS #include <glm/glm.hpp> #include <iostream> #include <iomanip> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <nanovg.h> #define NANOVG_GL3_IMPLEMENTATION #include <nanovg_gl.h> #include "gfx/Renderer.hpp" #include "gfx/SceneGraph.hpp" #include "gfx/Entity.hpp" #include "gfx/VertexArray.hpp" #include "gfx/SkyBox.hpp" #include "gfx/importer/ObjLoader.hpp" #include "gfx/lights/Light.hpp" #include "gfx/lights/PointLight.hpp" #include "gfx/lights/DirLight.hpp" #include "gfx/shader/SimpleShader.hpp" #include "input/Actions.hpp" #include "input/Input.hpp" #include "ui/DebugText.hpp" #include "DebugUtils.h" void glDebugCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *msg, void *data) { std::cout << "debug call: " << msg << std::endl; } glm::vec3 get_random_color() { auto r = ((rand() % 100)/100.0); auto g = ((rand() % 100)/100.0); auto b = ((rand() % 100)/100.0); return glm::normalize(glm::vec3{r, g, b}); } glm::vec3 pos; glm::vec3 scale; std::vector<std::pair<glm::vec3, glm::vec3>> rain; void draw_rain(Renderer* r) { static float speed = 0.75; //if((rand() % 100)/100.0 < 0.5) { //for(int i = 0; i < 5; i++) { { auto x = ((rand() % 100)/100.0) * -34 + 14; auto y = 22 + pos.y; auto z = ((rand() % 100)/100.0) * -10 + 3.1; glm::vec3 from = glm::vec3(x,y,z); glm::vec3 to = from + glm::vec3{5, -16, 5}; rain.push_back(std::make_pair(from, to)); } std::vector<std::pair<glm::vec3, glm::vec3>> new_rain; for(auto& rain_pos: rain) { auto& from = std::get<0>(rain_pos); auto& to = std::get<1>(rain_pos); auto dir = glm::normalize(to - from); from += dir * speed; to += dir * speed; if(from.y > 0) { new_rain.push_back(rain_pos); } } r->draw_lines(rain, {0.1, 0.1, 0.1}); rain = new_rain; } static void error_callback(int error, const char* description) { fputs(description, stderr); } float step = 0.01f; int selected_light = -1; static void scroll_callback(GLFWwindow* window, double x_offset, double y_offset) { step = fmax(0.01f, fmin(step * pow(1.5, y_offset), 5)); } double target_x = 0; double target_y = 0; double current_x = 0; double current_y = 0; double MOUSE_X_SENSITIVITY = 20; double MOUSE_Y_SENSITIVITY = 20; double PANNING_SPEED = 15; void rotate_camera(Camera& camera) { if(Input::is_mouse_locked()) { const auto x = Input::get_mouse_dx() / MOUSE_X_SENSITIVITY; const auto y = Input::get_mouse_dy() / MOUSE_Y_SENSITIVITY; target_x += x; target_y += y; auto dx = (target_x - current_x) / PANNING_SPEED; auto dy = (target_y - current_y) / PANNING_SPEED; if(fabs(dx) < 0.001 && fabs(dy) < 0.001) { return; } current_x += dx + copysign(0.01, dx); current_y += dy + copysign(0.01, dy); camera.rotate(-dx, camera.up); camera.rotate(dy, glm::cross(camera.up, camera.dir)); } else { target_x = current_x; target_y = current_y; } } int width = 1024; int height = 768; int main(int argc, char ** argv) { glfwSetErrorCallback(error_callback); if (!glfwInit()) exit(EXIT_FAILURE); bool fullscreen = false; for(int i = 0; i < argc; i++) { //std::cout << argv[i] << "\n"; if(!strcmp(argv[i], "-w")) { width = atoi(argv[i+1]); } if(!strcmp(argv[i], "-h")) { height = atoi(argv[i+1]); } if(!strcmp(argv[i], "-f")) { fullscreen = true; } } std::cout << "w: " << width << "\nheight: " << height << "\n"; glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint( GLFW_OPENGL_DEBUG_CONTEXT, true ); GLFWwindow* window = nullptr; if(fullscreen) { const auto& monitor = glfwGetPrimaryMonitor(); const GLFWvidmode* mode = glfwGetVideoMode(monitor); glfwWindowHint(GLFW_RED_BITS, mode->redBits); glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits); glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits); glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate); glfwWindowHint(GLFW_SAMPLES, 8); window = glfwCreateWindow(mode->width, mode->height, "Hondo", monitor, NULL); width = mode->width; height = mode->height; } else { window = glfwCreateWindow(width, height, "Hondo", NULL, NULL); } if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); glewExperimental = GL_TRUE; GLenum err = glewInit(); //To discard error 1280 from glewInit(). glGetError(); if(GLEW_OK != err) std::cout << glewGetErrorString(err) << std::endl; { const GLubyte* renderer = glGetString(GL_RENDERER); const GLubyte* version = glGetString(GL_VERSION); printf("Renderer: %s\n", renderer); printf("Version: %s\n", version); glfwSetCursorPosCallback(window, Input::cursor_pos_callback); glfwSetKeyCallback(window, Input::key_callback); glfwSetScrollCallback(window, scroll_callback); Input::set_active_window(window); } Renderer renderer(width, height); struct NVGcontext* vg = nvgCreateGL3(NVG_ANTIALIAS | NVG_DEBUG); glDebugMessageCallback(glDebugCallback, NULL ); auto& camera = renderer.get_camera(); Input::on(Actions::Forward, [&]() { camera.move_forward(step); }); Input::on(Actions::Backward, [&]() { camera.move_forward(-step); }); Input::on(Actions::Left, [&]() { camera.move_right(-step); }); Input::on(Actions::Right, [&]() { camera.move_right(step); }); Input::on(Actions::Up, [&]() { camera.translate({0, step, 0}); }); Input::on(Actions::Down, [&]() { camera.translate({0, -step, 0}); }); Input::on(GLFW_KEY_Z, [&] { renderer.toggle_wireframe(); }); Input::on(GLFW_KEY_G, []() { Input::lock_mouse(); }); ObjLoader loader; loader.preload_file("assets/sponza-minus.obj"); loader.preload_file("assets/Cube.obj"); loader.preload_file("assets/sphere.obj"); loader.preload_file("assets/SkyDome16.obj"); loader.load_files(); Mesh skydome_mesh = loader.get_meshes("assets/SkyDome16.obj")[0]; Mesh cube_mesh = loader.get_meshes("assets/Cube.obj")[0]; Mesh sphere_mesh = loader.get_meshes("assets/sphere.obj")[0]; std::vector<Mesh> sponza_meshes = loader.get_meshes("assets/sponza-minus.obj"); auto pl2 = std::make_shared<DirLight>(glm::vec3{-1, -1, -1}, glm::vec3{1, 1, 1}); pl2->ambient_intensity = 0.15f; //pl2->set_casts_shadow(true); pl2->diffuse_intensity = 0.2f; renderer.add_light(pl2); SceneGraph scene; Entity sponza = scene.create_entity(); for(auto& sponza_mesh: sponza_meshes) { scene.create_entity(sponza, RenderObject(sponza_mesh)); } scene.scale(sponza, {0.05, 0.05, 0.05}); Entity cube = scene.create_entity(RenderObject(cube_mesh)); scene.scale(cube, glm::vec3{0.5, 0.5, 0.5}); scene.translate(cube, glm::vec3{0, 2, 0}); Entity sphere1 = scene.create_entity(cube, RenderObject(sphere_mesh)); scene.translate(sphere1, glm::vec3{2, 0, 0}); Entity sphere2 = scene.create_entity(cube, RenderObject(sphere_mesh)); scene.translate(sphere2, glm::vec3{-2, 0, 0}); Entity sphere3 = scene.create_entity(cube, RenderObject(sphere_mesh)); scene.translate(sphere3, glm::vec3{0, 0, 2}); Entity sphere6 = scene.create_entity(sphere3, RenderObject(sphere_mesh)); scene.translate(sphere6, glm::vec3{0, 2, 0}); scene.scale(sphere6, glm::vec3{0.5, 0.5, 0.5}); Entity sphere4 = scene.create_entity(cube, RenderObject(sphere_mesh)); scene.translate(sphere4, glm::vec3{0, 0, -2}); Entity sphere5 = scene.create_entity(sphere4, RenderObject(sphere_mesh)); scene.translate(sphere5, glm::vec3{0, 2, 0}); scene.scale(sphere5, glm::vec3{0.5, 0.5, 0.5}); renderer.set_skybox(RenderObject(skydome_mesh)); Input::on(GLFW_KEY_I, [&] { renderer.get_shown_light()->translate({ 0.01f, 0, 0}); }, true); Input::on(GLFW_KEY_K, [&] { renderer.get_shown_light()->translate({-0.01f, 0, 0}); }, true); Input::on(GLFW_KEY_J, [&] { renderer.get_shown_light()->translate({0, 0, 0.01f}); }, true); Input::on(GLFW_KEY_L, [&] { renderer.get_shown_light()->translate({0, 0, -0.01f}); }, true); Input::on(GLFW_KEY_O, [&] { renderer.get_shown_light()->translate({0, 0.01f, 0}); }, true); Input::on(GLFW_KEY_U, [&] { renderer.get_shown_light()->translate({0, -0.01f, 0}); }, true); Input::on(GLFW_KEY_PAGE_UP, [&] { if(selected_light < renderer.light_count()) { renderer.show_single_light(++selected_light); } }, false); Input::on(GLFW_KEY_DELETE, [&] { renderer.clear_lights(); }, false); Input::on(GLFW_KEY_PAGE_DOWN, [&] { if(selected_light > 0) { renderer.show_single_light(--selected_light); } }, false); Input::on(GLFW_KEY_1, [&] { renderer.toggle_shadow_map(); }, false); Input::on(GLFW_KEY_P, [&] { if(Input::is_alt_down()) { auto light = std::make_shared<PointLight>(camera.pos, get_random_color()); light->set_casts_shadow(false); light->ambient_intensity = 0.0f; light->diffuse_intensity = 0.2f; renderer.add_light(light); } else { auto light = std::make_shared<SpotLight>(camera.pos, camera.dir, glm::vec3{1,1,1}); light->set_casts_shadow(true); light->ambient_intensity = 0.0f; light->diffuse_intensity = 2.0f; renderer.add_light(light); } std::cout << "Amount of lights: " << renderer.light_count() << "\n"; }, false); Input::on(GLFW_KEY_RIGHT_CONTROL, [&] { renderer.show_single_light(-1); }, false); bool draw_main = true; Input::on(GLFW_KEY_T, [&] { draw_main = !draw_main; }, false); Input::on(GLFW_KEY_Q, [&] { step = fmax(0.01f, fmin(step * pow(1.5, -1), 5)); }, false); Input::on(GLFW_KEY_E, [&] { step = fmax(0.01f, fmin(step * pow(1.5, 1), 5)); }, false); nvgCreateFont(vg, "sans", "/usr/share/fonts/truetype/freefont/FreeSans.ttf"); DebugText::set_context(vg); camera.translate({0, 2, 0}); while (!glfwWindowShouldClose(window)) { glfwPollEvents(); Input::handle_input(); rotate_camera(camera); renderer.render(scene); if(draw_main) { scene.rotate(cube, 0.01, glm::vec3{1, 1, 0}); scene.rotate(sphere1, -0.01, glm::vec3{0, 1, 0}); scene.rotate(sphere2, -0.01, glm::vec3{0, 1, 0}); scene.rotate(sphere3, -0.01, glm::vec3{0, 0, 1}); scene.rotate(sphere4, 0.01, glm::vec3{0, 0, 1}); } std::stringstream str; str << std::fixed << std::setprecision(1) << calcFPS(1.0); DebugText::set_value("fps", str.str().c_str()); nvgBeginFrame(vg, width, height, 1); DebugText::draw(); nvgEndFrame(vg); glfwSwapBuffers(window); Input::reset_delta(); checkForGlError(); } glfwDestroyWindow(window); glfwTerminate(); return 0; } <|endoftext|>
<commit_before>#include <algorithm> #include <cassert> #include <chrono> #include <cstddef> #include <cstdint> #include <exception> #include <functional> #include <iostream> #include <memory> #include <random> #include <string> #include "chainerx/array.h" #include "chainerx/array_index.h" #include "chainerx/backprop_mode.h" #include "chainerx/backward.h" #include "chainerx/device_id.h" #include "chainerx/dtype.h" #include "chainerx/routines/creation.h" #include "chainerx/routines/linalg.h" #include "chainerx/routines/manipulation.h" #include "chainerx/routines/math.h" #include "chainerx/shape.h" #include "chainerx/slice.h" #include "mnist.h" chainerx::Array GetRandomArray(std::mt19937& gen, std::normal_distribution<float>& dist, const chainerx::Shape& shape) { int64_t n = shape.GetTotalSize(); std::shared_ptr<float> data{new float[n], std::default_delete<float[]>{}}; std::generate_n(data.get(), n, [&dist, &gen]() { return dist(gen); }); return chainerx::FromContiguousHostData( shape, chainerx::TypeToDtype<float>, static_cast<std::shared_ptr<void>>(data), chainerx::GetDefaultDevice()); } class Model { public: Model(int64_t n_in, int64_t n_hidden, int64_t n_out, int64_t n_layers) : n_in_{n_in}, n_hidden_{n_hidden}, n_out_{n_out}, n_layers_{n_layers} {}; chainerx::Array operator()(const chainerx::Array& x) { chainerx::Array h = x; for (int64_t i = 0; i < n_layers_; ++i) { h = chainerx::Dot(h, params_[i * 2]) + params_[i * 2 + 1]; if (i != n_layers_ - 1) { h = chainerx::Maximum(0, h); } } return h; } const std::vector<chainerx::Array>& params() { return params_; } void Initialize(std::mt19937& gen, std::normal_distribution<float>& dist) { params_.clear(); for (int64_t i = 0; i < n_layers_; ++i) { int64_t n_in = i == 0 ? n_in_ : n_hidden_; int64_t n_out = i == n_layers_ - 1 ? n_out_ : n_hidden_; params_.emplace_back(GetRandomArray(gen, dist, {n_in, n_out})); params_.emplace_back(chainerx::Zeros({n_out}, chainerx::TypeToDtype<float>)); } for (const chainerx::Array& param : params_) { param.RequireGrad(); } } private: int64_t n_in_; int64_t n_hidden_; int64_t n_out_; int64_t n_layers_; std::vector<chainerx::Array> params_; }; chainerx::Array SoftmaxCrossEntropy(const chainerx::Array& y, const chainerx::Array& t, bool normalize = true) { chainerx::Array score = chainerx::LogSoftmax(y, 1); chainerx::Array mask = (t.At({chainerx::Slice{}, chainerx::NewAxis{}}) == chainerx::Arange(score.shape()[1], t.dtype())).AsType(score.dtype()); if (normalize) { return -(score * mask).Sum() / y.shape()[0]; } return -(score * mask).Sum(); } void RunWithDefaultDevice(int64_t epochs, int64_t batch_size, int64_t n_hidden, int64_t n_layers, float lr, const std::string& mnist_root) { // Read the MNIST dataset. chainerx::Array train_x = ReadMnistImages(mnist_root + "train-images-idx3-ubyte"); chainerx::Array train_t = ReadMnistLabels(mnist_root + "train-labels-idx1-ubyte"); chainerx::Array test_x = ReadMnistImages(mnist_root + "t10k-images-idx3-ubyte"); chainerx::Array test_t = ReadMnistLabels(mnist_root + "t10k-labels-idx1-ubyte"); train_x = train_x.AsType(chainerx::Dtype::kFloat32) / 255.f; train_t = train_t.AsType(chainerx::Dtype::kInt32); test_x = test_x.AsType(chainerx::Dtype::kFloat32) / 255.f; test_t = test_t.AsType(chainerx::Dtype::kInt32); int64_t n_train = train_x.shape().front(); int64_t n_test = test_x.shape().front(); chainerx::Array train_indices = chainerx::Arange(n_train, chainerx::Dtype::kInt64); // Initialize the model with random parameters. Model model{train_x.shape()[1], n_hidden, 10, n_layers}; std::random_device rd{}; std::mt19937 gen{rd()}; std::normal_distribution<float> dist{0.f, 0.05f}; model.Initialize(gen, dist); auto start = std::chrono::high_resolution_clock::now(); for (int64_t epoch = 0; epoch < epochs; ++epoch) { // The underlying data of the indices' Array is contiguous so we can use std::shuffle to randomize the order. assert(train_indices.IsContiguous()); std::shuffle( reinterpret_cast<int64_t*>(train_indices.raw_data()), reinterpret_cast<int64_t*>(train_indices.raw_data()) + n_train, gen); for (int64_t i = 0; i < n_train; i += batch_size) { chainerx::Array indices = train_indices.At({chainerx::Slice{i, i + batch_size}}); chainerx::Array x = train_x.Take(indices, 0); chainerx::Array t = train_t.Take(indices, 0); chainerx::Backward(SoftmaxCrossEntropy(model(x), t)); // Vanilla SGD. for (const chainerx::Array& p : model.params()) { chainerx::Array p_as_grad_stopped = p.AsGradStopped(); p_as_grad_stopped -= p.GetGrad()->AsGradStopped() * lr; p.ClearGrad(); } } // Evaluate. { chainerx::NoBackpropModeScope scope{}; chainerx::Array loss = chainerx::Zeros({}, chainerx::Dtype::kFloat32); chainerx::Array acc = chainerx::Zeros({}, chainerx::Dtype::kFloat32); for (int64_t i = 0; i < n_test; i += batch_size) { std::vector<chainerx::ArrayIndex> indices{chainerx::Slice{i, i + batch_size}}; chainerx::Array x = test_x.At(indices); chainerx::Array t = test_t.At(indices); chainerx::Array y = model(x); loss += SoftmaxCrossEntropy(y, t, false); acc += (y.ArgMax(1).AsType(t.dtype()) == t).Sum().AsType(acc.dtype()); } std::cout << "epoch: " << epoch << " loss=" << chainerx::AsScalar(loss / n_test) << " accuracy=" << chainerx::AsScalar(acc / n_test) << " elapsed_time=" << std::chrono::duration<double>{std::chrono::high_resolution_clock::now() - start}.count() << std::endl; } } } int main(int argc, char** argv) { int64_t epochs{20}; int64_t batch_size{100}; int64_t n_hidden{1000}; int64_t n_layers{3}; float lr{0.01}; std::string device_name{"native"}; std::string mnist_root{"./"}; for (int i = 1; i < argc; i += 2) { std::string arg = argv[i]; if (arg == "--epoch") { epochs = std::atoi(argv[i + 1]); } else if (arg == "--batchsize") { batch_size = std::atoi(argv[i + 1]); } else if (arg == "--n-hidden") { n_hidden = std::atoi(argv[i + 1]); } else if (arg == "--n-layers") { n_layers = std::atoi(argv[i + 1]); } else if (arg == "--lr") { lr = std::atof(argv[i + 1]); } else if (arg == "--device") { device_name = argv[i + 1]; } else if (arg == "--data") { mnist_root = argv[i + 1]; } else { throw std::runtime_error("Unknown argument: " + arg); } } if (mnist_root.back() != '/') { mnist_root += "/"; } chainerx::Context ctx{}; chainerx::SetDefaultContext(&ctx); chainerx::Device& device = ctx.GetDevice(device_name); chainerx::SetDefaultDevice(&device); std::cout << "Epochs: " << epochs << std::endl; std::cout << "Minibatch size: " << batch_size << std::endl; std::cout << "Hidden neurons: " << n_hidden << std::endl; std::cout << "Layers: " << n_layers << std::endl; std::cout << "Learning rate: " << lr << std::endl; std::cout << "Device: " << device.name() << std::endl; std::cout << "MNIST root: " << mnist_root << std::endl; RunWithDefaultDevice(epochs, batch_size, n_hidden, n_layers, lr, mnist_root); } <commit_msg>Align variable names with Python example<commit_after>#include <algorithm> #include <cassert> #include <chrono> #include <cstddef> #include <cstdint> #include <exception> #include <functional> #include <iostream> #include <memory> #include <random> #include <string> #include "chainerx/array.h" #include "chainerx/array_index.h" #include "chainerx/backprop_mode.h" #include "chainerx/backward.h" #include "chainerx/device_id.h" #include "chainerx/dtype.h" #include "chainerx/routines/creation.h" #include "chainerx/routines/linalg.h" #include "chainerx/routines/manipulation.h" #include "chainerx/routines/math.h" #include "chainerx/shape.h" #include "chainerx/slice.h" #include "mnist.h" chainerx::Array GetRandomArray(std::mt19937& gen, std::normal_distribution<float>& dist, const chainerx::Shape& shape) { int64_t n = shape.GetTotalSize(); std::shared_ptr<float> data{new float[n], std::default_delete<float[]>{}}; std::generate_n(data.get(), n, [&dist, &gen]() { return dist(gen); }); return chainerx::FromContiguousHostData( shape, chainerx::TypeToDtype<float>, static_cast<std::shared_ptr<void>>(data), chainerx::GetDefaultDevice()); } class Model { public: Model(int64_t n_in, int64_t n_hidden, int64_t n_out, int64_t n_layers) : n_in_{n_in}, n_hidden_{n_hidden}, n_out_{n_out}, n_layers_{n_layers} {}; chainerx::Array operator()(const chainerx::Array& x) { chainerx::Array h = x; for (int64_t i = 0; i < n_layers_; ++i) { h = chainerx::Dot(h, params_[i * 2]) + params_[i * 2 + 1]; if (i != n_layers_ - 1) { h = chainerx::Maximum(0, h); } } return h; } const std::vector<chainerx::Array>& params() { return params_; } void Initialize(std::mt19937& gen, std::normal_distribution<float>& dist) { params_.clear(); for (int64_t i = 0; i < n_layers_; ++i) { int64_t n_in = i == 0 ? n_in_ : n_hidden_; int64_t n_out = i == n_layers_ - 1 ? n_out_ : n_hidden_; params_.emplace_back(GetRandomArray(gen, dist, {n_in, n_out})); params_.emplace_back(chainerx::Zeros({n_out}, chainerx::TypeToDtype<float>)); } for (const chainerx::Array& param : params_) { param.RequireGrad(); } } private: int64_t n_in_; int64_t n_hidden_; int64_t n_out_; int64_t n_layers_; std::vector<chainerx::Array> params_; }; chainerx::Array SoftmaxCrossEntropy(const chainerx::Array& y, const chainerx::Array& t, bool normalize = true) { chainerx::Array score = chainerx::LogSoftmax(y, 1); chainerx::Array mask = (t.At({chainerx::Slice{}, chainerx::NewAxis{}}) == chainerx::Arange(score.shape()[1], t.dtype())).AsType(score.dtype()); if (normalize) { return -(score * mask).Sum() / y.shape()[0]; } return -(score * mask).Sum(); } void RunWithDefaultDevice(int64_t epochs, int64_t batch_size, int64_t n_hidden, int64_t n_layers, float lr, const std::string& mnist_root) { // Read the MNIST dataset. chainerx::Array train_x = ReadMnistImages(mnist_root + "train-images-idx3-ubyte"); chainerx::Array train_t = ReadMnistLabels(mnist_root + "train-labels-idx1-ubyte"); chainerx::Array test_x = ReadMnistImages(mnist_root + "t10k-images-idx3-ubyte"); chainerx::Array test_t = ReadMnistLabels(mnist_root + "t10k-labels-idx1-ubyte"); train_x = train_x.AsType(chainerx::Dtype::kFloat32) / 255.f; train_t = train_t.AsType(chainerx::Dtype::kInt32); test_x = test_x.AsType(chainerx::Dtype::kFloat32) / 255.f; test_t = test_t.AsType(chainerx::Dtype::kInt32); int64_t n_train = train_x.shape().front(); int64_t n_test = test_x.shape().front(); chainerx::Array train_indices = chainerx::Arange(n_train, chainerx::Dtype::kInt64); // Initialize the model with random parameters. Model model{train_x.shape()[1], n_hidden, 10, n_layers}; std::random_device rd{}; std::mt19937 gen{rd()}; std::normal_distribution<float> dist{0.f, 0.05f}; model.Initialize(gen, dist); auto start = std::chrono::high_resolution_clock::now(); for (int64_t epoch = 0; epoch < epochs; ++epoch) { // The underlying data of the indices' Array is contiguous so we can use std::shuffle to randomize the order. assert(train_indices.IsContiguous()); std::shuffle( reinterpret_cast<int64_t*>(train_indices.raw_data()), reinterpret_cast<int64_t*>(train_indices.raw_data()) + n_train, gen); for (int64_t i = 0; i < n_train; i += batch_size) { chainerx::Array indices = train_indices.At({chainerx::Slice{i, i + batch_size}}); chainerx::Array x = train_x.Take(indices, 0); chainerx::Array t = train_t.Take(indices, 0); chainerx::Backward(SoftmaxCrossEntropy(model(x), t)); // Vanilla SGD. for (const chainerx::Array& param : model.params()) { chainerx::Array p = param.AsGradStopped(); p -= param.GetGrad()->AsGradStopped() * lr; param.ClearGrad(); } } // Evaluate. { chainerx::NoBackpropModeScope scope{}; chainerx::Array loss = chainerx::Zeros({}, chainerx::Dtype::kFloat32); chainerx::Array acc = chainerx::Zeros({}, chainerx::Dtype::kFloat32); for (int64_t i = 0; i < n_test; i += batch_size) { std::vector<chainerx::ArrayIndex> indices{chainerx::Slice{i, i + batch_size}}; chainerx::Array x = test_x.At(indices); chainerx::Array t = test_t.At(indices); chainerx::Array y = model(x); loss += SoftmaxCrossEntropy(y, t, false); acc += (y.ArgMax(1).AsType(t.dtype()) == t).Sum().AsType(acc.dtype()); } std::cout << "epoch: " << epoch << " loss=" << chainerx::AsScalar(loss / n_test) << " accuracy=" << chainerx::AsScalar(acc / n_test) << " elapsed_time=" << std::chrono::duration<double>{std::chrono::high_resolution_clock::now() - start}.count() << std::endl; } } } int main(int argc, char** argv) { int64_t epochs{20}; int64_t batch_size{100}; int64_t n_hidden{1000}; int64_t n_layers{3}; float lr{0.01}; std::string device_name{"native"}; std::string mnist_root{"./"}; for (int i = 1; i < argc; i += 2) { std::string arg = argv[i]; if (arg == "--epoch") { epochs = std::atoi(argv[i + 1]); } else if (arg == "--batchsize") { batch_size = std::atoi(argv[i + 1]); } else if (arg == "--unit") { n_hidden = std::atoi(argv[i + 1]); } else if (arg == "--layer") { n_layers = std::atoi(argv[i + 1]); } else if (arg == "--lr") { lr = std::atof(argv[i + 1]); } else if (arg == "--device") { device_name = argv[i + 1]; } else if (arg == "--data") { mnist_root = argv[i + 1]; } else { throw std::runtime_error("Unknown argument: " + arg); } } if (mnist_root.back() != '/') { mnist_root += "/"; } chainerx::Context ctx{}; chainerx::SetDefaultContext(&ctx); chainerx::Device& device = ctx.GetDevice(device_name); chainerx::SetDefaultDevice(&device); std::cout << "Epochs: " << epochs << std::endl; std::cout << "Minibatch size: " << batch_size << std::endl; std::cout << "Hidden neurons: " << n_hidden << std::endl; std::cout << "Layers: " << n_layers << std::endl; std::cout << "Learning rate: " << lr << std::endl; std::cout << "Device: " << device.name() << std::endl; std::cout << "MNIST root: " << mnist_root << std::endl; RunWithDefaultDevice(epochs, batch_size, n_hidden, n_layers, lr, mnist_root); } <|endoftext|>
<commit_before>#include "foo_musicbrainz.h" #include "Metadata.h" #include "Release.h" #include "RequestThread.h" using namespace foo_musicbrainz; RequestThread::RequestThread(Query *query, HWND window, ReleaseList *mbc) : query(query), window(window), mbc(mbc) {} // TODO: abort checks, progress void RequestThread::run(threaded_process_status &p_status, abort_callback &p_abort) { try { Metadata *metadata = query->perform(); auto release = metadata->extract_release(); delete metadata; if (release == nullptr) { throw NotFound(); } mbc->add(release); ShowWindow(window, SW_SHOW); } catch (exception_aborted) { PostMessage(window, WM_CLOSE, 0, 0); } catch (GenericException e) { PostMessage(window, WM_CLOSE, 0, 0); popup_message::g_show(e.what(), COMPONENT_TITLE, popup_message::icon_error); } delete query; } <commit_msg>RequestThread: releases are now collected from all the possible XML locations<commit_after>#include "foo_musicbrainz.h" #include "Metadata.h" #include "Release.h" #include "RequestThread.h" using namespace foo_musicbrainz; RequestThread::RequestThread(Query *query, HWND window, ReleaseList *mbc) : query(query), window(window), mbc(mbc) {} // TODO: abort checks, progress void RequestThread::run(threaded_process_status &p_status, abort_callback &p_abort) { try { // Extracting releases from all possible locations: // /metadata/release // /metadata/release-list/release // /metadata/discid/release-list/release auto metadata = query->perform(); auto release = metadata->extract_release(); if (release != nullptr) { mbc->add(release); } else { auto release_list = metadata->get_release_list(); if (release_list == nullptr) { auto discid = metadata->get_discid(); if (discid != nullptr) { release_list = discid->get_release_list(); } } if (release_list != nullptr) { while (release_list->count() > 0) { mbc->add(release_list->extract(0)); } } } delete metadata; if (mbc->count() == 0) { throw NotFound(); } ShowWindow(window, SW_SHOW); } catch (exception_aborted) { PostMessage(window, WM_CLOSE, 0, 0); } catch (GenericException e) { PostMessage(window, WM_CLOSE, 0, 0); popup_message::g_show(e.what(), COMPONENT_TITLE, popup_message::icon_error); } delete query; } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/autofill/autofill_download.h" #include <algorithm> #include <ostream> #include <vector> #include "base/logging.h" #include "base/rand_util.h" #include "base/stl_util.h" #include "base/string_util.h" #include "chrome/browser/autofill/autofill_metrics.h" #include "chrome/browser/autofill/autofill_xml_parser.h" #include "chrome/browser/autofill/form_structure.h" #include "chrome/browser/api/prefs/pref_service_base.h" #include "chrome/common/pref_names.h" #include "content/public/browser/browser_context.h" #include "googleurl/src/gurl.h" #include "net/base/load_flags.h" #include "net/http/http_response_headers.h" #include "net/url_request/url_fetcher.h" #include "third_party/libjingle/source/talk/xmllite/xmlparser.h" using content::BrowserContext; namespace { const char kAutofillQueryServerRequestUrl[] = "https://clients1.google.com/tbproxy/af/query?client="; const char kAutofillUploadServerRequestUrl[] = "https://clients1.google.com/tbproxy/af/upload?client="; const char kAutofillQueryServerNameStartInHeader[] = "GFE/"; #if defined(GOOGLE_CHROME_BUILD) const char kClientName[] = "Google Chrome"; #else const char kClientName[] = "Chromium"; #endif // defined(GOOGLE_CHROME_BUILD) const size_t kMaxFormCacheSize = 16; }; struct AutofillDownloadManager::FormRequestData { std::vector<std::string> form_signatures; AutofillRequestType request_type; }; AutofillDownloadManager::AutofillDownloadManager(BrowserContext* context, Observer* observer) : browser_context_(context), observer_(observer), max_form_cache_size_(kMaxFormCacheSize), next_query_request_(base::Time::Now()), next_upload_request_(base::Time::Now()), positive_upload_rate_(0), negative_upload_rate_(0), fetcher_id_for_unittest_(0) { DCHECK(observer_); PrefServiceBase* preferences = PrefServiceBase::FromBrowserContext(browser_context_); positive_upload_rate_ = preferences->GetDouble(prefs::kAutofillPositiveUploadRate); negative_upload_rate_ = preferences->GetDouble(prefs::kAutofillNegativeUploadRate); } AutofillDownloadManager::~AutofillDownloadManager() { STLDeleteContainerPairFirstPointers(url_fetchers_.begin(), url_fetchers_.end()); } bool AutofillDownloadManager::StartQueryRequest( const std::vector<FormStructure*>& forms, const AutofillMetrics& metric_logger) { if (next_query_request_ > base::Time::Now()) { // We are in back-off mode: do not do the request. return false; } std::string form_xml; FormRequestData request_data; if (!FormStructure::EncodeQueryRequest(forms, &request_data.form_signatures, &form_xml)) { return false; } request_data.request_type = AutofillDownloadManager::REQUEST_QUERY; metric_logger.LogServerQueryMetric(AutofillMetrics::QUERY_SENT); std::string query_data; if (CheckCacheForQueryRequest(request_data.form_signatures, &query_data)) { DVLOG(1) << "AutofillDownloadManager: query request has been retrieved from" << "the cache"; observer_->OnLoadedServerPredictions(query_data); return true; } return StartRequest(form_xml, request_data); } bool AutofillDownloadManager::StartUploadRequest( const FormStructure& form, bool form_was_autofilled, const FieldTypeSet& available_field_types) { if (next_upload_request_ > base::Time::Now()) { // We are in back-off mode: do not do the request. DVLOG(1) << "AutofillDownloadManager: Upload request is throttled."; return false; } // Flip a coin to see if we should upload this form. double upload_rate = form_was_autofilled ? GetPositiveUploadRate() : GetNegativeUploadRate(); if (form.upload_required() == UPLOAD_NOT_REQUIRED || (form.upload_required() == USE_UPLOAD_RATES && base::RandDouble() > upload_rate)) { DVLOG(1) << "AutofillDownloadManager: Upload request is ignored."; // If we ever need notification that upload was skipped, add it here. return false; } std::string form_xml; if (!form.EncodeUploadRequest(available_field_types, form_was_autofilled, &form_xml)) return false; FormRequestData request_data; request_data.form_signatures.push_back(form.FormSignature()); request_data.request_type = AutofillDownloadManager::REQUEST_UPLOAD; return StartRequest(form_xml, request_data); } double AutofillDownloadManager::GetPositiveUploadRate() const { return positive_upload_rate_; } double AutofillDownloadManager::GetNegativeUploadRate() const { return negative_upload_rate_; } void AutofillDownloadManager::SetPositiveUploadRate(double rate) { if (rate == positive_upload_rate_) return; positive_upload_rate_ = rate; DCHECK_GE(rate, 0.0); DCHECK_LE(rate, 1.0); PrefServiceBase* preferences = PrefServiceBase::FromBrowserContext( browser_context_); preferences->SetDouble(prefs::kAutofillPositiveUploadRate, rate); } void AutofillDownloadManager::SetNegativeUploadRate(double rate) { if (rate == negative_upload_rate_) return; negative_upload_rate_ = rate; DCHECK_GE(rate, 0.0); DCHECK_LE(rate, 1.0); PrefServiceBase* preferences = PrefServiceBase::FromBrowserContext( browser_context_); preferences->SetDouble(prefs::kAutofillNegativeUploadRate, rate); } bool AutofillDownloadManager::StartRequest( const std::string& form_xml, const FormRequestData& request_data) { net::URLRequestContextGetter* request_context = browser_context_->GetRequestContext(); DCHECK(request_context); std::string request_url; if (request_data.request_type == AutofillDownloadManager::REQUEST_QUERY) request_url = kAutofillQueryServerRequestUrl; else request_url = kAutofillUploadServerRequestUrl; request_url += kClientName; // Id is ignored for regular chrome, in unit test id's for fake fetcher // factory will be 0, 1, 2, ... net::URLFetcher* fetcher = net::URLFetcher::Create( fetcher_id_for_unittest_++, GURL(request_url), net::URLFetcher::POST, this); url_fetchers_[fetcher] = request_data; fetcher->SetAutomaticallyRetryOn5xx(false); fetcher->SetRequestContext(request_context); fetcher->SetUploadData("text/plain", form_xml); fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DO_NOT_SEND_COOKIES); fetcher->Start(); return true; } void AutofillDownloadManager::CacheQueryRequest( const std::vector<std::string>& forms_in_query, const std::string& query_data) { std::string signature = GetCombinedSignature(forms_in_query); for (QueryRequestCache::iterator it = cached_forms_.begin(); it != cached_forms_.end(); ++it) { if (it->first == signature) { // We hit the cache, move to the first position and return. std::pair<std::string, std::string> data = *it; cached_forms_.erase(it); cached_forms_.push_front(data); return; } } std::pair<std::string, std::string> data; data.first = signature; data.second = query_data; cached_forms_.push_front(data); while (cached_forms_.size() > max_form_cache_size_) cached_forms_.pop_back(); } bool AutofillDownloadManager::CheckCacheForQueryRequest( const std::vector<std::string>& forms_in_query, std::string* query_data) const { std::string signature = GetCombinedSignature(forms_in_query); for (QueryRequestCache::const_iterator it = cached_forms_.begin(); it != cached_forms_.end(); ++it) { if (it->first == signature) { // We hit the cache, fill the data and return. *query_data = it->second; return true; } } return false; } std::string AutofillDownloadManager::GetCombinedSignature( const std::vector<std::string>& forms_in_query) const { size_t total_size = forms_in_query.size(); for (size_t i = 0; i < forms_in_query.size(); ++i) total_size += forms_in_query[i].length(); std::string signature; signature.reserve(total_size); for (size_t i = 0; i < forms_in_query.size(); ++i) { if (i) signature.append(","); signature.append(forms_in_query[i]); } return signature; } void AutofillDownloadManager::OnURLFetchComplete( const net::URLFetcher* source) { std::map<net::URLFetcher *, FormRequestData>::iterator it = url_fetchers_.find(const_cast<net::URLFetcher*>(source)); if (it == url_fetchers_.end()) { // Looks like crash on Mac is possibly caused with callback entering here // with unknown fetcher when network is refreshed. return; } std::string type_of_request( it->second.request_type == AutofillDownloadManager::REQUEST_QUERY ? "query" : "upload"); const int kHttpResponseOk = 200; const int kHttpInternalServerError = 500; const int kHttpBadGateway = 502; const int kHttpServiceUnavailable = 503; CHECK(it->second.form_signatures.size()); if (source->GetResponseCode() != kHttpResponseOk) { bool back_off = false; std::string server_header; switch (source->GetResponseCode()) { case kHttpBadGateway: if (!source->GetResponseHeaders()->EnumerateHeader(NULL, "server", &server_header) || StartsWithASCII(server_header.c_str(), kAutofillQueryServerNameStartInHeader, false) != 0) break; // Bad gateway was received from Autofill servers. Fall through to back // off. case kHttpInternalServerError: case kHttpServiceUnavailable: back_off = true; break; } if (back_off) { base::Time back_off_time(base::Time::Now() + source->GetBackoffDelay()); if (it->second.request_type == AutofillDownloadManager::REQUEST_QUERY) { next_query_request_ = back_off_time; } else { next_upload_request_ = back_off_time; } } DVLOG(1) << "AutofillDownloadManager: " << type_of_request << " request has failed with response " << source->GetResponseCode(); observer_->OnServerRequestError(it->second.form_signatures[0], it->second.request_type, source->GetResponseCode()); } else { DVLOG(1) << "AutofillDownloadManager: " << type_of_request << " request has succeeded"; std::string response_body; source->GetResponseAsString(&response_body); if (it->second.request_type == AutofillDownloadManager::REQUEST_QUERY) { CacheQueryRequest(it->second.form_signatures, response_body); observer_->OnLoadedServerPredictions(response_body); } else { double new_positive_upload_rate = 0; double new_negative_upload_rate = 0; AutofillUploadXmlParser parse_handler(&new_positive_upload_rate, &new_negative_upload_rate); buzz::XmlParser parser(&parse_handler); parser.Parse(response_body.data(), response_body.length(), true); if (parse_handler.succeeded()) { SetPositiveUploadRate(new_positive_upload_rate); SetNegativeUploadRate(new_negative_upload_rate); } observer_->OnUploadedPossibleFieldTypes(); } } delete it->first; url_fetchers_.erase(it); } <commit_msg>Add logging of autofill upload request.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/autofill/autofill_download.h" #include <algorithm> #include <ostream> #include <vector> #include "base/logging.h" #include "base/rand_util.h" #include "base/stl_util.h" #include "base/string_util.h" #include "chrome/browser/autofill/autofill_metrics.h" #include "chrome/browser/autofill/autofill_xml_parser.h" #include "chrome/browser/autofill/form_structure.h" #include "chrome/browser/api/prefs/pref_service_base.h" #include "chrome/common/pref_names.h" #include "content/public/browser/browser_context.h" #include "googleurl/src/gurl.h" #include "net/base/load_flags.h" #include "net/http/http_response_headers.h" #include "net/url_request/url_fetcher.h" #include "third_party/libjingle/source/talk/xmllite/xmlparser.h" using content::BrowserContext; namespace { const char kAutofillQueryServerRequestUrl[] = "https://clients1.google.com/tbproxy/af/query?client="; const char kAutofillUploadServerRequestUrl[] = "https://clients1.google.com/tbproxy/af/upload?client="; const char kAutofillQueryServerNameStartInHeader[] = "GFE/"; #if defined(GOOGLE_CHROME_BUILD) const char kClientName[] = "Google Chrome"; #else const char kClientName[] = "Chromium"; #endif // defined(GOOGLE_CHROME_BUILD) const size_t kMaxFormCacheSize = 16; // Log the contents of the upload request static void LogUploadRequest(const GURL& url, const std::string& signature, const std::string& form_xml) { VLOG(2) << url; VLOG(2) << signature; VLOG(2) << form_xml; } }; struct AutofillDownloadManager::FormRequestData { std::vector<std::string> form_signatures; AutofillRequestType request_type; }; AutofillDownloadManager::AutofillDownloadManager(BrowserContext* context, Observer* observer) : browser_context_(context), observer_(observer), max_form_cache_size_(kMaxFormCacheSize), next_query_request_(base::Time::Now()), next_upload_request_(base::Time::Now()), positive_upload_rate_(0), negative_upload_rate_(0), fetcher_id_for_unittest_(0) { DCHECK(observer_); PrefServiceBase* preferences = PrefServiceBase::FromBrowserContext(browser_context_); positive_upload_rate_ = preferences->GetDouble(prefs::kAutofillPositiveUploadRate); negative_upload_rate_ = preferences->GetDouble(prefs::kAutofillNegativeUploadRate); } AutofillDownloadManager::~AutofillDownloadManager() { STLDeleteContainerPairFirstPointers(url_fetchers_.begin(), url_fetchers_.end()); } bool AutofillDownloadManager::StartQueryRequest( const std::vector<FormStructure*>& forms, const AutofillMetrics& metric_logger) { if (next_query_request_ > base::Time::Now()) { // We are in back-off mode: do not do the request. return false; } std::string form_xml; FormRequestData request_data; if (!FormStructure::EncodeQueryRequest(forms, &request_data.form_signatures, &form_xml)) { return false; } request_data.request_type = AutofillDownloadManager::REQUEST_QUERY; metric_logger.LogServerQueryMetric(AutofillMetrics::QUERY_SENT); std::string query_data; if (CheckCacheForQueryRequest(request_data.form_signatures, &query_data)) { DVLOG(1) << "AutofillDownloadManager: query request has been retrieved from" << "the cache"; observer_->OnLoadedServerPredictions(query_data); return true; } return StartRequest(form_xml, request_data); } bool AutofillDownloadManager::StartUploadRequest( const FormStructure& form, bool form_was_autofilled, const FieldTypeSet& available_field_types) { if (next_upload_request_ > base::Time::Now()) { // We are in back-off mode: do not do the request. DVLOG(1) << "AutofillDownloadManager: Upload request is throttled."; return false; } // Flip a coin to see if we should upload this form. double upload_rate = form_was_autofilled ? GetPositiveUploadRate() : GetNegativeUploadRate(); if (form.upload_required() == UPLOAD_NOT_REQUIRED || (form.upload_required() == USE_UPLOAD_RATES && base::RandDouble() > upload_rate)) { DVLOG(1) << "AutofillDownloadManager: Upload request is ignored."; // If we ever need notification that upload was skipped, add it here. return false; } std::string form_xml; if (!form.EncodeUploadRequest(available_field_types, form_was_autofilled, &form_xml)) return false; LogUploadRequest(form.source_url(), form.FormSignature(), form_xml); FormRequestData request_data; request_data.form_signatures.push_back(form.FormSignature()); request_data.request_type = AutofillDownloadManager::REQUEST_UPLOAD; return StartRequest(form_xml, request_data); } double AutofillDownloadManager::GetPositiveUploadRate() const { return positive_upload_rate_; } double AutofillDownloadManager::GetNegativeUploadRate() const { return negative_upload_rate_; } void AutofillDownloadManager::SetPositiveUploadRate(double rate) { if (rate == positive_upload_rate_) return; positive_upload_rate_ = rate; DCHECK_GE(rate, 0.0); DCHECK_LE(rate, 1.0); PrefServiceBase* preferences = PrefServiceBase::FromBrowserContext( browser_context_); preferences->SetDouble(prefs::kAutofillPositiveUploadRate, rate); } void AutofillDownloadManager::SetNegativeUploadRate(double rate) { if (rate == negative_upload_rate_) return; negative_upload_rate_ = rate; DCHECK_GE(rate, 0.0); DCHECK_LE(rate, 1.0); PrefServiceBase* preferences = PrefServiceBase::FromBrowserContext( browser_context_); preferences->SetDouble(prefs::kAutofillNegativeUploadRate, rate); } bool AutofillDownloadManager::StartRequest( const std::string& form_xml, const FormRequestData& request_data) { net::URLRequestContextGetter* request_context = browser_context_->GetRequestContext(); DCHECK(request_context); std::string request_url; if (request_data.request_type == AutofillDownloadManager::REQUEST_QUERY) request_url = kAutofillQueryServerRequestUrl; else request_url = kAutofillUploadServerRequestUrl; request_url += kClientName; // Id is ignored for regular chrome, in unit test id's for fake fetcher // factory will be 0, 1, 2, ... net::URLFetcher* fetcher = net::URLFetcher::Create( fetcher_id_for_unittest_++, GURL(request_url), net::URLFetcher::POST, this); url_fetchers_[fetcher] = request_data; fetcher->SetAutomaticallyRetryOn5xx(false); fetcher->SetRequestContext(request_context); fetcher->SetUploadData("text/plain", form_xml); fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DO_NOT_SEND_COOKIES); fetcher->Start(); return true; } void AutofillDownloadManager::CacheQueryRequest( const std::vector<std::string>& forms_in_query, const std::string& query_data) { std::string signature = GetCombinedSignature(forms_in_query); for (QueryRequestCache::iterator it = cached_forms_.begin(); it != cached_forms_.end(); ++it) { if (it->first == signature) { // We hit the cache, move to the first position and return. std::pair<std::string, std::string> data = *it; cached_forms_.erase(it); cached_forms_.push_front(data); return; } } std::pair<std::string, std::string> data; data.first = signature; data.second = query_data; cached_forms_.push_front(data); while (cached_forms_.size() > max_form_cache_size_) cached_forms_.pop_back(); } bool AutofillDownloadManager::CheckCacheForQueryRequest( const std::vector<std::string>& forms_in_query, std::string* query_data) const { std::string signature = GetCombinedSignature(forms_in_query); for (QueryRequestCache::const_iterator it = cached_forms_.begin(); it != cached_forms_.end(); ++it) { if (it->first == signature) { // We hit the cache, fill the data and return. *query_data = it->second; return true; } } return false; } std::string AutofillDownloadManager::GetCombinedSignature( const std::vector<std::string>& forms_in_query) const { size_t total_size = forms_in_query.size(); for (size_t i = 0; i < forms_in_query.size(); ++i) total_size += forms_in_query[i].length(); std::string signature; signature.reserve(total_size); for (size_t i = 0; i < forms_in_query.size(); ++i) { if (i) signature.append(","); signature.append(forms_in_query[i]); } return signature; } void AutofillDownloadManager::OnURLFetchComplete( const net::URLFetcher* source) { std::map<net::URLFetcher *, FormRequestData>::iterator it = url_fetchers_.find(const_cast<net::URLFetcher*>(source)); if (it == url_fetchers_.end()) { // Looks like crash on Mac is possibly caused with callback entering here // with unknown fetcher when network is refreshed. return; } std::string type_of_request( it->second.request_type == AutofillDownloadManager::REQUEST_QUERY ? "query" : "upload"); const int kHttpResponseOk = 200; const int kHttpInternalServerError = 500; const int kHttpBadGateway = 502; const int kHttpServiceUnavailable = 503; CHECK(it->second.form_signatures.size()); if (source->GetResponseCode() != kHttpResponseOk) { bool back_off = false; std::string server_header; switch (source->GetResponseCode()) { case kHttpBadGateway: if (!source->GetResponseHeaders()->EnumerateHeader(NULL, "server", &server_header) || StartsWithASCII(server_header.c_str(), kAutofillQueryServerNameStartInHeader, false) != 0) break; // Bad gateway was received from Autofill servers. Fall through to back // off. case kHttpInternalServerError: case kHttpServiceUnavailable: back_off = true; break; } if (back_off) { base::Time back_off_time(base::Time::Now() + source->GetBackoffDelay()); if (it->second.request_type == AutofillDownloadManager::REQUEST_QUERY) { next_query_request_ = back_off_time; } else { next_upload_request_ = back_off_time; } } DVLOG(1) << "AutofillDownloadManager: " << type_of_request << " request has failed with response " << source->GetResponseCode(); observer_->OnServerRequestError(it->second.form_signatures[0], it->second.request_type, source->GetResponseCode()); } else { DVLOG(1) << "AutofillDownloadManager: " << type_of_request << " request has succeeded"; std::string response_body; source->GetResponseAsString(&response_body); if (it->second.request_type == AutofillDownloadManager::REQUEST_QUERY) { CacheQueryRequest(it->second.form_signatures, response_body); observer_->OnLoadedServerPredictions(response_body); } else { double new_positive_upload_rate = 0; double new_negative_upload_rate = 0; AutofillUploadXmlParser parse_handler(&new_positive_upload_rate, &new_negative_upload_rate); buzz::XmlParser parser(&parse_handler); parser.Parse(response_body.data(), response_body.length(), true); if (parse_handler.succeeded()) { SetPositiveUploadRate(new_positive_upload_rate); SetNegativeUploadRate(new_negative_upload_rate); } observer_->OnUploadedPossibleFieldTypes(); } } delete it->first; url_fetchers_.erase(it); } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/autofill/credit_card_field.h" #include "base/string16.h" #include "chrome/browser/autofill/autofill_field.h" bool CreditCardField::GetFieldInfo(FieldTypeMap* field_type_map) const { return false; } // static CreditCardField* CreditCardField::Parse( std::vector<AutoFillField*>::const_iterator* iter, bool is_ecml) { CreditCardField credit_card_field; std::vector<AutoFillField*>::const_iterator q = *iter; string16 pattern; // Credit card fields can appear in many different orders. for (int fields = 0; q != *iter; ++fields) { // Sometimes the cardholder field is just labeled "name" (e.g. on test page // Starbucks - Credit card.html). Unfortunately this is a dangerously // generic word to search for, since it will often match a name (not // cardholder name) field before or after credit card fields. So we search // for "name" only when we've already parsed at least one other credit card // field and haven't yet parsed the expiration date (which usually appears // at the end). if (credit_card_field.cardholder_ == NULL) { string16 name_pattern; if (is_ecml) { name_pattern = GetEcmlPattern(kEcmlCardHolder); } else { if (fields == 0 || credit_card_field.expiration_month_) { // at beginning or end name_pattern = ASCIIToUTF16("card holder|name on card"); } else { name_pattern = ASCIIToUTF16("name"); } } if (ParseText(&q, name_pattern, &credit_card_field.cardholder_)) { continue; } // As a hard-coded hack for Expedia's billing pages (expedia_checkout.html // and ExpediaBilling.html in our test suite), recognize separate fields // for the cardholder's first and last name if they have the labels "cfnm" // and "clnm". std::vector<AutoFillField*>::const_iterator p = q; AutoFillField* first; if (!is_ecml && ParseText(&p, ASCIIToUTF16("^cfnm"), &first) && ParseText(&p, ASCIIToUTF16("^clnm"), &credit_card_field.cardholder_last_)) { credit_card_field.cardholder_ = first; q = p; continue; } } // TODO(jhawkins): Parse the type select control. // We look for a card security code before we look for a credit card number // and match the general term "number". The security code has a plethora of // names; we've seen "verification #", "verification number", // "card identification number" and others listed in the ParseText() call // below. if (is_ecml) { pattern = GetEcmlPattern(kEcmlCardVerification); } else { pattern = ASCIIToUTF16( "verification|card identification|cvn|security code|cvv code|cvc"); } if (credit_card_field.verification_ == NULL && ParseText(&q, pattern, &credit_card_field.verification_)) { continue; } if (is_ecml) pattern = GetEcmlPattern(kEcmlCardNumber); else pattern = ASCIIToUTF16("number|card #|card no.|card_number"); if (credit_card_field.number_ == NULL && ParseText(&q, pattern, &credit_card_field.number_)) { continue; } // "Expiration date" is the most common label here, but some pages have // "Expires", "exp. date" or "exp. month" and "exp. year". We also look for // the field names ccmonth and ccyear, which appear on at least 4 of our // test pages. // // -> On at least one page (The China Shop2.html) we find only the labels // "month" and "year". So for now we match these words directly; we'll // see if this turns out to be too general. // // Toolbar Bug 51451: indeed, simply matching "month" is too general for // https://rps.fidelity.com/ftgw/rps/RtlCust/CreatePIN/Init. // Instead, we match only words beginning with "month". if (is_ecml) pattern = GetEcmlPattern(kEcmlCardExpireMonth); else pattern = ASCIIToUTF16("expir|exp month|exp date|ccmonth|&month"); if (!credit_card_field.expiration_month_ || credit_card_field.expiration_month_->IsEmpty() && ParseText(&q, pattern, &credit_card_field.expiration_month_)) { if (is_ecml) pattern = GetEcmlPattern(kEcmlCardExpireYear); else pattern = ASCIIToUTF16("|exp|^/|ccyear|year"); if (!ParseText(&q, pattern, &credit_card_field.expiration_year_)) { return NULL; } continue; } if (ParseText(&q, GetEcmlPattern(kEcmlCardExpireDay))) continue; // Some pages (e.g. ExpediaBilling.html) have a "card description" // field; we parse this field but ignore it. ParseText(&q, ASCIIToUTF16("card description")); } // On some pages, the user selects a card type using radio buttons // (e.g. test page Apple Store Billing.html). We can't handle that yet, // so we treat the card type as optional for now. if (credit_card_field.number_ != NULL && credit_card_field.expiration_month_ && !credit_card_field.expiration_month_->IsEmpty()) { *iter = q; return new CreditCardField(credit_card_field); } return NULL; } CreditCardField::CreditCardField() : cardholder_(NULL), cardholder_last_(NULL), type_(NULL), number_(NULL), verification_(NULL), expiration_month_(NULL), expiration_year_(NULL) { } CreditCardField::CreditCardField(const CreditCardField& field) : cardholder_(field.cardholder_), cardholder_last_(field.cardholder_last_), type_(field.type_), number_(field.number_), verification_(field.verification_), expiration_month_(field.expiration_month_), expiration_year_(field.expiration_year_) { } <commit_msg>Fix the ARM build. Clarify the logic with parentheses.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/autofill/credit_card_field.h" #include "base/string16.h" #include "chrome/browser/autofill/autofill_field.h" bool CreditCardField::GetFieldInfo(FieldTypeMap* field_type_map) const { return false; } // static CreditCardField* CreditCardField::Parse( std::vector<AutoFillField*>::const_iterator* iter, bool is_ecml) { CreditCardField credit_card_field; std::vector<AutoFillField*>::const_iterator q = *iter; string16 pattern; // Credit card fields can appear in many different orders. for (int fields = 0; q != *iter; ++fields) { // Sometimes the cardholder field is just labeled "name" (e.g. on test page // Starbucks - Credit card.html). Unfortunately this is a dangerously // generic word to search for, since it will often match a name (not // cardholder name) field before or after credit card fields. So we search // for "name" only when we've already parsed at least one other credit card // field and haven't yet parsed the expiration date (which usually appears // at the end). if (credit_card_field.cardholder_ == NULL) { string16 name_pattern; if (is_ecml) { name_pattern = GetEcmlPattern(kEcmlCardHolder); } else { if (fields == 0 || credit_card_field.expiration_month_) { // at beginning or end name_pattern = ASCIIToUTF16("card holder|name on card"); } else { name_pattern = ASCIIToUTF16("name"); } } if (ParseText(&q, name_pattern, &credit_card_field.cardholder_)) { continue; } // As a hard-coded hack for Expedia's billing pages (expedia_checkout.html // and ExpediaBilling.html in our test suite), recognize separate fields // for the cardholder's first and last name if they have the labels "cfnm" // and "clnm". std::vector<AutoFillField*>::const_iterator p = q; AutoFillField* first; if (!is_ecml && ParseText(&p, ASCIIToUTF16("^cfnm"), &first) && ParseText(&p, ASCIIToUTF16("^clnm"), &credit_card_field.cardholder_last_)) { credit_card_field.cardholder_ = first; q = p; continue; } } // TODO(jhawkins): Parse the type select control. // We look for a card security code before we look for a credit card number // and match the general term "number". The security code has a plethora of // names; we've seen "verification #", "verification number", // "card identification number" and others listed in the ParseText() call // below. if (is_ecml) { pattern = GetEcmlPattern(kEcmlCardVerification); } else { pattern = ASCIIToUTF16( "verification|card identification|cvn|security code|cvv code|cvc"); } if (credit_card_field.verification_ == NULL && ParseText(&q, pattern, &credit_card_field.verification_)) { continue; } if (is_ecml) pattern = GetEcmlPattern(kEcmlCardNumber); else pattern = ASCIIToUTF16("number|card #|card no.|card_number"); if (credit_card_field.number_ == NULL && ParseText(&q, pattern, &credit_card_field.number_)) { continue; } // "Expiration date" is the most common label here, but some pages have // "Expires", "exp. date" or "exp. month" and "exp. year". We also look for // the field names ccmonth and ccyear, which appear on at least 4 of our // test pages. // // -> On at least one page (The China Shop2.html) we find only the labels // "month" and "year". So for now we match these words directly; we'll // see if this turns out to be too general. // // Toolbar Bug 51451: indeed, simply matching "month" is too general for // https://rps.fidelity.com/ftgw/rps/RtlCust/CreatePIN/Init. // Instead, we match only words beginning with "month". if (is_ecml) pattern = GetEcmlPattern(kEcmlCardExpireMonth); else pattern = ASCIIToUTF16("expir|exp month|exp date|ccmonth|&month"); if ((!credit_card_field.expiration_month_ || credit_card_field.expiration_month_->IsEmpty()) && ParseText(&q, pattern, &credit_card_field.expiration_month_)) { if (is_ecml) pattern = GetEcmlPattern(kEcmlCardExpireYear); else pattern = ASCIIToUTF16("|exp|^/|ccyear|year"); if (!ParseText(&q, pattern, &credit_card_field.expiration_year_)) { return NULL; } continue; } if (ParseText(&q, GetEcmlPattern(kEcmlCardExpireDay))) continue; // Some pages (e.g. ExpediaBilling.html) have a "card description" // field; we parse this field but ignore it. ParseText(&q, ASCIIToUTF16("card description")); } // On some pages, the user selects a card type using radio buttons // (e.g. test page Apple Store Billing.html). We can't handle that yet, // so we treat the card type as optional for now. if (credit_card_field.number_ != NULL && credit_card_field.expiration_month_ && !credit_card_field.expiration_month_->IsEmpty()) { *iter = q; return new CreditCardField(credit_card_field); } return NULL; } CreditCardField::CreditCardField() : cardholder_(NULL), cardholder_last_(NULL), type_(NULL), number_(NULL), verification_(NULL), expiration_month_(NULL), expiration_year_(NULL) { } CreditCardField::CreditCardField(const CreditCardField& field) : cardholder_(field.cardholder_), cardholder_last_(field.cardholder_last_), type_(field.type_), number_(field.number_), verification_(field.verification_), expiration_month_(field.expiration_month_), expiration_year_(field.expiration_year_) { } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/boot_times_loader.h" #include <vector> #include "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/message_loop.h" #include "base/process_util.h" #include "base/string_util.h" #include "base/thread.h" #include "chrome/browser/browser_process.h" #include "chrome/common/chrome_switches.h" namespace chromeos { // Beginning of line we look for that gives version number. static const char kPrefix[] = "CHROMEOS_RELEASE_DESCRIPTION="; // File to look for version number in. static const char kVersionPath[] = "/etc/lsb-release"; // File uptime logs are located in. static const char kLogPath[] = "/tmp"; BootTimesLoader::BootTimesLoader() : backend_(new Backend()) { } BootTimesLoader::Handle BootTimesLoader::GetBootTimes( CancelableRequestConsumerBase* consumer, BootTimesLoader::GetBootTimesCallback* callback) { if (!g_browser_process->file_thread()) { // This should only happen if Chrome is shutting down, so we don't do // anything. return 0; } const CommandLine& command_line = *CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kTestType)) { // TODO(davemoore) This avoids boottimes for tests. This needs to be // replaced with a mock of BootTimesLoader. return 0; } scoped_refptr<CancelableRequest<GetBootTimesCallback> > request( new CancelableRequest<GetBootTimesCallback>(callback)); AddRequest(request, consumer); g_browser_process->file_thread()->message_loop()->PostTask( FROM_HERE, NewRunnableMethod(backend_.get(), &Backend::GetBootTimes, request)); return request->handle(); } // Executes command within a shell, allowing IO redirection. Searches // for a whitespace delimited string prefixed by prefix in the output and // returns it. static std::string ExecuteInShell( const std::string& command, const std::string& prefix) { std::vector<std::string> args; args.push_back("/bin/sh"); args.push_back("-c"); args.push_back(command); CommandLine cmd(args); std::string out; if (base::GetAppOutput(cmd, &out)) { size_t index = out.find(prefix); if (index != std::string::npos) { size_t value_index = index + prefix.size(); size_t whitespace_index = out.find(' ', value_index); size_t chars_left = std::string::npos; if (whitespace_index == std::string::npos) whitespace_index = out.find('\n', value_index); if (whitespace_index != std::string::npos) chars_left = whitespace_index - value_index; return out.substr(value_index, chars_left); } } return std::string(); } // Extracts the uptime value from files located in /tmp, returning the // value as a double in value. static bool GetUptime(const std::string& log, double* value) { FilePath log_dir(kLogPath); FilePath log_file = log_dir.Append(log); std::string contents; *value = 0.0; if (file_util::ReadFileToString(log_file, &contents)) { size_t space_index = contents.find(' '); size_t chars_left = space_index != std::string::npos ? space_index : std::string::npos; std::string value_string = contents.substr(0, chars_left); return StringToDouble(value_string, value); } return false; } void BootTimesLoader::Backend::GetBootTimes( scoped_refptr<GetBootTimesRequest> request) { const char* kInitialTSCCommand = "dmesg | grep 'Initial TSC value:'"; const char* kInitialTSCPrefix = "TSC value: "; const char* kClockSpeedCommand = "dmesg | grep -e 'Detected.*processor'"; const char* kClockSpeedPrefix = "Detected "; const char* kPreStartup = "uptime-pre-startup"; const char* kChromeExec = "uptime-chrome-exec"; const char* kChromeMain = "uptime-chrome-main"; const char* kXStarted = "uptime-x-started"; const char* kLoginPromptReady = "uptime-login-prompt-ready"; if (request->canceled()) return; // Wait until login_prompt_ready is output. FilePath log_dir(kLogPath); FilePath log_file = log_dir.Append(kLoginPromptReady); while (!file_util::PathExists(log_file)) { usleep(500000); } BootTimes boot_times; std::string tsc_value = ExecuteInShell(kInitialTSCCommand, kInitialTSCPrefix); std::string speed_value = ExecuteInShell(kClockSpeedCommand, kClockSpeedPrefix); boot_times.firmware = 0; if (!tsc_value.empty() && !speed_value.empty()) { int64 tsc = 0; double speed = 0; if (StringToInt64(tsc_value, &tsc) && StringToDouble(speed_value, &speed) && speed > 0) { boot_times.firmware = static_cast<double>(tsc) / (speed * 1000000); } } GetUptime(kPreStartup, &boot_times.pre_startup); GetUptime(kXStarted, &boot_times.x_started); GetUptime(kChromeExec, &boot_times.chrome_exec); GetUptime(kChromeMain, &boot_times.chrome_main); GetUptime(kLoginPromptReady, &boot_times.login_prompt_ready); request->ForwardResult( GetBootTimesCallback::TupleType(request->handle(), boot_times)); } } // namespace chromeos <commit_msg>Make boottime delay not block file thread BUG=None TEST=Boot on ARM...boottimes shouldn't display but chrome should still work. We will be stating a file every half second though until /tmp/uptime-login-prompt-ready is emited.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/boot_times_loader.h" #include <vector> #include "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/message_loop.h" #include "base/process_util.h" #include "base/string_util.h" #include "base/thread.h" #include "chrome/browser/browser_process.h" #include "chrome/common/chrome_switches.h" namespace chromeos { // File uptime logs are located in. static const char kLogPath[] = "/tmp"; BootTimesLoader::BootTimesLoader() : backend_(new Backend()) { } BootTimesLoader::Handle BootTimesLoader::GetBootTimes( CancelableRequestConsumerBase* consumer, BootTimesLoader::GetBootTimesCallback* callback) { if (!g_browser_process->file_thread()) { // This should only happen if Chrome is shutting down, so we don't do // anything. return 0; } const CommandLine& command_line = *CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kTestType)) { // TODO(davemoore) This avoids boottimes for tests. This needs to be // replaced with a mock of BootTimesLoader. return 0; } scoped_refptr<CancelableRequest<GetBootTimesCallback> > request( new CancelableRequest<GetBootTimesCallback>(callback)); AddRequest(request, consumer); g_browser_process->file_thread()->message_loop()->PostTask( FROM_HERE, NewRunnableMethod(backend_.get(), &Backend::GetBootTimes, request)); return request->handle(); } // Executes command within a shell, allowing IO redirection. Searches // for a whitespace delimited string prefixed by prefix in the output and // returns it. static std::string ExecuteInShell( const std::string& command, const std::string& prefix) { std::vector<std::string> args; args.push_back("/bin/sh"); args.push_back("-c"); args.push_back(command); CommandLine cmd(args); std::string out; if (base::GetAppOutput(cmd, &out)) { size_t index = out.find(prefix); if (index != std::string::npos) { size_t value_index = index + prefix.size(); size_t whitespace_index = out.find(' ', value_index); size_t chars_left = std::string::npos; if (whitespace_index == std::string::npos) whitespace_index = out.find('\n', value_index); if (whitespace_index != std::string::npos) chars_left = whitespace_index - value_index; return out.substr(value_index, chars_left); } } return std::string(); } // Extracts the uptime value from files located in /tmp, returning the // value as a double in value. static bool GetUptime(const std::string& log, double* value) { FilePath log_dir(kLogPath); FilePath log_file = log_dir.Append(log); std::string contents; *value = 0.0; if (file_util::ReadFileToString(log_file, &contents)) { size_t space_index = contents.find(' '); size_t chars_left = space_index != std::string::npos ? space_index : std::string::npos; std::string value_string = contents.substr(0, chars_left); return StringToDouble(value_string, value); } return false; } void BootTimesLoader::Backend::GetBootTimes( scoped_refptr<GetBootTimesRequest> request) { const char* kInitialTSCCommand = "dmesg | grep 'Initial TSC value:'"; const char* kInitialTSCPrefix = "TSC value: "; const char* kClockSpeedCommand = "dmesg | grep -e 'Detected.*processor'"; const char* kClockSpeedPrefix = "Detected "; const char* kPreStartup = "uptime-pre-startup"; const char* kChromeExec = "uptime-chrome-exec"; const char* kChromeMain = "uptime-chrome-main"; const char* kXStarted = "uptime-x-started"; const char* kLoginPromptReady = "uptime-login-prompt-ready"; if (request->canceled()) return; // Wait until login_prompt_ready is output by reposting. FilePath log_dir(kLogPath); FilePath log_file = log_dir.Append(kLoginPromptReady); if (!file_util::PathExists(log_file)) { g_browser_process->file_thread()->message_loop()->PostDelayedTask( FROM_HERE, NewRunnableMethod(this, &Backend::GetBootTimes, request), 500); return; } BootTimes boot_times; std::string tsc_value = ExecuteInShell(kInitialTSCCommand, kInitialTSCPrefix); std::string speed_value = ExecuteInShell(kClockSpeedCommand, kClockSpeedPrefix); boot_times.firmware = 0; if (!tsc_value.empty() && !speed_value.empty()) { int64 tsc = 0; double speed = 0; if (StringToInt64(tsc_value, &tsc) && StringToDouble(speed_value, &speed) && speed > 0) { boot_times.firmware = static_cast<double>(tsc) / (speed * 1000000); } } GetUptime(kPreStartup, &boot_times.pre_startup); GetUptime(kXStarted, &boot_times.x_started); GetUptime(kChromeExec, &boot_times.chrome_exec); GetUptime(kChromeMain, &boot_times.chrome_main); GetUptime(kLoginPromptReady, &boot_times.login_prompt_ready); request->ForwardResult( GetBootTimesCallback::TupleType(request->handle(), boot_times)); } } // namespace chromeos <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/login/login_utils.h" #include "base/command_line.h" #include "base/file_path.h" #include "base/lock.h" #include "base/nss_util.h" #include "base/path_service.h" #include "base/scoped_ptr.h" #include "base/singleton.h" #include "base/time.h" #include "chrome/browser/browser_init.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/cros/login_library.h" #include "chrome/browser/chromeos/cros/network_library.h" #include "chrome/browser/chromeos/external_cookie_handler.h" #include "chrome/browser/chromeos/login/cookie_fetcher.h" #include "chrome/browser/chromeos/login/google_authenticator.h" #include "chrome/browser/chromeos/login/user_image_downloader.h" #include "chrome/browser/chromeos/login/user_manager.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/profile.h" #include "chrome/browser/profile_manager.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/net/url_request_context_getter.h" #include "chrome/common/notification_observer.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/common/notification_type.h" #include "googleurl/src/gurl.h" #include "net/base/cookie_store.h" #include "net/url_request/url_request_context.h" #include "views/widget/widget_gtk.h" namespace chromeos { namespace { const int kWifiTimeoutInMS = 15000; static char kIncognitoUser[] = "incognito"; // Prefix for Auth token received from ClientLogin request. const char kAuthPrefix[] = "Auth="; // Suffix for Auth token received from ClientLogin request. const char kAuthSuffix[] = "\n"; // Find Auth token in given response from ClientLogin request. // Returns the token if found, empty string otherwise. std::string get_auth_token(const std::string& credentials) { size_t auth_start = credentials.find(kAuthPrefix); if (auth_start == std::string::npos) return std::string(); auth_start += arraysize(kAuthPrefix) - 1; size_t auth_end = credentials.find(kAuthSuffix, auth_start); if (auth_end == std::string::npos) return std::string(); return credentials.substr(auth_start, auth_end - auth_start); } } // namespace class LoginUtilsImpl : public LoginUtils, public NotificationObserver { public: LoginUtilsImpl() : wifi_connecting_(false) { registrar_.Add( this, NotificationType::LOGIN_USER_CHANGED, NotificationService::AllSources()); } virtual bool ShouldWaitForWifi(); // Invoked after the user has successfully logged in. This launches a browser // and does other bookkeeping after logging in. virtual void CompleteLogin(const std::string& username, const std::string& credentials); // Invoked after the tmpfs is successfully mounted. // Launches a browser in the off the record (incognito) mode. virtual void CompleteOffTheRecordLogin(); // Creates and returns the authenticator to use. The caller owns the returned // Authenticator and must delete it when done. virtual Authenticator* CreateAuthenticator(LoginStatusConsumer* consumer); // Used to postpone browser launch via DoBrowserLaunch() if some post // login screen is to be shown. virtual void EnableBrowserLaunch(bool enable); // Returns if browser launch enabled now or not. virtual bool IsBrowserLaunchEnabled() const; // Returns auth token for 'cp' Contacts service. virtual const std::string& GetAuthToken() const { return auth_token_; } // NotificationObserver implementation. virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details); private: // Attempt to connect to the preferred network if available. void ConnectToPreferredNetwork(); NotificationRegistrar registrar_; bool wifi_connecting_; base::Time wifi_connect_start_time_; // Indicates if DoBrowserLaunch will actually launch the browser or not. bool browser_launch_enabled_; // Auth token for Contacts service. Received by GoogleAuthenticator as // part of ClientLogin response. std::string auth_token_; DISALLOW_COPY_AND_ASSIGN(LoginUtilsImpl); }; class LoginUtilsWrapper { public: LoginUtilsWrapper() {} LoginUtils* get() { AutoLock create(create_lock_); if (!ptr_.get()) reset(new LoginUtilsImpl); return ptr_.get(); } void reset(LoginUtils* ptr) { ptr_.reset(ptr); } private: Lock create_lock_; scoped_ptr<LoginUtils> ptr_; DISALLOW_COPY_AND_ASSIGN(LoginUtilsWrapper); }; bool LoginUtilsImpl::ShouldWaitForWifi() { // If we are connecting to the preferred network, // wait kWifiTimeoutInMS until connection is made or failed. if (wifi_connecting_) { NetworkLibrary* cros = CrosLibrary::Get()->GetNetworkLibrary(); if (cros->PreferredNetworkConnected()) { LOG(INFO) << "Wifi connection successful."; return false; } else if (cros->PreferredNetworkFailed()) { LOG(INFO) << "Wifi connection failed."; return false; } else { base::TimeDelta diff = base::Time::Now() - wifi_connect_start_time_; // Keep waiting if we have not timed out yet. bool timedout = (diff.InMilliseconds() > kWifiTimeoutInMS); if (timedout) LOG(INFO) << "Wifi connection timed out."; return !timedout; } } return false; } void LoginUtilsImpl::CompleteLogin(const std::string& username, const std::string& credentials) { LOG(INFO) << "Completing login for " << username; if (CrosLibrary::Get()->EnsureLoaded()) CrosLibrary::Get()->GetLoginLibrary()->StartSession(username, ""); UserManager::Get()->UserLoggedIn(username); ConnectToPreferredNetwork(); // Now launch the initial browser window. FilePath user_data_dir; PathService::Get(chrome::DIR_USER_DATA, &user_data_dir); ProfileManager* profile_manager = g_browser_process->profile_manager(); // The default profile will have been changed because the ProfileManager // will process the notification that the UserManager sends out. Profile* profile = profile_manager->GetDefaultProfile(user_data_dir); // Take the credentials passed in and try to exchange them for // full-fledged Google authentication cookies. This is // best-effort; it's possible that we'll fail due to network // troubles or some such. Either way, |cf| will call // DoBrowserLaunch on the UI thread when it's done, and then // delete itself. CookieFetcher* cf = new CookieFetcher(profile); cf->AttemptFetch(credentials); auth_token_ = get_auth_token(credentials); } void LoginUtilsImpl::CompleteOffTheRecordLogin() { LOG(INFO) << "Completing off the record login"; if (CrosLibrary::Get()->EnsureLoaded()) CrosLibrary::Get()->GetLoginLibrary()->StartSession(kIncognitoUser, ""); // Incognito flag is not set by default. CommandLine::ForCurrentProcess()->AppendSwitch(switches::kIncognito); UserManager::Get()->OffTheRecordUserLoggedIn(); ConnectToPreferredNetwork(); LoginUtils::DoBrowserLaunch( ProfileManager::GetDefaultProfile()->GetOffTheRecordProfile()); } Authenticator* LoginUtilsImpl::CreateAuthenticator( LoginStatusConsumer* consumer) { return new GoogleAuthenticator(consumer); } void LoginUtilsImpl::EnableBrowserLaunch(bool enable) { browser_launch_enabled_ = enable; } bool LoginUtilsImpl::IsBrowserLaunchEnabled() const { return browser_launch_enabled_; } void LoginUtilsImpl::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { if (type == NotificationType::LOGIN_USER_CHANGED) base::OpenPersistentNSSDB(); } void LoginUtilsImpl::ConnectToPreferredNetwork() { NetworkLibrary* cros = CrosLibrary::Get()->GetNetworkLibrary(); wifi_connecting_ = cros->ConnectToPreferredNetworkIfAvailable(); if (wifi_connecting_) wifi_connect_start_time_ = base::Time::Now(); } LoginUtils* LoginUtils::Get() { return Singleton<LoginUtilsWrapper>::get()->get(); } void LoginUtils::Set(LoginUtils* mock) { Singleton<LoginUtilsWrapper>::get()->reset(mock); } void LoginUtils::DoBrowserLaunch(Profile* profile) { // If we should wait for wifi connection, post this task with a 100ms delay. if (LoginUtils::Get()->ShouldWaitForWifi()) { ChromeThread::PostDelayedTask( ChromeThread::UI, FROM_HERE, NewRunnableFunction(&LoginUtils::DoBrowserLaunch, profile), 100); return; } // Browser launch was disabled due to some post login screen. if (!LoginUtils::Get()->IsBrowserLaunchEnabled()) return; LOG(INFO) << "Launching browser..."; BrowserInit browser_init; int return_code; browser_init.LaunchBrowser(*CommandLine::ForCurrentProcess(), profile, std::wstring(), true, &return_code); } } // namespace chromeos <commit_msg>Quick fix: initializing member variable. Makes offline login work.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/login/login_utils.h" #include "base/command_line.h" #include "base/file_path.h" #include "base/lock.h" #include "base/nss_util.h" #include "base/path_service.h" #include "base/scoped_ptr.h" #include "base/singleton.h" #include "base/time.h" #include "chrome/browser/browser_init.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/cros/login_library.h" #include "chrome/browser/chromeos/cros/network_library.h" #include "chrome/browser/chromeos/external_cookie_handler.h" #include "chrome/browser/chromeos/login/cookie_fetcher.h" #include "chrome/browser/chromeos/login/google_authenticator.h" #include "chrome/browser/chromeos/login/user_image_downloader.h" #include "chrome/browser/chromeos/login/user_manager.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/profile.h" #include "chrome/browser/profile_manager.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/net/url_request_context_getter.h" #include "chrome/common/notification_observer.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/common/notification_type.h" #include "googleurl/src/gurl.h" #include "net/base/cookie_store.h" #include "net/url_request/url_request_context.h" #include "views/widget/widget_gtk.h" namespace chromeos { namespace { const int kWifiTimeoutInMS = 15000; static char kIncognitoUser[] = "incognito"; // Prefix for Auth token received from ClientLogin request. const char kAuthPrefix[] = "Auth="; // Suffix for Auth token received from ClientLogin request. const char kAuthSuffix[] = "\n"; // Find Auth token in given response from ClientLogin request. // Returns the token if found, empty string otherwise. std::string get_auth_token(const std::string& credentials) { size_t auth_start = credentials.find(kAuthPrefix); if (auth_start == std::string::npos) return std::string(); auth_start += arraysize(kAuthPrefix) - 1; size_t auth_end = credentials.find(kAuthSuffix, auth_start); if (auth_end == std::string::npos) return std::string(); return credentials.substr(auth_start, auth_end - auth_start); } } // namespace class LoginUtilsImpl : public LoginUtils, public NotificationObserver { public: LoginUtilsImpl() : wifi_connecting_(false), browser_launch_enabled_(true) { registrar_.Add( this, NotificationType::LOGIN_USER_CHANGED, NotificationService::AllSources()); } virtual bool ShouldWaitForWifi(); // Invoked after the user has successfully logged in. This launches a browser // and does other bookkeeping after logging in. virtual void CompleteLogin(const std::string& username, const std::string& credentials); // Invoked after the tmpfs is successfully mounted. // Launches a browser in the off the record (incognito) mode. virtual void CompleteOffTheRecordLogin(); // Creates and returns the authenticator to use. The caller owns the returned // Authenticator and must delete it when done. virtual Authenticator* CreateAuthenticator(LoginStatusConsumer* consumer); // Used to postpone browser launch via DoBrowserLaunch() if some post // login screen is to be shown. virtual void EnableBrowserLaunch(bool enable); // Returns if browser launch enabled now or not. virtual bool IsBrowserLaunchEnabled() const; // Returns auth token for 'cp' Contacts service. virtual const std::string& GetAuthToken() const { return auth_token_; } // NotificationObserver implementation. virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details); private: // Attempt to connect to the preferred network if available. void ConnectToPreferredNetwork(); NotificationRegistrar registrar_; bool wifi_connecting_; base::Time wifi_connect_start_time_; // Indicates if DoBrowserLaunch will actually launch the browser or not. bool browser_launch_enabled_; // Auth token for Contacts service. Received by GoogleAuthenticator as // part of ClientLogin response. std::string auth_token_; DISALLOW_COPY_AND_ASSIGN(LoginUtilsImpl); }; class LoginUtilsWrapper { public: LoginUtilsWrapper() {} LoginUtils* get() { AutoLock create(create_lock_); if (!ptr_.get()) reset(new LoginUtilsImpl); return ptr_.get(); } void reset(LoginUtils* ptr) { ptr_.reset(ptr); } private: Lock create_lock_; scoped_ptr<LoginUtils> ptr_; DISALLOW_COPY_AND_ASSIGN(LoginUtilsWrapper); }; bool LoginUtilsImpl::ShouldWaitForWifi() { // If we are connecting to the preferred network, // wait kWifiTimeoutInMS until connection is made or failed. if (wifi_connecting_) { NetworkLibrary* cros = CrosLibrary::Get()->GetNetworkLibrary(); if (cros->PreferredNetworkConnected()) { LOG(INFO) << "Wifi connection successful."; return false; } else if (cros->PreferredNetworkFailed()) { LOG(INFO) << "Wifi connection failed."; return false; } else { base::TimeDelta diff = base::Time::Now() - wifi_connect_start_time_; // Keep waiting if we have not timed out yet. bool timedout = (diff.InMilliseconds() > kWifiTimeoutInMS); if (timedout) LOG(INFO) << "Wifi connection timed out."; return !timedout; } } return false; } void LoginUtilsImpl::CompleteLogin(const std::string& username, const std::string& credentials) { LOG(INFO) << "Completing login for " << username; if (CrosLibrary::Get()->EnsureLoaded()) CrosLibrary::Get()->GetLoginLibrary()->StartSession(username, ""); UserManager::Get()->UserLoggedIn(username); ConnectToPreferredNetwork(); // Now launch the initial browser window. FilePath user_data_dir; PathService::Get(chrome::DIR_USER_DATA, &user_data_dir); ProfileManager* profile_manager = g_browser_process->profile_manager(); // The default profile will have been changed because the ProfileManager // will process the notification that the UserManager sends out. Profile* profile = profile_manager->GetDefaultProfile(user_data_dir); // Take the credentials passed in and try to exchange them for // full-fledged Google authentication cookies. This is // best-effort; it's possible that we'll fail due to network // troubles or some such. Either way, |cf| will call // DoBrowserLaunch on the UI thread when it's done, and then // delete itself. CookieFetcher* cf = new CookieFetcher(profile); cf->AttemptFetch(credentials); auth_token_ = get_auth_token(credentials); } void LoginUtilsImpl::CompleteOffTheRecordLogin() { LOG(INFO) << "Completing off the record login"; if (CrosLibrary::Get()->EnsureLoaded()) CrosLibrary::Get()->GetLoginLibrary()->StartSession(kIncognitoUser, ""); // Incognito flag is not set by default. CommandLine::ForCurrentProcess()->AppendSwitch(switches::kIncognito); UserManager::Get()->OffTheRecordUserLoggedIn(); ConnectToPreferredNetwork(); LoginUtils::DoBrowserLaunch( ProfileManager::GetDefaultProfile()->GetOffTheRecordProfile()); } Authenticator* LoginUtilsImpl::CreateAuthenticator( LoginStatusConsumer* consumer) { return new GoogleAuthenticator(consumer); } void LoginUtilsImpl::EnableBrowserLaunch(bool enable) { browser_launch_enabled_ = enable; } bool LoginUtilsImpl::IsBrowserLaunchEnabled() const { return browser_launch_enabled_; } void LoginUtilsImpl::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { if (type == NotificationType::LOGIN_USER_CHANGED) base::OpenPersistentNSSDB(); } void LoginUtilsImpl::ConnectToPreferredNetwork() { NetworkLibrary* cros = CrosLibrary::Get()->GetNetworkLibrary(); wifi_connecting_ = cros->ConnectToPreferredNetworkIfAvailable(); if (wifi_connecting_) wifi_connect_start_time_ = base::Time::Now(); } LoginUtils* LoginUtils::Get() { return Singleton<LoginUtilsWrapper>::get()->get(); } void LoginUtils::Set(LoginUtils* mock) { Singleton<LoginUtilsWrapper>::get()->reset(mock); } void LoginUtils::DoBrowserLaunch(Profile* profile) { // If we should wait for wifi connection, post this task with a 100ms delay. if (LoginUtils::Get()->ShouldWaitForWifi()) { ChromeThread::PostDelayedTask( ChromeThread::UI, FROM_HERE, NewRunnableFunction(&LoginUtils::DoBrowserLaunch, profile), 100); return; } // Browser launch was disabled due to some post login screen. if (!LoginUtils::Get()->IsBrowserLaunchEnabled()) return; LOG(INFO) << "Launching browser..."; BrowserInit browser_init; int return_code; browser_init.LaunchBrowser(*CommandLine::ForCurrentProcess(), profile, std::wstring(), true, &return_code); } } // namespace chromeos <|endoftext|>
<commit_before>#include "def_lang/impl/Ptr_Value.h" #include "def_lang/Value_Selector.h" #include "def_lang/Serialization.h" #include "def_lang/IStruct_Type.h" namespace ts { Ptr_Value::Ptr_Value(std::shared_ptr<IPtr_Type const> type) : m_type(type) { } Result<bool> Ptr_Value::is_equal(IValue const& other) const { IPtr_Value const* v = dynamic_cast<const IPtr_Value*>(&other); if (!v) { return Error("incompatible values"); } if (get_type() != v->get_type()) { return Error("incompatible types"); } if (get_specialized_type()->get_inner_type() != v->get_specialized_type()->get_inner_type()) { return Error("incompatible inner types"); } //if both are null, then they are equal if (get_value() == nullptr && v->get_value() == nullptr) { return true; } //if one is null and the other not null, the values are different if ((get_value() == nullptr) != (v->get_value() == nullptr)) { return true; } return get_value()->is_equal(*v->get_value()); } Result<void> Ptr_Value::copy_assign(IValue const& other) { IPtr_Value const* v = dynamic_cast<const IPtr_Value*>(&other); if (!v) { return Error("incompatible values"); } if (get_type() != v->get_type()) { return Error("incompatible types"); } if (!is_type_allowed(*v->get_specialized_type()->get_inner_type())) { return Error("Cannot point to type " + v->get_specialized_type()->get_inner_type()->get_symbol_path().to_string()); } if (get_value() == nullptr) { if (v->get_value() == nullptr) { return success; } return set_value(v->get_value()->clone()); } else { if (v->get_value() == nullptr) { return set_value(nullptr); } return get_value()->copy_assign(*v->get_value()); } } Result<void> Ptr_Value::copy_assign(IInitializer const& initializer) { return Error("not implemented"); } std::shared_ptr<IValue> Ptr_Value::clone() const { return std::make_shared<Ptr_Value>(*this); } std::shared_ptr<IType const> Ptr_Value::get_type() const { return m_type; } Result<void> Ptr_Value::parse_from_ui_string(std::string const& str) { return Error("Not Supported"); } Result<std::string> Ptr_Value::get_ui_string() const { return Error("Not Supported"); } std::shared_ptr<const IValue> Ptr_Value::select(Value_Selector&& selector) const { return const_cast<Ptr_Value*>(this)->select(std::move(selector)); } std::shared_ptr<IValue> Ptr_Value::select(Value_Selector&& selector) { TS_ASSERT(!selector.empty()); if (selector.empty()) { return nullptr; } if (get_value() == nullptr) { return nullptr; } return get_value()->select(std::move(selector)); } std::shared_ptr<IPtr_Type const> Ptr_Value::get_specialized_type() const { return m_type; } Result<serialization::Value> Ptr_Value::serialize() const { std::shared_ptr<const IValue> value = get_value(); if (value) { serialization::Value sz_value(serialization::Value::Type::OBJECT); sz_value.add_object_member("type", serialization::Value(value->get_type()->get_symbol_path().to_string())); auto result = value->serialize(); if (result != success) { return result; } sz_value.add_object_member("value", result.extract_payload()); return std::move(sz_value); } else { return serialization::Value(serialization::Value::Type::EMPTY); } } Result<void> Ptr_Value::deserialize(serialization::Value const& sz_value) { if (sz_value.get_type() == serialization::Value::Type::EMPTY) { set_value(std::shared_ptr<IValue>()); return success; } if (sz_value.get_type() != serialization::Value::Type::OBJECT) { return Error("Expected object or null value when deserializing"); } TS_ASSERT(false); return Error("Not implemented"); } std::shared_ptr<const IValue> Ptr_Value::get_value() const { return m_value; } std::shared_ptr<IValue> Ptr_Value::get_value() { return m_value; } Result<void> Ptr_Value::set_value(std::shared_ptr<IValue> value) { if (!value) { m_value = nullptr; return success; } if (!is_type_allowed(*value->get_type())) { return Error("Cannot point to type " + value->get_type()->get_symbol_path().to_string()); } m_value = value; return success; } bool Ptr_Value::is_type_allowed(IType const& type) const { if (get_specialized_type()->get_inner_type().get() == &type) { return true; } IStruct_Type const* inner_type = dynamic_cast<IStruct_Type const*>(get_specialized_type()->get_inner_type().get()); IStruct_Type const* other_type = dynamic_cast<IStruct_Type const*>(&type); if (inner_type && other_type) { return inner_type->is_base_of(*other_type); } return false; } } <commit_msg>Finished deserialization of the ptr value<commit_after>#include "def_lang/impl/Ptr_Value.h" #include "def_lang/Value_Selector.h" #include "def_lang/Serialization.h" #include "def_lang/IStruct_Type.h" namespace ts { Ptr_Value::Ptr_Value(std::shared_ptr<IPtr_Type const> type) : m_type(type) { } Result<bool> Ptr_Value::is_equal(IValue const& other) const { IPtr_Value const* v = dynamic_cast<const IPtr_Value*>(&other); if (!v) { return Error("incompatible values"); } if (get_type() != v->get_type()) { return Error("incompatible types"); } if (get_specialized_type()->get_inner_type() != v->get_specialized_type()->get_inner_type()) { return Error("incompatible inner types"); } //if both are null, then they are equal if (get_value() == nullptr && v->get_value() == nullptr) { return true; } //if one is null and the other not null, the values are different if ((get_value() == nullptr) != (v->get_value() == nullptr)) { return true; } return get_value()->is_equal(*v->get_value()); } Result<void> Ptr_Value::copy_assign(IValue const& other) { IPtr_Value const* v = dynamic_cast<const IPtr_Value*>(&other); if (!v) { return Error("incompatible values"); } if (get_type() != v->get_type()) { return Error("incompatible types"); } if (!is_type_allowed(*v->get_specialized_type()->get_inner_type())) { return Error("Cannot point to type " + v->get_specialized_type()->get_inner_type()->get_symbol_path().to_string()); } if (get_value() == nullptr) { if (v->get_value() == nullptr) { return success; } return set_value(v->get_value()->clone()); } else { if (v->get_value() == nullptr) { return set_value(nullptr); } return get_value()->copy_assign(*v->get_value()); } } Result<void> Ptr_Value::copy_assign(IInitializer const& initializer) { return Error("not implemented"); } std::shared_ptr<IValue> Ptr_Value::clone() const { return std::make_shared<Ptr_Value>(*this); } std::shared_ptr<IType const> Ptr_Value::get_type() const { return m_type; } Result<void> Ptr_Value::parse_from_ui_string(std::string const& str) { return Error("Not Supported"); } Result<std::string> Ptr_Value::get_ui_string() const { return Error("Not Supported"); } std::shared_ptr<const IValue> Ptr_Value::select(Value_Selector&& selector) const { return const_cast<Ptr_Value*>(this)->select(std::move(selector)); } std::shared_ptr<IValue> Ptr_Value::select(Value_Selector&& selector) { TS_ASSERT(!selector.empty()); if (selector.empty()) { return nullptr; } if (get_value() == nullptr) { return nullptr; } return get_value()->select(std::move(selector)); } std::shared_ptr<IPtr_Type const> Ptr_Value::get_specialized_type() const { return m_type; } Result<serialization::Value> Ptr_Value::serialize() const { std::shared_ptr<const IValue> value = get_value(); if (value) { serialization::Value sz_value(serialization::Value::Type::OBJECT); sz_value.add_object_member("type", serialization::Value(value->get_type()->get_symbol_path().to_string())); auto result = value->serialize(); if (result != success) { return result; } sz_value.add_object_member("value", result.extract_payload()); return std::move(sz_value); } else { return serialization::Value(serialization::Value::Type::EMPTY); } } Result<void> Ptr_Value::deserialize(serialization::Value const& sz_value) { if (sz_value.is_empty()) { set_value(std::shared_ptr<IValue>()); return success; } if (!sz_value.is_object()) { return Error("Expected object or null value when deserializing"); } serialization::Value const* type_sz_value = sz_value.find_object_member_by_name("type"); if (!type_sz_value || !type_sz_value->is_string()) { return Error("Expected 'type' string value when deserializing"); } std::shared_ptr<const IType> type = get_type()->get_parent_scope()->find_specialized_symbol_by_path<const IType>(Symbol_Path(type_sz_value->get_as_string())); if (!type) { return Error("Cannot find type '" + type_sz_value->get_as_string() + "' when deserializing"); } auto result = set_value(type->create_value()); if (result != success) { return Error("Cannot create value when deserializing: " + result.error().what()); } serialization::Value const* value_sz_value = sz_value.find_object_member_by_name("value"); if (!value_sz_value) { return Error("Expected 'value' when deserializing"); } return get_value()->deserialize(*value_sz_value); } std::shared_ptr<const IValue> Ptr_Value::get_value() const { return m_value; } std::shared_ptr<IValue> Ptr_Value::get_value() { return m_value; } Result<void> Ptr_Value::set_value(std::shared_ptr<IValue> value) { if (!value) { m_value = nullptr; return success; } if (!is_type_allowed(*value->get_type())) { return Error("Cannot point to type " + value->get_type()->get_symbol_path().to_string()); } m_value = value; return success; } bool Ptr_Value::is_type_allowed(IType const& type) const { if (get_specialized_type()->get_inner_type().get() == &type) { return true; } IStruct_Type const* inner_type = dynamic_cast<IStruct_Type const*>(get_specialized_type()->get_inner_type().get()); IStruct_Type const* other_type = dynamic_cast<IStruct_Type const*>(&type); if (inner_type && other_type) { return inner_type->is_base_of(*other_type); } return false; } } <|endoftext|>
<commit_before>//! //! @author Yue Wang //! @date 13 11 2014 //! //! @ex 41.01 //! (a) share data between two threads. //! (b) use mutex to avoid data race. //! // to compile (on linux) : // g++ -std=c++11 -Wall ex41_01.cpp -pthread //! #include <iostream> #include <thread> #include <mutex> #include <chrono> #include <memory> #include <vector> #include <string> using SharedData = std::shared_ptr<std::vector<std::string>>; void task1(SharedData data, std::mutex* mutex) { std::this_thread::sleep_for(std::chrono::milliseconds{5}); std::unique_lock<std::mutex> lock{*mutex}; for(const auto& elem : *data) std::cout << "\nfrom task 1 " << elem << " "; } void task2(SharedData data, std::mutex* mutex) { std::unique_lock<std::mutex> lock{*mutex}; data->push_back("pezy--added by task2"); } int main() { //! data for sharing auto data = std::make_shared<std::vector<std::string> >(); *data = {"alan","moophy","yue wang"}; //! two threads static std::mutex mutex; std::thread t1(task1,data,&mutex), t2(task2,data,&mutex); t1.join(); t2.join(); std::cout << "\n\ndone\n"; } //! output : //from task 1 alan //from task 1 moophy //from task 1 yue wang //from task 1 pezy--added by task2 //done <commit_msg> deleted: ch41/ex41_01.cpp<commit_after><|endoftext|>
<commit_before>/* This file is part of the Vc library. Copyright (C) 2009 Matthias Kretz <kretz@kde.org> Vc is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Vc 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 Vc. If not, see <http://www.gnu.org/licenses/>. */ #include <Vc/Vc> #include "benchmark.h" #include "random.h" #include "../cpuid.h" #include <cstdio> #include <cstdlib> using namespace Vc; template<typename T, int S> struct KeepResultsHelper { static inline void keep(const T &tmp0) { asm volatile(""::"r"(tmp0)); } }; #ifdef VC_IMPL_SSE template<typename T> struct KeepResultsHelper<T, 16> { static inline void keep(const T &tmp0) { asm volatile(""::"x"(reinterpret_cast<const __m128 &>(tmp0))); } }; template<typename T> struct KeepResultsHelper<T, 32> { static inline void keep(const T &tmp0) { asm volatile(""::"x"(reinterpret_cast<const __m128 &>(tmp0)), "x"(reinterpret_cast<const __m128 *>(&tmp0)[1])); } }; #endif #ifdef VC_IMPL_LRBni template<typename T> struct KeepResultsHelper<T, 64> { static inline void keep(const T &tmp0) { asm volatile(""::"x"(reinterpret_cast<const __m128 &>(tmp0)), "x"(reinterpret_cast<const __m128 *>(&tmp0)[1]), "x"(reinterpret_cast<const __m128 *>(&tmp0)[2]), "x"(reinterpret_cast<const __m128 *>(&tmp0)[3])); } }; #endif template<typename T> static inline void keepResults(const T &tmp0) { KeepResultsHelper<T, sizeof(T)>::keep(tmp0); } template<typename Vector> class DoMemIos { public: static void run() { Benchmark::setColumnData("MemorySize", "half L1"); run(CpuId::L1Data() / (sizeof(Vector) * 2), 128); Benchmark::setColumnData("MemorySize", "L1"); run(CpuId::L1Data() / (sizeof(Vector) * 1), 128); Benchmark::setColumnData("MemorySize", "half L2"); run(CpuId::L2Data() / (sizeof(Vector) * 2), 32); Benchmark::setColumnData("MemorySize", "L2"); run(CpuId::L2Data() / (sizeof(Vector) * 1), 16); if (CpuId::L3Data() > 0) { Benchmark::setColumnData("MemorySize", "half L3"); run(CpuId::L3Data() / (sizeof(Vector) * 2), 2); Benchmark::setColumnData("MemorySize", "L3"); run(CpuId::L3Data() / (sizeof(Vector) * 1), 2); Benchmark::setColumnData("MemorySize", "4x L3"); run(CpuId::L3Data() / sizeof(Vector) * 4, 1); } else { Benchmark::setColumnData("MemorySize", "4x L2"); run(CpuId::L2Data() / sizeof(Vector) * 4, 1); } } private: static void run(const int Factor, const int Factor2) { Vector *a = new Vector[Factor]; #ifndef VC_BENCHMARK_NO_MLOCK mlock(a, Factor * sizeof(Vector)); #endif { Benchmark bm("write", sizeof(Vector) * Factor * Factor2, "Byte"); const Vector foo = PseudoRandom<Vector>::next(); keepResults(foo); for (int i = 0; i < Factor; i += 4) { a[i + 0] = foo; a[i + 1] = foo; a[i + 2] = foo; a[i + 3] = foo; } while (bm.wantsMoreDataPoints()) { bm.Start(); for (int j = 0; j < Factor2; ++j) { keepResults(foo); for (int i = 0; i < Factor; i += 4) { a[i + 0] = foo; a[i + 1] = foo; a[i + 2] = foo; a[i + 3] = foo; } } bm.Stop(); } bm.Print(); } { Benchmark timer("r/w", sizeof(Vector) * Factor * Factor2, "Byte"); const Vector foo = PseudoRandom<Vector>::next(); while (timer.wantsMoreDataPoints()) { timer.Start(); for (int j = 0; j < Factor2; ++j) { keepResults(foo); for (int i = 0; i < Factor; i += 4) { const Vector &tmp0 = a[i + 0]; keepResults(tmp0); a[i + 0] = foo; const Vector &tmp1 = a[i + 1]; keepResults(tmp1); a[i + 1] = foo; const Vector &tmp2 = a[i + 2]; keepResults(tmp2); a[i + 2] = foo; const Vector &tmp3 = a[i + 3]; keepResults(tmp3); a[i + 3] = foo; } } timer.Stop(); } timer.Print(); } { Benchmark timer("read", sizeof(Vector) * Factor * Factor2, "Byte"); while (timer.wantsMoreDataPoints()) { timer.Start(); for (int j = 0; j < Factor2; ++j) { for (int i = 0; i < Factor; i += 4) { const Vector &tmp0 = a[i + 0]; keepResults(tmp0); const Vector &tmp1 = a[i + 1]; keepResults(tmp1); const Vector &tmp2 = a[i + 2]; keepResults(tmp2); const Vector &tmp3 = a[i + 3]; keepResults(tmp3); } } timer.Stop(); } timer.Print(); } delete[] a; } }; int bmain() { Benchmark::addColumn("MemorySize"); DoMemIos<float_v>::run(); return 0; } <commit_msg>test double_v and short_v in memio too<commit_after>/* This file is part of the Vc library. Copyright (C) 2009 Matthias Kretz <kretz@kde.org> Vc is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Vc 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 Vc. If not, see <http://www.gnu.org/licenses/>. */ #include <Vc/Vc> #include "benchmark.h" #include "random.h" #include "../cpuid.h" #include <cstdio> #include <cstdlib> using namespace Vc; template<typename T, int S> struct KeepResultsHelper { static inline void keep(const T &tmp0) { asm volatile(""::"r"(tmp0)); } }; #ifdef VC_IMPL_SSE template<typename T> struct KeepResultsHelper<T, 16> { static inline void keep(const T &tmp0) { asm volatile(""::"x"(reinterpret_cast<const __m128 &>(tmp0))); } }; template<typename T> struct KeepResultsHelper<T, 32> { static inline void keep(const T &tmp0) { asm volatile(""::"x"(reinterpret_cast<const __m128 &>(tmp0)), "x"(reinterpret_cast<const __m128 *>(&tmp0)[1])); } }; #endif #ifdef VC_IMPL_LRBni template<typename T> struct KeepResultsHelper<T, 64> { static inline void keep(const T &tmp0) { asm volatile(""::"x"(reinterpret_cast<const __m128 &>(tmp0)), "x"(reinterpret_cast<const __m128 *>(&tmp0)[1]), "x"(reinterpret_cast<const __m128 *>(&tmp0)[2]), "x"(reinterpret_cast<const __m128 *>(&tmp0)[3])); } }; #endif template<typename T> static inline void keepResults(const T &tmp0) { KeepResultsHelper<T, sizeof(T)>::keep(tmp0); } template<typename Vector> class DoMemIos { public: static void run() { Benchmark::setColumnData("MemorySize", "half L1"); run(CpuId::L1Data() / (sizeof(Vector) * 2), 128); Benchmark::setColumnData("MemorySize", "L1"); run(CpuId::L1Data() / (sizeof(Vector) * 1), 128); Benchmark::setColumnData("MemorySize", "half L2"); run(CpuId::L2Data() / (sizeof(Vector) * 2), 32); Benchmark::setColumnData("MemorySize", "L2"); run(CpuId::L2Data() / (sizeof(Vector) * 1), 16); if (CpuId::L3Data() > 0) { Benchmark::setColumnData("MemorySize", "half L3"); run(CpuId::L3Data() / (sizeof(Vector) * 2), 2); Benchmark::setColumnData("MemorySize", "L3"); run(CpuId::L3Data() / (sizeof(Vector) * 1), 2); Benchmark::setColumnData("MemorySize", "4x L3"); run(CpuId::L3Data() / sizeof(Vector) * 4, 1); } else { Benchmark::setColumnData("MemorySize", "4x L2"); run(CpuId::L2Data() / sizeof(Vector) * 4, 1); } } private: static void run(const int Factor, const int Factor2) { Vector *a = new Vector[Factor]; #ifndef VC_BENCHMARK_NO_MLOCK mlock(a, Factor * sizeof(Vector)); #endif { Benchmark bm("write", sizeof(Vector) * Factor * Factor2, "Byte"); const Vector foo = PseudoRandom<Vector>::next(); keepResults(foo); for (int i = 0; i < Factor; i += 4) { a[i + 0] = foo; a[i + 1] = foo; a[i + 2] = foo; a[i + 3] = foo; } while (bm.wantsMoreDataPoints()) { bm.Start(); for (int j = 0; j < Factor2; ++j) { keepResults(foo); for (int i = 0; i < Factor; i += 4) { a[i + 0] = foo; a[i + 1] = foo; a[i + 2] = foo; a[i + 3] = foo; } } bm.Stop(); } bm.Print(); } { Benchmark timer("r/w", sizeof(Vector) * Factor * Factor2, "Byte"); const Vector foo = PseudoRandom<Vector>::next(); while (timer.wantsMoreDataPoints()) { timer.Start(); for (int j = 0; j < Factor2; ++j) { keepResults(foo); for (int i = 0; i < Factor; i += 4) { const Vector &tmp0 = a[i + 0]; keepResults(tmp0); a[i + 0] = foo; const Vector &tmp1 = a[i + 1]; keepResults(tmp1); a[i + 1] = foo; const Vector &tmp2 = a[i + 2]; keepResults(tmp2); a[i + 2] = foo; const Vector &tmp3 = a[i + 3]; keepResults(tmp3); a[i + 3] = foo; } } timer.Stop(); } timer.Print(); } { Benchmark timer("read", sizeof(Vector) * Factor * Factor2, "Byte"); while (timer.wantsMoreDataPoints()) { timer.Start(); for (int j = 0; j < Factor2; ++j) { for (int i = 0; i < Factor; i += 4) { const Vector &tmp0 = a[i + 0]; keepResults(tmp0); const Vector &tmp1 = a[i + 1]; keepResults(tmp1); const Vector &tmp2 = a[i + 2]; keepResults(tmp2); const Vector &tmp3 = a[i + 3]; keepResults(tmp3); } } timer.Stop(); } timer.Print(); } delete[] a; } }; int bmain() { Benchmark::addColumn("MemorySize"); Benchmark::addColumn("datatype"); Benchmark::setColumnData("datatype", "double_v"); DoMemIos<double_v>::run(); Benchmark::setColumnData("datatype", "float_v"); DoMemIos<float_v>::run(); Benchmark::setColumnData("datatype", "short_v"); DoMemIos<short_v>::run(); return 0; } <|endoftext|>
<commit_before>// // Created by Miguel Rentes on 30/01/2017. // #include "STL.h" void printKMax(int arr[], int n, int k) { deque<int> mydeque; int greatest = 0; int value = 0; int index = 0; int iteration = 0; // pushing all the greatest values on each k-elements to the front of the deque for (int i = 0; i < n; ) { if (index < k) { value = arr[i]; if (value > greatest) greatest = value; if (index == k - 1) { mydeque.push_front(greatest); greatest = 0; index = 0; iteration++; i = iteration; } else { index++; i++; } } } // pop-ing the greatest values from the back of the deque while(mydeque.size() > 0) { cout << mydeque.back() << " "; mydeque.pop_back(); } cout << endl; } int main(void) { int t; cin >> t; while (t > 0) { int n, k; cin >> n >> k; int i; int arr[n]; for (i = 0; i < n; i++) cin >> arr[i]; printKMax(arr, n, k); t--; } return EXIT_SUCCESS; }<commit_msg>Starts solution for the Deque-STL challenge.<commit_after>// // Created by Miguel Rentes on 30/01/2017. // #include "STL.h" void printKMax(int arr[], int n, int k) { deque<int> mydeque; int greatest = 0; int value = 0; int index = 0; int iteration = 0; /* * pushing all the greatest values on each k-elements to the front of the deque */ for (int i = 0; i < n; ) { if (index < k) { value = arr[i]; if (value > greatest) greatest = value; if (index == k - 1) { mydeque.push_front(greatest); greatest = 0; index = 0; iteration++; i = iteration; } else { index++; i++; } } } /* * pop-ing the greatest values from the back of the deque */ while(mydeque.size() > 0) { cout << mydeque.back() << " "; mydeque.pop_back(); } cout << endl; } int main(void) { int t; cin >> t; while (t > 0) { int n, k; cin >> n >> k; int i; int arr[n]; for (i = 0; i < n; i++) cin >> arr[i]; printKMax(arr, n, k); t--; } return EXIT_SUCCESS; }<|endoftext|>
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "VideoWidget.h" #include <QApplication> #include <QDebug> #include <QPainter> #include <QThread> #include <QVariant> #include <QObject> #include <QDebug> #include <gst/interfaces/xoverlay.h> #ifdef Q_WS_X11 extern void qt_x11_set_global_double_buffer(bool); #endif namespace TelepathyIM { VideoWidget::VideoWidget(GstBus *bus, QWidget *parent, const QString &name) : Communication::VideoWidgetInterface(parent), bus_((GstBus *) gst_object_ref(bus)), video_overlay_(0), video_playback_element_(0), video_bin_(0), name_(name), window_id_(0), on_element_added_g_signal_(0), on_sync_message_g_signal_(0) { qDebug() << "VideoWidget " << name << " INIT STARTED"; setWindowTitle(name); // Element notifier init notifier_ = fs_element_added_notifier_new(); on_element_added_g_signal_ = g_signal_connect(notifier_, "element-added", G_CALLBACK(&VideoWidget::OnElementAdded), this); // UNIX -> autovideosink #ifdef Q_WS_X11 qt_x11_set_global_double_buffer(false); video_playback_element_ = gst_element_factory_make("autovideosink", name.toStdString().c_str()); gst_object_ref(video_playback_element_); gst_object_sink(video_playback_element_); fs_element_added_notifier_add(notifier_, GST_BIN(video_playback_element_)); #endif // WINDOWS -> autovideosink will chose one of there: glimagesink (best), directdrawsink (possible buffer errors), dshowvideosink (possible buffer errors) #ifdef Q_WS_WIN video_playback_element_ = gst_element_factory_make("glimagesink", 0); if (!video_playback_element_) { qDebug() << "VideoWidget " << name << " CANNOT CREATE video_playback_element_"; return; } //if (!video_playback_element_) //{ // fs_element_added_notifier_add(notifier_, GST_BIN(video_playback_element_)); // gst_object_ref(video_playback_element_); // gst_object_sink(video_playback_element_); //} //else //{ // Video bin init const QString video_bin_name = "video_bin_for_" + name; video_bin_ = gst_bin_new(video_bin_name.toStdString().c_str()); if (!video_bin_) { qDebug() << "VideoWidget " << name << " CANNOT CREATE video_bin_"; return; } // Add playback element to video bin gst_bin_add(GST_BIN(video_bin_), video_playback_element_); // Pad inits GstPad *static_sink_pad = gst_element_get_static_pad(video_playback_element_, "sink"); GstPad *sink_ghost_pad = gst_ghost_pad_new("sink", static_sink_pad); // Add bad to video bin gst_element_add_pad(GST_ELEMENT(video_bin_), sink_ghost_pad); gst_object_unref(G_OBJECT(static_sink_pad)); gst_object_ref(video_bin_); gst_object_sink(video_bin_); fs_element_added_notifier_add(notifier_, GST_BIN(video_bin_)); //} #endif gst_bus_enable_sync_message_emission(bus_); on_sync_message_g_signal_ = g_signal_connect(bus_, "sync-message", G_CALLBACK(&VideoWidget::OnSyncMessage), this); qDebug() << "VideoWidget " << name << " INIT COMPLETE"; // QWidget properties QPalette palette; palette.setColor(QPalette::Background, Qt::black); palette.setColor(QPalette::Window, Qt::black); setPalette(palette); setAutoFillBackground(true); setAttribute(Qt::WA_NoSystemBackground, true); setAttribute(Qt::WA_PaintOnScreen, true); resize(322, 240); setMinimumSize(322, 240); } VideoWidget::~VideoWidget() { if (notifier_) { fs_element_added_notifier_remove(notifier_, GST_BIN(video_playback_element_)); g_signal_handler_disconnect(notifier_, on_element_added_g_signal_); } if (bus_) g_signal_handler_disconnect(bus_, on_sync_message_g_signal_); if (bus_) { g_object_unref(bus_); bus_ = 0; } if (video_playback_element_) { if (GST_BIN(video_playback_element_)) g_object_unref(video_playback_element_); video_playback_element_ = 0; } if (video_bin_) { g_object_unref(video_bin_); video_bin_ = 0; } // todo unconnect signals ? } void VideoWidget::OnElementAdded(FsElementAddedNotifier *notifier, GstBin *bin, GstElement *element, VideoWidget *self) { // If element implements GST_X_OVERLAY interface, set local video_overlay_ to element // If true element = the current video sink if (!self->video_overlay_ && GST_IS_X_OVERLAY(element)) { qDebug() << self->name_ << " >> element-added CALLBACK >> Got overlay element, storing"; self->video_overlay_ = element; QMetaObject::invokeMethod(self, "WindowExposed", Qt::QueuedConnection); } // If element has property force-aspect-ratio set it to true // If true element = the current video sink if (g_object_class_find_property(G_OBJECT_GET_CLASS(element), "force-aspect-ratio")) { qDebug() << self->name_ << " >> element-added CALLBACK >> found 'force-aspect-ratio' from element"; g_object_set(G_OBJECT(element), "force-aspect-ratio", TRUE, NULL); } } void VideoWidget::OnSyncMessage(GstBus *bus, GstMessage *message, VideoWidget *self) { // Return if we are not interested in the message content if (GST_MESSAGE_TYPE(message) != GST_MESSAGE_ELEMENT) return; if (GST_MESSAGE_SRC(message) != (GstObject *)self->video_overlay_) return; // If message is about preparing xwindow id its from the current video sink // and we want to set our own qt widget window id where we want to render video const GstStructure *s = gst_message_get_structure(message); if (gst_structure_has_name(s, "prepare-xwindow-id") && self->video_overlay_) { qDebug() << self->name_ << " >> sync-message CALLBACK >> found 'prepare-xwindow-id' from GstMessage"; QMetaObject::invokeMethod(self, "SetOverlay", Qt::QueuedConnection); } } void VideoWidget::showEvent(QShowEvent *showEvent) { // Override showEvent so we can set QWidget attributes and set overlay qDebug() << name_ << " >> QWidget::showEvent() override called"; QWidget::showEvent(showEvent); SetOverlay(); } void VideoWidget::SetOverlay() { if (video_overlay_ && GST_IS_X_OVERLAY(video_overlay_)) { // Get window id from this widget and set it for video sink // so it renders to our widget id and does not open separate window (that is the default behaviour) qDebug() << name_ << " >> SetOverlay() called"; window_id_ = winId(); if (window_id_) { qDebug() << name_ << " >> Giving x overlay widgets window id " << window_id_; #ifdef Q_WS_X11 QApplication::syncX(); #endif gst_x_overlay_set_xwindow_id(GST_X_OVERLAY(video_overlay_), (gulong)window_id_); } } WindowExposed(); } void VideoWidget::WindowExposed() { if (video_overlay_ && GST_IS_X_OVERLAY(video_overlay_)) { // Expose the overlay (some sort of update) qDebug() << name_ << " >> WindowExposed() called"; #ifdef Q_WS_X11 QApplication::syncX(); #endif gst_x_overlay_expose(GST_X_OVERLAY(video_overlay_)); } } GstElement *VideoWidget::GetVideoPlaybackElement() const { if (video_bin_) return video_bin_; else if (video_playback_element_) return video_playback_element_; else return 0; } bool VideoWidget::VideoAvailable() { if (video_overlay_) return true; else return false; } } <commit_msg>remove unnecessary gst unref call<commit_after>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "VideoWidget.h" #include <QApplication> #include <QDebug> #include <QPainter> #include <QThread> #include <QVariant> #include <QObject> #include <QDebug> #include <gst/interfaces/xoverlay.h> #ifdef Q_WS_X11 extern void qt_x11_set_global_double_buffer(bool); #endif namespace TelepathyIM { VideoWidget::VideoWidget(GstBus *bus, QWidget *parent, const QString &name) : Communication::VideoWidgetInterface(parent), bus_((GstBus *) gst_object_ref(bus)), video_overlay_(0), video_playback_element_(0), video_bin_(0), name_(name), window_id_(0), on_element_added_g_signal_(0), on_sync_message_g_signal_(0) { qDebug() << "VideoWidget " << name << " INIT STARTED"; setWindowTitle(name); // Element notifier init notifier_ = fs_element_added_notifier_new(); on_element_added_g_signal_ = g_signal_connect(notifier_, "element-added", G_CALLBACK(&VideoWidget::OnElementAdded), this); // UNIX -> autovideosink #ifdef Q_WS_X11 qt_x11_set_global_double_buffer(false); video_playback_element_ = gst_element_factory_make("autovideosink", name.toStdString().c_str()); gst_object_ref(video_playback_element_); gst_object_sink(video_playback_element_); fs_element_added_notifier_add(notifier_, GST_BIN(video_playback_element_)); #endif // WINDOWS -> autovideosink will chose one of there: glimagesink (best), directdrawsink (possible buffer errors), dshowvideosink (possible buffer errors) #ifdef Q_WS_WIN video_playback_element_ = gst_element_factory_make("glimagesink", 0); if (!video_playback_element_) { qDebug() << "VideoWidget " << name << " CANNOT CREATE video_playback_element_"; return; } //if (!video_playback_element_) //{ // fs_element_added_notifier_add(notifier_, GST_BIN(video_playback_element_)); // gst_object_ref(video_playback_element_); // gst_object_sink(video_playback_element_); //} //else //{ // Video bin init const QString video_bin_name = "video_bin_for_" + name; video_bin_ = gst_bin_new(video_bin_name.toStdString().c_str()); if (!video_bin_) { qDebug() << "VideoWidget " << name << " CANNOT CREATE video_bin_"; return; } // Add playback element to video bin gst_bin_add(GST_BIN(video_bin_), video_playback_element_); // Pad inits GstPad *static_sink_pad = gst_element_get_static_pad(video_playback_element_, "sink"); GstPad *sink_ghost_pad = gst_ghost_pad_new("sink", static_sink_pad); // Add bad to video bin gst_element_add_pad(GST_ELEMENT(video_bin_), sink_ghost_pad); gst_object_unref(G_OBJECT(static_sink_pad)); gst_object_ref(video_bin_); gst_object_sink(video_bin_); fs_element_added_notifier_add(notifier_, GST_BIN(video_bin_)); //} #endif gst_bus_enable_sync_message_emission(bus_); on_sync_message_g_signal_ = g_signal_connect(bus_, "sync-message", G_CALLBACK(&VideoWidget::OnSyncMessage), this); qDebug() << "VideoWidget " << name << " INIT COMPLETE"; // QWidget properties QPalette palette; palette.setColor(QPalette::Background, Qt::black); palette.setColor(QPalette::Window, Qt::black); setPalette(palette); setAutoFillBackground(true); setAttribute(Qt::WA_NoSystemBackground, true); setAttribute(Qt::WA_PaintOnScreen, true); resize(322, 240); setMinimumSize(322, 240); } VideoWidget::~VideoWidget() { if (notifier_) { fs_element_added_notifier_remove(notifier_, GST_BIN(video_playback_element_)); g_signal_handler_disconnect(notifier_, on_element_added_g_signal_); } if (bus_) g_signal_handler_disconnect(bus_, on_sync_message_g_signal_); if (bus_) { g_object_unref(bus_); bus_ = 0; } if (video_playback_element_) { //if (GST_BIN(video_playback_element_)) // g_object_unref(video_playback_element_); video_playback_element_ = 0; } if (video_bin_) { g_object_unref(video_bin_); video_bin_ = 0; } // todo unconnect signals ? } void VideoWidget::OnElementAdded(FsElementAddedNotifier *notifier, GstBin *bin, GstElement *element, VideoWidget *self) { // If element implements GST_X_OVERLAY interface, set local video_overlay_ to element // If true element = the current video sink if (!self->video_overlay_ && GST_IS_X_OVERLAY(element)) { qDebug() << self->name_ << " >> element-added CALLBACK >> Got overlay element, storing"; self->video_overlay_ = element; QMetaObject::invokeMethod(self, "WindowExposed", Qt::QueuedConnection); } // If element has property force-aspect-ratio set it to true // If true element = the current video sink if (g_object_class_find_property(G_OBJECT_GET_CLASS(element), "force-aspect-ratio")) { qDebug() << self->name_ << " >> element-added CALLBACK >> found 'force-aspect-ratio' from element"; g_object_set(G_OBJECT(element), "force-aspect-ratio", TRUE, NULL); } } void VideoWidget::OnSyncMessage(GstBus *bus, GstMessage *message, VideoWidget *self) { // Return if we are not interested in the message content if (GST_MESSAGE_TYPE(message) != GST_MESSAGE_ELEMENT) return; if (GST_MESSAGE_SRC(message) != (GstObject *)self->video_overlay_) return; // If message is about preparing xwindow id its from the current video sink // and we want to set our own qt widget window id where we want to render video const GstStructure *s = gst_message_get_structure(message); if (gst_structure_has_name(s, "prepare-xwindow-id") && self->video_overlay_) { qDebug() << self->name_ << " >> sync-message CALLBACK >> found 'prepare-xwindow-id' from GstMessage"; QMetaObject::invokeMethod(self, "SetOverlay", Qt::QueuedConnection); } } void VideoWidget::showEvent(QShowEvent *showEvent) { // Override showEvent so we can set QWidget attributes and set overlay qDebug() << name_ << " >> QWidget::showEvent() override called"; QWidget::showEvent(showEvent); SetOverlay(); } void VideoWidget::SetOverlay() { if (video_overlay_ && GST_IS_X_OVERLAY(video_overlay_)) { // Get window id from this widget and set it for video sink // so it renders to our widget id and does not open separate window (that is the default behaviour) qDebug() << name_ << " >> SetOverlay() called"; window_id_ = winId(); if (window_id_) { qDebug() << name_ << " >> Giving x overlay widgets window id " << window_id_; #ifdef Q_WS_X11 QApplication::syncX(); #endif gst_x_overlay_set_xwindow_id(GST_X_OVERLAY(video_overlay_), (gulong)window_id_); } } WindowExposed(); } void VideoWidget::WindowExposed() { if (video_overlay_ && GST_IS_X_OVERLAY(video_overlay_)) { // Expose the overlay (some sort of update) qDebug() << name_ << " >> WindowExposed() called"; #ifdef Q_WS_X11 QApplication::syncX(); #endif gst_x_overlay_expose(GST_X_OVERLAY(video_overlay_)); } } GstElement *VideoWidget::GetVideoPlaybackElement() const { if (video_bin_) return video_bin_; else if (video_playback_element_) return video_playback_element_; else return 0; } bool VideoWidget::VideoAvailable() { if (video_overlay_) return true; else return false; } } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This utility program exists to process the False Start blacklist file into // a static hash table so that it can be efficiently queried by Chrome. #include <stdio.h> #include <stdlib.h> #include <set> #include <string> #include <vector> #include "base/basictypes.h" #include "net/base/ssl_false_start_blacklist.h" using net::SSLFalseStartBlacklist; static const unsigned kBuckets = SSLFalseStartBlacklist::kBuckets; static bool verbose = false; static int usage(const char* argv0) { fprintf(stderr, "Usage: %s <blacklist file> <output .c file>\n", argv0); return 1; } // StripWWWPrefix removes "www." from the beginning of any elements of the // vector. static void StripWWWPrefix(std::vector<std::string>* hosts) { static const char kPrefix[] = "www."; static const unsigned kPrefixLen = sizeof(kPrefix) - 1; for (size_t i = 0; i < hosts->size(); i++) { const std::string& h = (*hosts)[i]; if (h.size() >= kPrefixLen && memcmp(h.data(), kPrefix, kPrefixLen) == 0) { (*hosts)[i] = h.substr(kPrefixLen, h.size() - kPrefixLen); } } } // RemoveDuplicateEntries removes all duplicates from |hosts|. static void RemoveDuplicateEntries(std::vector<std::string>* hosts) { std::set<std::string> hosts_set; std::vector<std::string> ret; for (std::vector<std::string>::const_iterator i = hosts->begin(); i != hosts->end(); i++) { if (hosts_set.count(*i)) { if (verbose) fprintf(stderr, "Removing duplicate entry for %s\n", i->c_str()); continue; } hosts_set.insert(*i); ret.push_back(*i); } hosts->swap(ret); } // ParentDomain returns the parent domain for a given domain name or the empty // string if the name is a top-level domain. static std::string ParentDomain(const std::string& in) { for (size_t i = 0; i < in.size(); i++) { if (in[i] == '.') { return in.substr(i + 1, in.size() - i - 1); } } return std::string(); } // RemoveRedundantEntries removes any entries which are subdomains of other // entries. (i.e. foo.example.com would be removed if example.com were also // included.) static void RemoveRedundantEntries(std::vector<std::string>* hosts) { std::set<std::string> hosts_set; std::vector<std::string> ret; for (std::vector<std::string>::const_iterator i = hosts->begin(); i != hosts->end(); i++) { hosts_set.insert(*i); } for (std::vector<std::string>::const_iterator i = hosts->begin(); i != hosts->end(); i++) { std::string parent = ParentDomain(*i); while (!parent.empty()) { if (hosts_set.count(parent)) break; parent = ParentDomain(parent); } if (parent.empty()) { ret.push_back(*i); } else { if (verbose) fprintf(stderr, "Removing %s as redundant\n", i->c_str()); } } hosts->swap(ret); } // CheckLengths returns true iff every host is less than 256 bytes long (not // including the terminating NUL) and contains two or more labels. static bool CheckLengths(const std::vector<std::string>& hosts) { for (std::vector<std::string>::const_iterator i = hosts.begin(); i != hosts.end(); i++) { if (i->size() >= 256) { fprintf(stderr, "Entry %s is too large\n", i->c_str()); return false; } if (SSLFalseStartBlacklist::LastTwoLabels(i->c_str()) == NULL) { fprintf(stderr, "Entry %s contains too few labels\n", i->c_str()); return false; } } return true; } int main(int argc, char** argv) { if (argc != 3) return usage(argv[0]); const char* input_file = argv[1]; const char* output_file = argv[2]; FILE* input = fopen(input_file, "r"); if (!input) { perror("open"); return usage(argv[0]); } if (fseek(input, 0, SEEK_END)) { perror("fseek"); return 1; } const long input_size = ftell(input); if (fseek(input, 0, SEEK_SET)) { perror("fseek"); return 1; } char* buffer = static_cast<char*>(malloc(input_size)); if (fread(buffer, input_size, 1, input) != 1) { perror("fread"); free(buffer); fclose(input); return 1; } fclose(input); std::vector<std::string> hosts; off_t line_start = 0; bool is_comment = false; bool non_whitespace_seen = false; for (long i = 0; i <= input_size; i++) { if (i == input_size || buffer[i] == '\n') { if (!is_comment && non_whitespace_seen) hosts.push_back(std::string(&buffer[line_start], i - line_start)); is_comment = false; non_whitespace_seen = false; line_start = i + 1; continue; } if (i == line_start && buffer[i] == '#') is_comment = true; if (buffer[i] != ' ' && buffer[i] != '\t') non_whitespace_seen = true; } free(buffer); fprintf(stderr, "Have %d hosts after parse\n", (int) hosts.size()); StripWWWPrefix(&hosts); RemoveDuplicateEntries(&hosts); fprintf(stderr, "Have %d hosts after removing duplicates\n", (int) hosts.size()); RemoveRedundantEntries(&hosts); fprintf(stderr, "Have %d hosts after removing redundants\n", (int) hosts.size()); if (!CheckLengths(hosts)) { fprintf(stderr, "One or more entries is too large or too small\n"); return 2; } fprintf(stderr, "Using %d entry hash table\n", kBuckets); uint32 table[kBuckets]; std::vector<std::string> buckets[kBuckets]; for (std::vector<std::string>::const_iterator i = hosts.begin(); i != hosts.end(); i++) { const char* last_two_labels = SSLFalseStartBlacklist::LastTwoLabels(i->c_str()); const unsigned h = SSLFalseStartBlacklist::Hash(last_two_labels); buckets[h & (kBuckets - 1)].push_back(*i); } std::string table_data; unsigned max_bucket_size = 0; for (unsigned i = 0; i < kBuckets; i++) { if (buckets[i].size() > max_bucket_size) max_bucket_size = buckets[i].size(); table[i] = table_data.size(); for (std::vector<std::string>::const_iterator j = buckets[i].begin(); j != buckets[i].end(); j++) { table_data.push_back((char) j->size()); table_data.append(*j); } } fprintf(stderr, "Largest bucket has %d entries\n", max_bucket_size); FILE* out = fopen(output_file, "w+"); if (!out) { perror("opening output file"); return 4; } fprintf(out, "// Copyright (c) 2010 The Chromium Authors. All rights " "reserved.\n// Use of this source code is governed by a BSD-style " "license that can be\n// found in the LICENSE file.\n\n"); fprintf(out, "// WARNING: this code is generated by\n" "// ssl_false_start_blacklist_process.cc. Do not edit.\n\n"); fprintf(out, "#include \"base/basictypes.h\"\n\n"); fprintf(out, "#include \"net/base/ssl_false_start_blacklist.h\"\n\n"); fprintf(out, "namespace net {\n\n"); fprintf(out, "const uint32 SSLFalseStartBlacklist::kHashTable[%d + 1] = {\n", kBuckets); for (unsigned i = 0; i < kBuckets; i++) { fprintf(out, " %u,\n", (unsigned) table[i]); } fprintf(out, " %u,\n", (unsigned) table_data.size()); fprintf(out, "};\n\n"); fprintf(out, "const char SSLFalseStartBlacklist::kHashData[] = \n"); for (unsigned i = 0, line_length = 0; i < table_data.size(); i++) { if (line_length == 0) fprintf(out, " \""); uint8 c = static_cast<uint8>(table_data[i]); if (c < 32 || c > 127 || c == '"') { fprintf(out, "\\%c%c%c", '0' + ((c >> 6) & 7), '0' + ((c >> 3) & 7), '0' + (c & 7)); line_length += 4; } else { fprintf(out, "%c", c); line_length++; } if (i == table_data.size() - 1) { fprintf(out, "\";\n"); } else if (line_length >= 70) { fprintf(out, "\"\n"); line_length = 0; } } fprintf(out, "\n} // namespace net\n"); fclose(out); return 0; } <commit_msg>net: use a char array for the False Start blacklist.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This utility program exists to process the False Start blacklist file into // a static hash table so that it can be efficiently queried by Chrome. #include <stdio.h> #include <stdlib.h> #include <set> #include <string> #include <vector> #include "base/basictypes.h" #include "net/base/ssl_false_start_blacklist.h" using net::SSLFalseStartBlacklist; static const unsigned kBuckets = SSLFalseStartBlacklist::kBuckets; static bool verbose = false; static int usage(const char* argv0) { fprintf(stderr, "Usage: %s <blacklist file> <output .c file>\n", argv0); return 1; } // StripWWWPrefix removes "www." from the beginning of any elements of the // vector. static void StripWWWPrefix(std::vector<std::string>* hosts) { static const char kPrefix[] = "www."; static const unsigned kPrefixLen = sizeof(kPrefix) - 1; for (size_t i = 0; i < hosts->size(); i++) { const std::string& h = (*hosts)[i]; if (h.size() >= kPrefixLen && memcmp(h.data(), kPrefix, kPrefixLen) == 0) { (*hosts)[i] = h.substr(kPrefixLen, h.size() - kPrefixLen); } } } // RemoveDuplicateEntries removes all duplicates from |hosts|. static void RemoveDuplicateEntries(std::vector<std::string>* hosts) { std::set<std::string> hosts_set; std::vector<std::string> ret; for (std::vector<std::string>::const_iterator i = hosts->begin(); i != hosts->end(); i++) { if (hosts_set.count(*i)) { if (verbose) fprintf(stderr, "Removing duplicate entry for %s\n", i->c_str()); continue; } hosts_set.insert(*i); ret.push_back(*i); } hosts->swap(ret); } // ParentDomain returns the parent domain for a given domain name or the empty // string if the name is a top-level domain. static std::string ParentDomain(const std::string& in) { for (size_t i = 0; i < in.size(); i++) { if (in[i] == '.') { return in.substr(i + 1, in.size() - i - 1); } } return std::string(); } // RemoveRedundantEntries removes any entries which are subdomains of other // entries. (i.e. foo.example.com would be removed if example.com were also // included.) static void RemoveRedundantEntries(std::vector<std::string>* hosts) { std::set<std::string> hosts_set; std::vector<std::string> ret; for (std::vector<std::string>::const_iterator i = hosts->begin(); i != hosts->end(); i++) { hosts_set.insert(*i); } for (std::vector<std::string>::const_iterator i = hosts->begin(); i != hosts->end(); i++) { std::string parent = ParentDomain(*i); while (!parent.empty()) { if (hosts_set.count(parent)) break; parent = ParentDomain(parent); } if (parent.empty()) { ret.push_back(*i); } else { if (verbose) fprintf(stderr, "Removing %s as redundant\n", i->c_str()); } } hosts->swap(ret); } // CheckLengths returns true iff every host is less than 256 bytes long (not // including the terminating NUL) and contains two or more labels. static bool CheckLengths(const std::vector<std::string>& hosts) { for (std::vector<std::string>::const_iterator i = hosts.begin(); i != hosts.end(); i++) { if (i->size() >= 256) { fprintf(stderr, "Entry %s is too large\n", i->c_str()); return false; } if (SSLFalseStartBlacklist::LastTwoLabels(i->c_str()) == NULL) { fprintf(stderr, "Entry %s contains too few labels\n", i->c_str()); return false; } } return true; } int main(int argc, char** argv) { if (argc != 3) return usage(argv[0]); const char* input_file = argv[1]; const char* output_file = argv[2]; FILE* input = fopen(input_file, "r"); if (!input) { perror("open"); return usage(argv[0]); } if (fseek(input, 0, SEEK_END)) { perror("fseek"); return 1; } const long input_size = ftell(input); if (fseek(input, 0, SEEK_SET)) { perror("fseek"); return 1; } char* buffer = static_cast<char*>(malloc(input_size)); if (fread(buffer, input_size, 1, input) != 1) { perror("fread"); free(buffer); fclose(input); return 1; } fclose(input); std::vector<std::string> hosts; off_t line_start = 0; bool is_comment = false; bool non_whitespace_seen = false; for (long i = 0; i <= input_size; i++) { if (i == input_size || buffer[i] == '\n') { if (!is_comment && non_whitespace_seen) hosts.push_back(std::string(&buffer[line_start], i - line_start)); is_comment = false; non_whitespace_seen = false; line_start = i + 1; continue; } if (i == line_start && buffer[i] == '#') is_comment = true; if (buffer[i] != ' ' && buffer[i] != '\t') non_whitespace_seen = true; } free(buffer); fprintf(stderr, "Have %d hosts after parse\n", (int) hosts.size()); StripWWWPrefix(&hosts); RemoveDuplicateEntries(&hosts); fprintf(stderr, "Have %d hosts after removing duplicates\n", (int) hosts.size()); RemoveRedundantEntries(&hosts); fprintf(stderr, "Have %d hosts after removing redundants\n", (int) hosts.size()); if (!CheckLengths(hosts)) { fprintf(stderr, "One or more entries is too large or too small\n"); return 2; } fprintf(stderr, "Using %d entry hash table\n", kBuckets); uint32 table[kBuckets]; std::vector<std::string> buckets[kBuckets]; for (std::vector<std::string>::const_iterator i = hosts.begin(); i != hosts.end(); i++) { const char* last_two_labels = SSLFalseStartBlacklist::LastTwoLabels(i->c_str()); const unsigned h = SSLFalseStartBlacklist::Hash(last_two_labels); buckets[h & (kBuckets - 1)].push_back(*i); } std::string table_data; unsigned max_bucket_size = 0; for (unsigned i = 0; i < kBuckets; i++) { if (buckets[i].size() > max_bucket_size) max_bucket_size = buckets[i].size(); table[i] = table_data.size(); for (std::vector<std::string>::const_iterator j = buckets[i].begin(); j != buckets[i].end(); j++) { table_data.push_back((char) j->size()); table_data.append(*j); } } fprintf(stderr, "Largest bucket has %d entries\n", max_bucket_size); FILE* out = fopen(output_file, "w+"); if (!out) { perror("opening output file"); return 4; } fprintf(out, "// Copyright (c) 2010 The Chromium Authors. All rights " "reserved.\n// Use of this source code is governed by a BSD-style " "license that can be\n// found in the LICENSE file.\n\n"); fprintf(out, "// WARNING: this code is generated by\n" "// ssl_false_start_blacklist_process.cc. Do not edit.\n\n"); fprintf(out, "#include \"base/basictypes.h\"\n\n"); fprintf(out, "#include \"net/base/ssl_false_start_blacklist.h\"\n\n"); fprintf(out, "namespace net {\n\n"); fprintf(out, "const uint32 SSLFalseStartBlacklist::kHashTable[%d + 1] = {\n", kBuckets); for (unsigned i = 0; i < kBuckets; i++) { fprintf(out, " %u,\n", (unsigned) table[i]); } fprintf(out, " %u,\n", (unsigned) table_data.size()); fprintf(out, "};\n\n"); fprintf(out, "const char SSLFalseStartBlacklist::kHashData[] = {\n"); for (unsigned i = 0, line_length = 0; i < table_data.size(); i++) { if (line_length == 0) fprintf(out, " "); uint8 c = static_cast<uint8>(table_data[i]); line_length += fprintf(out, "%d, ", c); if (i == table_data.size() - 1) { fprintf(out, "\n};\n"); } else if (line_length >= 70) { fprintf(out, "\n"); line_length = 0; } } fprintf(out, "\n} // namespace net\n"); fclose(out); return 0; } <|endoftext|>
<commit_before><commit_msg>Simplify a proxy test. TEST=none<commit_after><|endoftext|>
<commit_before>/* * PathGrowingMatcher.cpp * * Created on: Jun 13, 2013 * Author: Henning */ #include "PathGrowingMatcher.h" #include "../auxiliary/PrioQueueForInts.h" namespace NetworKit { Matching PathGrowingMatcher::run(Graph& G) { // make copy since graph will be transformed count n = G.numberOfNodes(); // init matching to empty Matching m1(n); Matching m2(n); bool takeM1 = true; // degrees tracks degree of vertices, // avoids to make a copy of the graph and // delete vertices and edges explicitly std::vector<count> degrees(n); G.forNodes([&](node u) { degrees[u] = G.degree(u); }); // alive tracks if vertices are alive or not in the algorithm std::vector<bool> alive(n, true); count numEdges = G.numberOfEdges(); // PQ to retrieve vertices with degree > 0 quickly Aux::PrioQueueForInts bpq(degrees, n-1); // main loop while (numEdges > 0) { // use vertex with positive degree node v = bpq.extractMax(); assert(v != none); // path growing while (degrees[v] > 0) { // find heaviest incident edge node bestNeighbor = 0; edgeweight bestWeight = 0; G.forEdgesOf(v, [&](node v, node u, edgeweight weight) { if (alive[u]) { if (weight > bestWeight) { bestNeighbor = u; bestWeight = weight; } } }); if (takeM1) { // add edge to m1 m1.match(v, bestNeighbor); takeM1 = false; } else { // add edge to m2 m2.match(v, bestNeighbor); takeM1 = true; } // remove current vertex and its incident edges from graph G.forEdgesOf(v, [&](node v, node u) { if (alive[u]) { degrees[u]--; numEdges--; bpq.changePrio(u, degrees[u]); } }); alive[v] = false; bpq.remove(v); // start next iteration from best neighbor v = bestNeighbor; } } // return the heavier one of the two edgeweight weight1 = m1.weight(G); edgeweight weight2 = m2.weight(G); if (weight1 > weight2) return m1; else return m2; } } /* namespace NetworKit */ <commit_msg>PGA assertion: static graphs with all nodes alive<commit_after>/* * PathGrowingMatcher.cpp * * Created on: Jun 13, 2013 * Author: Henning */ #include "PathGrowingMatcher.h" #include "../auxiliary/PrioQueueForInts.h" namespace NetworKit { Matching PathGrowingMatcher::run(Graph& G) { // make copy since graph will be transformed count n = G.numberOfNodes(); assert(n == G.upperNodeIdBound()); // init matching to empty Matching m1(n); Matching m2(n); bool takeM1 = true; // degrees tracks degree of vertices, // avoids to make a copy of the graph and // delete vertices and edges explicitly std::vector<count> degrees(n); G.forNodes([&](node u) { degrees[u] = G.degree(u); }); // alive tracks if vertices are alive or not in the algorithm std::vector<bool> alive(n, true); count numEdges = G.numberOfEdges(); // PQ to retrieve vertices with degree > 0 quickly Aux::PrioQueueForInts bpq(degrees, n-1); // main loop while (numEdges > 0) { // use vertex with positive degree node v = bpq.extractMax(); assert(v != none); // path growing while (degrees[v] > 0) { // find heaviest incident edge node bestNeighbor = 0; edgeweight bestWeight = 0; G.forEdgesOf(v, [&](node v, node u, edgeweight weight) { if (alive[u]) { if (weight > bestWeight) { bestNeighbor = u; bestWeight = weight; } } }); if (takeM1) { // add edge to m1 m1.match(v, bestNeighbor); takeM1 = false; } else { // add edge to m2 m2.match(v, bestNeighbor); takeM1 = true; } // remove current vertex and its incident edges from graph G.forEdgesOf(v, [&](node v, node u) { if (alive[u]) { degrees[u]--; numEdges--; bpq.changePrio(u, degrees[u]); } }); alive[v] = false; bpq.remove(v); // start next iteration from best neighbor v = bestNeighbor; } } // return the heavier one of the two edgeweight weight1 = m1.weight(G); edgeweight weight2 = m2.weight(G); if (weight1 > weight2) return m1; else return m2; } } /* namespace NetworKit */ <|endoftext|>
<commit_before>/* *************************************** * Asylum3D @ 2014-12-17 *************************************** */ #ifndef __ASYLUM3D_HPP__ #define __ASYLUM3D_HPP__ /* Asylum Namespace */ namespace asy { /***************/ /* Effect Port */ /***************/ class IEffect : public asylum { private: int32s m_ref_cnt; public: /* ==== */ IEffect () { m_ref_cnt = 0; } /* ============= */ virtual ~IEffect () { } public: /* ====== */ void free () { m_ref_cnt -= 1; if (m_ref_cnt <= 0) delete this; } /* ========= */ void add_ref () { m_ref_cnt += 1; } public: /* ==================== */ virtual void enter () = 0; /* ==================== */ virtual void leave () = 0; }; /******************/ /* Attribute Port */ /******************/ class IAttrib : public asylum { protected: int64u m_type; public: /* ================ */ virtual ~IAttrib () {} public: /* ===================== */ virtual void commit () = 0; /* ============== */ int64u type () const { return (m_type); } }; // Attribute Type #define ATTR_TYPE_ALPHAOP 0x00000001ULL // Alpha Blend #define ATTR_TYPE_TEXTURE 0x00000002ULL // Have Texture #define ATTR_TYPE_SPECULAR 0x00000004ULL // Specular Light #define ATTR_TYPE_NRML_MAP 0x00000008ULL // Normal Map #define ATTR_TYPE_LGHT_MAP 0x00000010ULL // Light Map /*************/ /* Mesh Port */ /*************/ class IMesh : public asylum { public: /* ============== */ virtual ~IMesh () {} /* ===================== */ virtual void commit () = 0; }; /****************/ /* Commit Batch */ /****************/ struct commit_batch { IMesh** mesh; IAttrib* attr; /* ====== */ void free () { IMesh* tmp; size_t idx; if (this->attr != NULL) delete this->attr; if (this->mesh != NULL) { for (idx = 0; ; idx++) { tmp = this->mesh[idx]; if (tmp == NULL) break; delete tmp; } mem_free(this->mesh); } } }; /***************/ /* Object Base */ /***************/ struct object_inst; struct object_base { void* real; uint_t type; sAABB aabb; sSPHERE ball; array<commit_batch> list; void (*kill) (void* real); void (*tran) (object_inst* dest, void* param, const vec3d_t* rote, const vec3d_t* move, const vec3d_t* scale); /* ====== */ void free () { if (this->real != NULL && this->kill != NULL) this->kill(this->real); this->list.free(); } }; /*******************/ /* Object Instance */ /*******************/ struct object_inst { int32u type; mat4x4_t tran; object_base* base; union { sAABB aabb; sSPHERE ball; } bound; /* ========= */ void free () {} }; // Instance Type #define INST_TYPE_STATIC 0 #define INST_TYPE_DYNAMIC 1 /***************/ /* Commit Unit */ /***************/ struct commit_unit { object_inst* inst; commit_batch* unit; /* ========= */ void free () {} }; /***************/ /* Commit Pipe */ /***************/ struct commit_pipe { IEffect* effect; array<commit_unit> stuffz; /* ====== */ void free () { if (this->effect != NULL) this->effect->free(); this->stuffz.free(); } }; } /* namespace */ /******************/ /* Effect Factory */ /******************/ CR_API asy::IEffect* create_asy3d_ffct_array (asy::IEffect** list, size_t count); #endif /* __ASYLUM3D_HPP__ */ <commit_msg>Asylum: 加入计数用的基类<commit_after>/* *************************************** * Asylum3D @ 2014-12-17 *************************************** */ #ifndef __ASYLUM3D_HPP__ #define __ASYLUM3D_HPP__ /* Asylum Namespace */ namespace asy { /***************/ /* Effect Port */ /***************/ class IEffect : public asylum { private: int32s m_ref_cnt; public: /* ==== */ IEffect () { m_ref_cnt = 0; } /* ============= */ virtual ~IEffect () { } public: /* ====== */ void free () { m_ref_cnt -= 1; if (m_ref_cnt <= 0) delete this; } /* ========= */ void add_ref () { m_ref_cnt += 1; } public: /* ==================== */ virtual void enter () = 0; /* ==================== */ virtual void leave () = 0; }; /**************/ /* Stuff Base */ /**************/ class stuff_base : public asylum { protected: int32u m_nv, m_nt; public: /* ================== */ int32u get_vnum () const { return (m_nv); } /* ================== */ int32u get_tnum () const { return (m_nt); } }; /******************/ /* Attribute Port */ /******************/ class IAttrib : public stuff_base { protected: int64u m_type; public: /* ================ */ virtual ~IAttrib () {} public: /* ===================== */ virtual void commit () = 0; /* ============== */ int64u type () const { return (m_type); } }; // Attribute Type #define ATTR_TYPE_ALPHAOP 0x00000001ULL // Alpha Blend #define ATTR_TYPE_TEXTURE 0x00000002ULL // Have Texture #define ATTR_TYPE_SPECULAR 0x00000004ULL // Specular Light #define ATTR_TYPE_NRML_MAP 0x00000008ULL // Normal Map #define ATTR_TYPE_LGHT_MAP 0x00000010ULL // Light Map /*************/ /* Mesh Port */ /*************/ class IMesh : public stuff_base { public: /* ============== */ virtual ~IMesh () {} /* ===================== */ virtual void commit () = 0; }; /****************/ /* Commit Batch */ /****************/ struct commit_batch { IMesh** mesh; IAttrib* attr; /* ====== */ void free () { IMesh* tmp; size_t idx; if (this->attr != NULL) delete this->attr; if (this->mesh != NULL) { for (idx = 0; ; idx++) { tmp = this->mesh[idx]; if (tmp == NULL) break; delete tmp; } mem_free(this->mesh); } } }; /***************/ /* Object Base */ /***************/ struct object_inst; struct object_base { void* real; uint_t type; sAABB aabb; sSPHERE ball; array<commit_batch> list; void (*kill) (void* real); void (*tran) (object_inst* dest, void* param, const vec3d_t* rote, const vec3d_t* move, const vec3d_t* scale); /* ====== */ void free () { if (this->real != NULL && this->kill != NULL) this->kill(this->real); this->list.free(); } }; /*******************/ /* Object Instance */ /*******************/ struct object_inst { int32u type; mat4x4_t tran; object_base* base; union { sAABB aabb; sSPHERE ball; } bound; /* ========= */ void free () {} }; // Instance Type #define INST_TYPE_STATIC 0 #define INST_TYPE_DYNAMIC 1 /***************/ /* Commit Unit */ /***************/ struct commit_unit { object_inst* inst; commit_batch* unit; /* ========= */ void free () {} }; /***************/ /* Commit Pipe */ /***************/ struct commit_pipe { IEffect* effect; array<commit_unit> stuffz; /* ====== */ void free () { if (this->effect != NULL) this->effect->free(); this->stuffz.free(); } }; } /* namespace */ /******************/ /* Effect Factory */ /******************/ CR_API asy::IEffect* create_asy3d_ffct_array (asy::IEffect** list, size_t count); #endif /* __ASYLUM3D_HPP__ */ <|endoftext|>
<commit_before>//Copyright (c) 2022 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include "PolygonConnector.h" #include "linearAlg2D.h" #include "AABB.h" namespace cura { PolygonConnector::PolygonConnector(const coord_t line_width) : line_width(line_width) {} void PolygonConnector::add(const Polygons& input) { for (ConstPolygonRef poly : input) { input_polygons.push_back(poly); } } void PolygonConnector::add(const VariableWidthPaths& input) { for(const VariableWidthLines& lines : input) { for(const ExtrusionLine& line : lines) { input_paths.push_back(line); } } } void PolygonConnector::connect(Polygons& output_polygons, VariableWidthPaths& output_paths) { std::vector<Polygon> result_polygons = connectGroup(input_polygons); for(Polygon& polygon : result_polygons) { output_polygons.add(polygon); } std::vector<ExtrusionLine> result_paths = connectGroup(input_paths); output_paths.push_back(result_paths); } Point PolygonConnector::getPosition(const Point& vertex) const { return vertex; } Point PolygonConnector::getPosition(const ExtrusionJunction& junction) const { return junction.p; } coord_t PolygonConnector::getWidth(const Point&) const { return line_width; } coord_t PolygonConnector::getWidth(const ExtrusionJunction& junction) const { return junction.w; } void PolygonConnector::addVertex(Polygon& polygonal, const Point& position, const coord_t) const { polygonal.add(position); } void PolygonConnector::addVertex(Polygon& polygonal, const Point& vertex) const { polygonal.add(vertex); } void PolygonConnector::addVertex(ExtrusionLine& polygonal, const Point& position, const coord_t width) const { polygonal.emplace_back(position, width, 1); //Perimeter indices don't make sense any more once perimeters are merged. Use 1 as placeholder, being the first "normal" wall. } void PolygonConnector::addVertex(ExtrusionLine& polygonal, const ExtrusionJunction& vertex) const { polygonal.emplace_back(vertex); } bool PolygonConnector::isClosed(Polygon&) const { return true; } bool PolygonConnector::isClosed(ExtrusionLine& polygonal) const { return vSize2(polygonal.front() - polygonal.back()) < 10; } template<> ExtrusionLine PolygonConnector::createEmpty<ExtrusionLine>() const { constexpr size_t inset_index = 1; //Specialising to set inset_index to 1 instead of maximum int. Connected polys are not specific to any inset. constexpr bool is_odd = false; ExtrusionLine result(inset_index, is_odd); result.is_closed = true; return result; //No copy, via RVO. } }//namespace cura <commit_msg>Use a more standard 5um snap distance for detecting closed polys<commit_after>//Copyright (c) 2022 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include "PolygonConnector.h" #include "linearAlg2D.h" #include "AABB.h" namespace cura { PolygonConnector::PolygonConnector(const coord_t line_width) : line_width(line_width) {} void PolygonConnector::add(const Polygons& input) { for (ConstPolygonRef poly : input) { input_polygons.push_back(poly); } } void PolygonConnector::add(const VariableWidthPaths& input) { for(const VariableWidthLines& lines : input) { for(const ExtrusionLine& line : lines) { input_paths.push_back(line); } } } void PolygonConnector::connect(Polygons& output_polygons, VariableWidthPaths& output_paths) { std::vector<Polygon> result_polygons = connectGroup(input_polygons); for(Polygon& polygon : result_polygons) { output_polygons.add(polygon); } std::vector<ExtrusionLine> result_paths = connectGroup(input_paths); output_paths.push_back(result_paths); } Point PolygonConnector::getPosition(const Point& vertex) const { return vertex; } Point PolygonConnector::getPosition(const ExtrusionJunction& junction) const { return junction.p; } coord_t PolygonConnector::getWidth(const Point&) const { return line_width; } coord_t PolygonConnector::getWidth(const ExtrusionJunction& junction) const { return junction.w; } void PolygonConnector::addVertex(Polygon& polygonal, const Point& position, const coord_t) const { polygonal.add(position); } void PolygonConnector::addVertex(Polygon& polygonal, const Point& vertex) const { polygonal.add(vertex); } void PolygonConnector::addVertex(ExtrusionLine& polygonal, const Point& position, const coord_t width) const { polygonal.emplace_back(position, width, 1); //Perimeter indices don't make sense any more once perimeters are merged. Use 1 as placeholder, being the first "normal" wall. } void PolygonConnector::addVertex(ExtrusionLine& polygonal, const ExtrusionJunction& vertex) const { polygonal.emplace_back(vertex); } bool PolygonConnector::isClosed(Polygon&) const { return true; } bool PolygonConnector::isClosed(ExtrusionLine& polygonal) const { return vSize2(polygonal.front() - polygonal.back()) < 25; } template<> ExtrusionLine PolygonConnector::createEmpty<ExtrusionLine>() const { constexpr size_t inset_index = 1; //Specialising to set inset_index to 1 instead of maximum int. Connected polys are not specific to any inset. constexpr bool is_odd = false; ExtrusionLine result(inset_index, is_odd); result.is_closed = true; return result; //No copy, via RVO. } }//namespace cura <|endoftext|>
<commit_before>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/model/CModelValue.cpp,v $ $Revision: 1.24 $ $Name: $ $Author: shoops $ $Date: 2006/07/21 19:57:55 $ End CVS Header */ // Copyright 2005 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. #include <iostream> #include <string> #include <vector> #include <limits> #include "copasi.h" #include "CModel.h" #include "CModelValue.h" #include "CopasiDataModel/CCopasiDataModel.h" #include "function/CExpression.h" #include "report/CCopasiObjectReference.h" #include "report/CKeyFactory.h" #include "utilities/utility.h" //static const std::string CModelEntity::StatusName[] = { "fixed", "assignment", "ode", "determined by reactions", "" }; //static const char * CModelEntity::XMLStatus[] = { "fixed", "assignment", "ode", "reactions", NULL }; // the "variable" keyword is used for compatibility reasons. It actually means "this metab is part // of the reaction network, copasi needs to figure out if it is independent, dependent (moieties) or unused." CModelEntity::CModelEntity(const std::string & name, const CCopasiContainer * pParent, const std::string & type, const unsigned C_INT32 & flag): CCopasiContainer(name, pParent, type, (flag | CCopasiObject::Container | CCopasiObject::ValueDbl)), mKey(""), mpValueAccess(NULL), mpValueData(NULL), mpIValue(NULL), mRate(0.0), mStatus(FIXED), mUsed(true), mpModel(NULL) { initObjects(); *mpIValue = 1.0; *mpValueData = std::numeric_limits<C_FLOAT64>::quiet_NaN(); CONSTRUCTOR_TRACE; } CModelEntity::CModelEntity(const CModelEntity & src, const CCopasiContainer * pParent): CCopasiContainer(src, pParent), mKey(""), mpValueAccess(NULL), mpValueData(NULL), mpIValue(NULL), mRate(src.mRate), mStatus(FIXED), mUsed(src.mUsed), mpModel(NULL) { initObjects(); setStatus(src.mStatus); *mpValueData = *src.mpValueData; *mpIValue = *src.mpIValue; CONSTRUCTOR_TRACE; } CModelEntity::~CModelEntity() { if (mpModel) mpModel->getStateTemplate().remove(this); // After the above call we definitely own the data and // therfore must destroy them. pdelete(mpValueData); pdelete(mpIValue); DESTRUCTOR_TRACE; } const std::string & CModelEntity::getKey() const {return mKey;} const C_FLOAT64 & CModelEntity::getValue() const {return *mpValueAccess;} const C_FLOAT64 & CModelEntity::getInitialValue() const {return *mpIValue;} const CModelEntity::Status & CModelEntity::getStatus() const {return mStatus;} bool CModelEntity::compile() {return true;} void CModelEntity::calculate() {} /** * Return rate of production of this entity */ const C_FLOAT64 & CModelEntity::getRate() const { return mRate; } //*********** void CModelEntity::setValue(const C_FLOAT64 & value) { if (mStatus == FIXED) return; *mpValueData = value; #ifdef COPASI_DEBUG //if (mStatus == FIXED) //std::cout << "warning: set the transient concentration on a fixed entity" << std::endl; #endif } void CModelEntity::setInitialValue(const C_FLOAT64 & initialValue) { *mpIValue = initialValue; if (mStatus != FIXED) return; } void CModelEntity::setRate(const C_FLOAT64 & rate) { mRate = rate; } // ****************** void CModelEntity::setStatus(const CModelEntity::Status & status) { if (mStatus != status) { mStatus = status; this->setValuePtr(mpValueData); if (isFixed()) { mDependencies.clear(); mpValueReference->setDirectDependencies(mDependencies); mpValueReference->clearRefresh(); mpRateReference->setDirectDependencies(mDependencies); mpRateReference->clearRefresh(); } } } void * CModelEntity::getValuePointer() const {return const_cast<C_FLOAT64 *>(mpValueAccess);} void CModelEntity::initObjects() { C_FLOAT64 Dummy; mpValueReference = static_cast<CCopasiObjectReference<C_FLOAT64> *>(addObjectReference("Value", Dummy, CCopasiObject::ValueDbl)); mpIValueReference = static_cast<CCopasiObjectReference<C_FLOAT64> *>(addObjectReference("InitialValue", Dummy, CCopasiObject::ValueDbl)); mpRateReference = static_cast<CCopasiObjectReference<C_FLOAT64> *>(addObjectReference("Rate", mRate, CCopasiObject::ValueDbl)); addObjectReference("SBMLId", mSBMLId, CCopasiObject::ValueString); mpModel = static_cast<CModel *>(getObjectAncestor("Model")); if (mpModel) { mpModel->getStateTemplate().add(this); } else { // This creates the needed values. setInitialValuePtr(NULL); setValuePtr(NULL); } } void CModelEntity::setInitialValuePtr(C_FLOAT64 * pInitialValue) { mpIValue = pInitialValue; if (!mpIValue) mpIValue = new C_FLOAT64; mpIValueReference->setReference(*mpIValue); } void CModelEntity::setValuePtr(C_FLOAT64 * pValue) { mpValueData = pValue; if (!mpValueData) mpValueData = new C_FLOAT64; if (mStatus == FIXED) mpValueAccess = mpIValue; else mpValueAccess = mpValueData; mpValueReference->setReference(*mpValueAccess); } bool CModelEntity::setObjectParent(const CCopasiContainer * pParent) { CCopasiContainer::setObjectParent(pParent); CModel * pNewModel = static_cast<CModel *>(getObjectAncestor("Model")); if (mpModel == pNewModel) return true; C_FLOAT64 InitialValue = *mpIValue; C_FLOAT64 Value = *mpValueData; if (mpModel) { mpModel->getStateTemplate().remove(this); } else { pdelete(mpIValue); pdelete(mpValueData); } if (pNewModel) { pNewModel->getStateTemplate().add(this); } else { mpValueData = new C_FLOAT64; mpIValue = new C_FLOAT64; } mpModel = pNewModel; *mpIValue = InitialValue; *mpValueData = Value; return true; } void CModelEntity::setSBMLId(const std::string& id) { this->mSBMLId = id; } const std::string& CModelEntity::getSBMLId() const { return this->mSBMLId; } void CModelEntity::setUsed(const bool & used) {mUsed = used;} const bool & CModelEntity::isUsed() const {return mUsed;} //********************************************************************+ CModelValue::CModelValue(const std::string & name, const CCopasiContainer * pParent): CModelEntity(name, pParent, "ModelValue"), mpExpression(NULL) { mKey = GlobalKeys.add("ModelValue", this); initObjects(); CONSTRUCTOR_TRACE; } CModelValue::CModelValue(const CModelValue & src, const CCopasiContainer * pParent): CModelEntity(src, pParent), mpExpression(src.isFixed() ? NULL : new CExpression(*src.mpExpression)) { mKey = GlobalKeys.add("ModelValue", this); initObjects(); CONSTRUCTOR_TRACE; } CModelValue::~CModelValue() { GlobalKeys.remove(mKey); pdelete(mpExpression); DESTRUCTOR_TRACE; } void CModelValue::initObjects() {} void CModelValue::setStatus(const CModelEntity::Status & status) { CModelEntity::setStatus(status); std::set< const CCopasiObject * > NoDependencies; std::set< const CCopasiObject * > Self; Self.insert(this); if (isFixed()) { pdelete(mpExpression); } else if (mpExpression == NULL) { mpExpression = new CExpression; } switch (getStatus()) { case ASSIGNMENT: setDirectDependencies(mpExpression->getDirectDependencies()); setRefresh(this, &CModelValue::calculate); mpValueReference->setDirectDependencies(Self); mpRateReference->setDirectDependencies(NoDependencies); break; case ODE: setDirectDependencies(mpExpression->getDirectDependencies()); setRefresh(this, &CModelValue::calculate); mpValueReference->setDirectDependencies(NoDependencies); mpRateReference->setDirectDependencies(Self); break; case FIXED: default: setDirectDependencies(NoDependencies); clearRefresh(); mpValueReference->setDirectDependencies(NoDependencies); mpRateReference->setDirectDependencies(NoDependencies); break; } } bool CModelValue::compile() { if (isFixed()) return true; std::vector< CCopasiContainer * > listOfContainer; listOfContainer.push_back(getObjectAncestor("Model")); bool success = mpExpression->compile(listOfContainer); setDirectDependencies(mpExpression->getDirectDependencies()); return success; } void CModelValue::calculate() { switch (getStatus()) { case ASSIGNMENT: *mpValueData = mpExpression->calcValue(); break; case ODE: mRate = mpExpression->calcValue(); break; default: break; } } bool CModelValue::setExpression(const std::string & expression) { if (isFixed()) return false; if (mpExpression == NULL) mpExpression = new CExpression; return mpExpression->setInfix(expression); } std::string CModelValue::getExpression() const { if (isFixed() || mpExpression == NULL) return ""; return mpExpression->getInfix(); } std::ostream & operator<<(std::ostream &os, const CModelValue & d) { os << " ++++CModelValue: " << d.getObjectName() << std::endl; os << " mValue " << *d.mpValueAccess << " mIValue " << *d.mpIValue << std::endl; os << " mRate " << d.mRate << " mStatus " << d.getStatus() << std::endl; os << " ----CModelValue " << std::endl; return os; } <commit_msg>setStatus also sets whether the model entity is used in simulation, i.e., FIXED is always unused.<commit_after>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/model/CModelValue.cpp,v $ $Revision: 1.25 $ $Name: $ $Author: shoops $ $Date: 2006/08/02 20:10:08 $ End CVS Header */ // Copyright 2005 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. #include <iostream> #include <string> #include <vector> #include <limits> #include "copasi.h" #include "CModel.h" #include "CModelValue.h" #include "CopasiDataModel/CCopasiDataModel.h" #include "function/CExpression.h" #include "report/CCopasiObjectReference.h" #include "report/CKeyFactory.h" #include "utilities/utility.h" //static const std::string CModelEntity::StatusName[] = { "fixed", "assignment", "ode", "determined by reactions", "" }; //static const char * CModelEntity::XMLStatus[] = { "fixed", "assignment", "ode", "reactions", NULL }; // the "variable" keyword is used for compatibility reasons. It actually means "this metab is part // of the reaction network, copasi needs to figure out if it is independent, dependent (moieties) or unused." CModelEntity::CModelEntity(const std::string & name, const CCopasiContainer * pParent, const std::string & type, const unsigned C_INT32 & flag): CCopasiContainer(name, pParent, type, (flag | CCopasiObject::Container | CCopasiObject::ValueDbl)), mKey(""), mpValueAccess(NULL), mpValueData(NULL), mpIValue(NULL), mRate(0.0), mStatus(FIXED), mUsed(true), mpModel(NULL) { initObjects(); *mpIValue = 1.0; *mpValueData = std::numeric_limits<C_FLOAT64>::quiet_NaN(); CONSTRUCTOR_TRACE; } CModelEntity::CModelEntity(const CModelEntity & src, const CCopasiContainer * pParent): CCopasiContainer(src, pParent), mKey(""), mpValueAccess(NULL), mpValueData(NULL), mpIValue(NULL), mRate(src.mRate), mStatus(FIXED), mUsed(src.mUsed), mpModel(NULL) { initObjects(); setStatus(src.mStatus); *mpValueData = *src.mpValueData; *mpIValue = *src.mpIValue; CONSTRUCTOR_TRACE; } CModelEntity::~CModelEntity() { if (mpModel) mpModel->getStateTemplate().remove(this); // After the above call we definitely own the data and // therfore must destroy them. pdelete(mpValueData); pdelete(mpIValue); DESTRUCTOR_TRACE; } const std::string & CModelEntity::getKey() const {return mKey;} const C_FLOAT64 & CModelEntity::getValue() const {return *mpValueAccess;} const C_FLOAT64 & CModelEntity::getInitialValue() const {return *mpIValue;} const CModelEntity::Status & CModelEntity::getStatus() const {return mStatus;} bool CModelEntity::compile() {return true;} void CModelEntity::calculate() {} /** * Return rate of production of this entity */ const C_FLOAT64 & CModelEntity::getRate() const { return mRate; } //*********** void CModelEntity::setValue(const C_FLOAT64 & value) { if (mStatus == FIXED) return; *mpValueData = value; #ifdef COPASI_DEBUG //if (mStatus == FIXED) //std::cout << "warning: set the transient concentration on a fixed entity" << std::endl; #endif } void CModelEntity::setInitialValue(const C_FLOAT64 & initialValue) { *mpIValue = initialValue; if (mStatus != FIXED) return; } void CModelEntity::setRate(const C_FLOAT64 & rate) { mRate = rate; } // ****************** void CModelEntity::setStatus(const CModelEntity::Status & status) { if (mStatus != status) { mStatus = status; this->setValuePtr(mpValueData); if (isFixed()) { mDependencies.clear(); mpValueReference->setDirectDependencies(mDependencies); mpValueReference->clearRefresh(); mpRateReference->setDirectDependencies(mDependencies); mpRateReference->clearRefresh(); mUsed = false; } else mUsed = true; // We will detect during compilation whether this is actually correct. } } void * CModelEntity::getValuePointer() const {return const_cast<C_FLOAT64 *>(mpValueAccess);} void CModelEntity::initObjects() { C_FLOAT64 Dummy; mpValueReference = static_cast<CCopasiObjectReference<C_FLOAT64> *>(addObjectReference("Value", Dummy, CCopasiObject::ValueDbl)); mpIValueReference = static_cast<CCopasiObjectReference<C_FLOAT64> *>(addObjectReference("InitialValue", Dummy, CCopasiObject::ValueDbl)); mpRateReference = static_cast<CCopasiObjectReference<C_FLOAT64> *>(addObjectReference("Rate", mRate, CCopasiObject::ValueDbl)); addObjectReference("SBMLId", mSBMLId, CCopasiObject::ValueString); mpModel = static_cast<CModel *>(getObjectAncestor("Model")); if (mpModel) { mpModel->getStateTemplate().add(this); } else { // This creates the needed values. setInitialValuePtr(NULL); setValuePtr(NULL); } } void CModelEntity::setInitialValuePtr(C_FLOAT64 * pInitialValue) { mpIValue = pInitialValue; if (!mpIValue) mpIValue = new C_FLOAT64; mpIValueReference->setReference(*mpIValue); } void CModelEntity::setValuePtr(C_FLOAT64 * pValue) { mpValueData = pValue; if (!mpValueData) mpValueData = new C_FLOAT64; if (mStatus == FIXED) mpValueAccess = mpIValue; else mpValueAccess = mpValueData; mpValueReference->setReference(*mpValueAccess); } bool CModelEntity::setObjectParent(const CCopasiContainer * pParent) { CCopasiContainer::setObjectParent(pParent); CModel * pNewModel = static_cast<CModel *>(getObjectAncestor("Model")); if (mpModel == pNewModel) return true; C_FLOAT64 InitialValue = *mpIValue; C_FLOAT64 Value = *mpValueData; if (mpModel) { mpModel->getStateTemplate().remove(this); } else { pdelete(mpIValue); pdelete(mpValueData); } if (pNewModel) { pNewModel->getStateTemplate().add(this); } else { mpValueData = new C_FLOAT64; mpIValue = new C_FLOAT64; } mpModel = pNewModel; *mpIValue = InitialValue; *mpValueData = Value; return true; } void CModelEntity::setSBMLId(const std::string& id) { this->mSBMLId = id; } const std::string& CModelEntity::getSBMLId() const { return this->mSBMLId; } void CModelEntity::setUsed(const bool & used) {mUsed = used;} const bool & CModelEntity::isUsed() const {return mUsed;} //********************************************************************+ CModelValue::CModelValue(const std::string & name, const CCopasiContainer * pParent): CModelEntity(name, pParent, "ModelValue"), mpExpression(NULL) { mKey = GlobalKeys.add("ModelValue", this); initObjects(); CONSTRUCTOR_TRACE; } CModelValue::CModelValue(const CModelValue & src, const CCopasiContainer * pParent): CModelEntity(src, pParent), mpExpression(src.isFixed() ? NULL : new CExpression(*src.mpExpression)) { mKey = GlobalKeys.add("ModelValue", this); initObjects(); CONSTRUCTOR_TRACE; } CModelValue::~CModelValue() { GlobalKeys.remove(mKey); pdelete(mpExpression); DESTRUCTOR_TRACE; } void CModelValue::initObjects() {} void CModelValue::setStatus(const CModelEntity::Status & status) { CModelEntity::setStatus(status); std::set< const CCopasiObject * > NoDependencies; std::set< const CCopasiObject * > Self; Self.insert(this); if (isFixed()) { pdelete(mpExpression); } else if (mpExpression == NULL) { mpExpression = new CExpression; } switch (getStatus()) { case ASSIGNMENT: setDirectDependencies(mpExpression->getDirectDependencies()); setRefresh(this, &CModelValue::calculate); mpValueReference->setDirectDependencies(Self); mpRateReference->setDirectDependencies(NoDependencies); break; case ODE: setDirectDependencies(mpExpression->getDirectDependencies()); setRefresh(this, &CModelValue::calculate); mpValueReference->setDirectDependencies(NoDependencies); mpRateReference->setDirectDependencies(Self); break; case FIXED: default: setDirectDependencies(NoDependencies); clearRefresh(); mpValueReference->setDirectDependencies(NoDependencies); mpRateReference->setDirectDependencies(NoDependencies); break; } } bool CModelValue::compile() { if (isFixed()) return true; std::vector< CCopasiContainer * > listOfContainer; listOfContainer.push_back(getObjectAncestor("Model")); bool success = mpExpression->compile(listOfContainer); setDirectDependencies(mpExpression->getDirectDependencies()); return success; } void CModelValue::calculate() { switch (getStatus()) { case ASSIGNMENT: *mpValueData = mpExpression->calcValue(); break; case ODE: mRate = mpExpression->calcValue(); break; default: break; } } bool CModelValue::setExpression(const std::string & expression) { if (isFixed()) return false; if (mpExpression == NULL) mpExpression = new CExpression; return mpExpression->setInfix(expression); } std::string CModelValue::getExpression() const { if (isFixed() || mpExpression == NULL) return ""; return mpExpression->getInfix(); } std::ostream & operator<<(std::ostream &os, const CModelValue & d) { os << " ++++CModelValue: " << d.getObjectName() << std::endl; os << " mValue " << *d.mpValueAccess << " mIValue " << *d.mpIValue << std::endl; os << " mRate " << d.mRate << " mStatus " << d.getStatus() << std::endl; os << " ----CModelValue " << std::endl; return os; } <|endoftext|>
<commit_before>#include <iostream> #include <cmath> #include <cstring> #include "io/BmpIO.hpp" #include "matrix/Matrix" #include "improc/Filter.hpp" #include "improc/Kernels.hpp" #include "Util.hpp" using namespace sipl; void parse_commandline(int argc, char** argv); // Actions available enum class ActionType { SOBEL, PREWITT, CANNY, UNKNOWN }; // Globals for paths & action type std::string g_infile; std::string g_outfile; uint8_t g_threshold = 0; double g_sigma = 0; double g_t1 = 0; double g_t2 = 0; ActionType g_action = ActionType::UNKNOWN; int main(int argc, char** argv) { if (argc < 5) { std::cout << "Usage:" << std::endl; std::cout << " " << argv[0] << " -i inputFileName -o outputFileName {-s t} | {-p t} | " "{-c sigma t0 t1 t2}" << std::endl; std::exit(1); } parse_commandline(argc, argv); // Read input files const auto img = BmpIO::read(g_infile); // Perform relevant action switch (g_action) { case ActionType::SOBEL: { auto grad = sobel(img); auto clipped = grad.clip(util::min<uint8_t>, util::max<uint8_t>); auto thresh = threshold_binary(clipped.as_type<uint8_t>(), g_threshold); BmpIO::write(thresh, g_outfile); break; } case ActionType::PREWITT: { auto grad = prewitt(img); auto clipped = grad.clip(util::min<uint8_t>, util::max<uint8_t>); auto thresh = threshold_binary(clipped.as_type<uint8_t>(), g_threshold); BmpIO::write(thresh, g_outfile); break; } case ActionType::CANNY: { auto thinned = canny(img, g_sigma, g_t1, g_t2); BmpIO::write(thinned, g_outfile); break; } case ActionType::UNKNOWN: std::cerr << "[error]: unknown action type" << std::endl; std::exit(1); break; } } void parse_commandline(int32_t argc, char** argv) { int32_t i = 1; while (argv[i] != nullptr && i < argc) { if (std::strncmp(argv[i], "-i", std::strlen(argv[i])) == 0) { ++i; g_infile = std::string(argv[i]); } else if (std::strncmp(argv[i], "-o", std::strlen(argv[i])) == 0) { ++i; g_outfile = std::string(argv[i]); } else if (std::strncmp(argv[i], "-s", std::strlen(argv[i])) == 0) { ++i; g_action = ActionType::SOBEL; g_threshold = uint8_t(std::stoi(argv[i])); } else if (std::strncmp(argv[i], "-p", std::strlen(argv[i])) == 0) { ++i; g_action = ActionType::PREWITT; g_threshold = std::stoi(argv[i]); } else if (std::strncmp(argv[i], "-c", std::strlen(argv[i])) == 0) { ++i; g_action = ActionType::CANNY; g_sigma = std::stod(argv[i++]); g_t1 = std::stod(argv[i++]); g_t2 = std::stod(argv[i++]); } else { g_action = ActionType::UNKNOWN; } ++i; } } <commit_msg>Change variable name<commit_after>#include <iostream> #include <cmath> #include <cstring> #include "io/BmpIO.hpp" #include "matrix/Matrix" #include "improc/Filter.hpp" #include "improc/Kernels.hpp" #include "Util.hpp" using namespace sipl; void parse_commandline(int argc, char** argv); // Actions available enum class ActionType { SOBEL, PREWITT, CANNY, UNKNOWN }; // Globals for paths & action type std::string g_infile; std::string g_outfile; uint8_t g_threshold = 0; double g_sigma = 0; // double g_t0 = 0; double g_t1 = 0; double g_t2 = 0; ActionType g_action = ActionType::UNKNOWN; int main(int argc, char** argv) { if (argc < 5) { std::cout << "Usage:" << std::endl; std::cout << " " << argv[0] << " -i inputFileName -o outputFileName {-s t} | {-p t} | " "{-c sigma t0 t1 t2}" << std::endl; std::exit(1); } parse_commandline(argc, argv); // Read input files const auto img = BmpIO::read(g_infile); // Perform relevant action switch (g_action) { case ActionType::SOBEL: { auto grad = sobel(img); auto clipped = grad.clip(util::min<uint8_t>, util::max<uint8_t>); auto thresh = threshold_binary(clipped.as_type<uint8_t>(), g_threshold); BmpIO::write(thresh, g_outfile); break; } case ActionType::PREWITT: { auto grad = prewitt(img); auto clipped = grad.clip(util::min<uint8_t>, util::max<uint8_t>); auto thresh = threshold_binary(clipped.as_type<uint8_t>(), g_threshold); BmpIO::write(thresh, g_outfile); break; } case ActionType::CANNY: { auto filtered = canny(img, g_sigma, g_t1, g_t2); BmpIO::write(filtered, g_outfile); break; } case ActionType::UNKNOWN: std::cerr << "[error]: unknown action type" << std::endl; std::exit(1); break; } } void parse_commandline(int32_t argc, char** argv) { int32_t i = 1; while (argv[i] != nullptr && i < argc) { if (std::strncmp(argv[i], "-i", std::strlen(argv[i])) == 0) { ++i; g_infile = std::string(argv[i]); } else if (std::strncmp(argv[i], "-o", std::strlen(argv[i])) == 0) { ++i; g_outfile = std::string(argv[i]); } else if (std::strncmp(argv[i], "-s", std::strlen(argv[i])) == 0) { ++i; g_action = ActionType::SOBEL; g_threshold = uint8_t(std::stoi(argv[i])); } else if (std::strncmp(argv[i], "-p", std::strlen(argv[i])) == 0) { ++i; g_action = ActionType::PREWITT; g_threshold = std::stoi(argv[i]); } else if (std::strncmp(argv[i], "-c", std::strlen(argv[i])) == 0) { ++i; g_action = ActionType::CANNY; g_sigma = std::stod(argv[i++]); // g_t0 = std::stod(argv[i++]); g_t1 = std::stod(argv[i++]); g_t2 = std::stod(argv[i++]); } else { g_action = ActionType::UNKNOWN; } ++i; } } <|endoftext|>
<commit_before><commit_msg>Update initial fight pattern<commit_after><|endoftext|>
<commit_before>#include "navier_solver.hpp" #include <fstream> using namespace mfem; using namespace navier; struct s_FlowContext { int order = 5; double kin_vis = 1.0 / 40.0; double t_final = 10e-5; double dt = 1e-5; } ctx; void vel_kovasznay(const Vector &x, double t, Vector &u) { double xi = x(0); double yi = x(1); double reynolds = 1.0 / ctx.kin_vis; double lam = 0.5 * reynolds - sqrt(0.25 * reynolds * reynolds + 4.0 * M_PI * M_PI); u(0) = 1.0 - exp(lam * xi) * cos(2.0 * M_PI * yi); u(1) = lam / (2.0 * M_PI) * exp(lam * xi) * sin(2.0 * M_PI * yi); } double pres_kovasznay(const Vector &x) { double xi = x(0); double yi = x(1); double reynolds = 1.0 / ctx.kin_vis; double lam = 0.5 * reynolds - sqrt(0.25 * reynolds * reynolds + 4.0 * M_PI * M_PI); return -0.5 * exp(2.0 * lam * xi); } int main(int argc, char *argv[]) { MPI_Session mpi(argc, argv); int serial_refinements = 0; Mesh *mesh = new Mesh(2, 4, Element::QUADRILATERAL, false, 1.5, 2.0); mesh->EnsureNodes(); GridFunction *nodes = mesh->GetNodes(); *nodes -= 0.5; for (int i = 0; i < serial_refinements; ++i) { mesh->UniformRefinement(); } if (mpi.Root()) { std::cout << "Number of elements: " << mesh->GetNE() << std::endl; } auto *pmesh = new ParMesh(MPI_COMM_WORLD, *mesh); delete mesh; // Create the flow solver. NavierSolver flowsolver(pmesh, ctx.order, ctx.kin_vis); // Set the initial condition. // This is completely user customizeable. ParGridFunction *u_ic = flowsolver.GetCurrentVelocity(); VectorFunctionCoefficient u_excoeff(pmesh->Dimension(), vel_kovasznay); u_ic->ProjectCoefficient(u_excoeff); FunctionCoefficient p_excoeff(pres_kovasznay); // Add Dirichlet boundary conditions to velocity space restricted to // selected attributes on the mesh. Array<int> attr(pmesh->bdr_attributes.Max()); attr = 1; flowsolver.AddVelDirichletBC(vel_kovasznay, attr); double t = 0.0; double dt = ctx.dt; double t_final = ctx.t_final; bool last_step = false; flowsolver.Setup(dt); double err_u = 0.0; double err_p = 0.0; ParGridFunction *u_gf = nullptr; ParGridFunction *p_gf = nullptr; for (int step = 0; !last_step; ++step) { if (t + dt >= t_final - dt / 2) { last_step = true; } flowsolver.Step(t, dt, step); // Compare against exact solution of velocity and pressure. u_gf = flowsolver.GetCurrentVelocity(); p_gf = flowsolver.GetCurrentPressure(); u_excoeff.SetTime(t); p_excoeff.SetTime(t); err_u = u_gf->ComputeL2Error(u_excoeff); err_p = p_gf->ComputeL2Error(p_excoeff); if (mpi.Root()) { printf("%.5E %.5E %.5E %.5E err\n", t, dt, err_u, err_p); fflush(stdout); } } char vishost[] = "localhost"; int visport = 19916; socketstream sol_sock(vishost, visport); sol_sock.precision(8); sol_sock << "parallel " << mpi.WorldSize() << " " << mpi.WorldRank() << "\n"; sol_sock << "solution\n" << *pmesh << *u_ic << std::flush; flowsolver.PrintTimingData(); delete pmesh; return 0; } <commit_msg>fine tune kovasznay example<commit_after>#include "navier_solver.hpp" #include <fstream> using namespace mfem; using namespace navier; struct s_FlowContext { int order = 9; double kin_vis = 1.0 / 40.0; double t_final = 100 * 0.001; double dt = 0.001; double reference_pressure = 0.0; double reynolds = 1.0 / kin_vis; double lam = 0.5 * reynolds - sqrt(0.25 * reynolds * reynolds + 4.0 * M_PI * M_PI); } ctx; void vel_kovasznay(const Vector &x, double t, Vector &u) { double xi = x(0); double yi = x(1); u(0) = 1.0 - exp(ctx.lam * xi) * cos(2.0 * M_PI * yi); u(1) = ctx.lam / (2.0 * M_PI) * exp(ctx.lam * xi) * sin(2.0 * M_PI * yi); } double pres_kovasznay(const Vector &x, double t) { double xi = x(0); double yi = x(1); return 0.5 * (1.0 - exp(2.0 * ctx.lam * xi)) + ctx.reference_pressure; } int main(int argc, char *argv[]) { MPI_Session mpi(argc, argv); int serial_refinements = 1; Mesh *mesh = new Mesh(2, 4, Element::QUADRILATERAL, false, 1.5, 2.0); mesh->EnsureNodes(); GridFunction *nodes = mesh->GetNodes(); *nodes -= 0.5; for (int i = 0; i < serial_refinements; ++i) { mesh->UniformRefinement(); } if (mpi.Root()) { std::cout << "Number of elements: " << mesh->GetNE() << std::endl; } auto *pmesh = new ParMesh(MPI_COMM_WORLD, *mesh); delete mesh; // Create the flow solver. NavierSolver flowsolver(pmesh, ctx.order, ctx.kin_vis); // Set the initial condition. // This is completely user customizeable. ParGridFunction *u_ic = flowsolver.GetCurrentVelocity(); VectorFunctionCoefficient u_excoeff(pmesh->Dimension(), vel_kovasznay); u_ic->ProjectCoefficient(u_excoeff); FunctionCoefficient p_excoeff(pres_kovasznay); // Add Dirichlet boundary conditions to velocity space restricted to // selected attributes on the mesh. Array<int> attr(pmesh->bdr_attributes.Max()); attr = 1; flowsolver.AddVelDirichletBC(vel_kovasznay, attr); flowsolver.AddPresDirichletBC(pres_kovasznay, attr); double t = 0.0; double dt = ctx.dt; double t_final = ctx.t_final; bool last_step = false; flowsolver.Setup(dt); double err_u = 0.0; double err_p = 0.0; ParGridFunction *u_gf = nullptr; ParGridFunction *p_gf = nullptr; for (int step = 0; !last_step; ++step) { if (t + dt >= t_final - dt / 2) { last_step = true; } flowsolver.Step(t, dt, step); // Compare against exact solution of velocity and pressure. u_gf = flowsolver.GetCurrentVelocity(); p_gf = flowsolver.GetCurrentPressure(); u_excoeff.SetTime(t); p_excoeff.SetTime(t); err_u = u_gf->ComputeL2Error(u_excoeff); err_p = p_gf->ComputeL2Error(p_excoeff); if (mpi.Root()) { printf("%.5E %.5E %.5E %.5E err\n", t, dt, err_u, err_p); fflush(stdout); } } char vishost[] = "localhost"; int visport = 19916; socketstream sol_sock(vishost, visport); sol_sock.precision(8); sol_sock << "parallel " << mpi.WorldSize() << " " << mpi.WorldRank() << "\n"; sol_sock << "solution\n" << *pmesh << *u_ic << std::flush; flowsolver.PrintTimingData(); delete pmesh; return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "navier_solver.hpp" #include <fstream> using namespace mfem; using namespace navier; struct s_NavierContext { int ser_ref_levels = 1; int order = 6; double kinvis = 1.0 / 40.0; double t_final = 10 * 0.001; double dt = 0.001; double reference_pressure = 0.0; double reynolds = 1.0 / kinvis; double lam = 0.5 * reynolds - sqrt(0.25 * reynolds * reynolds + 4.0 * M_PI * M_PI); bool pa = true; bool ni = false; bool visualization = false; bool checkres = false; } ctx; void vel_kovasznay(const Vector &x, double t, Vector &u) { double xi = x(0); double yi = x(1); u(0) = 1.0 - exp(ctx.lam * xi) * cos(2.0 * M_PI * yi); u(1) = ctx.lam / (2.0 * M_PI) * exp(ctx.lam * xi) * sin(2.0 * M_PI * yi); } double pres_kovasznay(const Vector &x, double t) { double xi = x(0); return 0.5 * (1.0 - exp(2.0 * ctx.lam * xi)) + ctx.reference_pressure; } int main(int argc, char *argv[]) { MPI_Session mpi(argc, argv); OptionsParser args(argc, argv); args.AddOption(&ctx.ser_ref_levels, "-rs", "--refine-serial", "Number of times to refine the mesh uniformly in serial."); args.AddOption(&ctx.order, "-o", "--order", "Order (degree) of the finite elements."); args.AddOption(&ctx.dt, "-dt", "--time-step", "Time step."); args.AddOption(&ctx.t_final, "-tf", "--final-time", "Final time."); args.AddOption(&ctx.pa, "-pa", "--enable-pa", "-no-pi", "--disable-pi", "Enable partial assembly."); args.AddOption(&ctx.ni, "-ni", "--enable-ni", "-no-ni", "--disable-ni", "Enable numerical integration rules."); args.AddOption(&ctx.visualization, "-vis", "--visualization", "-no-vis", "--no-visualization", "Enable or disable GLVis visualization."); args.AddOption( &ctx.checkres, "-cr", "--checkresult", "-no-cr", "--no-checkresult", "Enable or disable checking of the result. Returns -1 on failure."); args.Parse(); if (!args.Good()) { if (mpi.Root()) { args.PrintUsage(mfem::out); } MPI_Finalize(); return 1; } if (mpi.Root()) { args.PrintOptions(mfem::out); } Mesh *mesh = new Mesh(2, 4, Element::QUADRILATERAL, false, 1.5, 2.0); mesh->EnsureNodes(); GridFunction *nodes = mesh->GetNodes(); *nodes -= 0.5; for (int i = 0; i < ctx.ser_ref_levels; ++i) { mesh->UniformRefinement(); } if (mpi.Root()) { std::cout << "Number of elements: " << mesh->GetNE() << std::endl; } auto *pmesh = new ParMesh(MPI_COMM_WORLD, *mesh); delete mesh; // Create the flow solver. NavierSolver flowsolver(pmesh, ctx.order, ctx.kinvis); flowsolver.EnablePA(ctx.pa); flowsolver.EnableNI(ctx.ni); // Set the initial condition. // This is completely user customizeable. ParGridFunction *u_ic = flowsolver.GetCurrentVelocity(); VectorFunctionCoefficient u_excoeff(pmesh->Dimension(), vel_kovasznay); u_ic->ProjectCoefficient(u_excoeff); FunctionCoefficient p_excoeff(pres_kovasznay); // Add Dirichlet boundary conditions to velocity space restricted to // selected attributes on the mesh. Array<int> attr(pmesh->bdr_attributes.Max()); attr = 1; flowsolver.AddVelDirichletBC(vel_kovasznay, attr); double t = 0.0; double dt = ctx.dt; double t_final = ctx.t_final; bool last_step = false; flowsolver.Setup(dt); double err_u = 0.0; double err_p = 0.0; ParGridFunction *u_gf = nullptr; ParGridFunction *p_gf = nullptr; ParGridFunction p_ex_gf(p_gf->ParFESpace()); GridFunctionCoefficient p_ex_gf_coeff(&p_ex_gf); for (int step = 0; !last_step; ++step) { if (t + dt >= t_final - dt / 2) { last_step = true; } flowsolver.Step(t, dt, step); // Compare against exact solution of velocity and pressure. u_gf = flowsolver.GetCurrentVelocity(); p_gf = flowsolver.GetCurrentPressure(); u_excoeff.SetTime(t); p_excoeff.SetTime(t); // Remove mean value from exact pressure solution. p_ex_gf.ProjectCoefficient(p_excoeff); flowsolver.MeanZero(p_ex_gf); err_u = u_gf->ComputeL2Error(u_excoeff); err_p = p_gf->ComputeL2Error(p_ex_gf_coeff); if (mpi.Root()) { printf("%.2d %.2E %.2E %.5E %.5E err\n", ctx.order, t, dt, err_u, err_p); fflush(stdout); } } if (ctx.visualization) { char vishost[] = "localhost"; int visport = 19916; socketstream sol_sock(vishost, visport); sol_sock.precision(8); sol_sock << "parallel " << mpi.WorldSize() << " " << mpi.WorldRank() << "\n"; sol_sock << "solution\n" << *pmesh << *u_ic << std::flush; } flowsolver.PrintTimingData(); // Test if the result for the test run is as expected. if (ctx.checkres) { double tol = 1e-6; if (err_u > tol || err_p > tol) { if (mpi.Root()) { mfem::out << "Result has a larger error than expected." << std::endl; } return -1; } } delete pmesh; return 0; } <commit_msg>Do not get an FESpace from a nullptr<commit_after>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "navier_solver.hpp" #include <fstream> using namespace mfem; using namespace navier; struct s_NavierContext { int ser_ref_levels = 1; int order = 6; double kinvis = 1.0 / 40.0; double t_final = 10 * 0.001; double dt = 0.001; double reference_pressure = 0.0; double reynolds = 1.0 / kinvis; double lam = 0.5 * reynolds - sqrt(0.25 * reynolds * reynolds + 4.0 * M_PI * M_PI); bool pa = true; bool ni = false; bool visualization = false; bool checkres = false; } ctx; void vel_kovasznay(const Vector &x, double t, Vector &u) { double xi = x(0); double yi = x(1); u(0) = 1.0 - exp(ctx.lam * xi) * cos(2.0 * M_PI * yi); u(1) = ctx.lam / (2.0 * M_PI) * exp(ctx.lam * xi) * sin(2.0 * M_PI * yi); } double pres_kovasznay(const Vector &x, double t) { double xi = x(0); return 0.5 * (1.0 - exp(2.0 * ctx.lam * xi)) + ctx.reference_pressure; } int main(int argc, char *argv[]) { MPI_Session mpi(argc, argv); OptionsParser args(argc, argv); args.AddOption(&ctx.ser_ref_levels, "-rs", "--refine-serial", "Number of times to refine the mesh uniformly in serial."); args.AddOption(&ctx.order, "-o", "--order", "Order (degree) of the finite elements."); args.AddOption(&ctx.dt, "-dt", "--time-step", "Time step."); args.AddOption(&ctx.t_final, "-tf", "--final-time", "Final time."); args.AddOption(&ctx.pa, "-pa", "--enable-pa", "-no-pi", "--disable-pi", "Enable partial assembly."); args.AddOption(&ctx.ni, "-ni", "--enable-ni", "-no-ni", "--disable-ni", "Enable numerical integration rules."); args.AddOption(&ctx.visualization, "-vis", "--visualization", "-no-vis", "--no-visualization", "Enable or disable GLVis visualization."); args.AddOption( &ctx.checkres, "-cr", "--checkresult", "-no-cr", "--no-checkresult", "Enable or disable checking of the result. Returns -1 on failure."); args.Parse(); if (!args.Good()) { if (mpi.Root()) { args.PrintUsage(mfem::out); } MPI_Finalize(); return 1; } if (mpi.Root()) { args.PrintOptions(mfem::out); } Mesh *mesh = new Mesh(2, 4, Element::QUADRILATERAL, false, 1.5, 2.0); mesh->EnsureNodes(); GridFunction *nodes = mesh->GetNodes(); *nodes -= 0.5; for (int i = 0; i < ctx.ser_ref_levels; ++i) { mesh->UniformRefinement(); } if (mpi.Root()) { std::cout << "Number of elements: " << mesh->GetNE() << std::endl; } auto *pmesh = new ParMesh(MPI_COMM_WORLD, *mesh); delete mesh; // Create the flow solver. NavierSolver flowsolver(pmesh, ctx.order, ctx.kinvis); flowsolver.EnablePA(ctx.pa); flowsolver.EnableNI(ctx.ni); // Set the initial condition. // This is completely user customizeable. ParGridFunction *u_ic = flowsolver.GetCurrentVelocity(); VectorFunctionCoefficient u_excoeff(pmesh->Dimension(), vel_kovasznay); u_ic->ProjectCoefficient(u_excoeff); FunctionCoefficient p_excoeff(pres_kovasznay); // Add Dirichlet boundary conditions to velocity space restricted to // selected attributes on the mesh. Array<int> attr(pmesh->bdr_attributes.Max()); attr = 1; flowsolver.AddVelDirichletBC(vel_kovasznay, attr); double t = 0.0; double dt = ctx.dt; double t_final = ctx.t_final; bool last_step = false; flowsolver.Setup(dt); double err_u = 0.0; double err_p = 0.0; ParGridFunction *u_gf = nullptr; ParGridFunction *p_gf = nullptr; ParGridFunction p_ex_gf(flowsolver.GetCurrentPressure()->ParFESpace()); GridFunctionCoefficient p_ex_gf_coeff(&p_ex_gf); for (int step = 0; !last_step; ++step) { if (t + dt >= t_final - dt / 2) { last_step = true; } flowsolver.Step(t, dt, step); // Compare against exact solution of velocity and pressure. u_gf = flowsolver.GetCurrentVelocity(); p_gf = flowsolver.GetCurrentPressure(); u_excoeff.SetTime(t); p_excoeff.SetTime(t); // Remove mean value from exact pressure solution. p_ex_gf.ProjectCoefficient(p_excoeff); flowsolver.MeanZero(p_ex_gf); err_u = u_gf->ComputeL2Error(u_excoeff); err_p = p_gf->ComputeL2Error(p_ex_gf_coeff); if (mpi.Root()) { printf("%.2d %.2E %.2E %.5E %.5E err\n", ctx.order, t, dt, err_u, err_p); fflush(stdout); } } if (ctx.visualization) { char vishost[] = "localhost"; int visport = 19916; socketstream sol_sock(vishost, visport); sol_sock.precision(8); sol_sock << "parallel " << mpi.WorldSize() << " " << mpi.WorldRank() << "\n"; sol_sock << "solution\n" << *pmesh << *u_ic << std::flush; } flowsolver.PrintTimingData(); // Test if the result for the test run is as expected. if (ctx.checkres) { double tol = 1e-6; if (err_u > tol || err_p > tol) { if (mpi.Root()) { mfem::out << "Result has a larger error than expected." << std::endl; } return -1; } } delete pmesh; return 0; } <|endoftext|>
<commit_before>/*------------------------------------------------------------------------ * (The MIT License) * * Copyright (c) 2008-2011 Rhomobile, 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. * * http://rhomobile.com *------------------------------------------------------------------------*/ #include "RhoLogSink.h" #include "common/RhoFile.h" #include "common/StringConverter.h" #include "common/RhodesApp.h" #include "net/RawSocket.h" #include "net/URI.h" #if defined( OS_SYMBIAN ) #include <e32debug.h> #endif #if defined(OS_MACOSX) && !defined(RHODES_EMULATOR) extern "C" void rho_ios_log_console_output(const char* message); #endif namespace rho { CLogFileSink::CLogFileSink(const LogSettings& oSettings) : m_pFile(0), m_pPosFile(0), m_oLogConf(oSettings), m_nCirclePos(-1), m_nFileLogSize(0) { } CLogFileSink::~CLogFileSink() { if(m_pFile) delete m_pFile; } void CLogFileSink::writeLogMessage( String& strMsg ){ unsigned int len = strMsg.length(); if ( !m_pFile ) m_pFile = new common::CRhoFile(); if ( !m_pFile->isOpened() ){ m_pFile->open( getLogConf().getLogFilePath().c_str(), common::CRhoFile::OpenForAppend ); m_nFileLogSize = m_pFile->size(); loadLogPosition(); } if ( getLogConf().getMaxLogFileSize() > 0 ) { if ( ( m_nCirclePos >= 0 && m_nCirclePos + len > getLogConf().getMaxLogFileSize() ) || ( m_nCirclePos < 0 && m_nFileLogSize + len > getLogConf().getMaxLogFileSize() ) ) { m_pFile->truncate(m_pFile->getPos()); m_pFile->movePosToStart(); m_nFileLogSize = 0; m_nCirclePos = 0; } } int nWritten = m_pFile->write( strMsg.c_str(), len ); m_pFile->flush(); if ( m_nCirclePos >= 0 ) m_nCirclePos += nWritten; else m_nFileLogSize += nWritten; saveLogPosition(); } int CLogFileSink::getCurPos() { return m_nCirclePos >= 0 ? m_nCirclePos : m_nFileLogSize; } void CLogFileSink::clear(){ if ( m_pFile ) { delete m_pFile; m_pFile = NULL; } common::CRhoFile().deleteFile(getLogConf().getLogFilePath().c_str()); String strPosPath = getLogConf().getLogFilePath() + "_pos"; common::CRhoFile().deleteFile(strPosPath.c_str()); } void CLogFileSink::loadLogPosition(){ if ( !m_pPosFile ) m_pPosFile = new common::CRhoFile(); if ( !m_pPosFile->isOpened() ){ String strPosPath = getLogConf().getLogFilePath() + "_pos"; m_pPosFile->open( strPosPath.c_str(), common::CRhoFile::OpenForReadWrite ); } if ( !m_pPosFile->isOpened() ) return; String strPos; m_pPosFile->movePosToStart(); m_pPosFile->readString(strPos); if ( strPos.length() == 0 ) return; m_nCirclePos = atoi(strPos.c_str()); if ( m_nCirclePos < 0 || m_nCirclePos > (int)m_nFileLogSize ) m_nCirclePos = -1; if ( m_nCirclePos >= 0 ) m_pFile->setPosTo( m_nCirclePos ); } void CLogFileSink::saveLogPosition(){ if ( m_nCirclePos < 0 ) return; if ( m_nCirclePos > (int)getLogConf().getMaxLogFileSize() ) return; String strPos = common::convertToStringA(m_nCirclePos); for( int i = strPos.length(); i < 10; i++ ) strPos += ' '; m_pPosFile->movePosToStart(); m_pPosFile->write( strPos.c_str(), strPos.length() ); m_pPosFile->flush(); } #ifndef min #define min(a,b) (((a) < (b)) ? (a) : (b)) #endif void CLogOutputSink::writeLogMessage( String& strMsg ) { if ( strMsg.length() > 1 && strMsg[strMsg.length()-2] == '\r' ) strMsg.erase(strMsg.length()-2,1); const char* szMsg = strMsg.c_str(); #if defined( OS_WINDOWS_DESKTOP ) ::OutputDebugStringA(szMsg); #elif defined( OS_PLATFORM_MOTCE ) ::OutputDebugStringW(common::convertToStringW(strMsg).c_str()); #elif defined(OS_WP8) ::OutputDebugStringW(common::convertToStringW(strMsg).c_str()); #elif defined( OS_SYMBIAN ) TPtrC8 des((const TUint8*)szMsg); RDebug::RawPrint(des); return; #elif defined(OS_MACOSX) && !defined(RHODES_EMULATOR) rho_ios_log_console_output(szMsg); #endif #if !defined( OS_PLATFORM_MOTCE ) && !(defined(OS_MACOSX) && !defined(RHODES_EMULATOR)) for( int n = 0; n < (int)strMsg.length(); n+= 100 ) fwrite(szMsg+n, 1, min(100,strMsg.length()-n) , stdout ); fflush(stdout); #endif } CLogSocketSink::CLogSocketSink(const LogSettings& oSettings) { m_URL = oSettings.getLogURL(); CThreadQueue::setLogCategory(LogCategory("NO_LOGGING")); setPollInterval(QUEUE_POLL_INTERVAL_INFINITE); start(epLow); } CLogSocketSink::~CLogSocketSink() { //wait till all commands will be sent to server CRhoThread::stop(2000); } void CLogSocketSink::setUrl(String url) { m_URL = url; } void CLogSocketSink::writeLogMessage( String& strMsg ) { addQueueCommand(new LogCommand(m_URL.c_str(), strMsg.c_str())); } void CLogSocketSink::processCommand(IQueueCommand* pCmd) { LogCommand *cmd = (LogCommand *)pCmd; /* Checking CRhodesApp instance is needed because net request requires it to be valid. If socket sink is initialized from ext manager, log messages could occur before app instance is set so we will crash. */ if (!cmd || (common::CRhodesApp::getInstance()==0)) return; #if defined(APP_BUILD_CAPABILITY_SHARED_RUNTIME) getNet().doRequest( "GET", cmd->m_url+"?LogSeverity="+cmd->m_body[0]+"&LogComment="+net::URI::urlEncode(cmd->m_body), String(), 0, 0 ); #else getNet().doRequest( "POST", cmd->m_url, cmd->m_body, 0, 0 ); #endif } } <commit_msg>Remote log crash has been fixed.<commit_after>/*------------------------------------------------------------------------ * (The MIT License) * * Copyright (c) 2008-2011 Rhomobile, 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. * * http://rhomobile.com *------------------------------------------------------------------------*/ #include "RhoLogSink.h" #include "common/RhoFile.h" #include "common/StringConverter.h" #include "common/RhodesApp.h" #include "net/RawSocket.h" #include "net/URI.h" #if defined( OS_SYMBIAN ) #include <e32debug.h> #endif #if defined(OS_MACOSX) && !defined(RHODES_EMULATOR) extern "C" void rho_ios_log_console_output(const char* message); #endif namespace rho { CLogFileSink::CLogFileSink(const LogSettings& oSettings) : m_pFile(0), m_pPosFile(0), m_oLogConf(oSettings), m_nCirclePos(-1), m_nFileLogSize(0) { } CLogFileSink::~CLogFileSink() { if(m_pFile) delete m_pFile; } void CLogFileSink::writeLogMessage( String& strMsg ){ unsigned int len = strMsg.length(); if ( !m_pFile ) m_pFile = new common::CRhoFile(); if ( !m_pFile->isOpened() ){ m_pFile->open( getLogConf().getLogFilePath().c_str(), common::CRhoFile::OpenForAppend ); m_nFileLogSize = m_pFile->size(); loadLogPosition(); } if ( getLogConf().getMaxLogFileSize() > 0 ) { if ( ( m_nCirclePos >= 0 && m_nCirclePos + len > getLogConf().getMaxLogFileSize() ) || ( m_nCirclePos < 0 && m_nFileLogSize + len > getLogConf().getMaxLogFileSize() ) ) { m_pFile->truncate(m_pFile->getPos()); m_pFile->movePosToStart(); m_nFileLogSize = 0; m_nCirclePos = 0; } } int nWritten = m_pFile->write( strMsg.c_str(), len ); m_pFile->flush(); if ( m_nCirclePos >= 0 ) m_nCirclePos += nWritten; else m_nFileLogSize += nWritten; saveLogPosition(); } int CLogFileSink::getCurPos() { return m_nCirclePos >= 0 ? m_nCirclePos : m_nFileLogSize; } void CLogFileSink::clear(){ if ( m_pFile ) { delete m_pFile; m_pFile = NULL; } common::CRhoFile().deleteFile(getLogConf().getLogFilePath().c_str()); String strPosPath = getLogConf().getLogFilePath() + "_pos"; common::CRhoFile().deleteFile(strPosPath.c_str()); } void CLogFileSink::loadLogPosition(){ if ( !m_pPosFile ) m_pPosFile = new common::CRhoFile(); if ( !m_pPosFile->isOpened() ){ String strPosPath = getLogConf().getLogFilePath() + "_pos"; m_pPosFile->open( strPosPath.c_str(), common::CRhoFile::OpenForReadWrite ); } if ( !m_pPosFile->isOpened() ) return; String strPos; m_pPosFile->movePosToStart(); m_pPosFile->readString(strPos); if ( strPos.length() == 0 ) return; m_nCirclePos = atoi(strPos.c_str()); if ( m_nCirclePos < 0 || m_nCirclePos > (int)m_nFileLogSize ) m_nCirclePos = -1; if ( m_nCirclePos >= 0 ) m_pFile->setPosTo( m_nCirclePos ); } void CLogFileSink::saveLogPosition(){ if ( m_nCirclePos < 0 ) return; if ( m_nCirclePos > (int)getLogConf().getMaxLogFileSize() ) return; String strPos = common::convertToStringA(m_nCirclePos); for( int i = strPos.length(); i < 10; i++ ) strPos += ' '; m_pPosFile->movePosToStart(); m_pPosFile->write( strPos.c_str(), strPos.length() ); m_pPosFile->flush(); } #ifndef min #define min(a,b) (((a) < (b)) ? (a) : (b)) #endif void CLogOutputSink::writeLogMessage( String& strMsg ) { if ( strMsg.length() > 1 && strMsg[strMsg.length()-2] == '\r' ) strMsg.erase(strMsg.length()-2,1); const char* szMsg = strMsg.c_str(); #if defined( OS_WINDOWS_DESKTOP ) ::OutputDebugStringA(szMsg); #elif defined( OS_PLATFORM_MOTCE ) ::OutputDebugStringW(common::convertToStringW(strMsg).c_str()); #elif defined(OS_WP8) ::OutputDebugStringW(common::convertToStringW(strMsg).c_str()); #elif defined( OS_SYMBIAN ) TPtrC8 des((const TUint8*)szMsg); RDebug::RawPrint(des); return; #elif defined(OS_MACOSX) && !defined(RHODES_EMULATOR) rho_ios_log_console_output(szMsg); #endif #if !defined( OS_PLATFORM_MOTCE ) && !(defined(OS_MACOSX) && !defined(RHODES_EMULATOR)) for( int n = 0; n < (int)strMsg.length(); n+= 100 ) fwrite(szMsg+n, 1, min(100,strMsg.length()-n) , stdout ); fflush(stdout); #endif } CLogSocketSink::CLogSocketSink(const LogSettings& oSettings) { m_URL = oSettings.getLogURL(); CThreadQueue::setLogCategory(LogCategory("NO_LOGGING")); setPollInterval(QUEUE_POLL_INTERVAL_INFINITE); #if !defined( OS_WINDOWS_DESKTOP ) start(epLow); #endif } CLogSocketSink::~CLogSocketSink() { //wait till all commands will be sent to server #if !defined( OS_WINDOWS_DESKTOP ) CRhoThread::stop(2000); #endif } void CLogSocketSink::setUrl(String url) { m_URL = url; } void CLogSocketSink::writeLogMessage( String& strMsg ) { addQueueCommand(new LogCommand(m_URL.c_str(), strMsg.c_str())); } void CLogSocketSink::processCommand(IQueueCommand* pCmd) { LogCommand *cmd = (LogCommand *)pCmd; /* Checking CRhodesApp instance is needed because net request requires it to be valid. If socket sink is initialized from ext manager, log messages could occur before app instance is set so we will crash. */ if (!cmd || (common::CRhodesApp::getInstance()==0)) return; #if defined(APP_BUILD_CAPABILITY_SHARED_RUNTIME) getNet().doRequest( "GET", cmd->m_url+"?LogSeverity="+cmd->m_body[0]+"&LogComment="+net::URI::urlEncode(cmd->m_body), String(), 0, 0 ); #else getNet().doRequest( "POST", cmd->m_url, cmd->m_body, 0, 0 ); #endif } } <|endoftext|>
<commit_before> #include <jni.h> extern "C" { void init(JNIEnv *env, jobject local_store_java, jobject asset_manager, int width, int height); void update(); void touch(int touch_id, int action, double x, double y); } #include <android/asset_manager.h> #include <android/asset_manager_jni.h> #include <GLES/gl.h> #include "gameengine/android/modules/ad_engine_android.h" #include "gameengine/android/modules/analytics_engine_android.h" #include "gameengine/android/modules/game_engine_factory_android.h" #include "gameengine/android/modules/local_store_android.h" #include "gameengine/game_engine.h" #include "gameengine/game_engine.h" #include "soundengine/sound_player.h" static sp<GameEngine> game_engine_; void init(JNIEnv *env, jobject local_store_java, jobject asset_manager, int width, int height) { glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glDepthMask(false); glEnable(GL_CULL_FACE); glEnable(GL_BLEND); glEnable(GL_TEXTURE_2D); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); // TODO This shouldn't be hardcoded. Rethink this anyways. game_engine_.reset(new GameEngine()); Texture2D::SetScreenHeight(height); game_engine_->set_screen_size(screen_size_make(width, height)); game_engine_->set_platform_type(kPlatformTypePhone); game_engine_->set_platform_resolution(kPlatformResolutionHigh); sp<GameEngineFactory> factory = sp<GameEngineFactory>(new GameEngineFactoryAndroid()); game_engine_->set_factory(factory); sp<LocalStore> local_store = sp<LocalStore>(new LocalStoreAndroid(env, local_store_java)); game_engine_->set_local_store(local_store); sp<AdEngine> ad_engine = sp<AdEngine>(new AdEngineAndroid()); game_engine_->set_ad_engine(ad_engine); sp<AnalyticsEngine> analytics_engine = sp<AnalyticsEngine>(new AnalyticsEngineAndroid()); game_engine_->set_analytics_engine(analytics_engine); AAssetManager *mgr = AAssetManager_fromJava(env, asset_manager); assert(NULL != mgr); // TODO casting is bad ((SoundPlayerImpl *)SoundPlayer::instance())->setAssetManager(mgr); sharkengine_init(game_engine_); } void update() { game_engine_->Update(); int backingWidth_ = 640; int backingHeight_ = 1138; glViewport(0, 0, backingWidth_, backingHeight_); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrthof(0, backingWidth_, 0, backingHeight_, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); game_engine_->Render(); } #include "gameengine/touch.h" #include <vector> using std::vector; void touch(int touch_id, int action, double x, double y) { Touch touch; touch.set_location(game_engine_->screen_point_to_game_point(screen_point_make(x, y))); touch.set_identifier((void *)touch_id); if (action == 0) { game_engine_->AddTouchBegan(touch); } else if (action == 1) { game_engine_->AddTouchEnded(touch); } else if (action == 2) { game_engine_->AddTouchMoved(touch); } } <commit_msg>[Android] Fix issue with NULL Touch identifiers.<commit_after> #include <jni.h> extern "C" { void init(JNIEnv *env, jobject local_store_java, jobject asset_manager, int width, int height); void update(); void touch(int touch_id, int action, double x, double y); } #include <android/asset_manager.h> #include <android/asset_manager_jni.h> #include <GLES/gl.h> #include "gameengine/android/modules/ad_engine_android.h" #include "gameengine/android/modules/analytics_engine_android.h" #include "gameengine/android/modules/game_engine_factory_android.h" #include "gameengine/android/modules/local_store_android.h" #include "gameengine/game_engine.h" #include "gameengine/game_engine.h" #include "soundengine/sound_player.h" static sp<GameEngine> game_engine_; void init(JNIEnv *env, jobject local_store_java, jobject asset_manager, int width, int height) { glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glDepthMask(false); glEnable(GL_CULL_FACE); glEnable(GL_BLEND); glEnable(GL_TEXTURE_2D); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); // TODO This shouldn't be hardcoded. Rethink this anyways. game_engine_.reset(new GameEngine()); Texture2D::SetScreenHeight(height); game_engine_->set_screen_size(screen_size_make(width, height)); game_engine_->set_platform_type(kPlatformTypePhone); game_engine_->set_platform_resolution(kPlatformResolutionHigh); sp<GameEngineFactory> factory = sp<GameEngineFactory>(new GameEngineFactoryAndroid()); game_engine_->set_factory(factory); sp<LocalStore> local_store = sp<LocalStore>(new LocalStoreAndroid(env, local_store_java)); game_engine_->set_local_store(local_store); sp<AdEngine> ad_engine = sp<AdEngine>(new AdEngineAndroid()); game_engine_->set_ad_engine(ad_engine); sp<AnalyticsEngine> analytics_engine = sp<AnalyticsEngine>(new AnalyticsEngineAndroid()); game_engine_->set_analytics_engine(analytics_engine); AAssetManager *mgr = AAssetManager_fromJava(env, asset_manager); assert(NULL != mgr); // TODO casting is bad ((SoundPlayerImpl *)SoundPlayer::instance())->setAssetManager(mgr); sharkengine_init(game_engine_); } void update() { game_engine_->Update(); int backingWidth_ = 640; int backingHeight_ = 1138; glViewport(0, 0, backingWidth_, backingHeight_); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrthof(0, backingWidth_, 0, backingHeight_, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); game_engine_->Render(); } #include "gameengine/touch.h" #include <vector> using std::vector; void touch(int touch_id, int action, double x, double y) { Touch touch; touch.set_location(game_engine_->screen_point_to_game_point(screen_point_make(x, y))); touch.set_identifier((void *)(touch_id + 100)); // We don't want NULL identifiers, so add 100. if (action == 0) { game_engine_->AddTouchBegan(touch); } else if (action == 1) { game_engine_->AddTouchEnded(touch); } else if (action == 2) { game_engine_->AddTouchMoved(touch); } } <|endoftext|>
<commit_before>#include "SFZeroAudioProcessor.h" #include "SFZeroEditor.h" #include "SFZSound.h" #include "SFZVoice.h" #include "SFZDebug.h" SFZeroAudioProcessor::SFZeroAudioProcessor() : loadProgress(0.0), loadThread(this) { #if JUCE_DEBUG setupLogging( FileLogger::createDefaultAppLogger( "SFZero", "SFZero.log", "SFZero started")); #endif formatManager.registerFormat(new WavAudioFormat(), false); formatManager.registerFormat(new OggVorbisAudioFormat(), false); for (int i = 0; i < 32; ++i) synth.addVoice(new SFZVoice()); } SFZeroAudioProcessor::~SFZeroAudioProcessor() { } const String SFZeroAudioProcessor::getName() const { return JucePlugin_Name; } int SFZeroAudioProcessor::getNumParameters() { return 0; } float SFZeroAudioProcessor::getParameter(int index) { return 0.0f; } void SFZeroAudioProcessor::setParameter(int index, float newValue) { } const String SFZeroAudioProcessor::getParameterName(int index) { return String::empty; } const String SFZeroAudioProcessor::getParameterText(int index) { return String::empty; } void SFZeroAudioProcessor::setSfzFile(File* newSfzFile) { sfzFile = *newSfzFile; loadSound(); } void SFZeroAudioProcessor::setSfzFileThreaded(File* newSfzFile) { loadThread.stopThread(2000); sfzFile = *newSfzFile; loadThread.startThread(); } const String SFZeroAudioProcessor::getInputChannelName(int channelIndex) const { return String(channelIndex + 1); } const String SFZeroAudioProcessor::getOutputChannelName(int channelIndex) const { return String(channelIndex + 1); } bool SFZeroAudioProcessor::isInputChannelStereoPair(int index) const { return true; } bool SFZeroAudioProcessor::isOutputChannelStereoPair(int index) const { return true; } bool SFZeroAudioProcessor::acceptsMidi() const { #if JucePlugin_WantsMidiInput return true; #else return false; #endif } bool SFZeroAudioProcessor::producesMidi() const { #if JucePlugin_ProducesMidiOutput return true; #else return false; #endif } int SFZeroAudioProcessor::getNumPrograms() { return 0; } int SFZeroAudioProcessor::getCurrentProgram() { return 0; } void SFZeroAudioProcessor::setCurrentProgram(int index) { } const String SFZeroAudioProcessor::getProgramName(int index) { return String::empty; } void SFZeroAudioProcessor::changeProgramName(int index, const String& newName) { } void SFZeroAudioProcessor::prepareToPlay(double sampleRate, int samplesPerBlock) { synth.setCurrentPlaybackSampleRate(sampleRate); keyboardState.reset(); } void SFZeroAudioProcessor::releaseResources() { // When playback stops, you can use this as an opportunity to free up any // spare memory, etc. keyboardState.reset(); } void SFZeroAudioProcessor::processBlock(AudioSampleBuffer& buffer, MidiBuffer& midiMessages) { int numSamples = buffer.getNumSamples(); keyboardState.processNextMidiBuffer(midiMessages, 0, numSamples, true); synth.renderNextBlock(buffer, midiMessages, 0, numSamples); } bool SFZeroAudioProcessor::hasEditor() const { return true; // (change this to false if you choose to not supply an editor) } AudioProcessorEditor* SFZeroAudioProcessor::createEditor() { return new SFZeroEditor(this); } void SFZeroAudioProcessor::getStateInformation(MemoryBlock& destData) { DynamicObject state; state.setProperty("sfzFilePath", sfzFile.getFullPathName()); MemoryOutputStream out(destData, false); JSON::writeToStream(out, &state); } void SFZeroAudioProcessor::setStateInformation(const void* data, int sizeInBytes) { MemoryInputStream in(data, sizeInBytes, false); var state = JSON::parse(in); var pathVar = state["sfzFilePath"]; if (pathVar.isString()) { String sfzFilePath = pathVar.toString(); if (!sfzFilePath.isEmpty()) { File file(sfzFilePath); setSfzFile(&file); } } } SFZSound* SFZeroAudioProcessor::getSound() { SynthesiserSound* sound = synth.getSound(0); return dynamic_cast<SFZSound*>(sound); } #if JUCE_DEBUG void SFZeroAudioProcessor::relayLogMessages() { relayFifoLogMessages(); } #endif void SFZeroAudioProcessor::loadSound(Thread* thread) { loadProgress = 0.0; synth.clearSounds(); if (!sfzFile.existsAsFile()) { //*** return; } SFZSound* sound = new SFZSound(sfzFile); sound->loadRegions(); sound->loadSamples(&formatManager, &loadProgress, thread); if (thread && thread->threadShouldExit()) { delete sound; return; } synth.addSound(sound); } SFZeroAudioProcessor::LoadThread::LoadThread(SFZeroAudioProcessor* processorIn) : Thread("SFZLoad"), processor(processorIn) { } void SFZeroAudioProcessor::LoadThread::run() { processor->loadSound(this); } AudioProcessor* JUCE_CALLTYPE createPluginFilter() { return new SFZeroAudioProcessor(); } <commit_msg>SF2: Using SF2Sound when appropriate.<commit_after>#include "SFZeroAudioProcessor.h" #include "SFZeroEditor.h" #include "SFZSound.h" #include "SF2Sound.h" #include "SFZVoice.h" #include "SFZDebug.h" SFZeroAudioProcessor::SFZeroAudioProcessor() : loadProgress(0.0), loadThread(this) { #if JUCE_DEBUG setupLogging( FileLogger::createDefaultAppLogger( "SFZero", "SFZero.log", "SFZero started")); #endif formatManager.registerFormat(new WavAudioFormat(), false); formatManager.registerFormat(new OggVorbisAudioFormat(), false); for (int i = 0; i < 32; ++i) synth.addVoice(new SFZVoice()); } SFZeroAudioProcessor::~SFZeroAudioProcessor() { } const String SFZeroAudioProcessor::getName() const { return JucePlugin_Name; } int SFZeroAudioProcessor::getNumParameters() { return 0; } float SFZeroAudioProcessor::getParameter(int index) { return 0.0f; } void SFZeroAudioProcessor::setParameter(int index, float newValue) { } const String SFZeroAudioProcessor::getParameterName(int index) { return String::empty; } const String SFZeroAudioProcessor::getParameterText(int index) { return String::empty; } void SFZeroAudioProcessor::setSfzFile(File* newSfzFile) { sfzFile = *newSfzFile; loadSound(); } void SFZeroAudioProcessor::setSfzFileThreaded(File* newSfzFile) { loadThread.stopThread(2000); sfzFile = *newSfzFile; loadThread.startThread(); } const String SFZeroAudioProcessor::getInputChannelName(int channelIndex) const { return String(channelIndex + 1); } const String SFZeroAudioProcessor::getOutputChannelName(int channelIndex) const { return String(channelIndex + 1); } bool SFZeroAudioProcessor::isInputChannelStereoPair(int index) const { return true; } bool SFZeroAudioProcessor::isOutputChannelStereoPair(int index) const { return true; } bool SFZeroAudioProcessor::acceptsMidi() const { #if JucePlugin_WantsMidiInput return true; #else return false; #endif } bool SFZeroAudioProcessor::producesMidi() const { #if JucePlugin_ProducesMidiOutput return true; #else return false; #endif } int SFZeroAudioProcessor::getNumPrograms() { return 0; } int SFZeroAudioProcessor::getCurrentProgram() { return 0; } void SFZeroAudioProcessor::setCurrentProgram(int index) { } const String SFZeroAudioProcessor::getProgramName(int index) { return String::empty; } void SFZeroAudioProcessor::changeProgramName(int index, const String& newName) { } void SFZeroAudioProcessor::prepareToPlay(double sampleRate, int samplesPerBlock) { synth.setCurrentPlaybackSampleRate(sampleRate); keyboardState.reset(); } void SFZeroAudioProcessor::releaseResources() { // When playback stops, you can use this as an opportunity to free up any // spare memory, etc. keyboardState.reset(); } void SFZeroAudioProcessor::processBlock(AudioSampleBuffer& buffer, MidiBuffer& midiMessages) { int numSamples = buffer.getNumSamples(); keyboardState.processNextMidiBuffer(midiMessages, 0, numSamples, true); synth.renderNextBlock(buffer, midiMessages, 0, numSamples); } bool SFZeroAudioProcessor::hasEditor() const { return true; // (change this to false if you choose to not supply an editor) } AudioProcessorEditor* SFZeroAudioProcessor::createEditor() { return new SFZeroEditor(this); } void SFZeroAudioProcessor::getStateInformation(MemoryBlock& destData) { DynamicObject state; state.setProperty("sfzFilePath", sfzFile.getFullPathName()); MemoryOutputStream out(destData, false); JSON::writeToStream(out, &state); } void SFZeroAudioProcessor::setStateInformation(const void* data, int sizeInBytes) { MemoryInputStream in(data, sizeInBytes, false); var state = JSON::parse(in); var pathVar = state["sfzFilePath"]; if (pathVar.isString()) { String sfzFilePath = pathVar.toString(); if (!sfzFilePath.isEmpty()) { File file(sfzFilePath); setSfzFile(&file); } } } SFZSound* SFZeroAudioProcessor::getSound() { SynthesiserSound* sound = synth.getSound(0); return dynamic_cast<SFZSound*>(sound); } #if JUCE_DEBUG void SFZeroAudioProcessor::relayLogMessages() { relayFifoLogMessages(); } #endif void SFZeroAudioProcessor::loadSound(Thread* thread) { loadProgress = 0.0; synth.clearSounds(); if (!sfzFile.existsAsFile()) { //*** return; } SFZSound* sound; String extension = sfzFile.getFileExtension(); if (extension == "sf2" || extension == "SF2") sound = new SF2Sound(sfzFile); else sound = new SFZSound(sfzFile); sound->loadRegions(); sound->loadSamples(&formatManager, &loadProgress, thread); if (thread && thread->threadShouldExit()) { delete sound; return; } synth.addSound(sound); } SFZeroAudioProcessor::LoadThread::LoadThread(SFZeroAudioProcessor* processorIn) : Thread("SFZLoad"), processor(processorIn) { } void SFZeroAudioProcessor::LoadThread::run() { processor->loadSound(this); } AudioProcessor* JUCE_CALLTYPE createPluginFilter() { return new SFZeroAudioProcessor(); } <|endoftext|>
<commit_before>/** * @copyright Copyright 2016 The J-PET Framework 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 find a copy of the License in the LICENCE file. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file JPetTaskChainExecutor.cpp */ #include "JPetTaskChainExecutor.h" #include <cassert> #include <memory> #include <chrono> #include "JPetTaskChainExecutorUtils.h" #include "../JPetLoggerInclude.h" JPetTaskChainExecutor::JPetTaskChainExecutor(TaskGeneratorChain* taskGeneratorChain, int processedFileId, const OptionsPerFile& opts): fInputSeqId(processedFileId), ftaskGeneratorChain(taskGeneratorChain) { assert(taskGeneratorChain->size() == opts.size()); /// ParamManager is generated and added to fParams fParams = JPetTaskChainExecutorUtils::generateParams(opts); assert(fParams.front().getParamManager()); if (taskGeneratorChain) { for (auto taskGenerator : *ftaskGeneratorChain) { auto task = taskGenerator(); fTasks.push_back(task); } } else { ERROR("taskGeneratorChain is null while constructing JPetTaskChainExecutor"); } } bool JPetTaskChainExecutor::preprocessing(const std::vector<JPetParams>& params) { if (params.empty()) { ERROR("No parameters provided!"); return false; } else { return JPetTaskChainExecutorUtils::process(params.front()); } } bool JPetTaskChainExecutor::process() { JPetTimer timer; timer.startMeasurement(); if (!preprocessing(fParams)) { ERROR("Error in preprocessing phase"); return false; } timer.stopMeasurement("Preprocessing"); JPetDataInterface nullDataObject; JPetParams outputParams; assert(fTasks.size() == fParams.size()); auto currParamsIt = fParams.begin(); /// We iterate over both tasks and parameters for (auto currentTaskIt = fTasks.begin(); currentTaskIt != fTasks.end(); currentTaskIt++) { auto currentTask = *currentTaskIt; auto taskName = currentTask->getName(); assert(currParamsIt != fParams.end()); auto currParams = *currParamsIt; jpet_options_tools::printOptionsToLog(currParams.getOptions(), std::string("Options for ") + taskName); currParamsIt++; timer.startMeasurement(); INFO(Form("Starting task: %s", taskName.c_str())); if (!currentTask->init(currParams)) { ERROR("In task initialization"); return false; } if (!currentTask->run(nullDataObject)) { ERROR("In task run()"); return false; } if (!currentTask->terminate(outputParams)) { ERROR("In task terminate() "); return false; } timer.stopMeasurement("task " + taskName); } timer.printElapsedTimeToInfo(); timer.printTotalElapsedTimeToInfo(); return true; } void* JPetTaskChainExecutor::processProxy(void* runner) { assert(runner); static_cast<JPetTaskChainExecutor*>(runner)->process(); return 0; } TThread* JPetTaskChainExecutor::run() { TThread* thread = new TThread(std::to_string(fInputSeqId).c_str(), processProxy, (void*)this); assert(thread); thread->Run(); return thread; } JPetTaskChainExecutor::~JPetTaskChainExecutor() { for (auto& task : fTasks) { if (task) { delete task; task = 0; } } } <commit_msg>Adapt to new JPetTimer methods<commit_after>/** * @copyright Copyright 2016 The J-PET Framework 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 find a copy of the License in the LICENCE file. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file JPetTaskChainExecutor.cpp */ #include "JPetTaskChainExecutor.h" #include <cassert> #include <memory> #include <chrono> #include "JPetTaskChainExecutorUtils.h" #include "../JPetLoggerInclude.h" JPetTaskChainExecutor::JPetTaskChainExecutor(TaskGeneratorChain* taskGeneratorChain, int processedFileId, const OptionsPerFile& opts): fInputSeqId(processedFileId), ftaskGeneratorChain(taskGeneratorChain) { assert(taskGeneratorChain->size() == opts.size()); /// ParamManager is generated and added to fParams fParams = JPetTaskChainExecutorUtils::generateParams(opts); assert(fParams.front().getParamManager()); if (taskGeneratorChain) { for (auto taskGenerator : *ftaskGeneratorChain) { auto task = taskGenerator(); fTasks.push_back(task); } } else { ERROR("taskGeneratorChain is null while constructing JPetTaskChainExecutor"); } } bool JPetTaskChainExecutor::preprocessing(const std::vector<JPetParams>& params) { if (params.empty()) { ERROR("No parameters provided!"); return false; } else { return JPetTaskChainExecutorUtils::process(params.front()); } } bool JPetTaskChainExecutor::process() { JPetTimer timer; timer.startMeasurement(); if (!preprocessing(fParams)) { ERROR("Error in preprocessing phase"); return false; } timer.stopMeasurement("Preprocessing"); JPetDataInterface nullDataObject; JPetParams outputParams; assert(fTasks.size() == fParams.size()); auto currParamsIt = fParams.begin(); /// We iterate over both tasks and parameters for (auto currentTaskIt = fTasks.begin(); currentTaskIt != fTasks.end(); currentTaskIt++) { auto currentTask = *currentTaskIt; auto taskName = currentTask->getName(); assert(currParamsIt != fParams.end()); auto currParams = *currParamsIt; jpet_options_tools::printOptionsToLog(currParams.getOptions(), std::string("Options for ") + taskName); currParamsIt++; timer.startMeasurement(); INFO(Form("Starting task: %s", taskName.c_str())); if (!currentTask->init(currParams)) { ERROR("In task initialization"); return false; } if (!currentTask->run(nullDataObject)) { ERROR("In task run()"); return false; } if (!currentTask->terminate(outputParams)) { ERROR("In task terminate() "); return false; } timer.stopMeasurement("task " + taskName); } INFO(timer.getElapsedTime()); INFO(timer.getTotalElapsedTime()); return true; } void* JPetTaskChainExecutor::processProxy(void* runner) { assert(runner); static_cast<JPetTaskChainExecutor*>(runner)->process(); return 0; } TThread* JPetTaskChainExecutor::run() { TThread* thread = new TThread(std::to_string(fInputSeqId).c_str(), processProxy, (void*)this); assert(thread); thread->Run(); return thread; } JPetTaskChainExecutor::~JPetTaskChainExecutor() { for (auto& task : fTasks) { if (task) { delete task; task = 0; } } } <|endoftext|>
<commit_before>/******************************************************************************\ * File: dialog.cpp * Purpose: Implementation of wxExDialog class * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/persist/toplevel.h> #include <wx/extension/dialog.h> #if wxUSE_GUI BEGIN_EVENT_TABLE(wxExDialog, wxDialog) EVT_CHAR_HOOK(wxExDialog::OnKeyDown) END_EVENT_TABLE() wxExDialog::wxExDialog(wxWindow* parent, const wxString& title, long button_flags, wxWindowID id, const wxPoint& pos, const wxSize& size, long style) : wxDialog(parent, id, title, pos, size, style) , m_ButtonFlags(button_flags) , m_TopSizer(new wxFlexGridSizer(1, 0, 0)) , m_UserSizer(new wxFlexGridSizer(1, 0, 0)) { SetName(title); } wxSizerItem* wxExDialog::AddUserSizer( wxWindow* window, const wxSizerFlags& flags) { wxSizerItem* item = m_UserSizer->Add(window, flags); if (flags.GetFlags() & wxEXPAND) { m_UserSizer->AddGrowableRow(m_UserSizer->GetChildren().GetCount() - 1); } return item; } wxSizerItem* wxExDialog::AddUserSizer( wxSizer* sizer, const wxSizerFlags& flags) { wxSizerItem* item = m_UserSizer->Add(sizer, flags); if (flags.GetFlags() & wxEXPAND) { m_UserSizer->AddGrowableRow(m_UserSizer->GetChildren().GetCount() - 1); } return item; } void wxExDialog::LayoutSizers(bool add_separator_line) { m_TopSizer->AddGrowableCol(0); m_UserSizer->AddGrowableCol(0); wxSizerFlags flag; flag.Expand().Center().Border(); // The top sizer starts with a spacer, for a nice border. m_TopSizer->AddSpacer(wxSizerFlags::GetDefaultBorder()); // Then place the growable user sizer. m_TopSizer->Add(m_UserSizer, flag); // So this is the user sizer, make the row growable. m_TopSizer->AddGrowableRow(m_TopSizer->GetChildren().GetCount() - 1); // Then, if buttons were specified, the button sizer. if (m_ButtonFlags != 0) { wxSizer* sizer = (add_separator_line ? CreateSeparatedButtonSizer(m_ButtonFlags): CreateButtonSizer(m_ButtonFlags)); if (sizer != NULL) { m_TopSizer->Add(sizer, flag); } } // The top sizer ends with a spacer as well. m_TopSizer->AddSpacer(wxSizerFlags::GetDefaultBorder()); SetSizerAndFit(m_TopSizer); wxPersistentRegisterAndRestore(this); } void wxExDialog::OnKeyDown(wxKeyEvent& event) { // If we did not specify any buttons, then // use the RETURN key as OK and ESCAPE key as CANCEL. if (m_ButtonFlags == 0) { if (event.GetKeyCode() == WXK_RETURN) { wxCommandEvent event(wxEVT_COMMAND_BUTTON_CLICKED, wxID_OK); wxPostEvent(this, event); } else if (event.GetKeyCode() == WXK_ESCAPE) { wxCommandEvent event(wxEVT_COMMAND_BUTTON_CLICKED, wxID_CANCEL); wxPostEvent(this, event); } else { event.Skip(); } } else { event.Skip(); } } #endif // wxUSE_GUI <commit_msg>use const flag<commit_after>/******************************************************************************\ * File: dialog.cpp * Purpose: Implementation of wxExDialog class * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/persist/toplevel.h> #include <wx/extension/dialog.h> #if wxUSE_GUI BEGIN_EVENT_TABLE(wxExDialog, wxDialog) EVT_CHAR_HOOK(wxExDialog::OnKeyDown) END_EVENT_TABLE() wxExDialog::wxExDialog(wxWindow* parent, const wxString& title, long button_flags, wxWindowID id, const wxPoint& pos, const wxSize& size, long style) : wxDialog(parent, id, title, pos, size, style) , m_ButtonFlags(button_flags) , m_TopSizer(new wxFlexGridSizer(1, 0, 0)) , m_UserSizer(new wxFlexGridSizer(1, 0, 0)) { SetName(title); } wxSizerItem* wxExDialog::AddUserSizer( wxWindow* window, const wxSizerFlags& flags) { wxSizerItem* item = m_UserSizer->Add(window, flags); if (flags.GetFlags() & wxEXPAND) { m_UserSizer->AddGrowableRow(m_UserSizer->GetChildren().GetCount() - 1); } return item; } wxSizerItem* wxExDialog::AddUserSizer( wxSizer* sizer, const wxSizerFlags& flags) { wxSizerItem* item = m_UserSizer->Add(sizer, flags); if (flags.GetFlags() & wxEXPAND) { m_UserSizer->AddGrowableRow(m_UserSizer->GetChildren().GetCount() - 1); } return item; } void wxExDialog::LayoutSizers(bool add_separator_line) { m_TopSizer->AddGrowableCol(0); m_UserSizer->AddGrowableCol(0); const wxSizerFlags flag = wxSizerFlags().Expand().Center().Border(); // The top sizer starts with a spacer, for a nice border. m_TopSizer->AddSpacer(wxSizerFlags::GetDefaultBorder()); // Then place the growable user sizer. m_TopSizer->Add(m_UserSizer, flag); // So this is the user sizer, make the row growable. m_TopSizer->AddGrowableRow(m_TopSizer->GetChildren().GetCount() - 1); // Then, if buttons were specified, the button sizer. if (m_ButtonFlags != 0) { wxSizer* sizer = (add_separator_line ? CreateSeparatedButtonSizer(m_ButtonFlags): CreateButtonSizer(m_ButtonFlags)); if (sizer != NULL) { m_TopSizer->Add(sizer, flag); } } // The top sizer ends with a spacer as well. m_TopSizer->AddSpacer(wxSizerFlags::GetDefaultBorder()); SetSizerAndFit(m_TopSizer); wxPersistentRegisterAndRestore(this); } void wxExDialog::OnKeyDown(wxKeyEvent& event) { // If we did not specify any buttons, then // use the RETURN key as OK and ESCAPE key as CANCEL. if (m_ButtonFlags == 0) { if (event.GetKeyCode() == WXK_RETURN) { wxCommandEvent event(wxEVT_COMMAND_BUTTON_CLICKED, wxID_OK); wxPostEvent(this, event); } else if (event.GetKeyCode() == WXK_ESCAPE) { wxCommandEvent event(wxEVT_COMMAND_BUTTON_CLICKED, wxID_CANCEL); wxPostEvent(this, event); } else { event.Skip(); } } else { event.Skip(); } } #endif // wxUSE_GUI <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), wizard(new Wizard(this)), world(NULL) { ui->setupUi(this); rooms_list = new RoomsList; room_view = new RoomView; settings = new SettingsWidget; ui->splitter->addWidget(rooms_list); widget = new QWidget; layout = new QGridLayout; vspacer = new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding); hspacer = new QSpacerItem(0, 0, QSizePolicy::Expanding); layout->addWidget(room_view, 0, 0); layout->addItem(hspacer, 0, 1); layout->addItem(vspacer, 1, 0, 1, 2); layout->setMargin(0); widget->setLayout(layout); ui->splitter->addWidget(widget); ui->splitter->addWidget(settings); ui->centralWidget->setDisabled(true); connect(room_view, SIGNAL(roomChanged(Room*)), room_view, SIGNAL(selected(Room*))); connect(room_view, SIGNAL(selected(Room*)), settings, SLOT(updateRoomSettings(Room*))); connect(room_view, SIGNAL(selected(Area*)), settings, SLOT(updateAreaSettings(Area*))); connect(ui->action_Save, SIGNAL(triggered()), this, SLOT(saveProject())); connect(ui->action_Open, SIGNAL(triggered()), this, SLOT(openProject())); connect(ui->action_New, SIGNAL(triggered()), wizard, SLOT(show())); connect(ui->action_Quit, SIGNAL(triggered()), this, SLOT(close())); connect(rooms_list, SIGNAL(selected(QModelIndex)), room_view, SLOT(changeActiveRoom(QModelIndex))); connect(wizard, SIGNAL(accepted()), this, SLOT(newProject())); adjustSize(); } MainWindow::~MainWindow() { delete ui; delete wizard; } void MainWindow::saveProject() { QString project_filename = QFileDialog::getSaveFileName(this, "Save project", QDir::homePath()); QFile file(project_filename); if (!file.open(QIODevice::WriteOnly)) return; file.write(createXml().toAscii()); file.close(); } void MainWindow::openProject() { QDomDocument doc("RoomsProjectFile"); QString project_filename = QFileDialog::getOpenFileName(this, "Open project", QDir::homePath(), "Rooms project (*.rooms)"); QFile file(project_filename); if (!file.open(QIODevice::ReadOnly)) return; if (!doc.setContent(&file)) { file.close(); return; } file.close(); if (world != NULL) delete world; world = createWorld(doc); rooms_list->setWorld(world); room_view->setWorld(world); settings->setWorld(world); adjustSize(); ui->centralWidget->setEnabled(true); } void MainWindow::newProject() { if (world != NULL) delete world; world = new World(wizard->worldName(), wizard->worldSize()); rooms_list->setWorld(world); room_view->setWorld(world); settings->setWorld(world); adjustSize(); ui->centralWidget->setEnabled(true); } QString MainWindow::createXml() const { QString xml; QDomDocument doc("RoomsProjectFile"); QDomElement xworld = doc.createElement("world"); xworld.setAttribute("version", "ROOMS_VANILLA"); xworld.setAttribute("name", world->name()); xworld.setAttribute("width", world->size().width()); xworld.setAttribute("height", world->size().height()); xworld.setAttribute("start", 0); doc.appendChild(xworld); //<images> //this block is useless for now because <img> contains only the filepath, which is //already included as "bg" attribute of <room> QDomElement ximages = doc.createElement("images"); for (int i = 0; i < world->rooms()->count(); i++) { QDomElement ximg = doc.createElement("img"); ximg.setAttribute("file", world->rooms()->at(i)->name()); ximages.appendChild(ximg); } xworld.appendChild(ximages); //</images> //<rooms> QDomElement xrooms = doc.createElement("rooms"); for (int i = 0; i < world->rooms()->count(); i++) { QDomElement xroom = doc.createElement("room"); xroom.setAttribute("id", world->rooms()->at(i)->name()); xroom.setAttribute("bg", world->rooms()->at(i)->name()); QDomElement xareas = doc.createElement("areas"); for (int j = 0; j < world->rooms()->at(i)->areas().count(); j++) { QDomElement xarea = doc.createElement("area"); xarea.setAttribute("id", world->rooms()->at(i)->areas().at(j)->name()); xarea.setAttribute("x", world->rooms()->at(i)->areas().at(j)->rect().x()); xarea.setAttribute("y", world->rooms()->at(i)->areas().at(j)->rect().y()); xarea.setAttribute("width", world->rooms()->at(i)->areas().at(j)->rect().width()); xarea.setAttribute("height", world->rooms()->at(i)->areas().at(j)->rect().height()); xareas.appendChild(xarea); } xroom.appendChild(xareas); xrooms.appendChild(xroom); } xworld.appendChild(xrooms); //</rooms> xml = doc.toString(); return xml; } World *MainWindow::createWorld(const QDomDocument &doc) { QDomElement xworld = doc.elementsByTagName("world").at(0).toElement(); World *world = new World(xworld.attribute("name"), QSize(xworld.attribute("width").toInt(), xworld.attribute("height").toInt())); //<images> //this block is useless for now because <img> contains only the filepath, which is //already included as "bg" attribute of <room> RoomsModel *rooms = world->rooms(); QDomNode ximages = xworld.elementsByTagName("images").at(0); QDomElement ximg = ximages.firstChildElement(); while (!ximg.isNull()) { ximg = ximg.nextSiblingElement(); } //</images> //<rooms> QDomNode xrooms = xworld.elementsByTagName("rooms").at(0); QDomElement xroom = xrooms.firstChildElement(); while (!xroom.isNull()) { rooms->appendRoom(); Room *room = rooms->at(rooms->count()-1); QString id(xroom.attribute("id")); QString bg_file(xroom.attribute("bg")); QPixmap bg(bg_file); bg = bg.scaled(world->size()); room->setName(id); room->setBackground(bg); //<areas> QDomNode xareas = xroom.firstChild(); QDomElement xarea = xareas.firstChildElement(); while (!xarea.isNull()) { QString id(xarea.attribute("id")); QRect rect(xarea.attribute("x").toInt(), xarea.attribute("y").toInt(), xarea.attribute("width").toInt(), xarea.attribute("height").toInt()); room->addArea(rect); room->areas().at(room->areas().count()-1)->setName(id); xarea = xarea.nextSiblingElement(); } //</areas> xroom = xroom.nextSiblingElement(); } //</rooms> return world; } <commit_msg>adding support for saving background images<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), wizard(new Wizard(this)), world(NULL) { ui->setupUi(this); rooms_list = new RoomsList; room_view = new RoomView; settings = new SettingsWidget; ui->splitter->addWidget(rooms_list); widget = new QWidget; layout = new QGridLayout; vspacer = new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding); hspacer = new QSpacerItem(0, 0, QSizePolicy::Expanding); layout->addWidget(room_view, 0, 0); layout->addItem(hspacer, 0, 1); layout->addItem(vspacer, 1, 0, 1, 2); layout->setMargin(0); widget->setLayout(layout); ui->splitter->addWidget(widget); ui->splitter->addWidget(settings); ui->centralWidget->setDisabled(true); connect(room_view, SIGNAL(roomChanged(Room*)), room_view, SIGNAL(selected(Room*))); connect(room_view, SIGNAL(selected(Room*)), settings, SLOT(updateRoomSettings(Room*))); connect(room_view, SIGNAL(selected(Area*)), settings, SLOT(updateAreaSettings(Area*))); connect(ui->action_Save, SIGNAL(triggered()), this, SLOT(saveProject())); connect(ui->action_Open, SIGNAL(triggered()), this, SLOT(openProject())); connect(ui->action_New, SIGNAL(triggered()), wizard, SLOT(show())); connect(ui->action_Quit, SIGNAL(triggered()), this, SLOT(close())); connect(rooms_list, SIGNAL(selected(QModelIndex)), room_view, SLOT(changeActiveRoom(QModelIndex))); connect(wizard, SIGNAL(accepted()), this, SLOT(newProject())); adjustSize(); } MainWindow::~MainWindow() { delete ui; delete wizard; } void MainWindow::saveProject() { QString project_filename = QFileDialog::getSaveFileName(this, "Save project", QDir::homePath()); QDir::setCurrent(project_filename.section("/", 0, -2)); QFile file(project_filename); if (!file.open(QIODevice::WriteOnly)) return; file.write(createXml().toAscii()); file.close(); QDir data_dir(QDir::currentPath() + "/" + world->name() + "_data"); data_dir.mkpath(data_dir.absolutePath()); for (int i = 0; i < world->rooms()->count(); i++) { world->rooms()->at(i)->background().save(data_dir.absolutePath() + "/" + world->rooms()->at(i)->name() + "_bg.png"); } } void MainWindow::openProject() { QDomDocument doc("RoomsProjectFile"); QString project_filename = QFileDialog::getOpenFileName(this, "Open project", QDir::homePath(), "Rooms project (*.rooms)"); QFile file(project_filename); if (!file.open(QIODevice::ReadOnly)) return; if (!doc.setContent(&file)) { file.close(); return; } file.close(); if (world != NULL) delete world; world = createWorld(doc); rooms_list->setWorld(world); room_view->setWorld(world); settings->setWorld(world); adjustSize(); ui->centralWidget->setEnabled(true); } void MainWindow::newProject() { if (world != NULL) delete world; world = new World(wizard->worldName(), wizard->worldSize()); rooms_list->setWorld(world); room_view->setWorld(world); settings->setWorld(world); adjustSize(); ui->centralWidget->setEnabled(true); } QString MainWindow::createXml() const { QString xml; QDomDocument doc("RoomsProjectFile"); QDomElement xworld = doc.createElement("world"); xworld.setAttribute("version", "ROOMS_VANILLA"); xworld.setAttribute("name", world->name()); xworld.setAttribute("width", world->size().width()); xworld.setAttribute("height", world->size().height()); xworld.setAttribute("start", 0); doc.appendChild(xworld); //<images> //this block is useless for now because <img> contains only the filepath, which is //already included as "bg" attribute of <room> QDomElement ximages = doc.createElement("images"); for (int i = 0; i < world->rooms()->count(); i++) { QDomElement ximg = doc.createElement("img"); ximg.setAttribute("file", world->rooms()->at(i)->name()); ximages.appendChild(ximg); } xworld.appendChild(ximages); //</images> //<rooms> QDomElement xrooms = doc.createElement("rooms"); for (int i = 0; i < world->rooms()->count(); i++) { QDomElement xroom = doc.createElement("room"); xroom.setAttribute("id", world->rooms()->at(i)->name()); xroom.setAttribute("bg", world->rooms()->at(i)->name()); QDomElement xareas = doc.createElement("areas"); for (int j = 0; j < world->rooms()->at(i)->areas().count(); j++) { QDomElement xarea = doc.createElement("area"); xarea.setAttribute("id", world->rooms()->at(i)->areas().at(j)->name()); xarea.setAttribute("x", world->rooms()->at(i)->areas().at(j)->rect().x()); xarea.setAttribute("y", world->rooms()->at(i)->areas().at(j)->rect().y()); xarea.setAttribute("width", world->rooms()->at(i)->areas().at(j)->rect().width()); xarea.setAttribute("height", world->rooms()->at(i)->areas().at(j)->rect().height()); xareas.appendChild(xarea); } xroom.appendChild(xareas); xrooms.appendChild(xroom); } xworld.appendChild(xrooms); //</rooms> xml = doc.toString(); return xml; } World *MainWindow::createWorld(const QDomDocument &doc) { QDomElement xworld = doc.elementsByTagName("world").at(0).toElement(); World *world = new World(xworld.attribute("name"), QSize(xworld.attribute("width").toInt(), xworld.attribute("height").toInt())); //<images> //this block is useless for now because <img> contains only the filepath, which is //already included as "bg" attribute of <room> RoomsModel *rooms = world->rooms(); QDomNode ximages = xworld.elementsByTagName("images").at(0); QDomElement ximg = ximages.firstChildElement(); while (!ximg.isNull()) { ximg = ximg.nextSiblingElement(); } //</images> //<rooms> QDomNode xrooms = xworld.elementsByTagName("rooms").at(0); QDomElement xroom = xrooms.firstChildElement(); while (!xroom.isNull()) { rooms->appendRoom(); Room *room = rooms->at(rooms->count()-1); QString id(xroom.attribute("id")); QString bg_file(xroom.attribute("bg")); QPixmap bg(bg_file); bg = bg.scaled(world->size()); room->setName(id); room->setBackground(bg); //<areas> QDomNode xareas = xroom.firstChild(); QDomElement xarea = xareas.firstChildElement(); while (!xarea.isNull()) { QString id(xarea.attribute("id")); QRect rect(xarea.attribute("x").toInt(), xarea.attribute("y").toInt(), xarea.attribute("width").toInt(), xarea.attribute("height").toInt()); room->addArea(rect); room->areas().at(room->areas().count()-1)->setName(id); xarea = xarea.nextSiblingElement(); } //</areas> xroom = xroom.nextSiblingElement(); } //</rooms> return world; } <|endoftext|>
<commit_before>// Copyright (C) 2019 by Pedro Mendes, Rector and Visitors of the // University of Virginia, University of Heidelberg, and University // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and University of // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. #include "CValidity.h" #include "copasi/core/CObjectInterface.h" // static const CIssue CIssue::Success(CIssue::eSeverity::Success); // static const CIssue CIssue::Information(CIssue::eSeverity::Information); // static const CIssue CIssue::Warning(CIssue::eSeverity::Warning); // static const CIssue CIssue::Error(CIssue::eSeverity::Error); // static const CEnumAnnotation< std::string, CIssue::eSeverity > CIssue::severityNames( { "success", "information", "warnings", "errors" }); // static const CEnumAnnotation< std::string, CIssue::eKind > CIssue::kindNames( { "unknown issue", "invalid expression", "empty expression", "missing initial value", "calculation problem", "missing event assignment", "event already has assignment", "missing event trigger expression", "undefined unit", "unit conflict", "invalid unit", "undefined or unrepresentable value", "unfound object", "unfound value", "unfound variable", "Invalid structure", "excess arguments", "circular dependency", "invalid expression data type", "variable in expression", "unfound expression", "unfound function", "mismatched variables", "inconsistent value types", "initial expression with assignment", "setting fixed expression", "reaction kinetics not defined" }); // static const CEnumAnnotation< std::string, CIssue::eKind > CIssue::kindDescriptions( { "Unknown issue.", "Invalid expression.", "Empty expression.", "Missing initial value.", "Problem with calculation.", "Missing event assignment.", "Event already has an assignment rule.", "Missing event trigger expression.", "Unit is undefined.", "Conflicting units.", "Invalid unit.", "Value is undefined or unrepresentable.", "Object not found.", "Value not found.", "Variable not found.", "Invalid structure.", "Too many arguments.", "Has circular dependency.", "Invalid expression data type.", "Expression contains a variable.", "CExpression not found.", "CFunction not found.", "Variables are mismatched.", "Inconsistent value types encountered.", "Initial expressions prohibited with assignment.", "Changing fixed expression prohibited", "Reaction kinetics are not defined" }); CIssue::CIssue(const CIssue::eSeverity & severity, const CIssue::eKind & kind): mSeverity(severity), mKind(kind) {} CIssue::CIssue(const CIssue & src): mSeverity(src.mSeverity), mKind(src.mKind) {} CIssue::~CIssue() {} CIssue::operator bool() const { // If this type is implicity cast to a bool, in a conditional // evaluation, it will evaluate to "true" that there IS NOT a // significant "issue", if it is not at "Error" severity. return (mSeverity != CIssue::eSeverity::Error); } CIssue & CIssue::operator &= (const CIssue & rhs) { if (rhs.mSeverity > mSeverity) { mSeverity = rhs.mSeverity; mKind = rhs.mKind; } return *this; } bool CIssue::operator == (const CIssue & rhs) const { if (mSeverity == rhs.mSeverity && mKind == rhs.mKind) return true; else return false; } bool CIssue::isError() const { return !isSuccess(); } bool CIssue::isSuccess() const { return (mSeverity != CIssue::eSeverity::Error); } CValidity & CValidity::operator |= (const CValidity & rhs) { size_t Count = mErrors.count() + mWarnings.count() + mInformation.count(); if (this != &rhs) { mErrors |= rhs.mErrors; mWarnings |= rhs.mWarnings; mInformation |= rhs.mInformation; } if (mpObjectInterface != NULL && Count < mErrors.count() + mWarnings.count() + mInformation.count()) { mpObjectInterface->validityChanged(*this); } return *this; } const CIssue & CValidity::getFirstWorstIssue() const { return mFirstWorstIssue; } CValidity & CValidity::operator = (const CValidity & rhs) { if (this == &rhs) return *this; bool Changed = false; if (mErrors != rhs.mErrors) { mErrors = rhs.mErrors; Changed = true; } if (mWarnings != rhs.mWarnings) { mWarnings = rhs.mWarnings; Changed = true; } if (mInformation != rhs.mInformation) { mInformation = rhs.mInformation; Changed = true; } if (mpObjectInterface != NULL && Changed) { mpObjectInterface->validityChanged(*this); } return *this; } const CIssue::eSeverity & CIssue::getSeverity() const { return mSeverity; } const CIssue::eKind & CIssue::getKind() const { return mKind; } CValidity::CValidity(CObjectInterface * pObjectInterface): mErrors(), mWarnings(), mInformation(), mpObjectInterface(pObjectInterface), mFirstWorstIssue() {} CValidity::CValidity(const CValidity & src, CObjectInterface * pObjectInterface): mErrors(src.mErrors), mWarnings(src.mWarnings), mInformation(src.mInformation), mpObjectInterface(pObjectInterface), mFirstWorstIssue(src.mFirstWorstIssue) {} CValidity::~CValidity() {} void CValidity::clear() { // Only need to reset, if anything is set (i.e. not already clear) if (0 < mErrors.count() + mWarnings.count() + mInformation.count()) { mFirstWorstIssue = CIssue::Success; mErrors.reset(); mWarnings.reset(); mInformation.reset(); // Given something changed, notify the parent // to do it's thing, if it exists. if (mpObjectInterface != NULL) { mpObjectInterface->validityChanged(*this); } } } bool CValidity::empty() const { return mErrors.count() + mWarnings.count() + mInformation.count() == 0; } void CValidity::add(const CIssue & issue) { mFirstWorstIssue &= issue; size_t Count = 0; bool Changed = false; switch (issue.getSeverity()) { case CIssue::eSeverity::Error: Count = mErrors.count(); mErrors |= issue.getKind(); Changed = Count < mErrors.count(); break; case CIssue::eSeverity::Warning: Count = mWarnings.count(); mWarnings |= issue.getKind(); Changed = Count < mWarnings.count(); break; case CIssue::eSeverity::Information: Count = mInformation.count(); mInformation |= issue.getKind(); Changed = Count < mInformation.count(); break; case CIssue::eSeverity::__SIZE: break; } if (Changed && mpObjectInterface != NULL) { mpObjectInterface->validityChanged(*this); } } void CValidity::remove(const CIssue & issue) { if (mFirstWorstIssue == issue) mFirstWorstIssue = CIssue::Success; size_t Count = 0; bool Changed = false; switch (issue.getSeverity()) { case CIssue::eSeverity::Error: Count = mErrors.count(); mErrors &= ~Kind(issue.getKind()); Changed = Count > mErrors.count(); break; case CIssue::eSeverity::Warning: Count = mWarnings.count(); mWarnings &= ~Kind(issue.getKind()); Changed = Count > mWarnings.count(); break; case CIssue::eSeverity::Information: Count = mInformation.count(); mInformation &= ~Kind(issue.getKind()); Changed = Count > mInformation.count(); break; case CIssue::eSeverity::__SIZE: break; } if (Changed && mpObjectInterface != NULL) { mpObjectInterface->validityChanged(*this); } } void CValidity::remove(const CValidity::Severity & severity, const CValidity::Kind & kind) { size_t Count = mErrors.count() + mWarnings.count() + mInformation.count(); if (severity.isSet(CIssue::eSeverity::Error)) mErrors &= ~kind; if (severity.isSet(CIssue::eSeverity::Warning)) mWarnings &= ~kind; if (severity.isSet(CIssue::eSeverity::Information)) mInformation &= ~kind; if (mpObjectInterface != NULL && Count > mErrors.count() + mWarnings.count() + mInformation.count()) { mpObjectInterface->validityChanged(*this); } } CIssue::eSeverity CValidity::getHighestSeverity(const CValidity::Severity & filterSeverity, const CValidity::Kind & filterKind) const { if (filterSeverity.isSet(CIssue::eSeverity::Error) && (mErrors & filterKind)) return CIssue::eSeverity::Error; if (filterSeverity.isSet(CIssue::eSeverity::Warning) && (mWarnings & filterKind)) return CIssue::eSeverity::Warning; if (filterSeverity.isSet(CIssue::eSeverity::Information) && (mInformation & filterKind)) return CIssue::eSeverity::Information; return CIssue::eSeverity::Success; } const CValidity::Kind & CValidity::get(const CIssue::eSeverity & severity) const { static const Kind OK; switch (severity) { case CIssue::eSeverity::Error: return mErrors; case CIssue::eSeverity::Warning: return mWarnings; case CIssue::eSeverity::Information: return mInformation; default: return OK; } } const std::string CValidity::getIssueMessages(const Severity & severityFilter, const Kind & kindFilter) const { std::string severityString = ""; std::vector< std::string > descriptions; std::string messages = ""; std::vector< std::string >::const_iterator it, end; if (severityFilter.isSet(CIssue::eSeverity::Error)) { severityString = "Error: "; descriptions = mErrors.getAnnotations(CIssue::kindDescriptions, kindFilter); it = descriptions.begin(); end = descriptions.end(); for (; it != end; ++it) { messages += severityString + *it + "\n"; } } if (severityFilter.isSet(CIssue::eSeverity::Warning)) { severityString = "Warning: "; descriptions = mWarnings.getAnnotations(CIssue::kindDescriptions, kindFilter); it = descriptions.begin(); end = descriptions.end(); for (; it != end; ++it) { messages += severityString + *it + "\n"; } } if (severityFilter.isSet(CIssue::eSeverity::Information)) { severityString = "Information: "; descriptions = mInformation.getAnnotations(CIssue::kindDescriptions, kindFilter); it = descriptions.begin(); end = descriptions.end(); for (; it != end; ++it) { messages += severityString + *it + "\n"; } } // Remove last newline if (!messages.empty()) messages = messages.substr(0, messages.size() - 1); return messages; } <commit_msg>Bug 2917: mFirstWorstIssue was not updated when combining validities.<commit_after>// Copyright (C) 2019 - 2020 by Pedro Mendes, Rector and Visitors of the // University of Virginia, University of Heidelberg, and University // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and University of // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. #include "CValidity.h" #include "copasi/core/CObjectInterface.h" // static const CIssue CIssue::Success(CIssue::eSeverity::Success); // static const CIssue CIssue::Information(CIssue::eSeverity::Information); // static const CIssue CIssue::Warning(CIssue::eSeverity::Warning); // static const CIssue CIssue::Error(CIssue::eSeverity::Error); // static const CEnumAnnotation< std::string, CIssue::eSeverity > CIssue::severityNames( { "success", "information", "warnings", "errors" }); // static const CEnumAnnotation< std::string, CIssue::eKind > CIssue::kindNames( { "unknown issue", "invalid expression", "empty expression", "missing initial value", "calculation problem", "missing event assignment", "event already has assignment", "missing event trigger expression", "undefined unit", "unit conflict", "invalid unit", "undefined or unrepresentable value", "unfound object", "unfound value", "unfound variable", "Invalid structure", "excess arguments", "circular dependency", "invalid expression data type", "variable in expression", "unfound expression", "unfound function", "mismatched variables", "inconsistent value types", "initial expression with assignment", "setting fixed expression", "reaction kinetics not defined" }); // static const CEnumAnnotation< std::string, CIssue::eKind > CIssue::kindDescriptions( { "Unknown issue.", "Invalid expression.", "Empty expression.", "Missing initial value.", "Problem with calculation.", "Missing event assignment.", "Event already has an assignment rule.", "Missing event trigger expression.", "Unit is undefined.", "Conflicting units.", "Invalid unit.", "Value is undefined or unrepresentable.", "Object not found.", "Value not found.", "Variable not found.", "Invalid structure.", "Too many arguments.", "Has circular dependency.", "Invalid expression data type.", "Expression contains a variable.", "CExpression not found.", "CFunction not found.", "Variables are mismatched.", "Inconsistent value types encountered.", "Initial expressions prohibited with assignment.", "Changing fixed expression prohibited", "Reaction kinetics are not defined" }); CIssue::CIssue(const CIssue::eSeverity & severity, const CIssue::eKind & kind): mSeverity(severity), mKind(kind) {} CIssue::CIssue(const CIssue & src): mSeverity(src.mSeverity), mKind(src.mKind) {} CIssue::~CIssue() {} CIssue::operator bool() const { // If this type is implicity cast to a bool, in a conditional // evaluation, it will evaluate to "true" that there IS NOT a // significant "issue", if it is not at "Error" severity. return (mSeverity != CIssue::eSeverity::Error); } CIssue & CIssue::operator &= (const CIssue & rhs) { if (rhs.mSeverity > mSeverity) { mSeverity = rhs.mSeverity; mKind = rhs.mKind; } return *this; } bool CIssue::operator == (const CIssue & rhs) const { if (mSeverity == rhs.mSeverity && mKind == rhs.mKind) return true; else return false; } bool CIssue::isError() const { return !isSuccess(); } bool CIssue::isSuccess() const { return (mSeverity != CIssue::eSeverity::Error); } CValidity & CValidity::operator |= (const CValidity & rhs) { size_t Count = mErrors.count() + mWarnings.count() + mInformation.count(); if (this != &rhs) { mErrors |= rhs.mErrors; mWarnings |= rhs.mWarnings; mInformation |= rhs.mInformation; mFirstWorstIssue &= rhs.mFirstWorstIssue; } if (mpObjectInterface != NULL && Count < mErrors.count() + mWarnings.count() + mInformation.count()) { mpObjectInterface->validityChanged(*this); } return *this; } const CIssue & CValidity::getFirstWorstIssue() const { return mFirstWorstIssue; } CValidity & CValidity::operator = (const CValidity & rhs) { if (this == &rhs) return *this; bool Changed = false; if (mErrors != rhs.mErrors) { mErrors = rhs.mErrors; Changed = true; } if (mWarnings != rhs.mWarnings) { mWarnings = rhs.mWarnings; Changed = true; } if (mInformation != rhs.mInformation) { mInformation = rhs.mInformation; Changed = true; } if (mpObjectInterface != NULL && Changed) { mpObjectInterface->validityChanged(*this); } return *this; } const CIssue::eSeverity & CIssue::getSeverity() const { return mSeverity; } const CIssue::eKind & CIssue::getKind() const { return mKind; } CValidity::CValidity(CObjectInterface * pObjectInterface): mErrors(), mWarnings(), mInformation(), mpObjectInterface(pObjectInterface), mFirstWorstIssue() {} CValidity::CValidity(const CValidity & src, CObjectInterface * pObjectInterface): mErrors(src.mErrors), mWarnings(src.mWarnings), mInformation(src.mInformation), mpObjectInterface(pObjectInterface), mFirstWorstIssue(src.mFirstWorstIssue) {} CValidity::~CValidity() {} void CValidity::clear() { // Only need to reset, if anything is set (i.e. not already clear) if (0 < mErrors.count() + mWarnings.count() + mInformation.count()) { mFirstWorstIssue = CIssue::Success; mErrors.reset(); mWarnings.reset(); mInformation.reset(); // Given something changed, notify the parent // to do it's thing, if it exists. if (mpObjectInterface != NULL) { mpObjectInterface->validityChanged(*this); } } } bool CValidity::empty() const { return mErrors.count() + mWarnings.count() + mInformation.count() == 0; } void CValidity::add(const CIssue & issue) { mFirstWorstIssue &= issue; size_t Count = 0; bool Changed = false; switch (issue.getSeverity()) { case CIssue::eSeverity::Error: Count = mErrors.count(); mErrors |= issue.getKind(); Changed = Count < mErrors.count(); break; case CIssue::eSeverity::Warning: Count = mWarnings.count(); mWarnings |= issue.getKind(); Changed = Count < mWarnings.count(); break; case CIssue::eSeverity::Information: Count = mInformation.count(); mInformation |= issue.getKind(); Changed = Count < mInformation.count(); break; case CIssue::eSeverity::__SIZE: break; } if (Changed && mpObjectInterface != NULL) { mpObjectInterface->validityChanged(*this); } } void CValidity::remove(const CIssue & issue) { if (mFirstWorstIssue == issue) mFirstWorstIssue = CIssue::Success; size_t Count = 0; bool Changed = false; switch (issue.getSeverity()) { case CIssue::eSeverity::Error: Count = mErrors.count(); mErrors &= ~Kind(issue.getKind()); Changed = Count > mErrors.count(); break; case CIssue::eSeverity::Warning: Count = mWarnings.count(); mWarnings &= ~Kind(issue.getKind()); Changed = Count > mWarnings.count(); break; case CIssue::eSeverity::Information: Count = mInformation.count(); mInformation &= ~Kind(issue.getKind()); Changed = Count > mInformation.count(); break; case CIssue::eSeverity::__SIZE: break; } if (Changed && mpObjectInterface != NULL) { mpObjectInterface->validityChanged(*this); } } void CValidity::remove(const CValidity::Severity & severity, const CValidity::Kind & kind) { size_t Count = mErrors.count() + mWarnings.count() + mInformation.count(); if (severity.isSet(CIssue::eSeverity::Error)) mErrors &= ~kind; if (severity.isSet(CIssue::eSeverity::Warning)) mWarnings &= ~kind; if (severity.isSet(CIssue::eSeverity::Information)) mInformation &= ~kind; if (mpObjectInterface != NULL && Count > mErrors.count() + mWarnings.count() + mInformation.count()) { mpObjectInterface->validityChanged(*this); } } CIssue::eSeverity CValidity::getHighestSeverity(const CValidity::Severity & filterSeverity, const CValidity::Kind & filterKind) const { if (filterSeverity.isSet(CIssue::eSeverity::Error) && (mErrors & filterKind)) return CIssue::eSeverity::Error; if (filterSeverity.isSet(CIssue::eSeverity::Warning) && (mWarnings & filterKind)) return CIssue::eSeverity::Warning; if (filterSeverity.isSet(CIssue::eSeverity::Information) && (mInformation & filterKind)) return CIssue::eSeverity::Information; return CIssue::eSeverity::Success; } const CValidity::Kind & CValidity::get(const CIssue::eSeverity & severity) const { static const Kind OK; switch (severity) { case CIssue::eSeverity::Error: return mErrors; case CIssue::eSeverity::Warning: return mWarnings; case CIssue::eSeverity::Information: return mInformation; default: return OK; } } const std::string CValidity::getIssueMessages(const Severity & severityFilter, const Kind & kindFilter) const { std::string severityString = ""; std::vector< std::string > descriptions; std::string messages = ""; std::vector< std::string >::const_iterator it, end; if (severityFilter.isSet(CIssue::eSeverity::Error)) { severityString = "Error: "; descriptions = mErrors.getAnnotations(CIssue::kindDescriptions, kindFilter); it = descriptions.begin(); end = descriptions.end(); for (; it != end; ++it) { messages += severityString + *it + "\n"; } } if (severityFilter.isSet(CIssue::eSeverity::Warning)) { severityString = "Warning: "; descriptions = mWarnings.getAnnotations(CIssue::kindDescriptions, kindFilter); it = descriptions.begin(); end = descriptions.end(); for (; it != end; ++it) { messages += severityString + *it + "\n"; } } if (severityFilter.isSet(CIssue::eSeverity::Information)) { severityString = "Information: "; descriptions = mInformation.getAnnotations(CIssue::kindDescriptions, kindFilter); it = descriptions.begin(); end = descriptions.end(); for (; it != end; ++it) { messages += severityString + *it + "\n"; } } // Remove last newline if (!messages.empty()) messages = messages.substr(0, messages.size() - 1); return messages; } <|endoftext|>
<commit_before>// @(#)root/cont:$Id$ // Author: Rene Brun 28/09/2001 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ /** \class TProcessID \ingroup Base A TProcessID identifies a ROOT job in a unique way in time and space. The TProcessID title consists of a TUUID object which provides a globally unique identifier (for more see TUUID.h). A TProcessID is automatically created by the TROOT constructor. When a TFile contains referenced objects (see TRef), the TProcessID object is written to the file. If a file has been written in multiple sessions (same machine or not), a TProcessID is written for each session. These objects are used by the class TRef to uniquely identified any TObject pointed by a TRef. When a referenced object is read from a file (its bit kIsReferenced is set), this object is entered into the objects table of the corresponding TProcessID. Each TFile has a list of TProcessIDs (see TFile::fProcessIDs) also accessible via TProcessID::fgPIDs (for all files). When this object is deleted, it is removed from the table via the cleanup mechanism invoked by the TObject destructor. Each TProcessID has a table (TObjArray *fObjects) that keeps track of all referenced objects. If a referenced object has a fUniqueID set, a pointer to this unique object may be found via fObjects->At(fUniqueID). In the same way, when a TRef::GetObject is called, GetObject uses its own fUniqueID to find the pointer to the referenced object. See TProcessID::GetObjectWithID and PutObjectWithID. When a referenced object is deleted, its slot in fObjects is set to null. // See also TProcessUUID: a specialized TProcessID to manage the single list of TUUIDs. */ #include "TProcessID.h" #include "TROOT.h" #include "TObjArray.h" #include "TExMap.h" #include "TVirtualMutex.h" #include "TError.h" TObjArray *TProcessID::fgPIDs = 0; //pointer to the list of TProcessID TProcessID *TProcessID::fgPID = 0; //pointer to the TProcessID of the current session std::atomic_uint TProcessID::fgNumber(0); //Current referenced object instance count TExMap *TProcessID::fgObjPIDs= 0; //Table (pointer,pids) ClassImp(TProcessID); static std::atomic<TProcessID *> gIsValidCache; using PIDCacheContent_t = std::pair<Int_t, TProcessID*>; static std::atomic<PIDCacheContent_t *> gGetProcessWithUIDCache; //////////////////////////////////////////////////////////////////////////////// /// Return hash value for this object. static inline ULong_t Void_Hash(const void *ptr) { return TString::Hash(&ptr, sizeof(void*)); } //////////////////////////////////////////////////////////////////////////////// /// Default constructor. TProcessID::TProcessID() { // MSVC doesn't support fSpinLock=ATOMIC_FLAG_INIT; in the class definition // and Apple LLVM version 7.3.0 (clang-703.0.31) warns about: // fLock(ATOMIC_FLAG_INIT) // ^~~~~~~~~~~~~~~~ // c++/v1/atomic:1779:26: note: expanded from macro 'ATOMIC_FLAG_INIT' // #define ATOMIC_FLAG_INIT {false} // So reset the flag instead. std::atomic_flag_clear( &fLock ); fCount = 0; fObjects = 0; } //////////////////////////////////////////////////////////////////////////////// /// Destructor. TProcessID::~TProcessID() { delete fObjects; fObjects = 0; TProcessID *This = this; // We need a referencable value for the 1st argument gIsValidCache.compare_exchange_strong(This, nullptr); auto current = gGetProcessWithUIDCache.load(); if (current && current->second == this) { gGetProcessWithUIDCache.compare_exchange_strong(current, nullptr); delete current; } R__WRITE_LOCKGUARD(ROOT::gCoreMutex); fgPIDs->Remove(this); } //////////////////////////////////////////////////////////////////////////////// /// Static function to add a new TProcessID to the list of PIDs. TProcessID *TProcessID::AddProcessID() { R__WRITE_LOCKGUARD(ROOT::gCoreMutex); if (fgPIDs && fgPIDs->GetEntriesFast() >= 65534) { if (fgPIDs->GetEntriesFast() == 65534) { ::Warning("TProcessID::AddProcessID","Maximum number of TProcessID (65535) is almost reached (one left). TRef will stop being functional when the limit is reached."); } else { ::Fatal("TProcessID::AddProcessID","Maximum number of TProcessID (65535) has been reached. TRef are not longer functional."); } } TProcessID *pid = new TProcessID(); if (!fgPIDs) { fgPID = pid; fgPIDs = new TObjArray(10); gROOT->GetListOfCleanups()->Add(fgPIDs); } UShort_t apid = fgPIDs->GetEntriesFast(); pid->IncrementCount(); fgPIDs->Add(pid); // if (apid == 0) for(int incr=0; incr < 65533; ++incr) fgPIDs->Add(0); // NOTE: DEBUGGING ONLY MUST BE REMOVED! char name[20]; snprintf(name,20,"ProcessID%d",apid); pid->SetName(name); pid->SetUniqueID((UInt_t)apid); TUUID u; //apid = fgPIDs->GetEntriesFast(); pid->SetTitle(u.AsString()); return pid; } //////////////////////////////////////////////////////////////////////////////// /// static function returning the ID assigned to obj /// If the object is not yet referenced, its kIsReferenced bit is set /// and its fUniqueID set to the current number of referenced objects so far. UInt_t TProcessID::AssignID(TObject *obj) { R__WRITE_LOCKGUARD(ROOT::gCoreMutex); UInt_t uid = obj->GetUniqueID() & 0xffffff; if (obj == fgPID->GetObjectWithID(uid)) return uid; if (obj->TestBit(kIsReferenced)) { fgPID->PutObjectWithID(obj,uid); return uid; } if (fgNumber >= 16777215) { // This process id is 'full', we need to use a new one. fgPID = AddProcessID(); fgNumber = 0; for(Int_t i = 0; i < fgPIDs->GetLast()+1; ++i) { TProcessID *pid = (TProcessID*)fgPIDs->At(i); if (pid && pid->fObjects && pid->fObjects->GetEntries() == 0) { pid->Clear(); } } } fgNumber++; obj->SetBit(kIsReferenced); uid = fgNumber; // if (fgNumber<10) fgNumber = 16777213; // NOTE: DEBUGGING ONLY MUST BE REMOVED! if ( fgPID->GetUniqueID() < 255 ) { obj->SetUniqueID( (uid & 0xffffff) + (fgPID->GetUniqueID()<<24) ); } else { obj->SetUniqueID( (uid & 0xffffff) + 0xff000000 /* 255 << 24 */ ); } fgPID->PutObjectWithID(obj,uid); return uid; } //////////////////////////////////////////////////////////////////////////////// /// Initialize fObjects. void TProcessID::CheckInit() { if (!fObjects) { while (fLock.test_and_set(std::memory_order_acquire)); // acquire lock if (!fObjects) fObjects = new TObjArray(100); fLock.clear(std::memory_order_release); } } //////////////////////////////////////////////////////////////////////////////// /// static function (called by TROOT destructor) to delete all TProcessIDs void TProcessID::Cleanup() { R__WRITE_LOCKGUARD(ROOT::gCoreMutex); fgPIDs->Delete(); gROOT->GetListOfCleanups()->Remove(fgPIDs); delete fgPIDs; fgPIDs = 0; } //////////////////////////////////////////////////////////////////////////////// /// delete the TObjArray pointing to referenced objects /// this function is called by TFile::Close("R") void TProcessID::Clear(Option_t *) { if (GetUniqueID()>254 && fObjects && fgObjPIDs) { // We might have many references registered in the map for(Int_t i = 0; i < fObjects->GetSize(); ++i) { TObject *obj = fObjects->UncheckedAt(i); if (obj) { ULong64_t hash = Void_Hash(obj); fgObjPIDs->Remove(hash,(Long64_t)obj); (*fObjects)[i] = 0; } } } delete fObjects; fObjects = 0; } //////////////////////////////////////////////////////////////////////////////// /// The reference fCount is used to delete the TProcessID /// in the TFile destructor when fCount = 0 Int_t TProcessID::DecrementCount() { fCount--; if (fCount < 0) fCount = 0; return fCount; } //////////////////////////////////////////////////////////////////////////////// /// static function returning a pointer to TProcessID number pid in fgPIDs TProcessID *TProcessID::GetProcessID(UShort_t pid) { return (TProcessID*)fgPIDs->At(pid); } //////////////////////////////////////////////////////////////////////////////// /// Return the (static) number of process IDs. UInt_t TProcessID::GetNProcessIDs() { return fgPIDs ? fgPIDs->GetLast()+1 : 0; } //////////////////////////////////////////////////////////////////////////////// /// static function returning a pointer to TProcessID with its pid /// encoded in the highest byte of uid TProcessID *TProcessID::GetProcessWithUID(UInt_t uid, const void *obj) { Int_t pid = (uid>>24)&0xff; if (pid==0xff) { // Look up the pid in the table (pointer,pid) if (fgObjPIDs==0) return 0; ULong_t hash = Void_Hash(obj); R__READ_LOCKGUARD(ROOT::gCoreMutex); pid = fgObjPIDs->GetValue(hash,(Long_t)obj); return (TProcessID*)fgPIDs->At(pid); } else { auto current = gGetProcessWithUIDCache.load(); if (current && current->first == pid) return current->second; R__READ_LOCKGUARD(ROOT::gCoreMutex); auto res = (TProcessID*)fgPIDs->At(pid); auto next = new PIDCacheContent_t(pid, res); auto old = gGetProcessWithUIDCache.exchange(next); delete old; return res; } } //////////////////////////////////////////////////////////////////////////////// /// static function returning a pointer to TProcessID with its pid /// encoded in the highest byte of obj->GetUniqueID() TProcessID *TProcessID::GetProcessWithUID(const TObject *obj) { return GetProcessWithUID(obj->GetUniqueID(),obj); } //////////////////////////////////////////////////////////////////////////////// /// static function returning the pointer to the session TProcessID TProcessID *TProcessID::GetSessionProcessID() { return fgPID; } //////////////////////////////////////////////////////////////////////////////// /// Increase the reference count to this object. Int_t TProcessID::IncrementCount() { CheckInit(); ++fCount; return fCount; } //////////////////////////////////////////////////////////////////////////////// /// Return the current referenced object count /// fgNumber is incremented every time a new object is referenced UInt_t TProcessID::GetObjectCount() { return fgNumber; } //////////////////////////////////////////////////////////////////////////////// /// returns the TObject with unique identifier uid in the table of objects TObject *TProcessID::GetObjectWithID(UInt_t uidd) { Int_t uid = uidd & 0xffffff; //take only the 24 lower bits if (fObjects==0 || uid >= fObjects->GetSize()) return 0; return fObjects->UncheckedAt(uid); } //////////////////////////////////////////////////////////////////////////////// /// static: returns pointer to current TProcessID TProcessID *TProcessID::GetPID() { return fgPID; } //////////////////////////////////////////////////////////////////////////////// /// static: returns array of TProcessIDs TObjArray *TProcessID::GetPIDs() { return fgPIDs; } //////////////////////////////////////////////////////////////////////////////// /// static function. return kTRUE if pid is a valid TProcessID Bool_t TProcessID::IsValid(TProcessID *pid) { if (gIsValidCache == pid) return kTRUE; R__READ_LOCKGUARD(ROOT::gCoreMutex); if (fgPIDs==0) return kFALSE; if (fgPIDs->IndexOf(pid) >= 0) { gIsValidCache = pid; return kTRUE; } if (pid == (TProcessID*)gROOT->GetUUIDs()) { gIsValidCache = pid; return kTRUE; } return kFALSE; } //////////////////////////////////////////////////////////////////////////////// /// stores the object at the uid th slot in the table of objects /// The object uniqued is set as well as its kMustCleanup bit void TProcessID::PutObjectWithID(TObject *obj, UInt_t uid) { R__LOCKGUARD_IMT(gROOTMutex); // Lock for parallel TTree I/O if (uid == 0) uid = obj->GetUniqueID() & 0xffffff; if (!fObjects) fObjects = new TObjArray(100); fObjects->AddAtAndExpand(obj,uid); obj->SetBit(kMustCleanup); if ( (obj->GetUniqueID()&0xff000000)==0xff000000 ) { // We have more than 255 pids we need to store this // pointer in the table(pointer,pid) since there is no // more space in fUniqueID if (fgObjPIDs==0) fgObjPIDs = new TExMap; ULong_t hash = Void_Hash(obj); // We use operator() rather than Add() because // if the address has already been registered, we want to // update it's uniqueID (this can easily happen when the // referenced object have been stored in a TClonesArray. (*fgObjPIDs)(hash, (Long_t)obj) = GetUniqueID(); } } //////////////////////////////////////////////////////////////////////////////// /// called by the object destructor /// remove reference to obj from the current table if it is referenced void TProcessID::RecursiveRemove(TObject *obj) { if (!fObjects) return; if (!obj->TestBit(kIsReferenced)) return; UInt_t uid = obj->GetUniqueID() & 0xffffff; if (obj == GetObjectWithID(uid)) { R__WRITE_LOCKGUARD(ROOT::gCoreMutex); if (fgObjPIDs) { ULong64_t hash = Void_Hash(obj); fgObjPIDs->Remove(hash,(Long64_t)obj); } (*fObjects)[uid] = 0; // Avoid recalculation of fLast (compared to ->RemoveAt(uid)) } } //////////////////////////////////////////////////////////////////////////////// /// static function to set the current referenced object count /// fgNumber is incremented every time a new object is referenced void TProcessID::SetObjectCount(UInt_t number) { fgNumber = number; } <commit_msg>TProcessID::RecursiveRemove: prevent spurrious error msg.<commit_after>// @(#)root/cont:$Id$ // Author: Rene Brun 28/09/2001 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ /** \class TProcessID \ingroup Base A TProcessID identifies a ROOT job in a unique way in time and space. The TProcessID title consists of a TUUID object which provides a globally unique identifier (for more see TUUID.h). A TProcessID is automatically created by the TROOT constructor. When a TFile contains referenced objects (see TRef), the TProcessID object is written to the file. If a file has been written in multiple sessions (same machine or not), a TProcessID is written for each session. These objects are used by the class TRef to uniquely identified any TObject pointed by a TRef. When a referenced object is read from a file (its bit kIsReferenced is set), this object is entered into the objects table of the corresponding TProcessID. Each TFile has a list of TProcessIDs (see TFile::fProcessIDs) also accessible via TProcessID::fgPIDs (for all files). When this object is deleted, it is removed from the table via the cleanup mechanism invoked by the TObject destructor. Each TProcessID has a table (TObjArray *fObjects) that keeps track of all referenced objects. If a referenced object has a fUniqueID set, a pointer to this unique object may be found via fObjects->At(fUniqueID). In the same way, when a TRef::GetObject is called, GetObject uses its own fUniqueID to find the pointer to the referenced object. See TProcessID::GetObjectWithID and PutObjectWithID. When a referenced object is deleted, its slot in fObjects is set to null. // See also TProcessUUID: a specialized TProcessID to manage the single list of TUUIDs. */ #include "TProcessID.h" #include "TROOT.h" #include "TObjArray.h" #include "TExMap.h" #include "TVirtualMutex.h" #include "TError.h" TObjArray *TProcessID::fgPIDs = 0; //pointer to the list of TProcessID TProcessID *TProcessID::fgPID = 0; //pointer to the TProcessID of the current session std::atomic_uint TProcessID::fgNumber(0); //Current referenced object instance count TExMap *TProcessID::fgObjPIDs= 0; //Table (pointer,pids) ClassImp(TProcessID); static std::atomic<TProcessID *> gIsValidCache; using PIDCacheContent_t = std::pair<Int_t, TProcessID*>; static std::atomic<PIDCacheContent_t *> gGetProcessWithUIDCache; //////////////////////////////////////////////////////////////////////////////// /// Return hash value for this object. static inline ULong_t Void_Hash(const void *ptr) { return TString::Hash(&ptr, sizeof(void*)); } //////////////////////////////////////////////////////////////////////////////// /// Default constructor. TProcessID::TProcessID() { // MSVC doesn't support fSpinLock=ATOMIC_FLAG_INIT; in the class definition // and Apple LLVM version 7.3.0 (clang-703.0.31) warns about: // fLock(ATOMIC_FLAG_INIT) // ^~~~~~~~~~~~~~~~ // c++/v1/atomic:1779:26: note: expanded from macro 'ATOMIC_FLAG_INIT' // #define ATOMIC_FLAG_INIT {false} // So reset the flag instead. std::atomic_flag_clear( &fLock ); fCount = 0; fObjects = 0; } //////////////////////////////////////////////////////////////////////////////// /// Destructor. TProcessID::~TProcessID() { delete fObjects; fObjects = 0; TProcessID *This = this; // We need a referencable value for the 1st argument gIsValidCache.compare_exchange_strong(This, nullptr); auto current = gGetProcessWithUIDCache.load(); if (current && current->second == this) { gGetProcessWithUIDCache.compare_exchange_strong(current, nullptr); delete current; } R__WRITE_LOCKGUARD(ROOT::gCoreMutex); fgPIDs->Remove(this); } //////////////////////////////////////////////////////////////////////////////// /// Static function to add a new TProcessID to the list of PIDs. TProcessID *TProcessID::AddProcessID() { R__WRITE_LOCKGUARD(ROOT::gCoreMutex); if (fgPIDs && fgPIDs->GetEntriesFast() >= 65534) { if (fgPIDs->GetEntriesFast() == 65534) { ::Warning("TProcessID::AddProcessID","Maximum number of TProcessID (65535) is almost reached (one left). TRef will stop being functional when the limit is reached."); } else { ::Fatal("TProcessID::AddProcessID","Maximum number of TProcessID (65535) has been reached. TRef are not longer functional."); } } TProcessID *pid = new TProcessID(); if (!fgPIDs) { fgPID = pid; fgPIDs = new TObjArray(10); gROOT->GetListOfCleanups()->Add(fgPIDs); } UShort_t apid = fgPIDs->GetEntriesFast(); pid->IncrementCount(); fgPIDs->Add(pid); // if (apid == 0) for(int incr=0; incr < 65533; ++incr) fgPIDs->Add(0); // NOTE: DEBUGGING ONLY MUST BE REMOVED! char name[20]; snprintf(name,20,"ProcessID%d",apid); pid->SetName(name); pid->SetUniqueID((UInt_t)apid); TUUID u; //apid = fgPIDs->GetEntriesFast(); pid->SetTitle(u.AsString()); return pid; } //////////////////////////////////////////////////////////////////////////////// /// static function returning the ID assigned to obj /// If the object is not yet referenced, its kIsReferenced bit is set /// and its fUniqueID set to the current number of referenced objects so far. UInt_t TProcessID::AssignID(TObject *obj) { R__WRITE_LOCKGUARD(ROOT::gCoreMutex); UInt_t uid = obj->GetUniqueID() & 0xffffff; if (obj == fgPID->GetObjectWithID(uid)) return uid; if (obj->TestBit(kIsReferenced)) { fgPID->PutObjectWithID(obj,uid); return uid; } if (fgNumber >= 16777215) { // This process id is 'full', we need to use a new one. fgPID = AddProcessID(); fgNumber = 0; for(Int_t i = 0; i < fgPIDs->GetLast()+1; ++i) { TProcessID *pid = (TProcessID*)fgPIDs->At(i); if (pid && pid->fObjects && pid->fObjects->GetEntries() == 0) { pid->Clear(); } } } fgNumber++; obj->SetBit(kIsReferenced); uid = fgNumber; // if (fgNumber<10) fgNumber = 16777213; // NOTE: DEBUGGING ONLY MUST BE REMOVED! if ( fgPID->GetUniqueID() < 255 ) { obj->SetUniqueID( (uid & 0xffffff) + (fgPID->GetUniqueID()<<24) ); } else { obj->SetUniqueID( (uid & 0xffffff) + 0xff000000 /* 255 << 24 */ ); } fgPID->PutObjectWithID(obj,uid); return uid; } //////////////////////////////////////////////////////////////////////////////// /// Initialize fObjects. void TProcessID::CheckInit() { if (!fObjects) { while (fLock.test_and_set(std::memory_order_acquire)); // acquire lock if (!fObjects) fObjects = new TObjArray(100); fLock.clear(std::memory_order_release); } } //////////////////////////////////////////////////////////////////////////////// /// static function (called by TROOT destructor) to delete all TProcessIDs void TProcessID::Cleanup() { R__WRITE_LOCKGUARD(ROOT::gCoreMutex); fgPIDs->Delete(); gROOT->GetListOfCleanups()->Remove(fgPIDs); delete fgPIDs; fgPIDs = 0; } //////////////////////////////////////////////////////////////////////////////// /// delete the TObjArray pointing to referenced objects /// this function is called by TFile::Close("R") void TProcessID::Clear(Option_t *) { if (GetUniqueID()>254 && fObjects && fgObjPIDs) { // We might have many references registered in the map for(Int_t i = 0; i < fObjects->GetSize(); ++i) { TObject *obj = fObjects->UncheckedAt(i); if (obj) { ULong64_t hash = Void_Hash(obj); fgObjPIDs->Remove(hash,(Long64_t)obj); (*fObjects)[i] = 0; } } } delete fObjects; fObjects = 0; } //////////////////////////////////////////////////////////////////////////////// /// The reference fCount is used to delete the TProcessID /// in the TFile destructor when fCount = 0 Int_t TProcessID::DecrementCount() { fCount--; if (fCount < 0) fCount = 0; return fCount; } //////////////////////////////////////////////////////////////////////////////// /// static function returning a pointer to TProcessID number pid in fgPIDs TProcessID *TProcessID::GetProcessID(UShort_t pid) { return (TProcessID*)fgPIDs->At(pid); } //////////////////////////////////////////////////////////////////////////////// /// Return the (static) number of process IDs. UInt_t TProcessID::GetNProcessIDs() { return fgPIDs ? fgPIDs->GetLast()+1 : 0; } //////////////////////////////////////////////////////////////////////////////// /// static function returning a pointer to TProcessID with its pid /// encoded in the highest byte of uid TProcessID *TProcessID::GetProcessWithUID(UInt_t uid, const void *obj) { Int_t pid = (uid>>24)&0xff; if (pid==0xff) { // Look up the pid in the table (pointer,pid) if (fgObjPIDs==0) return 0; ULong_t hash = Void_Hash(obj); R__READ_LOCKGUARD(ROOT::gCoreMutex); pid = fgObjPIDs->GetValue(hash,(Long_t)obj); return (TProcessID*)fgPIDs->At(pid); } else { auto current = gGetProcessWithUIDCache.load(); if (current && current->first == pid) return current->second; R__READ_LOCKGUARD(ROOT::gCoreMutex); auto res = (TProcessID*)fgPIDs->At(pid); auto next = new PIDCacheContent_t(pid, res); auto old = gGetProcessWithUIDCache.exchange(next); delete old; return res; } } //////////////////////////////////////////////////////////////////////////////// /// static function returning a pointer to TProcessID with its pid /// encoded in the highest byte of obj->GetUniqueID() TProcessID *TProcessID::GetProcessWithUID(const TObject *obj) { return GetProcessWithUID(obj->GetUniqueID(),obj); } //////////////////////////////////////////////////////////////////////////////// /// static function returning the pointer to the session TProcessID TProcessID *TProcessID::GetSessionProcessID() { return fgPID; } //////////////////////////////////////////////////////////////////////////////// /// Increase the reference count to this object. Int_t TProcessID::IncrementCount() { CheckInit(); ++fCount; return fCount; } //////////////////////////////////////////////////////////////////////////////// /// Return the current referenced object count /// fgNumber is incremented every time a new object is referenced UInt_t TProcessID::GetObjectCount() { return fgNumber; } //////////////////////////////////////////////////////////////////////////////// /// returns the TObject with unique identifier uid in the table of objects TObject *TProcessID::GetObjectWithID(UInt_t uidd) { Int_t uid = uidd & 0xffffff; //take only the 24 lower bits if (fObjects==0 || uid >= fObjects->GetSize()) return 0; return fObjects->UncheckedAt(uid); } //////////////////////////////////////////////////////////////////////////////// /// static: returns pointer to current TProcessID TProcessID *TProcessID::GetPID() { return fgPID; } //////////////////////////////////////////////////////////////////////////////// /// static: returns array of TProcessIDs TObjArray *TProcessID::GetPIDs() { return fgPIDs; } //////////////////////////////////////////////////////////////////////////////// /// static function. return kTRUE if pid is a valid TProcessID Bool_t TProcessID::IsValid(TProcessID *pid) { if (gIsValidCache == pid) return kTRUE; R__READ_LOCKGUARD(ROOT::gCoreMutex); if (fgPIDs==0) return kFALSE; if (fgPIDs->IndexOf(pid) >= 0) { gIsValidCache = pid; return kTRUE; } if (pid == (TProcessID*)gROOT->GetUUIDs()) { gIsValidCache = pid; return kTRUE; } return kFALSE; } //////////////////////////////////////////////////////////////////////////////// /// stores the object at the uid th slot in the table of objects /// The object uniqued is set as well as its kMustCleanup bit void TProcessID::PutObjectWithID(TObject *obj, UInt_t uid) { R__LOCKGUARD_IMT(gROOTMutex); // Lock for parallel TTree I/O if (uid == 0) uid = obj->GetUniqueID() & 0xffffff; if (!fObjects) fObjects = new TObjArray(100); fObjects->AddAtAndExpand(obj,uid); obj->SetBit(kMustCleanup); if ( (obj->GetUniqueID()&0xff000000)==0xff000000 ) { // We have more than 255 pids we need to store this // pointer in the table(pointer,pid) since there is no // more space in fUniqueID if (fgObjPIDs==0) fgObjPIDs = new TExMap; ULong_t hash = Void_Hash(obj); // We use operator() rather than Add() because // if the address has already been registered, we want to // update it's uniqueID (this can easily happen when the // referenced object have been stored in a TClonesArray. (*fgObjPIDs)(hash, (Long_t)obj) = GetUniqueID(); } } //////////////////////////////////////////////////////////////////////////////// /// called by the object destructor /// remove reference to obj from the current table if it is referenced void TProcessID::RecursiveRemove(TObject *obj) { if (!fObjects) return; if (!obj->TestBit(kIsReferenced)) return; UInt_t uid = obj->GetUniqueID() & 0xffffff; if (obj == GetObjectWithID(uid)) { R__WRITE_LOCKGUARD(ROOT::gCoreMutex); if (fgObjPIDs && ((obj->GetUniqueID()&0xff000000)==0xff000000)) { ULong64_t hash = Void_Hash(obj); fgObjPIDs->Remove(hash,(Long64_t)obj); } (*fObjects)[uid] = 0; // Avoid recalculation of fLast (compared to ->RemoveAt(uid)) } } //////////////////////////////////////////////////////////////////////////////// /// static function to set the current referenced object count /// fgNumber is incremented every time a new object is referenced void TProcessID::SetObjectCount(UInt_t number) { fgNumber = number; } <|endoftext|>
<commit_before>/*************************************************************************/ /* file_access_pack.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "file_access_pack.h" #include "core/version.h" #include <stdio.h> #define PACK_VERSION 1 Error PackedData::add_pack(const String &p_path) { for (int i = 0; i < sources.size(); i++) { if (sources[i]->try_open_pack(p_path)) { return OK; }; }; return ERR_FILE_UNRECOGNIZED; }; void PackedData::add_path(const String &pkg_path, const String &path, uint64_t ofs, uint64_t size, const uint8_t *p_md5, PackSource *p_src) { PathMD5 pmd5(path.md5_buffer()); //printf("adding path %ls, %lli, %lli\n", path.c_str(), pmd5.a, pmd5.b); bool exists = files.has(pmd5); PackedFile pf; pf.pack = pkg_path; pf.offset = ofs; pf.size = size; for (int i = 0; i < 16; i++) pf.md5[i] = p_md5[i]; pf.src = p_src; files[pmd5] = pf; if (!exists) { //search for dir String p = path.replace_first("res://", ""); PackedDir *cd = root; if (p.find("/") != -1) { //in a subdir Vector<String> ds = p.get_base_dir().split("/"); for (int j = 0; j < ds.size(); j++) { if (!cd->subdirs.has(ds[j])) { PackedDir *pd = memnew(PackedDir); pd->name = ds[j]; pd->parent = cd; cd->subdirs[pd->name] = pd; cd = pd; } else { cd = cd->subdirs[ds[j]]; } } } String filename = path.get_file(); // Don't add as a file if the path points to a directoryy if (!filename.empty()) { cd->files.insert(filename); } } } void PackedData::add_pack_source(PackSource *p_source) { if (p_source != NULL) { sources.push_back(p_source); } }; PackedData *PackedData::singleton = NULL; PackedData::PackedData() { singleton = this; root = memnew(PackedDir); root->parent = NULL; disabled = false; add_pack_source(memnew(PackedSourcePCK)); } void PackedData::_free_packed_dirs(PackedDir *p_dir) { for (Map<String, PackedDir *>::Element *E = p_dir->subdirs.front(); E; E = E->next()) _free_packed_dirs(E->get()); memdelete(p_dir); } PackedData::~PackedData() { for (int i = 0; i < sources.size(); i++) { memdelete(sources[i]); } _free_packed_dirs(root); } ////////////////////////////////////////////////////////////////// bool PackedSourcePCK::try_open_pack(const String &p_path) { FileAccess *f = FileAccess::open(p_path, FileAccess::READ); if (!f) return false; //printf("try open %ls!\n", p_path.c_str()); uint32_t magic = f->get_32(); if (magic != 0x43504447) { //maybe at the end.... self contained exe f->seek_end(); f->seek(f->get_position() - 4); magic = f->get_32(); if (magic != 0x43504447) { memdelete(f); return false; } f->seek(f->get_position() - 12); uint64_t ds = f->get_64(); f->seek(f->get_position() - ds - 8); magic = f->get_32(); if (magic != 0x43504447) { memdelete(f); return false; } } uint32_t version = f->get_32(); uint32_t ver_major = f->get_32(); uint32_t ver_minor = f->get_32(); f->get_32(); // ver_rev ERR_FAIL_COND_V_MSG(version != PACK_VERSION, false, "Pack version unsupported: " + itos(version) + "."); ERR_FAIL_COND_V_MSG(ver_major > VERSION_MAJOR || (ver_major == VERSION_MAJOR && ver_minor > VERSION_MINOR), false, "Pack created with a newer version of the engine: " + itos(ver_major) + "." + itos(ver_minor) + "."); for (int i = 0; i < 16; i++) { //reserved f->get_32(); } int file_count = f->get_32(); for (int i = 0; i < file_count; i++) { uint32_t sl = f->get_32(); CharString cs; cs.resize(sl + 1); f->get_buffer((uint8_t *)cs.ptr(), sl); cs[sl] = 0; String path; path.parse_utf8(cs.ptr()); uint64_t ofs = f->get_64(); uint64_t size = f->get_64(); uint8_t md5[16]; f->get_buffer(md5, 16); PackedData::get_singleton()->add_path(p_path, path, ofs, size, md5, this); }; return true; }; FileAccess *PackedSourcePCK::get_file(const String &p_path, PackedData::PackedFile *p_file) { return memnew(FileAccessPack(p_path, *p_file)); }; ////////////////////////////////////////////////////////////////// Error FileAccessPack::_open(const String &p_path, int p_mode_flags) { ERR_FAIL_V(ERR_UNAVAILABLE); return ERR_UNAVAILABLE; } void FileAccessPack::close() { f->close(); } bool FileAccessPack::is_open() const { return f->is_open(); } void FileAccessPack::seek(size_t p_position) { if (p_position > pf.size) { eof = true; } else { eof = false; } f->seek(pf.offset + p_position); pos = p_position; } void FileAccessPack::seek_end(int64_t p_position) { seek(pf.size + p_position); } size_t FileAccessPack::get_position() const { return pos; } size_t FileAccessPack::get_len() const { return pf.size; } bool FileAccessPack::eof_reached() const { return eof; } uint8_t FileAccessPack::get_8() const { if (pos >= pf.size) { eof = true; return 0; } pos++; return f->get_8(); } int FileAccessPack::get_buffer(uint8_t *p_dst, int p_length) const { if (eof) return 0; uint64_t to_read = p_length; if (to_read + pos > pf.size) { eof = true; to_read = int64_t(pf.size) - int64_t(pos); } pos += p_length; if (to_read <= 0) return 0; f->get_buffer(p_dst, to_read); return to_read; } void FileAccessPack::set_endian_swap(bool p_swap) { FileAccess::set_endian_swap(p_swap); f->set_endian_swap(p_swap); } Error FileAccessPack::get_error() const { if (eof) return ERR_FILE_EOF; return OK; } void FileAccessPack::flush() { ERR_FAIL(); } void FileAccessPack::store_8(uint8_t p_dest) { ERR_FAIL(); } void FileAccessPack::store_buffer(const uint8_t *p_src, int p_length) { ERR_FAIL(); } bool FileAccessPack::file_exists(const String &p_name) { return false; } FileAccessPack::FileAccessPack(const String &p_path, const PackedData::PackedFile &p_file) : pf(p_file), f(FileAccess::open(pf.pack, FileAccess::READ)) { ERR_FAIL_COND_MSG(!f, "Can't open pack-referenced file: " + String(pf.pack) + "."); f->seek(pf.offset); pos = 0; eof = false; } FileAccessPack::~FileAccessPack() { if (f) memdelete(f); } ////////////////////////////////////////////////////////////////////////////////// // DIR ACCESS ////////////////////////////////////////////////////////////////////////////////// Error DirAccessPack::list_dir_begin() { list_dirs.clear(); list_files.clear(); for (Map<String, PackedData::PackedDir *>::Element *E = current->subdirs.front(); E; E = E->next()) { list_dirs.push_back(E->key()); } for (Set<String>::Element *E = current->files.front(); E; E = E->next()) { list_files.push_back(E->get()); } return OK; } String DirAccessPack::get_next() { if (list_dirs.size()) { cdir = true; String d = list_dirs.front()->get(); list_dirs.pop_front(); return d; } else if (list_files.size()) { cdir = false; String f = list_files.front()->get(); list_files.pop_front(); return f; } else { return String(); } } bool DirAccessPack::current_is_dir() const { return cdir; } bool DirAccessPack::current_is_hidden() const { return false; } void DirAccessPack::list_dir_end() { list_dirs.clear(); list_files.clear(); } int DirAccessPack::get_drive_count() { return 0; } String DirAccessPack::get_drive(int p_drive) { return ""; } Error DirAccessPack::change_dir(String p_dir) { String nd = p_dir.replace("\\", "/"); bool absolute = false; if (nd.begins_with("res://")) { nd = nd.replace_first("res://", ""); absolute = true; } nd = nd.simplify_path(); if (nd == "") nd = "."; if (nd.begins_with("/")) { nd = nd.replace_first("/", ""); absolute = true; } Vector<String> paths = nd.split("/"); PackedData::PackedDir *pd; if (absolute) pd = PackedData::get_singleton()->root; else pd = current; for (int i = 0; i < paths.size(); i++) { String p = paths[i]; if (p == ".") { continue; } else if (p == "..") { if (pd->parent) { pd = pd->parent; } } else if (pd->subdirs.has(p)) { pd = pd->subdirs[p]; } else { return ERR_INVALID_PARAMETER; } } current = pd; return OK; } String DirAccessPack::get_current_dir() { PackedData::PackedDir *pd = current; String p = current->name; while (pd->parent) { pd = pd->parent; p = pd->name.plus_file(p); } return "res://" + p; } bool DirAccessPack::file_exists(String p_file) { return current->files.has(p_file); } bool DirAccessPack::dir_exists(String p_dir) { return current->subdirs.has(p_dir); } Error DirAccessPack::make_dir(String p_dir) { return ERR_UNAVAILABLE; } Error DirAccessPack::rename(String p_from, String p_to) { return ERR_UNAVAILABLE; } Error DirAccessPack::remove(String p_name) { return ERR_UNAVAILABLE; } size_t DirAccessPack::get_space_left() { return 0; } String DirAccessPack::get_filesystem_type() const { return "PCK"; } DirAccessPack::DirAccessPack() { current = PackedData::get_singleton()->root; cdir = false; } DirAccessPack::~DirAccessPack() { } <commit_msg>DirAccessPack: Fix dir_exists and file_exists for res:// paths<commit_after>/*************************************************************************/ /* file_access_pack.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "file_access_pack.h" #include "core/version.h" #include <stdio.h> #define PACK_VERSION 1 Error PackedData::add_pack(const String &p_path) { for (int i = 0; i < sources.size(); i++) { if (sources[i]->try_open_pack(p_path)) { return OK; }; }; return ERR_FILE_UNRECOGNIZED; }; void PackedData::add_path(const String &pkg_path, const String &path, uint64_t ofs, uint64_t size, const uint8_t *p_md5, PackSource *p_src) { PathMD5 pmd5(path.md5_buffer()); //printf("adding path %ls, %lli, %lli\n", path.c_str(), pmd5.a, pmd5.b); bool exists = files.has(pmd5); PackedFile pf; pf.pack = pkg_path; pf.offset = ofs; pf.size = size; for (int i = 0; i < 16; i++) pf.md5[i] = p_md5[i]; pf.src = p_src; files[pmd5] = pf; if (!exists) { //search for dir String p = path.replace_first("res://", ""); PackedDir *cd = root; if (p.find("/") != -1) { //in a subdir Vector<String> ds = p.get_base_dir().split("/"); for (int j = 0; j < ds.size(); j++) { if (!cd->subdirs.has(ds[j])) { PackedDir *pd = memnew(PackedDir); pd->name = ds[j]; pd->parent = cd; cd->subdirs[pd->name] = pd; cd = pd; } else { cd = cd->subdirs[ds[j]]; } } } String filename = path.get_file(); // Don't add as a file if the path points to a directory if (!filename.empty()) { cd->files.insert(filename); } } } void PackedData::add_pack_source(PackSource *p_source) { if (p_source != NULL) { sources.push_back(p_source); } }; PackedData *PackedData::singleton = NULL; PackedData::PackedData() { singleton = this; root = memnew(PackedDir); root->parent = NULL; disabled = false; add_pack_source(memnew(PackedSourcePCK)); } void PackedData::_free_packed_dirs(PackedDir *p_dir) { for (Map<String, PackedDir *>::Element *E = p_dir->subdirs.front(); E; E = E->next()) _free_packed_dirs(E->get()); memdelete(p_dir); } PackedData::~PackedData() { for (int i = 0; i < sources.size(); i++) { memdelete(sources[i]); } _free_packed_dirs(root); } ////////////////////////////////////////////////////////////////// bool PackedSourcePCK::try_open_pack(const String &p_path) { FileAccess *f = FileAccess::open(p_path, FileAccess::READ); if (!f) return false; //printf("try open %ls!\n", p_path.c_str()); uint32_t magic = f->get_32(); if (magic != 0x43504447) { //maybe at the end.... self contained exe f->seek_end(); f->seek(f->get_position() - 4); magic = f->get_32(); if (magic != 0x43504447) { memdelete(f); return false; } f->seek(f->get_position() - 12); uint64_t ds = f->get_64(); f->seek(f->get_position() - ds - 8); magic = f->get_32(); if (magic != 0x43504447) { memdelete(f); return false; } } uint32_t version = f->get_32(); uint32_t ver_major = f->get_32(); uint32_t ver_minor = f->get_32(); f->get_32(); // ver_rev ERR_FAIL_COND_V_MSG(version != PACK_VERSION, false, "Pack version unsupported: " + itos(version) + "."); ERR_FAIL_COND_V_MSG(ver_major > VERSION_MAJOR || (ver_major == VERSION_MAJOR && ver_minor > VERSION_MINOR), false, "Pack created with a newer version of the engine: " + itos(ver_major) + "." + itos(ver_minor) + "."); for (int i = 0; i < 16; i++) { //reserved f->get_32(); } int file_count = f->get_32(); for (int i = 0; i < file_count; i++) { uint32_t sl = f->get_32(); CharString cs; cs.resize(sl + 1); f->get_buffer((uint8_t *)cs.ptr(), sl); cs[sl] = 0; String path; path.parse_utf8(cs.ptr()); uint64_t ofs = f->get_64(); uint64_t size = f->get_64(); uint8_t md5[16]; f->get_buffer(md5, 16); PackedData::get_singleton()->add_path(p_path, path, ofs, size, md5, this); }; return true; }; FileAccess *PackedSourcePCK::get_file(const String &p_path, PackedData::PackedFile *p_file) { return memnew(FileAccessPack(p_path, *p_file)); }; ////////////////////////////////////////////////////////////////// Error FileAccessPack::_open(const String &p_path, int p_mode_flags) { ERR_FAIL_V(ERR_UNAVAILABLE); return ERR_UNAVAILABLE; } void FileAccessPack::close() { f->close(); } bool FileAccessPack::is_open() const { return f->is_open(); } void FileAccessPack::seek(size_t p_position) { if (p_position > pf.size) { eof = true; } else { eof = false; } f->seek(pf.offset + p_position); pos = p_position; } void FileAccessPack::seek_end(int64_t p_position) { seek(pf.size + p_position); } size_t FileAccessPack::get_position() const { return pos; } size_t FileAccessPack::get_len() const { return pf.size; } bool FileAccessPack::eof_reached() const { return eof; } uint8_t FileAccessPack::get_8() const { if (pos >= pf.size) { eof = true; return 0; } pos++; return f->get_8(); } int FileAccessPack::get_buffer(uint8_t *p_dst, int p_length) const { if (eof) return 0; uint64_t to_read = p_length; if (to_read + pos > pf.size) { eof = true; to_read = int64_t(pf.size) - int64_t(pos); } pos += p_length; if (to_read <= 0) return 0; f->get_buffer(p_dst, to_read); return to_read; } void FileAccessPack::set_endian_swap(bool p_swap) { FileAccess::set_endian_swap(p_swap); f->set_endian_swap(p_swap); } Error FileAccessPack::get_error() const { if (eof) return ERR_FILE_EOF; return OK; } void FileAccessPack::flush() { ERR_FAIL(); } void FileAccessPack::store_8(uint8_t p_dest) { ERR_FAIL(); } void FileAccessPack::store_buffer(const uint8_t *p_src, int p_length) { ERR_FAIL(); } bool FileAccessPack::file_exists(const String &p_name) { return false; } FileAccessPack::FileAccessPack(const String &p_path, const PackedData::PackedFile &p_file) : pf(p_file), f(FileAccess::open(pf.pack, FileAccess::READ)) { ERR_FAIL_COND_MSG(!f, "Can't open pack-referenced file: " + String(pf.pack) + "."); f->seek(pf.offset); pos = 0; eof = false; } FileAccessPack::~FileAccessPack() { if (f) memdelete(f); } ////////////////////////////////////////////////////////////////////////////////// // DIR ACCESS ////////////////////////////////////////////////////////////////////////////////// Error DirAccessPack::list_dir_begin() { list_dirs.clear(); list_files.clear(); for (Map<String, PackedData::PackedDir *>::Element *E = current->subdirs.front(); E; E = E->next()) { list_dirs.push_back(E->key()); } for (Set<String>::Element *E = current->files.front(); E; E = E->next()) { list_files.push_back(E->get()); } return OK; } String DirAccessPack::get_next() { if (list_dirs.size()) { cdir = true; String d = list_dirs.front()->get(); list_dirs.pop_front(); return d; } else if (list_files.size()) { cdir = false; String f = list_files.front()->get(); list_files.pop_front(); return f; } else { return String(); } } bool DirAccessPack::current_is_dir() const { return cdir; } bool DirAccessPack::current_is_hidden() const { return false; } void DirAccessPack::list_dir_end() { list_dirs.clear(); list_files.clear(); } int DirAccessPack::get_drive_count() { return 0; } String DirAccessPack::get_drive(int p_drive) { return ""; } Error DirAccessPack::change_dir(String p_dir) { String nd = p_dir.replace("\\", "/"); bool absolute = false; if (nd.begins_with("res://")) { nd = nd.replace_first("res://", ""); absolute = true; } nd = nd.simplify_path(); if (nd == "") nd = "."; if (nd.begins_with("/")) { nd = nd.replace_first("/", ""); absolute = true; } Vector<String> paths = nd.split("/"); PackedData::PackedDir *pd; if (absolute) pd = PackedData::get_singleton()->root; else pd = current; for (int i = 0; i < paths.size(); i++) { String p = paths[i]; if (p == ".") { continue; } else if (p == "..") { if (pd->parent) { pd = pd->parent; } } else if (pd->subdirs.has(p)) { pd = pd->subdirs[p]; } else { return ERR_INVALID_PARAMETER; } } current = pd; return OK; } String DirAccessPack::get_current_dir() { PackedData::PackedDir *pd = current; String p = current->name; while (pd->parent) { pd = pd->parent; p = pd->name.plus_file(p); } return "res://" + p; } bool DirAccessPack::file_exists(String p_file) { p_file = fix_path(p_file); return current->files.has(p_file); } bool DirAccessPack::dir_exists(String p_dir) { p_dir = fix_path(p_dir); return current->subdirs.has(p_dir); } Error DirAccessPack::make_dir(String p_dir) { return ERR_UNAVAILABLE; } Error DirAccessPack::rename(String p_from, String p_to) { return ERR_UNAVAILABLE; } Error DirAccessPack::remove(String p_name) { return ERR_UNAVAILABLE; } size_t DirAccessPack::get_space_left() { return 0; } String DirAccessPack::get_filesystem_type() const { return "PCK"; } DirAccessPack::DirAccessPack() { current = PackedData::get_singleton()->root; cdir = false; } DirAccessPack::~DirAccessPack() { } <|endoftext|>
<commit_before>/** * @file ada_delta.hpp * @author Marcus Edel * * Implmentation of the RmsProp optimizer. Adadelta is an optimizer that uses * the magnitude of recent gradients and steps to obtain an adaptive step rate. */ #ifndef __MLPACK_METHODS_ANN_OPTIMIZER_ADA_DELTA_HPP #define __MLPACK_METHODS_ANN_OPTIMIZER_ADA_DELTA_HPP #include <mlpack/core.hpp> namespace mlpack { namespace ann /** Artificial Neural Network. */ { /** * Adadelta is an optimizer that uses the magnitude of recent gradients and * steps to obtain an adaptive step rate. In its basic form, given a step rate * \f$ \gamma \f$ and a decay term \f$ \alpha \f$ we perform the following * updates: * * \f[ * g_t &=& (1 - \gamma)f'(\Delta_t)^2 + \gammag_{t - 1} \\ * \vec{\Delta} \Delta_t = \alpha \frac{\sqrt(s_{t-1} + * \epsilon)}{\sqrt{g_t + \epsilon}} f'(\Delta_t) \\ * \Delta_{t + 1} &=& \Delta_t - \vec{\Delta} \Delta_t \\ * s_t &=& (1 - \gamma) \vec{\Delta} \Delta_t^2 + \gammas_{t - 1} * \f] * * For more information, see the following. * * @code * @article{Zeiler2012, * author = {Matthew D. Zeiler}, * title = {{ADADELTA:} An Adaptive Learning Rate Method}, * journal = {CoRR}, * year = {2012} * } * @endcode */ template<typename DecomposableFunctionType, typename DataType> class AdaDelta { public: /** * Construct the AdaDelta optimizer with the given function and parameters. * * @param function Function to be optimized (minimized). * @param rho Constant similar to that used in AdaDelta and Momentum methods. * @param eps The eps coefficient to avoid division by zero. */ AdaDelta(DecomposableFunctionType& function, const double rho = 0.95, const double eps = 1e-6) : function(function), rho(rho), eps(eps) { // Nothing to do here. } /** * Optimize the given function using RmsProp. */ void Optimize() { if (meanSquaredGradient.n_elem == 0) { meanSquaredGradient = function.Weights(); meanSquaredGradient.zeros(); meanSquaredGradientDx = meanSquaredGradient; } Optimize(function.Weights(), gradient, meanSquaredGradient, meanSquaredGradientDx); } /* * Sum up all gradients and store the results in the gradients storage. */ void Update() { if (gradient.n_elem != 0) { DataType outputGradient; function.Gradient(outputGradient); gradient += outputGradient; } else { function.Gradient(gradient); } } /* * Reset the gradient storage. */ void Reset() { gradient.zeros(); } private: /** * Optimize the given function using AdaDelta. * * @param weights The weights that should be updated. * @param gradient The gradient used to update the weights. * @param meanSquaredGradient The current mean squared gradient Dx * @param meanSquaredGradientDx The current mean squared gradient. */ template<typename eT> void Optimize(arma::Cube<eT>& weights, arma::Cube<eT>& gradient, arma::Cube<eT>& meanSquaredGradient, arma::Cube<eT>& meanSquaredGradientDx) { for (size_t s = 0; s < weights.n_slices; s++) { Optimize(weights.slice(s), gradient.slice(s), meanSquaredGradient.slice(s), meanSquaredGradientDx.slice(s)); } } /** * Optimize the given function using AdaDelta. * * @param weights The weights that should be updated. * @param gradient The gradient used to update the weights. * @param meanSquaredGradient The current mean squared gradient Dx * @param meanSquaredGradientDx The current mean squared gradient. */ template<typename eT> void Optimize(arma::Mat<eT>& weights, arma::Mat<eT>& gradient, arma::Mat<eT>& meanSquaredGradient, arma::Mat<eT>& meanSquaredGradientDx) { // Accumulate gradient. meanSquaredGradient *= rho; meanSquaredGradient += (1 - rho) * (gradient % gradient); arma::Mat<eT> dx = arma::sqrt((meanSquaredGradientDx + eps) / (meanSquaredGradient + eps)) % gradient; // Accumulate updates. meanSquaredGradientDx *= rho; meanSquaredGradientDx += (1 - rho) * (dx % dx); // Apply update. weights -= dx; } //! The instantiated function. DecomposableFunctionType& function; //! The value used as learning rate. const double rho; //! The value used as eps. const double eps; //! The current gradient. DataType gradient; //! The current mean squared gradient. DataType meanSquaredGradient; //! The current mean squared gradient Dx DataType meanSquaredGradientDx; }; // class AdaDelta }; // namespace ann }; // namespace mlpack #endif <commit_msg>Add function to get the current gradient.<commit_after>/** * @file ada_delta.hpp * @author Marcus Edel * * Implmentation of the RmsProp optimizer. Adadelta is an optimizer that uses * the magnitude of recent gradients and steps to obtain an adaptive step rate. */ #ifndef __MLPACK_METHODS_ANN_OPTIMIZER_ADA_DELTA_HPP #define __MLPACK_METHODS_ANN_OPTIMIZER_ADA_DELTA_HPP #include <mlpack/core.hpp> namespace mlpack { namespace ann /** Artificial Neural Network. */ { /** * Adadelta is an optimizer that uses the magnitude of recent gradients and * steps to obtain an adaptive step rate. In its basic form, given a step rate * \f$ \gamma \f$ and a decay term \f$ \alpha \f$ we perform the following * updates: * * \f[ * g_t &=& (1 - \gamma)f'(\Delta_t)^2 + \gammag_{t - 1} \\ * \vec{\Delta} \Delta_t = \alpha \frac{\sqrt(s_{t-1} + * \epsilon)}{\sqrt{g_t + \epsilon}} f'(\Delta_t) \\ * \Delta_{t + 1} &=& \Delta_t - \vec{\Delta} \Delta_t \\ * s_t &=& (1 - \gamma) \vec{\Delta} \Delta_t^2 + \gammas_{t - 1} * \f] * * For more information, see the following. * * @code * @article{Zeiler2012, * author = {Matthew D. Zeiler}, * title = {{ADADELTA:} An Adaptive Learning Rate Method}, * journal = {CoRR}, * year = {2012} * } * @endcode */ template<typename DecomposableFunctionType, typename DataType> class AdaDelta { public: /** * Construct the AdaDelta optimizer with the given function and parameters. * * @param function Function to be optimized (minimized). * @param rho Constant similar to that used in AdaDelta and Momentum methods. * @param eps The eps coefficient to avoid division by zero. */ AdaDelta(DecomposableFunctionType& function, const double rho = 0.95, const double eps = 1e-6) : function(function), rho(rho), eps(eps), iteration(0) { // Nothing to do here. } /** * Optimize the given function using RmsProp. */ void Optimize() { if (meanSquaredGradient.n_elem == 0) { meanSquaredGradient = function.Weights(); meanSquaredGradient.zeros(); meanSquaredGradientDx = meanSquaredGradient; } if (iteration > 1) gradient /= iteration; Optimize(function.Weights(), gradient, meanSquaredGradient, meanSquaredGradientDx); } /* * Sum up all gradients and store the results in the gradients storage. */ void Update() { iteration++; if (gradient.n_elem != 0) { DataType outputGradient; function.Gradient(outputGradient); gradient += outputGradient; } else { function.Gradient(gradient); } } /* * Reset the gradient storage. */ void Reset() { iteration = 0; gradient.zeros(); } //! Get the gradient. DataType& Gradient() const { return gradient; } //! Modify the gradient. DataType& Gradient() { return gradient; } private: /** * Optimize the given function using AdaDelta. * * @param weights The weights that should be updated. * @param gradient The gradient used to update the weights. * @param meanSquaredGradient The current mean squared gradient Dx * @param meanSquaredGradientDx The current mean squared gradient. */ template<typename eT> void Optimize(arma::Cube<eT>& weights, arma::Cube<eT>& gradient, arma::Cube<eT>& meanSquaredGradient, arma::Cube<eT>& meanSquaredGradientDx) { for (size_t s = 0; s < weights.n_slices; s++) { Optimize(weights.slice(s), gradient.slice(s), meanSquaredGradient.slice(s), meanSquaredGradientDx.slice(s)); } } /** * Optimize the given function using AdaDelta. * * @param weights The weights that should be updated. * @param gradient The gradient used to update the weights. * @param meanSquaredGradient The current mean squared gradient Dx * @param meanSquaredGradientDx The current mean squared gradient. */ template<typename eT> void Optimize(arma::Mat<eT>& weights, arma::Mat<eT>& gradient, arma::Mat<eT>& meanSquaredGradient, arma::Mat<eT>& meanSquaredGradientDx) { // Accumulate gradient. meanSquaredGradient *= rho; meanSquaredGradient += (1 - rho) * (gradient % gradient); arma::Mat<eT> dx = arma::sqrt((meanSquaredGradientDx + eps) / (meanSquaredGradient + eps)) % gradient; // Accumulate updates. meanSquaredGradientDx *= rho; meanSquaredGradientDx += (1 - rho) * (dx % dx); // Apply update. weights -= dx; } //! The instantiated function. DecomposableFunctionType& function; //! The value used as learning rate. const double rho; //! The value used as eps. const double eps; //! The current gradient. DataType gradient; //! The current mean squared gradient. DataType meanSquaredGradient; //! The current mean squared gradient Dx DataType meanSquaredGradientDx; //! The locally stored number of iterations. size_t iteration; }; // class AdaDelta }; // namespace ann }; // namespace mlpack #endif <|endoftext|>
<commit_before>#include "Keyboard.h" #include "imgui/imgui.h" #include <algorithm> #include <iostream> namespace Preferences { Keyboard::Keyboard(KeyBindings &keybindings, Confparse &obvconfig) : keybindings(keybindings), obvconfig(obvconfig) { } void Keyboard::menuItem() { if (ImGui::MenuItem("Keyboard Preferences")) { shown = true; } } void Keyboard::render() { bool close_button_not_clicked = true; auto &io = ImGui::GetIO(); ImGui::SetNextWindowPos(ImVec2(io.DisplaySize.x * 0.5f, io.DisplaySize.y * 0.5f), 0, ImVec2(0.5f, 0.5f)); if (ImGui::BeginPopupModal("Keyboard Preferences", &close_button_not_clicked, ImGuiWindowFlags_AlwaysAutoResize)) { shown = false; // Find how many columns we need to show all the keybindings auto maxbindings = std::max_element(keybindings.keybindings.begin(), keybindings.keybindings.end(), [](const std::pair<std::string, std::vector<KeyBinding>> &a, const std::pair<std::string, std::vector<KeyBinding>> &b){ // C++14 has auto lambda argument deduction, would make it cleaner… return a.second.size() < b.second.size();}); // total number of columns: name + keybindings + add button auto colcount = 1 + (maxbindings != keybindings.keybindings.end() ? maxbindings->second.size() : 0) + 1; if (ImGui::BeginTable("KeyBindings", colcount, ImGuiTableFlags_SizingPolicyFixedX // size according to content | ImGuiTableFlags_RowBg // alternating background colors | ImGuiTableFlags_BordersH | ImGuiTableFlags_BordersV)) { for (auto &kbs : keybindings.keybindings) { ImGui::TableNextRow(); ImGui::TableSetColumnIndex(0); ImGui::Text("%s", kbs.first.c_str()); // binding name auto &bindings = kbs.second; // reference because we add/delete from it below // Show all bindings, potentially newly added button will be shown next frame since we need to compute number of column again first auto colindex = 1; for (auto it = bindings.begin(); it != bindings.end();) { auto keys = it->to_string(); ImGui::TableSetColumnIndex(colindex); if (ImGui::SmallButton(("X##" + kbs.first + std::to_string(colindex)).c_str())) { // Erase binding when clicking on X button it = bindings.erase(it); } else { // warning: iterator incremented here since it must not be incremented after reaffectation if binding is erased ++it; } ImGui::SameLine(); ImGui::Text("%s", keys.c_str()); colindex++; } // Add new binding after pressing add button, keep that after showing all bindings if (addingName == kbs.first) { // Check if a key is pressed for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) { if (io.KeysDown[i]) { auto scancode = static_cast<SDL_Scancode>(i); SDL_Keycode kc = SDL_GetKeyFromScancode(scancode); // Ignore modifier keys, cannot be a final key if (!keybindings.keyModifiers.isSDLKModifier(kc)) { addingScancode = scancode; addingBinding = KeyBinding(kc); } } } // Get the modifier keys pressed addingBinding.modifiers = keybindings.keyModifiers.pressed(); // Add binding once non-modifier key is released if (addingScancode != SDL_SCANCODE_UNKNOWN && ImGui::IsKeyReleased(addingScancode)) { bindings.push_back(addingBinding); addingScancode = SDL_SCANCODE_UNKNOWN; addingName = {}; addingBinding = {}; } } ImGui::TableSetColumnIndex(colindex); if (addingName == kbs.first) { // Adding a new key binding auto keys = addingBinding.to_string(); if (ImGui::SmallButton(("X##adding" + kbs.first).c_str())) { // Stop adding new keybinding addingScancode = SDL_SCANCODE_UNKNOWN; addingName = std::string{}; addingBinding = KeyBinding{}; } ImGui::SameLine(); if (!keys.empty()) { // Show current pressed keys ImGui::Text("%s", keys.c_str()); } else { // Or a message indicating to press a key ImGui::Text("%s", "<Press a key>"); } } else { // Show add button if (ImGui::SmallButton(("Add##" + kbs.first).c_str())) { addingName = kbs.first; } } } ImGui::EndTable(); } ImGui::Text("Note: %c and %c cannot be used as key bindings.", keybindings.bindingSeparator, keybindings.modifierSeparator); if (ImGui::Button("Save")) { keybindings.writeToConfig(obvconfig); ImGui::CloseCurrentPopup(); } ImGui::SameLine(); if (ImGui::Button("Cancel") || keybindings.isPressed("CloseDialog") || !close_button_not_clicked) { keybindings.readFromConfig(obvconfig); ImGui::CloseCurrentPopup(); } ImGui::SameLine(); if (ImGui::Button("Default")) { keybindings.reset(); } ImGui::EndPopup(); } if (!close_button_not_clicked) { // modal title bar close button clicked printf("Close\n"); keybindings.readFromConfig(obvconfig); } if (shown) { ImGui::OpenPopup("Keyboard Preferences"); } } } // namespace Preferences <commit_msg>Use auto lambda argument in GUI/Preferences/Keyboard.cpp since we have C++17<commit_after>#include "Keyboard.h" #include "imgui/imgui.h" #include <algorithm> #include <iostream> namespace Preferences { Keyboard::Keyboard(KeyBindings &keybindings, Confparse &obvconfig) : keybindings(keybindings), obvconfig(obvconfig) { } void Keyboard::menuItem() { if (ImGui::MenuItem("Keyboard Preferences")) { shown = true; } } void Keyboard::render() { bool close_button_not_clicked = true; auto &io = ImGui::GetIO(); ImGui::SetNextWindowPos(ImVec2(io.DisplaySize.x * 0.5f, io.DisplaySize.y * 0.5f), 0, ImVec2(0.5f, 0.5f)); if (ImGui::BeginPopupModal("Keyboard Preferences", &close_button_not_clicked, ImGuiWindowFlags_AlwaysAutoResize)) { shown = false; // Find how many columns we need to show all the keybindings auto maxbindings = std::max_element(keybindings.keybindings.begin(), keybindings.keybindings.end(), [](auto a, auto b){ return a.second.size() < b.second.size(); }); // total number of columns: name + keybindings + add button auto colcount = 1 + (maxbindings != keybindings.keybindings.end() ? maxbindings->second.size() : 0) + 1; if (ImGui::BeginTable("KeyBindings", colcount, ImGuiTableFlags_SizingPolicyFixedX // size according to content | ImGuiTableFlags_RowBg // alternating background colors | ImGuiTableFlags_BordersH | ImGuiTableFlags_BordersV)) { for (auto &kbs : keybindings.keybindings) { ImGui::TableNextRow(); ImGui::TableSetColumnIndex(0); ImGui::Text("%s", kbs.first.c_str()); // binding name auto &bindings = kbs.second; // reference because we add/delete from it below // Show all bindings, potentially newly added button will be shown next frame since we need to compute number of column again first auto colindex = 1; for (auto it = bindings.begin(); it != bindings.end();) { auto keys = it->to_string(); ImGui::TableSetColumnIndex(colindex); if (ImGui::SmallButton(("X##" + kbs.first + std::to_string(colindex)).c_str())) { // Erase binding when clicking on X button it = bindings.erase(it); } else { // warning: iterator incremented here since it must not be incremented after reaffectation if binding is erased ++it; } ImGui::SameLine(); ImGui::Text("%s", keys.c_str()); colindex++; } // Add new binding after pressing add button, keep that after showing all bindings if (addingName == kbs.first) { // Check if a key is pressed for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) { if (io.KeysDown[i]) { auto scancode = static_cast<SDL_Scancode>(i); SDL_Keycode kc = SDL_GetKeyFromScancode(scancode); // Ignore modifier keys, cannot be a final key if (!keybindings.keyModifiers.isSDLKModifier(kc)) { addingScancode = scancode; addingBinding = KeyBinding(kc); } } } // Get the modifier keys pressed addingBinding.modifiers = keybindings.keyModifiers.pressed(); // Add binding once non-modifier key is released if (addingScancode != SDL_SCANCODE_UNKNOWN && ImGui::IsKeyReleased(addingScancode)) { bindings.push_back(addingBinding); addingScancode = SDL_SCANCODE_UNKNOWN; addingName = {}; addingBinding = {}; } } ImGui::TableSetColumnIndex(colindex); if (addingName == kbs.first) { // Adding a new key binding auto keys = addingBinding.to_string(); if (ImGui::SmallButton(("X##adding" + kbs.first).c_str())) { // Stop adding new keybinding addingScancode = SDL_SCANCODE_UNKNOWN; addingName = std::string{}; addingBinding = KeyBinding{}; } ImGui::SameLine(); if (!keys.empty()) { // Show current pressed keys ImGui::Text("%s", keys.c_str()); } else { // Or a message indicating to press a key ImGui::Text("%s", "<Press a key>"); } } else { // Show add button if (ImGui::SmallButton(("Add##" + kbs.first).c_str())) { addingName = kbs.first; } } } ImGui::EndTable(); } ImGui::Text("Note: %c and %c cannot be used as key bindings.", keybindings.bindingSeparator, keybindings.modifierSeparator); if (ImGui::Button("Save")) { keybindings.writeToConfig(obvconfig); ImGui::CloseCurrentPopup(); } ImGui::SameLine(); if (ImGui::Button("Cancel") || keybindings.isPressed("CloseDialog") || !close_button_not_clicked) { keybindings.readFromConfig(obvconfig); ImGui::CloseCurrentPopup(); } ImGui::SameLine(); if (ImGui::Button("Default")) { keybindings.reset(); } ImGui::EndPopup(); } if (!close_button_not_clicked) { // modal title bar close button clicked printf("Close\n"); keybindings.readFromConfig(obvconfig); } if (shown) { ImGui::OpenPopup("Keyboard Preferences"); } } } // namespace Preferences <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved */ // TEST Foundation::Containers::DataHyperRectangle // STATUS PRELIMINARY #include "Stroika/Foundation/StroikaPreComp.h" #include <iostream> #include <sstream> #include "Stroika/Foundation/Containers/Concrete/DataHyperRectangle_DenseVector.h" #include "Stroika/Foundation/Containers/Concrete/DataHyperRectangle_Sparse_stdmap.h" #include "Stroika/Foundation/Containers/DataHyperRectangle.h" #include "Stroika/Foundation/Debug/Assertions.h" #include "Stroika/Foundation/Debug/Trace.h" #include "../TestHarness/SimpleClass.h" #include "../TestHarness/TestHarness.h" using namespace Stroika; using namespace Stroika::Foundation; using namespace Stroika::Foundation::Containers; namespace { void DoRegressionTests_ () { { DataHyperRectangle2<int> x = Concrete::DataHyperRectangle_DenseVector<int, size_t, size_t>{3, 4}; Verify (x.GetAt (2, 2) == 0); } { DataHyperRectangle2<int> x = Concrete::DataHyperRectangle_Sparse_stdmap<int, size_t, size_t>{}; Verify (x.GetAt (2, 2) == 0); } } } int main (int argc, const char* argv[]) { Stroika::TestHarness::Setup (); return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_); } <commit_msg>tiny progress on regtest for datahypercube<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved */ // TEST Foundation::Containers::DataHyperRectangle // STATUS PRELIMINARY #include "Stroika/Foundation/StroikaPreComp.h" #include <iostream> #include <sstream> #include "Stroika/Foundation/Characters/ToString.h" #include "Stroika/Foundation/Containers/Concrete/DataHyperRectangle_DenseVector.h" #include "Stroika/Foundation/Containers/Concrete/DataHyperRectangle_Sparse_stdmap.h" #include "Stroika/Foundation/Containers/DataHyperRectangle.h" #include "Stroika/Foundation/Debug/Assertions.h" #include "Stroika/Foundation/Debug/Trace.h" #include "../TestHarness/SimpleClass.h" #include "../TestHarness/TestHarness.h" using namespace Stroika; using namespace Stroika::Foundation; using namespace Stroika::Foundation::Containers; namespace { void DoRegressionTests_ () { { DataHyperRectangle2<int> x = Concrete::DataHyperRectangle_DenseVector<int, size_t, size_t>{3, 4}; Verify (x.GetAt (2, 2) == 0); for (auto t : x) { int breakhere = 1; int b2 = 3; } } { DataHyperRectangle2<int> x = Concrete::DataHyperRectangle_Sparse_stdmap<int, size_t, size_t>{}; Verify (x.GetAt (2, 2) == 0); for (auto t : x) { int breakhere = 1; int b2 = 3; } x.SetAt (2, 2, 4); for (auto t : x) { int breakhere = 1; int b2 = 3; } } } } int main (int argc, const char* argv[]) { Stroika::TestHarness::Setup (); return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_); } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved */ // TEST Foundation::Execution::ProcessRunner #include "Stroika/Foundation/StroikaPreComp.h" #include "Stroika/Foundation/Debug/Trace.h" #include "Stroika/Foundation/Execution/ProcessRunner.h" #if qPlatform_POSIX #include "Stroika/Foundation/Execution/SignalHandlers.h" #endif #include "Stroika/Foundation/Execution/Sleep.h" #include "Stroika/Foundation/Streams/MemoryStream.h" #include "Stroika/Foundation/Streams/SharedMemoryStream.h" #include "../TestHarness/TestHarness.h" using std::byte; using namespace Stroika::Foundation; using namespace Stroika::Foundation::Execution; using Characters::String; namespace { void RegressionTest1_ () { Debug::TraceContextBumper ctx{L"RegressionTest1_"}; Streams::MemoryStream<byte>::Ptr myStdOut = Streams::MemoryStream<byte>::New (); // quickie about to test.. ProcessRunner pr (L"echo hi mom", nullptr, myStdOut); pr.Run (); } void RegressionTest2_ () { Debug::TraceContextBumper ctx{L"RegressionTest2_"}; Streams::MemoryStream<byte>::Ptr myStdOut = Streams::MemoryStream<byte>::New (); // quickie about to test.. ProcessRunner pr (L"echo hi mom"); String out = pr.Run (L""); VerifyTestResult (out.Trim () == L"hi mom"); } void RegressionTest3_Pipe_ () { Debug::TraceContextBumper ctx{L"RegressionTest3_Pipe_"}; Streams::MemoryStream<byte>::Ptr myStdOut = Streams::MemoryStream<byte>::New (); ProcessRunner pr1 (L"echo hi mom"); Streams::MemoryStream<byte>::Ptr pipe = Streams::MemoryStream<byte>::New (); ProcessRunner pr2 (L"cat"); pr1.SetStdOut (pipe); pr2.SetStdIn (pipe); Streams::MemoryStream<byte>::Ptr pr2Out = Streams::MemoryStream<byte>::New (); pr2.SetStdOut (pr2Out); pr1.Run (); pr2.Run (); String out = String::FromUTF8 (pr2Out.As<string> ()); VerifyTestResult (out.Trim () == L"hi mom"); } void RegressionTest4_DocSample_ () { Debug::TraceContextBumper ctx{L"RegressionTest4_DocSample_"}; // cat doesn't exist on windows (without cygwin or some such) - but the regression test code depends on that anyhow // so this should be OK for now... -- LGP 2017-06-31 Memory::BLOB kData_{Memory::BLOB::Raw ("this is a test")}; Streams::MemoryStream<byte>::Ptr processStdIn = Streams::MemoryStream<byte>::New (kData_); Streams::MemoryStream<byte>::Ptr processStdOut = Streams::MemoryStream<byte>::New (); ProcessRunner pr (L"cat", processStdIn, processStdOut); pr.Run (); VerifyTestResult (processStdOut.ReadAll () == kData_); } } namespace { namespace LargeDataSentThroughPipe_Test5_ { namespace Private_ { const Memory::BLOB k1K_ = Memory::BLOB::Raw ("0123456789abcdef").Repeat (1024 / 16); const Memory::BLOB k1MB_ = k1K_.Repeat (1024); const Memory::BLOB k16MB_ = k1MB_.Repeat (16); void SingleProcessLargeDataSend_ () { /* * "Valgrind's memory management: out of memory:" * This only happens with DEBUG builds and valgrind/helgrind. So run with less memory used, and it works better. */ Memory::BLOB testBLOB = (Debug::IsRunningUnderValgrind () && qDebug) ? k1K_ : k16MB_; Streams::MemoryStream<byte>::Ptr myStdIn = Streams::MemoryStream<byte>::New (testBLOB); Streams::MemoryStream<byte>::Ptr myStdOut = Streams::MemoryStream<byte>::New (); ProcessRunner pr (L"cat", myStdIn, myStdOut); pr.Run (); VerifyTestResult (myStdOut.ReadAll () == testBLOB); } } void DoTests () { Debug::TraceContextBumper ctx{L"LargeDataSentThroughPipe_Test5_::DoTests"}; Private_::SingleProcessLargeDataSend_ (); } } } namespace { namespace LargeDataSentThroughPipeBackground_Test6_ { namespace Private_ { const Memory::BLOB k1K_ = Memory::BLOB::Raw ("0123456789abcdef").Repeat (1024 / 16); const Memory::BLOB k1MB_ = k1K_.Repeat (1024); const Memory::BLOB k16MB_ = k1MB_.Repeat (16); void SingleProcessLargeDataSend_ () { Assert (k1MB_.size () == 1024 * 1024); Streams::SharedMemoryStream<byte>::Ptr myStdIn = Streams::SharedMemoryStream<byte>::New (); // note must use SharedMemoryStream cuz we want to distinguish EOF from no data written yet Streams::SharedMemoryStream<byte>::Ptr myStdOut = Streams::SharedMemoryStream<byte>::New (); ProcessRunner pr (L"cat", myStdIn, myStdOut); ProcessRunner::BackgroundProcess bg = pr.RunInBackground (); Execution::Sleep (1); VerifyTestResult (not myStdOut.ReadNonBlocking ().has_value ()); // sb no data available, but NOT EOF /* * "Valgrind's memory management: out of memory:" * This only happens with DEBUG builds and valgrind/helgrind. So run with less memory used, and it works better. */ Memory::BLOB testBLOB = (Debug::IsRunningUnderValgrind () && qDebug) ? k1K_ : k16MB_; myStdIn.Write (testBLOB); myStdIn.CloseWrite (); // so cat process can finish bg.WaitForDone (); myStdOut.CloseWrite (); // one process done, no more writes to this stream VerifyTestResult (myStdOut.ReadAll () == testBLOB); } } void DoTests () { Debug::TraceContextBumper ctx{L"LargeDataSentThroughPipeBackground_Test6_::DoTests"}; Private_::SingleProcessLargeDataSend_ (); } } } void RegressionTes7_FaledRun_ () { Debug::TraceContextBumper ctx{L"RegressionTes7_FaledRun_"}; try { ProcessRunner pr (L"mount /fasdkfjasdfjasdkfjasdklfjasldkfjasdfkj /dadsf/a/sdf/asdf//"); pr.Run (); VerifyTestResult (false); } catch (...) { DbgTrace (L"got failure msg: %s", Characters::ToString (current_exception ()).c_str ()); } } namespace { void DoRegressionTests_ () { Debug::TraceContextBumper ctx{L"DoRegressionTests_"}; #if qPlatform_POSIX // Many performance instruments use pipes // @todo - REVIEW IF REALLY NEEDED AND WHY? SO LONG AS NO FAIL SHOULDNT BE? // --LGP 2014-02-05 Execution::SignalHandlerRegistry::Get ().SetSignalHandlers (SIGPIPE, Execution::SignalHandlerRegistry::kIGNORED); #endif RegressionTest1_ (); RegressionTest2_ (); RegressionTest3_Pipe_ (); RegressionTest4_DocSample_ (); LargeDataSentThroughPipe_Test5_::DoTests (); LargeDataSentThroughPipeBackground_Test6_::DoTests (); RegressionTes7_FaledRun_ (); } } int main ([[maybe_unused]] int argc, [[maybe_unused]] const char* argv[]) { Stroika::TestHarness::Setup (); return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_); } <commit_msg>note about new bug https://stroika.atlassian.net/browse/STK-713<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved */ // TEST Foundation::Execution::ProcessRunner #include "Stroika/Foundation/StroikaPreComp.h" #include "Stroika/Foundation/Debug/Trace.h" #include "Stroika/Foundation/Execution/ProcessRunner.h" #if qPlatform_POSIX #include "Stroika/Foundation/Execution/SignalHandlers.h" #endif #include "Stroika/Foundation/Execution/Sleep.h" #include "Stroika/Foundation/Streams/MemoryStream.h" #include "Stroika/Foundation/Streams/SharedMemoryStream.h" #include "../TestHarness/TestHarness.h" using std::byte; using namespace Stroika::Foundation; using namespace Stroika::Foundation::Execution; using Characters::String; namespace { void RegressionTest1_ () { Debug::TraceContextBumper ctx{L"RegressionTest1_"}; Streams::MemoryStream<byte>::Ptr myStdOut = Streams::MemoryStream<byte>::New (); // quickie about to test.. ProcessRunner pr (L"echo hi mom", nullptr, myStdOut); pr.Run (); } void RegressionTest2_ () { Debug::TraceContextBumper ctx{L"RegressionTest2_"}; Streams::MemoryStream<byte>::Ptr myStdOut = Streams::MemoryStream<byte>::New (); // quickie about to test.. ProcessRunner pr (L"echo hi mom"); String out = pr.Run (L""); VerifyTestResult (out.Trim () == L"hi mom"); } void RegressionTest3_Pipe_ () { Debug::TraceContextBumper ctx{L"RegressionTest3_Pipe_"}; Streams::MemoryStream<byte>::Ptr myStdOut = Streams::MemoryStream<byte>::New (); ProcessRunner pr1 (L"echo hi mom"); Streams::MemoryStream<byte>::Ptr pipe = Streams::MemoryStream<byte>::New (); ProcessRunner pr2 (L"cat"); pr1.SetStdOut (pipe); pr2.SetStdIn (pipe); Streams::MemoryStream<byte>::Ptr pr2Out = Streams::MemoryStream<byte>::New (); pr2.SetStdOut (pr2Out); pr1.Run (); pr2.Run (); String out = String::FromUTF8 (pr2Out.As<string> ()); VerifyTestResult (out.Trim () == L"hi mom"); } void RegressionTest4_DocSample_ () { Debug::TraceContextBumper ctx{L"RegressionTest4_DocSample_"}; // cat doesn't exist on windows (without cygwin or some such) - but the regression test code depends on that anyhow // so this should be OK for now... -- LGP 2017-06-31 Memory::BLOB kData_{Memory::BLOB::Raw ("this is a test")}; Streams::MemoryStream<byte>::Ptr processStdIn = Streams::MemoryStream<byte>::New (kData_); Streams::MemoryStream<byte>::Ptr processStdOut = Streams::MemoryStream<byte>::New (); ProcessRunner pr (L"cat", processStdIn, processStdOut); pr.Run (); VerifyTestResult (processStdOut.ReadAll () == kData_); } } namespace { namespace LargeDataSentThroughPipe_Test5_ { namespace Private_ { const Memory::BLOB k1K_ = Memory::BLOB::Raw ("0123456789abcdef").Repeat (1024 / 16); const Memory::BLOB k1MB_ = k1K_.Repeat (1024); const Memory::BLOB k16MB_ = k1MB_.Repeat (16); void SingleProcessLargeDataSend_ () { /* * "Valgrind's memory management: out of memory:" * This only happens with DEBUG builds and valgrind/helgrind. So run with less memory used, and it works better. * * @see https://stroika.atlassian.net/browse/STK-713 if you see hang here */ Memory::BLOB testBLOB = (Debug::IsRunningUnderValgrind () && qDebug) ? k1K_ : k16MB_; Streams::MemoryStream<byte>::Ptr myStdIn = Streams::MemoryStream<byte>::New (testBLOB); Streams::MemoryStream<byte>::Ptr myStdOut = Streams::MemoryStream<byte>::New (); ProcessRunner pr (L"cat", myStdIn, myStdOut); pr.Run (); VerifyTestResult (myStdOut.ReadAll () == testBLOB); } } void DoTests () { Debug::TraceContextBumper ctx{L"LargeDataSentThroughPipe_Test5_::DoTests"}; Private_::SingleProcessLargeDataSend_ (); } } } namespace { namespace LargeDataSentThroughPipeBackground_Test6_ { namespace Private_ { const Memory::BLOB k1K_ = Memory::BLOB::Raw ("0123456789abcdef").Repeat (1024 / 16); const Memory::BLOB k1MB_ = k1K_.Repeat (1024); const Memory::BLOB k16MB_ = k1MB_.Repeat (16); void SingleProcessLargeDataSend_ () { Assert (k1MB_.size () == 1024 * 1024); Streams::SharedMemoryStream<byte>::Ptr myStdIn = Streams::SharedMemoryStream<byte>::New (); // note must use SharedMemoryStream cuz we want to distinguish EOF from no data written yet Streams::SharedMemoryStream<byte>::Ptr myStdOut = Streams::SharedMemoryStream<byte>::New (); ProcessRunner pr (L"cat", myStdIn, myStdOut); ProcessRunner::BackgroundProcess bg = pr.RunInBackground (); Execution::Sleep (1); VerifyTestResult (not myStdOut.ReadNonBlocking ().has_value ()); // sb no data available, but NOT EOF /* * "Valgrind's memory management: out of memory:" * This only happens with DEBUG builds and valgrind/helgrind. So run with less memory used, and it works better. */ Memory::BLOB testBLOB = (Debug::IsRunningUnderValgrind () && qDebug) ? k1K_ : k16MB_; myStdIn.Write (testBLOB); myStdIn.CloseWrite (); // so cat process can finish bg.WaitForDone (); myStdOut.CloseWrite (); // one process done, no more writes to this stream VerifyTestResult (myStdOut.ReadAll () == testBLOB); } } void DoTests () { Debug::TraceContextBumper ctx{L"LargeDataSentThroughPipeBackground_Test6_::DoTests"}; Private_::SingleProcessLargeDataSend_ (); } } } void RegressionTes7_FaledRun_ () { Debug::TraceContextBumper ctx{L"RegressionTes7_FaledRun_"}; try { ProcessRunner pr (L"mount /fasdkfjasdfjasdkfjasdklfjasldkfjasdfkj /dadsf/a/sdf/asdf//"); pr.Run (); VerifyTestResult (false); } catch (...) { DbgTrace (L"got failure msg: %s", Characters::ToString (current_exception ()).c_str ()); } } namespace { void DoRegressionTests_ () { Debug::TraceContextBumper ctx{L"DoRegressionTests_"}; #if qPlatform_POSIX // Many performance instruments use pipes // @todo - REVIEW IF REALLY NEEDED AND WHY? SO LONG AS NO FAIL SHOULDNT BE? // --LGP 2014-02-05 Execution::SignalHandlerRegistry::Get ().SetSignalHandlers (SIGPIPE, Execution::SignalHandlerRegistry::kIGNORED); #endif RegressionTest1_ (); RegressionTest2_ (); RegressionTest3_Pipe_ (); RegressionTest4_DocSample_ (); LargeDataSentThroughPipe_Test5_::DoTests (); LargeDataSentThroughPipeBackground_Test6_::DoTests (); RegressionTes7_FaledRun_ (); } } int main ([[maybe_unused]] int argc, [[maybe_unused]] const char* argv[]) { Stroika::TestHarness::Setup (); return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_); } <|endoftext|>
<commit_before>#include "led.h" #include "flasher.h" #include "const.h" #include "logger.h" #include <Arduino.h> //Array keeping track of states uint8_t states[NUMBER_OF_BITS]; unsigned char led_flashingCounter = 0; void led_setup() { pinMode(P_LED_VCC, OUTPUT); pinMode(P_LED_DATA, OUTPUT); pinMode(P_LED_CLOCK, OUTPUT); pinMode(P_LED_LATCH, OUTPUT); } void led_shiftOut() { //Latch Low. VCC high digitalWrite(P_LED_VCC, HIGH); digitalWrite(P_LED_LATCH, LOW); //Shift out for (uint8_t i = NUMBER_OF_BITS; i <= NUMBER_OF_BITS; i--) { switch (states[i]) { case LED_STATE_OFF: digitalWrite(P_LED_DATA, LOW); break; case LED_STATE_ON: digitalWrite(P_LED_DATA, HIGH); break; case LED_STATE_FLASHING: flashed = true; digitalWrite(P_LED_DATA, flashingCurrentState); break; } //Clock digitalWrite(P_LED_CLOCK, HIGH); digitalWrite(P_LED_CLOCK, LOW); } //If data is left on high drop to low, so that the final output voltage is not altered digitalWrite(P_LED_DATA, LOW); //Latch high. VCC adjust to two volts digitalWrite(P_LED_LATCH, HIGH); analogWrite(P_LED_VCC, LED_VCC_PWM); } void led_setState(uint8_t led, uint8_t state) { //If we have a flashing led turn on. The thread will automatically turn off if no leds are flashing. if (state == LED_STATE_FLASHING) { flasher_thread.enabled = true; } states[led] = state; } <commit_msg>Add log statement<commit_after>#include "led.h" #include "flasher.h" #include "const.h" #include "logger.h" #include <Arduino.h> //Array keeping track of states uint8_t states[NUMBER_OF_BITS]; unsigned char led_flashingCounter = 0; void led_setup() { pinMode(P_LED_VCC, OUTPUT); pinMode(P_LED_DATA, OUTPUT); pinMode(P_LED_CLOCK, OUTPUT); pinMode(P_LED_LATCH, OUTPUT); } void led_shiftOut() { //Latch Low. VCC high digitalWrite(P_LED_VCC, HIGH); digitalWrite(P_LED_LATCH, LOW); //Shift out for (uint8_t i = NUMBER_OF_BITS; i <= NUMBER_OF_BITS; i--) { switch (states[i]) { case LED_STATE_OFF: digitalWrite(P_LED_DATA, LOW); break; case LED_STATE_ON: digitalWrite(P_LED_DATA, HIGH); break; case LED_STATE_FLASHING: flashed = true; digitalWrite(P_LED_DATA, flashingCurrentState); break; } //Clock digitalWrite(P_LED_CLOCK, HIGH); digitalWrite(P_LED_CLOCK, LOW); } //If data is left on high drop to low, so that the final output voltage is not altered digitalWrite(P_LED_DATA, LOW); //Latch high. VCC adjust to two volts digitalWrite(P_LED_LATCH, HIGH); analogWrite(P_LED_VCC, LED_VCC_PWM); } void led_setState(uint8_t led, uint8_t state) { logger(LOGGER_TYPE_INFO, "led", "Set led number " + String(led) + " to state " + String(state)); //If we have a flashing led turn on. The thread will automatically turn off if no leds are flashing. if (state == LED_STATE_FLASHING) { flasher_thread.enabled = true; } states[led] = state; } <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Wim Meeussen */ #include "urdf_import.hpp" #include "urdf_compatibility.h" #include <fstream> #include <kdl/tree.hpp> #include <kdl/jntarray.hpp> #include <tinyxml.h> using namespace std; using namespace KDL; namespace kdl_format_io{ void printTree(urdf::ConstLinkPtr link,int level = 0) { level+=2; int count = 0; for (urdf::LinkVector::const_iterator child = link->child_links.begin(); child != link->child_links.end(); child++) { if (*child) { for(int j=0;j<level;j++) std::cout << " "; //indent std::cout << "child(" << (count++)+1 << "): " << (*child)->name << std::endl; // first grandchild printTree(*child,level); } else { for(int j=0;j<level;j++) std::cout << " "; //indent std::cout << "root link: " << link->name << " has a null child!" << *child << std::endl; } } } // construct vector Vector toKdl(urdf::Vector3 v) { return Vector(v.x, v.y, v.z); } // construct rotation Rotation toKdl(urdf::Rotation r) { return Rotation::Quaternion(r.x, r.y, r.z, r.w); } // construct pose Frame toKdl(urdf::Pose p) { return Frame(toKdl(p.rotation), toKdl(p.position)); } // construct joint Joint toKdl(urdf::JointPtr jnt) { Frame F_parent_jnt = toKdl(jnt->parent_to_joint_origin_transform); switch (jnt->type){ case urdf::Joint::FIXED:{ return Joint(jnt->name, Joint::None); } case urdf::Joint::REVOLUTE:{ Vector axis = toKdl(jnt->axis); return Joint(jnt->name, F_parent_jnt.p, F_parent_jnt.M * axis, Joint::RotAxis); } case urdf::Joint::CONTINUOUS:{ Vector axis = toKdl(jnt->axis); return Joint(jnt->name, F_parent_jnt.p, F_parent_jnt.M * axis, Joint::RotAxis); } case urdf::Joint::PRISMATIC:{ Vector axis = toKdl(jnt->axis); return Joint(jnt->name, F_parent_jnt.p, F_parent_jnt.M * axis, Joint::TransAxis); } default:{ std::cerr << "Converting unknown joint type of joint " << jnt->name << " into a fixed joint" << std::endl; return Joint(jnt->name, Joint::None); } } return Joint(); } // construct inertia RigidBodyInertia toKdl(urdf::InertialPtr i) { Frame origin = toKdl(i->origin); // the mass is frame indipendent double kdl_mass = i->mass; // kdl and urdf both specify the com position in the reference frame of the link Vector kdl_com = origin.p; // kdl specifies the inertia matrix in the reference frame of the link, // while the urdf specifies the inertia matrix in the inertia reference frame RotationalInertia urdf_inertia = RotationalInertia(i->ixx, i->iyy, i->izz, i->ixy, i->ixz, i->iyz); // Rotation operators are not defined for rotational inertia, // so we use the RigidBodyInertia operators (with com = 0) as a workaround RigidBodyInertia kdl_inertia_wrt_com_workaround = origin.M *RigidBodyInertia(0, Vector::Zero(), urdf_inertia); // Note that the RigidBodyInertia constructor takes the 3d inertia wrt the com // while the getRotationalInertia method returns the 3d inertia wrt the frame origin // (but having com = Vector::Zero() in kdl_inertia_wrt_com_workaround they match) RotationalInertia kdl_inertia_wrt_com = kdl_inertia_wrt_com_workaround.getRotationalInertia(); return RigidBodyInertia(kdl_mass,kdl_com,kdl_inertia_wrt_com); } // recursive function to walk through tree bool addChildrenToTree(urdf::LinkPtr root, Tree& tree) { urdf::LinkVector children = root->child_links; //std::cerr << "[INFO] Link " << root->name << " had " << children.size() << " children" << std::endl; // constructs the optional inertia RigidBodyInertia inert(0); if (root->inertial) inert = toKdl(root->inertial); // constructs the kdl joint Joint jnt = toKdl(root->parent_joint); // construct the kdl segment Segment sgm(root->name, jnt, toKdl(root->parent_joint->parent_to_joint_origin_transform), inert); // add segment to tree tree.addSegment(sgm, root->parent_joint->parent_link_name); // recurslively add all children for (size_t i=0; i<children.size(); i++){ if (!addChildrenToTree(children[i], tree)) return false; } return true; } bool treeFromUrdfFile(const string& file, Tree& tree,const bool consider_root_link_inertia) { ifstream ifs(file.c_str()); std::string xml_string( (std::istreambuf_iterator<char>(ifs) ), (std::istreambuf_iterator<char>() ) ); return treeFromUrdfString(xml_string,tree,consider_root_link_inertia); } /* bool treeFromParam(const string& param, Tree& tree) { urdf::ModelInterface robot_model; if (!robot_model.initParam(param)){ logError("Could not generate robot model"); return false; } return treeFromUrdfModel(robot_model, tree); } */ int print_tree(urdf::ModelInterfacePtr & robot) { std::cout << "robot name is: " << robot->getName() << std::endl; // get info from parser std::cout << "---------- Successfully Parsed XML ---------------" << std::endl; // get root link urdf::ConstLinkPtr root_link=robot->getRoot(); if (!root_link) return -1; std::cout << "root Link: " << root_link->name << " has " << root_link->child_links.size() << " child(ren)" << std::endl; // print entire tree printTree(root_link); return 0; } bool treeFromUrdfString(const string& xml, Tree& tree, const bool consider_root_link_inertia) { urdf::ModelInterfacePtr urdf_model; urdf_model = urdf::parseURDF(xml); if( !urdf_model ) { std::cerr << "[ERR] Could not parse string to urdf::ModelInterface" << std::endl; return false; } return treeFromUrdfModel(*urdf_model,tree,consider_root_link_inertia); } /* bool treeFromUrdfXml(TiXmlDocument *xml_doc, Tree& tree) { urdf::ModelInterfacePtr robot_model; robot_model = urdf::parseURDF( if (!robot_model.parse(xml_doc)){ logError("Could not generate robot model"); return false; } return treeFromUrdfModel(robot_model, tree); }*/ bool treeFromUrdfModel(const urdf::ModelInterface& robot_model, Tree& tree, const bool consider_root_link_inertia) { if (consider_root_link_inertia) { //For giving a name to the root of KDL using the robot name, //as it is not used elsewhere in the KDL tree std::string fake_root_name = "__kdl_import__" + robot_model.getName()+"__fake_root__"; std::string fake_root_fixed_joint_name = "__kdl_import__" + robot_model.getName()+"__fake_root_fixed_joint__"; tree = Tree(fake_root_name); const urdf::ConstLinkPtr root = robot_model.getRoot(); // constructs the optional inertia RigidBodyInertia inert(0); if (root->inertial) inert = toKdl(root->inertial); // constructs the kdl joint Joint jnt = Joint(fake_root_fixed_joint_name, Joint::None); // construct the kdl segment Segment sgm(root->name, jnt, Frame::Identity(), inert); // add segment to tree tree.addSegment(sgm, fake_root_name); } else { tree = Tree(robot_model.getRoot()->name); // warn if root link has inertia. KDL does not support this if (robot_model.getRoot()->inertial) std::cerr << "The root link " << robot_model.getRoot()->name << " has an inertia specified in the URDF, but KDL does not support a root link with an inertia. As a workaround, you can add an extra dummy link to your URDF." << std::endl; } // add all children for (size_t i=0; i<robot_model.getRoot()->child_links.size(); i++) if (!addChildrenToTree(robot_model.getRoot()->child_links[i], tree)) return false; return true; } bool jointPosLimitsFromUrdfFile(const std::string& file, std::vector<std::string> & joint_names, KDL::JntArray & min, KDL::JntArray & max) { ifstream ifs(file.c_str()); std::string xml_string( (std::istreambuf_iterator<char>(ifs) ), (std::istreambuf_iterator<char>() ) ); return jointPosLimitsFromUrdfString(xml_string,joint_names,min,max); } bool jointPosLimitsFromUrdfString(const std::string& urdf_xml, std::vector<std::string> & joint_names, KDL::JntArray & min, KDL::JntArray & max) { urdf::ModelInterfacePtr urdf_model; urdf_model = urdf::parseURDF(urdf_xml); if( !urdf_model ) { std::cerr << "[ERR] Could not parse string to urdf::ModelInterface" << std::endl; return false; } return jointPosLimitsFromUrdfModel(*urdf_model,joint_names,min,max); } bool jointPosLimitsFromUrdfModel(const urdf::ModelInterface& robot_model, std::vector<std::string> & joint_names, KDL::JntArray & min, KDL::JntArray & max) { int nrOfJointsWithLimits=0; for (urdf::JointPtrMap::const_iterator it=robot_model.joints_.begin(); it!=robot_model.joints_.end(); ++it) { if( it->second->type == urdf::Joint::REVOLUTE || it->second->type == urdf::Joint::PRISMATIC ) { nrOfJointsWithLimits++; } } joint_names.resize(nrOfJointsWithLimits); min.resize(nrOfJointsWithLimits); max.resize(nrOfJointsWithLimits); int index =0; for (urdf::JointPtrMap::const_iterator it=robot_model.joints_.begin(); it!=robot_model.joints_.end(); ++it) { if( it->second->type == urdf::Joint::REVOLUTE || it->second->type == urdf::Joint::PRISMATIC ) { joint_names[index] = (it->first); min(index) = it->second->limits->lower; max(index) = it->second->limits->upper; index++; } } if( index != nrOfJointsWithLimits ) { std::cerr << "[ERR] kdl_format_io error in jointPosLimitsFromUrdfModel function" << std::endl; return false; } return true; } bool framesFromKDLTree(const KDL::Tree& tree, std::vector<std::string>& framesNames, std::vector<std::string>& parentLinkNames) { framesNames.clear(); parentLinkNames.clear(); KDL::SegmentMap::iterator seg; KDL::SegmentMap segs; KDL::SegmentMap::const_iterator root_seg; root_seg = tree.getRootSegment(); segs = tree.getSegments(); for( seg = segs.begin(); seg != segs.end(); seg++ ) { if( seg->second.children.size() == 0 && seg->second.segment.getJoint().getType() == KDL::Joint::None && seg->second.segment.getInertia().getMass() == 0.0 ) { std::string frameName = seg->second.segment.getName(); std::string parentLinkName = seg->second.parent->second.segment.getName(); framesNames.push_back(frameName); parentLinkNames.push_back(parentLinkName); } } return true; } } <commit_msg>Fixed code on clang<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Wim Meeussen */ #include "urdf_import.hpp" #include "urdf_compatibility.h" #include <fstream> #include <kdl/tree.hpp> #include <kdl/jntarray.hpp> #include <tinyxml.h> using namespace std; using namespace KDL; namespace kdl_format_io{ void printTree(urdf::ConstLinkPtr link,int level = 0) { level+=2; int count = 0; for (urdf::LinkVector::const_iterator child = link->child_links.begin(); child != link->child_links.end(); child++) { if (*child) { for(int j=0;j<level;j++) std::cout << " "; //indent std::cout << "child(" << (count++)+1 << "): " << (*child)->name << std::endl; // first grandchild printTree(*child,level); } else { for(int j=0;j<level;j++) std::cout << " "; //indent std::cout << "root link: " << link->name << " has a null child!" << *child << std::endl; } } } // construct vector Vector toKdl(urdf::Vector3 v) { return Vector(v.x, v.y, v.z); } // construct rotation Rotation toKdl(urdf::Rotation r) { return Rotation::Quaternion(r.x, r.y, r.z, r.w); } // construct pose Frame toKdl(urdf::Pose p) { return Frame(toKdl(p.rotation), toKdl(p.position)); } // construct joint Joint toKdl(urdf::JointPtr jnt) { Frame F_parent_jnt = toKdl(jnt->parent_to_joint_origin_transform); switch (jnt->type){ case urdf::Joint::FIXED:{ return Joint(jnt->name, Joint::None); } case urdf::Joint::REVOLUTE:{ Vector axis = toKdl(jnt->axis); return Joint(jnt->name, F_parent_jnt.p, F_parent_jnt.M * axis, Joint::RotAxis); } case urdf::Joint::CONTINUOUS:{ Vector axis = toKdl(jnt->axis); return Joint(jnt->name, F_parent_jnt.p, F_parent_jnt.M * axis, Joint::RotAxis); } case urdf::Joint::PRISMATIC:{ Vector axis = toKdl(jnt->axis); return Joint(jnt->name, F_parent_jnt.p, F_parent_jnt.M * axis, Joint::TransAxis); } default:{ std::cerr << "Converting unknown joint type of joint " << jnt->name << " into a fixed joint" << std::endl; return Joint(jnt->name, Joint::None); } } return Joint(); } // construct inertia RigidBodyInertia toKdl(urdf::InertialPtr i) { Frame origin = toKdl(i->origin); // the mass is frame indipendent double kdl_mass = i->mass; // kdl and urdf both specify the com position in the reference frame of the link Vector kdl_com = origin.p; // kdl specifies the inertia matrix in the reference frame of the link, // while the urdf specifies the inertia matrix in the inertia reference frame RotationalInertia urdf_inertia = RotationalInertia(i->ixx, i->iyy, i->izz, i->ixy, i->ixz, i->iyz); // Rotation operators are not defined for rotational inertia, // so we use the RigidBodyInertia operators (with com = 0) as a workaround RigidBodyInertia kdl_inertia_wrt_com_workaround = origin.M *RigidBodyInertia(0, Vector::Zero(), urdf_inertia); // Note that the RigidBodyInertia constructor takes the 3d inertia wrt the com // while the getRotationalInertia method returns the 3d inertia wrt the frame origin // (but having com = Vector::Zero() in kdl_inertia_wrt_com_workaround they match) RotationalInertia kdl_inertia_wrt_com = kdl_inertia_wrt_com_workaround.getRotationalInertia(); return RigidBodyInertia(kdl_mass,kdl_com,kdl_inertia_wrt_com); } // recursive function to walk through tree bool addChildrenToTree(urdf::LinkPtr root, Tree& tree) { urdf::LinkVector children = root->child_links; //std::cerr << "[INFO] Link " << root->name << " had " << children.size() << " children" << std::endl; // constructs the optional inertia RigidBodyInertia inert(0); if (root->inertial) inert = toKdl(root->inertial); // constructs the kdl joint Joint jnt = toKdl(root->parent_joint); // construct the kdl segment Segment sgm(root->name, jnt, toKdl(root->parent_joint->parent_to_joint_origin_transform), inert); // add segment to tree tree.addSegment(sgm, root->parent_joint->parent_link_name); // recurslively add all children for (size_t i=0; i<children.size(); i++){ if (!addChildrenToTree(children[i], tree)) return false; } return true; } bool treeFromUrdfFile(const string& file, Tree& tree,const bool consider_root_link_inertia) { ifstream ifs(file.c_str()); std::string xml_string( (std::istreambuf_iterator<char>(ifs) ), (std::istreambuf_iterator<char>() ) ); return treeFromUrdfString(xml_string,tree,consider_root_link_inertia); } /* bool treeFromParam(const string& param, Tree& tree) { urdf::ModelInterface robot_model; if (!robot_model.initParam(param)){ logError("Could not generate robot model"); return false; } return treeFromUrdfModel(robot_model, tree); } */ int print_tree(urdf::ModelInterfacePtr & robot) { std::cout << "robot name is: " << robot->getName() << std::endl; // get info from parser std::cout << "---------- Successfully Parsed XML ---------------" << std::endl; // get root link urdf::ConstLinkPtr root_link=robot->getRoot(); if (!root_link) return -1; std::cout << "root Link: " << root_link->name << " has " << root_link->child_links.size() << " child(ren)" << std::endl; // print entire tree printTree(root_link); return 0; } bool treeFromUrdfString(const string& xml, Tree& tree, const bool consider_root_link_inertia) { urdf::ModelInterfacePtr urdf_model; urdf_model = urdf::parseURDF(xml); if( !urdf_model ) { std::cerr << "[ERR] Could not parse string to urdf::ModelInterface" << std::endl; return false; } return treeFromUrdfModel(*urdf_model,tree,consider_root_link_inertia); } /* bool treeFromUrdfXml(TiXmlDocument *xml_doc, Tree& tree) { urdf::ModelInterfacePtr robot_model; robot_model = urdf::parseURDF( if (!robot_model.parse(xml_doc)){ logError("Could not generate robot model"); return false; } return treeFromUrdfModel(robot_model, tree); }*/ bool treeFromUrdfModel(const urdf::ModelInterface& robot_model, Tree& tree, const bool consider_root_link_inertia) { if (consider_root_link_inertia) { //For giving a name to the root of KDL using the robot name, //as it is not used elsewhere in the KDL tree std::string fake_root_name = "__kdl_import__" + robot_model.getName()+"__fake_root__"; std::string fake_root_fixed_joint_name = "__kdl_import__" + robot_model.getName()+"__fake_root_fixed_joint__"; tree = Tree(fake_root_name); const urdf::ConstLinkPtr root = robot_model.getRoot(); // constructs the optional inertia RigidBodyInertia inert(0); if (root->inertial) inert = toKdl(root->inertial); // constructs the kdl joint Joint jnt = Joint(fake_root_fixed_joint_name, Joint::None); // construct the kdl segment Segment sgm(root->name, jnt, Frame::Identity(), inert); // add segment to tree tree.addSegment(sgm, fake_root_name); } else { tree = Tree(robot_model.getRoot()->name); // warn if root link has inertia. KDL does not support this if (robot_model.getRoot()->inertial) std::cerr << "The root link " << robot_model.getRoot()->name << " has an inertia specified in the URDF, but KDL does not support a root link with an inertia. As a workaround, you can add an extra dummy link to your URDF." << std::endl; } // add all children for (size_t i=0; i<robot_model.getRoot()->child_links.size(); i++) if (!addChildrenToTree(robot_model.getRoot()->child_links[i], tree)) return false; return true; } bool jointPosLimitsFromUrdfFile(const std::string& file, std::vector<std::string> & joint_names, KDL::JntArray & min, KDL::JntArray & max) { ifstream ifs(file.c_str()); std::string xml_string( (std::istreambuf_iterator<char>(ifs) ), (std::istreambuf_iterator<char>() ) ); return jointPosLimitsFromUrdfString(xml_string,joint_names,min,max); } bool jointPosLimitsFromUrdfString(const std::string& urdf_xml, std::vector<std::string> & joint_names, KDL::JntArray & min, KDL::JntArray & max) { urdf::ModelInterfacePtr urdf_model; urdf_model = urdf::parseURDF(urdf_xml); if( !urdf_model ) { std::cerr << "[ERR] Could not parse string to urdf::ModelInterface" << std::endl; return false; } return jointPosLimitsFromUrdfModel(*urdf_model,joint_names,min,max); } bool jointPosLimitsFromUrdfModel(const urdf::ModelInterface& robot_model, std::vector<std::string> & joint_names, KDL::JntArray & min, KDL::JntArray & max) { int nrOfJointsWithLimits=0; for (urdf::JointPtrMap::const_iterator it=robot_model.joints_.begin(); it!=robot_model.joints_.end(); ++it) { if( it->second->type == urdf::Joint::REVOLUTE || it->second->type == urdf::Joint::PRISMATIC ) { nrOfJointsWithLimits++; } } joint_names.resize(nrOfJointsWithLimits); min.resize(nrOfJointsWithLimits); max.resize(nrOfJointsWithLimits); int index =0; for (urdf::JointPtrMap::const_iterator it=robot_model.joints_.begin(); it!=robot_model.joints_.end(); ++it) { if( it->second->type == urdf::Joint::REVOLUTE || it->second->type == urdf::Joint::PRISMATIC ) { joint_names[index] = (it->first); min(index) = it->second->limits->lower; max(index) = it->second->limits->upper; index++; } } if( index != nrOfJointsWithLimits ) { std::cerr << "[ERR] kdl_format_io error in jointPosLimitsFromUrdfModel function" << std::endl; return false; } return true; } bool framesFromKDLTree(const KDL::Tree& tree, std::vector<std::string>& framesNames, std::vector<std::string>& parentLinkNames) { framesNames.clear(); parentLinkNames.clear(); KDL::SegmentMap::iterator seg; KDL::SegmentMap segs; KDL::SegmentMap::const_iterator root_seg; root_seg = tree.getRootSegment(); segs = tree.getSegments(); for( seg = segs.begin(); seg != segs.end(); seg++ ) { if( GetTreeElementChildren(seg->second).size() == 0 && GetTreeElementSegment(seg->second).getJoint().getType() == KDL::Joint::None && GetTreeElementSegment(seg->second).getInertia().getMass() == 0.0 ) { std::string frameName = GetTreeElementSegment(seg->second).getName(); std::string parentLinkName = GetTreeElementSegment(GetTreeElementParent(seg->second)->second).getName(); framesNames.push_back(frameName); parentLinkNames.push_back(parentLinkName); } } return true; } } <|endoftext|>
<commit_before><commit_msg>Support the ECC cipher suites added in Mac OS X 10.6.<commit_after><|endoftext|>
<commit_before>/* * Copyright (C) 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "crash_handler.h" #include <gtest/gtest.h> #include <stdlib.h> #include <iostream> namespace core { namespace test { TEST(CrashHandlerTest, HandleCrash) { CrashHandler crashHandler; crashHandler.registerHandler([] (const std::string& minidumpPath, bool succeeded) { if (succeeded) { std::cerr << "crash handled."; } else { std::cerr << "crash not handled."; } }); EXPECT_DEATH({ int i = *((volatile int*)(0)); }, "crash handled."); } } // namespace test } // namespace core <commit_msg>core/cc: Work around #1788<commit_after>/* * Copyright (C) 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "crash_handler.h" #include "core/cc/target.h" #include <gtest/gtest.h> #include <stdlib.h> #include <iostream> namespace core { namespace test { #if TARGET_OS != GAPID_OS_OSX // Work around for https://github.com/google/gapid/issues/1788 TEST(CrashHandlerTest, HandleCrash) { CrashHandler crashHandler; crashHandler.registerHandler([] (const std::string& minidumpPath, bool succeeded) { if (succeeded) { std::cerr << "crash handled."; } else { std::cerr << "crash not handled."; } }); EXPECT_DEATH({ int i = *((volatile int*)(0)); }, "crash handled."); } #endif // TARGET_OS != GAPID_OS_OSX } // namespace test } // namespace core <|endoftext|>
<commit_before>/* * This file is part of telepathy-accounts-kcm * * Copyright (C) 2011 Florian Reinhard <florian.reinhard@googlemail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "haze-skype-account-ui.h" #include "skype-main-options-widget.h" #include "skype-advanced-settings-widget.h" HazeSkypeAccountUi::HazeSkypeAccountUi(QObject *parent) : AbstractAccountUi(parent) { // Register supported parameters // Main Options registerSupportedParameter(QLatin1String("account"), QVariant::String); // Advanced Options registerSupportedParameter(QLatin1String("skypeout-online"), QVariant::Bool); registerSupportedParameter(QLatin1String("skype-sync"), QVariant::Bool); registerSupportedParameter(QLatin1String("check-for-updates"), QVariant::Bool); registerSupportedParameter(QLatin1String("reject-all-auths"), QVariant::Bool); registerSupportedParameter(QLatin1String("skype-autostart"), QVariant::Bool); } HazeSkypeAccountUi::~HazeSkypeAccountUi() { } AbstractAccountParametersWidget *HazeSkypeAccountUi::mainOptionsWidget( ParameterEditModel *model, QWidget *parent) const { return new SkypeMainOptionsWidget(model, parent); } bool HazeSkypeAccountUi::hasAdvancedOptionsWidget() const { return true; } AbstractAccountParametersWidget *HazeSkypeAccountUi::advancedOptionsWidget( ParameterEditModel *model, QWidget *parent) const { AbstractAccountParametersWidget *skypeAdvancedSettingsWidget = new SkypeAdvancedSettingsWidget(model, parent); return skypeAdvancedSettingsWidget; } #include "haze-skype-account-ui.moc" <commit_msg>Disable advanced options widget in Haze-Skype<commit_after>/* * This file is part of telepathy-accounts-kcm * * Copyright (C) 2011 Florian Reinhard <florian.reinhard@googlemail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "haze-skype-account-ui.h" #include "skype-main-options-widget.h" #include "skype-advanced-settings-widget.h" HazeSkypeAccountUi::HazeSkypeAccountUi(QObject *parent) : AbstractAccountUi(parent) { // Register supported parameters // Main Options registerSupportedParameter(QLatin1String("account"), QVariant::String); // Advanced Options registerSupportedParameter(QLatin1String("skypeout-online"), QVariant::Bool); registerSupportedParameter(QLatin1String("skype-sync"), QVariant::Bool); registerSupportedParameter(QLatin1String("check-for-updates"), QVariant::Bool); registerSupportedParameter(QLatin1String("reject-all-auths"), QVariant::Bool); registerSupportedParameter(QLatin1String("skype-autostart"), QVariant::Bool); } HazeSkypeAccountUi::~HazeSkypeAccountUi() { } AbstractAccountParametersWidget *HazeSkypeAccountUi::mainOptionsWidget( ParameterEditModel *model, QWidget *parent) const { return new SkypeMainOptionsWidget(model, parent); } bool HazeSkypeAccountUi::hasAdvancedOptionsWidget() const { return false; } AbstractAccountParametersWidget *HazeSkypeAccountUi::advancedOptionsWidget( ParameterEditModel *model, QWidget *parent) const { AbstractAccountParametersWidget *skypeAdvancedSettingsWidget = new SkypeAdvancedSettingsWidget(model, parent); return skypeAdvancedSettingsWidget; } #include "haze-skype-account-ui.moc" <|endoftext|>
<commit_before>#include "Core.hpp" #include "midi.hpp" #include "dsp/digital.hpp" #include "dsp/filter.hpp" #include <algorithm> struct MIDIToCVInterface : Module { enum ParamIds { NUM_PARAMS }; enum InputIds { NUM_INPUTS }; enum OutputIds { CV_OUTPUT, GATE_OUTPUT, VELOCITY_OUTPUT, AFTERTOUCH_OUTPUT, PITCH_OUTPUT, MOD_OUTPUT, RETRIGGER_OUTPUT, CLOCK_1_OUTPUT, CLOCK_2_OUTPUT, START_OUTPUT, STOP_OUTPUT, CONTINUE_OUTPUT, NUM_OUTPUTS }; enum LightIds { NUM_LIGHTS }; MidiInputQueue midiInput; uint8_t mod = 0; ExponentialFilter modFilter; uint16_t pitch = 0; ExponentialFilter pitchFilter; PulseGenerator retriggerPulse; PulseGenerator clock1Pulse; PulseGenerator clock2Pulse; PulseGenerator startPulse; PulseGenerator stopPulse; PulseGenerator continuePulse; struct NoteData { uint8_t velocity = 0; uint8_t aftertouch = 0; }; NoteData noteData[128]; std::vector<uint8_t> heldNotes; uint8_t lastNote; bool pedal; bool gate; MIDIToCVInterface() : Module(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS), heldNotes(128) { onReset(); } json_t *toJson() override { json_t *rootJ = json_object(); json_object_set_new(rootJ, "midi", midiInput.toJson()); return rootJ; } void fromJson(json_t *rootJ) override { json_t *midiJ = json_object_get(rootJ, "midi"); if (midiJ) midiInput.fromJson(midiJ); } void onReset() override { heldNotes.clear(); lastNote = 60; pedal = false; gate = false; } void pressNote(uint8_t note) { // Remove existing similar note auto it = std::find(heldNotes.begin(), heldNotes.end(), note); if (it != heldNotes.end()) heldNotes.erase(it); // Push note heldNotes.push_back(note); lastNote = note; gate = true; retriggerPulse.trigger(1e-3); } void releaseNote(uint8_t note) { // Remove the note auto it = std::find(heldNotes.begin(), heldNotes.end(), note); if (it != heldNotes.end()) heldNotes.erase(it); // Hold note if pedal is pressed if (pedal) return; // Set last note if (!heldNotes.empty()) { lastNote = heldNotes[heldNotes.size() - 1]; gate = true; } else { gate = false; } } void pressPedal() { pedal = true; } void releasePedal() { pedal = false; releaseNote(255); } void step() override { MidiMessage msg; while (midiInput.shift(&msg)) { processMessage(msg); } float deltaTime = engineGetSampleTime(); outputs[CV_OUTPUT].value = (lastNote - 60) / 12.f; outputs[GATE_OUTPUT].value = gate ? 10.f : 0.f; outputs[VELOCITY_OUTPUT].value = rescale(noteData[lastNote].velocity, 0, 127, 0.f, 10.f); outputs[AFTERTOUCH_OUTPUT].value = rescale(noteData[lastNote].aftertouch, 0, 127, 0.f, 10.f); pitchFilter.lambda = 100.f * deltaTime; outputs[PITCH_OUTPUT].value = pitchFilter.process(rescale(pitch, 0, 16384, -5.f, 5.f)); modFilter.lambda = 100.f * deltaTime; outputs[MOD_OUTPUT].value = modFilter.process(rescale(mod, 0, 127, 0.f, 10.f)); outputs[RETRIGGER_OUTPUT].value = retriggerPulse.process(deltaTime) ? 10.f : 0.f; outputs[CLOCK_1_OUTPUT].value = clock1Pulse.process(deltaTime) ? 10.f : 0.f; outputs[CLOCK_2_OUTPUT].value = clock2Pulse.process(deltaTime) ? 10.f : 0.f; outputs[START_OUTPUT].value = startPulse.process(deltaTime) ? 10.f : 0.f; outputs[STOP_OUTPUT].value = stopPulse.process(deltaTime) ? 10.f : 0.f; outputs[CONTINUE_OUTPUT].value = continuePulse.process(deltaTime) ? 10.f : 0.f; } void processMessage(MidiMessage msg) { // debug("MIDI: %01x %01x %02x %02x", msg.status(), msg.channel(), msg.note(), msg.value()); switch (msg.status()) { // note off case 0x8: { releaseNote(msg.note()); } break; // note on case 0x9: { if (msg.value() > 0) { noteData[msg.note()].velocity = msg.value(); pressNote(msg.note()); } else { // For some reason, some keyboards send a "note on" event with a velocity of 0 to signal that the key has been released. releaseNote(msg.note()); } } break; // channel aftertouch case 0xa: { uint8_t note = msg.note(); noteData[note].aftertouch = msg.value(); } break; // cc case 0xb: { processCC(msg); } break; // pitch wheel case 0xe: { pitch = msg.value() * 128 + msg.note(); } break; case 0xf: { processSystem(msg); } break; default: break; } } void processCC(MidiMessage msg) { switch (msg.note()) { // mod case 0x01: { mod = msg.value(); } break; // sustain case 0x40: { if (msg.value() >= 64) pressPedal(); else releasePedal(); } break; default: break; } } void processSystem(MidiMessage msg) { switch (msg.channel()) { // Timing case 0x8: { // TODO } break; // Start case 0xa: { startPulse.trigger(1e-3); } break; // Continue case 0xb: { continuePulse.trigger(1e-3); } break; // Stop case 0xc: { stopPulse.trigger(1e-3); } break; default: break; } } }; struct MIDIToCVInterfaceWidget : ModuleWidget { MIDIToCVInterfaceWidget(MIDIToCVInterface *module) : ModuleWidget(module) { setPanel(SVG::load(assetGlobal("res/Core/MIDIToCVInterface.svg"))); addChild(Widget::create<ScrewSilver>(Vec(RACK_GRID_WIDTH, 0))); addChild(Widget::create<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0))); addChild(Widget::create<ScrewSilver>(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH))); addChild(Widget::create<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH))); addOutput(Port::create<PJ301MPort>(mm2px(Vec(4.61505, 60.1445)), Port::OUTPUT, module, MIDIToCVInterface::CV_OUTPUT)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(16.214, 60.1445)), Port::OUTPUT, module, MIDIToCVInterface::GATE_OUTPUT)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(27.8143, 60.1445)), Port::OUTPUT, module, MIDIToCVInterface::VELOCITY_OUTPUT)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(4.61505, 76.1449)), Port::OUTPUT, module, MIDIToCVInterface::AFTERTOUCH_OUTPUT)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(16.214, 76.1449)), Port::OUTPUT, module, MIDIToCVInterface::PITCH_OUTPUT)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(27.8143, 76.1449)), Port::OUTPUT, module, MIDIToCVInterface::MOD_OUTPUT)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(4.61505, 92.1439)), Port::OUTPUT, module, MIDIToCVInterface::RETRIGGER_OUTPUT)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(16.214, 92.1439)), Port::OUTPUT, module, MIDIToCVInterface::CLOCK_1_OUTPUT)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(27.8143, 92.1439)), Port::OUTPUT, module, MIDIToCVInterface::CLOCK_2_OUTPUT)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(4.61505, 108.144)), Port::OUTPUT, module, MIDIToCVInterface::START_OUTPUT)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(16.214, 108.144)), Port::OUTPUT, module, MIDIToCVInterface::STOP_OUTPUT)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(27.8143, 108.144)), Port::OUTPUT, module, MIDIToCVInterface::CONTINUE_OUTPUT)); MidiWidget *midiWidget = Widget::create<MidiWidget>(mm2px(Vec(3.41891, 14.8373))); midiWidget->box.size = mm2px(Vec(33.840, 28)); midiWidget->midiIO = &module->midiInput; addChild(midiWidget); } }; Model *modelMIDIToCVInterface = Model::create<MIDIToCVInterface, MIDIToCVInterfaceWidget>("Core", "MIDIToCVInterface", "MIDI-1", MIDI_TAG, EXTERNAL_TAG); <commit_msg>MIDI-1: Add retrigger when key is lifted<commit_after>#include "Core.hpp" #include "midi.hpp" #include "dsp/digital.hpp" #include "dsp/filter.hpp" #include <algorithm> struct MIDIToCVInterface : Module { enum ParamIds { NUM_PARAMS }; enum InputIds { NUM_INPUTS }; enum OutputIds { CV_OUTPUT, GATE_OUTPUT, VELOCITY_OUTPUT, AFTERTOUCH_OUTPUT, PITCH_OUTPUT, MOD_OUTPUT, RETRIGGER_OUTPUT, CLOCK_1_OUTPUT, CLOCK_2_OUTPUT, START_OUTPUT, STOP_OUTPUT, CONTINUE_OUTPUT, NUM_OUTPUTS }; enum LightIds { NUM_LIGHTS }; MidiInputQueue midiInput; uint8_t mod = 0; ExponentialFilter modFilter; uint16_t pitch = 0; ExponentialFilter pitchFilter; PulseGenerator retriggerPulse; PulseGenerator clock1Pulse; PulseGenerator clock2Pulse; PulseGenerator startPulse; PulseGenerator stopPulse; PulseGenerator continuePulse; struct NoteData { uint8_t velocity = 0; uint8_t aftertouch = 0; }; NoteData noteData[128]; std::vector<uint8_t> heldNotes; uint8_t lastNote; bool pedal; bool gate; MIDIToCVInterface() : Module(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS), heldNotes(128) { onReset(); } json_t *toJson() override { json_t *rootJ = json_object(); json_object_set_new(rootJ, "midi", midiInput.toJson()); return rootJ; } void fromJson(json_t *rootJ) override { json_t *midiJ = json_object_get(rootJ, "midi"); if (midiJ) midiInput.fromJson(midiJ); } void onReset() override { heldNotes.clear(); lastNote = 60; pedal = false; gate = false; } void pressNote(uint8_t note) { // Remove existing similar note auto it = std::find(heldNotes.begin(), heldNotes.end(), note); if (it != heldNotes.end()) heldNotes.erase(it); // Push note heldNotes.push_back(note); lastNote = note; gate = true; retriggerPulse.trigger(1e-3); } void releaseNote(uint8_t note) { // Remove the note auto it = std::find(heldNotes.begin(), heldNotes.end(), note); if (it != heldNotes.end()) heldNotes.erase(it); // Hold note if pedal is pressed if (pedal) return; // Set last note if (!heldNotes.empty()) { lastNote = heldNotes[heldNotes.size() - 1]; gate = true; retriggerPulse.trigger(1e-3); } else { gate = false; } } void pressPedal() { pedal = true; } void releasePedal() { pedal = false; releaseNote(255); } void step() override { MidiMessage msg; while (midiInput.shift(&msg)) { processMessage(msg); } float deltaTime = engineGetSampleTime(); outputs[CV_OUTPUT].value = (lastNote - 60) / 12.f; outputs[GATE_OUTPUT].value = gate ? 10.f : 0.f; outputs[VELOCITY_OUTPUT].value = rescale(noteData[lastNote].velocity, 0, 127, 0.f, 10.f); outputs[AFTERTOUCH_OUTPUT].value = rescale(noteData[lastNote].aftertouch, 0, 127, 0.f, 10.f); pitchFilter.lambda = 100.f * deltaTime; outputs[PITCH_OUTPUT].value = pitchFilter.process(rescale(pitch, 0, 16384, -5.f, 5.f)); modFilter.lambda = 100.f * deltaTime; outputs[MOD_OUTPUT].value = modFilter.process(rescale(mod, 0, 127, 0.f, 10.f)); outputs[RETRIGGER_OUTPUT].value = retriggerPulse.process(deltaTime) ? 10.f : 0.f; outputs[CLOCK_1_OUTPUT].value = clock1Pulse.process(deltaTime) ? 10.f : 0.f; outputs[CLOCK_2_OUTPUT].value = clock2Pulse.process(deltaTime) ? 10.f : 0.f; outputs[START_OUTPUT].value = startPulse.process(deltaTime) ? 10.f : 0.f; outputs[STOP_OUTPUT].value = stopPulse.process(deltaTime) ? 10.f : 0.f; outputs[CONTINUE_OUTPUT].value = continuePulse.process(deltaTime) ? 10.f : 0.f; } void processMessage(MidiMessage msg) { // debug("MIDI: %01x %01x %02x %02x", msg.status(), msg.channel(), msg.note(), msg.value()); switch (msg.status()) { // note off case 0x8: { releaseNote(msg.note()); } break; // note on case 0x9: { if (msg.value() > 0) { noteData[msg.note()].velocity = msg.value(); pressNote(msg.note()); } else { // For some reason, some keyboards send a "note on" event with a velocity of 0 to signal that the key has been released. releaseNote(msg.note()); } } break; // channel aftertouch case 0xa: { uint8_t note = msg.note(); noteData[note].aftertouch = msg.value(); } break; // cc case 0xb: { processCC(msg); } break; // pitch wheel case 0xe: { pitch = msg.value() * 128 + msg.note(); } break; case 0xf: { processSystem(msg); } break; default: break; } } void processCC(MidiMessage msg) { switch (msg.note()) { // mod case 0x01: { mod = msg.value(); } break; // sustain case 0x40: { if (msg.value() >= 64) pressPedal(); else releasePedal(); } break; default: break; } } void processSystem(MidiMessage msg) { switch (msg.channel()) { // Timing case 0x8: { // TODO } break; // Start case 0xa: { startPulse.trigger(1e-3); } break; // Continue case 0xb: { continuePulse.trigger(1e-3); } break; // Stop case 0xc: { stopPulse.trigger(1e-3); } break; default: break; } } }; struct MIDIToCVInterfaceWidget : ModuleWidget { MIDIToCVInterfaceWidget(MIDIToCVInterface *module) : ModuleWidget(module) { setPanel(SVG::load(assetGlobal("res/Core/MIDIToCVInterface.svg"))); addChild(Widget::create<ScrewSilver>(Vec(RACK_GRID_WIDTH, 0))); addChild(Widget::create<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0))); addChild(Widget::create<ScrewSilver>(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH))); addChild(Widget::create<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH))); addOutput(Port::create<PJ301MPort>(mm2px(Vec(4.61505, 60.1445)), Port::OUTPUT, module, MIDIToCVInterface::CV_OUTPUT)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(16.214, 60.1445)), Port::OUTPUT, module, MIDIToCVInterface::GATE_OUTPUT)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(27.8143, 60.1445)), Port::OUTPUT, module, MIDIToCVInterface::VELOCITY_OUTPUT)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(4.61505, 76.1449)), Port::OUTPUT, module, MIDIToCVInterface::AFTERTOUCH_OUTPUT)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(16.214, 76.1449)), Port::OUTPUT, module, MIDIToCVInterface::PITCH_OUTPUT)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(27.8143, 76.1449)), Port::OUTPUT, module, MIDIToCVInterface::MOD_OUTPUT)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(4.61505, 92.1439)), Port::OUTPUT, module, MIDIToCVInterface::RETRIGGER_OUTPUT)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(16.214, 92.1439)), Port::OUTPUT, module, MIDIToCVInterface::CLOCK_1_OUTPUT)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(27.8143, 92.1439)), Port::OUTPUT, module, MIDIToCVInterface::CLOCK_2_OUTPUT)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(4.61505, 108.144)), Port::OUTPUT, module, MIDIToCVInterface::START_OUTPUT)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(16.214, 108.144)), Port::OUTPUT, module, MIDIToCVInterface::STOP_OUTPUT)); addOutput(Port::create<PJ301MPort>(mm2px(Vec(27.8143, 108.144)), Port::OUTPUT, module, MIDIToCVInterface::CONTINUE_OUTPUT)); MidiWidget *midiWidget = Widget::create<MidiWidget>(mm2px(Vec(3.41891, 14.8373))); midiWidget->box.size = mm2px(Vec(33.840, 28)); midiWidget->midiIO = &module->midiInput; addChild(midiWidget); } }; Model *modelMIDIToCVInterface = Model::create<MIDIToCVInterface, MIDIToCVInterfaceWidget>("Core", "MIDIToCVInterface", "MIDI-1", MIDI_TAG, EXTERNAL_TAG); <|endoftext|>
<commit_before>/* Copyright (c) 2009 Stephen Kelly <steveire@gmail.com> 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 "akonadibrowsermodel.h" #include <kmime/kmime_message.h> #include <kabc/addressee.h> #include <kabc/contactgroup.h> #include <kcal/incidence.h> #include <kcal/event.h> #include <boost/shared_ptr.hpp> typedef boost::shared_ptr<KMime::Message> MessagePtr; typedef boost::shared_ptr<KCal::Incidence> IncidencePtr; class AkonadiBrowserModel::State { public: virtual ~State() {} QStringList m_collectionHeaders; QStringList m_itemHeaders; virtual QVariant getData( const Item &item, int column, int role ) const = 0; }; class GenericState : public AkonadiBrowserModel::State { public: GenericState() { m_collectionHeaders << "Collection"; m_itemHeaders << "Id" << "Remote Id" << "MimeType"; } virtual ~GenericState() {} QVariant getData( const Item &item, int column, int role ) const { if (Qt::DisplayRole != role) return QVariant(); switch (column) { case 0: return item.id(); case 1: return item.remoteId(); case 2: return item.mimeType(); } return QVariant(); } }; class MailState : public AkonadiBrowserModel::State { public: MailState() { m_collectionHeaders << "Collection"; m_itemHeaders << "Subject" << "Sender" << "Date"; } virtual ~MailState() {} QVariant getData( const Item &item, int column, int role ) const { if (Qt::DisplayRole != role) return QVariant(); if (!item.hasPayload<MessagePtr>()) { return QVariant(); } const MessagePtr mail = item.payload<MessagePtr>(); switch (column) { case 0: return mail->subject()->asUnicodeString(); case 1: return mail->from()->asUnicodeString(); case 2: return mail->date()->asUnicodeString(); } return QVariant(); } }; class ContactsState : public AkonadiBrowserModel::State { public: ContactsState() { m_collectionHeaders << "Collection"; m_itemHeaders << "Given Name" << "Family Name" << "Email"; } virtual ~ContactsState() {} QVariant getData( const Item &item, int column, int role ) const { if (Qt::DisplayRole != role) return QVariant(); if ( !item.hasPayload<KABC::Addressee>() && !item.hasPayload<KABC::ContactGroup>() ) { return QVariant(); } if ( item.hasPayload<KABC::Addressee>() ) { const KABC::Addressee addr = item.payload<KABC::Addressee>(); switch (column) { case 0: return addr.givenName(); case 1: return addr.familyName(); case 2: return addr.preferredEmail(); } return QVariant(); } if ( item.hasPayload<KABC::ContactGroup>() ) { switch (column) { case 0: const KABC::ContactGroup group = item.payload<KABC::ContactGroup>(); return group.name(); } return QVariant(); } return QVariant(); } }; class CalendarState : public AkonadiBrowserModel::State { public: CalendarState() { m_collectionHeaders << "Collection"; m_itemHeaders << "Summary" << "DateTime start" << "DateTime End" << "Type"; } virtual ~CalendarState() {} QVariant getData( const Item &item, int column, int role ) const { if (Qt::DisplayRole != role) return QVariant(); if ( !item.hasPayload<IncidencePtr>() ) { return QVariant(); } const IncidencePtr incidence = item.payload<IncidencePtr>(); switch (column) { case 0: return incidence->summary(); break; case 1: return incidence->dtStart().toString(); break; case 2: return incidence->dtEnd().toString(); break; case 3: return incidence->type(); break; default: break; } return QVariant(); } }; AkonadiBrowserModel::AkonadiBrowserModel( Session* session, ChangeRecorder* monitor, QObject* parent ) : EntityTreeModel( session, monitor, parent ), m_itemDisplayMode( GenericMode ) { m_genericState = new GenericState(); m_mailState = new MailState(); m_contactsState = new ContactsState(); m_calendarState = new CalendarState(); m_currentState = m_genericState; } int AkonadiBrowserModel::columnCount(const QModelIndex& parent) const { Q_UNUSED(parent); return qMax(m_currentState->m_collectionHeaders.size(), m_currentState->m_itemHeaders.size()); } QVariant AkonadiBrowserModel::entityData( const Item &item, int column, int role ) const { QVariant var = m_currentState->getData( item, column, role ); if ( !var.isValid() ) { if ( column < 1 ) return EntityTreeModel::entityData( item, column, role ); return QString(); } return var; } QVariant AkonadiBrowserModel::entityData(const Akonadi::Collection& collection, int column, int role) const { return Akonadi::EntityTreeModel::entityData( collection, column, role ); } int AkonadiBrowserModel::entityColumnCount( HeaderGroup headerGroup ) const { if ( ItemListHeaders == headerGroup ) { return m_currentState->m_itemHeaders.size(); } if ( CollectionTreeHeaders == headerGroup ) { return m_currentState->m_collectionHeaders.size(); } // Practically, this should never happen. return EntityTreeModel::entityColumnCount( headerGroup ); } QVariant AkonadiBrowserModel::entityHeaderData( int section, Qt::Orientation orientation, int role, HeaderGroup headerGroup ) const { if ( section < 0 ) return QVariant(); if ( orientation == Qt::Vertical ) return EntityTreeModel::entityHeaderData( section, orientation, role, headerGroup ); if ( headerGroup == EntityTreeModel::CollectionTreeHeaders ) { if ( role == Qt::DisplayRole ) { if ( section >= m_currentState->m_collectionHeaders.size() ) return QVariant(); return m_currentState->m_collectionHeaders.at( section ); } } else if ( headerGroup == EntityTreeModel::ItemListHeaders ) { if ( role == Qt::DisplayRole ) { if ( section >= m_currentState->m_itemHeaders.size() ) return QVariant(); return m_currentState->m_itemHeaders.at( section ); } } return EntityTreeModel::entityHeaderData( section, orientation, role, headerGroup ); } AkonadiBrowserModel::ItemDisplayMode AkonadiBrowserModel::itemDisplayMode() const { return m_itemDisplayMode; } void AkonadiBrowserModel::setItemDisplayMode( AkonadiBrowserModel::ItemDisplayMode itemDisplayMode ) { beginResetModel(); m_itemDisplayMode = itemDisplayMode; switch (itemDisplayMode) { case MailMode: m_currentState = m_mailState; break; case ContactsMode: m_currentState = m_contactsState; break; case CalendarMode: m_currentState = m_calendarState; break; case GenericMode: default: m_currentState = m_genericState; break; } endResetModel(); } void AkonadiBrowserModel::invalidatePersistentIndexes() { QModelIndexList oldList = this->persistentIndexList(); QModelIndexList newList; for (int i=0; i < oldList.size(); i++) newList << QModelIndex(); this->changePersistentIndexList(oldList, newList); } void AkonadiBrowserModel::beginResetModel() { QMetaObject::invokeMethod(this, "modelAboutToBeReset", Qt::DirectConnection); } void AkonadiBrowserModel::endResetModel() { invalidatePersistentIndexes(); QMetaObject::invokeMethod(this, "modelReset", Qt::DirectConnection); } <commit_msg>Rename internal virtual to make grep happier.<commit_after>/* Copyright (c) 2009 Stephen Kelly <steveire@gmail.com> 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 "akonadibrowsermodel.h" #include <kmime/kmime_message.h> #include <kabc/addressee.h> #include <kabc/contactgroup.h> #include <kcal/incidence.h> #include <kcal/event.h> #include <boost/shared_ptr.hpp> typedef boost::shared_ptr<KMime::Message> MessagePtr; typedef boost::shared_ptr<KCal::Incidence> IncidencePtr; class AkonadiBrowserModel::State { public: virtual ~State() {} QStringList m_collectionHeaders; QStringList m_itemHeaders; virtual QVariant entityData( const Item &item, int column, int role ) const = 0; }; class GenericState : public AkonadiBrowserModel::State { public: GenericState() { m_collectionHeaders << "Collection"; m_itemHeaders << "Id" << "Remote Id" << "MimeType"; } virtual ~GenericState() {} QVariant entityData( const Item &item, int column, int role ) const { if (Qt::DisplayRole != role) return QVariant(); switch (column) { case 0: return item.id(); case 1: return item.remoteId(); case 2: return item.mimeType(); } return QVariant(); } }; class MailState : public AkonadiBrowserModel::State { public: MailState() { m_collectionHeaders << "Collection"; m_itemHeaders << "Subject" << "Sender" << "Date"; } virtual ~MailState() {} QVariant entityData( const Item &item, int column, int role ) const { if (Qt::DisplayRole != role) return QVariant(); if (!item.hasPayload<MessagePtr>()) { return QVariant(); } const MessagePtr mail = item.payload<MessagePtr>(); switch (column) { case 0: return mail->subject()->asUnicodeString(); case 1: return mail->from()->asUnicodeString(); case 2: return mail->date()->asUnicodeString(); } return QVariant(); } }; class ContactsState : public AkonadiBrowserModel::State { public: ContactsState() { m_collectionHeaders << "Collection"; m_itemHeaders << "Given Name" << "Family Name" << "Email"; } virtual ~ContactsState() {} QVariant entityData( const Item &item, int column, int role ) const { if (Qt::DisplayRole != role) return QVariant(); if ( !item.hasPayload<KABC::Addressee>() && !item.hasPayload<KABC::ContactGroup>() ) { return QVariant(); } if ( item.hasPayload<KABC::Addressee>() ) { const KABC::Addressee addr = item.payload<KABC::Addressee>(); switch (column) { case 0: return addr.givenName(); case 1: return addr.familyName(); case 2: return addr.preferredEmail(); } return QVariant(); } if ( item.hasPayload<KABC::ContactGroup>() ) { switch (column) { case 0: const KABC::ContactGroup group = item.payload<KABC::ContactGroup>(); return group.name(); } return QVariant(); } return QVariant(); } }; class CalendarState : public AkonadiBrowserModel::State { public: CalendarState() { m_collectionHeaders << "Collection"; m_itemHeaders << "Summary" << "DateTime start" << "DateTime End" << "Type"; } virtual ~CalendarState() {} QVariant entityData( const Item &item, int column, int role ) const { if (Qt::DisplayRole != role) return QVariant(); if ( !item.hasPayload<IncidencePtr>() ) { return QVariant(); } const IncidencePtr incidence = item.payload<IncidencePtr>(); switch (column) { case 0: return incidence->summary(); break; case 1: return incidence->dtStart().toString(); break; case 2: return incidence->dtEnd().toString(); break; case 3: return incidence->type(); break; default: break; } return QVariant(); } }; AkonadiBrowserModel::AkonadiBrowserModel( Session* session, ChangeRecorder* monitor, QObject* parent ) : EntityTreeModel( session, monitor, parent ), m_itemDisplayMode( GenericMode ) { m_genericState = new GenericState(); m_mailState = new MailState(); m_contactsState = new ContactsState(); m_calendarState = new CalendarState(); m_currentState = m_genericState; } int AkonadiBrowserModel::columnCount(const QModelIndex& parent) const { Q_UNUSED(parent); return qMax(m_currentState->m_collectionHeaders.size(), m_currentState->m_itemHeaders.size()); } QVariant AkonadiBrowserModel::entityData( const Item &item, int column, int role ) const { QVariant var = m_currentState->entityData( item, column, role ); if ( !var.isValid() ) { if ( column < 1 ) return EntityTreeModel::entityData( item, column, role ); return QString(); } return var; } QVariant AkonadiBrowserModel::entityData(const Akonadi::Collection& collection, int column, int role) const { return Akonadi::EntityTreeModel::entityData( collection, column, role ); } int AkonadiBrowserModel::entityColumnCount( HeaderGroup headerGroup ) const { if ( ItemListHeaders == headerGroup ) { return m_currentState->m_itemHeaders.size(); } if ( CollectionTreeHeaders == headerGroup ) { return m_currentState->m_collectionHeaders.size(); } // Practically, this should never happen. return EntityTreeModel::entityColumnCount( headerGroup ); } QVariant AkonadiBrowserModel::entityHeaderData( int section, Qt::Orientation orientation, int role, HeaderGroup headerGroup ) const { if ( section < 0 ) return QVariant(); if ( orientation == Qt::Vertical ) return EntityTreeModel::entityHeaderData( section, orientation, role, headerGroup ); if ( headerGroup == EntityTreeModel::CollectionTreeHeaders ) { if ( role == Qt::DisplayRole ) { if ( section >= m_currentState->m_collectionHeaders.size() ) return QVariant(); return m_currentState->m_collectionHeaders.at( section ); } } else if ( headerGroup == EntityTreeModel::ItemListHeaders ) { if ( role == Qt::DisplayRole ) { if ( section >= m_currentState->m_itemHeaders.size() ) return QVariant(); return m_currentState->m_itemHeaders.at( section ); } } return EntityTreeModel::entityHeaderData( section, orientation, role, headerGroup ); } AkonadiBrowserModel::ItemDisplayMode AkonadiBrowserModel::itemDisplayMode() const { return m_itemDisplayMode; } void AkonadiBrowserModel::setItemDisplayMode( AkonadiBrowserModel::ItemDisplayMode itemDisplayMode ) { beginResetModel(); m_itemDisplayMode = itemDisplayMode; switch (itemDisplayMode) { case MailMode: m_currentState = m_mailState; break; case ContactsMode: m_currentState = m_contactsState; break; case CalendarMode: m_currentState = m_calendarState; break; case GenericMode: default: m_currentState = m_genericState; break; } endResetModel(); } void AkonadiBrowserModel::invalidatePersistentIndexes() { QModelIndexList oldList = this->persistentIndexList(); QModelIndexList newList; for (int i=0; i < oldList.size(); i++) newList << QModelIndex(); this->changePersistentIndexList(oldList, newList); } void AkonadiBrowserModel::beginResetModel() { QMetaObject::invokeMethod(this, "modelAboutToBeReset", Qt::DirectConnection); } void AkonadiBrowserModel::endResetModel() { invalidatePersistentIndexes(); QMetaObject::invokeMethod(this, "modelReset", Qt::DirectConnection); } <|endoftext|>