text
stringlengths
54
60.6k
<commit_before>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ // vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4: #ident "Copyright (c) 2007-2012 Tokutek Inc. All rights reserved." #ident "$Id$" #include <config.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <unistd.h> #include <string.h> #include <fcntl.h> #include <errno.h> #include <toku_assert.h> #if defined(HAVE_MALLOC_H) # include <malloc.h> #elif defined(HAVE_SYS_MALLOC_H) # include <sys/malloc.h> #endif #include <sys/types.h> #include <sys/stat.h> #include <sys/file.h> #if defined(HAVE_SYSCALL_H) # include <syscall.h> #endif #if defined(HAVE_SYS_SYSCALL_H) # include <sys/syscall.h> #endif #if defined(HAVE_SYS_SYSCTL_H) # include <sys/sysctl.h> #endif #if defined(HAVE_PTHREAD_NP_H) # include <pthread_np.h> #endif #include <inttypes.h> #include <sys/time.h> #if defined(HAVE_SYS_RESOURCE_H) # include <sys/resource.h> #endif #include <sys/statvfs.h> #include "toku_portability.h" #include "toku_os.h" #include "toku_time.h" #include "memory.h" int toku_portability_init(void) { int r = toku_memory_startup(); return r; } void toku_portability_destroy(void) { toku_memory_shutdown(); } int toku_os_getpid(void) { return getpid(); } int toku_os_gettid(void) { #if defined(__NR_gettid) return syscall(__NR_gettid); #elif defined(SYS_gettid) return syscall(SYS_gettid); #elif defined(HAVE_PTHREAD_GETTHREADID_NP) return pthread_getthreadid_np(); #else # error "no implementation of gettid available" #endif } int toku_os_get_number_processors(void) { return sysconf(_SC_NPROCESSORS_CONF); } int toku_os_get_number_active_processors(void) { int n = sysconf(_SC_NPROCESSORS_ONLN); #define DO_TOKU_NCPUS 1 #if DO_TOKU_NCPUS { char *toku_ncpus = getenv("TOKU_NCPUS"); if (toku_ncpus) { int ncpus = atoi(toku_ncpus); if (ncpus < n) n = ncpus; } } #endif return n; } int toku_os_get_pagesize(void) { return sysconf(_SC_PAGESIZE); } uint64_t toku_os_get_phys_memory_size(void) { #if defined(_SC_PHYS_PAGES) uint64_t npages = sysconf(_SC_PHYS_PAGES); uint64_t pagesize = sysconf(_SC_PAGESIZE); return npages*pagesize; #elif defined(HAVE_SYS_SYSCTL_H) uint64_t memsize; size_t len = sizeof memsize; sysctlbyname("hw.memsize", &memsize, &len, NULL, 0); return memsize; #else # error "cannot find _SC_PHYS_PAGES or sysctlbyname()" #endif } int toku_os_get_file_size(int fildes, int64_t *fsize) { toku_struct_stat sbuf; int r = fstat(fildes, &sbuf); if (r==0) { *fsize = sbuf.st_size; } return r; } int toku_os_get_unique_file_id(int fildes, struct fileid *id) { toku_struct_stat statbuf; memset(id, 0, sizeof(*id)); int r=fstat(fildes, &statbuf); if (r==0) { id->st_dev = statbuf.st_dev; id->st_ino = statbuf.st_ino; } return r; } int toku_os_lock_file(const char *name) { int r; int fd = open(name, O_RDWR|O_CREAT, S_IRUSR | S_IWUSR); if (fd>=0) { r = flock(fd, LOCK_EX | LOCK_NB); if (r!=0) { r = errno; //Save errno from flock. close(fd); fd = -1; //Disable fd. errno = r; } } return fd; } int toku_os_unlock_file(int fildes) { int r = flock(fildes, LOCK_UN); if (r==0) r = close(fildes); return r; } int toku_os_mkdir(const char *pathname, mode_t mode) { int r = mkdir(pathname, mode); return r; } int toku_os_get_process_times(struct timeval *usertime, struct timeval *kerneltime) { int r; struct rusage rusage; r = getrusage(RUSAGE_SELF, &rusage); if (r == -1) return get_error_errno(); if (usertime) *usertime = rusage.ru_utime; if (kerneltime) *kerneltime = rusage.ru_stime; return 0; } int toku_os_initialize_settings(int UU(verbosity)) { int r = 0; static int initialized = 0; assert(initialized==0); initialized=1; return r; } int toku_os_get_max_rss(int64_t *maxrss) { char statusname[100]; sprintf(statusname, "/proc/%d/status", getpid()); FILE *f = fopen(statusname, "r"); if (f == NULL) { #if defined(HAVE_SYS_RESOURCE_H) // try getrusage instead struct rusage rusage; getrusage(RUSAGE_SELF, &rusage); *maxrss = rusage.ru_maxrss * 1024; // ru_maxrss is in kB return 0; #else return get_error_errno(); #endif } int r = ENOENT; char line[100]; while (fgets(line, sizeof line, f)) { r = sscanf(line, "VmHWM:\t%lld kB\n", (long long *) maxrss); if (r == 1) { *maxrss *= 1<<10; r = 0; break; } } fclose(f); return r; } int toku_os_get_rss(int64_t *rss) { char statusname[100]; sprintf(statusname, "/proc/%d/status", getpid()); FILE *f = fopen(statusname, "r"); if (f == NULL) { #if defined(HAVE_SYS_RESOURCE_H) // try getrusage instead struct rusage rusage; getrusage(RUSAGE_SELF, &rusage); *rss = (rusage.ru_idrss + rusage.ru_ixrss + rusage.ru_isrss) * 1024; return 0; #else return get_error_errno(); #endif } int r = ENOENT; char line[100]; while (fgets(line, sizeof line, f)) { r = sscanf(line, "VmRSS:\t%lld kB\n", (long long *) rss); if (r == 1) { *rss *= 1<<10; r = 0; break; } } fclose(f); return r; } bool toku_os_is_absolute_name(const char* path) { return path[0] == '/'; } int toku_os_get_max_process_data_size(uint64_t *maxdata) { int r; struct rlimit rlimit; r = getrlimit(RLIMIT_DATA, &rlimit); if (r == 0) { uint64_t d; d = rlimit.rlim_max; // with the "right" macros defined, the rlimit is a 64 bit number on a // 32 bit system. getrlimit returns 2**64-1 which is clearly wrong. // for 32 bit processes, we assume that 1/2 of the address space is // used for mapping the kernel. this may be pessimistic. if (sizeof (void *) == 4 && d > (1ULL << 31)) d = 1ULL << 31; *maxdata = d; } else r = get_error_errno(); return r; } int toku_stat(const char *name, toku_struct_stat *buf) { int r = stat(name, buf); return r; } int toku_fstat(int fd, toku_struct_stat *buf) { int r = fstat(fd, buf); return r; } static int toku_get_processor_frequency_sys(uint64_t *hzret) { int r; FILE *fp = fopen("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq", "r"); if (!fp) r = get_error_errno(); else { unsigned int khz = 0; if (fscanf(fp, "%u", &khz) == 1) { *hzret = khz * 1000ULL; r = 0; } else r = ENOENT; fclose(fp); } return r; } static int toku_get_processor_frequency_cpuinfo(uint64_t *hzret) { int r; FILE *fp = fopen("/proc/cpuinfo", "r"); if (!fp) { r = get_error_errno(); } else { uint64_t maxhz = 0; char *buf = NULL; size_t n = 0; while (getline(&buf, &n, fp) >= 0) { unsigned int cpu; sscanf(buf, "processor : %u", &cpu); unsigned int ma, mb; if (sscanf(buf, "cpu MHz : %u.%u", &ma, &mb) == 2) { uint64_t hz = ma * 1000000ULL + mb * 1000ULL; if (hz > maxhz) maxhz = hz; } } if (buf) free(buf); fclose(fp); *hzret = maxhz; r = maxhz == 0 ? ENOENT : 0;; } return r; } static int toku_get_processor_frequency_sysctl(const char * const cmd, uint64_t *hzret) { int r = 0; FILE *fp = popen(cmd, "r"); if (!fp) { r = EINVAL; // popen doesn't return anything useful in errno, // gotta pick something goto exit; } r = fscanf(fp, "%" SCNu64, hzret); if (r != 1) { r = get_maybe_error_errno(); } else { r = 0; } pclose(fp); exit: return r; } int toku_os_get_processor_frequency(uint64_t *hzret) { int r; r = toku_get_processor_frequency_sys(hzret); if (r != 0) r = toku_get_processor_frequency_cpuinfo(hzret); if (r != 0) r = toku_get_processor_frequency_sysctl("sysctl -n hw.cpufrequency", hzret); if (r != 0) r = toku_get_processor_frequency_sysctl("sysctl -n machdep.tsc_freq", hzret); return r; } int toku_get_filesystem_sizes(const char *path, uint64_t *avail_size, uint64_t *free_size, uint64_t *total_size) { struct statvfs s; int r = statvfs(path, &s); if (r == -1) { r = get_error_errno(); } else { // get the block size in bytes uint64_t bsize = s.f_frsize ? s.f_frsize : s.f_bsize; // convert blocks to bytes if (avail_size) *avail_size = (uint64_t) s.f_bavail * bsize; if (free_size) *free_size = (uint64_t) s.f_bfree * bsize; if (total_size) *total_size = (uint64_t) s.f_blocks * bsize; } return r; } int toku_dup2(int fd, int fd2) { int r; r = dup2(fd, fd2); return r; } // Time static double seconds_per_clock = -1; double tokutime_to_seconds(tokutime_t t) { // Convert tokutime to seconds. if (seconds_per_clock<0) { uint64_t hz; int r = toku_os_get_processor_frequency(&hz); assert(r==0); // There's a race condition here, but it doesn't really matter. If two threads call tokutime_to_seconds // for the first time at the same time, then both will fetch the value and set the same value. seconds_per_clock = 1.0/hz; } return t*seconds_per_clock; } #if __GNUC__ && __i386__ // workaround for a gcc 4.1.2 bug on 32 bit platforms. uint64_t toku_sync_fetch_and_add_uint64(volatile uint64_t *a, uint64_t b) __attribute__((noinline)); uint64_t toku_sync_fetch_and_add_uint64(volatile uint64_t *a, uint64_t b) { return __sync_fetch_and_add(a, b); } #endif <commit_msg>refs #5368 clean up toku_os_get_*rss<commit_after>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ // vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4: #ident "Copyright (c) 2007-2012 Tokutek Inc. All rights reserved." #ident "$Id$" #include <config.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <unistd.h> #include <string.h> #include <fcntl.h> #include <errno.h> #include <toku_assert.h> #if defined(HAVE_MALLOC_H) # include <malloc.h> #elif defined(HAVE_SYS_MALLOC_H) # include <sys/malloc.h> #endif #include <sys/types.h> #include <sys/stat.h> #include <sys/file.h> #if defined(HAVE_SYSCALL_H) # include <syscall.h> #endif #if defined(HAVE_SYS_SYSCALL_H) # include <sys/syscall.h> #endif #if defined(HAVE_SYS_SYSCTL_H) # include <sys/sysctl.h> #endif #if defined(HAVE_PTHREAD_NP_H) # include <pthread_np.h> #endif #include <inttypes.h> #include <sys/time.h> #if defined(HAVE_SYS_RESOURCE_H) # include <sys/resource.h> #endif #include <sys/statvfs.h> #include "toku_portability.h" #include "toku_os.h" #include "toku_time.h" #include "memory.h" int toku_portability_init(void) { int r = toku_memory_startup(); return r; } void toku_portability_destroy(void) { toku_memory_shutdown(); } int toku_os_getpid(void) { return getpid(); } int toku_os_gettid(void) { #if defined(__NR_gettid) return syscall(__NR_gettid); #elif defined(SYS_gettid) return syscall(SYS_gettid); #elif defined(HAVE_PTHREAD_GETTHREADID_NP) return pthread_getthreadid_np(); #else # error "no implementation of gettid available" #endif } int toku_os_get_number_processors(void) { return sysconf(_SC_NPROCESSORS_CONF); } int toku_os_get_number_active_processors(void) { int n = sysconf(_SC_NPROCESSORS_ONLN); #define DO_TOKU_NCPUS 1 #if DO_TOKU_NCPUS { char *toku_ncpus = getenv("TOKU_NCPUS"); if (toku_ncpus) { int ncpus = atoi(toku_ncpus); if (ncpus < n) n = ncpus; } } #endif return n; } int toku_os_get_pagesize(void) { return sysconf(_SC_PAGESIZE); } uint64_t toku_os_get_phys_memory_size(void) { #if defined(_SC_PHYS_PAGES) uint64_t npages = sysconf(_SC_PHYS_PAGES); uint64_t pagesize = sysconf(_SC_PAGESIZE); return npages*pagesize; #elif defined(HAVE_SYS_SYSCTL_H) uint64_t memsize; size_t len = sizeof memsize; sysctlbyname("hw.memsize", &memsize, &len, NULL, 0); return memsize; #else # error "cannot find _SC_PHYS_PAGES or sysctlbyname()" #endif } int toku_os_get_file_size(int fildes, int64_t *fsize) { toku_struct_stat sbuf; int r = fstat(fildes, &sbuf); if (r==0) { *fsize = sbuf.st_size; } return r; } int toku_os_get_unique_file_id(int fildes, struct fileid *id) { toku_struct_stat statbuf; memset(id, 0, sizeof(*id)); int r=fstat(fildes, &statbuf); if (r==0) { id->st_dev = statbuf.st_dev; id->st_ino = statbuf.st_ino; } return r; } int toku_os_lock_file(const char *name) { int r; int fd = open(name, O_RDWR|O_CREAT, S_IRUSR | S_IWUSR); if (fd>=0) { r = flock(fd, LOCK_EX | LOCK_NB); if (r!=0) { r = errno; //Save errno from flock. close(fd); fd = -1; //Disable fd. errno = r; } } return fd; } int toku_os_unlock_file(int fildes) { int r = flock(fildes, LOCK_UN); if (r==0) r = close(fildes); return r; } int toku_os_mkdir(const char *pathname, mode_t mode) { int r = mkdir(pathname, mode); return r; } int toku_os_get_process_times(struct timeval *usertime, struct timeval *kerneltime) { int r; struct rusage rusage; r = getrusage(RUSAGE_SELF, &rusage); if (r == -1) return get_error_errno(); if (usertime) *usertime = rusage.ru_utime; if (kerneltime) *kerneltime = rusage.ru_stime; return 0; } int toku_os_initialize_settings(int UU(verbosity)) { int r = 0; static int initialized = 0; assert(initialized==0); initialized=1; return r; } int toku_os_get_max_rss(int64_t *maxrss) { int r; char statusname[100]; sprintf(statusname, "/proc/%d/status", getpid()); FILE *f = fopen(statusname, "r"); if (f == NULL) { struct rusage rusage; r = getrusage(RUSAGE_SELF, &rusage); if (r != 0) { return get_error_errno(); } *maxrss = rusage.ru_maxrss * 1024; // ru_maxrss is in kB return 0; } r = ENOENT; char line[100]; while (fgets(line, sizeof line, f)) { r = sscanf(line, "VmHWM:\t%lld kB\n", (long long *) maxrss); if (r == 1) { *maxrss *= 1<<10; r = 0; break; } } fclose(f); return r; } int toku_os_get_rss(int64_t *rss) { int r; char statusname[100]; sprintf(statusname, "/proc/%d/status", getpid()); FILE *f = fopen(statusname, "r"); if (f == NULL) { struct rusage rusage; r = getrusage(RUSAGE_SELF, &rusage); if (r != 0) { return get_error_errno(); } *rss = (rusage.ru_idrss + rusage.ru_ixrss + rusage.ru_isrss) * 1024; return 0; } r = ENOENT; char line[100]; while (fgets(line, sizeof line, f)) { r = sscanf(line, "VmRSS:\t%lld kB\n", (long long *) rss); if (r == 1) { *rss *= 1<<10; r = 0; break; } } fclose(f); return r; } bool toku_os_is_absolute_name(const char* path) { return path[0] == '/'; } int toku_os_get_max_process_data_size(uint64_t *maxdata) { int r; struct rlimit rlimit; r = getrlimit(RLIMIT_DATA, &rlimit); if (r == 0) { uint64_t d; d = rlimit.rlim_max; // with the "right" macros defined, the rlimit is a 64 bit number on a // 32 bit system. getrlimit returns 2**64-1 which is clearly wrong. // for 32 bit processes, we assume that 1/2 of the address space is // used for mapping the kernel. this may be pessimistic. if (sizeof (void *) == 4 && d > (1ULL << 31)) d = 1ULL << 31; *maxdata = d; } else r = get_error_errno(); return r; } int toku_stat(const char *name, toku_struct_stat *buf) { int r = stat(name, buf); return r; } int toku_fstat(int fd, toku_struct_stat *buf) { int r = fstat(fd, buf); return r; } static int toku_get_processor_frequency_sys(uint64_t *hzret) { int r; FILE *fp = fopen("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq", "r"); if (!fp) r = get_error_errno(); else { unsigned int khz = 0; if (fscanf(fp, "%u", &khz) == 1) { *hzret = khz * 1000ULL; r = 0; } else r = ENOENT; fclose(fp); } return r; } static int toku_get_processor_frequency_cpuinfo(uint64_t *hzret) { int r; FILE *fp = fopen("/proc/cpuinfo", "r"); if (!fp) { r = get_error_errno(); } else { uint64_t maxhz = 0; char *buf = NULL; size_t n = 0; while (getline(&buf, &n, fp) >= 0) { unsigned int cpu; sscanf(buf, "processor : %u", &cpu); unsigned int ma, mb; if (sscanf(buf, "cpu MHz : %u.%u", &ma, &mb) == 2) { uint64_t hz = ma * 1000000ULL + mb * 1000ULL; if (hz > maxhz) maxhz = hz; } } if (buf) free(buf); fclose(fp); *hzret = maxhz; r = maxhz == 0 ? ENOENT : 0;; } return r; } static int toku_get_processor_frequency_sysctl(const char * const cmd, uint64_t *hzret) { int r = 0; FILE *fp = popen(cmd, "r"); if (!fp) { r = EINVAL; // popen doesn't return anything useful in errno, // gotta pick something goto exit; } r = fscanf(fp, "%" SCNu64, hzret); if (r != 1) { r = get_maybe_error_errno(); } else { r = 0; } pclose(fp); exit: return r; } int toku_os_get_processor_frequency(uint64_t *hzret) { int r; r = toku_get_processor_frequency_sys(hzret); if (r != 0) r = toku_get_processor_frequency_cpuinfo(hzret); if (r != 0) r = toku_get_processor_frequency_sysctl("sysctl -n hw.cpufrequency", hzret); if (r != 0) r = toku_get_processor_frequency_sysctl("sysctl -n machdep.tsc_freq", hzret); return r; } int toku_get_filesystem_sizes(const char *path, uint64_t *avail_size, uint64_t *free_size, uint64_t *total_size) { struct statvfs s; int r = statvfs(path, &s); if (r == -1) { r = get_error_errno(); } else { // get the block size in bytes uint64_t bsize = s.f_frsize ? s.f_frsize : s.f_bsize; // convert blocks to bytes if (avail_size) *avail_size = (uint64_t) s.f_bavail * bsize; if (free_size) *free_size = (uint64_t) s.f_bfree * bsize; if (total_size) *total_size = (uint64_t) s.f_blocks * bsize; } return r; } int toku_dup2(int fd, int fd2) { int r; r = dup2(fd, fd2); return r; } // Time static double seconds_per_clock = -1; double tokutime_to_seconds(tokutime_t t) { // Convert tokutime to seconds. if (seconds_per_clock<0) { uint64_t hz; int r = toku_os_get_processor_frequency(&hz); assert(r==0); // There's a race condition here, but it doesn't really matter. If two threads call tokutime_to_seconds // for the first time at the same time, then both will fetch the value and set the same value. seconds_per_clock = 1.0/hz; } return t*seconds_per_clock; } #if __GNUC__ && __i386__ // workaround for a gcc 4.1.2 bug on 32 bit platforms. uint64_t toku_sync_fetch_and_add_uint64(volatile uint64_t *a, uint64_t b) __attribute__((noinline)); uint64_t toku_sync_fetch_and_add_uint64(volatile uint64_t *a, uint64_t b) { return __sync_fetch_and_add(a, b); } #endif <|endoftext|>
<commit_before>// This file is part of Poseidon. // Copyleft 2020, LH_Mouse. All wrongs reserved. #ifndef POSEIDON_UTILITIES_HPP_ #define POSEIDON_UTILITIES_HPP_ #include "fwd.hpp" #include "static/async_logger.hpp" #include "core/abstract_timer.hpp" #include "static/timer_driver.hpp" #include <asteria/utilities.hpp> #include <cstdio> namespace poseidon { using ::asteria::utf8_encode; using ::asteria::utf8_decode; using ::asteria::utf16_encode; using ::asteria::utf16_decode; using ::asteria::format_string; using ::asteria::weaken_enum; using ::asteria::generate_random_seed; using ::asteria::format_errno; template<typename... ParamsT> ROCKET_NOINLINE bool do_xlog_format(Log_Level level, const char* file, long line, const char* func, const char* templ, const ParamsT&... params) noexcept try { // Compose the message. ::rocket::tinyfmt_str fmt; format(fmt, templ, params...); // ADL intended auto text = fmt.extract_string(); // Push a new log entry. Async_Logger::write(level, file, line, func, ::std::move(text)); return true; } catch(exception& stdex) { // Ignore this exception, but print a message. ::std::fprintf(stderr, "WARNING: %s: could not format log: %s\n[exception `%s` thrown from '%s:%ld'\n", func, stdex.what(), typeid(stdex).name(), file, line); return false; } // Note the format string must be a string literal. #define POSEIDON_XLOG_(level, ...) \ (::poseidon::Async_Logger::is_enabled(level) && \ ::poseidon::do_xlog_format(level, __FILE__, __LINE__, __func__, \ "" __VA_ARGS__)) #define POSEIDON_LOG_FATAL(...) POSEIDON_XLOG_(::poseidon::log_level_fatal, __VA_ARGS__) #define POSEIDON_LOG_ERROR(...) POSEIDON_XLOG_(::poseidon::log_level_error, __VA_ARGS__) #define POSEIDON_LOG_WARN(...) POSEIDON_XLOG_(::poseidon::log_level_warn, __VA_ARGS__) #define POSEIDON_LOG_INFO(...) POSEIDON_XLOG_(::poseidon::log_level_info, __VA_ARGS__) #define POSEIDON_LOG_DEBUG(...) POSEIDON_XLOG_(::poseidon::log_level_debug, __VA_ARGS__) #define POSEIDON_LOG_TRACE(...) POSEIDON_XLOG_(::poseidon::log_level_trace, __VA_ARGS__) template<typename... ParamsT> [[noreturn]] ROCKET_NOINLINE bool do_xthrow_format(const char* file, long line, const char* func, const char* templ, const ParamsT&... params) { // Compose the message. ::rocket::tinyfmt_str fmt; format(fmt, templ, params...); // ADL intended auto text = fmt.extract_string(); // Push a new log entry. if(Async_Logger::is_enabled(log_level_warn)) Async_Logger::write(log_level_warn, file, line, func, text); // Throw the exception. ::rocket::sprintf_and_throw<::std::runtime_error>( "%s: %s\n[thrown from '%s:%ld']", func, text.c_str(), file, line); } #define POSEIDON_THROW(...) \ (::poseidon::do_xthrow_format(__FILE__, __LINE__, __func__, \ "" __VA_ARGS__)) // Creates an asynchronous timer. The timer function will be called by // the timer thread, so thread safety must be taken into account. template<typename FuncT> rcptr<Abstract_Timer> create_async_timer(int64_t next, int64_t period, FuncT&& func) { // This is the concrete timer class. struct Concrete_Timer : Abstract_Timer { typename ::std::decay<FuncT>::type m_func; Concrete_Timer(int64_t next, int64_t period, FuncT&& func) : Abstract_Timer(next, period), m_func(::std::forward<FuncT>(func)) { } void do_on_async_timer(int64_t now) override { this->m_func(now); } }; // Allocate an abstract timer and insert it. auto timer = ::rocket::make_unique<Concrete_Timer>(next, period, ::std::forward<FuncT>(func)); return Timer_Driver::insert(::std::move(timer)); } // Creates a one-shot timer. The timer is deleted after being triggered. template<typename FuncT> rcptr<Abstract_Timer> create_async_timer_oneshot(int64_t next, FuncT&& func) { return noadl::create_async_timer(next, 0, ::std::forward<FuncT>(func)); } // Creates a periodic timer. template<typename FuncT> rcptr<Abstract_Timer> create_async_timer_periodic(int64_t period, FuncT&& func) { return noadl::create_async_timer(period, period, ::std::forward<FuncT>(func)); } } // namespace asteria #endif <commit_msg>utilities: Change log level of exceptions from WARN to DEBUG<commit_after>// This file is part of Poseidon. // Copyleft 2020, LH_Mouse. All wrongs reserved. #ifndef POSEIDON_UTILITIES_HPP_ #define POSEIDON_UTILITIES_HPP_ #include "fwd.hpp" #include "static/async_logger.hpp" #include "core/abstract_timer.hpp" #include "static/timer_driver.hpp" #include <asteria/utilities.hpp> #include <cstdio> namespace poseidon { using ::asteria::utf8_encode; using ::asteria::utf8_decode; using ::asteria::utf16_encode; using ::asteria::utf16_decode; using ::asteria::format_string; using ::asteria::weaken_enum; using ::asteria::generate_random_seed; using ::asteria::format_errno; template<typename... ParamsT> ROCKET_NOINLINE bool do_xlog_format(Log_Level level, const char* file, long line, const char* func, const char* templ, const ParamsT&... params) noexcept try { // Compose the message. ::rocket::tinyfmt_str fmt; format(fmt, templ, params...); // ADL intended auto text = fmt.extract_string(); // Push a new log entry. Async_Logger::write(level, file, line, func, ::std::move(text)); return true; } catch(exception& stdex) { // Ignore this exception, but print a message. ::std::fprintf(stderr, "WARNING: %s: could not format log: %s\n[exception `%s` thrown from '%s:%ld'\n", func, stdex.what(), typeid(stdex).name(), file, line); return false; } // Note the format string must be a string literal. #define POSEIDON_XLOG_(level, ...) \ (::poseidon::Async_Logger::is_enabled(level) && \ ::poseidon::do_xlog_format(level, __FILE__, __LINE__, __func__, \ "" __VA_ARGS__)) #define POSEIDON_LOG_FATAL(...) POSEIDON_XLOG_(::poseidon::log_level_fatal, __VA_ARGS__) #define POSEIDON_LOG_ERROR(...) POSEIDON_XLOG_(::poseidon::log_level_error, __VA_ARGS__) #define POSEIDON_LOG_WARN(...) POSEIDON_XLOG_(::poseidon::log_level_warn, __VA_ARGS__) #define POSEIDON_LOG_INFO(...) POSEIDON_XLOG_(::poseidon::log_level_info, __VA_ARGS__) #define POSEIDON_LOG_DEBUG(...) POSEIDON_XLOG_(::poseidon::log_level_debug, __VA_ARGS__) #define POSEIDON_LOG_TRACE(...) POSEIDON_XLOG_(::poseidon::log_level_trace, __VA_ARGS__) template<typename... ParamsT> [[noreturn]] ROCKET_NOINLINE bool do_xthrow_format(const char* file, long line, const char* func, const char* templ, const ParamsT&... params) { // Compose the message. ::rocket::tinyfmt_str fmt; format(fmt, templ, params...); // ADL intended auto text = fmt.extract_string(); // Push a new log entry. if(Async_Logger::is_enabled(log_level_debug)) Async_Logger::write(log_level_debug, file, line, func, text); // Throw the exception. ::rocket::sprintf_and_throw<::std::runtime_error>( "%s: %s\n[thrown from '%s:%ld']", func, text.c_str(), file, line); } #define POSEIDON_THROW(...) \ (::poseidon::do_xthrow_format(__FILE__, __LINE__, __func__, \ "" __VA_ARGS__)) // Creates an asynchronous timer. The timer function will be called by // the timer thread, so thread safety must be taken into account. template<typename FuncT> rcptr<Abstract_Timer> create_async_timer(int64_t next, int64_t period, FuncT&& func) { // This is the concrete timer class. struct Concrete_Timer : Abstract_Timer { typename ::std::decay<FuncT>::type m_func; Concrete_Timer(int64_t next, int64_t period, FuncT&& func) : Abstract_Timer(next, period), m_func(::std::forward<FuncT>(func)) { } void do_on_async_timer(int64_t now) override { this->m_func(now); } }; // Allocate an abstract timer and insert it. auto timer = ::rocket::make_unique<Concrete_Timer>(next, period, ::std::forward<FuncT>(func)); return Timer_Driver::insert(::std::move(timer)); } // Creates a one-shot timer. The timer is deleted after being triggered. template<typename FuncT> rcptr<Abstract_Timer> create_async_timer_oneshot(int64_t next, FuncT&& func) { return noadl::create_async_timer(next, 0, ::std::forward<FuncT>(func)); } // Creates a periodic timer. template<typename FuncT> rcptr<Abstract_Timer> create_async_timer_periodic(int64_t period, FuncT&& func) { return noadl::create_async_timer(period, period, ::std::forward<FuncT>(func)); } } // namespace asteria #endif <|endoftext|>
<commit_before>// This file is part of Poseidon. // Copyleft 2020, LH_Mouse. All wrongs reserved. #ifndef POSEIDON_UTILITIES_HPP_ #define POSEIDON_UTILITIES_HPP_ #include "fwd.hpp" #include "static/async_logger.hpp" #include "core/abstract_timer.hpp" #include "static/timer_driver.hpp" #include "core/abstract_async_job.hpp" #include "core/promise.hpp" #include "core/future.hpp" #include "static/worker_pool.hpp" #include <asteria/utilities.hpp> #include <cstdio> namespace poseidon { using ::asteria::utf8_encode; using ::asteria::utf8_decode; using ::asteria::utf16_encode; using ::asteria::utf16_decode; using ::asteria::format_string; using ::asteria::weaken_enum; using ::asteria::generate_random_seed; using ::asteria::format_errno; template<typename... ParamsT> ROCKET_NOINLINE bool do_xlog_format(Log_Level level, const char* file, long line, const char* func, const char* templ, const ParamsT&... params) noexcept try { // Compose the message. ::rocket::tinyfmt_str fmt; format(fmt, templ, params...); // ADL intended auto text = fmt.extract_string(); // Push a new log entry. Async_Logger::enqueue(level, file, line, func, ::std::move(text)); return true; } catch(exception& stdex) { // Ignore this exception, but print a message. ::std::fprintf(stderr, "WARNING: %s: could not format log: %s\n[exception `%s` thrown from '%s:%ld'\n", func, stdex.what(), typeid(stdex).name(), file, line); return false; } // Note the format string must be a string literal. #define POSEIDON_XLOG_(level, ...) \ (::poseidon::Async_Logger::is_enabled(level) && \ ::poseidon::do_xlog_format(level, __FILE__, __LINE__, __func__, \ "" __VA_ARGS__)) #define POSEIDON_LOG_FATAL(...) POSEIDON_XLOG_(::poseidon::log_level_fatal, __VA_ARGS__) #define POSEIDON_LOG_ERROR(...) POSEIDON_XLOG_(::poseidon::log_level_error, __VA_ARGS__) #define POSEIDON_LOG_WARN(...) POSEIDON_XLOG_(::poseidon::log_level_warn, __VA_ARGS__) #define POSEIDON_LOG_INFO(...) POSEIDON_XLOG_(::poseidon::log_level_info, __VA_ARGS__) #define POSEIDON_LOG_DEBUG(...) POSEIDON_XLOG_(::poseidon::log_level_debug, __VA_ARGS__) #define POSEIDON_LOG_TRACE(...) POSEIDON_XLOG_(::poseidon::log_level_trace, __VA_ARGS__) template<typename... ParamsT> [[noreturn]] ROCKET_NOINLINE bool do_xthrow_format(const char* file, long line, const char* func, const char* templ, const ParamsT&... params) { // Compose the message. ::rocket::tinyfmt_str fmt; format(fmt, templ, params...); // ADL intended auto text = fmt.extract_string(); // Push a new log entry. static constexpr auto level = log_level_warn; if(Async_Logger::is_enabled(level)) Async_Logger::enqueue(level, file, line, func, "POSEIDON_THROW: " + text); // Throw the exception. ::rocket::sprintf_and_throw<::std::runtime_error>( "%s: %s\n[thrown from '%s:%ld']", func, text.c_str(), file, line); } #define POSEIDON_THROW(...) \ (::poseidon::do_xthrow_format(__FILE__, __LINE__, __func__, \ "" __VA_ARGS__)) // Creates an asynchronous timer. The timer function will be called by // the timer thread, so thread safety must be taken into account. template<typename FuncT> rcptr<Abstract_Timer> create_async_timer(int64_t next, int64_t period, FuncT&& func) { // This is the concrete timer class. struct Concrete_Timer : Abstract_Timer { typename ::std::decay<FuncT>::type m_func; explicit Concrete_Timer(int64_t next, int64_t period, FuncT&& func) : Abstract_Timer(next, period), m_func(::std::forward<FuncT>(func)) { } void do_on_async_timer(int64_t now) override { this->m_func(now); } }; // Allocate an abstract timer and insert it. auto timer = ::rocket::make_unique<Concrete_Timer>(next, period, ::std::forward<FuncT>(func)); return Timer_Driver::insert(::std::move(timer)); } // Creates a one-shot timer. The timer is deleted after being triggered. template<typename FuncT> rcptr<Abstract_Timer> create_async_timer_oneshot(int64_t next, FuncT&& func) { return noadl::create_async_timer(next, 0, ::std::forward<FuncT>(func)); } // Creates a periodic timer. template<typename FuncT> rcptr<Abstract_Timer> create_async_timer_periodic(int64_t period, FuncT&& func) { return noadl::create_async_timer(period, period, ::std::forward<FuncT>(func)); } // Enqueues an asynchronous job and returns a future to its result. // Functions with the same key will always be delivered to the same worker. template<typename FuncT> futp<typename ::std::result_of<FuncT ()>::type> enqueue_async_job_keyed(uintptr_t key, FuncT&& func) { // // This is the concrete function class. struct Concrete_Async_Job : Abstract_Async_Job { prom<typename ::std::result_of<FuncT ()>::type> m_prom; typename ::std::decay<FuncT>::type m_func; explicit Concrete_Async_Job(uintptr_t key, FuncT&& func) : Abstract_Async_Job(key), m_func(::std::forward<FuncT>(func)) { } void do_execute() override { this->m_prom.set_value(this->m_func()); } void do_set_exception(const ::std::exception_ptr& eptr) override { this->m_prom.set_exception(eptr); } }; // Allocate a function object. auto async = ::rocket::make_unique<Concrete_Async_Job>(key, ::std::forward<FuncT>(func)); auto futr = async->m_prom.future(); Worker_Pool::insert(::std::move(async)); return futr; } // Enqueues an asynchronous job and returns a future to its result. // The function is delivered to a random worker. template<typename FuncT> futp<typename ::std::result_of<FuncT ()>::type> enqueue_async_job_random(FuncT&& func) { // // This is the concrete function class. struct Concrete_Async_Job : Abstract_Async_Job { prom<typename ::std::result_of<FuncT ()>::type> m_prom; typename ::std::decay<FuncT>::type m_func; explicit Concrete_Async_Job(FuncT&& func) : Abstract_Async_Job(reinterpret_cast<uintptr_t>(this)), m_func(::std::forward<FuncT>(func)) { } void do_execute() override { this->m_prom.set_value(this->m_func()); } void do_set_exception(const ::std::exception_ptr& eptr) override { this->m_prom.set_exception(eptr); } }; // Allocate a function object. auto async = ::rocket::make_unique<Concrete_Async_Job>( ::std::forward<FuncT>(func)); auto futr = async->m_prom.future(); Worker_Pool::insert(::std::move(async)); return futr; } } // namespace asteria #endif <commit_msg>utilities: Reformat<commit_after>// This file is part of Poseidon. // Copyleft 2020, LH_Mouse. All wrongs reserved. #ifndef POSEIDON_UTILITIES_HPP_ #define POSEIDON_UTILITIES_HPP_ #include "fwd.hpp" #include "static/async_logger.hpp" #include "core/abstract_timer.hpp" #include "static/timer_driver.hpp" #include "core/abstract_async_job.hpp" #include "core/promise.hpp" #include "core/future.hpp" #include "static/worker_pool.hpp" #include <asteria/utilities.hpp> #include <cstdio> namespace poseidon { using ::asteria::utf8_encode; using ::asteria::utf8_decode; using ::asteria::utf16_encode; using ::asteria::utf16_decode; using ::asteria::format_string; using ::asteria::weaken_enum; using ::asteria::generate_random_seed; using ::asteria::format_errno; template<typename... ParamsT> ROCKET_NOINLINE bool do_xlog_format(Log_Level level, const char* file, long line, const char* func, const char* templ, const ParamsT&... params) noexcept try { // Compose the message. ::rocket::tinyfmt_str fmt; format(fmt, templ, params...); // ADL intended auto text = fmt.extract_string(); // Push a new log entry. Async_Logger::enqueue(level, file, line, func, ::std::move(text)); return true; } catch(exception& stdex) { // Ignore this exception, but print a message. ::std::fprintf(stderr, "WARNING: %s: could not format log: %s\n[exception `%s` thrown from '%s:%ld'\n", func, stdex.what(), typeid(stdex).name(), file, line); return false; } // Note the format string must be a string literal. #define POSEIDON_XLOG_(level, ...) \ (::poseidon::Async_Logger::is_enabled(level) && \ ::poseidon::do_xlog_format(level, __FILE__, __LINE__, __func__, \ "" __VA_ARGS__)) #define POSEIDON_LOG_FATAL(...) POSEIDON_XLOG_(::poseidon::log_level_fatal, __VA_ARGS__) #define POSEIDON_LOG_ERROR(...) POSEIDON_XLOG_(::poseidon::log_level_error, __VA_ARGS__) #define POSEIDON_LOG_WARN(...) POSEIDON_XLOG_(::poseidon::log_level_warn, __VA_ARGS__) #define POSEIDON_LOG_INFO(...) POSEIDON_XLOG_(::poseidon::log_level_info, __VA_ARGS__) #define POSEIDON_LOG_DEBUG(...) POSEIDON_XLOG_(::poseidon::log_level_debug, __VA_ARGS__) #define POSEIDON_LOG_TRACE(...) POSEIDON_XLOG_(::poseidon::log_level_trace, __VA_ARGS__) template<typename... ParamsT> [[noreturn]] ROCKET_NOINLINE bool do_xthrow_format(const char* file, long line, const char* func, const char* templ, const ParamsT&... params) { // Compose the message. ::rocket::tinyfmt_str fmt; format(fmt, templ, params...); // ADL intended auto text = fmt.extract_string(); // Push a new log entry. static constexpr auto level = log_level_warn; if(Async_Logger::is_enabled(level)) Async_Logger::enqueue(level, file, line, func, "POSEIDON_THROW: " + text); // Throw the exception. ::rocket::sprintf_and_throw<::std::runtime_error>( "%s: %s\n[thrown from '%s:%ld']", func, text.c_str(), file, line); } #define POSEIDON_THROW(...) \ (::poseidon::do_xthrow_format(__FILE__, __LINE__, __func__, \ "" __VA_ARGS__)) // Creates an asynchronous timer. The timer function will be called by // the timer thread, so thread safety must be taken into account. template<typename FuncT> rcptr<Abstract_Timer> create_async_timer(int64_t next, int64_t period, FuncT&& func) { // This is the concrete timer class. struct Concrete_Timer : Abstract_Timer { typename ::std::decay<FuncT>::type m_func; explicit Concrete_Timer(int64_t next, int64_t period, FuncT&& func) : Abstract_Timer(next, period), m_func(::std::forward<FuncT>(func)) { } void do_on_async_timer(int64_t now) override { this->m_func(now); } }; // Allocate an abstract timer and insert it. auto timer = ::rocket::make_unique<Concrete_Timer>(next, period, ::std::forward<FuncT>(func)); return Timer_Driver::insert(::std::move(timer)); } // Creates a one-shot timer. The timer is deleted after being triggered. template<typename FuncT> rcptr<Abstract_Timer> create_async_timer_oneshot(int64_t next, FuncT&& func) { return noadl::create_async_timer(next, 0, ::std::forward<FuncT>(func)); } // Creates a periodic timer. template<typename FuncT> rcptr<Abstract_Timer> create_async_timer_periodic(int64_t period, FuncT&& func) { return noadl::create_async_timer(period, period, ::std::forward<FuncT>(func)); } // Enqueues an asynchronous job and returns a future to its result. // Functions with the same key will always be delivered to the same worker. template<typename FuncT> futp<typename ::std::result_of<FuncT ()>::type> enqueue_async_job_keyed(uintptr_t key, FuncT&& func) { // // This is the concrete function class. struct Concrete_Async_Job : Abstract_Async_Job { prom<typename ::std::result_of<FuncT ()>::type> m_prom; typename ::std::decay<FuncT>::type m_func; explicit Concrete_Async_Job(uintptr_t key, FuncT&& func) : Abstract_Async_Job(key), m_func(::std::forward<FuncT>(func)) { } void do_execute() override { this->m_prom.set_value(this->m_func()); } void do_set_exception(const ::std::exception_ptr& eptr) override { this->m_prom.set_exception(eptr); } }; // Allocate a function object. auto async = ::rocket::make_unique<Concrete_Async_Job>(key, ::std::forward<FuncT>(func)); auto futr = async->m_prom.future(); Worker_Pool::insert(::std::move(async)); return futr; } // Enqueues an asynchronous job and returns a future to its result. // The function is delivered to a random worker. template<typename FuncT> futp<typename ::std::result_of<FuncT ()>::type> enqueue_async_job_random(FuncT&& func) { // // This is the concrete function class. struct Concrete_Async_Job : Abstract_Async_Job { prom<typename ::std::result_of<FuncT ()>::type> m_prom; typename ::std::decay<FuncT>::type m_func; explicit Concrete_Async_Job(FuncT&& func) : Abstract_Async_Job(reinterpret_cast<uintptr_t>(this)), m_func(::std::forward<FuncT>(func)) { } void do_execute() override { this->m_prom.set_value(this->m_func()); } void do_set_exception(const ::std::exception_ptr& eptr) override { this->m_prom.set_exception(eptr); } }; // Allocate a function object. auto async = ::rocket::make_unique<Concrete_Async_Job>( ::std::forward<FuncT>(func)); auto futr = async->m_prom.future(); Worker_Pool::insert(::std::move(async)); return futr; } } // namespace asteria #endif <|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 "ppapi/cpp/paint_manager.h" #include "ppapi/c/pp_errors.h" #include "ppapi/cpp/instance.h" #include "ppapi/cpp/logging.h" #include "ppapi/cpp/module.h" namespace pp { PaintManager::PaintManager() : instance_(NULL), client_(NULL), is_always_opaque_(false), callback_factory_(NULL) { // Set the callback object outside of the initializer list to avoid a // compiler warning about using "this" in an initializer list. callback_factory_.Initialize(this); } PaintManager::PaintManager(Instance* instance, Client* client, bool is_always_opaque) : instance_(instance), client_(client), is_always_opaque_(is_always_opaque), callback_factory_(NULL) { // Set the callback object outside of the initializer list to avoid a // compiler warning about using "this" in an initializer list. callback_factory_.Initialize(this); // You can not use a NULL client pointer. PP_DCHECK(client); } PaintManager::~PaintManager() { } void PaintManager::Initialize(Instance* instance, Client* client, bool is_always_opaque) { PP_DCHECK(!instance_ && !client_); // Can't initialize twice. instance_ = instance; client_ = client; is_always_opaque_ = is_always_opaque; } void PaintManager::SetSize(const Size& new_size) { if (new_size == graphics_.size()) return; graphics_ = Graphics2D(new_size, is_always_opaque_); if (graphics_.is_null()) return; instance_->BindGraphics(graphics_); manual_callback_pending_ = false; flush_pending_ = false; callback_factory_.CancelAll(); Invalidate(); } void PaintManager::Invalidate() { // You must call SetDevice before using. PP_DCHECK(!graphics_.is_null()); EnsureCallbackPending(); aggregator_.InvalidateRect(Rect(graphics_.size())); } void PaintManager::InvalidateRect(const Rect& rect) { // You must call SetDevice before using. PP_DCHECK(!graphics_.is_null()); // Clip the rect to the device area. Rect clipped_rect = rect.Intersect(Rect(graphics_.size())); if (clipped_rect.IsEmpty()) return; // Nothing to do. EnsureCallbackPending(); aggregator_.InvalidateRect(clipped_rect); } void PaintManager::ScrollRect(const Rect& clip_rect, const Point& amount) { // You must call SetDevice before using. PP_DCHECK(!graphics_.is_null()); EnsureCallbackPending(); aggregator_.ScrollRect(clip_rect, amount); } void PaintManager::EnsureCallbackPending() { // The best way for us to do the next update is to get a notification that // a previous one has completed. So if we're already waiting for one, we // don't have to do anything differently now. if (flush_pending_) return; // If no flush is pending, we need to do a manual call to get back to the // main thread. We may have one already pending, or we may need to schedule. if (manual_callback_pending_) return; Module::Get()->core()->CallOnMainThread( 0, callback_factory_.NewCallback(&PaintManager::OnManualCallbackComplete), 0); manual_callback_pending_ = true; } void PaintManager::DoPaint() { PP_DCHECK(aggregator_.HasPendingUpdate()); // Make a copy of the pending update and clear the pending update flag before // actually painting. A plugin might cause invalidates in its Paint code, and // we want those to go to the *next* paint. PaintAggregator::PaintUpdate update = aggregator_.GetPendingUpdate(); aggregator_.ClearPendingUpdate(); // Apply any scroll before asking the client to paint. if (update.has_scroll) graphics_.Scroll(update.scroll_rect, update.scroll_delta); if (!client_->OnPaint(graphics_, update.paint_rects, update.paint_bounds)) return; // Nothing was painted, don't schedule a flush. int32_t result = graphics_.Flush( callback_factory_.NewCallback(&PaintManager::OnFlushComplete)); // If you trigger this assertion, then your plugin has called Flush() // manually. When using the PaintManager, you should not call Flush, it will // handle that for you because it needs to know when it can do the next paint // by implementing the flush callback. // // Another possible cause of this assertion is re-using devices. If you // use one device, swap it with another, then swap it back, we won't know // that we've already scheduled a Flush on the first device. It's best to not // re-use devices in this way. PP_DCHECK(result != PP_ERROR_INPROGRESS); if (result == PP_ERROR_WOULDBLOCK) { flush_pending_ = true; } else { PP_DCHECK(result == PP_OK); // Catch all other errors in debug mode. } } void PaintManager::OnFlushComplete(int32_t) { PP_DCHECK(flush_pending_); flush_pending_ = false; // If more paints were enqueued while we were waiting for the flush to // complete, execute them now. if (aggregator_.HasPendingUpdate()) DoPaint(); } void PaintManager::OnManualCallbackComplete(int32_t) { PP_DCHECK(manual_callback_pending_); manual_callback_pending_ = false; // Just because we have a manual callback doesn't mean there are actually any // invalid regions. Even though we only schedule this callback when something // is pending, a Flush callback could have come in before this callback was // executed and that could have cleared the queue. if (aggregator_.HasPendingUpdate()) DoPaint(); } } // namespace pp <commit_msg>Fix some bugs in paint manager. Some of the class members were not getting initialized in the constructor.<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 "ppapi/cpp/paint_manager.h" #include "ppapi/c/pp_errors.h" #include "ppapi/cpp/instance.h" #include "ppapi/cpp/logging.h" #include "ppapi/cpp/module.h" namespace pp { PaintManager::PaintManager() : instance_(NULL), client_(NULL), is_always_opaque_(false), callback_factory_(NULL), manual_callback_pending_(false), flush_pending_(false) { // Set the callback object outside of the initializer list to avoid a // compiler warning about using "this" in an initializer list. callback_factory_.Initialize(this); } PaintManager::PaintManager(Instance* instance, Client* client, bool is_always_opaque) : instance_(instance), client_(client), is_always_opaque_(is_always_opaque), callback_factory_(NULL), manual_callback_pending_(false), flush_pending_(false) { // Set the callback object outside of the initializer list to avoid a // compiler warning about using "this" in an initializer list. callback_factory_.Initialize(this); // You can not use a NULL client pointer. PP_DCHECK(client); } PaintManager::~PaintManager() { } void PaintManager::Initialize(Instance* instance, Client* client, bool is_always_opaque) { PP_DCHECK(!instance_ && !client_); // Can't initialize twice. instance_ = instance; client_ = client; is_always_opaque_ = is_always_opaque; } void PaintManager::SetSize(const Size& new_size) { if (new_size == graphics_.size()) return; graphics_ = Graphics2D(new_size, is_always_opaque_); if (graphics_.is_null()) return; instance_->BindGraphics(graphics_); manual_callback_pending_ = false; flush_pending_ = false; callback_factory_.CancelAll(); Invalidate(); } void PaintManager::Invalidate() { // You must call SetDevice before using. PP_DCHECK(!graphics_.is_null()); EnsureCallbackPending(); aggregator_.InvalidateRect(Rect(graphics_.size())); } void PaintManager::InvalidateRect(const Rect& rect) { // You must call SetDevice before using. PP_DCHECK(!graphics_.is_null()); // Clip the rect to the device area. Rect clipped_rect = rect.Intersect(Rect(graphics_.size())); if (clipped_rect.IsEmpty()) return; // Nothing to do. EnsureCallbackPending(); aggregator_.InvalidateRect(clipped_rect); } void PaintManager::ScrollRect(const Rect& clip_rect, const Point& amount) { // You must call SetDevice before using. PP_DCHECK(!graphics_.is_null()); EnsureCallbackPending(); aggregator_.ScrollRect(clip_rect, amount); } void PaintManager::EnsureCallbackPending() { // The best way for us to do the next update is to get a notification that // a previous one has completed. So if we're already waiting for one, we // don't have to do anything differently now. if (flush_pending_) return; // If no flush is pending, we need to do a manual call to get back to the // main thread. We may have one already pending, or we may need to schedule. if (manual_callback_pending_) return; Module::Get()->core()->CallOnMainThread( 0, callback_factory_.NewCallback(&PaintManager::OnManualCallbackComplete), 0); manual_callback_pending_ = true; } void PaintManager::DoPaint() { PP_DCHECK(aggregator_.HasPendingUpdate()); // Make a copy of the pending update and clear the pending update flag before // actually painting. A plugin might cause invalidates in its Paint code, and // we want those to go to the *next* paint. PaintAggregator::PaintUpdate update = aggregator_.GetPendingUpdate(); aggregator_.ClearPendingUpdate(); // Apply any scroll before asking the client to paint. if (update.has_scroll) graphics_.Scroll(update.scroll_rect, update.scroll_delta); if (!client_->OnPaint(graphics_, update.paint_rects, update.paint_bounds)) return; // Nothing was painted, don't schedule a flush. int32_t result = graphics_.Flush( callback_factory_.NewCallback(&PaintManager::OnFlushComplete)); // If you trigger this assertion, then your plugin has called Flush() // manually. When using the PaintManager, you should not call Flush, it will // handle that for you because it needs to know when it can do the next paint // by implementing the flush callback. // // Another possible cause of this assertion is re-using devices. If you // use one device, swap it with another, then swap it back, we won't know // that we've already scheduled a Flush on the first device. It's best to not // re-use devices in this way. PP_DCHECK(result != PP_ERROR_INPROGRESS); if (result == PP_ERROR_WOULDBLOCK) { flush_pending_ = true; } else { PP_DCHECK(result == PP_OK); // Catch all other errors in debug mode. } } void PaintManager::OnFlushComplete(int32_t) { PP_DCHECK(flush_pending_); flush_pending_ = false; // If more paints were enqueued while we were waiting for the flush to // complete, execute them now. if (aggregator_.HasPendingUpdate()) DoPaint(); } void PaintManager::OnManualCallbackComplete(int32_t) { PP_DCHECK(manual_callback_pending_); manual_callback_pending_ = false; // Just because we have a manual callback doesn't mean there are actually any // invalid regions. Even though we only schedule this callback when something // is pending, a Flush callback could have come in before this callback was // executed and that could have cleared the queue. if (aggregator_.HasPendingUpdate() && !flush_pending_) DoPaint(); } } // namespace pp <|endoftext|>
<commit_before>#include "main.hpp" int main() { std::ofstream out("log.txt"); std::streambuf *coutbuf = std::cout.rdbuf(); std::cout.rdbuf(out.rdbuf()); fn::Coord::width = 800; fn::Coord::height = 600; fn::Coord::baseWidth = 800; fn::Coord::baseHeight = 600; sf::RenderWindow window(sf::VideoMode(800, 600), "", sf::Style::None); window.setMouseCursorVisible(false); sf::RectangleShape windowBorder(sf::Vector2f(798, 598)); windowBorder.setPosition(1, 1); windowBorder.setFillColor(sf::Color(40, 40, 40)); windowBorder.setOutlineColor(sf::Color::White); windowBorder.setOutlineThickness(1); sf::Vertex linetop[] = { sf::Vertex(sf::Vector2f(0, 60)), sf::Vertex(sf::Vector2f(800, 60)) }; sf::Vertex linemiddle[] = { sf::Vertex(sf::Vector2f(0, 450)), sf::Vertex(sf::Vector2f(800, 450)) }; sf::Vertex linebottom[] = { sf::Vertex(sf::Vector2f(0, 550)), sf::Vertex(sf::Vector2f(800, 550)) }; sf::Event sfevent; GUI::Container gui(&sfevent, &window, 800, 600); GUI::WidgetContainer* mainContainer = gui.createWidgetContainer("main", 1, 0, 0, 800, 600, GUI::ContainerMovement::Fixed, 0, 0); GUI::WidgetContainer* infoContainer = gui.createWidgetContainer("info", 1, 0, 60, 800, 390, GUI::ContainerMovement::Fixed, 0, 0); GUI::WidgetContainer* stgsContainer = gui.createWidgetContainer("stgs", 1, 0, 60, 800, 390, GUI::ContainerMovement::Fixed, 0, 0); GUI::WidgetContainer* logsContainer = gui.createWidgetContainer("logs", 1, 0, 450, 800, 100, GUI::ContainerMovement::Fixed, 0, 0); Cursor curs; curs.initialize(&window); sf::Font font; font.loadFromFile("Data/Fonts/weblysleekuil.ttf"); //Main UI gui.createLabel("main", "titleLbl", 10, 10, "Melting Saga Updater", "weblysleekuil.ttf", 32, sf::Color::White); gui.createLabel("main", "updaterVerLbl", 400, 10, "Updater : <Nightly> v1.0.5", "weblysleekuil.ttf", 12, sf::Color::White); gui.createLabel("main", "updaterVerLbl", 400, 30, "Game : <Nightly> v0.0.1", "weblysleekuil.ttf", 12, sf::Color::White); gui.createCheckbox("main", "settingsBtn", 700, 15, "SETTINGS", false); gui.createButton("main", "quitBtn", 750, 15, true, true, "QUIT"); gui.createButton("main", "updateBtn", 600, 560, true, true, "GREY"); gui.createLoadingBar("main", "updateBar", 10, 560, "UPDATER"); gui.createLabel("main", "updateBarLbl", 300, 560, "80%", "weblysleekuil.ttf", 24, sf::Color::White); //Infos UI gui.createLabel("info", "updateInfosTitleLbl", 10, 10, "Update Informations : ", "weblysleekuil.ttf", 24, sf::Color::Cyan); gui.createLabel("info", "updateInfosContLbl", 30, 45, "", "weblysleekuil.ttf", 16, sf::Color::White); std::ifstream changelogFile("changelog.txt"); std::string updateContent((std::istreambuf_iterator<char>(changelogFile)), std::istreambuf_iterator<char>()); GUI::Widget::getWidgetByID<GUI::Label>("updateInfosContLbl")->setComplexText(updateContent); infoContainer->addScrollBar(); gui.createScrollBar("info", "updateScrollBar", 790, 0, 400, 50, false, infoContainer, "V2"); GUI::Widget::getWidgetByID<GUI::ScrollBar>("updateScrollBar")->computeDynamicScroll(); //Settings UI gui.createLabel("stgs", "settingsTitleLbl", 10, 10, "Settings : ", "weblysleekuil.ttf", 24, sf::Color::Cyan); //Logs UI gui.createLabel("logs", "logsTitleLbl", 10, 10, "Logs : ", "weblysleekuil.ttf", 24, sf::Color::Cyan); gui.createLabel("logs", "logsContLbl", 10, 45, "lolibork", "weblysleekuil.ttf", 16, sf::Color::White); GUI::Widget::getWidgetByID<GUI::Label>("logsContLbl")->setComplexText("<color:255,255,255>Connection to MeSa Server : 132.14.88.22:9022 [ " "<color:0,255,0>Done" "<color:255,255,255> ]\n" "GET : changelog.txt 200 OK [ " "<color:0,255,0>Done" "<color:255,255,255> ]\n"); GUI::ButtonEvent* appQuitBool = GUI::Widget::getWidgetByID<GUI::Button>("quitBtn")->getHook(); bool* appSettingsBool = GUI::Widget::getWidgetByID<GUI::Checkbox>("settingsBtn")->getHook(); GUI::Widget::getWidgetByID<GUI::Button>("updateBtn")->setText("Update", "weblysleekuil.ttf", sf::Color::White, 18, true, 0, -3); GUI::Widget::getWidgetByID<GUI::LoadingBar>("updateBar")->fill(80, 2); sf::Vector2i grabbedOffset; bool grabbedWindow = false; while (window.isOpen()) { while (window.pollEvent(sfevent)) { if (sfevent.type == sf::Event::Closed) window.close(); else if (sfevent.type == sf::Event::KeyPressed) { if (sfevent.key.code == sf::Keyboard::Escape) window.close(); } else if (sfevent.type == sf::Event::MouseButtonPressed) { if (sf::Mouse::getPosition().y - window.getPosition().y < 60 && sf::Mouse::getPosition().x - window.getPosition().x < 680) { if (sfevent.mouseButton.button == sf::Mouse::Left) { grabbedOffset = window.getPosition() - sf::Mouse::getPosition(); grabbedWindow = true; } } } else if (sfevent.type == sf::Event::MouseButtonReleased) { if (sfevent.mouseButton.button == sf::Mouse::Left) grabbedWindow = false; } else if (sfevent.type == sf::Event::MouseMoved) { if (grabbedWindow) window.setPosition(sf::Mouse::getPosition() + grabbedOffset); } } gui.updateAllContainer(); curs.update(); if (*appQuitBool == GUI::ButtonEvent::Pressed) {window.close();} if (*appSettingsBool) { gui.getContainerByContainerName("info")->setDisplayed(false); gui.getContainerByContainerName("stgs")->setDisplayed(true); } else { gui.getContainerByContainerName("info")->setDisplayed(true); gui.getContainerByContainerName("stgs")->setDisplayed(false); } window.clear(sf::Color(40, 40, 40)); window.draw(windowBorder); gui.drawAllContainer(&window); window.draw(linetop, 2, sf::Lines); window.draw(linemiddle, 2, sf::Lines); window.draw(linebottom, 2, sf::Lines); window.draw(*curs.getSprite()); window.display(); } }<commit_msg>Removed double scrollbar<commit_after>#include "main.hpp" int main() { std::ofstream out("log.txt"); std::streambuf *coutbuf = std::cout.rdbuf(); std::cout.rdbuf(out.rdbuf()); fn::Coord::width = 800; fn::Coord::height = 600; fn::Coord::baseWidth = 800; fn::Coord::baseHeight = 600; sf::RenderWindow window(sf::VideoMode(800, 600), "", sf::Style::None); window.setMouseCursorVisible(false); sf::RectangleShape windowBorder(sf::Vector2f(798, 598)); windowBorder.setPosition(1, 1); windowBorder.setFillColor(sf::Color(40, 40, 40)); windowBorder.setOutlineColor(sf::Color::White); windowBorder.setOutlineThickness(1); sf::Vertex linetop[] = { sf::Vertex(sf::Vector2f(0, 60)), sf::Vertex(sf::Vector2f(800, 60)) }; sf::Vertex linemiddle[] = { sf::Vertex(sf::Vector2f(0, 450)), sf::Vertex(sf::Vector2f(800, 450)) }; sf::Vertex linebottom[] = { sf::Vertex(sf::Vector2f(0, 550)), sf::Vertex(sf::Vector2f(800, 550)) }; sf::Event sfevent; GUI::Container gui(&sfevent, &window, 800, 600); GUI::WidgetContainer* mainContainer = gui.createWidgetContainer("main", 1, 0, 0, 800, 600, GUI::ContainerMovement::Fixed, 0, 0); GUI::WidgetContainer* infoContainer = gui.createWidgetContainer("info", 1, 0, 60, 800, 390, GUI::ContainerMovement::Fixed, 0, 0); GUI::WidgetContainer* stgsContainer = gui.createWidgetContainer("stgs", 1, 0, 60, 800, 390, GUI::ContainerMovement::Fixed, 0, 0); GUI::WidgetContainer* logsContainer = gui.createWidgetContainer("logs", 1, 0, 450, 800, 100, GUI::ContainerMovement::Fixed, 0, 0); Cursor curs; curs.initialize(&window); sf::Font font; font.loadFromFile("Data/Fonts/weblysleekuil.ttf"); //Main UI gui.createLabel("main", "titleLbl", 10, 10, "Melting Saga Updater", "weblysleekuil.ttf", 32, sf::Color::White); gui.createLabel("main", "updaterVerLbl", 400, 10, "Updater : <Nightly> v1.0.5", "weblysleekuil.ttf", 12, sf::Color::White); gui.createLabel("main", "updaterVerLbl", 400, 30, "Game : <Nightly> v0.0.1", "weblysleekuil.ttf", 12, sf::Color::White); gui.createCheckbox("main", "settingsBtn", 700, 15, "SETTINGS", false); gui.createButton("main", "quitBtn", 750, 15, true, true, "QUIT"); gui.createButton("main", "updateBtn", 600, 560, true, true, "GREY"); gui.createLoadingBar("main", "updateBar", 10, 560, "UPDATER"); gui.createLabel("main", "updateBarLbl", 300, 560, "80%", "weblysleekuil.ttf", 24, sf::Color::White); //Infos UI gui.createLabel("info", "updateInfosTitleLbl", 10, 10, "Update Informations : ", "weblysleekuil.ttf", 24, sf::Color::Cyan); gui.createLabel("info", "updateInfosContLbl", 30, 45, "", "weblysleekuil.ttf", 16, sf::Color::White); std::ifstream changelogFile("changelog.txt"); std::string updateContent((std::istreambuf_iterator<char>(changelogFile)), std::istreambuf_iterator<char>()); GUI::Widget::getWidgetByID<GUI::Label>("updateInfosContLbl")->setComplexText(updateContent); infoContainer->addScrollBar(); //Settings UI gui.createLabel("stgs", "settingsTitleLbl", 10, 10, "Settings : ", "weblysleekuil.ttf", 24, sf::Color::Cyan); //Logs UI gui.createLabel("logs", "logsTitleLbl", 10, 10, "Logs : ", "weblysleekuil.ttf", 24, sf::Color::Cyan); gui.createLabel("logs", "logsContLbl", 10, 45, "lolibork", "weblysleekuil.ttf", 16, sf::Color::White); GUI::Widget::getWidgetByID<GUI::Label>("logsContLbl")->setComplexText("<color:255,255,255>Connection to MeSa Server : 132.14.88.22:9022 [ " "<color:0,255,0>Done" "<color:255,255,255> ]\n" "GET : changelog.txt 200 OK [ " "<color:0,255,0>Done" "<color:255,255,255> ]\n"); GUI::ButtonEvent* appQuitBool = GUI::Widget::getWidgetByID<GUI::Button>("quitBtn")->getHook(); bool* appSettingsBool = GUI::Widget::getWidgetByID<GUI::Checkbox>("settingsBtn")->getHook(); GUI::Widget::getWidgetByID<GUI::Button>("updateBtn")->setText("Update", "weblysleekuil.ttf", sf::Color::White, 18, true, 0, -3); GUI::Widget::getWidgetByID<GUI::LoadingBar>("updateBar")->fill(80, 2); sf::Vector2i grabbedOffset; bool grabbedWindow = false; while (window.isOpen()) { while (window.pollEvent(sfevent)) { if (sfevent.type == sf::Event::Closed) window.close(); else if (sfevent.type == sf::Event::KeyPressed) { if (sfevent.key.code == sf::Keyboard::Escape) window.close(); } else if (sfevent.type == sf::Event::MouseButtonPressed) { if (sf::Mouse::getPosition().y - window.getPosition().y < 60 && sf::Mouse::getPosition().x - window.getPosition().x < 680) { if (sfevent.mouseButton.button == sf::Mouse::Left) { grabbedOffset = window.getPosition() - sf::Mouse::getPosition(); grabbedWindow = true; } } } else if (sfevent.type == sf::Event::MouseButtonReleased) { if (sfevent.mouseButton.button == sf::Mouse::Left) grabbedWindow = false; } else if (sfevent.type == sf::Event::MouseMoved) { if (grabbedWindow) window.setPosition(sf::Mouse::getPosition() + grabbedOffset); } } gui.updateAllContainer(); curs.update(); if (*appQuitBool == GUI::ButtonEvent::Pressed) {window.close();} if (*appSettingsBool) { gui.getContainerByContainerName("info")->setDisplayed(false); gui.getContainerByContainerName("stgs")->setDisplayed(true); } else { gui.getContainerByContainerName("info")->setDisplayed(true); gui.getContainerByContainerName("stgs")->setDisplayed(false); } window.clear(sf::Color(40, 40, 40)); window.draw(windowBorder); gui.drawAllContainer(&window); window.draw(linetop, 2, sf::Lines); window.draw(linemiddle, 2, sf::Lines); window.draw(linebottom, 2, sf::Lines); window.draw(*curs.getSprite()); window.display(); } }<|endoftext|>
<commit_before>/* * This is part of the FL library, a C++ Bayesian filtering library * (https://github.com/filtering-library) * * Copyright (c) 2014 Jan Issac ([email protected]) * Copyright (c) 2014 Manuel Wuthrich ([email protected]) * * Max-Planck Institute for Intelligent Systems, AMD Lab * University of Southern California, CLMC Lab * * This Source Code Form is subject to the terms of the MIT License (MIT). * A copy of the license can be found in the LICENSE file distributed with this * source code. */ /** * \file linear_decorrelated_gaussian_observation_model.hpp * \date October 2014 * \author Jan Issac ([email protected]) */ #ifndef FL__MODEL__OBSERVATION__LINEAR_DECORRELATED_GAUSSIAN_OBSERVATION_MODEL_HPP #define FL__MODEL__OBSERVATION__LINEAR_DECORRELATED_GAUSSIAN_OBSERVATION_MODEL_HPP #include <fl/util/traits.hpp> #include <fl/util/types.hpp> #include <fl/util/descriptor.hpp> #include <fl/distribution/decorrelated_gaussian.hpp> #include <fl/model/observation/linear_observation_model.hpp> #include <fl/model/observation/interface/additive_uncorrelated_observation_function.hpp> namespace fl { /** * \ingroup observation_models */ template <typename Obsrv, typename State> class LinearDecorrelatedGaussianObservationModel : public AdditiveUncorrelatedNoiseModel<DecorrelatedGaussian<Obsrv>>, public AdditiveObservationFunction<Obsrv, State, Gaussian<Obsrv>>, public Descriptor, private internal::LinearModelType { public: // specify the main type of this model typedef internal::AdditiveUncorrelatedNoiseModelType Type; typedef AdditiveUncorrelatedNoiseModel< DecorrelatedGaussian<Obsrv> > AdditiveUncorrelatedInterface; typedef AdditiveObservationFunction< Obsrv, State, Gaussian<Obsrv> > AdditiveObservationFunctionInterface; typedef typename AdditiveObservationFunctionInterface::NoiseMatrix NoiseMatrix; typedef typename AdditiveUncorrelatedInterface::NoiseMatrix NoiseDiagonalMatrix; /** * Observation model sensor matrix \f$H_t\f$ use in * * \f$ y_t = H_t x_t + N_t v_t \f$ */ typedef Eigen::Matrix< typename State::Scalar, SizeOf<Obsrv>::Value, SizeOf<State>::Value > SensorMatrix; /** * Constructs a linear gaussian observation model * * \param obsrv_dim observation dimension if dynamic size * \param state_dim state dimension if dynamic size */ explicit LinearDecorrelatedGaussianObservationModel( int obsrv_dim = DimensionOf<Obsrv>(), int state_dim = DimensionOf<State>()) : sensor_matrix_(SensorMatrix::Identity(obsrv_dim, state_dim)), density_(obsrv_dim) { assert(obsrv_dim > 0); assert(state_dim > 0); } /** * \brief Overridable default destructor */ virtual ~LinearDecorrelatedGaussianObservationModel() { } virtual NoiseDiagonalMatrix noise_matrix_diagonal() const { return density_.square_root(); } virtual NoiseDiagonalMatrix noise_covariance_diagonal() const { return density_.covariance(); } /** * \brief expected_observation * \param state * \return */ Obsrv expected_observation(const State& state) const override { return sensor_matrix_ * state; } Real log_probability(const Obsrv& obsrv, const State& state) const { density_.mean(expected_observation(state)); return density_.log_probability(obsrv); } const SensorMatrix& sensor_matrix() const override { return sensor_matrix_; } NoiseMatrix noise_matrix() const override { return density_.square_root(); } NoiseMatrix noise_covariance() const override { return density_.covariance(); } int obsrv_dimension() const override { return sensor_matrix_.rows(); } int noise_dimension() const override { return density_.square_root().cols(); } int state_dimension() const override { return sensor_matrix_.cols(); } virtual void sensor_matrix(const SensorMatrix& sensor_mat) { sensor_matrix_ = sensor_mat; } virtual void noise_matrix(const NoiseMatrix& noise_mat) { density_.square_root(noise_mat.diagonal().asDiagonal()); } virtual void noise_covariance(const NoiseMatrix& noise_mat_squared) { density_.covariance(noise_mat_squared.diagonal().asDiagonal()); } virtual void noise_matrix_diagonal( const NoiseDiagonalMatrix& noise_mat) { density_.square_root(noise_mat); } virtual void noise_covariance_diagonal( const NoiseDiagonalMatrix& noise_mat_squared) { density_.covariance(noise_mat_squared); } virtual SensorMatrix create_sensor_matrix() const { auto H = sensor_matrix(); H.setIdentity(); return H; } virtual NoiseMatrix create_noise_matrix() const { auto N = noise_matrix(); N.setIdentity(); return N; } virtual std::string name() const { return "LinearDecorrelatedGaussianObservationModel"; } virtual std::string description() const { return "Linear observation model with additive decorrelated Gaussian " "noise"; } private: SensorMatrix sensor_matrix_; mutable DecorrelatedGaussian<Obsrv> density_; }; } #endif <commit_msg>added diagonal matrix factory functions<commit_after>/* * This is part of the FL library, a C++ Bayesian filtering library * (https://github.com/filtering-library) * * Copyright (c) 2014 Jan Issac ([email protected]) * Copyright (c) 2014 Manuel Wuthrich ([email protected]) * * Max-Planck Institute for Intelligent Systems, AMD Lab * University of Southern California, CLMC Lab * * This Source Code Form is subject to the terms of the MIT License (MIT). * A copy of the license can be found in the LICENSE file distributed with this * source code. */ /** * \file linear_decorrelated_gaussian_observation_model.hpp * \date October 2014 * \author Jan Issac ([email protected]) */ #ifndef FL__MODEL__OBSERVATION__LINEAR_DECORRELATED_GAUSSIAN_OBSERVATION_MODEL_HPP #define FL__MODEL__OBSERVATION__LINEAR_DECORRELATED_GAUSSIAN_OBSERVATION_MODEL_HPP #include <fl/util/traits.hpp> #include <fl/util/types.hpp> #include <fl/util/descriptor.hpp> #include <fl/distribution/decorrelated_gaussian.hpp> #include <fl/model/observation/linear_observation_model.hpp> #include <fl/model/observation/interface/additive_uncorrelated_observation_function.hpp> namespace fl { /** * \ingroup observation_models */ template <typename Obsrv, typename State> class LinearDecorrelatedGaussianObservationModel : public AdditiveUncorrelatedNoiseModel<DecorrelatedGaussian<Obsrv>>, public AdditiveObservationFunction<Obsrv, State, Gaussian<Obsrv>>, public Descriptor, private internal::LinearModelType { public: // specify the main type of this model typedef internal::AdditiveUncorrelatedNoiseModelType Type; typedef AdditiveUncorrelatedNoiseModel< DecorrelatedGaussian<Obsrv> > AdditiveUncorrelatedInterface; typedef AdditiveObservationFunction< Obsrv, State, Gaussian<Obsrv> > AdditiveObservationFunctionInterface; typedef typename AdditiveObservationFunctionInterface::NoiseMatrix NoiseMatrix; typedef typename AdditiveUncorrelatedInterface::NoiseMatrix NoiseDiagonalMatrix; /** * Observation model sensor matrix \f$H_t\f$ use in * * \f$ y_t = H_t x_t + N_t v_t \f$ */ typedef Eigen::Matrix< typename State::Scalar, SizeOf<Obsrv>::Value, SizeOf<State>::Value > SensorMatrix; /** * Constructs a linear gaussian observation model * * \param obsrv_dim observation dimension if dynamic size * \param state_dim state dimension if dynamic size */ explicit LinearDecorrelatedGaussianObservationModel( int obsrv_dim = DimensionOf<Obsrv>(), int state_dim = DimensionOf<State>()) : sensor_matrix_(SensorMatrix::Identity(obsrv_dim, state_dim)), density_(obsrv_dim) { assert(obsrv_dim > 0); assert(state_dim > 0); } /** * \brief Overridable default destructor */ virtual ~LinearDecorrelatedGaussianObservationModel() { } /** * \brief expected_observation * \param state * \return */ Obsrv expected_observation(const State& state) const override { return sensor_matrix_ * state; } Real log_probability(const Obsrv& obsrv, const State& state) const { density_.mean(expected_observation(state)); return density_.log_probability(obsrv); } const SensorMatrix& sensor_matrix() const override { return sensor_matrix_; } NoiseMatrix noise_matrix() const override { return density_.square_root(); } NoiseMatrix noise_covariance() const override { return density_.covariance(); } virtual NoiseDiagonalMatrix noise_diagonal_matrix() const { return density_.square_root(); } virtual NoiseDiagonalMatrix noise_diagonal_covariance() const { return density_.covariance(); } int obsrv_dimension() const override { return sensor_matrix_.rows(); } int noise_dimension() const override { return density_.square_root().cols(); } int state_dimension() const override { return sensor_matrix_.cols(); } virtual void sensor_matrix(const SensorMatrix& sensor_mat) { sensor_matrix_ = sensor_mat; } virtual void noise_matrix(const NoiseMatrix& noise_mat) { density_.square_root(noise_mat.diagonal().asDiagonal()); } virtual void noise_covariance(const NoiseMatrix& noise_mat_squared) { density_.covariance(noise_mat_squared.diagonal().asDiagonal()); } virtual void noise_diagonal_matrix( const NoiseDiagonalMatrix& noise_mat) { density_.square_root(noise_mat); } virtual void noise_diagonal_covariance( const NoiseDiagonalMatrix& noise_mat_squared) { density_.covariance(noise_mat_squared); } virtual SensorMatrix create_sensor_matrix() const { auto H = sensor_matrix(); H.setIdentity(); return H; } virtual NoiseMatrix create_noise_matrix() const { auto N = noise_matrix(); N.setIdentity(); return N; } virtual NoiseMatrix create_noise_covariance() const { auto C = noise_covariance(); C.setIdentity(); return C; } virtual NoiseMatrix create_noise_diagonal_matrix() const { auto N = noise_diagonal_matrix(); N.setIdentity(); return N; } virtual NoiseMatrix create_noise_diagonal_covariance() const { auto C = noise_diagonal_covariance(); C.setIdentity(); return C; } virtual std::string name() const { return "LinearDecorrelatedGaussianObservationModel"; } virtual std::string description() const { return "Linear observation model with additive decorrelated Gaussian " "noise"; } private: SensorMatrix sensor_matrix_; mutable DecorrelatedGaussian<Obsrv> density_; }; } #endif <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** No Commercial Usage ** ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** **************************************************************************/ #include "s60runcontrolfactory.h" #include "codaruncontrol.h" #include "s60devicerunconfiguration.h" #include "s60deployconfiguration.h" #include "trkruncontrol.h" #include "qt4symbiantarget.h" #include <utils/qtcassert.h> using namespace ProjectExplorer; using namespace Qt4ProjectManager; using namespace Qt4ProjectManager::Internal; S60RunControlFactory::S60RunControlFactory(const QString &mode, const QString &name, QObject *parent) : IRunControlFactory(parent), m_mode(mode), m_name(name) { } bool S60RunControlFactory::canRun(RunConfiguration *runConfiguration, const QString &mode) const { if (mode != m_mode) return false; S60DeviceRunConfiguration *rc = qobject_cast<S60DeviceRunConfiguration *>(runConfiguration); if (!rc) return false; S60DeployConfiguration *activeDeployConf = qobject_cast<S60DeployConfiguration *>(rc->qt4Target()->activeDeployConfiguration()); return activeDeployConf != 0; } RunControl* S60RunControlFactory::create(RunConfiguration *runConfiguration, const QString &mode) { S60DeviceRunConfiguration *rc = qobject_cast<S60DeviceRunConfiguration *>(runConfiguration); QTC_ASSERT(rc, return 0); QTC_ASSERT(mode == m_mode, return 0); S60DeployConfiguration *activeDeployConf = qobject_cast<S60DeployConfiguration *>(rc->qt4Target()->activeDeployConfiguration()); if (!activeDeployConf) return 0; if (activeDeployConf->communicationChannel() == S60DeployConfiguration::CommunicationTrkSerialConnection) return new TrkRunControl(rc, mode); return new CodaRunControl(rc, mode); } QString S60RunControlFactory::displayName() const { return m_name; } RunConfigWidget *S60RunControlFactory::createConfigurationWidget(RunConfiguration* runConfiguration /*S60DeviceRunConfiguration */) { return 0; } <commit_msg>Fixed 'unused' warning<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** No Commercial Usage ** ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** **************************************************************************/ #include "s60runcontrolfactory.h" #include "codaruncontrol.h" #include "s60devicerunconfiguration.h" #include "s60deployconfiguration.h" #include "trkruncontrol.h" #include "qt4symbiantarget.h" #include <utils/qtcassert.h> using namespace ProjectExplorer; using namespace Qt4ProjectManager; using namespace Qt4ProjectManager::Internal; S60RunControlFactory::S60RunControlFactory(const QString &mode, const QString &name, QObject *parent) : IRunControlFactory(parent), m_mode(mode), m_name(name) { } bool S60RunControlFactory::canRun(RunConfiguration *runConfiguration, const QString &mode) const { if (mode != m_mode) return false; S60DeviceRunConfiguration *rc = qobject_cast<S60DeviceRunConfiguration *>(runConfiguration); if (!rc) return false; S60DeployConfiguration *activeDeployConf = qobject_cast<S60DeployConfiguration *>(rc->qt4Target()->activeDeployConfiguration()); return activeDeployConf != 0; } RunControl* S60RunControlFactory::create(RunConfiguration *runConfiguration, const QString &mode) { S60DeviceRunConfiguration *rc = qobject_cast<S60DeviceRunConfiguration *>(runConfiguration); QTC_ASSERT(rc, return 0); QTC_ASSERT(mode == m_mode, return 0); S60DeployConfiguration *activeDeployConf = qobject_cast<S60DeployConfiguration *>(rc->qt4Target()->activeDeployConfiguration()); if (!activeDeployConf) return 0; if (activeDeployConf->communicationChannel() == S60DeployConfiguration::CommunicationTrkSerialConnection) return new TrkRunControl(rc, mode); return new CodaRunControl(rc, mode); } QString S60RunControlFactory::displayName() const { return m_name; } QWidget *S60RunControlFactory::createConfigurationWidget(RunConfiguration *runConfiguration) { Q_UNUSED(runConfiguration); return 0; } <|endoftext|>
<commit_before>#ifndef __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__UNIFORM_HPP__ #define __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__UNIFORM_HPP__ #include <stan/agrad.hpp> #include <stan/math/error_handling.hpp> #include <stan/math/special_functions.hpp> #include <stan/meta/traits.hpp> #include <stan/prob/constants.hpp> #include <stan/prob/traits.hpp> namespace stan { namespace prob { // CONTINUOUS, UNIVARIATE DENSITIES /** * The log of a uniform density for the given * y, lower, and upper bound. * \f{eqnarray*}{ y &\sim& \mbox{\sf{U}}(\alpha, \beta) \\ \log (p (y \,|\, \alpha, \beta)) &=& \log \left( \frac{1}{\beta-\alpha} \right) \\ &=& \log (1) - \log (\beta - \alpha) \\ &=& -\log (\beta - \alpha) \\ & & \mathrm{ where } \; y \in [\alpha, \beta], \log(0) \; \mathrm{otherwise} \f} * * @param y A scalar variable. * @param alpha Lower bound. * @param beta Upper bound. * @throw std::invalid_argument if the lower bound is greater than * or equal to the lower bound * @tparam T_y Type of scalar. * @tparam T_low Type of lower bound. * @tparam T_high Type of upper bound. */ template <bool propto, typename T_y, typename T_low, typename T_high, class Policy> typename return_type<T_y,T_low,T_high>::type uniform_log(const T_y& y, const T_low& alpha, const T_high& beta, const Policy&) { static const char* function = "stan::prob::uniform_log(%1%)"; using stan::math::check_not_nan; using stan::math::check_finite; using stan::math::check_greater; using stan::math::value_of; using stan::math::check_consistent_sizes; // check if any vectors are zero length if (!(stan::length(y) && stan::length(alpha) && stan::length(beta))) return 0.0; // set up return value accumulator typename return_type<T_y,T_low,T_high>::type logp(0.0); if(!check_not_nan(function, y, "Random variable", &logp, Policy())) return logp; if (!check_finite(function, alpha, "Lower bound parameter", &logp, Policy())) return logp; if (!check_finite(function, beta, "Upper bound parameter", &logp, Policy())) return logp; if (!check_greater(function, beta, alpha, "Upper bound parameter", &logp, Policy())) return logp; if (!(check_consistent_sizes(function, y,alpha,beta, "Random variable","Lower bound parameter","Upper bound parameter", &logp, Policy()))) return logp; // check if no variables are involved and prop-to if (!include_summand<propto,T_y,T_low,T_high>::value) return 0.0; VectorView<const T_y> y_vec(y); VectorView<const T_low> alpha_vec(alpha); VectorView<const T_high> beta_vec(beta); size_t N = max_size(y, alpha, beta); for (size_t n = 0; n < N; n++) { const double y_dbl = value_of(y_vec[n]); if (y_dbl < value_of(alpha_vec[n]) || y_dbl > value_of(beta_vec[n])) return LOG_ZERO; } for (size_t n = 0; n < N; n++) { if (include_summand<propto,T_low,T_high>::value) logp -= log(beta_vec[n] - alpha_vec[n]); } return logp; } template <bool propto, typename T_y, typename T_low, typename T_high> inline typename return_type<T_y,T_low,T_high>::type uniform_log(const T_y& y, const T_low& alpha, const T_high& beta) { return uniform_log<propto>(y,alpha,beta,stan::math::default_policy()); } template <typename T_y, typename T_low, typename T_high, class Policy> inline typename return_type<T_y,T_low,T_high>::type uniform_log(const T_y& y, const T_low& alpha, const T_high& beta, const Policy&) { return uniform_log<false>(y,alpha,beta,Policy()); } template <typename T_y, typename T_low, typename T_high> inline typename return_type<T_y,T_low,T_high>::type uniform_log(const T_y& y, const T_low& alpha, const T_high& beta) { return uniform_log<false>(y,alpha,beta,stan::math::default_policy()); } } } #endif <commit_msg>evaluated derivatives for uniform<commit_after>#ifndef __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__UNIFORM_HPP__ #define __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__UNIFORM_HPP__ #include <stan/agrad.hpp> #include <stan/math/error_handling.hpp> #include <stan/math/special_functions.hpp> #include <stan/meta/traits.hpp> #include <stan/prob/constants.hpp> #include <stan/prob/traits.hpp> namespace stan { namespace prob { // CONTINUOUS, UNIVARIATE DENSITIES /** * The log of a uniform density for the given * y, lower, and upper bound. * \f{eqnarray*}{ y &\sim& \mbox{\sf{U}}(\alpha, \beta) \\ \log (p (y \,|\, \alpha, \beta)) &=& \log \left( \frac{1}{\beta-\alpha} \right) \\ &=& \log (1) - \log (\beta - \alpha) \\ &=& -\log (\beta - \alpha) \\ & & \mathrm{ where } \; y \in [\alpha, \beta], \log(0) \; \mathrm{otherwise} \f} * * @param y A scalar variable. * @param alpha Lower bound. * @param beta Upper bound. * @throw std::invalid_argument if the lower bound is greater than * or equal to the lower bound * @tparam T_y Type of scalar. * @tparam T_low Type of lower bound. * @tparam T_high Type of upper bound. */ template <bool propto, typename T_y, typename T_low, typename T_high, class Policy> typename return_type<T_y,T_low,T_high>::type uniform_log(const T_y& y, const T_low& alpha, const T_high& beta, const Policy&) { static const char* function = "stan::prob::uniform_log(%1%)"; using stan::math::check_not_nan; using stan::math::check_finite; using stan::math::check_greater; using stan::math::value_of; using stan::math::check_consistent_sizes; // check if any vectors are zero length if (!(stan::length(y) && stan::length(alpha) && stan::length(beta))) return 0.0; // set up return value accumulator double logp(0.0); if(!check_not_nan(function, y, "Random variable", &logp, Policy())) return logp; if (!check_finite(function, alpha, "Lower bound parameter", &logp, Policy())) return logp; if (!check_finite(function, beta, "Upper bound parameter", &logp, Policy())) return logp; if (!check_greater(function, beta, alpha, "Upper bound parameter", &logp, Policy())) return logp; if (!(check_consistent_sizes(function, y,alpha,beta, "Random variable","Lower bound parameter","Upper bound parameter", &logp, Policy()))) return logp; // check if no variables are involved and prop-to if (!include_summand<propto,T_y,T_low,T_high>::value) return 0.0; VectorView<const T_y> y_vec(y); VectorView<const T_low> alpha_vec(alpha); VectorView<const T_high> beta_vec(beta); size_t N = max_size(y, alpha, beta); for (size_t n = 0; n < N; n++) { const double y_dbl = value_of(y_vec[n]); if (y_dbl < value_of(alpha_vec[n]) || y_dbl > value_of(beta_vec[n])) return LOG_ZERO; } DoubleVectorView<include_summand<propto,T_low,T_high>::value, is_vector<T_low>::value | is_vector<T_high>::value> inv_beta_minus_alpha(max_size(alpha,beta)); for (size_t i = 0; i < max_size(alpha,beta); i++) if (include_summand<propto,T_low,T_high>::value) inv_beta_minus_alpha[i] = 1.0 / (value_of(beta_vec[i]) - value_of(alpha_vec[i])); DoubleVectorView<include_summand<propto,T_low,T_high>::value, is_vector<T_low>::value | is_vector<T_high>::value> log_beta_minus_alpha(max_size(alpha,beta)); for (size_t i = 0; i < max_size(alpha,beta); i++) if (include_summand<propto,T_low,T_high>::value) log_beta_minus_alpha[i] = log(value_of(beta_vec[i]) - value_of(alpha_vec[i])); agrad::OperandsAndPartials<T_y,T_low,T_high> operands_and_partials(y,alpha,beta); for (size_t n = 0; n < N; n++) { if (include_summand<propto,T_low,T_high>::value) logp -= log_beta_minus_alpha[n]; if (!is_constant_struct<T_low>::value) operands_and_partials.d_x2[n] += inv_beta_minus_alpha[n]; if (!is_constant_struct<T_high>::value) operands_and_partials.d_x3[n] -= inv_beta_minus_alpha[n]; } return operands_and_partials.to_var(logp); } template <bool propto, typename T_y, typename T_low, typename T_high> inline typename return_type<T_y,T_low,T_high>::type uniform_log(const T_y& y, const T_low& alpha, const T_high& beta) { return uniform_log<propto>(y,alpha,beta,stan::math::default_policy()); } template <typename T_y, typename T_low, typename T_high, class Policy> inline typename return_type<T_y,T_low,T_high>::type uniform_log(const T_y& y, const T_low& alpha, const T_high& beta, const Policy&) { return uniform_log<false>(y,alpha,beta,Policy()); } template <typename T_y, typename T_low, typename T_high> inline typename return_type<T_y,T_low,T_high>::type uniform_log(const T_y& y, const T_low& alpha, const T_high& beta) { return uniform_log<false>(y,alpha,beta,stan::math::default_policy()); } } } #endif <|endoftext|>
<commit_before>#ifndef _SNARKFRONT_DSL_UTILITY_HPP_ #define _SNARKFRONT_DSL_UTILITY_HPP_ #include <array> #include <cstdint> #include <iostream> #include <istream> #include <ostream> #include <string> #include <vector> #include <snarklib/Util.hpp> #include <snarkfront/Alg.hpp> #include <snarkfront/AST.hpp> #include <snarkfront/BitwiseAST.hpp> #include <snarkfront/DSL_base.hpp> #include <snarkfront/HexUtil.hpp> namespace snarkfront { //////////////////////////////////////////////////////////////////////////////// // elliptic curve pairing // // check if string name is: BN128, Edwards bool validPairingName(const std::string& name); // returns true if "BN128" bool pairingBN128(const std::string& name); // returns true if "Edwards" bool pairingEdwards(const std::string& name); //////////////////////////////////////////////////////////////////////////////// // SHA-2 // // check if: "1", "224", "256", "384", "512", "512_224", "512_256" bool validSHA2Name(const std::string& shaBits); // check if: 1, 224, 256, 384, 512 bool validSHA2Name(const std::size_t shaBits); // returns true if "SHA256" bool nameSHA256(const std::string& shaBits); // returns true if "SHA512" bool nameSHA512(const std::string& shaBits); //////////////////////////////////////////////////////////////////////////////// // AES // // check if: 128, 192, 256 bool validAESName(const std::size_t aesBits); //////////////////////////////////////////////////////////////////////////////// // powers of 2 // template <typename ALG> std::size_t sizeBits(const AST_Const<ALG>&) { typename AST_Const<ALG>::ValueType dummy; return sizeBits(dummy); } template <typename ALG> std::size_t sizeBits(const AST_Var<ALG>&) { typename AST_Var<ALG>::ValueType dummy; return sizeBits(dummy); } //////////////////////////////////////////////////////////////////////////////// // convert between hexadecimal ASCII and binary // #define DEFN_ASCII_HEX_ARRAY(BITS) \ template <typename FR, std::size_t N> \ std::string asciiHex( \ const std::array<uint ## BITS ## _x<FR>, N>& a, \ const bool space = false) \ { \ std::array<uint ## BITS ## _t, N> tmp; \ for (std::size_t i = 0; i < N; ++i) \ tmp[i] = a[i]->value(); \ return asciiHex(tmp, space); \ } DEFN_ASCII_HEX_ARRAY(8) DEFN_ASCII_HEX_ARRAY(32) DEFN_ASCII_HEX_ARRAY(64) #undef DEFN_ASCII_HEX_ARRAY #define DEFN_ASCII_HEX_VECTOR(BITS) \ template <typename FR, std::size_t N> \ std::string asciiHex( \ const std::vector<uint ## BITS ## _x<FR>>& a, \ const bool space = false) \ { \ std::vector<uint ## BITS ## _t> tmp; \ for (std::size_t i = 0; i < N; ++i) \ tmp[i] = a[i]->value(); \ return asciiHex(tmp, space); \ } DEFN_ASCII_HEX_VECTOR(8) DEFN_ASCII_HEX_VECTOR(32) DEFN_ASCII_HEX_VECTOR(64) #undef DEFN_ASCII_HEX_VECTOR //////////////////////////////////////////////////////////////////////////////// // serialize hash digests and preimages // #define DEFN_ARRAY_OUT(UINT) \ template <std::size_t N> \ std::ostream& operator<< ( \ std::ostream& os, \ const std::array<UINT, N>& a) \ { \ const char *ptr = reinterpret_cast<const char*>(a.data()); \ if (snarklib::is_big_endian<int>()) { \ for (std::size_t i = 0; i < N; ++i) { \ for (int j = sizeof(UINT) - 1; j >= 0; --j) { \ os.put(ptr[i * sizeof(UINT) + j]); \ } \ } \ } else { \ os.write(ptr, sizeof(a)); \ } \ return os; \ } DEFN_ARRAY_OUT(std::uint8_t) DEFN_ARRAY_OUT(std::uint32_t) DEFN_ARRAY_OUT(std::uint64_t) #undef DEFN_ARRAY_OUT #define DEFN_VECTOR_ARRAY_OUT(UINT) \ template <std::size_t N> \ std::ostream& operator<< ( \ std::ostream& os, \ const std::vector<std::array<UINT, N>>& a) \ { \ os << a.size() << ' '; \ for (const auto& r : a) \ os << r; \ return os; \ } DEFN_VECTOR_ARRAY_OUT(std::uint8_t) DEFN_VECTOR_ARRAY_OUT(std::uint32_t) DEFN_VECTOR_ARRAY_OUT(std::uint64_t) #undef DEFN_VECTOR_ARRAY_OUT #define DEFN_ARRAY_IN(UINT) \ template <std::size_t N> \ std::istream& operator>> ( \ std::istream& is, \ std::array<UINT, N>& a) \ { \ char *ptr = reinterpret_cast<char*>(a.data()); \ if (snarklib::is_big_endian<int>()) { \ for (std::size_t i = 0; i < N; ++i) { \ for (int j = sizeof(UINT) - 1; j >= 0; --j) { \ if (! is.get(ptr[i * sizeof(UINT) + j])) \ return is; \ } \ } \ } else { \ is.read(ptr, sizeof(a)); \ } \ return is; \ } DEFN_ARRAY_IN(std::uint8_t) DEFN_ARRAY_IN(std::uint32_t) DEFN_ARRAY_IN(std::uint64_t) #undef DEFN_ARRAY_IN #define DEFN_VECTOR_ARRAY_IN(UINT) \ template <std::size_t N> \ std::istream& operator>> ( \ std::istream& is, \ std::vector<std::array<UINT, N>>& a) \ { \ std::size_t len = -1; \ if (!(is >> len) || (-1 == len)) return is; \ char c; \ if (!is.get(c) || (' ' != c)) return is; \ a.resize(len); \ for (auto& r : a) \ if (!(is >> r)) break; \ return is; \ } DEFN_VECTOR_ARRAY_IN(std::uint8_t) DEFN_VECTOR_ARRAY_IN(std::uint32_t) DEFN_VECTOR_ARRAY_IN(std::uint64_t) #undef DEFN_VECTOR_ARRAY_IN //////////////////////////////////////////////////////////////////////////////// // lookup table for unsigned integer types // template <typename T, typename U, typename VAL, typename BITWISE> class BitwiseLUT { public: template <std::size_t N> BitwiseLUT(const std::array<VAL, N>& table_elements) : m_value(table_elements.begin(), table_elements.end()) {} std::size_t size() const { return m_value.size(); } U operator[] (const T& x) const { const auto N = m_value.size(); auto sum = BITWISE::_AND(BITWISE::_constant(m_value[0]), BITWISE::_CMPLMNT(BITWISE::_bitmask(0 != x))); for (std::size_t i = 1; i < N - 1; ++i) { sum = BITWISE::_ADDMOD(sum, BITWISE::_AND( BITWISE::_constant(m_value[i]), BITWISE::_CMPLMNT(BITWISE::_bitmask(i != x)))); } return BITWISE::ADDMOD(sum, BITWISE::_AND( BITWISE::_constant(m_value[N - 1]), BITWISE::_CMPLMNT(BITWISE::_bitmask((N-1) != x)))); } private: const std::vector<VAL> m_value; }; template <typename FR> using array_uint8 = BitwiseLUT<AST_Node<Alg_uint8<FR>>, AST_Op<Alg_uint8<FR>>, std::uint8_t, BitwiseAST<Alg_uint8<FR>>>; template <typename FR> using array_uint32 = BitwiseLUT<AST_Node<Alg_uint32<FR>>, AST_Op<Alg_uint32<FR>>, std::uint32_t, BitwiseAST<Alg_uint32<FR>>>; template <typename FR> using array_uint64 = BitwiseLUT<AST_Node<Alg_uint64<FR>>, AST_Op<Alg_uint64<FR>>, std::uint64_t, BitwiseAST<Alg_uint64<FR>>>; } // namespace snarkfront #endif <commit_msg>finite field exponentiation<commit_after>#ifndef _SNARKFRONT_DSL_UTILITY_HPP_ #define _SNARKFRONT_DSL_UTILITY_HPP_ #include <array> #include <cassert> #include <cstdint> #include <iostream> #include <istream> #include <ostream> #include <string> #include <vector> #include <snarklib/Util.hpp> #include <snarkfront/Alg.hpp> #include <snarkfront/AST.hpp> #include <snarkfront/BitwiseAST.hpp> #include <snarkfront/DSL_base.hpp> #include <snarkfront/HexUtil.hpp> namespace snarkfront { //////////////////////////////////////////////////////////////////////////////// // elliptic curve pairing // // check if string name is: BN128, Edwards bool validPairingName(const std::string& name); // returns true if "BN128" bool pairingBN128(const std::string& name); // returns true if "Edwards" bool pairingEdwards(const std::string& name); //////////////////////////////////////////////////////////////////////////////// // SHA-2 // // check if: "1", "224", "256", "384", "512", "512_224", "512_256" bool validSHA2Name(const std::string& shaBits); // check if: 1, 224, 256, 384, 512 bool validSHA2Name(const std::size_t shaBits); // returns true if "SHA256" bool nameSHA256(const std::string& shaBits); // returns true if "SHA512" bool nameSHA512(const std::string& shaBits); //////////////////////////////////////////////////////////////////////////////// // AES // // check if: 128, 192, 256 bool validAESName(const std::size_t aesBits); //////////////////////////////////////////////////////////////////////////////// // powers of 2 // template <typename ALG> std::size_t sizeBits(const AST_Const<ALG>&) { typename AST_Const<ALG>::ValueType dummy; return sizeBits(dummy); } template <typename ALG> std::size_t sizeBits(const AST_Var<ALG>&) { typename AST_Var<ALG>::ValueType dummy; return sizeBits(dummy); } //////////////////////////////////////////////////////////////////////////////// // convert between hexadecimal ASCII and binary // #define DEFN_ASCII_HEX_ARRAY(BITS) \ template <typename FR, std::size_t N> \ std::string asciiHex( \ const std::array<uint ## BITS ## _x<FR>, N>& a, \ const bool space = false) \ { \ std::array<uint ## BITS ## _t, N> tmp; \ for (std::size_t i = 0; i < N; ++i) \ tmp[i] = a[i]->value(); \ return asciiHex(tmp, space); \ } DEFN_ASCII_HEX_ARRAY(8) DEFN_ASCII_HEX_ARRAY(32) DEFN_ASCII_HEX_ARRAY(64) #undef DEFN_ASCII_HEX_ARRAY #define DEFN_ASCII_HEX_VECTOR(BITS) \ template <typename FR, std::size_t N> \ std::string asciiHex( \ const std::vector<uint ## BITS ## _x<FR>>& a, \ const bool space = false) \ { \ std::vector<uint ## BITS ## _t> tmp; \ for (std::size_t i = 0; i < N; ++i) \ tmp[i] = a[i]->value(); \ return asciiHex(tmp, space); \ } DEFN_ASCII_HEX_VECTOR(8) DEFN_ASCII_HEX_VECTOR(32) DEFN_ASCII_HEX_VECTOR(64) #undef DEFN_ASCII_HEX_VECTOR //////////////////////////////////////////////////////////////////////////////// // serialize hash digests and preimages // #define DEFN_ARRAY_OUT(UINT) \ template <std::size_t N> \ std::ostream& operator<< ( \ std::ostream& os, \ const std::array<UINT, N>& a) \ { \ const char *ptr = reinterpret_cast<const char*>(a.data()); \ if (snarklib::is_big_endian<int>()) { \ for (std::size_t i = 0; i < N; ++i) { \ for (int j = sizeof(UINT) - 1; j >= 0; --j) { \ os.put(ptr[i * sizeof(UINT) + j]); \ } \ } \ } else { \ os.write(ptr, sizeof(a)); \ } \ return os; \ } DEFN_ARRAY_OUT(std::uint8_t) DEFN_ARRAY_OUT(std::uint32_t) DEFN_ARRAY_OUT(std::uint64_t) #undef DEFN_ARRAY_OUT #define DEFN_VECTOR_ARRAY_OUT(UINT) \ template <std::size_t N> \ std::ostream& operator<< ( \ std::ostream& os, \ const std::vector<std::array<UINT, N>>& a) \ { \ os << a.size() << ' '; \ for (const auto& r : a) \ os << r; \ return os; \ } DEFN_VECTOR_ARRAY_OUT(std::uint8_t) DEFN_VECTOR_ARRAY_OUT(std::uint32_t) DEFN_VECTOR_ARRAY_OUT(std::uint64_t) #undef DEFN_VECTOR_ARRAY_OUT #define DEFN_ARRAY_IN(UINT) \ template <std::size_t N> \ std::istream& operator>> ( \ std::istream& is, \ std::array<UINT, N>& a) \ { \ char *ptr = reinterpret_cast<char*>(a.data()); \ if (snarklib::is_big_endian<int>()) { \ for (std::size_t i = 0; i < N; ++i) { \ for (int j = sizeof(UINT) - 1; j >= 0; --j) { \ if (! is.get(ptr[i * sizeof(UINT) + j])) \ return is; \ } \ } \ } else { \ is.read(ptr, sizeof(a)); \ } \ return is; \ } DEFN_ARRAY_IN(std::uint8_t) DEFN_ARRAY_IN(std::uint32_t) DEFN_ARRAY_IN(std::uint64_t) #undef DEFN_ARRAY_IN #define DEFN_VECTOR_ARRAY_IN(UINT) \ template <std::size_t N> \ std::istream& operator>> ( \ std::istream& is, \ std::vector<std::array<UINT, N>>& a) \ { \ std::size_t len = -1; \ if (!(is >> len) || (-1 == len)) return is; \ char c; \ if (!is.get(c) || (' ' != c)) return is; \ a.resize(len); \ for (auto& r : a) \ if (!(is >> r)) break; \ return is; \ } DEFN_VECTOR_ARRAY_IN(std::uint8_t) DEFN_VECTOR_ARRAY_IN(std::uint32_t) DEFN_VECTOR_ARRAY_IN(std::uint64_t) #undef DEFN_VECTOR_ARRAY_IN //////////////////////////////////////////////////////////////////////////////// // lookup table for unsigned integer types // template <typename T, typename U, typename VAL, typename BITWISE> class BitwiseLUT { public: template <std::size_t N> BitwiseLUT(const std::array<VAL, N>& table_elements) : m_value(table_elements.begin(), table_elements.end()) { #ifdef USE_ASSERT // empty look up table does not make sense assert(N > 0); #endif } std::size_t size() const { return m_value.size(); } U operator[] (const T& x) const { const auto N = m_value.size(); if (1 == N) { // returns value if index is 0, else all clear bits return BITWISE::AND(BITWISE::_constant(m_value[0]), BITWISE::_CMPLMNT(BITWISE::_bitmask(0 != x))); } else { auto sum = BITWISE::_AND(BITWISE::_constant(m_value[0]), BITWISE::_CMPLMNT(BITWISE::_bitmask(0 != x))); for (std::size_t i = 1; i < N - 1; ++i) { sum = BITWISE::_ADDMOD(sum, BITWISE::_AND( BITWISE::_constant(m_value[i]), BITWISE::_CMPLMNT(BITWISE::_bitmask(i != x)))); } return BITWISE::ADDMOD(sum, BITWISE::_AND( BITWISE::_constant(m_value[N - 1]), BITWISE::_CMPLMNT(BITWISE::_bitmask((N-1) != x)))); } } private: const std::vector<VAL> m_value; }; template <typename FR> using array_uint8 = BitwiseLUT<AST_Node<Alg_uint8<FR>>, AST_Op<Alg_uint8<FR>>, std::uint8_t, BitwiseAST<Alg_uint8<FR>>>; template <typename FR> using array_uint32 = BitwiseLUT<AST_Node<Alg_uint32<FR>>, AST_Op<Alg_uint32<FR>>, std::uint32_t, BitwiseAST<Alg_uint32<FR>>>; template <typename FR> using array_uint64 = BitwiseLUT<AST_Node<Alg_uint64<FR>>, AST_Op<Alg_uint64<FR>>, std::uint64_t, BitwiseAST<Alg_uint64<FR>>>; //////////////////////////////////////////////////////////////////////////////// // finite field exponentiation // template <typename FR> AST_Op<Alg_Field<FR>> pow(const AST_Node<Alg_Field<FR>>& base, const AST_Node<Alg_bool<FR>>& exponent) { // base * exponent + ~exponent = exponent ? base : one return AST_Op<Alg_Field<FR>>( Alg_Field<FR>::OpType::ADD, new AST_Op<Alg_Field<FR>>(Alg_Field<FR>::OpType::MUL, base, _xword(exponent, base)), _xword(~exponent, base)); } template <typename FR> AST_Op<Alg_Field<FR>>* _pow(const AST_Node<Alg_Field<FR>>& base, const AST_Node<Alg_bool<FR>>& exponent) { // base * exponent + ~exponent = exponent ? base : one return new AST_Op<Alg_Field<FR>>( Alg_Field<FR>::OpType::ADD, new AST_Op<Alg_Field<FR>>(Alg_Field<FR>::OpType::MUL, base, _xword(exponent, base)), _xword(~exponent, base)); } template <typename FR> AST_Op<Alg_Field<FR>> pow(const AST_Node<Alg_Field<FR>>& base, const std::vector<AST_Node<Alg_bool<FR>>>& exponent) { const auto expBits = exponent.size(); #ifdef USE_ASSERT // no exponent bits does not make sense assert(expBits > 0); #endif if (1 == expBits) { return pow(base, exponent[0]); } else { auto sum = _pow(base, exponent[0]); // pow(base, 2) auto powbase = new AST_Op<Alg_Field<FR>>(Alg_Field<FR>::OpType::MUL, base, base); for (std::size_t i = 1; i < expBits - 1; ++i) { sum = new AST_Op<Alg_Field<FR>>(Alg_Field<FR>::OpType::ADD, sum, _pow(powbase, exponent[i])); // pow(base, pow(2, i + 1)) powbase = new AST_Op<Alg_Field<FR>>(Alg_Field<FR>::OpType::MUL, powbase, powbase); } return AST_Op<Alg_Field<FR>>(Alg_Field<FR>::OpType::ADD, sum, _pow(powbase, exponent[expBits - 1])); } } } // namespace snarkfront #endif <|endoftext|>
<commit_before>#include "../base/SRC_FIRST.hpp" #include "text_path.hpp" #include "../geometry/angles.hpp" namespace graphics { TextPath::TextPath() : m_pv(), m_fullLength(0), m_pathOffset(0) {} TextPath::TextPath(TextPath const & src, math::Matrix<double, 3, 3> const & m) { m_arr.resize(src.m_arr.size()); for (unsigned i = 0; i < m_arr.size(); ++i) m_arr[i] = src.m_arr[i] * m; m_fullLength = (m2::PointD(src.m_fullLength, 0) * m).Length(m2::PointD(0, 0) * m); m_pathOffset = (m2::PointD(src.m_pathOffset, 0) * m).Length(m2::PointD(0, 0) * m); m_pv = PathView(&m_arr[0], m_arr.size()); /// Fix: Check for reversing only when rotation is active, /// otherwise we have some flicker-blit issues for street names on zooming. /// @todo Should investigate this stuff. if (m(0, 1) != 0.0 && m(1, 0) != 0.0) checkReverse(); else setIsReverse(src.isReverse()); } TextPath::TextPath(m2::PointD const * arr, size_t sz, double fullLength, double pathOffset) : m_fullLength(fullLength), m_pathOffset(pathOffset) { ASSERT ( sz > 1, () ); m_arr.resize(sz); copy(arr, arr + sz, m_arr.begin()); m_pv = PathView(&m_arr[0], m_arr.size()); checkReverse(); } bool TextPath::isReverse() const { return m_pv.isReverse(); } void TextPath::setIsReverse(bool flag) { m_pv.setIsReverse(flag); } void TextPath::checkReverse() { /* assume, that readable text in path should be ('o' - start draw point): * / o * / \ * / or \ * o \ */ double const a = ang::AngleTo(m_arr[0], m_arr[m_arr.size() - 1]); if (fabs(a) > math::pi / 2.0) { // if we swap direction, we need to recalculate path offset from the end double len = 0.0; for (size_t i = 1; i < m_arr.size(); ++i) len += m_arr[i-1].Length(m_arr[i]); m_pathOffset = m_fullLength - m_pathOffset - len; ASSERT ( m_pathOffset >= -1.0E-6, () ); if (m_pathOffset < 0.0) m_pathOffset = 0.0; setIsReverse(true); } else setIsReverse(false); } double TextPath::fullLength() const { return m_fullLength; } double TextPath::pathOffset() const { return m_pathOffset; } size_t TextPath::size() const { return m_pv.size(); } m2::PointD TextPath::get(size_t i) const { return m_pv.get(i); } m2::PointD TextPath::operator[](size_t i) const { return get(i); } PathPoint const TextPath::offsetPoint(PathPoint const & pp, double offset) const { return m_pv.offsetPoint(pp, offset); } PivotPoint TextPath::findPivotPoint(PathPoint const & pp, GlyphMetrics const & sym) const { const PivotPoint ptStart = m_pv.findPivotPoint(pp, sym.m_xOffset - sym.m_width); const PivotPoint ptEnd = m_pv.findPivotPoint(pp, sym.m_xOffset + sym.m_width * 2); // both start and end are on the same segment, no need to calculate if (ptStart.m_pp.m_i == ptEnd.m_pp.m_i) return PivotPoint(ptStart.m_angle, PathPoint(ptStart.m_pp.m_i, ptStart.m_angle, (ptStart.m_pp.m_pt + ptEnd.m_pp.m_pt) / 2.0)); // points are on different segments, average the angle and middle point const PivotPoint ptMid = m_pv.findPivotPoint(pp, sym.m_xOffset + sym.m_width / 2.0); if ((ptStart.m_pp.m_i != -1) && (ptMid.m_pp.m_i != -1) && (ptEnd.m_pp.m_i != -1)) { const ang::AngleD avgAngle(ang::GetMiddleAngle(ptStart.m_angle.val(), ptEnd.m_angle.val())); return PivotPoint(avgAngle, PathPoint(ptMid.m_pp.m_i, ptMid.m_angle, (ptStart.m_pp.m_pt + ptMid.m_pp.m_pt + ptMid.m_pp.m_pt + // twice to compensate for long distance ptEnd.m_pp.m_pt) / 4.0)); } // if some of the pivot points are outside of the path, just take the middle value else return ptMid; } PathPoint const TextPath::front() const { return m_pv.front(); } } <commit_msg>formatting<commit_after>#include "../base/SRC_FIRST.hpp" #include "text_path.hpp" #include "../geometry/angles.hpp" namespace graphics { TextPath::TextPath() : m_pv(), m_fullLength(0), m_pathOffset(0) {} TextPath::TextPath(TextPath const & src, math::Matrix<double, 3, 3> const & m) { m_arr.resize(src.m_arr.size()); for (unsigned i = 0; i < m_arr.size(); ++i) m_arr[i] = src.m_arr[i] * m; m_fullLength = (m2::PointD(src.m_fullLength, 0) * m).Length(m2::PointD(0, 0) * m); m_pathOffset = (m2::PointD(src.m_pathOffset, 0) * m).Length(m2::PointD(0, 0) * m); m_pv = PathView(&m_arr[0], m_arr.size()); /// Fix: Check for reversing only when rotation is active, /// otherwise we have some flicker-blit issues for street names on zooming. /// @todo Should investigate this stuff. if (m(0, 1) != 0.0 && m(1, 0) != 0.0) checkReverse(); else setIsReverse(src.isReverse()); } TextPath::TextPath(m2::PointD const * arr, size_t sz, double fullLength, double pathOffset) : m_fullLength(fullLength), m_pathOffset(pathOffset) { ASSERT ( sz > 1, () ); m_arr.resize(sz); copy(arr, arr + sz, m_arr.begin()); m_pv = PathView(&m_arr[0], m_arr.size()); checkReverse(); } bool TextPath::isReverse() const { return m_pv.isReverse(); } void TextPath::setIsReverse(bool flag) { m_pv.setIsReverse(flag); } void TextPath::checkReverse() { /* assume, that readable text in path should be ('o' - start draw point): * / o * / \ * / or \ * o \ */ double const a = ang::AngleTo(m_arr[0], m_arr[m_arr.size() - 1]); if (fabs(a) > math::pi / 2.0) { // if we swap direction, we need to recalculate path offset from the end double len = 0.0; for (size_t i = 1; i < m_arr.size(); ++i) len += m_arr[i-1].Length(m_arr[i]); m_pathOffset = m_fullLength - m_pathOffset - len; ASSERT ( m_pathOffset >= -1.0E-6, () ); if (m_pathOffset < 0.0) m_pathOffset = 0.0; setIsReverse(true); } else setIsReverse(false); } double TextPath::fullLength() const { return m_fullLength; } double TextPath::pathOffset() const { return m_pathOffset; } size_t TextPath::size() const { return m_pv.size(); } m2::PointD TextPath::get(size_t i) const { return m_pv.get(i); } m2::PointD TextPath::operator[](size_t i) const { return get(i); } PathPoint const TextPath::offsetPoint(PathPoint const & pp, double offset) const { return m_pv.offsetPoint(pp, offset); } PivotPoint TextPath::findPivotPoint(PathPoint const & pp, GlyphMetrics const & sym) const { const PivotPoint ptStart = m_pv.findPivotPoint(pp, sym.m_xOffset - sym.m_width); const PivotPoint ptEnd = m_pv.findPivotPoint(pp, sym.m_xOffset + sym.m_width * 2); // both start and end are on the same segment, no need to calculate if (ptStart.m_pp.m_i == ptEnd.m_pp.m_i) return PivotPoint(ptStart.m_angle, PathPoint(ptStart.m_pp.m_i, ptStart.m_angle, (ptStart.m_pp.m_pt + ptEnd.m_pp.m_pt) / 2.0)); // points are on different segments, average the angle and middle point const PivotPoint ptMid = m_pv.findPivotPoint(pp, sym.m_xOffset + sym.m_width / 2.0); if ((ptStart.m_pp.m_i != -1) && (ptMid.m_pp.m_i != -1) && (ptEnd.m_pp.m_i != -1)) { const ang::AngleD avgAngle(ang::GetMiddleAngle(ptStart.m_angle.val(), ptEnd.m_angle.val())); return PivotPoint(avgAngle, PathPoint(ptMid.m_pp.m_i, ptMid.m_angle, (ptStart.m_pp.m_pt + ptMid.m_pp.m_pt + ptMid.m_pp.m_pt + // twice to compensate for long distance ptEnd.m_pp.m_pt) / 4.0)); } else { // if some of the pivot points are outside of the path, just take the middle value return ptMid; } } PathPoint const TextPath::front() const { return m_pv.front(); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ //--- interface include -------------------------------------------------------- #include "QueueWorkingModuleTest.h" //--- module under test -------------------------------------------------------- #include "QueueWorkingModule.h" //--- test modules used -------------------------------------------------------- #include "TestSuite.h" //--- project modules used ---------------------------------------------------- #include "Queue.h" //--- standard modules used ---------------------------------------------------- #include "System.h" #include "Dbg.h" //--- c-modules used ----------------------------------------------------------- //---- QueueWorkingModuleTest ---------------------------------------------------------------- QueueWorkingModuleTest::QueueWorkingModuleTest(TString tstrName) : TestCaseType(tstrName) { StartTrace(QueueWorkingModuleTest.QueueWorkingModuleTest); } TString QueueWorkingModuleTest::getConfigFileName() { return "QueueWorkingModuleTestConfig"; } QueueWorkingModuleTest::~QueueWorkingModuleTest() { StartTrace(QueueWorkingModuleTest.Dtor); } void QueueWorkingModuleTest::InitFinisNoModuleConfigTest() { StartTrace(QueueWorkingModuleTest.InitFinisNoModuleConfigTest); QueueWorkingModule aModule("QueueWorkingModule"); t_assertm( !aModule.Init(GetTestCaseConfig()["ModuleConfig"]), "module init should have failed due to missing configuration" ); } void QueueWorkingModuleTest::InitFinisDefaultsTest() { StartTrace(QueueWorkingModuleTest.InitFinisDefaultsTest); QueueWorkingModule aModule("QueueWorkingModule"); if ( t_assertm( aModule.Init(GetTestCaseConfig()["ModuleConfig"]), "module init should have succeeded" ) ) { if ( t_assert( aModule.fpContext != NULL ) ) { assertAnyEqual(GetTestCaseConfig()["ModuleConfig"]["QueueWorkingModule"], aModule.fpContext->GetEnvStore()); } if ( t_assert( aModule.fpQueue != NULL ) ) { assertEqualm(0L, aModule.fpQueue->GetSize(), "expected queue to be empty"); Anything anyStatistics; aModule.fpQueue->GetStatistics(anyStatistics); assertEqualm(100L, anyStatistics["QueueSize"].AsLong(-1L), "expected default queue size to be 100"); } // terminate module and perform some checks t_assert( aModule.Finis() ); t_assert( aModule.fpContext == NULL ); t_assert( aModule.fpQueue == NULL ); } } void QueueWorkingModuleTest::InitFinisTest() { StartTrace(QueueWorkingModuleTest.InitFinisTest); QueueWorkingModule aModule("QueueWorkingModule"); if ( t_assertm( aModule.Init(GetTestCaseConfig()["ModuleConfig"]), "module init should have succeeded" ) ) { if ( t_assert( aModule.fpContext != NULL ) ) { // check for invalid Server t_assertm( NULL == aModule.fpContext->GetServer(), "server must be NULL because of non-existing server"); assertAnyEqual(GetTestCaseConfig()["ModuleConfig"]["QueueWorkingModule"], aModule.fpContext->GetEnvStore()); } if ( t_assert( aModule.fpQueue != NULL ) ) { assertEqualm(0L, aModule.fpQueue->GetSize(), "expected queue to be empty"); Anything anyStatistics; aModule.fpQueue->GetStatistics(anyStatistics); assertEqualm(25L, anyStatistics["QueueSize"].AsLong(-1L), "expected queue size to be 25 as configured"); } // terminate module and perform some checks t_assert( aModule.Finis() ); t_assert( aModule.fpContext == NULL ); t_assert( aModule.fpQueue == NULL ); } } void QueueWorkingModuleTest::GetAndPutbackTest() { StartTrace(QueueWorkingModuleTest.GetAndPutbackTest); QueueWorkingModule aModule("QueueWorkingModule"); // set modules fAlive-field to enable working of the functions // first check if they don't work { Anything anyMsg; // must fail t_assert( !aModule.PutElement(anyMsg, false) ); // fails because of uninitialized queue t_assert( !aModule.GetElement(anyMsg, false) ); } aModule.IntInitQueue(GetTestCaseConfig()["ModuleConfig"]["QueueWorkingModule"]); { Anything anyMsg; // must still fail because of dead-state t_assert( !aModule.GetElement(anyMsg, false) ); } aModule.fAlive = 0xf007f007; if ( t_assertm( aModule.fpQueue != NULL , "queue should be created" ) ) { // queue is empty, so retrieving an element with tryLock=true should // return immediately and fail. { Anything anyElement; t_assert( !(aModule.GetElement(anyElement, true)) ); } // queue size is 1, so we load it with 1 element { Anything anyMsg; anyMsg["Number"] = 1; // this one must succeed t_assert( aModule.PutElement(anyMsg, false) ); } // now putback one message { Anything anyMsg; anyMsg["Number"] = 2; // this one must fail if ( t_assert( !aModule.PutElement(anyMsg, true) ) ) { aModule.PutBackElement(anyMsg); assertEqualm(1, aModule.fFailedPutbackMessages.GetSize(), "expected overflow buffer to contain an element"); } } Anything anyElement; if ( t_assert( aModule.GetElement(anyElement) ) ) { assertEqualm( 2, anyElement["Number"].AsLong(-1L), "expected to get putback element first"); } assertEqualm( 0, aModule.fFailedPutbackMessages.GetSize(), "expected overflow buffer to be empty now"); if ( t_assert( aModule.GetElement(anyElement) ) ) { assertEqualm( 1, anyElement["Number"].AsLong(-1L), "expected to get regular queue element last"); } assertEqualm( 0, aModule.fpQueue->GetSize(), "expected queue to be empty now"); aModule.IntCleanupQueue(); } } // builds up a suite of tests, add a line for each testmethod Test *QueueWorkingModuleTest::suite () { StartTrace(QueueWorkingModuleTest.suite); TestSuite *testSuite = new TestSuite; ADD_CASE(testSuite, QueueWorkingModuleTest, InitFinisNoModuleConfigTest); ADD_CASE(testSuite, QueueWorkingModuleTest, InitFinisDefaultsTest); ADD_CASE(testSuite, QueueWorkingModuleTest, InitFinisTest); ADD_CASE(testSuite, QueueWorkingModuleTest, GetAndPutbackTest); return testSuite; } <commit_msg>adjusted StatusCode checking of method calls<commit_after>/* * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ //--- interface include -------------------------------------------------------- #include "QueueWorkingModuleTest.h" //--- module under test -------------------------------------------------------- #include "QueueWorkingModule.h" //--- test modules used -------------------------------------------------------- #include "TestSuite.h" //--- project modules used ---------------------------------------------------- #include "Queue.h" //--- standard modules used ---------------------------------------------------- #include "System.h" #include "Dbg.h" //--- c-modules used ----------------------------------------------------------- //---- QueueWorkingModuleTest ---------------------------------------------------------------- QueueWorkingModuleTest::QueueWorkingModuleTest(TString tstrName) : TestCaseType(tstrName) { StartTrace(QueueWorkingModuleTest.QueueWorkingModuleTest); } TString QueueWorkingModuleTest::getConfigFileName() { return "QueueWorkingModuleTestConfig"; } QueueWorkingModuleTest::~QueueWorkingModuleTest() { StartTrace(QueueWorkingModuleTest.Dtor); } void QueueWorkingModuleTest::InitFinisNoModuleConfigTest() { StartTrace(QueueWorkingModuleTest.InitFinisNoModuleConfigTest); QueueWorkingModule aModule("QueueWorkingModule"); t_assertm( !aModule.Init(GetTestCaseConfig()["ModuleConfig"]), "module init should have failed due to missing configuration" ); } void QueueWorkingModuleTest::InitFinisDefaultsTest() { StartTrace(QueueWorkingModuleTest.InitFinisDefaultsTest); QueueWorkingModule aModule("QueueWorkingModule"); if ( t_assertm( aModule.Init(GetTestCaseConfig()["ModuleConfig"]), "module init should have succeeded" ) ) { if ( t_assert( aModule.fpContext != NULL ) ) { assertAnyEqual(GetTestCaseConfig()["ModuleConfig"]["QueueWorkingModule"], aModule.fpContext->GetEnvStore()); } if ( t_assert( aModule.fpQueue != NULL ) ) { assertEqualm(0L, aModule.fpQueue->GetSize(), "expected queue to be empty"); Anything anyStatistics; aModule.fpQueue->GetStatistics(anyStatistics); assertEqualm(100L, anyStatistics["QueueSize"].AsLong(-1L), "expected default queue size to be 100"); } // terminate module and perform some checks t_assert( aModule.Finis() ); t_assert( aModule.fpContext == NULL ); t_assert( aModule.fpQueue == NULL ); } } void QueueWorkingModuleTest::InitFinisTest() { StartTrace(QueueWorkingModuleTest.InitFinisTest); QueueWorkingModule aModule("QueueWorkingModule"); if ( t_assertm( aModule.Init(GetTestCaseConfig()["ModuleConfig"]), "module init should have succeeded" ) ) { if ( t_assert( aModule.fpContext != NULL ) ) { // check for invalid Server t_assertm( NULL == aModule.fpContext->GetServer(), "server must be NULL because of non-existing server"); assertAnyEqual(GetTestCaseConfig()["ModuleConfig"]["QueueWorkingModule"], aModule.fpContext->GetEnvStore()); } if ( t_assert( aModule.fpQueue != NULL ) ) { assertEqualm(0L, aModule.fpQueue->GetSize(), "expected queue to be empty"); Anything anyStatistics; aModule.fpQueue->GetStatistics(anyStatistics); assertEqualm(25L, anyStatistics["QueueSize"].AsLong(-1L), "expected queue size to be 25 as configured"); } // terminate module and perform some checks t_assert( aModule.Finis() ); t_assert( aModule.fpContext == NULL ); t_assert( aModule.fpQueue == NULL ); } } void QueueWorkingModuleTest::GetAndPutbackTest() { StartTrace(QueueWorkingModuleTest.GetAndPutbackTest); QueueWorkingModule aModule("QueueWorkingModule"); // set modules fAlive-field to enable working of the functions // first check if they don't work { Anything anyMsg; // must fail assertEqual( Queue::eDead, aModule.PutElement(anyMsg, false) ); // fails because of uninitialized queue assertEqual( Queue::eDead, aModule.GetElement(anyMsg, false) ); } aModule.IntInitQueue(GetTestCaseConfig()["ModuleConfig"]["QueueWorkingModule"]); { Anything anyMsg; // must still fail because of dead-state assertEqual( Queue::eDead, aModule.GetElement(anyMsg, false) ); } aModule.fAlive = 0xf007f007; if ( t_assertm( aModule.fpQueue != NULL , "queue should be created" ) ) { // queue is empty, so retrieving an element with tryLock=true should // return immediately and fail. { Anything anyElement; assertEqual( Queue::eEmpty, aModule.GetElement(anyElement, true) ); } // queue size is 1, so we load it with 1 element { Anything anyMsg; anyMsg["Number"] = 1; // this one must succeed assertEqual( Queue::eSuccess, aModule.PutElement(anyMsg, false) ); } // now putback one message { Anything anyMsg; anyMsg["Number"] = 2; // this one must fail if ( assertEqual( Queue::eFull, aModule.PutElement(anyMsg, true) ) ) { aModule.PutBackElement(anyMsg); assertEqualm(1, aModule.fFailedPutbackMessages.GetSize(), "expected overflow buffer to contain an element"); } } Anything anyElement; if ( assertEqual( Queue::eSuccess, aModule.GetElement(anyElement) ) ) { assertEqualm( 2, anyElement["Number"].AsLong(-1L), "expected to get putback element first"); } assertEqualm( 0, aModule.fFailedPutbackMessages.GetSize(), "expected overflow buffer to be empty now"); if ( assertEqual( Queue::eSuccess, aModule.GetElement(anyElement) ) ) { assertEqualm( 1, anyElement["Number"].AsLong(-1L), "expected to get regular queue element last"); } assertEqualm( 0, aModule.fpQueue->GetSize(), "expected queue to be empty now"); aModule.IntCleanupQueue(); } } // builds up a suite of tests, add a line for each testmethod Test *QueueWorkingModuleTest::suite () { StartTrace(QueueWorkingModuleTest.suite); TestSuite *testSuite = new TestSuite; ADD_CASE(testSuite, QueueWorkingModuleTest, InitFinisNoModuleConfigTest); ADD_CASE(testSuite, QueueWorkingModuleTest, InitFinisDefaultsTest); ADD_CASE(testSuite, QueueWorkingModuleTest, InitFinisTest); ADD_CASE(testSuite, QueueWorkingModuleTest, GetAndPutbackTest); return testSuite; } <|endoftext|>
<commit_before>#include <fcntl.h> constexpr size_t ev_buffsz = 512; #ifdef __linux__ #include "epoll.hpp" typedef nntpchan::ev::EpollLoop<ev_buffsz> LoopImpl; #else #ifdef __freebsd__ #include "kqueue.hpp" typedef nntpchan::ev::KqueueLoop<ev_buffsz> LoopImpl; #else #ifdef __netbsd__ typedef nntpchan::ev::KqueueLoop<ev_buffsz> LoopImpl; #else #error "unsupported platform" #endif #endif #endif namespace nntpchan { namespace ev { bool ev::Loop::BindTCP(const sockaddr *addr, ev::io *handler) { assert(handler->acceptable()); socklen_t slen; switch (addr->sa_family) { case AF_INET: slen = sizeof(sockaddr_in); break; case AF_INET6: slen = sizeof(sockaddr_in6); break; case AF_UNIX: slen = sizeof(sockaddr_un); break; default: return false; } int fd = socket(addr->sa_family, SOCK_STREAM | SOCK_NONBLOCK, 0); if (fd == -1) { return false; } if (bind(fd, addr, slen) == -1) { ::close(fd); return false; } if (listen(fd, 5) == -1) { ::close(fd); return false; } handler->fd = fd; return TrackConn(handler); } bool Loop::SetNonBlocking(ev::io *handler) { return fcntl(handler->fd, F_SETFL, fcntl(handler->fd, F_GETFL, 0) | O_NONBLOCK) != -1; } } ev::Loop *NewMainLoop() { return new LoopImpl; } }<commit_msg>correct define<commit_after>#include <fcntl.h> constexpr size_t ev_buffsz = 512; #ifdef __linux__ #include "epoll.hpp" typedef nntpchan::ev::EpollLoop<ev_buffsz> LoopImpl; #else #ifdef __FreeBSD__ #include "kqueue.hpp" typedef nntpchan::ev::KqueueLoop<ev_buffsz> LoopImpl; #else #ifdef __netbsd__ typedef nntpchan::ev::KqueueLoop<ev_buffsz> LoopImpl; #else #error "unsupported platform" #endif #endif #endif namespace nntpchan { namespace ev { bool ev::Loop::BindTCP(const sockaddr *addr, ev::io *handler) { assert(handler->acceptable()); socklen_t slen; switch (addr->sa_family) { case AF_INET: slen = sizeof(sockaddr_in); break; case AF_INET6: slen = sizeof(sockaddr_in6); break; case AF_UNIX: slen = sizeof(sockaddr_un); break; default: return false; } int fd = socket(addr->sa_family, SOCK_STREAM | SOCK_NONBLOCK, 0); if (fd == -1) { return false; } if (bind(fd, addr, slen) == -1) { ::close(fd); return false; } if (listen(fd, 5) == -1) { ::close(fd); return false; } handler->fd = fd; return TrackConn(handler); } bool Loop::SetNonBlocking(ev::io *handler) { return fcntl(handler->fd, F_SETFL, fcntl(handler->fd, F_GETFL, 0) | O_NONBLOCK) != -1; } } ev::Loop *NewMainLoop() { return new LoopImpl; } }<|endoftext|>
<commit_before>#include <gtest/gtest.h> #include "../../main/models/baseline/TransitionProbabilityModel.h" #include "../../main/models/baseline/TransitionProbabilityModelUpdater.h" #include "../../main/loggers/TransitionModelEndLogger.h" namespace{ class TestTransitionProbabilityModel : public ::testing::Test { public: TestTransitionProbabilityModel(){} virtual ~TestTransitionProbabilityModel(){} virtual void SetUp(){ } virtual void TearDown(){ } RecDat create_recdat(int time,int user,int item,int score){ RecDat rec_dat; rec_dat.time = time; rec_dat.user = user; rec_dat.item = item; rec_dat.score = score; return rec_dat; } }; class TestTransitionEndLogger : public ::testing::Test { public: TestTransitionEndLogger(){} virtual ~TestTransitionEndLogger(){} virtual void SetUp(){ } virtual void TearDown(){ for(int i=0;i<rec_dat_container_.size();i++){ delete rec_dat_container_[i]; } } vector<RecDat*> rec_dat_container_; RecDat* create_recdat(int time,int user,int item,int score){ RecDat* rec_dat = new RecDat; rec_dat->time = time; rec_dat->user = user; rec_dat->item = item; rec_dat->score = score; rec_dat_container_.push_back(rec_dat); return rec_dat; } }; } TEST_F(TestTransitionProbabilityModel, test){ //data vector<RecDat> timeline; timeline.push_back(create_recdat(0,10,20,1)); timeline.push_back(create_recdat(1,10,10,1)); timeline.push_back(create_recdat(2,10,20,1)); timeline.push_back(create_recdat(3,10,10,1)); timeline.push_back(create_recdat(4,10,20,1)); timeline.push_back(create_recdat(5,10,30,1)); timeline.push_back(create_recdat(5,20,20,1)); //another user timeline.push_back(create_recdat(6,10,20,1)); timeline.push_back(create_recdat(7,10,30,1)); timeline.push_back(create_recdat(8,10,20,1)); timeline.push_back(create_recdat(9,10,30,1)); timeline.push_back(create_recdat(10,10,20,1)); //statistics: a 20-as itemet 3-szor a 30-as, 2-szer a 10-es kovette //statistics: a 10-es itemet 2-szor a 20-as, 0-szor a 30-es kovette //statistics: a 30-as itemet 3-szor a 20-as, 0-szor a 10-es kovette TransitionProbabilityModel model; TransitionProbabilityModelUpdaterParameters params; TransitionProbabilityModelUpdater updater(&params); updater.set_model(&model); EXPECT_TRUE(model.self_test()); EXPECT_TRUE(updater.self_test()); RecDat rec_dat; rec_dat = create_recdat(30,10,30,1); EXPECT_EQ(0, model.prediction(&rec_dat)); rec_dat = create_recdat(30,20,30,1); EXPECT_EQ(0, model.prediction(&rec_dat)); for(RecDat rec_dat : timeline){ updater.update(&rec_dat); } rec_dat = create_recdat(30,10,30,1); EXPECT_EQ(log(3+1), model.prediction(&rec_dat)); rec_dat = create_recdat(30,20,30,1); EXPECT_EQ(log(3+1), model.prediction(&rec_dat)); rec_dat = create_recdat(30,10,10,1); EXPECT_EQ(log(2+1), model.prediction(&rec_dat)); rec_dat = create_recdat(30,20,10,1); EXPECT_EQ(log(2+1), model.prediction(&rec_dat)); } TEST_F(TestTransitionEndLogger, test){ vector<RecDat> timeline; TransitionProbabilityModel model; TransitionProbabilityModelUpdaterParameters params; params.filter_freq_updates = false; //default: do not do any filtering TransitionProbabilityModelUpdater updater(&params); updater.set_model(&model); EXPECT_TRUE(model.self_test()); EXPECT_TRUE(updater.self_test()); TransitionModelEndLoggerParameters logger_params; logger_params.max_length=5; TransitionModelEndLogger logger(&logger_params); logger.set_model(&model); PopContainer pop_container; logger.set_pop_container(&pop_container); EXPECT_TRUE(logger.self_test()); pop_container.increase(2); pop_container.increase(2); pop_container.increase(2); pop_container.increase(2); //4x pop_container.increase(3); pop_container.increase(3); //2x pop_container.increase(5); pop_container.increase(5); pop_container.increase(5); pop_container.increase(5); pop_container.increase(5); pop_container.increase(5); //6x RecDat* rec_dat; rec_dat = create_recdat(1,1,1,1); updater.update(rec_dat); for(int i=0;i<10;i++){ rec_dat = create_recdat(1,1,2,1); updater.update(rec_dat); rec_dat = create_recdat(1,1,3,1); updater.update(rec_dat); } rec_dat = create_recdat(1,1,1,1); updater.update(rec_dat); for(int i=0;i<10;i++){ rec_dat = create_recdat(1,1,4,1); updater.update(rec_dat); rec_dat = create_recdat(1,1,5,1); updater.update(rec_dat); rec_dat = create_recdat(1,1,6,1); updater.update(rec_dat); } rec_dat = create_recdat(1,1,1,1); updater.update(rec_dat); for(int i=0;i<10;i++){ RecDat* rec_dat_1 = create_recdat(1,1,7,1); RecDat* rec_dat_2 = create_recdat(1,1,i,1); for(int j=0;j<i;j++){ updater.update(rec_dat_1); updater.update(rec_dat_2); } } std::stringstream ss; logger.run_core(ss); vector<string> expected_lines; expected_lines.push_back("0 0 0"); expected_lines.push_back("1 3 0 7,2 2,1 4,1"); expected_lines.push_back("2 2 4 3,10 7,2"); expected_lines.push_back("3 3 2 2,9 7,3 1,1"); expected_lines.push_back("4 2 0 5,10 7,4"); expected_lines.push_back("5 2 6 6,10 7,5"); expected_lines.push_back("6 3 0 4,9 7,6 1,1"); expected_lines.push_back("7 9 0 7,14 9,9 8,8 6,6 5,5");// 4,4 3,3 2,2 1,1"); expected_lines.push_back("8 1 0 7,8"); expected_lines.push_back("9 1 0 7,8"); for(int i=0;i<expected_lines.size();i++){ string actual_line; std::getline(ss,actual_line); EXPECT_EQ(expected_lines[i],actual_line); } //cerr << ss.str() << endl; } int main (int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>expanded test of TransitionModel<commit_after>#include <gtest/gtest.h> #include "../../main/models/baseline/TransitionProbabilityModel.h" #include "../../main/models/baseline/TransitionProbabilityModelUpdater.h" #include "../../main/loggers/TransitionModelEndLogger.h" namespace{ class TestTransitionProbabilityModel : public ::testing::Test { public: TestTransitionProbabilityModel(){} virtual ~TestTransitionProbabilityModel(){} virtual void SetUp(){ } virtual void TearDown(){ } RecDat create_recdat(int time,int user,int item,int score){ RecDat rec_dat; rec_dat.time = time; rec_dat.user = user; rec_dat.item = item; rec_dat.score = score; return rec_dat; } }; class TestTransitionEndLogger : public ::testing::Test { public: TestTransitionEndLogger(){} virtual ~TestTransitionEndLogger(){} virtual void SetUp(){ } virtual void TearDown(){ for(int i=0;i<rec_dat_container_.size();i++){ delete rec_dat_container_[i]; } } vector<RecDat*> rec_dat_container_; RecDat* create_recdat(int time,int user,int item,int score){ RecDat* rec_dat = new RecDat; rec_dat->time = time; rec_dat->user = user; rec_dat->item = item; rec_dat->score = score; rec_dat_container_.push_back(rec_dat); return rec_dat; } }; } TEST_F(TestTransitionProbabilityModel, test_prediction){ //data vector<RecDat> timeline; timeline.push_back(create_recdat(0,10,20,1)); timeline.push_back(create_recdat(1,10,10,1)); timeline.push_back(create_recdat(2,10,20,1)); timeline.push_back(create_recdat(3,10,10,1)); timeline.push_back(create_recdat(4,10,20,1)); timeline.push_back(create_recdat(5,10,30,1)); timeline.push_back(create_recdat(5,20,20,1)); //another user timeline.push_back(create_recdat(6,10,20,1)); timeline.push_back(create_recdat(7,10,30,1)); timeline.push_back(create_recdat(8,10,20,1)); timeline.push_back(create_recdat(9,10,30,1)); timeline.push_back(create_recdat(10,10,20,1)); timeline.push_back(create_recdat(11,30,10,1)); //another user //statistics: a 20-as itemet 3-szor a 30-as, 2-szer a 10-es kovette //statistics: a 10-es itemet 2-szor a 20-as, 0-szor a 30-as kovette //statistics: a 30-as itemet 3-szor a 20-as, 0-szor a 10-es kovette TransitionProbabilityModel model; TransitionProbabilityModelUpdaterParameters params; TransitionProbabilityModelUpdater updater(&params); updater.set_model(&model); EXPECT_TRUE(model.self_test()); EXPECT_TRUE(updater.self_test()); RecDat rec_dat; rec_dat = create_recdat(30,10,30,1); EXPECT_EQ(0, model.prediction(&rec_dat)); rec_dat = create_recdat(30,20,30,1); EXPECT_EQ(0, model.prediction(&rec_dat)); for(RecDat rec_dat : timeline){ updater.update(&rec_dat); } rec_dat = create_recdat(30,10,10,1); EXPECT_EQ(log(2+1), model.prediction(&rec_dat)); rec_dat = create_recdat(30,10,30,1); EXPECT_EQ(log(3+1), model.prediction(&rec_dat)); rec_dat = create_recdat(30,20,10,1); EXPECT_EQ(log(2+1), model.prediction(&rec_dat)); rec_dat = create_recdat(30,20,30,1); EXPECT_EQ(log(3+1), model.prediction(&rec_dat)); rec_dat = create_recdat(30,30,20,1); EXPECT_EQ(log(2+1), model.prediction(&rec_dat)); rec_dat = create_recdat(30,30,30,1); EXPECT_EQ(0, model.prediction(&rec_dat)); } TEST_F(TestTransitionProbabilityModel, test_rsi){ //data vector<RecDat> timeline; timeline.push_back(create_recdat(0,10,20,1)); timeline.push_back(create_recdat(1,10,10,1)); timeline.push_back(create_recdat(2,10,20,1)); timeline.push_back(create_recdat(3,10,10,1)); timeline.push_back(create_recdat(4,10,20,1)); timeline.push_back(create_recdat(5,10,30,1)); timeline.push_back(create_recdat(5,20,20,1)); //another user timeline.push_back(create_recdat(6,10,20,1)); timeline.push_back(create_recdat(7,10,30,1)); timeline.push_back(create_recdat(8,10,20,1)); timeline.push_back(create_recdat(9,10,30,1)); timeline.push_back(create_recdat(10,10,20,1)); timeline.push_back(create_recdat(11,30,10,1)); //another user //statistics: a 20-as itemet 3-szor a 30-as, 2-szer a 10-es kovette //statistics: a 10-es itemet 2-szor a 20-as, 0-szor a 30-es kovette //statistics: a 30-as itemet 3-szor a 20-as, 0-szor a 10-es kovette TransitionProbabilityModel model; TransitionProbabilityModelUpdaterParameters params; TransitionProbabilityModelUpdater updater(&params); updater.set_model(&model); EXPECT_TRUE(model.self_test()); EXPECT_TRUE(updater.self_test()); for(RecDat rec_dat : timeline){ updater.update(&rec_dat); } RankingScoreIterator* rsi; double item_score; int item_id; vector<int> users = {10, 20}; for(user : users){ rsi = model.get_ranking_score_iterator(user); EXPECT_TRUE(rsi->has_next()); tie(item_id, item_score) = rsi->get_next(); EXPECT_EQ(30,item_id); EXPECT_DOUBLE_EQ(log(3+1),item_score); EXPECT_TRUE(rsi->has_next()); tie(item_id, item_score) = rsi->get_next(); EXPECT_EQ(10,item_id); EXPECT_DOUBLE_EQ(log(2+1),item_score); EXPECT_FALSE(rsi->has_next()); } rsi = model.get_ranking_score_iterator(30); //user 30 EXPECT_TRUE(rsi->has_next()); EXPECT_FALSE(rsi->has_next(log(2+1)+0.1)); EXPECT_TRUE(rsi->has_next(log(2+1)-0.1)); EXPECT_FALSE(rsi->has_next(log(2+1),true)); //strict EXPECT_TRUE(rsi->has_next(log(2+1),false)); //not strict tie(item_id, item_score) = rsi->get_next(); EXPECT_EQ(20,item_id); EXPECT_DOUBLE_EQ(log(2+1),item_score); EXPECT_FALSE(rsi->has_next()); } TEST_F(TestTransitionEndLogger, test){ vector<RecDat> timeline; TransitionProbabilityModel model; TransitionProbabilityModelUpdaterParameters params; params.filter_freq_updates = false; //default: do not do any filtering TransitionProbabilityModelUpdater updater(&params); updater.set_model(&model); EXPECT_TRUE(model.self_test()); EXPECT_TRUE(updater.self_test()); TransitionModelEndLoggerParameters logger_params; logger_params.max_length=5; TransitionModelEndLogger logger(&logger_params); logger.set_model(&model); PopContainer pop_container; logger.set_pop_container(&pop_container); EXPECT_TRUE(logger.self_test()); pop_container.increase(2); pop_container.increase(2); pop_container.increase(2); pop_container.increase(2); //4x pop_container.increase(3); pop_container.increase(3); //2x pop_container.increase(5); pop_container.increase(5); pop_container.increase(5); pop_container.increase(5); pop_container.increase(5); pop_container.increase(5); //6x RecDat* rec_dat; rec_dat = create_recdat(1,1,1,1); updater.update(rec_dat); for(int i=0;i<10;i++){ rec_dat = create_recdat(1,1,2,1); updater.update(rec_dat); rec_dat = create_recdat(1,1,3,1); updater.update(rec_dat); } rec_dat = create_recdat(1,1,1,1); updater.update(rec_dat); for(int i=0;i<10;i++){ rec_dat = create_recdat(1,1,4,1); updater.update(rec_dat); rec_dat = create_recdat(1,1,5,1); updater.update(rec_dat); rec_dat = create_recdat(1,1,6,1); updater.update(rec_dat); } rec_dat = create_recdat(1,1,1,1); updater.update(rec_dat); for(int i=0;i<10;i++){ RecDat* rec_dat_1 = create_recdat(1,1,7,1); RecDat* rec_dat_2 = create_recdat(1,1,i,1); for(int j=0;j<i;j++){ updater.update(rec_dat_1); updater.update(rec_dat_2); } } std::stringstream ss; logger.run_core(ss); vector<string> expected_lines; expected_lines.push_back("0 0 0"); expected_lines.push_back("1 3 0 7,2 2,1 4,1"); expected_lines.push_back("2 2 4 3,10 7,2"); expected_lines.push_back("3 3 2 2,9 7,3 1,1"); expected_lines.push_back("4 2 0 5,10 7,4"); expected_lines.push_back("5 2 6 6,10 7,5"); expected_lines.push_back("6 3 0 4,9 7,6 1,1"); expected_lines.push_back("7 9 0 7,14 9,9 8,8 6,6 5,5");// 4,4 3,3 2,2 1,1"); expected_lines.push_back("8 1 0 7,8"); expected_lines.push_back("9 1 0 7,8"); for(int i=0;i<expected_lines.size();i++){ string actual_line; std::getline(ss,actual_line); EXPECT_EQ(expected_lines[i],actual_line); } //cerr << ss.str() << endl; } int main (int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>// The MIT License (MIT) // // Copyright (c) 2016 Northeastern University // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS 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 "include/gpu_operations.h" #include "Eigen/Dense" #include "gtest/gtest.h" TEST(GPU_MATRIX_SCALAR_ADD, Basic_Test) { Nice::Matrix<float> a(3,4); a << 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4; Nice::Matrix<float> b = Nice::GpuOperations<float>::Add(a, 1); Nice::Matrix<float> answer(3, 4); answer << 2, 3, 4, 5, 2, 3, 4, 5, 2, 3, 4, 5; ASSERT_TRUE(answer.isApprox(b)); } <commit_msg>completed matrix-scalar-add<commit_after>// The MIT License (MIT) // // Copyright (c) 2016 Northeastern University // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS 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 "include/gpu_operations.h" #include "Eigen/Dense" #include "gtest/gtest.h" template<class T> class GPU_MATRIX_SCALAR_ADD : public ::testing::Test { public: Nice::Matrix<T> a; Nice::Matrix<T> correct_ans; Nice::Matrix<T> calc_ans; T scalar; void Add() { calc_ans = Nice::GpuOperations<T>::Add(a, scalar); } }; typedef ::testing::Types<float, double> dataTypes; TYPED_TEST_CASE(GPU_MATRIX_SCALAR_ADD, dataTypes); TYPED_TEST(GPU_MATRIX_SCALAR_ADD, Basic_Test) { this->a.resize(3,4); this->a << 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4; this->scalar = 1; this->Add(); this->correct_ans.resize(3, 4); this->correct_ans << 2, 3, 4, 5, 2, 3, 4, 5, 2, 3, 4, 5; ASSERT_TRUE(this->correct_ans.isApprox(this->calc_ans)); } <|endoftext|>
<commit_before>// // Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/boostorg/beast // //------------------------------------------------------------------------------ // // Example: WebSocket server, synchronous // //------------------------------------------------------------------------------ #include <boost/beast/core.hpp> #include <boost/beast/websocket.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/strand.hpp> #include <boost/functional/hash.hpp> //#include <boost/asio/buffers_iterator.hpp> //#include <cstdlib> //#include <functional> #include <iostream> #include <string> #include <thread> #include <array> #include <unordered_map> #include <strawpoll.hpp> using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp> namespace websocket = boost::beast::websocket; // from <boost/beast/websocket.hpp> //------------------------------------------------------------------------------ namespace detail { template<typename T> struct hash { size_t operator() (const T& v) const noexcept { if (v.is_v4()) return v.to_v4().to_ulong(); if (v.is_v6()) { auto const& range = v.to_v6().to_bytes(); return boost::hash_range(range.begin(), range.end()); } if (v.is_unspecified()) return 0x4751301174351161ul; return boost::hash_value(v.to_string()); } }; template<typename T, typename M> class member_func_ptr_closure { public: using obj_ptr_t = T*; using member_func_ptr_t = M; constexpr member_func_ptr_closure( obj_ptr_t obj_ptr, member_func_ptr_t member_func_ptr ) noexcept : obj_ptr_{obj_ptr}, member_func_ptr_{member_func_ptr} {} template<typename... Args> auto operator() (Args&&... args) { return ((obj_ptr_)->*(member_func_ptr_))(std::forward<Args>(args)...); } private: obj_ptr_t obj_ptr_; member_func_ptr_t member_func_ptr_; }; namespace conv { boost::asio::const_buffer m_b(FlatBufferRef buffer) { return { buffer.data, buffer.size }; } } } // namespace detail //using poll_data_t = PollData<VoteGuard<boost::asio::ip::address, detail::hash>>; using poll_data_t = PollData<HippieVoteGuard<boost::asio::ip::address>>; // Report a failure void fail(boost::system::error_code ec, char const* what) { std::cerr << what << ": " << ec.message() << "\n"; } // Echoes back all received WebSocket messages template<typename FC, typename FB> class session { public: // Take ownership of the socket explicit session( tcp::socket&& socket, boost::asio::ip::address address, FC on_close, FB broadcast, size_t session_id, poll_data_t& poll_data ) : ws_{std::move(socket)} , address_{address} , strand_{ws_.get_io_service()} , read_in_process_{false} , write_in_process_{false} , on_close_{on_close} , broadcast_{broadcast} , session_id_{session_id} , poll_data_{poll_data} { ws_.binary(true); // we'll only write binary // Accept the websocket handshake ws_.async_accept( strand_.wrap([this](boost::system::error_code ec) { on_accept(ec); }) ); } session(const session&) = delete; session(session&&) = default; session& operator= (const session&) = delete; session& operator= (session&&) = default; ~session() = default; void add_message(FlatBufferRef br) { if ( std::is_same_v< poll_data_t::vote_guard_t, HippieVoteGuard<boost::asio::ip::address> > || !write_in_process_ // write should always write the most recent || poll_data_.vote_guard.has_voted(address_) ) message_queue_.push_back(detail::conv::m_b(br)); } void flush_message_queue() { if (write_in_process_) return; if (message_queue_.empty()) return; ws_.async_write( std::array<boost::asio::const_buffer, 1>{{ std::move(message_queue_.back()) }}, strand_.wrap( [this](boost::system::error_code ec, size_t bytes_transferred) { write_in_process_ = false; on_write(ec, bytes_transferred); } ) ); write_in_process_ = true; message_queue_.pop_back(); } private: websocket::stream<tcp::socket> ws_; boost::asio::ip::address address_; boost::asio::io_service::strand strand_; boost::beast::multi_buffer buffer_; std::vector<boost::asio::const_buffer> message_queue_; bool read_in_process_; bool write_in_process_; FC on_close_; FB broadcast_; size_t session_id_; poll_data_t& poll_data_; void on_accept(boost::system::error_code ec) { if (ec) return fail(ec, "accept"); // Read a message do_read(); } void do_read() { if (read_in_process_) return; // Clear the buffer buffer_.consume(buffer_.size()); // Read a message into our buffer ws_.async_read( buffer_, strand_.wrap( [this](boost::system::error_code ec, size_t bytes_transferred) { read_in_process_ = false; on_read(ec, bytes_transferred); } ) ); read_in_process_ = true; } void on_read( boost::system::error_code ec, size_t bytes_transferred ) { boost::ignore_unused(bytes_transferred); // This indicates that the session was closed if (ec == websocket::error::closed) { on_close_(session_id_); return; } if (ec) fail(ec, "read"); build_responses(); flush_message_queue(); } void on_write( boost::system::error_code ec, size_t// bytes_transferred ) { //boost::ignore_unused(bytes_transferred); if (ec) return fail(ec, "write"); if (!message_queue_.empty()) { flush_message_queue(); return; } // Do another read do_read(); } void build_responses() { const auto add_response = [&queue = message_queue_](FlatBufferRef br) { queue.push_back(detail::conv::m_b(br)); }; for (const auto buffer : buffer_.data()) { const auto ok = flatbuffers::Verifier( boost::asio::buffer_cast<const uint8_t*>(buffer), boost::asio::buffer_size(buffer) ).VerifyBuffer<Strawpoll::Request>(nullptr); if (!ok) { add_response(poll_data_.error_responses.invalid_message.ref()); continue; } const auto request = flatbuffers::GetRoot<Strawpoll::Request>( boost::asio::buffer_cast<const uint8_t*>(buffer) ); switch(request->type()) { case Strawpoll::RequestType_Poll: add_response(poll_data_.poll_response.ref()); if (poll_data_.vote_guard.has_voted(address_)) add_response(poll_data_.result_ref()); break; case Strawpoll::RequestType_Result: poll_data_.register_vote( request->vote(), address_, add_response, [&broadcast = broadcast_](FlatBufferRef br) { broadcast(br); } ); break; default: add_response(poll_data_.error_responses.invalid_type.ref()); } } } }; // Accepts incoming connections and launches the sessions class listener { public: void on_session_close(size_t session_id) { sessions_.erase(session_id); } void broadcast(FlatBufferRef br) { for (auto& [key, session] : sessions_) { session.add_message(br); session.flush_message_queue(); } } using on_session_close_t = detail::member_func_ptr_closure< listener, decltype(&listener::on_session_close) >; using broadcast_t = detail::member_func_ptr_closure< listener, decltype(&listener::broadcast) >; using session_t = session<on_session_close_t, broadcast_t>; using sessions_t = std::unordered_map<size_t, session_t>; explicit listener( boost::asio::io_service& ios, tcp::endpoint endpoint) : strand_{ios} , acceptor_{ios} , socket_{ios} , session_id_counter_{} , on_session_close_{this, &listener::on_session_close} , broadcast_{this, &listener::broadcast} , poll_data_{} { boost::system::error_code ec; // Open the acceptor acceptor_.open(endpoint.protocol(), ec); if (ec) { fail(ec, "open"); return; } // Bind to the server address acceptor_.bind(endpoint, ec); if (ec) { fail(ec, "bind"); return; } // Start listening for connections acceptor_.listen(boost::asio::socket_base::max_connections, ec); if (ec) { fail(ec, "listen"); return; } if (! acceptor_.is_open()) return; do_accept(); } listener(const listener&) = delete; listener(listener&&) = default; listener& operator= (const listener&) = delete; listener& operator= (listener&&) = default; ~listener() = default; void do_accept() { acceptor_.async_accept( socket_, strand_.wrap([this](boost::system::error_code ec) { on_accept(ec); }) ); } void on_accept(boost::system::error_code ec) { if (ec) { fail(ec, "accept"); } else { // Create the session and run it const auto address = socket_.remote_endpoint().address(); sessions_.try_emplace( session_id_counter_, std::move(socket_), std::move(address), on_session_close_, broadcast_, session_id_counter_, poll_data_ ); ++session_id_counter_; } // Accept another connection do_accept(); } private: boost::asio::io_service::strand strand_; tcp::acceptor acceptor_; tcp::socket socket_; size_t session_id_counter_; on_session_close_t on_session_close_; broadcast_t broadcast_; sessions_t sessions_; poll_data_t poll_data_; }; //------------------------------------------------------------------------------ int main() { const auto address = boost::asio::ip::address::from_string("127.0.0.1"); const auto port = static_cast<unsigned short>(3003); boost::asio::io_service ios{1}; listener lis{ios, tcp::endpoint{address, port}}; ios.run(); // blocking } <commit_msg>Beast example cleanup<commit_after>// // Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/boostorg/beast // //------------------------------------------------------------------------------ // // Example: WebSocket server, synchronous // //------------------------------------------------------------------------------ #include <boost/beast/core.hpp> #include <boost/beast/websocket.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/strand.hpp> #include <boost/functional/hash.hpp> #include <iostream> #include <array> #include <unordered_map> #include <strawpoll.hpp> using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp> namespace websocket = boost::beast::websocket; // from <boost/beast/websocket.hpp> //------------------------------------------------------------------------------ namespace detail { template<typename T> struct hash { size_t operator() (const T& v) const noexcept { if (v.is_v4()) return v.to_v4().to_ulong(); if (v.is_v6()) { auto const& range = v.to_v6().to_bytes(); return boost::hash_range(range.begin(), range.end()); } if (v.is_unspecified()) return 0x4751301174351161ul; return boost::hash_value(v.to_string()); } }; template<typename T, typename M> class member_func_ptr_closure { public: using obj_ptr_t = T*; using member_func_ptr_t = M; constexpr member_func_ptr_closure( obj_ptr_t obj_ptr, member_func_ptr_t member_func_ptr ) noexcept : obj_ptr_{obj_ptr}, member_func_ptr_{member_func_ptr} {} template<typename... Args> auto operator() (Args&&... args) { return ((obj_ptr_)->*(member_func_ptr_))(std::forward<Args>(args)...); } private: obj_ptr_t obj_ptr_; member_func_ptr_t member_func_ptr_; }; namespace conv { boost::asio::const_buffer m_b(FlatBufferRef buffer) { return { buffer.data, buffer.size }; } } } // namespace detail //using poll_data_t = PollData<VoteGuard<boost::asio::ip::address, detail::hash>>; using poll_data_t = PollData<HippieVoteGuard<boost::asio::ip::address>>; // Report a failure void fail(boost::system::error_code ec, char const* what) { std::cerr << what << ": " << ec.message() << "\n"; } // Echoes back all received WebSocket messages template<typename FC, typename FB> class session { public: // Take ownership of the socket explicit session( tcp::socket&& socket, boost::asio::ip::address address, FC on_close, FB broadcast, size_t session_id, poll_data_t& poll_data ) : ws_{std::move(socket)} , address_{address} , strand_{ws_.get_io_service()} , read_in_process_{false} , write_in_process_{false} , on_close_{on_close} , broadcast_{broadcast} , session_id_{session_id} , poll_data_{poll_data} { ws_.binary(true); // we'll only write binary // Accept the websocket handshake ws_.async_accept( strand_.wrap([this](boost::system::error_code ec) { on_accept(ec); }) ); } session(const session&) = delete; session(session&&) = default; session& operator= (const session&) = delete; session& operator= (session&&) = default; ~session() = default; void add_message(FlatBufferRef br) { if ( std::is_same_v< poll_data_t::vote_guard_t, HippieVoteGuard<boost::asio::ip::address> > || !write_in_process_ // write should always write the most recent || poll_data_.vote_guard.has_voted(address_) ) message_queue_.push_back(detail::conv::m_b(br)); } void flush_message_queue() { if (write_in_process_) return; if (message_queue_.empty()) return; ws_.async_write( std::array<boost::asio::const_buffer, 1>{{ std::move(message_queue_.back()) }}, strand_.wrap( [this](boost::system::error_code ec, size_t bytes_transferred) { write_in_process_ = false; on_write(ec, bytes_transferred); } ) ); write_in_process_ = true; message_queue_.pop_back(); } private: websocket::stream<tcp::socket> ws_; boost::asio::ip::address address_; boost::asio::io_service::strand strand_; boost::beast::multi_buffer buffer_; std::vector<boost::asio::const_buffer> message_queue_; bool read_in_process_; bool write_in_process_; FC on_close_; FB broadcast_; size_t session_id_; poll_data_t& poll_data_; void on_accept(boost::system::error_code ec) { if (ec) return fail(ec, "accept"); // Read a message do_read(); } void do_read() { if (read_in_process_) return; // Clear the buffer buffer_.consume(buffer_.size()); // Read a message into our buffer ws_.async_read( buffer_, strand_.wrap( [this](boost::system::error_code ec, size_t bytes_transferred) { read_in_process_ = false; on_read(ec, bytes_transferred); } ) ); read_in_process_ = true; } void on_read( boost::system::error_code ec, size_t bytes_transferred ) { boost::ignore_unused(bytes_transferred); // This indicates that the session was closed if (ec == websocket::error::closed) { on_close_(session_id_); return; } if (ec) fail(ec, "read"); build_responses(); flush_message_queue(); } void on_write( boost::system::error_code ec, size_t// bytes_transferred ) { //boost::ignore_unused(bytes_transferred); if (ec) return fail(ec, "write"); if (!message_queue_.empty()) { flush_message_queue(); return; } // Do another read do_read(); } void build_responses() { const auto add_response = [&queue = message_queue_](FlatBufferRef br) { queue.push_back(detail::conv::m_b(br)); }; for (const auto buffer : buffer_.data()) { const auto ok = flatbuffers::Verifier( boost::asio::buffer_cast<const uint8_t*>(buffer), boost::asio::buffer_size(buffer) ).VerifyBuffer<Strawpoll::Request>(nullptr); if (!ok) { add_response(poll_data_.error_responses.invalid_message.ref()); continue; } const auto request = flatbuffers::GetRoot<Strawpoll::Request>( boost::asio::buffer_cast<const uint8_t*>(buffer) ); switch(request->type()) { case Strawpoll::RequestType_Poll: add_response(poll_data_.poll_response.ref()); if (poll_data_.vote_guard.has_voted(address_)) add_response(poll_data_.result_ref()); break; case Strawpoll::RequestType_Result: poll_data_.register_vote( request->vote(), address_, add_response, [&broadcast = broadcast_](FlatBufferRef br) { broadcast(br); } ); break; default: add_response(poll_data_.error_responses.invalid_type.ref()); } } } }; // Accepts incoming connections and launches the sessions class listener { public: void on_session_close(size_t session_id) { sessions_.erase(session_id); } void broadcast(FlatBufferRef br) { for (auto& [key, session] : sessions_) { session.add_message(br); session.flush_message_queue(); } } using on_session_close_t = detail::member_func_ptr_closure< listener, decltype(&listener::on_session_close) >; using broadcast_t = detail::member_func_ptr_closure< listener, decltype(&listener::broadcast) >; using session_t = session<on_session_close_t, broadcast_t>; using sessions_t = std::unordered_map<size_t, session_t>; explicit listener( boost::asio::io_service& ios, tcp::endpoint endpoint) : strand_{ios} , acceptor_{ios} , socket_{ios} , session_id_counter_{} , on_session_close_{this, &listener::on_session_close} , broadcast_{this, &listener::broadcast} , poll_data_{} { boost::system::error_code ec; // Open the acceptor acceptor_.open(endpoint.protocol(), ec); if (ec) { fail(ec, "open"); return; } // Bind to the server address acceptor_.bind(endpoint, ec); if (ec) { fail(ec, "bind"); return; } // Start listening for connections acceptor_.listen(boost::asio::socket_base::max_connections, ec); if (ec) { fail(ec, "listen"); return; } if (!acceptor_.is_open()) return; do_accept(); } listener(const listener&) = delete; listener(listener&&) = default; listener& operator= (const listener&) = delete; listener& operator= (listener&&) = default; ~listener() = default; void do_accept() { acceptor_.async_accept( socket_, strand_.wrap([this](boost::system::error_code ec) { on_accept(ec); }) ); } void on_accept(boost::system::error_code ec) { if (ec) { fail(ec, "accept"); } else { // Create the session and run it const auto address = socket_.remote_endpoint().address(); sessions_.try_emplace( session_id_counter_, std::move(socket_), std::move(address), on_session_close_, broadcast_, session_id_counter_, poll_data_ ); ++session_id_counter_; } // Accept another connection do_accept(); } private: boost::asio::io_service::strand strand_; tcp::acceptor acceptor_; tcp::socket socket_; size_t session_id_counter_; on_session_close_t on_session_close_; broadcast_t broadcast_; sessions_t sessions_; poll_data_t poll_data_; }; //------------------------------------------------------------------------------ int main() { const auto address = boost::asio::ip::address::from_string("127.0.0.1"); const auto port = static_cast<unsigned short>(3003); boost::asio::io_service ios{1}; listener lis{ios, tcp::endpoint{address, port}}; ios.run(); // blocking } <|endoftext|>
<commit_before>#include "Random.h" #include "VectorMath.h" #include "Common.h" namespace ECSE { std::random_device randomDevice; std::mt19937 ECSE::randomEngine(randomDevice()); sf::Vector2f ECSE::randomSpreadVector(float midAngle, float angleSpread, float minMag, float maxMag) { auto angleDist = std::uniform_real_distribution<float>( midAngle - angleSpread * 0.5f, midAngle + angleSpread * 0.5f ); auto magDist = std::uniform_real_distribution<float>(minMag, maxMag); float angle = angleDist(randomEngine); float mag = magDist(randomEngine); auto v = sf::Vector2f(mag, 0.f); setHeading(v, angle); return v; } sf::Vector2f ECSE::randomEllipticalVector(float xScale, float angle, float minMag, float maxMag) { // Just generate a random circular vector, scale it, and rotate it auto vec = ECSE::randomSpreadVector(0.f, ECSE::twoPi, minMag, maxMag); vec.x *= xScale; ECSE::rotate(vec, angle); return vec; } }<commit_msg>Fix explicit qualification.<commit_after>#include "Random.h" #include "VectorMath.h" #include "Common.h" namespace ECSE { std::random_device randomDevice; std::mt19937 randomEngine(randomDevice()); sf::Vector2f randomSpreadVector(float midAngle, float angleSpread, float minMag, float maxMag) { auto angleDist = std::uniform_real_distribution<float>( midAngle - angleSpread * 0.5f, midAngle + angleSpread * 0.5f ); auto magDist = std::uniform_real_distribution<float>(minMag, maxMag); float angle = angleDist(randomEngine); float mag = magDist(randomEngine); auto v = sf::Vector2f(mag, 0.f); setHeading(v, angle); return v; } sf::Vector2f randomEllipticalVector(float xScale, float angle, float minMag, float maxMag) { // Just generate a random circular vector, scale it, and rotate it auto vec = randomSpreadVector(0.f, ECSE::twoPi, minMag, maxMag); vec.x *= xScale; rotate(vec, angle); return vec; } } <|endoftext|>
<commit_before>//===- Strings.cpp -------------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Strings.h" #include "Config.h" #include "Error.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Twine.h" #include "llvm/Demangle/Demangle.h" #include <algorithm> #include <cstring> using namespace llvm; using namespace lld; using namespace lld::elf; StringMatcher::StringMatcher(ArrayRef<StringRef> Pat) { for (StringRef S : Pat) { Expected<GlobPattern> Pat = GlobPattern::create(S); if (!Pat) error(toString(Pat.takeError())); else Patterns.push_back(*Pat); } } bool StringMatcher::match(StringRef S) const { for (const GlobPattern &Pat : Patterns) if (Pat.match(S)) return true; return false; } // If an input string is in the form of "foo.N" where N is a number, // return N. Otherwise, returns 65536, which is one greater than the // lowest priority. int elf::getPriority(StringRef S) { size_t Pos = S.rfind('.'); if (Pos == StringRef::npos) return 65536; int V; if (S.substr(Pos + 1).getAsInteger(10, V)) return 65536; return V; } bool elf::hasWildcard(StringRef S) { return S.find_first_of("?*[") != StringRef::npos; } StringRef elf::unquote(StringRef S) { if (!S.startswith("\"")) return S; return S.substr(1, S.size() - 2); } // Converts a hex string (e.g. "deadbeef") to a vector. std::vector<uint8_t> elf::parseHex(StringRef S) { std::vector<uint8_t> Hex; while (!S.empty()) { StringRef B = S.substr(0, 2); S = S.substr(2); uint8_t H; if (B.getAsInteger(16, H)) { error("not a hexadecimal value: " + B); return {}; } Hex.push_back(H); } return Hex; } static bool isAlpha(char C) { return ('a' <= C && C <= 'z') || ('A' <= C && C <= 'Z') || C == '_'; } static bool isAlnum(char C) { return isAlpha(C) || ('0' <= C && C <= '9'); } // Returns true if S is valid as a C language identifier. bool elf::isValidCIdentifier(StringRef S) { return !S.empty() && isAlpha(S[0]) && std::all_of(S.begin() + 1, S.end(), isAlnum); } // Returns the demangled C++ symbol name for Name. Optional<std::string> elf::demangle(StringRef Name) { // __cxa_demangle can be used to demangle strings other than symbol // names which do not necessarily start with "_Z". Name can be // either a C or C++ symbol. Don't call __cxa_demangle if the name // does not look like a C++ symbol name to avoid getting unexpected // result for a C symbol that happens to match a mangled type name. if (!Name.startswith("_Z")) return None; char *Buf = itaniumDemangle(Name.str().c_str(), nullptr, nullptr, nullptr); if (!Buf) return None; std::string S(Buf); free(Buf); return S; } <commit_msg>[ELF] __cxa_demangle is now called itaniumDemangle. Update.<commit_after>//===- Strings.cpp -------------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Strings.h" #include "Config.h" #include "Error.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Twine.h" #include "llvm/Demangle/Demangle.h" #include <algorithm> #include <cstring> using namespace llvm; using namespace lld; using namespace lld::elf; StringMatcher::StringMatcher(ArrayRef<StringRef> Pat) { for (StringRef S : Pat) { Expected<GlobPattern> Pat = GlobPattern::create(S); if (!Pat) error(toString(Pat.takeError())); else Patterns.push_back(*Pat); } } bool StringMatcher::match(StringRef S) const { for (const GlobPattern &Pat : Patterns) if (Pat.match(S)) return true; return false; } // If an input string is in the form of "foo.N" where N is a number, // return N. Otherwise, returns 65536, which is one greater than the // lowest priority. int elf::getPriority(StringRef S) { size_t Pos = S.rfind('.'); if (Pos == StringRef::npos) return 65536; int V; if (S.substr(Pos + 1).getAsInteger(10, V)) return 65536; return V; } bool elf::hasWildcard(StringRef S) { return S.find_first_of("?*[") != StringRef::npos; } StringRef elf::unquote(StringRef S) { if (!S.startswith("\"")) return S; return S.substr(1, S.size() - 2); } // Converts a hex string (e.g. "deadbeef") to a vector. std::vector<uint8_t> elf::parseHex(StringRef S) { std::vector<uint8_t> Hex; while (!S.empty()) { StringRef B = S.substr(0, 2); S = S.substr(2); uint8_t H; if (B.getAsInteger(16, H)) { error("not a hexadecimal value: " + B); return {}; } Hex.push_back(H); } return Hex; } static bool isAlpha(char C) { return ('a' <= C && C <= 'z') || ('A' <= C && C <= 'Z') || C == '_'; } static bool isAlnum(char C) { return isAlpha(C) || ('0' <= C && C <= '9'); } // Returns true if S is valid as a C language identifier. bool elf::isValidCIdentifier(StringRef S) { return !S.empty() && isAlpha(S[0]) && std::all_of(S.begin() + 1, S.end(), isAlnum); } // Returns the demangled C++ symbol name for Name. Optional<std::string> elf::demangle(StringRef Name) { // itaniumDemangle can be used to demangle strings other than symbol // names which do not necessarily start with "_Z". Name can be // either a C or C++ symbol. Don't call itaniumDemangle if the name // does not look like a C++ symbol name to avoid getting unexpected // result for a C symbol that happens to match a mangled type name. if (!Name.startswith("_Z")) return None; char *Buf = itaniumDemangle(Name.str().c_str(), nullptr, nullptr, nullptr); if (!Buf) return None; std::string S(Buf); free(Buf); return S; } <|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/ui/views/location_bar/chrome_to_mobile_view.h" #include "base/utf_string_conversions.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/ui/view_ids.h" #include "chrome/browser/ui/views/browser_dialogs.h" #include "chrome/browser/ui/views/location_bar/location_bar_view.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "grit/theme_resources_standard.h" #include "ui/base/accessibility/accessible_view_state.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" ChromeToMobileView::ChromeToMobileView( LocationBarView* location_bar_view, CommandUpdater* command_updater) : location_bar_view_(location_bar_view), command_updater_(command_updater) { set_id(VIEW_ID_CHROME_TO_MOBILE_BUTTON); set_accessibility_focusable(true); SetImage(ResourceBundle::GetSharedInstance().GetBitmapNamed(IDR_STAR)); SetTooltipText( l10n_util::GetStringUTF16(IDS_CHROME_TO_MOBILE_BUBBLE_TOOLTIP)); SetVisible(command_updater_->IsCommandEnabled(IDC_CHROME_TO_MOBILE_PAGE)); command_updater_->AddCommandObserver(IDC_CHROME_TO_MOBILE_PAGE, this); } ChromeToMobileView::~ChromeToMobileView() { command_updater_->RemoveCommandObserver(IDC_CHROME_TO_MOBILE_PAGE, this); } void ChromeToMobileView::EnabledStateChangedForCommand(int id, bool enabled) { DCHECK_EQ(id, IDC_CHROME_TO_MOBILE_PAGE); if (enabled != visible()) { SetVisible(enabled); location_bar_view_->Update(NULL); } } void ChromeToMobileView::GetAccessibleState(ui::AccessibleViewState* state) { state->name = l10n_util::GetStringUTF16(IDS_ACCNAME_CHROME_TO_MOBILE); state->role = ui::AccessibilityTypes::ROLE_PUSHBUTTON; } bool ChromeToMobileView::GetTooltipText(const gfx::Point& p, string16* tooltip) const { // Don't show tooltip to distract user if ChromeToMobileBubbleView is showing. if (browser::IsChromeToMobileBubbleViewShowing()) return false; return ImageView::GetTooltipText(p, tooltip); } bool ChromeToMobileView::OnMousePressed(const views::MouseEvent& event) { // Show the bubble on mouse release; that is standard button behavior. return true; } void ChromeToMobileView::OnMouseReleased(const views::MouseEvent& event) { if (event.IsOnlyLeftMouseButton() && HitTest(event.location())) command_updater_->ExecuteCommand(IDC_CHROME_TO_MOBILE_PAGE); } bool ChromeToMobileView::OnKeyPressed(const views::KeyEvent& event) { if (event.key_code() == ui::VKEY_SPACE || event.key_code() == ui::VKEY_RETURN) { command_updater_->ExecuteCommand(IDC_CHROME_TO_MOBILE_PAGE); return true; } return false; } <commit_msg>Use Chrome To Mobile's new mobile device/phone icon. Replace IDR_STAR with IDR_MOBILE for the page action icon.<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/ui/views/location_bar/chrome_to_mobile_view.h" #include "base/utf_string_conversions.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/ui/view_ids.h" #include "chrome/browser/ui/views/browser_dialogs.h" #include "chrome/browser/ui/views/location_bar/location_bar_view.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "grit/theme_resources_standard.h" #include "ui/base/accessibility/accessible_view_state.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" ChromeToMobileView::ChromeToMobileView( LocationBarView* location_bar_view, CommandUpdater* command_updater) : location_bar_view_(location_bar_view), command_updater_(command_updater) { set_id(VIEW_ID_CHROME_TO_MOBILE_BUTTON); set_accessibility_focusable(true); SetImage(ResourceBundle::GetSharedInstance().GetBitmapNamed(IDR_MOBILE)); SetTooltipText( l10n_util::GetStringUTF16(IDS_CHROME_TO_MOBILE_BUBBLE_TOOLTIP)); SetVisible(command_updater_->IsCommandEnabled(IDC_CHROME_TO_MOBILE_PAGE)); command_updater_->AddCommandObserver(IDC_CHROME_TO_MOBILE_PAGE, this); } ChromeToMobileView::~ChromeToMobileView() { command_updater_->RemoveCommandObserver(IDC_CHROME_TO_MOBILE_PAGE, this); } void ChromeToMobileView::EnabledStateChangedForCommand(int id, bool enabled) { DCHECK_EQ(id, IDC_CHROME_TO_MOBILE_PAGE); if (enabled != visible()) { SetVisible(enabled); location_bar_view_->Update(NULL); } } void ChromeToMobileView::GetAccessibleState(ui::AccessibleViewState* state) { state->name = l10n_util::GetStringUTF16(IDS_ACCNAME_CHROME_TO_MOBILE); state->role = ui::AccessibilityTypes::ROLE_PUSHBUTTON; } bool ChromeToMobileView::GetTooltipText(const gfx::Point& p, string16* tooltip) const { // Don't show tooltip to distract user if ChromeToMobileBubbleView is showing. if (browser::IsChromeToMobileBubbleViewShowing()) return false; return ImageView::GetTooltipText(p, tooltip); } bool ChromeToMobileView::OnMousePressed(const views::MouseEvent& event) { // Show the bubble on mouse release; that is standard button behavior. return true; } void ChromeToMobileView::OnMouseReleased(const views::MouseEvent& event) { if (event.IsOnlyLeftMouseButton() && HitTest(event.location())) command_updater_->ExecuteCommand(IDC_CHROME_TO_MOBILE_PAGE); } bool ChromeToMobileView::OnKeyPressed(const views::KeyEvent& event) { if (event.key_code() == ui::VKEY_SPACE || event.key_code() == ui::VKEY_RETURN) { command_updater_->ExecuteCommand(IDC_CHROME_TO_MOBILE_PAGE); return true; } return false; } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #if !defined(OS_CHROMEOS) #include "chrome/browser/ui/webui/options/advanced_options_utils.h" #include "base/environment.h" #include "base/file_util.h" #include "base/nix/xdg_util.h" #include "base/process_util.h" #include "base/string_tokenizer.h" #include "chrome/browser/ui/browser_list.h" #include "content/browser/browser_thread.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/common/process_watcher.h" #include "ui/base/gtk/gtk_signal.h" // Command used to configure GNOME proxy settings. The command was renamed // in January 2009, so both are used to work on both old and new systems. const char* kOldGNOMEProxyConfigCommand[] = {"gnome-network-preferences", NULL}; const char* kGNOMEProxyConfigCommand[] = {"gnome-network-properties", NULL}; // KDE3 and KDE4 are only slightly different, but incompatible. Go figure. const char* kKDE3ProxyConfigCommand[] = {"kcmshell", "proxy", NULL}; const char* kKDE4ProxyConfigCommand[] = {"kcmshell4", "proxy", NULL}; // The URL for Linux proxy configuration help when not running under a // supported desktop environment. const char kLinuxProxyConfigUrl[] = "about:linux-proxy-config"; struct ProxyConfigCommand { std::string binary; const char** argv; }; namespace { // Search $PATH to find one of the commands. Store the full path to // it in the |binary| field and the command array index in in |index|. bool SearchPATH(ProxyConfigCommand* commands, size_t ncommands, size_t* index) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); const char* path = getenv("PATH"); if (!path) return false; FilePath bin_path; CStringTokenizer tk(path, path + strlen(path), ":"); // Search $PATH looking for the commands in order. while (tk.GetNext()) { for (size_t i = 0; i < ncommands; i++) { bin_path = FilePath(tk.token()).Append(commands[i].argv[0]); if (file_util::PathExists(bin_path)) { commands[i].binary = bin_path.value(); if (index) *index = i; return true; } } } // Did not find any of the binaries in $PATH. return false; } // Show the proxy config URL in the given tab. void ShowLinuxProxyConfigUrl(TabContents* tab_contents) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); scoped_ptr<base::Environment> env(base::Environment::Create()); const char* name = base::nix::GetDesktopEnvironmentName(env.get()); if (name) LOG(ERROR) << "Could not find " << name << " network settings in $PATH"; tab_contents->OpenURL(GURL(kLinuxProxyConfigUrl), GURL(), NEW_FOREGROUND_TAB, PageTransition::LINK); } // Start the given proxy configuration utility. void StartProxyConfigUtil(TabContents* tab_contents, const ProxyConfigCommand& command) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); std::vector<std::string> argv; argv.push_back(command.binary); for (size_t i = 1; command.argv[i]; i++) argv.push_back(command.argv[i]); base::file_handle_mapping_vector no_files; base::ProcessHandle handle; if (!base::LaunchApp(argv, no_files, false, &handle)) { LOG(ERROR) << "StartProxyConfigUtil failed to start " << command.binary; BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, NewRunnableFunction(&ShowLinuxProxyConfigUrl, tab_contents)); return; } ProcessWatcher::EnsureProcessGetsReaped(handle); } // Detect, and if possible, start the appropriate proxy config utility. On // failure to do so, show the Linux proxy config URL in a new tab instead. void DetectAndStartProxyConfigUtil(TabContents* tab_contents) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); scoped_ptr<base::Environment> env(base::Environment::Create()); ProxyConfigCommand command; bool found_command = false; switch (base::nix::GetDesktopEnvironment(env.get())) { case base::nix::DESKTOP_ENVIRONMENT_GNOME: { size_t index; ProxyConfigCommand commands[2]; commands[0].argv = kGNOMEProxyConfigCommand; commands[1].argv = kOldGNOMEProxyConfigCommand; found_command = SearchPATH(commands, 2, &index); if (found_command) command = commands[index]; break; } case base::nix::DESKTOP_ENVIRONMENT_KDE3: command.argv = kKDE3ProxyConfigCommand; found_command = SearchPATH(&command, 1, NULL); break; case base::nix::DESKTOP_ENVIRONMENT_KDE4: command.argv = kKDE4ProxyConfigCommand; found_command = SearchPATH(&command, 1, NULL); break; case base::nix::DESKTOP_ENVIRONMENT_XFCE: case base::nix::DESKTOP_ENVIRONMENT_OTHER: break; } if (found_command) { StartProxyConfigUtil(tab_contents, command); } else { BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, NewRunnableFunction(&ShowLinuxProxyConfigUrl, tab_contents)); } } } // anonymous namespace void AdvancedOptionsUtilities::ShowNetworkProxySettings( TabContents* tab_contents) { BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, NewRunnableFunction(&DetectAndStartProxyConfigUtil, tab_contents)); } #endif // !defined(OS_CHROMEOS) <commit_msg>Cleanup: Simplify the Linux proxy options code.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #if !defined(OS_CHROMEOS) #include "chrome/browser/ui/webui/options/advanced_options_utils.h" #include "base/environment.h" #include "base/nix/xdg_util.h" #include "base/process_util.h" #include "content/browser/browser_thread.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/common/process_watcher.h" // Command used to configure GNOME proxy settings. The command was renamed // in January 2009, so both are used to work on both old and new systems. // As on April 2011, many systems do not have the old command anymore. // TODO(thestig) Remove the old command in the future. const char* kOldGNOMEProxyConfigCommand[] = {"gnome-network-preferences", NULL}; const char* kGNOMEProxyConfigCommand[] = {"gnome-network-properties", NULL}; // KDE3 and KDE4 are only slightly different, but incompatible. Go figure. const char* kKDE3ProxyConfigCommand[] = {"kcmshell", "proxy", NULL}; const char* kKDE4ProxyConfigCommand[] = {"kcmshell4", "proxy", NULL}; // The URL for Linux proxy configuration help when not running under a // supported desktop environment. const char kLinuxProxyConfigUrl[] = "about:linux-proxy-config"; namespace { // Show the proxy config URL in the given tab. void ShowLinuxProxyConfigUrl(TabContents* tab_contents) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); scoped_ptr<base::Environment> env(base::Environment::Create()); const char* name = base::nix::GetDesktopEnvironmentName(env.get()); if (name) LOG(ERROR) << "Could not find " << name << " network settings in $PATH"; tab_contents->OpenURL(GURL(kLinuxProxyConfigUrl), GURL(), NEW_FOREGROUND_TAB, PageTransition::LINK); } // Start the given proxy configuration utility. bool StartProxyConfigUtil(TabContents* tab_contents, const char* command[]) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); std::vector<std::string> argv; for (size_t i = 0; command[i]; ++i) argv.push_back(command[i]); base::file_handle_mapping_vector no_files; base::ProcessHandle handle; if (!base::LaunchApp(argv, no_files, false, &handle)) { LOG(ERROR) << "StartProxyConfigUtil failed to start " << command[0]; return false; } ProcessWatcher::EnsureProcessGetsReaped(handle); return true; } // Detect, and if possible, start the appropriate proxy config utility. On // failure to do so, show the Linux proxy config URL in a new tab instead. void DetectAndStartProxyConfigUtil(TabContents* tab_contents) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); scoped_ptr<base::Environment> env(base::Environment::Create()); bool launched = false; switch (base::nix::GetDesktopEnvironment(env.get())) { case base::nix::DESKTOP_ENVIRONMENT_GNOME: { launched = StartProxyConfigUtil(tab_contents, kGNOMEProxyConfigCommand); if (!launched) { launched = StartProxyConfigUtil(tab_contents, kOldGNOMEProxyConfigCommand); } break; } case base::nix::DESKTOP_ENVIRONMENT_KDE3: launched = StartProxyConfigUtil(tab_contents, kKDE3ProxyConfigCommand); break; case base::nix::DESKTOP_ENVIRONMENT_KDE4: launched = StartProxyConfigUtil(tab_contents, kKDE4ProxyConfigCommand); break; case base::nix::DESKTOP_ENVIRONMENT_XFCE: case base::nix::DESKTOP_ENVIRONMENT_OTHER: break; } if (launched) return; BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, NewRunnableFunction(&ShowLinuxProxyConfigUrl, tab_contents)); } } // anonymous namespace void AdvancedOptionsUtilities::ShowNetworkProxySettings( TabContents* tab_contents) { BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, NewRunnableFunction(&DetectAndStartProxyConfigUtil, tab_contents)); } #endif // !defined(OS_CHROMEOS) <|endoftext|>
<commit_before>#include "FileChooser.h" #include "Settings.h" #include "GUIHelper.h" #include <QFileDialog> #include <QDragEnterEvent> #include <QDropEvent> #include <QUrl> #include <QMenu> #include <QDesktopServices> #include <QMimeData> #include <QBoxLayout> FileChooser::FileChooser(FileChooser::Type type, QWidget *parent) : QWidget(parent) , type_(type) { setAcceptDrops(true); //create layout QBoxLayout* layout = new QBoxLayout(QBoxLayout::LeftToRight); layout->setMargin(0); layout->setSpacing(3); setLayout(layout); //add widgets text_ = new QLineEdit(); layout->addWidget(text_); button_ = new QPushButton("browse"); layout->addWidget(button_); connect(button_, SIGNAL(clicked()), this, SLOT(browseFile())); } QString FileChooser::file() { return text_->text(); } void FileChooser::setFile(QString file) { text_->setText(file); } void FileChooser::browseFile() { QString file = ""; if (type_==LOAD) { file = QFileDialog::getOpenFileName(this, "Select input file.", Settings::path("open_data_folder"), "*.*"); if (file!="") { Settings::setPath("open_data_folder", file); } } else { file = QFileDialog::getSaveFileName(this, "Select output file.", Settings::path("store_data_folder"), "*.*"); if (file!="") { Settings::setPath("store_data_folder", file); } } text_->setText(file); text_->setToolTip(file); } void FileChooser::dragEnterEvent(QDragEnterEvent* e) { if (e->mimeData()->hasFormat("text/uri-list") && e->mimeData()->urls().count()==1) { e->acceptProposedAction(); } } void FileChooser::dropEvent(QDropEvent* e) { QString filename = e->mimeData()->urls().first().toLocalFile(); if (filename.isEmpty()) return; text_->setText(filename); } void FileChooser::contextMenuEvent(QContextMenuEvent* e) { //create menu QMenu* menu = new QMenu(); menu->addAction("Copy"); menu->addAction("Paste"); menu->addAction("Delete"); menu->addSeparator(); if (text_->text()!="") { menu->addAction("Open"); } //execute QAction* selected = menu->exec(e->globalPos()); //evaluate if (selected!=0) { if(selected->text()=="Copy") { text_->selectAll(); text_->copy(); text_->deselect(); } else if(selected->text()=="Paste") { QString previous = text_->text(); //paste text_->selectAll(); text_->paste(); text_->deselect(); //check file exists if (!QFile::exists(text_->text())) { GUIHelper::showMessage("Error", "File '" + text_->text() + "' does not exist!"); text_->setText(previous); } } else if(selected->text()=="Delete") { text_->clear(); } else if(selected->text()=="Open") { QDesktopServices::openUrl("file:///" + text_->text()); } } } <commit_msg>Updated because of settings handling.<commit_after>#include "FileChooser.h" #include "Settings.h" #include "GUIHelper.h" #include <QFileDialog> #include <QDragEnterEvent> #include <QDropEvent> #include <QUrl> #include <QMenu> #include <QDesktopServices> #include <QMimeData> #include <QBoxLayout> FileChooser::FileChooser(FileChooser::Type type, QWidget *parent) : QWidget(parent) , type_(type) { setAcceptDrops(true); //create layout QBoxLayout* layout = new QBoxLayout(QBoxLayout::LeftToRight); layout->setMargin(0); layout->setSpacing(3); setLayout(layout); //add widgets text_ = new QLineEdit(); layout->addWidget(text_); button_ = new QPushButton("browse"); layout->addWidget(button_); connect(button_, SIGNAL(clicked()), this, SLOT(browseFile())); } QString FileChooser::file() { return text_->text(); } void FileChooser::setFile(QString file) { text_->setText(file); } void FileChooser::browseFile() { QString file = ""; if (type_==LOAD) { file = QFileDialog::getOpenFileName(this, "Select input file.", Settings::path("open_data_folder", true), "*.*"); if (file!="") { Settings::setPath("open_data_folder", file); } } else { file = QFileDialog::getSaveFileName(this, "Select output file.", Settings::path("store_data_folder", true), "*.*"); if (file!="") { Settings::setPath("store_data_folder", file); } } text_->setText(file); text_->setToolTip(file); } void FileChooser::dragEnterEvent(QDragEnterEvent* e) { if (e->mimeData()->hasFormat("text/uri-list") && e->mimeData()->urls().count()==1) { e->acceptProposedAction(); } } void FileChooser::dropEvent(QDropEvent* e) { QString filename = e->mimeData()->urls().first().toLocalFile(); if (filename.isEmpty()) return; text_->setText(filename); } void FileChooser::contextMenuEvent(QContextMenuEvent* e) { //create menu QMenu* menu = new QMenu(); menu->addAction("Copy"); menu->addAction("Paste"); menu->addAction("Delete"); menu->addSeparator(); if (text_->text()!="") { menu->addAction("Open"); } //execute QAction* selected = menu->exec(e->globalPos()); //evaluate if (selected!=0) { if(selected->text()=="Copy") { text_->selectAll(); text_->copy(); text_->deselect(); } else if(selected->text()=="Paste") { QString previous = text_->text(); //paste text_->selectAll(); text_->paste(); text_->deselect(); //check file exists if (!QFile::exists(text_->text())) { GUIHelper::showMessage("Error", "File '" + text_->text() + "' does not exist!"); text_->setText(previous); } } else if(selected->text()=="Delete") { text_->clear(); } else if(selected->text()=="Open") { QDesktopServices::openUrl("file:///" + text_->text()); } } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: hyphenimp.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-07 19:40:02 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _LINGU2_HYPHENIMP_HXX_ #define _LINGU2_HYPHENIMP_HXX_ #include <uno/lbnames.h> // CPPU_CURRENT_LANGUAGE_BINDING_NAME macro, which specify the environment type #include <cppuhelper/implbase1.hxx> // helper for implementations #include <cppuhelper/implbase6.hxx> // helper for implementations #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEDISPLAYNAME_HPP_ #include <com/sun/star/lang/XServiceDisplayName.hpp> #endif #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/beans/PropertyValues.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/linguistic2/XHyphenator.hpp> #include <com/sun/star/linguistic2/XSearchableDictionaryList.hpp> #include <com/sun/star/linguistic2/XLinguServiceEventBroadcaster.hpp> #ifndef _TOOLS_TABLE_HXX #include <tools/table.hxx> #endif #include <unotools/charclass.hxx> #include <linguistic/misc.hxx> #include "hprophelp.hxx" #include <stdio.h> using namespace ::rtl; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::linguistic2; #define A2OU(x) ::rtl::OUString::createFromAscii( x ) #define OU2A(rtlOUString) ::rtl::OString((rtlOUString).getStr(), (rtlOUString).getLength(), RTL_TEXTENCODING_ASCII_US).getStr() #define OU2UTF8(rtlOUString) ::rtl::OString((rtlOUString).getStr(), (rtlOUString).getLength(), RTL_TEXTENCODING_UTF8).getStr() #define OU2ISO_1(rtlOUString) ::rtl::OString((rtlOUString).getStr(), (rtlOUString).getLength(), RTL_TEXTENCODING_ISO_8859_1).getStr() #define OU2ENC(rtlOUString, rtlEncoding) ::rtl::OString((rtlOUString).getStr(), (rtlOUString).getLength(), rtlEncoding).getStr() /////////////////////////////////////////////////////////////////////////// struct HDInfo { HyphenDict * aPtr; OUString aName; Locale aLoc; rtl_TextEncoding aEnc; CharClass * apCC; }; class Hyphenator : public cppu::WeakImplHelper6 < XHyphenator, XLinguServiceEventBroadcaster, XInitialization, XComponent, XServiceInfo, XServiceDisplayName > { Sequence< Locale > aSuppLocales; HDInfo * aDicts; sal_Int32 numdict; ::cppu::OInterfaceContainerHelper aEvtListeners; Reference< XPropertyChangeListener > xPropHelper; Reference< XMultiServiceFactory > rSMgr; PropertyHelper_Hyphen * pPropHelper; BOOL bDisposing; // disallow copy-constructor and assignment-operator for now Hyphenator(const Hyphenator &); Hyphenator & operator = (const Hyphenator &); PropertyHelper_Hyphen & GetPropHelper_Impl(); PropertyHelper_Hyphen & GetPropHelper() { return pPropHelper ? *pPropHelper : GetPropHelper_Impl(); } public: Hyphenator(); virtual ~Hyphenator(); // XSupportedLocales (for XHyphenator) virtual Sequence< Locale > SAL_CALL getLocales() throw(RuntimeException); virtual sal_Bool SAL_CALL hasLocale( const Locale& rLocale ) throw(RuntimeException); // XHyphenator virtual ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XHyphenatedWord > SAL_CALL hyphenate( const ::rtl::OUString& aWord, const ::com::sun::star::lang::Locale& aLocale, sal_Int16 nMaxLeading, const ::com::sun::star::beans::PropertyValues& aProperties ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XHyphenatedWord > SAL_CALL queryAlternativeSpelling( const ::rtl::OUString& aWord, const ::com::sun::star::lang::Locale& aLocale, sal_Int16 nIndex, const ::com::sun::star::beans::PropertyValues& aProperties ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XPossibleHyphens > SAL_CALL createPossibleHyphens( const ::rtl::OUString& aWord, const ::com::sun::star::lang::Locale& aLocale, const ::com::sun::star::beans::PropertyValues& aProperties ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); // XLinguServiceEventBroadcaster virtual sal_Bool SAL_CALL addLinguServiceEventListener( const Reference< XLinguServiceEventListener >& rxLstnr ) throw(RuntimeException); virtual sal_Bool SAL_CALL removeLinguServiceEventListener( const Reference< XLinguServiceEventListener >& rxLstnr ) throw(RuntimeException); // XServiceDisplayName virtual OUString SAL_CALL getServiceDisplayName( const Locale& rLocale ) throw(RuntimeException); // XInitialization virtual void SAL_CALL initialize( const Sequence< Any >& rArguments ) throw(Exception, RuntimeException); // XComponent virtual void SAL_CALL dispose() throw(RuntimeException); virtual void SAL_CALL addEventListener( const Reference< XEventListener >& rxListener ) throw(RuntimeException); virtual void SAL_CALL removeEventListener( const Reference< XEventListener >& rxListener ) throw(RuntimeException); //////////////////////////////////////////////////////////// // Service specific part // // XServiceInfo virtual OUString SAL_CALL getImplementationName() throw(RuntimeException); virtual sal_Bool SAL_CALL supportsService( const OUString& rServiceName ) throw(RuntimeException); virtual Sequence< OUString > SAL_CALL getSupportedServiceNames() throw(RuntimeException); static inline OUString getImplementationName_Static() throw(); static Sequence< OUString > getSupportedServiceNames_Static() throw(); private: OUString SAL_CALL makeLowerCase(const OUString&, CharClass *); }; inline OUString Hyphenator::getImplementationName_Static() throw() { return A2OU( "org.openoffice.lingu.LibHnjHyphenator" ); } /////////////////////////////////////////////////////////////////////////// #endif <commit_msg>INTEGRATION: CWS hyphenator2 (1.6.28); FILE MERGED 2006/01/27 00:44:15 nemeth 1.6.28.1: i61214 i58558<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: hyphenimp.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2006-02-06 16:23:50 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _LINGU2_HYPHENIMP_HXX_ #define _LINGU2_HYPHENIMP_HXX_ #include <uno/lbnames.h> // CPPU_CURRENT_LANGUAGE_BINDING_NAME macro, which specify the environment type #include <cppuhelper/implbase1.hxx> // helper for implementations #include <cppuhelper/implbase6.hxx> // helper for implementations #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEDISPLAYNAME_HPP_ #include <com/sun/star/lang/XServiceDisplayName.hpp> #endif #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/beans/PropertyValues.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/linguistic2/XHyphenator.hpp> #include <com/sun/star/linguistic2/XSearchableDictionaryList.hpp> #include <com/sun/star/linguistic2/XLinguServiceEventBroadcaster.hpp> #ifndef _TOOLS_TABLE_HXX #include <tools/table.hxx> #endif #include <unotools/charclass.hxx> #include <linguistic/misc.hxx> #include "hprophelp.hxx" #include <stdio.h> using namespace ::rtl; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::linguistic2; #define A2OU(x) ::rtl::OUString::createFromAscii( x ) #define OU2A(rtlOUString) ::rtl::OString((rtlOUString).getStr(), (rtlOUString).getLength(), RTL_TEXTENCODING_ASCII_US).getStr() #define OU2UTF8(rtlOUString) ::rtl::OString((rtlOUString).getStr(), (rtlOUString).getLength(), RTL_TEXTENCODING_UTF8).getStr() #define OU2ISO_1(rtlOUString) ::rtl::OString((rtlOUString).getStr(), (rtlOUString).getLength(), RTL_TEXTENCODING_ISO_8859_1).getStr() #define OU2ENC(rtlOUString, rtlEncoding) ::rtl::OString((rtlOUString).getStr(), (rtlOUString).getLength(), rtlEncoding).getStr() /////////////////////////////////////////////////////////////////////////// struct HDInfo { HyphenDict * aPtr; OUString aName; Locale aLoc; rtl_TextEncoding aEnc; CharClass * apCC; }; class Hyphenator : public cppu::WeakImplHelper6 < XHyphenator, XLinguServiceEventBroadcaster, XInitialization, XComponent, XServiceInfo, XServiceDisplayName > { Sequence< Locale > aSuppLocales; HDInfo * aDicts; sal_Int32 numdict; ::cppu::OInterfaceContainerHelper aEvtListeners; Reference< XPropertyChangeListener > xPropHelper; Reference< XMultiServiceFactory > rSMgr; PropertyHelper_Hyphen * pPropHelper; BOOL bDisposing; // disallow copy-constructor and assignment-operator for now Hyphenator(const Hyphenator &); Hyphenator & operator = (const Hyphenator &); PropertyHelper_Hyphen & GetPropHelper_Impl(); PropertyHelper_Hyphen & GetPropHelper() { return pPropHelper ? *pPropHelper : GetPropHelper_Impl(); } public: Hyphenator(); virtual ~Hyphenator(); // XSupportedLocales (for XHyphenator) virtual Sequence< Locale > SAL_CALL getLocales() throw(RuntimeException); virtual sal_Bool SAL_CALL hasLocale( const Locale& rLocale ) throw(RuntimeException); // XHyphenator virtual ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XHyphenatedWord > SAL_CALL hyphenate( const ::rtl::OUString& aWord, const ::com::sun::star::lang::Locale& aLocale, sal_Int16 nMaxLeading, const ::com::sun::star::beans::PropertyValues& aProperties ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XHyphenatedWord > SAL_CALL queryAlternativeSpelling( const ::rtl::OUString& aWord, const ::com::sun::star::lang::Locale& aLocale, sal_Int16 nIndex, const ::com::sun::star::beans::PropertyValues& aProperties ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XPossibleHyphens > SAL_CALL createPossibleHyphens( const ::rtl::OUString& aWord, const ::com::sun::star::lang::Locale& aLocale, const ::com::sun::star::beans::PropertyValues& aProperties ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); // XLinguServiceEventBroadcaster virtual sal_Bool SAL_CALL addLinguServiceEventListener( const Reference< XLinguServiceEventListener >& rxLstnr ) throw(RuntimeException); virtual sal_Bool SAL_CALL removeLinguServiceEventListener( const Reference< XLinguServiceEventListener >& rxLstnr ) throw(RuntimeException); // XServiceDisplayName virtual OUString SAL_CALL getServiceDisplayName( const Locale& rLocale ) throw(RuntimeException); // XInitialization virtual void SAL_CALL initialize( const Sequence< Any >& rArguments ) throw(Exception, RuntimeException); // XComponent virtual void SAL_CALL dispose() throw(RuntimeException); virtual void SAL_CALL addEventListener( const Reference< XEventListener >& rxListener ) throw(RuntimeException); virtual void SAL_CALL removeEventListener( const Reference< XEventListener >& rxListener ) throw(RuntimeException); //////////////////////////////////////////////////////////// // Service specific part // // XServiceInfo virtual OUString SAL_CALL getImplementationName() throw(RuntimeException); virtual sal_Bool SAL_CALL supportsService( const OUString& rServiceName ) throw(RuntimeException); virtual Sequence< OUString > SAL_CALL getSupportedServiceNames() throw(RuntimeException); static inline OUString getImplementationName_Static() throw(); static Sequence< OUString > getSupportedServiceNames_Static() throw(); private: sal_uInt16 SAL_CALL capitalType(const OUString&, CharClass *); OUString SAL_CALL makeLowerCase(const OUString&, CharClass *); OUString SAL_CALL makeUpperCase(const OUString&, CharClass *); OUString SAL_CALL makeInitCap(const OUString&, CharClass *); }; inline OUString Hyphenator::getImplementationName_Static() throw() { return A2OU( "org.openoffice.lingu.LibHnjHyphenator" ); } /////////////////////////////////////////////////////////////////////////// #endif <|endoftext|>
<commit_before>/* * RemoteSyslogAppender.cpp * * Copyright 2001, LifeLine Networks BV (www.lifeline.nl). All rights reserved. * Copyright 2001, Walter Stroebel. All rights reserved. * * See the COPYING file for the terms of usage and distribution. */ #include "log4cpp/Portability.hh" #ifdef LOG4CPP_HAVE_UNISTD_H # include <unistd.h> #endif #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "log4cpp/RemoteSyslogAppender.hh" #ifdef WIN32 #include <winsock2.h> #else #include <netdb.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #endif namespace log4cpp { int RemoteSyslogAppender::toSyslogPriority(Priority::Value priority) { static int priorities[8] = { LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG }; int result; priority++; priority /= 100; if (priority < 0) { result = LOG_EMERG; } else if (priority > 7) { result = LOG_DEBUG; } else { result = priorities[priority]; } return result; } RemoteSyslogAppender::RemoteSyslogAppender(const std::string& name, const std::string& syslogName, const std::string& relayer, int facility, int portNumber) : AppenderSkeleton(name), _syslogName(syslogName), _relayer(relayer), _facility(facility), _portNumber (portNumber), _socket (0), _ipAddr (0), _cludge (0) { open(); } RemoteSyslogAppender::~RemoteSyslogAppender() { close(); #ifdef WIN32 if (_cludge) { // we started it, we end it. WSACleanup (); } #endif } void RemoteSyslogAppender::open() { if (!_ipAddr) { struct hostent *pent = gethostbyname (_relayer.c_str ()); if (pent == NULL) { #ifdef WIN32 if (WSAGetLastError () == WSANOTINITIALISED) { WSADATA wsaData; int err; err = WSAStartup (0x101, &wsaData ); if (err) abort (); pent = gethostbyname (_relayer.c_str ()); _cludge = 1; } else { abort (); } #endif } if (pent == NULL) { unsigned long ip = (unsigned long) inet_addr (_relayer.c_str ()); pent = gethostbyaddr ((const char *) &ip, 4, AF_INET); } if (pent == NULL) { abort (); } _ipAddr = *((unsigned long *) pent->h_addr); } // Get a datagram socket. if ((_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { abort (); } else { sockaddr_in sain; sain.sin_family = AF_INET; sain.sin_port = htons (_portNumber); sain.sin_addr.s_addr = htonl (_ipAddr); if (connect (_socket, (struct sockaddr *) &sain, sizeof (sain)) < 0) { abort (); } } } void RemoteSyslogAppender::close() { if (_socket) { #if WIN32 closesocket (_socket); #else close (_socket); #endif _socket = 0; } } void RemoteSyslogAppender::_append(const LoggingEvent& event) { if (!_layout) { // XXX help! help! return; } std::string msgStr = _layout->format(event); const char* message = msgStr.c_str(); int len = strlen (message) + 16; char *buf = new char [len]; int priority = toSyslogPriority(event.priority); sprintf (buf, "<%d>", priority); memcpy (buf + strlen (buf), message, len - 16); sockaddr_in sain; sain.sin_family = AF_INET; sain.sin_port = htons (_portNumber); sain.sin_addr.s_addr = htonl (_ipAddr); int r = sendto (_socket, buf, (int) len, 0, (struct sockaddr *) &sain, sizeof (sain)); printf ("sendto: %d\n", r); delete buf; } bool RemoteSyslogAppender::reopen() { close(); open(); return true; } bool RemoteSyslogAppender::requiresLayout() const { return true; } void RemoteSyslogAppender::setLayout(Layout* layout) { _layout = layout; } } <commit_msg>Debugging<commit_after>/* * RemoteSyslogAppender.cpp * * Copyright 2001, LifeLine Networks BV (www.lifeline.nl). All rights reserved. * Copyright 2001, Walter Stroebel. All rights reserved. * * See the COPYING file for the terms of usage and distribution. */ #include "log4cpp/Portability.hh" #ifdef LOG4CPP_HAVE_UNISTD_H # include <unistd.h> #endif #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "log4cpp/RemoteSyslogAppender.hh" #ifdef WIN32 #include <winsock2.h> #else #include <netdb.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #endif namespace log4cpp { int RemoteSyslogAppender::toSyslogPriority(Priority::Value priority) { static int priorities[8] = { LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG }; int result; priority++; priority /= 100; if (priority < 0) { result = LOG_EMERG; } else if (priority > 7) { result = LOG_DEBUG; } else { result = priorities[priority]; } return result; } RemoteSyslogAppender::RemoteSyslogAppender(const std::string& name, const std::string& syslogName, const std::string& relayer, int facility, int portNumber) : AppenderSkeleton(name), _syslogName(syslogName), _relayer(relayer), _facility(facility), _portNumber (portNumber), _socket (0), _ipAddr (0), _cludge (0) { open(); } RemoteSyslogAppender::~RemoteSyslogAppender() { close(); #ifdef WIN32 if (_cludge) { // we started it, we end it. WSACleanup (); } #endif } void RemoteSyslogAppender::open() { if (!_ipAddr) { struct hostent *pent = gethostbyname (_relayer.c_str ()); if (pent == NULL) { #ifdef WIN32 if (WSAGetLastError () == WSANOTINITIALISED) { WSADATA wsaData; int err; err = WSAStartup (0x101, &wsaData ); if (err) abort (); pent = gethostbyname (_relayer.c_str ()); _cludge = 1; } else { abort (); } #endif } if (pent == NULL) { unsigned long ip = (unsigned long) inet_addr (_relayer.c_str ()); pent = gethostbyaddr ((const char *) &ip, 4, AF_INET); } if (pent == NULL) { abort (); } _ipAddr = *((unsigned long *) pent->h_addr); } // Get a datagram socket. if ((_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { abort (); } else { sockaddr_in sain; sain.sin_family = AF_INET; sain.sin_port = htons (_portNumber); sain.sin_addr.s_addr = htonl (_ipAddr); if (connect (_socket, (struct sockaddr *) &sain, sizeof (sain)) < 0) { abort (); } } } void RemoteSyslogAppender::close() { if (_socket) { #if WIN32 closesocket (_socket); #else ::close (_socket); #endif _socket = 0; } } void RemoteSyslogAppender::_append(const LoggingEvent& event) { if (!_layout) { // XXX help! help! return; } std::string msgStr = _layout->format(event); const char* message = msgStr.c_str(); int len = strlen (message) + 16; char *buf = new char [len]; int priority = toSyslogPriority(event.priority); sprintf (buf, "<%d>", priority); memcpy (buf + strlen (buf), message, len - 16); sockaddr_in sain; sain.sin_family = AF_INET; sain.sin_port = htons (_portNumber); sain.sin_addr.s_addr = htonl (_ipAddr); int r = sendto (_socket, buf, (int) len, 0, (struct sockaddr *) &sain, sizeof (sain)); printf ("sendto: %d\n", r); delete buf; } bool RemoteSyslogAppender::reopen() { close(); open(); return true; } bool RemoteSyslogAppender::requiresLayout() const { return true; } void RemoteSyslogAppender::setLayout(Layout* layout) { _layout = layout; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2016, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <wangle/acceptor/Acceptor.h> #include <wangle/acceptor/ManagedConnection.h> #include <wangle/ssl/SSLContextManager.h> #include <wangle/acceptor/AcceptorHandshakeManager.h> #include <wangle/acceptor/SecurityProtocolContextManager.h> #include <fcntl.h> #include <folly/ScopeGuard.h> #include <folly/io/async/EventBase.h> #include <fstream> #include <sys/types.h> #include <folly/io/async/AsyncSSLSocket.h> #include <folly/io/async/AsyncSocket.h> #include <folly/portability/Sockets.h> #include <folly/portability/Unistd.h> #include <gflags/gflags.h> using folly::AsyncSocket; using folly::AsyncSSLSocket; using folly::AsyncSocketException; using folly::AsyncServerSocket; using folly::AsyncTransportWrapper; using folly::EventBase; using folly::SocketAddress; using std::chrono::microseconds; using std::chrono::milliseconds; using std::filebuf; using std::ifstream; using std::ios; using std::shared_ptr; using std::string; namespace wangle { static const std::string empty_string; std::atomic<uint64_t> Acceptor::totalNumPendingSSLConns_{0}; Acceptor::Acceptor(const ServerSocketConfig& accConfig) : accConfig_(accConfig), socketOptions_(accConfig.getSocketOptions()) { } void Acceptor::init(AsyncServerSocket* serverSocket, EventBase* eventBase, SSLStats* stats) { CHECK(nullptr == this->base_ || eventBase == this->base_); if (accConfig_.isSSL()) { if (accConfig_.allowInsecureConnectionsOnSecureServer) { securityProtocolCtxManager_.addPeeker(&tlsPlaintextPeekingCallback_); } securityProtocolCtxManager_.addPeeker(&defaultPeekingCallback_); if (!sslCtxManager_) { sslCtxManager_ = folly::make_unique<SSLContextManager>( eventBase, "vip_" + getName(), accConfig_.strictSSL, stats); } try { for (const auto& sslCtxConfig : accConfig_.sslContextConfigs) { sslCtxManager_->addSSLContextConfig( sslCtxConfig, accConfig_.sslCacheOptions, &accConfig_.initialTicketSeeds, accConfig_.bindAddress, cacheProvider_); parseClientHello_ |= sslCtxConfig.clientHelloParsingEnabled; } CHECK(sslCtxManager_->getDefaultSSLCtx()); } catch (const std::runtime_error& ex) { sslCtxManager_->clear(); LOG(ERROR) << "Failed to configure TLS: " << ex.what(); } } base_ = eventBase; state_ = State::kRunning; downstreamConnectionManager_ = ConnectionManager::makeUnique( eventBase, accConfig_.connectionIdleTimeout, this); if (serverSocket) { serverSocket->addAcceptCallback(this, eventBase); for (auto& fd : serverSocket->getSockets()) { if (fd < 0) { continue; } for (const auto& opt: socketOptions_) { opt.first.apply(fd, opt.second); } } } } void Acceptor::resetSSLContextConfigs() { try { sslCtxManager_->resetSSLContextConfigs(accConfig_.sslContextConfigs, accConfig_.sslCacheOptions, &accConfig_.initialTicketSeeds, accConfig_.bindAddress, cacheProvider_); } catch (const std::runtime_error& ex) { LOG(ERROR) << "Failed to re-configure TLS: " << ex.what() << "will keep old config"; } } Acceptor::~Acceptor(void) { } void Acceptor::addSSLContextConfig(const SSLContextConfig& sslCtxConfig) { sslCtxManager_->addSSLContextConfig(sslCtxConfig, accConfig_.sslCacheOptions, &accConfig_.initialTicketSeeds, accConfig_.bindAddress, cacheProvider_); } void Acceptor::drainAllConnections() { if (downstreamConnectionManager_) { downstreamConnectionManager_->initiateGracefulShutdown( gracefulShutdownTimeout_); } } void Acceptor::setLoadShedConfig(const LoadShedConfiguration& from, IConnectionCounter* counter) { loadShedConfig_ = from; connectionCounter_ = counter; } bool Acceptor::canAccept(const SocketAddress& address) { if (!connectionCounter_) { return true; } uint64_t maxConnections = connectionCounter_->getMaxConnections(); if (maxConnections == 0) { return true; } uint64_t currentConnections = connectionCounter_->getNumConnections(); if (currentConnections < maxConnections) { return true; } if (loadShedConfig_.isWhitelisted(address)) { return true; } // Take care of the connection counts across all acceptors. // Expensive since a lock must be taken to get the counter. const auto activeConnLimit = loadShedConfig_.getMaxActiveConnections(); const auto totalConnLimit = loadShedConfig_.getMaxConnections(); const auto activeConnCount = getActiveConnectionCountForLoadShedding(); const auto totalConnCount = getConnectionCountForLoadShedding(); bool activeConnExceeded = (activeConnLimit > 0) && (activeConnCount >= activeConnLimit); bool totalConnExceeded = (totalConnLimit > 0) && (totalConnCount >= totalConnLimit); if (!activeConnExceeded && !totalConnExceeded) { return true; } VLOG(4) << address.describe() << " not whitelisted"; return false; } void Acceptor::connectionAccepted( int fd, const SocketAddress& clientAddr) noexcept { if (!canAccept(clientAddr)) { // Send a RST to free kernel memory faster struct linger optLinger = {1, 0}; ::setsockopt(fd, SOL_SOCKET, SO_LINGER, &optLinger, sizeof(optLinger)); close(fd); return; } auto acceptTime = std::chrono::steady_clock::now(); for (const auto& opt: socketOptions_) { opt.first.apply(fd, opt.second); } onDoneAcceptingConnection(fd, clientAddr, acceptTime); } void Acceptor::onDoneAcceptingConnection( int fd, const SocketAddress& clientAddr, std::chrono::steady_clock::time_point acceptTime) noexcept { TransportInfo tinfo; processEstablishedConnection(fd, clientAddr, acceptTime, tinfo); } void Acceptor::processEstablishedConnection( int fd, const SocketAddress& clientAddr, std::chrono::steady_clock::time_point acceptTime, TransportInfo& tinfo) noexcept { bool shouldDoSSL = false; if (accConfig_.isSSL()) { CHECK(sslCtxManager_); shouldDoSSL = sslCtxManager_->getDefaultSSLCtx() != nullptr; } if (shouldDoSSL) { AsyncSSLSocket::UniquePtr sslSock( makeNewAsyncSSLSocket( sslCtxManager_->getDefaultSSLCtx(), base_, fd)); ++numPendingSSLConns_; ++totalNumPendingSSLConns_; if (numPendingSSLConns_ > accConfig_.maxConcurrentSSLHandshakes) { VLOG(2) << "dropped SSL handshake on " << accConfig_.name << " too many handshakes in progress"; auto error = SSLErrorEnum::DROPPED; auto latency = std::chrono::milliseconds(0); updateSSLStats(sslSock.get(), latency, error); auto ex = folly::make_exception_wrapper<SSLException>( error, latency, sslSock->getRawBytesReceived()); sslConnectionError(ex); return; } startHandshakeManager( std::move(sslSock), this, clientAddr, acceptTime, tinfo); } else { tinfo.secure = false; tinfo.acceptTime = acceptTime; AsyncSocket::UniquePtr sock(makeNewAsyncSocket(base_, fd)); plaintextConnectionReady( std::move(sock), clientAddr, empty_string, SecureTransportType::NONE, tinfo); } } void Acceptor::startHandshakeManager( AsyncSSLSocket::UniquePtr sslSock, Acceptor* acceptor, const SocketAddress& clientAddr, std::chrono::steady_clock::time_point acceptTime, TransportInfo& tinfo) noexcept { auto manager = securityProtocolCtxManager_.getHandshakeManager( this, clientAddr, acceptTime, tinfo); manager->start(std::move(sslSock)); } void Acceptor::connectionReady( AsyncTransportWrapper::UniquePtr sock, const SocketAddress& clientAddr, const string& nextProtocolName, SecureTransportType secureTransportType, TransportInfo& tinfo) { // Limit the number of reads from the socket per poll loop iteration, // both to keep memory usage under control and to prevent one fast- // writing client from starving other connections. auto asyncSocket = sock->getUnderlyingTransport<AsyncSocket>(); asyncSocket->setMaxReadsPerEvent(16); tinfo.initWithSocket(asyncSocket); onNewConnection( std::move(sock), &clientAddr, nextProtocolName, secureTransportType, tinfo); } void Acceptor::plaintextConnectionReady( AsyncTransportWrapper::UniquePtr sock, const SocketAddress& clientAddr, const string& nextProtocolName, SecureTransportType secureTransportType, TransportInfo& tinfo) { connectionReady( std::move(sock), clientAddr, nextProtocolName, secureTransportType, tinfo); } void Acceptor::sslConnectionReady(AsyncTransportWrapper::UniquePtr sock, const SocketAddress& clientAddr, const string& nextProtocol, SecureTransportType secureTransportType, TransportInfo& tinfo) { CHECK(numPendingSSLConns_ > 0); --numPendingSSLConns_; --totalNumPendingSSLConns_; connectionReady( std::move(sock), clientAddr, nextProtocol, secureTransportType, tinfo); if (state_ == State::kDraining) { checkDrained(); } } void Acceptor::sslConnectionError(const folly::exception_wrapper& ex) { CHECK(numPendingSSLConns_ > 0); --numPendingSSLConns_; --totalNumPendingSSLConns_; if (state_ == State::kDraining) { checkDrained(); } } void Acceptor::acceptError(const std::exception& ex) noexcept { // An error occurred. // The most likely error is out of FDs. AsyncServerSocket will back off // briefly if we are out of FDs, then continue accepting later. // Just log a message here. LOG(ERROR) << "error accepting on acceptor socket: " << ex.what(); } void Acceptor::acceptStopped() noexcept { VLOG(3) << "Acceptor " << this << " acceptStopped()"; // Drain the open client connections drainAllConnections(); // If we haven't yet finished draining, begin doing so by marking ourselves // as in the draining state. We must be sure to hit checkDrained() here, as // if we're completely idle, we can should consider ourself drained // immediately (as there is no outstanding work to complete to cause us to // re-evaluate this). if (state_ != State::kDone) { state_ = State::kDraining; checkDrained(); } } void Acceptor::onEmpty(const ConnectionManager& cm) { VLOG(3) << "Acceptor=" << this << " onEmpty()"; if (state_ == State::kDraining) { checkDrained(); } } void Acceptor::checkDrained() { CHECK(state_ == State::kDraining); if (forceShutdownInProgress_ || (downstreamConnectionManager_->getNumConnections() != 0) || (numPendingSSLConns_ != 0)) { return; } VLOG(2) << "All connections drained from Acceptor=" << this << " in thread " << base_; downstreamConnectionManager_.reset(); state_ = State::kDone; onConnectionsDrained(); } void Acceptor::drainConnections(double pctToDrain) { if (downstreamConnectionManager_) { VLOG(3) << "Dropping " << pctToDrain * 100 << "% of " << getNumConnections() << " connections from Acceptor=" << this << " in thread " << base_; assert(base_->isInEventBaseThread()); downstreamConnectionManager_-> drainConnections(pctToDrain, gracefulShutdownTimeout_); } } milliseconds Acceptor::getConnTimeout() const { return accConfig_.connectionIdleTimeout; } void Acceptor::addConnection(ManagedConnection* conn) { // Add the socket to the timeout manager so that it can be cleaned // up after being left idle for a long time. downstreamConnectionManager_->addConnection(conn, true); } void Acceptor::forceStop() { base_->runInEventBaseThread([&] { dropAllConnections(); }); } void Acceptor::dropAllConnections() { if (downstreamConnectionManager_) { VLOG(3) << "Dropping all connections from Acceptor=" << this << " in thread " << base_; assert(base_->isInEventBaseThread()); forceShutdownInProgress_ = true; downstreamConnectionManager_->dropAllConnections(); CHECK(downstreamConnectionManager_->getNumConnections() == 0); downstreamConnectionManager_.reset(); } CHECK(numPendingSSLConns_ == 0); state_ = State::kDone; onConnectionsDrained(); } } // namespace wangle <commit_msg>Change config validation<commit_after>/* * Copyright (c) 2016, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <wangle/acceptor/Acceptor.h> #include <wangle/acceptor/ManagedConnection.h> #include <wangle/ssl/SSLContextManager.h> #include <wangle/acceptor/AcceptorHandshakeManager.h> #include <wangle/acceptor/SecurityProtocolContextManager.h> #include <fcntl.h> #include <folly/ScopeGuard.h> #include <folly/io/async/EventBase.h> #include <fstream> #include <sys/types.h> #include <folly/io/async/AsyncSSLSocket.h> #include <folly/io/async/AsyncSocket.h> #include <folly/portability/Sockets.h> #include <folly/portability/Unistd.h> #include <gflags/gflags.h> using folly::AsyncSocket; using folly::AsyncSSLSocket; using folly::AsyncSocketException; using folly::AsyncServerSocket; using folly::AsyncTransportWrapper; using folly::EventBase; using folly::SocketAddress; using std::chrono::microseconds; using std::chrono::milliseconds; using std::filebuf; using std::ifstream; using std::ios; using std::shared_ptr; using std::string; namespace wangle { static const std::string empty_string; std::atomic<uint64_t> Acceptor::totalNumPendingSSLConns_{0}; Acceptor::Acceptor(const ServerSocketConfig& accConfig) : accConfig_(accConfig), socketOptions_(accConfig.getSocketOptions()) { } void Acceptor::init(AsyncServerSocket* serverSocket, EventBase* eventBase, SSLStats* stats) { CHECK(nullptr == this->base_ || eventBase == this->base_); if (accConfig_.isSSL()) { if (accConfig_.allowInsecureConnectionsOnSecureServer) { securityProtocolCtxManager_.addPeeker(&tlsPlaintextPeekingCallback_); } securityProtocolCtxManager_.addPeeker(&defaultPeekingCallback_); if (!sslCtxManager_) { sslCtxManager_ = folly::make_unique<SSLContextManager>( eventBase, "vip_" + getName(), accConfig_.strictSSL, stats); } try { for (const auto& sslCtxConfig : accConfig_.sslContextConfigs) { sslCtxManager_->addSSLContextConfig( sslCtxConfig, accConfig_.sslCacheOptions, &accConfig_.initialTicketSeeds, accConfig_.bindAddress, cacheProvider_); parseClientHello_ |= sslCtxConfig.clientHelloParsingEnabled; } CHECK(sslCtxManager_->getDefaultSSLCtx()); } catch (const std::runtime_error& ex) { sslCtxManager_->clear(); // This is not a Not a fatal error, but useful to know. LOG(INFO) << "Failed to configure TLS. This is not a fatal error. " << ex.what(); } } base_ = eventBase; state_ = State::kRunning; downstreamConnectionManager_ = ConnectionManager::makeUnique( eventBase, accConfig_.connectionIdleTimeout, this); if (serverSocket) { serverSocket->addAcceptCallback(this, eventBase); for (auto& fd : serverSocket->getSockets()) { if (fd < 0) { continue; } for (const auto& opt: socketOptions_) { opt.first.apply(fd, opt.second); } } } } void Acceptor::resetSSLContextConfigs() { try { sslCtxManager_->resetSSLContextConfigs(accConfig_.sslContextConfigs, accConfig_.sslCacheOptions, &accConfig_.initialTicketSeeds, accConfig_.bindAddress, cacheProvider_); } catch (const std::runtime_error& ex) { LOG(ERROR) << "Failed to re-configure TLS: " << ex.what() << "will keep old config"; } } Acceptor::~Acceptor(void) { } void Acceptor::addSSLContextConfig(const SSLContextConfig& sslCtxConfig) { sslCtxManager_->addSSLContextConfig(sslCtxConfig, accConfig_.sslCacheOptions, &accConfig_.initialTicketSeeds, accConfig_.bindAddress, cacheProvider_); } void Acceptor::drainAllConnections() { if (downstreamConnectionManager_) { downstreamConnectionManager_->initiateGracefulShutdown( gracefulShutdownTimeout_); } } void Acceptor::setLoadShedConfig(const LoadShedConfiguration& from, IConnectionCounter* counter) { loadShedConfig_ = from; connectionCounter_ = counter; } bool Acceptor::canAccept(const SocketAddress& address) { if (!connectionCounter_) { return true; } uint64_t maxConnections = connectionCounter_->getMaxConnections(); if (maxConnections == 0) { return true; } uint64_t currentConnections = connectionCounter_->getNumConnections(); if (currentConnections < maxConnections) { return true; } if (loadShedConfig_.isWhitelisted(address)) { return true; } // Take care of the connection counts across all acceptors. // Expensive since a lock must be taken to get the counter. const auto activeConnLimit = loadShedConfig_.getMaxActiveConnections(); const auto totalConnLimit = loadShedConfig_.getMaxConnections(); const auto activeConnCount = getActiveConnectionCountForLoadShedding(); const auto totalConnCount = getConnectionCountForLoadShedding(); bool activeConnExceeded = (activeConnLimit > 0) && (activeConnCount >= activeConnLimit); bool totalConnExceeded = (totalConnLimit > 0) && (totalConnCount >= totalConnLimit); if (!activeConnExceeded && !totalConnExceeded) { return true; } VLOG(4) << address.describe() << " not whitelisted"; return false; } void Acceptor::connectionAccepted( int fd, const SocketAddress& clientAddr) noexcept { if (!canAccept(clientAddr)) { // Send a RST to free kernel memory faster struct linger optLinger = {1, 0}; ::setsockopt(fd, SOL_SOCKET, SO_LINGER, &optLinger, sizeof(optLinger)); close(fd); return; } auto acceptTime = std::chrono::steady_clock::now(); for (const auto& opt: socketOptions_) { opt.first.apply(fd, opt.second); } onDoneAcceptingConnection(fd, clientAddr, acceptTime); } void Acceptor::onDoneAcceptingConnection( int fd, const SocketAddress& clientAddr, std::chrono::steady_clock::time_point acceptTime) noexcept { TransportInfo tinfo; processEstablishedConnection(fd, clientAddr, acceptTime, tinfo); } void Acceptor::processEstablishedConnection( int fd, const SocketAddress& clientAddr, std::chrono::steady_clock::time_point acceptTime, TransportInfo& tinfo) noexcept { bool shouldDoSSL = false; if (accConfig_.isSSL()) { CHECK(sslCtxManager_); shouldDoSSL = sslCtxManager_->getDefaultSSLCtx() != nullptr; } if (shouldDoSSL) { AsyncSSLSocket::UniquePtr sslSock( makeNewAsyncSSLSocket( sslCtxManager_->getDefaultSSLCtx(), base_, fd)); ++numPendingSSLConns_; ++totalNumPendingSSLConns_; if (numPendingSSLConns_ > accConfig_.maxConcurrentSSLHandshakes) { VLOG(2) << "dropped SSL handshake on " << accConfig_.name << " too many handshakes in progress"; auto error = SSLErrorEnum::DROPPED; auto latency = std::chrono::milliseconds(0); updateSSLStats(sslSock.get(), latency, error); auto ex = folly::make_exception_wrapper<SSLException>( error, latency, sslSock->getRawBytesReceived()); sslConnectionError(ex); return; } startHandshakeManager( std::move(sslSock), this, clientAddr, acceptTime, tinfo); } else { tinfo.secure = false; tinfo.acceptTime = acceptTime; AsyncSocket::UniquePtr sock(makeNewAsyncSocket(base_, fd)); plaintextConnectionReady( std::move(sock), clientAddr, empty_string, SecureTransportType::NONE, tinfo); } } void Acceptor::startHandshakeManager( AsyncSSLSocket::UniquePtr sslSock, Acceptor* acceptor, const SocketAddress& clientAddr, std::chrono::steady_clock::time_point acceptTime, TransportInfo& tinfo) noexcept { auto manager = securityProtocolCtxManager_.getHandshakeManager( this, clientAddr, acceptTime, tinfo); manager->start(std::move(sslSock)); } void Acceptor::connectionReady( AsyncTransportWrapper::UniquePtr sock, const SocketAddress& clientAddr, const string& nextProtocolName, SecureTransportType secureTransportType, TransportInfo& tinfo) { // Limit the number of reads from the socket per poll loop iteration, // both to keep memory usage under control and to prevent one fast- // writing client from starving other connections. auto asyncSocket = sock->getUnderlyingTransport<AsyncSocket>(); asyncSocket->setMaxReadsPerEvent(16); tinfo.initWithSocket(asyncSocket); onNewConnection( std::move(sock), &clientAddr, nextProtocolName, secureTransportType, tinfo); } void Acceptor::plaintextConnectionReady( AsyncTransportWrapper::UniquePtr sock, const SocketAddress& clientAddr, const string& nextProtocolName, SecureTransportType secureTransportType, TransportInfo& tinfo) { connectionReady( std::move(sock), clientAddr, nextProtocolName, secureTransportType, tinfo); } void Acceptor::sslConnectionReady(AsyncTransportWrapper::UniquePtr sock, const SocketAddress& clientAddr, const string& nextProtocol, SecureTransportType secureTransportType, TransportInfo& tinfo) { CHECK(numPendingSSLConns_ > 0); --numPendingSSLConns_; --totalNumPendingSSLConns_; connectionReady( std::move(sock), clientAddr, nextProtocol, secureTransportType, tinfo); if (state_ == State::kDraining) { checkDrained(); } } void Acceptor::sslConnectionError(const folly::exception_wrapper& ex) { CHECK(numPendingSSLConns_ > 0); --numPendingSSLConns_; --totalNumPendingSSLConns_; if (state_ == State::kDraining) { checkDrained(); } } void Acceptor::acceptError(const std::exception& ex) noexcept { // An error occurred. // The most likely error is out of FDs. AsyncServerSocket will back off // briefly if we are out of FDs, then continue accepting later. // Just log a message here. LOG(ERROR) << "error accepting on acceptor socket: " << ex.what(); } void Acceptor::acceptStopped() noexcept { VLOG(3) << "Acceptor " << this << " acceptStopped()"; // Drain the open client connections drainAllConnections(); // If we haven't yet finished draining, begin doing so by marking ourselves // as in the draining state. We must be sure to hit checkDrained() here, as // if we're completely idle, we can should consider ourself drained // immediately (as there is no outstanding work to complete to cause us to // re-evaluate this). if (state_ != State::kDone) { state_ = State::kDraining; checkDrained(); } } void Acceptor::onEmpty(const ConnectionManager& cm) { VLOG(3) << "Acceptor=" << this << " onEmpty()"; if (state_ == State::kDraining) { checkDrained(); } } void Acceptor::checkDrained() { CHECK(state_ == State::kDraining); if (forceShutdownInProgress_ || (downstreamConnectionManager_->getNumConnections() != 0) || (numPendingSSLConns_ != 0)) { return; } VLOG(2) << "All connections drained from Acceptor=" << this << " in thread " << base_; downstreamConnectionManager_.reset(); state_ = State::kDone; onConnectionsDrained(); } void Acceptor::drainConnections(double pctToDrain) { if (downstreamConnectionManager_) { VLOG(3) << "Dropping " << pctToDrain * 100 << "% of " << getNumConnections() << " connections from Acceptor=" << this << " in thread " << base_; assert(base_->isInEventBaseThread()); downstreamConnectionManager_-> drainConnections(pctToDrain, gracefulShutdownTimeout_); } } milliseconds Acceptor::getConnTimeout() const { return accConfig_.connectionIdleTimeout; } void Acceptor::addConnection(ManagedConnection* conn) { // Add the socket to the timeout manager so that it can be cleaned // up after being left idle for a long time. downstreamConnectionManager_->addConnection(conn, true); } void Acceptor::forceStop() { base_->runInEventBaseThread([&] { dropAllConnections(); }); } void Acceptor::dropAllConnections() { if (downstreamConnectionManager_) { VLOG(3) << "Dropping all connections from Acceptor=" << this << " in thread " << base_; assert(base_->isInEventBaseThread()); forceShutdownInProgress_ = true; downstreamConnectionManager_->dropAllConnections(); CHECK(downstreamConnectionManager_->getNumConnections() == 0); downstreamConnectionManager_.reset(); } CHECK(numPendingSSLConns_ == 0); state_ = State::kDone; onConnectionsDrained(); } } // namespace wangle <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "app/gfx/gl/gl_implementation.h" #include "base/basictypes.h" #include "base/file_path.h" #include "base/string_util.h" #include "base/test/test_timeouts.h" #include "base/threading/platform_thread.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/test_launcher_utils.h" #include "chrome/test/ui/ui_layout_test.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" class MediaTest : public UITest { protected: virtual void SetUp() { EXPECT_TRUE(test_launcher_utils::OverrideGLImplementation( &launch_arguments_, gfx::kGLImplementationOSMesaName)); #if defined(OS_MACOSX) // Accelerated compositing does not work with OSMesa. AcceleratedSurface // assumes GL contexts are native. launch_arguments_.AppendSwitch(switches::kDisableAcceleratedCompositing); #endif UITest::SetUp(); } void PlayMedia(const char* tag, const char* media_file) { FilePath test_file(test_data_directory_); test_file = test_file.AppendASCII("media/player.html"); GURL player_gurl = net::FilePathToFileURL(test_file); std::string url = StringPrintf("%s?%s=%s", player_gurl.spec().c_str(), tag, media_file); NavigateToURL(GURL(url)); // Allow the media file to be loaded. const std::wstring kPlaying = L"PLAYING"; const std::wstring kFailed = L"FAILED"; const std::wstring kError = L"ERROR"; for (int i = 0; i < 10; ++i) { base::PlatformThread::Sleep(TestTimeouts::action_timeout_ms()); const std::wstring& title = GetActiveTabTitle(); if (title == kPlaying || title == kFailed || StartsWith(title, kError, true)) break; } EXPECT_EQ(kPlaying, GetActiveTabTitle()); } void PlayAudio(const char* url) { PlayMedia("audio", url); } void PlayVideo(const char* url) { PlayMedia("video", url); } }; TEST_F(MediaTest, VideoBearTheora) { PlayVideo("bear.ogv"); } TEST_F(MediaTest, VideoBearSilentTheora) { PlayVideo("bear_silent.ogv"); } TEST_F(MediaTest, VideoBearWebm) { PlayVideo("bear.webm"); } TEST_F(MediaTest, VideoBearSilentWebm) { PlayVideo("bear_silent.webm"); } #if defined(GOOGLE_CHROME_BUILD) || defined(USE_PROPRIETARY_CODECS) TEST_F(MediaTest, VideoBearMp4) { PlayVideo("bear.mp4"); } TEST_F(MediaTest, VideoBearSilentMp4) { PlayVideo("bear_silent.mp4"); } #endif TEST_F(MediaTest, VideoBearWav) { PlayVideo("bear.wav"); } // See crbug/73287. TEST_F(UILayoutTest, FAILS_MediaUILayoutTest) { static const char* kResources[] = { "content", "media-file.js", "media-fullscreen.js", "video-paint-test.js", "video-played.js", "video-test.js", }; static const char* kMediaTests[] = { "video-autoplay.html", // "video-loop.html", disabled due to 52887. "video-no-autoplay.html", // TODO(sergeyu): Add more tests here. }; FilePath test_dir; FilePath media_test_dir; media_test_dir = media_test_dir.AppendASCII("media"); InitializeForLayoutTest(test_dir, media_test_dir, kNoHttpPort); // Copy resources first. for (size_t i = 0; i < arraysize(kResources); ++i) AddResourceForLayoutTest( test_dir, media_test_dir.AppendASCII(kResources[i])); for (size_t i = 0; i < arraysize(kMediaTests); ++i) RunLayoutTest(kMediaTests[i], kNoHttpPort); } <commit_msg>Re-enable UILayoutTest.MediaUILayoutTest<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "app/gfx/gl/gl_implementation.h" #include "base/basictypes.h" #include "base/file_path.h" #include "base/string_util.h" #include "base/test/test_timeouts.h" #include "base/threading/platform_thread.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/test_launcher_utils.h" #include "chrome/test/ui/ui_layout_test.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" class MediaTest : public UITest { protected: virtual void SetUp() { EXPECT_TRUE(test_launcher_utils::OverrideGLImplementation( &launch_arguments_, gfx::kGLImplementationOSMesaName)); #if defined(OS_MACOSX) // Accelerated compositing does not work with OSMesa. AcceleratedSurface // assumes GL contexts are native. launch_arguments_.AppendSwitch(switches::kDisableAcceleratedCompositing); #endif UITest::SetUp(); } void PlayMedia(const char* tag, const char* media_file) { FilePath test_file(test_data_directory_); test_file = test_file.AppendASCII("media/player.html"); GURL player_gurl = net::FilePathToFileURL(test_file); std::string url = StringPrintf("%s?%s=%s", player_gurl.spec().c_str(), tag, media_file); NavigateToURL(GURL(url)); // Allow the media file to be loaded. const std::wstring kPlaying = L"PLAYING"; const std::wstring kFailed = L"FAILED"; const std::wstring kError = L"ERROR"; for (int i = 0; i < 10; ++i) { base::PlatformThread::Sleep(TestTimeouts::action_timeout_ms()); const std::wstring& title = GetActiveTabTitle(); if (title == kPlaying || title == kFailed || StartsWith(title, kError, true)) break; } EXPECT_EQ(kPlaying, GetActiveTabTitle()); } void PlayAudio(const char* url) { PlayMedia("audio", url); } void PlayVideo(const char* url) { PlayMedia("video", url); } }; TEST_F(MediaTest, VideoBearTheora) { PlayVideo("bear.ogv"); } TEST_F(MediaTest, VideoBearSilentTheora) { PlayVideo("bear_silent.ogv"); } TEST_F(MediaTest, VideoBearWebm) { PlayVideo("bear.webm"); } TEST_F(MediaTest, VideoBearSilentWebm) { PlayVideo("bear_silent.webm"); } #if defined(GOOGLE_CHROME_BUILD) || defined(USE_PROPRIETARY_CODECS) TEST_F(MediaTest, VideoBearMp4) { PlayVideo("bear.mp4"); } TEST_F(MediaTest, VideoBearSilentMp4) { PlayVideo("bear_silent.mp4"); } #endif TEST_F(MediaTest, VideoBearWav) { PlayVideo("bear.wav"); } TEST_F(UILayoutTest, MediaUILayoutTest) { static const char* kResources[] = { "content", "media-file.js", "media-fullscreen.js", "video-paint-test.js", "video-played.js", "video-test.js", }; static const char* kMediaTests[] = { "video-autoplay.html", // "video-loop.html", disabled due to 52887. "video-no-autoplay.html", // TODO(sergeyu): Add more tests here. }; FilePath test_dir; FilePath media_test_dir; media_test_dir = media_test_dir.AppendASCII("media"); InitializeForLayoutTest(test_dir, media_test_dir, kNoHttpPort); // Copy resources first. for (size_t i = 0; i < arraysize(kResources); ++i) AddResourceForLayoutTest( test_dir, media_test_dir.AppendASCII(kResources[i])); for (size_t i = 0; i < arraysize(kMediaTests); ++i) RunLayoutTest(kMediaTests[i], kNoHttpPort); } <|endoftext|>
<commit_before> #include "base64.h" #include <iostream> #include <stdint.h> #include <stdlib.h> #include <stdint.h> #include <stdlib.h> static char encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; static int mod_table[] = {0, 2, 1}; void b64::build_decoding_table() { this->decoding_table = (char *) malloc(256); for (int i = 0; i < 64; i++) this->decoding_table[(unsigned char) encoding_table[i]] = i; } void b64::base64_cleanup() { free(this->decoding_table); } b64::b64(){ //c'tor build_decoding_table(); } b64::~b64(){ //d'tor base64_cleanup(); } std::string b64::base64_encode(std::string src_str){ //Public interface unsigned int dst_len = 0; char * dst_data = base64_encode((const unsigned char *)src_str.c_str(), src_str.size()+1, &dst_len); std::string ret(dst_data, dst_len); delete dst_data; return ret; } std::string b64::base64_decode(std::string src_str){ //Public interface unsigned int dst_len = 0; unsigned char * dst_data = base64_decode(src_str.c_str(), src_str.size()+1, &dst_len); std::string ret((char*)dst_data, dst_len); delete dst_data; return ret; } std::string b64::base64_encode(unsigned char const* src_data, unsigned int src_len){ //Public interface unsigned int dst_len = 0; char * dst_data = base64_encode(src_data, src_len, &dst_len); std::string ret(dst_data, dst_len); delete dst_data; return ret; } std::string b64::base64_decode(char const* src_data, unsigned int src_len){ //Public interface unsigned int dst_len = 0; unsigned char * dst_data = base64_decode(src_data, src_len, &dst_len); std::string ret((char*)dst_data, dst_len); delete dst_data; return ret; } char * b64::base64_encode(const unsigned char *data, unsigned int input_length, unsigned int *output_length) { *output_length = 4 * ((input_length + 2) / 3); char *encoded_data = (char *)malloc(*output_length); if (encoded_data == NULL) return NULL; for (int i = 0, j = 0; i < input_length;) { uint32_t octet_a = i < input_length ? (unsigned char)data[i++] : 0; uint32_t octet_b = i < input_length ? (unsigned char)data[i++] : 0; uint32_t octet_c = i < input_length ? (unsigned char)data[i++] : 0; uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c; encoded_data[j++] = encoding_table[(triple >> 3 * 6) & 0x3F]; encoded_data[j++] = encoding_table[(triple >> 2 * 6) & 0x3F]; encoded_data[j++] = encoding_table[(triple >> 1 * 6) & 0x3F]; encoded_data[j++] = encoding_table[(triple >> 0 * 6) & 0x3F]; } for (int i = 0; i < mod_table[input_length % 3]; i++) encoded_data[*output_length - 1 - i] = '='; return encoded_data; } unsigned char * b64::base64_decode(const char *data, unsigned int input_length, unsigned int *output_length) { if (this->decoding_table == NULL) build_decoding_table(); if (input_length % 4 != 0) return NULL; *output_length = input_length / 4 * 3; if (data[input_length - 1] == '=') (*output_length)--; if (data[input_length - 2] == '=') (*output_length)--; unsigned char *decoded_data = (unsigned char *) malloc(*output_length); if (decoded_data == NULL) return NULL; for (int i = 0, j = 0; i < input_length;) { uint32_t sextet_a = data[i] == '=' ? 0 & i++ : this->decoding_table[data[i++]]; uint32_t sextet_b = data[i] == '=' ? 0 & i++ : this->decoding_table[data[i++]]; uint32_t sextet_c = data[i] == '=' ? 0 & i++ : this->decoding_table[data[i++]]; uint32_t sextet_d = data[i] == '=' ? 0 & i++ : this->decoding_table[data[i++]]; uint32_t triple = (sextet_a << 3 * 6) + (sextet_b << 2 * 6) + (sextet_c << 1 * 6) + (sextet_d << 0 * 6); if (j < *output_length) decoded_data[j++] = (triple >> 2 * 8) & 0xFF; if (j < *output_length) decoded_data[j++] = (triple >> 1 * 8) & 0xFF; if (j < *output_length) decoded_data[j++] = (triple >> 0 * 8) & 0xFF; } return decoded_data; } <commit_msg>Minor fixes<commit_after> #include "base64.h" #include <iostream> #include <stdint.h> #include <stdlib.h> #include <stdint.h> #include <stdlib.h> using namespace std; static char encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; static int mod_table[] = {0, 2, 1}; void b64::build_decoding_table() { this->decoding_table = (char *) malloc(256); for (int i = 0; i < 64; i++){ this->decoding_table[(unsigned char) encoding_table[i]] = i; } } void b64::base64_cleanup() { free(this->decoding_table); } b64::b64(){ //c'tor build_decoding_table(); } b64::~b64(){ //d'tor base64_cleanup(); } std::string b64::base64_encode(std::string src_str){ //Public interface unsigned int dst_len = 0; char * dst_data = base64_encode((const unsigned char *)src_str.c_str(), src_str.size(), &dst_len); std::string ret(dst_data, dst_len); delete dst_data; return ret; } std::string b64::base64_decode(std::string src_str){ //Public interface unsigned int dst_len = 0; unsigned char * dst_data = base64_decode(src_str.c_str(), src_str.size(), &dst_len); std::string ret((char*)dst_data, dst_len); delete dst_data; return ret; } std::string b64::base64_encode(unsigned char const* src_data, unsigned int src_len){ //Public interface unsigned int dst_len = 0; char * dst_data = base64_encode(src_data, src_len, &dst_len); std::string ret(dst_data, dst_len); delete dst_data; return ret; } std::string b64::base64_decode(char const* src_data, unsigned int src_len){ //Public interface unsigned int dst_len = 0; unsigned char * dst_data = base64_decode(src_data, src_len, &dst_len); std::string ret((char*)dst_data, dst_len); delete dst_data; return ret; } char * b64::base64_encode(const unsigned char *data, unsigned int input_length, unsigned int *output_length) { *output_length = 4 * ((input_length + 2) / 3); char *encoded_data = (char *)malloc(*output_length); if (encoded_data == NULL) return NULL; for (int i = 0, j = 0; i < input_length;) { uint32_t octet_a = i < input_length ? (unsigned char)data[i++] : 0; uint32_t octet_b = i < input_length ? (unsigned char)data[i++] : 0; uint32_t octet_c = i < input_length ? (unsigned char)data[i++] : 0; uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c; encoded_data[j++] = encoding_table[(triple >> 3 * 6) & 0x3F]; encoded_data[j++] = encoding_table[(triple >> 2 * 6) & 0x3F]; encoded_data[j++] = encoding_table[(triple >> 1 * 6) & 0x3F]; encoded_data[j++] = encoding_table[(triple >> 0 * 6) & 0x3F]; } for (int i = 0; i < mod_table[input_length % 3]; i++){ encoded_data[*output_length - 1 - i] = '='; } return encoded_data; } unsigned char * b64::base64_decode(const char *data, unsigned int input_length, unsigned int *output_length) { if (this->decoding_table == NULL) build_decoding_table(); if (input_length % 4 != 0) return NULL; *output_length = input_length / 4 * 3; if (data[input_length - 1] == '=') (*output_length)--; if (data[input_length - 2] == '=') (*output_length)--; unsigned char *decoded_data = (unsigned char *) malloc(*output_length); if (decoded_data == NULL) return NULL; for (int i = 0, j = 0; i < input_length;) { uint32_t sextet_a = data[i] == '=' ? 0 & i++ : this->decoding_table[data[i++]]; uint32_t sextet_b = data[i] == '=' ? 0 & i++ : this->decoding_table[data[i++]]; uint32_t sextet_c = data[i] == '=' ? 0 & i++ : this->decoding_table[data[i++]]; uint32_t sextet_d = data[i] == '=' ? 0 & i++ : this->decoding_table[data[i++]]; uint32_t triple = (sextet_a << 3 * 6) + (sextet_b << 2 * 6) + (sextet_c << 1 * 6) + (sextet_d << 0 * 6); if (j < *output_length) decoded_data[j++] = (triple >> 2 * 8) & 0xFF; if (j < *output_length) decoded_data[j++] = (triple >> 1 * 8) & 0xFF; if (j < *output_length) decoded_data[j++] = (triple >> 0 * 8) & 0xFF; } return decoded_data; } <|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 "base/file_util.h" #include "base/path_service.h" #include "build/build_config.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/test/test_server.h" #include "webkit/glue/plugins/plugin_switches.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); FilePath::StringType pepper_plugin = plugin_lib.value(); pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests")); launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); // Some stuff is hung off of the testing interface which is not enabled // by default. launch_arguments_.AppendSwitch(switches::kEnablePepperTesting); } void RunTest(const std::string& test_case) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("third_party")); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html")); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL::Replacements replacements; replacements.SetQuery(test_case.c_str(), url_parse::Component(0, test_case.size())); GURL test_url = net::FilePathToFileURL(test_path); RunTestURL(test_url.ReplaceComponents(replacements)); } void RunTestViaHTTP(const std::string& test_case) { net::TestServer test_server( net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("third_party/ppapi/tests"))); ASSERT_TRUE(test_server.Start()); RunTestURL(test_server.GetURL("files/test_case.html?" + test_case)); } private: void RunTestURL(const GURL& test_url) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); std::string escaped_value = WaitUntilCookieNonEmpty(tab.get(), test_url, "COMPLETION_COOKIE", action_max_timeout_ms()); EXPECT_STREQ("PASS", escaped_value.c_str()); } }; TEST_F(PPAPITest, FAILS_Instance) { RunTest("Instance"); } // http://crbug.com/54150 TEST_F(PPAPITest, FLAKY_Graphics2D) { RunTest("Graphics2D"); } // TODO(brettw) bug 51344: this is flaky on bots. Seems to timeout navigating. // Possibly all the image allocations slow things down on a loaded bot too much. TEST_F(PPAPITest, FLAKY_ImageData) { RunTest("ImageData"); } TEST_F(PPAPITest, Buffer) { RunTest("Buffer"); } TEST_F(PPAPITest, URLLoader) { RunTestViaHTTP("URLLoader"); } // Flaky, http://crbug.com/51012 TEST_F(PPAPITest, FLAKY_PaintAggregator) { RunTestViaHTTP("PaintAggregator"); } // Flaky, http://crbug.com/48544. TEST_F(PPAPITest, FLAKY_Scrollbar) { RunTest("Scrollbar"); } TEST_F(PPAPITest, UrlUtil) { RunTest("UrlUtil"); } TEST_F(PPAPITest, CharSet) { RunTest("CharSet"); } <commit_msg>Mark PPAPITest.URLLoader as flaky.<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 "base/file_util.h" #include "base/path_service.h" #include "build/build_config.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/test/test_server.h" #include "webkit/glue/plugins/plugin_switches.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); FilePath::StringType pepper_plugin = plugin_lib.value(); pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests")); launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); // Some stuff is hung off of the testing interface which is not enabled // by default. launch_arguments_.AppendSwitch(switches::kEnablePepperTesting); } void RunTest(const std::string& test_case) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("third_party")); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html")); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL::Replacements replacements; replacements.SetQuery(test_case.c_str(), url_parse::Component(0, test_case.size())); GURL test_url = net::FilePathToFileURL(test_path); RunTestURL(test_url.ReplaceComponents(replacements)); } void RunTestViaHTTP(const std::string& test_case) { net::TestServer test_server( net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("third_party/ppapi/tests"))); ASSERT_TRUE(test_server.Start()); RunTestURL(test_server.GetURL("files/test_case.html?" + test_case)); } private: void RunTestURL(const GURL& test_url) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); std::string escaped_value = WaitUntilCookieNonEmpty(tab.get(), test_url, "COMPLETION_COOKIE", action_max_timeout_ms()); EXPECT_STREQ("PASS", escaped_value.c_str()); } }; TEST_F(PPAPITest, FAILS_Instance) { RunTest("Instance"); } // http://crbug.com/54150 TEST_F(PPAPITest, FLAKY_Graphics2D) { RunTest("Graphics2D"); } // TODO(brettw) bug 51344: this is flaky on bots. Seems to timeout navigating. // Possibly all the image allocations slow things down on a loaded bot too much. TEST_F(PPAPITest, FLAKY_ImageData) { RunTest("ImageData"); } TEST_F(PPAPITest, Buffer) { RunTest("Buffer"); } TEST_F(PPAPITest, FLAKY_URLLoader) { RunTestViaHTTP("URLLoader"); } // Flaky, http://crbug.com/51012 TEST_F(PPAPITest, FLAKY_PaintAggregator) { RunTestViaHTTP("PaintAggregator"); } // Flaky, http://crbug.com/48544. TEST_F(PPAPITest, FLAKY_Scrollbar) { RunTest("Scrollbar"); } TEST_F(PPAPITest, UrlUtil) { RunTest("UrlUtil"); } TEST_F(PPAPITest, CharSet) { RunTest("CharSet"); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: tbxctl.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: obo $ $Date: 2004-07-06 13:07:25 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _TBXCTL_HXX #define _TBXCTL_HXX #ifndef _SFXTBXCTRL_HXX //autogen #include <sfx2/tbxctrl.hxx> #endif /************************************************************************* |* |* Klasse f"ur SwToolbox |* \************************************************************************/ class SvxTbxCtlDraw : public SfxToolBoxControl { private: USHORT nLastAction; public: virtual void Select( BOOL bMod1 = FALSE ); virtual void StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ); virtual SfxPopupWindowType GetPopupWindowType() const; virtual SfxPopupWindow* CreatePopupWindow(); SFX_DECL_TOOLBOX_CONTROL(); SvxTbxCtlDraw( USHORT nSlotId, USHORT nId, ToolBox& rTbx ); ~SvxTbxCtlDraw() {} void SetLastAction( USHORT nAction ) { nLastAction = nAction; } }; #endif <commit_msg>INTEGRATION: CWS toolbars3 (1.2.250); FILE MERGED 2004/11/12 11:20:33 pb 1.2.250.1: fix: #i37018# toggleToolbox() added<commit_after>/************************************************************************* * * $RCSfile: tbxctl.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2004-11-26 20:13:23 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _TBXCTL_HXX #define _TBXCTL_HXX #ifndef _SFXTBXCTRL_HXX //autogen #include <sfx2/tbxctrl.hxx> #endif /************************************************************************* |* |* Klasse f"ur SwToolbox |* \************************************************************************/ class SvxTbxCtlDraw : public SfxToolBoxControl { private: ::rtl::OUString m_sToolboxName; void toggleToolbox(); public: SvxTbxCtlDraw( USHORT nSlotId, USHORT nId, ToolBox& rTbx ); ~SvxTbxCtlDraw() {} SFX_DECL_TOOLBOX_CONTROL(); virtual void Select( BOOL bMod1 = FALSE ); virtual void StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ); virtual SfxPopupWindowType GetPopupWindowType() const; }; #endif <|endoftext|>
<commit_before>#include "core/argparse.h" #include "core/image.h" #include "core/imagefilters.h" #include "core/palette_all.h" #include "core/io.h" #include <iostream> #include <sstream> #include <iomanip> using namespace euphoria::core; int main(int argc, char* argv[]) { auto parser = argparse::Parser {"Apply filters to images"}; std::string input; std::string output = "ret.png"; Image image; auto load_image = [&] { auto ret = LoadImage(io::FileToChunk(input), input, AlphaLoad::Keep); if(!ret.error.empty()) { std::cerr << ret.error << "\n"; return false; } else { image = ret.image; return true; } }; auto write_image = [&] { io::ChunkToFile(image.Write(ImageWriteFormat::PNG), output); }; // todo(Gustav): change to generate/open - filter - save subparsing instead (with image targets) parser.Add("input", &input).Help("The image to apply filters to"); parser.Add("-o, --output", &output) .Help("Where to write the resulting image"); auto subs = parser.AddSubParsers(); subs->Add ( "nop", "Don't do anything", [&](argparse::SubParser* sub) { return sub->OnComplete ( [&] { if(!load_image()) { return; } write_image(); } ); } ); subs->Add ( "grayscale", "Apply grayscale", [&](argparse::SubParser* sub) { Grayscale grayscale = Grayscale::Average; sub->Add("-g,--grayscale", &grayscale); return sub->OnComplete ( [&] { if(!load_image()) { return; } MakeGrayscale(&image, grayscale); write_image(); } ); } ); subs->Add ( "palswap", "Switch palette", [&](argparse::SubParser* sub) { palette::PaletteName palette = palette::PaletteName::OneBit; bool pal_dither = false; sub->Add("-p, --palette", &palette); sub->SetTrue("-d, --dither", &pal_dither); return sub->OnComplete ( [&] { if(!load_image()) { return; } if(pal_dither) { MatchPaletteDither(&image, palette::GetPalette(palette)); } else { MatchPalette(&image, palette::GetPalette(palette)); } write_image(); } ); } ); subs->Add ( "edge", "Edge detection", [&](argparse::SubParser* sub) { float edge_r = 0.5f; sub->Add("-r, --range", &edge_r); return sub->OnComplete ( [&] { if(!load_image()) { return; } EdgeDetection(&image, edge_r); write_image(); } ); } ); subs->Add ( "color", "Detect colors", [&](argparse::SubParser* sub) { float edge_r = 0.5f; auto color_color = Color::Red; sub->Add("-r, --range", &edge_r); sub->Add("-c, --color", &color_color); return sub->OnComplete ( [&] { if(!load_image()) { return; } ColorDetection(&image, color_color, edge_r); write_image(); } ); } ); subs->Add ( "bright", "Change brightness", [&](argparse::SubParser* sub) { int bright_c = 10; sub->Add("-c, --change", &bright_c); return sub->OnComplete ( [&] { if(!load_image()) { return; } ChangeBrightness(&image, bright_c); write_image(); } ); } ); subs->Add ( "contrast", "Change contrast", [&](argparse::SubParser* sub) { float contrast = 10; sub->Add("-c, --change", &contrast); return sub->OnComplete ( [&] { if (!load_image()) { return; } ChangeContrast(&image, contrast); write_image(); } ); } ); return argparse::ParseFromMain(&parser, argc, argv); } <commit_msg>refactored img tool so that it reflects how it is supposed to work (but currently doesn't)<commit_after>#include "core/argparse.h" #include "core/image.h" #include "core/imagefilters.h" #include "core/palette_all.h" #include "core/io.h" #include <iostream> #include <sstream> #include <iomanip> using namespace euphoria::core; int main(int argc, char* argv[]) { Image image; auto parser = argparse::Parser {"Apply filters to images"}; auto io_subs = parser.AddSubParsers("transfer image to/from disk"); io_subs->Add ( "open", "Load image from disk", [&](argparse::SubParser* sub) { std::string input; parser.Add("input", &input).Help("The image to apply filters to"); return sub->OnComplete ( [&] { auto ret = LoadImage(io::FileToChunk(input), input, AlphaLoad::Keep); if(!ret.error.empty()) { std::cerr << ret.error << "\n"; // return false; } else { image = ret.image; // return true; } } ); } ); io_subs->Add ( "save", "Write image to disk", [&](argparse::SubParser* sub) { std::string output = "ret.png"; parser.Add("-o, --output", &output).Help ( "Where to write the resulting image" ); return sub->OnComplete ( [&] { io::ChunkToFile(image.Write(ImageWriteFormat::PNG), output); } ); } ); auto filters_subs = parser.AddSubParsers("apply filter to current image"); filters_subs->Add ( "grayscale", "Apply grayscale", [&](argparse::SubParser* sub) { Grayscale grayscale = Grayscale::Average; sub->Add("-g,--grayscale", &grayscale); return sub->OnComplete ( [&] { MakeGrayscale(&image, grayscale); } ); } ); filters_subs->Add ( "palswap", "Switch palette", [&](argparse::SubParser* sub) { palette::PaletteName palette = palette::PaletteName::OneBit; bool pal_dither = false; sub->Add("-p, --palette", &palette); sub->SetTrue("-d, --dither", &pal_dither); return sub->OnComplete ( [&] { if(pal_dither) { MatchPaletteDither(&image, palette::GetPalette(palette)); } else { MatchPalette(&image, palette::GetPalette(palette)); } } ); } ); filters_subs->Add ( "edge", "Edge detection", [&](argparse::SubParser* sub) { float edge_r = 0.5f; sub->Add("-r, --range", &edge_r); return sub->OnComplete ( [&] { EdgeDetection(&image, edge_r); } ); } ); filters_subs->Add ( "color", "Detect colors", [&](argparse::SubParser* sub) { float edge_r = 0.5f; auto color_color = Color::Red; sub->Add("-r, --range", &edge_r); sub->Add("-c, --color", &color_color); return sub->OnComplete ( [&] { ColorDetection(&image, color_color, edge_r); } ); } ); filters_subs->Add ( "bright", "Change brightness", [&](argparse::SubParser* sub) { int bright_c = 10; sub->Add("-c, --change", &bright_c); return sub->OnComplete ( [&] { ChangeBrightness(&image, bright_c); } ); } ); filters_subs->Add ( "contrast", "Change contrast", [&](argparse::SubParser* sub) { float contrast = 10; sub->Add("-c, --change", &contrast); return sub->OnComplete ( [&] { ChangeContrast(&image, contrast); } ); } ); return argparse::ParseFromMain(&parser, argc, argv); } <|endoftext|>
<commit_before>/* mbed Microcontroller Library * Copyright (c) 2018 ARM Limited * * 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 "hal/LowPowerTickerWrapper.h" #include "platform/Callback.h" LowPowerTickerWrapper::LowPowerTickerWrapper(const ticker_data_t *data, const ticker_interface_t *interface, uint32_t min_cycles_between_writes, uint32_t min_cycles_until_match) : _intf(data->interface), _min_count_between_writes(min_cycles_between_writes + 1), _min_count_until_match(min_cycles_until_match + 1), _suspended(false) { core_util_critical_section_enter(); this->data.interface = interface; this->data.queue = data->queue; _reset(); core_util_critical_section_exit(); } void LowPowerTickerWrapper::irq_handler(ticker_irq_handler_type handler) { core_util_critical_section_enter(); if (_suspended) { if (handler) { handler(&data); } core_util_critical_section_exit(); return; } if (_pending_fire_now || _match_check(_intf->read())) { _timeout.detach(); _pending_timeout = false; _pending_match = false; _pending_fire_now = false; if (handler) { handler(&data); } } else { // Spurious interrupt _intf->clear_interrupt(); } core_util_critical_section_exit(); } void LowPowerTickerWrapper::suspend() { core_util_critical_section_enter(); // Wait until rescheduling is allowed while (!_set_interrupt_allowed) { timestamp_t current = _intf->read(); if (((current - _last_actual_set_interrupt) & _mask) >= _min_count_between_writes) { _set_interrupt_allowed = true; } } _reset(); _suspended = true; core_util_critical_section_exit(); } void LowPowerTickerWrapper::resume() { core_util_critical_section_enter(); _suspended = false; core_util_critical_section_exit(); } bool LowPowerTickerWrapper::timeout_pending() { core_util_critical_section_enter(); bool pending = _pending_timeout; core_util_critical_section_exit(); return pending; } void LowPowerTickerWrapper::init() { core_util_critical_section_enter(); _reset(); _intf->init(); core_util_critical_section_exit(); } void LowPowerTickerWrapper::free() { core_util_critical_section_enter(); _reset(); _intf->free(); core_util_critical_section_exit(); } uint32_t LowPowerTickerWrapper::read() { core_util_critical_section_enter(); timestamp_t current = _intf->read(); if (_match_check(current)) { _intf->fire_interrupt(); } core_util_critical_section_exit(); return current; } void LowPowerTickerWrapper::set_interrupt(timestamp_t timestamp) { core_util_critical_section_enter(); _last_set_interrupt = _intf->read(); _cur_match_time = timestamp; _pending_match = true; _schedule_match(_last_set_interrupt); core_util_critical_section_exit(); } void LowPowerTickerWrapper::disable_interrupt() { core_util_critical_section_enter(); _intf->disable_interrupt(); core_util_critical_section_exit(); } void LowPowerTickerWrapper::clear_interrupt() { core_util_critical_section_enter(); _intf->clear_interrupt(); core_util_critical_section_exit(); } void LowPowerTickerWrapper::fire_interrupt() { core_util_critical_section_enter(); _pending_fire_now = 1; _intf->fire_interrupt(); core_util_critical_section_exit(); } const ticker_info_t *LowPowerTickerWrapper::get_info() { core_util_critical_section_enter(); const ticker_info_t *info = _intf->get_info(); core_util_critical_section_exit(); return info; } void LowPowerTickerWrapper::_reset() { MBED_ASSERT(core_util_in_critical_section()); _timeout.detach(); _pending_timeout = false; _pending_match = false; _pending_fire_now = false; _set_interrupt_allowed = true; _cur_match_time = 0; _last_set_interrupt = 0; _last_actual_set_interrupt = 0; const ticker_info_t *info = _intf->get_info(); if (info->bits >= 32) { _mask = 0xffffffff; } else { _mask = ((uint64_t)1 << info->bits) - 1; } // Round us_per_tick up _us_per_tick = (1000000 + info->frequency - 1) / info->frequency; } void LowPowerTickerWrapper::_timeout_handler() { core_util_critical_section_enter(); _pending_timeout = false; timestamp_t current = _intf->read(); /* Add extra check for '_last_set_interrupt == _cur_match_time' * * When '_last_set_interrupt == _cur_match_time', _ticker_match_interval_passed sees it as * one-round interval rather than just-pass, so add extra check for it. In rare cases, we * may trap in _timeout_handler/_schedule_match loop. This check can break it. */ if ((_last_set_interrupt == _cur_match_time) || _ticker_match_interval_passed(_last_set_interrupt, current, _cur_match_time)) { _intf->fire_interrupt(); } else { _schedule_match(current); } core_util_critical_section_exit(); } bool LowPowerTickerWrapper::_match_check(timestamp_t current) { MBED_ASSERT(core_util_in_critical_section()); if (!_pending_match) { return false; } /* Add extra check for '_last_set_interrupt == _cur_match_time' as above */ return (_last_set_interrupt == _cur_match_time) || _ticker_match_interval_passed(_last_set_interrupt, current, _cur_match_time); } uint32_t LowPowerTickerWrapper::_lp_ticks_to_us(uint32_t ticks) { MBED_ASSERT(core_util_in_critical_section()); // Add 4 microseconds to round up the micro second ticker time (which has a frequency of at least 250KHz - 4us period) return _us_per_tick * ticks + 4; } void LowPowerTickerWrapper::_schedule_match(timestamp_t current) { MBED_ASSERT(core_util_in_critical_section()); // Check if _intf->set_interrupt is allowed if (!_set_interrupt_allowed) { if (((current - _last_actual_set_interrupt) & _mask) >= _min_count_between_writes) { _set_interrupt_allowed = true; } } uint32_t cycles_until_match = (_cur_match_time - current) & _mask; bool too_close = cycles_until_match < _min_count_until_match; if (!_set_interrupt_allowed) { // Can't use _intf->set_interrupt so use microsecond Timeout instead // Speed optimization - if a timer has already been scheduled // then don't schedule it again. if (!_pending_timeout) { uint32_t ticks = cycles_until_match < _min_count_until_match ? cycles_until_match : _min_count_until_match; _timeout.attach_us(mbed::callback(this, &LowPowerTickerWrapper::_timeout_handler), _lp_ticks_to_us(ticks)); _pending_timeout = true; } return; } if (!too_close) { // Schedule LP ticker _intf->set_interrupt(_cur_match_time); current = _intf->read(); _last_actual_set_interrupt = current; _set_interrupt_allowed = false; // Check for overflow uint32_t new_cycles_until_match = (_cur_match_time - current) & _mask; if (new_cycles_until_match > cycles_until_match) { // Overflow so fire now _intf->fire_interrupt(); return; } // Update variables with new time cycles_until_match = new_cycles_until_match; too_close = cycles_until_match < _min_count_until_match; } if (too_close) { // Low power ticker incremented to less than _min_count_until_match // so low power ticker may not fire. Use Timeout to ensure it does fire. uint32_t ticks = cycles_until_match < _min_count_until_match ? cycles_until_match : _min_count_until_match; _timeout.attach_us(mbed::callback(this, &LowPowerTickerWrapper::_timeout_handler), _lp_ticks_to_us(ticks)); _pending_timeout = true; return; } } <commit_msg>low power ticker: fix astyle<commit_after>/* mbed Microcontroller Library * Copyright (c) 2018 ARM Limited * * 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 "hal/LowPowerTickerWrapper.h" #include "platform/Callback.h" LowPowerTickerWrapper::LowPowerTickerWrapper(const ticker_data_t *data, const ticker_interface_t *interface, uint32_t min_cycles_between_writes, uint32_t min_cycles_until_match) : _intf(data->interface), _min_count_between_writes(min_cycles_between_writes + 1), _min_count_until_match(min_cycles_until_match + 1), _suspended(false) { core_util_critical_section_enter(); this->data.interface = interface; this->data.queue = data->queue; _reset(); core_util_critical_section_exit(); } void LowPowerTickerWrapper::irq_handler(ticker_irq_handler_type handler) { core_util_critical_section_enter(); if (_suspended) { if (handler) { handler(&data); } core_util_critical_section_exit(); return; } if (_pending_fire_now || _match_check(_intf->read())) { _timeout.detach(); _pending_timeout = false; _pending_match = false; _pending_fire_now = false; if (handler) { handler(&data); } } else { // Spurious interrupt _intf->clear_interrupt(); } core_util_critical_section_exit(); } void LowPowerTickerWrapper::suspend() { core_util_critical_section_enter(); // Wait until rescheduling is allowed while (!_set_interrupt_allowed) { timestamp_t current = _intf->read(); if (((current - _last_actual_set_interrupt) & _mask) >= _min_count_between_writes) { _set_interrupt_allowed = true; } } _reset(); _suspended = true; core_util_critical_section_exit(); } void LowPowerTickerWrapper::resume() { core_util_critical_section_enter(); _suspended = false; core_util_critical_section_exit(); } bool LowPowerTickerWrapper::timeout_pending() { core_util_critical_section_enter(); bool pending = _pending_timeout; core_util_critical_section_exit(); return pending; } void LowPowerTickerWrapper::init() { core_util_critical_section_enter(); _reset(); _intf->init(); core_util_critical_section_exit(); } void LowPowerTickerWrapper::free() { core_util_critical_section_enter(); _reset(); _intf->free(); core_util_critical_section_exit(); } uint32_t LowPowerTickerWrapper::read() { core_util_critical_section_enter(); timestamp_t current = _intf->read(); if (_match_check(current)) { _intf->fire_interrupt(); } core_util_critical_section_exit(); return current; } void LowPowerTickerWrapper::set_interrupt(timestamp_t timestamp) { core_util_critical_section_enter(); _last_set_interrupt = _intf->read(); _cur_match_time = timestamp; _pending_match = true; _schedule_match(_last_set_interrupt); core_util_critical_section_exit(); } void LowPowerTickerWrapper::disable_interrupt() { core_util_critical_section_enter(); _intf->disable_interrupt(); core_util_critical_section_exit(); } void LowPowerTickerWrapper::clear_interrupt() { core_util_critical_section_enter(); _intf->clear_interrupt(); core_util_critical_section_exit(); } void LowPowerTickerWrapper::fire_interrupt() { core_util_critical_section_enter(); _pending_fire_now = 1; _intf->fire_interrupt(); core_util_critical_section_exit(); } const ticker_info_t *LowPowerTickerWrapper::get_info() { core_util_critical_section_enter(); const ticker_info_t *info = _intf->get_info(); core_util_critical_section_exit(); return info; } void LowPowerTickerWrapper::_reset() { MBED_ASSERT(core_util_in_critical_section()); _timeout.detach(); _pending_timeout = false; _pending_match = false; _pending_fire_now = false; _set_interrupt_allowed = true; _cur_match_time = 0; _last_set_interrupt = 0; _last_actual_set_interrupt = 0; const ticker_info_t *info = _intf->get_info(); if (info->bits >= 32) { _mask = 0xffffffff; } else { _mask = ((uint64_t)1 << info->bits) - 1; } // Round us_per_tick up _us_per_tick = (1000000 + info->frequency - 1) / info->frequency; } void LowPowerTickerWrapper::_timeout_handler() { core_util_critical_section_enter(); _pending_timeout = false; timestamp_t current = _intf->read(); /* Add extra check for '_last_set_interrupt == _cur_match_time' * * When '_last_set_interrupt == _cur_match_time', _ticker_match_interval_passed sees it as * one-round interval rather than just-pass, so add extra check for it. In rare cases, we * may trap in _timeout_handler/_schedule_match loop. This check can break it. */ if ((_last_set_interrupt == _cur_match_time) || _ticker_match_interval_passed(_last_set_interrupt, current, _cur_match_time)) { _intf->fire_interrupt(); } else { _schedule_match(current); } core_util_critical_section_exit(); } bool LowPowerTickerWrapper::_match_check(timestamp_t current) { MBED_ASSERT(core_util_in_critical_section()); if (!_pending_match) { return false; } /* Add extra check for '_last_set_interrupt == _cur_match_time' as above */ return (_last_set_interrupt == _cur_match_time) || _ticker_match_interval_passed(_last_set_interrupt, current, _cur_match_time); } uint32_t LowPowerTickerWrapper::_lp_ticks_to_us(uint32_t ticks) { MBED_ASSERT(core_util_in_critical_section()); // Add 4 microseconds to round up the micro second ticker time (which has a frequency of at least 250KHz - 4us period) return _us_per_tick * ticks + 4; } void LowPowerTickerWrapper::_schedule_match(timestamp_t current) { MBED_ASSERT(core_util_in_critical_section()); // Check if _intf->set_interrupt is allowed if (!_set_interrupt_allowed) { if (((current - _last_actual_set_interrupt) & _mask) >= _min_count_between_writes) { _set_interrupt_allowed = true; } } uint32_t cycles_until_match = (_cur_match_time - current) & _mask; bool too_close = cycles_until_match < _min_count_until_match; if (!_set_interrupt_allowed) { // Can't use _intf->set_interrupt so use microsecond Timeout instead // Speed optimization - if a timer has already been scheduled // then don't schedule it again. if (!_pending_timeout) { uint32_t ticks = cycles_until_match < _min_count_until_match ? cycles_until_match : _min_count_until_match; _timeout.attach_us(mbed::callback(this, &LowPowerTickerWrapper::_timeout_handler), _lp_ticks_to_us(ticks)); _pending_timeout = true; } return; } if (!too_close) { // Schedule LP ticker _intf->set_interrupt(_cur_match_time); current = _intf->read(); _last_actual_set_interrupt = current; _set_interrupt_allowed = false; // Check for overflow uint32_t new_cycles_until_match = (_cur_match_time - current) & _mask; if (new_cycles_until_match > cycles_until_match) { // Overflow so fire now _intf->fire_interrupt(); return; } // Update variables with new time cycles_until_match = new_cycles_until_match; too_close = cycles_until_match < _min_count_until_match; } if (too_close) { // Low power ticker incremented to less than _min_count_until_match // so low power ticker may not fire. Use Timeout to ensure it does fire. uint32_t ticks = cycles_until_match < _min_count_until_match ? cycles_until_match : _min_count_until_match; _timeout.attach_us(mbed::callback(this, &LowPowerTickerWrapper::_timeout_handler), _lp_ticks_to_us(ticks)); _pending_timeout = true; return; } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "kitinformationconfigwidget.h" #include "devicesupport/devicemanager.h" #include "devicesupport/devicemanagermodel.h" #include "devicesupport/idevicefactory.h" #include "projectexplorerconstants.h" #include "kit.h" #include "kitinformation.h" #include "toolchain.h" #include "toolchainmanager.h" #include "environmentwidget.h" #include <coreplugin/icore.h> #include <extensionsystem/pluginmanager.h> #include <utils/algorithm.h> #include <utils/fancylineedit.h> #include <utils/environment.h> #include <utils/qtcassert.h> #include <utils/pathchooser.h> #include <QComboBox> #include <QDialog> #include <QDialogButtonBox> #include <QFontMetrics> #include <QLabel> #include <QPlainTextEdit> #include <QPushButton> #include <QVBoxLayout> using namespace Core; namespace ProjectExplorer { namespace Internal { // -------------------------------------------------------------------------- // SysRootInformationConfigWidget: // -------------------------------------------------------------------------- SysRootInformationConfigWidget::SysRootInformationConfigWidget(Kit *k, const KitInformation *ki) : KitConfigWidget(k, ki), m_ignoreChange(false) { m_chooser = new Utils::PathChooser; m_chooser->setExpectedKind(Utils::PathChooser::ExistingDirectory); m_chooser->setHistoryCompleter(QLatin1String("PE.SysRoot.History")); m_chooser->setFileName(SysRootKitInformation::sysRoot(k)); connect(m_chooser, SIGNAL(changed(QString)), this, SLOT(pathWasChanged())); } SysRootInformationConfigWidget::~SysRootInformationConfigWidget() { delete m_chooser; } QString SysRootInformationConfigWidget::displayName() const { return tr("Sysroot:"); } QString SysRootInformationConfigWidget::toolTip() const { return tr("The root directory of the system image to use.<br>" "Leave empty when building for the desktop."); } void SysRootInformationConfigWidget::refresh() { if (!m_ignoreChange) m_chooser->setFileName(SysRootKitInformation::sysRoot(m_kit)); } void SysRootInformationConfigWidget::makeReadOnly() { m_chooser->setReadOnly(true); } QWidget *SysRootInformationConfigWidget::mainWidget() const { return m_chooser->lineEdit(); } QWidget *SysRootInformationConfigWidget::buttonWidget() const { return m_chooser->buttonAtIndex(0); } void SysRootInformationConfigWidget::pathWasChanged() { m_ignoreChange = true; SysRootKitInformation::setSysRoot(m_kit, m_chooser->fileName()); m_ignoreChange = false; } // -------------------------------------------------------------------------- // ToolChainInformationConfigWidget: // -------------------------------------------------------------------------- ToolChainInformationConfigWidget::ToolChainInformationConfigWidget(Kit *k, const KitInformation *ki) : KitConfigWidget(k, ki), m_ignoreChanges(false) { m_comboBox = new QComboBox; m_comboBox->setEnabled(false); m_comboBox->setToolTip(toolTip()); refresh(); connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(currentToolChainChanged(int))); m_manageButton = new QPushButton(KitConfigWidget::msgManage()); m_manageButton->setContentsMargins(0, 0, 0, 0); connect(m_manageButton, SIGNAL(clicked()), this, SLOT(manageToolChains())); } ToolChainInformationConfigWidget::~ToolChainInformationConfigWidget() { delete m_comboBox; delete m_manageButton; } QString ToolChainInformationConfigWidget::displayName() const { return tr("Compiler:"); } QString ToolChainInformationConfigWidget::toolTip() const { return tr("The compiler to use for building.<br>" "Make sure the compiler will produce binaries compatible with the target device, " "Qt version and other libraries used."); } void ToolChainInformationConfigWidget::refresh() { m_ignoreChanges = true; m_comboBox->clear(); foreach (ToolChain *tc, ToolChainManager::toolChains()) m_comboBox->addItem(tc->displayName(), tc->id()); m_comboBox->setCurrentIndex(indexOf(ToolChainKitInformation::toolChain(m_kit))); m_ignoreChanges = false; } void ToolChainInformationConfigWidget::makeReadOnly() { m_comboBox->setEnabled(false); } QWidget *ToolChainInformationConfigWidget::mainWidget() const { return m_comboBox; } QWidget *ToolChainInformationConfigWidget::buttonWidget() const { return m_manageButton; } void ToolChainInformationConfigWidget::manageToolChains() { ICore::showOptionsDialog(Constants::TOOLCHAIN_SETTINGS_PAGE_ID, buttonWidget()); } void ToolChainInformationConfigWidget::currentToolChainChanged(int idx) { if (m_ignoreChanges) return; const QString id = m_comboBox->itemData(idx).toString(); ToolChainKitInformation::setToolChain(m_kit, ToolChainManager::findToolChain(id)); } void ToolChainInformationConfigWidget::updateComboBox() { // remove unavailable tool chain: int pos = indexOf(0); if (pos >= 0) m_comboBox->removeItem(pos); if (m_comboBox->count() == 0) { m_comboBox->addItem(tr("<No compiler available>"), QString()); m_comboBox->setEnabled(false); } else { m_comboBox->setEnabled(true); } } int ToolChainInformationConfigWidget::indexOf(const ToolChain *tc) { const QString id = tc ? tc->id() : QString(); for (int i = 0; i < m_comboBox->count(); ++i) { if (id == m_comboBox->itemData(i).toString()) return i; } return -1; } // -------------------------------------------------------------------------- // DeviceTypeInformationConfigWidget: // -------------------------------------------------------------------------- DeviceTypeInformationConfigWidget::DeviceTypeInformationConfigWidget(Kit *workingCopy, const KitInformation *ki) : KitConfigWidget(workingCopy, ki), m_comboBox(new QComboBox) { QList<IDeviceFactory *> factories = ExtensionSystem::PluginManager::getObjects<IDeviceFactory>(); foreach (IDeviceFactory *factory, factories) { foreach (Id id, factory->availableCreationIds()) m_comboBox->addItem(factory->displayNameForId(id), id.uniqueIdentifier()); } m_comboBox->setToolTip(toolTip()); refresh(); connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(currentTypeChanged(int))); } DeviceTypeInformationConfigWidget::~DeviceTypeInformationConfigWidget() { delete m_comboBox; } QWidget *DeviceTypeInformationConfigWidget::mainWidget() const { return m_comboBox; } QString DeviceTypeInformationConfigWidget::displayName() const { return tr("Device type:"); } QString DeviceTypeInformationConfigWidget::toolTip() const { return tr("The type of device to run applications on."); } void DeviceTypeInformationConfigWidget::refresh() { Id devType = DeviceTypeKitInformation::deviceTypeId(m_kit); if (!devType.isValid()) m_comboBox->setCurrentIndex(-1); for (int i = 0; i < m_comboBox->count(); ++i) { if (m_comboBox->itemData(i).toInt() == devType.uniqueIdentifier()) { m_comboBox->setCurrentIndex(i); break; } } } void DeviceTypeInformationConfigWidget::makeReadOnly() { m_comboBox->setEnabled(false); } void DeviceTypeInformationConfigWidget::currentTypeChanged(int idx) { Id type = idx < 0 ? Id() : Id::fromUniqueIdentifier(m_comboBox->itemData(idx).toInt()); DeviceTypeKitInformation::setDeviceTypeId(m_kit, type); } // -------------------------------------------------------------------------- // DeviceInformationConfigWidget: // -------------------------------------------------------------------------- DeviceInformationConfigWidget::DeviceInformationConfigWidget(Kit *workingCopy, const KitInformation *ki) : KitConfigWidget(workingCopy, ki), m_isReadOnly(false), m_ignoreChange(false), m_comboBox(new QComboBox), m_model(new DeviceManagerModel(DeviceManager::instance())) { m_comboBox->setModel(m_model); m_manageButton = new QPushButton(KitConfigWidget::msgManage()); refresh(); m_comboBox->setToolTip(toolTip()); connect(m_model, SIGNAL(modelAboutToBeReset()), SLOT(modelAboutToReset())); connect(m_model, SIGNAL(modelReset()), SLOT(modelReset())); connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(currentDeviceChanged())); connect(m_manageButton, SIGNAL(clicked()), this, SLOT(manageDevices())); } DeviceInformationConfigWidget::~DeviceInformationConfigWidget() { delete m_comboBox; delete m_model; delete m_manageButton; } QWidget *DeviceInformationConfigWidget::mainWidget() const { return m_comboBox; } QString DeviceInformationConfigWidget::displayName() const { return tr("Device:"); } QString DeviceInformationConfigWidget::toolTip() const { return tr("The device to run the applications on."); } void DeviceInformationConfigWidget::refresh() { m_model->setTypeFilter(DeviceTypeKitInformation::deviceTypeId(m_kit)); m_comboBox->setCurrentIndex(m_model->indexOf(DeviceKitInformation::device(m_kit))); } void DeviceInformationConfigWidget::makeReadOnly() { m_comboBox->setEnabled(false); } QWidget *DeviceInformationConfigWidget::buttonWidget() const { return m_manageButton; } void DeviceInformationConfigWidget::manageDevices() { ICore::showOptionsDialog(Constants::DEVICE_SETTINGS_PAGE_ID, buttonWidget()); } void DeviceInformationConfigWidget::modelAboutToReset() { m_selectedId = m_model->deviceId(m_comboBox->currentIndex()); m_ignoreChange = true; } void DeviceInformationConfigWidget::modelReset() { m_comboBox->setCurrentIndex(m_model->indexForId(m_selectedId)); m_ignoreChange = false; } void DeviceInformationConfigWidget::currentDeviceChanged() { if (m_ignoreChange) return; DeviceKitInformation::setDeviceId(m_kit, m_model->deviceId(m_comboBox->currentIndex())); } // -------------------------------------------------------------------- // KitEnvironmentConfigWidget: // -------------------------------------------------------------------- KitEnvironmentConfigWidget::KitEnvironmentConfigWidget(Kit *workingCopy, const KitInformation *ki) : KitConfigWidget(workingCopy, ki), m_summaryLabel(new QLabel), m_manageButton(new QPushButton), m_dialog(0), m_editor(0) { refresh(); m_manageButton->setText(tr("Change...")); connect(m_manageButton, SIGNAL(clicked()), this, SLOT(editEnvironmentChanges())); } QWidget *KitEnvironmentConfigWidget::mainWidget() const { return m_summaryLabel; } QString KitEnvironmentConfigWidget::displayName() const { return tr("Environment:"); } QString KitEnvironmentConfigWidget::toolTip() const { return tr("Additional environment settings when using this kit."); } void KitEnvironmentConfigWidget::refresh() { QList<Utils::EnvironmentItem> changes = EnvironmentKitInformation::environmentChanges(m_kit); Utils::sort(changes, [](const Utils::EnvironmentItem &lhs, const Utils::EnvironmentItem &rhs) { return QString::localeAwareCompare(lhs.name, rhs.name) < 0; }); QString shortSummary = Utils::EnvironmentItem::toStringList(changes).join(QLatin1String("; ")); QFontMetrics fm(m_summaryLabel->font()); shortSummary = fm.elidedText(shortSummary, Qt::ElideRight, m_summaryLabel->width()); m_summaryLabel->setText(shortSummary.isEmpty() ? tr("No Changes to apply") : shortSummary); if (m_editor) m_editor->setPlainText(Utils::EnvironmentItem::toStringList(changes).join(QLatin1Char('\n'))); } void KitEnvironmentConfigWidget::makeReadOnly() { m_manageButton->setEnabled(false); if (m_dialog) m_dialog->reject(); } void KitEnvironmentConfigWidget::editEnvironmentChanges() { if (m_dialog) { m_dialog->activateWindow(); m_dialog->raise(); return; } QTC_ASSERT(!m_editor, return); m_dialog = new QDialog(m_summaryLabel); m_dialog->setWindowTitle(tr("Edit Environment Changes")); QVBoxLayout *layout = new QVBoxLayout(m_dialog); m_editor = new QPlainTextEdit; QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Apply|QDialogButtonBox::Cancel); layout->addWidget(m_editor); layout->addWidget(buttons); connect(buttons, SIGNAL(accepted()), m_dialog, SLOT(accept())); connect(buttons, SIGNAL(rejected()), m_dialog, SLOT(reject())); connect(m_dialog, SIGNAL(accepted()), this, SLOT(acceptChangesDialog())); connect(m_dialog, SIGNAL(rejected()), this, SLOT(closeChangesDialog())); connect(buttons->button(QDialogButtonBox::Apply), SIGNAL(clicked()), this, SLOT(applyChanges())); refresh(); m_dialog->show(); } void KitEnvironmentConfigWidget::applyChanges() { QTC_ASSERT(m_editor, return); auto changes = Utils::EnvironmentItem::fromStringList(m_editor->toPlainText().split(QLatin1Char('\n'))); EnvironmentKitInformation::setEnvironmentChanges(m_kit, changes); } void KitEnvironmentConfigWidget::closeChangesDialog() { m_dialog->deleteLater(); m_dialog = 0; m_editor = 0; } void KitEnvironmentConfigWidget::acceptChangesDialog() { applyChanges(); closeChangesDialog(); } QWidget *KitEnvironmentConfigWidget::buttonWidget() const { return m_manageButton; } } // namespace Internal } // namespace ProjectExplorer <commit_msg>ProjectExplorer: fix one more capitalization issue<commit_after>/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "kitinformationconfigwidget.h" #include "devicesupport/devicemanager.h" #include "devicesupport/devicemanagermodel.h" #include "devicesupport/idevicefactory.h" #include "projectexplorerconstants.h" #include "kit.h" #include "kitinformation.h" #include "toolchain.h" #include "toolchainmanager.h" #include "environmentwidget.h" #include <coreplugin/icore.h> #include <extensionsystem/pluginmanager.h> #include <utils/algorithm.h> #include <utils/fancylineedit.h> #include <utils/environment.h> #include <utils/qtcassert.h> #include <utils/pathchooser.h> #include <QComboBox> #include <QDialog> #include <QDialogButtonBox> #include <QFontMetrics> #include <QLabel> #include <QPlainTextEdit> #include <QPushButton> #include <QVBoxLayout> using namespace Core; namespace ProjectExplorer { namespace Internal { // -------------------------------------------------------------------------- // SysRootInformationConfigWidget: // -------------------------------------------------------------------------- SysRootInformationConfigWidget::SysRootInformationConfigWidget(Kit *k, const KitInformation *ki) : KitConfigWidget(k, ki), m_ignoreChange(false) { m_chooser = new Utils::PathChooser; m_chooser->setExpectedKind(Utils::PathChooser::ExistingDirectory); m_chooser->setHistoryCompleter(QLatin1String("PE.SysRoot.History")); m_chooser->setFileName(SysRootKitInformation::sysRoot(k)); connect(m_chooser, SIGNAL(changed(QString)), this, SLOT(pathWasChanged())); } SysRootInformationConfigWidget::~SysRootInformationConfigWidget() { delete m_chooser; } QString SysRootInformationConfigWidget::displayName() const { return tr("Sysroot:"); } QString SysRootInformationConfigWidget::toolTip() const { return tr("The root directory of the system image to use.<br>" "Leave empty when building for the desktop."); } void SysRootInformationConfigWidget::refresh() { if (!m_ignoreChange) m_chooser->setFileName(SysRootKitInformation::sysRoot(m_kit)); } void SysRootInformationConfigWidget::makeReadOnly() { m_chooser->setReadOnly(true); } QWidget *SysRootInformationConfigWidget::mainWidget() const { return m_chooser->lineEdit(); } QWidget *SysRootInformationConfigWidget::buttonWidget() const { return m_chooser->buttonAtIndex(0); } void SysRootInformationConfigWidget::pathWasChanged() { m_ignoreChange = true; SysRootKitInformation::setSysRoot(m_kit, m_chooser->fileName()); m_ignoreChange = false; } // -------------------------------------------------------------------------- // ToolChainInformationConfigWidget: // -------------------------------------------------------------------------- ToolChainInformationConfigWidget::ToolChainInformationConfigWidget(Kit *k, const KitInformation *ki) : KitConfigWidget(k, ki), m_ignoreChanges(false) { m_comboBox = new QComboBox; m_comboBox->setEnabled(false); m_comboBox->setToolTip(toolTip()); refresh(); connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(currentToolChainChanged(int))); m_manageButton = new QPushButton(KitConfigWidget::msgManage()); m_manageButton->setContentsMargins(0, 0, 0, 0); connect(m_manageButton, SIGNAL(clicked()), this, SLOT(manageToolChains())); } ToolChainInformationConfigWidget::~ToolChainInformationConfigWidget() { delete m_comboBox; delete m_manageButton; } QString ToolChainInformationConfigWidget::displayName() const { return tr("Compiler:"); } QString ToolChainInformationConfigWidget::toolTip() const { return tr("The compiler to use for building.<br>" "Make sure the compiler will produce binaries compatible with the target device, " "Qt version and other libraries used."); } void ToolChainInformationConfigWidget::refresh() { m_ignoreChanges = true; m_comboBox->clear(); foreach (ToolChain *tc, ToolChainManager::toolChains()) m_comboBox->addItem(tc->displayName(), tc->id()); m_comboBox->setCurrentIndex(indexOf(ToolChainKitInformation::toolChain(m_kit))); m_ignoreChanges = false; } void ToolChainInformationConfigWidget::makeReadOnly() { m_comboBox->setEnabled(false); } QWidget *ToolChainInformationConfigWidget::mainWidget() const { return m_comboBox; } QWidget *ToolChainInformationConfigWidget::buttonWidget() const { return m_manageButton; } void ToolChainInformationConfigWidget::manageToolChains() { ICore::showOptionsDialog(Constants::TOOLCHAIN_SETTINGS_PAGE_ID, buttonWidget()); } void ToolChainInformationConfigWidget::currentToolChainChanged(int idx) { if (m_ignoreChanges) return; const QString id = m_comboBox->itemData(idx).toString(); ToolChainKitInformation::setToolChain(m_kit, ToolChainManager::findToolChain(id)); } void ToolChainInformationConfigWidget::updateComboBox() { // remove unavailable tool chain: int pos = indexOf(0); if (pos >= 0) m_comboBox->removeItem(pos); if (m_comboBox->count() == 0) { m_comboBox->addItem(tr("<No compiler available>"), QString()); m_comboBox->setEnabled(false); } else { m_comboBox->setEnabled(true); } } int ToolChainInformationConfigWidget::indexOf(const ToolChain *tc) { const QString id = tc ? tc->id() : QString(); for (int i = 0; i < m_comboBox->count(); ++i) { if (id == m_comboBox->itemData(i).toString()) return i; } return -1; } // -------------------------------------------------------------------------- // DeviceTypeInformationConfigWidget: // -------------------------------------------------------------------------- DeviceTypeInformationConfigWidget::DeviceTypeInformationConfigWidget(Kit *workingCopy, const KitInformation *ki) : KitConfigWidget(workingCopy, ki), m_comboBox(new QComboBox) { QList<IDeviceFactory *> factories = ExtensionSystem::PluginManager::getObjects<IDeviceFactory>(); foreach (IDeviceFactory *factory, factories) { foreach (Id id, factory->availableCreationIds()) m_comboBox->addItem(factory->displayNameForId(id), id.uniqueIdentifier()); } m_comboBox->setToolTip(toolTip()); refresh(); connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(currentTypeChanged(int))); } DeviceTypeInformationConfigWidget::~DeviceTypeInformationConfigWidget() { delete m_comboBox; } QWidget *DeviceTypeInformationConfigWidget::mainWidget() const { return m_comboBox; } QString DeviceTypeInformationConfigWidget::displayName() const { return tr("Device type:"); } QString DeviceTypeInformationConfigWidget::toolTip() const { return tr("The type of device to run applications on."); } void DeviceTypeInformationConfigWidget::refresh() { Id devType = DeviceTypeKitInformation::deviceTypeId(m_kit); if (!devType.isValid()) m_comboBox->setCurrentIndex(-1); for (int i = 0; i < m_comboBox->count(); ++i) { if (m_comboBox->itemData(i).toInt() == devType.uniqueIdentifier()) { m_comboBox->setCurrentIndex(i); break; } } } void DeviceTypeInformationConfigWidget::makeReadOnly() { m_comboBox->setEnabled(false); } void DeviceTypeInformationConfigWidget::currentTypeChanged(int idx) { Id type = idx < 0 ? Id() : Id::fromUniqueIdentifier(m_comboBox->itemData(idx).toInt()); DeviceTypeKitInformation::setDeviceTypeId(m_kit, type); } // -------------------------------------------------------------------------- // DeviceInformationConfigWidget: // -------------------------------------------------------------------------- DeviceInformationConfigWidget::DeviceInformationConfigWidget(Kit *workingCopy, const KitInformation *ki) : KitConfigWidget(workingCopy, ki), m_isReadOnly(false), m_ignoreChange(false), m_comboBox(new QComboBox), m_model(new DeviceManagerModel(DeviceManager::instance())) { m_comboBox->setModel(m_model); m_manageButton = new QPushButton(KitConfigWidget::msgManage()); refresh(); m_comboBox->setToolTip(toolTip()); connect(m_model, SIGNAL(modelAboutToBeReset()), SLOT(modelAboutToReset())); connect(m_model, SIGNAL(modelReset()), SLOT(modelReset())); connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(currentDeviceChanged())); connect(m_manageButton, SIGNAL(clicked()), this, SLOT(manageDevices())); } DeviceInformationConfigWidget::~DeviceInformationConfigWidget() { delete m_comboBox; delete m_model; delete m_manageButton; } QWidget *DeviceInformationConfigWidget::mainWidget() const { return m_comboBox; } QString DeviceInformationConfigWidget::displayName() const { return tr("Device:"); } QString DeviceInformationConfigWidget::toolTip() const { return tr("The device to run the applications on."); } void DeviceInformationConfigWidget::refresh() { m_model->setTypeFilter(DeviceTypeKitInformation::deviceTypeId(m_kit)); m_comboBox->setCurrentIndex(m_model->indexOf(DeviceKitInformation::device(m_kit))); } void DeviceInformationConfigWidget::makeReadOnly() { m_comboBox->setEnabled(false); } QWidget *DeviceInformationConfigWidget::buttonWidget() const { return m_manageButton; } void DeviceInformationConfigWidget::manageDevices() { ICore::showOptionsDialog(Constants::DEVICE_SETTINGS_PAGE_ID, buttonWidget()); } void DeviceInformationConfigWidget::modelAboutToReset() { m_selectedId = m_model->deviceId(m_comboBox->currentIndex()); m_ignoreChange = true; } void DeviceInformationConfigWidget::modelReset() { m_comboBox->setCurrentIndex(m_model->indexForId(m_selectedId)); m_ignoreChange = false; } void DeviceInformationConfigWidget::currentDeviceChanged() { if (m_ignoreChange) return; DeviceKitInformation::setDeviceId(m_kit, m_model->deviceId(m_comboBox->currentIndex())); } // -------------------------------------------------------------------- // KitEnvironmentConfigWidget: // -------------------------------------------------------------------- KitEnvironmentConfigWidget::KitEnvironmentConfigWidget(Kit *workingCopy, const KitInformation *ki) : KitConfigWidget(workingCopy, ki), m_summaryLabel(new QLabel), m_manageButton(new QPushButton), m_dialog(0), m_editor(0) { refresh(); m_manageButton->setText(tr("Change...")); connect(m_manageButton, SIGNAL(clicked()), this, SLOT(editEnvironmentChanges())); } QWidget *KitEnvironmentConfigWidget::mainWidget() const { return m_summaryLabel; } QString KitEnvironmentConfigWidget::displayName() const { return tr("Environment:"); } QString KitEnvironmentConfigWidget::toolTip() const { return tr("Additional environment settings when using this kit."); } void KitEnvironmentConfigWidget::refresh() { QList<Utils::EnvironmentItem> changes = EnvironmentKitInformation::environmentChanges(m_kit); Utils::sort(changes, [](const Utils::EnvironmentItem &lhs, const Utils::EnvironmentItem &rhs) { return QString::localeAwareCompare(lhs.name, rhs.name) < 0; }); QString shortSummary = Utils::EnvironmentItem::toStringList(changes).join(QLatin1String("; ")); QFontMetrics fm(m_summaryLabel->font()); shortSummary = fm.elidedText(shortSummary, Qt::ElideRight, m_summaryLabel->width()); m_summaryLabel->setText(shortSummary.isEmpty() ? tr("No changes to apply.") : shortSummary); if (m_editor) m_editor->setPlainText(Utils::EnvironmentItem::toStringList(changes).join(QLatin1Char('\n'))); } void KitEnvironmentConfigWidget::makeReadOnly() { m_manageButton->setEnabled(false); if (m_dialog) m_dialog->reject(); } void KitEnvironmentConfigWidget::editEnvironmentChanges() { if (m_dialog) { m_dialog->activateWindow(); m_dialog->raise(); return; } QTC_ASSERT(!m_editor, return); m_dialog = new QDialog(m_summaryLabel); m_dialog->setWindowTitle(tr("Edit Environment Changes")); QVBoxLayout *layout = new QVBoxLayout(m_dialog); m_editor = new QPlainTextEdit; QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Apply|QDialogButtonBox::Cancel); layout->addWidget(m_editor); layout->addWidget(buttons); connect(buttons, SIGNAL(accepted()), m_dialog, SLOT(accept())); connect(buttons, SIGNAL(rejected()), m_dialog, SLOT(reject())); connect(m_dialog, SIGNAL(accepted()), this, SLOT(acceptChangesDialog())); connect(m_dialog, SIGNAL(rejected()), this, SLOT(closeChangesDialog())); connect(buttons->button(QDialogButtonBox::Apply), SIGNAL(clicked()), this, SLOT(applyChanges())); refresh(); m_dialog->show(); } void KitEnvironmentConfigWidget::applyChanges() { QTC_ASSERT(m_editor, return); auto changes = Utils::EnvironmentItem::fromStringList(m_editor->toPlainText().split(QLatin1Char('\n'))); EnvironmentKitInformation::setEnvironmentChanges(m_kit, changes); } void KitEnvironmentConfigWidget::closeChangesDialog() { m_dialog->deleteLater(); m_dialog = 0; m_editor = 0; } void KitEnvironmentConfigWidget::acceptChangesDialog() { applyChanges(); closeChangesDialog(); } QWidget *KitEnvironmentConfigWidget::buttonWidget() const { return m_manageButton; } } // namespace Internal } // namespace ProjectExplorer <|endoftext|>
<commit_before>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "GapConductanceConstraint.h" registerMooseObject("HeatConductionApp", GapConductanceConstraint); InputParameters GapConductanceConstraint::validParams() { InputParameters params = ADMortarConstraint::validParams(); params.addClassDescription( "Computes the residual and Jacobian contributions for the 'Lagrange Multiplier' " "implementation of the thermal contact problem. For more information, see the " "detailed description here: http://tinyurl.com/gmmhbe9"); params.addRequiredParam<Real>("k", "Gap conductance"); return params; } GapConductanceConstraint::GapConductanceConstraint(const InputParameters & parameters) : ADMortarConstraint(parameters), _k(getParam<Real>("k")) { } ADReal GapConductanceConstraint::computeQpResidual(Moose::MortarType mortar_type) { switch (mortar_type) { case Moose::MortarType::Primary: return _lambda[_qp] * _test_primary[_i][_qp]; case Moose::MortarType::Secondary: return -_lambda[_qp] * _test_secondary[_i][_qp]; case Moose::MortarType::Lower: { auto l = (_phys_points_primary[_qp] - _phys_points_secondary[_qp]).norm(); return (_k * (_u_primary[_qp] - _u_secondary[_qp]) / l - _lambda[_qp]) * _test[_i][_qp]; } default: return 0; } } <commit_msg>Make lm diagonal entry positive instead of negative<commit_after>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "GapConductanceConstraint.h" registerMooseObject("HeatConductionApp", GapConductanceConstraint); InputParameters GapConductanceConstraint::validParams() { InputParameters params = ADMortarConstraint::validParams(); params.addClassDescription( "Computes the residual and Jacobian contributions for the 'Lagrange Multiplier' " "implementation of the thermal contact problem. For more information, see the " "detailed description here: http://tinyurl.com/gmmhbe9"); params.addRequiredParam<Real>("k", "Gap conductance"); return params; } GapConductanceConstraint::GapConductanceConstraint(const InputParameters & parameters) : ADMortarConstraint(parameters), _k(getParam<Real>("k")) { } ADReal GapConductanceConstraint::computeQpResidual(Moose::MortarType mortar_type) { switch (mortar_type) { case Moose::MortarType::Primary: return _lambda[_qp] * _test_primary[_i][_qp]; case Moose::MortarType::Secondary: return -_lambda[_qp] * _test_secondary[_i][_qp]; case Moose::MortarType::Lower: { auto l = (_phys_points_primary[_qp] - _phys_points_secondary[_qp]).norm(); return (_lambda[_qp] - _k * (_u_primary[_qp] - _u_secondary[_qp]) / l) * _test[_i][_qp]; } default: return 0; } } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/lattice/behavior_decider/signal_light_scenario.h" #include <limits> #include <string> #include <vector> #include "gflags/gflags.h" #include "modules/common/adapters/adapter_manager.h" #include "modules/common/log.h" #include "modules/common/util/map_util.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/proto/planning_internal.pb.h" namespace apollo { namespace planning { using apollo::common::adapter::AdapterManager; using apollo::common::util::WithinBound; using apollo::perception::TrafficLight; using apollo::perception::TrafficLightDetection; void SignalLightScenario::Reset() {} bool SignalLightScenario::Init() { exist_ = true; return exist_; } int SignalLightScenario::ComputeScenarioDecision( Frame* frame, ReferenceLineInfo* const reference_line_info, PlanningTarget* planning_target) { CHECK(frame != nullptr); if (!FindValidSignalLight(reference_line_info)) { ADEBUG << "No valid signal light along reference line"; return 0; } ReadSignals(); for (const hdmap::PathOverlap* signal_light : signal_lights_along_reference_line_) { const TrafficLight signal = GetSignal(signal_light->object_id); double stop_deceleration = GetStopDeceleration(reference_line_info, signal_light); if ((signal.color() == TrafficLight::RED && stop_deceleration < FLAGS_max_stop_deceleration) || (signal.color() == TrafficLight::UNKNOWN && stop_deceleration < FLAGS_max_stop_deceleration) || (signal.color() == TrafficLight::YELLOW && stop_deceleration < FLAGS_max_stop_deacceleration_for_yellow_light)) { CreateStopObstacle(frame, reference_line_info, signal_light); } } return 0; } bool SignalLightScenario::FindValidSignalLight( ReferenceLineInfo* const reference_line_info) { const std::vector<hdmap::PathOverlap>& signal_lights = reference_line_info->reference_line().map_path().signal_overlaps(); if (signal_lights.size() <= 0) { ADEBUG << "No signal lights from reference line."; return false; } else { ADEBUG << "Found signal_lights size=" << signal_lights.size(); } signal_lights_along_reference_line_.clear(); for (const hdmap::PathOverlap& signal_light : signal_lights) { if (signal_light.start_s + FLAGS_max_stop_distance_buffer > reference_line_info->AdcSlBoundary().end_s()) { signal_lights_along_reference_line_.push_back(&signal_light); } } return signal_lights_along_reference_line_.size() > 0; } void SignalLightScenario::ReadSignals() { detected_signals_.clear(); detected_signals_.clear(); if (AdapterManager::GetTrafficLightDetection()->Empty()) { return; } if (AdapterManager::GetTrafficLightDetection()->GetDelaySec() > FLAGS_signal_expire_time_sec) { AWARN << "traffic signals msg is expired: " << AdapterManager::GetTrafficLightDetection()->GetDelaySec(); return; } const TrafficLightDetection& detection = AdapterManager::GetTrafficLightDetection()->GetLatestObserved(); for (int j = 0; j < detection.traffic_light_size(); j++) { const TrafficLight& signal = detection.traffic_light(j); detected_signals_[signal.id()] = &signal; } } TrafficLight SignalLightScenario::GetSignal(const std::string& signal_id) { const auto* result = apollo::common::util::FindPtrOrNull(detected_signals_, signal_id); if (result == nullptr) { TrafficLight traffic_light; traffic_light.set_id(signal_id); traffic_light.set_color(TrafficLight::UNKNOWN); traffic_light.set_confidence(0.0); traffic_light.set_tracking_time(0.0); return traffic_light; } return *result; } double SignalLightScenario::GetStopDeceleration( ReferenceLineInfo* const reference_line_info, const hdmap::PathOverlap* signal_light) { double adc_speed = common::VehicleStateProvider::instance()->linear_velocity(); if (adc_speed < FLAGS_max_stop_speed) { return 0.0; } double stop_distance = 0.0; double adc_front_s = reference_line_info->AdcSlBoundary().end_s(); double stop_line_s = signal_light->start_s; if (stop_line_s > adc_front_s) { stop_distance = stop_line_s - adc_front_s; } else { stop_distance = stop_line_s + FLAGS_max_stop_distance_buffer - adc_front_s; } if (stop_distance < 1e-5) { // longitudinal_acceleration_lower_bound is a negative value. return -FLAGS_longitudinal_acceleration_lower_bound; } return (adc_speed * adc_speed) / (2 * stop_distance); } void SignalLightScenario::CreateStopObstacle( Frame* frame, ReferenceLineInfo* const reference_line_info, const hdmap::PathOverlap* signal_light) { // check const auto& reference_line = reference_line_info->reference_line(); const double stop_s = signal_light->start_s - FLAGS_traffic_light_stop_distance; const double box_center_s = signal_light->start_s + FLAGS_virtual_stop_wall_length / 2.0; if (!WithinBound(0.0, reference_line.Length(), stop_s) || !WithinBound(0.0, reference_line.Length(), box_center_s)) { ADEBUG << "signal " << signal_light->object_id << " is not on reference line"; return; } // create virtual stop wall std::string virtual_obstacle_id = FLAGS_signal_light_virtual_obstacle_id_prefix + signal_light->object_id; auto* obstacle = frame->CreateVirtualStopObstacle( reference_line_info, virtual_obstacle_id, signal_light->start_s); if (!obstacle) { AERROR << "Failed to create obstacle [" << virtual_obstacle_id << "]"; return; } PathObstacle* stop_wall = reference_line_info->AddObstacle(obstacle); if (!stop_wall) { AERROR << "Failed to create path_obstacle for: " << virtual_obstacle_id; return; } return; } } // namespace planning } // namespace apollo <commit_msg>planning: fixed a bug of colliding with traffic light virtual obstacle<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/lattice/behavior_decider/signal_light_scenario.h" #include <limits> #include <string> #include <vector> #include "gflags/gflags.h" #include "modules/common/adapters/adapter_manager.h" #include "modules/common/log.h" #include "modules/common/util/map_util.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/proto/planning_internal.pb.h" namespace apollo { namespace planning { using apollo::common::adapter::AdapterManager; using apollo::common::util::WithinBound; using apollo::perception::TrafficLight; using apollo::perception::TrafficLightDetection; void SignalLightScenario::Reset() {} bool SignalLightScenario::Init() { exist_ = true; return exist_; } int SignalLightScenario::ComputeScenarioDecision( Frame* frame, ReferenceLineInfo* const reference_line_info, PlanningTarget* planning_target) { CHECK(frame != nullptr); if (!FindValidSignalLight(reference_line_info)) { ADEBUG << "No valid signal light along reference line"; return 0; } ReadSignals(); for (const hdmap::PathOverlap* signal_light : signal_lights_along_reference_line_) { const TrafficLight signal = GetSignal(signal_light->object_id); double stop_deceleration = GetStopDeceleration(reference_line_info, signal_light); if ((signal.color() == TrafficLight::RED && stop_deceleration < FLAGS_max_stop_deceleration) || // (signal.color() == TrafficLight::UNKNOWN && // stop_deceleration < FLAGS_max_stop_deceleration) || (signal.color() == TrafficLight::YELLOW && stop_deceleration < FLAGS_max_stop_deacceleration_for_yellow_light)) { CreateStopObstacle(frame, reference_line_info, signal_light); } } return 0; } bool SignalLightScenario::FindValidSignalLight( ReferenceLineInfo* const reference_line_info) { const std::vector<hdmap::PathOverlap>& signal_lights = reference_line_info->reference_line().map_path().signal_overlaps(); if (signal_lights.size() <= 0) { ADEBUG << "No signal lights from reference line."; return false; } else { ADEBUG << "Found signal_lights size=" << signal_lights.size(); } signal_lights_along_reference_line_.clear(); for (const hdmap::PathOverlap& signal_light : signal_lights) { if (signal_light.start_s + FLAGS_max_stop_distance_buffer > reference_line_info->AdcSlBoundary().end_s()) { signal_lights_along_reference_line_.push_back(&signal_light); } } return signal_lights_along_reference_line_.size() > 0; } void SignalLightScenario::ReadSignals() { detected_signals_.clear(); detected_signals_.clear(); if (AdapterManager::GetTrafficLightDetection()->Empty()) { return; } if (AdapterManager::GetTrafficLightDetection()->GetDelaySec() > FLAGS_signal_expire_time_sec) { AWARN << "traffic signals msg is expired: " << AdapterManager::GetTrafficLightDetection()->GetDelaySec(); return; } const TrafficLightDetection& detection = AdapterManager::GetTrafficLightDetection()->GetLatestObserved(); for (int j = 0; j < detection.traffic_light_size(); j++) { const TrafficLight& signal = detection.traffic_light(j); detected_signals_[signal.id()] = &signal; } } TrafficLight SignalLightScenario::GetSignal(const std::string& signal_id) { const auto* result = apollo::common::util::FindPtrOrNull(detected_signals_, signal_id); if (result == nullptr) { TrafficLight traffic_light; traffic_light.set_id(signal_id); traffic_light.set_color(TrafficLight::UNKNOWN); traffic_light.set_confidence(0.0); traffic_light.set_tracking_time(0.0); return traffic_light; } return *result; } double SignalLightScenario::GetStopDeceleration( ReferenceLineInfo* const reference_line_info, const hdmap::PathOverlap* signal_light) { double adc_speed = common::VehicleStateProvider::instance()->linear_velocity(); if (adc_speed < FLAGS_max_stop_speed) { return 0.0; } double stop_distance = 0.0; double adc_front_s = reference_line_info->AdcSlBoundary().end_s(); double stop_line_s = signal_light->start_s; if (stop_line_s > adc_front_s) { stop_distance = stop_line_s - adc_front_s; } else { stop_distance = stop_line_s + FLAGS_max_stop_distance_buffer - adc_front_s; } if (stop_distance < 1e-5) { // longitudinal_acceleration_lower_bound is a negative value. return -FLAGS_longitudinal_acceleration_lower_bound; } return (adc_speed * adc_speed) / (2 * stop_distance); } void SignalLightScenario::CreateStopObstacle( Frame* frame, ReferenceLineInfo* const reference_line_info, const hdmap::PathOverlap* signal_light) { // check const auto& reference_line = reference_line_info->reference_line(); const double stop_s = signal_light->start_s - FLAGS_traffic_light_stop_distance; const double box_center_s = signal_light->start_s + FLAGS_virtual_stop_wall_length / 2.0; if (!WithinBound(0.0, reference_line.Length(), stop_s) || !WithinBound(0.0, reference_line.Length(), box_center_s)) { ADEBUG << "signal " << signal_light->object_id << " is not on reference line"; return; } // create virtual stop wall std::string virtual_obstacle_id = FLAGS_signal_light_virtual_obstacle_id_prefix + signal_light->object_id; auto* obstacle = frame->CreateVirtualStopObstacle( reference_line_info, virtual_obstacle_id, signal_light->start_s); if (!obstacle) { AERROR << "Failed to create obstacle [" << virtual_obstacle_id << "]"; return; } PathObstacle* stop_wall = reference_line_info->AddObstacle(obstacle); if (!stop_wall) { AERROR << "Failed to create path_obstacle for: " << virtual_obstacle_id; return; } return; } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file qp_piecewise_st_graph.cc **/ #include "modules/planning/tasks/qp_spline_st_speed/qp_piecewise_st_graph.h" #include <algorithm> #include <limits> #include <string> #include <utility> #include "modules/common/log.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::VehicleParam; using apollo::planning_internal::STGraphDebug; QpPiecewiseStGraph::QpPiecewiseStGraph( const QpSplineStSpeedConfig& qp_spline_st_speed_config, const VehicleParam& veh_param) : qp_spline_st_speed_config_(qp_spline_st_speed_config), t_evaluated_resolution_( qp_spline_st_speed_config_.total_time() / qp_spline_st_speed_config_.number_of_evaluated_graph_t()) { Init(); } void QpPiecewiseStGraph::Init() { // init evaluated t positions double curr_t = t_evaluated_resolution_; for (uint32_t i = 0; i < qp_spline_st_speed_config_.number_of_evaluated_graph_t(); ++i) { t_evaluated_.push_back(curr_t); curr_t += t_evaluated_resolution_; } } void QpPiecewiseStGraph::SetDebugLogger( planning_internal::STGraphDebug* st_graph_debug) { if (st_graph_debug) { st_graph_debug->Clear(); st_graph_debug_ = st_graph_debug; } } Status QpPiecewiseStGraph::Search( const StGraphData& st_graph_data, SpeedData* const speed_data, const std::pair<double, double>& accel_bound) { cruise_.clear(); // reset piecewise linear generator generator_.reset(new PiecewiseLinearGenerator( qp_spline_st_speed_config_.number_of_evaluated_graph_t(), t_evaluated_resolution_)); // start to search for best st points init_point_ = st_graph_data.init_point(); // modified total path length if (st_graph_data.path_data_length() < qp_spline_st_speed_config_.total_path_length()) { qp_spline_st_speed_config_.set_total_path_length( st_graph_data.path_data_length()); } if (!ApplyConstraint(st_graph_data.init_point(), st_graph_data.speed_limit(), st_graph_data.st_boundaries(), accel_bound) .ok()) { const std::string msg = "Apply constraint failed!"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } if (!ApplyKernel(st_graph_data.st_boundaries(), st_graph_data.speed_limit()) .ok()) { const std::string msg = "Apply kernel failed!"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } if (!Solve().ok()) { const std::string msg = "Solve qp problem failed!"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } // extract output speed_data->Clear(); const auto& res = generator_->params(); speed_data->AppendSpeedPoint(0.0, 0.0, init_point_.v(), init_point_.a(), 0.0); double s = 0.0; double v = 0.0; double a = 0.0; double time = t_evaluated_resolution_; double dt = t_evaluated_resolution_; for (int i = 0; i < res.rows(); ++i, time += t_evaluated_resolution_) { s = res(i, 0); if (i == 0) { v = s / dt; a = (v - init_point_.v()) / dt; } else { const double curr_v = (s - res(i - 1, 0)) / dt; a = (curr_v - v) / dt; v = curr_v; } speed_data->AppendSpeedPoint(s, time, v, a, 0.0); } return Status::OK(); } Status QpPiecewiseStGraph::ApplyConstraint( const common::TrajectoryPoint& init_point, const SpeedLimit& speed_limit, const std::vector<StBoundary>& boundaries, const std::pair<double, double>& accel_bound) { // TODO(Lianliang): implement this function. return Status::OK(); } Status QpPiecewiseStGraph::ApplyKernel( const std::vector<StBoundary>& boundaries, const SpeedLimit& speed_limit) { // TODO(Lianliang): implement this function. return Status::OK(); } Status QpPiecewiseStGraph::AddFollowReferenceLineKernel( const std::vector<StBoundary>& boundaries, const double weight) { // TODO(Lianliang): implement this function. return Status::OK(); } Status QpPiecewiseStGraph::GetSConstraintByTime( const std::vector<StBoundary>& boundaries, const double time, const double total_path_s, double* const s_upper_bound, double* const s_lower_bound) const { // TODO(Lianliang): implement this function. return Status::OK(); } Status QpPiecewiseStGraph::EstimateSpeedUpperBound( const common::TrajectoryPoint& init_point, const SpeedLimit& speed_limit, std::vector<double>* speed_upper_bound) const { // TODO(Lianliang): implement this function. return Status::OK(); } } // namespace planning } // namespace apollo <commit_msg>Planning: Updated qp_piecewise_st_graph.<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file qp_piecewise_st_graph.cc **/ #include "modules/planning/tasks/qp_spline_st_speed/qp_piecewise_st_graph.h" #include <algorithm> #include <limits> #include <string> #include <utility> #include "modules/common/log.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::VehicleParam; using apollo::planning_internal::STGraphDebug; QpPiecewiseStGraph::QpPiecewiseStGraph( const QpSplineStSpeedConfig& qp_spline_st_speed_config, const VehicleParam& veh_param) : qp_spline_st_speed_config_(qp_spline_st_speed_config), t_evaluated_resolution_( qp_spline_st_speed_config_.total_time() / qp_spline_st_speed_config_.number_of_evaluated_graph_t()) { Init(); } void QpPiecewiseStGraph::Init() { // init evaluated t positions double curr_t = t_evaluated_resolution_; for (uint32_t i = 0; i < qp_spline_st_speed_config_.number_of_evaluated_graph_t(); ++i) { t_evaluated_.push_back(curr_t); curr_t += t_evaluated_resolution_; } } void QpPiecewiseStGraph::SetDebugLogger( planning_internal::STGraphDebug* st_graph_debug) { if (st_graph_debug) { st_graph_debug->Clear(); st_graph_debug_ = st_graph_debug; } } Status QpPiecewiseStGraph::Search( const StGraphData& st_graph_data, SpeedData* const speed_data, const std::pair<double, double>& accel_bound) { cruise_.clear(); // reset piecewise linear generator generator_.reset(new PiecewiseLinearGenerator( qp_spline_st_speed_config_.number_of_evaluated_graph_t(), t_evaluated_resolution_)); // start to search for best st points init_point_ = st_graph_data.init_point(); // modified total path length if (st_graph_data.path_data_length() < qp_spline_st_speed_config_.total_path_length()) { qp_spline_st_speed_config_.set_total_path_length( st_graph_data.path_data_length()); } if (!ApplyConstraint(st_graph_data.init_point(), st_graph_data.speed_limit(), st_graph_data.st_boundaries(), accel_bound) .ok()) { const std::string msg = "Apply constraint failed!"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } if (!ApplyKernel(st_graph_data.st_boundaries(), st_graph_data.speed_limit()) .ok()) { const std::string msg = "Apply kernel failed!"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } if (!Solve().ok()) { const std::string msg = "Solve qp problem failed!"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } // extract output speed_data->Clear(); const auto& res = generator_->params(); speed_data->AppendSpeedPoint(0.0, 0.0, init_point_.v(), init_point_.a(), 0.0); double s = 0.0; double v = 0.0; double a = 0.0; double time = t_evaluated_resolution_; double dt = t_evaluated_resolution_; for (int i = 0; i < res.rows(); ++i, time += t_evaluated_resolution_) { s = res(i, 0); if (i == 0) { v = s / dt; a = (v - init_point_.v()) / dt; } else { const double curr_v = (s - res(i - 1, 0)) / dt; a = (curr_v - v) / dt; v = curr_v; } speed_data->AppendSpeedPoint(s, time, v, a, 0.0); } return Status::OK(); } Status QpPiecewiseStGraph::ApplyConstraint( const common::TrajectoryPoint& init_point, const SpeedLimit& speed_limit, const std::vector<StBoundary>& boundaries, const std::pair<double, double>& accel_bound) { // TODO(Lianliang): implement this function. return Status::OK(); } Status QpPiecewiseStGraph::ApplyKernel( const std::vector<StBoundary>& boundaries, const SpeedLimit& speed_limit) { // TODO(Lianliang): implement this function. return Status::OK(); } Status QpPiecewiseStGraph::AddFollowReferenceLineKernel( const std::vector<StBoundary>& boundaries, const double weight) { // TODO(Lianliang): implement this function. return Status::OK(); } Status QpPiecewiseStGraph::GetSConstraintByTime( const std::vector<StBoundary>& boundaries, const double time, const double total_path_s, double* const s_upper_bound, double* const s_lower_bound) const { // TODO(Lianliang): implement this function. return Status::OK(); } Status QpPiecewiseStGraph::EstimateSpeedUpperBound( const common::TrajectoryPoint& init_point, const SpeedLimit& speed_limit, std::vector<double>* speed_upper_bound) const { // TODO(Lianliang): define a QpStGraph class and move this function in it. DCHECK_NOTNULL(speed_upper_bound); speed_upper_bound->clear(); // use v to estimate position: not accurate, but feasible in cyclic // processing. We can do the following process multiple times and use // previous cycle's results for better estimation. const double v = init_point.v(); if (static_cast<double>(t_evaluated_.size() + speed_limit.speed_limit_points().size()) < t_evaluated_.size() * std::log(static_cast<double>( speed_limit.speed_limit_points().size()))) { uint32_t i = 0; uint32_t j = 0; const double kDistanceEpsilon = 1e-6; while (i < t_evaluated_.size() && j + 1 < speed_limit.speed_limit_points().size()) { const double distance = v * t_evaluated_[i]; if (fabs(distance - speed_limit.speed_limit_points()[j].first) < kDistanceEpsilon) { speed_upper_bound->push_back( speed_limit.speed_limit_points()[j].second); ++i; ADEBUG << "speed upper bound:" << speed_upper_bound->back(); } else if (distance < speed_limit.speed_limit_points()[j].first) { ++i; } else if (distance <= speed_limit.speed_limit_points()[j + 1].first) { speed_upper_bound->push_back(speed_limit.GetSpeedLimitByS(distance)); ADEBUG << "speed upper bound:" << speed_upper_bound->back(); ++i; } else { ++j; } } for (uint32_t k = speed_upper_bound->size(); k < t_evaluated_.size(); ++k) { speed_upper_bound->push_back(FLAGS_planning_upper_speed_limit); ADEBUG << "speed upper bound:" << speed_upper_bound->back(); } } else { auto cmp = [](const std::pair<double, double>& p1, const double s) { return p1.first < s; }; const auto& speed_limit_points = speed_limit.speed_limit_points(); for (const double t : t_evaluated_) { const double s = v * t; // NOTICE: we are using binary search here based on two assumptions: // (1) The s in speed_limit_points increase monotonically. // (2) The evaluated_t_.size() << number of speed_limit_points.size() // // If either of the two assumption is failed, a new algorithm must be // used // to replace the binary search. const auto& it = std::lower_bound(speed_limit_points.begin(), speed_limit_points.end(), s, cmp); if (it != speed_limit_points.end()) { speed_upper_bound->push_back(it->second); } else { speed_upper_bound->push_back(speed_limit_points.back().second); } } } const double kTimeBuffer = 2.0; const double kSpeedBuffer = 0.1; for (uint32_t k = 0; k < t_evaluated_.size() && t_evaluated_[k] < kTimeBuffer; ++k) { speed_upper_bound->at(k) = std::fmax(init_point_.v() + kSpeedBuffer, speed_upper_bound->at(k)); } return Status::OK(); } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before>// (C) 2014 Arek Olek #pragma once #include <stack> #include <vector> #include <boost/graph/adjacency_list.hpp> #include "range.hpp" namespace detail { unsigned typedef node; std::pair<node, node> typedef edge; template <class Graph> void visit(Graph& G, Graph& T, node v, node& next_rank, std::vector<node>& rank, std::vector<node>& deg, std::stack<edge>& edges) { rank[v] = next_rank++; node w, x, y; unsigned min_deg = UINT_MAX; for(auto u : range(adjacent_vertices(v, G))) { --deg[u]; if(rank[u] == 0 && deg[u] < min_deg) { w = u; min_deg = deg[u]; } } if(min_deg == UINT_MAX) { while(!edges.empty() && rank[edges.top().second] != 0) edges.pop(); if(edges.empty()) return; std::tie(x, y) = edges.top(); } else std::tie(x, y) = edge(v, w); add_edge(x, y, T); for(auto u : range(adjacent_vertices(x, G))) if(u != y && rank[u] == 0) edges.emplace(x, u); visit(G, T, y, next_rank, rank, deg, edges); } } template <class Graph> Graph rdfs_tree(Graph& G) { unsigned n = num_vertices(G); Graph T(n); unsigned next_rank = 1; std::vector<detail::node> rank(n, 0), deg(n); std::stack<detail::edge> edges; for(auto v : range(vertices(G))) deg[v] = degree(v, G); detail::visit(G, T, 0, next_rank, rank, deg, edges); return T; } <commit_msg>fix compile warning<commit_after>// (C) 2014 Arek Olek #pragma once #include <stack> #include <vector> #include <boost/graph/adjacency_list.hpp> #include "range.hpp" namespace detail { unsigned typedef node; std::pair<node, node> typedef edge; template <class Graph> void visit(Graph& G, Graph& T, node v, node& next_rank, std::vector<node>& rank, std::vector<node>& deg, std::stack<edge>& edges) { rank[v] = next_rank++; node w = -1, x, y; unsigned min_deg = UINT_MAX; for(auto u : range(adjacent_vertices(v, G))) { --deg[u]; if(rank[u] == 0 && deg[u] < min_deg) { w = u; min_deg = deg[u]; } } if(min_deg == UINT_MAX) { while(!edges.empty() && rank[edges.top().second] != 0) edges.pop(); if(edges.empty()) return; std::tie(x, y) = edges.top(); } else std::tie(x, y) = edge(v, w); add_edge(x, y, T); for(auto u : range(adjacent_vertices(x, G))) if(u != y && rank[u] == 0) edges.emplace(x, u); visit(G, T, y, next_rank, rank, deg, edges); } } template <class Graph> Graph rdfs_tree(Graph& G) { unsigned n = num_vertices(G); Graph T(n); unsigned next_rank = 1; std::vector<detail::node> rank(n, 0), deg(n); std::stack<detail::edge> edges; for(auto v : range(vertices(G))) deg[v] = degree(v, G); detail::visit(G, T, 0, next_rank, rank, deg, edges); return T; } <|endoftext|>
<commit_before>#pragma once #include <bitset> #include <cstring> #include <iostream> namespace bitwise { using std::cout; using std::ostream; template <typename A> class binary final { template <typename B> using conref = const B&; constexpr static size_t sz{sizeof(A)}; constexpr static size_t szB{sz << 3}; using bitA = std::bitset<szB>; using byte = unsigned char; using bit = bool; public: explicit binary(void) = delete; explicit binary(conref<A> a) noexcept { byte* ptr = new byte[sz]; memcpy((void *) ptr, (const void* const) &a, sz); for (size_t i = 0; i < sz; ++i) { static byte ch; ch = ptr[i]; for (size_t j = 0; j < 8; ++j) { static bool bitVal; bitVal = binary<A>::getBitFromByte(ch, j); this->bits[binary<A>::getBitIdx(i, j)] = bitVal; } } delete [] ptr; } explicit binary(A&& a) noexcept : binary(a) {} template <typename... B> explicit binary(B... b) = delete; inline ~binary(void) noexcept{ bits.~bitA(); } inline void print(void) const noexcept { binary<A>::print(std::cout, *this); } inline bool getBit(conref<size_t> idx) const noexcept { return bits[idx]; } inline bool getBit(conref<byte> byteIdx, conref<byte> bitIdx) const noexcept { return binary<A>::getBit(*this, byteIdx, bitIdx); } template <typename... B> inline bool getBit(B... b) const noexcept = delete; template <typename B> friend inline ostream& operator<<(ostream& os, conref<binary<B>> a) noexcept { a.print(); return os; } template <typename B> friend inline ostream& operator<<(ostream& os, binary<B>&& a) noexcept { a.print(); return os; } private: static inline void print(std::ostream& os, conref<binary<A>> a) noexcept { constexpr static size_t szOneLess{sz - 1}; for (size_t i = 0; i < sz; ++i) { for (size_t j = 0; j < 8; ++j) { static bit bitIdx; bitIdx = (bit) a.bits[getBitIdx(i, j)]; os << bitIdx; } if (szOneLess != i) { os << ' '; } } } static inline bit getBitFromByte(conref<byte> data, conref<byte> bitIdx) noexcept { return data & (1 << bitIdx); } static inline size_t getBitIdx(conref<size_t> byteIdx, conref<size_t> bitIdx) noexcept { return (byteIdx << 3) + bitIdx; } static inline bit getBit(conref<binary<A>> bits, conref<size_t> byteIdx, conref<size_t> bitIdx) noexcept { return bits[getBitIdx(byteIdx, bitIdx)]; } bitA bits; }; }<commit_msg>added to whole despairagus interproject namespace<commit_after>#pragma once #include <bitset> #include <cstring> #include <iostream> namespace desparaigus { namespace bitwise { using std::cout; using std::ostream; template<typename A> class binary final { template<typename B> using conref = const B &; constexpr static size_t sz{sizeof(A)}; constexpr static size_t szB{sz << 3}; using bitA = std::bitset<szB>; using byte = unsigned char; using bit = bool; public: explicit binary(void) = delete; explicit binary(conref<A> a) noexcept { byte *ptr = new byte[sz]; memcpy((void *) ptr, (const void *const) &a, sz); for (size_t i = 0; i < sz; ++i) { static byte ch; ch = ptr[i]; for (size_t j = 0; j < 8; ++j) { static bool bitVal; bitVal = binary<A>::getBitFromByte(ch, j); this->bits[binary<A>::getBitIdx(i, j)] = bitVal; } } delete[] ptr; } explicit binary(A &&a) noexcept : binary(a) { } template<typename... B> explicit binary(B... b) = delete; inline ~binary(void) noexcept { bits.~bitA(); } inline void print(void) const noexcept { binary<A>::print(std::cout, *this); } inline bool getBit(conref<size_t> idx) const noexcept { return bits[idx]; } inline bool getBit(conref<byte> byteIdx, conref<byte> bitIdx) const noexcept { return binary<A>::getBit(*this, byteIdx, bitIdx); } template<typename... B> inline bool getBit(B... b) const noexcept = delete; template<typename B> friend inline ostream &operator<<(ostream &os, conref<binary<B>> a) noexcept { a.print(); return os; } template<typename B> friend inline ostream &operator<<(ostream &os, binary<B> &&a) noexcept { a.print(); return os; } private: static inline void print(std::ostream &os, conref<binary<A>> a) noexcept { constexpr static size_t szOneLess{sz - 1}; for (size_t i = 0; i < sz; ++i) { for (size_t j = 0; j < 8; ++j) { static bit bitIdx; bitIdx = (bit) a.bits[getBitIdx(i, j)]; os << bitIdx; } if (szOneLess != i) { os << ' '; } } } static inline bit getBitFromByte(conref<byte> data, conref<byte> bitIdx) noexcept { return data & (1 << bitIdx); } static inline size_t getBitIdx(conref<size_t> byteIdx, conref<size_t> bitIdx) noexcept { return (byteIdx << 3) + bitIdx; } static inline bit getBit(conref<binary<A>> bits, conref<size_t> byteIdx, conref<size_t> bitIdx) noexcept { return bits[getBitIdx(byteIdx, bitIdx)]; } bitA bits; }; } }<|endoftext|>
<commit_before>#include <node.h> #include <nan.h> #include <v8.h> #include "gamepad/Gamepad.h" using namespace v8; Nan::Persistent<Object> persistentHandle; Nan::AsyncResource asyncResource("gamepad"); NAN_METHOD(nGamepad_init) { Nan::HandleScope scope; Gamepad_init(); return; } NAN_METHOD(nGamepad_shutdown) { Nan::HandleScope scope; Gamepad_shutdown(); return; } NAN_METHOD(nGamepad_numDevices) { Nan::HandleScope scope; info.GetReturnValue().Set(Nan::New<Number>(Gamepad_numDevices())); } Local<Object> nGamepad_toObject(Gamepad_device* device) { Local<Object> obj = Nan::New<Object>(); obj->Set(Nan::New("deviceID").ToLocalChecked(), Nan::New<Number>(device->deviceID)); obj->Set(Nan::New("description").ToLocalChecked(), Nan::New<String>(device->description).ToLocalChecked()); obj->Set(Nan::New("vendorID").ToLocalChecked(), Nan::New<Number>(device->vendorID)); obj->Set(Nan::New("productID").ToLocalChecked(), Nan::New<Number>(device->productID)); Local<Array> axes = Nan::New<Array>(device->numAxes); for (unsigned int i = 0; i < device->numAxes; i++) { axes->Set(i, Nan::New<Number>(device->axisStates[i])); } obj->Set(Nan::New("axisStates").ToLocalChecked(), axes); Local<Array> buttons = Nan::New<Array>(device->numButtons); for (unsigned int i = 0; i < device->numButtons; i++) { buttons->Set(i, Nan::New<Boolean>(device->buttonStates[i])); } obj->Set(Nan::New("buttonStates").ToLocalChecked(), buttons); return obj; } NAN_METHOD(nGamepad_deviceAtIndex) { Nan::HandleScope scope; int deviceIndex = info[0].As<Int32>()->Value(); struct Gamepad_device* device = Gamepad_deviceAtIndex(deviceIndex); if (!device) return; info.GetReturnValue().Set(nGamepad_toObject(device)); } NAN_METHOD(nGamepad_detectDevices) { Nan::HandleScope scope; Gamepad_detectDevices(); return; } NAN_METHOD(nGamepad_processEvents) { Nan::HandleScope scope; Gamepad_processEvents(); return; } void nGamepad_deviceAttach_cb(struct Gamepad_device* device, void* context) { Local<Value> info[] = { Nan::New("attach").ToLocalChecked(), Nan::New<Number>(device->deviceID), nGamepad_toObject(device), }; asyncResource.runInAsyncScope(Nan::New<Object>(persistentHandle), "on", 3, info); } void nGamepad_deviceRemove_cb(struct Gamepad_device* device, void* context) { Local<Value> info[] = { Nan::New("remove").ToLocalChecked(), Nan::New<Number>(device->deviceID), }; asyncResource.runInAsyncScope(Nan::New<Object>(persistentHandle), "on", 2, info); } void nGamepad_buttonDown_cb(struct Gamepad_device* device, unsigned int buttonID, double timestamp, void* context) { Local<Value> info[] = { Nan::New("down").ToLocalChecked(), Nan::New<Number>(device->deviceID), Nan::New<Number>(buttonID), Nan::New<Number>(timestamp), }; asyncResource.runInAsyncScope(Nan::New<Object>(persistentHandle), "on", 4, info); } void nGamepad_buttonUp_cb(struct Gamepad_device* device, unsigned int buttonID, double timestamp, void* context) { Local<Value> info[] = { Nan::New("up").ToLocalChecked(), Nan::New<Number>(device->deviceID), Nan::New<Number>(buttonID), Nan::New<Number>(timestamp), }; asyncResource.runInAsyncScope(Nan::New<Object>(persistentHandle), "on", 4, info); } void nGamepad_axisMove_cb(struct Gamepad_device* device, unsigned int axisID, float value, float lastValue, double timestamp, void * context) { Local<Value> info[] = { Nan::New("move").ToLocalChecked(), Nan::New<Number>(device->deviceID), Nan::New<Number>(axisID), Nan::New<Number>(value), Nan::New<Number>(lastValue), Nan::New<Number>(timestamp), }; asyncResource.runInAsyncScope(Nan::New<Object>(persistentHandle), "on", 6, info); } void init(Local<Object> target) { Local<Object> handle = Nan::New<Object>(); persistentHandle.Reset(handle); target->Set(Nan::New<String>("context").ToLocalChecked(), handle); Gamepad_deviceAttachFunc(nGamepad_deviceAttach_cb, NULL); Gamepad_deviceRemoveFunc(nGamepad_deviceRemove_cb, NULL); Gamepad_buttonDownFunc(nGamepad_buttonDown_cb, NULL); Gamepad_buttonUpFunc(nGamepad_buttonUp_cb, NULL); Gamepad_axisMoveFunc(nGamepad_axisMove_cb, NULL); Nan::SetMethod(target, "init", nGamepad_init); Nan::SetMethod(target, "shutdown", nGamepad_shutdown); Nan::SetMethod(target, "numDevices", nGamepad_numDevices); Nan::SetMethod(target, "deviceAtIndex", nGamepad_deviceAtIndex); Nan::SetMethod(target, "detectDevices", nGamepad_detectDevices); Nan::SetMethod(target, "processEvents", nGamepad_processEvents); } NODE_MODULE(gamepad, init) <commit_msg>Replace deprecated usage of Set with Nan::Set<commit_after>#include <node.h> #include <nan.h> #include <v8.h> #include "gamepad/Gamepad.h" using namespace v8; Nan::Persistent<Object> persistentHandle; Nan::AsyncResource asyncResource("gamepad"); NAN_METHOD(nGamepad_init) { Nan::HandleScope scope; Gamepad_init(); return; } NAN_METHOD(nGamepad_shutdown) { Nan::HandleScope scope; Gamepad_shutdown(); return; } NAN_METHOD(nGamepad_numDevices) { Nan::HandleScope scope; info.GetReturnValue().Set(Nan::New<Number>(Gamepad_numDevices())); } Local<Object> nGamepad_toObject(Gamepad_device* device) { Local<Object> obj = Nan::New<Object>(); Nan::Set(obj, Nan::New("deviceID").ToLocalChecked(), Nan::New<Number>(device->deviceID)); Nan::Set(obj, Nan::New("description").ToLocalChecked(), Nan::New<String>(device->description).ToLocalChecked()); Nan::Set(obj, Nan::New("vendorID").ToLocalChecked(), Nan::New<Number>(device->vendorID)); Nan::Set(obj, Nan::New("productID").ToLocalChecked(), Nan::New<Number>(device->productID)); Local<Array> axes = Nan::New<Array>(device->numAxes); for (unsigned int i = 0; i < device->numAxes; i++) { Nan::Set(axes, i, Nan::New<Number>(device->axisStates[i])); } Nan::Set(obj, Nan::New("axisStates").ToLocalChecked(), axes); Local<Array> buttons = Nan::New<Array>(device->numButtons); for (unsigned int i = 0; i < device->numButtons; i++) { Nan::Set(buttons, i, Nan::New<Boolean>(device->buttonStates[i])); } Nan::Set(obj, Nan::New("buttonStates").ToLocalChecked(), buttons); return obj; } NAN_METHOD(nGamepad_deviceAtIndex) { Nan::HandleScope scope; int deviceIndex = info[0].As<Int32>()->Value(); struct Gamepad_device* device = Gamepad_deviceAtIndex(deviceIndex); if (!device) return; info.GetReturnValue().Set(nGamepad_toObject(device)); } NAN_METHOD(nGamepad_detectDevices) { Nan::HandleScope scope; Gamepad_detectDevices(); return; } NAN_METHOD(nGamepad_processEvents) { Nan::HandleScope scope; Gamepad_processEvents(); return; } void nGamepad_deviceAttach_cb(struct Gamepad_device* device, void* context) { Local<Value> info[] = { Nan::New("attach").ToLocalChecked(), Nan::New<Number>(device->deviceID), nGamepad_toObject(device), }; asyncResource.runInAsyncScope(Nan::New<Object>(persistentHandle), "on", 3, info); } void nGamepad_deviceRemove_cb(struct Gamepad_device* device, void* context) { Local<Value> info[] = { Nan::New("remove").ToLocalChecked(), Nan::New<Number>(device->deviceID), }; asyncResource.runInAsyncScope(Nan::New<Object>(persistentHandle), "on", 2, info); } void nGamepad_buttonDown_cb(struct Gamepad_device* device, unsigned int buttonID, double timestamp, void* context) { Local<Value> info[] = { Nan::New("down").ToLocalChecked(), Nan::New<Number>(device->deviceID), Nan::New<Number>(buttonID), Nan::New<Number>(timestamp), }; asyncResource.runInAsyncScope(Nan::New<Object>(persistentHandle), "on", 4, info); } void nGamepad_buttonUp_cb(struct Gamepad_device* device, unsigned int buttonID, double timestamp, void* context) { Local<Value> info[] = { Nan::New("up").ToLocalChecked(), Nan::New<Number>(device->deviceID), Nan::New<Number>(buttonID), Nan::New<Number>(timestamp), }; asyncResource.runInAsyncScope(Nan::New<Object>(persistentHandle), "on", 4, info); } void nGamepad_axisMove_cb(struct Gamepad_device* device, unsigned int axisID, float value, float lastValue, double timestamp, void * context) { Local<Value> info[] = { Nan::New("move").ToLocalChecked(), Nan::New<Number>(device->deviceID), Nan::New<Number>(axisID), Nan::New<Number>(value), Nan::New<Number>(lastValue), Nan::New<Number>(timestamp), }; asyncResource.runInAsyncScope(Nan::New<Object>(persistentHandle), "on", 6, info); } void init(Local<Object> target) { Local<Object> handle = Nan::New<Object>(); persistentHandle.Reset(handle); Nan::Set(target, Nan::New<String>("context").ToLocalChecked(), handle); Gamepad_deviceAttachFunc(nGamepad_deviceAttach_cb, NULL); Gamepad_deviceRemoveFunc(nGamepad_deviceRemove_cb, NULL); Gamepad_buttonDownFunc(nGamepad_buttonDown_cb, NULL); Gamepad_buttonUpFunc(nGamepad_buttonUp_cb, NULL); Gamepad_axisMoveFunc(nGamepad_axisMove_cb, NULL); Nan::SetMethod(target, "init", nGamepad_init); Nan::SetMethod(target, "shutdown", nGamepad_shutdown); Nan::SetMethod(target, "numDevices", nGamepad_numDevices); Nan::SetMethod(target, "deviceAtIndex", nGamepad_deviceAtIndex); Nan::SetMethod(target, "detectDevices", nGamepad_detectDevices); Nan::SetMethod(target, "processEvents", nGamepad_processEvents); } NODE_MODULE(gamepad, init) <|endoftext|>
<commit_before>/* * producer.cpp * * Created on: Dec 28, 2012 * Author: partio */ #include "producer.h" using namespace himan; producer::producer() : itsFmiProducerId(kHPMissingInt) , itsProcess(kHPMissingInt) , itsCentre(kHPMissingInt) , itsTableVersion(kHPMissingInt) , itsNeonsName("") { } producer::producer(long theFmiProducerId) : itsFmiProducerId(theFmiProducerId) , itsProcess(kHPMissingInt) , itsCentre(kHPMissingInt) , itsTableVersion(kHPMissingInt) , itsNeonsName("") { } producer::producer(long theCentre, long theProcess) : itsFmiProducerId(kHPMissingInt) , itsProcess(theProcess) , itsCentre(theCentre) , itsTableVersion(kHPMissingInt) , itsNeonsName("") { } producer::producer(long theFmiProducerId, long theCentre, long theProcess, const std::string& theNeonsName) : itsFmiProducerId(theFmiProducerId) , itsProcess(theProcess) , itsCentre(theCentre) , itsTableVersion(kHPMissingInt) , itsNeonsName("") { } void producer::Centre(long theCentre) { itsCentre = theCentre; } long producer::Centre() const { return itsCentre; } void producer::Process(long theProcess) { itsProcess = theProcess; } long producer::Process() const { return itsProcess; } void producer::Id(long theId) { itsFmiProducerId = theId; } long producer::Id() const { return itsFmiProducerId; } void producer::Name(const std::string& theName) { itsNeonsName = theName; } std::string producer::Name() const { return itsNeonsName; } long producer::TableVersion() const { return itsTableVersion; } void producer::TableVersion(long theTableVersion) { itsTableVersion = theTableVersion; } std::ostream& producer::Write(std::ostream& file) const { file << "<" << ClassName() << " " << Version() << ">" << std::endl; file << "__itsFmiProducerId__ " << itsFmiProducerId << std::endl; file << "__itsProcess__ " << itsProcess << std::endl; file << "__itsCentre__ " << itsCentre << std::endl; file << "__itsNeonsName__ " << itsNeonsName << std::endl; file << "__itsTableVersion__ " << itsTableVersion << std::endl; return file; } <commit_msg>Set default name<commit_after>/* * producer.cpp * * Created on: Dec 28, 2012 * Author: partio */ #include "producer.h" using namespace himan; producer::producer() : itsFmiProducerId(kHPMissingInt) , itsProcess(kHPMissingInt) , itsCentre(kHPMissingInt) , itsTableVersion(kHPMissingInt) , itsNeonsName("himanDefaultProducer") { } producer::producer(long theFmiProducerId) : itsFmiProducerId(theFmiProducerId) , itsProcess(kHPMissingInt) , itsCentre(kHPMissingInt) , itsTableVersion(kHPMissingInt) , itsNeonsName("himanDefaultProducer") { } producer::producer(long theCentre, long theProcess) : itsFmiProducerId(kHPMissingInt) , itsProcess(theProcess) , itsCentre(theCentre) , itsTableVersion(kHPMissingInt) , itsNeonsName("himanDefaultProducer") { } producer::producer(long theFmiProducerId, long theCentre, long theProcess, const std::string& theNeonsName) : itsFmiProducerId(theFmiProducerId) , itsProcess(theProcess) , itsCentre(theCentre) , itsTableVersion(kHPMissingInt) , itsNeonsName(theNeonsName) { } void producer::Centre(long theCentre) { itsCentre = theCentre; } long producer::Centre() const { return itsCentre; } void producer::Process(long theProcess) { itsProcess = theProcess; } long producer::Process() const { return itsProcess; } void producer::Id(long theId) { itsFmiProducerId = theId; } long producer::Id() const { return itsFmiProducerId; } void producer::Name(const std::string& theName) { itsNeonsName = theName; } std::string producer::Name() const { return itsNeonsName; } long producer::TableVersion() const { return itsTableVersion; } void producer::TableVersion(long theTableVersion) { itsTableVersion = theTableVersion; } std::ostream& producer::Write(std::ostream& file) const { file << "<" << ClassName() << " " << Version() << ">" << std::endl; file << "__itsFmiProducerId__ " << itsFmiProducerId << std::endl; file << "__itsProcess__ " << itsProcess << std::endl; file << "__itsCentre__ " << itsCentre << std::endl; file << "__itsNeonsName__ " << itsNeonsName << std::endl; file << "__itsTableVersion__ " << itsTableVersion << std::endl; return file; } <|endoftext|>
<commit_before>#include "SysControl.h" #include "ControlsApp.h" #include "ControlsXPad360.h" #include "Engine.h" #include "App.h" #include "Engine.h" #include "App.h" #include "Input.h" #include "ObjectGui.h" #include "WidgetLabel.h" //解决跨平台字符集兼容问题 #ifdef _WIN32 #pragma execution_character_set("utf-8") #endif using namespace MathLib; class CSysControlLocal : public CSysControl { public: CSysControlLocal(); virtual ~CSysControlLocal(); virtual void Init(); //角色要初始化,着色器要初始化, virtual void Update(float ifps); virtual void Shutdown(); virtual int GetState(int state); //鼠标状态,键盘状态,人物状态,子弹状态等等。 virtual int ClearState(int state); virtual float GetMouseDX(); virtual float GetMouseDY(); virtual void SetMouseGrab(int g); //设置是否显示鼠标 virtual int GetMouseGrab(); //获取鼠标状态,是显示呢还是不显示的状态。 virtual void SetControlMode(ControlMode mode); //控制模式 virtual ControlMode GetControlMode() const; //获取控制模式 private: void Update_Mouse(float ifps); void Update_Keyboard(float ifps); void Update_XPad360(float ifps); CControlsApp *m_pControlsApp; //控制游戏中移动 CControlsXPad360 *m_pControlsXPad360; ControlMode m_nControlMode; //控制模式 int m_nOldMouseX; //上一个鼠标坐标X int m_nOldMouseY; //上一个鼠标坐标Y CObjectGui *m_pTest3DUI; CWidgetLabel *m_pTestMessageLabel; }; CSysControlLocal::CSysControlLocal() { } CSysControlLocal::~CSysControlLocal() { } void CSysControlLocal::Init() { m_pControlsApp = new CControlsApp; m_pControlsXPad360 = new CControlsXPad360(0); g_Engine.pApp->SetMouseGrab(0); g_Engine.pApp->SetMouseShow(0); SetControlMode(CONTROL_KEYBORAD_MOUSE); m_pTest3DUI = new CObjectGui(2.0f, 1.0f, "data/core/gui/"); m_pTest3DUI->SetMouseShow(0); m_pTest3DUI->SetBackground(1); m_pTest3DUI->SetBackgroundColor(vec4(1.0f, 0.0f, 0.0f, 1.0f)); m_pTest3DUI->SetScreenSize(800, 400); m_pTest3DUI->SetControlDistance(1000.0f); m_pTest3DUI->CreateMaterial("gui_base"); //show in game m_pTest3DUI->SetWorldTransform(Translate(0.0f, 0.0f, 2.0f) * MakeRotationFromZY(vec3(0.0f, -1.0f, 0.0f), vec3(0.0f, 0.0f, 1.0f))); m_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui()); //初始化文字标签 m_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER); m_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f)); m_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui()); //初始化文字标签 m_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER); m_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f)); m_pTestMessageLabel->SetFontSize(80); //设置字体大小 m_pTestMessageLabel->SetFontOutline(1); //设置字体轮廓 m_pTestMessageLabel->SetText("两个黄鹂鸣翠柳\n一行白鹭上青天\n窗含西岭千秋雪\n门泊东吴万里船"); void CSysControlLocal::Update(float ifps) { Update_Mouse(ifps); Update_Keyboard(ifps); Update_XPad360(ifps); } m_nOldMouseX = 0; m_nOldMouseY = 0; } void CSysControlLocal::Shutdown() { g_Engine.pApp->SetMouseGrab(0); g_Engine.pApp->SetMouseShow(0); delete m_pControlsApp; m_pControlsApp = NULL; delete m_pControlsXPad360; m_pControlsXPad360 = NULL; delete m_pTestMessageLabel; m_pTestMessageLabel = NULL; delete m_pTest3DUI; m_pTest3DUI = NULL; } int CSysControlLocal::GetState(int state) { return m_pControlsApp->GetState(state); } int CSysControlLocal::ClearState(int state) { return m_pControlsApp->ClearState(state); } float CSysControlLocal::GetMouseDX() { return m_pControlsApp->GetMouseDX(); } float CSysControlLocal::GetMouseDY() { return m_pControlsApp->GetMouseDY(); } void CSysControlLocal::SetMouseGrab(int g) { g_Engine.pApp->SetMouseGrab(g); g_Engine.pGui->SetMouseShow(!g); } int CSysControlLocal::GetMouseGrab() { return g_Engine.pApp->GetMouseGrab(); } void CSysControlLocal::SetControlMode(ControlMode mode) { m_nControlMode = mode; } CSysControl::ControlMode CSysControlLocal::GetControlMode() const { return m_nControlMode; } CSysControl::ControlMode CSysControlLocal::GetControlMode() const { return m_nControlMode; } void CSysControlLocal::Update_Mouse(float ifps) { float dx = (g_Engine.pApp->GetMouseX() - m_nOldMouseX) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;//0.1f这个数值越大,鼠标移动越快 float dy = (g_Engine.pApp->GetMouseY() - m_nOldMouseY) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;//0.1这个数值越小,鼠标移动越慢 m_pControlsApp->SetMouseDX(dx); m_pControlsApp->SetMouseDY(dy); if (g_Engine.pApp->GetMouseGrab() && g_Engine.pApp->GetActive()) { g_Engine.pApp->SetMouse(g_Engine.pApp->GetWidth() / 2, g_Engine.pApp->GetHeight() / 2); } m_nOldMouseX = g_Engine.pApp->GetMouseX(); m_nOldMouseY = g_Engine.pApp->GetMouseY(); } void CSysControlLocal::Update_Keyboard(float ifps) //键盘按键响应wsad { if (g_Engine.pInput->IsKeyDown('w')) m_pControlsApp->SetState(CControls::STATE_FORWARD, 1); if (g_Engine.pInput->IsKeyDown('s')) m_pControlsApp->SetState(CControls::STATE_BACKWARD, 1); if (g_Engine.pInput->IsKeyDown('a')) m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 1); if (g_Engine.pInput->IsKeyDown('d')) m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 1); if (g_Engine.pInput->IsKeyUp('w')) m_pControlsApp->SetState(CControls::STATE_FORWARD, 0); else if (g_Engine.pInput->IsKeyUp('s')) m_pControlsApp->SetState(CControls::STATE_BACKWARD, 0); if (g_Engine.pInput->IsKeyUp('a')) m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 0); else if (g_Engine.pInput->IsKeyUp('d')) m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 0); if (g_Engine.pInput->IsKeyDown(' ')) //空格跳跃 m_pControlsApp->SetState(CControls::STATE_JUMP, 1); else m_pControlsApp->SetState(CControls::STATE_JUMP, 0); } void CSysControlLocal::Update_XPad360(float ifps) { m_pControlsXPad360->UpdateEvents(); CUtilStr strMessage; strMessage = CUtilStr("测试3D UI\n"), strMessage += CUtilStr(m_pControlsXPad360->GetName()) + "\n"; strMessage += CUtilStr::Format("\n手柄测试\n"); strMessage += CUtilStr::Format("LeftX: %5.2f\n", m_pControlsXPad360->GetLeftX()); strMessage += CUtilStr::Format("LeftY: %5.2f\n", m_pControlsXPad360->GetLeftY()); strMessage += CUtilStr::Format("RightX: %5.2f\n", m_pControlsXPad360->GetRightX()); strMessage += CUtilStr::Format("RightY: %5.2f\n", m_pControlsXPad360->GetRightY()); strMessage += "\nTriggers:\n"; strMessage += CUtilStr::Format("Left: %5.2f\n", m_pControlsXPad360->GetLeftTrigger()); strMessage += CUtilStr::Format("Right: %5.2f\n", m_pControlsXPad360->GetRightTrigger()); strMessage += CUtilStr::Format("\nButtons:\n"); for (int i = 0; i < CControlsXPad360::NUM_BUTTONS; ++i) { strMessage += CUtilStr::Format("%d ", m_pControlsXPad360->GetButton(i)); } m_pTestMessageLabel->SetText(strMessage.Get()); const float fPadThreshold = 0.5f; if (m_pControlsXPad360->GetLeftX() > fPadThreshold) m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 1); else if (m_pControlsXPad360->GetLeftX() < -fPadThreshold) m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 1); else { m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 0); m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 0); } }<commit_msg>Signed-off-by: mrlitong <[email protected]><commit_after>#include "SysControl.h" #include "ControlsApp.h" #include "ControlsXPad360.h" #include "Engine.h" #include "App.h" #include "Engine.h" #include "App.h" #include "Input.h" #include "ObjectGui.h" #include "WidgetLabel.h" //解决跨平台字符集兼容问题 #ifdef _WIN32 #pragma execution_character_set("utf-8") #endif using namespace MathLib; class CSysControlLocal : public CSysControl { public: CSysControlLocal(); virtual ~CSysControlLocal(); virtual void Init(); //角色要初始化,着色器要初始化, virtual void Update(float ifps); virtual void Shutdown(); virtual int GetState(int state); //鼠标状态,键盘状态,人物状态,子弹状态等等。 virtual int ClearState(int state); virtual float GetMouseDX(); virtual float GetMouseDY(); virtual void SetMouseGrab(int g); //设置是否显示鼠标 virtual int GetMouseGrab(); //获取鼠标状态,是显示呢还是不显示的状态。 virtual void SetControlMode(ControlMode mode); //控制模式 virtual ControlMode GetControlMode() const; //获取控制模式 private: void Update_Mouse(float ifps); void Update_Keyboard(float ifps); void Update_XPad360(float ifps); CControlsApp *m_pControlsApp; //控制游戏中移动 CControlsXPad360 *m_pControlsXPad360; ControlMode m_nControlMode; //控制模式 int m_nOldMouseX; //上一个鼠标坐标X int m_nOldMouseY; //上一个鼠标坐标Y CObjectGui *m_pTest3DUI; CWidgetLabel *m_pTestMessageLabel; }; CSysControlLocal::CSysControlLocal() { } CSysControlLocal::~CSysControlLocal() { } void CSysControlLocal::Init() { m_pControlsApp = new CControlsApp; m_pControlsXPad360 = new CControlsXPad360(0); g_Engine.pApp->SetMouseGrab(0); g_Engine.pApp->SetMouseShow(0); SetControlMode(CONTROL_KEYBORAD_MOUSE); m_pTest3DUI = new CObjectGui(2.0f, 1.0f, "data/core/gui/"); m_pTest3DUI->SetMouseShow(0); m_pTest3DUI->SetBackground(1); m_pTest3DUI->SetBackgroundColor(vec4(1.0f, 0.0f, 0.0f, 1.0f)); m_pTest3DUI->SetScreenSize(800, 400); m_pTest3DUI->SetControlDistance(1000.0f); m_pTest3DUI->CreateMaterial("gui_base"); //show in game m_pTest3DUI->SetWorldTransform(Translate(0.0f, 0.0f, 2.0f) * MakeRotationFromZY(vec3(0.0f, -1.0f, 0.0f), vec3(0.0f, 0.0f, 1.0f))); m_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui()); //初始化文字标签 m_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER); m_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f)); m_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui()); //初始化文字标签 m_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER); m_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f)); m_pTestMessageLabel->SetFontSize(80); //设置字体大小 m_pTestMessageLabel->SetFontOutline(1); //设置字体轮廓 m_pTestMessageLabel->SetText("两个黄鹂鸣翠柳\n一行白鹭上青天\n窗含西岭千秋雪\n门泊东吴万里船"); void CSysControlLocal::Update(float ifps) { Update_Mouse(ifps); Update_Keyboard(ifps); Update_XPad360(ifps); } m_nOldMouseX = 0; m_nOldMouseY = 0; } void CSysControlLocal::Shutdown() { g_Engine.pApp->SetMouseGrab(0); g_Engine.pApp->SetMouseShow(0); delete m_pControlsApp; m_pControlsApp = NULL; delete m_pControlsXPad360; m_pControlsXPad360 = NULL; delete m_pTestMessageLabel; m_pTestMessageLabel = NULL; delete m_pTest3DUI; m_pTest3DUI = NULL; } int CSysControlLocal::GetState(int state) { return m_pControlsApp->GetState(state); } int CSysControlLocal::ClearState(int state) { return m_pControlsApp->ClearState(state); } float CSysControlLocal::GetMouseDX() { return m_pControlsApp->GetMouseDX(); } float CSysControlLocal::GetMouseDY() { return m_pControlsApp->GetMouseDY(); } void CSysControlLocal::SetMouseGrab(int g) { g_Engine.pApp->SetMouseGrab(g); g_Engine.pGui->SetMouseShow(!g); } int CSysControlLocal::GetMouseGrab() { return g_Engine.pApp->GetMouseGrab(); } void CSysControlLocal::SetControlMode(ControlMode mode) { m_nControlMode = mode; } CSysControl::ControlMode CSysControlLocal::GetControlMode() const { return m_nControlMode; } CSysControl::ControlMode CSysControlLocal::GetControlMode() const { return m_nControlMode; } void CSysControlLocal::Update_Mouse(float ifps) { float dx = (g_Engine.pApp->GetMouseX() - m_nOldMouseX) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;//0.1f这个数值越大,鼠标移动越快 float dy = (g_Engine.pApp->GetMouseY() - m_nOldMouseY) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;//0.1这个数值越小,鼠标移动越慢 m_pControlsApp->SetMouseDX(dx); m_pControlsApp->SetMouseDY(dy); if (g_Engine.pApp->GetMouseGrab() && g_Engine.pApp->GetActive()) { g_Engine.pApp->SetMouse(g_Engine.pApp->GetWidth() / 2, g_Engine.pApp->GetHeight() / 2); } m_nOldMouseX = g_Engine.pApp->GetMouseX(); m_nOldMouseY = g_Engine.pApp->GetMouseY(); } void CSysControlLocal::Update_Keyboard(float ifps) //键盘按键响应wsad { if (g_Engine.pInput->IsKeyDown('w')) m_pControlsApp->SetState(CControls::STATE_FORWARD, 1); if (g_Engine.pInput->IsKeyDown('s')) m_pControlsApp->SetState(CControls::STATE_BACKWARD, 1); if (g_Engine.pInput->IsKeyDown('a')) m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 1); if (g_Engine.pInput->IsKeyDown('d')) m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 1); if (g_Engine.pInput->IsKeyUp('w')) m_pControlsApp->SetState(CControls::STATE_FORWARD, 0); else if (g_Engine.pInput->IsKeyUp('s')) m_pControlsApp->SetState(CControls::STATE_BACKWARD, 0); if (g_Engine.pInput->IsKeyUp('a')) m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 0); else if (g_Engine.pInput->IsKeyUp('d')) m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 0); if (g_Engine.pInput->IsKeyDown(' ')) //空格跳跃 m_pControlsApp->SetState(CControls::STATE_JUMP, 1); else m_pControlsApp->SetState(CControls::STATE_JUMP, 0); } void CSysControlLocal::Update_XPad360(float ifps) { m_pControlsXPad360->UpdateEvents(); CUtilStr strMessage; strMessage = CUtilStr("测试3D UI\n"), strMessage += CUtilStr(m_pControlsXPad360->GetName()) + "\n"; strMessage += CUtilStr::Format("\n手柄测试\n"); strMessage += CUtilStr::Format("LeftX: %5.2f\n", m_pControlsXPad360->GetLeftX()); strMessage += CUtilStr::Format("LeftY: %5.2f\n", m_pControlsXPad360->GetLeftY()); strMessage += CUtilStr::Format("RightX: %5.2f\n", m_pControlsXPad360->GetRightX()); strMessage += CUtilStr::Format("RightY: %5.2f\n", m_pControlsXPad360->GetRightY()); strMessage += "\nTriggers:\n"; strMessage += CUtilStr::Format("Left: %5.2f\n", m_pControlsXPad360->GetLeftTrigger()); strMessage += CUtilStr::Format("Right: %5.2f\n", m_pControlsXPad360->GetRightTrigger()); strMessage += CUtilStr::Format("\nButtons:\n"); for (int i = 0; i < CControlsXPad360::NUM_BUTTONS; ++i) { strMessage += CUtilStr::Format("%d ", m_pControlsXPad360->GetButton(i)); } m_pTestMessageLabel->SetText(strMessage.Get()); const float fPadThreshold = 0.5f; if (m_pControlsXPad360->GetLeftX() > fPadThreshold) m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 1); else if (m_pControlsXPad360->GetLeftX() < -fPadThreshold) m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 1); else { m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 0); m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 0); } if (m_pControlsXPad360->GetLeftY() > fPadThreshold) m_pControlsApp->SetState(CControls::STATE_FORWARD, 1); }<|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/toolkits/optimizers/road_graph/trajectory_cost.h" #include <algorithm> #include <cmath> #include <limits> #include <utility> #include "modules/common/proto/pnc_point.pb.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/math/vec2d.h" #include "modules/common/util/util.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::TrajectoryPoint; using apollo::common::math::Box2d; using apollo::common::math::Sigmoid; using apollo::common::math::Vec2d; TrajectoryCost::TrajectoryCost(const DpPolyPathConfig &config, const ReferenceLine &reference_line, const bool is_change_lane_path, const std::vector<const Obstacle *> &obstacles, const common::VehicleParam &vehicle_param, const SpeedData &heuristic_speed_data, const common::SLPoint &init_sl_point, const SLBoundary &adc_sl_boundary) : config_(config), reference_line_(&reference_line), is_change_lane_path_(is_change_lane_path), vehicle_param_(vehicle_param), heuristic_speed_data_(heuristic_speed_data), init_sl_point_(init_sl_point), adc_sl_boundary_(adc_sl_boundary) { const double total_time = std::min(heuristic_speed_data_.TotalTime(), FLAGS_prediction_total_time); num_of_time_stamps_ = static_cast<uint32_t>( std::floor(total_time / config.eval_time_interval())); for (const auto *ptr_obstacle : obstacles) { if (ptr_obstacle->IsIgnore()) { continue; } else if (ptr_obstacle->LongitudinalDecision().has_stop()) { continue; } const auto &sl_boundary = ptr_obstacle->PerceptionSLBoundary(); const double adc_left_l = init_sl_point_.l() + vehicle_param_.left_edge_to_center(); const double adc_right_l = init_sl_point_.l() - vehicle_param_.right_edge_to_center(); if (adc_left_l + FLAGS_lateral_ignore_buffer < sl_boundary.start_l() || adc_right_l - FLAGS_lateral_ignore_buffer > sl_boundary.end_l()) { continue; } bool is_bycycle_or_pedestrian = (ptr_obstacle->Perception().type() == perception::PerceptionObstacle::BICYCLE || ptr_obstacle->Perception().type() == perception::PerceptionObstacle::PEDESTRIAN); if (ptr_obstacle->IsVirtual()) { // Virtual obstacle continue; } else if (ptr_obstacle->IsStatic() || is_bycycle_or_pedestrian) { static_obstacle_sl_boundaries_.push_back(std::move(sl_boundary)); } else { std::vector<Box2d> box_by_time; for (uint32_t t = 0; t <= num_of_time_stamps_; ++t) { TrajectoryPoint trajectory_point = ptr_obstacle->GetPointAtTime(t * config.eval_time_interval()); Box2d obstacle_box = ptr_obstacle->GetBoundingBox(trajectory_point); constexpr double kBuff = 0.5; Box2d expanded_obstacle_box = Box2d(obstacle_box.center(), obstacle_box.heading(), obstacle_box.length() + kBuff, obstacle_box.width() + kBuff); box_by_time.push_back(expanded_obstacle_box); } dynamic_obstacle_boxes_.push_back(std::move(box_by_time)); } } } ComparableCost TrajectoryCost::CalculatePathCost( const QuinticPolynomialCurve1d &curve, const double start_s, const double end_s, const uint32_t curr_level, const uint32_t total_level) { ComparableCost cost; double path_cost = 0.0; std::function<double(const double)> quasi_softmax = [this](const double x) { const double l0 = this->config_.path_l_cost_param_l0(); const double b = this->config_.path_l_cost_param_b(); const double k = this->config_.path_l_cost_param_k(); return (b + std::exp(-k * (x - l0))) / (1.0 + std::exp(-k * (x - l0))); }; for (double curve_s = 0.0; curve_s < (end_s - start_s); curve_s += config_.path_resolution()) { const double l = curve.Evaluate(0, curve_s); path_cost += l * l * config_.path_l_cost() * quasi_softmax(std::fabs(l)); const double dl = std::fabs(curve.Evaluate(1, curve_s)); if (IsOffRoad(curve_s + start_s, l, dl, is_change_lane_path_)) { cost.cost_items[ComparableCost::OUT_OF_BOUNDARY] = true; } path_cost += dl * dl * config_.path_dl_cost(); const double ddl = std::fabs(curve.Evaluate(2, curve_s)); path_cost += ddl * ddl * config_.path_ddl_cost(); } path_cost *= config_.path_resolution(); if (curr_level == total_level) { const double end_l = curve.Evaluate(0, end_s - start_s); path_cost += std::sqrt(end_l - init_sl_point_.l() / 2.0) * config_.path_end_l_cost(); } cost.smoothness_cost = path_cost; return cost; } bool TrajectoryCost::IsOffRoad(const double ref_s, const double l, const double dl, const bool is_change_lane_path) { constexpr double kIgnoreDistance = 5.0; if (ref_s - init_sl_point_.s() < kIgnoreDistance) { return false; } Vec2d rear_center(0.0, l); const auto &param = common::VehicleConfigHelper::GetConfig().vehicle_param(); Vec2d vec_to_center( (param.front_edge_to_center() - param.back_edge_to_center()) / 2.0, (param.left_edge_to_center() - param.right_edge_to_center()) / 2.0); Vec2d rear_center_to_center = vec_to_center.rotate(std::atan(dl)); Vec2d center = rear_center + rear_center_to_center; Vec2d front_center = center + rear_center_to_center; const double buffer = 0.1; // in meters const double r_w = (param.left_edge_to_center() + param.right_edge_to_center()) / 2.0; const double r_l = param.back_edge_to_center(); const double r = std::sqrt(r_w * r_w + r_l * r_l); double left_width = 0.0; double right_width = 0.0; reference_line_->GetLaneWidth(ref_s, &left_width, &right_width); double left_bound = std::max(init_sl_point_.l() + r + buffer, left_width); double right_bound = std::min(init_sl_point_.l() - r - buffer, -right_width); if (rear_center.y() + r + buffer / 2.0 > left_bound || rear_center.y() - r - buffer / 2.0 < right_bound) { return true; } if (front_center.y() + r + buffer / 2.0 > left_bound || front_center.y() - r - buffer / 2.0 < right_bound) { return true; } return false; } ComparableCost TrajectoryCost::CalculateStaticObstacleCost( const QuinticPolynomialCurve1d &curve, const double start_s, const double end_s) { ComparableCost obstacle_cost; for (double curr_s = start_s; curr_s <= end_s; curr_s += config_.path_resolution()) { const double curr_l = curve.Evaluate(0, curr_s - start_s); for (const auto &obs_sl_boundary : static_obstacle_sl_boundaries_) { obstacle_cost += GetCostFromObsSL(curr_s, curr_l, obs_sl_boundary); } } obstacle_cost.safety_cost *= config_.path_resolution(); return obstacle_cost; } ComparableCost TrajectoryCost::CalculateDynamicObstacleCost( const QuinticPolynomialCurve1d &curve, const double start_s, const double end_s) const { ComparableCost obstacle_cost; if (dynamic_obstacle_boxes_.empty()) { return obstacle_cost; } double time_stamp = 0.0; for (size_t index = 0; index < num_of_time_stamps_; ++index, time_stamp += config_.eval_time_interval()) { common::SpeedPoint speed_point; heuristic_speed_data_.EvaluateByTime(time_stamp, &speed_point); double ref_s = speed_point.s() + init_sl_point_.s(); if (ref_s < start_s) { continue; } if (ref_s > end_s) { break; } const double s = ref_s - start_s; // s on spline curve const double l = curve.Evaluate(0, s); const double dl = curve.Evaluate(1, s); const common::SLPoint sl = common::util::MakeSLPoint(ref_s, l); const Box2d ego_box = GetBoxFromSLPoint(sl, dl); for (const auto &obstacle_trajectory : dynamic_obstacle_boxes_) { obstacle_cost += GetCostBetweenObsBoxes(ego_box, obstacle_trajectory.at(index)); } } constexpr double kDynamicObsWeight = 1e-6; obstacle_cost.safety_cost *= (config_.eval_time_interval() * kDynamicObsWeight); return obstacle_cost; } ComparableCost TrajectoryCost::GetCostFromObsSL( const double adc_s, const double adc_l, const SLBoundary &obs_sl_boundary) { const auto &vehicle_param = common::VehicleConfigHelper::Instance()->GetConfig().vehicle_param(); ComparableCost obstacle_cost; if (obs_sl_boundary.start_l() * obs_sl_boundary.end_l() <= 0.0) { return obstacle_cost; } const double adc_front_s = adc_s + vehicle_param.front_edge_to_center(); const double adc_end_s = adc_s - vehicle_param.back_edge_to_center(); const double adc_left_l = adc_l + vehicle_param.left_edge_to_center(); const double adc_right_l = adc_l - vehicle_param.right_edge_to_center(); if (adc_left_l + FLAGS_lateral_ignore_buffer < obs_sl_boundary.start_l() || adc_right_l - FLAGS_lateral_ignore_buffer > obs_sl_boundary.end_l()) { return obstacle_cost; } bool no_overlap = ((adc_front_s < obs_sl_boundary.start_s() || adc_end_s > obs_sl_boundary.end_s()) || // longitudinal (adc_left_l + 0.1 < obs_sl_boundary.start_l() || adc_right_l - 0.1 > obs_sl_boundary.end_l())); // lateral if (!no_overlap) { obstacle_cost.cost_items[ComparableCost::HAS_COLLISION] = true; } // if obstacle is behind ADC, ignore its cost contribution. if (adc_front_s > obs_sl_boundary.end_s()) { return obstacle_cost; } const double delta_l = std::fmax(adc_right_l - obs_sl_boundary.end_l(), obs_sl_boundary.start_l() - adc_left_l); /* AWARN << "adc_s: " << adc_s << "; adc_left_l: " << adc_left_l << "; adc_right_l: " << adc_right_l << "; delta_l = " << delta_l; AWARN << obs_sl_boundary.ShortDebugString(); */ constexpr double kSafeDistance = 1.0; if (delta_l < kSafeDistance) { obstacle_cost.safety_cost += config_.obstacle_collision_cost() * Sigmoid(config_.obstacle_collision_distance() - delta_l); } return obstacle_cost; } // Simple version: calculate obstacle cost by distance ComparableCost TrajectoryCost::GetCostBetweenObsBoxes( const Box2d &ego_box, const Box2d &obstacle_box) const { ComparableCost obstacle_cost; const double distance = obstacle_box.DistanceTo(ego_box); if (distance > config_.obstacle_ignore_distance()) { return obstacle_cost; } obstacle_cost.safety_cost += config_.obstacle_collision_cost() * Sigmoid(config_.obstacle_collision_distance() - distance); obstacle_cost.safety_cost += 20.0 * Sigmoid(config_.obstacle_risk_distance() - distance); return obstacle_cost; } Box2d TrajectoryCost::GetBoxFromSLPoint(const common::SLPoint &sl, const double dl) const { Vec2d xy_point; reference_line_->SLToXY(sl, &xy_point); ReferencePoint reference_point = reference_line_->GetReferencePoint(sl.s()); const double one_minus_kappa_r_d = 1 - reference_point.kappa() * sl.l(); const double delta_theta = std::atan2(dl, one_minus_kappa_r_d); const double theta = common::math::NormalizeAngle(delta_theta + reference_point.heading()); return Box2d(xy_point, theta, vehicle_param_.length(), vehicle_param_.width()); } // TODO(All): optimize obstacle cost calculation time ComparableCost TrajectoryCost::Calculate(const QuinticPolynomialCurve1d &curve, const double start_s, const double end_s, const uint32_t curr_level, const uint32_t total_level) { ComparableCost total_cost; // path cost total_cost += CalculatePathCost(curve, start_s, end_s, curr_level, total_level); // static obstacle cost total_cost += CalculateStaticObstacleCost(curve, start_s, end_s); // dynamic obstacle cost total_cost += CalculateDynamicObstacleCost(curve, start_s, end_s); return total_cost; } } // namespace planning } // namespace apollo <commit_msg>Planning: reduced the distance for cost calculation.<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/toolkits/optimizers/road_graph/trajectory_cost.h" #include <algorithm> #include <cmath> #include <limits> #include <utility> #include "modules/common/proto/pnc_point.pb.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/math/vec2d.h" #include "modules/common/util/util.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::TrajectoryPoint; using apollo::common::math::Box2d; using apollo::common::math::Sigmoid; using apollo::common::math::Vec2d; TrajectoryCost::TrajectoryCost(const DpPolyPathConfig &config, const ReferenceLine &reference_line, const bool is_change_lane_path, const std::vector<const Obstacle *> &obstacles, const common::VehicleParam &vehicle_param, const SpeedData &heuristic_speed_data, const common::SLPoint &init_sl_point, const SLBoundary &adc_sl_boundary) : config_(config), reference_line_(&reference_line), is_change_lane_path_(is_change_lane_path), vehicle_param_(vehicle_param), heuristic_speed_data_(heuristic_speed_data), init_sl_point_(init_sl_point), adc_sl_boundary_(adc_sl_boundary) { const double total_time = std::min(heuristic_speed_data_.TotalTime(), FLAGS_prediction_total_time); num_of_time_stamps_ = static_cast<uint32_t>( std::floor(total_time / config.eval_time_interval())); for (const auto *ptr_obstacle : obstacles) { if (ptr_obstacle->IsIgnore()) { continue; } else if (ptr_obstacle->LongitudinalDecision().has_stop()) { continue; } const auto &sl_boundary = ptr_obstacle->PerceptionSLBoundary(); const double adc_left_l = init_sl_point_.l() + vehicle_param_.left_edge_to_center(); const double adc_right_l = init_sl_point_.l() - vehicle_param_.right_edge_to_center(); if (adc_left_l + FLAGS_lateral_ignore_buffer < sl_boundary.start_l() || adc_right_l - FLAGS_lateral_ignore_buffer > sl_boundary.end_l()) { continue; } bool is_bycycle_or_pedestrian = (ptr_obstacle->Perception().type() == perception::PerceptionObstacle::BICYCLE || ptr_obstacle->Perception().type() == perception::PerceptionObstacle::PEDESTRIAN); if (ptr_obstacle->IsVirtual()) { // Virtual obstacle continue; } else if (ptr_obstacle->IsStatic() || is_bycycle_or_pedestrian) { static_obstacle_sl_boundaries_.push_back(std::move(sl_boundary)); } else { std::vector<Box2d> box_by_time; for (uint32_t t = 0; t <= num_of_time_stamps_; ++t) { TrajectoryPoint trajectory_point = ptr_obstacle->GetPointAtTime(t * config.eval_time_interval()); Box2d obstacle_box = ptr_obstacle->GetBoundingBox(trajectory_point); constexpr double kBuff = 0.5; Box2d expanded_obstacle_box = Box2d(obstacle_box.center(), obstacle_box.heading(), obstacle_box.length() + kBuff, obstacle_box.width() + kBuff); box_by_time.push_back(expanded_obstacle_box); } dynamic_obstacle_boxes_.push_back(std::move(box_by_time)); } } } ComparableCost TrajectoryCost::CalculatePathCost( const QuinticPolynomialCurve1d &curve, const double start_s, const double end_s, const uint32_t curr_level, const uint32_t total_level) { ComparableCost cost; double path_cost = 0.0; std::function<double(const double)> quasi_softmax = [this](const double x) { const double l0 = this->config_.path_l_cost_param_l0(); const double b = this->config_.path_l_cost_param_b(); const double k = this->config_.path_l_cost_param_k(); return (b + std::exp(-k * (x - l0))) / (1.0 + std::exp(-k * (x - l0))); }; for (double curve_s = 0.0; curve_s < (end_s - start_s); curve_s += config_.path_resolution()) { const double l = curve.Evaluate(0, curve_s); path_cost += l * l * config_.path_l_cost() * quasi_softmax(std::fabs(l)); const double dl = std::fabs(curve.Evaluate(1, curve_s)); if (IsOffRoad(curve_s + start_s, l, dl, is_change_lane_path_)) { cost.cost_items[ComparableCost::OUT_OF_BOUNDARY] = true; } path_cost += dl * dl * config_.path_dl_cost(); const double ddl = std::fabs(curve.Evaluate(2, curve_s)); path_cost += ddl * ddl * config_.path_ddl_cost(); } path_cost *= config_.path_resolution(); if (curr_level == total_level) { const double end_l = curve.Evaluate(0, end_s - start_s); path_cost += std::sqrt(end_l - init_sl_point_.l() / 2.0) * config_.path_end_l_cost(); } cost.smoothness_cost = path_cost; return cost; } bool TrajectoryCost::IsOffRoad(const double ref_s, const double l, const double dl, const bool is_change_lane_path) { constexpr double kIgnoreDistance = 5.0; if (ref_s - init_sl_point_.s() < kIgnoreDistance) { return false; } Vec2d rear_center(0.0, l); const auto &param = common::VehicleConfigHelper::GetConfig().vehicle_param(); Vec2d vec_to_center( (param.front_edge_to_center() - param.back_edge_to_center()) / 2.0, (param.left_edge_to_center() - param.right_edge_to_center()) / 2.0); Vec2d rear_center_to_center = vec_to_center.rotate(std::atan(dl)); Vec2d center = rear_center + rear_center_to_center; Vec2d front_center = center + rear_center_to_center; const double buffer = 0.1; // in meters const double r_w = (param.left_edge_to_center() + param.right_edge_to_center()) / 2.0; const double r_l = param.back_edge_to_center(); const double r = std::sqrt(r_w * r_w + r_l * r_l); double left_width = 0.0; double right_width = 0.0; reference_line_->GetLaneWidth(ref_s, &left_width, &right_width); double left_bound = std::max(init_sl_point_.l() + r + buffer, left_width); double right_bound = std::min(init_sl_point_.l() - r - buffer, -right_width); if (rear_center.y() + r + buffer / 2.0 > left_bound || rear_center.y() - r - buffer / 2.0 < right_bound) { return true; } if (front_center.y() + r + buffer / 2.0 > left_bound || front_center.y() - r - buffer / 2.0 < right_bound) { return true; } return false; } ComparableCost TrajectoryCost::CalculateStaticObstacleCost( const QuinticPolynomialCurve1d &curve, const double start_s, const double end_s) { ComparableCost obstacle_cost; for (double curr_s = start_s; curr_s <= end_s; curr_s += config_.path_resolution()) { const double curr_l = curve.Evaluate(0, curr_s - start_s); for (const auto &obs_sl_boundary : static_obstacle_sl_boundaries_) { obstacle_cost += GetCostFromObsSL(curr_s, curr_l, obs_sl_boundary); } } obstacle_cost.safety_cost *= config_.path_resolution(); return obstacle_cost; } ComparableCost TrajectoryCost::CalculateDynamicObstacleCost( const QuinticPolynomialCurve1d &curve, const double start_s, const double end_s) const { ComparableCost obstacle_cost; if (dynamic_obstacle_boxes_.empty()) { return obstacle_cost; } double time_stamp = 0.0; for (size_t index = 0; index < num_of_time_stamps_; ++index, time_stamp += config_.eval_time_interval()) { common::SpeedPoint speed_point; heuristic_speed_data_.EvaluateByTime(time_stamp, &speed_point); double ref_s = speed_point.s() + init_sl_point_.s(); if (ref_s < start_s) { continue; } if (ref_s > end_s) { break; } const double s = ref_s - start_s; // s on spline curve const double l = curve.Evaluate(0, s); const double dl = curve.Evaluate(1, s); const common::SLPoint sl = common::util::MakeSLPoint(ref_s, l); const Box2d ego_box = GetBoxFromSLPoint(sl, dl); for (const auto &obstacle_trajectory : dynamic_obstacle_boxes_) { obstacle_cost += GetCostBetweenObsBoxes(ego_box, obstacle_trajectory.at(index)); } } constexpr double kDynamicObsWeight = 1e-6; obstacle_cost.safety_cost *= (config_.eval_time_interval() * kDynamicObsWeight); return obstacle_cost; } ComparableCost TrajectoryCost::GetCostFromObsSL( const double adc_s, const double adc_l, const SLBoundary &obs_sl_boundary) { const auto &vehicle_param = common::VehicleConfigHelper::Instance()->GetConfig().vehicle_param(); ComparableCost obstacle_cost; if (obs_sl_boundary.start_l() * obs_sl_boundary.end_l() <= 0.0) { return obstacle_cost; } const double adc_front_s = adc_s + vehicle_param.front_edge_to_center(); const double adc_end_s = adc_s - vehicle_param.back_edge_to_center(); const double adc_left_l = adc_l + vehicle_param.left_edge_to_center(); const double adc_right_l = adc_l - vehicle_param.right_edge_to_center(); if (adc_left_l + FLAGS_lateral_ignore_buffer < obs_sl_boundary.start_l() || adc_right_l - FLAGS_lateral_ignore_buffer > obs_sl_boundary.end_l()) { return obstacle_cost; } bool no_overlap = ((adc_front_s < obs_sl_boundary.start_s() || adc_end_s > obs_sl_boundary.end_s()) || // longitudinal (adc_left_l + 0.1 < obs_sl_boundary.start_l() || adc_right_l - 0.1 > obs_sl_boundary.end_l())); // lateral if (!no_overlap) { obstacle_cost.cost_items[ComparableCost::HAS_COLLISION] = true; } // if obstacle is behind ADC, ignore its cost contribution. if (adc_front_s > obs_sl_boundary.end_s()) { return obstacle_cost; } const double delta_l = std::fmax(adc_right_l - obs_sl_boundary.end_l(), obs_sl_boundary.start_l() - adc_left_l); /* AWARN << "adc_s: " << adc_s << "; adc_left_l: " << adc_left_l << "; adc_right_l: " << adc_right_l << "; delta_l = " << delta_l; AWARN << obs_sl_boundary.ShortDebugString(); */ constexpr double kSafeDistance = 0.6; if (delta_l < kSafeDistance) { obstacle_cost.safety_cost += config_.obstacle_collision_cost() * Sigmoid(config_.obstacle_collision_distance() - delta_l); } return obstacle_cost; } // Simple version: calculate obstacle cost by distance ComparableCost TrajectoryCost::GetCostBetweenObsBoxes( const Box2d &ego_box, const Box2d &obstacle_box) const { ComparableCost obstacle_cost; const double distance = obstacle_box.DistanceTo(ego_box); if (distance > config_.obstacle_ignore_distance()) { return obstacle_cost; } obstacle_cost.safety_cost += config_.obstacle_collision_cost() * Sigmoid(config_.obstacle_collision_distance() - distance); obstacle_cost.safety_cost += 20.0 * Sigmoid(config_.obstacle_risk_distance() - distance); return obstacle_cost; } Box2d TrajectoryCost::GetBoxFromSLPoint(const common::SLPoint &sl, const double dl) const { Vec2d xy_point; reference_line_->SLToXY(sl, &xy_point); ReferencePoint reference_point = reference_line_->GetReferencePoint(sl.s()); const double one_minus_kappa_r_d = 1 - reference_point.kappa() * sl.l(); const double delta_theta = std::atan2(dl, one_minus_kappa_r_d); const double theta = common::math::NormalizeAngle(delta_theta + reference_point.heading()); return Box2d(xy_point, theta, vehicle_param_.length(), vehicle_param_.width()); } // TODO(All): optimize obstacle cost calculation time ComparableCost TrajectoryCost::Calculate(const QuinticPolynomialCurve1d &curve, const double start_s, const double end_s, const uint32_t curr_level, const uint32_t total_level) { ComparableCost total_cost; // path cost total_cost += CalculatePathCost(curve, start_s, end_s, curr_level, total_level); // static obstacle cost total_cost += CalculateStaticObstacleCost(curve, start_s, end_s); // dynamic obstacle cost total_cost += CalculateDynamicObstacleCost(curve, start_s, end_s); return total_cost; } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before>// Include the defined classes that are to be exported to python #include "IntegratorHPMC.h" #include "IntegratorHPMCMono.h" #include "IntegratorHPMCMono_FL.h" #include "ShapeSphere.h" #include "ShapeConvexPolygon.h" #include "ShapePolyhedron.h" #include "ShapeConvexPolyhedron.h" #include "ShapeSpheropolyhedron.h" #include "ShapeSpheropolygon.h" #include "ShapeSimplePolygon.h" #include "ShapeEllipsoid.h" #include "ShapeFacetedSphere.h" #include "ShapeSphinx.h" #include "ShapeUnion.h" #include "AnalyzerSDF.h" #include "UpdaterBoxNPT.h" #ifdef ENABLE_CUDA #include "IntegratorHPMCMonoGPU.h" #include "IntegratorHPMCMonoImplicitGPU.h" #endif /*! \file module.cc \brief Export classes to python */ // Include boost.python to do the exporting #include <boost/python.hpp> using namespace boost::python; using namespace hpmc; using namespace hpmc::detail; namespace hpmc { //! Export the GPU integrators void export_hpmc_gpu() { #ifdef ENABLE_CUDA export_IntegratorHPMCMonoGPU< ShapeSphere >("IntegratorHPMCMonoGPUSphere"); export_IntegratorHPMCMonoGPU< ShapeUnion<ShapeSphere> >("IntegratorHPMCMonoGPUSphereUnion"); export_IntegratorHPMCMonoGPU< ShapeConvexPolygon >("IntegratorHPMCMonoGPUConvexPolygon"); export_IntegratorHPMCMonoGPU< ShapeSimplePolygon >("IntegratorHPMCMonoGPUSimplePolygon"); export_IntegratorHPMCMonoGPU< ShapePolyhedron >("IntegratorHPMCMonoGPUPolyhedron"); export_IntegratorHPMCMonoGPU< ShapeConvexPolyhedron<8> >("IntegratorHPMCMonoGPUConvexPolyhedron8"); export_IntegratorHPMCMonoGPU< ShapeConvexPolyhedron<16> >("IntegratorHPMCMonoGPUConvexPolyhedron16"); export_IntegratorHPMCMonoGPU< ShapeConvexPolyhedron<32> >("IntegratorHPMCMonoGPUConvexPolyhedron32"); export_IntegratorHPMCMonoGPU< ShapeConvexPolyhedron<64> >("IntegratorHPMCMonoGPUConvexPolyhedron64"); export_IntegratorHPMCMonoGPU< ShapeConvexPolyhedron<128> >("IntegratorHPMCMonoGPUConvexPolyhedron128"); export_IntegratorHPMCMonoGPU< ShapeSpheropolyhedron<8> >("IntegratorHPMCMonoGPUSpheropolyhedron8"); export_IntegratorHPMCMonoGPU< ShapeSpheropolyhedron<16> >("IntegratorHPMCMonoGPUSpheropolyhedron16"); export_IntegratorHPMCMonoGPU< ShapeSpheropolyhedron<32> >("IntegratorHPMCMonoGPUSpheropolyhedron32"); export_IntegratorHPMCMonoGPU< ShapeSpheropolyhedron<64> >("IntegratorHPMCMonoGPUSpheropolyhedron64"); export_IntegratorHPMCMonoGPU< ShapeSpheropolyhedron<128> >("IntegratorHPMCMonoGPUSpheropolyhedron128"); export_IntegratorHPMCMonoGPU< ShapeEllipsoid >("IntegratorHPMCMonoGPUEllipsoid"); export_IntegratorHPMCMonoGPU< ShapeSpheropolygon >("IntegratorHPMCMonoGPUSpheropolygon"); export_IntegratorHPMCMonoGPU< ShapeFacetedSphere >("IntegratorHPMCMonoGPUFacetedSphere"); #ifdef ENABLE_SPHINX_GPU export_IntegratorHPMCMonoGPU< ShapeSphinx >("IntegratorHPMCMonoGPUSphinx"); #endif export_IntegratorHPMCMonoImplicitGPU< ShapeSphere >("IntegratorHPMCMonoImplicitGPUSphere"); export_IntegratorHPMCMonoImplicitGPU< ShapeConvexPolygon >("IntegratorHPMCMonoImplicitGPUConvexPolygon"); export_IntegratorHPMCMonoImplicitGPU< ShapeSimplePolygon >("IntegratorHPMCMonoImplicitGPUSimplePolygon"); export_IntegratorHPMCMonoImplicitGPU< ShapePolyhedron >("IntegratorHPMCMonoImplicitGPUPolyhedron"); export_IntegratorHPMCMonoImplicitGPU< ShapeConvexPolyhedron<8> >("IntegratorHPMCMonoImplicitGPUConvexPolyhedron8"); export_IntegratorHPMCMonoImplicitGPU< ShapeConvexPolyhedron<16> >("IntegratorHPMCMonoImplicitGPUConvexPolyhedron16"); export_IntegratorHPMCMonoImplicitGPU< ShapeConvexPolyhedron<32> >("IntegratorHPMCMonoImplicitGPUConvexPolyhedron32"); export_IntegratorHPMCMonoImplicitGPU< ShapeConvexPolyhedron<64> >("IntegratorHPMCMonoImplicitGPUConvexPolyhedron64"); export_IntegratorHPMCMonoImplicitGPU< ShapeConvexPolyhedron<128> >("IntegratorHPMCMonoImplicitGPUConvexPolyhedron128"); export_IntegratorHPMCMonoImplicitGPU< ShapeSpheropolyhedron<8> >("IntegratorHPMCMonoImplicitGPUSpheropolyhedron8"); export_IntegratorHPMCMonoImplicitGPU< ShapeSpheropolyhedron<16> >("IntegratorHPMCMonoImplicitGPUSpheropolyhedron16"); export_IntegratorHPMCMonoImplicitGPU< ShapeSpheropolyhedron<32> >("IntegratorHPMCMonoImplicitGPUSpheropolyhedron32"); export_IntegratorHPMCMonoImplicitGPU< ShapeSpheropolyhedron<64> >("IntegratorHPMCMonoImplicitGPUSpheropolyhedron64"); export_IntegratorHPMCMonoImplicitGPU< ShapeSpheropolyhedron<128> >("IntegratorHPMCMonoImplicitGPUSpheropolyhedron128"); export_IntegratorHPMCMonoImplicitGPU< ShapeEllipsoid>("IntegratorHPMCMonoImplicitGPUEllipsoid"); export_IntegratorHPMCMonoImplicitGPU< ShapeSpheropolygon>("IntegratorHPMCMonoImplicitGPUSpheropolygon"); export_IntegratorHPMCMonoImplicitGPU< ShapeFacetedSphere>("IntegratorHPMCMonoImplicitGPUFacetedSphere"); #ifdef ENABLE_SPHINX_GPU export_IntegratorHPMCMonoImplicitGPU< ShapeSphinx >("IntegratorHPMCMonoImplicitGPUSphinx"); #endif #endif } } <commit_msg>export sphere_union implicit integrator on GPU<commit_after>// Include the defined classes that are to be exported to python #include "IntegratorHPMC.h" #include "IntegratorHPMCMono.h" #include "IntegratorHPMCMono_FL.h" #include "ShapeSphere.h" #include "ShapeConvexPolygon.h" #include "ShapePolyhedron.h" #include "ShapeConvexPolyhedron.h" #include "ShapeSpheropolyhedron.h" #include "ShapeSpheropolygon.h" #include "ShapeSimplePolygon.h" #include "ShapeEllipsoid.h" #include "ShapeFacetedSphere.h" #include "ShapeSphinx.h" #include "ShapeUnion.h" #include "AnalyzerSDF.h" #include "UpdaterBoxNPT.h" #ifdef ENABLE_CUDA #include "IntegratorHPMCMonoGPU.h" #include "IntegratorHPMCMonoImplicitGPU.h" #endif /*! \file module.cc \brief Export classes to python */ // Include boost.python to do the exporting #include <boost/python.hpp> using namespace boost::python; using namespace hpmc; using namespace hpmc::detail; namespace hpmc { //! Export the GPU integrators void export_hpmc_gpu() { #ifdef ENABLE_CUDA export_IntegratorHPMCMonoGPU< ShapeSphere >("IntegratorHPMCMonoGPUSphere"); export_IntegratorHPMCMonoGPU< ShapeUnion<ShapeSphere> >("IntegratorHPMCMonoGPUSphereUnion"); export_IntegratorHPMCMonoGPU< ShapeConvexPolygon >("IntegratorHPMCMonoGPUConvexPolygon"); export_IntegratorHPMCMonoGPU< ShapeSimplePolygon >("IntegratorHPMCMonoGPUSimplePolygon"); export_IntegratorHPMCMonoGPU< ShapePolyhedron >("IntegratorHPMCMonoGPUPolyhedron"); export_IntegratorHPMCMonoGPU< ShapeConvexPolyhedron<8> >("IntegratorHPMCMonoGPUConvexPolyhedron8"); export_IntegratorHPMCMonoGPU< ShapeConvexPolyhedron<16> >("IntegratorHPMCMonoGPUConvexPolyhedron16"); export_IntegratorHPMCMonoGPU< ShapeConvexPolyhedron<32> >("IntegratorHPMCMonoGPUConvexPolyhedron32"); export_IntegratorHPMCMonoGPU< ShapeConvexPolyhedron<64> >("IntegratorHPMCMonoGPUConvexPolyhedron64"); export_IntegratorHPMCMonoGPU< ShapeConvexPolyhedron<128> >("IntegratorHPMCMonoGPUConvexPolyhedron128"); export_IntegratorHPMCMonoGPU< ShapeSpheropolyhedron<8> >("IntegratorHPMCMonoGPUSpheropolyhedron8"); export_IntegratorHPMCMonoGPU< ShapeSpheropolyhedron<16> >("IntegratorHPMCMonoGPUSpheropolyhedron16"); export_IntegratorHPMCMonoGPU< ShapeSpheropolyhedron<32> >("IntegratorHPMCMonoGPUSpheropolyhedron32"); export_IntegratorHPMCMonoGPU< ShapeSpheropolyhedron<64> >("IntegratorHPMCMonoGPUSpheropolyhedron64"); export_IntegratorHPMCMonoGPU< ShapeSpheropolyhedron<128> >("IntegratorHPMCMonoGPUSpheropolyhedron128"); export_IntegratorHPMCMonoGPU< ShapeEllipsoid >("IntegratorHPMCMonoGPUEllipsoid"); export_IntegratorHPMCMonoGPU< ShapeSpheropolygon >("IntegratorHPMCMonoGPUSpheropolygon"); export_IntegratorHPMCMonoGPU< ShapeFacetedSphere >("IntegratorHPMCMonoGPUFacetedSphere"); #ifdef ENABLE_SPHINX_GPU export_IntegratorHPMCMonoGPU< ShapeSphinx >("IntegratorHPMCMonoGPUSphinx"); #endif export_IntegratorHPMCMonoImplicitGPU< ShapeSphere >("IntegratorHPMCMonoImplicitGPUSphere"); export_IntegratorHPMCMonoImplicitGPU< ShapeUnion<ShapeSphere> >("IntegratorHPMCMonoImplicitGPUSphereUnion"); export_IntegratorHPMCMonoImplicitGPU< ShapeConvexPolygon >("IntegratorHPMCMonoImplicitGPUConvexPolygon"); export_IntegratorHPMCMonoImplicitGPU< ShapeSimplePolygon >("IntegratorHPMCMonoImplicitGPUSimplePolygon"); export_IntegratorHPMCMonoImplicitGPU< ShapePolyhedron >("IntegratorHPMCMonoImplicitGPUPolyhedron"); export_IntegratorHPMCMonoImplicitGPU< ShapeConvexPolyhedron<8> >("IntegratorHPMCMonoImplicitGPUConvexPolyhedron8"); export_IntegratorHPMCMonoImplicitGPU< ShapeConvexPolyhedron<16> >("IntegratorHPMCMonoImplicitGPUConvexPolyhedron16"); export_IntegratorHPMCMonoImplicitGPU< ShapeConvexPolyhedron<32> >("IntegratorHPMCMonoImplicitGPUConvexPolyhedron32"); export_IntegratorHPMCMonoImplicitGPU< ShapeConvexPolyhedron<64> >("IntegratorHPMCMonoImplicitGPUConvexPolyhedron64"); export_IntegratorHPMCMonoImplicitGPU< ShapeConvexPolyhedron<128> >("IntegratorHPMCMonoImplicitGPUConvexPolyhedron128"); export_IntegratorHPMCMonoImplicitGPU< ShapeSpheropolyhedron<8> >("IntegratorHPMCMonoImplicitGPUSpheropolyhedron8"); export_IntegratorHPMCMonoImplicitGPU< ShapeSpheropolyhedron<16> >("IntegratorHPMCMonoImplicitGPUSpheropolyhedron16"); export_IntegratorHPMCMonoImplicitGPU< ShapeSpheropolyhedron<32> >("IntegratorHPMCMonoImplicitGPUSpheropolyhedron32"); export_IntegratorHPMCMonoImplicitGPU< ShapeSpheropolyhedron<64> >("IntegratorHPMCMonoImplicitGPUSpheropolyhedron64"); export_IntegratorHPMCMonoImplicitGPU< ShapeSpheropolyhedron<128> >("IntegratorHPMCMonoImplicitGPUSpheropolyhedron128"); export_IntegratorHPMCMonoImplicitGPU< ShapeEllipsoid>("IntegratorHPMCMonoImplicitGPUEllipsoid"); export_IntegratorHPMCMonoImplicitGPU< ShapeSpheropolygon>("IntegratorHPMCMonoImplicitGPUSpheropolygon"); export_IntegratorHPMCMonoImplicitGPU< ShapeFacetedSphere>("IntegratorHPMCMonoImplicitGPUFacetedSphere"); #ifdef ENABLE_SPHINX_GPU export_IntegratorHPMCMonoImplicitGPU< ShapeSphinx >("IntegratorHPMCMonoImplicitGPUSphinx"); #endif #endif } } <|endoftext|>
<commit_before>/* * Thread.cpp 15.08.2006 (mueller) * * Copyright (C) 2006 by Universitaet Stuttgart (VIS). Alle Rechte vorbehalten. */ #include "vislib/Thread.h" #ifndef _WIN32 #include <unistd.h> #endif /* !_WIN32 */ #include "vislib/assert.h" #include "vislib/error.h" #include "vislib/IllegalParamException.h" #include "vislib/IllegalStateException.h" #include "vislib/SystemException.h" #include "vislib/Trace.h" #include "vislib/UnsupportedOperationException.h" #include "DynamicFunctionPointer.h" #include <cstdio> #include <iostream> #ifndef _WIN32 /** * Return code that marks a thread as still running. Make sure that the value * is the same as on Windows. */ #define STILL_ACTIVE (259) #endif /* !_WIN32 */ /* * vislib::sys::Thread::Sleep */ void vislib::sys::Thread::Sleep(const DWORD millis) { #ifdef _WIN32 ::Sleep(millis); #else /* _WIN32 */ if (millis >= 1000) { /* At least one second to sleep. Use ::sleep() for full seconds. */ ::sleep(millis / 1000); } ::usleep((millis % 1000) * 1000); #endif /* _WIN32 */ } /* * vislib::sys::Thread::Reschedule */ void vislib::sys::Thread::Reschedule(void) { #ifdef _WIN32 #if (_WIN32_WINNT >= 0x0400) ::SwitchToThread(); #else DynamicFunctionPointer<BOOL (*)(void)> stt("kernel32", "SwitchToThread"); if (stt.IsValid()) { stt(); } else { ::Sleep(0); } #endif #else /* _WIN32 */ if (::sched_yield() != 0) { throw SystemException(__FILE__, __LINE__); } #endif /* _WIN32 */ } /* * vislib::sys::Thread::Thread */ vislib::sys::Thread::Thread(Runnable *runnable) : id(0), runnable(runnable), runnableFunc(NULL) { #ifdef _WIN32 this->handle = NULL; #else /* _WIN32 */ ::pthread_attr_init(&this->attribs); ::pthread_attr_setscope(&this->attribs, PTHREAD_SCOPE_SYSTEM); ::pthread_attr_setdetachstate(&this->attribs, PTHREAD_CREATE_JOINABLE); this->exitCode = 0; #endif /* _WIN32 */ this->threadFuncParam.thread = this; this->threadFuncParam.userData = NULL; } /* * vislib::sys::Thread::Thread */ vislib::sys::Thread::Thread(Runnable::Function runnableFunc) : id(0), runnable(NULL), runnableFunc(runnableFunc) { #ifdef _WIN32 this->handle = NULL; #else /* _WIN32 */ ::pthread_attr_init(&this->attribs); ::pthread_attr_setscope(&this->attribs, PTHREAD_SCOPE_SYSTEM); ::pthread_attr_setdetachstate(&this->attribs, PTHREAD_CREATE_JOINABLE); this->exitCode = 0; #endif /* _WIN32 */ this->threadFuncParam.thread = this; this->threadFuncParam.userData = NULL; } /* * vislib::sys::Thread::~Thread */ vislib::sys::Thread::~Thread(void) { #ifdef _WIN32 if (this->handle != NULL) { ::CloseHandle(this->handle); } #else /* _WIIN32 */ // TODO: Dirty hack, don't know whether this is always working. if (this->id != 0) { ::pthread_detach(this->id); ::pthread_attr_destroy(&this->attribs); } #endif /* _WIN32 */ } /* * vislib::sys::Thread::GetExitCode */ DWORD vislib::sys::Thread::GetExitCode(void) const { #ifdef _WIN32 DWORD retval = 0; if (::GetExitCodeThread(this->handle, &retval) == FALSE) { throw SystemException(__FILE__, __LINE__); } return retval; #else /* _WIN32 */ return this->exitCode; #endif /* _WIN32 */ } /* * vislib::sys::Thread::IsRunning */ bool vislib::sys::Thread::IsRunning(void) const { try { return (this->GetExitCode() == STILL_ACTIVE); } catch (SystemException) { return false; } } /* * vislib::sys::Thread::Join */ void vislib::sys::Thread::Join(void) { #ifdef _WIN32 if (this->handle != NULL) { if (::WaitForSingleObject(this->handle, INFINITE) == WAIT_FAILED) { throw SystemException(__FILE__, __LINE__); } } #else /* _WIN32 */ if (this->id != 0) { if (::pthread_join(this->id, NULL) != 0) { throw SystemException(__FILE__, __LINE__); } } #endif /* _WIN32 */ } /* * vislib::sys::Thread::Start */ bool vislib::sys::Thread::Start(void *userData) { if (this->IsRunning()) { /* * The thread must not be started twice at the same time as this would * leave unclosed handles. */ return false; } /* Set the user data. */ this->threadFuncParam.userData = userData; #ifdef _WIN32 /* Close possible old handle. */ if (this->handle != NULL) { ::CloseHandle(this->handle); } if ((this->handle = ::CreateThread(NULL, 0, Thread::ThreadFunc, &this->threadFuncParam, 0, &this->id)) != NULL) { return true; } else { VLTRACE(Trace::LEVEL_VL_ERROR, "CreateThread() failed with error %d.\n", ::GetLastError()); throw SystemException(__FILE__, __LINE__); } #else /* _WIN32 */ if (::pthread_create(&this->id, &this->attribs, Thread::ThreadFunc, static_cast<void *>(&this->threadFuncParam)) == 0) { this->exitCode = STILL_ACTIVE; // Mark thread as running. return true; } else { VLTRACE(Trace::LEVEL_VL_ERROR, "pthread_create() failed with error %d.\n", ::GetLastError()); throw SystemException(__FILE__, __LINE__); } #endif /* _WIN32 */ } /* * vislib::sys::Thread::Terminate */ bool vislib::sys::Thread::Terminate(const bool forceTerminate, const int exitCode) { ASSERT(exitCode != STILL_ACTIVE); // User should never set this. if (forceTerminate) { /* Force immediate termination of the thread. */ #ifdef _WIN32 if (::TerminateThread(this->handle, exitCode) == FALSE) { VLTRACE(Trace::LEVEL_VL_ERROR, "TerminateThread() failed with error " "%d.\n", ::GetLastError()); throw SystemException(__FILE__, __LINE__); } return true; #else /* _WIN32 */ this->exitCode = exitCode; if (::pthread_cancel(this->id) != 0) { VLTRACE(Trace::LEVEL_VL_ERROR, "pthread_cancel() failed with error " "%d.\n", ::GetLastError()); throw SystemException(__FILE__, __LINE__); } return true; #endif /* _WIN32 */ } else { return this->TryTerminate(true); } /* end if (forceTerminate) */ } /* * vislib::sys::Thread::TryTerminate */ bool vislib::sys::Thread::TryTerminate(const bool doWait) { if (this->runnable == NULL) { throw IllegalStateException("TryTerminate can only be used, if the " "thread is using a Runnable.", __FILE__, __LINE__); } ASSERT(this->runnable != NULL); if (this->runnable->Terminate()) { /* * Wait for thread to finish, if Runnable acknowledged and waiting was * requested. */ if (doWait) { this->Join(); } return true; } else { /* Runnable did not acknowledge. */ return false; } } #ifndef _WIN32 /* * vislib::sys::Thread::CleanupFunc */ void vislib::sys::Thread::CleanupFunc(void *param) { ASSERT(param != NULL); Thread *t = static_cast<Thread *>(param); /* * In case the thread has still an exit code of STILL_ACTIVE, set a new one * to mark the thread as finished. */ if (t->exitCode == STILL_ACTIVE) { VLTRACE(Trace::LEVEL_VL_WARN, "CleanupFunc called with exit code " "STILL_ACTIVE"); t->exitCode = 0; } } #endif /* !_WIN32 */ /* * vislib::sys::Thread::ThreadFunc */ #ifdef _WIN32 DWORD WINAPI vislib::sys::Thread::ThreadFunc(void *param) { #else /* _WIN32 */ void *vislib::sys::Thread::ThreadFunc(void *param) { #endif /* _WIN32 */ ASSERT(param != NULL); int retval = 0; ThreadFuncParam *tfp = static_cast<ThreadFuncParam *>(param); Thread *t = tfp->thread; ASSERT(t != NULL); #ifndef _WIN32 pthread_cleanup_push(Thread::CleanupFunc, t); #endif /* !_WIN32 */ if (t->runnable != NULL) { retval = t->runnable->Run(tfp->userData); } else { ASSERT(t->runnableFunc != NULL); retval = t->runnableFunc(tfp->userData); } ASSERT(retval != STILL_ACTIVE); // Thread should never use STILL_ACTIVE! #ifndef _WIN32 t->exitCode = retval; pthread_cleanup_pop(1); #endif /* !_WIN32 */ VLTRACE(Trace::LEVEL_VL_INFO, "Thread [%u] has exited with code %d (0x%x).\n", t->id, retval, retval); #ifdef _WIN32 return static_cast<DWORD>(retval); #else /* _WIN32 */ return reinterpret_cast<void *>(retval); #endif /* _WIN32 */ } /* * vislib::sys::Thread::Thread */ vislib::sys::Thread::Thread(const Thread& rhs) { throw UnsupportedOperationException("vislib::sys::Thread::Thread", __FILE__, __LINE__); } /* * vislib::sys::Thread::operator = */ vislib::sys::Thread& vislib::sys::Thread::operator =(const Thread& rhs) { if (this != &rhs) { throw IllegalParamException("rhs_", __FILE__, __LINE__); } return *this; } <commit_msg>Added an additional test to Thread::IsRunning to fix a weird behavior.<commit_after>/* * Thread.cpp 15.08.2006 (mueller) * * Copyright (C) 2006 by Universitaet Stuttgart (VIS). Alle Rechte vorbehalten. */ #include "vislib/Thread.h" #ifndef _WIN32 #include <unistd.h> #endif /* !_WIN32 */ #include "vislib/assert.h" #include "vislib/error.h" #include "vislib/IllegalParamException.h" #include "vislib/IllegalStateException.h" #include "vislib/SystemException.h" #include "vislib/Trace.h" #include "vislib/UnsupportedOperationException.h" #include "DynamicFunctionPointer.h" #include <cstdio> #include <iostream> #ifndef _WIN32 /** * Return code that marks a thread as still running. Make sure that the value * is the same as on Windows. */ #define STILL_ACTIVE (259) #endif /* !_WIN32 */ /* * vislib::sys::Thread::Sleep */ void vislib::sys::Thread::Sleep(const DWORD millis) { #ifdef _WIN32 ::Sleep(millis); #else /* _WIN32 */ if (millis >= 1000) { /* At least one second to sleep. Use ::sleep() for full seconds. */ ::sleep(millis / 1000); } ::usleep((millis % 1000) * 1000); #endif /* _WIN32 */ } /* * vislib::sys::Thread::Reschedule */ void vislib::sys::Thread::Reschedule(void) { #ifdef _WIN32 #if (_WIN32_WINNT >= 0x0400) ::SwitchToThread(); #else DynamicFunctionPointer<BOOL (*)(void)> stt("kernel32", "SwitchToThread"); if (stt.IsValid()) { stt(); } else { ::Sleep(0); } #endif #else /* _WIN32 */ if (::sched_yield() != 0) { throw SystemException(__FILE__, __LINE__); } #endif /* _WIN32 */ } /* * vislib::sys::Thread::Thread */ vislib::sys::Thread::Thread(Runnable *runnable) : id(0), runnable(runnable), runnableFunc(NULL) { #ifdef _WIN32 this->handle = NULL; #else /* _WIN32 */ ::pthread_attr_init(&this->attribs); ::pthread_attr_setscope(&this->attribs, PTHREAD_SCOPE_SYSTEM); ::pthread_attr_setdetachstate(&this->attribs, PTHREAD_CREATE_JOINABLE); this->exitCode = 0; #endif /* _WIN32 */ this->threadFuncParam.thread = this; this->threadFuncParam.userData = NULL; } /* * vislib::sys::Thread::Thread */ vislib::sys::Thread::Thread(Runnable::Function runnableFunc) : id(0), runnable(NULL), runnableFunc(runnableFunc) { #ifdef _WIN32 this->handle = NULL; #else /* _WIN32 */ ::pthread_attr_init(&this->attribs); ::pthread_attr_setscope(&this->attribs, PTHREAD_SCOPE_SYSTEM); ::pthread_attr_setdetachstate(&this->attribs, PTHREAD_CREATE_JOINABLE); this->exitCode = 0; #endif /* _WIN32 */ this->threadFuncParam.thread = this; this->threadFuncParam.userData = NULL; } /* * vislib::sys::Thread::~Thread */ vislib::sys::Thread::~Thread(void) { #ifdef _WIN32 if (this->handle != NULL) { ::CloseHandle(this->handle); } #else /* _WIIN32 */ // TODO: Dirty hack, don't know whether this is always working. if (this->id != 0) { ::pthread_detach(this->id); ::pthread_attr_destroy(&this->attribs); } #endif /* _WIN32 */ } /* * vislib::sys::Thread::GetExitCode */ DWORD vislib::sys::Thread::GetExitCode(void) const { #ifdef _WIN32 DWORD retval = 0; if (::GetExitCodeThread(this->handle, &retval) == FALSE) { throw SystemException(__FILE__, __LINE__); } return retval; #else /* _WIN32 */ return this->exitCode; #endif /* _WIN32 */ } /* * vislib::sys::Thread::IsRunning */ bool vislib::sys::Thread::IsRunning(void) const { try { return ((this->handle != NULL) && (this->GetExitCode() == STILL_ACTIVE)); } catch (SystemException) { return false; } } /* * vislib::sys::Thread::Join */ void vislib::sys::Thread::Join(void) { #ifdef _WIN32 if (this->handle != NULL) { if (::WaitForSingleObject(this->handle, INFINITE) == WAIT_FAILED) { throw SystemException(__FILE__, __LINE__); } } #else /* _WIN32 */ if (this->id != 0) { if (::pthread_join(this->id, NULL) != 0) { throw SystemException(__FILE__, __LINE__); } } #endif /* _WIN32 */ } /* * vislib::sys::Thread::Start */ bool vislib::sys::Thread::Start(void *userData) { if (this->IsRunning()) { /* * The thread must not be started twice at the same time as this would * leave unclosed handles. */ return false; } /* Set the user data. */ this->threadFuncParam.userData = userData; #ifdef _WIN32 /* Close possible old handle. */ if (this->handle != NULL) { ::CloseHandle(this->handle); } if ((this->handle = ::CreateThread(NULL, 0, Thread::ThreadFunc, &this->threadFuncParam, 0, &this->id)) != NULL) { return true; } else { VLTRACE(Trace::LEVEL_VL_ERROR, "CreateThread() failed with error %d.\n", ::GetLastError()); throw SystemException(__FILE__, __LINE__); } #else /* _WIN32 */ if (::pthread_create(&this->id, &this->attribs, Thread::ThreadFunc, static_cast<void *>(&this->threadFuncParam)) == 0) { this->exitCode = STILL_ACTIVE; // Mark thread as running. return true; } else { VLTRACE(Trace::LEVEL_VL_ERROR, "pthread_create() failed with error %d.\n", ::GetLastError()); throw SystemException(__FILE__, __LINE__); } #endif /* _WIN32 */ } /* * vislib::sys::Thread::Terminate */ bool vislib::sys::Thread::Terminate(const bool forceTerminate, const int exitCode) { ASSERT(exitCode != STILL_ACTIVE); // User should never set this. if (forceTerminate) { /* Force immediate termination of the thread. */ #ifdef _WIN32 if (::TerminateThread(this->handle, exitCode) == FALSE) { VLTRACE(Trace::LEVEL_VL_ERROR, "TerminateThread() failed with error " "%d.\n", ::GetLastError()); throw SystemException(__FILE__, __LINE__); } return true; #else /* _WIN32 */ this->exitCode = exitCode; if (::pthread_cancel(this->id) != 0) { VLTRACE(Trace::LEVEL_VL_ERROR, "pthread_cancel() failed with error " "%d.\n", ::GetLastError()); throw SystemException(__FILE__, __LINE__); } return true; #endif /* _WIN32 */ } else { return this->TryTerminate(true); } /* end if (forceTerminate) */ } /* * vislib::sys::Thread::TryTerminate */ bool vislib::sys::Thread::TryTerminate(const bool doWait) { if (this->runnable == NULL) { throw IllegalStateException("TryTerminate can only be used, if the " "thread is using a Runnable.", __FILE__, __LINE__); } ASSERT(this->runnable != NULL); if (this->runnable->Terminate()) { /* * Wait for thread to finish, if Runnable acknowledged and waiting was * requested. */ if (doWait) { this->Join(); } return true; } else { /* Runnable did not acknowledge. */ return false; } } #ifndef _WIN32 /* * vislib::sys::Thread::CleanupFunc */ void vislib::sys::Thread::CleanupFunc(void *param) { ASSERT(param != NULL); Thread *t = static_cast<Thread *>(param); /* * In case the thread has still an exit code of STILL_ACTIVE, set a new one * to mark the thread as finished. */ if (t->exitCode == STILL_ACTIVE) { VLTRACE(Trace::LEVEL_VL_WARN, "CleanupFunc called with exit code " "STILL_ACTIVE"); t->exitCode = 0; } } #endif /* !_WIN32 */ /* * vislib::sys::Thread::ThreadFunc */ #ifdef _WIN32 DWORD WINAPI vislib::sys::Thread::ThreadFunc(void *param) { #else /* _WIN32 */ void *vislib::sys::Thread::ThreadFunc(void *param) { #endif /* _WIN32 */ ASSERT(param != NULL); int retval = 0; ThreadFuncParam *tfp = static_cast<ThreadFuncParam *>(param); Thread *t = tfp->thread; ASSERT(t != NULL); #ifndef _WIN32 pthread_cleanup_push(Thread::CleanupFunc, t); #endif /* !_WIN32 */ if (t->runnable != NULL) { retval = t->runnable->Run(tfp->userData); } else { ASSERT(t->runnableFunc != NULL); retval = t->runnableFunc(tfp->userData); } ASSERT(retval != STILL_ACTIVE); // Thread should never use STILL_ACTIVE! #ifndef _WIN32 t->exitCode = retval; pthread_cleanup_pop(1); #endif /* !_WIN32 */ VLTRACE(Trace::LEVEL_VL_INFO, "Thread [%u] has exited with code %d (0x%x).\n", t->id, retval, retval); #ifdef _WIN32 return static_cast<DWORD>(retval); #else /* _WIN32 */ return reinterpret_cast<void *>(retval); #endif /* _WIN32 */ } /* * vislib::sys::Thread::Thread */ vislib::sys::Thread::Thread(const Thread& rhs) { throw UnsupportedOperationException("vislib::sys::Thread::Thread", __FILE__, __LINE__); } /* * vislib::sys::Thread::operator = */ vislib::sys::Thread& vislib::sys::Thread::operator =(const Thread& rhs) { if (this != &rhs) { throw IllegalParamException("rhs_", __FILE__, __LINE__); } return *this; } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2014, Esteban Tovagliari. 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 Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "boost/lexical_cast.hpp" #include "renderer/api/color.h" #include "IECore/MessageHandler.h" #include "IECore/SimpleTypedData.h" #include "IECoreAppleseed/private/AppleseedUtil.h" using namespace IECore; using namespace std; namespace asf = foundation; namespace asr = renderer; string IECoreAppleseed::dataToString( ConstDataPtr value ) { stringstream ss; switch( value->typeId() ) { case IntDataTypeId : { int x = static_cast<const IntData*>( value.get() )->readable(); ss << x; } break; case FloatDataTypeId : { float x = static_cast<const FloatData*>( value.get() )->readable(); ss << x; } break; case StringDataTypeId : { const string &x = static_cast<const StringData*>( value.get() )->readable(); ss << x; } break; case V2iDataTypeId : { const Imath::V2i &x = static_cast<const V2iData*>( value.get() )->readable(); ss << x.x << ", " << x.y; } break; case Color3fDataTypeId : { const Imath::Color3f &x = static_cast<const Color3fData*>( value.get() )->readable(); ss << x.x << ", " << x.y << ", " << x.z; } break; case BoolDataTypeId : { bool x = static_cast<const BoolData*>( value.get() )->readable(); ss << x; } break; default: break; } return ss.str(); } void IECoreAppleseed::setParam( const string &name, const Data *value, asr::ParamArray &params ) { switch( value->typeId() ) { case IntDataTypeId : { int x = static_cast<const IntData*>( value )->readable(); params.insert( name, x ); } break; case FloatDataTypeId : { float x = static_cast<const FloatData*>( value )->readable(); params.insert( name, x ); } break; case StringDataTypeId : { const string &x = static_cast<const StringData*>( value )->readable(); params.insert( name, x.c_str() ); } break; case BoolDataTypeId : { bool x = static_cast<const BoolData*>( value )->readable(); params.insert( name, x ); } break; default: // TODO: some kind of warning would be nice here... break; } } asr::ParamArray IECoreAppleseed::convertParams( const CompoundDataMap &parameters ) { asr::ParamArray result; for( CompoundDataMap::const_iterator it=parameters.begin(); it!=parameters.end(); ++it ) setParam( it->first.value(), it->second.get(), result ); return result; } string IECoreAppleseed::createColorEntity( asr::ColorContainer &colorContainer, const Imath::C3f &color, const string &name ) { // for monochrome colors, we don't need to create a color entity at all. if( color.x == color.y && color.x == color.z ) { return boost::lexical_cast<string>( color.x ); } asr::ColorValueArray values( 3, &color.x ); asr::ParamArray params; params.insert( "color_space", "linear_rgb" ); asf::auto_release_ptr<asr::ColorEntity> c = asr::ColorEntityFactory::create( name.c_str(), params, values ); return insertEntityWithUniqueName( colorContainer, c, name.c_str() ); } namespace { string doCreateTextureEntity( asr::TextureContainer &textureContainer, asr::TextureInstanceContainer &textureInstanceContainer, const asf::SearchPaths &searchPaths, const string &textureName, const string &fileName, const asr::ParamArray &txInstanceParams ) { asr::ParamArray params; params.insert( "filename", fileName.c_str() ); params.insert( "color_space", "linear_rgb" ); asf::auto_release_ptr<asr::Texture> texture( asr::DiskTexture2dFactory().create( textureName.c_str(), params, searchPaths ) ); string txName = IECoreAppleseed::insertEntityWithUniqueName( textureContainer, texture, textureName ); string textureInstanceName = txName + "_instance"; asf::auto_release_ptr<asr::TextureInstance> textureInstance( asr::TextureInstanceFactory().create( textureInstanceName.c_str(), txInstanceParams, txName.c_str() ) ); return IECoreAppleseed::insertEntityWithUniqueName( textureInstanceContainer, textureInstance, textureInstanceName.c_str() ); } } string IECoreAppleseed::createTextureEntity( asr::TextureContainer &textureContainer, asr::TextureInstanceContainer &textureInstanceContainer, const asf::SearchPaths &searchPaths, const string &textureName, const string &fileName ) { return doCreateTextureEntity( textureContainer, textureInstanceContainer, searchPaths, textureName, fileName, asr::ParamArray() ); } string IECoreAppleseed::createAlphaMapTextureEntity( asr::TextureContainer &textureContainer, asr::TextureInstanceContainer &textureInstanceContainer, const asf::SearchPaths &searchPaths, const string &textureName, const string &fileName ) { asr::ParamArray params; params.insert( "alpha_mode", "detect" ); return doCreateTextureEntity( textureContainer, textureInstanceContainer, searchPaths, textureName, fileName, params ); } <commit_msg>Removed namespace qualifiers. Added some warnings.<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2014, Esteban Tovagliari. 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 Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "boost/lexical_cast.hpp" #include "renderer/api/color.h" #include "IECore/MessageHandler.h" #include "IECore/SimpleTypedData.h" #include "IECoreAppleseed/private/AppleseedUtil.h" using namespace IECore; using namespace Imath; using namespace boost; using namespace std; namespace asf = foundation; namespace asr = renderer; string IECoreAppleseed::dataToString( ConstDataPtr value ) { stringstream ss; switch( value->typeId() ) { case IntDataTypeId : { int x = static_cast<const IntData*>( value.get() )->readable(); ss << x; } break; case FloatDataTypeId : { float x = static_cast<const FloatData*>( value.get() )->readable(); ss << x; } break; case StringDataTypeId : { const string &x = static_cast<const StringData*>( value.get() )->readable(); ss << x; } break; case V2iDataTypeId : { const V2i &x = static_cast<const V2iData*>( value.get() )->readable(); ss << x.x << ", " << x.y; } break; case Color3fDataTypeId : { const Color3f &x = static_cast<const Color3fData*>( value.get() )->readable(); ss << x.x << ", " << x.y << ", " << x.z; } break; case BoolDataTypeId : { bool x = static_cast<const BoolData*>( value.get() )->readable(); ss << x; } break; default: msg( MessageHandler::Warning, "IECoreAppleseed::dataToString", format( "Unknown data typeid \"%s\"." ) % value->typeName() ); break; } return ss.str(); } void IECoreAppleseed::setParam( const string &name, const Data *value, asr::ParamArray &params ) { switch( value->typeId() ) { case IntDataTypeId : { int x = static_cast<const IntData*>( value )->readable(); params.insert( name, x ); } break; case FloatDataTypeId : { float x = static_cast<const FloatData*>( value )->readable(); params.insert( name, x ); } break; case StringDataTypeId : { const string &x = static_cast<const StringData*>( value )->readable(); params.insert( name, x.c_str() ); } break; case BoolDataTypeId : { bool x = static_cast<const BoolData*>( value )->readable(); params.insert( name, x ); } break; default: msg( MessageHandler::Warning, "IECoreAppleseed::setParam", format( "Unknown data typeid \"%s\"." ) % value->typeName() ); break; } } asr::ParamArray IECoreAppleseed::convertParams( const CompoundDataMap &parameters ) { asr::ParamArray result; for( CompoundDataMap::const_iterator it=parameters.begin(); it!=parameters.end(); ++it ) setParam( it->first.value(), it->second.get(), result ); return result; } string IECoreAppleseed::createColorEntity( asr::ColorContainer &colorContainer, const C3f &color, const string &name ) { // for monochrome colors, we don't need to create a color entity at all. if( color.x == color.y && color.x == color.z ) { return lexical_cast<string>( color.x ); } asr::ColorValueArray values( 3, &color.x ); asr::ParamArray params; params.insert( "color_space", "linear_rgb" ); asf::auto_release_ptr<asr::ColorEntity> c = asr::ColorEntityFactory::create( name.c_str(), params, values ); return insertEntityWithUniqueName( colorContainer, c, name.c_str() ); } namespace { string doCreateTextureEntity( asr::TextureContainer &textureContainer, asr::TextureInstanceContainer &textureInstanceContainer, const asf::SearchPaths &searchPaths, const string &textureName, const string &fileName, const asr::ParamArray &txInstanceParams ) { asr::ParamArray params; params.insert( "filename", fileName.c_str() ); params.insert( "color_space", "linear_rgb" ); asf::auto_release_ptr<asr::Texture> texture( asr::DiskTexture2dFactory().create( textureName.c_str(), params, searchPaths ) ); string txName = IECoreAppleseed::insertEntityWithUniqueName( textureContainer, texture, textureName ); string textureInstanceName = txName + "_instance"; asf::auto_release_ptr<asr::TextureInstance> textureInstance( asr::TextureInstanceFactory().create( textureInstanceName.c_str(), txInstanceParams, txName.c_str() ) ); return IECoreAppleseed::insertEntityWithUniqueName( textureInstanceContainer, textureInstance, textureInstanceName.c_str() ); } } string IECoreAppleseed::createTextureEntity( asr::TextureContainer &textureContainer, asr::TextureInstanceContainer &textureInstanceContainer, const asf::SearchPaths &searchPaths, const string &textureName, const string &fileName ) { return doCreateTextureEntity( textureContainer, textureInstanceContainer, searchPaths, textureName, fileName, asr::ParamArray() ); } string IECoreAppleseed::createAlphaMapTextureEntity( asr::TextureContainer &textureContainer, asr::TextureInstanceContainer &textureInstanceContainer, const asf::SearchPaths &searchPaths, const string &textureName, const string &fileName ) { asr::ParamArray params; params.insert( "alpha_mode", "detect" ); return doCreateTextureEntity( textureContainer, textureInstanceContainer, searchPaths, textureName, fileName, params ); } <|endoftext|>
<commit_before>/* * * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <node.h> #include "grpc/grpc.h" #include "grpc/grpc_security.h" #include "grpc/support/log.h" #include "server_credentials.h" namespace grpc { namespace node { using Nan::Callback; using Nan::EscapableHandleScope; using Nan::HandleScope; using Nan::Maybe; using Nan::MaybeLocal; using Nan::ObjectWrap; using Nan::Persistent; using Nan::Utf8String; using v8::Array; using v8::Exception; using v8::External; using v8::Function; using v8::FunctionTemplate; using v8::Integer; using v8::Local; using v8::Object; using v8::ObjectTemplate; using v8::String; using v8::Value; Nan::Callback *ServerCredentials::constructor; Persistent<FunctionTemplate> ServerCredentials::fun_tpl; ServerCredentials::ServerCredentials(grpc_server_credentials *credentials) : wrapped_credentials(credentials) {} ServerCredentials::~ServerCredentials() { grpc_server_credentials_release(wrapped_credentials); } void ServerCredentials::Init(Local<Object> exports) { Nan::HandleScope scope; Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New); tpl->SetClassName(Nan::New("ServerCredentials").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Local<Function> ctr = tpl->GetFunction(); Nan::Set(ctr, Nan::New("createSsl").ToLocalChecked(), Nan::GetFunction( Nan::New<FunctionTemplate>(CreateSsl)).ToLocalChecked()); Nan::Set(ctr, Nan::New("createInsecure").ToLocalChecked(), Nan::GetFunction( Nan::New<FunctionTemplate>(CreateInsecure)).ToLocalChecked()); fun_tpl.Reset(tpl); constructor = new Nan::Callback(ctr); Nan::Set(exports, Nan::New("ServerCredentials").ToLocalChecked(), ctr); } bool ServerCredentials::HasInstance(Local<Value> val) { Nan::HandleScope scope; return Nan::New(fun_tpl)->HasInstance(val); } Local<Value> ServerCredentials::WrapStruct( grpc_server_credentials *credentials) { Nan::EscapableHandleScope scope; const int argc = 1; Local<Value> argv[argc] = { Nan::New<External>(reinterpret_cast<void *>(credentials))}; MaybeLocal<Object> maybe_instance = Nan::NewInstance( constructor->GetFunction(), argc, argv); if (maybe_instance.IsEmpty()) { return scope.Escape(Nan::Null()); } else { return scope.Escape(maybe_instance.ToLocalChecked()); } } grpc_server_credentials *ServerCredentials::GetWrappedServerCredentials() { return wrapped_credentials; } NAN_METHOD(ServerCredentials::New) { if (info.IsConstructCall()) { if (!info[0]->IsExternal()) { return Nan::ThrowTypeError( "ServerCredentials can only be created with the provided functions"); } Local<External> ext = info[0].As<External>(); grpc_server_credentials *creds_value = reinterpret_cast<grpc_server_credentials *>(ext->Value()); ServerCredentials *credentials = new ServerCredentials(creds_value); credentials->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } else { // This should never be called directly return Nan::ThrowTypeError( "ServerCredentials can only be created with the provided functions"); } } NAN_METHOD(ServerCredentials::CreateSsl) { Nan::HandleScope scope; char *root_certs = NULL; if (::node::Buffer::HasInstance(info[0])) { root_certs = ::node::Buffer::Data(info[0]); } else if (!(info[0]->IsNull() || info[0]->IsUndefined())) { return Nan::ThrowTypeError( "createSSl's first argument must be a Buffer if provided"); } if (!info[1]->IsArray()) { return Nan::ThrowTypeError( "createSsl's second argument must be a list of objects"); } int force_client_auth = 0; if (info[2]->IsBoolean()) { force_client_auth = (int)Nan::To<bool>(info[2]).FromJust(); } else if (!(info[2]->IsUndefined() || info[2]->IsNull())) { return Nan::ThrowTypeError( "createSsl's third argument must be a boolean if provided"); } Local<Array> pair_list = Local<Array>::Cast(info[1]); uint32_t key_cert_pair_count = pair_list->Length(); grpc_ssl_pem_key_cert_pair *key_cert_pairs = new grpc_ssl_pem_key_cert_pair[ key_cert_pair_count]; Local<String> key_key = Nan::New("private_key").ToLocalChecked(); Local<String> cert_key = Nan::New("cert_chain").ToLocalChecked(); for(uint32_t i = 0; i < key_cert_pair_count; i++) { Local<Value> pair_val = Nan::Get(pair_list, i).ToLocalChecked(); if (!pair_val->IsObject()) { delete key_cert_pairs; return Nan::ThrowTypeError("Key/cert pairs must be objects"); } Local<Object> pair_obj = Nan::To<Object>(pair_val).ToLocalChecked(); Local<Value> maybe_key = Nan::Get(pair_obj, key_key).ToLocalChecked(); Local<Value> maybe_cert = Nan::Get(pair_obj, cert_key).ToLocalChecked(); if (!::node::Buffer::HasInstance(maybe_key)) { delete key_cert_pairs; return Nan::ThrowTypeError("private_key must be a Buffer"); } if (!::node::Buffer::HasInstance(maybe_cert)) { delete key_cert_pairs; return Nan::ThrowTypeError("cert_chain must be a Buffer"); } key_cert_pairs[i].private_key = ::node::Buffer::Data(maybe_key); key_cert_pairs[i].cert_chain = ::node::Buffer::Data(maybe_cert); } grpc_server_credentials *creds = grpc_ssl_server_credentials_create( root_certs, key_cert_pairs, key_cert_pair_count, force_client_auth, NULL); delete key_cert_pairs; if (creds == NULL) { info.GetReturnValue().SetNull(); } else { info.GetReturnValue().Set(WrapStruct(creds)); } } NAN_METHOD(ServerCredentials::CreateInsecure) { info.GetReturnValue().Set(WrapStruct(NULL)); } } // namespace node } // namespace grpc <commit_msg>Add various options to verify ssl/tls client cert including letting the application handle the authentication.<commit_after>/* * * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <node.h> #include "grpc/grpc.h" #include "grpc/grpc_security.h" #include "grpc/support/log.h" #include "server_credentials.h" namespace grpc { namespace node { using Nan::Callback; using Nan::EscapableHandleScope; using Nan::HandleScope; using Nan::Maybe; using Nan::MaybeLocal; using Nan::ObjectWrap; using Nan::Persistent; using Nan::Utf8String; using v8::Array; using v8::Exception; using v8::External; using v8::Function; using v8::FunctionTemplate; using v8::Integer; using v8::Local; using v8::Object; using v8::ObjectTemplate; using v8::String; using v8::Value; Nan::Callback *ServerCredentials::constructor; Persistent<FunctionTemplate> ServerCredentials::fun_tpl; ServerCredentials::ServerCredentials(grpc_server_credentials *credentials) : wrapped_credentials(credentials) {} ServerCredentials::~ServerCredentials() { grpc_server_credentials_release(wrapped_credentials); } void ServerCredentials::Init(Local<Object> exports) { Nan::HandleScope scope; Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New); tpl->SetClassName(Nan::New("ServerCredentials").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Local<Function> ctr = tpl->GetFunction(); Nan::Set(ctr, Nan::New("createSsl").ToLocalChecked(), Nan::GetFunction( Nan::New<FunctionTemplate>(CreateSsl)).ToLocalChecked()); Nan::Set(ctr, Nan::New("createInsecure").ToLocalChecked(), Nan::GetFunction( Nan::New<FunctionTemplate>(CreateInsecure)).ToLocalChecked()); fun_tpl.Reset(tpl); constructor = new Nan::Callback(ctr); Nan::Set(exports, Nan::New("ServerCredentials").ToLocalChecked(), ctr); } bool ServerCredentials::HasInstance(Local<Value> val) { Nan::HandleScope scope; return Nan::New(fun_tpl)->HasInstance(val); } Local<Value> ServerCredentials::WrapStruct( grpc_server_credentials *credentials) { Nan::EscapableHandleScope scope; const int argc = 1; Local<Value> argv[argc] = { Nan::New<External>(reinterpret_cast<void *>(credentials))}; MaybeLocal<Object> maybe_instance = Nan::NewInstance( constructor->GetFunction(), argc, argv); if (maybe_instance.IsEmpty()) { return scope.Escape(Nan::Null()); } else { return scope.Escape(maybe_instance.ToLocalChecked()); } } grpc_server_credentials *ServerCredentials::GetWrappedServerCredentials() { return wrapped_credentials; } NAN_METHOD(ServerCredentials::New) { if (info.IsConstructCall()) { if (!info[0]->IsExternal()) { return Nan::ThrowTypeError( "ServerCredentials can only be created with the provided functions"); } Local<External> ext = info[0].As<External>(); grpc_server_credentials *creds_value = reinterpret_cast<grpc_server_credentials *>(ext->Value()); ServerCredentials *credentials = new ServerCredentials(creds_value); credentials->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } else { // This should never be called directly return Nan::ThrowTypeError( "ServerCredentials can only be created with the provided functions"); } } NAN_METHOD(ServerCredentials::CreateSsl) { Nan::HandleScope scope; char *root_certs = NULL; if (::node::Buffer::HasInstance(info[0])) { root_certs = ::node::Buffer::Data(info[0]); } else if (!(info[0]->IsNull() || info[0]->IsUndefined())) { return Nan::ThrowTypeError( "createSSl's first argument must be a Buffer if provided"); } if (!info[1]->IsArray()) { return Nan::ThrowTypeError( "createSsl's second argument must be a list of objects"); } grpc_ssl_client_certificate_request_type client_certificate_request; if (info[2]->IsBoolean()) { client_certificate_request = Nan::To<bool>(info[2]).FromJust() ? GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY : GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE; } else if (!(info[2]->IsUndefined() || info[2]->IsNull())) { return Nan::ThrowTypeError( "createSsl's third argument must be a boolean if provided"); } Local<Array> pair_list = Local<Array>::Cast(info[1]); uint32_t key_cert_pair_count = pair_list->Length(); grpc_ssl_pem_key_cert_pair *key_cert_pairs = new grpc_ssl_pem_key_cert_pair[ key_cert_pair_count]; Local<String> key_key = Nan::New("private_key").ToLocalChecked(); Local<String> cert_key = Nan::New("cert_chain").ToLocalChecked(); for(uint32_t i = 0; i < key_cert_pair_count; i++) { Local<Value> pair_val = Nan::Get(pair_list, i).ToLocalChecked(); if (!pair_val->IsObject()) { delete key_cert_pairs; return Nan::ThrowTypeError("Key/cert pairs must be objects"); } Local<Object> pair_obj = Nan::To<Object>(pair_val).ToLocalChecked(); Local<Value> maybe_key = Nan::Get(pair_obj, key_key).ToLocalChecked(); Local<Value> maybe_cert = Nan::Get(pair_obj, cert_key).ToLocalChecked(); if (!::node::Buffer::HasInstance(maybe_key)) { delete key_cert_pairs; return Nan::ThrowTypeError("private_key must be a Buffer"); } if (!::node::Buffer::HasInstance(maybe_cert)) { delete key_cert_pairs; return Nan::ThrowTypeError("cert_chain must be a Buffer"); } key_cert_pairs[i].private_key = ::node::Buffer::Data(maybe_key); key_cert_pairs[i].cert_chain = ::node::Buffer::Data(maybe_cert); } grpc_server_credentials *creds = grpc_ssl_server_credentials_create_ex( root_certs, key_cert_pairs, key_cert_pair_count, client_certificate_request, NULL); delete key_cert_pairs; if (creds == NULL) { info.GetReturnValue().SetNull(); } else { info.GetReturnValue().Set(WrapStruct(creds)); } } NAN_METHOD(ServerCredentials::CreateInsecure) { info.GetReturnValue().Set(WrapStruct(NULL)); } } // namespace node } // namespace grpc <|endoftext|>
<commit_before>#pragma once #include "../traits.hpp" #include "fft2d.pb.h" #include <thrust/device_vector.h> namespace cujak { namespace fft2d { inline int calc_stride(int Ny) { return Ny / 2 + 1; } template <typename Container> class wrapper_base { protected: const int Nx, Ny, stride, N; Container &u; wrapper_base(int Nx_, int Ny_, int stride_, int N_, Container &u_) : Nx(Nx_), Ny(Ny_), stride(stride_), N(N_), u(u_) {} public: typedef typename Container::value_type value_type; pb::Property property; value_type *get() const { return u.data().get(); } Container &data() const { return u; } value_type operator()(int i, int j) const { if (i >= 0) { return u[stride * i + j]; } else { return u[stride * (Nx + i) + j]; } } void set(int i, int j, value_type v) { if (i >= 0) { u[stride * i + j] = v; } else { u[stride * (Nx + i) + j] = v; } } int size_x() const { return Nx; } int size_y() const { return Ny; } int size() const { return N; } int get_stride() const { return stride; } }; template <typename Float> class Field_wrapper : public wrapper_base<rdVector<Float> > { public: typedef rdVector<Float> Container; Field_wrapper(int Nx, int Ny, Container &u) : wrapper_base<Container>(Nx, Ny, Ny, Nx * Ny, u) {} virtual ~Field_wrapper() = default; }; template <typename Float> class Coefficient_wrapper : public wrapper_base<cdVector<Float> > { public: typedef cdVector<Float> Container; Coefficient_wrapper(int Nx, int Ny, Container &u) : wrapper_base<Container>(Nx, Ny, calc_stride(Ny), Nx * calc_stride(Ny), u) {} virtual ~Coefficient_wrapper() = default; }; template <typename Float> class Field : public Field_wrapper<Float> { typename Field_wrapper<Float>::Container data_; public: Field(int Nx, int Ny) : data_(Nx * Ny), Field_wrapper<Float>(Nx, Ny, data_) {} }; template <typename Float> class Coefficient : public Coefficient_wrapper<Float> { typename Coefficient<Float>::Container data_; public: Coefficient(int Nx, int Ny) : data_(Nx * calc_stride(Ny)), Coefficient_wrapper<Float>(Nx, Ny, data_) { } }; } // namespace fft2d } // namespace Kolmogorov2D <commit_msg>Add begin/end<commit_after>#pragma once #include "../traits.hpp" #include "fft2d.pb.h" #include <thrust/device_vector.h> namespace cujak { namespace fft2d { inline int calc_stride(int Ny) { return Ny / 2 + 1; } template <typename Container> class wrapper_base { protected: const int Nx, Ny, stride, N; Container &u; wrapper_base(int Nx_, int Ny_, int stride_, int N_, Container &u_) : Nx(Nx_), Ny(Ny_), stride(stride_), N(N_), u(u_) {} public: typedef typename Container::value_type value_type; typedef decltype(u.begin()) iterator; pb::Property property; value_type *get() const { return u.data().get(); } Container &data() const { return u; } iterator begin() const { return u.begin(); } iterator end() const { return u.end(); } value_type operator()(int i, int j) const { if (i >= 0) { return u[stride * i + j]; } else { return u[stride * (Nx + i) + j]; } } void set(int i, int j, value_type v) { if (i >= 0) { u[stride * i + j] = v; } else { u[stride * (Nx + i) + j] = v; } } int size_x() const { return Nx; } int size_y() const { return Ny; } int size() const { return N; } int get_stride() const { return stride; } }; template <typename Float> class Field_wrapper : public wrapper_base<rdVector<Float> > { public: typedef rdVector<Float> Container; Field_wrapper(int Nx, int Ny, Container &u) : wrapper_base<Container>(Nx, Ny, Ny, Nx * Ny, u) {} virtual ~Field_wrapper() = default; }; template <typename Float> class Coefficient_wrapper : public wrapper_base<cdVector<Float> > { public: typedef cdVector<Float> Container; Coefficient_wrapper(int Nx, int Ny, Container &u) : wrapper_base<Container>(Nx, Ny, calc_stride(Ny), Nx * calc_stride(Ny), u) {} virtual ~Coefficient_wrapper() = default; }; template <typename Float> class Field : public Field_wrapper<Float> { typename Field_wrapper<Float>::Container data_; public: Field(int Nx, int Ny) : data_(Nx * Ny), Field_wrapper<Float>(Nx, Ny, data_) {} }; template <typename Float> class Coefficient : public Coefficient_wrapper<Float> { typename Coefficient<Float>::Container data_; public: Coefficient(int Nx, int Ny) : data_(Nx * calc_stride(Ny)), Coefficient_wrapper<Float>(Nx, Ny, data_) { } }; } // namespace fft2d } // namespace Kolmogorov2D <|endoftext|>
<commit_before>// The MIT License (MIT) // Copyright (c) 2015 nabijaczleweli // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #ifndef HASHABLE_HPP #define HASHABLE_HPP #include <functional> namespace cpponfiguration { // T must publicly interhit hashable<T>, as in `class foo : public hashable<foo> {};` template <class T> class hashable { friend std::hash<hashable<T>>; protected: virtual size_t hash_code() const = 0; inline virtual ~hashable() noexcept = default; }; } namespace cpponfig = cpponfiguration; namespace std { template <class T> struct hash<cpponfig::hashable<T>> { inline size_t operator()(const cpponfig::hashable<T> & tohash) const { return tohash.hash_code(); } }; template <class T> struct hash : std::hash<cpponfig::hashable<T>> {}; } #endif // HASHABLE_HPP <commit_msg>Revert "Explicitly specify the namespace"<commit_after>// The MIT License (MIT) // Copyright (c) 2015 nabijaczleweli // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #ifndef HASHABLE_HPP #define HASHABLE_HPP #include <functional> namespace cpponfiguration { // T must publicly interhit hashable<T>, as in `class foo : public hashable<foo> {};` template <class T> class hashable { friend std::hash<hashable<T>>; protected: virtual size_t hash_code() const = 0; inline virtual ~hashable() noexcept = default; }; } namespace cpponfig = cpponfiguration; namespace std { template <class T> struct hash<cpponfig::hashable<T>> { inline size_t operator()(const cpponfig::hashable<T> & tohash) const { return tohash.hash_code(); } }; template <class T> struct hash : hash<cpponfig::hashable<T>> {}; } #endif // HASHABLE_HPP <|endoftext|>
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp: /* The MIT License Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or http://flusspferd.org/contributors.txt) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FLUSSPFERD_CREATE_HPP #define FLUSSPFERD_CREATE_HPP #ifndef PREPROC_DEBUG #include "object.hpp" #include "function.hpp" #include "native_function.hpp" #include "local_root_scope.hpp" #include <boost/type_traits/is_function.hpp> #include <boost/utility/enable_if.hpp> #include <boost/mpl/bool.hpp> #include <boost/range.hpp> #include <boost/parameter/parameters.hpp> #include <boost/parameter/keyword.hpp> #include <boost/parameter/name.hpp> #include <boost/parameter/binding.hpp> #include <boost/type_traits.hpp> #endif #include "detail/limit.hpp" #include <boost/preprocessor.hpp> #include <boost/parameter/config.hpp> namespace flusspferd { class native_object_base; class function; class native_function_base; /** * @name Creating functions * @addtogroup create_function */ //@{ /** * Create a new native function. * * @p ptr will be <code>delete</code>d by Flusspferd. * * @param ptr The native function object. * @return The new function. */ function create_native_function(native_function_base *ptr); /** * Create a new native function as method of an object. * * The new method of object @p o will have the name @c ptr->name(). * * @param o The object to add the method to. * @param ptr The native function object. * @return The new method. */ function create_native_function(object const &o, native_function_base *ptr); #ifndef IN_DOXYGEN #define FLUSSPFERD_FN_CREATE_NATIVE_FUNCTION(z, n_args, d) \ template< \ typename T \ BOOST_PP_ENUM_TRAILING_PARAMS(n_args, typename T) \ > \ object old_create_native_functor_function( \ object const &o \ BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(n_args, T, const & param), \ typename boost::enable_if_c<!boost::is_function<T>::value>::type * = 0 \ ) { \ return create_native_function(o, new T(BOOST_PP_ENUM_PARAMS(n_args, param))); \ } \ /* */ BOOST_PP_REPEAT( BOOST_PP_INC(FLUSSPFERD_PARAM_LIMIT), FLUSSPFERD_FN_CREATE_NATIVE_FUNCTION, ~ ) #else /** * Create a new native function of type @p F as method of an object. * * @p F must inherit from #native_function_base. * * The new method of object @p o will have the name @c ptr->name(). * * @param F The functor type. * @param o The object to add the method to. * @param ... The parameters to pass to the constructor of @p F. * @return The new method. */ template<typename F> object create_native_functor_function(object const &o, ...); #endif /** * Create a new native method of an object. * * @param o The object to add the method to. * @param name The method name. * @param fn The functor to call. * @param arity The function arity. * @return The new function. */ inline function create_native_function( object const &o, std::string const &name, boost::function<void (call_context &)> const &fn, unsigned arity = 0) { return old_create_native_functor_function<native_function<void> >( o, fn, arity, name); } /** * Create a new native method of an object. * * @param T The function signature to use. * @param o The object to add the method to. * @param name The function name. * @param fn The functor to call. * @return The new function. */ template<typename T> function create_native_function( object const &o, std::string const &name, boost::function<T> const &fn) { return old_create_native_functor_function<native_function<T,false> >(o, fn, name); } /** * Create a new native method of an object. * * The first parameter passed will be 'this'. * * @param T The function signature to use. * @param o The object to add the method to. * @param name The function name. * @param fn The functor to call. * @return The new function. */ template<typename T> function create_native_method( object const &o, std::string const &name, boost::function<T> const &fn) { return old_create_native_functor_function<native_function<T,true> >(o, fn, name); } /** * Create a new native method of an object. * * @param o The object to add the method to. * @param name The method name. * @param fnptr The function to call (also determines the function signature). * @return The new method. */ template<typename T> function create_native_function( object const &o, std::string const &name, T *fnptr, typename boost::enable_if_c<boost::is_function<T>::value>::type* =0) { return create_native_function<T>(o, name, boost::function<T>(fnptr)); } /** * Create a new native method of an object. * * The first parameter passed will be 'this'. * * @param o The object to add the method to. * @param name The method name. * @param fnptr The function to call (also determines the function signature). * @return The new method. */ template<typename T> function create_native_method( object const &o, std::string const &name, T *fnptr, typename boost::enable_if_c<boost::is_function<T>::value>::type* =0) { return create_native_method<T>(o, name, boost::function<T>(fnptr)); } /** * Create a new native method of an object. * * @param o The object to add the method to. * @param name The method name. * @param memfnptr The member function to call. * @return The new function. */ template<typename T> function create_native_method( object const &o, std::string const &name, void (T::*memfnptr)(call_context &), unsigned arity = 0) { return old_create_native_functor_function<native_member_function<void, T> >( o, memfnptr, arity, name); } /** * Create a new native method of an object. * * @param o The object to add the method to. * @param name The method name. * @param memfnptr The member function to call (also determines the function * signature). * @return The new function. */ template<typename R, typename T> function create_native_method( object const &o, std::string const &name, R T::*memfnptr) { return old_create_native_functor_function<native_member_function<R, T> >( o, memfnptr, name); } //@} namespace param { BOOST_PARAMETER_NAME(container) BOOST_PARAMETER_NAME(name) BOOST_PARAMETER_NAME(attributes) BOOST_PARAMETER_NAME(length) BOOST_PARAMETER_NAME(contents) BOOST_PARAMETER_NAME(prototype) BOOST_PARAMETER_NAME(parent) BOOST_PARAMETER_NAME(argument_names) BOOST_PARAMETER_NAME(source) BOOST_PARAMETER_NAME(file) BOOST_PARAMETER_NAME(line) BOOST_PARAMETER_NAME(arguments) } namespace detail { template<typename Class> struct new_functor { template<typename> struct result { typedef Class &type; }; Class &operator()() { return *new Class; } #define FLUSSPFERD_NEW_FUNCTOR_INVOKE(z, n, d) \ template< \ BOOST_PP_ENUM_PARAMS(n, typename T) \ > \ Class &operator()( \ BOOST_PP_ENUM_BINARY_PARAMS(n, T, &x) \ ) \ { \ return *new Class(BOOST_PP_ENUM_PARAMS(n, x)); \ } \ /* */ BOOST_PP_REPEAT_FROM_TO( 1, BOOST_PP_INC(FLUSSPFERD_PARAM_LIMIT), FLUSSPFERD_NEW_FUNCTOR_INVOKE, ~) #undef FLUSSPFERD_NEW_FUNCTOR_INVOKE }; template<typename Class, typename Cond = void> struct create_traits; typedef param::tag::container container_spec; typedef param::tag::name name_spec; typedef param::tag::attributes attributes_spec; template<typename Class, typename ArgPack> typename boost::enable_if< boost::is_same< typename boost::parameter::binding< ArgPack, param::tag::container, void >::type, void >, typename create_traits<Class>::result_type >::type create_helper(ArgPack const &arg) { return create_traits<Class>::create(arg); } template<typename Class, typename ArgPack> typename boost::disable_if< boost::is_same< typename boost::parameter::binding< ArgPack, param::tag::container, void >::type, void >, typename create_traits<Class>::result_type >::type create_helper(ArgPack const &arg) { typedef create_traits<Class> traits; local_root_scope scope; typename traits::result_type result = traits::create(arg); object container(arg[param::_container]); container.define_property( arg[param::_name], result, arg[param::_attributes | dont_enumerate]); return result; } } template<typename Class> typename detail::create_traits<Class>::result_type create() { return detail::create_traits<Class>::create(); } #define FLUSSPFERD_CREATE(z, n, d) \ template< \ typename Class, \ BOOST_PP_ENUM_PARAMS(n, typename T) \ > \ typename detail::create_traits<Class>::result_type \ create( \ BOOST_PP_ENUM_BINARY_PARAMS(n, T, const &x), \ typename detail::create_traits<Class>::parameters::template match<T0>::type kw = typename detail::create_traits<Class>::parameters()) \ { \ typedef detail::create_traits<Class> traits; \ return detail::create_helper<Class>(kw(BOOST_PP_ENUM_PARAMS(n, x))); \ } \ /* */ BOOST_PP_REPEAT_FROM_TO( 1, BOOST_PP_INC(BOOST_PARAMETER_MAX_ARITY), FLUSSPFERD_CREATE, ~) #undef FLUSSPFERD_CREATE } #endif <commit_msg>new_create: add flusspferd::param::type<T> for passing types to flusspferd::create()<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp: /* The MIT License Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or http://flusspferd.org/contributors.txt) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FLUSSPFERD_CREATE_HPP #define FLUSSPFERD_CREATE_HPP #ifndef PREPROC_DEBUG #include "object.hpp" #include "function.hpp" #include "native_function.hpp" #include "local_root_scope.hpp" #include <boost/type_traits/is_function.hpp> #include <boost/utility/enable_if.hpp> #include <boost/mpl/bool.hpp> #include <boost/range.hpp> #include <boost/parameter/parameters.hpp> #include <boost/parameter/keyword.hpp> #include <boost/parameter/name.hpp> #include <boost/parameter/binding.hpp> #include <boost/type_traits.hpp> #endif #include "detail/limit.hpp" #include <boost/preprocessor.hpp> #include <boost/parameter/config.hpp> namespace flusspferd { class native_object_base; class function; class native_function_base; /** * @name Creating functions * @addtogroup create_function */ //@{ /** * Create a new native function. * * @p ptr will be <code>delete</code>d by Flusspferd. * * @param ptr The native function object. * @return The new function. */ function create_native_function(native_function_base *ptr); /** * Create a new native function as method of an object. * * The new method of object @p o will have the name @c ptr->name(). * * @param o The object to add the method to. * @param ptr The native function object. * @return The new method. */ function create_native_function(object const &o, native_function_base *ptr); #ifndef IN_DOXYGEN #define FLUSSPFERD_FN_CREATE_NATIVE_FUNCTION(z, n_args, d) \ template< \ typename T \ BOOST_PP_ENUM_TRAILING_PARAMS(n_args, typename T) \ > \ object old_create_native_functor_function( \ object const &o \ BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(n_args, T, const & param), \ typename boost::enable_if_c<!boost::is_function<T>::value>::type * = 0 \ ) { \ return create_native_function(o, new T(BOOST_PP_ENUM_PARAMS(n_args, param))); \ } \ /* */ BOOST_PP_REPEAT( BOOST_PP_INC(FLUSSPFERD_PARAM_LIMIT), FLUSSPFERD_FN_CREATE_NATIVE_FUNCTION, ~ ) #else /** * Create a new native function of type @p F as method of an object. * * @p F must inherit from #native_function_base. * * The new method of object @p o will have the name @c ptr->name(). * * @param F The functor type. * @param o The object to add the method to. * @param ... The parameters to pass to the constructor of @p F. * @return The new method. */ template<typename F> object create_native_functor_function(object const &o, ...); #endif /** * Create a new native method of an object. * * @param o The object to add the method to. * @param name The method name. * @param fn The functor to call. * @param arity The function arity. * @return The new function. */ inline function create_native_function( object const &o, std::string const &name, boost::function<void (call_context &)> const &fn, unsigned arity = 0) { return old_create_native_functor_function<native_function<void> >( o, fn, arity, name); } /** * Create a new native method of an object. * * @param T The function signature to use. * @param o The object to add the method to. * @param name The function name. * @param fn The functor to call. * @return The new function. */ template<typename T> function create_native_function( object const &o, std::string const &name, boost::function<T> const &fn) { return old_create_native_functor_function<native_function<T,false> >(o, fn, name); } /** * Create a new native method of an object. * * The first parameter passed will be 'this'. * * @param T The function signature to use. * @param o The object to add the method to. * @param name The function name. * @param fn The functor to call. * @return The new function. */ template<typename T> function create_native_method( object const &o, std::string const &name, boost::function<T> const &fn) { return old_create_native_functor_function<native_function<T,true> >(o, fn, name); } /** * Create a new native method of an object. * * @param o The object to add the method to. * @param name The method name. * @param fnptr The function to call (also determines the function signature). * @return The new method. */ template<typename T> function create_native_function( object const &o, std::string const &name, T *fnptr, typename boost::enable_if_c<boost::is_function<T>::value>::type* =0) { return create_native_function<T>(o, name, boost::function<T>(fnptr)); } /** * Create a new native method of an object. * * The first parameter passed will be 'this'. * * @param o The object to add the method to. * @param name The method name. * @param fnptr The function to call (also determines the function signature). * @return The new method. */ template<typename T> function create_native_method( object const &o, std::string const &name, T *fnptr, typename boost::enable_if_c<boost::is_function<T>::value>::type* =0) { return create_native_method<T>(o, name, boost::function<T>(fnptr)); } /** * Create a new native method of an object. * * @param o The object to add the method to. * @param name The method name. * @param memfnptr The member function to call. * @return The new function. */ template<typename T> function create_native_method( object const &o, std::string const &name, void (T::*memfnptr)(call_context &), unsigned arity = 0) { return old_create_native_functor_function<native_member_function<void, T> >( o, memfnptr, arity, name); } /** * Create a new native method of an object. * * @param o The object to add the method to. * @param name The method name. * @param memfnptr The member function to call (also determines the function * signature). * @return The new function. */ template<typename R, typename T> function create_native_method( object const &o, std::string const &name, R T::*memfnptr) { return old_create_native_functor_function<native_member_function<R, T> >( o, memfnptr, name); } //@} namespace param { BOOST_PARAMETER_NAME(container) BOOST_PARAMETER_NAME(name) BOOST_PARAMETER_NAME(attributes) BOOST_PARAMETER_NAME(length) BOOST_PARAMETER_NAME(contents) BOOST_PARAMETER_NAME(prototype) BOOST_PARAMETER_NAME(parent) BOOST_PARAMETER_NAME(argument_names) BOOST_PARAMETER_NAME(source) BOOST_PARAMETER_NAME(file) BOOST_PARAMETER_NAME(line) BOOST_PARAMETER_NAME(arguments) /* For passing types. Like this: _param = param::type<int>() */ template<typename T> struct type {}; } namespace detail { template<typename Class> struct new_functor { template<typename> struct result { typedef Class &type; }; Class &operator()() { return *new Class; } #define FLUSSPFERD_NEW_FUNCTOR_INVOKE(z, n, d) \ template< \ BOOST_PP_ENUM_PARAMS(n, typename T) \ > \ Class &operator()( \ BOOST_PP_ENUM_BINARY_PARAMS(n, T, &x) \ ) \ { \ return *new Class(BOOST_PP_ENUM_PARAMS(n, x)); \ } \ /* */ BOOST_PP_REPEAT_FROM_TO( 1, BOOST_PP_INC(FLUSSPFERD_PARAM_LIMIT), FLUSSPFERD_NEW_FUNCTOR_INVOKE, ~) #undef FLUSSPFERD_NEW_FUNCTOR_INVOKE }; template<typename Class, typename Cond = void> struct create_traits; typedef param::tag::container container_spec; typedef param::tag::name name_spec; typedef param::tag::attributes attributes_spec; template<typename Class, typename ArgPack> typename boost::enable_if< boost::is_same< typename boost::parameter::binding< ArgPack, param::tag::container, void >::type, void >, typename create_traits<Class>::result_type >::type create_helper(ArgPack const &arg) { return create_traits<Class>::create(arg); } template<typename Class, typename ArgPack> typename boost::disable_if< boost::is_same< typename boost::parameter::binding< ArgPack, param::tag::container, void >::type, void >, typename create_traits<Class>::result_type >::type create_helper(ArgPack const &arg) { typedef create_traits<Class> traits; local_root_scope scope; typename traits::result_type result = traits::create(arg); object container(arg[param::_container]); container.define_property( arg[param::_name], result, arg[param::_attributes | dont_enumerate]); return result; } } template<typename Class> typename detail::create_traits<Class>::result_type create() { return detail::create_traits<Class>::create(); } #define FLUSSPFERD_CREATE(z, n, d) \ template< \ typename Class, \ BOOST_PP_ENUM_PARAMS(n, typename T) \ > \ typename detail::create_traits<Class>::result_type \ create( \ BOOST_PP_ENUM_BINARY_PARAMS(n, T, const &x), \ typename detail::create_traits<Class>::parameters::template match<T0>::type kw = typename detail::create_traits<Class>::parameters()) \ { \ typedef detail::create_traits<Class> traits; \ return detail::create_helper<Class>(kw(BOOST_PP_ENUM_PARAMS(n, x))); \ } \ /* */ BOOST_PP_REPEAT_FROM_TO( 1, BOOST_PP_INC(BOOST_PARAMETER_MAX_ARITY), FLUSSPFERD_CREATE, ~) #undef FLUSSPFERD_CREATE } #endif <|endoftext|>
<commit_before>#ifndef UTILS_LOG_HPP #define UTILS_LOG_HPP #include <iostream> // Older versions of Visual Studio fail compiling this file. #ifdef DISABLE_LOGGING # define LOG(...) # define LOG_WARN(...) # define LOG_ERROR(...) # define LOG_DEBUG(...) # define LOG_DEBUG_WARN(...) # define LOG_DEBUG_ERROR(...) # define LOG_RAW(...) # define LOG_DEBUG_RAW(...) # define NLOGDEBUG #else #ifdef __linux__ # define LOG_WARNING_PREFIX "\033[1;33mWARNING: \033[0m" # define LOG_ERROR_PREFIX "\033[1;31mERROR: \033[0m" // # define LOG_DEBUG_PREFIX "\033[;35mDEBUG: \033[0m" #else # define LOG_WARNING_PREFIX "WARNING: " # define LOG_ERROR_PREFIX "ERROR: " // # define LOG_DEBUG_PREFIX "DEBUG: " #endif #define LOG_NORMAL_PREFIX "" #define LOG_DEBUG_PREFIX "DEBUG: " // Use like this: // int x = 5; // LOG("Some log entry"); // LOG("some variable: ", x); // LOG_WARN("Something is wrong: ", x, "!"); #define LOG(...) logutils::logfunc_init(__VA_ARGS__) #define LOG_WARN(...) logutils::logfunc_init<logutils::Warning>(__VA_ARGS__) #define LOG_ERROR(...) logutils::logfunc_init<logutils::Error, std::cerr>(__VA_ARGS__) // Same as above but without appending a new line character at the end #define LOG_RAW(...) logutils::logfunc_init<logutils::Normal, std::cout, false>(__VA_ARGS__) // Same as above but will only be displayed when NLOGDEBUG is NOT defined #ifndef NLOGDEBUG # define LOG_DEBUG(...) logutils::logfunc_init<logutils::Debug>(__VA_ARGS__) # define LOG_DEBUG_WARN(...) logutils::logfunc_init<logutils::DebugWarning>(__VA_ARGS__) # define LOG_DEBUG_ERROR(...) logutils::logfunc_init<logutils::DebugError, std::cerr>(__VA_ARGS__) # define LOG_DEBUG_RAW(...) logutils::logfunc_init<logutils::Debug, std::cout, false>(__VA_ARGS__) #else // No, no, Mr. Debug no here. # define LOG_DEBUG(...) # define LOG_DEBUG_WARN(...) # define LOG_DEBUG_ERROR(...) # define LOG_DEBUG_RAW(...) #endif // Use like this: // int x = 5; // LOG(LOG_DUMP(x)); #define LOG_DUMP(var) #var, ": ", (var) namespace logutils { enum LogLevel { Normal, Warning, Error, Debug, DebugWarning, DebugError }; template<std::ostream& stream, bool nl> void logfunc_join() { if (nl) stream<<"\n"; else stream.flush(); } template<std::ostream& stream, bool nl, class T, class... Args> void logfunc_join(const T& arg, const Args&... rest) { stream<<arg; logfunc_join<stream, nl>(rest...); } template<LogLevel level = Normal, std::ostream& stream = std::cout, bool nl = true, class... Args> void logfunc_init(const Args&... args) { switch (level) { case DebugWarning: case Warning: stream<<LOG_WARNING_PREFIX; break; case DebugError: case Error: stream<<LOG_ERROR_PREFIX; break; case Normal: default: stream<<LOG_NORMAL_PREFIX; break; } if (level >= 3) stream<<LOG_DEBUG_PREFIX; logfunc_join<stream, nl>(args...); } } #endif #endif <commit_msg>Add macro that expands __PRETTY_FUNCTION__ depending on platform<commit_after>#ifndef UTILS_LOG_HPP #define UTILS_LOG_HPP #include <iostream> // Older versions of Visual Studio fail compiling this file. #ifdef DISABLE_LOGGING # define LOG(...) # define LOG_WARN(...) # define LOG_ERROR(...) # define LOG_DEBUG(...) # define LOG_DEBUG_WARN(...) # define LOG_DEBUG_ERROR(...) # define LOG_RAW(...) # define LOG_DEBUG_RAW(...) # define NLOGDEBUG #else #ifdef __linux__ # define LOG_WARNING_PREFIX "\033[1;33mWARNING: \033[0m" # define LOG_ERROR_PREFIX "\033[1;31mERROR: \033[0m" // # define LOG_DEBUG_PREFIX "\033[;35mDEBUG: \033[0m" #else # define LOG_WARNING_PREFIX "WARNING: " # define LOG_ERROR_PREFIX "ERROR: " // # define LOG_DEBUG_PREFIX "DEBUG: " #endif #define LOG_NORMAL_PREFIX "" #define LOG_DEBUG_PREFIX "DEBUG: " #ifdef _WIN32 # define FUNC_STRING __FUNCSIG__ #else # define FUNC_STRING __PRETTY_FUNCTION__ #endif // Use like this: // int x = 5; // LOG("Some log entry"); // LOG("some variable: ", x); // LOG_WARN("Something is wrong: ", x, "!"); #define LOG(...) logutils::logfunc_init(__VA_ARGS__) #define LOG_WARN(...) logutils::logfunc_init<logutils::Warning>(__VA_ARGS__) #define LOG_ERROR(...) logutils::logfunc_init<logutils::Error, std::cerr>(__VA_ARGS__) // Same as above but without appending a new line character at the end #define LOG_RAW(...) logutils::logfunc_init<logutils::Normal, std::cout, false>(__VA_ARGS__) // Same as above but will only be displayed when NLOGDEBUG is NOT defined #ifndef NLOGDEBUG # define LOG_DEBUG(...) logutils::logfunc_init<logutils::Debug>(__VA_ARGS__) # define LOG_DEBUG_WARN(...) logutils::logfunc_init<logutils::DebugWarning>(__VA_ARGS__) # define LOG_DEBUG_ERROR(...) logutils::logfunc_init<logutils::DebugError, std::cerr>(__VA_ARGS__) # define LOG_DEBUG_RAW(...) logutils::logfunc_init<logutils::Debug, std::cout, false>(__VA_ARGS__) #else // No, no, Mr. Debug no here. # define LOG_DEBUG(...) # define LOG_DEBUG_WARN(...) # define LOG_DEBUG_ERROR(...) # define LOG_DEBUG_RAW(...) #endif // Use like this: // int x = 5; // LOG(LOG_DUMP(x)); #define LOG_DUMP(var) #var, ": ", (var) namespace logutils { enum LogLevel { Normal, Warning, Error, Debug, DebugWarning, DebugError }; template<std::ostream& stream, bool nl> void logfunc_join() { if (nl) stream<<"\n"; else stream.flush(); } template<std::ostream& stream, bool nl, class T, class... Args> void logfunc_join(const T& arg, const Args&... rest) { stream<<arg; logfunc_join<stream, nl>(rest...); } template<LogLevel level = Normal, std::ostream& stream = std::cout, bool nl = true, class... Args> void logfunc_init(const Args&... args) { switch (level) { case DebugWarning: case Warning: stream<<LOG_WARNING_PREFIX; break; case DebugError: case Error: stream<<LOG_ERROR_PREFIX; break; case Normal: default: stream<<LOG_NORMAL_PREFIX; break; } if (level >= 3) stream<<LOG_DEBUG_PREFIX; logfunc_join<stream, nl>(args...); } } #endif #endif <|endoftext|>
<commit_before>/* * Copyright (C) 2009, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ /** ** \file libport/select-ref.hh ** \brief Select between a non ref or a ref type. */ #ifndef LIBPORT_SELECT_REF_HH # define LIBPORT_SELECT_REF_HH # warn use libport/traits.hh instead. namespace libport { /*---------------. | ref addition. | `---------------*/ /// Return \a T&. template <typename T> struct ref_traits { typedef T& type; }; // Do not form reference to references template <typename T> struct ref_traits<T&> { typedef T& type; }; /*--------------. | ref removal. | `--------------*/ /// Return \a T without any reference. template <typename T> struct unref_traits { typedef T type; }; template <typename T> struct unref_traits<T&> { typedef T type; }; } //namespace libport #endif // !LIBPORT_SELECT_REF_HH <commit_msg>fix cpp directive.<commit_after>/* * Copyright (C) 2009, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ /** ** \file libport/select-ref.hh ** \brief Select between a non ref or a ref type. */ #ifndef LIBPORT_SELECT_REF_HH # define LIBPORT_SELECT_REF_HH # warning "use libport/traits.hh instead." namespace libport { /*---------------. | ref addition. | `---------------*/ /// Return \a T&. template <typename T> struct ref_traits { typedef T& type; }; // Do not form reference to references template <typename T> struct ref_traits<T&> { typedef T& type; }; /*--------------. | ref removal. | `--------------*/ /// Return \a T without any reference. template <typename T> struct unref_traits { typedef T type; }; template <typename T> struct unref_traits<T&> { typedef T type; }; } //namespace libport #endif // !LIBPORT_SELECT_REF_HH <|endoftext|>
<commit_before>/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_ALLOCA #include "libtorrent/config.hpp" #ifdef TORRENT_WINDOWS #include <malloc.h> #define TORRENT_ALLOCA(t, n) static_cast<t*>(_alloca(sizeof(t) * (n))) #else #include <alloca.h> #define TORRENT_ALLOCA(t, n) static_cast<t*>(alloca(sizeof(t) * (n))) #endif #endif <commit_msg>Possibly fixed not found alloca on FreeBSD.<commit_after>/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_ALLOCA #include "libtorrent/config.hpp" #ifdef TORRENT_WINDOWS #include <malloc.h> #define TORRENT_ALLOCA(t, n) static_cast<t*>(_alloca(sizeof(t) * (n))) #else #include <alloca.h> #include <stdlib.h> #define TORRENT_ALLOCA(t, n) static_cast<t*>(alloca(sizeof(t) * (n))) #endif #endif <|endoftext|>
<commit_before>/* Copyright (c) 2005, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_CONFIG_HPP_INCLUDED #define TORRENT_CONFIG_HPP_INCLUDED #include <boost/config.hpp> #include <boost/version.hpp> #include <stdio.h> // for snprintf #ifndef WIN32 #define __STDC_FORMAT_MACROS #include <inttypes.h> #endif #ifndef PRId64 #ifdef _WIN32 #define PRId64 "I64d" #else #define PRId64 "lld" #endif #endif #if defined(__GNUC__) && __GNUC__ >= 4 #define TORRENT_DEPRECATED __attribute__ ((deprecated)) # if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __attribute__ ((visibility("default"))) # else # define TORRENT_EXPORT # endif #elif defined(__GNUC__) # define TORRENT_EXPORT #elif defined(BOOST_MSVC) #pragma warning(disable: 4258) #pragma warning(disable: 4251) # if defined(TORRENT_BUILDING_SHARED) # define TORRENT_EXPORT __declspec(dllexport) # elif defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __declspec(dllimport) # else # define TORRENT_EXPORT # endif #else # define TORRENT_EXPORT #endif #ifndef TORRENT_DEPRECATED #define TORRENT_DEPRECATED #endif // set up defines for target environments #if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \ || defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \ || defined __FreeBSD_kernel__ #define TORRENT_BSD #elif defined __linux__ #define TORRENT_LINUX #elif defined __MINGW32__ #define TORRENT_MINGW #elif defined WIN32 #define TORRENT_WINDOWS #elif defined sun || defined __sun #define TORRENT_SOLARIS #else #warning unkown OS, assuming BSD #define TORRENT_BSD #endif #define TORRENT_USE_IPV6 1 #define TORRENT_USE_MLOCK 1 #define TORRENT_USE_READV 1 #define TORRENT_USE_WRITEV 1 #define TORRENT_USE_IOSTREAM 1 // should wpath or path be used? #if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY \ && BOOST_VERSION >= 103400 && !defined __APPLE__ #define TORRENT_USE_WPATH 1 #else #define TORRENT_USE_WPATH 0 #endif #ifdef TORRENT_WINDOWS #include <stdarg.h> // this is the maximum number of characters in a // path element / filename on windows #define NAME_MAX 255 inline int snprintf(char* buf, int len, char const* fmt, ...) { va_list lp; va_start(lp, fmt); return vsnprintf_s(buf, len, _TRUNCATE, fmt, lp); } #define strtoll _strtoi64 #else #include <limits.h> #endif #if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING) #define TORRENT_UPNP_LOGGING #endif #if !TORRENT_USE_WPATH && defined TORRENT_LINUX // libiconv presnce, not implemented yet #define TORRENT_USE_LOCALE_FILENAMES 1 #else #define TORRENT_USE_LOCALE_FILENAMES 0 #endif #if !defined(TORRENT_READ_HANDLER_MAX_SIZE) # define TORRENT_READ_HANDLER_MAX_SIZE 256 #endif #if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE) # define TORRENT_WRITE_HANDLER_MAX_SIZE 256 #endif // determine what timer implementation we can use #if defined(__MACH__) #define TORRENT_USE_ABSOLUTE_TIME 1 #elif defined(_WIN32) #define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1 #elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0 #define TORRENT_USE_CLOCK_GETTIME 1 #else #define TORRENT_USE_BOOST_DATE_TIME 1 #endif #endif // TORRENT_CONFIG_HPP_INCLUDED <commit_msg>attempt to make it build on windows<commit_after>/* Copyright (c) 2005, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_CONFIG_HPP_INCLUDED #define TORRENT_CONFIG_HPP_INCLUDED #include <boost/config.hpp> #include <boost/version.hpp> #include <stdio.h> // for snprintf #include <stdlib.h> // for _TRUNCATE (windows) #include <stdarg.h> #ifndef WIN32 #define __STDC_FORMAT_MACROS #include <inttypes.h> #endif #ifndef PRId64 #ifdef _WIN32 #define PRId64 "I64d" #else #define PRId64 "lld" #endif #endif #if defined(__GNUC__) && __GNUC__ >= 4 #define TORRENT_DEPRECATED __attribute__ ((deprecated)) # if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __attribute__ ((visibility("default"))) # else # define TORRENT_EXPORT # endif #elif defined(__GNUC__) # define TORRENT_EXPORT #elif defined(BOOST_MSVC) #pragma warning(disable: 4258) #pragma warning(disable: 4251) # if defined(TORRENT_BUILDING_SHARED) # define TORRENT_EXPORT __declspec(dllexport) # elif defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __declspec(dllimport) # else # define TORRENT_EXPORT # endif #else # define TORRENT_EXPORT #endif #ifndef TORRENT_DEPRECATED #define TORRENT_DEPRECATED #endif // set up defines for target environments #if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \ || defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \ || defined __FreeBSD_kernel__ #define TORRENT_BSD #elif defined __linux__ #define TORRENT_LINUX #elif defined __MINGW32__ #define TORRENT_MINGW #elif defined WIN32 #define TORRENT_WINDOWS #elif defined sun || defined __sun #define TORRENT_SOLARIS #else #warning unkown OS, assuming BSD #define TORRENT_BSD #endif #define TORRENT_USE_IPV6 1 #define TORRENT_USE_MLOCK 1 #define TORRENT_USE_READV 1 #define TORRENT_USE_WRITEV 1 #define TORRENT_USE_IOSTREAM 1 // should wpath or path be used? #if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY \ && BOOST_VERSION >= 103400 && !defined __APPLE__ #define TORRENT_USE_WPATH 1 #else #define TORRENT_USE_WPATH 0 #endif #ifdef TORRENT_WINDOWS #include <stdarg.h> // this is the maximum number of characters in a // path element / filename on windows #define NAME_MAX 255 inline int snprintf(char* buf, int len, char const* fmt, ...) { va_list lp; va_start(lp, fmt); return vsnprintf_s(buf, len, _TRUNCATE, fmt, lp); } #define strtoll _strtoi64 #else #include <limits.h> #endif #if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING) #define TORRENT_UPNP_LOGGING #endif #if !TORRENT_USE_WPATH && defined TORRENT_LINUX // libiconv presnce, not implemented yet #define TORRENT_USE_LOCALE_FILENAMES 1 #else #define TORRENT_USE_LOCALE_FILENAMES 0 #endif #if !defined(TORRENT_READ_HANDLER_MAX_SIZE) # define TORRENT_READ_HANDLER_MAX_SIZE 256 #endif #if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE) # define TORRENT_WRITE_HANDLER_MAX_SIZE 256 #endif // determine what timer implementation we can use #if defined(__MACH__) #define TORRENT_USE_ABSOLUTE_TIME 1 #elif defined(_WIN32) #define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1 #elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0 #define TORRENT_USE_CLOCK_GETTIME 1 #else #define TORRENT_USE_BOOST_DATE_TIME 1 #endif #endif // TORRENT_CONFIG_HPP_INCLUDED <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_IMAGE_NULL_HPP #define MAPNIK_IMAGE_NULL_HPP // mapnik #include <mapnik/config.hpp> #include <mapnik/pixel_types.hpp> //stl #include <stdexcept> namespace mapnik { template <> class MAPNIK_DECL image<null_t> { public: using pixel_type = null_t::type; static const image_dtype dtype = null_t::id; private: public: image() {} image(int /*width*/, int /*height*/, bool /*initialize*/ = true, bool /*premultiplied*/ = false, bool /*painted*/ = false) {} image(image<null_t> const&) {} image(image<null_t> &&) noexcept {} image<null_t>& operator=(image<null_t>) { return *this; } image<null_t>const& operator=(image<null_t> const& rhs) const { return rhs; } bool operator==(image<null_t> const&) const { return true; } bool operator<(image<null_t> const&) const { return false; } std::size_t width() const { return 0; } std::size_t height() const { return 0; } std::size_t size() const { return 0; } std::size_t row_size() const { return 0; } void set(pixel_type const&) { throw std::runtime_error("Can not set values for null image"); } pixel_type& operator() (std::size_t, std::size_t) { throw std::runtime_error("Can not get or set values for null image"); } pixel_type const& operator() (std::size_t, std::size_t) const { throw std::runtime_error("Can not get or set values for null image"); } unsigned const char* bytes() const { return nullptr; } unsigned char* bytes() {return nullptr; } double get_offset() const { return 0.0; } void set_offset(double) {} double get_scaling() const { return 1.0; } void set_scaling(double) {} bool get_premultiplied() const { return false; } void set_premultiplied(bool) {} void painted(bool) {} bool painted() const { return false; } image_dtype get_dtype() const { return dtype; } }; } // end ns mapnik #endif // MAPNIK_IMAGE_NULL_HPP <commit_msg>remove duplicate operator=<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_IMAGE_NULL_HPP #define MAPNIK_IMAGE_NULL_HPP // mapnik #include <mapnik/config.hpp> #include <mapnik/pixel_types.hpp> //stl #include <stdexcept> namespace mapnik { template <> class MAPNIK_DECL image<null_t> { public: using pixel_type = null_t::type; static const image_dtype dtype = null_t::id; private: public: image() {} image(int /*width*/, int /*height*/, bool /*initialize*/ = true, bool /*premultiplied*/ = false, bool /*painted*/ = false) {} image(image<null_t> const&) {} image(image<null_t> &&) noexcept {} image<null_t>& operator=(image<null_t>) { return *this; } bool operator==(image<null_t> const&) const { return true; } bool operator<(image<null_t> const&) const { return false; } std::size_t width() const { return 0; } std::size_t height() const { return 0; } std::size_t size() const { return 0; } std::size_t row_size() const { return 0; } void set(pixel_type const&) { throw std::runtime_error("Can not set values for null image"); } pixel_type& operator() (std::size_t, std::size_t) { throw std::runtime_error("Can not get or set values for null image"); } pixel_type const& operator() (std::size_t, std::size_t) const { throw std::runtime_error("Can not get or set values for null image"); } unsigned const char* bytes() const { return nullptr; } unsigned char* bytes() {return nullptr; } double get_offset() const { return 0.0; } void set_offset(double) {} double get_scaling() const { return 1.0; } void set_scaling(double) {} bool get_premultiplied() const { return false; } void set_premultiplied(bool) {} void painted(bool) {} bool painted() const { return false; } image_dtype get_dtype() const { return dtype; } }; } // end ns mapnik #endif // MAPNIK_IMAGE_NULL_HPP <|endoftext|>
<commit_before>#ifndef PROTOCOL_MESSAGES_HPP_ #define PROTOCOL_MESSAGES_HPP_ #include <cstdint> namespace protocol { namespace message { struct heartbeat_message_t { enum { ID = 0x00 }; std::uint8_t seq; } __attribute__((packed)); struct log_message_t { enum { ID = 0x01 }; uint32_t time; char data[100]; } __attribute__((packed)); struct attitude_message_t { enum { ID = 0x02 }; uint32_t time; float dcm[9]; } __attribute__((packed)); struct set_arm_state_message_t { enum { ID = 0x03 }; bool armed; } __attribute__((packed)); struct set_control_mode_message_t { enum { ID = 0x04 }; enum class ControlMode { MANUAL, OFFBOARD }; ControlMode mode; } __attribute__((packed)); struct offboard_attitude_control_message_t { enum { ID = 0x05 }; float roll; float pitch; float yaw; float throttle; uint16_t buttons; // Bitfield of buttons uint8_t mode; } __attribute__((packed)); struct motor_throttle_message_t { enum { ID = 0x06 }; uint32_t time; float throttles[4]; } __attribute__((packed)); struct sensor_calibration_request_message_t { enum { ID = 0x07 }; } __attribute__((packed)); struct sensor_calibration_response_message_t { enum { ID = 0x08 }; enum class SensorType { ACCEL, GYRO, MAG }; SensorType type; float offsets[3]; } __attribute__((packed)); struct location_message_t { enum { ID = 0x09 }; uint32_t time; float lat; float lon; float alt; } __attribute__((packed)); struct imu_message_t { enum { ID = 0x0a }; uint32_t time; float gyro[3]; float accel[3]; } __attribute__((packed)); struct system_message_t { enum { ID = 0x0b }; uint32_t time; uint8_t state; float motorDC; // TODO(yoos): Hack for esra test launch } __attribute__((packed)); inline std::uint16_t length(int id) { // TODO(kyle): sizeof(empty struct) is 1 in C++... switch(id) { case heartbeat_message_t::ID: return sizeof(heartbeat_message_t); case log_message_t::ID: return sizeof(log_message_t); case attitude_message_t::ID: return sizeof(attitude_message_t); case set_arm_state_message_t::ID: return sizeof(set_arm_state_message_t); case set_control_mode_message_t::ID: return sizeof(set_control_mode_message_t); case offboard_attitude_control_message_t::ID: return sizeof(offboard_attitude_control_message_t); case motor_throttle_message_t::ID: return sizeof(motor_throttle_message_t); case sensor_calibration_request_message_t::ID: return sizeof(sensor_calibration_request_message_t); case sensor_calibration_response_message_t::ID: return sizeof(sensor_calibration_response_message_t); case location_message_t::ID: return sizeof(location_message_t); case imu_message_t::ID: return sizeof(imu_message_t); case system_message_t::ID: return sizeof(system_message_t); } return 0; // TODO(kyle): Return something more meaningful? } } } #endif // MESSAGES_HPP_ <commit_msg>Add stream messages.<commit_after>#ifndef PROTOCOL_MESSAGES_HPP_ #define PROTOCOL_MESSAGES_HPP_ #include <cstdint> namespace protocol { namespace message { struct heartbeat_message_t { enum { ID = 0x00 }; std::uint8_t seq; } __attribute__((packed)); struct log_message_t { enum { ID = 0x01 }; uint32_t time; char data[100]; } __attribute__((packed)); struct attitude_message_t { enum { ID = 0x02 }; uint32_t time; float dcm[9]; } __attribute__((packed)); struct set_arm_state_message_t { enum { ID = 0x03 }; bool armed; } __attribute__((packed)); struct set_control_mode_message_t { enum { ID = 0x04 }; enum class ControlMode { MANUAL, OFFBOARD }; ControlMode mode; } __attribute__((packed)); struct offboard_attitude_control_message_t { enum { ID = 0x05 }; float roll; float pitch; float yaw; float throttle; uint16_t buttons; // Bitfield of buttons uint8_t mode; } __attribute__((packed)); struct motor_throttle_message_t { enum { ID = 0x06 }; uint32_t time; float throttles[4]; } __attribute__((packed)); struct sensor_calibration_request_message_t { enum { ID = 0x07 }; } __attribute__((packed)); struct sensor_calibration_response_message_t { enum { ID = 0x08 }; enum class SensorType { ACCEL, GYRO, MAG }; SensorType type; float offsets[3]; } __attribute__((packed)); struct location_message_t { enum { ID = 0x09 }; uint32_t time; float lat; float lon; float alt; } __attribute__((packed)); struct imu_message_t { enum { ID = 0x0a }; uint32_t time; float gyro[3]; // Gyroscope float accel[3]; // Accelerometer } __attribute__((packed)); struct system_message_t { enum { ID = 0x0b }; uint32_t time; uint8_t state; float motorDC; // TODO(yoos): Hack for esra test launch } __attribute__((packed)); struct raw_1000_message_t { enum { ID = 0x0c }; uint32_t time; float accel[3]; // Accelerometer float accelH[3]; // High-g accel float gyro[3]; // Gyroscope } __attribute__((packed)); struct raw_50_message_t { enum { ID = 0x0d }; uint32_t time; float bar; // Barometric pressure float temp; // Temperature float mag[3]; // Magnetometer } __attribute((packed)); struct raw_10_message_t { enum { ID = 0x0e }; uint32_t time; float lat; float lon; float utc; // UTC time } __attribute((packed)); inline std::uint16_t length(int id) { // TODO(kyle): sizeof(empty struct) is 1 in C++... switch(id) { case heartbeat_message_t::ID: return sizeof(heartbeat_message_t); case log_message_t::ID: return sizeof(log_message_t); case attitude_message_t::ID: return sizeof(attitude_message_t); case set_arm_state_message_t::ID: return sizeof(set_arm_state_message_t); case set_control_mode_message_t::ID: return sizeof(set_control_mode_message_t); case offboard_attitude_control_message_t::ID: return sizeof(offboard_attitude_control_message_t); case motor_throttle_message_t::ID: return sizeof(motor_throttle_message_t); case sensor_calibration_request_message_t::ID: return sizeof(sensor_calibration_request_message_t); case sensor_calibration_response_message_t::ID: return sizeof(sensor_calibration_response_message_t); case location_message_t::ID: return sizeof(location_message_t); case imu_message_t::ID: return sizeof(imu_message_t); case system_message_t::ID: return sizeof(system_message_t); case raw_1000_message_t::ID: return sizeof(raw_1000_message_t); case raw_50_message_t::ID: return sizeof(raw_50_message_t); case raw_10_message_t::ID: return sizeof(raw_10_message_t); } return 0; // TODO(kyle): Return something more meaningful? } } } #endif // MESSAGES_HPP_ <|endoftext|>
<commit_before>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright 2015 Cloudius Systems */ #pragma once #include <chrono> #include <seastar/util/std-compat.hh> #include <atomic> #include <functional> #include <seastar/core/future.hh> #include <seastar/core/timer-set.hh> #include <seastar/core/scheduling.hh> namespace seastar { using steady_clock_type = std::chrono::steady_clock; template <typename Clock = steady_clock_type> class timer { public: typedef typename Clock::time_point time_point; typedef typename Clock::duration duration; typedef Clock clock; private: using callback_t = noncopyable_function<void()>; boost::intrusive::list_member_hook<> _link; scheduling_group _sg; callback_t _callback; time_point _expiry; compat::optional<duration> _period; bool _armed = false; bool _queued = false; bool _expired = false; void readd_periodic(); void arm_state(time_point until, compat::optional<duration> period) { assert(!_armed); _period = period; _armed = true; _expired = false; _expiry = until; _queued = true; } public: timer() = default; timer(timer&& t) noexcept : _sg(t._sg), _callback(std::move(t._callback)), _expiry(std::move(t._expiry)), _period(std::move(t._period)), _armed(t._armed), _queued(t._queued), _expired(t._expired) { _link.swap_nodes(t._link); t._queued = false; t._armed = false; } timer(scheduling_group sg, callback_t&& callback) : _sg(sg), _callback{std::move(callback)} { } explicit timer(callback_t&& callback) : timer(current_scheduling_group(), std::move(callback)) { } ~timer(); void set_callback(scheduling_group sg, callback_t&& callback) { _sg = sg; _callback = std::move(callback); } void set_callback(callback_t&& callback) { set_callback(current_scheduling_group(), std::move(callback)); } void arm(time_point until, compat::optional<duration> period = {}); void rearm(time_point until, compat::optional<duration> period = {}) { if (_armed) { cancel(); } arm(until, period); } void arm(duration delta) { return arm(Clock::now() + delta); } void arm_periodic(duration delta) { arm(Clock::now() + delta, {delta}); } bool armed() const { return _armed; } bool cancel(); time_point get_timeout() { return _expiry; } friend class reactor; friend class timer_set<timer, &timer::_link>; }; extern template class timer<steady_clock_type>; } <commit_msg>timer: document<commit_after>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright 2015 Cloudius Systems */ #pragma once #include <chrono> #include <seastar/util/std-compat.hh> #include <atomic> #include <functional> #include <seastar/core/future.hh> #include <seastar/core/timer-set.hh> #include <seastar/core/scheduling.hh> /// \file /// \defgroup timers Timers /// /// Seastar provides timers that can be defined to run a callback at a certain /// time point in the future; timers are provided for \ref lowres_clock (10ms /// resolution, efficient), for std::chrono::steady_clock (accurate but less /// efficient) and for \ref manual_clock_type (for testing purposes). /// /// Timers are optimized for cancellation; that is, adding a timer and cancelling /// it is very efficient. This means that attaching a timer per object for /// a timeout that rarely happens is reasonable; one does not have to maintain /// a single timer and a sorted list for this use case. /// /// Timer callbacks should be short and execute quickly. If involved processing /// is required, a timer can launch a continuation. namespace seastar { using steady_clock_type = std::chrono::steady_clock; /// \addtogroup timers /// @{ /// Timer - run a callback at a certain time point in the future. /// /// Timer callbacks should execute quickly. If more involved computation /// is required, the timer should launch it as a fiber (or signal an /// existing fiber to continue execution). Fibers launched from a timer /// callback are executed under the scheduling group that was current /// when the timer was created (see current_scheduling_group()), or the /// scheduling that was given explicitly by the caller when the callback /// was specified. /// /// Expiration of a `timer<std::chrono::steady_clock>` is independent of /// task_quota, so it has relatively high accuracy, but as a result this /// is a relatively expensive timer. It is recommended to use `timer<lowres_clock>` /// instead, which has very coarse resolution (~10ms) but is quite efficient. /// It is suitable for most user timeouts. /// /// \tparam Clock type of clock used to denote time points; can be /// std::chrono::steady_clock_type (default), lowres_clock (more efficient /// but with less resolution) and manual_clock_type (fine-grained control /// for testing. template <typename Clock = steady_clock_type> class timer { public: typedef typename Clock::time_point time_point; typedef typename Clock::duration duration; typedef Clock clock; private: using callback_t = noncopyable_function<void()>; boost::intrusive::list_member_hook<> _link; scheduling_group _sg; callback_t _callback; time_point _expiry; compat::optional<duration> _period; bool _armed = false; bool _queued = false; bool _expired = false; void readd_periodic(); void arm_state(time_point until, compat::optional<duration> period) { assert(!_armed); _period = period; _armed = true; _expired = false; _expiry = until; _queued = true; } public: /// Constructs a timer with no callback set and no expiration time. timer() = default; /// Constructs a timer from another timer that is moved from. /// /// \note care should be taken when moving a timer whose callback captures `this`, /// since the object pointed to by `this` may have been moved as well. timer(timer&& t) noexcept : _sg(t._sg), _callback(std::move(t._callback)), _expiry(std::move(t._expiry)), _period(std::move(t._period)), _armed(t._armed), _queued(t._queued), _expired(t._expired) { _link.swap_nodes(t._link); t._queued = false; t._armed = false; } /// Constructs a timer with a callback. The timer is not armed. /// /// \param sg Scheduling group to run the callback under. /// \param callback function (with signature `void ()`) to execute after the timer is armed and expired. timer(scheduling_group sg, noncopyable_function<void ()>&& callback) : _sg(sg), _callback{std::move(callback)} { } /// Constructs a timer with a callback. The timer is not armed. /// /// \param callback function (with signature `void ()`) to execute after the timer is armed and expired. explicit timer(noncopyable_function<void ()>&& callback) : timer(current_scheduling_group(), std::move(callback)) { } /// Destroys the timer. The timer is cancelled if armed. ~timer(); /// Sets the callback function to be called when the timer expires. /// /// \param sg the scheduling group under which the callback will be executed. /// \param callback the callback to be executed when the timer expires. void set_callback(scheduling_group sg, noncopyable_function<void ()>&& callback) { _sg = sg; _callback = std::move(callback); } /// Sets the callback function to be called when the timer expires. /// /// \param callback the callback to be executed when the timer expires. void set_callback(noncopyable_function<void ()>&& callback) { set_callback(current_scheduling_group(), std::move(callback)); } /// Sets the timer expiration time. /// /// It is illegal to arm a timer that has already been armed (and /// not disarmed by expiration or cancel()). In the current /// implementation, this will result in an assertion failure. See /// rearm(). /// /// \param until the time when the timer expires /// \param period optional automatic rearm duration; if given the timer /// will automatically rearm itself when it expires, using the period /// to calculate the next expiration time. void arm(time_point until, compat::optional<duration> period = {}); /// Sets the timer expiration time. If the timer was already armed, it is /// canceled first. /// /// \param until the time when the timer expires /// \param period optional automatic rearm duration; if given the timer /// will automatically rearm itself when it expires, using the period /// to calculate the next expiration time. void rearm(time_point until, compat::optional<duration> period = {}) { if (_armed) { cancel(); } arm(until, period); } /// Sets the timer expiration time. /// /// It is illegal to arm a timer that has already been armed (and /// not disarmed by expiration or cancel()). In the current /// implementation, this will result in an assertion failure. See /// rearm(). /// /// \param delta the time when the timer expires, relative to now void arm(duration delta) { return arm(Clock::now() + delta); } /// Sets the timer expiration time, with automatic rearming /// /// \param delta the time when the timer expires, relative to now. The timer /// will also rearm automatically using the same delta time. void arm_periodic(duration delta) { arm(Clock::now() + delta, {delta}); } /// Returns whether the timer is armed /// /// \return `true` if the timer is armed and has not expired yet. bool armed() const { return _armed; } /// Cancels an armed timer. /// /// If the timer was armed, it is disarmed. If the timer was not /// armed, does nothing. /// /// \return `true` if the timer was armed before the call. bool cancel(); /// Gets the expiration time of an armed timer. /// /// \return the time at which the timer is scheduled to expire (undefined if the /// timer is not armed). time_point get_timeout() { return _expiry; } friend class reactor; friend class timer_set<timer, &timer::_link>; }; extern template class timer<steady_clock_type>; /// @} } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: office_connect.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: kz $ $Date: 2006-11-06 15:03:17 $ * * The Contents of this file are made available subject to the terms of * the BSD license. * * Copyright (c) 2003 by Sun Microsystems, 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. * 3. Neither the name of Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *************************************************************************/ #include <stdio.h> #include <cppuhelper/bootstrap.hxx> #include <com/sun/star/bridge/XUnoUrlResolver.hpp> #include <com/sun/star/lang/XMultiServiceFactory.hpp> using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::bridge; using namespace rtl; using namespace cppu; int main( ) { // create the initial component context Reference< XComponentContext > rComponentContext = defaultBootstrap_InitialComponentContext(); // retrieve the servicemanager from the context Reference< XMultiComponentFactory > rServiceManager = rComponentContext->getServiceManager(); // instantiate a sample service with the servicemanager. Reference< XInterface > rInstance = rServiceManager->createInstanceWithContext( OUString::createFromAscii("com.sun.star.bridge.UnoUrlResolver" ), rComponentContext ); // Query for the XUnoUrlResolver interface Reference< XUnoUrlResolver > rResolver( rInstance, UNO_QUERY ); if( ! rResolver.is() ) { printf( "Error: Couldn't instantiate com.sun.star.bridge.UnoUrlResolver service\n" ); return 1; } try { // resolve the uno-url rInstance = rResolver->resolve( OUString::createFromAscii( "uno:socket,host=localhost,port=2083;urp;StarOffice.ServiceManager" ) ); if( ! rInstance.is() ) { printf( "StarOffice.ServiceManager is not exported from remote counterpart\n" ); return 1; } // query for the simpler XMultiServiceFactory interface, sufficient for scripting Reference< XMultiServiceFactory > rOfficeServiceManager (rInstance, UNO_QUERY); if( ! rInstance.is() ) { printf( "XMultiServiceFactory interface is not exported for StarOffice.ServiceManager\n" ); return 1; } printf( "Connected sucessfully to the office\n" ); } catch( Exception &e ) { OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US ); printf( "Error: %s\n", o.pData->buffer ); return 1; } return 0; } <commit_msg>INTEGRATION: CWS jsc21 (1.6.92); FILE MERGED 2008/05/21 15:03:04 jsc 1.6.92.1: #i88797# adapted to new structure<commit_after>/************************************************************************* * * $RCSfile: office_connect.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2008-07-11 14:24:32 $ * * The Contents of this file are made available subject to the terms of * the BSD license. * * Copyright (c) 2003 by Sun Microsystems, 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. * 3. Neither the name of Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *************************************************************************/ #include <stdio.h> #include <cppuhelper/bootstrap.hxx> #include <com/sun/star/bridge/XUnoUrlResolver.hpp> #include <com/sun/star/lang/XMultiServiceFactory.hpp> #include <com/sun/star/lang/XMultiComponentFactory.hpp> using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::bridge; using namespace rtl; using namespace cppu; int main( ) { // create the initial component context Reference< XComponentContext > rComponentContext = defaultBootstrap_InitialComponentContext(); // retrieve the servicemanager from the context Reference< XMultiComponentFactory > rServiceManager = rComponentContext->getServiceManager(); // instantiate a sample service with the servicemanager. Reference< XInterface > rInstance = rServiceManager->createInstanceWithContext( OUString::createFromAscii("com.sun.star.bridge.UnoUrlResolver" ), rComponentContext ); // Query for the XUnoUrlResolver interface Reference< XUnoUrlResolver > rResolver( rInstance, UNO_QUERY ); if( ! rResolver.is() ) { printf( "Error: Couldn't instantiate com.sun.star.bridge.UnoUrlResolver service\n" ); return 1; } try { // resolve the uno-url rInstance = rResolver->resolve( OUString::createFromAscii( "uno:socket,host=localhost,port=2083;urp;StarOffice.ServiceManager" ) ); if( ! rInstance.is() ) { printf( "StarOffice.ServiceManager is not exported from remote counterpart\n" ); return 1; } // query for the simpler XMultiServiceFactory interface, sufficient for scripting Reference< XMultiServiceFactory > rOfficeServiceManager (rInstance, UNO_QUERY); if( ! rInstance.is() ) { printf( "XMultiServiceFactory interface is not exported for StarOffice.ServiceManager\n" ); return 1; } printf( "Connected sucessfully to the office\n" ); } catch( Exception &e ) { OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US ); printf( "Error: %s\n", o.pData->buffer ); return 1; } return 0; } <|endoftext|>
<commit_before>#pragma once #include "zmsg_utils.hpp" #include "zmsg_types.hpp" namespace zmsg { template<> struct zmsg<mid_t::set_fs_spec> { public: int32_t window_x_row; // unit: pixel int32_t window_x_col; // unit: pixel int32_t window_y_row; // unit: pixel int32_t window_y_col; // unit: pixel /*deprecated*/ uint32_t nm_per_pixel; // unit: nm/pixel double zmotor_spec_nm_per_step; // unit: nm/step double lz_nm_per_step; // unit: nm/step double rz_nm_per_step; // unit: nm/step uint16_t img_cap_delay; // unit: ms double clr_discharge_strength; // unit: volt uint32_t clr_discharge_gap; // unit: nm uint16_t check_fiber_exist_time; // unit: ms std::array<uint16_t, motorId_t::NUM> motor_min_speed; std::array<uint16_t, motorId_t::NUM> motor_max_speed; double entering_speed; double push1_speed; double push2_stage1_speed; double push2_stage2_speed; double manual_calibrate_speed; double motor_xy_precise_calibrate_speed; double tensionSpeed; uint32_t tensionStretchLength; uint16_t motor_xy_steps_per_pixel; // unit: step/pixel double fiber_outline_blacklevel; // 0.0 ~ 1.0 double calibrating_xy_dist_threshold; // unit: pixel double precise_calibrating_xy_dist_threshold; // unit: pixel double z_dist_threshold; // unit: pixel discharge_data_t discharge_base; discharge_data_t discharge_revise; double dust_check_threshold0; double dust_check_threshold1; uint16_t img_denoise_threshold; std::array<double, ledId_t::LED_NUM> led_brightness; double x_focal_distance; double y_focal_distance; double zmotor_speed_factor; double zmotor_speed_pow; double zmotor_speed_max; /// 0.0 ~ 1.0 double xymotor_speed_factor; double xymotor_speed_pow; double xymotor_speed_max; /// 0.0 ~ 1.0 double zmotor_forward_distance; /// unit: nm double zmotor_stroke; /// unit: nm double dbg_hangle_limit; /// unit: degree double dbg_vangle_limit; /// unit: degree double pre_cal_xy_dist_threshold_relax_ratio; std::array<rt_revise_data_t, to_val(fiber_t::max)> rt_revise_data; double loss_factor; public: ZMSG_PU( window_x_row, window_x_col, window_y_row, window_y_col, nm_per_pixel, zmotor_spec_nm_per_step, lz_nm_per_step, rz_nm_per_step, img_cap_delay, clr_discharge_strength, clr_discharge_gap, check_fiber_exist_time, motor_min_speed, motor_max_speed, entering_speed, push1_speed, push2_stage1_speed, push2_stage2_speed, manual_calibrate_speed, motor_xy_precise_calibrate_speed, tensionSpeed, tensionStretchLength, motor_xy_steps_per_pixel, fiber_outline_blacklevel, calibrating_xy_dist_threshold, precise_calibrating_xy_dist_threshold, z_dist_threshold, discharge_base, discharge_revise, dust_check_threshold0, dust_check_threshold1, img_denoise_threshold, led_brightness, x_focal_distance, y_focal_distance, zmotor_speed_factor, zmotor_speed_pow, zmotor_speed_max, xymotor_speed_factor, xymotor_speed_pow, xymotor_speed_max, zmotor_forward_distance, zmotor_stroke, dbg_hangle_limit, dbg_vangle_limit, pre_cal_xy_dist_threshold_relax_ratio, rt_revise_data, loss_factor) }; template<> struct zmsg<mid_t::update_led_brightness> { public: ledId_t id; double brightness; public: ZMSG_PU(id, brightness) }; template<> struct zmsg<mid_t::update_window_position> { bool is_pos_x; int32_t row; int32_t column; public: ZMSG_PU(is_pos_x,row,column) }; template<> struct zmsg<mid_t::update_cmos_focal_distance> { public: double x_focal_distance; double y_focal_distance; public: ZMSG_PU(x_focal_distance, y_focal_distance) }; } <commit_msg>add comment for motor_speed_factor<commit_after>#pragma once #include "zmsg_utils.hpp" #include "zmsg_types.hpp" namespace zmsg { template<> struct zmsg<mid_t::set_fs_spec> { public: int32_t window_x_row; // unit: pixel int32_t window_x_col; // unit: pixel int32_t window_y_row; // unit: pixel int32_t window_y_col; // unit: pixel /*deprecated*/ uint32_t nm_per_pixel; // unit: nm/pixel double zmotor_spec_nm_per_step; // unit: nm/step double lz_nm_per_step; // unit: nm/step double rz_nm_per_step; // unit: nm/step uint16_t img_cap_delay; // unit: ms double clr_discharge_strength; // unit: volt uint32_t clr_discharge_gap; // unit: nm uint16_t check_fiber_exist_time; // unit: ms std::array<uint16_t, motorId_t::NUM> motor_min_speed; std::array<uint16_t, motorId_t::NUM> motor_max_speed; double entering_speed; double push1_speed; double push2_stage1_speed; double push2_stage2_speed; double manual_calibrate_speed; double motor_xy_precise_calibrate_speed; double tensionSpeed; uint32_t tensionStretchLength; uint16_t motor_xy_steps_per_pixel; // unit: step/pixel double fiber_outline_blacklevel; // 0.0 ~ 1.0 double calibrating_xy_dist_threshold; // unit: pixel double precise_calibrating_xy_dist_threshold; // unit: pixel double z_dist_threshold; // unit: pixel discharge_data_t discharge_base; discharge_data_t discharge_revise; double dust_check_threshold0; double dust_check_threshold1; uint16_t img_denoise_threshold; std::array<double, ledId_t::LED_NUM> led_brightness; double x_focal_distance; double y_focal_distance; double zmotor_speed_factor; /// unit: um double zmotor_speed_pow; double zmotor_speed_max; /// 0.0 ~ 1.0 double xymotor_speed_factor; /// unit: um double xymotor_speed_pow; double xymotor_speed_max; /// 0.0 ~ 1.0 double zmotor_forward_distance; /// unit: nm double zmotor_stroke; /// unit: nm double dbg_hangle_limit; /// unit: degree double dbg_vangle_limit; /// unit: degree double pre_cal_xy_dist_threshold_relax_ratio; std::array<rt_revise_data_t, to_val(fiber_t::max)> rt_revise_data; double loss_factor; public: ZMSG_PU( window_x_row, window_x_col, window_y_row, window_y_col, nm_per_pixel, zmotor_spec_nm_per_step, lz_nm_per_step, rz_nm_per_step, img_cap_delay, clr_discharge_strength, clr_discharge_gap, check_fiber_exist_time, motor_min_speed, motor_max_speed, entering_speed, push1_speed, push2_stage1_speed, push2_stage2_speed, manual_calibrate_speed, motor_xy_precise_calibrate_speed, tensionSpeed, tensionStretchLength, motor_xy_steps_per_pixel, fiber_outline_blacklevel, calibrating_xy_dist_threshold, precise_calibrating_xy_dist_threshold, z_dist_threshold, discharge_base, discharge_revise, dust_check_threshold0, dust_check_threshold1, img_denoise_threshold, led_brightness, x_focal_distance, y_focal_distance, zmotor_speed_factor, zmotor_speed_pow, zmotor_speed_max, xymotor_speed_factor, xymotor_speed_pow, xymotor_speed_max, zmotor_forward_distance, zmotor_stroke, dbg_hangle_limit, dbg_vangle_limit, pre_cal_xy_dist_threshold_relax_ratio, rt_revise_data, loss_factor) }; template<> struct zmsg<mid_t::update_led_brightness> { public: ledId_t id; double brightness; public: ZMSG_PU(id, brightness) }; template<> struct zmsg<mid_t::update_window_position> { bool is_pos_x; int32_t row; int32_t column; public: ZMSG_PU(is_pos_x,row,column) }; template<> struct zmsg<mid_t::update_cmos_focal_distance> { public: double x_focal_distance; double y_focal_distance; public: ZMSG_PU(x_focal_distance, y_focal_distance) }; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////// // This file is part of Grappa, a system for scaling irregular // applications on commodity clusters. // Copyright (C) 2010-2014 University of Washington and Battelle // Memorial Institute. University of Washington authorizes use of this // Grappa software. // Grappa is free software: you can redistribute it and/or modify it // under the terms of the Affero General Public License as published // by Affero, Inc., either version 1 of the License, or (at your // option) any later version. // Grappa 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 // Affero General Public License for more details. // You should have received a copy of the Affero General Public // License along with this program. If not, you may obtain one from // http://www.affero.org/oagl.html. //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// /// Demonstrates using the GraphLab API to implement Pagerank //////////////////////////////////////////////////////////////////////// #include <Grappa.hpp> #include "graphlab.hpp" DEFINE_bool( metrics, false, "Dump metrics"); DEFINE_int32(scale, 10, "Log2 number of vertices."); DEFINE_int32(edgefactor, 16, "Average number of edges per vertex."); DEFINE_string(path, "", "Path to graph source file."); DEFINE_string(format, "bintsv4", "Format of graph source file."); GRAPPA_DEFINE_METRIC(SimpleMetric<double>, init_time, 0); GRAPPA_DEFINE_METRIC(SimpleMetric<double>, tuple_time, 0); GRAPPA_DEFINE_METRIC(SimpleMetric<double>, construction_time, 0); GRAPPA_DEFINE_METRIC(SimpleMetric<double>, total_time, 0); const double RESET_PROB = 0.15; DEFINE_double(tolerance, 1.0E-2, "tolerance"); #define TOLERANCE FLAGS_tolerance struct CCData : public GraphlabVertexData<CCData> { uint64_t label; }; struct MinLabel { uint64_t v; explicit MinLabel(uint64_t v): v(v) {} MinLabel(): v(std::numeric_limits<uint64_t>::max()) {} MinLabel& operator+=(const MinLabel& o) { v = std::min(v, o.v); return *this; } operator uint64_t () const { return v; } }; using G = Graph<CCData,Empty>; struct LabelPropagation : public GraphlabVertexProgram<G,MinLabel> { bool do_scatter; uint64_t tmp_label; LabelPropagation(Vertex& v): tmp_label(-1) {} bool gather_edges(const Vertex& v) const { return true; } Gather gather(const Vertex& v, Edge& e) const { return MinLabel(v->label); } void apply(Vertex& v, const Gather& total) { uint64_t min_label = static_cast<uint64_t>(total); if (v->label > min_label) { v->label = tmp_label = min_label; do_scatter = true; } } bool scatter_edges(const Vertex& v) const { return do_scatter; } Gather scatter(const Edge& e, Vertex& target) const { if (target->label > tmp_label) { target->activate(); return MinLabel(tmp_label); } return MinLabel(); } }; Reducer<int64_t,ReducerType::Add> nc; int main(int argc, char* argv[]) { init(&argc, &argv); run([]{ double t; TupleGraph tg; GRAPPA_TIME_REGION(tuple_time) { if (FLAGS_path.empty()) { int64_t NE = (1L << FLAGS_scale) * FLAGS_edgefactor; tg = TupleGraph::Kronecker(FLAGS_scale, NE, 111, 222); } else { LOG(INFO) << "loading " << FLAGS_path; tg = TupleGraph::Load(FLAGS_path, FLAGS_format); } } LOG(INFO) << tuple_time; LOG(INFO) << "constructing graph"; t = walltime(); auto g = G::Undirected(tg); construction_time = walltime()-t; LOG(INFO) << construction_time; GRAPPA_TIME_REGION(total_time) { forall(g, [](VertexID i, G::Vertex& v){ v->label = i; v->activate(); }); run_synchronous<LabelPropagation>(g); } LOG(INFO) << total_time; if (FLAGS_scale <= 8) { g->dump([](std::ostream& o, G::Vertex& v){ o << "{ label:" << v->label << " }"; }); } nc = 0; forall(g, [](VertexID i, G::Vertex& v){ if (v->label == i) nc++; }); LOG(INFO) << "ncomponents: " << nc; }); finalize(); } <commit_msg>graphlab cc: deactivate scatter<commit_after>//////////////////////////////////////////////////////////////////////// // This file is part of Grappa, a system for scaling irregular // applications on commodity clusters. // Copyright (C) 2010-2014 University of Washington and Battelle // Memorial Institute. University of Washington authorizes use of this // Grappa software. // Grappa is free software: you can redistribute it and/or modify it // under the terms of the Affero General Public License as published // by Affero, Inc., either version 1 of the License, or (at your // option) any later version. // Grappa 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 // Affero General Public License for more details. // You should have received a copy of the Affero General Public // License along with this program. If not, you may obtain one from // http://www.affero.org/oagl.html. //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// /// Demonstrates using the GraphLab API to implement Pagerank //////////////////////////////////////////////////////////////////////// #include <Grappa.hpp> #include "graphlab.hpp" DEFINE_bool( metrics, false, "Dump metrics"); DEFINE_int32(scale, 10, "Log2 number of vertices."); DEFINE_int32(edgefactor, 16, "Average number of edges per vertex."); DEFINE_string(path, "", "Path to graph source file."); DEFINE_string(format, "bintsv4", "Format of graph source file."); GRAPPA_DEFINE_METRIC(SimpleMetric<double>, init_time, 0); GRAPPA_DEFINE_METRIC(SimpleMetric<double>, tuple_time, 0); GRAPPA_DEFINE_METRIC(SimpleMetric<double>, construction_time, 0); GRAPPA_DEFINE_METRIC(SimpleMetric<double>, total_time, 0); const double RESET_PROB = 0.15; DEFINE_double(tolerance, 1.0E-2, "tolerance"); #define TOLERANCE FLAGS_tolerance struct CCData : public GraphlabVertexData<CCData> { uint64_t label; }; struct MinLabel { uint64_t v; explicit MinLabel(uint64_t v): v(v) {} MinLabel(): v(std::numeric_limits<uint64_t>::max()) {} MinLabel& operator+=(const MinLabel& o) { v = std::min(v, o.v); return *this; } operator uint64_t () const { return v; } }; using G = Graph<CCData,Empty>; struct LabelPropagation : public GraphlabVertexProgram<G,MinLabel> { bool do_scatter; uint64_t tmp_label; LabelPropagation(Vertex& v): tmp_label(-1) {} bool gather_edges(const Vertex& v) const { return true; } Gather gather(const Vertex& v, Edge& e) const { return MinLabel(v->label); } void apply(Vertex& v, const Gather& total) { uint64_t min_label = static_cast<uint64_t>(total); if (v->label > min_label) { v->label = tmp_label = min_label; do_scatter = true; } else { do_scatter = false; } } bool scatter_edges(const Vertex& v) const { return do_scatter; } Gather scatter(const Edge& e, Vertex& target) const { if (target->label > tmp_label) { target->activate(); return MinLabel(tmp_label); } return MinLabel(); } }; Reducer<int64_t,ReducerType::Add> nc; int main(int argc, char* argv[]) { init(&argc, &argv); run([]{ double t; TupleGraph tg; GRAPPA_TIME_REGION(tuple_time) { if (FLAGS_path.empty()) { int64_t NE = (1L << FLAGS_scale) * FLAGS_edgefactor; tg = TupleGraph::Kronecker(FLAGS_scale, NE, 111, 222); } else { LOG(INFO) << "loading " << FLAGS_path; tg = TupleGraph::Load(FLAGS_path, FLAGS_format); } } LOG(INFO) << tuple_time; LOG(INFO) << "constructing graph"; t = walltime(); auto g = G::Undirected(tg); construction_time = walltime()-t; LOG(INFO) << construction_time; GRAPPA_TIME_REGION(total_time) { forall(g, [](VertexID i, G::Vertex& v){ v->label = i; v->activate(); }); run_synchronous<LabelPropagation>(g); } LOG(INFO) << total_time; if (FLAGS_scale <= 8) { g->dump([](std::ostream& o, G::Vertex& v){ o << "{ label:" << v->label << " }"; }); } nc = 0; forall(g, [](VertexID i, G::Vertex& v){ if (v->label == i) nc++; }); LOG(INFO) << "ncomponents: " << nc; }); finalize(); } <|endoftext|>
<commit_before>// Copyright (C) 2015 The Regents of the University of California (Regents). // 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 Regents or University of California 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 HOLDERS 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. // // Please contact the author of this library if you have any questions. // Author: Chris Sweeney ([email protected]) #include "theia/sfm/extract_maximally_parallel_rigid_subgraph.h" #include <ceres/rotation.h> #include <Eigen/Core> #include <Eigen/LU> #include <algorithm> #include <unordered_map> #include <vector> #include "theia/sfm/pose/util.h" #include "theia/sfm/types.h" #include "theia/sfm/view_graph/view_graph.h" #include "theia/util/map_util.h" namespace theia { namespace { void FormAngleMeasurementMatrix( const std::unordered_map<ViewId, Eigen::Vector3d>& orientations, const ViewGraph& view_graph, const std::unordered_map<ViewId, int>& view_ids_to_index, Eigen::MatrixXd* angle_measurements) { const auto& view_pairs = view_graph.GetAllEdges(); angle_measurements->setZero(); // Set up the matrix such that t_{i,j} x (c_j - c_i) = 0. int i = 0; for (const auto& view_pair : view_pairs) { // Get t_{i,j} and rotate it such that it is oriented in the global // reference frame. Eigen::Matrix3d world_to_view1_rotation; ceres::AngleAxisToRotationMatrix( FindOrDie(orientations, view_pair.first.first).data(), ceres::ColumnMajorAdapter3x3(world_to_view1_rotation.data())); const Eigen::Vector3d rotated_translation = world_to_view1_rotation.transpose() * view_pair.second.position_2; const Eigen::Matrix3d cross_product_mat = CrossProductMatrix(rotated_translation); // Find the column locations of the two views. const int view1_col = 3 * FindOrDie(view_ids_to_index, view_pair.first.first); const int view2_col = 3 * FindOrDie(view_ids_to_index, view_pair.first.second); angle_measurements->block<3, 3>(3 * i, view1_col) = -cross_product_mat; angle_measurements->block<3, 3>(3 * i, view2_col) = cross_product_mat; ++i; } } // Computes the cosine distance in each dimension x, y, and z and returns the // maximum cosine distance. // // cos distance = 1.0 - a.dot(b) / (norm(a) * norm(b)) double ComputeCosineDistance(const Eigen::MatrixXd& mat1, const Eigen::MatrixXd& mat2) { Eigen::Vector3d cos_distance; for (int i =0; i < 3; i++) { cos_distance(i) = 1.0 - std::abs(mat1.row(0).dot(mat2.row(0))); } return cos_distance.maxCoeff(); } // Find the maximal rigid component containing fixed_node. This is done by // examining which nodes are parallel when removing node fixed_node from the // null space. The nodes are only parallel if they are part of the maximal rigid // component with fixed_node. void FindMaximalParallelRigidComponent(const Eigen::MatrixXd& null_space, const int fixed_node, std::unordered_set<int>* largest_cc) { static const double kMaxCosDistance = 1e-5; static const double kMaxNorm = 1e-10; const int num_nodes = null_space.rows() / 3; largest_cc->insert(fixed_node); const Eigen::MatrixXd fixed_null_space_component = null_space.block(3 * fixed_node, 0, 3, null_space.cols()); // Remove the fixed node from the rest of the null space. Eigen::MatrixXd modified_null_space = null_space - fixed_null_space_component.replicate(num_nodes, 1); // Normalize all rows to be unit-norm. If the rows have a very small norm then // they are parallel to the fixed_node. and should be set to zero. const Eigen::VectorXd norms = modified_null_space.rowwise().norm(); modified_null_space.rowwise().normalize(); // Find the pairs to match. Add all indices that are close to 0-vectors, as // they are clearly part of the rigid component. std::vector<int> indices_to_match; for (int i = 0; i < num_nodes; i++) { // Skip this index if it is fixed. if (i == fixed_node) { continue; } // Skip this index if it is nearly a 0-vector because this means it is // clearly part of the rigid component. if (norms(3 * i) < kMaxNorm && norms(3 * i + 1) < kMaxNorm && norms(3 * i + 2) < kMaxNorm) { largest_cc->insert(i); continue; } indices_to_match.emplace_back(i); } // Each node has three dimensions (x, y, z). We only compare parallel-ness // between similar dimensions. If all x, y, z dimensions are parallel then // the two nodes will be parallel. for (int i = 0; i < indices_to_match.size(); i++) { // Test all other nodes (that have not been tested) to determine if they are // parallel to this node. const Eigen::MatrixXd& block1 = modified_null_space.block( 3 * indices_to_match[i], 0, 3, null_space.cols()); for (int j = i + 1; j < indices_to_match.size(); j++) { const Eigen::MatrixXd& block2 = modified_null_space.block( 3 * indices_to_match[j], 0, 3, null_space.cols()); const double cos_distance = ComputeCosineDistance(block1, block2); if (cos_distance < kMaxCosDistance) { largest_cc->insert(indices_to_match[i]); largest_cc->insert(indices_to_match[j]); } } } } } // namespace void ExtractMaximallyParallelRigidSubgraph( const std::unordered_map<ViewId, Eigen::Vector3d>& orientations, ViewGraph* view_graph) { // Create a mapping of indexes to ViewIds for our linear system. std::unordered_map<ViewId, int> view_ids_to_index; view_ids_to_index.reserve(orientations.size()); for (const auto& orientation : orientations) { const int current_index = view_ids_to_index.size(); InsertIfNotPresent(&view_ids_to_index, orientation.first, current_index); } // Form the global angle measurements matrix from: // t_{i,j} x (c_j - c_i) = 0. Eigen::MatrixXd angle_measurements(3 * view_graph->NumEdges(), 3 * orientations.size()); FormAngleMeasurementMatrix(orientations, *view_graph, view_ids_to_index, &angle_measurements); // Extract the null space of the angle measurements matrix. Eigen::FullPivLU<Eigen::MatrixXd> lu(angle_measurements.transpose() * angle_measurements); const Eigen::MatrixXd null_space = lu.kernel(); // For each node in the graph (i.e. each camera), set the null space component // to be zero such that the camera position would be fixed at the origin. If // two nodes i and j are in the same rigid component, then their null spaces // will be parallel because the camera positions may only change by a // scale. We find all components that are parallel to find the rigid // components. The largest of such component is the maximally parallel rigid // component of the graph. std::unordered_set<int> maximal_rigid_component; for (int i = 0; i < orientations.size(); i++) { std::unordered_set<int> temp_cc; FindMaximalParallelRigidComponent(null_space, i, &temp_cc); if (temp_cc.size() > maximal_rigid_component.size()) { std::swap(temp_cc, maximal_rigid_component); } } // Only keep the nodes in the largest maximally parallel rigid component. for (const auto& orientation : orientations) { const int index = FindOrDie(view_ids_to_index, orientation.first); // If the view is not in the maximal rigid component then remove it from the // view graph. if (!ContainsKey(maximal_rigid_component, index)) { CHECK(view_graph->RemoveView(orientation.first)) << "Could not remove view id " << orientation.first << " from the view graph because it does not exist."; } } } } // namespace theia <commit_msg>Bug fix in cos distance function. Thanks to inspirit for spotting it!<commit_after>// Copyright (C) 2015 The Regents of the University of California (Regents). // 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 Regents or University of California 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 HOLDERS 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. // // Please contact the author of this library if you have any questions. // Author: Chris Sweeney ([email protected]) #include "theia/sfm/extract_maximally_parallel_rigid_subgraph.h" #include <ceres/rotation.h> #include <Eigen/Core> #include <Eigen/LU> #include <algorithm> #include <unordered_map> #include <vector> #include "theia/sfm/pose/util.h" #include "theia/sfm/types.h" #include "theia/sfm/view_graph/view_graph.h" #include "theia/util/map_util.h" namespace theia { namespace { void FormAngleMeasurementMatrix( const std::unordered_map<ViewId, Eigen::Vector3d>& orientations, const ViewGraph& view_graph, const std::unordered_map<ViewId, int>& view_ids_to_index, Eigen::MatrixXd* angle_measurements) { const auto& view_pairs = view_graph.GetAllEdges(); angle_measurements->setZero(); // Set up the matrix such that t_{i,j} x (c_j - c_i) = 0. int i = 0; for (const auto& view_pair : view_pairs) { // Get t_{i,j} and rotate it such that it is oriented in the global // reference frame. Eigen::Matrix3d world_to_view1_rotation; ceres::AngleAxisToRotationMatrix( FindOrDie(orientations, view_pair.first.first).data(), ceres::ColumnMajorAdapter3x3(world_to_view1_rotation.data())); const Eigen::Vector3d rotated_translation = world_to_view1_rotation.transpose() * view_pair.second.position_2; const Eigen::Matrix3d cross_product_mat = CrossProductMatrix(rotated_translation); // Find the column locations of the two views. const int view1_col = 3 * FindOrDie(view_ids_to_index, view_pair.first.first); const int view2_col = 3 * FindOrDie(view_ids_to_index, view_pair.first.second); angle_measurements->block<3, 3>(3 * i, view1_col) = -cross_product_mat; angle_measurements->block<3, 3>(3 * i, view2_col) = cross_product_mat; ++i; } } // Computes the cosine distance in each dimension x, y, and z and returns the // maximum cosine distance. // // cos distance = 1.0 - a.dot(b) / (norm(a) * norm(b)) double ComputeCosineDistance(const Eigen::MatrixXd& mat1, const Eigen::MatrixXd& mat2) { Eigen::Vector3d cos_distance; for (int i =0; i < 3; i++) { cos_distance(i) = 1.0 - std::abs(mat1.row(i).dot(mat2.row(i))); } return cos_distance.maxCoeff(); } // Find the maximal rigid component containing fixed_node. This is done by // examining which nodes are parallel when removing node fixed_node from the // null space. The nodes are only parallel if they are part of the maximal rigid // component with fixed_node. void FindMaximalParallelRigidComponent(const Eigen::MatrixXd& null_space, const int fixed_node, std::unordered_set<int>* largest_cc) { static const double kMaxCosDistance = 1e-5; static const double kMaxNorm = 1e-10; const int num_nodes = null_space.rows() / 3; largest_cc->insert(fixed_node); const Eigen::MatrixXd fixed_null_space_component = null_space.block(3 * fixed_node, 0, 3, null_space.cols()); // Remove the fixed node from the rest of the null space. Eigen::MatrixXd modified_null_space = null_space - fixed_null_space_component.replicate(num_nodes, 1); // Normalize all rows to be unit-norm. If the rows have a very small norm then // they are parallel to the fixed_node. and should be set to zero. const Eigen::VectorXd norms = modified_null_space.rowwise().norm(); modified_null_space.rowwise().normalize(); // Find the pairs to match. Add all indices that are close to 0-vectors, as // they are clearly part of the rigid component. std::vector<int> indices_to_match; for (int i = 0; i < num_nodes; i++) { // Skip this index if it is fixed. if (i == fixed_node) { continue; } // Skip this index if it is nearly a 0-vector because this means it is // clearly part of the rigid component. if (norms(3 * i) < kMaxNorm && norms(3 * i + 1) < kMaxNorm && norms(3 * i + 2) < kMaxNorm) { largest_cc->insert(i); continue; } indices_to_match.emplace_back(i); } // Each node has three dimensions (x, y, z). We only compare parallel-ness // between similar dimensions. If all x, y, z dimensions are parallel then // the two nodes will be parallel. for (int i = 0; i < indices_to_match.size(); i++) { // Test all other nodes (that have not been tested) to determine if they are // parallel to this node. const Eigen::MatrixXd& block1 = modified_null_space.block( 3 * indices_to_match[i], 0, 3, null_space.cols()); for (int j = i + 1; j < indices_to_match.size(); j++) { const Eigen::MatrixXd& block2 = modified_null_space.block( 3 * indices_to_match[j], 0, 3, null_space.cols()); const double cos_distance = ComputeCosineDistance(block1, block2); if (cos_distance < kMaxCosDistance) { largest_cc->insert(indices_to_match[i]); largest_cc->insert(indices_to_match[j]); } } } } } // namespace void ExtractMaximallyParallelRigidSubgraph( const std::unordered_map<ViewId, Eigen::Vector3d>& orientations, ViewGraph* view_graph) { // Create a mapping of indexes to ViewIds for our linear system. std::unordered_map<ViewId, int> view_ids_to_index; view_ids_to_index.reserve(orientations.size()); for (const auto& orientation : orientations) { const int current_index = view_ids_to_index.size(); InsertIfNotPresent(&view_ids_to_index, orientation.first, current_index); } // Form the global angle measurements matrix from: // t_{i,j} x (c_j - c_i) = 0. Eigen::MatrixXd angle_measurements(3 * view_graph->NumEdges(), 3 * orientations.size()); FormAngleMeasurementMatrix(orientations, *view_graph, view_ids_to_index, &angle_measurements); // Extract the null space of the angle measurements matrix. Eigen::FullPivLU<Eigen::MatrixXd> lu(angle_measurements.transpose() * angle_measurements); const Eigen::MatrixXd null_space = lu.kernel(); // For each node in the graph (i.e. each camera), set the null space component // to be zero such that the camera position would be fixed at the origin. If // two nodes i and j are in the same rigid component, then their null spaces // will be parallel because the camera positions may only change by a // scale. We find all components that are parallel to find the rigid // components. The largest of such component is the maximally parallel rigid // component of the graph. std::unordered_set<int> maximal_rigid_component; for (int i = 0; i < orientations.size(); i++) { std::unordered_set<int> temp_cc; FindMaximalParallelRigidComponent(null_space, i, &temp_cc); if (temp_cc.size() > maximal_rigid_component.size()) { std::swap(temp_cc, maximal_rigid_component); } } // Only keep the nodes in the largest maximally parallel rigid component. for (const auto& orientation : orientations) { const int index = FindOrDie(view_ids_to_index, orientation.first); // If the view is not in the maximal rigid component then remove it from the // view graph. if (!ContainsKey(maximal_rigid_component, index)) { CHECK(view_graph->RemoveView(orientation.first)) << "Could not remove view id " << orientation.first << " from the view graph because it does not exist."; } } } } // namespace theia <|endoftext|>
<commit_before>#ifndef ITER_ENUMERATE_H_ #define ITER_ENUMERATE_H_ #include "internal/iterbase.hpp" #include <utility> #include <iterator> #include <functional> #include <initializer_list> #include <type_traits> namespace iter { namespace impl { template <typename Container> class Enumerable; using EnumerateFn = IterToolFn<Enumerable>; } constexpr impl::EnumerateFn enumerate; } template <typename Container> class iter::impl::Enumerable { private: Container container; const std::size_t start; friend EnumerateFn; // for IterYield using BasePair = std::pair<std::size_t, iterator_deref<Container>>; // Value constructor for use only in the enumerate function Enumerable(Container&& in_container, std::size_t in_start = 0) : container(std::forward<Container>(in_container)), start{in_start} {} public: Enumerable(Enumerable&&) = default; // "yielded" by the Enumerable::Iterator. Has a .index, and a // .element referencing the value yielded by the subiterator class IterYield : public BasePair { public: using BasePair::BasePair; typename BasePair::first_type& index = BasePair::first; typename BasePair::second_type& element = BasePair::second; }; // Holds an iterator of the contained type and a size_t for the // index. Each call to ++ increments both of these data members. // Each dereference returns an IterYield. class Iterator : public std::iterator<std::input_iterator_tag, IterYield> { private: iterator_type<Container> sub_iter; std::size_t index; public: Iterator(iterator_type<Container>&& si, std::size_t start) : sub_iter{std::move(si)}, index{start} {} IterYield operator*() { return {this->index, *this->sub_iter}; } ArrowProxy<IterYield> operator->() { return {**this}; } Iterator& operator++() { ++this->sub_iter; ++this->index; return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } bool operator!=(const Iterator& other) const { return this->sub_iter != other.sub_iter; } bool operator==(const Iterator& other) const { return !(*this != other); } }; Iterator begin() { return {std::begin(this->container), start}; } Iterator end() { return {std::end(this->container), start}; } }; #endif <commit_msg>explicit {} on enumerate init<commit_after>#ifndef ITER_ENUMERATE_H_ #define ITER_ENUMERATE_H_ #include "internal/iterbase.hpp" #include <utility> #include <iterator> #include <functional> #include <initializer_list> #include <type_traits> namespace iter { namespace impl { template <typename Container> class Enumerable; using EnumerateFn = IterToolFn<Enumerable>; } constexpr impl::EnumerateFn enumerate{}; } template <typename Container> class iter::impl::Enumerable { private: Container container; const std::size_t start; friend EnumerateFn; // for IterYield using BasePair = std::pair<std::size_t, iterator_deref<Container>>; // Value constructor for use only in the enumerate function Enumerable(Container&& in_container, std::size_t in_start = 0) : container(std::forward<Container>(in_container)), start{in_start} {} public: Enumerable(Enumerable&&) = default; // "yielded" by the Enumerable::Iterator. Has a .index, and a // .element referencing the value yielded by the subiterator class IterYield : public BasePair { public: using BasePair::BasePair; typename BasePair::first_type& index = BasePair::first; typename BasePair::second_type& element = BasePair::second; }; // Holds an iterator of the contained type and a size_t for the // index. Each call to ++ increments both of these data members. // Each dereference returns an IterYield. class Iterator : public std::iterator<std::input_iterator_tag, IterYield> { private: iterator_type<Container> sub_iter; std::size_t index; public: Iterator(iterator_type<Container>&& si, std::size_t start) : sub_iter{std::move(si)}, index{start} {} IterYield operator*() { return {this->index, *this->sub_iter}; } ArrowProxy<IterYield> operator->() { return {**this}; } Iterator& operator++() { ++this->sub_iter; ++this->index; return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } bool operator!=(const Iterator& other) const { return this->sub_iter != other.sub_iter; } bool operator==(const Iterator& other) const { return !(*this != other); } }; Iterator begin() { return {std::begin(this->container), start}; } Iterator end() { return {std::end(this->container), start}; } }; #endif <|endoftext|>
<commit_before>/* * File: btree.cpp * Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS) */ #include "common/sedna.h" #include "tr/idx/btree/btree.h" #include "tr/idx/btree/btintern.h" #include "tr/idx/btree/btpage.h" #include "tr/idx/btree/btstruct.h" #include "tr/vmm/vmm.h" /* variables for debug */ //shft BTREE_HEIGHT=1; xptr bt_create(xmlscm_type t) { xptr root; char* pg; vmm_alloc_data_block(&root); pg = (char*)XADDR(root); bt_page_markup(pg, t); return root; } void bt_drop(const xptr &root) { char* cur_pg; xptr cur_xpg = root; do { CHECKP(cur_xpg); cur_pg = (char*)XADDR(cur_xpg); xptr next_level_lmp = BT_LMP(cur_pg); if ((next_level_lmp == XNULL) && !BT_IS_LEAF(cur_pg)) throw USER_EXCEPTION2(SE1008, "Encountered XNULL LMP field when trying to get left-most path in btree"); /* walk through pages at current layer */ do { xptr tmp = cur_xpg; CHECKP(cur_xpg); cur_xpg = BT_NEXT(cur_pg); cur_pg = (char*)XADDR(cur_xpg); vmm_delete_block(tmp); } while (cur_xpg != XNULL); cur_xpg = next_level_lmp; } while (cur_xpg != XNULL); } bt_cursor bt_find(const xptr &root, const bt_key &key) { bool rc; shft key_idx; xptr res_blk = root; CHECKP(res_blk); rc = bt_find_key(res_blk, (bt_key*)&key, key_idx); if (!rc) /* no matching key */ return bt_cursor(); else return bt_cursor((char*)XADDR(res_blk), key_idx); } /// !!! potential error here bt_cursor bt_find_ge(const xptr &root, const bt_key &key) { bool rc; shft key_idx; xptr next; xptr res_blk = root; CHECKP(res_blk); char* pg = (char*)XADDR(res_blk); rc = bt_find_key(res_blk, (bt_key*)&key, key_idx); if (!rc && key_idx == BT_RIGHTMOST) { #ifdef PERMIT_CLUSTERS if (BT_IS_CLUS(pg)) { pg = bt_cluster_tail(pg); if (BT_KEY_NUM(pg) > 1) return bt_cursor(pg, 1); } #endif next = BT_NEXT(pg); if (next != XNULL) { CHECKP(next); return bt_cursor((char*)XADDR(next), 0); } else return bt_cursor(); } else return bt_cursor((char*)XADDR(res_blk), key_idx); } /// !!! potential error here bt_cursor bt_find_gt(const xptr &root, const bt_key &key) { bool rc; shft key_idx; xptr next; xptr res_blk = root; bt_key old_val=key; CHECKP(res_blk); char* pg = (char*)XADDR(res_blk); rc = bt_find_key(res_blk, (bt_key*)&key, key_idx); if (!rc && key_idx == BT_RIGHTMOST) { #ifdef PERMIT_CLUSTERS if (BT_IS_CLUS(pg)) { pg = bt_cluster_tail(pg); if (BT_KEY_NUM(pg) > 1) return bt_cursor(pg, 1); } #endif next = BT_NEXT(pg); if (next != XNULL) { CHECKP(next); return bt_cursor((char*)XADDR(next), 0); } else return bt_cursor(); } else { bt_cursor c((char*)XADDR(res_blk), key_idx); if (!bt_cmp_key(c.get_key(),old_val)) { c.bt_next_key(); return c; } else { return c; } } } bt_cursor bt_lm(const xptr& root) { CHECKP(root); char* pg = (char*)XADDR(root); #ifdef PERMIT_CLUSTERS /// !!! FIX ME UP #endif if (!BT_IS_LEAF(pg)) { return bt_lm(BT_LMP(pg)); } else { return bt_cursor(pg, 0); } } void bt_insert(xptr &root, const bt_key &key, const object &obj) { bool rc; shft key_idx = 0; shft obj_idx = 0; xptr insert_xpg = root; /* xptr passed to search functions, that can change, pointing to insert new data */ char* insert_pg; /* check key length doesn't exceed limit */ if (key.get_size() >= BT_PAGE_PAYLOAD / 2) throw USER_EXCEPTION2(SE1008, "The size of the index key exceeds max key limit"); rc = bt_find_key(insert_xpg, (bt_key*)&key, key_idx); /* page could change */ insert_pg = (char*)XADDR(insert_xpg); if (rc) { rc = bt_leaf_find_obj(insert_xpg, obj, key_idx, obj_idx); /* if (rc) throw USER_EXCEPTION2(SE1008, "The key/object pair already exists in btree"); else {*/ CHECKP(insert_xpg); insert_pg = (char*)XADDR(insert_xpg); if (obj_idx == BT_RIGHTMOST) obj_idx = *((shft*)BT_CHNK_TAB_AT(insert_pg, key_idx) + 1); bt_leaf_insert(root, insert_pg, key_idx, false, key, obj, obj_idx); /*}*/ } else { CHECKP(insert_xpg); if (key_idx == BT_RIGHTMOST) key_idx = BT_KEY_NUM(insert_pg); bt_leaf_insert(root, insert_pg, key_idx, true, key, obj, obj_idx); } } void bt_modify(xptr &root, const bt_key &old_key, const bt_key &new_key, const object &obj) { bt_delete(root, old_key, obj); bt_insert(root, new_key, obj); } /* light delete functions - delete only data from pages, not droping the pages, i.e no implementation of page merge/drop */ /* delete key/obj pair */ void bt_delete(xptr &root, const bt_key& key, const object &obj) { bool rc; shft key_idx; shft obj_idx; xptr delete_xpg = root; /* xptr passed to search functions, that can change, pointing to page where data resides */ char* delete_pg = (char*)XADDR(delete_xpg); CHECKP(delete_xpg); rc = bt_find_key(delete_xpg, (bt_key*)&key, key_idx); if (rc) { rc = bt_leaf_find_obj(delete_xpg, obj, key_idx, obj_idx); /* page could change */ CHECKP(delete_xpg); delete_pg = (char*)XADDR(delete_xpg); if (rc) bt_delete_obj(delete_pg, key_idx, obj_idx); else throw USER_EXCEPTION2(SE1008, "Cannot delete object which is not in the btree"); } else throw USER_EXCEPTION2(SE1008, "Cannot delete object which is not in the btree"); } /* delete key and all associated objects */ void bt_delete(xptr &root, const bt_key &key) { bool rc; shft key_idx; xptr delete_xpg = root; /* xptr passed to search functions, that can change, pointing to page where data resides */ char* delete_pg = (char*)XADDR(delete_xpg); CHECKP(delete_xpg); rc = bt_find_key(delete_xpg, (bt_key*)&key, key_idx); if (rc) { /* page could change */ CHECKP(delete_xpg); delete_pg = (char*)XADDR(delete_xpg); bt_leaf_delete_key(delete_pg, key_idx); } } /* drop empty page*/ void bt_drop_page(const btree_blk_hdr * pg) { xptr page=ADDR2XPTR(pg); btree_blk_hdr * page_hdr= (btree_blk_hdr*)XADDR(page); xptr left=page_hdr->prev; xptr right=page_hdr->next; //1. fixing block chain if (left!=XNULL) { CHECKP(left); ((btree_blk_hdr*)XADDR(left))->next=right; VMM_SIGNAL_MODIFICATION(left); } if (right!=XNULL) { CHECKP(right); ((btree_blk_hdr*)XADDR(right))->prev=left; VMM_SIGNAL_MODIFICATION(right); } //remove key from upper layers xptr parent=page_hdr->parent; if (parent==XNULL) return; vmm_delete_block(page); CHECKP(parent); btree_blk_hdr * par_hdr= (btree_blk_hdr*)XADDR(parent); // fix lmp if (par_hdr->lmp==page) par_hdr->lmp=right; //find key by xptr int key_idx=-1; for (int i=0;i<BT_KEY_NUM(par_hdr);i++) { if (page==( *(xptr*)BT_BIGPTR_TAB_AT((char*)par_hdr, i))) { key_idx=i; break; } } if (key_idx<0) throw USER_EXCEPTION2(SE1008, "System error in indexes"); bt_nleaf_delete_key((char*)par_hdr,key_idx); //VMM_SIGNAL_MODIFICATION(parent); //recursive walthrough if (!BT_KEY_NUM(par_hdr)) bt_drop_page(par_hdr); } <commit_msg>bug fix in btrees<commit_after>/* * File: btree.cpp * Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS) */ #include "common/sedna.h" #include "tr/idx/btree/btree.h" #include "tr/idx/btree/btintern.h" #include "tr/idx/btree/btpage.h" #include "tr/idx/btree/btstruct.h" #include "tr/idx/btree/buff.h" #include "tr/vmm/vmm.h" /* variables for debug */ //shft BTREE_HEIGHT=1; xptr bt_create(xmlscm_type t) { xptr root; char* pg; vmm_alloc_data_block(&root); pg = (char*)XADDR(root); bt_page_markup(pg, t); return root; } void bt_drop(const xptr &root) { char* cur_pg; xptr cur_xpg = root; do { CHECKP(cur_xpg); cur_pg = (char*)XADDR(cur_xpg); xptr next_level_lmp = BT_LMP(cur_pg); if ((next_level_lmp == XNULL) && !BT_IS_LEAF(cur_pg)) throw USER_EXCEPTION2(SE1008, "Encountered XNULL LMP field when trying to get left-most path in btree"); /* walk through pages at current layer */ do { xptr tmp = cur_xpg; CHECKP(cur_xpg); cur_xpg = BT_NEXT(cur_pg); cur_pg = (char*)XADDR(cur_xpg); vmm_delete_block(tmp); } while (cur_xpg != XNULL); cur_xpg = next_level_lmp; } while (cur_xpg != XNULL); } bt_cursor bt_find(const xptr &root, const bt_key &key) { bool rc; shft key_idx; xptr res_blk = root; CHECKP(res_blk); rc = bt_find_key(res_blk, (bt_key*)&key, key_idx); if (!rc) /* no matching key */ return bt_cursor(); else return bt_cursor((char*)XADDR(res_blk), key_idx); } /// !!! potential error here bt_cursor bt_find_ge(const xptr &root, const bt_key &key) { bool rc; shft key_idx; xptr next; xptr res_blk = root; CHECKP(res_blk); char* pg = (char*)XADDR(res_blk); rc = bt_find_key(res_blk, (bt_key*)&key, key_idx); if (!rc && key_idx == BT_RIGHTMOST) { #ifdef PERMIT_CLUSTERS if (BT_IS_CLUS(pg)) { pg = bt_cluster_tail(pg); if (BT_KEY_NUM(pg) > 1) return bt_cursor(pg, 1); } #endif next = BT_NEXT(pg); if (next != XNULL) { CHECKP(next); return bt_cursor((char*)XADDR(next), 0); } else return bt_cursor(); } else return bt_cursor((char*)XADDR(res_blk), key_idx); } /// !!! potential error here bt_cursor bt_find_gt(const xptr &root, const bt_key &key) { bool rc; shft key_idx; xptr next; xptr res_blk = root; bt_key old_val=key; CHECKP(res_blk); char* pg = (char*)XADDR(res_blk); rc = bt_find_key(res_blk, (bt_key*)&key, key_idx); if (!rc && key_idx == BT_RIGHTMOST) { #ifdef PERMIT_CLUSTERS if (BT_IS_CLUS(pg)) { pg = bt_cluster_tail(pg); if (BT_KEY_NUM(pg) > 1) return bt_cursor(pg, 1); } #endif next = BT_NEXT(pg); if (next != XNULL) { CHECKP(next); return bt_cursor((char*)XADDR(next), 0); } else return bt_cursor(); } else { bt_cursor c((char*)XADDR(res_blk), key_idx); if (!bt_cmp_key(c.get_key(),old_val)) { c.bt_next_key(); return c; } else { return c; } } } bt_cursor bt_lm(const xptr& root) { CHECKP(root); char* pg = (char*)XADDR(root); #ifdef PERMIT_CLUSTERS /// !!! FIX ME UP #endif if (!BT_IS_LEAF(pg)) { return bt_lm(BT_LMP(pg)); } else { return bt_cursor(pg, 0); } } void bt_insert(xptr &root, const bt_key &key, const object &obj) { bool rc; shft key_idx = 0; shft obj_idx = 0; xptr insert_xpg = root; /* xptr passed to search functions, that can change, pointing to insert new data */ char* insert_pg; /* check key length doesn't exceed limit */ if (key.get_size() >= BT_PAGE_PAYLOAD / 2) throw USER_EXCEPTION2(SE1008, "The size of the index key exceeds max key limit"); rc = bt_find_key(insert_xpg, (bt_key*)&key, key_idx); /* page could change */ insert_pg = (char*)XADDR(insert_xpg); if (rc) { rc = bt_leaf_find_obj(insert_xpg, obj, key_idx, obj_idx); /* if (rc) throw USER_EXCEPTION2(SE1008, "The key/object pair already exists in btree"); else {*/ CHECKP(insert_xpg); insert_pg = (char*)XADDR(insert_xpg); if (obj_idx == BT_RIGHTMOST) obj_idx = *((shft*)BT_CHNK_TAB_AT(insert_pg, key_idx) + 1); bt_leaf_insert(root, insert_pg, key_idx, false, key, obj, obj_idx); /*}*/ } else { CHECKP(insert_xpg); if (key_idx == BT_RIGHTMOST) key_idx = BT_KEY_NUM(insert_pg); bt_leaf_insert(root, insert_pg, key_idx, true, key, obj, obj_idx); } } void bt_modify(xptr &root, const bt_key &old_key, const bt_key &new_key, const object &obj) { bt_delete(root, old_key, obj); bt_insert(root, new_key, obj); } /* light delete functions - delete only data from pages, not droping the pages, i.e no implementation of page merge/drop */ /* delete key/obj pair */ void bt_delete(xptr &root, const bt_key& key, const object &obj) { bool rc; shft key_idx; shft obj_idx; xptr delete_xpg = root; /* xptr passed to search functions, that can change, pointing to page where data resides */ char* delete_pg = (char*)XADDR(delete_xpg); CHECKP(delete_xpg); rc = bt_find_key(delete_xpg, (bt_key*)&key, key_idx); if (rc) { rc = bt_leaf_find_obj(delete_xpg, obj, key_idx, obj_idx); /* page could change */ CHECKP(delete_xpg); delete_pg = (char*)XADDR(delete_xpg); if (rc) bt_delete_obj(delete_pg, key_idx, obj_idx); else throw USER_EXCEPTION2(SE1008, "Cannot delete object which is not in the btree"); } else throw USER_EXCEPTION2(SE1008, "Cannot delete object which is not in the btree"); } /* delete key and all associated objects */ void bt_delete(xptr &root, const bt_key &key) { bool rc; shft key_idx; xptr delete_xpg = root; /* xptr passed to search functions, that can change, pointing to page where data resides */ char* delete_pg = (char*)XADDR(delete_xpg); CHECKP(delete_xpg); rc = bt_find_key(delete_xpg, (bt_key*)&key, key_idx); if (rc) { /* page could change */ CHECKP(delete_xpg); delete_pg = (char*)XADDR(delete_xpg); bt_leaf_delete_key(delete_pg, key_idx); } } /* drop empty page*/ void bt_drop_page(const btree_blk_hdr * pg) { xptr page=ADDR2XPTR(pg); btree_blk_hdr * page_hdr= (btree_blk_hdr*)XADDR(page); xptr left=page_hdr->prev; xptr right=page_hdr->next; //1. fixing block chain if (left!=XNULL) { CHECKP(left); ((btree_blk_hdr*)XADDR(left))->next=right; VMM_SIGNAL_MODIFICATION(left); } if (right!=XNULL) { CHECKP(right); ((btree_blk_hdr*)XADDR(right))->prev=left; VMM_SIGNAL_MODIFICATION(right); } //remove key from upper layers xptr parent=page_hdr->parent; if (parent==XNULL) return; vmm_delete_block(page); CHECKP(parent); btree_blk_hdr * par_hdr= (btree_blk_hdr*)XADDR(parent); // fix lmp if (par_hdr->lmp==page) par_hdr->lmp=right; //find key by xptr int key_idx=-1; for (int i=0;i<BT_KEY_NUM(par_hdr);i++) { if (page==( *(xptr*)BT_BIGPTR_TAB_AT((char*)par_hdr, i))) { key_idx=i; break; } } if (key_idx<0) throw USER_EXCEPTION2(SE1008, "System error in indexes"); bt_nleaf_delete_key((char*)par_hdr,key_idx); //VMM_SIGNAL_MODIFICATION(parent); //recursive walthrough if (!BT_KEY_NUM(par_hdr)) { if (par_hdr->lmp!=XNULL) { //the case whe only one pointer left in non-leaf page xptr grandpa=par_hdr->parent;//save parent xptr left_unc=par_hdr->prev;//save left xptr right_unc=par_hdr->next;//save right xptr lmp=par_hdr->lmp; CHECKP(lmp); char* dst = bt_tune_buffering(true, 4); memcpy(dst,(char*)XADDR(lmp)+sizeof(vmm_sm_blk_hdr),PAGE_SIZE-sizeof(vmm_sm_blk_hdr)); CHECKP(parent); memcpy((char*)XADDR(parent)+sizeof(vmm_sm_blk_hdr),dst,PAGE_SIZE-sizeof(vmm_sm_blk_hdr)); par_hdr->parent=grandpa;//restore par_hdr->prev=left_unc; par_hdr->next=right_unc; VMM_SIGNAL_MODIFICATION(parent); vmm_delete_block(lmp); } else bt_drop_page(par_hdr); } } <|endoftext|>
<commit_before>/* * File: other_updates.cpp * Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS) */ #include "common/sedna.h" #include "tr/updates/updates.h" #include "tr/executor/base/xptr_sequence.h" #include "tr/mo/mo.h" #include "tr/auth/auc.h" #include "tr/locks/locks.h" #ifdef SE_ENABLE_TRIGGERS #include "tr/triggers/triggers.h" #endif #include "tr/structures/nodeutils.h" #include "tr/structures/textcptr.h" void replace(PPOpIn arg) { xptr node, parent, tmp_node, old_node, node_child, del_node, attr_node; schema_node_xptr scm_node; tuple t(arg.ts); xptr_sequence arg1seq; // Indirection of nodes which are going to be replaced xptr_sequence arg1seq_tmp; // Nodes which are going to be replaced xptr_sequence arg2seq; // Nodes to replace with (both persistent and temp) /* Persistent nodes to replace with (+ theirs position in arg2seq) */ descript_sequence arg3seq(2); upd_ns_map* ins_swiz = NULL; bool is_node_updated = true; /* * Fill up sequences with nodes to update and update with, * child (arg) returns the following sequence of items: * 1. node to be replaced (1) * 2. nodes to replace with (2) * 3. special tuple which contains separator value (3) */ arg.op->next(t); while (!t.is_eos()) { if (t.cells[0].is_node()) { node=t.cells[0].get_node(); CHECKP(node); /* * In (1) case node must be persistent (is_node_updated is true) * In (2) case it can be temporary * In both cases document nodes are not allowed */ if ((!is_node_updated || is_node_persistent(node)) && !is_node_document(node)) { xptr indir=nodeGetIndirection(node); if (is_node_updated) { /* Case (1) - fill up sequence with nodes to be replaced */ is_node_updated=false; /* Next nodes from arg are case (2) nodes, so we can use shared lock */ local_lock_mrg->lock(lm_s); arg1seq.add(indir); arg1seq_tmp.add(node); } else { /* Case (2) - fill up sequence with nodes to replace with */ if (is_node_persistent(node)) { tuple tup(2); tup.copy(tuple_cell::node(node),tuple_cell((int64_t)(arg2seq.size()))); arg3seq.add(tup); } arg2seq.add(indir); } } #ifndef IGNORE_UPDATE_ERRORS else { throw USER_EXCEPTION(SE2020); } #endif } else { /* Must be separator in this case (3) */ if (t.cells[0].get_atomic_type() == se_separator) { arg2seq.add(XNULL); is_node_updated=true; /* Next nodes from arg are case (1) node, so we can use shared lock */ local_lock_mrg->lock(lm_x); } #ifndef IGNORE_UPDATE_ERRORS else throw USER_EXCEPTION(SE2021); #endif } arg.op->next(t); } /* Nothing to do in this case */ if (arg1seq.size()<=0) return; /* Checking authorization */ if (is_auth_check_needed(REPLACE_STATEMENT)) auth_for_update(&arg1seq, REPLACE_STATEMENT, false); /* Find all common nodes in agr3seq (nodes to replace with) and * arg1seq_tmp (nodes to be replaced). Make a copy of all such nodes. */ arg1seq_tmp.sort(); arg3seq.sort(); descript_sequence::iterator it3 = arg3seq.begin(); xptr_sequence::iterator it1 = arg1seq_tmp.begin(); while(it3 != arg3seq.end() && it1 != arg1seq_tmp.end()) { switch(nid_cmp_effective((*it3).cells[0].get_node(), *it1)) { case 0: case -2: { node = copy_to_temp((*it3).cells[0].get_node()); xptr indir=nodeGetIndirection(node); arg2seq.set(indir,(*it3).cells[1].get_xs_integer()); ++it3; } break; case 1: ++it1; break; case 2: ++it1; break; case -1: ++it3; break; } } #ifdef SE_ENABLE_TRIGGERS apply_per_statement_triggers(&arg1seq, false, NULL, false, TRIGGER_BEFORE, TRIGGER_REPLACE_EVENT); #endif arg3seq.clear(); xptr_sequence::iterator it = arg1seq.begin(); xptr_sequence::iterator sit = arg2seq.begin(); int ctr=0; do { tuple tup(2); /* arg3seq will contain pairs: node -> int, namely * node to be replaced -> place in sequence of nodes to replace with */ tup.copy(tuple_cell::node(indirectionDereferenceCP(*it)),tuple_cell((int64_t)ctr)); arg3seq.add(tup); /* XNULL separates nodes in arg2seq (nodes replace with) per each * node in arg1seq (nodes to be replaced) */ while(*sit!=XNULL) { sit++; ctr++; } sit++; ctr++; it++; } while (it != arg1seq.end()); arg3seq.sort(); it3=arg3seq.begin(); descript_sequence arg4seq(2); do { node=(*it3).cells[0].get_node(); tuple t=(*it3); t.cells[0].set_safenode(node); ++it3; arg4seq.add(t); } while (it3!=arg3seq.end()); /* Deleting, inserting new nodes */ it3 = arg4seq.end(); do { --it3; node = old_node = (*it3).cells[0].get_safenode(); int pos=(*it3).cells[1].get_xs_integer(); sit=arg2seq.begin()+pos; CHECKP(node); xptr leftn=nodeGetLeftSibling(old_node); xptr rightn=nodeGetRightSibling(old_node); xptr par_ind= nodeGetParentIndirection(old_node); bool a_m=is_node_attribute(node); bool d_m=a_m||is_node_text(node); #ifdef SE_ENABLE_TRIGGERS CHECKP(old_node); scm_node = getSchemaPointer(old_node); parent= nodeGetParent(old_node); CHECKP(old_node); tmp_node = prepare_old_node(old_node, scm_node, TRIGGER_REPLACE_EVENT); /* Before-for-each-node triggers (cycle for all inserted nodes) */ xptr_sequence::iterator tr_it=sit; while(*tr_it!=XNULL) { node_child=*tr_it; parent=indirectionDereferenceCP(par_ind); if(apply_per_node_triggers(indirectionDereferenceCP(node_child), old_node, parent, scm_node, TRIGGER_BEFORE, TRIGGER_REPLACE_EVENT) == XNULL) goto next_replacement; tr_it++; } #endif //pre_deletion if (d_m) { delete_node(old_node); } //1.inserting attributes from sequence while(*sit != XNULL) { node_child = *sit; if (is_node_attribute(indirectionDereferenceCP(node_child))) { parent = indirectionDereferenceCP(par_ind); attr_node=deep_copy_node(XNULL, XNULL, parent, indirectionDereferenceCP(node_child), is_node_persistent(node_child) ? NULL : &ins_swiz, true); #ifdef SE_ENABLE_TRIGGERS apply_per_node_triggers(attr_node, tmp_node, parent, scm_node, TRIGGER_AFTER, TRIGGER_REPLACE_EVENT); #endif } sit++; } //2. finding place of insertion if (a_m) { node= getFirstChildNode(indirectionDereferenceCP(par_ind)); if (node!=XNULL) { CHECKP(node); if (is_node_element(node)) { rightn=node; node=XNULL; } else { rightn=XNULL; } } } else { if (d_m) { if (rightn==XNULL) node=leftn; else node=XNULL; } } //3.main insert cycle sit = arg2seq.begin() + pos; while(*sit != XNULL) { node_child = *sit; if (!is_node_attribute(indirectionDereferenceCP(node_child))) { parent = indirectionDereferenceCP(par_ind); node = deep_copy_node(node, rightn, parent, indirectionDereferenceCP(node_child), is_node_persistent(node_child) ? NULL : &ins_swiz, true); #ifdef SE_ENABLE_TRIGGERS apply_per_node_triggers(node, tmp_node, indirectionDereferenceCP(par_ind), scm_node, TRIGGER_AFTER, TRIGGER_REPLACE_EVENT); #endif } sit++; } //post_deletion if (!d_m) { del_node = (*it3).cells[0].get_safenode(); CHECKP(del_node); delete_node(del_node); } next_replacement:; } while (it3!=arg4seq.begin()); if (ins_swiz!=NULL) { delete ins_swiz; } #ifdef SE_ENABLE_FTSEARCH execute_modifications(); #endif #ifdef SE_ENABLE_TRIGGERS apply_per_statement_triggers(NULL, false, NULL, false, TRIGGER_AFTER, TRIGGER_REPLACE_EVENT); #endif } <commit_msg>CHECKP fixed in replace + small refactoring<commit_after>/* * File: other_updates.cpp * Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS) */ #include "common/sedna.h" #include "tr/updates/updates.h" #include "tr/executor/base/xptr_sequence.h" #include "tr/mo/mo.h" #include "tr/auth/auc.h" #include "tr/locks/locks.h" #ifdef SE_ENABLE_TRIGGERS #include "tr/triggers/triggers.h" #endif #include "tr/structures/nodeutils.h" #include "tr/structures/textcptr.h" void replace(PPOpIn arg) { xptr node, tmp_node, attr_node; schema_node_xptr scm_node; tuple t(arg.ts); xptr_sequence arg1seq; // Indirection of nodes which are going to be replaced xptr_sequence arg1seq_tmp; // Nodes which are going to be replaced xptr_sequence arg2seq; // Nodes to replace with (both persistent and temp) /* Persistent nodes to replace with (+ theirs position in arg2seq) */ descript_sequence arg3seq(2); upd_ns_map* ins_swiz = NULL; bool is_node_updated = true; /* * Fill up sequences with nodes to update and update with, * child (arg) returns the following sequence of items: * 1. node to be replaced (1) * 2. nodes to replace with (2) * 3. special tuple which contains separator value (3) */ arg.op->next(t); while (!t.is_eos()) { if (t.cells[0].is_node()) { node = t.cells[0].get_node(); CHECKP(node); /* * In (1) case node must be persistent (is_node_updated is true) * In (2) case it can be temporary * In both cases document nodes are not allowed */ if ((!is_node_updated || is_node_persistent(node)) && !is_node_document(node)) { xptr indir = nodeGetIndirection(node); if (is_node_updated) { /* Case (1) - fill up sequence with nodes to be replaced */ is_node_updated=false; /* Next nodes from arg are case (2) nodes, so we can use shared lock */ local_lock_mrg->lock(lm_s); arg1seq.add(indir); arg1seq_tmp.add(node); } else { /* Case (2) - fill up sequence with nodes to replace with */ if (is_node_persistent(node)) { tuple tup(2); tup.copy(tuple_cell::node(node),tuple_cell((int64_t)(arg2seq.size()))); arg3seq.add(tup); } arg2seq.add(indir); } } #ifndef IGNORE_UPDATE_ERRORS else { throw USER_EXCEPTION(SE2020); } #endif } else { /* Must be separator in this case (3) */ if (t.cells[0].get_atomic_type() == se_separator) { arg2seq.add(XNULL); is_node_updated=true; /* Next nodes from arg are case (1) node, so we can use shared lock */ local_lock_mrg->lock(lm_x); } #ifndef IGNORE_UPDATE_ERRORS else throw USER_EXCEPTION(SE2021); #endif } arg.op->next(t); } /* Nothing to do in this case */ if (arg1seq.size()<=0) return; /* Checking authorization */ if (is_auth_check_needed(REPLACE_STATEMENT)) auth_for_update(&arg1seq, REPLACE_STATEMENT, false); /* Find all common nodes in agr3seq (nodes to replace with) and * arg1seq_tmp (nodes to be replaced). Make a copy of all such nodes. */ arg1seq_tmp.sort(); arg3seq.sort(); descript_sequence::iterator it3 = arg3seq.begin(); xptr_sequence::iterator it1 = arg1seq_tmp.begin(); while(it3 != arg3seq.end() && it1 != arg1seq_tmp.end()) { switch(nid_cmp_effective((*it3).cells[0].get_node(), *it1)) { case 0: case -2: { node = copy_to_temp((*it3).cells[0].get_node()); xptr indir=nodeGetIndirection(node); arg2seq.set(indir,(*it3).cells[1].get_xs_integer()); ++it3; } break; case 1: ++it1; break; case 2: ++it1; break; case -1: ++it3; break; } } #ifdef SE_ENABLE_TRIGGERS apply_per_statement_triggers(&arg1seq, false, NULL, false, TRIGGER_BEFORE, TRIGGER_REPLACE_EVENT); #endif arg3seq.clear(); xptr_sequence::iterator it = arg1seq.begin(); xptr_sequence::iterator sit = arg2seq.begin(); int ctr=0; do { tuple tup(2); /* arg3seq will contain pairs: node -> int, namely * node to be replaced -> place in sequence of nodes to replace with */ tup.copy(tuple_cell::node(indirectionDereferenceCP(*it)),tuple_cell((int64_t)ctr)); arg3seq.add(tup); /* XNULL separates nodes in arg2seq (nodes replace with) per each * node in arg1seq (nodes to be replaced) */ while(*sit!=XNULL) { sit++; ctr++; } sit++; ctr++; it++; } while (it != arg1seq.end()); arg3seq.sort(); it3=arg3seq.begin(); descript_sequence arg4seq(2); do { node = (*it3).cells[0].get_node(); tuple t = (*it3); t.cells[0].set_safenode(node); ++it3; arg4seq.add(t); } while (it3!=arg3seq.end()); /* Deleting, inserting new nodes */ it3 = arg4seq.end(); do { --it3; node = (*it3).cells[0].get_safenode(); int pos = (*it3).cells[1].get_xs_integer(); sit = arg2seq.begin() + pos; CHECKP(node); xptr leftn = nodeGetLeftSibling(node); xptr rightn = nodeGetRightSibling(node); xptr par_ind = nodeGetParentIndirection(node); bool a_m = is_node_attribute(node); bool d_m = a_m || is_node_text(node); #ifdef SE_ENABLE_TRIGGERS scm_node = getSchemaPointer(node); tmp_node = prepare_old_node(node, scm_node, TRIGGER_REPLACE_EVENT); /* Before-for-each-node triggers (cycle for all inserted nodes) */ xptr_sequence::iterator tr_it = sit; while(*tr_it != XNULL) { if(apply_per_node_triggers(indirectionDereferenceCP(*tr_it), node, indirectionDereferenceCP(par_ind), scm_node, TRIGGER_BEFORE, TRIGGER_REPLACE_EVENT) == XNULL) { goto next_replacement; } tr_it++; } #endif /* SE_ENABLE_TRIGGERS */ //pre_deletion if (d_m) { delete_node(node); } //1.inserting attributes from sequence while(*sit != XNULL) { xptr node_child = indirectionDereferenceCP(*sit); if (is_node_attribute(node_child)) { attr_node = deep_copy_node(XNULL, XNULL, indirectionDereferenceCP(par_ind), node_child, is_node_persistent(node_child) ? NULL : &ins_swiz, true); #ifdef SE_ENABLE_TRIGGERS apply_per_node_triggers(attr_node, tmp_node, indirectionDereferenceCP(par_ind), scm_node, TRIGGER_AFTER, TRIGGER_REPLACE_EVENT); #endif } sit++; } //2. finding place of insertion if (a_m) { node = getFirstChildNode(indirectionDereferenceCP(par_ind)); if (node != XNULL) { CHECKP(node); if (is_node_element(node)) { rightn=node; node=XNULL; } else { rightn=XNULL; } } } else { if (d_m) { if (rightn==XNULL) node=leftn; else node=XNULL; } } //3.main insert cycle sit = arg2seq.begin() + pos; while(*sit != XNULL) { xptr node_child = indirectionDereferenceCP(*sit); CHECKP(node_child); if (!is_node_attribute(node_child)) { node = deep_copy_node(node, rightn, indirectionDereferenceCP(par_ind), node_child, is_node_persistent(node_child) ? NULL : &ins_swiz, true); #ifdef SE_ENABLE_TRIGGERS apply_per_node_triggers(node, tmp_node, indirectionDereferenceCP(par_ind), scm_node, TRIGGER_AFTER, TRIGGER_REPLACE_EVENT); #endif } sit++; } //post_deletion if (!d_m) { xptr del_node = (*it3).cells[0].get_safenode(); delete_node(del_node); } next_replacement:; } while (it3 != arg4seq.begin()); if (ins_swiz != NULL) { delete ins_swiz; } #ifdef SE_ENABLE_FTSEARCH execute_modifications(); #endif #ifdef SE_ENABLE_TRIGGERS apply_per_statement_triggers(NULL, false, NULL, false, TRIGGER_AFTER, TRIGGER_REPLACE_EVENT); #endif } <|endoftext|>
<commit_before>// // conflict.cpp // Parse // // Created by Andrew Hunter on 04/06/2011. // Copyright 2011 __MyCompanyName__. All rights reserved. // #include "conflict.h" using namespace std; using namespace contextfree; using namespace lr; /// \brief Creates a new conflict object (describing a non-conflict) conflict::conflict(int stateId, const item_container& token) : m_StateId(stateId) , m_Token(token) { } /// \brief Copy constructor conflict::conflict(const conflict& copyFrom) : m_StateId(copyFrom.m_StateId) , m_Token(copyFrom.m_Token) , m_Shift(copyFrom.m_Shift) , m_Reduce(copyFrom.m_Reduce) { } /// \brief Destroys this conflict object conflict::~conflict() { } /// \brief Clones this conflict conflict* conflict::clone() const { return new conflict(*this); } /// \brief Returns true if conflict a is less than conflict b bool conflict::compare(const conflict* a, const conflict* b) { if (a == b) return false; if (!a) return true; if (!b) return false; return (*a) < (*b); } /// \brief Orders this conflict relative to another bool conflict::operator<(const conflict& compareTo) const { if (m_StateId < compareTo.m_StateId) return true; if (m_StateId > compareTo.m_StateId) return false; if (m_Token < compareTo.m_Token) return true; if (m_Token > compareTo.m_Token) return false; if (m_Shift < compareTo.m_Shift) return true; if (m_Shift > compareTo.m_Shift) return false; if (m_Reduce < compareTo.m_Reduce) return true; return false; } /// \brief Adds an LR(0) item that will be followed if the token is shifted void conflict::add_shift_item(const lr0_item_container& item) { m_Shift.insert(item); } /// \brief Adds an LR(0) item that will be reduced if the token is in the lookahead /// /// This returns an item that the caller can add the set of reduce states for this item conflict::possible_reduce_states& conflict::add_reduce_item(const lr0_item_container& item) { return m_Reduce[item]; } /// \brief Adds the conflicts found in a single state of the specified LALR builder to the given target list static void find_conflicts(const lalr_builder& builder, int stateId, conflict_list& target) { // Get the actions in this state const lr_action_set& actions = builder.actions_for_state(stateId); // Run through these actions, and find places where there are conflicts (two actions for a single symbol) typedef map<item_container, lr_action_set> items_to_actions; items_to_actions actionsForItem; for (lr_action_set::const_iterator nextAction = actions.begin(); nextAction != actions.end(); nextAction++) { // Ignore actions that don't cause conflicts bool ignore; switch ((*nextAction)->type()) { case lr_action::act_goto: case lr_action::act_ignore: case lr_action::act_accept: ignore = true; break; default: ignore = false; break; } if (ignore) continue; // Add this as an action for this item actionsForItem[(*nextAction)->item()].insert(*nextAction); } // Generate conflicts for any item with multiple actions for (items_to_actions::iterator nextItem = actionsForItem.begin(); nextItem != actionsForItem.end(); nextItem++) { // Ignore items with just one action (or no actions, if that's ever possible) if (nextItem->second.size() < 2) continue; // Ignore items if all but one of the items are 'weak' int numWeak = 0; for (lr_action_set::const_iterator nextAction = nextItem->second.begin(); nextAction != nextItem->second.end(); nextAction++) { switch ((*nextAction)->type()) { case lr_action::act_weakreduce: case lr_action::act_ignore: numWeak++; break; default: break; } } if (nextItem->second.size() - numWeak < 2) continue; // Create a new conflict for this action const item_container& conflictToken = *nextItem->first; conflict_container newConf(new conflict(stateId, conflictToken), true); // Fetch the items in this state const lalr_state& thisState = *builder.machine().state_with_id(stateId); // Get the closure of this state lr1_item_set closure; builder.generate_closure(thisState, closure); // Describe the actions resulting in this conflict by going through the items in the closure of the state const grammar* gram = &builder.gram(); // Iterate through the closure to get the items that can be shifted as part of this conflict for (lr1_item_set::const_iterator nextItem = closure.begin(); nextItem != closure.end(); nextItem++) { if (!(*nextItem)->at_end()) { // This item will result in a shift: add it to the list if it can shift our item const item_set& firstItems = gram->first((*nextItem)->rule()->items()[(*nextItem)->offset()]); if (firstItems.find(conflictToken) != firstItems.end()) { // This item can result in a shift of the specified token newConf->add_shift_item(**nextItem); } } } // Iterate through the closure to find the items that can be reduced as part of this conflict for (lr1_item_set::const_iterator nextItem = closure.begin(); nextItem != closure.end(); nextItem++) { if ((*nextItem)->at_end()) { // This item will result in a reduction, depending on its lookahead const lr1_item::lookahead_set& la = (*nextItem)->lookahead(); if (la.find(conflictToken) != la.end()) { // The conflicted token is in the lookahead: add this to the conflict list conflict::possible_reduce_states& reduceTo = newConf->add_reduce_item(**nextItem); // TODO: fill in the set of items that this can reduce to } } } // Add the new conflict to the list target.push_back(newConf); } } /// \brief Adds the conflicts found in the specified LALR builder object to the passed in list void conflict::find_conflicts(const lalr_builder& builder, conflict_list& target) { // Iterate through the states in the builder for (int stateId=0; stateId < builder.count_states(); stateId++) { ::find_conflicts(builder, stateId, target); } } <commit_msg>Added a TODO note about some stuff that can go wrong<commit_after>// // conflict.cpp // Parse // // Created by Andrew Hunter on 04/06/2011. // Copyright 2011 __MyCompanyName__. All rights reserved. // #include "conflict.h" using namespace std; using namespace contextfree; using namespace lr; /// \brief Creates a new conflict object (describing a non-conflict) conflict::conflict(int stateId, const item_container& token) : m_StateId(stateId) , m_Token(token) { } /// \brief Copy constructor conflict::conflict(const conflict& copyFrom) : m_StateId(copyFrom.m_StateId) , m_Token(copyFrom.m_Token) , m_Shift(copyFrom.m_Shift) , m_Reduce(copyFrom.m_Reduce) { } /// \brief Destroys this conflict object conflict::~conflict() { } /// \brief Clones this conflict conflict* conflict::clone() const { return new conflict(*this); } /// \brief Returns true if conflict a is less than conflict b bool conflict::compare(const conflict* a, const conflict* b) { if (a == b) return false; if (!a) return true; if (!b) return false; return (*a) < (*b); } /// \brief Orders this conflict relative to another bool conflict::operator<(const conflict& compareTo) const { if (m_StateId < compareTo.m_StateId) return true; if (m_StateId > compareTo.m_StateId) return false; if (m_Token < compareTo.m_Token) return true; if (m_Token > compareTo.m_Token) return false; if (m_Shift < compareTo.m_Shift) return true; if (m_Shift > compareTo.m_Shift) return false; if (m_Reduce < compareTo.m_Reduce) return true; return false; } /// \brief Adds an LR(0) item that will be followed if the token is shifted void conflict::add_shift_item(const lr0_item_container& item) { m_Shift.insert(item); } /// \brief Adds an LR(0) item that will be reduced if the token is in the lookahead /// /// This returns an item that the caller can add the set of reduce states for this item conflict::possible_reduce_states& conflict::add_reduce_item(const lr0_item_container& item) { return m_Reduce[item]; } /// \brief Adds the conflicts found in a single state of the specified LALR builder to the given target list static void find_conflicts(const lalr_builder& builder, int stateId, conflict_list& target) { // Get the actions in this state const lr_action_set& actions = builder.actions_for_state(stateId); // Run through these actions, and find places where there are conflicts (two actions for a single symbol) typedef map<item_container, lr_action_set> items_to_actions; items_to_actions actionsForItem; for (lr_action_set::const_iterator nextAction = actions.begin(); nextAction != actions.end(); nextAction++) { // Ignore actions that don't cause conflicts bool ignore; switch ((*nextAction)->type()) { case lr_action::act_goto: case lr_action::act_ignore: case lr_action::act_accept: ignore = true; break; default: ignore = false; break; } if (ignore) continue; // Add this as an action for this item actionsForItem[(*nextAction)->item()].insert(*nextAction); } // Generate conflicts for any item with multiple actions for (items_to_actions::iterator nextItem = actionsForItem.begin(); nextItem != actionsForItem.end(); nextItem++) { // Ignore items with just one action (or no actions, if that's ever possible) if (nextItem->second.size() < 2) continue; // Ignore items if all but one of the items are 'weak' int numWeak = 0; for (lr_action_set::const_iterator nextAction = nextItem->second.begin(); nextAction != nextItem->second.end(); nextAction++) { switch ((*nextAction)->type()) { case lr_action::act_weakreduce: case lr_action::act_ignore: numWeak++; break; default: break; } } if (nextItem->second.size() - numWeak < 2) continue; // Create a new conflict for this action const item_container& conflictToken = *nextItem->first; conflict_container newConf(new conflict(stateId, conflictToken), true); // Fetch the items in this state const lalr_state& thisState = *builder.machine().state_with_id(stateId); // Get the closure of this state lr1_item_set closure; builder.generate_closure(thisState, closure); // Describe the actions resulting in this conflict by going through the items in the closure of the state const grammar* gram = &builder.gram(); // Iterate through the closure to get the items that can be shifted as part of this conflict for (lr1_item_set::const_iterator nextItem = closure.begin(); nextItem != closure.end(); nextItem++) { if (!(*nextItem)->at_end()) { // This item will result in a shift: add it to the list if it can shift our item const item_set& firstItems = gram->first((*nextItem)->rule()->items()[(*nextItem)->offset()]); if (firstItems.find(conflictToken) != firstItems.end()) { // This item can result in a shift of the specified token newConf->add_shift_item(**nextItem); } } } // Iterate through the closure to find the items that can be reduced as part of this conflict for (lr1_item_set::const_iterator nextItem = closure.begin(); nextItem != closure.end(); nextItem++) { if ((*nextItem)->at_end()) { // This item will result in a reduction, depending on its lookahead const lr1_item::lookahead_set& la = (*nextItem)->lookahead(); if (la.find(conflictToken) != la.end()) { // The conflicted token is in the lookahead: add this to the conflict list conflict::possible_reduce_states& reduceTo = newConf->add_reduce_item(**nextItem); // TODO: fill in the set of items that this can reduce to // TODO: if the reduction is not in a kernel item (which probably means that we've got an empty production), then we need to be able to trace these as well. } } } // Add the new conflict to the list target.push_back(newConf); } } /// \brief Adds the conflicts found in the specified LALR builder object to the passed in list void conflict::find_conflicts(const lalr_builder& builder, conflict_list& target) { // Iterate through the states in the builder for (int stateId=0; stateId < builder.count_states(); stateId++) { ::find_conflicts(builder, stateId, target); } } <|endoftext|>
<commit_before>/* gdnet_peer.cpp */ #include "gdnet_peer.h" GDNetPeer::GDNetPeer(GDNetHost* host, ENetPeer* peer) : _host(host), _peer(peer) { _host->reference(); } GDNetPeer::~GDNetPeer() { _host->unreference(); } int GDNetPeer::get_peer_id() { ERR_FAIL_COND_V(_host->_host == NULL, -1); return (int)(_peer - _host->_host->peers); } Ref<GDNetAddress> GDNetPeer::get_address() { Ref<GDNetAddress> address = memnew(GDNetAddress); address->set_port(_peer->address.port); char ip[64]; enet_address_get_host_ip(&_peer->address, ip, 64); address->set_host(ip); return address; } int GDNetPeer::get_avg_rtt() { ERR_FAIL_COND_V(_host->_host == NULL, -1); return _peer->roundTripTime; } void GDNetPeer::ping() { ERR_FAIL_COND(_host->_host == NULL); while (true) { if (_host->_mutex->try_lock() == 0) { enet_peer_ping(_peer); _host->_mutex->unlock(); break; } } } void GDNetPeer::reset() { ERR_FAIL_COND(_host->_host == NULL); while (true) { if (_host->_mutex->try_lock() == 0) { enet_peer_reset(_peer); _host->_mutex->unlock(); break; } } } void GDNetPeer::disconnect(int data) { ERR_FAIL_COND(_host->_host == NULL); while (true) { if (_host->_mutex->try_lock() == 0) { enet_peer_disconnect(_peer, data); _host->_mutex->unlock(); break; } } } void GDNetPeer::disconnect_later(int data) { ERR_FAIL_COND(_host->_host == NULL); while (true) { if (_host->_mutex->try_lock() == 0) { enet_peer_disconnect_later(_peer, data); _host->_mutex->unlock(); break; } } } void GDNetPeer::disconnect_now(int data) { ERR_FAIL_COND(_host->_host == NULL); while (true) { if (_host->_mutex->try_lock() == 0) { enet_peer_disconnect_now(_peer, data); _host->_mutex->unlock(); break; } } } void GDNetPeer::send_packet(const ByteArray& packet, int channel_id, int type) { ERR_FAIL_COND(_host->_host == NULL); GDNetMessage* message = memnew(GDNetMessage((GDNetMessage::Type)type)); message->set_peer_id(get_peer_id()); message->set_channel_id(channel_id); message->set_packet(packet); _host->_message_queue.push(message); } void GDNetPeer::send_var(const Variant& var, int channel_id, int type) { ERR_FAIL_COND(_host->_host == NULL); int len; Error err = encode_variant(var, NULL, len); ERR_FAIL_COND(err != OK || len == 0); GDNetMessage* message = memnew(GDNetMessage((GDNetMessage::Type)type)); message->set_peer_id(get_peer_id()); message->set_channel_id(channel_id); ByteArray packet; packet.resize(len); ByteArray::Write w = packet.write(); err = encode_variant(var, w.ptr(), len); ERR_FAIL_COND(err != OK); message->set_packet(packet); _host->_message_queue.push(message); } void GDNetPeer::set_timeout(int limit, int min_timeout, int max_timeout) { enet_peer_timeout(_peer, limit, min_timeout, max_timeout); } void GDNetPeer::_bind_methods() { ObjectTypeDB::bind_method("get_peer_id", &GDNetPeer::get_peer_id); ObjectTypeDB::bind_method("get_address", &GDNetPeer::get_address); ObjectTypeDB::bind_method("get_avg_rtt", &GDNetPeer::get_avg_rtt); ObjectTypeDB::bind_method("ping", &GDNetPeer::ping); ObjectTypeDB::bind_method("reset", &GDNetPeer::reset); ObjectTypeDB::bind_method("disconnect", &GDNetPeer::disconnect,DEFVAL(0)); ObjectTypeDB::bind_method("disconnect_later", &GDNetPeer::disconnect_later,DEFVAL(0)); ObjectTypeDB::bind_method("disconnect_now", &GDNetPeer::disconnect_now,DEFVAL(0)); ObjectTypeDB::bind_method("send_packet", &GDNetPeer::send_packet,DEFVAL(0),DEFVAL(GDNetMessage::UNSEQUENCED)); ObjectTypeDB::bind_method("send_var", &GDNetPeer::send_var,DEFVAL(0),DEFVAL(GDNetMessage::UNSEQUENCED)); ObjectTypeDB::bind_method("set_timeout", &GDNetPeer::set_timeout); } <commit_msg>Added locking for set_timeout<commit_after>/* gdnet_peer.cpp */ #include "gdnet_peer.h" GDNetPeer::GDNetPeer(GDNetHost* host, ENetPeer* peer) : _host(host), _peer(peer) { _host->reference(); } GDNetPeer::~GDNetPeer() { _host->unreference(); } int GDNetPeer::get_peer_id() { ERR_FAIL_COND_V(_host->_host == NULL, -1); return (int)(_peer - _host->_host->peers); } Ref<GDNetAddress> GDNetPeer::get_address() { Ref<GDNetAddress> address = memnew(GDNetAddress); address->set_port(_peer->address.port); char ip[64]; enet_address_get_host_ip(&_peer->address, ip, 64); address->set_host(ip); return address; } int GDNetPeer::get_avg_rtt() { ERR_FAIL_COND_V(_host->_host == NULL, -1); return _peer->roundTripTime; } void GDNetPeer::ping() { ERR_FAIL_COND(_host->_host == NULL); while (true) { if (_host->_mutex->try_lock() == 0) { enet_peer_ping(_peer); _host->_mutex->unlock(); break; } } } void GDNetPeer::reset() { ERR_FAIL_COND(_host->_host == NULL); while (true) { if (_host->_mutex->try_lock() == 0) { enet_peer_reset(_peer); _host->_mutex->unlock(); break; } } } void GDNetPeer::disconnect(int data) { ERR_FAIL_COND(_host->_host == NULL); while (true) { if (_host->_mutex->try_lock() == 0) { enet_peer_disconnect(_peer, data); _host->_mutex->unlock(); break; } } } void GDNetPeer::disconnect_later(int data) { ERR_FAIL_COND(_host->_host == NULL); while (true) { if (_host->_mutex->try_lock() == 0) { enet_peer_disconnect_later(_peer, data); _host->_mutex->unlock(); break; } } } void GDNetPeer::disconnect_now(int data) { ERR_FAIL_COND(_host->_host == NULL); while (true) { if (_host->_mutex->try_lock() == 0) { enet_peer_disconnect_now(_peer, data); _host->_mutex->unlock(); break; } } } void GDNetPeer::send_packet(const ByteArray& packet, int channel_id, int type) { ERR_FAIL_COND(_host->_host == NULL); GDNetMessage* message = memnew(GDNetMessage((GDNetMessage::Type)type)); message->set_peer_id(get_peer_id()); message->set_channel_id(channel_id); message->set_packet(packet); _host->_message_queue.push(message); } void GDNetPeer::send_var(const Variant& var, int channel_id, int type) { ERR_FAIL_COND(_host->_host == NULL); int len; Error err = encode_variant(var, NULL, len); ERR_FAIL_COND(err != OK || len == 0); GDNetMessage* message = memnew(GDNetMessage((GDNetMessage::Type)type)); message->set_peer_id(get_peer_id()); message->set_channel_id(channel_id); ByteArray packet; packet.resize(len); ByteArray::Write w = packet.write(); err = encode_variant(var, w.ptr(), len); ERR_FAIL_COND(err != OK); message->set_packet(packet); _host->_message_queue.push(message); } void GDNetPeer::set_timeout(int limit, int min_timeout, int max_timeout) { ERR_FAIL_COND(_host->_host == NULL); while (true) { if (_host->_mutex->try_lock() == 0) { enet_peer_timeout(_peer, limit, min_timeout, max_timeout); _host->_mutex->unlock(); break; } } } void GDNetPeer::_bind_methods() { ObjectTypeDB::bind_method("get_peer_id", &GDNetPeer::get_peer_id); ObjectTypeDB::bind_method("get_address", &GDNetPeer::get_address); ObjectTypeDB::bind_method("get_avg_rtt", &GDNetPeer::get_avg_rtt); ObjectTypeDB::bind_method("ping", &GDNetPeer::ping); ObjectTypeDB::bind_method("reset", &GDNetPeer::reset); ObjectTypeDB::bind_method("disconnect", &GDNetPeer::disconnect,DEFVAL(0)); ObjectTypeDB::bind_method("disconnect_later", &GDNetPeer::disconnect_later,DEFVAL(0)); ObjectTypeDB::bind_method("disconnect_now", &GDNetPeer::disconnect_now,DEFVAL(0)); ObjectTypeDB::bind_method("send_packet", &GDNetPeer::send_packet,DEFVAL(0),DEFVAL(GDNetMessage::UNSEQUENCED)); ObjectTypeDB::bind_method("send_var", &GDNetPeer::send_var,DEFVAL(0),DEFVAL(GDNetMessage::UNSEQUENCED)); ObjectTypeDB::bind_method("set_timeout", &GDNetPeer::set_timeout); } <|endoftext|>
<commit_before>// @(#)root/test:$Name: $:$Id: MainEvent.cxx,v 1.8 2001/01/15 01:28:08 rdm Exp $ // Author: Rene Brun 19/01/97 //////////////////////////////////////////////////////////////////////// // // A simple example with a ROOT tree // ================================= // // This program creates : // - a ROOT file // - a tree // Additional arguments can be passed to the program to control the flow // of execution. (see comments describing the arguments in the code). // Event nevent comp split fill // All arguments are optional: Default is // Event 400 1 1 1 // // In this example, the tree consists of one single "super branch" // The statement ***tree->Branch("event", event, 64000,split);*** below // will parse the structure described in Event.h and will make // a new branch for each data member of the class if split is set to 1. // - 5 branches corresponding to the basic types fNtrack,fNseg,fNvertex // ,fFlag and fTemperature. // - 3 branches corresponding to the members of the subobject EventHeader. // - one branch for each data member of the class Track of TClonesArray. // - one branch for the object fH (histogram of class TH1F). // // if split = 0 only one single branch is created and the complete event // is serialized in one single buffer. // if comp = 0 no compression at all. // if comp = 1 event is compressed. // if comp = 2 same as 1. In addition branches with floats in the TClonesArray // are also compressed. // The 4th argument fill can be set to 0 if one wants to time // the percentage of time spent in creating the event structure and // not write the event in the file. // In this example, one loops over nevent events. // The branch "event" is created at the first event. // The branch address is set for all other events. // For each event, the event header is filled and ntrack tracks // are generated and added to the TClonesArray list. // For each event the event histogram is saved as well as the list // of all tracks. // // The number of events can be given as the first argument to the program. // By default 400 events are generated. // The compression option can be activated/deactivated via the second argument. // // ---Running/Linking instructions---- // This program consists of the following files and procedures. // - Event.h event class description // - Event.C event class implementation // - MainEvent.C the main program to demo this class might be used (this file) // - EventCint.C the CINT dictionary for the event and Track classes // this file is automatically generated by rootcint (see Makefile), // when the class definition in Event.h is modified. // // ---Analyzing the Event.root file with the interactive root // example of a simple session // Root > TFile f("Event.root") // Root > T.Draw("fNtrack") //histogram the number of tracks per event // Root > T.Draw("fPx") //histogram fPx for all tracks in all events // Root > T.Draw("fXfirst:fYfirst","fNtrack>600") // //scatter-plot for x versus y of first point of each track // Root > T.Draw("fH.GetRMS()") //histogram of the RMS of the event histogram // // Look also in the same directory at the following macros: // - eventa.C an example how to read the tree // - eventb.C how to read events conditionally // //////////////////////////////////////////////////////////////////////// #include <stdlib.h> #include "TROOT.h" #include "TFile.h" #include "TNetFile.h" #include "TRandom.h" #include "TTree.h" #include "TBranch.h" #include "TClonesArray.h" #include "TStopwatch.h" #include "Event.h" //______________________________________________________________________________ int main(int argc, char **argv) { TROOT simple("simple","Example of creation of a tree"); Int_t nevent = 400; // by default create 400 events Int_t comp = 1; // by default file is compressed Int_t split = 1; // by default, split Event in sub branches Int_t write = 1; // by default the tree is filled Int_t hfill = 0; // by default histograms are not filled Int_t read = 0; Int_t arg4 = 1; Int_t arg5 = 600; //default number of tracks per event Int_t netf = 0; if (argc > 1) nevent = atoi(argv[1]); if (argc > 2) comp = atoi(argv[2]); if (argc > 3) split = atoi(argv[3]); if (argc > 4) arg4 = atoi(argv[4]); if (argc > 5) arg5 = atoi(argv[5]); if (arg4 == 0) { write = 0; hfill = 0; read = 1;} if (arg4 == 1) { write = 1; hfill = 0;} if (arg4 == 2) { write = 0; hfill = 0;} if (arg4 == 10) { write = 0; hfill = 1;} if (arg4 == 11) { write = 1; hfill = 1;} if (arg4 == 20) { write = 0; read = 1;} //read sequential if (arg4 == 25) { write = 0; read = 2;} //read random if (arg4 >= 30) { netf = 1; } //use TNetFile if (arg4 == 30) { write = 0; read = 1;} //netfile + read sequential if (arg4 == 35) { write = 0; read = 2;} //netfile + read random if (arg4 == 36) { write = 1; } //netfile + write sequential TFile *hfile; TTree *tree; Event *event = 0; // Fill event, header and tracks with some random numbers // Create a timer object to benchmark this loop TStopwatch timer; timer.Start(); Int_t nb = 0; Int_t ev; Int_t bufsize; Double_t told = 0; Double_t tnew = 0; Int_t printev = 100; if (arg5 < 100) printev = 1000; if (arg5 < 10) printev = 10000; Track::Class()->IgnoreTObjectStreamer(); Track::Class()->BypassStreamer(); // Read case if (read) { if (netf) { hfile = new TNetFile("root://localhost/root/test/EventNet.root"); hfile->UseCache(10); } else hfile = new TFile("Event.root"); tree = (TTree*)hfile->Get("T"); TBranch *branch = tree->GetBranch("event"); branch->SetAddress(&event); Int_t nentries = (Int_t)tree->GetEntries(); nevent = TMath::Max(nevent,nentries); if (read == 1) { //read sequential for (ev = 0; ev < nevent; ev++) { if (ev%printev == 0) { tnew = timer.RealTime(); printf("event:%d, rtime=%f s\n",ev,tnew-told); told=tnew; timer.Continue(); } nb += tree->GetEntry(ev); //read complete event in memory } } else { //read random Int_t evrandom; for (ev = 0; ev < nevent; ev++) { if (ev%printev == 0) cout<<"event="<<ev<<endl; evrandom = Int_t(nevent*gRandom->Rndm(1)); nb += tree->GetEntry(evrandom); //read complete event in memory } } } else { // Write case // Create a new ROOT binary machine independent file. // Note that this file may contain any kind of ROOT objects, histograms, // pictures, graphics objects, detector geometries, tracks, events, etc.. // This file is now becoming the current directory. if (netf) { hfile = new TNetFile("root://localhost/root/test/EventNet.root","RECREATE","TTree benchmark ROOT file"); hfile->UseCache(10); } else hfile = new TFile("Event.root","RECREATE","TTree benchmark ROOT file"); hfile->SetCompressionLevel(comp); // Create histogram to show write_time in function of time Float_t curtime = -0.5; Int_t ntime = nevent/printev; TH1F *htime = new TH1F("htime","Real-Time to write versus time",ntime,0,ntime); HistogramManager *hm = 0; if (hfill) { TDirectory *hdir = new TDirectory("histograms", "all histograms"); hm = new HistogramManager(hdir); } // Create a ROOT Tree and one superbranch TTree *tree = new TTree("T","An example of a ROOT tree"); tree->SetAutoSave(1000000000); // autosave when 1 Gbyte written bufsize = 64000; if (split) bufsize /= 4; event = new Event(); TBranch *branch = tree->Bronch("event", "Event", &event, bufsize,split); branch->SetAutoDelete(kFALSE); char etype[20]; for (ev = 0; ev < nevent; ev++) { if (ev%printev == 0) { tnew = timer.RealTime(); printf("event:%d, rtime=%f s\n",ev,tnew-told); htime->Fill(curtime,tnew-told); curtime += 1; told=tnew; timer.Continue(); } Float_t sigmat, sigmas; gRandom->Rannor(sigmat,sigmas); Int_t ntrack = Int_t(arg5 +arg5*sigmat/120.); Float_t random = gRandom->Rndm(1); sprintf(etype,"type%d",ev%5); event->SetType(etype); event->SetHeader(ev, 200, 960312, random); event->SetNseg(Int_t(10*ntrack+20*sigmas)); event->SetNvertex(Int_t(1+20*gRandom->Rndm())); event->SetFlag(UInt_t(random+0.5)); event->SetTemperature(random+20.); for(UChar_t m = 0; m < 10; m++) { event->SetMeasure(m, Int_t(gRandom->Gaus(m,m+1))); } for(UChar_t i0 = 0; i0 < 4; i0++) { for(UChar_t i1 = 0; i1 < 4; i1++) { event->SetMatrix(i0,i1,gRandom->Gaus(i0*i1,1)); } } // Create and Fill the Track objects for (Int_t t = 0; t < ntrack; t++) event->AddTrack(random); if (write) nb += tree->Fill(); //fill the tree if (hm) hm->Hfill(event); //fill histograms event->Clear(); } if (write) { hfile->Write(); tree->Print(); } } // Stop timer and print results timer.Stop(); Float_t mbytes = 0.000001*nb; Double_t rtime = timer.RealTime(); Double_t ctime = timer.CpuTime(); printf("\n%d events and %d bytes processed.\n",nevent,nb); printf("RealTime=%f seconds, CpuTime=%f seconds\n",rtime,ctime); if (read) { printf("You read %f Mbytes/Realtime seconds\n",mbytes/rtime); printf("You read %f Mbytes/Cputime seconds\n",mbytes/ctime); } else { printf("compression level=%d, split=%d, arg4=%d\n",comp,split,arg4); printf("You write %f Mbytes/Realtime seconds\n",mbytes/rtime); printf("You write %f Mbytes/Cputime seconds\n",mbytes/ctime); //printf("file compression factor = %f\n",hfile.GetCompressionFactor()); } hfile->Close(); return 0; } <commit_msg>A wrong version of MainEvent was checked in..<commit_after>// @(#)root/test:$Name: $:$Id: MainEvent.cxx,v 1.9 2001/02/09 10:24:46 brun Exp $ // Author: Rene Brun 19/01/97 //////////////////////////////////////////////////////////////////////// // // A simple example with a ROOT tree // ================================= // // This program creates : // - a ROOT file // - a tree // Additional arguments can be passed to the program to control the flow // of execution. (see comments describing the arguments in the code). // Event nevent comp split fill // All arguments are optional: Default is // Event 400 1 1 1 // // In this example, the tree consists of one single "super branch" // The statement ***tree->Branch("event", event, 64000,split);*** below // will parse the structure described in Event.h and will make // a new branch for each data member of the class if split is set to 1. // - 5 branches corresponding to the basic types fNtrack,fNseg,fNvertex // ,fFlag and fTemperature. // - 3 branches corresponding to the members of the subobject EventHeader. // - one branch for each data member of the class Track of TClonesArray. // - one branch for the object fH (histogram of class TH1F). // // if split = 0 only one single branch is created and the complete event // is serialized in one single buffer. // if comp = 0 no compression at all. // if comp = 1 event is compressed. // if comp = 2 same as 1. In addition branches with floats in the TClonesArray // are also compressed. // The 4th argument fill can be set to 0 if one wants to time // the percentage of time spent in creating the event structure and // not write the event in the file. // In this example, one loops over nevent events. // The branch "event" is created at the first event. // The branch address is set for all other events. // For each event, the event header is filled and ntrack tracks // are generated and added to the TClonesArray list. // For each event the event histogram is saved as well as the list // of all tracks. // // The number of events can be given as the first argument to the program. // By default 400 events are generated. // The compression option can be activated/deactivated via the second argument. // // ---Running/Linking instructions---- // This program consists of the following files and procedures. // - Event.h event class description // - Event.C event class implementation // - MainEvent.C the main program to demo this class might be used (this file) // - EventCint.C the CINT dictionary for the event and Track classes // this file is automatically generated by rootcint (see Makefile), // when the class definition in Event.h is modified. // // ---Analyzing the Event.root file with the interactive root // example of a simple session // Root > TFile f("Event.root") // Root > T.Draw("fNtrack") //histogram the number of tracks per event // Root > T.Draw("fPx") //histogram fPx for all tracks in all events // Root > T.Draw("fXfirst:fYfirst","fNtrack>600") // //scatter-plot for x versus y of first point of each track // Root > T.Draw("fH.GetRMS()") //histogram of the RMS of the event histogram // // Look also in the same directory at the following macros: // - eventa.C an example how to read the tree // - eventb.C how to read events conditionally // //////////////////////////////////////////////////////////////////////// #include <stdlib.h> #include "TROOT.h" #include "TFile.h" #include "TNetFile.h" #include "TRandom.h" #include "TTree.h" #include "TBranch.h" #include "TClonesArray.h" #include "TStopwatch.h" #include "Event.h" //______________________________________________________________________________ int main(int argc, char **argv) { TROOT simple("simple","Example of creation of a tree"); Int_t nevent = 400; // by default create 400 events Int_t comp = 1; // by default file is compressed Int_t split = 1; // by default, split Event in sub branches Int_t write = 1; // by default the tree is filled Int_t hfill = 0; // by default histograms are not filled Int_t read = 0; Int_t arg4 = 1; Int_t arg5 = 600; //default number of tracks per event Int_t netf = 0; if (argc > 1) nevent = atoi(argv[1]); if (argc > 2) comp = atoi(argv[2]); if (argc > 3) split = atoi(argv[3]); if (argc > 4) arg4 = atoi(argv[4]); if (argc > 5) arg5 = atoi(argv[5]); if (arg4 == 0) { write = 0; hfill = 0; read = 1;} if (arg4 == 1) { write = 1; hfill = 0;} if (arg4 == 2) { write = 0; hfill = 0;} if (arg4 == 10) { write = 0; hfill = 1;} if (arg4 == 11) { write = 1; hfill = 1;} if (arg4 == 20) { write = 0; read = 1;} //read sequential if (arg4 == 25) { write = 0; read = 2;} //read random if (arg4 >= 30) { netf = 1; } //use TNetFile if (arg4 == 30) { write = 0; read = 1;} //netfile + read sequential if (arg4 == 35) { write = 0; read = 2;} //netfile + read random if (arg4 == 36) { write = 1; } //netfile + write sequential TFile *hfile; TTree *tree; Event *event = 0; // Fill event, header and tracks with some random numbers // Create a timer object to benchmark this loop TStopwatch timer; timer.Start(); Int_t nb = 0; Int_t ev; Int_t bufsize; Double_t told = 0; Double_t tnew = 0; Int_t printev = 100; if (arg5 < 100) printev = 1000; if (arg5 < 10) printev = 10000; Track::Class()->IgnoreTObjectStreamer(); Track::Class()->BypassStreamer(); // Read case if (read) { if (netf) { hfile = new TNetFile("root://localhost/root/test/EventNet.root"); hfile->UseCache(10); } else hfile = new TFile("Event.root"); tree = (TTree*)hfile->Get("T"); TBranch *branch = tree->GetBranch("event"); branch->SetAddress(&event); Int_t nentries = (Int_t)tree->GetEntries(); nevent = TMath::Max(nevent,nentries); if (read == 1) { //read sequential for (ev = 0; ev < nevent; ev++) { if (ev%printev == 0) { tnew = timer.RealTime(); printf("event:%d, rtime=%f s\n",ev,tnew-told); told=tnew; timer.Continue(); } nb += tree->GetEntry(ev); //read complete event in memory } } else { //read random Int_t evrandom; for (ev = 0; ev < nevent; ev++) { if (ev%printev == 0) cout<<"event="<<ev<<endl; evrandom = Int_t(nevent*gRandom->Rndm(1)); nb += tree->GetEntry(evrandom); //read complete event in memory } } } else { // Write case // Create a new ROOT binary machine independent file. // Note that this file may contain any kind of ROOT objects, histograms, // pictures, graphics objects, detector geometries, tracks, events, etc.. // This file is now becoming the current directory. if (netf) { hfile = new TNetFile("root://localhost/root/test/EventNet.root","RECREATE","TTree benchmark ROOT file"); hfile->UseCache(10); } else hfile = new TFile("Event.root","RECREATE","TTree benchmark ROOT file"); hfile->SetCompressionLevel(comp); // Create histogram to show write_time in function of time Float_t curtime = -0.5; Int_t ntime = nevent/printev; TH1F *htime = new TH1F("htime","Real-Time to write versus time",ntime,0,ntime); HistogramManager *hm = 0; if (hfill) { TDirectory *hdir = new TDirectory("histograms", "all histograms"); hm = new HistogramManager(hdir); } // Create a ROOT Tree and one superbranch TTree *tree = new TTree("T","An example of a ROOT tree"); tree->SetAutoSave(1000000000); // autosave when 1 Gbyte written bufsize = 64000; if (split) bufsize /= 4; event = new Event(); TBranch *branch = tree->Branch("event", "Event", &event, bufsize,split); branch->SetAutoDelete(kFALSE); char etype[20]; for (ev = 0; ev < nevent; ev++) { if (ev%printev == 0) { tnew = timer.RealTime(); printf("event:%d, rtime=%f s\n",ev,tnew-told); htime->Fill(curtime,tnew-told); curtime += 1; told=tnew; timer.Continue(); } Float_t sigmat, sigmas; gRandom->Rannor(sigmat,sigmas); Int_t ntrack = Int_t(arg5 +arg5*sigmat/120.); Float_t random = gRandom->Rndm(1); sprintf(etype,"type%d",ev%5); event->SetType(etype); event->SetHeader(ev, 200, 960312, random); event->SetNseg(Int_t(10*ntrack+20*sigmas)); event->SetNvertex(Int_t(1+20*gRandom->Rndm())); event->SetFlag(UInt_t(random+0.5)); event->SetTemperature(random+20.); for(UChar_t m = 0; m < 10; m++) { event->SetMeasure(m, Int_t(gRandom->Gaus(m,m+1))); } for(UChar_t i0 = 0; i0 < 4; i0++) { for(UChar_t i1 = 0; i1 < 4; i1++) { event->SetMatrix(i0,i1,gRandom->Gaus(i0*i1,1)); } } // Create and Fill the Track objects for (Int_t t = 0; t < ntrack; t++) event->AddTrack(random); if (write) nb += tree->Fill(); //fill the tree if (hm) hm->Hfill(event); //fill histograms event->Clear(); } if (write) { hfile->Write(); tree->Print(); } } // Stop timer and print results timer.Stop(); Float_t mbytes = 0.000001*nb; Double_t rtime = timer.RealTime(); Double_t ctime = timer.CpuTime(); printf("\n%d events and %d bytes processed.\n",nevent,nb); printf("RealTime=%f seconds, CpuTime=%f seconds\n",rtime,ctime); if (read) { printf("You read %f Mbytes/Realtime seconds\n",mbytes/rtime); printf("You read %f Mbytes/Cputime seconds\n",mbytes/ctime); } else { printf("compression level=%d, split=%d, arg4=%d\n",comp,split,arg4); printf("You write %f Mbytes/Realtime seconds\n",mbytes/rtime); printf("You write %f Mbytes/Cputime seconds\n",mbytes/ctime); //printf("file compression factor = %f\n",hfile.GetCompressionFactor()); } hfile->Close(); return 0; } <|endoftext|>
<commit_before>/* * Copyright 2001,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id$ */ #if !defined(UNION_DATATYPEVALIDATOR_HPP) #define UNION_DATATYPEVALIDATOR_HPP #include <xercesc/validators/datatype/DatatypeValidator.hpp> XERCES_CPP_NAMESPACE_BEGIN class VALIDATORS_EXPORT UnionDatatypeValidator : public DatatypeValidator { public: // ----------------------------------------------------------------------- // Public ctor/dtor // ----------------------------------------------------------------------- /** @name Constructors and Destructor. */ //@{ UnionDatatypeValidator ( MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); // // constructor for native Union datatype validator // <simpleType name="nativeUnion"> // <union memberTypes="member1 member2 ..."> // </simpleType> // UnionDatatypeValidator ( RefVectorOf<DatatypeValidator>* const memberTypeValidators , const int finalSet , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); // // constructor for derived Union datatype validator // <simpleType name="derivedUnion"> // <restriction base="nativeUnion"> // <pattern value="patter_value"/> // <enumeration value="enum_value"/> // </restriction> // </simpleType> // UnionDatatypeValidator ( DatatypeValidator* const baseValidator , RefHashTableOf<KVStringPair>* const facets , RefArrayVectorOf<XMLCh>* const enums , const int finalSet , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager , RefVectorOf<DatatypeValidator>* const memberTypeValidators = 0 , const bool memberTypesInherited = true ); virtual ~UnionDatatypeValidator(); //@} virtual const RefArrayVectorOf<XMLCh>* getEnumString() const; // ----------------------------------------------------------------------- // Getter methods // ----------------------------------------------------------------------- /** @name Getter Functions */ //@{ /** * Returns whether the type is atomic or not */ virtual bool isAtomic() const; virtual const XMLCh* getCanonicalRepresentation ( const XMLCh* const rawData , MemoryManager* const memMgr = 0 , bool toValidate = false ) const; //@} // ----------------------------------------------------------------------- // Validation methods // ----------------------------------------------------------------------- /** @name Validation Function */ //@{ /** * validate that a string matches the boolean datatype * @param content A string containing the content to be validated * * @exception throws InvalidDatatypeException if the content is * is not valid. */ virtual void validate ( const XMLCh* const content , ValidationContext* const context = 0 , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); /** * Checks whether a given type can be used as a substitute * * @param toCheck A datatype validator of the type to be used as a * substitute * * To be redefined in UnionDatatypeValidator */ virtual bool isSubstitutableBy(const DatatypeValidator* const toCheck); //@} // ----------------------------------------------------------------------- // Compare methods // ----------------------------------------------------------------------- /** @name Compare Function */ //@{ /** * Compare two boolean data types * * @param content1 * @param content2 * @return */ int compare(const XMLCh* const, const XMLCh* const , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); //@} /** * Returns an instance of the base datatype validator class * Used by the DatatypeValidatorFactory. */ virtual DatatypeValidator* newInstance ( RefHashTableOf<KVStringPair>* const facets , RefArrayVectorOf<XMLCh>* const enums , const int finalSet , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); /*** * Support for Serialization/De-serialization ***/ DECL_XSERIALIZABLE(UnionDatatypeValidator) RefVectorOf<DatatypeValidator>* getMemberTypeValidators() const; private: // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- UnionDatatypeValidator(const UnionDatatypeValidator&); UnionDatatypeValidator& operator=(const UnionDatatypeValidator&); virtual void checkContent(const XMLCh* const content , ValidationContext* const context , bool asBase , MemoryManager* const manager); void init(DatatypeValidator* const baseValidator , RefHashTableOf<KVStringPair>* const facets , RefArrayVectorOf<XMLCh>* const enums , MemoryManager* const manager); void cleanUp(); RefArrayVectorOf<XMLCh>* getEnumeration() const; void setEnumeration(RefArrayVectorOf<XMLCh>*, bool); // ----------------------------------------------------------------------- // Private data members // // fEnumeration // we own it (or not, depending on state of fEnumerationInherited). // // fMemberTypeValidators // we own it (or not, depending on the state of fMemberTypesInherited). // // ----------------------------------------------------------------------- bool fEnumerationInherited; bool fMemberTypesInherited; RefArrayVectorOf<XMLCh>* fEnumeration; RefVectorOf<DatatypeValidator>* fMemberTypeValidators; }; inline DatatypeValidator* UnionDatatypeValidator::newInstance ( RefHashTableOf<KVStringPair>* const facets , RefArrayVectorOf<XMLCh>* const enums , const int finalSet , MemoryManager* const manager ) { return (DatatypeValidator*) new (manager) UnionDatatypeValidator(this, facets, enums, finalSet, manager, fMemberTypeValidators, true); } inline void UnionDatatypeValidator::validate( const XMLCh* const content , ValidationContext* const context , MemoryManager* const manager) { checkContent(content, context, false, manager); } inline void UnionDatatypeValidator::cleanUp() { //~RefVectorOf will delete all adopted elements if ( !fEnumerationInherited && fEnumeration) delete fEnumeration; if (!fMemberTypesInherited && fMemberTypeValidators) delete fMemberTypeValidators; } inline RefArrayVectorOf<XMLCh>* UnionDatatypeValidator:: getEnumeration() const { return fEnumeration; } inline void UnionDatatypeValidator::setEnumeration(RefArrayVectorOf<XMLCh>* enums , bool inherited) { if (enums) { if ( !fEnumerationInherited && fEnumeration) delete fEnumeration; fEnumeration = enums; fEnumerationInherited = inherited; setFacetsDefined(DatatypeValidator::FACET_ENUMERATION); } } // // get the native UnionDTV's fMemberTypeValidators // inline RefVectorOf<DatatypeValidator>* UnionDatatypeValidator::getMemberTypeValidators() const { return this->fMemberTypeValidators; } inline bool UnionDatatypeValidator::isAtomic() const { if (!fMemberTypeValidators) { return false; } unsigned int memberSize = fMemberTypeValidators->size(); for (unsigned int i=0; i < memberSize; i++) { if (!fMemberTypeValidators->elementAt(i)->isAtomic()) { return false; } } return true; } inline bool UnionDatatypeValidator::isSubstitutableBy(const DatatypeValidator* const toCheck) { if (toCheck == this) { return true; } if (fMemberTypeValidators) { unsigned int memberSize = fMemberTypeValidators->size(); for (unsigned int i=0; i < memberSize; i++) { if (fMemberTypeValidators->elementAt(i)->getType() == DatatypeValidator::Union) return false; if (fMemberTypeValidators->elementAt(i)->isSubstitutableBy(toCheck)) { return true; } } } return false; } XERCES_CPP_NAMESPACE_END #endif /** * End of file UnionDatatypeValidator.hpp */ <commit_msg>Schema fixes for union of union.<commit_after>/* * Copyright 2001,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id$ */ #if !defined(UNION_DATATYPEVALIDATOR_HPP) #define UNION_DATATYPEVALIDATOR_HPP #include <xercesc/validators/datatype/DatatypeValidator.hpp> XERCES_CPP_NAMESPACE_BEGIN class VALIDATORS_EXPORT UnionDatatypeValidator : public DatatypeValidator { public: // ----------------------------------------------------------------------- // Public ctor/dtor // ----------------------------------------------------------------------- /** @name Constructors and Destructor. */ //@{ UnionDatatypeValidator ( MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); // // constructor for native Union datatype validator // <simpleType name="nativeUnion"> // <union memberTypes="member1 member2 ..."> // </simpleType> // UnionDatatypeValidator ( RefVectorOf<DatatypeValidator>* const memberTypeValidators , const int finalSet , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); // // constructor for derived Union datatype validator // <simpleType name="derivedUnion"> // <restriction base="nativeUnion"> // <pattern value="patter_value"/> // <enumeration value="enum_value"/> // </restriction> // </simpleType> // UnionDatatypeValidator ( DatatypeValidator* const baseValidator , RefHashTableOf<KVStringPair>* const facets , RefArrayVectorOf<XMLCh>* const enums , const int finalSet , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager , RefVectorOf<DatatypeValidator>* const memberTypeValidators = 0 , const bool memberTypesInherited = true ); virtual ~UnionDatatypeValidator(); //@} virtual const RefArrayVectorOf<XMLCh>* getEnumString() const; // ----------------------------------------------------------------------- // Getter methods // ----------------------------------------------------------------------- /** @name Getter Functions */ //@{ /** * Returns whether the type is atomic or not */ virtual bool isAtomic() const; virtual const XMLCh* getCanonicalRepresentation ( const XMLCh* const rawData , MemoryManager* const memMgr = 0 , bool toValidate = false ) const; //@} // ----------------------------------------------------------------------- // Validation methods // ----------------------------------------------------------------------- /** @name Validation Function */ //@{ /** * validate that a string matches the boolean datatype * @param content A string containing the content to be validated * * @exception throws InvalidDatatypeException if the content is * is not valid. */ virtual void validate ( const XMLCh* const content , ValidationContext* const context = 0 , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); /** * Checks whether a given type can be used as a substitute * * @param toCheck A datatype validator of the type to be used as a * substitute * * To be redefined in UnionDatatypeValidator */ virtual bool isSubstitutableBy(const DatatypeValidator* const toCheck); //@} // ----------------------------------------------------------------------- // Compare methods // ----------------------------------------------------------------------- /** @name Compare Function */ //@{ /** * Compare two boolean data types * * @param content1 * @param content2 * @return */ int compare(const XMLCh* const, const XMLCh* const , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); //@} /** * Returns an instance of the base datatype validator class * Used by the DatatypeValidatorFactory. */ virtual DatatypeValidator* newInstance ( RefHashTableOf<KVStringPair>* const facets , RefArrayVectorOf<XMLCh>* const enums , const int finalSet , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); /*** * Support for Serialization/De-serialization ***/ DECL_XSERIALIZABLE(UnionDatatypeValidator) RefVectorOf<DatatypeValidator>* getMemberTypeValidators() const; private: // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- UnionDatatypeValidator(const UnionDatatypeValidator&); UnionDatatypeValidator& operator=(const UnionDatatypeValidator&); virtual void checkContent(const XMLCh* const content , ValidationContext* const context , bool asBase , MemoryManager* const manager); void init(DatatypeValidator* const baseValidator , RefHashTableOf<KVStringPair>* const facets , RefArrayVectorOf<XMLCh>* const enums , MemoryManager* const manager); void cleanUp(); RefArrayVectorOf<XMLCh>* getEnumeration() const; void setEnumeration(RefArrayVectorOf<XMLCh>*, bool); // ----------------------------------------------------------------------- // Private data members // // fEnumeration // we own it (or not, depending on state of fEnumerationInherited). // // fMemberTypeValidators // we own it (or not, depending on the state of fMemberTypesInherited). // // ----------------------------------------------------------------------- bool fEnumerationInherited; bool fMemberTypesInherited; RefArrayVectorOf<XMLCh>* fEnumeration; RefVectorOf<DatatypeValidator>* fMemberTypeValidators; }; inline DatatypeValidator* UnionDatatypeValidator::newInstance ( RefHashTableOf<KVStringPair>* const facets , RefArrayVectorOf<XMLCh>* const enums , const int finalSet , MemoryManager* const manager ) { return (DatatypeValidator*) new (manager) UnionDatatypeValidator(this, facets, enums, finalSet, manager, fMemberTypeValidators, true); } inline void UnionDatatypeValidator::validate( const XMLCh* const content , ValidationContext* const context , MemoryManager* const manager) { checkContent(content, context, false, manager); } inline void UnionDatatypeValidator::cleanUp() { //~RefVectorOf will delete all adopted elements if ( !fEnumerationInherited && fEnumeration) delete fEnumeration; if (!fMemberTypesInherited && fMemberTypeValidators) delete fMemberTypeValidators; } inline RefArrayVectorOf<XMLCh>* UnionDatatypeValidator:: getEnumeration() const { return fEnumeration; } inline void UnionDatatypeValidator::setEnumeration(RefArrayVectorOf<XMLCh>* enums , bool inherited) { if (enums) { if ( !fEnumerationInherited && fEnumeration) delete fEnumeration; fEnumeration = enums; fEnumerationInherited = inherited; setFacetsDefined(DatatypeValidator::FACET_ENUMERATION); } } // // get the native UnionDTV's fMemberTypeValidators // inline RefVectorOf<DatatypeValidator>* UnionDatatypeValidator::getMemberTypeValidators() const { return this->fMemberTypeValidators; } inline bool UnionDatatypeValidator::isAtomic() const { if (!fMemberTypeValidators) { return false; } unsigned int memberSize = fMemberTypeValidators->size(); for (unsigned int i=0; i < memberSize; i++) { if (!fMemberTypeValidators->elementAt(i)->isAtomic()) { return false; } } return true; } inline bool UnionDatatypeValidator::isSubstitutableBy(const DatatypeValidator* const toCheck) { if (toCheck == this) { return true; } if (fMemberTypeValidators) { unsigned int memberSize = fMemberTypeValidators->size(); for (unsigned int i=0; i < memberSize; i++) { if ((fMemberTypeValidators->elementAt(i)->getType() == DatatypeValidator::Union) && (fMemberTypeValidators->elementAt(i) == toCheck)) return false; if (fMemberTypeValidators->elementAt(i)->isSubstitutableBy(toCheck)) { return true; } } } return false; } XERCES_CPP_NAMESPACE_END #endif /** * End of file UnionDatatypeValidator.hpp */ <|endoftext|>
<commit_before>// dear imgui, v1.50 WIP // (demo code) // Message to the person tempted to delete this file when integrating ImGui into their code base: // Do NOT remove this file from your project! It is useful reference code that you and other users will want to refer to. // Everything in this file will be stripped out by the linker if you don't call ImGui::ShowTestWindow(). // During development, you can call ImGui::ShowTestWindow() in your code to learn about various features of ImGui. // Removing this file from your project is hindering your access to documentation, likely leading you to poorer usage of the library. #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) #define _CRT_SECURE_NO_WARNINGS #endif #include "imgui.h" #include <ctype.h> // toupper, isprint #include <math.h> // sqrtf, powf, cosf, sinf, floorf, ceilf #include <stdio.h> // vsnprintf, sscanf, printf #include <stdlib.h> // NULL, malloc, free, qsort, atoi #include <windows.h> #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier #include <stddef.h> // intptr_t #else #include <stdint.h> // intptr_t #endif #ifdef _MSC_VER #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen #define snprintf _snprintf #endif #ifdef __clang__ #pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. #pragma clang diagnostic ignored "-Wdeprecated-declarations" // warning : 'xx' is deprecated: The POSIX name for this item.. // for strdup used in demo code (so user can copy & paste the code) #pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int' #pragma clang diagnostic ignored "-Wformat-security" // warning : warning: format string is not a string literal #pragma clang diagnostic ignored "-Wexit-time-destructors" // warning : declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. #if __has_warning("-Wreserved-id-macro") #pragma clang diagnostic ignored "-Wreserved-id-macro" // warning : macro name is a reserved identifier // #endif #elif defined(__GNUC__) #pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size #pragma GCC diagnostic ignored "-Wformat-security" // warning : format string is not a string literal (potentially insecure) #pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function #pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value #if (__GNUC__ >= 6) #pragma GCC diagnostic ignored "-Wmisleading-indentation" // warning: this 'if' clause does not guard this statement // GCC 6.0+ only. See #883 on github. #endif #endif // Play it nice with Windows users. Notepad in 2015 still doesn't display text data with Unix-style \n. #ifdef _WIN32 #define IM_NEWLINE "\r\n" #else #define IM_NEWLINE "\n" #endif #define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR))) #define IM_MAX(_A,_B) (((_A) >= (_B)) ? (_A) : (_B)) //----------------------------------------------------------------------------- // DEMO CODE //----------------------------------------------------------------------------- #ifndef IMGUI_DISABLE_TEST_WINDOWS //EJEMPLO static int generarTiempoLLegada(float P); static int generarTiempoLLamada(float A); static int seleccionarMenor(int n1, int n2, int n3); static int generarTipo(); static int menor = 0, reloj = 0, delta = 0, deltaAnt = 0, TSLL = 0, tipo = 0, TClientes = 0, Tllamadas = 0, cola = 0, llamadasP = 0, llamadasCont = 0, TCELL = 0, CELL = 0; static bool LLA = false, CLA = false; static float P = 0.0f; //EJEMPLO void ImGui::Simulacion(bool* p_open, int tiempoMax, int nFilas, int nServicio) { static int i = 0; static bool atendido = false; static int TLL = generarTiempoLLegada(P); static int estaciones[10][2] = { {0,0} ,{ 0,0 } ,{ 0,0 } ,{ 0,0 } ,{ 0,0 } ,{ 0,0 } ,{ 0,0 } ,{ 0,0 } ,{ 0,0 } ,{ 0,0 } }; static int TS[10][2] = { { 0,0 } ,{ 0,0 } ,{ 0,0 } ,{ 0,0 } ,{ 0,0 } ,{ 0,0 } ,{ 0,0 } ,{ 0,0 } ,{ 0,0 } ,{ 0,0 } }; ImGui::SetNextWindowSize(ImVec2(550, 300)); if (!ImGui::Begin("Simulacion", p_open)) { // Early out if the window is collapsed, as an optimization. ImGui::End(); return; } if (reloj<tiempoMax) { Sleep(1000); menor = TLL; for (i = 0; i < nServicio; i++) { delta = seleccionarMenor(TS[i][0],TS[i][1],menor);//seleccionar el menor de 3 numeros menor = delta; } delta = 10; reloj = reloj + delta; //Pendiente formula tiempo de espera total //Revisar el tiempo de llegada TLL = TLL - delta; i = 0; if (TLL == 0) { tipo = generarTipo(); while ((i < nServicio)&&(atendido == false)) { printf("checar %i\n",i); if (tipo == 0) { TClientes++; cola++; atendido = true; } else { printf("estacion: %i estado: %i\n", i, estaciones[i][1]); if (estaciones[i][1] == 0) { estaciones[i][1] = 1; TS[i][1] = generarTiempoLLamada(1) + delta; llamadasCont++; printf("atencion: %i\n", i); atendido = true; if (estaciones[i][0] == 1) { TS[i][0] = TS[i][0] + TS[i][1]; TCELL = TCELL + TS[i][1]; CELL++; } } } i++; } printf("atendido\n"); if (atendido == false) { llamadasP++; } TLL = generarTiempoLLegada(P);//obtener un tiempo de llegada } //Revisar el tiempo de servicio de llamada for (i = 0; i < nServicio; i++) { TS[i][1] = TS[i][1] - delta; if (TS[i][1] <= 0) { estaciones[i][1] = 0; } } //Revisar el tiempo de servicio del cliente for (i = 0; i < nServicio; i++) { TS[i][0] = TS[i][0] - delta; if (TS[i][0]<=0) { } } atendido = false; printf("\n"); } //Impresion de estado Tllamadas = llamadasCont + llamadasP; ImGui::Text("Reloj: %i", reloj); ImGui::Text("Cola: %i \n", cola); ImGui::Text("Clientes: %i \n", TClientes); ImGui::Text("Llamadas: %i \n", Tllamadas); ImGui::Text("Llamadas Perdidas: %i \n", llamadasP); ImGui::Text("Llamadas Contestadas: %i \n", llamadasCont); //Calculo de promedios //Impresiones ImGui::End(); } static int generarTiempoLLegada(float P) { static int tiempo = 0; tiempo = 10; return tiempo; } static int generarTiempoLLamada(float A) { static int tiempo = 0; tiempo = 20; return tiempo; } static int seleccionarMenor(int n1, int n2, int n3) { static int mayor; mayor = 10; return mayor; } static int generarTipo() { static int tipo; tipo = 1; return tipo; } #else void ImGui::ShowTestWindow(bool*) {} void ImGui::ShowUserGuide() {} void ImGui::ShowStyleEditor(ImGuiStyle*) {} #endif <commit_msg>ejemplo de generacion de tiempos de llegada<commit_after>// dear imgui, v1.50 WIP // (demo code) // Message to the person tempted to delete this file when integrating ImGui into their code base: // Do NOT remove this file from your project! It is useful reference code that you and other users will want to refer to. // Everything in this file will be stripped out by the linker if you don't call ImGui::ShowTestWindow(). // During development, you can call ImGui::ShowTestWindow() in your code to learn about various features of ImGui. // Removing this file from your project is hindering your access to documentation, likely leading you to poorer usage of the library. #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) #define _CRT_SECURE_NO_WARNINGS #endif #include "imgui.h" #include <ctype.h> // toupper, isprint #include <math.h> // sqrtf, powf, cosf, sinf, floorf, ceilf #include <stdio.h> // vsnprintf, sscanf, printf #include <stdlib.h> // NULL, malloc, free, qsort, atoi //#include <windows.h> #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier #include <stddef.h> // intptr_t #else #include <stdint.h> // intptr_t #endif #include<iostream> #include <random> #ifdef _MSC_VER #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen #define snprintf _snprintf #endif #ifdef __clang__ #pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. #pragma clang diagnostic ignored "-Wdeprecated-declarations" // warning : 'xx' is deprecated: The POSIX name for this item.. // for strdup used in demo code (so user can copy & paste the code) #pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int' #pragma clang diagnostic ignored "-Wformat-security" // warning : warning: format string is not a string literal #pragma clang diagnostic ignored "-Wexit-time-destructors" // warning : declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. #if __has_warning("-Wreserved-id-macro") #pragma clang diagnostic ignored "-Wreserved-id-macro" // warning : macro name is a reserved identifier // #endif #elif defined(__GNUC__) #pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size #pragma GCC diagnostic ignored "-Wformat-security" // warning : format string is not a string literal (potentially insecure) #pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function #pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value #if (__GNUC__ >= 6) #pragma GCC diagnostic ignored "-Wmisleading-indentation" // warning: this 'if' clause does not guard this statement // GCC 6.0+ only. See #883 on github. #endif #endif // Play it nice with Windows users. Notepad in 2015 still doesn't display text data with Unix-style \n. #ifdef _WIN32 #define IM_NEWLINE "\r\n" #else #define IM_NEWLINE "\n" #endif #define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR))) #define IM_MAX(_A,_B) (((_A) >= (_B)) ? (_A) : (_B)) //----------------------------------------------------------------------------- // DEMO CODE //----------------------------------------------------------------------------- #ifndef IMGUI_DISABLE_TEST_WINDOWS //EJEMPLO static int generarTiempoLLegada(float P); static int generarTiempoLLamada(float A); static int seleccionarMenor(int n1, int n2, int n3); static int generarTipo(); static float getRandomNumber(); static int randomInteger(); static void geometrica(); static int menor = 0, reloj = 0, delta = 0, deltaAnt = 0, TSLL = 0, tipo = 0, TClientes = 0, Tllamadas = 0, cola = 0, llamadasP = 0, llamadasCont = 0, TCELL = 0, CELL = 0; static bool LLA = false, CLA = false; static float P = 0.0f; enum { MIN = 0, MAX = 1000 }; using namespace std; #define LEN 20 char times[LEN]; struct ExampleAppLog { ImGuiTextBuffer Buf; ImGuiTextFilter Filter; ImVector<int> LineOffsets; // Index to lines offset bool ScrollToBottom; void Clear() { Buf.clear(); LineOffsets.clear(); } void AddLog(const char* fmt, ...) IM_PRINTFARGS(2) { int old_size = Buf.size(); va_list args; va_start(args, fmt); Buf.appendv(fmt, args); va_end(args); for (int new_size = Buf.size(); old_size < new_size; old_size++) if (Buf[old_size] == '\n') LineOffsets.push_back(old_size); ScrollToBottom = true; } void Draw(const char* title, bool* p_open = NULL) { ImGui::SetNextWindowSize(ImVec2(500,400), ImGuiSetCond_FirstUseEver); ImGui::Begin(title, p_open); if (ImGui::Button("Clear")) Clear(); ImGui::SameLine(); bool copy = ImGui::Button("Copy"); ImGui::SameLine(); Filter.Draw("Filter", -100.0f); ImGui::Separator(); ImGui::BeginChild("scrolling", ImVec2(0,0), false, ImGuiWindowFlags_HorizontalScrollbar); if (copy) ImGui::LogToClipboard(); if (Filter.IsActive()) { const char* buf_begin = Buf.begin(); const char* line = buf_begin; for (int line_no = 0; line != NULL; line_no++) { const char* line_end = (line_no < LineOffsets.Size) ? buf_begin + LineOffsets[line_no] : NULL; if (Filter.PassFilter(line, line_end)) ImGui::TextUnformatted(line, line_end); line = line_end && line_end[1] ? line_end + 1 : NULL; } } else { ImGui::TextUnformatted(Buf.begin()); } if (ScrollToBottom) ImGui::SetScrollHere(1.0f); ScrollToBottom = false; ImGui::EndChild(); ImGui::End(); } }; //EJEMPLO void ImGui::Simulacion(bool* p_open, int tiempoMax, int nFilas, int nServicio) { static ExampleAppLog log; ImGui::Begin("Simulacion", p_open); if(ImGui::Button("Generate times")) { geometrica(); log.AddLog("\n\n \tNew Generation\n\n"); for(int i = 0; i < LEN; i++) log.AddLog("%d\n", times[i]); } log.Draw("Numbers for time", p_open); ImGui::End(); } static int generarTiempoLLegada(float P) { static int tiempo = 0; tiempo = 10; return tiempo; } static int generarTiempoLLamada(float A) { static int tiempo = 0; tiempo = 20; return tiempo; } static int seleccionarMenor(int n1, int n2, int n3) { static int mayor; mayor = 10; return mayor; } static int generarTipo() { static int tipo; tipo = 1; return tipo; } static int randomInteger() { std::mt19937 rng; // only used once to initialise (seed) engine rng.seed(std::random_device()()); std::uniform_int_distribution<std::mt19937::result_type> dist(MIN,MAX); // distribution in range [MIN, MAX] auto random_integer = dist(rng); return random_integer; } //Metodo Congruencial Lineal static float getRandomNumber() { long int m = 97711 /* 97711 */; int c = 7, a = 7; double nrandom = 0.0f, temp = 0.0f; double uniforme = 0.0f; int random_stop = randomInteger(); cout << "rs = " << random_stop << " "; for (long int i = 0; i < random_stop; ++i) { nrandom = ((int)(a*temp + c) % m); temp = nrandom; } uniforme = nrandom / m; return uniforme; } static void geometrica(){ double p, suma, y = 0; double r; int x; p = 0.07203; for (int i = 0; i < LEN; ++i) { x = 0; suma = 0; r = getRandomNumber(); //cout << "r = " << r << endl; while (suma < r) { x++; y = (pow((1-p), x-1))*p; suma += y; } times[i] = x; printf("X = %d\n", x); } } #else void ImGui::ShowTestWindow(bool*) {} void ImGui::ShowUserGuide() {} void ImGui::ShowStyleEditor(ImGuiStyle*) {} #endif <|endoftext|>
<commit_before>/* * benchmark.cpp * * Created on: 04.05.2015 * Author: gmueller */ #include <iostream> #include <sstream> #include <sys/stat.h> #include <sys/time.h> #include <omp.h> #include <quimby/Database.h> #include <quimby/Grid.h> #include <quimby/HCube.h> #include <quimby/tga.h> using namespace quimby; using namespace std; bool check_file(const std::string filename) { struct stat s; int r = stat(filename.c_str(), &s); return ((r == 0) && S_ISREG(s.st_mode) && (s.st_size > 0)); } class Timer { struct timeval start; public: Timer() { reset(); } void reset() { ::gettimeofday(&start, NULL); } size_t microns() { struct timeval now; ::gettimeofday(&now, NULL); size_t ms = (now.tv_sec - start.tv_sec) * 1000000; ms += (now.tv_usec - start.tv_usec); return ms; } size_t millisecods() { return microns() / 1000; } double seconds() { struct timeval now; ::gettimeofday(&now, NULL); return double(now.tv_sec - start.tv_sec) + double(now.tv_usec - start.tv_usec) / 1000000; } }; class Accessor { public: virtual Vector3f get(const Vector3f &pos) { return Vector3f(0, 0, 0); } }; class GridAccessor: public Accessor { Vector3f origin; Grid<Vector3f> &grid; public: GridAccessor(const Vector3f &origin, Grid<Vector3f> &grid) : origin(origin), grid(grid) { } Vector3f get(const Vector3f &pos) { Vector3f r = pos - origin; return grid.get(r.x, r.y, r.z); } }; template<size_t N> class HCubeAccessor: public Accessor { Vector3f origin; float size; const HCube<N> *hcube; public: HCubeAccessor(const Vector3f &origin, float size, const HCube<N> *hcube) : origin(origin), size(size), hcube(hcube) { } Vector3f get(const Vector3f &pos) { Vector3f r = pos - origin; return hcube->getValue(r, size); } }; class RandomAccessBenchmark { Vector3f origin; float size; public: RandomAccessBenchmark(Vector3f origin, float size) : origin(origin), size(size) { } double run(Accessor &accessor, size_t threads = 1, size_t samples = 10000000) { Timer timer; omp_set_num_threads(threads); #pragma omp parallel { int seed = 1202107158 + omp_get_thread_num() * 1999; struct drand48_data drand_buf; srand48_r(seed, &drand_buf); float s = size * (1 - 1e-6); #pragma omp parallel for for (size_t i = 0; i < samples; i++) { double x, y, z; drand48_r(&drand_buf, &x); drand48_r(&drand_buf, &y); drand48_r(&drand_buf, &z); accessor.get(origin + Vector3f(x, y, z) * s); } } return timer.seconds(); } }; class RandomWalkBenchmark { Vector3f origin; float size; public: RandomWalkBenchmark(Vector3f origin, float size) : origin(origin), size(size) { } double run(Accessor &accessor, size_t threads = 1, size_t samples = 10000000) { Timer timer; omp_set_num_threads(threads); float step = size / 1000.; Vector3f end = origin + Vector3f(size, size, size) * (1 - 1e-6); #pragma omp parallel { int seed = 1202107158 + omp_get_thread_num() * 1999; struct drand48_data drand_buf; srand48_r(seed, &drand_buf); Vector3f pos = origin + Vector3f(size / 2., size / 2., size / 2.); #pragma omp parallel for for (size_t i = 0; i < samples; i++) { double x, y, z; drand48_r(&drand_buf, &x); drand48_r(&drand_buf, &y); drand48_r(&drand_buf, &z); pos += Vector3f(x-0.5, y-0.5, z-0.5) * step; pos.setUpper(origin); pos.setLower(end); accessor.get(pos); //cout << pos << endl; } } return timer.seconds(); } }; void print_slice(Accessor &accessor, size_t bins, size_t z, const Vector3f &origin, float size, const string &filename) { const float rl = 1e-15; const float ru = 1e-5; ofstream tgafile(filename.c_str()); tga_write_header(tgafile, bins, bins); for (size_t x = 0; x < bins; x++) { for (size_t y = 0; y < bins; y++) { float value = accessor.get( origin + Vector3f(x, y, z) * (size / bins)).length(); // normalize value = (log10(value) - log10(rl)) / (log10(ru) - log10(rl)); tga_write_float(tgafile, value); } } } int main(int argc, const char **argv) { if (argc < 3) { cout << "benchmark <comaprofile.db> <bins>" << endl; return 1; } size_t bins = atoi(argv[2]); cout << "load coma db" << endl; FileDatabase fdb; fdb.open(argv[1]); cout << " particles: " << fdb.getCount() << endl; cout << " lower: " << fdb.getLowerBounds() << endl; cout << " upper: " << fdb.getUpperBounds() << endl; Vector3f origin = fdb.getLowerBounds(); Vector3f size3 = fdb.getUpperBounds() - fdb.getLowerBounds(); float size = std::min(std::min(size3.x, size3.y), size3.z); cout << " size: " << size << endl; cout << "create sample" << endl; Grid<Vector3f> grid(bins, size); stringstream gridfilename; gridfilename << "benchmark-" << bins << "-grid.grid"; if (check_file(gridfilename.str())) { grid.load(gridfilename.str()); } else { grid.reset(Vector3f(0, 0, 0)); cout << "create visitor" << endl; SimpleSamplingVisitor v(grid, fdb.getLowerBounds(), size); v.showProgress(true); cout << "start sampling" << endl; fdb.accept(v); cout << endl; grid.save(gridfilename.str()); } GridAccessor gridaccessor(fdb.getLowerBounds(), grid); cout << "print slices" << endl; for (size_t z = 0; z < bins; z += bins / 16) { stringstream filename; filename << "benchmark-" << bins << "-slice-grid-" << z << ".tga"; print_slice(gridaccessor, bins, z, origin, size, filename.str()); } size_t maxdepth = 0; while (pow(4, maxdepth + 1) < bins) maxdepth++; stringstream hcubefilename; hcubefilename << "benchmark-" << bins << "-hcube.hc4"; if (!check_file(hcubefilename.str())) { cout << "create hc4, maxdepth=" << maxdepth << endl; HCubeFile4::create(grid, Vector3f(0, 0, 0), size, 0.1, 1e-19, maxdepth, hcubefilename.str()); } cout << "open hc4" << endl; HCubeFile4 hcf; hcf.open(hcubefilename.str()); const HCube4 *hcube = hcf.hcube(); HCubeAccessor<4> hcubeaccessor(origin, size, hcube); cout << "print hcube slices" << endl; for (size_t z = 0; z < bins; z += bins / 16) { stringstream filename; filename << "benchmark-" << bins << "-slice-hcube-" << z << ".tga"; print_slice(hcubeaccessor, bins, z, origin, size, filename.str()); } RandomAccessBenchmark rab(origin, size); RandomWalkBenchmark rwb(origin, size); Accessor nullaccessor; //ToDo: THREADS //ToDo: zorder //ToDo: mmap grid size_t max_threads = omp_get_max_threads(); for (size_t threads = 1; threads <= max_threads; threads++) { cout << "threads: " << threads << "/" << max_threads << endl; cout << " run null benchmark" << endl; cout << " " << rab.run(nullaccessor, threads) << endl; cout << " " << rab.run(nullaccessor, threads) << endl; cout << " run grid benchmark" << endl; cout << " " << rab.run(gridaccessor, threads) << endl; cout << " " << rab.run(gridaccessor, threads) << endl; cout << " run hcube benchmark" << endl; cout << " " << rab.run(hcubeaccessor, threads) << endl; cout << " " << rab.run(hcubeaccessor, threads) << endl; cout << "random walk"; cout << " run null benchmark" << endl; cout << " " << rwb.run(nullaccessor, threads) << endl; cout << " " << rwb.run(nullaccessor, threads) << endl; cout << " run grid benchmark" << endl; cout << " " << rwb.run(gridaccessor, threads) << endl; cout << " " << rwb.run(gridaccessor, threads) << endl; cout << " run hcube benchmark" << endl; cout << " " << rwb.run(hcubeaccessor, threads) << endl; cout << " " << rwb.run(hcubeaccessor, threads) << endl; } cout << "done" << endl; } <commit_msg>improve benchmark<commit_after>/* * benchmark.cpp * * Created on: 04.05.2015 * Author: gmueller */ #include <iostream> #include <sstream> #include <sys/stat.h> #include <sys/time.h> #include <omp.h> #include <quimby/Database.h> #include <quimby/Grid.h> #include <quimby/HCube.h> #include <quimby/tga.h> using namespace quimby; using namespace std; bool check_file(const std::string filename) { struct stat s; int r = stat(filename.c_str(), &s); return ((r == 0) && S_ISREG(s.st_mode) && (s.st_size > 0)); } class Timer { struct timeval start; public: Timer() { reset(); } void reset() { ::gettimeofday(&start, NULL); } size_t microns() { struct timeval now; ::gettimeofday(&now, NULL); size_t ms = (now.tv_sec - start.tv_sec) * 1000000; ms += (now.tv_usec - start.tv_usec); return ms; } size_t millisecods() { return microns() / 1000; } double seconds() { struct timeval now; ::gettimeofday(&now, NULL); return double(now.tv_sec - start.tv_sec) + double(now.tv_usec - start.tv_usec) / 1000000; } }; class Accessor { public: virtual Vector3f get(const Vector3f &pos) { return Vector3f(0, 0, 0); } }; class GridAccessor: public Accessor { Vector3f origin; Grid<Vector3f> &grid; public: GridAccessor(const Vector3f &origin, Grid<Vector3f> &grid) : origin(origin), grid(grid) { } Vector3f get(const Vector3f &pos) { Vector3f r = pos - origin; return grid.get(r.x, r.y, r.z); } }; template<size_t N> class HCubeAccessor: public Accessor { Vector3f origin; float size; const HCube<N> *hcube; public: HCubeAccessor(const Vector3f &origin, float size, const HCube<N> *hcube) : origin(origin), size(size), hcube(hcube) { } Vector3f get(const Vector3f &pos) { Vector3f r = pos - origin; return hcube->getValue(r, size); } }; class RandomAccessBenchmark { Vector3f origin; float size; public: RandomAccessBenchmark(Vector3f origin, float size) : origin(origin), size(size) { } double run(Accessor &accessor, size_t threads = 1, size_t samples = 10000000) { Timer timer; omp_set_num_threads(threads); #pragma omp parallel { int seed = 1202107158 + omp_get_thread_num() * 1999; struct drand48_data drand_buf; srand48_r(seed, &drand_buf); float s = size * (1 - 1e-6); #pragma omp parallel for for (size_t i = 0; i < samples; i++) { double x, y, z; drand48_r(&drand_buf, &x); drand48_r(&drand_buf, &y); drand48_r(&drand_buf, &z); accessor.get(origin + Vector3f(x, y, z) * s); } } return timer.seconds(); } }; class RandomWalkBenchmark { Vector3f origin; float size; public: RandomWalkBenchmark(Vector3f origin, float size) : origin(origin), size(size) { } double run(Accessor &accessor, size_t threads = 1, size_t samples = 10000000) { Timer timer; omp_set_num_threads(threads); float step = size / 1000.; Vector3f end = origin + Vector3f(size, size, size) * (1 - 1e-6); #pragma omp parallel { int seed = 1202107158 + omp_get_thread_num() * 1999; struct drand48_data drand_buf; srand48_r(seed, &drand_buf); Vector3f pos = origin + Vector3f(size / 2., size / 2., size / 2.); #pragma omp parallel for for (size_t i = 0; i < samples; i++) { double x, y, z; drand48_r(&drand_buf, &x); drand48_r(&drand_buf, &y); drand48_r(&drand_buf, &z); pos += Vector3f(x-0.5, y-0.5, z-0.5) * step; pos.setUpper(origin); pos.setLower(end); accessor.get(pos); //cout << pos << endl; } } return timer.seconds(); } }; void print_slice(Accessor &accessor, size_t bins, size_t z, const Vector3f &origin, float size, const string &filename) { const float rl = 1e-15; const float ru = 1e-5; ofstream tgafile(filename.c_str()); tga_write_header(tgafile, bins, bins); for (size_t x = 0; x < bins; x++) { for (size_t y = 0; y < bins; y++) { float value = accessor.get( origin + Vector3f(x, y, z) * (size / bins)).length(); // normalize value = (log10(value) - log10(rl)) / (log10(ru) - log10(rl)); tga_write_float(tgafile, value); } } } int main(int argc, const char **argv) { if (argc < 3) { cout << "benchmark <comaprofile.db> <bins>" << endl; return 1; } size_t bins = atoi(argv[2]); cout << "load coma db" << endl; FileDatabase fdb; fdb.open(argv[1]); cout << " particles: " << fdb.getCount() << endl; cout << " lower: " << fdb.getLowerBounds() << endl; cout << " upper: " << fdb.getUpperBounds() << endl; Vector3f origin = fdb.getLowerBounds(); Vector3f size3 = fdb.getUpperBounds() - fdb.getLowerBounds(); float size = std::min(std::min(size3.x, size3.y), size3.z); cout << " size: " << size << endl; cout << "create sample" << endl; Grid<Vector3f> grid(bins, size); stringstream gridfilename; gridfilename << "benchmark-" << bins << "-grid.grid"; if (check_file(gridfilename.str())) { grid.load(gridfilename.str()); } else { grid.reset(Vector3f(0, 0, 0)); cout << "create visitor" << endl; SimpleSamplingVisitor v(grid, fdb.getLowerBounds(), size); v.showProgress(true); cout << "start sampling" << endl; fdb.accept(v); cout << endl; grid.save(gridfilename.str()); } GridAccessor gridaccessor(fdb.getLowerBounds(), grid); cout << "print slices" << endl; for (size_t z = 0; z < bins; z += bins / 16) { stringstream filename; filename << "benchmark-" << bins << "-slice-grid-" << z << ".tga"; print_slice(gridaccessor, bins, z, origin, size, filename.str()); } size_t maxdepth = 0; while (pow(4, maxdepth + 1) < bins) maxdepth++; stringstream hcubefilename; hcubefilename << "benchmark-" << bins << "-hcube.hc4"; if (!check_file(hcubefilename.str())) { cout << "create hc4, maxdepth=" << maxdepth << endl; HCubeFile4::create(grid, Vector3f(0, 0, 0), size, 0.1, 1e-19, maxdepth, hcubefilename.str()); } cout << "open hc4" << endl; HCubeFile4 hcf; hcf.open(hcubefilename.str()); const HCube4 *hcube = hcf.hcube(); HCubeAccessor<4> hcubeaccessor(origin, size, hcube); cout << "print hcube slices" << endl; for (size_t z = 0; z < bins; z += bins / 16) { stringstream filename; filename << "benchmark-" << bins << "-slice-hcube-" << z << ".tga"; print_slice(hcubeaccessor, bins, z, origin, size, filename.str()); } RandomAccessBenchmark rab(origin, size); RandomWalkBenchmark rwb(origin, size); Accessor nullaccessor; //ToDo: zorder //ToDo: mmap grid cout << "accessor benchmark threads time" << endl; const size_t samples = 3; size_t max_threads = omp_get_max_threads(); for (size_t threads = 1; threads <= max_threads; threads++) { for (size_t i = 0; i < samples; i++) cout << "0 0 " << threads << " " << rab.run(nullaccessor, threads) << endl; for (size_t i = 0; i < samples; i++) cout << "1 0 " << threads << " " << rab.run(gridaccessor, threads) << endl; for (size_t i = 0; i < samples; i++) cout << "2 0 " << threads << " " << rab.run(hcubeaccessor, threads) << endl; for (size_t i = 0; i < samples; i++) cout << "0 1 " << threads << " " << rwb.run(nullaccessor, threads) << endl; for (size_t i = 0; i < samples; i++) cout << "1 1 " << threads << " " << rwb.run(gridaccessor, threads) << endl; for (size_t i = 0; i < samples; i++) cout << "2 1 " << threads << " " << rwb.run(hcubeaccessor, threads) << endl; } cout << "done" << endl; } <|endoftext|>
<commit_before>// // Copyright (c) 2008 Advanced Micro Devices, Inc. All rights reserved. // #ifndef WITHOUT_HSA_BACKEND #include <string> #include <sstream> #include <fstream> #include <iostream> #include "os/os.hpp" #include "rocdevice.hpp" #include "rocprogram.hpp" #if defined(WITH_LIGHTNING_COMPILER) #include "opencl1.2-c.amdgcn.inc" #include "opencl2.0-c.amdgcn.inc" #else // !defined(WITH_LIGHTNING_COMPILER) #include "roccompilerlib.hpp" #endif // !defined(WITH_LIGHTNING_COMPILER) #include "utils/options.hpp" #include <cstdio> #if defined(ATI_OS_LINUX) #include <dlfcn.h> #include <libgen.h> #endif // defined(ATI_OS_LINUX) #if defined(WITH_LIGHTNING_COMPILER) static std::string llvmBin_(amd::Os::getEnvironment("LLVM_BIN")); #endif // defined(WITH_LIGHTNING_COMPILER) //CLC_IN_PROCESS_CHANGE extern int openclFrontEnd(const char* cmdline, std::string*, std::string* typeInfo = NULL); namespace roc { /* Temporary log function for the compiler library */ static void logFunction(const char* msg, size_t size) { std::cout<< "Compiler Log: " << msg << std::endl; } static int programsCount = 0; #if defined(WITH_LIGHTNING_COMPILER) bool HSAILProgram::compileImpl_LC( const std::string& sourceCode, const std::vector<const std::string*>& headers, const char** headerIncludeNames, amd::option::Options* options) { using namespace amd::opencl_driver; std::auto_ptr<Compiler> C(newCompilerInstance()); std::vector<Data*> inputs; Data* input = C->NewBufferReference(DT_CL, sourceCode.c_str(), sourceCode.length()); if (input == NULL) { buildLog_ += "Error while creating data from source code"; return false; } inputs.push_back(input); //Find the temp folder for the OS std::string tempFolder = amd::Os::getEnvironment("TEMP"); if (tempFolder.empty()) { tempFolder = amd::Os::getEnvironment("TMP"); if (tempFolder.empty()) { tempFolder = WINDOWS_SWITCH(".","/tmp");; } } //Iterate through each source code and dump it into tmp std::fstream f; std::vector<std::string> headerFileNames(headers.size()); std::vector<std::string> newDirs; for (size_t i = 0; i < headers.size(); ++i) { std::string headerPath = tempFolder; std::string headerIncludeName(headerIncludeNames[i]); // replace / in path with current os's file separator if ( amd::Os::fileSeparator() != '/') { for (std::string::iterator it = headerIncludeName.begin(), end = headerIncludeName.end(); it != end; ++it) { if (*it == '/') *it = amd::Os::fileSeparator(); } } size_t pos = headerIncludeName.rfind(amd::Os::fileSeparator()); if (pos != std::string::npos) { headerPath += amd::Os::fileSeparator(); headerPath += headerIncludeName.substr(0, pos); headerIncludeName = headerIncludeName.substr(pos+1); } if (!amd::Os::pathExists(headerPath)) { bool ret = amd::Os::createPath(headerPath); assert(ret && "failed creating path!"); newDirs.push_back(headerPath); } std::string headerFullName = headerPath + amd::Os::fileSeparator() + headerIncludeName; headerFileNames[i] = headerFullName; f.open(headerFullName.c_str(), std::fstream::out); //Should we allow asserts assert(!f.fail() && "failed creating header file!"); f.write(headers[i]->c_str(), headers[i]->length()); f.close(); Data* inc = C->NewFileReference(DT_CL_HEADER, headerFileNames[i]); if (inc == NULL) { buildLog_ += "Error while creating data from headers"; return false; } inputs.push_back(inc); } //Set the options for the compiler std::ostringstream ostrstr; std::copy(options->clangOptions.begin(), options->clangOptions.end(), std::ostream_iterator<std::string>(ostrstr, " ")); std::string driverOptions(ostrstr.str()); //Set the include path for the temp folder that contains the includes if(!headers.empty()) { driverOptions.append(" -I"); driverOptions.append(tempFolder); } const char* xLang = options->oVariables->XLang; if (xLang != NULL && strcmp(xLang, "cl")) { buildLog_ += "Unsupported OpenCL language.\n"; } //FIXME_Nikolay: the program manager should be setting the language //driverOptions.append(" -x cl"); driverOptions.append(" -cl-std=").append(options->oVariables->CLStd); // Set the -O# std::ostringstream optLevel; optLevel << " -O" << options->oVariables->OptLevel; driverOptions.append(optLevel.str()); //FIXME_lmoriche: has the CL option been validated? uint clcStd = (options->oVariables->CLStd[2] - '0') * 100 + (options->oVariables->CLStd[4] - '0') * 10; driverOptions.append(preprocessorOptions(options)); Buffer* output = C->NewBuffer(DT_LLVM_BC); if (output == NULL) { buildLog_ += "Error while creating buffer for the LLVM bitcode"; return false; } driverOptions.append(options->llvmOptions); // Set fp32-denormals and fp64-denormals bool fp32Denormals = !options->oVariables->DenormsAreZero && dev().deviceInfo().gfxipVersion_ >= 900; driverOptions.append(" -Xclang -target-feature -Xclang "); driverOptions.append(fp32Denormals ? "+" : "-") .append("fp32-denormals,+fp64-denormals"); if (options->isDumpFlagSet(amd::option::DUMP_CL)) { std::ofstream f(options->getDumpFileName(".cl").c_str(), std::ios::trunc); if(f.is_open()) { f << "/* Compiler options:\n" \ "-c -emit-llvm -target amdgcn-amd-amdhsa-opencl -x cl" \ " -include opencl-c.h " << driverOptions << "\n*/\n\n" << sourceCode; } else { buildLog_ += "Warning: opening the file to dump the OpenCL source failed.\n"; } } std::pair<const void*, size_t> hdr; switch(clcStd) { case 120: hdr = std::make_pair(opencl1_2_c_amdgcn, opencl1_2_c_amdgcn_size); break; case 200: hdr = std::make_pair(opencl2_0_c_amdgcn, opencl2_0_c_amdgcn_size); break; default: buildLog_ += "Unsupported requested OpenCL C version (-cl-std).\n"; return false; } File* pch = C->NewTempFile(DT_CL_HEADER); if (pch == NULL || !pch->WriteData((const char*) hdr.first, hdr.second)) { buildLog_ += "Error while opening the opencl-c header "; return false; } driverOptions.append(" -include-pch " + pch->Name()); driverOptions.append(" -Xclang -fno-validate-pch"); // Tokenize the options string into a vector of strings std::istringstream istrstr(driverOptions); std::istream_iterator<std::string> sit(istrstr), end; std::vector<std::string> params(sit, end); // Compile source to IR bool ret = C->CompileToLLVMBitcode(inputs, output, params); buildLog_ += C->Output(); if (!ret) { buildLog_ += "Error: Failed to compile opencl source (from CL to LLVM IR).\n"; return false; } llvmBinary_.assign(output->Buf().data(), output->Size()); elfSectionType_ = amd::OclElf::LLVMIR; if (options->isDumpFlagSet(amd::option::DUMP_BC_ORIGINAL)) { std::ofstream f(options->getDumpFileName("_original.bc").c_str(), std::ios::trunc); if(f.is_open()) { f.write(llvmBinary_.data(), llvmBinary_.size()); } else { buildLog_ += "Warning: opening the file to dump the compiled IR failed.\n"; } } if (clBinary()->saveSOURCE()) { clBinary()->elfOut()->addSection( amd::OclElf::SOURCE, sourceCode.data(), sourceCode.size()); } if (clBinary()->saveLLVMIR()) { clBinary()->elfOut()->addSection( amd::OclElf::LLVMIR, llvmBinary_.data(), llvmBinary_.size(), false); // store the original compile options clBinary()->storeCompileOptions(compileOptions_); } return true; } #endif // defined(WITH_LIGHTNING_COMPILER) bool HSAILProgram::compileImpl( const std::string& sourceCode, const std::vector<const std::string*>& headers, const char** headerIncludeNames, amd::option::Options* options) { #if defined(WITH_LIGHTNING_COMPILER) return compileImpl_LC(sourceCode, headers, headerIncludeNames, options); #else // !defined(WITH_LIGHTNING_COMPILER) acl_error errorCode; aclTargetInfo target; target = g_complibApi._aclGetTargetInfo(LP64_SWITCH("hsail","hsail64"), dev().deviceInfo().complibTarget_, &errorCode); //end if asic info is ready // We dump the source code for each program (param: headers) // into their filenames (headerIncludeNames) into the TEMP // folder specific to the OS and add the include path while // compiling //Find the temp folder for the OS std::string tempFolder = amd::Os::getEnvironment("TEMP"); if (tempFolder.empty()) { tempFolder = amd::Os::getEnvironment("TMP"); if (tempFolder.empty()) { tempFolder = WINDOWS_SWITCH(".","/tmp");; } } //Iterate through each source code and dump it into tmp std::fstream f; std::vector<std::string> headerFileNames(headers.size()); std::vector<std::string> newDirs; for (size_t i = 0; i < headers.size(); ++i) { std::string headerPath = tempFolder; std::string headerIncludeName(headerIncludeNames[i]); // replace / in path with current os's file separator if ( amd::Os::fileSeparator() != '/') { for (std::string::iterator it = headerIncludeName.begin(), end = headerIncludeName.end(); it != end; ++it) { if (*it == '/') *it = amd::Os::fileSeparator(); } } size_t pos = headerIncludeName.rfind(amd::Os::fileSeparator()); if (pos != std::string::npos) { headerPath += amd::Os::fileSeparator(); headerPath += headerIncludeName.substr(0, pos); headerIncludeName = headerIncludeName.substr(pos+1); } if (!amd::Os::pathExists(headerPath)) { bool ret = amd::Os::createPath(headerPath); assert(ret && "failed creating path!"); newDirs.push_back(headerPath); } std::string headerFullName = headerPath + amd::Os::fileSeparator() + headerIncludeName; headerFileNames[i] = headerFullName; f.open(headerFullName.c_str(), std::fstream::out); //Should we allow asserts assert(!f.fail() && "failed creating header file!"); f.write(headers[i]->c_str(), headers[i]->length()); f.close(); } //Create Binary binaryElf_ = g_complibApi._aclBinaryInit(sizeof(aclBinary), &target, &binOpts_, &errorCode); if( errorCode!=ACL_SUCCESS ) { buildLog_ += "Error while compiling opencl source:\ aclBinary init failure \n"; LogWarning("aclBinaryInit failed"); return false; } //Insert opencl into binary errorCode = g_complibApi._aclInsertSection(device().compiler(), binaryElf_, sourceCode.c_str(), strlen(sourceCode.c_str()), aclSOURCE); if ( errorCode != ACL_SUCCESS ) { buildLog_ += "Error while converting to BRIG: \ Inserting openCl Source \n"; } //Set the options for the compiler //Set the include path for the temp folder that contains the includes if(!headers.empty()) { this->compileOptions_.append(" -I"); this->compileOptions_.append(tempFolder); } //Add only for CL2.0 and later if (options->oVariables->CLStd[2] >= '2') { std::stringstream opts; opts << " -D" << "CL_DEVICE_MAX_GLOBAL_VARIABLE_SIZE=" << device().info().maxGlobalVariableSize_; compileOptions_.append(opts.str()); } //Compile source to IR this->compileOptions_.append(preprocessorOptions(options)); this->compileOptions_.append(codegenOptions(options)); errorCode = g_complibApi._aclCompile(device().compiler(), binaryElf_, //"-Wf,--support_all_extensions", this->compileOptions_.c_str(), ACL_TYPE_OPENCL, ACL_TYPE_LLVMIR_BINARY, logFunction); buildLog_ += g_complibApi._aclGetCompilerLog(device().compiler()); if( errorCode!=ACL_SUCCESS ) { LogWarning("aclCompile failed"); buildLog_ += "Error while compiling \ opencl source: Compiling CL to IR"; return false; } // Save the binary in the interface class saveBinaryAndSetType(TYPE_COMPILED); return true; #endif // !defined(WITH_LIGHTNING_COMPILER) } #if defined(WITH_LIGHTNING_COMPILER) #if defined(ATI_OS_LINUX) static pthread_once_t once = PTHREAD_ONCE_INIT; static void checkLLVM_BIN() { if (llvmBin_.empty()) { Dl_info info; if (dladdr((const void*)&amd::Device::init, &info)) { llvmBin_ = dirname(strdup(info.dli_fname)); size_t pos = llvmBin_.rfind("lib"); if (pos != std::string::npos) { llvmBin_.replace(pos, 3, "bin"); } } } #if defined(DEBUG) std::string clangExe(llvmBin_ + "/clang"); struct stat buf; if (stat(clangExe.c_str(), &buf)) { std::string msg("Could not find the Clang binary in " + llvmBin_); LogWarning(msg.c_str()); } #endif // defined(DEBUG) } #endif // defined(ATI_OS_LINUX) std::auto_ptr<amd::opencl_driver::Compiler> HSAILProgram::newCompilerInstance() { #if defined(ATI_OS_LINUX) pthread_once(&once, checkLLVM_BIN); #endif // defined(ATI_OS_LINUX) return std::auto_ptr<amd::opencl_driver::Compiler>( amd::opencl_driver::CompilerFactory().CreateAMDGPUCompiler(llvmBin_)); } #endif // defined(WITH_LIGHTNING_COMPILER) } // namespace roc #endif // WITHOUT_GPU_BACKEND <commit_msg>P4 to Git Change 1323311 by lmoriche@lmoriche_opencl_dev on 2016/10/06 13:26:29<commit_after>// // Copyright (c) 2008 Advanced Micro Devices, Inc. All rights reserved. // #ifndef WITHOUT_HSA_BACKEND #include <string> #include <sstream> #include <fstream> #include <iostream> #include "os/os.hpp" #include "rocdevice.hpp" #include "rocprogram.hpp" #if defined(WITH_LIGHTNING_COMPILER) #include "opencl1.2-c.amdgcn.inc" #include "opencl2.0-c.amdgcn.inc" #else // !defined(WITH_LIGHTNING_COMPILER) #include "roccompilerlib.hpp" #endif // !defined(WITH_LIGHTNING_COMPILER) #include "utils/options.hpp" #include <cstdio> #if defined(ATI_OS_LINUX) #include <dlfcn.h> #include <libgen.h> #endif // defined(ATI_OS_LINUX) #if defined(WITH_LIGHTNING_COMPILER) static std::string llvmBin_(amd::Os::getEnvironment("LLVM_BIN")); #endif // defined(WITH_LIGHTNING_COMPILER) //CLC_IN_PROCESS_CHANGE extern int openclFrontEnd(const char* cmdline, std::string*, std::string* typeInfo = NULL); namespace roc { /* Temporary log function for the compiler library */ static void logFunction(const char* msg, size_t size) { std::cout<< "Compiler Log: " << msg << std::endl; } static int programsCount = 0; #if defined(WITH_LIGHTNING_COMPILER) bool HSAILProgram::compileImpl_LC( const std::string& sourceCode, const std::vector<const std::string*>& headers, const char** headerIncludeNames, amd::option::Options* options) { using namespace amd::opencl_driver; std::auto_ptr<Compiler> C(newCompilerInstance()); std::vector<Data*> inputs; Data* input = C->NewBufferReference(DT_CL, sourceCode.c_str(), sourceCode.length()); if (input == NULL) { buildLog_ += "Error while creating data from source code"; return false; } inputs.push_back(input); Buffer* output = C->NewBuffer(DT_LLVM_BC); if (output == NULL) { buildLog_ += "Error while creating buffer for the LLVM bitcode"; return false; } //Set the options for the compiler std::ostringstream ostrstr; std::copy(options->clangOptions.begin(), options->clangOptions.end(), std::ostream_iterator<std::string>(ostrstr, " ")); ostrstr << " -m" << sizeof(void*) * 8; std::string driverOptions(ostrstr.str()); const char* xLang = options->oVariables->XLang; if (xLang != NULL && strcmp(xLang, "cl")) { buildLog_ += "Unsupported OpenCL language.\n"; } //FIXME_Nikolay: the program manager should be setting the language //driverOptions.append(" -x cl"); driverOptions.append(" -cl-std=").append(options->oVariables->CLStd); // Set the -O# std::ostringstream optLevel; optLevel << " -O" << options->oVariables->OptLevel; driverOptions.append(optLevel.str()); // Set the machine target driverOptions.append(" -mcpu="); driverOptions.append(dev().deviceInfo().machineTarget_); driverOptions.append(options->llvmOptions); driverOptions.append(preprocessorOptions(options)); //Find the temp folder for the OS std::string tempFolder = amd::Os::getEnvironment("TEMP"); if (tempFolder.empty()) { tempFolder = amd::Os::getEnvironment("TMP"); if (tempFolder.empty()) { tempFolder = WINDOWS_SWITCH(".","/tmp");; } } //Iterate through each source code and dump it into tmp std::fstream f; std::vector<std::string> headerFileNames(headers.size()); std::vector<std::string> newDirs; for (size_t i = 0; i < headers.size(); ++i) { std::string headerPath = tempFolder; std::string headerIncludeName(headerIncludeNames[i]); // replace / in path with current os's file separator if ( amd::Os::fileSeparator() != '/') { for (std::string::iterator it = headerIncludeName.begin(), end = headerIncludeName.end(); it != end; ++it) { if (*it == '/') *it = amd::Os::fileSeparator(); } } size_t pos = headerIncludeName.rfind(amd::Os::fileSeparator()); if (pos != std::string::npos) { headerPath += amd::Os::fileSeparator(); headerPath += headerIncludeName.substr(0, pos); headerIncludeName = headerIncludeName.substr(pos+1); } if (!amd::Os::pathExists(headerPath)) { bool ret = amd::Os::createPath(headerPath); assert(ret && "failed creating path!"); newDirs.push_back(headerPath); } std::string headerFullName = headerPath + amd::Os::fileSeparator() + headerIncludeName; headerFileNames[i] = headerFullName; f.open(headerFullName.c_str(), std::fstream::out); //Should we allow asserts assert(!f.fail() && "failed creating header file!"); f.write(headers[i]->c_str(), headers[i]->length()); f.close(); Data* inc = C->NewFileReference(DT_CL_HEADER, headerFileNames[i]); if (inc == NULL) { buildLog_ += "Error while creating data from headers"; return false; } inputs.push_back(inc); } //Set the include path for the temp folder that contains the includes if(!headers.empty()) { driverOptions.append(" -I"); driverOptions.append(tempFolder); } if (options->isDumpFlagSet(amd::option::DUMP_CL)) { std::ofstream f(options->getDumpFileName(".cl").c_str(), std::ios::trunc); if(f.is_open()) { f << "/* Compiler options:\n" \ "-c -emit-llvm -target amdgcn-amd-amdhsa-opencl -x cl " << driverOptions << " -include opencl-c.h " << "\n*/\n\n" << sourceCode; } else { buildLog_ += "Warning: opening the file to dump the OpenCL source failed.\n"; } } //FIXME_lmoriche: has the CL option been validated? uint clcStd = (options->oVariables->CLStd[2] - '0') * 100 + (options->oVariables->CLStd[4] - '0') * 10; std::pair<const void*, size_t> hdr; switch(clcStd) { case 120: hdr = std::make_pair(opencl1_2_c_amdgcn, opencl1_2_c_amdgcn_size); break; case 200: hdr = std::make_pair(opencl2_0_c_amdgcn, opencl2_0_c_amdgcn_size); break; default: buildLog_ += "Unsupported requested OpenCL C version (-cl-std).\n"; return false; } File* pch = C->NewTempFile(DT_CL_HEADER); if (pch == NULL || !pch->WriteData((const char*) hdr.first, hdr.second)) { buildLog_ += "Error while opening the opencl-c header "; return false; } driverOptions.append(" -include-pch " + pch->Name()); driverOptions.append(" -Xclang -fno-validate-pch"); // Tokenize the options string into a vector of strings std::istringstream istrstr(driverOptions); std::istream_iterator<std::string> sit(istrstr), end; std::vector<std::string> params(sit, end); // Compile source to IR bool ret = C->CompileToLLVMBitcode(inputs, output, params); buildLog_ += C->Output(); if (!ret) { buildLog_ += "Error: Failed to compile opencl source (from CL to LLVM IR).\n"; return false; } llvmBinary_.assign(output->Buf().data(), output->Size()); elfSectionType_ = amd::OclElf::LLVMIR; if (options->isDumpFlagSet(amd::option::DUMP_BC_ORIGINAL)) { std::ofstream f(options->getDumpFileName("_original.bc").c_str(), std::ios::trunc); if(f.is_open()) { f.write(llvmBinary_.data(), llvmBinary_.size()); } else { buildLog_ += "Warning: opening the file to dump the compiled IR failed.\n"; } } if (clBinary()->saveSOURCE()) { clBinary()->elfOut()->addSection( amd::OclElf::SOURCE, sourceCode.data(), sourceCode.size()); } if (clBinary()->saveLLVMIR()) { clBinary()->elfOut()->addSection( amd::OclElf::LLVMIR, llvmBinary_.data(), llvmBinary_.size(), false); // store the original compile options clBinary()->storeCompileOptions(compileOptions_); } return true; } #endif // defined(WITH_LIGHTNING_COMPILER) bool HSAILProgram::compileImpl( const std::string& sourceCode, const std::vector<const std::string*>& headers, const char** headerIncludeNames, amd::option::Options* options) { #if defined(WITH_LIGHTNING_COMPILER) return compileImpl_LC(sourceCode, headers, headerIncludeNames, options); #else // !defined(WITH_LIGHTNING_COMPILER) acl_error errorCode; aclTargetInfo target; target = g_complibApi._aclGetTargetInfo(LP64_SWITCH("hsail","hsail64"), dev().deviceInfo().complibTarget_, &errorCode); //end if asic info is ready // We dump the source code for each program (param: headers) // into their filenames (headerIncludeNames) into the TEMP // folder specific to the OS and add the include path while // compiling //Find the temp folder for the OS std::string tempFolder = amd::Os::getEnvironment("TEMP"); if (tempFolder.empty()) { tempFolder = amd::Os::getEnvironment("TMP"); if (tempFolder.empty()) { tempFolder = WINDOWS_SWITCH(".","/tmp");; } } //Iterate through each source code and dump it into tmp std::fstream f; std::vector<std::string> headerFileNames(headers.size()); std::vector<std::string> newDirs; for (size_t i = 0; i < headers.size(); ++i) { std::string headerPath = tempFolder; std::string headerIncludeName(headerIncludeNames[i]); // replace / in path with current os's file separator if ( amd::Os::fileSeparator() != '/') { for (std::string::iterator it = headerIncludeName.begin(), end = headerIncludeName.end(); it != end; ++it) { if (*it == '/') *it = amd::Os::fileSeparator(); } } size_t pos = headerIncludeName.rfind(amd::Os::fileSeparator()); if (pos != std::string::npos) { headerPath += amd::Os::fileSeparator(); headerPath += headerIncludeName.substr(0, pos); headerIncludeName = headerIncludeName.substr(pos+1); } if (!amd::Os::pathExists(headerPath)) { bool ret = amd::Os::createPath(headerPath); assert(ret && "failed creating path!"); newDirs.push_back(headerPath); } std::string headerFullName = headerPath + amd::Os::fileSeparator() + headerIncludeName; headerFileNames[i] = headerFullName; f.open(headerFullName.c_str(), std::fstream::out); //Should we allow asserts assert(!f.fail() && "failed creating header file!"); f.write(headers[i]->c_str(), headers[i]->length()); f.close(); } //Create Binary binaryElf_ = g_complibApi._aclBinaryInit(sizeof(aclBinary), &target, &binOpts_, &errorCode); if( errorCode!=ACL_SUCCESS ) { buildLog_ += "Error while compiling opencl source:\ aclBinary init failure \n"; LogWarning("aclBinaryInit failed"); return false; } //Insert opencl into binary errorCode = g_complibApi._aclInsertSection(device().compiler(), binaryElf_, sourceCode.c_str(), strlen(sourceCode.c_str()), aclSOURCE); if ( errorCode != ACL_SUCCESS ) { buildLog_ += "Error while converting to BRIG: \ Inserting openCl Source \n"; } //Set the options for the compiler //Set the include path for the temp folder that contains the includes if(!headers.empty()) { this->compileOptions_.append(" -I"); this->compileOptions_.append(tempFolder); } //Add only for CL2.0 and later if (options->oVariables->CLStd[2] >= '2') { std::stringstream opts; opts << " -D" << "CL_DEVICE_MAX_GLOBAL_VARIABLE_SIZE=" << device().info().maxGlobalVariableSize_; compileOptions_.append(opts.str()); } //Compile source to IR this->compileOptions_.append(preprocessorOptions(options)); this->compileOptions_.append(codegenOptions(options)); errorCode = g_complibApi._aclCompile(device().compiler(), binaryElf_, //"-Wf,--support_all_extensions", this->compileOptions_.c_str(), ACL_TYPE_OPENCL, ACL_TYPE_LLVMIR_BINARY, logFunction); buildLog_ += g_complibApi._aclGetCompilerLog(device().compiler()); if( errorCode!=ACL_SUCCESS ) { LogWarning("aclCompile failed"); buildLog_ += "Error while compiling \ opencl source: Compiling CL to IR"; return false; } // Save the binary in the interface class saveBinaryAndSetType(TYPE_COMPILED); return true; #endif // !defined(WITH_LIGHTNING_COMPILER) } #if defined(WITH_LIGHTNING_COMPILER) #if defined(ATI_OS_LINUX) static pthread_once_t once = PTHREAD_ONCE_INIT; static void checkLLVM_BIN() { if (llvmBin_.empty()) { Dl_info info; if (dladdr((const void*)&amd::Device::init, &info)) { llvmBin_ = dirname(strdup(info.dli_fname)); size_t pos = llvmBin_.rfind("lib"); if (pos != std::string::npos) { llvmBin_.replace(pos, 3, "bin"); } } } #if defined(DEBUG) std::string clangExe(llvmBin_ + "/clang"); struct stat buf; if (stat(clangExe.c_str(), &buf)) { std::string msg("Could not find the Clang binary in " + llvmBin_); LogWarning(msg.c_str()); } #endif // defined(DEBUG) } #endif // defined(ATI_OS_LINUX) std::auto_ptr<amd::opencl_driver::Compiler> HSAILProgram::newCompilerInstance() { #if defined(ATI_OS_LINUX) pthread_once(&once, checkLLVM_BIN); #endif // defined(ATI_OS_LINUX) return std::auto_ptr<amd::opencl_driver::Compiler>( amd::opencl_driver::CompilerFactory().CreateAMDGPUCompiler(llvmBin_)); } #endif // defined(WITH_LIGHTNING_COMPILER) } // namespace roc #endif // WITHOUT_GPU_BACKEND <|endoftext|>
<commit_before>/* * Copyright 2011, 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 "common.h" #include <string.h> #include <android/bitmap.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /************ * ReadFile * ************/ jlong Java_com_googlecode_leptonica_android_ReadFile_nativeReadMem(JNIEnv *env, jclass clazz, jbyteArray image, jint length) { jbyte *image_buffer = env->GetByteArrayElements(image, NULL); int buffer_length = env->GetArrayLength(image); PIX *pix = pixReadMem((const l_uint8 *) image_buffer, buffer_length); env->ReleaseByteArrayElements(image, image_buffer, JNI_ABORT); return (jlong) pix; } jlong Java_com_googlecode_leptonica_android_ReadFile_nativeReadBytes8(JNIEnv *env, jclass clazz, jbyteArray data, jint w, jint h) { PIX *pix = pixCreateNoInit((l_int32) w, (l_int32) h, 8); l_uint8 **lineptrs = pixSetupByteProcessing(pix, NULL, NULL); jbyte *data_buffer = env->GetByteArrayElements(data, NULL); l_uint8 *byte_buffer = (l_uint8 *) data_buffer; for (int i = 0; i < h; i++) { memcpy(lineptrs[i], (byte_buffer + (i * w)), w); } env->ReleaseByteArrayElements(data, data_buffer, JNI_ABORT); pixCleanupByteProcessing(pix, lineptrs); l_int32 d; pixGetDimensions(pix, &w, &h, &d); LOGE("Created image width w=%d, h=%d, d=%d", w, h, d); return (jlong) pix; } jboolean Java_com_googlecode_leptonica_android_ReadFile_nativeReplaceBytes8(JNIEnv *env, jclass clazz, jlong nativePix, jbyteArray data, jint srcw, jint srch) { PIX *pix = (PIX *) nativePix; l_int32 w, h, d; pixGetDimensions(pix, &w, &h, &d); if (d != 8 || (l_int32) srcw != w || (l_int32) srch != h) { LOGE("Failed to replace bytes at w=%d, h=%d, d=%d with w=%d, h=%d", w, h, d, srcw, srch); return JNI_FALSE; } l_uint8 **lineptrs = pixSetupByteProcessing(pix, NULL, NULL); jbyte *data_buffer = env->GetByteArrayElements(data, NULL); l_uint8 *byte_buffer = (l_uint8 *) data_buffer; for (int i = 0; i < h; i++) { memcpy(lineptrs[i], (byte_buffer + (i * w)), w); } env->ReleaseByteArrayElements(data, data_buffer, JNI_ABORT); pixCleanupByteProcessing(pix, lineptrs); return JNI_TRUE; } jlong Java_com_googlecode_leptonica_android_ReadFile_nativeReadFiles(JNIEnv *env, jclass clazz, jstring dirName, jstring prefix) { PIXA *pixad = NULL; const char *c_dirName = env->GetStringUTFChars(dirName, NULL); if (c_dirName == NULL) { LOGE("could not extract dirName string!"); return JNI_FALSE; } const char *c_prefix = env->GetStringUTFChars(prefix, NULL); if (c_prefix == NULL) { LOGE("could not extract prefix string!"); return JNI_FALSE; } pixad = pixaReadFiles(c_dirName, c_prefix); env->ReleaseStringUTFChars(dirName, c_dirName); env->ReleaseStringUTFChars(prefix, c_prefix); return (jlong) pixad; } jlong Java_com_googlecode_leptonica_android_ReadFile_nativeReadFile(JNIEnv *env, jclass clazz, jstring fileName) { PIX *pixd = NULL; const char *c_fileName = env->GetStringUTFChars(fileName, NULL); if (c_fileName == NULL) { LOGE("could not extract fileName string!"); return JNI_FALSE; } pixd = pixRead(c_fileName); env->ReleaseStringUTFChars(fileName, c_fileName); return (jlong) pixd; } jlong Java_com_googlecode_leptonica_android_ReadFile_nativeReadBitmap(JNIEnv *env, jclass clazz, jobject bitmap) { l_int32 w, h, d; AndroidBitmapInfo info; void* pixels; int ret; if ((ret = AndroidBitmap_getInfo(env, bitmap, &info)) < 0) { LOGE("AndroidBitmap_getInfo() failed ! error=%d", ret); return JNI_FALSE; } if (info.format != ANDROID_BITMAP_FORMAT_RGBA_8888) { LOGE("Bitmap format is not RGBA_8888 !"); return JNI_FALSE; } if ((ret = AndroidBitmap_lockPixels(env, bitmap, &pixels)) < 0) { LOGE("AndroidBitmap_lockPixels() failed ! error=%d", ret); return JNI_FALSE; } PIX *pixd = pixCreate(info.width, info.height, 8); l_uint32 *src = (l_uint32 *) pixels; l_int32 srcWpl = (info.stride / 4); l_uint32 *dst = pixGetData(pixd); l_int32 dstWpl = pixGetWpl(pixd); l_uint8 a, r, g, b, pixel8; for (int y = 0; y < info.height; y++) { l_uint32 *dst_line = dst + (y * dstWpl); l_uint32 *src_line = src + (y * srcWpl); for (int x = 0; x < info.width; x++) { // Get pixel from RGBA_8888 r = *src_line >> SK_R32_SHIFT; g = *src_line >> SK_G32_SHIFT; b = *src_line >> SK_B32_SHIFT; a = *src_line >> SK_A32_SHIFT; pixel8 = (l_uint8)((r + g + b) / 3); // Set pixel to LUMA_8 SET_DATA_BYTE(dst_line, x, pixel8); // Move to the next pixel src_line++; } } AndroidBitmap_unlockPixels(env, bitmap); return (jlong) pixd; } #ifdef __cplusplus } #endif /* __cplusplus */ <commit_msg>Fix return type<commit_after>/* * Copyright 2011, 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 "common.h" #include <string.h> #include <android/bitmap.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /************ * ReadFile * ************/ jlong Java_com_googlecode_leptonica_android_ReadFile_nativeReadMem(JNIEnv *env, jclass clazz, jbyteArray image, jint length) { jbyte *image_buffer = env->GetByteArrayElements(image, NULL); int buffer_length = env->GetArrayLength(image); PIX *pix = pixReadMem((const l_uint8 *) image_buffer, buffer_length); env->ReleaseByteArrayElements(image, image_buffer, JNI_ABORT); return (jlong) pix; } jlong Java_com_googlecode_leptonica_android_ReadFile_nativeReadBytes8(JNIEnv *env, jclass clazz, jbyteArray data, jint w, jint h) { PIX *pix = pixCreateNoInit((l_int32) w, (l_int32) h, 8); l_uint8 **lineptrs = pixSetupByteProcessing(pix, NULL, NULL); jbyte *data_buffer = env->GetByteArrayElements(data, NULL); l_uint8 *byte_buffer = (l_uint8 *) data_buffer; for (int i = 0; i < h; i++) { memcpy(lineptrs[i], (byte_buffer + (i * w)), w); } env->ReleaseByteArrayElements(data, data_buffer, JNI_ABORT); pixCleanupByteProcessing(pix, lineptrs); l_int32 d; pixGetDimensions(pix, &w, &h, &d); LOGE("Created image width w=%d, h=%d, d=%d", w, h, d); return (jlong) pix; } jboolean Java_com_googlecode_leptonica_android_ReadFile_nativeReplaceBytes8(JNIEnv *env, jclass clazz, jlong nativePix, jbyteArray data, jint srcw, jint srch) { PIX *pix = (PIX *) nativePix; l_int32 w, h, d; pixGetDimensions(pix, &w, &h, &d); if (d != 8 || (l_int32) srcw != w || (l_int32) srch != h) { LOGE("Failed to replace bytes at w=%d, h=%d, d=%d with w=%d, h=%d", w, h, d, srcw, srch); return JNI_FALSE; } l_uint8 **lineptrs = pixSetupByteProcessing(pix, NULL, NULL); jbyte *data_buffer = env->GetByteArrayElements(data, NULL); l_uint8 *byte_buffer = (l_uint8 *) data_buffer; for (int i = 0; i < h; i++) { memcpy(lineptrs[i], (byte_buffer + (i * w)), w); } env->ReleaseByteArrayElements(data, data_buffer, JNI_ABORT); pixCleanupByteProcessing(pix, lineptrs); return JNI_TRUE; } jlong Java_com_googlecode_leptonica_android_ReadFile_nativeReadFiles(JNIEnv *env, jclass clazz, jstring dirName, jstring prefix) { PIXA *pixad = NULL; const char *c_dirName = env->GetStringUTFChars(dirName, NULL); if (c_dirName == NULL) { LOGE("could not extract dirName string!"); return (jlong) NULL; } const char *c_prefix = env->GetStringUTFChars(prefix, NULL); if (c_prefix == NULL) { LOGE("could not extract prefix string!"); return (jlong) NULL; } pixad = pixaReadFiles(c_dirName, c_prefix); env->ReleaseStringUTFChars(dirName, c_dirName); env->ReleaseStringUTFChars(prefix, c_prefix); return (jlong) pixad; } jlong Java_com_googlecode_leptonica_android_ReadFile_nativeReadFile(JNIEnv *env, jclass clazz, jstring fileName) { PIX *pixd = NULL; const char *c_fileName = env->GetStringUTFChars(fileName, NULL); if (c_fileName == NULL) { LOGE("could not extract fileName string!"); return (jlong) NULL; } pixd = pixRead(c_fileName); env->ReleaseStringUTFChars(fileName, c_fileName); return (jlong) pixd; } jlong Java_com_googlecode_leptonica_android_ReadFile_nativeReadBitmap(JNIEnv *env, jclass clazz, jobject bitmap) { l_int32 w, h, d; AndroidBitmapInfo info; void* pixels; int ret; if ((ret = AndroidBitmap_getInfo(env, bitmap, &info)) < 0) { LOGE("AndroidBitmap_getInfo() failed ! error=%d", ret); return (jlong) NULL; } if (info.format != ANDROID_BITMAP_FORMAT_RGBA_8888) { LOGE("Bitmap format is not RGBA_8888 !"); return (jlong) NULL; } if ((ret = AndroidBitmap_lockPixels(env, bitmap, &pixels)) < 0) { LOGE("AndroidBitmap_lockPixels() failed ! error=%d", ret); return (jlong) NULL; } PIX *pixd = pixCreate(info.width, info.height, 8); l_uint32 *src = (l_uint32 *) pixels; l_int32 srcWpl = (info.stride / 4); l_uint32 *dst = pixGetData(pixd); l_int32 dstWpl = pixGetWpl(pixd); l_uint8 a, r, g, b, pixel8; for (int y = 0; y < info.height; y++) { l_uint32 *dst_line = dst + (y * dstWpl); l_uint32 *src_line = src + (y * srcWpl); for (int x = 0; x < info.width; x++) { // Get pixel from RGBA_8888 r = *src_line >> SK_R32_SHIFT; g = *src_line >> SK_G32_SHIFT; b = *src_line >> SK_B32_SHIFT; a = *src_line >> SK_A32_SHIFT; pixel8 = (l_uint8)((r + g + b) / 3); // Set pixel to LUMA_8 SET_DATA_BYTE(dst_line, x, pixel8); // Move to the next pixel src_line++; } } AndroidBitmap_unlockPixels(env, bitmap); return (jlong) pixd; } #ifdef __cplusplus } #endif /* __cplusplus */ <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include "precompiled_sal.hxx" #include "sal/config.h" #include "sal/precppunit.hxx" #ifdef WNT #include <windows.h> #endif #include <cstdlib> #include <iostream> #include <limits> #include <string> #include "cppunittester/protectorfactory.hxx" #include "osl/module.h" #include "osl/module.hxx" #include "osl/thread.h" #include "rtl/process.h" #include "rtl/string.h" #include "rtl/string.hxx" #include "rtl/textcvt.h" #include "rtl/ustring.hxx" #include "sal/main.h" #include "sal/types.h" #include "cppunit/CompilerOutputter.h" #include "cppunit/TestResult.h" #include "cppunit/TestResultCollector.h" #include "cppunit/TestRunner.h" #include "cppunit/extensions/TestFactoryRegistry.h" #include "cppunit/plugin/PlugInManager.h" #include "cppunit/portability/Stream.h" #include "boost/noncopyable.hpp" namespace { void usageFailure() { std::cerr << ("Usage: cppunittester (--protector <shared-library-path>" " <function-symbol>)* <shared-library-path>") << std::endl; std::exit(EXIT_FAILURE); } rtl::OUString getArgument(sal_Int32 index) { rtl::OUString arg; rtl_getAppCommandArg(index, &arg.pData); return arg; } std::string convertLazy(rtl::OUString const & s16) { rtl::OString s8(rtl::OUStringToOString(s16, osl_getThreadTextEncoding())); return std::string( s8.getStr(), ((static_cast< sal_uInt32 >(s8.getLength()) > (std::numeric_limits< std::string::size_type >::max)()) ? (std::numeric_limits< std::string::size_type >::max)() : static_cast< std::string::size_type >(s8.getLength()))); } //Output how long each test took class TimingListener : public CppUnit::TestListener , private boost::noncopyable { public: void startTest( CppUnit::Test *) { m_nStartTime = osl_getGlobalTimer(); } void endTest( CppUnit::Test *test ) { sal_uInt32 nEndTime = osl_getGlobalTimer(); std::cout << test->getName() << ": " << nEndTime-m_nStartTime << "ms" << std::endl; } private: sal_uInt32 m_nStartTime; }; //Allow the whole uniting testing framework to be run inside a "Protector" //which knows about uno exceptions, so it can print the content of the //exception before falling over and dying class CPPUNIT_API ProtectedFixtureFunctor : public CppUnit::Functor , private boost::noncopyable { private: const std::string &testlib; const std::string &args; CppUnit::TestResult &result; public: ProtectedFixtureFunctor(const std::string& testlib_, const std::string &args_, CppUnit::TestResult &result_) : testlib(testlib_) , args(args_) , result(result_) { } bool run() const { CppUnit::PlugInManager manager; manager.load(testlib, args); CppUnit::TestRunner runner; runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest()); CppUnit::TestResultCollector collector; result.addListener(&collector); #ifdef TIMETESTS TimingListener timer; result.addListener(&timer); #endif runner.run(result); CppUnit::CompilerOutputter(&collector, CppUnit::stdCErr()).write(); return collector.wasSuccessful(); } virtual bool operator()() const { return run(); } }; } SAL_IMPLEMENT_MAIN() { #ifdef WNT //Disable Dr-Watson in order to crash simply without popup dialogs under //windows DWORD dwMode = SetErrorMode(SEM_NOGPFAULTERRORBOX); SetErrorMode(SEM_NOGPFAULTERRORBOX|dwMode); #ifdef _DEBUG // These functions are present only in the debgging runtime _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG|_CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG|_CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR); _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG|_CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); #endif #endif CppUnit::TestResult result; cppunittester::LibreOfficeProtector *throw_protector = 0; std::string args; std::string testlib; sal_uInt32 index = 0; while (index < rtl_getAppCommandArgCount()) { rtl::OUString arg = getArgument(index); if (!arg.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("--protector"))) { if (testlib.empty()) { testlib = rtl::OUStringToOString(arg, osl_getThreadTextEncoding()).getStr(); args += testlib; } else { args += ' '; args += rtl::OUStringToOString(arg, osl_getThreadTextEncoding()).getStr(); } ++index; continue; } if (rtl_getAppCommandArgCount() - index < 3) { usageFailure(); } rtl::OUString lib(getArgument(index + 1)); rtl::OUString sym(getArgument(index + 2)); oslGenericFunction fn = (new osl::Module(lib, SAL_LOADMODULE_GLOBAL)) ->getFunctionSymbol(sym); throw_protector = fn == 0 ? 0 : (*reinterpret_cast< cppunittester::ProtectorFactory * >(fn))(); if (throw_protector == 0) { std::cerr << "Failure instantiating protector \"" << convertLazy(lib) << "\", \"" << convertLazy(sym) << '"' << std::endl; std::exit(EXIT_FAILURE); } result.pushProtector(throw_protector); index+=3; } bool ok = false; ProtectedFixtureFunctor tests(testlib, args, result); //if the unoprotector was given on the command line, use it to catch //and report the error message of exceptions if (throw_protector) ok = throw_protector->protect(tests); else ok = tests.run(); return ok ? EXIT_SUCCESS : EXIT_FAILURE; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>easier to find leaks if the test harness doesn't leak<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include "precompiled_sal.hxx" #include "sal/config.h" #include "sal/precppunit.hxx" #ifdef WNT #include <windows.h> #endif #include <cstdlib> #include <iostream> #include <limits> #include <string> #include "cppunittester/protectorfactory.hxx" #include "osl/module.h" #include "osl/module.hxx" #include "osl/thread.h" #include "rtl/process.h" #include "rtl/string.h" #include "rtl/string.hxx" #include "rtl/textcvt.h" #include "rtl/ustring.hxx" #include "sal/main.h" #include "sal/types.h" #include "cppunit/CompilerOutputter.h" #include "cppunit/TestResult.h" #include "cppunit/TestResultCollector.h" #include "cppunit/TestRunner.h" #include "cppunit/extensions/TestFactoryRegistry.h" #include "cppunit/plugin/PlugInManager.h" #include "cppunit/portability/Stream.h" #include "boost/noncopyable.hpp" #include "boost/ptr_container/ptr_vector.hpp" namespace { void usageFailure() { std::cerr << ("Usage: cppunittester (--protector <shared-library-path>" " <function-symbol>)* <shared-library-path>") << std::endl; std::exit(EXIT_FAILURE); } rtl::OUString getArgument(sal_Int32 index) { rtl::OUString arg; rtl_getAppCommandArg(index, &arg.pData); return arg; } std::string convertLazy(rtl::OUString const & s16) { rtl::OString s8(rtl::OUStringToOString(s16, osl_getThreadTextEncoding())); return std::string( s8.getStr(), ((static_cast< sal_uInt32 >(s8.getLength()) > (std::numeric_limits< std::string::size_type >::max)()) ? (std::numeric_limits< std::string::size_type >::max)() : static_cast< std::string::size_type >(s8.getLength()))); } //Output how long each test took class TimingListener : public CppUnit::TestListener , private boost::noncopyable { public: void startTest( CppUnit::Test *) { m_nStartTime = osl_getGlobalTimer(); } void endTest( CppUnit::Test *test ) { sal_uInt32 nEndTime = osl_getGlobalTimer(); std::cout << test->getName() << ": " << nEndTime-m_nStartTime << "ms" << std::endl; } private: sal_uInt32 m_nStartTime; }; //Allow the whole uniting testing framework to be run inside a "Protector" //which knows about uno exceptions, so it can print the content of the //exception before falling over and dying class CPPUNIT_API ProtectedFixtureFunctor : public CppUnit::Functor , private boost::noncopyable { private: const std::string &testlib; const std::string &args; CppUnit::TestResult &result; public: ProtectedFixtureFunctor(const std::string& testlib_, const std::string &args_, CppUnit::TestResult &result_) : testlib(testlib_) , args(args_) , result(result_) { } bool run() const { CppUnit::PlugInManager manager; manager.load(testlib, args); CppUnit::TestRunner runner; runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest()); CppUnit::TestResultCollector collector; result.addListener(&collector); #ifdef TIMETESTS TimingListener timer; result.addListener(&timer); #endif runner.run(result); CppUnit::CompilerOutputter(&collector, CppUnit::stdCErr()).write(); return collector.wasSuccessful(); } virtual bool operator()() const { return run(); } }; } SAL_IMPLEMENT_MAIN() { #ifdef WNT //Disable Dr-Watson in order to crash simply without popup dialogs under //windows DWORD dwMode = SetErrorMode(SEM_NOGPFAULTERRORBOX); SetErrorMode(SEM_NOGPFAULTERRORBOX|dwMode); #ifdef _DEBUG // These functions are present only in the debgging runtime _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG|_CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG|_CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR); _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG|_CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); #endif #endif CppUnit::TestResult result; boost::ptr_vector<osl::Module> modules; cppunittester::LibreOfficeProtector *throw_protector = 0; std::string args; std::string testlib; sal_uInt32 index = 0; while (index < rtl_getAppCommandArgCount()) { rtl::OUString arg = getArgument(index); if (!arg.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("--protector"))) { if (testlib.empty()) { testlib = rtl::OUStringToOString(arg, osl_getThreadTextEncoding()).getStr(); args += testlib; } else { args += ' '; args += rtl::OUStringToOString(arg, osl_getThreadTextEncoding()).getStr(); } ++index; continue; } if (rtl_getAppCommandArgCount() - index < 3) { usageFailure(); } rtl::OUString lib(getArgument(index + 1)); rtl::OUString sym(getArgument(index + 2)); modules.push_back(new osl::Module(lib, SAL_LOADMODULE_GLOBAL)); oslGenericFunction fn = modules.back().getFunctionSymbol(sym); throw_protector = fn == 0 ? 0 : (*reinterpret_cast< cppunittester::ProtectorFactory * >(fn))(); if (throw_protector == 0) { std::cerr << "Failure instantiating protector \"" << convertLazy(lib) << "\", \"" << convertLazy(sym) << '"' << std::endl; std::exit(EXIT_FAILURE); } result.pushProtector(throw_protector); index+=3; } bool ok = false; ProtectedFixtureFunctor tests(testlib, args, result); //if the unoprotector was given on the command line, use it to catch //and report the error message of exceptions if (throw_protector) ok = throw_protector->protect(tests); else ok = tests.run(); return ok ? EXIT_SUCCESS : EXIT_FAILURE; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/************************************************************************* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2010 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. ************************************************************************/ #include "precompiled_sal.hxx" #include "sal/config.h" #include <cstdlib> #include <iostream> #include "cppunit/CompilerOutputter.h" #include "cppunit/TestResult.h" #include "cppunit/TestResultCollector.h" #include "cppunit/TestRunner.h" #include "cppunit/extensions/TestFactoryRegistry.h" #include "cppunit/plugin/PlugInManager.h" #include "cppunit/portability/Stream.h" #include "osl/thread.h" #include "rtl/process.h" #include "rtl/string.hxx" #include "rtl/ustring.hxx" #include "sal/main.h" SAL_IMPLEMENT_MAIN() { if (rtl_getAppCommandArgCount() != 1) { std::cerr << "Usage: cppunittest <shared-library-path>" << std::endl; return EXIT_FAILURE; } rtl::OUString path; rtl_getAppCommandArg(0, &path.pData); CppUnit::PlugInManager manager; manager.load( rtl::OUStringToOString(path, osl_getThreadTextEncoding()).getStr()); CppUnit::TestRunner runner; runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest()); CppUnit::TestResult result; CppUnit::TestResultCollector collector; result.addListener(&collector); runner.run(result); CppUnit::CompilerOutputter(&collector, CppUnit::stdCErr()).write(); return collector.wasSuccessful() ? EXIT_SUCCESS : EXIT_FAILURE; } <commit_msg>sb118: typo<commit_after>/************************************************************************* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2010 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. ************************************************************************/ #include "precompiled_sal.hxx" #include "sal/config.h" #include <cstdlib> #include <iostream> #include "cppunit/CompilerOutputter.h" #include "cppunit/TestResult.h" #include "cppunit/TestResultCollector.h" #include "cppunit/TestRunner.h" #include "cppunit/extensions/TestFactoryRegistry.h" #include "cppunit/plugin/PlugInManager.h" #include "cppunit/portability/Stream.h" #include "osl/thread.h" #include "rtl/process.h" #include "rtl/string.hxx" #include "rtl/ustring.hxx" #include "sal/main.h" SAL_IMPLEMENT_MAIN() { if (rtl_getAppCommandArgCount() != 1) { std::cerr << "Usage: cppunittester <shared-library-path>" << std::endl; return EXIT_FAILURE; } rtl::OUString path; rtl_getAppCommandArg(0, &path.pData); CppUnit::PlugInManager manager; manager.load( rtl::OUStringToOString(path, osl_getThreadTextEncoding()).getStr()); CppUnit::TestRunner runner; runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest()); CppUnit::TestResult result; CppUnit::TestResultCollector collector; result.addListener(&collector); runner.run(result); CppUnit::CompilerOutputter(&collector, CppUnit::stdCErr()).write(); return collector.wasSuccessful() ? EXIT_SUCCESS : EXIT_FAILURE; } <|endoftext|>
<commit_before>/* * main.cpp -- irccd main file * * Copyright (c) 2013, 2014, 2015 David Demelier <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <iostream> #include <chrono> #include <js/Js.h> using namespace std::chrono_literals; std::atomic<bool> g_running{true}; void quit(int) { g_running = false; } int main(void) { duk_context *ctx = duk_create_heap_default(); duk_push_c_function(ctx, dukopen_filesystem, 0); duk_call(ctx, 0); duk_put_global_string(ctx, "fs"); irccd::ServerSettings settings; if (duk_peval_file(ctx, "test.js") != 0) { printf("%s\n", duk_safe_to_string(ctx, -1)); info.port = 6667; settings.recotimeout = 3; settings.channels = { { "#staff", "" }, { "#test", "" } }; smanager.add(std::move(info), irccd::Identity(), std::move(settings)); while (g_running) { } duk_destroy_heap(ctx); printf("Quitting...\n"); return 0; } #if 0 #include <cstdlib> #include <cstring> #include <signal.h> #include <Logger.h> #include "Irccd.h" #include "Test.h" #include "PluginManager.h" using namespace irccd; using namespace std; namespace { void quit(int) { Irccd::instance().shutdown(); Irccd::instance().stop(); } void usage() { Logger::warn("usage: %s [-fv] [-c config] [-p pluginpath] [-P plugin]", getprogname()); Logger::fatal(1, " %s test plugin.lua [command] [parameters...]", getprogname()); } } // !namespace int main(int argc, char **argv) { Irccd &irccd = Irccd::instance(); int ch; setprogname("irccd"); atexit([] () { quit(0); }); irccd.initialize(); while ((ch = getopt(argc, argv, "fc:p:P:v")) != -1) { switch (ch) { case 'c': irccd.setConfigPath(string(optarg)); irccd.override(Options::Config); break; case 'f': irccd.setForeground(true); irccd.override(Options::Foreground); break; case 'p': #if defined(WITH_LUA) PluginManager::instance().addPath(string(optarg)); #endif break; case 'P': irccd.deferPlugin(string(optarg)); break; case 'v': Logger::setVerbose(true); irccd.override(Options::Verbose); break; case '?': default: usage(); // NOTREACHED } } argc -= optind; argv += optind; if (argc > 0) { if (strcmp(argv[0], "test") == 0) { #if defined(WITH_LUA) test(argc, argv); // NOTREACHED #else Logger::fatal(1, "irccd: Lua support is disabled"); #endif } if (strcmp(argv[0], "version") == 0) { Logger::setVerbose(true); Logger::log("irccd version %s", VERSION); Logger::log("Copyright (c) 2013, 2014, 2015 David Demelier <[email protected]>"); Logger::log(""); Logger::log("Irccd is a customizable IRC bot daemon compatible with Lua plugins"); Logger::log("to fit your needs."); Logger::log(""); #if defined(WITH_LUA) auto enabled = "enabled"; #else auto enabled = "disabled"; #endif Logger::log("* Lua support is %s", enabled); std::exit(0); } } signal(SIGINT, quit); signal(SIGTERM, quit); #if defined(SIGQUIT) signal(SIGQUIT, quit); #endif return irccd.run(); } #endif <commit_msg>Update main.<commit_after>/* * main.cpp -- irccd main file * * Copyright (c) 2013, 2014, 2015 David Demelier <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <iostream> #include <chrono> #include <js/Js.h> int main(void) { duk_context *ctx = duk_create_heap_default(); duk_push_c_function(ctx, dukopen_filesystem, 0); duk_call(ctx, 0); duk_put_global_string(ctx, "fs"); if (duk_peval_file(ctx, "test.js") != 0) { printf("%s\n", duk_safe_to_string(ctx, -1)); duk_destroy_heap(ctx); return 0; } #if 0 #include <cstdlib> #include <cstring> #include <signal.h> #include <Logger.h> #include "Irccd.h" #include "Test.h" #include "PluginManager.h" using namespace irccd; using namespace std; namespace { void quit(int) { Irccd::instance().shutdown(); Irccd::instance().stop(); } void usage() { Logger::warn("usage: %s [-fv] [-c config] [-p pluginpath] [-P plugin]", getprogname()); Logger::fatal(1, " %s test plugin.lua [command] [parameters...]", getprogname()); } } // !namespace int main(int argc, char **argv) { Irccd &irccd = Irccd::instance(); int ch; setprogname("irccd"); atexit([] () { quit(0); }); irccd.initialize(); while ((ch = getopt(argc, argv, "fc:p:P:v")) != -1) { switch (ch) { case 'c': irccd.setConfigPath(string(optarg)); irccd.override(Options::Config); break; case 'f': irccd.setForeground(true); irccd.override(Options::Foreground); break; case 'p': #if defined(WITH_LUA) PluginManager::instance().addPath(string(optarg)); #endif break; case 'P': irccd.deferPlugin(string(optarg)); break; case 'v': Logger::setVerbose(true); irccd.override(Options::Verbose); break; case '?': default: usage(); // NOTREACHED } } argc -= optind; argv += optind; if (argc > 0) { if (strcmp(argv[0], "test") == 0) { #if defined(WITH_LUA) test(argc, argv); // NOTREACHED #else Logger::fatal(1, "irccd: Lua support is disabled"); #endif } if (strcmp(argv[0], "version") == 0) { Logger::setVerbose(true); Logger::log("irccd version %s", VERSION); Logger::log("Copyright (c) 2013, 2014, 2015 David Demelier <[email protected]>"); Logger::log(""); Logger::log("Irccd is a customizable IRC bot daemon compatible with Lua plugins"); Logger::log("to fit your needs."); Logger::log(""); #if defined(WITH_LUA) auto enabled = "enabled"; #else auto enabled = "disabled"; #endif Logger::log("* Lua support is %s", enabled); std::exit(0); } } signal(SIGINT, quit); signal(SIGTERM, quit); #if defined(SIGQUIT) signal(SIGQUIT, quit); #endif return irccd.run(); } #endif <|endoftext|>
<commit_before>#ifndef MANIFOLDS_FUNCTIONS_IS_FUNCTION_HH #define MANIFOLDS_FUNCTIONS_IS_FUNCTION_HH #include "function.hh" #include <type_traits> #include <utility> #include <tuple> namespace manifolds { //For now just test whether first function is a function template <class Func> struct is_function { typedef typename std::remove_cv< typename std::remove_reference< Func>::type >::type F; typedef std::integral_constant< bool, std::is_base_of< Function, F>::value || std::is_base_of< MultiFunction, F>::value> type; static const bool value = type::value; }; template <class T> struct is_tuple: std::false_type{}; template <class ... Args> struct is_tuple<std::tuple<Args...>>: std::true_type{}; } #endif <commit_msg>Changed meta-function to accomodate new Function format, namely that function is now a template<commit_after>#ifndef MANIFOLDS_FUNCTIONS_IS_FUNCTION_HH #define MANIFOLDS_FUNCTIONS_IS_FUNCTION_HH #include "function.hh" #include <type_traits> #include <utility> #include <tuple> namespace manifolds { //For now just test whether first function is a function template <class F> std::true_type is_function_helper(int,int_<F::input_dim> = int_<F::input_dim>(), int_<F::output_dim> = int_<F::output_dim>(), bool_<F::stateless> = bool_<F::stateless>(), bool_<F::abelian_arithmetic> = bool_<F::abelian_arithmetic>()); template <class> std::false_type is_function_helper(long); template <class F> using is_function = decltype(is_function_helper<F>(0)); template <class T> struct is_tuple: std::false_type{}; template <class ... Args> struct is_tuple<std::tuple<Args...>>: std::true_type{}; } #endif <|endoftext|>
<commit_before>// Copyright 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ozone/wayland/dispatcher.h" #include "ozone/wayland/display.h" #include "ozone/wayland/input/kbd_conversion.h" #include "base/bind.h" #include "base/message_loop/message_pump_ozone.h" #include "content/child/child_thread.h" #include "content/child/child_process.h" #include <errno.h> #include <fcntl.h> #include <sys/epoll.h> #include <sys/socket.h> #include <sys/types.h> #include <wayland-client.h> namespace { content::ChildThread* GetProcessMainThread() { content::ChildProcess* process = content::ChildProcess::current(); DCHECK(process); DCHECK(process->main_thread()); return process ? process->main_thread() : NULL; } } namespace ozonewayland { WaylandDispatcher* WaylandDispatcher::instance_ = NULL; // os-compatibility extern "C" { int osEpollCreateCloExec(void); static int setCloExecOrClose(int fd) { long flags; if (fd == -1) return -1; flags = fcntl(fd, F_GETFD); if (flags == -1) goto err; if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) goto err; return fd; err: close(fd); return -1; } int osEpollCreateCloExec(void) { int fd; #ifdef EPOLL_CLOEXEC fd = epoll_create1(EPOLL_CLOEXEC); if (fd >= 0) return fd; if (errno != EINVAL) return -1; #endif fd = epoll_create(1); return setCloExecOrClose(fd); } } // os-compatibility void WaylandDispatcher::MotionNotify(float x, float y) { if (epoll_fd_) { if (!running) return; PostTaskOnMainLoop(FROM_HERE, base::Bind( &WaylandDispatcher::SendMotionNotify, x, y)); } else { scoped_ptr<ui::MouseEvent> mouseev( new ui::MouseEvent(ui::ET_MOUSE_MOVED, gfx::Point(x, y), gfx::Point(x, y), 0)); PostTaskOnMainLoop(FROM_HERE, base::Bind( &WaylandDispatcher::DispatchEventHelper, base::Passed( mouseev.PassAs<ui::Event>()))); } } void WaylandDispatcher::ButtonNotify(unsigned handle, int state, int flags, float x, float y) { if (epoll_fd_) { if (!running) return; PostTaskOnMainLoop(FROM_HERE, base::Bind(&WaylandDispatcher::SendButtonNotify, handle, state, flags, x, y)); } else { ui::EventType type; if (state == 1) type = ui::ET_MOUSE_PRESSED; else type = ui::ET_MOUSE_RELEASED; scoped_ptr<ui::MouseEvent> mouseev( new ui::MouseEvent(type, gfx::Point(x, y), gfx::Point(x, y), flags)); PostTaskOnMainLoop(FROM_HERE, base::Bind( &WaylandDispatcher::NotifyButtonPress, this, handle)); PostTaskOnMainLoop(FROM_HERE, base::Bind( &WaylandDispatcher::DispatchEventHelper, base::Passed( mouseev.PassAs<ui::Event>()))); } } void WaylandDispatcher::AxisNotify(float x, float y, float xoffset, float yoffset) { if (epoll_fd_) { if (!running) return; PostTaskOnMainLoop(FROM_HERE, base::Bind(&WaylandDispatcher::SendAxisNotify, x, y, xoffset, yoffset)); } else { ui::MouseEvent mouseev( ui::ET_MOUSEWHEEL, gfx::Point(x,y), gfx::Point(x,y), 0); scoped_ptr<ui::MouseWheelEvent> wheelev( new ui::MouseWheelEvent(mouseev, xoffset, yoffset)); PostTaskOnMainLoop(FROM_HERE, base::Bind( &WaylandDispatcher::DispatchEventHelper, base::Passed( wheelev.PassAs<ui::Event>()))); } } void WaylandDispatcher::PointerEnter(unsigned handle, float x, float y) { if (epoll_fd_) { if (!running) return; PostTaskOnMainLoop(FROM_HERE, base::Bind(&WaylandDispatcher::SendPointerEnter, handle, x, y)); } else { scoped_ptr<ui::MouseEvent> mouseev( new ui::MouseEvent(ui::ET_MOUSE_ENTERED, gfx::Point(x, y), gfx::Point(x, y), handle)); PostTaskOnMainLoop(FROM_HERE, base::Bind( &WaylandDispatcher::NotifyPointerEnter, this, handle)); PostTaskOnMainLoop(FROM_HERE, base::Bind( &WaylandDispatcher::DispatchEventHelper, base::Passed( mouseev.PassAs<ui::Event>()))); } } void WaylandDispatcher::PointerLeave(unsigned handle, float x, float y) { if (epoll_fd_) { if (!running) return; PostTaskOnMainLoop(FROM_HERE, base::Bind(&WaylandDispatcher::SendPointerLeave, handle, x, y)); } else { scoped_ptr<ui::MouseEvent> mouseev( new ui::MouseEvent(ui::ET_MOUSE_EXITED, gfx::Point(x, y), gfx::Point(x, y), 0)); PostTaskOnMainLoop(FROM_HERE, base::Bind( &WaylandDispatcher::NotifyPointerLeave, this, handle)); PostTaskOnMainLoop(FROM_HERE, base::Bind( &WaylandDispatcher::DispatchEventHelper, base::Passed( mouseev.PassAs<ui::Event>()))); } } void WaylandDispatcher::KeyNotify(unsigned state, unsigned code, unsigned modifiers) { if (epoll_fd_) { if (!running) return; PostTaskOnMainLoop(FROM_HERE, base::Bind(&WaylandDispatcher::SendKeyNotify, state, code, modifiers)); } else { ui::EventType type; if (state) type = ui::ET_KEY_PRESSED; else type = ui::ET_KEY_RELEASED; scoped_ptr<ui::KeyEvent> keyev( new ui::KeyEvent(type, KeyboardCodeFromXKeysym(code), 0, true)); PostTaskOnMainLoop(FROM_HERE, base::Bind( &WaylandDispatcher::DispatchEventHelper, base::Passed( keyev.PassAs<ui::Event>()))); } } void WaylandDispatcher::OutputSizeChanged(unsigned width, unsigned height) { if (!running || !epoll_fd_) return; PostTaskOnMainLoop(FROM_HERE, base::Bind( &WaylandDispatcher::SendOutputSizeChanged, width, height)); } void WaylandDispatcher::PostTask(Task type) { if (!IsRunning() || ignore_task_) return; switch (type) { case (Flush): message_loop_proxy()->PostTask( FROM_HERE, base::Bind(&WaylandDispatcher::HandleFlush)); break; case (Poll): if (epoll_fd_) { loop_ = base::MessageLoop::current(); if (!running) message_loop_proxy()->PostTask(FROM_HERE, base::Bind( &WaylandDispatcher::DisplayRun, this)); } default: break; } } void WaylandDispatcher::DispatchEvent(scoped_ptr<ui::Event> event) { PostTaskOnMainLoop(FROM_HERE, base::Bind(&WaylandDispatcher::DispatchEventHelper, base::Passed(&event))); } void WaylandDispatcher::PostTaskOnMainLoop( const tracked_objects::Location& from_here, const base::Closure& task) { if (ignore_task_ || !IsRunning() || !loop_) return; loop_->message_loop_proxy()->PostTask(from_here, task); } WaylandDispatcher::WaylandDispatcher(int fd) : Thread("WaylandDispatcher"), ignore_task_(false), running(false), epoll_fd_(0), display_fd_(fd), observer_(NULL) { instance_ = this; if (display_fd_) { epoll_fd_ = osEpollCreateCloExec(); struct epoll_event ep; ep.events = EPOLLIN | EPOLLOUT; ep.data.ptr = 0; epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, display_fd_, &ep); } loop_ = base::MessageLoop::current(); Options options; options.message_loop_type = base::MessageLoop::TYPE_IO; StartWithOptions(options); SetPriority(base::kThreadPriority_Background); } WaylandDispatcher::~WaylandDispatcher() { ignore_task_ = true; loop_ = NULL; running = false; Stop(); if (epoll_fd_) { close(epoll_fd_); epoll_fd_ = 0; } instance_ = NULL; } void WaylandDispatcher::HandleFlush() { wl_display* waylandDisp = WaylandDisplay::GetInstance()->display(); while (wl_display_prepare_read(waylandDisp) != 0) wl_display_dispatch_pending(waylandDisp); wl_display_flush(waylandDisp); wl_display_read_events(waylandDisp); wl_display_dispatch_pending(waylandDisp); } void WaylandDispatcher::DisplayRun(WaylandDispatcher* data) { struct epoll_event ep[16]; int i, count, ret; data->running = 1; // Adopted from: // http://cgit.freedesktop.org/wayland/weston/tree/clients/window.c#n5531. while (1) { wl_display* waylandDisp = WaylandDisplay::GetInstance()->display(); wl_display_dispatch_pending(waylandDisp); if (!data->running) break; ret = wl_display_flush(waylandDisp); if (ret < 0 && errno == EAGAIN) { ep[0].events = EPOLLIN | EPOLLOUT | EPOLLERR | EPOLLHUP; epoll_ctl(data->epoll_fd_, EPOLL_CTL_MOD, data->display_fd_, &ep[0]); } else if (ret < 0) { break; } count = epoll_wait(data->epoll_fd_, ep, 16, -1); for (i = 0; i < count; i++) { int ret; uint32_t event = ep[i].events; if (event & EPOLLERR || event & EPOLLHUP) return; if (event & EPOLLIN) { ret = wl_display_dispatch(waylandDisp); if (ret == -1) return; } if (event & EPOLLOUT) { ret = wl_display_flush(waylandDisp); if (ret == 0) { struct epoll_event eps; memset(&eps, 0, sizeof(eps)); eps.events = EPOLLIN | EPOLLERR | EPOLLHUP; epoll_ctl(data->epoll_fd_, EPOLL_CTL_MOD, data->display_fd_, &eps); } else if (ret == -1 && errno != EAGAIN) { return; } } } } } void WaylandDispatcher::NotifyPointerEnter(WaylandDispatcher* data, unsigned handle) { if (data->observer_) data->observer_->OnWindowEnter(handle); } void WaylandDispatcher::NotifyPointerLeave(WaylandDispatcher* data, unsigned handle) { if (data->observer_) data->observer_->OnWindowLeave(handle); } void WaylandDispatcher::NotifyButtonPress(WaylandDispatcher* data, unsigned handle) { if (data->observer_) data->observer_->OnWindowFocused(handle); } void WaylandDispatcher::DispatchEventHelper(scoped_ptr<ui::Event> key) { base::MessagePumpOzone::Current()->Dispatch(key.get()); } void WaylandDispatcher::SendMotionNotify(float x, float y) { content::ChildThread* thread = GetProcessMainThread(); thread->Send(new WaylandInput_MotionNotify(x, y)); } void WaylandDispatcher::SendButtonNotify(unsigned handle, int state, int flags, float x, float y) { content::ChildThread* thread = GetProcessMainThread(); thread->Send(new WaylandInput_ButtonNotify(handle, state, flags, x, y)); } void WaylandDispatcher::SendAxisNotify(float x, float y, float xoffset, float yoffset) { content::ChildThread* thread = GetProcessMainThread(); thread->Send(new WaylandInput_AxisNotify(x, y, xoffset, yoffset)); } void WaylandDispatcher::SendPointerEnter(unsigned handle, float x, float y) { content::ChildThread* thread = GetProcessMainThread(); thread->Send(new WaylandInput_PointerEnter(handle, x, y)); } void WaylandDispatcher::SendPointerLeave(unsigned handle, float x, float y) { content::ChildThread* thread = GetProcessMainThread(); thread->Send(new WaylandInput_PointerLeave(handle, x, y)); } void WaylandDispatcher::SendKeyNotify(unsigned type, unsigned code, unsigned modifiers) { content::ChildThread* thread = GetProcessMainThread(); thread->Send(new WaylandInput_KeyNotify(type, code, modifiers)); } void WaylandDispatcher::SendOutputSizeChanged(unsigned width, unsigned height) { content::ChildThread* thread = GetProcessMainThread(); thread->Send(new WaylandInput_OutputSize(width, height)); } void WaylandDispatcher::MessageLoopDestroyed() { if (!IsRunning()) return; ignore_task_ = true; loop_ = NULL; running = false; Stop(); } } // namespace ozonewayland <commit_msg>Pass keyboard modifiers correctly.<commit_after>// Copyright 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ozone/wayland/dispatcher.h" #include "ozone/wayland/display.h" #include "ozone/wayland/input/kbd_conversion.h" #include "base/bind.h" #include "base/message_loop/message_pump_ozone.h" #include "content/child/child_thread.h" #include "content/child/child_process.h" #include <errno.h> #include <fcntl.h> #include <sys/epoll.h> #include <sys/socket.h> #include <sys/types.h> #include <wayland-client.h> namespace { content::ChildThread* GetProcessMainThread() { content::ChildProcess* process = content::ChildProcess::current(); DCHECK(process); DCHECK(process->main_thread()); return process ? process->main_thread() : NULL; } } namespace ozonewayland { WaylandDispatcher* WaylandDispatcher::instance_ = NULL; // os-compatibility extern "C" { int osEpollCreateCloExec(void); static int setCloExecOrClose(int fd) { long flags; if (fd == -1) return -1; flags = fcntl(fd, F_GETFD); if (flags == -1) goto err; if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) goto err; return fd; err: close(fd); return -1; } int osEpollCreateCloExec(void) { int fd; #ifdef EPOLL_CLOEXEC fd = epoll_create1(EPOLL_CLOEXEC); if (fd >= 0) return fd; if (errno != EINVAL) return -1; #endif fd = epoll_create(1); return setCloExecOrClose(fd); } } // os-compatibility void WaylandDispatcher::MotionNotify(float x, float y) { if (epoll_fd_) { if (!running) return; PostTaskOnMainLoop(FROM_HERE, base::Bind( &WaylandDispatcher::SendMotionNotify, x, y)); } else { scoped_ptr<ui::MouseEvent> mouseev( new ui::MouseEvent(ui::ET_MOUSE_MOVED, gfx::Point(x, y), gfx::Point(x, y), 0)); PostTaskOnMainLoop(FROM_HERE, base::Bind( &WaylandDispatcher::DispatchEventHelper, base::Passed( mouseev.PassAs<ui::Event>()))); } } void WaylandDispatcher::ButtonNotify(unsigned handle, int state, int flags, float x, float y) { if (epoll_fd_) { if (!running) return; PostTaskOnMainLoop(FROM_HERE, base::Bind(&WaylandDispatcher::SendButtonNotify, handle, state, flags, x, y)); } else { ui::EventType type; if (state == 1) type = ui::ET_MOUSE_PRESSED; else type = ui::ET_MOUSE_RELEASED; scoped_ptr<ui::MouseEvent> mouseev( new ui::MouseEvent(type, gfx::Point(x, y), gfx::Point(x, y), flags)); PostTaskOnMainLoop(FROM_HERE, base::Bind( &WaylandDispatcher::NotifyButtonPress, this, handle)); PostTaskOnMainLoop(FROM_HERE, base::Bind( &WaylandDispatcher::DispatchEventHelper, base::Passed( mouseev.PassAs<ui::Event>()))); } } void WaylandDispatcher::AxisNotify(float x, float y, float xoffset, float yoffset) { if (epoll_fd_) { if (!running) return; PostTaskOnMainLoop(FROM_HERE, base::Bind(&WaylandDispatcher::SendAxisNotify, x, y, xoffset, yoffset)); } else { ui::MouseEvent mouseev( ui::ET_MOUSEWHEEL, gfx::Point(x,y), gfx::Point(x,y), 0); scoped_ptr<ui::MouseWheelEvent> wheelev( new ui::MouseWheelEvent(mouseev, xoffset, yoffset)); PostTaskOnMainLoop(FROM_HERE, base::Bind( &WaylandDispatcher::DispatchEventHelper, base::Passed( wheelev.PassAs<ui::Event>()))); } } void WaylandDispatcher::PointerEnter(unsigned handle, float x, float y) { if (epoll_fd_) { if (!running) return; PostTaskOnMainLoop(FROM_HERE, base::Bind(&WaylandDispatcher::SendPointerEnter, handle, x, y)); } else { scoped_ptr<ui::MouseEvent> mouseev( new ui::MouseEvent(ui::ET_MOUSE_ENTERED, gfx::Point(x, y), gfx::Point(x, y), handle)); PostTaskOnMainLoop(FROM_HERE, base::Bind( &WaylandDispatcher::NotifyPointerEnter, this, handle)); PostTaskOnMainLoop(FROM_HERE, base::Bind( &WaylandDispatcher::DispatchEventHelper, base::Passed( mouseev.PassAs<ui::Event>()))); } } void WaylandDispatcher::PointerLeave(unsigned handle, float x, float y) { if (epoll_fd_) { if (!running) return; PostTaskOnMainLoop(FROM_HERE, base::Bind(&WaylandDispatcher::SendPointerLeave, handle, x, y)); } else { scoped_ptr<ui::MouseEvent> mouseev( new ui::MouseEvent(ui::ET_MOUSE_EXITED, gfx::Point(x, y), gfx::Point(x, y), 0)); PostTaskOnMainLoop(FROM_HERE, base::Bind( &WaylandDispatcher::NotifyPointerLeave, this, handle)); PostTaskOnMainLoop(FROM_HERE, base::Bind( &WaylandDispatcher::DispatchEventHelper, base::Passed( mouseev.PassAs<ui::Event>()))); } } void WaylandDispatcher::KeyNotify(unsigned state, unsigned code, unsigned modifiers) { if (epoll_fd_) { if (!running) return; PostTaskOnMainLoop(FROM_HERE, base::Bind(&WaylandDispatcher::SendKeyNotify, state, code, modifiers)); } else { ui::EventType type; if (state) type = ui::ET_KEY_PRESSED; else type = ui::ET_KEY_RELEASED; scoped_ptr<ui::KeyEvent> keyev( new ui::KeyEvent(type, KeyboardCodeFromXKeysym(code), modifiers, true)); PostTaskOnMainLoop(FROM_HERE, base::Bind( &WaylandDispatcher::DispatchEventHelper, base::Passed( keyev.PassAs<ui::Event>()))); } } void WaylandDispatcher::OutputSizeChanged(unsigned width, unsigned height) { if (!running || !epoll_fd_) return; PostTaskOnMainLoop(FROM_HERE, base::Bind( &WaylandDispatcher::SendOutputSizeChanged, width, height)); } void WaylandDispatcher::PostTask(Task type) { if (!IsRunning() || ignore_task_) return; switch (type) { case (Flush): message_loop_proxy()->PostTask( FROM_HERE, base::Bind(&WaylandDispatcher::HandleFlush)); break; case (Poll): if (epoll_fd_) { loop_ = base::MessageLoop::current(); if (!running) message_loop_proxy()->PostTask(FROM_HERE, base::Bind( &WaylandDispatcher::DisplayRun, this)); } default: break; } } void WaylandDispatcher::DispatchEvent(scoped_ptr<ui::Event> event) { PostTaskOnMainLoop(FROM_HERE, base::Bind(&WaylandDispatcher::DispatchEventHelper, base::Passed(&event))); } void WaylandDispatcher::PostTaskOnMainLoop( const tracked_objects::Location& from_here, const base::Closure& task) { if (ignore_task_ || !IsRunning() || !loop_) return; loop_->message_loop_proxy()->PostTask(from_here, task); } WaylandDispatcher::WaylandDispatcher(int fd) : Thread("WaylandDispatcher"), ignore_task_(false), running(false), epoll_fd_(0), display_fd_(fd), observer_(NULL) { instance_ = this; if (display_fd_) { epoll_fd_ = osEpollCreateCloExec(); struct epoll_event ep; ep.events = EPOLLIN | EPOLLOUT; ep.data.ptr = 0; epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, display_fd_, &ep); } loop_ = base::MessageLoop::current(); Options options; options.message_loop_type = base::MessageLoop::TYPE_IO; StartWithOptions(options); SetPriority(base::kThreadPriority_Background); } WaylandDispatcher::~WaylandDispatcher() { ignore_task_ = true; loop_ = NULL; running = false; Stop(); if (epoll_fd_) { close(epoll_fd_); epoll_fd_ = 0; } instance_ = NULL; } void WaylandDispatcher::HandleFlush() { wl_display* waylandDisp = WaylandDisplay::GetInstance()->display(); while (wl_display_prepare_read(waylandDisp) != 0) wl_display_dispatch_pending(waylandDisp); wl_display_flush(waylandDisp); wl_display_read_events(waylandDisp); wl_display_dispatch_pending(waylandDisp); } void WaylandDispatcher::DisplayRun(WaylandDispatcher* data) { struct epoll_event ep[16]; int i, count, ret; data->running = 1; // Adopted from: // http://cgit.freedesktop.org/wayland/weston/tree/clients/window.c#n5531. while (1) { wl_display* waylandDisp = WaylandDisplay::GetInstance()->display(); wl_display_dispatch_pending(waylandDisp); if (!data->running) break; ret = wl_display_flush(waylandDisp); if (ret < 0 && errno == EAGAIN) { ep[0].events = EPOLLIN | EPOLLOUT | EPOLLERR | EPOLLHUP; epoll_ctl(data->epoll_fd_, EPOLL_CTL_MOD, data->display_fd_, &ep[0]); } else if (ret < 0) { break; } count = epoll_wait(data->epoll_fd_, ep, 16, -1); for (i = 0; i < count; i++) { int ret; uint32_t event = ep[i].events; if (event & EPOLLERR || event & EPOLLHUP) return; if (event & EPOLLIN) { ret = wl_display_dispatch(waylandDisp); if (ret == -1) return; } if (event & EPOLLOUT) { ret = wl_display_flush(waylandDisp); if (ret == 0) { struct epoll_event eps; memset(&eps, 0, sizeof(eps)); eps.events = EPOLLIN | EPOLLERR | EPOLLHUP; epoll_ctl(data->epoll_fd_, EPOLL_CTL_MOD, data->display_fd_, &eps); } else if (ret == -1 && errno != EAGAIN) { return; } } } } } void WaylandDispatcher::NotifyPointerEnter(WaylandDispatcher* data, unsigned handle) { if (data->observer_) data->observer_->OnWindowEnter(handle); } void WaylandDispatcher::NotifyPointerLeave(WaylandDispatcher* data, unsigned handle) { if (data->observer_) data->observer_->OnWindowLeave(handle); } void WaylandDispatcher::NotifyButtonPress(WaylandDispatcher* data, unsigned handle) { if (data->observer_) data->observer_->OnWindowFocused(handle); } void WaylandDispatcher::DispatchEventHelper(scoped_ptr<ui::Event> key) { base::MessagePumpOzone::Current()->Dispatch(key.get()); } void WaylandDispatcher::SendMotionNotify(float x, float y) { content::ChildThread* thread = GetProcessMainThread(); thread->Send(new WaylandInput_MotionNotify(x, y)); } void WaylandDispatcher::SendButtonNotify(unsigned handle, int state, int flags, float x, float y) { content::ChildThread* thread = GetProcessMainThread(); thread->Send(new WaylandInput_ButtonNotify(handle, state, flags, x, y)); } void WaylandDispatcher::SendAxisNotify(float x, float y, float xoffset, float yoffset) { content::ChildThread* thread = GetProcessMainThread(); thread->Send(new WaylandInput_AxisNotify(x, y, xoffset, yoffset)); } void WaylandDispatcher::SendPointerEnter(unsigned handle, float x, float y) { content::ChildThread* thread = GetProcessMainThread(); thread->Send(new WaylandInput_PointerEnter(handle, x, y)); } void WaylandDispatcher::SendPointerLeave(unsigned handle, float x, float y) { content::ChildThread* thread = GetProcessMainThread(); thread->Send(new WaylandInput_PointerLeave(handle, x, y)); } void WaylandDispatcher::SendKeyNotify(unsigned type, unsigned code, unsigned modifiers) { content::ChildThread* thread = GetProcessMainThread(); thread->Send(new WaylandInput_KeyNotify(type, code, modifiers)); } void WaylandDispatcher::SendOutputSizeChanged(unsigned width, unsigned height) { content::ChildThread* thread = GetProcessMainThread(); thread->Send(new WaylandInput_OutputSize(width, height)); } void WaylandDispatcher::MessageLoopDestroyed() { if (!IsRunning()) return; ignore_task_ = true; loop_ = NULL; running = false; Stop(); } } // namespace ozonewayland <|endoftext|>
<commit_before>#include <map> #include <string> #include <vector> #include <cmath> #include "defs.hh" #include "msfgtest.hh" #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> using namespace std; CPPUNIT_TEST_SUITE_REGISTRATION (msfgtest); void msfgtest :: setUp (void) { start_end.assign("*"); } void msfgtest :: tearDown (void) { } void msfgtest :: MultiStringFactorGraphTest1 (void) { MultiStringFactorGraph msfg(start_end); map<string, flt_type> vocab; vocab["k"] = 0.0; vocab["i"] = 0.0; vocab["s"] = 0.0; vocab["a"] = 0.0; vocab["sa"] = 0.0; vocab["ki"] = 0.0; vocab["kis"] = 0.0; vocab["kissa"] = 0.0; vocab["lle"] = 0.0; vocab["kin"] = 0.0; vocab["kala"] = 0.0; string sentence("kissa"); FactorGraph fg(sentence, start_end, vocab, 5); string sentence2("kissallekin"); FactorGraph fg2(sentence2, start_end, vocab, 5); string sentence3("kissakala"); FactorGraph fg3(sentence3, start_end, vocab, 5); msfg.add(fg); CPPUNIT_ASSERT_EQUAL( 1, (int)msfg.string_end_nodes.size() ); CPPUNIT_ASSERT_EQUAL( 7, (int)msfg.num_paths(sentence) ); msfg.add(fg2); CPPUNIT_ASSERT_EQUAL( 2, (int)msfg.string_end_nodes.size() ); CPPUNIT_ASSERT_EQUAL( 7, (int)msfg.num_paths(sentence2) ); msfg.add(fg3); CPPUNIT_ASSERT_EQUAL( 3, (int)msfg.string_end_nodes.size() ); CPPUNIT_ASSERT_EQUAL( 7, (int)msfg.num_paths(sentence3) ); } void msfgtest :: MultiStringFactorGraphTest2 (void) { MultiStringFactorGraph msfg(start_end); map<string, flt_type> vocab; vocab["k"] = 0.0; vocab["i"] = 0.0; vocab["s"] = 0.0; vocab["a"] = 0.0; vocab["sa"] = 0.0; vocab["ki"] = 0.0; vocab["la"] = 0.0; vocab["kis"] = 0.0; vocab["kissa"] = 0.0; vocab["lle"] = 0.0; vocab["kin"] = 0.0; vocab["kala"] = 0.0; string sentence("kissa"); FactorGraph fg(sentence, start_end, vocab, 5); string sentence2("kala"); FactorGraph fg2(sentence2, start_end, vocab, 5); string sentence3("kissakala"); FactorGraph fg3(sentence3, start_end, vocab, 5); msfg.add(fg); msfg.add(fg2); msfg.add(fg3); } // No possible segmentation void msfgtest :: MultiStringFactorGraphTest3 (void) { CPPUNIT_ASSERT (false); } <commit_msg>Failing test case for path counting.<commit_after>#include <map> #include <string> #include <vector> #include <cmath> #include "defs.hh" #include "msfgtest.hh" #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> using namespace std; CPPUNIT_TEST_SUITE_REGISTRATION (msfgtest); void msfgtest :: setUp (void) { start_end.assign("*"); } void msfgtest :: tearDown (void) { } void msfgtest :: MultiStringFactorGraphTest1 (void) { MultiStringFactorGraph msfg(start_end); map<string, flt_type> vocab; vocab["k"] = 0.0; vocab["i"] = 0.0; vocab["s"] = 0.0; vocab["a"] = 0.0; vocab["sa"] = 0.0; vocab["ki"] = 0.0; vocab["kis"] = 0.0; vocab["kissa"] = 0.0; vocab["lle"] = 0.0; vocab["kin"] = 0.0; vocab["kala"] = 0.0; string sentence("kissa"); FactorGraph fg(sentence, start_end, vocab, 5); string sentence2("kissallekin"); FactorGraph fg2(sentence2, start_end, vocab, 5); string sentence3("kissakala"); FactorGraph fg3(sentence3, start_end, vocab, 5); msfg.add(fg); CPPUNIT_ASSERT_EQUAL( 1, (int)msfg.string_end_nodes.size() ); CPPUNIT_ASSERT_EQUAL( 7, (int)msfg.num_paths(sentence) ); msfg.add(fg2); CPPUNIT_ASSERT_EQUAL( 2, (int)msfg.string_end_nodes.size() ); CPPUNIT_ASSERT_EQUAL( 7, (int)msfg.num_paths(sentence2) ); msfg.add(fg3); CPPUNIT_ASSERT_EQUAL( 3, (int)msfg.string_end_nodes.size() ); CPPUNIT_ASSERT_EQUAL( 7, (int)msfg.num_paths(sentence3) ); } void msfgtest :: MultiStringFactorGraphTest2 (void) { MultiStringFactorGraph msfg(start_end); map<string, flt_type> vocab; vocab["k"] = 0.0; vocab["i"] = 0.0; vocab["s"] = 0.0; vocab["a"] = 0.0; vocab["sa"] = 0.0; vocab["ki"] = 0.0; vocab["la"] = 0.0; vocab["kis"] = 0.0; vocab["kissa"] = 0.0; vocab["lle"] = 0.0; vocab["kin"] = 0.0; vocab["kala"] = 0.0; string sentence("kissa"); FactorGraph fg(sentence, start_end, vocab, 5); string sentence2("kala"); FactorGraph fg2(sentence2, start_end, vocab, 5); string sentence3("kissakala"); FactorGraph fg3(sentence3, start_end, vocab, 5); msfg.add(fg); msfg.add(fg2); msfg.add(fg3); } // No possible segmentation void msfgtest :: MultiStringFactorGraphTest3 (void) { MultiStringFactorGraph msfg(start_end); map<string, flt_type> vocab; vocab["aarian"] = 0.0; vocab["aari"] = 0.0; vocab["an"] = 0.0; vocab["a"] = 0.0; vocab["ari"] = 0.0; vocab["ri"] = 0.0; vocab["ar"] = 0.0; vocab["i"] = 0.0; vocab["n"] = 0.0; vocab["r"] = 0.0; string word("aarian"); FactorGraph fg(word, start_end, vocab, 6); msfg.add(fg); vector<vector<string> > paths; msfg.get_paths(word, paths); CPPUNIT_ASSERT_EQUAL( 11, (int)paths.size() ); CPPUNIT_ASSERT_EQUAL( 11, msfg.num_paths(word) ); } <|endoftext|>
<commit_before>#include <aikido/constraint/dart.hpp> #include <aikido/constraint/DifferentiableSubSpace.hpp> #include <aikido/constraint/StackedConstraint.hpp> #include <dart/common/StlHelpers.h> namespace aikido { namespace constraint { //============================================================================= std::unique_ptr<Differentiable> createDifferentiableBounds( std::shared_ptr<statespace::JointStateSpace> _stateSpace) { return detail::ForOneOf< detail::createDifferentiableFor_impl, statespace::JointStateSpace, detail::JointStateSpaceTypeList >::create(std::move(_stateSpace)); } //============================================================================= std::unique_ptr<Differentiable> createDifferentiableBounds( statespace::MetaSkeletonStateSpacePtr _metaSkeleton) { const auto n = _metaSkeleton->getNumStates(); std::vector<std::shared_ptr<Differentiable>> constraints; constraints.reserve(n); // TODO: Filter out trivial constraints for efficiency. for (size_t i = 0; i < n; ++i) { auto subspace = _metaSkeleton->getSubSpace<statespace::JointStateSpace>(i); auto subSpaceConstraint = createDifferentiableBounds(std::move(subspace)); auto constraint = std::make_shared<DifferentiableSubSpace>( _metaSkeleton, std::move(subSpaceConstraint), i); constraints.emplace_back(std::move(constraint)); } // TODO: We should std::move constraints here, but we can't because // StackedConstraint does not take by value. return dart::common::make_unique<StackedConstraint>( constraints, _metaSkeleton); } //============================================================================= std::unique_ptr<Projectable> createProjectableBounds( std::shared_ptr<statespace::JointStateSpace> _stateSpace) { return detail::ForOneOf< detail::createProjectableFor_impl, statespace::JointStateSpace, detail::JointStateSpaceTypeList >::create(std::move(_stateSpace)); } //============================================================================= std::unique_ptr<Projectable> createProjectableBounds( statespace::MetaSkeletonStateSpacePtr _metaSkeleton) { const auto n = _metaSkeleton->getNumStates(); std::vector<std::shared_ptr<Projectable>> constraints; constraints.reserve(n); for (size_t i = 0; i < n; ++i) { auto subspace = _metaSkeleton->getSubSpace<statespace::JointStateSpace>(i); auto constraint = createProjectableBounds(std::move(subspace)); constraints.emplace_back(constraint.release()); } // TODO: Apply a separate constraint to each dimension. throw std::runtime_error("not implemented"); } //============================================================================= std::unique_ptr<TestableConstraint> createTestableBounds( std::shared_ptr<statespace::JointStateSpace> _stateSpace) { return detail::ForOneOf< detail::createTestableFor_impl, statespace::JointStateSpace, detail::JointStateSpaceTypeList >::create(std::move(_stateSpace)); } //============================================================================= std::unique_ptr<TestableConstraint> createTestableBounds( statespace::MetaSkeletonStateSpacePtr _metaSkeleton) { const auto n = _metaSkeleton->getNumStates(); std::vector<std::shared_ptr<TestableConstraint>> constraints; constraints.reserve(n); for (size_t i = 0; i < n; ++i) { auto subspace = _metaSkeleton->getSubSpace<statespace::JointStateSpace>(i); auto constraint = createTestableBounds(std::move(subspace)); constraints.emplace_back(constraint.release()); } // TODO: Apply a separate constraint to each dimension. throw std::runtime_error("not implemented"); } //============================================================================= std::unique_ptr<SampleableConstraint> createSampleableBounds( std::shared_ptr<statespace::JointStateSpace> _stateSpace, std::unique_ptr<util::RNG> _rng) { return detail::ForOneOf< detail::createSampleableFor_impl, statespace::JointStateSpace, detail::JointStateSpaceTypeList >::create(std::move(_stateSpace), std::move(_rng)); } //============================================================================= std::unique_ptr<SampleableConstraint> createSampleableBounds( statespace::MetaSkeletonStateSpacePtr _metaSkeleton, std::unique_ptr<util::RNG> _rng) { // TODO: Create N random number generators. throw std::runtime_error("not implemented"); } } // namespace constraint } // namespace aikido <commit_msg>Added an error check<commit_after>#include <aikido/constraint/dart.hpp> #include <aikido/constraint/DifferentiableSubSpace.hpp> #include <aikido/constraint/StackedConstraint.hpp> #include <dart/common/StlHelpers.h> namespace aikido { namespace constraint { //============================================================================= std::unique_ptr<Differentiable> createDifferentiableBounds( std::shared_ptr<statespace::JointStateSpace> _stateSpace) { return detail::ForOneOf< detail::createDifferentiableFor_impl, statespace::JointStateSpace, detail::JointStateSpaceTypeList >::create(std::move(_stateSpace)); } //============================================================================= std::unique_ptr<Differentiable> createDifferentiableBounds( statespace::MetaSkeletonStateSpacePtr _metaSkeleton) { if (!_metaSkeleton) throw std::invalid_argument("MetaSkeletonStateSpace is nullptr."); const auto n = _metaSkeleton->getNumStates(); std::vector<std::shared_ptr<Differentiable>> constraints; constraints.reserve(n); // TODO: Filter out trivial constraints for efficiency. for (size_t i = 0; i < n; ++i) { auto subspace = _metaSkeleton->getSubSpace<statespace::JointStateSpace>(i); auto subSpaceConstraint = createDifferentiableBounds(std::move(subspace)); auto constraint = std::make_shared<DifferentiableSubSpace>( _metaSkeleton, std::move(subSpaceConstraint), i); constraints.emplace_back(std::move(constraint)); } // TODO: We should std::move constraints here, but we can't because // StackedConstraint does not take by value. return dart::common::make_unique<StackedConstraint>( constraints, _metaSkeleton); } //============================================================================= std::unique_ptr<Projectable> createProjectableBounds( std::shared_ptr<statespace::JointStateSpace> _stateSpace) { return detail::ForOneOf< detail::createProjectableFor_impl, statespace::JointStateSpace, detail::JointStateSpaceTypeList >::create(std::move(_stateSpace)); } //============================================================================= std::unique_ptr<Projectable> createProjectableBounds( statespace::MetaSkeletonStateSpacePtr _metaSkeleton) { const auto n = _metaSkeleton->getNumStates(); std::vector<std::shared_ptr<Projectable>> constraints; constraints.reserve(n); for (size_t i = 0; i < n; ++i) { auto subspace = _metaSkeleton->getSubSpace<statespace::JointStateSpace>(i); auto constraint = createProjectableBounds(std::move(subspace)); constraints.emplace_back(constraint.release()); } // TODO: Apply a separate constraint to each dimension. throw std::runtime_error("not implemented"); } //============================================================================= std::unique_ptr<TestableConstraint> createTestableBounds( std::shared_ptr<statespace::JointStateSpace> _stateSpace) { return detail::ForOneOf< detail::createTestableFor_impl, statespace::JointStateSpace, detail::JointStateSpaceTypeList >::create(std::move(_stateSpace)); } //============================================================================= std::unique_ptr<TestableConstraint> createTestableBounds( statespace::MetaSkeletonStateSpacePtr _metaSkeleton) { const auto n = _metaSkeleton->getNumStates(); std::vector<std::shared_ptr<TestableConstraint>> constraints; constraints.reserve(n); for (size_t i = 0; i < n; ++i) { auto subspace = _metaSkeleton->getSubSpace<statespace::JointStateSpace>(i); auto constraint = createTestableBounds(std::move(subspace)); constraints.emplace_back(constraint.release()); } // TODO: Apply a separate constraint to each dimension. throw std::runtime_error("not implemented"); } //============================================================================= std::unique_ptr<SampleableConstraint> createSampleableBounds( std::shared_ptr<statespace::JointStateSpace> _stateSpace, std::unique_ptr<util::RNG> _rng) { return detail::ForOneOf< detail::createSampleableFor_impl, statespace::JointStateSpace, detail::JointStateSpaceTypeList >::create(std::move(_stateSpace), std::move(_rng)); } //============================================================================= std::unique_ptr<SampleableConstraint> createSampleableBounds( statespace::MetaSkeletonStateSpacePtr _metaSkeleton, std::unique_ptr<util::RNG> _rng) { // TODO: Create N random number generators. throw std::runtime_error("not implemented"); } } // namespace constraint } // namespace aikido <|endoftext|>
<commit_before>/* Copyright (c) 2014, Project OSRM, Dennis Luxen, others All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TINY_COMPONENTS_HPP #define TINY_COMPONENTS_HPP #include "../typedefs.h" #include "../data_structures/deallocating_vector.hpp" #include "../data_structures/import_edge.hpp" #include "../data_structures/query_node.hpp" #include "../data_structures/percent.hpp" #include "../data_structures/restriction.hpp" #include "../data_structures/restriction_map.hpp" #include "../data_structures/turn_instructions.hpp" #include "../Util/integer_range.hpp" #include "../Util/OSRMException.h" #include "../Util/simple_logger.hpp" #include "../Util/std_hash.hpp" #include "../Util/timing_util.hpp" #include <osrm/Coordinate.h> #include <boost/assert.hpp> #include <tbb/parallel_sort.h> #include <cstdint> #include <memory> #include <stack> #include <unordered_map> #include <unordered_set> #include <vector> template <typename GraphT> class TarjanSCC { struct TarjanStackFrame { explicit TarjanStackFrame(NodeID v, NodeID parent) : v(v), parent(parent) {} NodeID v; NodeID parent; }; struct TarjanNode { TarjanNode() : index(SPECIAL_NODEID), low_link(SPECIAL_NODEID), on_stack(false) {} unsigned index; unsigned low_link; bool on_stack; }; std::vector<unsigned> components_index; std::vector<NodeID> component_size_vector; std::shared_ptr<GraphT> m_node_based_graph; std::unordered_set<NodeID> barrier_node_set; RestrictionMap m_restriction_map; unsigned size_one_counter; public: template<class ContainerT> TarjanSCC(std::shared_ptr<GraphT> graph, const RestrictionMap &restrictions, const ContainerT &barrier_node_list) : components_index(graph->GetNumberOfNodes(), SPECIAL_NODEID), m_node_based_graph(graph), m_restriction_map(restrictions), size_one_counter(0) { barrier_node_set.insert(std::begin(barrier_node_list), std::end(barrier_node_list)); BOOST_ASSERT(m_node_based_graph->GetNumberOfNodes() > 0); } void run() { TIMER_START(SCC_RUN); // The following is a hack to distinguish between stuff that happens // before the recursive call and stuff that happens after std::stack<TarjanStackFrame> recursion_stack; // true = stuff before, false = stuff after call std::stack<NodeID> tarjan_stack; std::vector<TarjanNode> tarjan_node_list(m_node_based_graph->GetNumberOfNodes()); unsigned component_index = 0, size_of_current_component = 0; int index = 0; const NodeID last_node = m_node_based_graph->GetNumberOfNodes(); std::vector<bool> processing_node_before_recursion(m_node_based_graph->GetNumberOfNodes(), true); for(const NodeID node : osrm::irange(0u, last_node)) { if (SPECIAL_NODEID == components_index[node]) { recursion_stack.emplace(TarjanStackFrame(node, node)); } while (!recursion_stack.empty()) { TarjanStackFrame currentFrame = recursion_stack.top(); const NodeID u = currentFrame.parent; const NodeID v = currentFrame.v; recursion_stack.pop(); const bool before_recursion = processing_node_before_recursion[v]; if (before_recursion && tarjan_node_list[v].index != UINT_MAX) { continue; } if (before_recursion) { // Mark frame to handle tail of recursion recursion_stack.emplace(currentFrame); processing_node_before_recursion[v] = false; // Mark essential information for SCC tarjan_node_list[v].index = index; tarjan_node_list[v].low_link = index; tarjan_stack.push(v); tarjan_node_list[v].on_stack = true; ++index; // Traverse outgoing edges if (barrier_node_set.find(v) != barrier_node_set.end()) { continue; } const NodeID to_node_of_only_restriction = m_restriction_map.CheckForEmanatingIsOnlyTurn(u, v); for (const auto current_edge : m_node_based_graph->GetAdjacentEdgeRange(v)) { const auto vprime = m_node_based_graph->GetTarget(current_edge); if (to_node_of_only_restriction != std::numeric_limits<unsigned>::max() && vprime == to_node_of_only_restriction) { // At an only_-restriction but not at the right turn // continue; } if (m_restriction_map.CheckIfTurnIsRestricted(u, v, vprime)) { // continue; } if (SPECIAL_NODEID == tarjan_node_list[vprime].index) { recursion_stack.emplace(TarjanStackFrame(vprime, v)); } else { if (tarjan_node_list[vprime].on_stack && tarjan_node_list[vprime].index < tarjan_node_list[v].low_link) { tarjan_node_list[v].low_link = tarjan_node_list[vprime].index; } } } } else { processing_node_before_recursion[v] = true; tarjan_node_list[currentFrame.parent].low_link = std::min(tarjan_node_list[currentFrame.parent].low_link, tarjan_node_list[v].low_link); // after recursion, lets do cycle checking // Check if we found a cycle. This is the bottom part of the recursion if (tarjan_node_list[v].low_link == tarjan_node_list[v].index) { NodeID vprime; do { vprime = tarjan_stack.top(); tarjan_stack.pop(); tarjan_node_list[vprime].on_stack = false; components_index[vprime] = component_index; ++size_of_current_component; } while (v != vprime); component_size_vector.emplace_back(size_of_current_component); if (size_of_current_component > 1000) { SimpleLogger().Write() << "large component [" << component_index << "]=" << size_of_current_component; } ++component_index; size_of_current_component = 0; } } } } TIMER_STOP(SCC_RUN); SimpleLogger().Write() << "SCC run took: " << TIMER_MSEC(SCC_RUN)/1000. << "s"; SimpleLogger().Write() << "identified: " << component_size_vector.size() << " many components"; size_one_counter = std::count_if(component_size_vector.begin(), component_size_vector.end(), [](unsigned value) { return 1 == value; }); SimpleLogger().Write() << "identified " << size_one_counter << " SCCs of size 1"; } std::size_t get_number_of_components() const { return component_size_vector.size(); } unsigned get_component_size(const NodeID node) const { return component_size_vector[components_index[node]]; } }; #endif /* TINY_COMPONENTS_HPP */ <commit_msg>move SCC stats output out of algo implementation<commit_after>/* Copyright (c) 2014, Project OSRM, Dennis Luxen, others All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TINY_COMPONENTS_HPP #define TINY_COMPONENTS_HPP #include "../typedefs.h" #include "../data_structures/deallocating_vector.hpp" #include "../data_structures/import_edge.hpp" #include "../data_structures/query_node.hpp" #include "../data_structures/percent.hpp" #include "../data_structures/restriction.hpp" #include "../data_structures/restriction_map.hpp" #include "../data_structures/turn_instructions.hpp" #include "../Util/integer_range.hpp" #include "../Util/OSRMException.h" #include "../Util/simple_logger.hpp" #include "../Util/std_hash.hpp" #include "../Util/timing_util.hpp" #include <osrm/Coordinate.h> #include <boost/assert.hpp> #include <tbb/parallel_sort.h> #include <cstdint> #include <memory> #include <stack> #include <unordered_map> #include <unordered_set> #include <vector> template <typename GraphT> class TarjanSCC { struct TarjanStackFrame { explicit TarjanStackFrame(NodeID v, NodeID parent) : v(v), parent(parent) {} NodeID v; NodeID parent; }; struct TarjanNode { TarjanNode() : index(SPECIAL_NODEID), low_link(SPECIAL_NODEID), on_stack(false) {} unsigned index; unsigned low_link; bool on_stack; }; std::vector<unsigned> components_index; std::vector<NodeID> component_size_vector; std::shared_ptr<GraphT> m_node_based_graph; std::unordered_set<NodeID> barrier_node_set; RestrictionMap m_restriction_map; unsigned size_one_counter; public: template<class ContainerT> TarjanSCC(std::shared_ptr<GraphT> graph, const RestrictionMap &restrictions, const ContainerT &barrier_node_list) : components_index(graph->GetNumberOfNodes(), SPECIAL_NODEID), m_node_based_graph(graph), m_restriction_map(restrictions), size_one_counter(0) { barrier_node_set.insert(std::begin(barrier_node_list), std::end(barrier_node_list)); BOOST_ASSERT(m_node_based_graph->GetNumberOfNodes() > 0); } void run() { TIMER_START(SCC_RUN); // The following is a hack to distinguish between stuff that happens // before the recursive call and stuff that happens after std::stack<TarjanStackFrame> recursion_stack; // true = stuff before, false = stuff after call std::stack<NodeID> tarjan_stack; std::vector<TarjanNode> tarjan_node_list(m_node_based_graph->GetNumberOfNodes()); unsigned component_index = 0, size_of_current_component = 0; int index = 0; const NodeID last_node = m_node_based_graph->GetNumberOfNodes(); std::vector<bool> processing_node_before_recursion(m_node_based_graph->GetNumberOfNodes(), true); for(const NodeID node : osrm::irange(0u, last_node)) { if (SPECIAL_NODEID == components_index[node]) { recursion_stack.emplace(TarjanStackFrame(node, node)); } while (!recursion_stack.empty()) { TarjanStackFrame currentFrame = recursion_stack.top(); const NodeID u = currentFrame.parent; const NodeID v = currentFrame.v; recursion_stack.pop(); const bool before_recursion = processing_node_before_recursion[v]; if (before_recursion && tarjan_node_list[v].index != UINT_MAX) { continue; } if (before_recursion) { // Mark frame to handle tail of recursion recursion_stack.emplace(currentFrame); processing_node_before_recursion[v] = false; // Mark essential information for SCC tarjan_node_list[v].index = index; tarjan_node_list[v].low_link = index; tarjan_stack.push(v); tarjan_node_list[v].on_stack = true; ++index; // Traverse outgoing edges if (barrier_node_set.find(v) != barrier_node_set.end()) { continue; } const NodeID to_node_of_only_restriction = m_restriction_map.CheckForEmanatingIsOnlyTurn(u, v); for (const auto current_edge : m_node_based_graph->GetAdjacentEdgeRange(v)) { const auto vprime = m_node_based_graph->GetTarget(current_edge); if (to_node_of_only_restriction != std::numeric_limits<unsigned>::max() && vprime == to_node_of_only_restriction) { // At an only_-restriction but not at the right turn // continue; } if (m_restriction_map.CheckIfTurnIsRestricted(u, v, vprime)) { // continue; } if (SPECIAL_NODEID == tarjan_node_list[vprime].index) { recursion_stack.emplace(TarjanStackFrame(vprime, v)); } else { if (tarjan_node_list[vprime].on_stack && tarjan_node_list[vprime].index < tarjan_node_list[v].low_link) { tarjan_node_list[v].low_link = tarjan_node_list[vprime].index; } } } } else { processing_node_before_recursion[v] = true; tarjan_node_list[currentFrame.parent].low_link = std::min(tarjan_node_list[currentFrame.parent].low_link, tarjan_node_list[v].low_link); // after recursion, lets do cycle checking // Check if we found a cycle. This is the bottom part of the recursion if (tarjan_node_list[v].low_link == tarjan_node_list[v].index) { NodeID vprime; do { vprime = tarjan_stack.top(); tarjan_stack.pop(); tarjan_node_list[vprime].on_stack = false; components_index[vprime] = component_index; ++size_of_current_component; } while (v != vprime); component_size_vector.emplace_back(size_of_current_component); if (size_of_current_component > 1000) { SimpleLogger().Write() << "large component [" << component_index << "]=" << size_of_current_component; } ++component_index; size_of_current_component = 0; } } } } TIMER_STOP(SCC_RUN); SimpleLogger().Write() << "SCC run took: " << TIMER_MSEC(SCC_RUN)/1000. << "s"; size_one_counter = std::count_if(component_size_vector.begin(), component_size_vector.end(), [](unsigned value) { return 1 == value; }); } std::size_t get_number_of_components() const { return component_size_vector.size(); } unsigned get_size_one_count() const { return size_one_counter; } unsigned get_component_size(const NodeID node) const { return component_size_vector[components_index[node]]; } }; #endif /* TINY_COMPONENTS_HPP */ <|endoftext|>
<commit_before>void loopdir() { // example of script to loop on all the objects of a ROOT file directory // and print on Postscript all TH1 derived objects // This script uses the file generated by tutorial hsimple.C //Author: Rene Brun TString dir = gSystem->UnixPathName(gInterpreter->GetCurrentMacroName()); dir.ReplaceAll("loopdir.C","../hsimple.C"); dir.ReplaceAll("/./","/"); if (!gInterpreter->IsLoaded(dir.Data())) gInterpreter->LoadMacro(dir.Data()); TFile *f1 = (TFile*)gROOT->ProcessLineFast("hsimple(1)"); TIter next(f1->GetListOfKeys()); TKey *key; TCanvas c1; c1.Print("hsimple.ps["); while ((key = (TKey*)next())) { TClass *cl = gROOT->GetClass(key->GetClassName()); if (!cl->InheritsFrom("TH1")) continue; TH1 *h = (TH1*)key->ReadObj(); h->Draw(); c1.Print("hsimple.ps"); } c1.Print("hsimple.ps]"); } <commit_msg>Do not trigger the creation of hsimple.root, which may create clashes when running in parallel.<commit_after>void loopdir() { // example of script to loop on all the objects of a ROOT file directory // and print on Postscript all TH1 derived objects // This script uses the file generated by tutorial hsimple.C //Author: Rene Brun TFile *f1 = TFile::Open("hsimple.root"); TIter next(f1->GetListOfKeys()); TKey *key; TCanvas c1; c1.Print("hsimple.ps["); while ((key = (TKey*)next())) { TClass *cl = gROOT->GetClass(key->GetClassName()); if (!cl->InheritsFrom("TH1")) continue; TH1 *h = (TH1*)key->ReadObj(); h->Draw(); c1.Print("hsimple.ps"); } c1.Print("hsimple.ps]"); } <|endoftext|>
<commit_before>/* * Copyright (C) 2014 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "mutation.hh" #include "query-result-writer.hh" mutation::data::data(dht::decorated_key&& key, schema_ptr&& schema) : _schema(std::move(schema)) , _dk(std::move(key)) , _p(_schema) { } mutation::data::data(partition_key&& key_, schema_ptr&& schema) : _schema(std::move(schema)) , _dk(dht::global_partitioner().decorate_key(*_schema, std::move(key_))) , _p(_schema) { } mutation::data::data(schema_ptr&& schema, dht::decorated_key&& key, const mutation_partition& mp) : _schema(std::move(schema)) , _dk(std::move(key)) , _p(mp) { } mutation::data::data(schema_ptr&& schema, dht::decorated_key&& key, mutation_partition&& mp) : _schema(std::move(schema)) , _dk(std::move(key)) , _p(std::move(mp)) { } void mutation::set_static_cell(const column_definition& def, atomic_cell_or_collection&& value) { partition().static_row().apply(def, std::move(value)); } void mutation::set_static_cell(const bytes& name, const data_value& value, api::timestamp_type timestamp, ttl_opt ttl) { auto column_def = schema()->get_column_definition(name); if (!column_def) { throw std::runtime_error(sprint("no column definition found for '%s'", name)); } if (!column_def->is_static()) { throw std::runtime_error(sprint("column '%s' is not static", name)); } partition().static_row().apply(*column_def, atomic_cell::make_live(timestamp, column_def->type->decompose(value), ttl)); } void mutation::set_clustered_cell(const exploded_clustering_prefix& prefix, const column_definition& def, atomic_cell_or_collection&& value) { auto& row = partition().clustered_row(clustering_key::from_clustering_prefix(*schema(), prefix)).cells(); row.apply(def, std::move(value)); } void mutation::set_clustered_cell(const clustering_key& key, const bytes& name, const data_value& value, api::timestamp_type timestamp, ttl_opt ttl) { auto column_def = schema()->get_column_definition(name); if (!column_def) { throw std::runtime_error(sprint("no column definition found for '%s'", name)); } return set_clustered_cell(key, *column_def, atomic_cell::make_live(timestamp, column_def->type->decompose(value), ttl)); } void mutation::set_clustered_cell(const clustering_key& key, const column_definition& def, atomic_cell_or_collection&& value) { auto& row = partition().clustered_row(key).cells(); row.apply(def, std::move(value)); } void mutation::set_cell(const exploded_clustering_prefix& prefix, const bytes& name, const data_value& value, api::timestamp_type timestamp, ttl_opt ttl) { auto column_def = schema()->get_column_definition(name); if (!column_def) { throw std::runtime_error(sprint("no column definition found for '%s'", name)); } return set_cell(prefix, *column_def, atomic_cell::make_live(timestamp, column_def->type->decompose(value), ttl)); } void mutation::set_cell(const exploded_clustering_prefix& prefix, const column_definition& def, atomic_cell_or_collection&& value) { if (def.is_static()) { set_static_cell(def, std::move(value)); } else if (def.is_regular()) { set_clustered_cell(prefix, def, std::move(value)); } else { throw std::runtime_error("attemting to store into a key cell"); } } std::experimental::optional<atomic_cell_or_collection> mutation::get_cell(const clustering_key& rkey, const column_definition& def) const { if (def.is_static()) { const atomic_cell_or_collection* cell = partition().static_row().find_cell(def.id); if (!cell) { return {}; } return { *cell }; } else { const row* r = partition().find_row(rkey); if (!r) { return {}; } const atomic_cell_or_collection* cell = r->find_cell(def.id); return { *cell }; } } bool mutation::operator==(const mutation& m) const { return decorated_key().equal(*schema(), m.decorated_key()) && partition().equal(*schema(), m.partition(), *m.schema()); } bool mutation::operator!=(const mutation& m) const { return !(*this == m); } void mutation::query(query::result::builder& builder, const query::partition_slice& slice, gc_clock::time_point now, uint32_t row_limit) && { auto pb = builder.add_partition(*schema(), key()); auto is_reversed = slice.options.contains<query::partition_slice::option::reversed>(); mutation_partition& p = partition(); auto limit = std::min(row_limit, slice.partition_row_limit()); p.compact_for_query(*schema(), now, slice.row_ranges(*schema(), key()), is_reversed, limit); p.query_compacted(pb, *schema(), limit); } query::result mutation::query(const query::partition_slice& slice, query::result_request request, gc_clock::time_point now, uint32_t row_limit) && { query::result::builder builder(slice, request); std::move(*this).query(builder, slice, now, row_limit); return builder.build(); } query::result mutation::query(const query::partition_slice& slice, query::result_request request, gc_clock::time_point now, uint32_t row_limit) const& { return mutation(*this).query(slice, request, now, row_limit); } size_t mutation::live_row_count(gc_clock::time_point query_time) const { return partition().live_row_count(*schema(), query_time); } bool mutation_decorated_key_less_comparator::operator()(const mutation& m1, const mutation& m2) const { return m1.decorated_key().less_compare(*m1.schema(), m2.decorated_key()); } boost::iterator_range<std::vector<mutation>::const_iterator> slice(const std::vector<mutation>& partitions, const query::partition_range& r) { struct cmp { bool operator()(const dht::ring_position& pos, const mutation& m) const { return m.decorated_key().tri_compare(*m.schema(), pos) > 0; }; bool operator()(const mutation& m, const dht::ring_position& pos) const { return m.decorated_key().tri_compare(*m.schema(), pos) < 0; }; }; return boost::make_iterator_range( r.start() ? (r.start()->is_inclusive() ? std::lower_bound(partitions.begin(), partitions.end(), r.start()->value(), cmp()) : std::upper_bound(partitions.begin(), partitions.end(), r.start()->value(), cmp())) : partitions.cbegin(), r.end() ? (r.end()->is_inclusive() ? std::upper_bound(partitions.begin(), partitions.end(), r.end()->value(), cmp()) : std::lower_bound(partitions.begin(), partitions.end(), r.end()->value(), cmp())) : partitions.cend()); } void mutation::upgrade(const schema_ptr& new_schema) { if (_ptr->_schema != new_schema) { schema_ptr s = new_schema; partition().upgrade(*schema(), *new_schema); _ptr->_schema = std::move(s); } } void mutation::apply(mutation&& m) { partition().apply(*schema(), std::move(m.partition()), *m.schema()); } void mutation::apply(const mutation& m) { partition().apply(*schema(), m.partition(), *m.schema()); } mutation& mutation::operator=(const mutation& m) { return *this = mutation(m); } mutation mutation::operator+(const mutation& other) const { auto m = *this; m.apply(other); return m; } mutation& mutation::operator+=(const mutation& other) { apply(other); return *this; } mutation& mutation::operator+=(mutation&& other) { apply(std::move(other)); return *this; } enum class limit_mutation_size { yes, no }; template <limit_mutation_size with_limit> class mutation_rebuilder { mutation _m; streamed_mutation& _sm; size_t _remaining_limit; template <typename T> bool check_remaining_limit(const T& e) { if (with_limit == limit_mutation_size::no) { return true; } size_t size = sizeof(e) + e.external_memory_usage(); if (_remaining_limit <= size) { _remaining_limit = 0; } else { _remaining_limit -= size; } return _remaining_limit > 0; } public: mutation_rebuilder(streamed_mutation& sm) : _m(sm.decorated_key(), sm.schema()), _sm(sm), _remaining_limit(0) { static_assert(with_limit == limit_mutation_size::no, "This constructor should be used only for mutation_rebuildeer with no limit"); } mutation_rebuilder(streamed_mutation& sm, size_t limit) : _m(sm.decorated_key(), sm.schema()), _sm(sm), _remaining_limit(limit) { static_assert(with_limit == limit_mutation_size::yes, "This constructor should be used only for mutation_rebuildeer with limit"); check_remaining_limit(_m.key()); } stop_iteration consume(tombstone t) { _m.partition().apply(t); return stop_iteration::no; } stop_iteration consume(range_tombstone&& rt) { if (!check_remaining_limit(rt)) { return stop_iteration::yes; } _m.partition().apply_row_tombstone(*_m.schema(), std::move(rt)); return stop_iteration::no; } stop_iteration consume(static_row&& sr) { if (!check_remaining_limit(sr)) { return stop_iteration::yes; } _m.partition().static_row().apply(*_m.schema(), column_kind::static_column, std::move(sr.cells())); return stop_iteration::no; } stop_iteration consume(clustering_row&& cr) { if (!check_remaining_limit(cr)) { return stop_iteration::yes; } auto& dr = _m.partition().clustered_row(std::move(cr.key())); dr.apply(cr.tomb()); dr.apply(cr.marker()); dr.cells().apply(*_m.schema(), column_kind::regular_column, std::move(cr.cells())); return stop_iteration::no; } mutation_opt consume_end_of_stream() { return with_limit == limit_mutation_size::yes && _remaining_limit == 0 ? mutation_opt() : mutation_opt(std::move(_m)); } }; future<mutation_opt> mutation_from_streamed_mutation_with_limit(streamed_mutation sm, size_t limit) { return do_with(std::move(sm), [limit] (auto& sm) { return consume(sm, mutation_rebuilder<limit_mutation_size::yes>(sm, limit)); }); } future<mutation_opt> mutation_from_streamed_mutation(streamed_mutation_opt sm) { if (!sm) { return make_ready_future<mutation_opt>(); } return do_with(std::move(*sm), [] (auto& sm) { return consume(sm, mutation_rebuilder<limit_mutation_size::no>(sm)); }); } <commit_msg>mutation_rebuilder: use memory_usage()<commit_after>/* * Copyright (C) 2014 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "mutation.hh" #include "query-result-writer.hh" mutation::data::data(dht::decorated_key&& key, schema_ptr&& schema) : _schema(std::move(schema)) , _dk(std::move(key)) , _p(_schema) { } mutation::data::data(partition_key&& key_, schema_ptr&& schema) : _schema(std::move(schema)) , _dk(dht::global_partitioner().decorate_key(*_schema, std::move(key_))) , _p(_schema) { } mutation::data::data(schema_ptr&& schema, dht::decorated_key&& key, const mutation_partition& mp) : _schema(std::move(schema)) , _dk(std::move(key)) , _p(mp) { } mutation::data::data(schema_ptr&& schema, dht::decorated_key&& key, mutation_partition&& mp) : _schema(std::move(schema)) , _dk(std::move(key)) , _p(std::move(mp)) { } void mutation::set_static_cell(const column_definition& def, atomic_cell_or_collection&& value) { partition().static_row().apply(def, std::move(value)); } void mutation::set_static_cell(const bytes& name, const data_value& value, api::timestamp_type timestamp, ttl_opt ttl) { auto column_def = schema()->get_column_definition(name); if (!column_def) { throw std::runtime_error(sprint("no column definition found for '%s'", name)); } if (!column_def->is_static()) { throw std::runtime_error(sprint("column '%s' is not static", name)); } partition().static_row().apply(*column_def, atomic_cell::make_live(timestamp, column_def->type->decompose(value), ttl)); } void mutation::set_clustered_cell(const exploded_clustering_prefix& prefix, const column_definition& def, atomic_cell_or_collection&& value) { auto& row = partition().clustered_row(clustering_key::from_clustering_prefix(*schema(), prefix)).cells(); row.apply(def, std::move(value)); } void mutation::set_clustered_cell(const clustering_key& key, const bytes& name, const data_value& value, api::timestamp_type timestamp, ttl_opt ttl) { auto column_def = schema()->get_column_definition(name); if (!column_def) { throw std::runtime_error(sprint("no column definition found for '%s'", name)); } return set_clustered_cell(key, *column_def, atomic_cell::make_live(timestamp, column_def->type->decompose(value), ttl)); } void mutation::set_clustered_cell(const clustering_key& key, const column_definition& def, atomic_cell_or_collection&& value) { auto& row = partition().clustered_row(key).cells(); row.apply(def, std::move(value)); } void mutation::set_cell(const exploded_clustering_prefix& prefix, const bytes& name, const data_value& value, api::timestamp_type timestamp, ttl_opt ttl) { auto column_def = schema()->get_column_definition(name); if (!column_def) { throw std::runtime_error(sprint("no column definition found for '%s'", name)); } return set_cell(prefix, *column_def, atomic_cell::make_live(timestamp, column_def->type->decompose(value), ttl)); } void mutation::set_cell(const exploded_clustering_prefix& prefix, const column_definition& def, atomic_cell_or_collection&& value) { if (def.is_static()) { set_static_cell(def, std::move(value)); } else if (def.is_regular()) { set_clustered_cell(prefix, def, std::move(value)); } else { throw std::runtime_error("attemting to store into a key cell"); } } std::experimental::optional<atomic_cell_or_collection> mutation::get_cell(const clustering_key& rkey, const column_definition& def) const { if (def.is_static()) { const atomic_cell_or_collection* cell = partition().static_row().find_cell(def.id); if (!cell) { return {}; } return { *cell }; } else { const row* r = partition().find_row(rkey); if (!r) { return {}; } const atomic_cell_or_collection* cell = r->find_cell(def.id); return { *cell }; } } bool mutation::operator==(const mutation& m) const { return decorated_key().equal(*schema(), m.decorated_key()) && partition().equal(*schema(), m.partition(), *m.schema()); } bool mutation::operator!=(const mutation& m) const { return !(*this == m); } void mutation::query(query::result::builder& builder, const query::partition_slice& slice, gc_clock::time_point now, uint32_t row_limit) && { auto pb = builder.add_partition(*schema(), key()); auto is_reversed = slice.options.contains<query::partition_slice::option::reversed>(); mutation_partition& p = partition(); auto limit = std::min(row_limit, slice.partition_row_limit()); p.compact_for_query(*schema(), now, slice.row_ranges(*schema(), key()), is_reversed, limit); p.query_compacted(pb, *schema(), limit); } query::result mutation::query(const query::partition_slice& slice, query::result_request request, gc_clock::time_point now, uint32_t row_limit) && { query::result::builder builder(slice, request); std::move(*this).query(builder, slice, now, row_limit); return builder.build(); } query::result mutation::query(const query::partition_slice& slice, query::result_request request, gc_clock::time_point now, uint32_t row_limit) const& { return mutation(*this).query(slice, request, now, row_limit); } size_t mutation::live_row_count(gc_clock::time_point query_time) const { return partition().live_row_count(*schema(), query_time); } bool mutation_decorated_key_less_comparator::operator()(const mutation& m1, const mutation& m2) const { return m1.decorated_key().less_compare(*m1.schema(), m2.decorated_key()); } boost::iterator_range<std::vector<mutation>::const_iterator> slice(const std::vector<mutation>& partitions, const query::partition_range& r) { struct cmp { bool operator()(const dht::ring_position& pos, const mutation& m) const { return m.decorated_key().tri_compare(*m.schema(), pos) > 0; }; bool operator()(const mutation& m, const dht::ring_position& pos) const { return m.decorated_key().tri_compare(*m.schema(), pos) < 0; }; }; return boost::make_iterator_range( r.start() ? (r.start()->is_inclusive() ? std::lower_bound(partitions.begin(), partitions.end(), r.start()->value(), cmp()) : std::upper_bound(partitions.begin(), partitions.end(), r.start()->value(), cmp())) : partitions.cbegin(), r.end() ? (r.end()->is_inclusive() ? std::upper_bound(partitions.begin(), partitions.end(), r.end()->value(), cmp()) : std::lower_bound(partitions.begin(), partitions.end(), r.end()->value(), cmp())) : partitions.cend()); } void mutation::upgrade(const schema_ptr& new_schema) { if (_ptr->_schema != new_schema) { schema_ptr s = new_schema; partition().upgrade(*schema(), *new_schema); _ptr->_schema = std::move(s); } } void mutation::apply(mutation&& m) { partition().apply(*schema(), std::move(m.partition()), *m.schema()); } void mutation::apply(const mutation& m) { partition().apply(*schema(), m.partition(), *m.schema()); } mutation& mutation::operator=(const mutation& m) { return *this = mutation(m); } mutation mutation::operator+(const mutation& other) const { auto m = *this; m.apply(other); return m; } mutation& mutation::operator+=(const mutation& other) { apply(other); return *this; } mutation& mutation::operator+=(mutation&& other) { apply(std::move(other)); return *this; } enum class limit_mutation_size { yes, no }; template <limit_mutation_size with_limit> class mutation_rebuilder { mutation _m; streamed_mutation& _sm; size_t _remaining_limit; template <typename T> bool check_remaining_limit(const T& e) { if (with_limit == limit_mutation_size::no) { return true; } size_t size = e.memory_usage(); if (_remaining_limit <= size) { _remaining_limit = 0; } else { _remaining_limit -= size; } return _remaining_limit > 0; } public: mutation_rebuilder(streamed_mutation& sm) : _m(sm.decorated_key(), sm.schema()), _sm(sm), _remaining_limit(0) { static_assert(with_limit == limit_mutation_size::no, "This constructor should be used only for mutation_rebuildeer with no limit"); } mutation_rebuilder(streamed_mutation& sm, size_t limit) : _m(sm.decorated_key(), sm.schema()), _sm(sm), _remaining_limit(limit) { static_assert(with_limit == limit_mutation_size::yes, "This constructor should be used only for mutation_rebuildeer with limit"); check_remaining_limit(_m.key()); } stop_iteration consume(tombstone t) { _m.partition().apply(t); return stop_iteration::no; } stop_iteration consume(range_tombstone&& rt) { if (!check_remaining_limit(rt)) { return stop_iteration::yes; } _m.partition().apply_row_tombstone(*_m.schema(), std::move(rt)); return stop_iteration::no; } stop_iteration consume(static_row&& sr) { if (!check_remaining_limit(sr)) { return stop_iteration::yes; } _m.partition().static_row().apply(*_m.schema(), column_kind::static_column, std::move(sr.cells())); return stop_iteration::no; } stop_iteration consume(clustering_row&& cr) { if (!check_remaining_limit(cr)) { return stop_iteration::yes; } auto& dr = _m.partition().clustered_row(std::move(cr.key())); dr.apply(cr.tomb()); dr.apply(cr.marker()); dr.cells().apply(*_m.schema(), column_kind::regular_column, std::move(cr.cells())); return stop_iteration::no; } mutation_opt consume_end_of_stream() { return with_limit == limit_mutation_size::yes && _remaining_limit == 0 ? mutation_opt() : mutation_opt(std::move(_m)); } }; future<mutation_opt> mutation_from_streamed_mutation_with_limit(streamed_mutation sm, size_t limit) { return do_with(std::move(sm), [limit] (auto& sm) { return consume(sm, mutation_rebuilder<limit_mutation_size::yes>(sm, limit)); }); } future<mutation_opt> mutation_from_streamed_mutation(streamed_mutation_opt sm) { if (!sm) { return make_ready_future<mutation_opt>(); } return do_with(std::move(*sm), [] (auto& sm) { return consume(sm, mutation_rebuilder<limit_mutation_size::no>(sm)); }); } <|endoftext|>
<commit_before>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Guido Tack <[email protected]> */ /* 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 <iostream> #include <fstream> #include <ctime> #include <iomanip> #include <minizinc/model.hh> #include <minizinc/parser.hh> #include <minizinc/prettyprinter.hh> #include <minizinc/typecheck.hh> #include <minizinc/exception.hh> #include <minizinc/flatten.hh> #include <minizinc/optimize.hh> #include <minizinc/builtins.hh> using namespace MiniZinc; using namespace std; std::string stoptime(clock_t& start) { std::ostringstream oss; clock_t now = clock(); oss << std::setprecision(0) << std::fixed << ((static_cast<double>(now-start) / CLOCKS_PER_SEC) * 1000.0) << " ms"; start = now; return oss.str(); } int main(int argc, char** argv) { int i=1; string filename; vector<string> datafiles; vector<string> includePaths; bool flag_ignoreStdlib = false; bool flag_typecheck = true; bool flag_eval = true; bool flag_verbose = false; bool flag_newfzn = false; bool flag_optimize = true; clock_t starttime = std::clock(); clock_t lasttime = std::clock(); string std_lib_dir; if (char* MZNSTDLIBDIR = getenv("MZN_STDLIB_DIR")) { std_lib_dir = string(MZNSTDLIBDIR); } string globals_dir; bool flag_no_output_ozn = false; string flag_output_base; string flag_output_fzn; string flag_output_ozn; bool flag_output_fzn_stdout = false; bool flag_output_ozn_stdout = false; FlatteningOptions fopts; if (argc < 2) goto error; GC::init(); for (;;) { if (string(argv[i])==string("-h") || string(argv[i])==string("--help")) goto error; if (string(argv[i])==string("--version")) { std::cout << "NICTA MiniZinc to FlatZinc converter, version " << MZN_VERSION_MAJOR << "." << MZN_VERSION_MINOR << "." << MZN_VERSION_PATCH << std::endl; std::cout << "Copyright (C) 2014 Monash University and NICTA" << std::endl; std::exit(EXIT_SUCCESS); } if (string(argv[i])==string("-I")) { i++; if (i==argc) { goto error; } includePaths.push_back(argv[i]+string("/")); } else if (string(argv[i])==string("--ignore-stdlib")) { flag_ignoreStdlib = true; } else if (string(argv[i])==string("--no-typecheck")) { flag_typecheck = false; flag_eval=false; } else if (string(argv[i])==string("--no-eval")) { flag_eval = false; } else if (string(argv[i])==string("--verbose")) { flag_verbose = true; } else if (string(argv[i])==string("--newfzn")) { flag_newfzn = true; } else if (string(argv[i])==string("--no-optimize")) { flag_optimize = false; } else if (string(argv[i])==string("--no-output-ozn") || string(argv[i])==string("-O-")) { flag_no_output_ozn = false; } else if (string(argv[i])=="--output-base") { i++; if (i==argc) goto error; flag_output_base = argv[i]; } else if (string(argv[i])=="-o" || string(argv[i])=="--output-to-file" || string(argv[i])=="--output-fzn-to-file") { i++; if (i==argc) goto error; flag_output_fzn = argv[i]; } else if (string(argv[i])=="--output-ozn-to-file") { i++; if (i==argc) goto error; flag_output_ozn = argv[i]; } else if (string(argv[i])=="--output-to-stdout" || string(argv[i])=="--output-fzn-to-stdout") { flag_output_fzn_stdout = true; } else if (string(argv[i])=="--output-ozn-to-stdout") { flag_output_ozn_stdout = true; } else if (string(argv[i])=="--stdlib-dir") { i++; if (i==argc) goto error; std_lib_dir = argv[i]; } else if (string(argv[i])=="-G" || string(argv[i])=="--globals-dir" || string(argv[i])=="--mzn-globals-dir") { i++; if (i==argc) goto error; globals_dir = argv[i]; } else if (string(argv[i])=="--only-range-domains") { fopts.onlyRangeDomains = true; } else { break; } i++; } if (std_lib_dir=="") { std::cerr << "Error: unknown minizinc standard library directory.\n" << "Specify --stdlib-dir on the command line or set the\n" << "MZN_STDLIB_DIR environment variable.\n"; std::exit(EXIT_FAILURE); } if (globals_dir!="") { includePaths.push_back(std_lib_dir+"/"+globals_dir+"/"); } includePaths.push_back(std_lib_dir+"/std/"); if (i==argc) { goto error; } filename = argv[i++]; if (filename.length()<=4 || filename.substr(filename.length()-4,string::npos) != ".mzn") goto error; if (flag_output_base == "") { flag_output_base = filename.substr(0,filename.length()-4); } if (flag_output_fzn == "") { flag_output_fzn = flag_output_base+".fzn"; } if (flag_output_ozn == "") { flag_output_ozn = flag_output_base+".ozn"; } while (i<argc) { std::string datafile = argv[i++]; if (datafile.length()<=4 || datafile.substr(datafile.length()-4,string::npos) != ".dzn") goto error; datafiles.push_back(datafile); } { std::stringstream errstream; if (flag_verbose) std::cerr << "Parsing '" << filename << "' ..."; if (Model* m = parse(filename, datafiles, includePaths, flag_ignoreStdlib, errstream)) { try { if (flag_typecheck) { if (flag_verbose) std::cerr << " done (" << stoptime(lasttime) << ")" << std::endl; if (flag_verbose) std::cerr << "Typechecking ..."; MiniZinc::typecheck(m); MiniZinc::registerBuiltins(m); if (flag_verbose) std::cerr << " done (" << stoptime(lasttime) << ")" << std::endl; if (flag_verbose) std::cerr << "Flattening ..."; Env env(m); try { flatten(env,fopts); } catch (LocationException& e) { if (flag_verbose) std::cerr << std::endl; std::cerr << e.what() << ": " << e.msg() << std::endl; std::cerr << e.loc() << std::endl; env.dumpErrorStack(std::cerr); exit(EXIT_FAILURE); } Model* flat = env.flat(); if (flag_verbose) std::cerr << " done (" << stoptime(lasttime) << ")" << std::endl; if (flag_optimize) { if (flag_verbose) std::cerr << "Optimizing ..."; optimize(env); if (flag_verbose) std::cerr << " done (" << stoptime(lasttime) << ")" << std::endl; } if (!flag_newfzn) { if (flag_verbose) std::cerr << "Converting to old FlatZinc ..."; oldflatzinc(env); if (flag_verbose) std::cerr << " done (" << stoptime(lasttime) << ")" << std::endl; } if (flag_verbose) std::cerr << "Printing FlatZinc ..."; if (flag_output_fzn_stdout) { Printer p(std::cout,0); p.print(flat); } else { std::ofstream os; os.open(flag_output_fzn.c_str(), ios::out); Printer p(os,0); p.print(flat); os.close(); } if (flag_verbose) std::cerr << " done (" << stoptime(lasttime) << ")" << std::endl; if (!flag_no_output_ozn) { if (flag_verbose) std::cerr << "Printing .ozn ..."; if (flag_output_ozn_stdout) { Printer p(std::cout,0); p.print(env.output()); } else { std::ofstream os; os.open(flag_output_ozn.c_str(), ios::out); Printer p(os,0); p.print(env.output()); os.close(); } if (flag_verbose) std::cerr << " done (" << stoptime(lasttime) << ")" << std::endl; } } else { // !flag_typecheck Printer p(std::cout); p.print(m); } } catch (LocationException& e) { if (flag_verbose) std::cerr << std::endl; std::cerr << e.what() << ": " << e.msg() << std::endl; std::cerr << e.loc() << std::endl; exit(EXIT_FAILURE); } catch (Exception& e) { if (flag_verbose) std::cerr << std::endl; std::cerr << e.what() << ": " << e.msg() << std::endl; exit(EXIT_FAILURE); } delete m; } else { if (flag_verbose) std::cerr << std::endl; std::copy(istreambuf_iterator<char>(errstream),istreambuf_iterator<char>(),ostreambuf_iterator<char>(std::cerr)); } } if (flag_verbose) std::cerr << "Done (overall time " << stoptime(starttime) << ")." << std::endl; return 0; error: std::cerr << "Usage: "<< argv[0] << " [<options>] [-I <include path>] <model>.mzn [<data>.dzn ...]" << std::endl << std::endl << "Options:" << std::endl << " --help, -h\n Print this help message" << std::endl << " --version\n Print version information" << std::endl << " --ignore-stdlib\n Ignore the standard libraries stdlib.mzn and builtins.mzn" << std::endl << " --newfzn\n Output in the new FlatZinc format" << std::endl << " --verbose\n Print progress statements" << std::endl << " --no-typecheck\n Do not typecheck (implies --no-eval)" << std::endl << " --no-eval\n Do not evaluate" << std::endl << " --no-optimize\n Do not optimize the FlatZinc (may speed up large instances)" << std::endl << " --no-output-ozn, -O-\n Do not output ozn file" << std::endl << " --output-base <name>\n Base name for output files" << std::endl << " -o <file>, --output-to-file <file>, --output-fzn-to-file <file>\n Filename for generated FlatZinc output" << std::endl << " --output-ozn-to-file <file>\n Filename for model output specification" << std::endl << " --output-to-stdout, --output-fzn-to-stdout\n Print generated FlatZinc to standard output" << std::endl << " --output-ozn-to-stdout\n Print model output specification to standard output" << std::endl << " --stdlib-dir <dir>\n Path to MiniZinc standard library directory" << std::endl << " -G --globals-dir --mzn-globals-dir\n Search for included files in <stdlib>/<dir>." << std::endl ; exit(EXIT_FAILURE); } <commit_msg>Support short command line arguments (like -Gg12_fd)<commit_after>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Guido Tack <[email protected]> */ /* 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 <iostream> #include <fstream> #include <ctime> #include <iomanip> #include <minizinc/model.hh> #include <minizinc/parser.hh> #include <minizinc/prettyprinter.hh> #include <minizinc/typecheck.hh> #include <minizinc/exception.hh> #include <minizinc/flatten.hh> #include <minizinc/optimize.hh> #include <minizinc/builtins.hh> using namespace MiniZinc; using namespace std; std::string stoptime(clock_t& start) { std::ostringstream oss; clock_t now = clock(); oss << std::setprecision(0) << std::fixed << ((static_cast<double>(now-start) / CLOCKS_PER_SEC) * 1000.0) << " ms"; start = now; return oss.str(); } bool beginswith(string s, string t) { return s.compare(0, t.length(), t)==0; } int main(int argc, char** argv) { int i=1; string filename; vector<string> datafiles; vector<string> includePaths; bool flag_ignoreStdlib = false; bool flag_typecheck = true; bool flag_eval = true; bool flag_verbose = false; bool flag_newfzn = false; bool flag_optimize = true; clock_t starttime = std::clock(); clock_t lasttime = std::clock(); string std_lib_dir; if (char* MZNSTDLIBDIR = getenv("MZN_STDLIB_DIR")) { std_lib_dir = string(MZNSTDLIBDIR); } string globals_dir; bool flag_no_output_ozn = false; string flag_output_base; string flag_output_fzn; string flag_output_ozn; bool flag_output_fzn_stdout = false; bool flag_output_ozn_stdout = false; FlatteningOptions fopts; if (argc < 2) goto error; GC::init(); for (;;) { if (string(argv[i])==string("-h") || string(argv[i])==string("--help")) goto error; if (string(argv[i])==string("--version")) { std::cout << "NICTA MiniZinc to FlatZinc converter, version " << MZN_VERSION_MAJOR << "." << MZN_VERSION_MINOR << "." << MZN_VERSION_PATCH << std::endl; std::cout << "Copyright (C) 2014 Monash University and NICTA" << std::endl; std::exit(EXIT_SUCCESS); } if (beginswith(string(argv[i]),"-I")) { string include(argv[i]); if (include.length() > 2) { includePaths.push_back(include.substr(2)+string("/")); } else { i++; if (i==argc) { goto error; } includePaths.push_back(argv[i]+string("/")); } } else if (string(argv[i])==string("--ignore-stdlib")) { flag_ignoreStdlib = true; } else if (string(argv[i])==string("--no-typecheck")) { flag_typecheck = false; flag_eval=false; } else if (string(argv[i])==string("--no-eval")) { flag_eval = false; } else if (string(argv[i])==string("--verbose")) { flag_verbose = true; } else if (string(argv[i])==string("--newfzn")) { flag_newfzn = true; } else if (string(argv[i])==string("--no-optimize")) { flag_optimize = false; } else if (string(argv[i])==string("--no-output-ozn") || string(argv[i])==string("-O-")) { flag_no_output_ozn = false; } else if (string(argv[i])=="--output-base") { i++; if (i==argc) goto error; flag_output_base = argv[i]; } else if (beginswith(string(argv[i]),"-o")) { string filename(argv[i]); if (filename.length() > 2) { flag_output_fzn = filename.substr(2); } else { i++; if (i==argc) { goto error; } flag_output_fzn = argv[i]; } } else if (string(argv[i])=="--output-to-file" || string(argv[i])=="--output-fzn-to-file") { i++; if (i==argc) goto error; flag_output_fzn = argv[i]; } else if (string(argv[i])=="--output-ozn-to-file") { i++; if (i==argc) goto error; flag_output_ozn = argv[i]; } else if (string(argv[i])=="--output-to-stdout" || string(argv[i])=="--output-fzn-to-stdout") { flag_output_fzn_stdout = true; } else if (string(argv[i])=="--output-ozn-to-stdout") { flag_output_ozn_stdout = true; } else if (string(argv[i])=="--stdlib-dir") { i++; if (i==argc) goto error; std_lib_dir = argv[i]; } else if (beginswith(string(argv[i]),"-G")) { string filename(argv[i]); if (filename.length() > 2) { globals_dir = filename.substr(2); } else { i++; if (i==argc) { goto error; } globals_dir = argv[i]; } } else if (string(argv[i])=="--globals-dir" || string(argv[i])=="--mzn-globals-dir") { i++; if (i==argc) goto error; globals_dir = argv[i]; } else if (string(argv[i])=="--only-range-domains") { fopts.onlyRangeDomains = true; } else { break; } i++; if (i==argc) goto error; } if (std_lib_dir=="") { std::cerr << "Error: unknown minizinc standard library directory.\n" << "Specify --stdlib-dir on the command line or set the\n" << "MZN_STDLIB_DIR environment variable.\n"; std::exit(EXIT_FAILURE); } if (globals_dir!="") { includePaths.push_back(std_lib_dir+"/"+globals_dir+"/"); } includePaths.push_back(std_lib_dir+"/std/"); if (i==argc) { goto error; } filename = argv[i++]; if (filename.length()<=4 || filename.substr(filename.length()-4,string::npos) != ".mzn") goto error; if (flag_output_base == "") { flag_output_base = filename.substr(0,filename.length()-4); } if (flag_output_fzn == "") { flag_output_fzn = flag_output_base+".fzn"; } if (flag_output_ozn == "") { flag_output_ozn = flag_output_base+".ozn"; } while (i<argc) { std::string datafile = argv[i++]; if (datafile.length()<=4 || datafile.substr(datafile.length()-4,string::npos) != ".dzn") goto error; datafiles.push_back(datafile); } { std::stringstream errstream; if (flag_verbose) std::cerr << "Parsing '" << filename << "' ..."; if (Model* m = parse(filename, datafiles, includePaths, flag_ignoreStdlib, errstream)) { try { if (flag_typecheck) { if (flag_verbose) std::cerr << " done (" << stoptime(lasttime) << ")" << std::endl; if (flag_verbose) std::cerr << "Typechecking ..."; MiniZinc::typecheck(m); MiniZinc::registerBuiltins(m); if (flag_verbose) std::cerr << " done (" << stoptime(lasttime) << ")" << std::endl; if (flag_verbose) std::cerr << "Flattening ..."; Env env(m); try { flatten(env,fopts); } catch (LocationException& e) { if (flag_verbose) std::cerr << std::endl; std::cerr << e.what() << ": " << e.msg() << std::endl; std::cerr << e.loc() << std::endl; env.dumpErrorStack(std::cerr); exit(EXIT_FAILURE); } Model* flat = env.flat(); if (flag_verbose) std::cerr << " done (" << stoptime(lasttime) << ")" << std::endl; if (flag_optimize) { if (flag_verbose) std::cerr << "Optimizing ..."; optimize(env); if (flag_verbose) std::cerr << " done (" << stoptime(lasttime) << ")" << std::endl; } if (!flag_newfzn) { if (flag_verbose) std::cerr << "Converting to old FlatZinc ..."; oldflatzinc(env); if (flag_verbose) std::cerr << " done (" << stoptime(lasttime) << ")" << std::endl; } if (flag_verbose) std::cerr << "Printing FlatZinc ..."; if (flag_output_fzn_stdout) { Printer p(std::cout,0); p.print(flat); } else { std::ofstream os; os.open(flag_output_fzn.c_str(), ios::out); Printer p(os,0); p.print(flat); os.close(); } if (flag_verbose) std::cerr << " done (" << stoptime(lasttime) << ")" << std::endl; if (!flag_no_output_ozn) { if (flag_verbose) std::cerr << "Printing .ozn ..."; if (flag_output_ozn_stdout) { Printer p(std::cout,0); p.print(env.output()); } else { std::ofstream os; os.open(flag_output_ozn.c_str(), ios::out); Printer p(os,0); p.print(env.output()); os.close(); } if (flag_verbose) std::cerr << " done (" << stoptime(lasttime) << ")" << std::endl; } } else { // !flag_typecheck Printer p(std::cout); p.print(m); } } catch (LocationException& e) { if (flag_verbose) std::cerr << std::endl; std::cerr << e.what() << ": " << e.msg() << std::endl; std::cerr << e.loc() << std::endl; exit(EXIT_FAILURE); } catch (Exception& e) { if (flag_verbose) std::cerr << std::endl; std::cerr << e.what() << ": " << e.msg() << std::endl; exit(EXIT_FAILURE); } delete m; } else { if (flag_verbose) std::cerr << std::endl; std::copy(istreambuf_iterator<char>(errstream),istreambuf_iterator<char>(),ostreambuf_iterator<char>(std::cerr)); } } if (flag_verbose) std::cerr << "Done (overall time " << stoptime(starttime) << ")." << std::endl; return 0; error: std::cerr << "Usage: "<< argv[0] << " [<options>] [-I <include path>] <model>.mzn [<data>.dzn ...]" << std::endl << std::endl << "Options:" << std::endl << " --help, -h\n Print this help message" << std::endl << " --version\n Print version information" << std::endl << " --ignore-stdlib\n Ignore the standard libraries stdlib.mzn and builtins.mzn" << std::endl << " --newfzn\n Output in the new FlatZinc format" << std::endl << " --verbose\n Print progress statements" << std::endl << " --no-typecheck\n Do not typecheck (implies --no-eval)" << std::endl << " --no-eval\n Do not evaluate" << std::endl << " --no-optimize\n Do not optimize the FlatZinc (may speed up large instances)" << std::endl << " --no-output-ozn, -O-\n Do not output ozn file" << std::endl << " --output-base <name>\n Base name for output files" << std::endl << " -o <file>, --output-to-file <file>, --output-fzn-to-file <file>\n Filename for generated FlatZinc output" << std::endl << " --output-ozn-to-file <file>\n Filename for model output specification" << std::endl << " --output-to-stdout, --output-fzn-to-stdout\n Print generated FlatZinc to standard output" << std::endl << " --output-ozn-to-stdout\n Print model output specification to standard output" << std::endl << " --stdlib-dir <dir>\n Path to MiniZinc standard library directory" << std::endl << " -G --globals-dir --mzn-globals-dir\n Search for included files in <stdlib>/<dir>." << std::endl ; exit(EXIT_FAILURE); } <|endoftext|>
<commit_before>/* * ArcEmu MMORPG Server * Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/> * Copyright (C) 2008 <http://www.ArcEmu.org/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "StdAfx.h" initialiseSingleton( TaxiMgr ); /************************ * TaxiPath * ************************/ void TaxiPath::ComputeLen() { m_length1 = m_length1 = 0; m_map1 = m_map2 = 0; float * curptr = &m_length1; if (!m_pathNodes.size()) return; std::map<uint32, TaxiPathNode*>::iterator itr; itr = m_pathNodes.begin(); float x = itr->second->x; float y = itr->second->y; float z = itr->second->z; uint32 curmap = itr->second->mapid; m_map1 = curmap; itr++; while (itr != m_pathNodes.end()) { if( itr->second->mapid != curmap ) { curptr = &m_length2; m_map2 = itr->second->mapid; curmap = itr->second->mapid; } *curptr += sqrt((itr->second->x - x)*(itr->second->x - x) + (itr->second->y - y)*(itr->second->y - y) + (itr->second->z - z)*(itr->second->z - z)); x = itr->second->x; y = itr->second->y; z = itr->second->z; itr++; } } void TaxiPath::SetPosForTime(float &x, float &y, float &z, uint32 time, uint32 *last_node, uint32 mapid) { if (!time) return; float length; if( mapid == m_map1 ) length = m_length1; else length = m_length2; float traveled_len = (time/(length * TAXI_TRAVEL_SPEED))*length; uint32 len = 0; x = 0; y = 0; z = 0; if (!m_pathNodes.size()) return; std::map<uint32, TaxiPathNode*>::iterator itr; itr = m_pathNodes.begin(); float nx,ny,nz = 0.0f; bool set = false; uint32 nodecounter = 0; while (itr != m_pathNodes.end()) { if( itr->second->mapid != mapid ) { itr++; nodecounter++; continue; } if(!set) { nx = itr->second->x; ny = itr->second->y; nz = itr->second->z; set = true; continue; } len = (uint32)sqrt((itr->second->x - nx)*(itr->second->x - nx) + (itr->second->y - ny)*(itr->second->y - ny) + (itr->second->z - nz)*(itr->second->z - nz)); if (len >= traveled_len) { x = (itr->second->x - nx)*(traveled_len/len) + nx; y = (itr->second->y - ny)*(traveled_len/len) + ny; z = (itr->second->z - nz)*(traveled_len/len) + nz; *last_node = nodecounter; return; } else { traveled_len -= len; } nx = itr->second->x; ny = itr->second->y; nz = itr->second->z; itr++; nodecounter++; } x = nx; y = ny; z = nz; } TaxiPathNode* TaxiPath::GetPathNode(uint32 i) { if (m_pathNodes.find(i) == m_pathNodes.end()) return NULL; else return m_pathNodes.find(i)->second; } void TaxiPath::SendMoveForTime(Player *riding, Player *to, uint32 time) { if (!time) return; float length; uint32 mapid = riding->GetMapId(); if( mapid == m_map1 ) length = m_length1; else length = m_length2; float traveled_len = (time/(length * TAXI_TRAVEL_SPEED))*length; uint32 len = 0; float x = 0,y = 0,z = 0; if (!m_pathNodes.size()) return; std::map<uint32, TaxiPathNode*>::iterator itr; itr = m_pathNodes.begin(); float nx,ny,nz = 0.0f; bool set = false; uint32 nodecounter = 1; while (itr != m_pathNodes.end()) { if( itr->second->mapid != mapid ) { itr++; nodecounter++; continue; } if(!set) { nx = itr->second->x; ny = itr->second->y; nz = itr->second->z; set = true; continue; } len = (uint32)sqrt((itr->second->x - nx)*(itr->second->x - nx) + (itr->second->y - ny)*(itr->second->y - ny) + (itr->second->z - nz)*(itr->second->z - nz)); if (len >= traveled_len) { x = (itr->second->x - nx)*(traveled_len/len) + nx; y = (itr->second->y - ny)*(traveled_len/len) + ny; z = (itr->second->z - nz)*(traveled_len/len) + nz; break; } else { traveled_len -= len; } nx = itr->second->x; ny = itr->second->y; nz = itr->second->z; itr++; } if (itr == m_pathNodes.end()) return; WorldPacket * data = new WorldPacket(SMSG_MONSTER_MOVE, 2000); size_t pos; *data << riding->GetNewGUID(); *data << riding->GetPositionX( ) << riding->GetPositionY( ) << riding->GetPositionZ( ); *data << getMSTime(); *data << uint8( 0 ); *data << uint32( 0x00000300 ); *data << uint32( uint32((length * TAXI_TRAVEL_SPEED) - time)); *data << uint32( nodecounter ); pos = data->wpos(); *data << nx << ny << nz; while (itr != m_pathNodes.end()) { TaxiPathNode *pn = itr->second; if( pn->mapid != mapid ) break; *data << pn->x << pn->y << pn->z; ++itr; ++nodecounter; } *(uint32*)&(data->contents()[pos]) = nodecounter; to->delayedPackets.add(data); /* if (!time) return; float traveled_len = (time/(getLength() * TAXI_TRAVEL_SPEED))*getLength();; uint32 len = 0, count = 0; float x = 0,y = 0,z = 0; if (!m_pathNodes.size()) return; std::map<uint32, TaxiPathNode*>::iterator itr; itr = m_pathNodes.begin(); float nx = itr->second->x; float ny = itr->second->y; float nz = itr->second->z; itr++; while (itr != m_pathNodes.end()) { len = (uint32)sqrt((itr->second->x - nx)*(itr->second->x - nx) + (itr->second->y - ny)*(itr->second->y - ny) + (itr->second->z - nz)*(itr->second->z - nz)); if (len > traveled_len) { x = (itr->second->x - nx)*(traveled_len/len) + nx; y = (itr->second->y - ny)*(traveled_len/len) + ny; z = (itr->second->z - nz)*(traveled_len/len) + nz; break; } else { traveled_len -= len; } nx = itr->second->x; ny = itr->second->y; nz = itr->second->z; itr++; count++; } if (itr == m_pathNodes.end()) return; WorldPacket * data = new WorldPacket(SMSG_MONSTER_MOVE, 2000); *data << riding->GetNewGUID(); *data << riding->GetPositionX( ) << riding->GetPositionY( ) << riding->GetPositionZ( ); *data << getMSTime(); *data << uint8( 0 ); *data << uint32( 0x00000300 ); *data << uint32( uint32((getLength() * TAXI_TRAVEL_SPEED) - time)); *data << uint32( GetNodeCount() - count ); *data << nx << ny << nz; while (itr != m_pathNodes.end()) { TaxiPathNode *pn = itr->second; *data << pn->x << pn->y << pn->z; itr++; } //to->GetSession()->SendPacket(&data); to->delayedPackets.add(data);*/ } /*********************** * TaxiMgr * ***********************/ void TaxiMgr::_LoadTaxiNodes() { uint32 i; for(i = 0; i < dbcTaxiNode.GetNumRows(); i++) { DBCTaxiNode *node = dbcTaxiNode.LookupRow(i); if (node) { TaxiNode *n = new TaxiNode; n->id = node->id; n->mapid = node->mapid; n->alliance_mount = node->alliance_mount; n->horde_mount = node->horde_mount; n->x = node->x; n->y = node->y; n->z = node->z; this->m_taxiNodes.insert(std::map<uint32, TaxiNode*>::value_type(n->id, n)); } } //todo: load mounts } void TaxiMgr::_LoadTaxiPaths() { uint32 i, j; for(i = 0; i < dbcTaxiPath.GetNumRows(); i++) { DBCTaxiPath *path = dbcTaxiPath.LookupRow(i); if (path) { TaxiPath *p = new TaxiPath; p->from = path->from; p->to = path->to; p->id = path->id; p->price = path->price; //Load Nodes for(j = 0; j < dbcTaxiPathNode.GetNumRows(); j++) { DBCTaxiPathNode *pathnode = dbcTaxiPathNode.LookupRow(j); if (pathnode) { if (pathnode->path == p->id) { TaxiPathNode *pn = new TaxiPathNode; pn->x = pathnode->x; pn->y = pathnode->y; pn->z = pathnode->z; pn->mapid = pathnode->mapid; p->AddPathNode(pathnode->seq, pn); } } } p->ComputeLen(); this->m_taxiPaths.insert(std::map<uint32, TaxiPath*>::value_type(p->id, p)); } } } TaxiPath* TaxiMgr::GetTaxiPath(uint32 path) { HM_NAMESPACE::hash_map<uint32, TaxiPath*>::iterator itr; itr = this->m_taxiPaths.find(path); if (itr == m_taxiPaths.end()) return NULL; else return itr->second; } TaxiPath* TaxiMgr::GetTaxiPath(uint32 from, uint32 to) { HM_NAMESPACE::hash_map<uint32, TaxiPath*>::iterator itr; for (itr = m_taxiPaths.begin(); itr != m_taxiPaths.end(); itr++) if ((itr->second->to == to) && (itr->second->from == from)) return itr->second; return NULL; } TaxiNode* TaxiMgr::GetTaxiNode(uint32 node) { HM_NAMESPACE::hash_map<uint32, TaxiNode*>::iterator itr; itr = this->m_taxiNodes.find(node); if (itr == m_taxiNodes.end()) return NULL; else return itr->second; } uint32 TaxiMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid ) { uint32 nearest = 0; float distance = -1; float nx, ny, nz, nd; HM_NAMESPACE::hash_map<uint32, TaxiNode*>::iterator itr; for (itr = m_taxiNodes.begin(); itr != m_taxiNodes.end(); itr++) { if (itr->second->mapid == mapid) { nx = itr->second->x - x; ny = itr->second->y - y; nz = itr->second->z - z; nd = nx * nx + ny * ny + nz * nz; if( nd < distance || distance < 0 ) { distance = nd; nearest = itr->second->id; } } } return nearest; } bool TaxiMgr::GetGlobalTaxiNodeMask( uint32 curloc, uint32 *Mask ) { HM_NAMESPACE::hash_map<uint32, TaxiPath*>::iterator itr; uint8 field; for (itr = m_taxiPaths.begin(); itr != m_taxiPaths.end(); itr++) { /*if( itr->second->from == curloc ) {*/ field = (uint8)((itr->second->to - 1) / 32); Mask[field] |= 1 << ( (itr->second->to - 1 ) % 32 ); //} } return true; } <commit_msg>Fixes a client crash when clicking on a flight path Seem to only affect some servers http://arcemu.org/forums/index.php?showtopic=8885&st=0&p=41293&#<commit_after>/* * ArcEmu MMORPG Server * Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/> * Copyright (C) 2008 <http://www.ArcEmu.org/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "StdAfx.h" initialiseSingleton( TaxiMgr ); /************************ * TaxiPath * ************************/ void TaxiPath::ComputeLen() { m_length1 = m_length1 = 0; m_map1 = m_map2 = 0; float * curptr = &m_length1; if (!m_pathNodes.size()) return; std::map<uint32, TaxiPathNode*>::iterator itr; itr = m_pathNodes.begin(); float x = itr->second->x; float y = itr->second->y; float z = itr->second->z; uint32 curmap = itr->second->mapid; m_map1 = curmap; itr++; while (itr != m_pathNodes.end()) { if( itr->second->mapid != curmap ) { curptr = &m_length2; m_map2 = itr->second->mapid; curmap = itr->second->mapid; } *curptr += sqrt((itr->second->x - x)*(itr->second->x - x) + (itr->second->y - y)*(itr->second->y - y) + (itr->second->z - z)*(itr->second->z - z)); x = itr->second->x; y = itr->second->y; z = itr->second->z; itr++; } } void TaxiPath::SetPosForTime(float &x, float &y, float &z, uint32 time, uint32 *last_node, uint32 mapid) { if (!time) return; float length; if( mapid == m_map1 ) length = m_length1; else length = m_length2; float traveled_len = (time/(length * TAXI_TRAVEL_SPEED))*length; uint32 len = 0; x = 0; y = 0; z = 0; if (!m_pathNodes.size()) return; std::map<uint32, TaxiPathNode*>::iterator itr; itr = m_pathNodes.begin(); float nx,ny,nz = 0.0f; bool set = false; uint32 nodecounter = 0; while (itr != m_pathNodes.end()) { if( itr->second->mapid != mapid ) { itr++; nodecounter++; continue; } if(!set) { nx = itr->second->x; ny = itr->second->y; nz = itr->second->z; set = true; continue; } len = (uint32)sqrt((itr->second->x - nx)*(itr->second->x - nx) + (itr->second->y - ny)*(itr->second->y - ny) + (itr->second->z - nz)*(itr->second->z - nz)); if (len >= traveled_len) { x = (itr->second->x - nx)*(traveled_len/len) + nx; y = (itr->second->y - ny)*(traveled_len/len) + ny; z = (itr->second->z - nz)*(traveled_len/len) + nz; *last_node = nodecounter; return; } else { traveled_len -= len; } nx = itr->second->x; ny = itr->second->y; nz = itr->second->z; itr++; nodecounter++; } x = nx; y = ny; z = nz; } TaxiPathNode* TaxiPath::GetPathNode(uint32 i) { if (m_pathNodes.find(i) == m_pathNodes.end()) return NULL; else return m_pathNodes.find(i)->second; } void TaxiPath::SendMoveForTime(Player *riding, Player *to, uint32 time) { if (!time) return; float length; uint32 mapid = riding->GetMapId(); if( mapid == m_map1 ) length = m_length1; else length = m_length2; float traveled_len = (time/(length * TAXI_TRAVEL_SPEED))*length; uint32 len = 0; float x = 0,y = 0,z = 0; if (!m_pathNodes.size()) return; std::map<uint32, TaxiPathNode*>::iterator itr; itr = m_pathNodes.begin(); float nx,ny,nz = 0.0f; bool set = false; uint32 nodecounter = 1; while (itr != m_pathNodes.end()) { if( itr->second->mapid != mapid ) { itr++; nodecounter++; continue; } if(!set) { nx = itr->second->x; ny = itr->second->y; nz = itr->second->z; set = true; continue; } len = (uint32)sqrt((itr->second->x - nx)*(itr->second->x - nx) + (itr->second->y - ny)*(itr->second->y - ny) + (itr->second->z - nz)*(itr->second->z - nz)); if (len >= traveled_len) { x = (itr->second->x - nx)*(traveled_len/len) + nx; y = (itr->second->y - ny)*(traveled_len/len) + ny; z = (itr->second->z - nz)*(traveled_len/len) + nz; break; } else { traveled_len -= len; } nx = itr->second->x; ny = itr->second->y; nz = itr->second->z; itr++; } if (itr == m_pathNodes.end()) return; WorldPacket * data = new WorldPacket(SMSG_MONSTER_MOVE, 2000); size_t pos; *data << riding->GetNewGUID(); *data << riding->GetPositionX( ) << riding->GetPositionY( ) << riding->GetPositionZ( ); *data << getMSTime(); *data << uint8( 0 ); *data << uint32( 0x00000300 ); *data << uint32( uint32((length * TAXI_TRAVEL_SPEED) - time)); *data << uint32( nodecounter ); pos = data->wpos(); *data << nx << ny << nz; while (itr != m_pathNodes.end()) { TaxiPathNode *pn = itr->second; if( pn->mapid != mapid ) break; *data << pn->x << pn->y << pn->z; ++itr; ++nodecounter; } *(uint32*)&(data->contents()[pos]) = nodecounter; to->delayedPackets.add(data); /* if (!time) return; float traveled_len = (time/(getLength() * TAXI_TRAVEL_SPEED))*getLength();; uint32 len = 0, count = 0; float x = 0,y = 0,z = 0; if (!m_pathNodes.size()) return; std::map<uint32, TaxiPathNode*>::iterator itr; itr = m_pathNodes.begin(); float nx = itr->second->x; float ny = itr->second->y; float nz = itr->second->z; itr++; while (itr != m_pathNodes.end()) { len = (uint32)sqrt((itr->second->x - nx)*(itr->second->x - nx) + (itr->second->y - ny)*(itr->second->y - ny) + (itr->second->z - nz)*(itr->second->z - nz)); if (len > traveled_len) { x = (itr->second->x - nx)*(traveled_len/len) + nx; y = (itr->second->y - ny)*(traveled_len/len) + ny; z = (itr->second->z - nz)*(traveled_len/len) + nz; break; } else { traveled_len -= len; } nx = itr->second->x; ny = itr->second->y; nz = itr->second->z; itr++; count++; } if (itr == m_pathNodes.end()) return; WorldPacket * data = new WorldPacket(SMSG_MONSTER_MOVE, 2000); *data << riding->GetNewGUID(); *data << riding->GetPositionX( ) << riding->GetPositionY( ) << riding->GetPositionZ( ); *data << getMSTime(); *data << uint8( 0 ); *data << uint32( 0x00000300 ); *data << uint32( uint32((getLength() * TAXI_TRAVEL_SPEED) - time)); *data << uint32( GetNodeCount() - count ); *data << nx << ny << nz; while (itr != m_pathNodes.end()) { TaxiPathNode *pn = itr->second; *data << pn->x << pn->y << pn->z; itr++; } //to->GetSession()->SendPacket(&data); to->delayedPackets.add(data);*/ } /*********************** * TaxiMgr * ***********************/ void TaxiMgr::_LoadTaxiNodes() { uint32 i; for(i = 0; i < dbcTaxiNode.GetNumRows(); i++) { DBCTaxiNode *node = dbcTaxiNode.LookupRow(i); if (node) { TaxiNode *n = new TaxiNode; n->id = node->id; n->mapid = node->mapid; n->alliance_mount = node->alliance_mount; n->horde_mount = node->horde_mount; n->x = node->x; n->y = node->y; n->z = node->z; this->m_taxiNodes.insert(std::map<uint32, TaxiNode*>::value_type(n->id, n)); } } //todo: load mounts } void TaxiMgr::_LoadTaxiPaths() { uint32 i, j; for(i = 0; i < dbcTaxiPath.GetNumRows(); i++) { DBCTaxiPath *path = dbcTaxiPath.LookupRow(i); if (path) { TaxiPath *p = new TaxiPath; p->from = path->from; p->to = path->to; p->id = path->id; p->price = path->price; //Load Nodes for(j = 0; j < dbcTaxiPathNode.GetNumRows(); j++) { DBCTaxiPathNode *pathnode = dbcTaxiPathNode.LookupRow(j); if (pathnode) { if (pathnode->path == p->id) { TaxiPathNode *pn = new TaxiPathNode; pn->x = pathnode->x; pn->y = pathnode->y; pn->z = pathnode->z; pn->mapid = pathnode->mapid; p->AddPathNode(pathnode->seq, pn); } } } p->ComputeLen(); this->m_taxiPaths.insert(std::map<uint32, TaxiPath*>::value_type(p->id, p)); } } } TaxiPath* TaxiMgr::GetTaxiPath(uint32 path) { HM_NAMESPACE::hash_map<uint32, TaxiPath*>::iterator itr; itr = this->m_taxiPaths.find(path); if (itr == m_taxiPaths.end()) return NULL; else return itr->second; } TaxiPath* TaxiMgr::GetTaxiPath(uint32 from, uint32 to) { HM_NAMESPACE::hash_map<uint32, TaxiPath*>::iterator itr; for (itr = m_taxiPaths.begin(); itr != m_taxiPaths.end(); itr++) if ((itr->second->to == to) && (itr->second->from == from)) return itr->second; return NULL; } TaxiNode* TaxiMgr::GetTaxiNode(uint32 node) { HM_NAMESPACE::hash_map<uint32, TaxiNode*>::iterator itr; itr = this->m_taxiNodes.find(node); if (itr == m_taxiNodes.end()) return NULL; else return itr->second; } uint32 TaxiMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid ) { uint32 nearest = 0; float distance = -1; float nx, ny, nz, nd; HM_NAMESPACE::hash_map<uint32, TaxiNode*>::iterator itr; for (itr = m_taxiNodes.begin(); itr != m_taxiNodes.end(); itr++) { if (itr->second->mapid == mapid) { nx = itr->second->x - x; ny = itr->second->y - y; nz = itr->second->z - z; nd = nx * nx + ny * ny + nz * nz; if( nd < distance || distance < 0 ) { distance = nd; nearest = itr->second->id; } } } return nearest; } bool TaxiMgr::GetGlobalTaxiNodeMask( uint32 curloc, uint32 *Mask ) { HM_NAMESPACE::hash_map<uint32, TaxiPath*>::iterator itr; uint8 field; for (itr = m_taxiPaths.begin(); itr != m_taxiPaths.end(); itr++) { if( itr->second->from == curloc ) { field = (uint8)((itr->second->to - 1) / 32); Mask[field] |= 1 << ( (itr->second->to - 1 ) % 32 ); } } return true; } <|endoftext|>
<commit_before>#include "cinder/app/App.h" #include "cinder/app/RendererGl.h" #include "cinder/gl/Context.h" #include "cinder/gl/Texture.h" #include "cinder/Xml.h" #include "cinder/Timeline.h" #include "cinder/ImageIo.h" #include "cinder/Thread.h" #include "cinder/ConcurrentCircularBuffer.h" /* The heart of this sample is to show how to create a background thread that interacts with OpenGL. It launches a secondary thread which pulls down images from a Flickr group and puts them in a thread-safe buffer. We can allocate a gl::Context which shares resources (specifically Textures) with the primary gl::Context. Note that this Context should be created in the primary thread and passed as a parameter to the secondary thread. */ using namespace ci; using namespace ci::app; using namespace std; class FlickrTestMTApp : public App { public: void setup(); void update(); void draw(); void shutdown(); void loadImagesThreadFn( gl::ContextRef sharedGlContext ); ConcurrentCircularBuffer<gl::TextureRef> *mImages; bool mShouldQuit; shared_ptr<thread> mThread; gl::TextureRef mTexture, mLastTexture; Anim<float> mFade; double mLastTime; }; void FlickrTestMTApp::setup() { mShouldQuit = false; mImages = new ConcurrentCircularBuffer<gl::TextureRef>( 5 ); // room for 5 images // create and launch the thread with a new gl::Context just for that thread gl::ContextRef backgroundCtx = gl::Context::create( gl::context() ); mThread = shared_ptr<thread>( new thread( bind( &FlickrTestMTApp::loadImagesThreadFn, this, backgroundCtx ) ) ); mLastTime = getElapsedSeconds() - 10; // force an initial update by make it "ten seconds ago" gl::enableAlphaBlending(); } void FlickrTestMTApp::loadImagesThreadFn( gl::ContextRef context ) { ci::ThreadSetup threadSetup; // instantiate this if you're talking to Cinder from a secondary thread // we received as a parameter a gl::Context we can use safely that shares resources with the primary Context context->makeCurrent(); vector<Url> urls; // parse the image URLS from the XML feed and push them into 'urls' const Url sunFlickrGroup = Url( "http://api.flickr.com/services/feeds/groups_pool.gne?id=52242317293@N01&format=rss_200" ); const XmlTree xml( loadUrl( sunFlickrGroup ) ); for( auto item = xml.begin( "rss/channel/item" ); item != xml.end(); ++item ) { const XmlTree &urlXml = ( ( *item / "media:content" ) ); urls.push_back( Url( urlXml["url"] ) ); } // load images as Textures into our ConcurrentCircularBuffer // don't create gl::Textures on a background thread while( ( ! mShouldQuit ) && ( ! urls.empty() ) ) { try { mImages->pushFront( gl::Texture::create( loadImage( loadUrl( urls.back() ) ) ) ); urls.pop_back(); } catch( ci::Exception &exc ) { console() << "failed to create texture, what: " << exc.what() << std::endl; } } } void FlickrTestMTApp::update() { double timeSinceLastImage = getElapsedSeconds() - mLastTime; if( ( timeSinceLastImage > 2.5 ) && mImages->isNotEmpty() ) { mLastTexture = mTexture; // the "last" texture is now the current text mImages->popBack( &mTexture ); mLastTime = getElapsedSeconds(); // blend from 0 to 1 over 1.5sec timeline().apply( &mFade, 0.0f, 1.0f, 1.5f ); } } void FlickrTestMTApp::draw() { gl::clear( Color( 0.1f, 0.1f, 0.2f ) ); if( mLastTexture ) { gl::color( 1, 1, 1, 1.0f - mFade ); Rectf textureBounds = mLastTexture->getBounds(); Rectf drawBounds = textureBounds.getCenteredFit( getWindowBounds(), true ); gl::draw( mLastTexture, drawBounds ); } if( mTexture ) { gl::color( 1, 1, 1, mFade ); Rectf textureBounds = mTexture->getBounds(); Rectf drawBounds = textureBounds.getCenteredFit( getWindowBounds(), true ); gl::draw( mTexture, drawBounds ); } } void FlickrTestMTApp::shutdown() { mShouldQuit = true; mImages->cancel(); mThread->join(); } CINDER_APP( FlickrTestMTApp, RendererGl )<commit_msg>Updates to MTFlickr sample for app_refactor<commit_after>#include "cinder/app/App.h" #include "cinder/app/RendererGl.h" #include "cinder/gl/Context.h" #include "cinder/gl/Texture.h" #include "cinder/gl/Sync.h" #include "cinder/Xml.h" #include "cinder/Timeline.h" #include "cinder/ImageIo.h" #include "cinder/Thread.h" #include "cinder/ConcurrentCircularBuffer.h" /* The heart of this sample is to show how to create a background thread that interacts with OpenGL. It launches a secondary thread which pulls down images from a Flickr group and puts them in a thread-safe buffer. We can allocate a gl::Context which shares resources (specifically Textures) with the primary gl::Context. Note that this Context should be created in the primary thread and passed as a parameter to the secondary thread. */ using namespace ci; using namespace ci::app; using namespace std; class FlickrTestMTApp : public App { public: ~FlickrTestMTApp(); void setup() override; void update() override; void draw() override; void loadImagesThreadFn( gl::ContextRef sharedGlContext ); ConcurrentCircularBuffer<gl::TextureRef> *mImages; bool mShouldQuit; shared_ptr<thread> mThread; gl::TextureRef mTexture, mLastTexture; Anim<float> mFade; double mLastTime; }; void FlickrTestMTApp::setup() { mShouldQuit = false; mImages = new ConcurrentCircularBuffer<gl::TextureRef>( 5 ); // room for 5 images // create and launch the thread with a new gl::Context just for that thread gl::ContextRef backgroundCtx = gl::Context::create( gl::context() ); mThread = shared_ptr<thread>( new thread( bind( &FlickrTestMTApp::loadImagesThreadFn, this, backgroundCtx ) ) ); mLastTime = getElapsedSeconds() - 10; // force an initial update by make it "ten seconds ago" gl::enableAlphaBlending(); } void FlickrTestMTApp::loadImagesThreadFn( gl::ContextRef context ) { ci::ThreadSetup threadSetup; // instantiate this if you're talking to Cinder from a secondary thread // we received as a parameter a gl::Context we can use safely that shares resources with the primary Context context->makeCurrent(); vector<Url> urls; // parse the image URLS from the XML feed and push them into 'urls' const Url sunFlickrGroup = Url( "http://api.flickr.com/services/feeds/groups_pool.gne?id=52242317293@N01&format=rss_200" ); const XmlTree xml( loadUrl( sunFlickrGroup ) ); for( auto item = xml.begin( "rss/channel/item" ); item != xml.end(); ++item ) { const XmlTree &urlXml = ( ( *item / "media:content" ) ); urls.push_back( Url( urlXml["url"] ) ); } // load images as Textures into our ConcurrentCircularBuffer while( ( ! mShouldQuit ) && ( ! urls.empty() ) ) { try { // we need to wait on a fence before alerting the primary thread that the Texture is ready auto fence = gl::Sync::create(); auto tex = gl::Texture::create( loadImage( loadUrl( urls.back() ) ) ); // wait on the fence fence->clientWaitSync(); mImages->pushFront( tex ); urls.pop_back(); } catch( ci::Exception &exc ) { console() << "failed to create texture, what: " << exc.what() << std::endl; } } } void FlickrTestMTApp::update() { double timeSinceLastImage = getElapsedSeconds() - mLastTime; if( ( timeSinceLastImage > 2.5 ) && mImages->isNotEmpty() ) { mLastTexture = mTexture; // the "last" texture is now the current text mImages->popBack( &mTexture ); mLastTime = getElapsedSeconds(); // blend from 0 to 1 over 1.5sec timeline().apply( &mFade, 0.0f, 1.0f, 1.5f ); } } void FlickrTestMTApp::draw() { gl::clear( Color( 0.1f, 0.1f, 0.2f ) ); if( mLastTexture ) { gl::color( 1, 1, 1, 1.0f - mFade ); Rectf textureBounds = mLastTexture->getBounds(); Rectf drawBounds = textureBounds.getCenteredFit( getWindowBounds(), true ); gl::draw( mLastTexture, drawBounds ); } if( mTexture ) { gl::color( 1, 1, 1, mFade ); Rectf textureBounds = mTexture->getBounds(); Rectf drawBounds = textureBounds.getCenteredFit( getWindowBounds(), true ); gl::draw( mTexture, drawBounds ); } } FlickrTestMTApp::~FlickrTestMTApp() { mShouldQuit = true; mImages->cancel(); mThread->join(); } CINDER_APP( FlickrTestMTApp, RendererGl )<|endoftext|>
<commit_before>/* * CLDevice.cpp * * Created on: Oct 24, 2009 * Author: rasmussn */ #include "CLDevice.hpp" #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #ifdef PV_USE_OPENCL namespace PV { static char * load_program_source(const char *filename); CLDevice::CLDevice(int device) { this->device = device; initialize(device); } CLDevice::~CLDevice() { } int CLDevice::initialize(int device) { int status = 0; // get number of devices available // status = clGetDeviceIDs(NULL, CL_DEVICE_TYPE_ALL, MAX_DEVICES, device_ids, &num_devices); if (status != CL_SUCCESS) { printf("Error: Failed to find a device group!\n"); print_error_code(status); exit(status); } // create a compute context // context = clCreateContext(0, 1, &device_ids[device], NULL, NULL, &status); if (!context) { printf("Error: Failed to create a compute context for device %d!\n", device); exit(PVCL_CREATE_CONTEXT_FAILURE); } // create a command queue // commands = clCreateCommandQueue(context, device_ids[device], 0, &status); if (!commands) { printf("Error: Failed to create a command commands!\n"); return PVCL_CREATE_CMD_QUEUE_FAILURE; } // turn on profiling // elapsed = 0; profiling = true; status = clSetCommandQueueProperty(commands, CL_QUEUE_PROFILING_ENABLE, CL_TRUE, NULL); if (status != CL_SUCCESS) { print_error_code(status); exit(status); } return status; } int CLDevice::run(size_t global_work_size) { size_t local_work_size; int status = 0; // get the maximum work group size for executing the kernel on the device // status = clGetKernelWorkGroupInfo(kernel, device_ids[device], CL_KERNEL_WORK_GROUP_SIZE, sizeof(size_t), &local_work_size, NULL); if (status != CL_SUCCESS) { fprintf(stderr, "Error: Failed to retrieve kernel work group info! %d\n", status); print_error_code(status); exit(status); } else { printf("run: local_work_size==%ld global_work_size==%ld\n", local_work_size, global_work_size); } // execute the kernel over the entire range of our 1d input data set // using the maximum number of work group items for this device // status = clEnqueueNDRangeKernel(commands, kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL); if (status != CL_SUCCESS) { fprintf(stderr, "CLDevice::run(): Failed to execute kernel!\n"); print_error_code(status); exit(status); } // wait for the command commands to get serviced before reading back results // clFinish(commands); return status; } int CLDevice::run(size_t gWorkSizeX, size_t gWorkSizeY, size_t lWorkSizeX, size_t lWorkSizeY) { size_t local_work_size[2]; size_t global_work_size[2]; size_t max_local_size; int status = 0; global_work_size[0] = gWorkSizeX; global_work_size[1] = gWorkSizeY; local_work_size[0] = lWorkSizeX; local_work_size[1] = lWorkSizeY; // get the maximum work group size for executing the kernel on the device // status = clGetKernelWorkGroupInfo(kernel, device_ids[device], CL_KERNEL_WORK_GROUP_SIZE, sizeof(size_t), &max_local_size, NULL); if (status != CL_SUCCESS) { fprintf(stderr, "Error: Failed to retrieve kernel work group info! (status==%d)\n", status); print_error_code(status); exit(status); } else { printf("run: local_work_size==(%ld,%ld) global_work_size==(%ld,%ld)\n", local_work_size[0], local_work_size[1], global_work_size[0], global_work_size[1]); } if (device == 1) { // Apple's CPU device has only one thread per group local_work_size[0] = 1; local_work_size[1] = 1; } // execute the kernel over the entire range of our 1d input data set // using the maximum number of work group items for this device // status = clEnqueueNDRangeKernel(commands, kernel, 2, NULL, global_work_size, local_work_size, 0, NULL, &event); if (status) { fprintf(stderr, "CLDevice::run(): Failed to execute kernel! (status==%d)\n", status); fprintf(stderr, "CLDevice::run(): max_local_work_size==%ld\n", max_local_size); print_error_code(status); exit(status); } // wait for the command commands to get serviced before reading back results // clFinish(commands); // get profiling information // if (profiling) { size_t param_size; cl_ulong start, end; status = clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_START, sizeof(start), &start, &param_size); status = clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_END, sizeof(end), &end, &param_size); if (status == 0) { elapsed = (end - start) / 1000; // microseconds } } return status; } int CLDevice::createKernel(const char * filename, const char * name) { int status = 0; // Create the compute program from the source buffer // char * source = load_program_source(filename); program = clCreateProgramWithSource(context, 1, (const char **) &source, NULL, &status); if (!program || status != CL_SUCCESS) { printf("Error: Failed to create compute program!\n"); print_error_code(status); exit(status); } // Build the program executable // status = clBuildProgram(program, 0, NULL, NULL, NULL, NULL); if (status != CL_SUCCESS) { size_t len; char buffer[2048]; printf("Error: Failed to build program executable!\n"); clGetProgramBuildInfo(program, device_ids[device], CL_PROGRAM_BUILD_LOG, sizeof(buffer), buffer, &len); printf("%s\n", buffer); print_error_code(status); exit(status); } // Create the compute kernel in the program we wish to run // kernel = clCreateKernel(program, name, &status); if (!kernel || status != CL_SUCCESS) { fprintf(stderr, "Error: Failed to create compute kernel!\n"); print_error_code(status); exit(status); } return status; } CLBuffer * CLDevice::createBuffer(cl_mem_flags flags, size_t size, void * host_ptr) { return new CLBuffer(context, commands, flags, size, host_ptr); } int CLDevice::addKernelArg(int argid, int arg) { int status = 0; status = clSetKernelArg(kernel, argid, sizeof(int), &arg); if (status != CL_SUCCESS) { fprintf(stderr, "CLDevice::addKernelArg: Failed to set kernel argument! %d\n", status); print_error_code(status); exit(status); } return status; } int CLDevice::addKernelArg(int argid, CLBuffer * buf) { int status = 0; cl_mem mobj = buf->clMemObject(); status = clSetKernelArg(kernel, argid, sizeof(cl_mem), &mobj); if (status != CL_SUCCESS) { fprintf(stderr, "CLDevice::addKernelArg: Failed to set kernel argument! %d\n", status); print_error_code(status); exit(status); } return status; } int CLDevice::addLocalArg(int argid, size_t size) { int status = 0; status = clSetKernelArg(kernel, argid, size, 0); if (status != CL_SUCCESS) { fprintf(stderr, "CLDevice::addLocalArg: Failed to set kernel argument! %d\n", status); print_error_code(status); exit(status); } return status; } int CLDevice::query_device_info() { // query and print information about the devices found // printf("\n"); printf("Number of OpenCL devices found: %d\n", num_devices); printf("\n"); for (unsigned int i = 0; i < num_devices; i++) { query_device_info(i, device_ids[i]); } return 0; } int CLDevice::query_device_info(int id, cl_device_id device) { const int str_size = 64; const int vals_len = MAX_WORK_ITEM_DIMENSIONS; long long val; size_t vals[vals_len]; unsigned int max_dims; int status; char param_value[str_size]; size_t param_value_size; status = clGetDeviceInfo(device, CL_DEVICE_NAME, str_size, param_value, &param_value_size); param_value[str_size-1] = '\0'; printf("OpenCL Device # %d == %s\n", id, param_value); status = clGetDeviceInfo(device, CL_DEVICE_TYPE, sizeof(val), &val, NULL); if (status == CL_SUCCESS) { printf("\tdevice[%p]: Type: ", device); if (val & CL_DEVICE_TYPE_DEFAULT) { val &= ~CL_DEVICE_TYPE_DEFAULT; printf("Default "); } if (val & CL_DEVICE_TYPE_CPU) { val &= ~CL_DEVICE_TYPE_CPU; printf("CPU "); } if (val & CL_DEVICE_TYPE_GPU) { val &= ~CL_DEVICE_TYPE_GPU; printf("GPU "); } if (val & CL_DEVICE_TYPE_ACCELERATOR) { val &= ~CL_DEVICE_TYPE_ACCELERATOR; printf("Accelerator "); } if (val != 0) { printf("Unknown (0x%llx) ", val); } } else { printf("\tdevice[%p]: Unable to get TYPE: %s!\n", device, "CLErrString(status)"); print_error_code(status); exit(status); } status = clGetDeviceInfo(device, CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(val), &val, &param_value_size); printf("with %u units/cores", (unsigned int) val); status = clGetDeviceInfo(device, CL_DEVICE_MAX_CLOCK_FREQUENCY, sizeof(val), &val, &param_value_size); printf(" at %u MHz\n", (unsigned int) val); status = clGetDeviceInfo(device, CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT, sizeof(val), &val, &param_value_size); printf("\tfloat vector width == %u\n", (unsigned int) val); status = clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(val), &val, &param_value_size); printf("\tMaximum work group size == %lu\n", (size_t) val); status = clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS, sizeof(max_dims), &max_dims, &param_value_size); printf("\tMaximum work item dimensions == %u\n", max_dims); status = clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_ITEM_SIZES, vals_len*sizeof(size_t), vals, &param_value_size); printf("\tMaximum work item sizes == ("); for (int i = 0; i < max_dims; i++) printf(" %ld", vals[i]); printf(" )\n"); status = clGetDeviceInfo(device, CL_DEVICE_LOCAL_MEM_SIZE, sizeof(val), &val, &param_value_size); printf("\tLocal mem size == %u\n", (unsigned int) val); status = clGetDeviceInfo(device, CL_DEVICE_GLOBAL_MEM_SIZE, sizeof(val), &val, &param_value_size); printf("\tGlobal mem size == %u\n", (unsigned int) val); status = clGetDeviceInfo(device, CL_DEVICE_GLOBAL_MEM_CACHE_SIZE, sizeof(val), &val, &param_value_size); printf("\tGlobal mem cache size == %u\n", (unsigned int) val); status = clGetDeviceInfo(device, CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE, sizeof(val), &val, &param_value_size); printf("\tGlobal mem cache line size == %u\n", (unsigned int) val); printf("\n"); return status; } ///////////////////////////////////////////////////////////////////////////// void print_error_code(int code) { char msg[256]; switch (code) { case CL_INVALID_WORK_GROUP_SIZE: sprintf(msg, "%s (%d)", "CL_INVALID_WORK_GROUP_SIZE", code); break; case CL_INVALID_COMMAND_QUEUE: sprintf(msg, "%s (%d)", "CL_INVALID_COMMAND_QUEUE", code); break; case CL_INVALID_KERNEL_ARGS: sprintf(msg, "%s (%d)", "CL_INVALID_KERNEL_ARGS", code); break; default: sprintf(msg, "%s (%d)\n", "UNKNOWN_CODE", code); break; } printf("ERROR_CODE==%s\n", msg); } static char * load_program_source(const char *filename) { struct stat statbuf; FILE *fh; char *source; fh = fopen(filename, "r"); if (fh == 0) return 0; stat(filename, &statbuf); source = (char *) malloc(statbuf.st_size + 1); fread(source, statbuf.st_size, 1, fh); source[statbuf.st_size] = '\0'; return source; } } // namespace PV #else void cldevice_noop() { ; } #endif // PV_USE_OPENCL <commit_msg>Reworked #ifdefs to provide a little more null functionality with not using OpenCL.<commit_after>/* * CLDevice.cpp * * Created on: Oct 24, 2009 * Author: rasmussn */ #include "CLDevice.hpp" #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> namespace PV { CLDevice::CLDevice(int device) { this->device = device; initialize(device); } int CLDevice::initialize(int device) { int status = 0; #ifdef PV_USE_OPENCL // get number of devices available // status = clGetDeviceIDs(NULL, CL_DEVICE_TYPE_ALL, MAX_DEVICES, device_ids, &num_devices); if (status != CL_SUCCESS) { printf("Error: Failed to find a device group!\n"); print_error_code(status); exit(status); } // create a compute context // context = clCreateContext(0, 1, &device_ids[device], NULL, NULL, &status); if (!context) { printf("Error: Failed to create a compute context for device %d!\n", device); exit(PVCL_CREATE_CONTEXT_FAILURE); } // create a command queue // commands = clCreateCommandQueue(context, device_ids[device], 0, &status); if (!commands) { printf("Error: Failed to create a command commands!\n"); return PVCL_CREATE_CMD_QUEUE_FAILURE; } // turn on profiling // elapsed = 0; profiling = true; status = clSetCommandQueueProperty(commands, CL_QUEUE_PROFILING_ENABLE, CL_TRUE, NULL); if (status != CL_SUCCESS) { print_error_code(status); exit(status); } #endif PV_USE_OPENCL return status; } #ifdef PV_USE_OPENCL static char * load_program_source(const char *filename); int CLDevice::run(size_t global_work_size) { size_t local_work_size; int status = 0; // get the maximum work group size for executing the kernel on the device // status = clGetKernelWorkGroupInfo(kernel, device_ids[device], CL_KERNEL_WORK_GROUP_SIZE, sizeof(size_t), &local_work_size, NULL); if (status != CL_SUCCESS) { fprintf(stderr, "Error: Failed to retrieve kernel work group info! %d\n", status); print_error_code(status); exit(status); } else { printf("run: local_work_size==%ld global_work_size==%ld\n", local_work_size, global_work_size); } // execute the kernel over the entire range of our 1d input data set // using the maximum number of work group items for this device // status = clEnqueueNDRangeKernel(commands, kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL); if (status != CL_SUCCESS) { fprintf(stderr, "CLDevice::run(): Failed to execute kernel!\n"); print_error_code(status); exit(status); } // wait for the command commands to get serviced before reading back results // clFinish(commands); return status; } int CLDevice::run(size_t gWorkSizeX, size_t gWorkSizeY, size_t lWorkSizeX, size_t lWorkSizeY) { size_t local_work_size[2]; size_t global_work_size[2]; size_t max_local_size; int status = 0; global_work_size[0] = gWorkSizeX; global_work_size[1] = gWorkSizeY; local_work_size[0] = lWorkSizeX; local_work_size[1] = lWorkSizeY; // get the maximum work group size for executing the kernel on the device // status = clGetKernelWorkGroupInfo(kernel, device_ids[device], CL_KERNEL_WORK_GROUP_SIZE, sizeof(size_t), &max_local_size, NULL); if (status != CL_SUCCESS) { fprintf(stderr, "Error: Failed to retrieve kernel work group info! (status==%d)\n", status); print_error_code(status); exit(status); } else { printf("run: local_work_size==(%ld,%ld) global_work_size==(%ld,%ld)\n", local_work_size[0], local_work_size[1], global_work_size[0], global_work_size[1]); } if (device == 1) { // Apple's CPU device has only one thread per group local_work_size[0] = 1; local_work_size[1] = 1; } // execute the kernel over the entire range of our 1d input data set // using the maximum number of work group items for this device // status = clEnqueueNDRangeKernel(commands, kernel, 2, NULL, global_work_size, local_work_size, 0, NULL, &event); if (status) { fprintf(stderr, "CLDevice::run(): Failed to execute kernel! (status==%d)\n", status); fprintf(stderr, "CLDevice::run(): max_local_work_size==%ld\n", max_local_size); print_error_code(status); exit(status); } // wait for the command commands to get serviced before reading back results // clFinish(commands); // get profiling information // if (profiling) { size_t param_size; cl_ulong start, end; status = clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_START, sizeof(start), &start, &param_size); status = clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_END, sizeof(end), &end, &param_size); if (status == 0) { elapsed = (end - start) / 1000; // microseconds } } return status; } int CLDevice::createKernel(const char * filename, const char * name) { int status = 0; // Create the compute program from the source buffer // char * source = load_program_source(filename); program = clCreateProgramWithSource(context, 1, (const char **) &source, NULL, &status); if (!program || status != CL_SUCCESS) { printf("Error: Failed to create compute program!\n"); print_error_code(status); exit(status); } // Build the program executable // status = clBuildProgram(program, 0, NULL, NULL, NULL, NULL); if (status != CL_SUCCESS) { size_t len; char buffer[2048]; printf("Error: Failed to build program executable!\n"); clGetProgramBuildInfo(program, device_ids[device], CL_PROGRAM_BUILD_LOG, sizeof(buffer), buffer, &len); printf("%s\n", buffer); print_error_code(status); exit(status); } // Create the compute kernel in the program we wish to run // kernel = clCreateKernel(program, name, &status); if (!kernel || status != CL_SUCCESS) { fprintf(stderr, "Error: Failed to create compute kernel!\n"); print_error_code(status); exit(status); } return status; } #endif // PV_USE_OPENCL CLBuffer * CLDevice::createBuffer(cl_mem_flags flags, size_t size, void * host_ptr) { #ifdef PV_USE_OPENCL return new CLBuffer(context, commands, flags, size, host_ptr); #else return new CLBuffer(); #endif } #ifdef PV_USE_OPENCL int CLDevice::addKernelArg(int argid, int arg) { int status = 0; status = clSetKernelArg(kernel, argid, sizeof(int), &arg); if (status != CL_SUCCESS) { fprintf(stderr, "CLDevice::addKernelArg: Failed to set kernel argument! %d\n", status); print_error_code(status); exit(status); } return status; } int CLDevice::addKernelArg(int argid, CLBuffer * buf) { int status = 0; cl_mem mobj = buf->clMemObject(); status = clSetKernelArg(kernel, argid, sizeof(cl_mem), &mobj); if (status != CL_SUCCESS) { fprintf(stderr, "CLDevice::addKernelArg: Failed to set kernel argument! %d\n", status); print_error_code(status); exit(status); } return status; } int CLDevice::addLocalArg(int argid, size_t size) { int status = 0; status = clSetKernelArg(kernel, argid, size, 0); if (status != CL_SUCCESS) { fprintf(stderr, "CLDevice::addLocalArg: Failed to set kernel argument! %d\n", status); print_error_code(status); exit(status); } return status; } int CLDevice::query_device_info() { // query and print information about the devices found // printf("\n"); printf("Number of OpenCL devices found: %d\n", num_devices); printf("\n"); for (unsigned int i = 0; i < num_devices; i++) { query_device_info(i, device_ids[i]); } return 0; } int CLDevice::query_device_info(int id, cl_device_id device) { const int str_size = 64; const int vals_len = MAX_WORK_ITEM_DIMENSIONS; long long val; size_t vals[vals_len]; unsigned int max_dims; int status; char param_value[str_size]; size_t param_value_size; status = clGetDeviceInfo(device, CL_DEVICE_NAME, str_size, param_value, &param_value_size); param_value[str_size-1] = '\0'; printf("OpenCL Device # %d == %s\n", id, param_value); status = clGetDeviceInfo(device, CL_DEVICE_TYPE, sizeof(val), &val, NULL); if (status == CL_SUCCESS) { printf("\tdevice[%p]: Type: ", device); if (val & CL_DEVICE_TYPE_DEFAULT) { val &= ~CL_DEVICE_TYPE_DEFAULT; printf("Default "); } if (val & CL_DEVICE_TYPE_CPU) { val &= ~CL_DEVICE_TYPE_CPU; printf("CPU "); } if (val & CL_DEVICE_TYPE_GPU) { val &= ~CL_DEVICE_TYPE_GPU; printf("GPU "); } if (val & CL_DEVICE_TYPE_ACCELERATOR) { val &= ~CL_DEVICE_TYPE_ACCELERATOR; printf("Accelerator "); } if (val != 0) { printf("Unknown (0x%llx) ", val); } } else { printf("\tdevice[%p]: Unable to get TYPE: %s!\n", device, "CLErrString(status)"); print_error_code(status); exit(status); } status = clGetDeviceInfo(device, CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(val), &val, &param_value_size); printf("with %u units/cores", (unsigned int) val); status = clGetDeviceInfo(device, CL_DEVICE_MAX_CLOCK_FREQUENCY, sizeof(val), &val, &param_value_size); printf(" at %u MHz\n", (unsigned int) val); status = clGetDeviceInfo(device, CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT, sizeof(val), &val, &param_value_size); printf("\tfloat vector width == %u\n", (unsigned int) val); status = clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(val), &val, &param_value_size); printf("\tMaximum work group size == %lu\n", (size_t) val); status = clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS, sizeof(max_dims), &max_dims, &param_value_size); printf("\tMaximum work item dimensions == %u\n", max_dims); status = clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_ITEM_SIZES, vals_len*sizeof(size_t), vals, &param_value_size); printf("\tMaximum work item sizes == ("); for (int i = 0; i < max_dims; i++) printf(" %ld", vals[i]); printf(" )\n"); status = clGetDeviceInfo(device, CL_DEVICE_LOCAL_MEM_SIZE, sizeof(val), &val, &param_value_size); printf("\tLocal mem size == %u\n", (unsigned int) val); status = clGetDeviceInfo(device, CL_DEVICE_GLOBAL_MEM_SIZE, sizeof(val), &val, &param_value_size); printf("\tGlobal mem size == %u\n", (unsigned int) val); status = clGetDeviceInfo(device, CL_DEVICE_GLOBAL_MEM_CACHE_SIZE, sizeof(val), &val, &param_value_size); printf("\tGlobal mem cache size == %u\n", (unsigned int) val); status = clGetDeviceInfo(device, CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE, sizeof(val), &val, &param_value_size); printf("\tGlobal mem cache line size == %u\n", (unsigned int) val); printf("\n"); return status; } ///////////////////////////////////////////////////////////////////////////// void print_error_code(int code) { char msg[256]; switch (code) { case CL_INVALID_WORK_GROUP_SIZE: sprintf(msg, "%s (%d)", "CL_INVALID_WORK_GROUP_SIZE", code); break; case CL_INVALID_COMMAND_QUEUE: sprintf(msg, "%s (%d)", "CL_INVALID_COMMAND_QUEUE", code); break; case CL_INVALID_KERNEL_ARGS: sprintf(msg, "%s (%d)", "CL_INVALID_KERNEL_ARGS", code); break; default: sprintf(msg, "%s (%d)\n", "UNKNOWN_CODE", code); break; } printf("ERROR_CODE==%s\n", msg); } static char * load_program_source(const char *filename) { struct stat statbuf; FILE *fh; char *source; fh = fopen(filename, "r"); if (fh == 0) return 0; stat(filename, &statbuf); source = (char *) malloc(statbuf.st_size + 1); fread(source, statbuf.st_size, 1, fh); source[statbuf.st_size] = '\0'; return source; } #endif // PV_USE_OPENCL } // namespace PV <|endoftext|>
<commit_before>/* * CLKernel.cpp * * Created on: Aug 1, 2010 * Author: rasmussn */ #include "CLKernel.hpp" #include "CLDevice.hpp" #include <stdio.h> #include <sys/stat.h> namespace PV { static char * load_program_source(const char *filename); CLKernel::CLKernel(cl_context context, cl_command_queue commands, cl_device_id device, const char * filename, const char * name) { this->device = device; this->commands = commands; this->profiling = true; this->elapsed = 0; #ifdef PV_USE_OPENCL int status = CL_SUCCESS; // Create the compute program from the source buffer // char * source = load_program_source(filename); program = clCreateProgramWithSource(context, 1, (const char **) &source, NULL, &status); if (!program || status != CL_SUCCESS) { printf("Error: Failed to create compute program!\n"); CLDevice::print_error_code(status); exit(status); } // Build the program executable // status = clBuildProgram(program, 0, NULL, NULL, NULL, NULL); if (status != CL_SUCCESS) { size_t len; char buffer[2048]; printf("Error: Failed to build program executable!\n"); clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, sizeof(buffer), buffer, &len); printf("%s\n", buffer); CLDevice::print_error_code(status); exit(status); } // Create the compute kernel in the program we wish to run // kernel = clCreateKernel(program, name, &status); if (!kernel || status != CL_SUCCESS) { fprintf(stderr, "Error: Failed to create compute kernel!\n"); CLDevice::print_error_code(status); exit(status); } #endif // PV_USE_OPENCL } int CLKernel::run(size_t global_work_size) { int status = CL_SUCCESS; #ifdef PV_USE_OPENCL size_t local_work_size; // get the maximum work group size for executing the kernel on the device // status = clGetKernelWorkGroupInfo(kernel, device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(size_t), &local_work_size, NULL); if (status != CL_SUCCESS) { fprintf(stderr, "Error: Failed to retrieve kernel work group info! %d\n", status); CLDevice::print_error_code(status); exit(status); } else { printf("run: local_work_size==%ld global_work_size==%ld\n", local_work_size, global_work_size); } // execute the kernel over the entire range of our 1d input data set // using the maximum number of work group items for this device // status = clEnqueueNDRangeKernel(commands, kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, &event); if (status != CL_SUCCESS) { fprintf(stderr, "CLDevice::run(): Failed to execute kernel!\n"); CLDevice::print_error_code(status); exit(status); } // wait for the command commands to get serviced before reading back results // clFinish(commands); #endif // PV_USE_OPENCL return status; } int CLKernel::run(size_t gWorkSizeX, size_t gWorkSizeY, size_t lWorkSizeX, size_t lWorkSizeY) { int status = CL_SUCCESS; #ifdef PV_USE_OPENCL size_t local_work_size[2]; size_t global_work_size[2]; size_t max_local_size; global_work_size[0] = gWorkSizeX; global_work_size[1] = gWorkSizeY; local_work_size[0] = lWorkSizeX; local_work_size[1] = lWorkSizeY; #ifdef PV_USE_TAU int tau_id = 10; TAU_START("CLKernel::run::CPU"); #endif // get the maximum work group size for executing the kernel on the device // status = clGetKernelWorkGroupInfo(kernel, device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(size_t), &max_local_size, NULL); if (status != CL_SUCCESS) { fprintf(stderr, "Error: Failed to retrieve kernel work group info! (status==%d)\n", status); CLDevice::print_error_code(status); exit(status); } else { //printf("run: local_work_size==(%ld,%ld) global_work_size==(%ld,%ld)\n", // local_work_size[0], local_work_size[1], global_work_size[0], global_work_size[1]); } // execute the kernel over the entire range of our 1d input data set // using the maximum number of work group items for this device // status = clEnqueueNDRangeKernel(commands, kernel, 2, NULL, global_work_size, local_work_size, 0, NULL, &event); if (status) { fprintf(stderr, "CLDevice::run(): Failed to execute kernel! (status==%d)\n", status); fprintf(stderr, "CLDevice::run(): max_local_work_size==%ld\n", max_local_size); CLDevice::print_error_code(status); exit(status); } // wait for the command commands to get serviced before reading back results // clFinish(commands); // get profiling information // if (profiling) { size_t param_size; cl_ulong start, end; #ifdef PV_USE_TAU tau_id += 1000; TAU_STOP("CLKernel::run::CPU"); #endif status = clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_START, sizeof(start), &start, &param_size); status = clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_END, sizeof(end), &end, &param_size); if (status == 0) { elapsed = (end - start) / 1000; // microseconds } #ifdef PV_USE_TAU Tau_opencl_register_gpu_event("CLKernel::run::GPU", tau_id, start, end); #endif } #endif // PV_USE_OPENCL return status; } int CLKernel::setKernelArg(int argid, int arg) { int status = CL_SUCCESS; #ifdef PV_USE_OPENCL status = clSetKernelArg(kernel, argid, sizeof(int), &arg); if (status != CL_SUCCESS) { fprintf(stderr, "CLDevice::addKernelArg: Failed to set kernel argument! %d\n", status); CLDevice::print_error_code(status); exit(status); } #endif // PV_USE_OPENCL return status; } int CLKernel::setKernelArg(int argid, float arg) { int status = CL_SUCCESS; #ifdef PV_USE_OPENCL status = clSetKernelArg(kernel, argid, sizeof(float), &arg); if (status != CL_SUCCESS) { fprintf(stderr, "CLDevice::addKernelArg: Failed to set kernel argument! %d\n", status); CLDevice::print_error_code(status); exit(status); } #endif // PV_USE_OPENCL return status; } int CLKernel::setKernelArg(int argid, CLBuffer * buf) { int status = CL_SUCCESS; #ifdef PV_USE_OPENCL cl_mem mobj = buf->clMemObject(); status = clSetKernelArg(kernel, argid, sizeof(cl_mem), &mobj); if (status != CL_SUCCESS) { fprintf(stderr, "CLDevice::addKernelArg: Failed to set kernel argument! %d\n", status); CLDevice::print_error_code(status); exit(status); } #endif // PV_USE_OPENCL return status; } int CLKernel::setLocalArg(int argid, size_t size) { int status = CL_SUCCESS; #ifdef PV_USE_OPENCL status = clSetKernelArg(kernel, argid, size, 0); if (status != CL_SUCCESS) { fprintf(stderr, "CLDevice::addLocalArg: Failed to set kernel argument! %d\n", status); CLDevice::print_error_code(status); exit(status); } #endif // PV_USE_OPENCL return status; } static char * load_program_source(const char *filename) { struct stat statbuf; FILE *fh; char *source; fh = fopen(filename, "r"); if (fh == 0) return 0; stat(filename, &statbuf); source = (char *) malloc(statbuf.st_size + 1); fread(source, statbuf.st_size, 1, fh); source[statbuf.st_size] = '\0'; return source; } } <commit_msg>Set local_work_size to 1 if max_local_work_size is less than the local work size chosen. This is needed if device is 1 (using CPU).<commit_after>/* * CLKernel.cpp * * Created on: Aug 1, 2010 * Author: rasmussn */ #include "CLKernel.hpp" #include "CLDevice.hpp" #include <stdio.h> #include <sys/stat.h> namespace PV { static char * load_program_source(const char *filename); CLKernel::CLKernel(cl_context context, cl_command_queue commands, cl_device_id device, const char * filename, const char * name) { this->device = device; this->commands = commands; this->profiling = true; this->elapsed = 0; #ifdef PV_USE_OPENCL int status = CL_SUCCESS; // Create the compute program from the source buffer // char * source = load_program_source(filename); program = clCreateProgramWithSource(context, 1, (const char **) &source, NULL, &status); if (!program || status != CL_SUCCESS) { printf("Error: Failed to create compute program!\n"); CLDevice::print_error_code(status); exit(status); } // Build the program executable // status = clBuildProgram(program, 0, NULL, NULL, NULL, NULL); if (status != CL_SUCCESS) { size_t len; char buffer[2048]; printf("Error: Failed to build program executable!\n"); clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, sizeof(buffer), buffer, &len); printf("%s\n", buffer); CLDevice::print_error_code(status); exit(status); } // Create the compute kernel in the program we wish to run // kernel = clCreateKernel(program, name, &status); if (!kernel || status != CL_SUCCESS) { fprintf(stderr, "Error: Failed to create compute kernel!\n"); CLDevice::print_error_code(status); exit(status); } #endif // PV_USE_OPENCL } int CLKernel::run(size_t global_work_size) { int status = CL_SUCCESS; #ifdef PV_USE_OPENCL size_t local_work_size; // get the maximum work group size for executing the kernel on the device // status = clGetKernelWorkGroupInfo(kernel, device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(size_t), &local_work_size, NULL); if (status != CL_SUCCESS) { fprintf(stderr, "Error: Failed to retrieve kernel work group info! %d\n", status); CLDevice::print_error_code(status); exit(status); } else { printf("run: local_work_size==%ld global_work_size==%ld\n", local_work_size, global_work_size); } // execute the kernel over the entire range of our 1d input data set // using the maximum number of work group items for this device // status = clEnqueueNDRangeKernel(commands, kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, &event); if (status != CL_SUCCESS) { fprintf(stderr, "CLDevice::run(): Failed to execute kernel!\n"); CLDevice::print_error_code(status); exit(status); } // wait for the command commands to get serviced before reading back results // clFinish(commands); #endif // PV_USE_OPENCL return status; } int CLKernel::run(size_t gWorkSizeX, size_t gWorkSizeY, size_t lWorkSizeX, size_t lWorkSizeY) { int status = CL_SUCCESS; #ifdef PV_USE_OPENCL size_t local_work_size[2]; size_t global_work_size[2]; size_t max_local_size; global_work_size[0] = gWorkSizeX; global_work_size[1] = gWorkSizeY; local_work_size[0] = lWorkSizeX; local_work_size[1] = lWorkSizeY; #ifdef PV_USE_TAU int tau_id = 10; TAU_START("CLKernel::run::CPU"); #endif // get the maximum work group size for executing the kernel on the device // status = clGetKernelWorkGroupInfo(kernel, device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(size_t), &max_local_size, NULL); if (status != CL_SUCCESS) { fprintf(stderr, "Error: Failed to retrieve kernel work group info! (status==%d)\n", status); CLDevice::print_error_code(status); exit(status); } else { //printf("run: local_work_size==(%ld,%ld) global_work_size==(%ld,%ld)\n", // local_work_size[0], local_work_size[1], global_work_size[0], global_work_size[1]); } if (lWorkSizeX * lWorkSizeY > max_local_size) { local_work_size[0] = 1; local_work_size[1] = 1; } // execute the kernel over the entire range of our 1d input data set // using the maximum number of work group items for this device // status = clEnqueueNDRangeKernel(commands, kernel, 2, NULL, global_work_size, local_work_size, 0, NULL, &event); if (status) { fprintf(stderr, "CLDevice::run(): Failed to execute kernel! (status==%d)\n", status); fprintf(stderr, "CLDevice::run(): max_local_work_size==%ld\n", max_local_size); CLDevice::print_error_code(status); exit(status); } // wait for the command commands to get serviced before reading back results // clFinish(commands); // get profiling information // if (profiling) { size_t param_size; cl_ulong start, end; #ifdef PV_USE_TAU tau_id += 1000; TAU_STOP("CLKernel::run::CPU"); #endif status = clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_START, sizeof(start), &start, &param_size); status = clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_END, sizeof(end), &end, &param_size); if (status == 0) { elapsed = (end - start) / 1000; // microseconds } #ifdef PV_USE_TAU Tau_opencl_register_gpu_event("CLKernel::run::GPU", tau_id, start, end); #endif } #endif // PV_USE_OPENCL return status; } int CLKernel::setKernelArg(int argid, int arg) { int status = CL_SUCCESS; #ifdef PV_USE_OPENCL status = clSetKernelArg(kernel, argid, sizeof(int), &arg); if (status != CL_SUCCESS) { fprintf(stderr, "CLDevice::addKernelArg: Failed to set kernel argument! %d\n", status); CLDevice::print_error_code(status); exit(status); } #endif // PV_USE_OPENCL return status; } int CLKernel::setKernelArg(int argid, float arg) { int status = CL_SUCCESS; #ifdef PV_USE_OPENCL status = clSetKernelArg(kernel, argid, sizeof(float), &arg); if (status != CL_SUCCESS) { fprintf(stderr, "CLDevice::addKernelArg: Failed to set kernel argument! %d\n", status); CLDevice::print_error_code(status); exit(status); } #endif // PV_USE_OPENCL return status; } int CLKernel::setKernelArg(int argid, CLBuffer * buf) { int status = CL_SUCCESS; #ifdef PV_USE_OPENCL cl_mem mobj = buf->clMemObject(); status = clSetKernelArg(kernel, argid, sizeof(cl_mem), &mobj); if (status != CL_SUCCESS) { fprintf(stderr, "CLDevice::addKernelArg: Failed to set kernel argument! %d\n", status); CLDevice::print_error_code(status); exit(status); } #endif // PV_USE_OPENCL return status; } int CLKernel::setLocalArg(int argid, size_t size) { int status = CL_SUCCESS; #ifdef PV_USE_OPENCL status = clSetKernelArg(kernel, argid, size, 0); if (status != CL_SUCCESS) { fprintf(stderr, "CLDevice::addLocalArg: Failed to set kernel argument! %d\n", status); CLDevice::print_error_code(status); exit(status); } #endif // PV_USE_OPENCL return status; } static char * load_program_source(const char *filename) { struct stat statbuf; FILE *fh; char *source; fh = fopen(filename, "r"); if (fh == 0) return 0; stat(filename, &statbuf); source = (char *) malloc(statbuf.st_size + 1); fread(source, statbuf.st_size, 1, fh); source[statbuf.st_size] = '\0'; return source; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2002-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Nathan Binkert */ /* * Copyright (c) 1990, 1993 * The Regents of the University of California. All rights reserved. * * This software was developed by the Computer Systems Engineering group * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and * contributed to Berkeley. * * All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Lawrence Berkeley Laboratories. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University 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 REGENTS 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 REGENTS 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. * * @(#)kgdb_stub.c 8.4 (Berkeley) 1/12/94 */ /*- * Copyright (c) 2001 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Jason R. Thorpe. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the NetBSD * Foundation, Inc. and its contributors. * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * $NetBSD: kgdb_stub.c,v 1.8 2001/07/07 22:58:00 wdk Exp $ * * Taken from NetBSD * * "Stub" to allow remote cpu to debug over a serial line using gdb. */ #include <sys/signal.h> #include <string> #include <unistd.h> #include "arch/vtophys.hh" #include "arch/sparc/remote_gdb.hh" #include "base/intmath.hh" #include "base/remote_gdb.hh" #include "base/socket.hh" #include "base/trace.hh" #include "config/full_system.hh" #include "cpu/thread_context.hh" #include "cpu/static_inst.hh" #include "mem/physical.hh" #include "mem/port.hh" #include "sim/system.hh" using namespace std; using namespace TheISA; RemoteGDB::RemoteGDB(System *_system, ThreadContext *c) : BaseRemoteGDB(_system, c, NumGDBRegs), nextBkpt(0) {} /////////////////////////////////////////////////////////// // RemoteGDB::acc // // Determine if the mapping at va..(va+len) is valid. // bool RemoteGDB::acc(Addr va, size_t len) { //@Todo In NetBSD, this function checks if all addresses //from va to va + len have valid page mape entries. Not //sure how this will work for other OSes or in general. if (va) return true; return false; } /////////////////////////////////////////////////////////// // RemoteGDB::getregs // // Translate the kernel debugger register format into // the GDB register format. void RemoteGDB::getregs() { memset(gdbregs.regs, 0, gdbregs.size); if (context->readMiscReg(MISCREG_PSTATE) & PSTATE::am) { uint32_t *regs; regs = (uint32_t*)gdbregs.regs; regs[Reg32Pc] = htobe((uint32_t)context->readPC()); regs[Reg32Npc] = htobe((uint32_t)context->readNextPC()); for(int x = RegG0; x <= RegI0 + 7; x++) regs[x] = htobe((uint32_t)context->readIntReg(x - RegG0)); regs[Reg32Y] = htobe((uint32_t)context->readIntReg(NumIntArchRegs + 1)); regs[Reg32Psr] = htobe((uint32_t)context->readMiscReg(MISCREG_PSTATE)); regs[Reg32Fsr] = htobe((uint32_t)context->readMiscReg(MISCREG_FSR)); regs[Reg32Csr] = htobe((uint32_t)context->readIntReg(NumIntArchRegs + 2)); } else { gdbregs.regs[RegPc] = htobe(context->readPC()); gdbregs.regs[RegNpc] = htobe(context->readNextPC()); for(int x = RegG0; x <= RegI0 + 7; x++) gdbregs.regs[x] = htobe(context->readIntReg(x - RegG0)); gdbregs.regs[RegFsr] = htobe(context->readMiscReg(MISCREG_FSR)); gdbregs.regs[RegFprs] = htobe(context->readMiscReg(MISCREG_FPRS)); gdbregs.regs[RegY] = htobe(context->readIntReg(NumIntArchRegs + 1)); gdbregs.regs[RegState] = htobe( context->readMiscReg(MISCREG_CWP) | context->readMiscReg(MISCREG_PSTATE) << 8 | context->readMiscReg(MISCREG_ASI) << 24 | context->readIntReg(NumIntArchRegs + 2) << 32); } DPRINTF(GDBRead, "PC=%#x\n", gdbregs.regs[RegPc]); //Floating point registers are left at 0 in netbsd //All registers other than the pc, npc and int regs //are ignored as well. } /////////////////////////////////////////////////////////// // RemoteGDB::setregs // // Translate the GDB register format into the kernel // debugger register format. // void RemoteGDB::setregs() { context->setPC(gdbregs.regs[RegPc]); context->setNextPC(gdbregs.regs[RegNpc]); for(int x = RegG0; x <= RegI0 + 7; x++) context->setIntReg(x - RegG0, gdbregs.regs[x]); //Only the integer registers, pc and npc are set in netbsd } void RemoteGDB::clearSingleStep() { if (nextBkpt) clearTempBreakpoint(nextBkpt); } void RemoteGDB::setSingleStep() { nextBkpt = context->readNextPC(); setTempBreakpoint(nextBkpt); } <commit_msg>SPARC,Remote GDB: Flesh out the acc function for SE mode.<commit_after>/* * Copyright (c) 2002-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Nathan Binkert */ /* * Copyright (c) 1990, 1993 * The Regents of the University of California. All rights reserved. * * This software was developed by the Computer Systems Engineering group * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and * contributed to Berkeley. * * All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Lawrence Berkeley Laboratories. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University 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 REGENTS 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 REGENTS 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. * * @(#)kgdb_stub.c 8.4 (Berkeley) 1/12/94 */ /*- * Copyright (c) 2001 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Jason R. Thorpe. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the NetBSD * Foundation, Inc. and its contributors. * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * $NetBSD: kgdb_stub.c,v 1.8 2001/07/07 22:58:00 wdk Exp $ * * Taken from NetBSD * * "Stub" to allow remote cpu to debug over a serial line using gdb. */ #include <sys/signal.h> #include <string> #include <unistd.h> #include "arch/vtophys.hh" #include "arch/sparc/remote_gdb.hh" #include "base/intmath.hh" #include "base/remote_gdb.hh" #include "base/socket.hh" #include "base/trace.hh" #include "config/full_system.hh" #include "cpu/thread_context.hh" #include "cpu/static_inst.hh" #include "mem/page_table.hh" #include "mem/physical.hh" #include "mem/port.hh" #include "sim/process.hh" #include "sim/system.hh" using namespace std; using namespace TheISA; RemoteGDB::RemoteGDB(System *_system, ThreadContext *c) : BaseRemoteGDB(_system, c, NumGDBRegs), nextBkpt(0) {} /////////////////////////////////////////////////////////// // RemoteGDB::acc // // Determine if the mapping at va..(va+len) is valid. // bool RemoteGDB::acc(Addr va, size_t len) { //@Todo In NetBSD, this function checks if all addresses //from va to va + len have valid page map entries. Not //sure how this will work for other OSes or in general. #if FULL_SYSTEM if (va) return true; return false; #else TlbEntry entry; //Check to make sure the first byte is mapped into the processes address //space. if (context->getProcessPtr()->pTable->lookup(va, entry)) return true; return false; #endif } /////////////////////////////////////////////////////////// // RemoteGDB::getregs // // Translate the kernel debugger register format into // the GDB register format. void RemoteGDB::getregs() { memset(gdbregs.regs, 0, gdbregs.size); if (context->readMiscReg(MISCREG_PSTATE) & PSTATE::am) { uint32_t *regs; regs = (uint32_t*)gdbregs.regs; regs[Reg32Pc] = htobe((uint32_t)context->readPC()); regs[Reg32Npc] = htobe((uint32_t)context->readNextPC()); for(int x = RegG0; x <= RegI0 + 7; x++) regs[x] = htobe((uint32_t)context->readIntReg(x - RegG0)); regs[Reg32Y] = htobe((uint32_t)context->readIntReg(NumIntArchRegs + 1)); regs[Reg32Psr] = htobe((uint32_t)context->readMiscReg(MISCREG_PSTATE)); regs[Reg32Fsr] = htobe((uint32_t)context->readMiscReg(MISCREG_FSR)); regs[Reg32Csr] = htobe((uint32_t)context->readIntReg(NumIntArchRegs + 2)); } else { gdbregs.regs[RegPc] = htobe(context->readPC()); gdbregs.regs[RegNpc] = htobe(context->readNextPC()); for(int x = RegG0; x <= RegI0 + 7; x++) gdbregs.regs[x] = htobe(context->readIntReg(x - RegG0)); gdbregs.regs[RegFsr] = htobe(context->readMiscReg(MISCREG_FSR)); gdbregs.regs[RegFprs] = htobe(context->readMiscReg(MISCREG_FPRS)); gdbregs.regs[RegY] = htobe(context->readIntReg(NumIntArchRegs + 1)); gdbregs.regs[RegState] = htobe( context->readMiscReg(MISCREG_CWP) | context->readMiscReg(MISCREG_PSTATE) << 8 | context->readMiscReg(MISCREG_ASI) << 24 | context->readIntReg(NumIntArchRegs + 2) << 32); } DPRINTF(GDBRead, "PC=%#x\n", gdbregs.regs[RegPc]); //Floating point registers are left at 0 in netbsd //All registers other than the pc, npc and int regs //are ignored as well. } /////////////////////////////////////////////////////////// // RemoteGDB::setregs // // Translate the GDB register format into the kernel // debugger register format. // void RemoteGDB::setregs() { context->setPC(gdbregs.regs[RegPc]); context->setNextPC(gdbregs.regs[RegNpc]); for(int x = RegG0; x <= RegI0 + 7; x++) context->setIntReg(x - RegG0, gdbregs.regs[x]); //Only the integer registers, pc and npc are set in netbsd } void RemoteGDB::clearSingleStep() { if (nextBkpt) clearTempBreakpoint(nextBkpt); } void RemoteGDB::setSingleStep() { nextBkpt = context->readNextPC(); setTempBreakpoint(nextBkpt); } <|endoftext|>
<commit_before>/* * Copyright 2018 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkFont.h" #include "SkPath.h" // This GM shows off a flaw in delta-based rasterizers (DAA, CCPR, etc.). // See also the bottom of dashing4 and skia:6886. static const int K = 50; DEF_SIMPLE_GM(daa, canvas, K+350, K) { SkPaint paint; paint.setAntiAlias(true); paint.setColor(SK_ColorBLACK); canvas->drawString("Should be a green square with no red showing through.", K*1.5f, K/2, SkFont(), paint); paint.setColor(SK_ColorRED); canvas->drawRect({0,0,K,K}, paint); SkPath path; SkPoint tri1[] = {{0,0},{K,K},{0,K},{0,0}}; SkPoint tri2[] = {{0,0},{K,K},{K,0},{0,0}}; path.addPoly(tri1, SK_ARRAY_COUNT(tri1), false); path.addPoly(tri2, SK_ARRAY_COUNT(tri2), false); paint.setColor(SK_ColorGREEN); canvas->drawPath(path, paint); } <commit_msg>Roll external/skia d6841487e..1edcea99a (1 commits)<commit_after>/* * Copyright 2018 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkFont.h" #include "SkPath.h" // This GM shows off a flaw in delta-based rasterizers (DAA, CCPR, etc.). // See also the bottom of dashing4 and skia:6886. static const int K = 49; DEF_SIMPLE_GM(daa, canvas, K+350, 5*K) { SkPaint paint; paint.setAntiAlias(true); { paint.setColor(SK_ColorBLACK); canvas->drawString("Should be a green square with no red showing through.", K*1.5f, K*0.5f, SkFont(), paint); paint.setColor(SK_ColorRED); canvas->drawRect({0,0,K,K}, paint); SkPath path; SkPoint tri1[] = {{0,0},{K,K},{0,K},{0,0}}; SkPoint tri2[] = {{0,0},{K,K},{K,0},{0,0}}; path.addPoly(tri1, SK_ARRAY_COUNT(tri1), false); path.addPoly(tri2, SK_ARRAY_COUNT(tri2), false); paint.setColor(SK_ColorGREEN); canvas->drawPath(path, paint); } canvas->translate(0,K); { paint.setColor(SK_ColorBLACK); canvas->drawString("Adjacent rects, two draws. Blue then green, no red?", K*1.5f, K*0.5f, SkFont(), paint); paint.setColor(SK_ColorRED); canvas->drawRect({0,0,K,K}, paint); { SkPath path; SkPoint rect1[] = {{0,0},{0,K},{K*0.5f,K},{K*0.5f,0}}; path.addPoly(rect1, SK_ARRAY_COUNT(rect1), false); paint.setColor(SK_ColorBLUE); canvas->drawPath(path, paint); } { SkPath path; SkPoint rect2[] = {{K*0.5f,0},{K*0.5f,K},{K,K},{K,0}}; path.addPoly(rect2, SK_ARRAY_COUNT(rect2), false); paint.setColor(SK_ColorGREEN); canvas->drawPath(path, paint); } } canvas->translate(0,K); { paint.setColor(SK_ColorBLACK); canvas->drawString("Adjacent rects, wound together. All green?", K*1.5f, K*0.5f, SkFont(), paint); paint.setColor(SK_ColorRED); canvas->drawRect({0,0,K,K}, paint); { SkPath path; SkPoint rect1[] = {{0,0},{0,K},{K*0.5f,K},{K*0.5f,0}}; SkPoint rect2[] = {{K*0.5f,0},{K*0.5f,K},{K,K},{K,0}}; path.addPoly(rect1, SK_ARRAY_COUNT(rect1), false); path.addPoly(rect2, SK_ARRAY_COUNT(rect2), false); paint.setColor(SK_ColorGREEN); canvas->drawPath(path, paint); } } canvas->translate(0,K); { paint.setColor(SK_ColorBLACK); canvas->drawString("Adjacent rects, wound opposite. All green?", K*1.5f, K*0.5f, SkFont(), paint); paint.setColor(SK_ColorRED); canvas->drawRect({0,0,K,K}, paint); { SkPath path; SkPoint rect1[] = {{0,0},{0,K},{K*0.5f,K},{K*0.5f,0}}; SkPoint rect2[] = {{K*0.5f,0},{K,0},{K,K},{K*0.5f,K}}; path.addPoly(rect1, SK_ARRAY_COUNT(rect1), false); path.addPoly(rect2, SK_ARRAY_COUNT(rect2), false); paint.setColor(SK_ColorGREEN); canvas->drawPath(path, paint); } } canvas->translate(0,K); { paint.setColor(SK_ColorBLACK); canvas->drawString("One poly, wound opposite. All green?", K*1.5f, K*0.5f, SkFont(), paint); paint.setColor(SK_ColorRED); canvas->drawRect({0,0,K,K}, paint); { SkPath path; SkPoint poly[] = {{K*0.5f,0},{0,0},{0,K},{K*0.5f,K},{K*0.5f,0},{K,0},{K,K},{K*0.5f,K}}; path.addPoly(poly, SK_ARRAY_COUNT(poly), false); paint.setColor(SK_ColorGREEN); canvas->drawPath(path, paint); } } } <|endoftext|>
<commit_before>//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #include <iostream> #include <map> using namespace std; #include <ossim/init/ossimInit.h> #include <ossim/base/ossimArgumentParser.h> #include <ossim/base/ossimApplicationUsage.h> #include <ossim/base/ossimStdOutProgress.h> #include <ossim/base/ossimTimer.h> #include <ossim/base/ossimKeywordlist.h> #include <ossim/base/ossimString.h> #include <ossim/util/ossimUtilityRegistry.h> #include <ossim/base/ossimException.h> int main(int argc, char *argv[]) { ossimArgumentParser ap(&argc, argv); ap.getApplicationUsage()->setApplicationName(argv[0]); try { // Initialize ossim stuff, factories, plugin, etc. ossimInit::instance()->initialize(ap); ossimUtilityFactoryBase* factory = ossimUtilityRegistry::instance(); map<string, string> capabilities; factory->getCapabilities(capabilities); ossimRefPtr<ossimUtility> utility = 0; ossimString toolName; ossimKeywordlist kwl; char input[4096]; bool usingCmdLineMode = false; if ((argc > 1) && (ossimString(argv[1]).contains("help"))) { cout << "\nUsages: "<<endl; cout << " "<<argv[0]<<" <command> [command options and parameters]"<<endl; cout << " "<<argv[0]<<" --version"<<endl; cout << " "<<argv[0]<<" (with no args, displays command descriptions)\n"<<endl; exit (0); } if (argc > 1) { if (ossimString(argv[1]).contains("--")) { // Support ossim-info style system queries by interpreting any options as options to // info tool: toolName = "info"; usingCmdLineMode = true; } else if (kwl.addFile(argv[1])) { // KWL filename provided, get tool name from it: toolName = kwl.find("tool"); ap.remove(0); } else { // The tool name was explicitely provided on command line: toolName = argv[1]; if (argc > 2) usingCmdLineMode = true; ap.remove(0); } } // Using one-time do-loop for breaking out when finished processing: do { if (toolName.empty()) { map<string, string>::iterator iter = capabilities.begin(); cout<<"\n\nAvailable commands:"<<endl; for (;iter != capabilities.end(); ++iter) cout<<" "<<iter->first<<" -- "<<iter->second<<endl; // Query for operation: cout << "\nossim> "; cin.getline(input, 256); if (input[0] == 'q') break; toolName = input; } // Fetch the utility object: ossimRefPtr<ossimUtility> utility = factory->createUtility(toolName); if (!utility.valid()) { cout << "\nDid not understand <"<<toolName<<">"<<endl; continue; } if (usingCmdLineMode) { // Check if user provided options along with tool name: // Init utility with command line if (!utility->initialize(ap)) { cout << "\nCould not execute command with options provided."<<endl; } if (!utility->execute()) { cout << "\nAn error was encountered executing the command. Check options."<<endl; } continue; } if (utility.valid() && !toolName.empty()) { // Have toolname but no command line options: cout << "\nEnter command arguments/options or return for usage. "<<endl; cout << "\nossim> "; cin.getline(input, 4096); if (input[0] == 'q') break; // Create the command line with either "help" or inputs: ossimString cmdLine (toolName); cmdLine += " "; if (input[0] == '\0') cmdLine += "--help"; else cmdLine += input; // Run command: ossimArgumentParser tap (cmdLine); utility->initialize(tap); if (cmdLine.contains("--help")) continue; utility->execute(); break; } if (kwl.getSize() == 0) { // // Query for config filename: ossimKeywordlist kwl; cout << "\nEnter config file name or <return> for template: " << ends; cin.getline(input, 4096); if (input[0] && !kwl.addFile(input)) { cout<<"\nCould not load config file at <"<<input<<">"<<endl; break; } } // Init utility with KWL if available: if (kwl.getSize()) { utility->initialize(kwl); utility->execute(); break; } // Display API: ossimKeywordlist kwl_template; utility->getKwlTemplate(kwl_template); cout << "\nUtility template specification: "<<endl; cout << kwl_template << endl; // Accept inputs: do { cout << "Enter \"<keyword>: <value>\" with colon separator (or 'x' to finish): "; cin.getline(input, 4096); if (input[0] == 'x' || (!kwl.parseString(string(input)))) break; } while (1); if (kwl.getSize() == 0) break; // Display final KWL: cout << "\nUtility final specification: "<<endl; cout << kwl << endl; // Query go-ahead. Perform operation: while (1) { cout << "Perform operation? [y|n]: "; cin.getline(input, 4096); if (input[0] == 'n') break; else if (input[0] == 'y') { utility->initialize(kwl); utility->execute(); break; } } } while (true); } catch (const ossimException& e) { ossimNotify(ossimNotifyLevel_FATAL)<<e.what()<<endl; exit(1); } catch( ... ) { cerr << "Caught unknown exception!" << endl; } exit(0); } <commit_msg>Fixed typo in ossim-cli<commit_after>//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #include <iostream> #include <map> using namespace std; #include <ossim/init/ossimInit.h> #include <ossim/base/ossimArgumentParser.h> #include <ossim/base/ossimApplicationUsage.h> #include <ossim/base/ossimStdOutProgress.h> #include <ossim/base/ossimTimer.h> #include <ossim/base/ossimKeywordlist.h> #include <ossim/base/ossimString.h> #include <ossim/util/ossimUtilityRegistry.h> #include <ossim/base/ossimException.h> int main(int argc, char *argv[]) { ossimArgumentParser ap(&argc, argv); ap.getApplicationUsage()->setApplicationName(argv[0]); try { // Initialize ossim stuff, factories, plugin, etc. ossimInit::instance()->initialize(ap); ossimUtilityFactoryBase* factory = ossimUtilityRegistry::instance(); map<string, string> capabilities; factory->getCapabilities(capabilities); ossimRefPtr<ossimUtility> utility = 0; ossimString toolName; ossimKeywordlist kwl; char input[4096]; bool usingCmdLineMode = false; if ((argc > 1) && (ossimString(argv[1]).contains("help"))) { cout << "\nUsages: "<<endl; cout << " "<<argv[0]<<" <command> [command options and parameters]"<<endl; cout << " "<<argv[0]<<" --version"<<endl; cout << " "<<argv[0]<<" (with no args, displays command descriptions)\n"<<endl; exit (0); } if (argc > 1) { if (ossimString(argv[1]).contains("--")) { // Support ossim-info style system queries by interpreting any options as options to // info tool: toolName = "info"; usingCmdLineMode = true; } else if (kwl.addFile(argv[1])) { // KWL filename provided, get tool name from it: toolName = kwl.find("tool"); ap.remove(0); } else { // The tool name was explicitely provided on command line: toolName = argv[1]; if (argc > 2) usingCmdLineMode = true; ap.remove(0); } } // Using one-time do-loop for breaking out when finished processing: do { if (toolName.empty()) { map<string, string>::iterator iter = capabilities.begin(); cout<<"\n\nAvailable commands:"<<endl; for (;iter != capabilities.end(); ++iter) cout<<" "<<iter->first<<" -- "<<iter->second<<endl; // Query for operation: cout << "\nossim> "; cin.getline(input, 256); if (input[0] == 'q') break; toolName = input; } // Fetch the utility object: ossimRefPtr<ossimUtility> utility = factory->createUtility(toolName); if (!utility.valid()) { cout << "\nDid not understand <"<<toolName<<">"<<endl; continue; } if (usingCmdLineMode) { // Check if user provided options along with tool name: // Init utility with command line if (!utility->initialize(ap)) { cout << "\nCould not execute command with options provided."<<endl; } if (!utility->execute()) { cout << "\nAn error was encountered executing the command. Check options."<<endl; } break; } if (utility.valid() && !toolName.empty()) { // Have toolname but no command line options: cout << "\nEnter command arguments/options or return for usage. "<<endl; cout << "\nossim> "; cin.getline(input, 4096); if (input[0] == 'q') break; // Create the command line with either "help" or inputs: ossimString cmdLine (toolName); cmdLine += " "; if (input[0] == '\0') cmdLine += "--help"; else cmdLine += input; // Run command: ossimArgumentParser tap (cmdLine); utility->initialize(tap); if (cmdLine.contains("--help")) { toolName = ""; continue; } utility->execute(); break; } if (kwl.getSize() == 0) { // // Query for config filename: ossimKeywordlist kwl; cout << "\nEnter config file name or <return> for template: " << ends; cin.getline(input, 4096); if (input[0] && !kwl.addFile(input)) { cout<<"\nCould not load config file at <"<<input<<">"<<endl; break; } } // Init utility with KWL if available: if (kwl.getSize()) { utility->initialize(kwl); utility->execute(); break; } // Display API: ossimKeywordlist kwl_template; utility->getKwlTemplate(kwl_template); cout << "\nUtility template specification: "<<endl; cout << kwl_template << endl; // Accept inputs: do { cout << "Enter \"<keyword>: <value>\" with colon separator (or 'x' to finish): "; cin.getline(input, 4096); if (input[0] == 'x' || (!kwl.parseString(string(input)))) break; } while (1); if (kwl.getSize() == 0) break; // Display final KWL: cout << "\nUtility final specification: "<<endl; cout << kwl << endl; // Query go-ahead. Perform operation: while (1) { cout << "Perform operation? [y|n]: "; cin.getline(input, 4096); if (input[0] == 'n') break; else if (input[0] == 'y') { utility->initialize(kwl); utility->execute(); break; } } } while (true); } catch (const ossimException& e) { ossimNotify(ossimNotifyLevel_FATAL)<<e.what()<<endl; exit(1); } catch( ... ) { cerr << "Caught unknown exception!" << endl; } exit(0); } <|endoftext|>
<commit_before>#define BENCHMARK_FIB //#define SINGLESTEP #ifdef BENCHMARK_FIB # define START 0 # define ENTRY 0 #else # define START 0 # define ENTRY 0 #endif #include "timings.h" #define START_NO 1000000000 #define TIMES 100 #include <libcpu.h> #include "arch/m88k/libcpu_m88k.h" #include "arch/m88k/m88k_isa.h" ////////////////////////////////////////////////////////////////////// // command line parsing helpers ////////////////////////////////////////////////////////////////////// void tag_extra(cpu_t *cpu, char *entries) { addr_t entry; char* old_entries; while (entries && *entries) { /* just one for now */ if (entries[0] == ',') entries++; if (!entries[0]) break; old_entries = entries; entry = (addr_t)strtol(entries, &entries, 0); if (entries == old_entries) { printf("Error parsing entries!\n"); exit(3); } cpu_tag(cpu, entry); } } void tag_extra_filename(cpu_t *cpu, char *filename) { FILE *fp; char *buf; size_t nbytes; fp = fopen(filename, "r"); if (!fp) { perror("error opening tag file"); exit(3); } fseek(fp, 0, SEEK_END); nbytes = ftell(fp); fseek(fp, 0, SEEK_SET); buf = (char*)malloc(nbytes + 1); nbytes = fread(buf, 1, nbytes, fp); buf[nbytes] = '\0'; fclose(fp); while (nbytes && buf[nbytes - 1] == '\n') buf[--nbytes] = '\0'; tag_extra(cpu, buf); free(buf); } void __attribute__((noinline)) breakpoint() { asm("nop"); } static double ieee754_fp80_to_double(fp80_reg_t reg) { #if defined(__i386__) || defined(__x86_64__) #if 0 uint32_t sign = (reg.i.hi & 0x8000) != 0; uint32_t exp = reg.i.hi & 0x7fff; uint64_t mantissa = reg.i.lo; #endif return (double)reg.f; #else uint32_t sign = (reg.i.hi & 0x8000) != 0; uint32_t exp = reg.i.hi & 0x7fff; uint64_t mantissa = reg.i.lo << 1; uint64_t v64 = ((uint64_t)sign << 63) | ((uint64_t)(exp & 0x7000) << 48) | ((uint64_t)(exp & 0x3ff) << 52) | (mantissa >> 12); return *(double *)&v64; #endif } #if 0 static void ieee754_fp80_set_d(fp80_reg_t *reg, double v) { #if defined(__i386__) || defined(__x86_64__) reg->f = v; #else uint64_t v64 = *(uint64_t *)&v; uint32_t sign = (v64 >> 63); uint32_t exp = (v64 >> 52) & 0x7ff; uint64_t mantissa = v64 & ((1ULL << 52) - 1); mantissa <<= 11; mantissa |= (1ULL << 63); exp = ((exp & 0x700) << 4) | ((-((exp >> 9) & 1)) & 0xf00) | (exp & 0x3ff); reg->i.hi = (sign << 15) | exp; reg->i.lo = mantissa; #endif } #endif static void dump_state(uint8_t *RAM, m88k_grf_t *reg, m88k_xrf_t *xrf) { printf("%08llx:", (unsigned long long)reg->sxip); for (int i=0; i<32; i++) { if (!(i%4)) printf("\n"); printf("R%02d=%08x ", i, (unsigned int)reg->r[i]); } for (int i=0; xrf != NULL && i<32; i++) { if (!(i%2)) printf("\n"); printf("X%02d=%04x%016llx (%.8f) ", i, xrf->x[i].i.hi, xrf->x[i].i.lo, ieee754_fp80_to_double(xrf->x[i])); } uint32_t base = reg->r[31]; for (int i=0; i<256 && i+base<65536; i+=4) { if (!(i%16)) printf("\nSTACK: "); printf("%08x ", *(unsigned int*)&RAM[(base+i)]); } printf("\n"); } static void debug_function(cpu_t *cpu) { fprintf(stderr, "%s:%u\n", __FILE__, __LINE__); } #if 0 int fib(int n) { if (n==0 || n==1) return n; else return fib(n-1) + fib(n-2); } #else int fib(int n) { int f2=0; int f1=1; int fib=0; int i; if (n==0 || n==1) return n; for(i=2;i<=n;i++){ fib=f1+f2; /*sum*/ f2=f1; f1=fib; } return fib; } #endif ////////////////////////////////////////////////////////////////////// int main(int argc, char **argv) { char *executable; char *entries; cpu_t *cpu; uint8_t *RAM; FILE *f; int ramsize; char *stack; int i; #ifdef BENCHMARK_FIB int r1, r2; uint64_t t1, t2, t3, t4; unsigned start_no = START_NO; #endif #ifdef SINGLESTEP int step = 0; #endif ramsize = 5*1024*1024; RAM = (uint8_t*)malloc(ramsize); cpu = cpu_new(CPU_ARCH_M88K, CPU_FLAG_ENDIAN_BIG, 0); #ifdef SINGLESTEP cpu_set_flags_optimize(cpu, CPU_OPTIMIZE_ALL); cpu_set_flags_debug(cpu, CPU_DEBUG_SINGLESTEP | CPU_DEBUG_PRINT_IR | CPU_DEBUG_PRINT_IR_OPTIMIZED); #else cpu_set_flags_optimize(cpu, CPU_OPTIMIZE_ALL); // cpu_set_flags_optimize(cpu, CPU_OPTIMIZE_NONE); // cpu_set_flags_optimize(cpu, 0x3eff); // cpu_set_flags_optimize(cpu, 0x3eff); cpu_set_flags_debug(cpu, CPU_DEBUG_PRINT_IR | CPU_DEBUG_PRINT_IR_OPTIMIZED); #endif cpu_set_ram(cpu, RAM); /* parameter parsing */ if (argc < 2) { #ifdef BENCHMARK_FIB printf("Usage: %s executable [itercount] [entries]\n", argv[0]); #else printf("Usage: %s executable [entries]\n", argv[0]); #endif return 0; } executable = argv[1]; #ifdef BENCHMARK_FIB if (argc >= 3) start_no = atoi(argv[2]); if (argc >= 4) entries = argv[3]; else entries = 0; #else if (argc >= 3) entries = argv[2]; else entries = 0; #endif /* load code */ if (!(f = fopen(executable, "rb"))) { printf("Could not open %s!\n", executable); return 2; } cpu->code_start = START; cpu->code_end = cpu->code_start + fread(&RAM[cpu->code_start], 1, ramsize-cpu->code_start, f); fclose(f); cpu->code_entry = cpu->code_start + ENTRY; cpu_tag(cpu, cpu->code_entry); if (entries && *entries == '@') tag_extra_filename(cpu, entries + 1); else tag_extra(cpu, entries); /* tag extra entry points from the command line */ #ifdef RET_OPTIMIZATION find_rets(RAM, cpu->code_start, cpu->code_end); #endif printf("*** Executing...\n"); #define STACK_SIZE 65536 stack = (char *)(ramsize - STACK_SIZE); // THIS IS *GUEST* ADDRESS! #define STACK ((long long)(stack+STACK_SIZE-4)) #define PC (((m88k_grf_t*)cpu->rf.grf)->sxip) #define PSR (((m88k_grf_t*)cpu->rf.grf)->psr) #define R (((m88k_grf_t*)cpu->rf.grf)->r) #define X (((m88k_xrf_t*)cpu->rf.fpr)->x) PC = cpu->code_entry; #if 0 for (i = 1; i < 32; i++) R[i] = 0xF0000000 + i; // DEBUG #endif R[31] = STACK; // STACK R[1] = -1; // return address #ifdef BENCHMARK_FIB//fib R[2] = start_no; // parameter #else R[2] = 0x3f800000; // 1.0 ieee754_fp80_set_d(&X[2], 1.0); #endif dump_state(RAM, (m88k_grf_t*)cpu->rf.grf, NULL); #ifdef SINGLESTEP for(step = 0;;) { printf("::STEP:: %d\n", step++); cpu_run(cpu, debug_function); dump_state(RAM, (m88k_grf_t*)cpu->reg); printf ("NPC=%08x\n", PC); if (PC == -1) break; cpu_flush(cpu); printf("*** PRESS <ENTER> TO CONTINUE ***\n"); getchar(); } #else for(;;) { int ret; breakpoint(); ret = cpu_run(cpu, debug_function); printf("ret = %d\n", ret); switch (ret) { case JIT_RETURN_NOERR: /* JIT code wants us to end execution */ break; case JIT_RETURN_FUNCNOTFOUND: dump_state(RAM, (m88k_grf_t*)cpu->rf.grf, (m88k_xrf_t*)cpu->rf.frf); if (PC == (uint32_t)(-1)) goto double_break; // bad :( printf("%s: error: $%llX not found!\n", __func__, (unsigned long long)PC); printf("PC: "); for (i = 0; i < 16; i++) printf("%02X ", RAM[PC+i]); printf("\n"); exit(1); default: printf("unknown return code: %d\n", ret); } } double_break: #ifdef BENCHMARK_FIB printf("start_no=%u\n", start_no); printf("RUN1..."); fflush(stdout); PC = cpu->code_entry; for (i = 1; i < 32; i++) R[i] = 0xF0000000 + i; // DEBUG R[31] = STACK; // STACK R[1] = -1; // return address R[2] = start_no; // parameter breakpoint(); t1 = abs_time(); // for (int i=0; i<TIMES; i++) cpu_run(cpu, debug_function); r1 = R[2]; t2 = abs_time(); printf("done!\n"); dump_state(RAM, (m88k_grf_t*)cpu->rf.grf, NULL); printf("RUN2..."); fflush(stdout); t3 = abs_time(); // for (int i=0; i<TIMES; i++) r2 = fib(start_no); t4 = abs_time(); printf("done!\n"); printf("%d -- %d\n", r1, r2); printf("%lld -- %lld\n", t2-t1, t4-t3); printf("%f%%\n", (float)(t2-t1)/(float)(t4-t3)); #endif #endif printf("done.\n"); int base = 0x2000; for (int i=0; i<256; i+=4) { if (!(i%16)) printf("\nDATA: "); printf("%08x ", *(unsigned int*)&RAM[(base+i)]); } printf("\n"); return 0; } <commit_msg>Pass fp80_reg_t by reference (MSVC doesn't like passing structs with alignment by value)<commit_after>#define BENCHMARK_FIB //#define SINGLESTEP #ifdef BENCHMARK_FIB # define START 0 # define ENTRY 0 #else # define START 0 # define ENTRY 0 #endif #include "timings.h" #define START_NO 1000000000 #define TIMES 100 #include <libcpu.h> #include "arch/m88k/libcpu_m88k.h" #include "arch/m88k/m88k_isa.h" ////////////////////////////////////////////////////////////////////// // command line parsing helpers ////////////////////////////////////////////////////////////////////// void tag_extra(cpu_t *cpu, char *entries) { addr_t entry; char* old_entries; while (entries && *entries) { /* just one for now */ if (entries[0] == ',') entries++; if (!entries[0]) break; old_entries = entries; entry = (addr_t)strtol(entries, &entries, 0); if (entries == old_entries) { printf("Error parsing entries!\n"); exit(3); } cpu_tag(cpu, entry); } } void tag_extra_filename(cpu_t *cpu, char *filename) { FILE *fp; char *buf; size_t nbytes; fp = fopen(filename, "r"); if (!fp) { perror("error opening tag file"); exit(3); } fseek(fp, 0, SEEK_END); nbytes = ftell(fp); fseek(fp, 0, SEEK_SET); buf = (char*)malloc(nbytes + 1); nbytes = fread(buf, 1, nbytes, fp); buf[nbytes] = '\0'; fclose(fp); while (nbytes && buf[nbytes - 1] == '\n') buf[--nbytes] = '\0'; tag_extra(cpu, buf); free(buf); } void __attribute__((noinline)) breakpoint() { asm("nop"); } static double ieee754_fp80_to_double(const fp80_reg_t &reg) { #if defined(__i386__) || defined(__x86_64__) #if 0 uint32_t sign = (reg.i.hi & 0x8000) != 0; uint32_t exp = reg.i.hi & 0x7fff; uint64_t mantissa = reg.i.lo; #endif return (double)reg.f; #else uint32_t sign = (reg.i.hi & 0x8000) != 0; uint32_t exp = reg.i.hi & 0x7fff; uint64_t mantissa = reg.i.lo << 1; uint64_t v64 = ((uint64_t)sign << 63) | ((uint64_t)(exp & 0x7000) << 48) | ((uint64_t)(exp & 0x3ff) << 52) | (mantissa >> 12); return *(double *)&v64; #endif } #if 0 static void ieee754_fp80_set_d(fp80_reg_t *reg, double v) { #if defined(__i386__) || defined(__x86_64__) reg->f = v; #else uint64_t v64 = *(uint64_t *)&v; uint32_t sign = (v64 >> 63); uint32_t exp = (v64 >> 52) & 0x7ff; uint64_t mantissa = v64 & ((1ULL << 52) - 1); mantissa <<= 11; mantissa |= (1ULL << 63); exp = ((exp & 0x700) << 4) | ((-((exp >> 9) & 1)) & 0xf00) | (exp & 0x3ff); reg->i.hi = (sign << 15) | exp; reg->i.lo = mantissa; #endif } #endif static void dump_state(uint8_t *RAM, m88k_grf_t *reg, m88k_xrf_t *xrf) { printf("%08llx:", (unsigned long long)reg->sxip); for (int i=0; i<32; i++) { if (!(i%4)) printf("\n"); printf("R%02d=%08x ", i, (unsigned int)reg->r[i]); } for (int i=0; xrf != NULL && i<32; i++) { if (!(i%2)) printf("\n"); printf("X%02d=%04x%016llx (%.8f) ", i, xrf->x[i].i.hi, xrf->x[i].i.lo, ieee754_fp80_to_double(xrf->x[i])); } uint32_t base = reg->r[31]; for (int i=0; i<256 && i+base<65536; i+=4) { if (!(i%16)) printf("\nSTACK: "); printf("%08x ", *(unsigned int*)&RAM[(base+i)]); } printf("\n"); } static void debug_function(cpu_t *cpu) { fprintf(stderr, "%s:%u\n", __FILE__, __LINE__); } #if 0 int fib(int n) { if (n==0 || n==1) return n; else return fib(n-1) + fib(n-2); } #else int fib(int n) { int f2=0; int f1=1; int fib=0; int i; if (n==0 || n==1) return n; for(i=2;i<=n;i++){ fib=f1+f2; /*sum*/ f2=f1; f1=fib; } return fib; } #endif ////////////////////////////////////////////////////////////////////// int main(int argc, char **argv) { char *executable; char *entries; cpu_t *cpu; uint8_t *RAM; FILE *f; int ramsize; char *stack; int i; #ifdef BENCHMARK_FIB int r1, r2; uint64_t t1, t2, t3, t4; unsigned start_no = START_NO; #endif #ifdef SINGLESTEP int step = 0; #endif ramsize = 5*1024*1024; RAM = (uint8_t*)malloc(ramsize); cpu = cpu_new(CPU_ARCH_M88K, CPU_FLAG_ENDIAN_BIG, 0); #ifdef SINGLESTEP cpu_set_flags_optimize(cpu, CPU_OPTIMIZE_ALL); cpu_set_flags_debug(cpu, CPU_DEBUG_SINGLESTEP | CPU_DEBUG_PRINT_IR | CPU_DEBUG_PRINT_IR_OPTIMIZED); #else cpu_set_flags_optimize(cpu, CPU_OPTIMIZE_ALL); // cpu_set_flags_optimize(cpu, CPU_OPTIMIZE_NONE); // cpu_set_flags_optimize(cpu, 0x3eff); // cpu_set_flags_optimize(cpu, 0x3eff); cpu_set_flags_debug(cpu, CPU_DEBUG_PRINT_IR | CPU_DEBUG_PRINT_IR_OPTIMIZED); #endif cpu_set_ram(cpu, RAM); /* parameter parsing */ if (argc < 2) { #ifdef BENCHMARK_FIB printf("Usage: %s executable [itercount] [entries]\n", argv[0]); #else printf("Usage: %s executable [entries]\n", argv[0]); #endif return 0; } executable = argv[1]; #ifdef BENCHMARK_FIB if (argc >= 3) start_no = atoi(argv[2]); if (argc >= 4) entries = argv[3]; else entries = 0; #else if (argc >= 3) entries = argv[2]; else entries = 0; #endif /* load code */ if (!(f = fopen(executable, "rb"))) { printf("Could not open %s!\n", executable); return 2; } cpu->code_start = START; cpu->code_end = cpu->code_start + fread(&RAM[cpu->code_start], 1, ramsize-cpu->code_start, f); fclose(f); cpu->code_entry = cpu->code_start + ENTRY; cpu_tag(cpu, cpu->code_entry); if (entries && *entries == '@') tag_extra_filename(cpu, entries + 1); else tag_extra(cpu, entries); /* tag extra entry points from the command line */ #ifdef RET_OPTIMIZATION find_rets(RAM, cpu->code_start, cpu->code_end); #endif printf("*** Executing...\n"); #define STACK_SIZE 65536 stack = (char *)(ramsize - STACK_SIZE); // THIS IS *GUEST* ADDRESS! #define STACK ((long long)(stack+STACK_SIZE-4)) #define PC (((m88k_grf_t*)cpu->rf.grf)->sxip) #define PSR (((m88k_grf_t*)cpu->rf.grf)->psr) #define R (((m88k_grf_t*)cpu->rf.grf)->r) #define X (((m88k_xrf_t*)cpu->rf.fpr)->x) PC = cpu->code_entry; #if 0 for (i = 1; i < 32; i++) R[i] = 0xF0000000 + i; // DEBUG #endif R[31] = STACK; // STACK R[1] = -1; // return address #ifdef BENCHMARK_FIB//fib R[2] = start_no; // parameter #else R[2] = 0x3f800000; // 1.0 ieee754_fp80_set_d(&X[2], 1.0); #endif dump_state(RAM, (m88k_grf_t*)cpu->rf.grf, NULL); #ifdef SINGLESTEP for(step = 0;;) { printf("::STEP:: %d\n", step++); cpu_run(cpu, debug_function); dump_state(RAM, (m88k_grf_t*)cpu->reg); printf ("NPC=%08x\n", PC); if (PC == -1) break; cpu_flush(cpu); printf("*** PRESS <ENTER> TO CONTINUE ***\n"); getchar(); } #else for(;;) { int ret; breakpoint(); ret = cpu_run(cpu, debug_function); printf("ret = %d\n", ret); switch (ret) { case JIT_RETURN_NOERR: /* JIT code wants us to end execution */ break; case JIT_RETURN_FUNCNOTFOUND: dump_state(RAM, (m88k_grf_t*)cpu->rf.grf, (m88k_xrf_t*)cpu->rf.frf); if (PC == (uint32_t)(-1)) goto double_break; // bad :( printf("%s: error: $%llX not found!\n", __func__, (unsigned long long)PC); printf("PC: "); for (i = 0; i < 16; i++) printf("%02X ", RAM[PC+i]); printf("\n"); exit(1); default: printf("unknown return code: %d\n", ret); } } double_break: #ifdef BENCHMARK_FIB printf("start_no=%u\n", start_no); printf("RUN1..."); fflush(stdout); PC = cpu->code_entry; for (i = 1; i < 32; i++) R[i] = 0xF0000000 + i; // DEBUG R[31] = STACK; // STACK R[1] = -1; // return address R[2] = start_no; // parameter breakpoint(); t1 = abs_time(); // for (int i=0; i<TIMES; i++) cpu_run(cpu, debug_function); r1 = R[2]; t2 = abs_time(); printf("done!\n"); dump_state(RAM, (m88k_grf_t*)cpu->rf.grf, NULL); printf("RUN2..."); fflush(stdout); t3 = abs_time(); // for (int i=0; i<TIMES; i++) r2 = fib(start_no); t4 = abs_time(); printf("done!\n"); printf("%d -- %d\n", r1, r2); printf("%lld -- %lld\n", t2-t1, t4-t3); printf("%f%%\n", (float)(t2-t1)/(float)(t4-t3)); #endif #endif printf("done.\n"); int base = 0x2000; for (int i=0; i<256; i+=4) { if (!(i%16)) printf("\nDATA: "); printf("%08x ", *(unsigned int*)&RAM[(base+i)]); } printf("\n"); return 0; } <|endoftext|>
<commit_before>// // yas_ui_collider.cpp // #include "yas_observing.h" #include "yas_property.h" #include "yas_to_bool.h" #include "yas_ui_collider.h" using namespace yas; #pragma mark - shape bool ui::anywhere_shape::hit_test(ui::point const &) const { return true; } bool ui::circle_shape::hit_test(ui::point const &pos) const { return std::powf(pos.x - center.x, 2.0f) + std::powf(pos.y - center.y, 2.0f) < std::powf(radius, 2.0f); } bool ui::rect_shape::hit_test(ui::point const &pos) const { return contains(rect, pos); } struct ui::shape::impl_base : base::impl { virtual std::type_info const &type() const = 0; virtual bool hit_test(ui::point const &) = 0; }; template <typename T> struct ui::shape::impl : impl_base { typename T::type _value; impl(typename T::type &&value) : _value(std::move(value)) { } std::type_info const &type() const override { return typeid(T); } bool hit_test(ui::point const &pos) override { return _value.hit_test(pos); } }; ui::shape::shape(anywhere::type shape) : base(std::make_shared<impl<anywhere>>(std::move(shape))) { } ui::shape::shape(circle::type shape) : base(std::make_shared<impl<circle>>(std::move(shape))) { } ui::shape::shape(rect::type shape) : base(std::make_shared<impl<rect>>(std::move(shape))) { } ui::shape::shape(std::nullptr_t) : base(nullptr) { } ui::shape::~shape() = default; std::type_info const &ui::shape::type_info() const { return impl_ptr<impl_base>()->type(); } bool ui::shape::hit_test(ui::point const &pos) const { return impl_ptr<impl_base>()->hit_test(pos); } template <typename T> typename T::type const &ui::shape::get() const { if (auto ip = std::dynamic_pointer_cast<impl<T>>(impl_ptr())) { return ip->_value; } static const typename T::type _default{}; return _default; } template ui::anywhere_shape const &ui::shape::get<ui::shape::anywhere>() const; template ui::circle_shape const &ui::shape::get<ui::shape::circle>() const; template ui::rect_shape const &ui::shape::get<ui::shape::rect>() const; #pragma mark - collider struct ui::collider::impl : base::impl, renderable_collider::impl { property<ui::shape> _shape_property{{.value = nullptr}}; property<bool> _enabled_property{{.value = true}}; subject_t _subject; std::vector<base> _property_observers; impl(ui::shape &&shape) : _shape_property({.value = std::move(shape)}) { _property_observers.reserve(2); } void dispatch_method(ui::collider::method const method) { auto weak_collider = to_weak(cast<ui::collider>()); base observer = nullptr; switch (method) { case ui::collider::method::shape_changed: observer = _shape_property.subject().make_observer( property_method::did_change, [weak_collider](auto const &context) { if (auto collider = weak_collider.lock()) { collider.subject().notify(ui::collider::method::shape_changed, collider); } }); break; case ui::collider::method::enabled_changed: observer = _enabled_property.subject().make_observer( property_method::did_change, [weak_collider](auto const &context) { if (auto collider = weak_collider.lock()) { collider.subject().notify(ui::collider::method::enabled_changed, collider); } }); break; } _property_observers.emplace_back(std::move(observer)); } bool hit_test(ui::point const &loc) { auto const &shape = _shape_property.value(); if (shape && _enabled_property.value()) { auto pos = simd::float4x4(matrix_invert(_matrix)) * to_float4(loc.v); return shape.hit_test({pos.x, pos.y}); } return false; } simd::float4x4 const &matrix() const override { return _matrix; } void set_matrix(simd::float4x4 &&matrix) override { _matrix = std::move(matrix); } private: simd::float4x4 _matrix = matrix_identity_float4x4; }; ui::collider::collider() : base(std::make_shared<impl>(nullptr)) { } ui::collider::collider(ui::shape shape) : base(std::make_shared<impl>(std::move(shape))) { } ui::collider::collider(std::nullptr_t) : base(nullptr) { } ui::collider::~collider() = default; void ui::collider::set_shape(ui::shape shape) { impl_ptr<impl>()->_shape_property.set_value(std::move(shape)); } ui::shape const &ui::collider::shape() const { return impl_ptr<impl>()->_shape_property.value(); } void ui::collider::set_enabled(bool const enabled) { impl_ptr<impl>()->_enabled_property.set_value(enabled); } bool ui::collider::is_enabled() const { return impl_ptr<impl>()->_enabled_property.value(); } bool ui::collider::hit_test(ui::point const &pos) const { return impl_ptr<impl>()->hit_test(pos); } ui::collider::subject_t &ui::collider::subject() { return impl_ptr<impl>()->_subject; } void ui::collider::dispatch_method(ui::collider::method const method) { impl_ptr<impl>()->dispatch_method(method); } ui::renderable_collider &ui::collider::renderable() { if (!_renderable) { _renderable = ui::renderable_collider{impl_ptr<ui::renderable_collider::impl>()}; } return _renderable; } <commit_msg>update collider<commit_after>// // yas_ui_collider.cpp // #include "yas_observing.h" #include "yas_property.h" #include "yas_to_bool.h" #include "yas_ui_collider.h" using namespace yas; #pragma mark - shape bool ui::anywhere_shape::hit_test(ui::point const &) const { return true; } bool ui::circle_shape::hit_test(ui::point const &pos) const { return std::powf(pos.x - center.x, 2.0f) + std::powf(pos.y - center.y, 2.0f) < std::powf(radius, 2.0f); } bool ui::rect_shape::hit_test(ui::point const &pos) const { return contains(rect, pos); } struct ui::shape::impl_base : base::impl { virtual std::type_info const &type() const = 0; virtual bool hit_test(ui::point const &) = 0; }; template <typename T> struct ui::shape::impl : impl_base { typename T::type _value; impl(typename T::type &&value) : _value(std::move(value)) { } std::type_info const &type() const override { return typeid(T); } bool hit_test(ui::point const &pos) override { return _value.hit_test(pos); } }; ui::shape::shape(anywhere::type shape) : base(std::make_shared<impl<anywhere>>(std::move(shape))) { } ui::shape::shape(circle::type shape) : base(std::make_shared<impl<circle>>(std::move(shape))) { } ui::shape::shape(rect::type shape) : base(std::make_shared<impl<rect>>(std::move(shape))) { } ui::shape::shape(std::nullptr_t) : base(nullptr) { } ui::shape::~shape() = default; std::type_info const &ui::shape::type_info() const { return impl_ptr<impl_base>()->type(); } bool ui::shape::hit_test(ui::point const &pos) const { return impl_ptr<impl_base>()->hit_test(pos); } template <typename T> typename T::type const &ui::shape::get() const { if (auto ip = std::dynamic_pointer_cast<impl<T>>(impl_ptr())) { return ip->_value; } static const typename T::type _default{}; return _default; } template ui::anywhere_shape const &ui::shape::get<ui::shape::anywhere>() const; template ui::circle_shape const &ui::shape::get<ui::shape::circle>() const; template ui::rect_shape const &ui::shape::get<ui::shape::rect>() const; #pragma mark - collider struct ui::collider::impl : base::impl, renderable_collider::impl { property<ui::shape> _shape_property{{.value = nullptr}}; property<bool> _enabled_property{{.value = true}}; subject_t _subject; impl(ui::shape &&shape) : _shape_property({.value = std::move(shape)}) { _property_observers.reserve(2); } void dispatch_method(ui::collider::method const method) { if (_property_observers.count(method)) { return; } auto weak_collider = to_weak(cast<ui::collider>()); base observer = nullptr; switch (method) { case ui::collider::method::shape_changed: observer = _shape_property.subject().make_observer( property_method::did_change, [weak_collider](auto const &context) { if (auto collider = weak_collider.lock()) { collider.subject().notify(ui::collider::method::shape_changed, collider); } }); break; case ui::collider::method::enabled_changed: observer = _enabled_property.subject().make_observer( property_method::did_change, [weak_collider](auto const &context) { if (auto collider = weak_collider.lock()) { collider.subject().notify(ui::collider::method::enabled_changed, collider); } }); break; } _property_observers.emplace(std::make_pair(method, std::move(observer))); } bool hit_test(ui::point const &loc) { auto const &shape = _shape_property.value(); if (shape && _enabled_property.value()) { auto pos = simd::float4x4(matrix_invert(_matrix)) * to_float4(loc.v); return shape.hit_test({pos.x, pos.y}); } return false; } simd::float4x4 const &matrix() const override { return _matrix; } void set_matrix(simd::float4x4 &&matrix) override { _matrix = std::move(matrix); } private: simd::float4x4 _matrix = matrix_identity_float4x4; std::unordered_map<ui::collider::method, base> _property_observers; }; ui::collider::collider() : base(std::make_shared<impl>(nullptr)) { } ui::collider::collider(ui::shape shape) : base(std::make_shared<impl>(std::move(shape))) { } ui::collider::collider(std::nullptr_t) : base(nullptr) { } ui::collider::~collider() = default; void ui::collider::set_shape(ui::shape shape) { impl_ptr<impl>()->_shape_property.set_value(std::move(shape)); } ui::shape const &ui::collider::shape() const { return impl_ptr<impl>()->_shape_property.value(); } void ui::collider::set_enabled(bool const enabled) { impl_ptr<impl>()->_enabled_property.set_value(enabled); } bool ui::collider::is_enabled() const { return impl_ptr<impl>()->_enabled_property.value(); } bool ui::collider::hit_test(ui::point const &pos) const { return impl_ptr<impl>()->hit_test(pos); } ui::collider::subject_t &ui::collider::subject() { return impl_ptr<impl>()->_subject; } void ui::collider::dispatch_method(ui::collider::method const method) { impl_ptr<impl>()->dispatch_method(method); } ui::renderable_collider &ui::collider::renderable() { if (!_renderable) { _renderable = ui::renderable_collider{impl_ptr<ui::renderable_collider::impl>()}; } return _renderable; } <|endoftext|>
<commit_before>/** * \file * \brief staticThreadBlinker example application * * \author Copyright (C) 2016 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/. */ #include "distortos/distortosConfiguration.h" #if defined(CONFIG_BOARD_LEDS_ENABLE) && CONFIG_BOARD_TOTAL_LEDS >= 1 #include "distortos/board/leds.hpp" #include "distortos/chip/ChipOutputPin.hpp" #endif // defined(CONFIG_BOARD_LEDS_ENABLE) && CONFIG_BOARD_TOTAL_LEDS >= 1 #include "distortos/StaticThread.hpp" #include "distortos/ThisThread.hpp" namespace { #if defined(CONFIG_BOARD_LEDS_ENABLE) && CONFIG_BOARD_TOTAL_LEDS >= 1 /** * \brief LED blinking function * * Constantly toggles state of \a led and waits for half of \a periodMs. * * \param [in] led is a reference to distortos::devices::OutputPin object which will be toggled by this function * \param [in] periodMs is a full (on -> off -> on) period of toggling, milliseconds */ void ledBlinkerFunction(distortos::devices::OutputPin& led, const std::chrono::milliseconds periodMs) { while (1) { led.set(!led.get()); // invert state of LED distortos::ThisThread::sleepFor(periodMs / 2); } } #endif // defined(CONFIG_BOARD_LEDS_ENABLE) && CONFIG_BOARD_TOTAL_LEDS >= 1 /** * \brief Boolean variable "blinking" function * * Constantly toggles value of \a variable and waits for half of \a periodMs. This function is meant as a demonstration * for configuration which either has no LEDs or doesn't enable them. * * \param [in] variable is a reference to bool variable which will be toggled by this function * \param [in] periodMs is a full (true -> false -> true) period of toggling, milliseconds */ void variableBlinkerFunction(bool& variable, const std::chrono::milliseconds periodMs) { while (1) { variable = !variable; // invert state of variable distortos::ThisThread::sleepFor(periodMs / 2); } } } // namespace /*---------------------------------------------------------------------------------------------------------------------+ | global functions +---------------------------------------------------------------------------------------------------------------------*/ /** * \brief Main code block of staticThreadBlinker application * * This example application tries to demonstrate the most basic aspects of static threads: * - creating and starting them, * - passing arguments to thread's function by reference and by value, * - joining them. * * If the configured board has no LEDs or if they are not enabled in the configuration, only one dummy thread is * created - it "blinks" a boolean variable instead of a real LED. Otherwise up to four additional threads are created * (but no more than the number of LEDs on the board - CONFIG_BOARD_TOTAL_LEDS) - each one blinks its own LED (which was * passed to the thread's function by reference) with provided period (passed by value). The periods of blinking are * slightly different for each thread, so if there are multiple LEDs they are not in sync with each other. The periods * are actually prime numbers, so they create very long "global" period (in which the whole pattern repeats). * * Even though all created threads never terminate (their functions have infinite loops and never return), main thread * calls Thread::join() for each of them anyway. This is a good and safe practice, which also happens to be the easiest * way to suspend main thread in this example application. * * \return doesn't return */ int main() { bool variable {}; // create and immediately start static thread with 1024 bytes of stack, low priority (1), variableBlinkerFunction() // will get variable by reference and period by value auto variableBlinkerThread = distortos::makeAndStartStaticThread<1024>(1, variableBlinkerFunction, std::ref(variable), std::chrono::milliseconds{401}); #if defined(CONFIG_BOARD_LEDS_ENABLE) && CONFIG_BOARD_TOTAL_LEDS >= 1 // create and immediately start static thread with 1024 bytes of stack, low priority (1), ledBlinkerFunction() will // get its own LED by reference and period by value auto ledBlinkerThread0 = distortos::makeAndStartStaticThread<1024>(1, ledBlinkerFunction, std::ref(distortos::board::leds[0]), std::chrono::milliseconds{397}); # if CONFIG_BOARD_TOTAL_LEDS >= 2 auto ledBlinkerThread1 = distortos::makeAndStartStaticThread<1024>(1, ledBlinkerFunction, std::ref(distortos::board::leds[1]), std::chrono::milliseconds{389}); # if CONFIG_BOARD_TOTAL_LEDS >= 3 auto ledBlinkerThread2 = distortos::makeAndStartStaticThread<1024>(1, ledBlinkerFunction, std::ref(distortos::board::leds[2]), std::chrono::milliseconds{383}); # if CONFIG_BOARD_TOTAL_LEDS >= 4 auto ledBlinkerThread3 = distortos::makeAndStartStaticThread<1024>(1, ledBlinkerFunction, std::ref(distortos::board::leds[3]), std::chrono::milliseconds{379}); ledBlinkerThread3.join(); # endif // CONFIG_BOARD_TOTAL_LEDS >= 4 ledBlinkerThread2.join(); # endif // CONFIG_BOARD_TOTAL_LEDS >= 3 ledBlinkerThread1.join(); # endif // CONFIG_BOARD_TOTAL_LEDS >= 2 ledBlinkerThread0.join(); #endif // defined(CONFIG_BOARD_LEDS_ENABLE) && CONFIG_BOARD_TOTAL_LEDS >= 1 variableBlinkerThread.join(); return 0; } <commit_msg>Add "local functions" header in staticThreadBlinker.cpp<commit_after>/** * \file * \brief staticThreadBlinker example application * * \author Copyright (C) 2016 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/. */ #include "distortos/distortosConfiguration.h" #if defined(CONFIG_BOARD_LEDS_ENABLE) && CONFIG_BOARD_TOTAL_LEDS >= 1 #include "distortos/board/leds.hpp" #include "distortos/chip/ChipOutputPin.hpp" #endif // defined(CONFIG_BOARD_LEDS_ENABLE) && CONFIG_BOARD_TOTAL_LEDS >= 1 #include "distortos/StaticThread.hpp" #include "distortos/ThisThread.hpp" namespace { /*---------------------------------------------------------------------------------------------------------------------+ | local functions +---------------------------------------------------------------------------------------------------------------------*/ #if defined(CONFIG_BOARD_LEDS_ENABLE) && CONFIG_BOARD_TOTAL_LEDS >= 1 /** * \brief LED blinking function * * Constantly toggles state of \a led and waits for half of \a periodMs. * * \param [in] led is a reference to distortos::devices::OutputPin object which will be toggled by this function * \param [in] periodMs is a full (on -> off -> on) period of toggling, milliseconds */ void ledBlinkerFunction(distortos::devices::OutputPin& led, const std::chrono::milliseconds periodMs) { while (1) { led.set(!led.get()); // invert state of LED distortos::ThisThread::sleepFor(periodMs / 2); } } #endif // defined(CONFIG_BOARD_LEDS_ENABLE) && CONFIG_BOARD_TOTAL_LEDS >= 1 /** * \brief Boolean variable "blinking" function * * Constantly toggles value of \a variable and waits for half of \a periodMs. This function is meant as a demonstration * for configuration which either has no LEDs or doesn't enable them. * * \param [in] variable is a reference to bool variable which will be toggled by this function * \param [in] periodMs is a full (true -> false -> true) period of toggling, milliseconds */ void variableBlinkerFunction(bool& variable, const std::chrono::milliseconds periodMs) { while (1) { variable = !variable; // invert state of variable distortos::ThisThread::sleepFor(periodMs / 2); } } } // namespace /*---------------------------------------------------------------------------------------------------------------------+ | global functions +---------------------------------------------------------------------------------------------------------------------*/ /** * \brief Main code block of staticThreadBlinker application * * This example application tries to demonstrate the most basic aspects of static threads: * - creating and starting them, * - passing arguments to thread's function by reference and by value, * - joining them. * * If the configured board has no LEDs or if they are not enabled in the configuration, only one dummy thread is * created - it "blinks" a boolean variable instead of a real LED. Otherwise up to four additional threads are created * (but no more than the number of LEDs on the board - CONFIG_BOARD_TOTAL_LEDS) - each one blinks its own LED (which was * passed to the thread's function by reference) with provided period (passed by value). The periods of blinking are * slightly different for each thread, so if there are multiple LEDs they are not in sync with each other. The periods * are actually prime numbers, so they create very long "global" period (in which the whole pattern repeats). * * Even though all created threads never terminate (their functions have infinite loops and never return), main thread * calls Thread::join() for each of them anyway. This is a good and safe practice, which also happens to be the easiest * way to suspend main thread in this example application. * * \return doesn't return */ int main() { bool variable {}; // create and immediately start static thread with 1024 bytes of stack, low priority (1), variableBlinkerFunction() // will get variable by reference and period by value auto variableBlinkerThread = distortos::makeAndStartStaticThread<1024>(1, variableBlinkerFunction, std::ref(variable), std::chrono::milliseconds{401}); #if defined(CONFIG_BOARD_LEDS_ENABLE) && CONFIG_BOARD_TOTAL_LEDS >= 1 // create and immediately start static thread with 1024 bytes of stack, low priority (1), ledBlinkerFunction() will // get its own LED by reference and period by value auto ledBlinkerThread0 = distortos::makeAndStartStaticThread<1024>(1, ledBlinkerFunction, std::ref(distortos::board::leds[0]), std::chrono::milliseconds{397}); # if CONFIG_BOARD_TOTAL_LEDS >= 2 auto ledBlinkerThread1 = distortos::makeAndStartStaticThread<1024>(1, ledBlinkerFunction, std::ref(distortos::board::leds[1]), std::chrono::milliseconds{389}); # if CONFIG_BOARD_TOTAL_LEDS >= 3 auto ledBlinkerThread2 = distortos::makeAndStartStaticThread<1024>(1, ledBlinkerFunction, std::ref(distortos::board::leds[2]), std::chrono::milliseconds{383}); # if CONFIG_BOARD_TOTAL_LEDS >= 4 auto ledBlinkerThread3 = distortos::makeAndStartStaticThread<1024>(1, ledBlinkerFunction, std::ref(distortos::board::leds[3]), std::chrono::milliseconds{379}); ledBlinkerThread3.join(); # endif // CONFIG_BOARD_TOTAL_LEDS >= 4 ledBlinkerThread2.join(); # endif // CONFIG_BOARD_TOTAL_LEDS >= 3 ledBlinkerThread1.join(); # endif // CONFIG_BOARD_TOTAL_LEDS >= 2 ledBlinkerThread0.join(); #endif // defined(CONFIG_BOARD_LEDS_ENABLE) && CONFIG_BOARD_TOTAL_LEDS >= 1 variableBlinkerThread.join(); return 0; } <|endoftext|>
<commit_before>// This file is part of the "x0" project // (c) 2009-2014 Christian Parpart <[email protected]> // // Licensed under the MIT License (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of // the License at: http://opensource.org/licenses/MIT /** * HTTP Server example for serving local static files. * * Highlights: * * This code has builtin support for: * <ul> * <li> GET and HEAD requests </li> * <li> client cache aware response handling </li> * <li> Range requests </li> * </ul> * */ #include <xzero/HttpRequest.h> #include <xzero/HttpServer.h> #include <sys/stat.h> #include <stdio.h> #include <ev++.h> int main() { xzero::HttpServer httpServer(ev::default_loop(0)); httpServer.setupListener("0.0.0.0", 3000); char cwd[1024]; if (!getcwd(cwd, sizeof(cwd))) { cwd[0] = '.'; cwd[1] = '\0'; } printf("Serving HTTP from 0.0.0.0:3000 ...\n"); httpServer.requestHandler = [&](xzero::HttpRequest* r) { r->documentRoot = cwd; r->fileinfo = r->connection.worker().fileinfo(r->documentRoot + r->path); if (r->fileinfo) { r->sendfile(r->fileinfo); } else { r->status = xzero::HttpStatus::NotFound; } r->finish(); }; return httpServer.run(); } <commit_msg>libxzero: improves staticfile example code quality<commit_after>// This file is part of the "x0" project // (c) 2009-2014 Christian Parpart <[email protected]> // // Licensed under the MIT License (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of // the License at: http://opensource.org/licenses/MIT /** * HTTP Server example for serving local static files. * * Highlights: * * This code has builtin support for: * <ul> * <li> GET and HEAD requests </li> * <li> client cache aware response handling </li> * <li> Range requests </li> * </ul> * */ #include <xzero/HttpRequest.h> #include <xzero/HttpServer.h> #include <sys/stat.h> #include <stdio.h> #include <ev++.h> int main() { xzero::HttpServer httpServer(ev::default_loop(0)); httpServer.setupListener("0.0.0.0", 3000); char cwd[1024]; if (!getcwd(cwd, sizeof(cwd))) { cwd[0] = '.'; cwd[1] = '\0'; } printf("Serving HTTP from 0.0.0.0:3000 ...\n"); httpServer.requestHandler = [&](xzero::HttpRequest* r) { r->documentRoot = cwd; r->fileinfo = r->connection.worker().fileinfo(r->documentRoot + r->path); r->sendfile(r->fileinfo); r->finish(); }; return httpServer.run(); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: geometrycontrolmodel_impl.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-09 12:49:20 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // no include protection. This is included from within geometrycontrolmodel.hxx only //==================================================================== //= OGeometryControlModel //==================================================================== //-------------------------------------------------------------------- template <class CONTROLMODEL> OGeometryControlModel<CONTROLMODEL>::OGeometryControlModel() :OGeometryControlModel_Base(new CONTROLMODEL) { } //-------------------------------------------------------------------- template <class CONTROLMODEL> OGeometryControlModel<CONTROLMODEL>::OGeometryControlModel(::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable >& _rxAggregateInstance) :OGeometryControlModel_Base(_rxAggregateInstance) { } //-------------------------------------------------------------------- template <class CONTROLMODEL> ::cppu::IPropertyArrayHelper& SAL_CALL OGeometryControlModel<CONTROLMODEL>::getInfoHelper() { return *this->getArrayHelper(); } //-------------------------------------------------------------------- template <class CONTROLMODEL> void OGeometryControlModel<CONTROLMODEL>::fillProperties(::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& _rProps, ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& _rAggregateProps) const { // our own properties OPropertyContainer::describeProperties(_rProps); // the aggregate properties if (m_xAggregateSet.is()) _rAggregateProps = m_xAggregateSet->getPropertySetInfo()->getProperties(); } //-------------------------------------------------------------------- template <class CONTROLMODEL> ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL OGeometryControlModel<CONTROLMODEL>::getImplementationId( ) throw (::com::sun::star::uno::RuntimeException) { static ::cppu::OImplementationId * pId = NULL; if ( !pId ) { ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if ( !pId ) { static ::cppu::OImplementationId s_aId; pId = &s_aId; } } return pId->getImplementationId(); } //-------------------------------------------------------------------- template <class CONTROLMODEL> OGeometryControlModel_Base* OGeometryControlModel<CONTROLMODEL>::createClone_Impl( ::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable >& _rxAggregateInstance) { return new OGeometryControlModel<CONTROLMODEL>(_rxAggregateInstance); } /************************************************************************* * history: * $Log: not supported by cvs2svn $ * Revision 1.4.122.1 2005/09/05 16:57:39 rt * #i54170# Change license header: remove SISSL * * Revision 1.4 2004/07/30 15:33:34 kz * INTEGRATION: CWS gcc340fixes01 (1.3.268); FILE MERGED * 2004/07/13 16:56:04 hr 1.3.268.1: #i31439#: fix template resolution * * Revision 1.3.268.1 2004/07/13 16:56:04 hr * #i31439#: fix template resolution * * Revision 1.3 2001/09/05 06:40:48 fs * #88891# override the XTypeProvider methods * * Revision 1.2 2001/03/02 12:34:13 tbe * clone geometry control model * * Revision 1.1 2001/01/24 14:57:30 mt * model for dialog controls (weith pos/size) * * * Revision 1.0 17.01.01 12:50:24 fs ************************************************************************/ <commit_msg>INTEGRATION: CWS rt15 (1.5.104); FILE MERGED 2006/06/27 09:19:40 rt 1.5.104.1: #i54459# CVS history removed from file.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: geometrycontrolmodel_impl.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2006-07-25 09:19:49 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // no include protection. This is included from within geometrycontrolmodel.hxx only //==================================================================== //= OGeometryControlModel //==================================================================== //-------------------------------------------------------------------- template <class CONTROLMODEL> OGeometryControlModel<CONTROLMODEL>::OGeometryControlModel() :OGeometryControlModel_Base(new CONTROLMODEL) { } //-------------------------------------------------------------------- template <class CONTROLMODEL> OGeometryControlModel<CONTROLMODEL>::OGeometryControlModel(::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable >& _rxAggregateInstance) :OGeometryControlModel_Base(_rxAggregateInstance) { } //-------------------------------------------------------------------- template <class CONTROLMODEL> ::cppu::IPropertyArrayHelper& SAL_CALL OGeometryControlModel<CONTROLMODEL>::getInfoHelper() { return *this->getArrayHelper(); } //-------------------------------------------------------------------- template <class CONTROLMODEL> void OGeometryControlModel<CONTROLMODEL>::fillProperties(::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& _rProps, ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& _rAggregateProps) const { // our own properties OPropertyContainer::describeProperties(_rProps); // the aggregate properties if (m_xAggregateSet.is()) _rAggregateProps = m_xAggregateSet->getPropertySetInfo()->getProperties(); } //-------------------------------------------------------------------- template <class CONTROLMODEL> ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL OGeometryControlModel<CONTROLMODEL>::getImplementationId( ) throw (::com::sun::star::uno::RuntimeException) { static ::cppu::OImplementationId * pId = NULL; if ( !pId ) { ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if ( !pId ) { static ::cppu::OImplementationId s_aId; pId = &s_aId; } } return pId->getImplementationId(); } //-------------------------------------------------------------------- template <class CONTROLMODEL> OGeometryControlModel_Base* OGeometryControlModel<CONTROLMODEL>::createClone_Impl( ::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable >& _rxAggregateInstance) { return new OGeometryControlModel<CONTROLMODEL>(_rxAggregateInstance); } <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include <string.h> #include "../../src/buffer_t.h" // TODO: use custom version to test use of user-created OpenGL context. extern "C" int halide_opengl_create_context(); class Image { public: enum Layout { Interleaved, Planar }; buffer_t buf; Image(int w, int h, int c, int elem_size, Layout layout = Interleaved) { memset(&buf, 0, sizeof(buffer_t)); buf.extent[0] = w; buf.extent[1] = h; buf.extent[2] = c; buf.elem_size = elem_size; if (layout == Interleaved) { buf.stride[0] = buf.extent[2]; buf.stride[1] = buf.extent[0] * buf.stride[0]; buf.stride[2] = 1; } else { buf.stride[0] = 1; buf.stride[1] = buf.extent[0] * buf.stride[0]; buf.stride[2] = buf.extent[1] * buf.stride[1]; } size_t size = w * h * c * elem_size; buf.host = (uint8_t*)malloc(size); memset(buf.host, 0, size); buf.host_dirty = true; } ~Image() { free(buf.host); } }; #include "blur.h" #include "ycc.h" void test_blur() { const int W = 12, H = 32, C = 3; Image input(W, H, C, sizeof(uint8_t), Image::Planar); Image output(W, H, C, sizeof(uint8_t), Image::Planar); fprintf(stderr, "test_blur\n"); blur_filter(&input.buf, &output.buf); fprintf(stderr, "test_blur complete\n"); } void test_ycc() { const int W = 12, H = 32, C = 3; Image input(W, H, C, sizeof(uint8_t), Image::Planar); Image output(W, H, C, sizeof(uint8_t), Image::Planar); fprintf(stderr, "test_ycc\n"); ycc_filter(&input.buf, &output.buf); fprintf(stderr, "Ycc complete\n"); } int main(int argc, char* argv[]) { if (halide_opengl_create_context() != 0) { fprintf(stderr, "Could not create OpenGL context\n"); exit(1); } test_blur(); test_ycc(); } <commit_msg>Fix apps/glsl. Include HalideRuntime.h instead of removed buffer_t.h<commit_after>#include <stdio.h> #include <stdlib.h> #include <string.h> #include "HalideRuntime.h" // TODO: use custom version to test use of user-created OpenGL context. extern "C" int halide_opengl_create_context(); class Image { public: enum Layout { Interleaved, Planar }; buffer_t buf; Image(int w, int h, int c, int elem_size, Layout layout = Interleaved) { memset(&buf, 0, sizeof(buffer_t)); buf.extent[0] = w; buf.extent[1] = h; buf.extent[2] = c; buf.elem_size = elem_size; if (layout == Interleaved) { buf.stride[0] = buf.extent[2]; buf.stride[1] = buf.extent[0] * buf.stride[0]; buf.stride[2] = 1; } else { buf.stride[0] = 1; buf.stride[1] = buf.extent[0] * buf.stride[0]; buf.stride[2] = buf.extent[1] * buf.stride[1]; } size_t size = w * h * c * elem_size; buf.host = (uint8_t*)malloc(size); memset(buf.host, 0, size); buf.host_dirty = true; } ~Image() { free(buf.host); } }; #include "blur.h" #include "ycc.h" void test_blur() { const int W = 12, H = 32, C = 3; Image input(W, H, C, sizeof(uint8_t), Image::Planar); Image output(W, H, C, sizeof(uint8_t), Image::Planar); fprintf(stderr, "test_blur\n"); blur_filter(&input.buf, &output.buf); fprintf(stderr, "test_blur complete\n"); } void test_ycc() { const int W = 12, H = 32, C = 3; Image input(W, H, C, sizeof(uint8_t), Image::Planar); Image output(W, H, C, sizeof(uint8_t), Image::Planar); fprintf(stderr, "test_ycc\n"); ycc_filter(&input.buf, &output.buf); fprintf(stderr, "Ycc complete\n"); } int main(int argc, char* argv[]) { if (halide_opengl_create_context() != 0) { fprintf(stderr, "Could not create OpenGL context\n"); exit(1); } test_blur(); test_ycc(); } <|endoftext|>
<commit_before>#include "Halide.h" using namespace Halide; Var x("x"), y("y"), c("c"); int main(int argc, char **argv) { // First define the function that gives the initial state. { Func initial; // The state is just a counter initial() = 0; initial.compile_to_file("julia_init"); } // Then the function that updates the state. Also depends on user input. { ImageParam state(Int(32), 0); Param<int> mouse_x, mouse_y; Func new_state; // Increment the counter new_state() = state() + 1; new_state.compile_to_file("julia_update", state, mouse_x, mouse_y); } // Now the function that converts the state into an argb image. { ImageParam state(Int(32), 0); Expr c_real = cos(state() / 30.0f); Expr c_imag = sin(state() / 30.0f); Expr r_adjust = (cos(state() / 43.0f) + 2.0f) * 0.25f; c_real *= r_adjust; c_imag *= r_adjust; Func julia; julia(x, y, c) = Tuple((x - 511.5f)/350.0f, (y - 511.5f)/350.0f); const int iters = 20; RDom t(1, iters); Expr old_real = julia(x, y, t-1)[0]; Expr old_imag = julia(x, y, t-1)[1]; Expr new_real = old_real * old_real - old_imag * old_imag + c_real; Expr new_imag = 2 * old_real * old_imag + c_imag; Expr mag = new_real * new_real + new_imag * new_imag; new_real = select(mag > 1e20f, old_real, new_real); new_imag = select(mag > 1e20f, old_imag, new_imag); julia(x, y, t) = Tuple(new_real, new_imag); // What's the closest to the origin a point gets in 20 iterations? new_real = julia(x, y, t)[0]; new_imag = julia(x, y, t)[1]; mag = new_real * new_real + new_imag * new_imag; Expr escape = minimum(mag); // Now pick a color based on that Expr r_f = 16 * sqrt(2.0f/(escape + 0.01f)); Expr b_f = 512 * escape * fast_exp(-escape*escape); Expr g_f = (r_f + b_f)/2; Expr min_c = min(r_f, min(b_f, g_f)); r_f -= min_c; b_f -= min_c; g_f -= min_c; Expr r = cast<int32_t>(min(r_f, 255)); Expr g = cast<int32_t>(min(g_f, 255)); Expr b = cast<int32_t>(min(b_f, 255)); Expr color = (255 << 24) | (r << 16) | (g << 8) | b; Func render; render(x, y) = color; Var yi; // The julia set has rotational symmetry, so we just render // the top half and then flip it for the bottom half. Func final; Expr y_up = min(y, 511); Expr y_down = max(y, 512); final(x, y) = select(y < 512, render(x, y_up), render(1023 - x, 1023 - y_down)); Var yo; final.bound(x, 0, 1024).bound(y, 0, 1024); final.split(y, y, yi, 4).parallel(y); render.compute_root(); render.bound(x, 0, 1024).bound(y, 0, 512); render.split(y, y, yi, 4).parallel(y); julia.compute_at(render, x); render.vectorize(x, 4); julia.update().vectorize(x, 4); final.vectorize(x, 4); final.compile_to_file("julia_render", state); } return 0; } <commit_msg>Julia demo looks cooler still<commit_after>#include "Halide.h" using namespace Halide; Var x("x"), y("y"), c("c"); int main(int argc, char **argv) { // First define the function that gives the initial state. { Func initial; // The state is just a counter initial() = 0; initial.compile_to_file("julia_init"); } // Then the function that updates the state. Also depends on user input. { ImageParam state(Int(32), 0); Param<int> mouse_x, mouse_y; Func new_state; // Increment the counter new_state() = state() + 1; new_state.compile_to_file("julia_update", state, mouse_x, mouse_y); } // Now the function that converts the state into an argb image. { ImageParam state(Int(32), 0); Expr c_real = cos(state() / 60.0f); Expr c_imag = sin(state() / 43.0f); Expr r_adjust = (cos(state() / 86.0f) + 2.0f) * 0.25f; c_real *= r_adjust; c_imag *= r_adjust; Func julia; julia(x, y, c) = Tuple((x - 511.5f)/350.0f, (y - 511.5f)/350.0f); const int iters = 20; RDom t(1, iters); Expr old_real = julia(x, y, t-1)[0]; Expr old_imag = julia(x, y, t-1)[1]; Expr new_real = old_real * old_real - old_imag * old_imag + c_real; Expr new_imag = 2 * old_real * old_imag + c_imag; Expr mag = new_real * new_real + new_imag * new_imag; new_real = select(mag > 1e20f, old_real, new_real); new_imag = select(mag > 1e20f, old_imag, new_imag); julia(x, y, t) = Tuple(new_real, new_imag); // Define some arbitrary measure on the complex plane, and // compute the minimum of that measure over the orbit of each // point. new_real = julia(x, y, t)[0]; new_imag = julia(x, y, t)[1]; mag = new_real * c_real - new_imag * new_imag * c_imag; Expr measure = minimum(abs(mag - 0.1f)); // Now pick a color based on that Expr r_f = 16 * sqrt(2.0f/(measure + 0.01f)); Expr b_f = 512 * measure * fast_exp(-measure*measure); Expr g_f = (r_f + b_f)/2; Expr min_c = min(r_f, min(b_f, g_f)); r_f -= min_c; b_f -= min_c; g_f -= min_c; Expr r = cast<int32_t>(min(r_f, 255)); Expr g = cast<int32_t>(min(g_f, 255)); Expr b = cast<int32_t>(min(b_f, 255)); Expr color = (255 << 24) | (r << 16) | (g << 8) | b; Func render; render(x, y) = color; Var yi; // The julia set has rotational symmetry, so we just render // the top half and then flip it for the bottom half. Func final; Expr y_up = min(y, 511); Expr y_down = max(y, 512); final(x, y) = select(y < 512, render(x, y_up), render(1023 - x, 1023 - y_down)); Var yo; final.bound(x, 0, 1024).bound(y, 0, 1024); final.split(y, y, yi, 4).parallel(y); render.compute_root(); render.bound(x, 0, 1024).bound(y, 0, 512); render.split(y, y, yi, 4).parallel(y); julia.compute_at(render, x); render.vectorize(x, 4); julia.update().vectorize(x, 4); final.vectorize(x, 4); final.compile_to_file("julia_render", state); } return 0; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the QtDeclarative module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the either Technology Preview License Agreement or the ** Beta Release License Agreement. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qfximage.h" #include "qfximage_p.h" #include <QKeyEvent> #include <QPainter> QT_BEGIN_NAMESPACE QML_DEFINE_TYPE(Qt,4,6,(QT_VERSION&0x00ff00)>>8,Image,QFxImage) /*! \qmlclass Image QFxImage \brief The Image element allows you to add bitmaps to a scene. \inherits Item The Image element supports untransformed, stretched and tiled. For an explanation of stretching and tiling, see the fillMode property description. Examples: \table \row \o \image declarative-qtlogo1.png \o Untransformed \qml Image { source: "pics/qtlogo.png" } \endqml \row \o \image declarative-qtlogo2.png \o fillMode: Stretch (default) \qml Image { width: 160 height: 160 source: "pics/qtlogo.png" } \endqml \row \o \image declarative-qtlogo3.png \o fillMode: Tile \qml Image { fillMode: "Tile" width: 160; height: 160 source: "pics/qtlogo.png" } \endqml \row \o \image declarative-qtlogo6.png \o fillMode: TileVertically \qml Image { fillMode: "TileVertically" width: 160; height: 160 source: "pics/qtlogo.png" } \endqml \row \o \image declarative-qtlogo5.png \o fillMode: TileHorizontally \qml Image { fillMode: "TileHorizontally" width: 160; height: 160 source: "pics/qtlogo.png" } \endqml \endtable */ /*! \internal \class QFxImage Image \brief The QFxImage class provides an image item that you can add to a QFxView. \ingroup group_coreitems Example: \qml Image { source: "pics/star.png" } \endqml A QFxImage object can be instantiated in Qml using the tag \l Image. */ QFxImage::QFxImage(QFxItem *parent) : QFxImageBase(*(new QFxImagePrivate), parent) { setFlag(QGraphicsItem::ItemHasNoContents, false); } QFxImage::QFxImage(QFxImagePrivate &dd, QFxItem *parent) : QFxImageBase(dd, parent) { setFlag(QGraphicsItem::ItemHasNoContents, false); } QFxImage::~QFxImage() { } QPixmap QFxImage::pixmap() const { Q_D(const QFxImage); return d->pix; } void QFxImage::setPixmap(const QPixmap &pix) { Q_D(QFxImage); if (!d->url.isEmpty()) return; d->pix = pix; setImplicitWidth(d->pix.width()); setImplicitHeight(d->pix.height()); update(); } /*! \qmlproperty FillMode Image::fillMode Set this property to define what happens when the image set for the item is smaller than the size of the item. \list \o Stretch - the image is scaled to fit \o PreserveAspectFit - the image is scaled uniformly to fit without cropping \o PreserveAspectCrop - the image is scaled uniformly to fill, cropping if necessary \o Tile - the image is duplicated horizontally and vertically \o TileVertically - the image is stretched horizontally and tiled vertically \o TileHorizontally - the image is stretched vertically and tiled horizontally \endlist \image declarative-image_fillMode.gif \sa examples/declarative/fillmode \sa examples/declarative/aspectratio */ QFxImage::FillMode QFxImage::fillMode() const { Q_D(const QFxImage); return d->fillMode; } void QFxImage::setFillMode(FillMode mode) { Q_D(QFxImage); if (d->fillMode == mode) return; d->fillMode = mode; update(); emit fillModeChanged(); } /*! \qmlproperty enum Image::status This property holds the status of image loading. It can be one of: \list \o Null - no image has been set \o Ready - the image has been loaded \o Loading - the image is currently being loaded \o Error - an error occurred while loading the image \endlist \sa progress */ /*! \qmlproperty real Image::progress This property holds the progress of image loading, from 0.0 (nothing loaded) to 1.0 (finished). \sa status */ /*! \qmlproperty bool Image::smooth Set this property if you want the image to be smoothly filtered when scaled or transformed. Smooth filtering gives better visual quality, but is slower. If the image is displayed at its natural size, this property has no visual or performance effect. \note Generally scaling artifacts are only visible if the image is stationary on the screen. A common pattern when animating an image is to disable smooth filtering at the beginning of the animation and reenable it at the conclusion. */ /*! \qmlproperty url Image::source Image can handle any image format supported by Qt, loaded from any URL scheme supported by Qt. The URL may be absolute, or relative to the URL of the component. */ void QFxImage::paint(QPainter *p, const QStyleOptionGraphicsItem *, QWidget *) { Q_D(QFxImage); if (d->pix.isNull()) return; bool oldAA = p->testRenderHint(QPainter::Antialiasing); bool oldSmooth = p->testRenderHint(QPainter::SmoothPixmapTransform); if (d->smooth) p->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform, d->smooth); if (width() != d->pix.width() || height() != d->pix.height()) { if (d->fillMode >= Tile) { p->save(); p->setClipRect(0, 0, width(), height(), Qt::IntersectClip); if (d->fillMode == Tile) { const int pw = d->pix.width(); const int ph = d->pix.height(); int yy = 0; while(yy < height()) { int xx = 0; while(xx < width()) { p->drawPixmap(xx, yy, d->pix); xx += pw; } yy += ph; } } else if (d->fillMode == TileVertically) { const int ph = d->pix.height(); int yy = 0; while(yy < height()) { p->drawPixmap(QRect(0, yy, width(), ph), d->pix); yy += ph; } } else { const int pw = d->pix.width(); int xx = 0; while(xx < width()) { p->drawPixmap(QRect(xx, 0, pw, height()), d->pix); xx += pw; } } p->restore(); } else { qreal widthScale = width() / qreal(d->pix.width()); qreal heightScale = height() / qreal(d->pix.height()); QTransform scale; if (d->fillMode == PreserveAspectFit) { if (widthScale < heightScale) { heightScale = widthScale; scale.translate(0, (height() - heightScale * d->pix.height()) / 2); } else if(heightScale < widthScale) { widthScale = heightScale; scale.translate((width() - widthScale * d->pix.width()) / 2, 0); } } else if (d->fillMode == PreserveAspectCrop) { if (widthScale < heightScale) { widthScale = heightScale; scale.translate((width() - widthScale * d->pix.width()) / 2, 0); } else if(heightScale < widthScale) { heightScale = widthScale; scale.translate(0, (height() - heightScale * d->pix.height()) / 2); } } scale.scale(widthScale, heightScale); QTransform old = p->transform(); p->setWorldTransform(scale * old); p->drawPixmap(0, 0, d->pix); p->setWorldTransform(old); } } else { p->drawPixmap(0, 0, d->pix); } if (d->smooth) { p->setRenderHint(QPainter::Antialiasing, oldAA); p->setRenderHint(QPainter::SmoothPixmapTransform, oldSmooth); } } QT_END_NAMESPACE <commit_msg>Use drawTiledPixmap for tiling.<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the QtDeclarative module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the either Technology Preview License Agreement or the ** Beta Release License Agreement. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qfximage.h" #include "qfximage_p.h" #include <QKeyEvent> #include <QPainter> QT_BEGIN_NAMESPACE QML_DEFINE_TYPE(Qt,4,6,(QT_VERSION&0x00ff00)>>8,Image,QFxImage) /*! \qmlclass Image QFxImage \brief The Image element allows you to add bitmaps to a scene. \inherits Item The Image element supports untransformed, stretched and tiled. For an explanation of stretching and tiling, see the fillMode property description. Examples: \table \row \o \image declarative-qtlogo1.png \o Untransformed \qml Image { source: "pics/qtlogo.png" } \endqml \row \o \image declarative-qtlogo2.png \o fillMode: Stretch (default) \qml Image { width: 160 height: 160 source: "pics/qtlogo.png" } \endqml \row \o \image declarative-qtlogo3.png \o fillMode: Tile \qml Image { fillMode: "Tile" width: 160; height: 160 source: "pics/qtlogo.png" } \endqml \row \o \image declarative-qtlogo6.png \o fillMode: TileVertically \qml Image { fillMode: "TileVertically" width: 160; height: 160 source: "pics/qtlogo.png" } \endqml \row \o \image declarative-qtlogo5.png \o fillMode: TileHorizontally \qml Image { fillMode: "TileHorizontally" width: 160; height: 160 source: "pics/qtlogo.png" } \endqml \endtable */ /*! \internal \class QFxImage Image \brief The QFxImage class provides an image item that you can add to a QFxView. \ingroup group_coreitems Example: \qml Image { source: "pics/star.png" } \endqml A QFxImage object can be instantiated in Qml using the tag \l Image. */ QFxImage::QFxImage(QFxItem *parent) : QFxImageBase(*(new QFxImagePrivate), parent) { setFlag(QGraphicsItem::ItemHasNoContents, false); } QFxImage::QFxImage(QFxImagePrivate &dd, QFxItem *parent) : QFxImageBase(dd, parent) { setFlag(QGraphicsItem::ItemHasNoContents, false); } QFxImage::~QFxImage() { } QPixmap QFxImage::pixmap() const { Q_D(const QFxImage); return d->pix; } void QFxImage::setPixmap(const QPixmap &pix) { Q_D(QFxImage); if (!d->url.isEmpty()) return; d->pix = pix; setImplicitWidth(d->pix.width()); setImplicitHeight(d->pix.height()); update(); } /*! \qmlproperty FillMode Image::fillMode Set this property to define what happens when the image set for the item is smaller than the size of the item. \list \o Stretch - the image is scaled to fit \o PreserveAspectFit - the image is scaled uniformly to fit without cropping \o PreserveAspectCrop - the image is scaled uniformly to fill, cropping if necessary \o Tile - the image is duplicated horizontally and vertically \o TileVertically - the image is stretched horizontally and tiled vertically \o TileHorizontally - the image is stretched vertically and tiled horizontally \endlist \image declarative-image_fillMode.gif \sa examples/declarative/fillmode \sa examples/declarative/aspectratio */ QFxImage::FillMode QFxImage::fillMode() const { Q_D(const QFxImage); return d->fillMode; } void QFxImage::setFillMode(FillMode mode) { Q_D(QFxImage); if (d->fillMode == mode) return; d->fillMode = mode; update(); emit fillModeChanged(); } /*! \qmlproperty enum Image::status This property holds the status of image loading. It can be one of: \list \o Null - no image has been set \o Ready - the image has been loaded \o Loading - the image is currently being loaded \o Error - an error occurred while loading the image \endlist \sa progress */ /*! \qmlproperty real Image::progress This property holds the progress of image loading, from 0.0 (nothing loaded) to 1.0 (finished). \sa status */ /*! \qmlproperty bool Image::smooth Set this property if you want the image to be smoothly filtered when scaled or transformed. Smooth filtering gives better visual quality, but is slower. If the image is displayed at its natural size, this property has no visual or performance effect. \note Generally scaling artifacts are only visible if the image is stationary on the screen. A common pattern when animating an image is to disable smooth filtering at the beginning of the animation and reenable it at the conclusion. */ /*! \qmlproperty url Image::source Image can handle any image format supported by Qt, loaded from any URL scheme supported by Qt. The URL may be absolute, or relative to the URL of the component. */ void QFxImage::paint(QPainter *p, const QStyleOptionGraphicsItem *, QWidget *) { Q_D(QFxImage); if (d->pix.isNull()) return; bool oldAA = p->testRenderHint(QPainter::Antialiasing); bool oldSmooth = p->testRenderHint(QPainter::SmoothPixmapTransform); if (d->smooth) p->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform, d->smooth); if (width() != d->pix.width() || height() != d->pix.height()) { if (d->fillMode >= Tile) { p->save(); p->setClipRect(0, 0, width(), height(), Qt::IntersectClip); if (d->fillMode == Tile) p->drawTiledPixmap(QRectF(0,0,width(),height()), d->pix); else if (d->fillMode == TileVertically) p->drawTiledPixmap(QRectF(0,0,d->pix.width(),height()), d->pix); else p->drawTiledPixmap(QRectF(0,0,width(),d->pix.height()), d->pix); p->restore(); } else { qreal widthScale = width() / qreal(d->pix.width()); qreal heightScale = height() / qreal(d->pix.height()); QTransform scale; if (d->fillMode == PreserveAspectFit) { if (widthScale < heightScale) { heightScale = widthScale; scale.translate(0, (height() - heightScale * d->pix.height()) / 2); } else if(heightScale < widthScale) { widthScale = heightScale; scale.translate((width() - widthScale * d->pix.width()) / 2, 0); } } else if (d->fillMode == PreserveAspectCrop) { if (widthScale < heightScale) { widthScale = heightScale; scale.translate((width() - widthScale * d->pix.width()) / 2, 0); } else if(heightScale < widthScale) { heightScale = widthScale; scale.translate(0, (height() - heightScale * d->pix.height()) / 2); } } scale.scale(widthScale, heightScale); QTransform old = p->transform(); p->setWorldTransform(scale * old); p->drawPixmap(0, 0, d->pix); p->setWorldTransform(old); } } else { p->drawPixmap(0, 0, d->pix); } if (d->smooth) { p->setRenderHint(QPainter::Antialiasing, oldAA); p->setRenderHint(QPainter::SmoothPixmapTransform, oldSmooth); } } QT_END_NAMESPACE <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: idlc.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2006-04-19 13:45:23 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _IDLC_IDLC_HXX_ #define _IDLC_IDLC_HXX_ #ifndef _IDLC_IDLCTYPES_HXX_ #include <idlc/idlctypes.hxx> #endif #ifndef _IDLC_ASTSTACK_HXX_ #include <idlc/aststack.hxx> #endif #ifndef _IDLC_OPTIONS_HXX_ #include <idlc/options.hxx> #endif #ifdef SAL_UNX #define SEPARATOR '/' #define PATH_SEPARATOR "/" #else #define SEPARATOR '\\' #define PATH_SEPARATOR "\\" #endif class AstInterface; class AstModule; class AstType; class Options; class ErrorHandler; class Idlc { public: Idlc(Options* pOptions); virtual ~Idlc(); void init(); Options* getOptions() { return m_pOptions; } AstStack* scopes() { return m_pScopes; } AstModule* getRoot() { return m_pRoot; } ErrorHandler* error() { return m_pErrorHandler; } const ::rtl::OString& getFileName() { return m_fileName; } void setFileName(const ::rtl::OString& fileName) { m_fileName = fileName; } const ::rtl::OString& getMainFileName() { return m_mainFileName; } void setMainFileName(const ::rtl::OString& mainFileName) { m_mainFileName = mainFileName; } const ::rtl::OString& getRealFileName() { return m_realFileName; } void setRealFileName(const ::rtl::OString& realFileName) { m_realFileName = realFileName; } const ::rtl::OString& getDocumentation() { m_bIsDocValid = sal_False; return m_documentation; } void setDocumentation(const ::rtl::OString& documentation) { m_documentation = documentation; m_bIsDocValid = sal_True; } sal_Bool isDocValid(); sal_Bool isInMainFile() { return m_bIsInMainfile; } void setInMainfile(sal_Bool bInMainfile) { m_bIsInMainfile = bInMainfile; } sal_uInt32 getErrorCount() { return m_errorCount; } void setErrorCount(sal_uInt32 errorCount) { m_errorCount = errorCount; } void incErrorCount() { m_errorCount++; } sal_uInt32 getWarningCount() { return m_warningCount; } void setWarningCount(sal_uInt32 warningCount) { m_warningCount = warningCount; } void incWarningCount() { m_warningCount++; } sal_uInt32 getLineNumber() { return m_lineNumber; } void setLineNumber(sal_uInt32 lineNumber) { m_lineNumber = lineNumber; } void incLineNumber() { m_lineNumber++; } ParseState getParseState() { return m_parseState; } void setParseState(ParseState parseState) { m_parseState = parseState; } void insertInclude(const ::rtl::OString& inc) { m_includes.insert(inc); } StringSet* getIncludes() { return &m_includes; } void setPublished(bool published) { m_published = published; } bool isPublished() const { return m_published; } void reset(); private: Options* m_pOptions; AstStack* m_pScopes; AstModule* m_pRoot; ErrorHandler* m_pErrorHandler; ::rtl::OString m_fileName; ::rtl::OString m_mainFileName; ::rtl::OString m_realFileName; ::rtl::OString m_documentation; sal_Bool m_bIsDocValid; sal_Bool m_bGenerateDoc; sal_Bool m_bIsInMainfile; bool m_published; sal_uInt32 m_errorCount; sal_uInt32 m_warningCount; sal_uInt32 m_lineNumber; ParseState m_parseState; StringSet m_includes; }; sal_Int32 compileFile(const ::rtl::OString * pathname); // a null pathname means stdin sal_Int32 produceFile(const ::rtl::OString& filenameBase); // filenameBase is filename without ".idl" void removeIfExists(const ::rtl::OString& pathname); ::rtl::OString makeTempName(const ::rtl::OString& prefix, const ::rtl::OString& postfix); sal_Bool copyFile(const ::rtl::OString* source, const ::rtl::OString& target); // a null source means stdin sal_Bool isFileUrl(const ::rtl::OString& fileName); ::rtl::OString convertToAbsoluteSystemPath(const ::rtl::OString& fileName); ::rtl::OString convertToFileUrl(const ::rtl::OString& fileName); Idlc* SAL_CALL idlc(); Idlc* SAL_CALL setIdlc(Options* pOptions); AstDeclaration const * resolveTypedefs(AstDeclaration const * type); AstDeclaration const * deconstructAndResolveTypedefs( AstDeclaration const * type, sal_Int32 * rank); AstInterface const * resolveInterfaceTypedefs(AstType const * type); #endif // _IDLC_IDLC_HXX_ <commit_msg>INTEGRATION: CWS changefileheader (1.7.70); FILE MERGED 2008/04/01 12:31:27 thb 1.7.70.2: #i85898# Stripping all external header guards 2008/03/31 07:23:49 rt 1.7.70.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: idlc.hxx,v $ * $Revision: 1.8 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _IDLC_IDLC_HXX_ #define _IDLC_IDLC_HXX_ #include <idlc/idlctypes.hxx> #include <idlc/aststack.hxx> #include <idlc/options.hxx> #ifdef SAL_UNX #define SEPARATOR '/' #define PATH_SEPARATOR "/" #else #define SEPARATOR '\\' #define PATH_SEPARATOR "\\" #endif class AstInterface; class AstModule; class AstType; class Options; class ErrorHandler; class Idlc { public: Idlc(Options* pOptions); virtual ~Idlc(); void init(); Options* getOptions() { return m_pOptions; } AstStack* scopes() { return m_pScopes; } AstModule* getRoot() { return m_pRoot; } ErrorHandler* error() { return m_pErrorHandler; } const ::rtl::OString& getFileName() { return m_fileName; } void setFileName(const ::rtl::OString& fileName) { m_fileName = fileName; } const ::rtl::OString& getMainFileName() { return m_mainFileName; } void setMainFileName(const ::rtl::OString& mainFileName) { m_mainFileName = mainFileName; } const ::rtl::OString& getRealFileName() { return m_realFileName; } void setRealFileName(const ::rtl::OString& realFileName) { m_realFileName = realFileName; } const ::rtl::OString& getDocumentation() { m_bIsDocValid = sal_False; return m_documentation; } void setDocumentation(const ::rtl::OString& documentation) { m_documentation = documentation; m_bIsDocValid = sal_True; } sal_Bool isDocValid(); sal_Bool isInMainFile() { return m_bIsInMainfile; } void setInMainfile(sal_Bool bInMainfile) { m_bIsInMainfile = bInMainfile; } sal_uInt32 getErrorCount() { return m_errorCount; } void setErrorCount(sal_uInt32 errorCount) { m_errorCount = errorCount; } void incErrorCount() { m_errorCount++; } sal_uInt32 getWarningCount() { return m_warningCount; } void setWarningCount(sal_uInt32 warningCount) { m_warningCount = warningCount; } void incWarningCount() { m_warningCount++; } sal_uInt32 getLineNumber() { return m_lineNumber; } void setLineNumber(sal_uInt32 lineNumber) { m_lineNumber = lineNumber; } void incLineNumber() { m_lineNumber++; } ParseState getParseState() { return m_parseState; } void setParseState(ParseState parseState) { m_parseState = parseState; } void insertInclude(const ::rtl::OString& inc) { m_includes.insert(inc); } StringSet* getIncludes() { return &m_includes; } void setPublished(bool published) { m_published = published; } bool isPublished() const { return m_published; } void reset(); private: Options* m_pOptions; AstStack* m_pScopes; AstModule* m_pRoot; ErrorHandler* m_pErrorHandler; ::rtl::OString m_fileName; ::rtl::OString m_mainFileName; ::rtl::OString m_realFileName; ::rtl::OString m_documentation; sal_Bool m_bIsDocValid; sal_Bool m_bGenerateDoc; sal_Bool m_bIsInMainfile; bool m_published; sal_uInt32 m_errorCount; sal_uInt32 m_warningCount; sal_uInt32 m_lineNumber; ParseState m_parseState; StringSet m_includes; }; sal_Int32 compileFile(const ::rtl::OString * pathname); // a null pathname means stdin sal_Int32 produceFile(const ::rtl::OString& filenameBase); // filenameBase is filename without ".idl" void removeIfExists(const ::rtl::OString& pathname); ::rtl::OString makeTempName(const ::rtl::OString& prefix, const ::rtl::OString& postfix); sal_Bool copyFile(const ::rtl::OString* source, const ::rtl::OString& target); // a null source means stdin sal_Bool isFileUrl(const ::rtl::OString& fileName); ::rtl::OString convertToAbsoluteSystemPath(const ::rtl::OString& fileName); ::rtl::OString convertToFileUrl(const ::rtl::OString& fileName); Idlc* SAL_CALL idlc(); Idlc* SAL_CALL setIdlc(Options* pOptions); AstDeclaration const * resolveTypedefs(AstDeclaration const * type); AstDeclaration const * deconstructAndResolveTypedefs( AstDeclaration const * type, sal_Int32 * rank); AstInterface const * resolveInterfaceTypedefs(AstType const * type); #endif // _IDLC_IDLC_HXX_ <|endoftext|>
<commit_before>/*** Copyright (c), The Regents of the University of California *** *** For more information please refer to files in the COPYRIGHT directory ***/ /* packInstruct.h - header file for pack instruction definition */ #ifndef PACK_INSTRUCT_HPP #define PACK_INSTRUCT_HPP #define IRODS_STR_PI "str myStr[MAX_NAME_LEN];" #define STR_PI "str myStr;" #define CHAR_PI "char myChar;" #define STR_PTR_PI "str *myStr;" #define PI_STR_PI "piStr myStr[MAX_NAME_LEN];" #define INT_PI "int myInt;" #define INT16_PI "int16 myInt;" #define BUF_LEN_PI "int myInt;" #define DOUBLE_PI "double myDouble;" /* packInstruct for msgHeader_t */ #define MsgHeader_PI "str type[HEADER_TYPE_LEN]; int msgLen; int errorLen; int bsLen; int intInfo;" /* packInstruct for startupPack_t */ #define StartupPack_PI "int irodsProt; int reconnFlag; int connectCnt; str proxyUser[NAME_LEN]; str proxyRcatZone[NAME_LEN]; str clientUser[NAME_LEN]; str clientRcatZone[NAME_LEN]; str relVersion[NAME_LEN]; str apiVersion[NAME_LEN]; str option[NAME_LEN];" /* packInstruct for version_t */ #define Version_PI "int status; str relVersion[NAME_LEN]; str apiVersion[NAME_LEN]; int reconnPort; str reconnAddr[LONG_NAME_LEN]; int cookie;" /* packInstruct for rErrMsg_t */ #define RErrMsg_PI "int status; str msg[ERR_MSG_LEN];" /* packInstruct for rError_t */ #define RError_PI "int count; struct *RErrMsg_PI[count];" #define RHostAddr_PI "str hostAddr[LONG_NAME_LEN]; str rodsZone[NAME_LEN]; int port; int dummyInt;" #define RODS_STAT_T_PI "double st_size; int st_dev; int st_ino; int st_mode; int st_nlink; int st_uid; int st_gid; int st_rdev; int st_atim; int st_mtim; int st_ctim; int st_blksize; int st_blocks;" #define RODS_DIRENT_T_PI "int d_offset; int d_ino; int d_reclen; int d_namlen; str d_name[DIR_LEN];" #define KeyValPair_PI "int ssLen; str *keyWord[ssLen]; str *svalue[ssLen];" // =-=-=-=-=-=-=- // pack struct for client server negotiations #define CS_NEG_PI "int status; str result[MAX_NAME_LEN];" #define InxIvalPair_PI "int iiLen; int *inx(iiLen); int *ivalue(iiLen);" #define InxValPair_PI "int isLen; int *inx(isLen); str *svalue[isLen];" #define DataObjInp_PI "str objPath[MAX_NAME_LEN]; int createMode; int openFlags; double offset; double dataSize; int numThreads; int oprType; struct *SpecColl_PI; struct KeyValPair_PI;" #define OpenedDataObjInp_PI "int l1descInx; int len; int whence; int oprType; double offset; double bytesWritten; struct KeyValPair_PI;" #define PortList_PI "int portNum; int cookie; int sock; int windowSize; str hostAddr[LONG_NAME_LEN];" #define PortalOprOut_PI "int status; int l1descInx; int numThreads; str chksum[NAME_LEN]; struct PortList_PI;" #define DataOprInp_PI "int oprType; int numThreads; int srcL3descInx; int destL3descInx; int srcRescTypeInx; int destRescTypeInx; double offset; double dataSize; struct KeyValPair_PI;" #define CollInpNew_PI "str collName[MAX_NAME_LEN]; int flags; int oprType; struct KeyValPair_PI;" #define GenQueryInp_PI "int maxRows; int continueInx; int partialStartIndex; int options; struct KeyValPair_PI; struct InxIvalPair_PI; struct InxValPair_PI;" #define SqlResult_PI "int attriInx; int reslen; str *value(rowCnt)(reslen);" #define GenQueryOut_PI "int rowCnt; int attriCnt; int continueInx; int totalRowCount; struct SqlResult_PI[MAX_SQL_ATTR];" #define GenArraysInp_PI "int rowCnt; int attriCnt; int continueInx; int totalRowCount; struct KeyValPair_PI; struct SqlResult_PI[MAX_SQL_ATTR];" #define DataObjInfo_PI "str objPath[MAX_NAME_LEN]; str rescName[NAME_LEN]; str rescHier[MAX_NAME_LEN]; str dataType[NAME_LEN]; double dataSize; str chksum[NAME_LEN]; str version[NAME_LEN]; str filePath[MAX_NAME_LEN]; str dataOwnerName[NAME_LEN]; str dataOwnerZone[NAME_LEN]; int replNum; int replStatus; str statusString[NAME_LEN]; double dataId; double collId; int dataMapId; int flags; str dataComments[LONG_NAME_LEN]; str dataMode[SHORT_STR_LEN]; str dataExpiry[TIME_LEN]; str dataCreate[TIME_LEN]; str dataModify[TIME_LEN]; str dataAccess[NAME_LEN]; int dataAccessInx; int writeFlag; str destRescName[NAME_LEN]; str backupRescName[NAME_LEN]; str subPath[MAX_NAME_LEN]; int *specColl; int regUid; int otherFlags; struct KeyValPair_PI; str in_pdmo[MAX_NAME_LEN]; int *next;" /* transStat_t is being replaced by transferStat_t because of the 64 bits * padding */ #define TransStat_PI "int numThreads; double bytesWritten;" #define TransferStat_PI "int numThreads; int flags; double bytesWritten;" #define AuthInfo_PI "str authScheme[NAME_LEN]; int authFlag; int flag; int ppid; str host[NAME_LEN]; str authStr[NAME_LEN];" #define UserOtherInfo_PI "str userInfo[NAME_LEN]; str userComments[NAME_LEN]; str userCreate[TIME_LEN]; str userModify[TIME_LEN];" #define UserInfo_PI "str userName[NAME_LEN]; str rodsZone[NAME_LEN]; str userType[NAME_LEN]; int sysUid; struct AuthInfo_PI; struct UserOtherInfo_PI;" #define CollInfo_PI "double collId; str collName[MAX_NAME_LEN]; str collParentName[MAX_NAME_LEN]; str collOwnerName[NAME_LEN]; str collOwnerZone[NAME_LEN]; int collMapId; int collAccessInx; str collComments[LONG_NAME_LEN]; str collInheritance[LONG_NAME_LEN]; str collExpiry[TIME_LEN]; str collCreate[TIME_LEN]; str collModify[TIME_LEN]; str collAccess[NAME_LEN]; str collType[NAME_LEN]; str collInfo1[MAX_NAME_LEN]; str collInfo2[MAX_NAME_LEN]; struct KeyValPair_PI; int *next;" #define Rei_PI "int status; str statusStr[MAX_NAME_LEN]; str ruleName[NAME_LEN]; int *rsComm; str pluginInstanceName[MAX_NAME_LEN]; struct *MsParamArray_PI; struct MsParamArray_PI; int l1descInx; struct *DataObjInp_PI; struct *DataObjInfo_PI; struct *UserInfo_PI; struct *UserInfo_PI; struct *CollInfo_PI; struct *UserInfo_PI; struct *KeyValPair_PI; str ruleSet[RULE_SET_DEF_LENGTH]; int *next;" #define ReArg_PI "int myArgc; str *myArgv[myArgc];" #define ReiAndArg_PI "struct *Rei_PI; struct ReArg_PI;" #define BytesBuf_PI "int buflen; char *buf(buflen);" /* PI for dataArray_t */ #define charDataArray_PI "int type; int len; char *buf(len);" #define strDataArray_PI "int type; int len; str *buf[len];" #define intDataArray_PI "int type; int len; int *buf(len);" #define int16DataArray_PI "int type; int len; int16 *buf(len);" #define int64DataArray_PI "int type; int len; double *buf(len);" #define BinBytesBuf_PI "int buflen; bin *buf(buflen);" #define MsParam_PI "str *label; piStr *type; ?type *inOutStruct; struct *BinBytesBuf_PI;" #define MsParamArray_PI "int paramLen; int oprType; struct *MsParam_PI[paramLen];" #define TagStruct_PI "int ssLen; str *preTag[ssLen]; str *postTag[ssLen]; str *keyWord[ssLen];" #define RodsObjStat_PI "double objSize; int objType; int dataMode; str dataId[NAME_LEN]; str chksum[NAME_LEN]; str ownerName[NAME_LEN]; str ownerZone[NAME_LEN]; str createTime[TIME_LEN]; str modifyTime[TIME_LEN]; struct *SpecColl_PI;" #define ReconnMsg_PI "int status; int cookie; int procState; int flag;" #define VaultPathPolicy_PI "int scheme; int addUserName; int trimDirCnt;" #define StrArray_PI "int len; int size; str *value(len)(size);" #define IntArray_PI "int len; int *value(len);" #define SpecColl_PI "int collClass; int type; str collection[MAX_NAME_LEN]; str objPath[MAX_NAME_LEN]; str resource[NAME_LEN]; str rescHier[MAX_NAME_LEN]; str phyPath[MAX_NAME_LEN]; str cacheDir[MAX_NAME_LEN]; int cacheDirty; int replNum;" #define SubFile_PI "struct RHostAddr_PI; str subFilePath[MAX_NAME_LEN]; int mode; int flags; double offset; struct *SpecColl_PI;" #define XmsgTicketInfo_PI "int sendTicket; int rcvTicket; int expireTime; int flag;" #define SendXmsgInfo_PI "int msgNumber; str msgType[HEADER_TYPE_LEN]; int numRcv; int flag; str *msg; int numDel; str *delAddress[numDel]; int *delPort(numDel); str *miscInfo;" #define GetXmsgTicketInp_PI "int expireTime; int flag;" #define SendXmsgInp_PI "struct XmsgTicketInfo_PI; str sendAddr[NAME_LEN]; struct SendXmsgInfo_PI;" #define RcvXmsgInp_PI "int rcvTicket; int msgNumber; int seqNumber; str msgCondition[MAX_NAME_LEN];" #define RcvXmsgOut_PI "str msgType[HEADER_TYPE_LEN]; str sendUserName[NAME_LEN]; str sendAddr[NAME_LEN]; int msgNumber; int seqNumber; str *msg;" /* XXXXX start of HDF5 PI */ #define h5error_PI "str major[MAX_ERROR_SIZE]; str minor[MAX_ERROR_SIZE];" #define h5File_PI "int fopID; str *filename; int ffid; struct *h5Group_PI; struct h5error_PI;int ftime;" #define h5Group_PI "int gopID; int gfid; int gobjID[OBJID_DIM]; str *gfullpath; int $dummyParent; int nGroupMembers; struct *h5Group_PI(nGroupMembers); int nDatasetMembers; struct *h5Dataset_PI(nDatasetMembers); int nattributes; struct *h5Attribute_PI(nattributes); struct h5error_PI;int gtime;" /* XXXXX need to fix the type dependence */ #define h5Dataset_PI "int dopID; int dfid; int dobjID[OBJID_DIM]; int dclass; int nattributes; str *dfullpath; struct *h5Attribute_PI(nattributes); struct h5Datatype_PI; struct h5Dataspace_PI; int nvalue; int dtime; % dclass:3,6,9 = str *value[nvalue]:default= char *value(nvalue); struct h5error_PI;" /* XXXXX need to fix the type dependence */ #define h5Attribute_PI "int aopID; int afid; str *aname; str *aobj_path; int aobj_type; int aclass; struct h5Datatype_PI; struct h5Dataspace_PI; int nvalue; % aclass:3,6,9 = str *value[nvalue]:default= char *value(nvalue); struct h5error_PI;" #define h5Datatype_PI "int tclass; int torder; int tsign; int tsize; int ntmenbers; int *mtypes(ntmenbers); str *mnames[ntmenbers];" #define h5Dataspace_PI "int rank; int dims[H5S_MAX_RANK]; int npoints; int start[H5DATASPACE_MAX_RANK]; int stride[H5DATASPACE_MAX_RANK]; int count[H5DATASPACE_MAX_RANK];" /* content of collEnt_t cannot be freed since they are pointers in "value" * of sqlResult */ #define CollEnt_PI "int objType; int replNum; int replStatus; int dataMode; double dataSize; str $collName; str $dataName; str $dataId; str $createTime; str $modifyTime; str $chksum; str $resource; str $phyPath; str $ownerName; str $dataType; struct SpecColl_PI;" #define CollOprStat_PI "int filesCnt; int totalFileCnt; double bytesWritten; str lastObjPath[MAX_NAME_LEN];" /* XXXXX end of HDF5 PI */ #define RuleStruct_PI "int maxNumOfRules; str *ruleBase[maxNumOfRules]; str *action[maxNumOfRules]; str *ruleHead[maxNumOfRules]; str *ruleCondition[maxNumOfRules]; str *ruleAction[maxNumOfRules]; str *ruleRecovery[maxNumOfRules]; double ruleId[maxNumOfRules];" #define DVMapStruct_PI "int maxNumOfDVars; str *varName[maxNumOfDVars]; str *action[maxNumOfDVars]; str *var2CMap[maxNumOfDVars]; double varId[maxNumOfDVars];" #define FNMapStruct_PI "int maxNumOfFMaps; str *funcName[maxNumOfFMaps]; str *func2CMap[maxNumOfFMaps]; double fmapId[maxNumOfFMaps];" #define MsrvcStruct_PI "int maxNumOfMsrvcs; double msrvcId[maxNumOfMsrvcs]; str moduleName[maxNumOfMsrvcs]; str msrvcName[maxNumOfMsrvcs]; str msrvcSiganture[maxNumOfMsrvcs]; str msrvcVersion[maxNumOfMsrvcs]; str msrvcHost[maxNumOfMsrvcs]; str msrvcLocation[maxNumOfMsrvcs]; str msrvcLanguage[maxNumOfMsrvcs]; str msrvcTypeName[maxNumOfMsrvcs]; double msrvcStatus[maxNumOfMsrvcs];" #define DataSeg_PI "double len; double offset;" #define FileRestartInfo_PI "str fileName[MAX_NAME_LEN]; str objPath[MAX_NAME_LEN]; int numSeg; int flags; double fileSize; struct DataSeg_PI[numSeg];" #endif /* PACK_INSTRUCT_H */ <commit_msg>[#1472] Packing instruction for rei didn't match struct definition anymore<commit_after>/*** Copyright (c), The Regents of the University of California *** *** For more information please refer to files in the COPYRIGHT directory ***/ /* packInstruct.h - header file for pack instruction definition */ #ifndef PACK_INSTRUCT_HPP #define PACK_INSTRUCT_HPP #define IRODS_STR_PI "str myStr[MAX_NAME_LEN];" #define STR_PI "str myStr;" #define CHAR_PI "char myChar;" #define STR_PTR_PI "str *myStr;" #define PI_STR_PI "piStr myStr[MAX_NAME_LEN];" #define INT_PI "int myInt;" #define INT16_PI "int16 myInt;" #define BUF_LEN_PI "int myInt;" #define DOUBLE_PI "double myDouble;" /* packInstruct for msgHeader_t */ #define MsgHeader_PI "str type[HEADER_TYPE_LEN]; int msgLen; int errorLen; int bsLen; int intInfo;" /* packInstruct for startupPack_t */ #define StartupPack_PI "int irodsProt; int reconnFlag; int connectCnt; str proxyUser[NAME_LEN]; str proxyRcatZone[NAME_LEN]; str clientUser[NAME_LEN]; str clientRcatZone[NAME_LEN]; str relVersion[NAME_LEN]; str apiVersion[NAME_LEN]; str option[NAME_LEN];" /* packInstruct for version_t */ #define Version_PI "int status; str relVersion[NAME_LEN]; str apiVersion[NAME_LEN]; int reconnPort; str reconnAddr[LONG_NAME_LEN]; int cookie;" /* packInstruct for rErrMsg_t */ #define RErrMsg_PI "int status; str msg[ERR_MSG_LEN];" /* packInstruct for rError_t */ #define RError_PI "int count; struct *RErrMsg_PI[count];" #define RHostAddr_PI "str hostAddr[LONG_NAME_LEN]; str rodsZone[NAME_LEN]; int port; int dummyInt;" #define RODS_STAT_T_PI "double st_size; int st_dev; int st_ino; int st_mode; int st_nlink; int st_uid; int st_gid; int st_rdev; int st_atim; int st_mtim; int st_ctim; int st_blksize; int st_blocks;" #define RODS_DIRENT_T_PI "int d_offset; int d_ino; int d_reclen; int d_namlen; str d_name[DIR_LEN];" #define KeyValPair_PI "int ssLen; str *keyWord[ssLen]; str *svalue[ssLen];" // =-=-=-=-=-=-=- // pack struct for client server negotiations #define CS_NEG_PI "int status; str result[MAX_NAME_LEN];" #define InxIvalPair_PI "int iiLen; int *inx(iiLen); int *ivalue(iiLen);" #define InxValPair_PI "int isLen; int *inx(isLen); str *svalue[isLen];" #define DataObjInp_PI "str objPath[MAX_NAME_LEN]; int createMode; int openFlags; double offset; double dataSize; int numThreads; int oprType; struct *SpecColl_PI; struct KeyValPair_PI;" #define OpenedDataObjInp_PI "int l1descInx; int len; int whence; int oprType; double offset; double bytesWritten; struct KeyValPair_PI;" #define PortList_PI "int portNum; int cookie; int sock; int windowSize; str hostAddr[LONG_NAME_LEN];" #define PortalOprOut_PI "int status; int l1descInx; int numThreads; str chksum[NAME_LEN]; struct PortList_PI;" #define DataOprInp_PI "int oprType; int numThreads; int srcL3descInx; int destL3descInx; int srcRescTypeInx; int destRescTypeInx; double offset; double dataSize; struct KeyValPair_PI;" #define CollInpNew_PI "str collName[MAX_NAME_LEN]; int flags; int oprType; struct KeyValPair_PI;" #define GenQueryInp_PI "int maxRows; int continueInx; int partialStartIndex; int options; struct KeyValPair_PI; struct InxIvalPair_PI; struct InxValPair_PI;" #define SqlResult_PI "int attriInx; int reslen; str *value(rowCnt)(reslen);" #define GenQueryOut_PI "int rowCnt; int attriCnt; int continueInx; int totalRowCount; struct SqlResult_PI[MAX_SQL_ATTR];" #define GenArraysInp_PI "int rowCnt; int attriCnt; int continueInx; int totalRowCount; struct KeyValPair_PI; struct SqlResult_PI[MAX_SQL_ATTR];" #define DataObjInfo_PI "str objPath[MAX_NAME_LEN]; str rescName[NAME_LEN]; str rescHier[MAX_NAME_LEN]; str dataType[NAME_LEN]; double dataSize; str chksum[NAME_LEN]; str version[NAME_LEN]; str filePath[MAX_NAME_LEN]; str dataOwnerName[NAME_LEN]; str dataOwnerZone[NAME_LEN]; int replNum; int replStatus; str statusString[NAME_LEN]; double dataId; double collId; int dataMapId; int flags; str dataComments[LONG_NAME_LEN]; str dataMode[SHORT_STR_LEN]; str dataExpiry[TIME_LEN]; str dataCreate[TIME_LEN]; str dataModify[TIME_LEN]; str dataAccess[NAME_LEN]; int dataAccessInx; int writeFlag; str destRescName[NAME_LEN]; str backupRescName[NAME_LEN]; str subPath[MAX_NAME_LEN]; int *specColl; int regUid; int otherFlags; struct KeyValPair_PI; str in_pdmo[MAX_NAME_LEN]; int *next;" /* transStat_t is being replaced by transferStat_t because of the 64 bits * padding */ #define TransStat_PI "int numThreads; double bytesWritten;" #define TransferStat_PI "int numThreads; int flags; double bytesWritten;" #define AuthInfo_PI "str authScheme[NAME_LEN]; int authFlag; int flag; int ppid; str host[NAME_LEN]; str authStr[NAME_LEN];" #define UserOtherInfo_PI "str userInfo[NAME_LEN]; str userComments[NAME_LEN]; str userCreate[TIME_LEN]; str userModify[TIME_LEN];" #define UserInfo_PI "str userName[NAME_LEN]; str rodsZone[NAME_LEN]; str userType[NAME_LEN]; int sysUid; struct AuthInfo_PI; struct UserOtherInfo_PI;" #define CollInfo_PI "double collId; str collName[MAX_NAME_LEN]; str collParentName[MAX_NAME_LEN]; str collOwnerName[NAME_LEN]; str collOwnerZone[NAME_LEN]; int collMapId; int collAccessInx; str collComments[LONG_NAME_LEN]; str collInheritance[LONG_NAME_LEN]; str collExpiry[TIME_LEN]; str collCreate[TIME_LEN]; str collModify[TIME_LEN]; str collAccess[NAME_LEN]; str collType[NAME_LEN]; str collInfo1[MAX_NAME_LEN]; str collInfo2[MAX_NAME_LEN]; struct KeyValPair_PI; int *next;" #define Rei_PI "int status; str statusStr[MAX_NAME_LEN]; str ruleName[NAME_LEN]; int *rsComm; str pluginInstanceName[MAX_NAME_LEN]; struct *MsParamArray_PI; struct MsParamArray_PI; int l1descInx; struct *DataObjInp_PI; struct *DataObjInfo_PI; str rescName[NAME_LEN]; struct *UserInfo_PI; struct *UserInfo_PI; struct *CollInfo_PI; struct *UserInfo_PI; struct *KeyValPair_PI; str ruleSet[RULE_SET_DEF_LENGTH]; int *next;" #define ReArg_PI "int myArgc; str *myArgv[myArgc];" #define ReiAndArg_PI "struct *Rei_PI; struct ReArg_PI;" #define BytesBuf_PI "int buflen; char *buf(buflen);" /* PI for dataArray_t */ #define charDataArray_PI "int type; int len; char *buf(len);" #define strDataArray_PI "int type; int len; str *buf[len];" #define intDataArray_PI "int type; int len; int *buf(len);" #define int16DataArray_PI "int type; int len; int16 *buf(len);" #define int64DataArray_PI "int type; int len; double *buf(len);" #define BinBytesBuf_PI "int buflen; bin *buf(buflen);" #define MsParam_PI "str *label; piStr *type; ?type *inOutStruct; struct *BinBytesBuf_PI;" #define MsParamArray_PI "int paramLen; int oprType; struct *MsParam_PI[paramLen];" #define TagStruct_PI "int ssLen; str *preTag[ssLen]; str *postTag[ssLen]; str *keyWord[ssLen];" #define RodsObjStat_PI "double objSize; int objType; int dataMode; str dataId[NAME_LEN]; str chksum[NAME_LEN]; str ownerName[NAME_LEN]; str ownerZone[NAME_LEN]; str createTime[TIME_LEN]; str modifyTime[TIME_LEN]; struct *SpecColl_PI;" #define ReconnMsg_PI "int status; int cookie; int procState; int flag;" #define VaultPathPolicy_PI "int scheme; int addUserName; int trimDirCnt;" #define StrArray_PI "int len; int size; str *value(len)(size);" #define IntArray_PI "int len; int *value(len);" #define SpecColl_PI "int collClass; int type; str collection[MAX_NAME_LEN]; str objPath[MAX_NAME_LEN]; str resource[NAME_LEN]; str rescHier[MAX_NAME_LEN]; str phyPath[MAX_NAME_LEN]; str cacheDir[MAX_NAME_LEN]; int cacheDirty; int replNum;" #define SubFile_PI "struct RHostAddr_PI; str subFilePath[MAX_NAME_LEN]; int mode; int flags; double offset; struct *SpecColl_PI;" #define XmsgTicketInfo_PI "int sendTicket; int rcvTicket; int expireTime; int flag;" #define SendXmsgInfo_PI "int msgNumber; str msgType[HEADER_TYPE_LEN]; int numRcv; int flag; str *msg; int numDel; str *delAddress[numDel]; int *delPort(numDel); str *miscInfo;" #define GetXmsgTicketInp_PI "int expireTime; int flag;" #define SendXmsgInp_PI "struct XmsgTicketInfo_PI; str sendAddr[NAME_LEN]; struct SendXmsgInfo_PI;" #define RcvXmsgInp_PI "int rcvTicket; int msgNumber; int seqNumber; str msgCondition[MAX_NAME_LEN];" #define RcvXmsgOut_PI "str msgType[HEADER_TYPE_LEN]; str sendUserName[NAME_LEN]; str sendAddr[NAME_LEN]; int msgNumber; int seqNumber; str *msg;" /* XXXXX start of HDF5 PI */ #define h5error_PI "str major[MAX_ERROR_SIZE]; str minor[MAX_ERROR_SIZE];" #define h5File_PI "int fopID; str *filename; int ffid; struct *h5Group_PI; struct h5error_PI;int ftime;" #define h5Group_PI "int gopID; int gfid; int gobjID[OBJID_DIM]; str *gfullpath; int $dummyParent; int nGroupMembers; struct *h5Group_PI(nGroupMembers); int nDatasetMembers; struct *h5Dataset_PI(nDatasetMembers); int nattributes; struct *h5Attribute_PI(nattributes); struct h5error_PI;int gtime;" /* XXXXX need to fix the type dependence */ #define h5Dataset_PI "int dopID; int dfid; int dobjID[OBJID_DIM]; int dclass; int nattributes; str *dfullpath; struct *h5Attribute_PI(nattributes); struct h5Datatype_PI; struct h5Dataspace_PI; int nvalue; int dtime; % dclass:3,6,9 = str *value[nvalue]:default= char *value(nvalue); struct h5error_PI;" /* XXXXX need to fix the type dependence */ #define h5Attribute_PI "int aopID; int afid; str *aname; str *aobj_path; int aobj_type; int aclass; struct h5Datatype_PI; struct h5Dataspace_PI; int nvalue; % aclass:3,6,9 = str *value[nvalue]:default= char *value(nvalue); struct h5error_PI;" #define h5Datatype_PI "int tclass; int torder; int tsign; int tsize; int ntmenbers; int *mtypes(ntmenbers); str *mnames[ntmenbers];" #define h5Dataspace_PI "int rank; int dims[H5S_MAX_RANK]; int npoints; int start[H5DATASPACE_MAX_RANK]; int stride[H5DATASPACE_MAX_RANK]; int count[H5DATASPACE_MAX_RANK];" /* content of collEnt_t cannot be freed since they are pointers in "value" * of sqlResult */ #define CollEnt_PI "int objType; int replNum; int replStatus; int dataMode; double dataSize; str $collName; str $dataName; str $dataId; str $createTime; str $modifyTime; str $chksum; str $resource; str $phyPath; str $ownerName; str $dataType; struct SpecColl_PI;" #define CollOprStat_PI "int filesCnt; int totalFileCnt; double bytesWritten; str lastObjPath[MAX_NAME_LEN];" /* XXXXX end of HDF5 PI */ #define RuleStruct_PI "int maxNumOfRules; str *ruleBase[maxNumOfRules]; str *action[maxNumOfRules]; str *ruleHead[maxNumOfRules]; str *ruleCondition[maxNumOfRules]; str *ruleAction[maxNumOfRules]; str *ruleRecovery[maxNumOfRules]; double ruleId[maxNumOfRules];" #define DVMapStruct_PI "int maxNumOfDVars; str *varName[maxNumOfDVars]; str *action[maxNumOfDVars]; str *var2CMap[maxNumOfDVars]; double varId[maxNumOfDVars];" #define FNMapStruct_PI "int maxNumOfFMaps; str *funcName[maxNumOfFMaps]; str *func2CMap[maxNumOfFMaps]; double fmapId[maxNumOfFMaps];" #define MsrvcStruct_PI "int maxNumOfMsrvcs; double msrvcId[maxNumOfMsrvcs]; str moduleName[maxNumOfMsrvcs]; str msrvcName[maxNumOfMsrvcs]; str msrvcSiganture[maxNumOfMsrvcs]; str msrvcVersion[maxNumOfMsrvcs]; str msrvcHost[maxNumOfMsrvcs]; str msrvcLocation[maxNumOfMsrvcs]; str msrvcLanguage[maxNumOfMsrvcs]; str msrvcTypeName[maxNumOfMsrvcs]; double msrvcStatus[maxNumOfMsrvcs];" #define DataSeg_PI "double len; double offset;" #define FileRestartInfo_PI "str fileName[MAX_NAME_LEN]; str objPath[MAX_NAME_LEN]; int numSeg; int flags; double fileSize; struct DataSeg_PI[numSeg];" #endif /* PACK_INSTRUCT_H */ <|endoftext|>
<commit_before>#include <bits/stdc++.h> using namespace std; #define DEBUG_ON 1 #define INF 0x3f3f3f3f #define NSYNC ios::sync_with_stdio(false); #define FOR(i,a,b) for(int i=a; i<(b); ++i) #define FOR0(i,b) for(int i=0; i<(b); ++i) #define TRAV(it,c) for(__typeof((c).begin()) it=(c).begin(); it!=(c).end(); ++it) #define RTRAV(it,c) for(__typeof((c).rbegin()) it=(c).rbegin(); it!=(c).rend(); ++it) #define DBG(x) if(DEBUG_ON) cout << #x << " == " << x << endl #define DBGP(x) if(DEBUG_ON) cout << "(" << (x).first << ", " << (x).second << ")" << endl #define pb(x) push_back(x) #define mp(x,y) make_pair(x,y) #define R(x) scanf(" %d",&(x)) #define RR(x,y) scanf(" %d %d",&(x), &(y)) #define RRR(x,y,z) scanf(" %d %d %d",&(x), &(y),&(z)) #define CLR(v) memset(v, 0, sizeof(v)) #define SET(v) memset(v, -1, sizeof(v)) typedef long long ll; typedef int int_type; typedef pair<int_type, int_type> pii; typedef vector<int_type> vi; const int MAXN = 100010; vi adj[MAXN]; int d[MAXN], low[MAXN], visi[MAXN], t; bool art[MAXN]; set<pii> bs; void dfs(int u, int p=-1) { visi[u] = true; d[u] = low[u] = t++; bool found = false; int ct=0; for(auto v : adj[u]) { if(!visi[v]) { ++ct; dfs(v,u); low[u] = min(low[u],low[v]); if(low[v]>=d[u]) found = true; if(low[v]>d[u]) bs.insert(mp(min(u,v),max(u,v))); } else if(v!=p) { low[u] = min(low[u], d[v]); } } art[u] = (u ? found : ct>1); } int main() { NSYNC; return 0; } <commit_msg>migue<commit_after>#include <bits/stdc++.h> using namespace std; #define DEBUG_ON 1 #define INF 0x3f3f3f3f #define NSYNC ios::sync_with_stdio(false); #define FOR(i,a,b) for(int i=a; i<(b); ++i) #define FOR0(i,b) for(int i=0; i<(b); ++i) #define TRAV(it,c) for(__typeof((c).begin()) it=(c).begin(); it!=(c).end(); ++it) #define RTRAV(it,c) for(__typeof((c).rbegin()) it=(c).rbegin(); it!=(c).rend(); ++it) #define DBG(x) if(DEBUG_ON) cout << #x << " == " << x << endl #define DBGP(x) if(DEBUG_ON) cout << "(" << (x).first << ", " << (x).second << ")" << endl #define pb(x) push_back(x) #define mp(x,y) make_pair(x,y) #define R(x) scanf(" %d",&(x)) #define RR(x,y) scanf(" %d %d",&(x), &(y)) #define RRR(x,y,z) scanf(" %d %d %d",&(x), &(y),&(z)) #define CLR(v) memset(v, 0, sizeof(v)) #define SET(v) memset(v, -1, sizeof(v)) typedef long long ll; typedef int int_type; typedef pair<int_type, int_type> pii; typedef vector<int_type> vi; const int MAXN = 100010; vi adj[MAXN]; int d[MAXN], low[MAXN], visi[MAXN], t; bool art[MAXN]; set<pii> bs; void dfs(int u, int p=-1) { visi[u] = true; d[u] = low[u] = t++; bool found = false; int ct=0; for(auto v : adj[u]) { if(!visi[v]) { ++ct; dfs(v,u); low[u] = min(low[u],low[v]); if(low[v]>=d[u]) found = true; if(low[v]>d[u]) bs.insert(mp(min(u,v),max(u,v))); } else if(v!=p) { low[u] = min(low[u], d[v]); } } art[u] = (u ? found : ct>1); } //call with FOR0(i,n) if (!visi[i]) dfs(i); int main() { NSYNC; return 0; } <|endoftext|>
<commit_before>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008 Benoit Jacob <[email protected]> // // Eigen 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. // // Alternatively, you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of // the License, or (at your option) any later version. // // Eigen 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 or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include "main.h" #include <Eigen/StdVector> #include <Eigen/Geometry> template<typename MatrixType> void check_stdvector_matrix(const MatrixType& m) { int rows = m.rows(); int cols = m.cols(); MatrixType x = MatrixType::Random(rows,cols), y = MatrixType::Random(rows,cols); std::vector<MatrixType,Eigen::aligned_allocator<MatrixType> > v(10, MatrixType(rows,cols)), w(20, y); v[5] = x; w[6] = v[5]; VERIFY_IS_APPROX(w[6], v[5]); v = w; for(int i = 0; i < 20; i++) { VERIFY_IS_APPROX(w[i], v[i]); } v.resize(21); v[20] = x; VERIFY_IS_APPROX(v[20], x); v.resize(22,y); VERIFY_IS_APPROX(v[21], y); v.push_back(x); VERIFY_IS_APPROX(v[22], x); VERIFY((size_t)&(v[22]) == (size_t)&(v[21]) + sizeof(MatrixType)); // do a lot of push_back such that the vector gets internally resized // (with memory reallocation) MatrixType* ref = &w[0]; for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i) v.push_back(w[i%w.size()]); for(unsigned int i=23; i<v.size(); ++i) { VERIFY(v[i]==w[(i-23)%w.size()]); } } template<typename TransformType> void check_stdvector_transform(const TransformType&) { typedef typename TransformType::MatrixType MatrixType; TransformType x(MatrixType::Random()), y(MatrixType::Random()); std::vector<TransformType,Eigen::aligned_allocator<TransformType> > v(10), w(20, y); v[5] = x; w[6] = v[5]; VERIFY_IS_APPROX(w[6], v[5]); v = w; for(int i = 0; i < 20; i++) { VERIFY_IS_APPROX(w[i], v[i]); } v.resize(21); v[20] = x; VERIFY_IS_APPROX(v[20], x); v.resize(22,y); VERIFY_IS_APPROX(v[21], y); v.push_back(x); VERIFY_IS_APPROX(v[22], x); VERIFY((size_t)&(v[22]) == (size_t)&(v[21]) + sizeof(TransformType)); // do a lot of push_back such that the vector gets internally resized // (with memory reallocation) TransformType* ref = &w[0]; for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i) v.push_back(w[i%w.size()]); for(unsigned int i=23; i<v.size(); ++i) { VERIFY(v[i].matrix()==w[(i-23)%w.size()].matrix()); } } template<typename QuaternionType> void check_stdvector_quaternion(const QuaternionType&) { typedef typename QuaternionType::Coefficients Coefficients; QuaternionType x(Coefficients::Random()), y(Coefficients::Random()); std::vector<QuaternionType,Eigen::aligned_allocator<QuaternionType> > v(10), w(20, y); v[5] = x; w[6] = v[5]; VERIFY_IS_APPROX(w[6], v[5]); v = w; for(int i = 0; i < 20; i++) { VERIFY_IS_APPROX(w[i], v[i]); } v.resize(21); v[20] = x; VERIFY_IS_APPROX(v[20], x); v.resize(22,y); VERIFY_IS_APPROX(v[21], y); v.push_back(x); VERIFY_IS_APPROX(v[22], x); VERIFY((size_t)&(v[22]) == (size_t)&(v[21]) + sizeof(QuaternionType)); // do a lot of push_back such that the vector gets internally resized // (with memory reallocation) QuaternionType* ref = &w[0]; for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i) v.push_back(w[i%w.size()]); for(unsigned int i=23; i<v.size(); ++i) { VERIFY(v[i].coeffs()==w[(i-23)%w.size()].coeffs()); } } void test_stdvector() { // some non vectorizable fixed sizes CALL_SUBTEST(check_stdvector_matrix(Vector2f())); CALL_SUBTEST(check_stdvector_matrix(Matrix3f())); CALL_SUBTEST(check_stdvector_matrix(Matrix3d())); // some vectorizable fixed sizes CALL_SUBTEST(check_stdvector_matrix(Matrix2f())); CALL_SUBTEST(check_stdvector_matrix(Vector4f())); CALL_SUBTEST(check_stdvector_matrix(Matrix4f())); CALL_SUBTEST(check_stdvector_matrix(Matrix4d())); // some dynamic sizes CALL_SUBTEST(check_stdvector_matrix(MatrixXd(1,1))); CALL_SUBTEST(check_stdvector_matrix(VectorXd(20))); CALL_SUBTEST(check_stdvector_matrix(RowVectorXf(20))); CALL_SUBTEST(check_stdvector_matrix(MatrixXcf(10,10))); // some Transform CALL_SUBTEST(check_stdvector_transform(Transform2f())); CALL_SUBTEST(check_stdvector_transform(Transform3f())); CALL_SUBTEST(check_stdvector_transform(Transform3d())); //CALL_SUBTEST(check_stdvector_transform(Transform4d())); // some Quaternion CALL_SUBTEST(check_stdvector_quaternion(Quaternionf())); CALL_SUBTEST(check_stdvector_quaternion(Quaternionf())); } <commit_msg>fix typo<commit_after>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008 Benoit Jacob <[email protected]> // // Eigen 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. // // Alternatively, you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of // the License, or (at your option) any later version. // // Eigen 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 or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include "main.h" #include <Eigen/StdVector> #include <Eigen/Geometry> template<typename MatrixType> void check_stdvector_matrix(const MatrixType& m) { int rows = m.rows(); int cols = m.cols(); MatrixType x = MatrixType::Random(rows,cols), y = MatrixType::Random(rows,cols); std::vector<MatrixType,Eigen::aligned_allocator<MatrixType> > v(10, MatrixType(rows,cols)), w(20, y); v[5] = x; w[6] = v[5]; VERIFY_IS_APPROX(w[6], v[5]); v = w; for(int i = 0; i < 20; i++) { VERIFY_IS_APPROX(w[i], v[i]); } v.resize(21); v[20] = x; VERIFY_IS_APPROX(v[20], x); v.resize(22,y); VERIFY_IS_APPROX(v[21], y); v.push_back(x); VERIFY_IS_APPROX(v[22], x); VERIFY((size_t)&(v[22]) == (size_t)&(v[21]) + sizeof(MatrixType)); // do a lot of push_back such that the vector gets internally resized // (with memory reallocation) MatrixType* ref = &w[0]; for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i) v.push_back(w[i%w.size()]); for(unsigned int i=23; i<v.size(); ++i) { VERIFY(v[i]==w[(i-23)%w.size()]); } } template<typename TransformType> void check_stdvector_transform(const TransformType&) { typedef typename TransformType::MatrixType MatrixType; TransformType x(MatrixType::Random()), y(MatrixType::Random()); std::vector<TransformType,Eigen::aligned_allocator<TransformType> > v(10), w(20, y); v[5] = x; w[6] = v[5]; VERIFY_IS_APPROX(w[6], v[5]); v = w; for(int i = 0; i < 20; i++) { VERIFY_IS_APPROX(w[i], v[i]); } v.resize(21); v[20] = x; VERIFY_IS_APPROX(v[20], x); v.resize(22,y); VERIFY_IS_APPROX(v[21], y); v.push_back(x); VERIFY_IS_APPROX(v[22], x); VERIFY((size_t)&(v[22]) == (size_t)&(v[21]) + sizeof(TransformType)); // do a lot of push_back such that the vector gets internally resized // (with memory reallocation) TransformType* ref = &w[0]; for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i) v.push_back(w[i%w.size()]); for(unsigned int i=23; i<v.size(); ++i) { VERIFY(v[i].matrix()==w[(i-23)%w.size()].matrix()); } } template<typename QuaternionType> void check_stdvector_quaternion(const QuaternionType&) { typedef typename QuaternionType::Coefficients Coefficients; QuaternionType x(Coefficients::Random()), y(Coefficients::Random()); std::vector<QuaternionType,Eigen::aligned_allocator<QuaternionType> > v(10), w(20, y); v[5] = x; w[6] = v[5]; VERIFY_IS_APPROX(w[6], v[5]); v = w; for(int i = 0; i < 20; i++) { VERIFY_IS_APPROX(w[i], v[i]); } v.resize(21); v[20] = x; VERIFY_IS_APPROX(v[20], x); v.resize(22,y); VERIFY_IS_APPROX(v[21], y); v.push_back(x); VERIFY_IS_APPROX(v[22], x); VERIFY((size_t)&(v[22]) == (size_t)&(v[21]) + sizeof(QuaternionType)); // do a lot of push_back such that the vector gets internally resized // (with memory reallocation) QuaternionType* ref = &w[0]; for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i) v.push_back(w[i%w.size()]); for(unsigned int i=23; i<v.size(); ++i) { VERIFY(v[i].coeffs()==w[(i-23)%w.size()].coeffs()); } } void test_stdvector() { // some non vectorizable fixed sizes CALL_SUBTEST(check_stdvector_matrix(Vector2f())); CALL_SUBTEST(check_stdvector_matrix(Matrix3f())); CALL_SUBTEST(check_stdvector_matrix(Matrix3d())); // some vectorizable fixed sizes CALL_SUBTEST(check_stdvector_matrix(Matrix2f())); CALL_SUBTEST(check_stdvector_matrix(Vector4f())); CALL_SUBTEST(check_stdvector_matrix(Matrix4f())); CALL_SUBTEST(check_stdvector_matrix(Matrix4d())); // some dynamic sizes CALL_SUBTEST(check_stdvector_matrix(MatrixXd(1,1))); CALL_SUBTEST(check_stdvector_matrix(VectorXd(20))); CALL_SUBTEST(check_stdvector_matrix(RowVectorXf(20))); CALL_SUBTEST(check_stdvector_matrix(MatrixXcf(10,10))); // some Transform CALL_SUBTEST(check_stdvector_transform(Transform2f())); CALL_SUBTEST(check_stdvector_transform(Transform3f())); CALL_SUBTEST(check_stdvector_transform(Transform3d())); //CALL_SUBTEST(check_stdvector_transform(Transform4d())); // some Quaternion CALL_SUBTEST(check_stdvector_quaternion(Quaternionf())); CALL_SUBTEST(check_stdvector_quaternion(Quaterniond())); } <|endoftext|>
<commit_before>/* This file is part of KOrganizer. Copyright (c) 2000,2001 Cornelius Schumacher <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <klocale.h> #include <kdebug.h> #include "kotodoviewitem.h" #include "kotodoview.h" #include "koprefs.h" KOTodoViewItem::KOTodoViewItem( QListView *parent, Todo *todo, KOTodoView *kotodo) : QCheckListItem( parent , "", CheckBox ), mTodo( todo ), mTodoView( kotodo ) { construct(); } KOTodoViewItem::KOTodoViewItem( KOTodoViewItem *parent, Todo *todo, KOTodoView *kotodo ) : QCheckListItem( parent, "", CheckBox ), mTodo( todo ), mTodoView( kotodo ) { construct(); } QString KOTodoViewItem::key(int column,bool) const { QMap<int,QString>::ConstIterator it = mKeyMap.find(column); if (it == mKeyMap.end()) { return text(column); } else { return *it; } } void KOTodoViewItem::setSortKey(int column,const QString &key) { mKeyMap.insert(column,key); } #if QT_VERSION >= 300 void KOTodoViewItem::paintBranches(QPainter *p,const QColorGroup & cg,int w, int y,int h) { QListViewItem::paintBranches(p,cg,w,y,h); } #else #endif void KOTodoViewItem::construct() { m_init = true; QString keyd = "=="; QString keyt = "=="; setOn(mTodo->isCompleted()); setText(0,mTodo->summary()); setText(1,QString::number(mTodo->priority())); setPixmap(2, progressImg(mTodo->percentComplete())); if (mTodo->percentComplete()<100) { if (mTodo->isCompleted()) setSortKey(2,QString::number(999)); else setSortKey(2,QString::number(mTodo->percentComplete())); } else { if (mTodo->isCompleted()) setSortKey(2,QString::number(999)); else setSortKey(2,QString::number(99)); } if (mTodo->hasDueDate()) { setText(3, mTodo->dtDueDateStr()); QDate d = mTodo->dtDue().date(); keyd.sprintf("%04d%02d%02d",d.year(),d.month(),d.day()); setSortKey(3,keyd); if (mTodo->doesFloat()) { setText(4,""); } else { setText(4,mTodo->dtDueTimeStr()); QTime t = mTodo->dtDue().time(); keyt.sprintf("%02d%02d",t.hour(),t.minute()); setSortKey(4,keyt); } } else { setText(3,""); setText(4,""); } setSortKey(3,keyd); setSortKey(4,keyt); QString priorityKey = QString::number( mTodo->priority() ) + keyd + keyt; if ( mTodo->isCompleted() ) setSortKey( 1, "1" + priorityKey ); else setSortKey( 1, "0" + priorityKey ); setText(5,mTodo->categoriesStr()); #if 0 // Find sort id in description. It's the text behind the last '#' character // found in the description. White spaces are removed from beginning and end // of sort id. int pos = mTodo->description().findRev('#'); if (pos < 0) { setText(6,""); } else { QString str = mTodo->description().mid(pos+1); str.stripWhiteSpace(); setText(6,str); } #endif m_known = false; m_init = false; } void KOTodoViewItem::stateChange(bool state) { // do not change setting on startup if ( m_init ) return; kdDebug(5850) << "State changed, modified " << state << endl; QString keyd = "=="; QString keyt = "=="; Todo*oldTodo = mTodo->clone(); if (state) mTodo->setCompleted(state); else mTodo->setPercentComplete(0); if (isOn()!=state) { setOn(state); } if (mTodo->hasDueDate()) { setText(3, mTodo->dtDueDateStr()); QDate d = mTodo->dtDue().date(); keyd.sprintf("%04d%02d%02d",d.year(),d.month(),d.day()); setSortKey(3,keyd); if (mTodo->doesFloat()) { setText(4,""); } else { setText(4,mTodo->dtDueTimeStr()); QTime t = mTodo->dtDue().time(); keyt.sprintf("%02d%02d",t.hour(),t.minute()); setSortKey(4,keyt); } } QString priorityKey = QString::number( mTodo->priority() ) + keyd + keyt; if ( mTodo->isCompleted() ) setSortKey( 1, "1" + priorityKey ); else setSortKey( 1, "0" + priorityKey ); setPixmap(2, progressImg(mTodo->percentComplete())); if (mTodo->percentComplete()<100) { if (mTodo->isCompleted()) setSortKey(2,QString::number(999)); else setSortKey(2,QString::number(mTodo->percentComplete())); } else { if (mTodo->isCompleted()) setSortKey(2,QString::number(999)); else setSortKey(2,QString::number(99)); } QListViewItem *myChild = firstChild(); KOTodoViewItem *item; while( myChild ) { item = static_cast<KOTodoViewItem*>(myChild); item->stateChange(state); myChild = myChild->nextSibling(); } mTodoView->modified(true); mTodoView->setTodoModified( oldTodo, mTodo ); delete oldTodo; } QPixmap KOTodoViewItem::progressImg(int progress) { QImage img(64, 11, 32, 16); QPixmap progr; int x, y; /* White Background */ img.fill(KGlobalSettings::baseColor().rgb()); /* Check wether progress is in valid range */ if(progress > 100) progress = 100; else if (progress < 0) progress=0; /* Calculating the number of pixels to fill */ progress=(int) (((float)progress)/100 * 62 + 0.5); /* Drawing the border */ for(x = 0; x < 64; x++) { img.setPixel(x, 0, KGlobalSettings::textColor().rgb()); img.setPixel(x, 10, KGlobalSettings::textColor().rgb()); } for(y = 0; y < 11; y++) { img.setPixel(0, y, KGlobalSettings::textColor().rgb()); img.setPixel(63, y, KGlobalSettings::textColor().rgb()); } /* Drawing the progress */ for(y = 1; y <= 9; ++y) for(x = 1; x <= progress; ++x) img.setPixel(x, y, KGlobalSettings::highlightColor().rgb()); /* Converting to a pixmap */ progr.convertFromImage(img); return progr; } bool KOTodoViewItem::isAlternate() { #ifndef KORG_NOLVALTERNATION KOTodoListView *lv = static_cast<KOTodoListView *>(listView()); if (lv && lv->alternateBackground().isValid()) { KOTodoViewItem *above = 0; above = dynamic_cast<KOTodoViewItem *>(itemAbove()); m_known = above ? above->m_known : true; if (m_known) { m_odd = above ? !above->m_odd : false; } else { KOTodoViewItem *item; bool previous = true; if (QListViewItem::parent()) { item = dynamic_cast<KOTodoViewItem *>(QListViewItem::parent()); if (item) previous = item->m_odd; item = dynamic_cast<KOTodoViewItem *>(QListViewItem::parent()->firstChild()); } else { item = dynamic_cast<KOTodoViewItem *>(lv->firstChild()); } while(item) { item->m_odd = previous = !previous; item->m_known = true; item = dynamic_cast<KOTodoViewItem *>(item->nextSibling()); } } return m_odd; } return false; #else return false; #endif } void KOTodoViewItem::paintCell(QPainter *p, const QColorGroup &cg, int column, int width, int alignment) { QColorGroup _cg = cg; #ifndef KORG_NOLVALTERNATION if (isAlternate()) _cg.setColor(QColorGroup::Base, static_cast< KOTodoListView* >(listView())->alternateBackground()); if (mTodo->hasDueDate()) { if (mTodo->dtDue().date()==QDate::currentDate() && !mTodo->isCompleted()) { _cg.setColor(QColorGroup::Base, KOPrefs::instance()->mTodoDueTodayColor); } if (mTodo->dtDue().date() < QDate::currentDate() && !mTodo->isCompleted()) { _cg.setColor(QColorGroup::Base, KOPrefs::instance()->mTodoOverdueColor); } } #endif QCheckListItem::paintCell(p, _cg, column, width, alignment); } <commit_msg>Speed up the performance of changing views/date range. The todo list items used QImage with setPixel to set every single pixel of the progress bar manually! Now I use a QPainter on a QPixmap to draw the bar using drawRect, and the time to display a different date range in korganizer has increased from ~2 secs to something below 0.3 secs (with 173 todos and more than 1000 events).<commit_after>/* This file is part of KOrganizer. Copyright (c) 2000,2001 Cornelius Schumacher <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <klocale.h> #include <kdebug.h> #include <qpainter.h> #include <qpixmap.h> #include "kotodoviewitem.h" #include "kotodoview.h" #include "koprefs.h" KOTodoViewItem::KOTodoViewItem( QListView *parent, Todo *todo, KOTodoView *kotodo) : QCheckListItem( parent , "", CheckBox ), mTodo( todo ), mTodoView( kotodo ) { construct(); } KOTodoViewItem::KOTodoViewItem( KOTodoViewItem *parent, Todo *todo, KOTodoView *kotodo ) : QCheckListItem( parent, "", CheckBox ), mTodo( todo ), mTodoView( kotodo ) { construct(); } QString KOTodoViewItem::key(int column,bool) const { QMap<int,QString>::ConstIterator it = mKeyMap.find(column); if (it == mKeyMap.end()) { return text(column); } else { return *it; } } void KOTodoViewItem::setSortKey(int column,const QString &key) { mKeyMap.insert(column,key); } #if QT_VERSION >= 300 void KOTodoViewItem::paintBranches(QPainter *p,const QColorGroup & cg,int w, int y,int h) { QListViewItem::paintBranches(p,cg,w,y,h); } #else #endif void KOTodoViewItem::construct() { m_init = true; QString keyd = "=="; QString keyt = "=="; setOn(mTodo->isCompleted()); setText(0,mTodo->summary()); setText(1,QString::number(mTodo->priority())); setPixmap(2, progressImg(mTodo->percentComplete())); if (mTodo->percentComplete()<100) { if (mTodo->isCompleted()) setSortKey(2,QString::number(999)); else setSortKey(2,QString::number(mTodo->percentComplete())); } else { if (mTodo->isCompleted()) setSortKey(2,QString::number(999)); else setSortKey(2,QString::number(99)); } if (mTodo->hasDueDate()) { setText(3, mTodo->dtDueDateStr()); QDate d = mTodo->dtDue().date(); keyd.sprintf("%04d%02d%02d",d.year(),d.month(),d.day()); setSortKey(3,keyd); if (mTodo->doesFloat()) { setText(4,""); } else { setText(4,mTodo->dtDueTimeStr()); QTime t = mTodo->dtDue().time(); keyt.sprintf("%02d%02d",t.hour(),t.minute()); setSortKey(4,keyt); } } else { setText(3,""); setText(4,""); } setSortKey(3,keyd); setSortKey(4,keyt); QString priorityKey = QString::number( mTodo->priority() ) + keyd + keyt; if ( mTodo->isCompleted() ) setSortKey( 1, "1" + priorityKey ); else setSortKey( 1, "0" + priorityKey ); setText(5,mTodo->categoriesStr()); #if 0 // Find sort id in description. It's the text behind the last '#' character // found in the description. White spaces are removed from beginning and end // of sort id. int pos = mTodo->description().findRev('#'); if (pos < 0) { setText(6,""); } else { QString str = mTodo->description().mid(pos+1); str.stripWhiteSpace(); setText(6,str); } #endif m_known = false; m_init = false; } void KOTodoViewItem::stateChange(bool state) { // do not change setting on startup if ( m_init ) return; kdDebug(5850) << "State changed, modified " << state << endl; QString keyd = "=="; QString keyt = "=="; Todo*oldTodo = mTodo->clone(); if (state) mTodo->setCompleted(state); else mTodo->setPercentComplete(0); if (isOn()!=state) { setOn(state); } if (mTodo->hasDueDate()) { setText(3, mTodo->dtDueDateStr()); QDate d = mTodo->dtDue().date(); keyd.sprintf("%04d%02d%02d",d.year(),d.month(),d.day()); setSortKey(3,keyd); if (mTodo->doesFloat()) { setText(4,""); } else { setText(4,mTodo->dtDueTimeStr()); QTime t = mTodo->dtDue().time(); keyt.sprintf("%02d%02d",t.hour(),t.minute()); setSortKey(4,keyt); } } QString priorityKey = QString::number( mTodo->priority() ) + keyd + keyt; if ( mTodo->isCompleted() ) setSortKey( 1, "1" + priorityKey ); else setSortKey( 1, "0" + priorityKey ); setPixmap(2, progressImg(mTodo->percentComplete())); if (mTodo->percentComplete()<100) { if (mTodo->isCompleted()) setSortKey(2,QString::number(999)); else setSortKey(2,QString::number(mTodo->percentComplete())); } else { if (mTodo->isCompleted()) setSortKey(2,QString::number(999)); else setSortKey(2,QString::number(99)); } QListViewItem *myChild = firstChild(); KOTodoViewItem *item; while( myChild ) { item = static_cast<KOTodoViewItem*>(myChild); item->stateChange(state); myChild = myChild->nextSibling(); } mTodoView->modified(true); mTodoView->setTodoModified( oldTodo, mTodo ); delete oldTodo; } QPixmap KOTodoViewItem::progressImg(int progress) { QPixmap img(64, 11, 16); QPainter painter( &img ); /* Check wether progress is in valid range */ if(progress > 100) progress = 100; else if (progress < 0) progress=0; /* Calculating the number of pixels to fill */ progress=(int) (((float)progress)/100 * 62 + 0.5); /* White Background */ painter.setPen( KGlobalSettings::textColor().rgb() ); painter.setBrush( KGlobalSettings::baseColor().rgb() ); painter.drawRect( 0, 0, 64, 11 ); painter.setPen( Qt::NoPen ); painter.setBrush( KGlobalSettings::highlightColor().rgb() ); // TODO_RK: do I need to subtract 1 from the w and h? painter.drawRect( 1, 1, progress, 9 ); painter.end(); return img; } bool KOTodoViewItem::isAlternate() { #ifndef KORG_NOLVALTERNATION KOTodoListView *lv = static_cast<KOTodoListView *>(listView()); if (lv && lv->alternateBackground().isValid()) { KOTodoViewItem *above = 0; above = dynamic_cast<KOTodoViewItem *>(itemAbove()); m_known = above ? above->m_known : true; if (m_known) { m_odd = above ? !above->m_odd : false; } else { KOTodoViewItem *item; bool previous = true; if (QListViewItem::parent()) { item = dynamic_cast<KOTodoViewItem *>(QListViewItem::parent()); if (item) previous = item->m_odd; item = dynamic_cast<KOTodoViewItem *>(QListViewItem::parent()->firstChild()); } else { item = dynamic_cast<KOTodoViewItem *>(lv->firstChild()); } while(item) { item->m_odd = previous = !previous; item->m_known = true; item = dynamic_cast<KOTodoViewItem *>(item->nextSibling()); } } return m_odd; } return false; #else return false; #endif } void KOTodoViewItem::paintCell(QPainter *p, const QColorGroup &cg, int column, int width, int alignment) { QColorGroup _cg = cg; #ifndef KORG_NOLVALTERNATION if (isAlternate()) _cg.setColor(QColorGroup::Base, static_cast< KOTodoListView* >(listView())->alternateBackground()); if (mTodo->hasDueDate()) { if (mTodo->dtDue().date()==QDate::currentDate() && !mTodo->isCompleted()) { _cg.setColor(QColorGroup::Base, KOPrefs::instance()->mTodoDueTodayColor); } if (mTodo->dtDue().date() < QDate::currentDate() && !mTodo->isCompleted()) { _cg.setColor(QColorGroup::Base, KOPrefs::instance()->mTodoOverdueColor); } } #endif QCheckListItem::paintCell(p, _cg, column, width, alignment); } <|endoftext|>
<commit_before>#include <cassert> #include <cstddef> #include <cstdint> #include <type_traits> #include <utility> #include <new> namespace generic { template<typename F> class forwarder; template<typename R, typename ...A> class forwarder<R (A...)> { public: forwarder() = default; template<typename T> forwarder(T&& f) noexcept : stub_(handler<T>::invoke) { static_assert(sizeof(T) <= sizeof(store_), "functor too large"); static_assert(::std::is_trivially_destructible<T>::value, "functor not trivially destructible"); new (&store_) handler<T>(::std::forward<T>(f)); } forwarder& operator=(forwarder const&) = default; template < typename T, typename = typename ::std::enable_if< !::std::is_same<forwarder, typename ::std::decay<T>::type>{} >::type > forwarder& operator=(T&& f) noexcept { static_assert(sizeof(T) <= sizeof(store_), "functor too large"); static_assert(::std::is_trivially_destructible<T>::value, "functor not trivially destructible"); new (&store_) handler<T>(::std::forward<T>(f)); stub_ = handler<T>::invoke; return *this; } R operator() (A... args) { //assert(stub_); return stub_(&store_, ::std::forward<A>(args)...); } private: template<typename T> struct handler { handler(T&& f) noexcept : f_(::std::forward<T>(f)) { } static R invoke(void* ptr, A&&... args) { return static_cast<handler<T>*>(ptr)->f_(::std::forward<A>(args)...); } T f_; }; #if defined(__clang__) using max_align_type = long double; #elif defined(__GNUC__) using max_align_type = ::max_align_t; #else using max_align_type = ::std::max_align_t; #endif alignas(max_align_type) ::std::uintptr_t store_; R (*stub_)(void*, A&&...){}; }; } <commit_msg>smoe fixes<commit_after>#include <cassert> #include <cstddef> #include <cstdint> #include <type_traits> #include <utility> #include <new> namespace generic { template<typename F> class forwarder; template<typename R, typename ...A> class forwarder<R (A...)> { public: forwarder() = default; template<typename T> forwarder(T&& f) noexcept : stub_(handler<T>::stub) { static_assert(sizeof(T) <= sizeof(store_), "functor too large"); static_assert(::std::is_trivially_destructible<T>::value, "functor not trivially destructible"); new (&store_) handler<T>(::std::forward<T>(f)); } forwarder& operator=(forwarder const&) = default; template < typename T, typename = typename ::std::enable_if< !::std::is_same<forwarder, typename ::std::decay<T>::type>{} >::type > forwarder& operator=(T&& f) noexcept { static_assert(sizeof(T) <= sizeof(store_), "functor too large"); static_assert(::std::is_trivially_destructible<T>::value, "functor not trivially destructible"); new (&store_) handler<T>(::std::forward<T>(f)); stub_ = handler<T>::stub; return *this; } R operator() (A... args) { //assert(stub_); return stub_(&store_, ::std::forward<A>(args)...); } private: template<typename T> struct handler { handler(T&& f) noexcept : f_(::std::forward<T>(f)) { } static R stub(void* ptr, A&&... args) { return static_cast<handler<T>*>(ptr)->f_(::std::forward<A>(args)...); } T f_; }; #if defined(__clang__) using max_align_type = long double; #elif defined(__GNUC__) using max_align_type = ::max_align_t; #else using max_align_type = ::std::max_align_t; #endif alignas(max_align_type) ::std::uintptr_t store_; R (*stub_)(void*, A&&...){}; }; } <|endoftext|>